web-push-notifications
Version:
Pushwoosh web push notifications
2 lines • 43.9 kB
JavaScript
!function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var s=e();for(var a in s)("object"==typeof exports?exports:t)[a]=s[a]}}(this,(()=>(()=>{"use strict";var t={d:(e,s)=>{for(var a in s)t.o(s,a)&&!t.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:s[a]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{Pushwoosh:()=>dt});const s="/pushwoosh-service-worker.js",a="deviceRegistrationStatus",i="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",v="onPushDelivery",b="onNotificationClick",y="onNotificationClose",f="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",k="onUpdateInboxMessages",P="onShowNotificationPermissionDialog",C="onHideNotificationPermissionDialog",x="onShowSubscriptionWidget",D="onHideSubscriptionWidget",I="PW_SiteOpened",M={autoSubscribe:!0,serviceWorkerUrl:s};function E(){return globalThis}function T(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)}))}const _=t=>"function"==typeof t,R={[g]:{name:"register"},[u]:{name:"subscribe"},[d]:{name:"unsubscribe"},[w]:{name:"initialize-service-worker-error",prop:"error"},[v]:{name:"receive-push",prop:"notification"},[b]:{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"},[k]:{name:"update-inbox-messages",prop:"messages"},[P]:{name:"show-notification-permission-dialog"},[C]:{name:"hide-notification-permission-dialog",prop:"permission"},[x]:{name:"show-subscription-widget"},[D]:{name:"hide-subscription-widget"},[p]:{name:"permission-denied"},[l]:{name:"permission-default"},[m]:{name:"permission-granted"}},A="keyValue",O="messages",W="log",q="inboxMessages";function N(t,e){return function(s){s.objectStoreNames.contains(t)||e(s)}}const U=[N(q,(function(t){const e="status",s=t.createObjectStore(q,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(e,e,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})}))];const B=[N(A,(function(t){t.createObjectStore(A,{keyPath:"key"})})),N(W,(function(t){const e=t.createObjectStore(W,{keyPath:"id",autoIncrement:!0});e.createIndex("environment","environment",{unique:!1}),e.createIndex("date","date",{unique:!1}),e.createIndex("type","type",{unique:!1})})),N(O,(function(t){t.createObjectStore(O,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}))];class L{constructor(t=new Date){this._date=t}set date(t){this._date=t}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 t=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(t)}addDays(t){const e=this._date.getTime()+24*t*60*60*1e3;this._date=new Date(e)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}class V{constructor(t=new L){this.migrations={initial:B,"2018/11/26":U},this.dateModule=t}get initial(){return this.migrations.initial}get dateSorted(){return Object.keys(this.migrations).filter((t=>"initial"!==t)).sort(((t,e)=>{const s=new L(new Date(t)),a=new L(new Date(e));return s.getTimestamp()-a.getTimestamp()})).map((t=>this.migrations[t]))}}class H{constructor(t,e=new V){this.db=t,this.migrationsBuilder=e}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.initial),this.migrationsBuilder.dateSorted.forEach((t=>{this.applyMigrationsPack(t)}))}applyMigrationsPack(t){t.forEach((t=>{t(this.db)}))}}function j(t,e){console.info("onversionchange",e),t.close()}let F;function $(t){return(F||(F=new Promise(((t,e)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const a=s.target.result;a.onversionchange=j.bind(null,a,e),t(a)},s.onerror=()=>e(s.error),s.onupgradeneeded=t=>{const s=t.target.result;s.onversionchange=j.bind(null,s,e),new H(s).applyMigrations()}}))),F).then((e=>new Promise(((s,a)=>t(e,s,a)))))}class K{_add(t){return $(((e,s,a)=>{const i=e.transaction([this.name],"readwrite").objectStore(this.name).add(t);i.onsuccess=()=>{s(t)},i.onerror=()=>{a(i.error)}})).then((t=>this.getAll().then((e=>{if(Array.isArray(e)){const s=e.map((t=>t.id)).sort(((t,e)=>t==e?0:t<e?1:-1));if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map((t=>this.delete(t)))).then((()=>t))}return t}))))}delete(t){return $(((e,s,a)=>{const i=e.transaction([this.name],"readwrite").objectStore(this.name).delete(t);i.onsuccess=()=>{s(i.result)},i.onerror=()=>{a(i.error)}}))}getAll(){return $(((t,e,s)=>{const a=[],i=t.transaction(this.name).objectStore(this.name).openCursor();i.onsuccess=t=>{const s=t.target.result;s?(s.value&&a.push(s.value),s.continue()):e(a)},i.onerror=()=>{s(i.error)}}))}}const G=(z=A,{get:(t,e)=>$(((s,a,i)=>{const r=s.transaction(z).objectStore(z).get(t);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?a(r.result?.value||e):c?i(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})),getAll:()=>$(((t,e,s)=>{const a={},i=t.transaction(z).objectStore(z).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?e(a):o?s(i.error):r=setTimeout(c,0)};i.onsuccess=t=>{const e=t.target.result;e?(a[e.key]=e.value.value,e.continue()):n=!0},i.onerror=()=>o=!0,c()})),async extend(t,e){const s=await this.get(t),{...a}=e;await this.set(t,{...s,...a})},set:(t,e)=>$(((s,a,i)=>{const r=s.transaction([z],"readwrite").objectStore(z).put({key:t,value:e});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?a(t):c?i(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=W,this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(t,e,s){const a={type:t,environment:this.environment,message:`${e}`,date:new Date};return e instanceof Error&&(a.stack=e.stack),s&&(a.additional=s),this._add(a)}},Y=new class extends K{constructor(){super(...arguments),this.name=O,this.maxItems=25}add(t){return this._add({...t,date:new Date})}},Q={error:1,info:2,debug:3};let X=3;const Z={setLevel(t){Q[t]||(t="error"),X=Q[t]},write(t,e,s){return"error"===t?this.error(e):this.info(e),J.add(t,e,s)}};Object.keys(Q).forEach((t=>{const e=Q[t];Z[t]=(...s)=>{e<=X&&(console.groupCollapsed(t),console.info("",...s),console.trace("trace"),console.groupEnd())}}));class tt{constructor(){this.addEventHandler=(t,e)=>{let s=this.handlers[t];s||(s=[]),s.push(e),this.handlers[t]=s},this.removeEventHandler=(t,e)=>{const s=this.handlers[t];s&&(this.handlers[t]=s.filter((t=>t!==e)))},this.dispatchEvent=(t,e)=>{const s=e.eventId||T(),a=this.handlers[t];return a?(a.forEach((t=>{_(t)&&setTimeout((()=>{t({...e,eventId:s})}),0)})),s):s},this.handlers={}}}class et{constructor(t,e,s,a=new L){this.data=t,this.api=e,this.inboxModel=s,this.dateModule=a,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}messageTypeFactory(t,e){let s=0;return 2===t?s=1:"l"in e&&null!=e.l&&(s=e.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(t,e,s){const a=[],i=[];e.forEach((async e=>{-1!==t.indexOf(e.inbox_id)&&(e.status=s,a.push(e),i.push(this.api.inboxStatus(e.order,e.status)))})),await this.inboxModel.putBulkMessages(a),await Promise.all(i)}async publicMessageBuilder({action_type:t,action_params:e,image:s,title:a,send_date:i,inbox_id:r,text:n,status:o}){const c=s||await this.data.getDefaultNotificationImage(),h=a||await this.data.getDefaultNotificationTitle(),u=JSON.parse(e);return this.dateModule.date=new Date(1e3*parseInt(i)),this.dateModule.setLocal(),{title:h,imageUrl:c,code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(t,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 t=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort(((t,e)=>parseInt(e.send_date,10)-parseInt(t.send_date,10))).sort(((t,e)=>parseInt(e.order||"0",10)-parseInt(t.order||"0",10))).map(this.publicMessageBuilder);return Promise.all(t)}async readMessagesWithCodes(t){const e=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(t,e,2)}async performActionForMessageWithCode(t){const e=await this.inboxModel.getMessage(t),s=JSON.parse(e.action_params),a=this.messageTypeFactory(e.action_type,s);2===a&&null!=s.l?document.location.href=s.l:3===a&&null!=s.l&&window.history.go(s.l),e.status=3,await this.inboxModel.putMessage(e),await this.api.inboxStatus(e.order,e.status)}async deleteMessagesWithCodes(t){const e=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(t,[...e,...s],4)}async syncMessages(){await this.inboxModel.updateMessages()}}class st{constructor(t,e){this.name=e,this.store=t.transaction(this.name,"readwrite").objectStore(this.name)}set index(t){this.store.indexNames.contains(t)?this._index=this.store.index(t):console.warn(`Index "${t}" in `)}writeRequestPromise(t,e){return new Promise(((s,a)=>{t.onsuccess=()=>{s(e)},t.onerror=()=>{a(t.error)}}))}readRequestPromise(t,e){return new Promise(((s,a)=>{t.onsuccess=t=>{const a=t.target;s(a.result||e)},t.onerror=()=>{a(t.error)}}))}put(t,e){const s=this.store.put(t,e);return this.writeRequestPromise(s,e)}add(t,e){return this.put(t,e)}delete(t){const e=this.store.delete(t);return this.writeRequestPromise(e)}get(t,e){const s=this.store.get(t);return this.readRequestPromise(s,e)}getAll(){const t=this.store.openCursor(),e=[];return new Promise(((s,a)=>{t.onsuccess=t=>{const a=t.target.result;a?(e.push(a.value),a.continue()):s(e)},t.onerror=()=>{a(t.error)}}))}count(t){const e=this.store.count(t);return this.readRequestPromise(e,0)}countByIndex(t){const e=this._index.count(t);return this.readRequestPromise(e,0)}}class at{dbVersionChangeHandler(t,e){console.info("onversionchange",e),t.close()}dbRequestSuccessHandler(t,e){const s=e.target.result;s.onversionchange=t=>{this.dbVersionChangeHandler(s,t)},t(s)}dbRequestUpgradeNeededHandler(t){const e=t.target.result;e.onversionchange=t=>{this.dbVersionChangeHandler(e,t)};new H(e).applyMigrations()}getDB(){return new Promise(((t,e)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=e=>{this.dbRequestSuccessHandler(t,e)},s.onupgradeneeded=t=>{this.dbRequestUpgradeNeededHandler(t)},s.onerror=()=>e(s.error)}))}async put(t,e,s){const a=await this.getDB(),i=new st(a,t),r=await i.put(e,s);return a.close(),r}async delete(t,e){const s=await this.getDB(),a=new st(s,t),i=await a.delete(e);return s.close(),i}async get(t,e,s){const a=await this.getDB(),i=new st(a,t),r=await i.get(e,s);return a.close(),r}async getAll(t){const e=await this.getDB(),s=new st(e,t),a=await s.getAll();return e.close(),a||[]}async count(t,e){const s=await this.getDB(),a=new st(s,t),i=await a.count(e);return s.close(),i}async countByIndex(t,e,s){const a=await this.getDB(),i=new st(a,t);i.index=e;const r=await i.countByIndex(s);return a.close(),r}}class it{constructor(t,e,s,a=new at,i=new L){this.eventBus=t,this.data=e,this.api=s,this.storage=a,this.storeName="inboxMessages",this.dateModule=i}async getInboxMessages(){const t=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(t.next,t.new_inbox),t}async storeGetInboxMessagesRequestParams(t,e){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(t),await this.data.setInboxNewMessagesCount(e)}async putServerMessages(t){const e=t.map((async t=>{const e=await this.storage.get(this.storeName,t.inbox_id,{});return"status"in e&&(t.status=e.status),this.putMessage(t)}));return Promise.all(e)}putMessage(t){return this.storage.put(this.storeName,t)}putBulkMessages(t){const e=t.map((t=>this.putMessage(t)));return Promise.all(e)}deleteMessages(t){const e=t.map((t=>this.storage.delete(this.storeName,t)));return Promise.all(e)}async deleteExpiredMessages(){this.dateModule.date=new Date;const t=this.dateModule.getTimestamp().toString(),e=(await this.storage.getAll(this.storeName)).filter((e=>e.rt<t)).map((t=>t.inbox_id));return this.deleteMessages(e)}getMessage(t){return this.storage.get(this.storeName,t)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter((t=>2===t.status||3===t.status))}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter((t=>1===t.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[t,e]=[2,3],s=IDBKeyRange.bound(t,e);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const t=await this.getInboxMessages();await this.deleteExpiredMessages(),t.deleted&&await this.deleteMessages(t.deleted),await this.putServerMessages(t.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new et(this.data,this.api,this)})}}class rt{constructor(t=G){this.store=t}async clearAll(){await this.store.set("params.applicationCode",void 0),await this.store.set("params.hwid",void 0),await this.store.set("params.deviceType",void 0),await this.store.set("params.deviceModel",void 0),await this.store.set("params.language",void 0),await this.store.set("params.apiEntrypoint",void 0),await this.store.set("params.tokens",void 0),await this.store.set("params.applicationServerKey",void 0),await this.store.set("params.senderId",void 0),await this.store.set("params.webSitePushId",void 0),await this.store.set("params.defaultNotificationImage",void 0),await this.store.set("params.defaultNotificationTitle",void 0),await this.store.set("params.userId",void 0),await this.store.set("params.email",void 0),await this.store.set("params.userIdWasChanged",void 0),await this.store.set("params.isLastPermissionStatus",void 0),await this.store.set("params.isManualUnsubscribed",void 0),await this.store.set("params.isCommunicationDisabled",void 0),await this.store.set("params.isDropAllData",void 0),await this.store.set("params.sdkVersion",void 0),await this.store.set("params.serviceWorkerVersion",void 0),await this.store.set("params.serviceWorkerUrl",void 0),await this.store.set("params.serviceWorkerScope",void 0),await this.store.set("params.lastOpenMessage",void 0),await this.store.set("params.lastOpenApplicationTime",void 0),await this.store.set("params.features",void 0),await this.store.set("params.init",void 0)}async setApplicationCode(t){await this.store.set("params.applicationCode",t)}async getApplicationCode(){return await this.store.get("params.applicationCode")}async setApiToken(t){return await this.store.set("params.apiToken",t)}async getApiToken(){return await this.store.get("params.apiToken")}async setHwid(t){await this.store.set("params.hwid",t)}async getHwid(){return await this.store.get("params.hwid")}async setDeviceType(t){await this.store.set("params.deviceType",t)}async getDeviceType(){return await this.store.get("params.deviceType")}async setDeviceModel(t){await this.store.set("params.deviceModel",t)}async getDeviceModel(){return await this.store.get("params.deviceModel")}async setLanguage(t){await this.store.set("params.language",t)}async getLanguage(){return await this.store.get("params.language","en")}async setApiEntrypoint(t){await this.store.set("params.apiEntrypoint",t)}async getApiEntrypoint(){return await this.store.get("params.apiEntrypoint","https://cp.pushwoosh.com/json/1.3/")}async setTokens(t){await this.store.set("params.tokens",t)}getTokens(){return this.store.get("params.tokens")}async setApplicationServerKey(t){await this.store.set("params.applicationServerKey",t)}async getApplicationServerKey(){return await this.store.get("params.applicationServerKey")}async setIsVapidChanged(t){await this.store.set("params.isVapidChanged",t)}async getIsVapidChanged(){return await this.store.get("params.isVapidChanged",!1)}async setWebSitePushId(t){await this.store.set("params.webSitePushId",t)}async getWebSitePushId(){return await this.store.get("params.webSitePushId")}async setDefaultNotificationImage(t){await this.store.set("params.defaultNotificationImage",t)}async getDefaultNotificationImage(){return await this.store.get("params.defaultNotificationImage","https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(t){await this.store.set("params.defaultNotificationTitle",t)}async getDefaultNotificationTitle(){return await this.store.get("params.defaultNotificationTitle","Pushwoosh notification")}async setUserId(t){t?await this.store.set("params.userId",t.toString()):await this.store.set("params.userId",void 0)}async getUserId(){return await this.store.get("params.userId")}async setStatusUserIdWasChanged(t){await this.store.set("params.userIdWasChanged",t)}async getStatusUserIdWasChanged(){return await this.store.get("params.userIdWasChanged",!1)}async setEmail(t){t?await this.store.set("params.email",t.toString()):await this.store.set("params.email",void 0)}async getEmail(){return await this.store.get("params.email")}async setStatusEmailWasChanged(t){await this.store.set("params.emailWasChanged",t)}async getStatusEmailWasChanged(){return await this.store.get("params.emailWasChanged",!1)}async setLastPermissionStatus(t){await this.store.set("params.isLastPermissionStatus",t)}async getLastPermissionStatus(){return await this.store.get("params.isLastPermissionStatus")}async setStatusManualUnsubscribed(t){await this.store.set("params.isManualUnsubscribed",t)}getStatusManualUnsubscribed(){return this.store.get("params.isManualUnsubscribed",!1)}async setStatusCommunicationDisabled(t){await this.store.set("params.isCommunicationDisabled",t)}getStatusCommunicationDisabled(){return this.store.get("params.isCommunicationDisabled",!1)}async setStatusDropAllData(t){await this.store.set("params.isDropAllData",t)}getStatusDropAllData(){return this.store.get("params.isDropAllData",!1)}async setSdkVersion(t){await this.store.set("params.sdkVersion",t)}async getSdkVersion(){return await this.store.get("params.sdkVersion")}async setServiceWorkerVersion(t){await this.store.set("params.serviceWorkerVersion",t)}getServiceWorkerVersion(){return this.store.get("params.serviceWorkerVersion")}async setServiceWorkerUrl(t){t&&await this.store.set("params.serviceWorkerUrl",t)}async getServiceWorkerUrl(){return await this.store.get("params.serviceWorkerUrl",s)}async setServiceWorkerScope(t){t&&await this.store.set("params.serviceWorkerScope",t)}async getServiceWorkerScope(){return await this.store.get("params.serviceWorkerScope")}async setLastOpenMessage(t){await this.store.set("params.lastOpenMessage",t)}getLastOpenMessage(){return this.store.get("params.lastOpenMessage")}async setLastOpenApplicationTime(t){await this.store.set("params.lastOpenApplicationTime",t)}async getLastOpenApplicationTime(){return await this.store.get("params.lastOpenApplicationTime")}async setFeatures(t){await this.store.set("params.features",t)}async getFeatures(){return await this.store.get("params.features")}async setInitParams(t){await this.store.set("params.init",t)}async getInitParams(){return await this.store.get("params.init")}async setInboxLastRequestCode(t){await this.store.set("params.inbox.lastRequestCode",t)}async getInboxLastRequestCode(){return await this.store.get("params.inbox.lastRequestCode","")}async setInboxLastRequestTime(t){await this.store.set("params.inbox.lastRequestTime",t)}async getInboxLastRequestTime(){return this.store.get("params.inbox.lastRequestTime",0)}async setInboxNewMessagesCount(t){await this.store.set("params.inbox.newMessagesCount",t)}async getInboxNewMessagesCount(){return this.store.get("params.inbox.newMessagesCount",0)}async setDelayedEvent(t){await this.store.set("params.delayedEvent",t)}getDelayedEvent(){return this.store.get("params.delayedEvent")}async setPromptDisplayCount(t){await this.store.set("params.promptDisplayCount",t)}async getPromptDisplayCount(){return this.store.get("params.promptDisplayCount",0)}async setPromptLastSeenTime(t){await this.store.set("params.promptLastSeenTime",t)}async getPromptLastSeenTime(){return this.store.get("params.promptLastSeenTime",0)}}class nt{constructor(t=new rt,e=Z){this.data=t,this.logger=e}checkDevice(t){return this.createRequest("checkDevice",t)}getConfig(t){return this.createRequest("getConfig",t,"",!0)}applicationOpen(t){return this.createRequest("applicationOpen",t)}registerDevice(t){return this.createRequest("registerDevice",t)}unregisterDevice(t){return this.createRequest("unregisterDevice",t)}deleteDevice(t){return this.createRequest("deleteDevice",t)}messageDeliveryEvent(t){return this.createRequest("messageDeliveryEvent",t)}pushStat(t){return this.createRequest("pushStat",t)}setTags(t){return this.createRequest("setTags",t)}getTags(t){return this.createRequest("getTags",t)}registerUser(t){return this.createRequest("registerUser",t)}registerEmail(t){return this.createRequest("registerEmail",t)}registerEmailUser(t){return this.createRequest("registerEmailUser",t)}setEmailTags(t){return this.createRequest("setEmailTags",t)}postEvent(t){return this.createRequest("postEvent",t)}getInboxMessages(t){return this.createRequest("getInboxMessages",t)}inboxStatus(t){return this.createRequest("inboxStatus",t)}pageVisit(t,e){return this.createRequest("pageVisit",t,e)}setPurchase(t){return this.createRequest("setPurchase",t)}async createRequest(t,e,s,a){const i=await this.data.getApiEntrypoint(),r=a?"":await this.data.getApiToken(),n=s||i+t,o=r?{headers:{Authorization:`Token ${r}`,"Content-Type":"text/plain;charset=UTF-8",Origin:E().location.origin},credentials:"include"}:{},c=await fetch(n,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:e}),...o}),h=await this.checkResponse(c);return h.base_url&&await this.data.setApiEntrypoint(h.base_url),await this.logger.write("apirequest",`${t} call with arguments: ${JSON.stringify(e)} to Pushwoosh has been successful. Result: ${JSON.stringify(h.response)}`),h.response}async checkResponse(t){if(200!==t.status)throw new Error(`Error code: ${t.status}. Error text: ${t.statusText}`);const e=await t.json();if(200!==e.status_code)throw new Error(`Error code: ${e.status_code}. Error text: ${e.status_message}`);return e}}class ot{constructor(t,e=new rt,s=new nt){this.eventBus=t,this.data=e,this.apiClient=s}async checkDevice(){const t=await this.getRequestParams();return await this.apiClient.checkDevice(t)}async checkDeviceSubscribeForPushNotifications(t=!0){let e=localStorage.getItem(a);if(void 0===e||!t){const{exist:t,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,t&&s?i:r),e=localStorage.getItem(a)}return e===i}async getConfig(t){const e=await this.getRequestParams();return this.apiClient.getConfig({...e,features:t})}async applicationOpen(){const t=await this.getRequestParams();return await this.data.setLastOpenApplicationTime(Date.now()),this.apiClient.applicationOpen(t)}async registerDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const t=await this.getRequestParams(),e=await this.data.getTokens();if(!e.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=await this.apiClient.registerDevice({...t,push_token:e.pushToken,auth_token:e.authToken,public_key:e.publicKey});return await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,i),this.eventBus.dispatchEvent("register",{}),s}async unregisterDevice(){const t=await this.getRequestParams(),e=await this.apiClient.unregisterDevice(t);return localStorage.setItem(a,r),this.eventBus.dispatchEvent("unsubscribe",{}),e}async deleteDevice(){const t=await this.getRequestParams(),e=await this.apiClient.deleteDevice(t);return await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,r),this.eventBus.dispatchEvent("unsubscribe",{}),e}async messageDeliveryEvent(t,e,s={}){const a=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...a,hash:t,metaData:s})}async pushStat(t,e,s={}){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:t,metaData:s})}async setTags(t){const{hwid:e,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getEmail();return i&&await this.apiClient.setEmailTags({...a,email:i,tags:t}),this.apiClient.setTags({...a,hwid:e,device_type:s,tags:t})}async getTags(){const t=await this.getRequestParams();return this.apiClient.getTags(t)}async registerUser(t){const{hwid:e,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getDeviceType(),r=`${t}`,n=await this.data.getEmail(),o=await this.apiClient.registerUser({...a,hwid:e,userId:r,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:i});return n&&await this.apiClient.registerEmailUser({...a,email:n,userId:r,ts_offset:60*-(new Date).getTimezoneOffset()}),await this.data.setUserId(`${t}`),await this.data.setStatusUserIdWasChanged(!0),o}async registerEmail(t,e){const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.apiClient.registerEmail({...i,...e,email:t,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(`${t}`),await this.data.setStatusEmailWasChanged(!0),r}async postEvent(t,e){const s=await this.getRequestParams(),a=new Date,i=a.getTime(),r=Math.floor(i/1e3),n=r-a.getTimezoneOffset()/60*3600,o=await this.data.getLastOpenMessage();if(o&&o.expiry>Date.now()){if(e.msgHash)return Promise.reject("attribute msgHash already defined");e={...e,msgHash:o.messageHash}}await this.data.setLastOpenMessage(void 0);const c=await this.apiClient.postEvent({...s,event:t,timestampUTC:r,timestampCurrent:n,attributes:e});return c&&c.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:c.code}),c}async getInboxMessages(t=0){const e=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),a=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...e,count:t,last_code:s,last_request_time:a})}async inboxStatus(t,e){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:t,status:e,time:(new Date).getTime()})}async pageVisit(t){const e=await this.getRequestParams(),s=await this.data.getFeatures(),a=s&&s.page_visit&&s.page_visit.entrypoint;if(a)return this.apiClient.pageVisit({...e,...t},a)}async setPurchase(t){const e=await this.getRequestParams();return this.apiClient.setPurchase({...e,...t})}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const t=await this.data.getApplicationCode(),e=await this.data.getHwid(),s=await this.data.getUserId(),a=await this.data.getDeviceType(),i=await this.data.getDeviceModel(),r=await this.data.getLanguage(),n=await this.data.getSdkVersion();return{application:t,hwid:e,userId:s||e,device_type:a,device_model:i,timezone:60*-(new Date).getTimezoneOffset(),language:r,v:n}}}class ct{constructor(t){this.global=t,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 t=11;switch(!0){case this._isSafari:t=10;break;case this._isOpera||this._isChrome:t=11;break;case this._isFirefox:t=12;break;case this._isEdge:t=150}return t}getBrowserVersion(){const{userAgent:t}=navigator,e=t.match(/\bOPR\/(\d+)/);if(null!==e)return`Opera ${e[1]}`;const s=t.match(/\bEdge\/(\d+)/);if(null!==s)return`Edge ${s[1]}`;const a=t.match(/\bEdg\/(\d+)/);if(null!==a)return`Edge ${a[1]}`;let i=t.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[];const[,r=""]=i;i=i[2]?[r,i[2]]:[navigator.appName,navigator.appVersion,"-?"];const n=t.match(/version\/([.\d]+)/i);return null!==n&&i.splice(1,1,n[1]),i.join(" ")}}class ht{constructor(t,e,s){this.api=t,this.data=e,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(t){const e=t||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void Z.error("You must have permission granted before subscribe!");const s=this.getPushToken(e),a=e.getKey("p256dh"),i=e.getKey("auth");if(!a||!i)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(a))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(i)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:e.endpoint}),await this.api.registerDevice()}async unsubscribe(){const t=await this.getServiceWorkerRegistration(),e=await t.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),e&&await e.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const t=await this.data.getLastPermissionStatus(),e=this.getPermission();if(t!==e)return await this.data.setLastPermissionStatus(e),!0;const s=await this.getCredentials(),a=this.getPushToken(s),i=await this.data.getTokens(),r=a===(i&&i.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const t=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(t),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const t=await this.data.getServiceWorkerUrl(),e=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${T()}`),await navigator.serviceWorker.register(`${t}${s}`,{scope:e})}async trySubscribe(){try{return await this.subscribePushManager()}catch(t){return console.error(t),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const t=await this.getServiceWorkerRegistration(),e=await this.getApplicationServerKey();return t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:e?this.urlBase64ToUint8Array(e):null})}async getCredentials(){const t=await this.getServiceWorkerRegistration();return await t.pushManager.getSubscription()}getPushToken(t){return t?t.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(t){const e=(t+"=".repeat((4-t.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(e),a=new Uint8Array(s.length);for(let t=0;t<s.length;++t)a[t]=s.charCodeAt(t);return a}}class ut{constructor(t,e,s){this.api=t,this.config=s,this.data=e}getPermission(){const{permission:t}=this.getPermissionInfo();return t}checkIsPermissionGranted(){return this.getPermission()===o}checkIsPermissionDefault(){return this.getPermission()===c}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const t={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise((e=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,t,(()=>e()))}))}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void Z.error("You must have permission granted before subscribe!");const{deviceToken:t}=this.getPermissionInfo();await this.data.setTokens({pushToken:t}),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 t=await this.data.getWebSitePushId(),e=void 0!==t&&this.config.webSitePushId!==t;await this.data.setWebSitePushId(this.config.webSitePushId);const s=await this.data.getLastPermissionStatus(),a=this.getPermission();return s!==a?(await this.data.setLastPermissionStatus(a),!0):e}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class dt{constructor(){this.ready=!1,this.moduleRegistry={},this.addEventHandler=(t,e)=>this.eventBus.addEventHandler(t,e),this.removeEventHandler=(t,e)=>this.eventBus.removeEventHandler(t,e),this.dispatchEvent=(t,e)=>this.eventBus.dispatchEvent(t,e),this.debug={async showLog(){const t=await J.getAll();console.log(t)},async showKeyValues(){const t=await G.getAll();console.log(t)},async showMessages(){(await Y.getAll()).forEach((t=>console.log(t)))}},this.eventBus=new tt,this.data=new rt,this.apiClient=new nt(this.data),this.api=new ot(this.eventBus,this.data,this.apiClient),this.platformChecker=new ct(E()),this.inboxModel=new it(this.eventBus,this.data,this.api),this.pwinbox=new et(this.data,this.api,this.inboxModel)}push(t){if(_(t))this.subscribeToLegacyEvents(h,t);else{if(!Array.isArray(t))throw new Error("Invalid command!");if("init"===t[0])this.initialize(t[1]).catch((t=>{console.error("Pushwoosh: Error during initialization",t)}));else if(!this.subscribeToLegacyEvents(t[0],t[1]))throw console.log("Pushwoosh: Unknown command",t),new Error("Unknown command!")}}async subscribe(t=!0){this.isCommunicationDisabled&&Z.error("Communication is disabled!");if(this.driver.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await this.driver.askPermission();const t=this.driver.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:t})}const e=this.driver.getPermission(),s=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(e===o){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!s||t)&&await this.driver.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if(e===n)return this.eventBus.dispatchEvent("permission-denied",{}),void(a&&await this.driver.unsubscribe())}async unsubscribe(){try{await this.driver.unsubscribe()}catch(t){throw Z.error(t,"Error occurred during the unsubscribe"),t}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===i}isDeviceUnregistered(){return localStorage.getItem(a)===r}async isSubscribed(){return this.api.checkDeviceSubscribeForPushNotifications()}async isCommunicationEnabled(){return!await this.data.getStatusCommunicationDisabled()}async setCommunicationEnabled(t=!0){const e=await this.data.getDeviceType(),s=this.driver.checkIsPermissionGranted();await this.data.setStatusCommunicationDisabled(!t),t?(await this.data.setStatusDropAllData(!1),s&&await this.api.registerDevice()):await this.api.unregisterDevice(),this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:t}),await this.api.postEvent("GDPRConsent",{channel:t,device_type:e})}async removeAllDeviceData(){const t=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:t}),await this.api.deleteDevice(),await this.data.clearAll(),await this.data.setStatusDropAllData(!0)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:t}=await this.data.getTokens();return t}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return this.platformChecker.isAvailableNotifications}async sendStatisticsVisitedPage(){const{document:{title:t},location:{origin:e,pathname:s,href:a}}=window;await this.api.pageVisit({title:t,url_path:`${e}${s}`,url:a})}async initialize(t){this.initParams={...M,...t};const e=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(Z.setLevel(e||t.logLevel||"error"),!this.platformChecker.isAvailableNotifications)return;if(!t.applicationCode)throw new Error("Can't find application code!");const s=await this.data.getApplicationCode();s&&s===t.applicationCode||(await this.data.clearAll(),await this.data.setApplicationCode(t.applicationCode));if(!await this.data.getHwid()){const e=t.applicationCode+"_"+T();await this.data.setHwid(e)}await this.data.setDeviceType(this.platformChecker.getPlatformType()),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion()),await this.data.setLanguage(t.tags&&t.tags.Language||navigator.language),await this.data.setApiEntrypoint(t.pushwooshUrl||""),await this.data.setApiToken(t.apiToken||""),await this.data.setSdkVersion("3.45.2");const a=await this.api.getConfig(["page_visit","vapid_key","web_in_apps","events","subscription_prompt"]);await this.onGetConfig(a&&a.features),this.isCommunicationDisabled=await this.data.getStatusCommunicationDisabled(),await this.open();const i=await this.data.getStatusUserIdWasChanged();t.userId&&"user_id"!==t.userId&&!i&&await this.api.registerUser(t.userId);const r=await this.data.getStatusEmailWasChanged();t.email&&""!==t.email&&!r&&(/^\S+@\S+\.\S+$/.test(t.email)?await this.api.registerEmail(t.email):Z.write("error",`can't register invalid email: ${t.email}`)),t.tags&&this.api.setTags(t.tags);const n=await this.data.getApplicationServerKey();this.platformChecker.isAvailableNotifications&&n&&await this.initPushNotifications(t);try{await this.inboxModel.updateMessages()}catch(t){Z.write("error",t)}this.ready=!0,this.eventBus.dispatchEvent("ready",{});const o=await this.data.getDelayedEvent();if(o){const{type:t,payload:e}=o;this.emitLegacyEventsFromServiceWorker(t,e),await this.data.setDelayedEvent(null)}if("serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=t=>this.onServiceWorkerMessage(t)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}})),this.platformChecker.isSafari){const t=/#P(.*)/,e=decodeURIComponent(document.location.hash);t.test(e)&&this.api.pushStat(t.exec(e)[1]).then((()=>history.pushState(null,"","#")))}}async defaultProcess(){const t=this.driver.getPermission();"granted"===t&&await this.data.setLastPermissionStatus(t);const e=await this.data.getStatusCommunicationDisabled(),s=await this.data.getStatusDropAllData(),a=await this.driver.checkIsNeedResubscribe();if(e||s)return void await this.unsubscribe();a&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const i=await this.data.getStatusManualUnsubscribed(),r=await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(t){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",{}),i&&r&&await this.unsubscribe(),(!r&&!i||a)&&await this.subscribe(!0)}}onServiceWorkerMessage(t){const{data:e={}}=t||{},{type:s="",payload:a={}}=e||{};this.emitLegacyEventsFromServiceWorker(s,a)}async open(t){let e=await this.data.getLastOpenApplicationTime();const s=Date.now();e||(e=0);(t||!(s-e<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}async onGetConfig(t){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((t=>t===I))&&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(t){await this.data.setDefaultNotificationImage(t.defaultNotificationImage),await this.data.setDefaultNotificationTitle(t.defaultNotificationTitle),await this.data.setServiceWorkerUrl(t.serviceWorkerUrl),await this.data.setServiceWorkerScope(t.scope),await this.data.setInitParams(t),await this.initDriver();try{await this.defaultProcess()}catch(t){Z.error(t,"Internal error: defaultProcess fail")}}async initDriver(){if(this.platformChecker.isSafari){const{safariWebsitePushID:t}=await this.data.getInitParams();return t?void(this.driver=new ut(this.api,this.data,{webSitePushId:t})):void Z.info("For work with Safari Push Notification add safariWebsitePushID to initParams!")}this.platformChecker.isAvailableServiceWorker&&(this.driver=new ht(this.api,this.data,{}))}sendPostEventVisitedPage(){const{document:{title:t},location:{href:e}}=window;this.api.postEvent(I,{url:e,title:t,device_type:this.platformChecker.platform})}subscribeToLegacyEvents(t,e){let s=!0;switch(!0){case"onLoad"===t:e();break;case t===h:if(this.ready){e(this.api);break}this.eventBus.addEventHandler("ready",(()=>e(this.api)));break;case t in R:this.eventBus.addEventHandler(R[t].name,(s=>{const{prop:a}=R[t];e(this.api,a?s[a]:void 0)}));break;default:s=!1}return s}emitLegacyEventsFromServiceWorker(t,e){switch(t){case v:this.eventBus.dispatchEvent("receive-push",{notification:e});break;case b:this.eventBus.dispatchEvent("open-notification",{notification:e});break;case y:this.eventBus.dispatchEvent("hide-notification",{notification:e});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:e})}}}return e})()));
//# sourceMappingURL=npm.js.map