web-push-notifications 3.122.0 → 3.123.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/npm.js +1 -1
- package/package.json +2 -2
- package/service-worker.js +1 -1
- package/widget-web-popups.js +1 -1
- package/widget-web-popups.js.map +1 -1
package/service-worker.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!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";const t="deviceRegistrationStatus",e="reportedPushPermissionStatus",s="registered",a="unregistered";function i(t,e){if("string"==typeof t)try{return JSON.parse(t)}catch(t){console.log(t)}return void 0===t&&void 0!==e?e:t}function r(){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 n=t=>"function"==typeof t;function o(t){const e=new WeakSet;return async s=>{if(e.has(s))return!1;const a=await function(t,e){let s;const a=new Promise(t=>{s=setTimeout(()=>t(!1),e)}),i=t.then(()=>!0,()=>!0);return Promise.race([i,a]).finally(()=>clearTimeout(s))}(s,t);return a||e.add(s),a}}const c="keyValue",u="messages",h="inboxMessages";function d(t,e){return function(s){s.objectStoreNames.contains(t)||e(s)}}const l=[d(c,function(t){t.createObjectStore(c,{keyPath:"key"})}),d("log",function(t){const e=t.createObjectStore("log",{keyPath:"id",autoIncrement:!0});e.createIndex("environment","environment",{unique:!1}),e.createIndex("date","date",{unique:!1}),e.createIndex("type","type",{unique:!1})}),d(u,function(t){t.createObjectStore(u,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),d(h,function(t){const e="status",s=t.createObjectStore(h,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(e,e,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class g{get all(){return l}}class p{constructor(t,e=new g){this.db=t,this.migrationsBuilder=e}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(t){t.forEach(t=>{t(this.db)})}}function m(t,e){console.info("onversionchange",e),t.close()}let w;function y(){return w||(w=new Promise((t,e)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const a=s.target.result;a.onversionchange=m.bind(null,a,e),t(a)},s.onerror=()=>e(s.error),s.onupgradeneeded=t=>{const s=t.target.result;s.onversionchange=m.bind(null,s,e);new p(s).applyMigrations()}})),w}function b(t){return y().then(e=>new Promise((s,a)=>t(e,s,a)))}class f{_add(t){return b((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 b((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 b((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 v=(P=c,{get:(t,e)=>b((s,a,i)=>{const r=s.transaction(P).objectStore(P).get(t);let n,o=!1,c=!1;const u=()=>{clearTimeout(n),o?a(r.result?.value||e):c?i(r.error):n=setTimeout(u,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,u()}),getAll:()=>b((t,e,s)=>{const a={},i=t.transaction(P).objectStore(P).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)=>b((s,a,i)=>{const r=s.transaction([P],"readwrite").objectStore(P).put({key:t,value:e});let n,o=!1,c=!1;const u=()=>{clearTimeout(n),o?a(t):c?i(r.error):n=setTimeout(u,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,u()})});var P;const S=new class extends f{constructor(){super(...arguments),this.name="log",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)}},C=new class extends f{constructor(){super(...arguments),this.name=u,this.maxItems=25}add(t){return this._add({...t,date:new Date})}},x={error:1,info:2,debug:3};let D=3;const I={setLevel(t){x[t]||(t="error"),D=x[t]},write(t,e,s){return"error"===t?this.error(e):this.info(e),S.add(t,e,s)}};Object.keys(x).forEach(t=>{const e=x[t];I[t]=(...s)=>{e<=D&&(console.groupCollapsed(t),console.info("",...s),console.trace("trace"),console.groupEnd())}});const k="silent",T="fatal",M="error",R="warn",E="info",_="debug",W={[k]:0,[T]:10,[M]:20,[R]:30,[E]:40,[_]:50};function A(t){const{code:e,text:s,type:a}=t,i=function(t){switch(t){case"fatal":case"error":return console.error;case"warn":case"info":case"debug":return console.log}}(a);console.groupCollapsed(a),i(e?`${e}: ${s}`:s),console.groupEnd()}const q=new class{constructor(t){this.relations=W,this.level=t&&void 0!==t.level?t.level:"error",this.applicationType=t&&void 0!==t.applicationType?t.applicationType:"sdk",this.subscribers=t&&void 0!==t.subscribers?t.subscribers:[]}updateLogLevel(t){this.level=t}updateApplicationType(t){this.applicationType=t}updateApplicationCode(t){this.applicationCode=t}updateDomain(t){this.domain=t}updateDeviceInfo(t){this.deviceInfo=t}subscribe(t,e){this.subscribers.push({handler:e,level:t})}async log(t){const e=[],{options:s,...a}=t;let i=a;if(s){const{handler:t,...e}=s;i={...a,...e}}const r=this.getMessage(i);this.subscribers.forEach(s=>{s.level===t.type&&this.relations[s.level]<=this.relations[this.level]&&e.push(s.handler.call(null,r))}),s&&s.handler&&"silent"!==this.level&&s.handler.call(null,r),await Promise.all(e)}async debug(t,e){return this.log({type:"debug",text:t,options:e})}async info(t,e){return this.log({type:"info",text:t,options:e})}async warn(t,e,s){return this.log({type:"warn",text:t,code:e,options:s})}async error(t,e,s){return this.log({type:"error",text:t,code:e,options:s})}async fatal(t,e,s){return this.log({type:"fatal",text:t,code:e,options:s})}async errorAndThrow(t,e,s){return this.logAndThrow({type:"error",text:t,code:e,options:s})}async errorAndReject(t,e,s,a){return this.logAndReject(t,{type:"error",text:e,code:s,options:a})}async fatalAndThrow(t,e,s){return this.logAndThrow({type:"fatal",text:t,code:e,options:s})}async fatalAndReject(t,e,s,a){return this.logAndReject(t,{type:"fatal",text:e,code:s,options:a})}async logAndThrow(t){await this.log(t);const e=new Error(t.text);throw t.code&&(e.code=t.code),e}async logAndReject(t,e){await this.log(e);const s=new Error(e.text);e.code&&(s.code=e.code),t(s)}getMessage(t){return{applicationCode:this.applicationCode,domain:this.domain,applicationType:this.applicationType,deviceInfo:this.deviceInfo,...t}}}({level:"error",subscribers:[{level:"fatal",handler:A},{level:"error",handler:A}]});async function N(t){const e=L(t);return q.fatal(e.text,e.code,e.options)}function L(t){const{message:e,code:s,error:a,...i}=t,r=function(t){let e=new Error("unknown error");"string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t||(e.message=t.toString());t instanceof Error&&(e=t);return e}(a);return{text:e,code:s,options:{...i,errorText:r.message,errorStack:r.stack}}}class U{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()}}const O=["classic","captioned","banner","carousel"];function F(t){return(Array.isArray(t)?t:[]).filter(t=>!!t&&!!t.imageUrl).slice(0,5)}const j=/^#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;const V=/^(?:javascript|vbscript|data|blob|file):/i,B=/^[a-z][a-z\d+\-.]*:/i;function $(t){return t.split("").filter(t=>t.charCodeAt(0)>32&&127!==t.charCodeAt(0)).join("")}function H(t){const e=$(t);return B.test(e)&&!V.test(e)}const K=/^intent:/i;const z=["id","title","text_color","bg_color"];function J(t){return"string"==typeof t?t:""}function G(t){return!!t&&"object"==typeof t&&!Array.isArray(t)}function Y(t){const e=J(t);return e&&H(e)&&!function(t){return K.test($(t))}(e)?e:""}function Q(t,e){return e?"":(s=t,("string"==typeof s&&j.test(s)?s:void 0)||"").toUpperCase();var s}function X(t){return Object.keys(t).filter(t=>-1===z.indexOf(t)).reduce((e,s)=>(e[s]=t[s],e),{})}const Z=/^[0-2]$/;function tt(t){return G(t)&&"string"==typeof t.title&&""!==t.title.trim()}function et(t){return(Array.isArray(t.buttons)?t.buttons:[]).filter(tt).slice(0,3).map((t,e)=>{const s="string"==typeof t.id&&Z.test(t.id);return function(t,e,s){const a=Y(t.url),i={id:e,title:J(t.title),textColor:Q(t.text_color,s),bgColor:Q(t.bg_color,s),action:"custom",url:a,copyText:J(t.copy_text),data:G(t.data)?t.data:{}};if(s){const e="dismiss"===t.action||"markRead"===t.action||"markread"===t.action;a&&!e?i.action="open":i.data=X(t)}else"open"===t.action||"copy"===t.action||"custom"===t.action?i.action=t.action:i.data=X(t);return i}(t,s?t.id:String(e),!s)})}function st(t,e){return e||t.image||""}function at(t){const e=["displayType","carousel","buttons","image"];return Object.keys(t).filter(t=>-1===e.indexOf(t)).reduce((e,s)=>(e[s]=t[s],e),{})}class it{constructor(t,e,s,a={},i=()=>Promise.resolve(void 0),r=new U){this.data=t,this.api=e,this.inboxModel=s,this.moduleRegistry=a,this.loadWebPopups=i,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(t){try{return JSON.parse(t)||{}}catch(e){return I.write("error",`Pushwoosh: cannot parse inbox action_params: ${t}`,e),{}}}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=this.parseActionParams(e),u=function(t){const e=t?.u;if(!e)return{};if("string"==typeof e)try{return JSON.parse(e)||{}}catch{return{}}return"object"==typeof e?e:{}}(c),h=function(t){return(Array.isArray(t.carousel)?t.carousel:[]).filter(t=>!!t&&!!t.image).slice(0,5).map(t=>({imageUrl:t.image,caption:t.title||"",link:t.url&&H(t.url)?t.url:""}))}(u),d=function(t,e,s){return t?.b||s||e.image||""}(c,u,s),l=function(t){const e=!!t.title,s=!!t.body,a=function(t){return t.bannerUrl||t.iconUrl||""}(t);let i=t.layoutType;switch(O.includes(i)||(i=t.bannerUrl&&!e?"banner":t.bannerUrl&&e&&s?"captioned":"classic"),i){case"banner":return a?"banner":"classic";case"captioned":return a&&e&&s?"captioned":"classic";case"carousel":return e&&s&&F(t.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:a,body:n,iconUrl:st(u,s),bannerUrl:c.b,layoutType:u.displayType,carousel:h}),g=st(u,s)||await this.data.getDefaultNotificationImage(),p=a||await this.data.getDefaultNotificationTitle();return this.dateModule.date=new Date(1e3*parseInt(i)),{title:p,imageUrl:g,iconUrl:g,heroUrl:d,layout:l,carousel:h,customData:at(u),webPopupCode:c.wp||"",buttons:et(u),code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(t,c),link:c?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const 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=this.parseActionParams(e.action_params),a=this.messageTypeFactory(e.action_type,s),i=2===a||3===a;var r;!await this.showWebPopup(s.wp)&&i&&null!=s.l&&((r=s.l)&&!V.test($(r)))&&(document.location.href=s.l),e.status=3,await this.inboxModel.putMessage(e),await this.api.inboxStatus(e.order,e.status)}async reportButtonClick(t,e){const s=await this.inboxModel.getMessage(t),a=3!==s.status;a&&await this.sendStatus(s.order,3),await this.sendStatus(s.order,6,e),a&&(s.status=3,await this.inboxModel.putMessage(s))}sendStatus(t,e,s){return new Promise(a=>{this.api.inboxStatus(t,e,s,{keepalive:!0,onSent:a}).catch(s=>I.write("error",`Pushwoosh: inbox status ${e} for "${t}" failed`,s)).finally(a)})}async showWebPopup(t){if(!t)return!1;try{const e=this.moduleRegistry.webPopups??await this.loadWebPopups();return e?await e.show(t):(I.write("error",`Pushwoosh: inbox message opens web popup "${t}", but the web popups widget could not be loaded`),!1)}catch(e){return I.write("error",`Pushwoosh: failed to open web popup "${t}" from inbox`,e),!1}}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.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class rt{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 nt{getDB(){return y()}async put(t,e,s){const a=await this.getDB();return new rt(a,t).put(e,s)}async delete(t,e){const s=await this.getDB();return new rt(s,t).delete(e)}async get(t,e,s){const a=await this.getDB();return new rt(a,t).get(e,s)}async getAll(t){const e=await this.getDB(),s=new rt(e,t);return await s.getAll()||[]}async count(t,e){const s=await this.getDB();return new rt(s,t).count(e)}async countByIndex(t,e,s){const a=await this.getDB(),i=new rt(a,t);return i.index=e,i.countByIndex(s)}}class ot{constructor(t,e,s,a=new nt,i=new U){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 it(this.data,this.api,this)})}}const ct={"&":"&","<":"<",">":">",""":'"',"'":"'"},ut=/&(?:amp|lt|gt|quot|#39);/g,ht=RegExp(ut.source);const dt=t=>`params.${t}`;class lt{constructor(t=v){this.store=t}async clearAll(){const t=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const e of t)await this.store.set(dt(e),void 0)}async setApplicationCode(t){await this.store.set(dt("applicationCode"),t)}async getApplicationCode(){return this.store.get(dt("applicationCode"))}async setApiToken(t){return await this.store.set(dt("apiToken"),t)}async getApiToken(){return this.store.get(dt("apiToken"))}async setHwid(t){await this.store.set(dt("hwid"),t)}async getHwid(){return this.store.get(dt("hwid"))}async setDeviceType(t){await this.store.set(dt("deviceType"),t)}async getDeviceType(){return this.store.get(dt("deviceType"))}async setFormFactor(t){await this.store.set(dt("formFactor"),t)}async getFormFactor(){return this.store.get(dt("formFactor"))}async setDeviceModel(t){await this.store.set(dt("deviceModel"),t)}async getDeviceModel(){return this.store.get(dt("deviceModel"))}async setLanguage(t){await this.store.set(dt("language"),t)}async getLanguage(){return this.store.get(dt("language"),"en")}async setStatusLanguageWasChanged(t){await this.store.set(dt("languageWasChanged"),t)}async getStatusLanguageWasChanged(){return this.store.get(dt("languageWasChanged"),!1)}async setApiEntrypoint(t){await this.store.set(dt("apiEntrypoint"),t)}async getApiEntrypoint(){return this.store.get(dt("apiEntrypoint"),"https://api.pushwoosh.com/json/1.3/")}async setTokens(t){await this.store.set(dt("tokens"),t)}getTokens(){return this.store.get(dt("tokens"))}async setApplicationServerKey(t){await this.store.set(dt("applicationServerKey"),t)}async getApplicationServerKey(){return this.store.get(dt("applicationServerKey"))}async setIsVapidChanged(t){await this.store.set(dt("isVapidChanged"),t)}async getIsVapidChanged(){return this.store.get(dt("isVapidChanged"),!1)}async setWebVapidConfigured(t){await this.store.set(dt("webVapidConfigured"),t)}async getWebVapidConfigured(){return this.store.get(dt("webVapidConfigured"),!1)}async setWebSitePushId(t){await this.store.set(dt("webSitePushId"),t)}async getWebSitePushId(){return this.store.get(dt("webSitePushId"))}async setDefaultNotificationImage(t){await this.store.set(dt("defaultNotificationImage"),t)}async getDefaultNotificationImage(){return this.store.get(dt("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(t){await this.store.set(dt("defaultNotificationTitle"),t)}async getDefaultNotificationTitle(){return this.store.get(dt("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(t){await this.store.set(dt("userId"),t?`${t}`:void 0)}async getUserId(){return this.store.get(dt("userId"))}async getFeatureFlags(){return this.store.get(dt("featureFlags"))}async setFeatureFlags(t){await this.store.set(dt("featureFlags"),t)}async getFeatureFlagImpressions(){return this.store.get(dt("featureFlagImpressions"),{})}async setFeatureFlagImpressions(t){await this.store.set(dt("featureFlagImpressions"),t)}async setStatusUserIdWasChanged(t){await this.store.set(dt("userIdWasChanged"),t)}async getStatusUserIdWasChanged(){return this.store.get(dt("userIdWasChanged"),!1)}async setEmail(t){await this.store.set(dt("email"),t?`${t}`:void 0)}async getEmail(){return this.store.get(dt("email"))}async setStatusEmailWasChanged(t){await this.store.set(dt("emailWasChanged"),t)}async getStatusEmailWasChanged(){return this.store.get(dt("emailWasChanged"),!1)}async setSmsNumber(t){await this.store.set(dt("smsNumber"),t?`${t}`:void 0)}async getSmsNumber(){return this.store.get(dt("smsNumber"))}async setStatusSmsNumberWasChanged(t){await this.store.set(dt("smsNumberWasChanged"),t)}async getStatusSmsNumberWasChanged(){return this.store.get(dt("smsNumberWasChanged"),!1)}async setWhatsAppNumber(t){await this.store.set(dt("whatsAppNumber"),t?`${t}`:void 0)}async getWhatsAppNumber(){return this.store.get(dt("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(t){await this.store.set(dt("whatsAppNumberWasChanged"),t)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(dt("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(t){await this.store.set(dt("isLastPermissionStatus"),t)}async getLastPermissionStatus(){return this.store.get(dt("isLastPermissionStatus"))}async setStatusManualUnsubscribed(t){await this.store.set(dt("isManualUnsubscribed"),t)}getStatusManualUnsubscribed(){return this.store.get(dt("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(t){await this.store.set(dt("isCommunicationDisabled"),t)}getStatusCommunicationDisabled(){return this.store.get(dt("isCommunicationDisabled"),!1)}async setCommunicationEnabled(t){await this.store.set(dt("communicationEnabled"),t)}getCommunicationEnabled(){return this.store.get(dt("communicationEnabled"))}async setStatusDropAllData(t){await this.store.set(dt("isDropAllData"),t)}getStatusDropAllData(){return this.store.get(dt("isDropAllData"),!1)}async setSdkVersion(t){await this.store.set(dt("sdkVersion"),t)}async getSdkVersion(){return this.store.get(dt("sdkVersion"))}async setServiceWorkerVersion(t){await this.store.set(dt("serviceWorkerVersion"),t)}getServiceWorkerVersion(){return this.store.get(dt("serviceWorkerVersion"))}async setServiceWorkerUrl(t){t&&await this.store.set(dt("serviceWorkerUrl"),t)}async getServiceWorkerUrl(){return this.store.get(dt("serviceWorkerUrl"),"/pushwoosh-service-worker.js")}async setServiceWorkerScope(t){t&&await this.store.set(dt("serviceWorkerScope"),t)}async getServiceWorkerScope(){return this.store.get(dt("serviceWorkerScope"))}async setLastOpenMessage(t){await this.store.set(dt("lastOpenMessage"),t)}getLastOpenMessage(){return this.store.get(dt("lastOpenMessage"))}async setLastOpenApplicationTime(t){await this.store.set(dt("lastOpenApplicationTime"),t)}async getLastOpenApplicationTime(){return this.store.get(dt("lastOpenApplicationTime"))}async setFeatures(t){await this.store.set(dt("features"),t)}async getFeatures(){return this.store.get(dt("features"))}async setInitParams(t){await this.store.set(dt("init"),t)}async getInitParams(){return this.store.get(dt("init"))}async setInboxLastRequestCode(t){await this.store.set(dt("inbox.lastRequestCode"),t)}async getInboxLastRequestCode(){return this.store.get(dt("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(t){await this.store.set(dt("inbox.lastRequestTime"),t)}async getInboxLastRequestTime(){return this.store.get(dt("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(t){await this.store.set(dt("inbox.newMessagesCount"),t)}async getInboxNewMessagesCount(){return this.store.get(dt("inbox.newMessagesCount"),0)}async setDelayedEvent(t){await this.store.set(dt("delayedEvent"),t)}getDelayedEvent(){return this.store.get(dt("delayedEvent"))}async setPromptDisplayCount(t){await this.store.set(dt("promptDisplayCount"),t)}async getPromptDisplayCount(){return this.store.get(dt("promptDisplayCount"),0)}async setPromptLastSeenTime(t){await this.store.set(dt("promptLastSeenTime"),t)}async getPromptLastSeenTime(){return this.store.get(dt("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(t){await this.store.set(dt("subscriptionWidgetHistory"),t)}async getSubscriptionWidgetHistory(){return this.store.get(dt("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(t){await this.store.set(dt("logLevel"),t)}async getLogLevel(){return this.store.get(dt("logLevel"),"error")}async getShownWebPopups(){return this.store.get(dt("shownWebPopups"),[])}async addShownWebPopup(t){const e=await this.getShownWebPopups();e.includes(t)||(e.push(t),await this.store.set(dt("shownWebPopups"),e))}async setIsRecurringVisitor(t){await this.store.set(dt("isRecurringVisitor"),t)}async getIsRecurringVisitor(){return this.store.get(dt("isRecurringVisitor"),!1)}}class gt{constructor(t,e=new lt,s=new U){if("data"in t){const e=t;this.payload=e.data}else this.payload=t;this.data=e,this.code=`notificationCode-${Date.now()}-${Math.random().toString(16).slice(2,10)}`,this.dateModule=s}async getIcon(){return this.payload.i||await this.data.getDefaultNotificationImage()}async getTitle(){return this.payload.header||await this.data.getDefaultNotificationTitle()}get silent(){return Boolean(this.payload.silent)}get body(){return this.payload.body}get messageHash(){return this.payload.p||""}get metaData(){return this.payload.md?i(this.payload.md):{}}get image(){return this.payload.image||""}get buttons(){return this.payload.buttons?i(this.payload.buttons):[]}get customData(){return this.payload.u?i(this.payload.u):{}}get campaignCode(){return this.payload.pwcid||""}get link(){return this.payload.l?(t=this.payload.l)&&ht.test(t)?t.replace(ut,t=>ct[t]):t:"/";var t}get inboxId(){return this.payload.pw_inbox||""}get inboxParams(){return this.payload.inbox_params?i(this.payload.inbox_params):{}}get inboxRemovalTime(){return this.inboxParams&&this.inboxParams.rt?this.inboxParams.rt:(this.dateModule.date=new Date,this.dateModule.addDays(1),this.dateModule.getUtcTimestamp().toString())}async getInboxImage(){return this.inboxParams&&this.inboxParams.image?this.inboxParams.image:""}get rootParams(){const{body:t,p:e,header:s,i:a,u:i,l:r,pwcid:n,image:o,buttons:c,pw_inbox:u,inbox_params:h,...d}=this.payload;return d}async getNotificationOptionsPayload(){const t=await this.getTitle(),e=await this.getIcon();return{...this.rootParams,body:this.body,title:t,icon:e,image:this.image,buttons:this.buttons,customData:this.customData,metaData:this.metaData,campaignCode:this.campaignCode,openUrl:this.link,messageHash:this.messageHash}}async getShowNotificationOptions(){const t=await this.getIcon(),e=this.buttons.map((t,e)=>(t.action=t.id||`action-${e}`,t));return{renotify:!0,...this.rootParams,body:this.body,icon:t,tag:JSON.stringify({url:this.link,messageHash:this.messageHash,customData:this.customData,metaData:this.metaData}),data:{code:this.code,buttons:e,image:this.image,campaignCode:this.campaignCode,inboxId:this.inboxId},silent:this.silent,actions:e,image:this.image,buttons:e}}async getInboxMessage(){this.dateModule.date=new Date;const t=this.dateModule.getTimestamp().toString();return{title:this.payload.header||"",image:await this.getInboxImage(),status:1,order:this.dateModule.getInboxFakeOrder(),inbox_id:this.inboxId,send_date:t,rt:this.inboxRemovalTime,text:this.body,action_type:1,action_params:JSON.stringify({l:this.link})}}}function pt(){const{pathname:t}=window.location;try{return decodeURIComponent(t)}catch{return t}}class mt extends Error{constructor(t,e){super(t),this.name="ApiRequestError",this.statusCode=e}}class wt{constructor(t=new lt,e=I){this.data=t,this.logger=e}checkDevice(t){return this.createRequest("checkDevice",t)}getConfig(t){return this.createRequest("getConfig",t)}getPopupForms(t){return this.createRequest("getPopupForms",t)}getPopupFormContent(t){return this.createRequest("getPopupFormContent",t)}recordPopupFormEvent(t){return this.createRequest("recordPopupFormEvent",t)}submitPopupForm(t){return this.createRequest("submitPopupForm",t)}getWebPlacements(t){return this.createRequest("getWebPlacements",t)}trackWebPlacement(t){return this.createRequest("trackWebPlacement",t)}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,e){return this.createRequest("postEvent",t,e)}getInboxMessages(t){return this.createRequest("getInboxMessages",t)}inboxStatus(t,e){return this.createRequest("inboxStatus",t,e)}multiRegisterDevice(t){return this.createRequest("multiRegisterDevice",t)}sdkUsage(t,e){return this.createRequest("sdkUsage",t,e)}async createRequest(t,e,s={}){const a=await this.data.getApiEntrypoint(),i=await this.data.getApiToken(),r=a+t,n=i?{headers:{Authorization:`Token ${i}`,"Content-Type":"text/plain;charset=UTF-8",Origin:globalThis.location.origin},credentials:"include"}:{},o=fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:e}),...n,keepalive:s.keepalive});s.onSent?.();const c=await o,u=await this.checkResponse(c);return u.base_url&&await this.data.setApiEntrypoint(u.base_url),await this.logger.write("apirequest",`${t} call with arguments: ${JSON.stringify(e)} to Pushwoosh has been successful. Result: ${JSON.stringify(u.response)}`),u.response}async checkResponse(t){if(200!==t.status){let e,s=`status: ${t.status}. statusText: ${t.statusText}.`;try{const a=await t.json();a&&"number"==typeof a.status_code&&(e=a.status_code),a&&a.status_message&&(s+=` status_code: ${a.status_code}. status_message: ${a.status_message}.`)}catch(t){}throw new mt(s,e)}const e=await t.json();if(200!==e.status_code)throw new mt(`Error code: ${e.status_code}. Error text: ${e.status_message}`,"number"==typeof e.status_code?e.status_code:void 0);return e}}function yt(t){try{return t?Intl.getCanonicalLocales(t)[0]??"":""}catch{return""}}class bt{constructor(t,e,s){this.api=t,this.data=e,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return"granted"===this.getPermission()}checkIsPermissionDefault(){return"default"===this.getPermission()}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 I.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&&(await this.data.setLastPermissionStatus(e),void 0!==t))return!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=${r()}`),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 ft{constructor(t,e,s){this._canceled=!1,this.showNotificationOptions=t,this.body=e,this.title=s}async show(){if(this._canceled)return;const t=this.showNotificationOptions;t.silent||await self.registration.showNotification(this.title,t)}cancel(){this._canceled=!0}}const vt=new class{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||r(),a=this.handlers[t];return a?(a.forEach(t=>{n(t)&&setTimeout(()=>{t({...e,eventId:s})},0)}),s):s},this.handlers={}}},Pt=new lt,St=new class{constructor(t,e=new lt,s=new wt,a=()=>!1,i=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=o(1e4),this.eventBus=t,this.data=e,this.apiClient=s,this.getIsCommunicationDisabled=a,this.getInitUserId=i,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(t=>{throw this.checkDevicePromise=null,t})),this.checkDevicePromise}async requestCheckDevice(){const t=await this.getRequestParams();return await this.apiClient.checkDevice(t)}async checkDeviceSubscribeForPushNotifications(e=!0){let i=localStorage.getItem(t);if(null===i||!e){const{exist:e,push_token_exist:r}=await this.checkDevice();localStorage.setItem(t,e&&r?s:a),i=localStorage.getItem(t)}return i===s}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(t=>{throw this.ensureDeviceRegisteredPromise=null,t})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:t}=await this.checkDevice();if(t)return!1;const e=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:e,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(e),!0}async reportPushPermissionStatus(t=!1){const s=this.getPushPermissionStatus();if(s&&s!==this.reportingPushPermissionStatus&&s!==localStorage.getItem(e)){this.reportingPushPermissionStatus=s;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!t&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:s,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(s)}finally{this.reportingPushPermissionStatus===s&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(e)}rememberReportedPushPermissionStatus(t){t&&localStorage.setItem(e,t)}async getConfig(t){const e=await this.getRequestParams();return this.apiClient.getConfig({...e,features:t})}async applicationOpen(){const t=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const e=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...t,push_permission_status:e,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(e),s}async registerDevice(){const t=this.requestRegisterDevice();this.registerDevicePromise=t;try{return await t}finally{this.registerDevicePromise===t&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),a=await this.data.getTokens();if(!a.pushToken)throw new Error("Can't register device: pushToken is not exist!");const i=this.getPushPermissionStatus(),r=await this.apiClient.registerDevice({...e,push_permission_status:i,locale:await this.getLocale(),page:pt(),push_token:a.pushToken,auth_token:a.authToken,public_key:a.publicKey});return this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(i),await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(t,s),this.eventBus.dispatchEvent("register",{}),r}async unregisterDevice(){const e=await this.getRequestParams(),s=await this.apiClient.unregisterDevice(e);return this.checkDevicePromise=null,localStorage.setItem(t,a),this.eventBus.dispatchEvent("unsubscribe",{}),s}async deleteDevice(){const e=await this.getRequestParams(),s=await this.apiClient.deleteDevice(e);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(t,a),this.eventBus.dispatchEvent("unsubscribe",{}),s}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={},a){const i=await this.getRequestParams();return await this.apiClient.pushStat({...i,hash:t,metaData:s,...a?{button_id:a}:{}})}async setTags(t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));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 setLanguage(t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:t}))}async setLocale(t){if(!t)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const e=yt(t.trim().replace(/_/g,"-"));e&&(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return yt(await this.data.getLanguage())||void 0}async registerUser(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${t}`,o=await this.data.getUserId(),c=await this.apiClient.registerUser({...i,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),n&&n!==o&&this.eventBus.dispatchEvent("change-user-id",{userId:n}),e&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(t))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),a=await this.apiClient.registerEmail({...s,email:t,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(t),e&&await this.data.setStatusEmailWasChanged(!0),a}async registerSmsNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:a}=await this.getIdentityRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:t,device_type:18});return await this.data.setSmsNumber(t),e&&await this.data.setStatusSmsNumberWasChanged(!0),i}async registerWhatsappNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:a}=await this.getIdentityRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:t,device_type:21});return await this.data.setWhatsAppNumber(t),e&&await this.data.setStatusWhatsAppNumberWasChanged(!0),i}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:t})}async recordPopupFormEvent(t,e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:t,event:e};return this.apiClient.recordPopupFormEvent(3===e?{...s,clickId:r()}:s)}async getWebPlacements(){if(this.getIsCommunicationDisabled())return[];const t=await this.apiClient.getWebPlacements(await this.getRequestParams());return t?.web_placements??[]}async trackWebPlacement(t,e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.trackWebPlacement({...await this.getRequestParams(),hash:t,action:e})}async submitPopupForm(t,e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:t,email:e.email,tags:e.tags,policy_accepted:e.policyAccepted})}async sdkUsage(t,e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams();return this.apiClient.sdkUsage({...s,...t},e)}async postEvent(t,e,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const a=await this.getRequestParams(),i=new Date,r=i.getTime(),n=Math.floor(r/1e3),o=n-i.getTimezoneOffset()/60*3600,c=await this.data.getLastOpenMessage();if(c&&c.expiry>Date.now()){if(e.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));e={...e,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const u=await this.apiClient.postEvent({...a,event:t,timestampUTC:n,timestampCurrent:o,attributes:e},s);return u&&u.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:u.code}),u?.web_placements?.length&&this.eventBus.dispatchEvent("receive-web-placements",{placements:u.web_placements}),u}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,s,a){const i=await this.getRequestParams();return this.apiClient.inboxStatus({...i,inbox_code:t,status:e,time:(new Date).getTime(),...void 0===s?{}:{button_id:s}},a)}async multiRegisterDevice(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const a=await this.data.getApplicationCode(),i=await this.data.getDeviceModel(),r=await this.data.getDeviceType(),n=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),u=await this.data.getHwid();!e.push_devices&&c.pushToken&&await this.requireHwid();const h={application:a,...e};if(e.user_id){h.user_id=String(e.user_id);await this.data.getUserId()!==h.user_id&&(await this.data.setUserId(h.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(e.email){if(!/^\S+@\S+\.\S+$/.test(e.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==e.email&&(await this.data.setEmail(e.email),await this.data.setStatusEmailWasChanged(!0))}if(e.sms_phone_number){if(!/^\+?[0-9]+$/.test(e.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==e.sms_phone_number&&(await this.data.setSmsNumber(e.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(e.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(e.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==e.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(e.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(h.language?(await this.data.setLanguage(h.language),await this.data.setStatusLanguageWasChanged(!0)):h.language=n,!h.timezone){const t=60*-(new Date).getTimezoneOffset();h.timezone=String(t)}if(!h.push_devices&&c.pushToken){const t={hwid:u,platform:r,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||i){const e={};c.publicKey&&(e.public_key=c.publicKey),c.authToken&&(e.auth_token=c.authToken),i&&(e.browser=i),t.platformData=e}h.push_devices=[t]}const d=await this.apiClient.multiRegisterDevice(h);return h.push_devices?.length&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(t,s),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const t=await this.requireHwid(),e=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:t,device_type:e}}async getIdentityRequestParams(){const t=await this.data.getApplicationCode(),e=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),a=await this.data.getDeviceModel(),i=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!e)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:t,userId:s||e,device_model:a,timezone:n,language:i,v:r}}async requireHwid(){const t=await this.data.getHwid();if(!t)throw new Error("Pushwoosh: the SDK storage does not keep the hwid in this browser (in-app webview, private window or insecure context), so this device cannot be identified. Requests that need an hwid are not sent.");return t}}(vt,Pt);Pt.getLogLevel().then(t=>{t&&I.setLevel(t)});const Ct=self.Pushwoosh=new class{constructor(t,e,s){this._listeners={},this.eventBus=t,this.data=e,this.api=s}push(t){Array.isArray(t)&&"onPush"===t[0]&&n(t[1])&&(this._listeners[t[0]]||(this._listeners[t[0]]=[]),this._listeners[t[0]].push(t[1]))}getListeners(t){return this._listeners[t]||[]}async initApi(){return Promise.resolve()}}(vt,Pt,St),xt=[];async function Dt(t){(await self.clients.matchAll()).forEach(e=>e.postMessage(t))}async function It(t){const{notification:e={}}=t,{data:s}=e,a=i(e.tag,{});let r,n="";if(t.action&&Array.isArray(s.buttons)){const e=s.buttons.find(e=>e.action===t.action)||{};n=e.url,r=e.id}else n=a.url;return{title:e.title,body:e.body,icon:e.icon,buttons:s.buttons,image:s.image,code:s.code,campaignCode:s.campaignCode,inboxId:s.inboxId,messageHash:a.messageHash,customData:a.customData,metaData:a.metaData,openUrl:a.url,tag:e.tag,url:n,buttonId:r}}async function kt(t){const e=await Ct.data.getApplicationCode(),s=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onInstallEventHandler",code:"FATAL-SW-001",error:t,applicationCode:e,workerVersion:s})}async function Tt(t){const e=await Ct.data.getApplicationCode(),s=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onActivateEventHandler",code:"FATAL-SW-002",error:t,applicationCode:e,workerVersion:s})}async function Mt(t){const e=await Ct.data.getApplicationCode(),s=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onNotificationClickEventHandler",code:"FATAL-SW-004",error:t,applicationCode:e,workerVersion:s})}async function Rt(t){const e=await Ct.data.getApplicationCode(),s=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onNotificationCloseEventHandler",code:"FATAL-SW-005",error:t,applicationCode:e,workerVersion:s})}async function Et(t){const e=await Ct.data.getApplicationCode(),s=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onPushSubscriptionChange",code:"FATAL-SW-006",error:t,applicationCode:e,workerVersion:s})}return self.addEventListener("install",function(t){return t.waitUntil(async function(){await Promise.all([Ct.data.setServiceWorkerVersion("3.122.0"),I.write("info","install")]),await self.skipWaiting()}().catch(kt))}),self.addEventListener("activate",function(t){t.waitUntil(async function(){await Promise.all([I.write("info","activate")]),await self.clients.claim()}().catch(Tt))}),self.addEventListener("push",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await t.data.json(),s=new gt(e),a=await s.getNotificationOptionsPayload(),i=await s.getShowNotificationOptions(),r=s.messageHash;await I.write("info",JSON.stringify(a),"onPush");const n=new ft(i,s.body,await s.getTitle()),o=Ct.getListeners("onPush");await o.reduce((t,e)=>t.then(()=>e(n)),Promise.resolve());const c=[n.show(),C.add({payload:e,parsedPayload:a,showOptions:i}),Dt({type:"onPushDelivery",payload:a})];if(r&&c.push(Ct.initApi().then(()=>Ct.api.messageDeliveryEvent(r,!0,a.metaData))),""!==s.inboxId){const t=new ot(Ct.eventBus,Ct.data,Ct.api),e=new it(Ct.data,Ct.api,t),a=await s.getInboxMessage(),i=await e.publicMessageBuilder(a);c.push(t.putMessage(a),Dt({type:"onPutNewMessageToInboxStore",payload:i}))}await Promise.all(c)}(t).catch(e=>async function(t,e){const s=await Ct.data.getApplicationCode(),a=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onPushEventHandler",code:"FATAL-SW-003",error:t,applicationCode:s,workerVersion:a}),t instanceof Error||(t=new Error(t));return C.add({error:`${t}`,stack:t.stack,payload:e.data&&e.data.text()})}(e,t)))}),self.addEventListener("notificationclick",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await It(t),{messageHash:s,metaData:a,url:i,buttonId:r,code:n,inboxId:o}=e;if(n&&xt.push(n),""!==o){const t=new ot(Ct.eventBus,Ct.data,Ct.api),e=await t.getMessage(o);e.status=3,await t.putMessage(e)}t.notification.close();const c={type:"onNotificationClick",payload:e};return i&&t.waitUntil(self.clients.matchAll({type:"window"}).then(t=>async function(t,e){const{hostname:s,pathname:a}=new URL(e,self.location.origin),i=t.find(t=>{const{hostname:e,pathname:i}=new URL(t.url);return e===s&&i===a});return i?(await i.focus(),!1):(await self.clients.openWindow(e).then(t=>{t&&t.focus()}),!0)}(t,i)).then(t=>{t&&Ct.data.setDelayedEvent(c)})),Promise.all([Ct.initApi().then(()=>Ct.api.pushStat(s,!0,a,r)),Ct.data.setLastOpenMessage({url:i,messageHash:s,expiry:Date.now()+864e5}),Dt(c)])}(t).catch(Mt))}),self.addEventListener("notificationclose",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await It(t),{code:s}=e;if(t.notification.close(),!s)return;const a=xt.indexOf(s);if(!(a>=0))return Dt({type:"onNotificationClose",payload:e});xt.splice(a,1)}(t).catch(Rt))}),self.addEventListener("pushsubscriptionchange",async function(t){t.waitUntil(async function(t){let e=t.newSubscription;if(!e&&(e=await self.registration.pushManager.getSubscription(),!e))return;const s=new bt(St,Pt,{});await s.subscribe(e)}(t).catch(Et))}),{}})());
|
|
1
|
+
!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";const t="deviceRegistrationStatus",e="reportedPushPermissionStatus",s="registered",a="unregistered";function i(t,e){if("string"==typeof t)try{return JSON.parse(t)}catch(t){console.log(t)}return void 0===t&&void 0!==e?e:t}function r(){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 n=t=>"function"==typeof t;function o(t){const e=new WeakSet;return async s=>{if(e.has(s))return!1;const a=await function(t,e){let s;const a=new Promise(t=>{s=setTimeout(()=>t(!1),e)}),i=t.then(()=>!0,()=>!0);return Promise.race([i,a]).finally(()=>clearTimeout(s))}(s,t);return a||e.add(s),a}}const c="keyValue",u="messages",h="inboxMessages";function d(t,e){return function(s){s.objectStoreNames.contains(t)||e(s)}}const l=[d(c,function(t){t.createObjectStore(c,{keyPath:"key"})}),d("log",function(t){const e=t.createObjectStore("log",{keyPath:"id",autoIncrement:!0});e.createIndex("environment","environment",{unique:!1}),e.createIndex("date","date",{unique:!1}),e.createIndex("type","type",{unique:!1})}),d(u,function(t){t.createObjectStore(u,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),d(h,function(t){const e="status",s=t.createObjectStore(h,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(e,e,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class g{get all(){return l}}class p{constructor(t,e=new g){this.db=t,this.migrationsBuilder=e}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(t){t.forEach(t=>{t(this.db)})}}function m(t,e){console.info("onversionchange",e),t.close()}let w;function y(){return w||(w=new Promise((t,e)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const a=s.target.result;a.onversionchange=m.bind(null,a,e),t(a)},s.onerror=()=>e(s.error),s.onupgradeneeded=t=>{const s=t.target.result;s.onversionchange=m.bind(null,s,e);new p(s).applyMigrations()}})),w}function b(t){return y().then(e=>new Promise((s,a)=>t(e,s,a)))}class f{_add(t){return b((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 b((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 b((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 v=(P=c,{get:(t,e)=>b((s,a,i)=>{const r=s.transaction(P).objectStore(P).get(t);let n,o=!1,c=!1;const u=()=>{clearTimeout(n),o?a(r.result?.value||e):c?i(r.error):n=setTimeout(u,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,u()}),getAll:()=>b((t,e,s)=>{const a={},i=t.transaction(P).objectStore(P).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)=>b((s,a,i)=>{const r=s.transaction([P],"readwrite").objectStore(P).put({key:t,value:e});let n,o=!1,c=!1;const u=()=>{clearTimeout(n),o?a(t):c?i(r.error):n=setTimeout(u,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,u()})});var P;const S=new class extends f{constructor(){super(...arguments),this.name="log",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)}},C=new class extends f{constructor(){super(...arguments),this.name=u,this.maxItems=25}add(t){return this._add({...t,date:new Date})}},x={error:1,info:2,debug:3};let D=3;const I={setLevel(t){x[t]||(t="error"),D=x[t]},write(t,e,s){return"error"===t?this.error(e):this.info(e),S.add(t,e,s)}};Object.keys(x).forEach(t=>{const e=x[t];I[t]=(...s)=>{e<=D&&(console.groupCollapsed(t),console.info("",...s),console.trace("trace"),console.groupEnd())}});const k="silent",T="fatal",M="error",R="warn",E="info",_="debug",W={[k]:0,[T]:10,[M]:20,[R]:30,[E]:40,[_]:50};function A(t){const{code:e,text:s,type:a}=t,i=function(t){switch(t){case"fatal":case"error":return console.error;case"warn":case"info":case"debug":return console.log}}(a);console.groupCollapsed(a),i(e?`${e}: ${s}`:s),console.groupEnd()}const q=new class{constructor(t){this.relations=W,this.level=t&&void 0!==t.level?t.level:"error",this.applicationType=t&&void 0!==t.applicationType?t.applicationType:"sdk",this.subscribers=t&&void 0!==t.subscribers?t.subscribers:[]}updateLogLevel(t){this.level=t}updateApplicationType(t){this.applicationType=t}updateApplicationCode(t){this.applicationCode=t}updateDomain(t){this.domain=t}updateDeviceInfo(t){this.deviceInfo=t}subscribe(t,e){this.subscribers.push({handler:e,level:t})}async log(t){const e=[],{options:s,...a}=t;let i=a;if(s){const{handler:t,...e}=s;i={...a,...e}}const r=this.getMessage(i);this.subscribers.forEach(s=>{s.level===t.type&&this.relations[s.level]<=this.relations[this.level]&&e.push(s.handler.call(null,r))}),s&&s.handler&&"silent"!==this.level&&s.handler.call(null,r),await Promise.all(e)}async debug(t,e){return this.log({type:"debug",text:t,options:e})}async info(t,e){return this.log({type:"info",text:t,options:e})}async warn(t,e,s){return this.log({type:"warn",text:t,code:e,options:s})}async error(t,e,s){return this.log({type:"error",text:t,code:e,options:s})}async fatal(t,e,s){return this.log({type:"fatal",text:t,code:e,options:s})}async errorAndThrow(t,e,s){return this.logAndThrow({type:"error",text:t,code:e,options:s})}async errorAndReject(t,e,s,a){return this.logAndReject(t,{type:"error",text:e,code:s,options:a})}async fatalAndThrow(t,e,s){return this.logAndThrow({type:"fatal",text:t,code:e,options:s})}async fatalAndReject(t,e,s,a){return this.logAndReject(t,{type:"fatal",text:e,code:s,options:a})}async logAndThrow(t){await this.log(t);const e=new Error(t.text);throw t.code&&(e.code=t.code),e}async logAndReject(t,e){await this.log(e);const s=new Error(e.text);e.code&&(s.code=e.code),t(s)}getMessage(t){return{applicationCode:this.applicationCode,domain:this.domain,applicationType:this.applicationType,deviceInfo:this.deviceInfo,...t}}}({level:"error",subscribers:[{level:"fatal",handler:A},{level:"error",handler:A}]});async function N(t){const e=L(t);return q.fatal(e.text,e.code,e.options)}function L(t){const{message:e,code:s,error:a,...i}=t,r=function(t){let e=new Error("unknown error");"string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t||(e.message=t.toString());t instanceof Error&&(e=t);return e}(a);return{text:e,code:s,options:{...i,errorText:r.message,errorStack:r.stack}}}class U{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()}}const O=["classic","captioned","banner","carousel"];function F(t){return(Array.isArray(t)?t:[]).filter(t=>!!t&&!!t.imageUrl).slice(0,5)}const j=/^#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;const V=/^(?:javascript|vbscript|data|blob|file):/i,B=/^[a-z][a-z\d+\-.]*:/i;function $(t){return t.split("").filter(t=>t.charCodeAt(0)>32&&127!==t.charCodeAt(0)).join("")}function H(t){const e=$(t);return B.test(e)&&!V.test(e)}const K=/^intent:/i;const z=["id","title","text_color","bg_color"];function J(t){return"string"==typeof t?t:""}function G(t){return!!t&&"object"==typeof t&&!Array.isArray(t)}function Y(t){const e=J(t);return e&&H(e)&&!function(t){return K.test($(t))}(e)?e:""}function Q(t,e){return e?"":(s=t,("string"==typeof s&&j.test(s)?s:void 0)||"").toUpperCase();var s}function X(t){return Object.keys(t).filter(t=>-1===z.indexOf(t)).reduce((e,s)=>(e[s]=t[s],e),{})}const Z=/^[0-2]$/;function tt(t){return G(t)&&"string"==typeof t.title&&""!==t.title.trim()}function et(t){return(Array.isArray(t.buttons)?t.buttons:[]).filter(tt).slice(0,3).map((t,e)=>{const s="string"==typeof t.id&&Z.test(t.id);return function(t,e,s){const a=Y(t.url),i={id:e,title:J(t.title),textColor:Q(t.text_color,s),bgColor:Q(t.bg_color,s),action:"custom",url:a,copyText:J(t.copy_text),data:G(t.data)?t.data:{}};if(s){const e="dismiss"===t.action||"markRead"===t.action||"markread"===t.action;a&&!e?i.action="open":i.data=X(t)}else"open"===t.action||"copy"===t.action||"custom"===t.action?i.action=t.action:i.data=X(t);return i}(t,s?t.id:String(e),!s)})}function st(t,e){return e||t.image||""}function at(t){const e=["displayType","carousel","buttons","image"];return Object.keys(t).filter(t=>-1===e.indexOf(t)).reduce((e,s)=>(e[s]=t[s],e),{})}class it{constructor(t,e,s,a={},i=()=>Promise.resolve(void 0),r=new U){this.data=t,this.api=e,this.inboxModel=s,this.moduleRegistry=a,this.loadWebPopups=i,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(t){try{return JSON.parse(t)||{}}catch(e){return I.write("error",`Pushwoosh: cannot parse inbox action_params: ${t}`,e),{}}}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=this.parseActionParams(e),u=function(t){const e=t?.u;if(!e)return{};if("string"==typeof e)try{return JSON.parse(e)||{}}catch{return{}}return"object"==typeof e?e:{}}(c),h=function(t){return(Array.isArray(t.carousel)?t.carousel:[]).filter(t=>!!t&&!!t.image).slice(0,5).map(t=>({imageUrl:t.image,caption:t.title||"",link:t.url&&H(t.url)?t.url:""}))}(u),d=function(t,e,s){return t?.b||s||e.image||""}(c,u,s),l=function(t){const e=!!t.title,s=!!t.body,a=function(t){return t.bannerUrl||t.iconUrl||""}(t);let i=t.layoutType;switch(O.includes(i)||(i=t.bannerUrl&&!e?"banner":t.bannerUrl&&e&&s?"captioned":"classic"),i){case"banner":return a?"banner":"classic";case"captioned":return a&&e&&s?"captioned":"classic";case"carousel":return e&&s&&F(t.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:a,body:n,iconUrl:st(u,s),bannerUrl:c.b,layoutType:u.displayType,carousel:h}),g=st(u,s)||await this.data.getDefaultNotificationImage(),p=a||await this.data.getDefaultNotificationTitle();return this.dateModule.date=new Date(1e3*parseInt(i)),{title:p,imageUrl:g,iconUrl:g,heroUrl:d,layout:l,carousel:h,customData:at(u),webPopupCode:c.wp||"",buttons:et(u),code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(t,c),link:c?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const 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=this.parseActionParams(e.action_params),a=this.messageTypeFactory(e.action_type,s),i=2===a||3===a;var r;!await this.showWebPopup(s.wp)&&i&&null!=s.l&&((r=s.l)&&!V.test($(r)))&&(document.location.href=s.l),e.status=3,await this.inboxModel.putMessage(e),await this.api.inboxStatus(e.order,e.status)}async reportButtonClick(t,e){const s=await this.inboxModel.getMessage(t),a=3!==s.status;a&&await this.sendStatus(s.order,3),await this.sendStatus(s.order,6,e),a&&(s.status=3,await this.inboxModel.putMessage(s))}sendStatus(t,e,s){return new Promise(a=>{this.api.inboxStatus(t,e,s,{keepalive:!0,onSent:a}).catch(s=>I.write("error",`Pushwoosh: inbox status ${e} for "${t}" failed`,s)).finally(a)})}async showWebPopup(t){if(!t)return!1;try{const e=this.moduleRegistry.webPopups??await this.loadWebPopups();return e?await e.show(t):(I.write("error",`Pushwoosh: inbox message opens web popup "${t}", but the web popups widget could not be loaded`),!1)}catch(e){return I.write("error",`Pushwoosh: failed to open web popup "${t}" from inbox`,e),!1}}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.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class rt{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 nt{getDB(){return y()}async put(t,e,s){const a=await this.getDB();return new rt(a,t).put(e,s)}async delete(t,e){const s=await this.getDB();return new rt(s,t).delete(e)}async get(t,e,s){const a=await this.getDB();return new rt(a,t).get(e,s)}async getAll(t){const e=await this.getDB(),s=new rt(e,t);return await s.getAll()||[]}async count(t,e){const s=await this.getDB();return new rt(s,t).count(e)}async countByIndex(t,e,s){const a=await this.getDB(),i=new rt(a,t);return i.index=e,i.countByIndex(s)}}class ot{constructor(t,e,s,a=new nt,i=new U){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 it(this.data,this.api,this)})}}const ct={"&":"&","<":"<",">":">",""":'"',"'":"'"},ut=/&(?:amp|lt|gt|quot|#39);/g,ht=RegExp(ut.source);const dt=t=>`params.${t}`;class lt{constructor(t=v){this.store=t}async clearAll(){const t=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const e of t)await this.store.set(dt(e),void 0)}async setApplicationCode(t){await this.store.set(dt("applicationCode"),t)}async getApplicationCode(){return this.store.get(dt("applicationCode"))}async setApiToken(t){return await this.store.set(dt("apiToken"),t)}async getApiToken(){return this.store.get(dt("apiToken"))}async setHwid(t){await this.store.set(dt("hwid"),t)}async getHwid(){return this.store.get(dt("hwid"))}async setDeviceType(t){await this.store.set(dt("deviceType"),t)}async getDeviceType(){return this.store.get(dt("deviceType"))}async setFormFactor(t){await this.store.set(dt("formFactor"),t)}async getFormFactor(){return this.store.get(dt("formFactor"))}async setDeviceModel(t){await this.store.set(dt("deviceModel"),t)}async getDeviceModel(){return this.store.get(dt("deviceModel"))}async setLanguage(t){await this.store.set(dt("language"),t)}async getLanguage(){return this.store.get(dt("language"),"en")}async setStatusLanguageWasChanged(t){await this.store.set(dt("languageWasChanged"),t)}async getStatusLanguageWasChanged(){return this.store.get(dt("languageWasChanged"),!1)}async setApiEntrypoint(t){await this.store.set(dt("apiEntrypoint"),t)}async getApiEntrypoint(){return this.store.get(dt("apiEntrypoint"),"https://api.pushwoosh.com/json/1.3/")}async setTokens(t){await this.store.set(dt("tokens"),t)}getTokens(){return this.store.get(dt("tokens"))}async setApplicationServerKey(t){await this.store.set(dt("applicationServerKey"),t)}async getApplicationServerKey(){return this.store.get(dt("applicationServerKey"))}async setIsVapidChanged(t){await this.store.set(dt("isVapidChanged"),t)}async getIsVapidChanged(){return this.store.get(dt("isVapidChanged"),!1)}async setWebVapidConfigured(t){await this.store.set(dt("webVapidConfigured"),t)}async getWebVapidConfigured(){return this.store.get(dt("webVapidConfigured"),!1)}async setWebSitePushId(t){await this.store.set(dt("webSitePushId"),t)}async getWebSitePushId(){return this.store.get(dt("webSitePushId"))}async setDefaultNotificationImage(t){await this.store.set(dt("defaultNotificationImage"),t)}async getDefaultNotificationImage(){return this.store.get(dt("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(t){await this.store.set(dt("defaultNotificationTitle"),t)}async getDefaultNotificationTitle(){return this.store.get(dt("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(t){await this.store.set(dt("userId"),t?`${t}`:void 0)}async getUserId(){return this.store.get(dt("userId"))}async getFeatureFlags(){return this.store.get(dt("featureFlags"))}async setFeatureFlags(t){await this.store.set(dt("featureFlags"),t)}async getFeatureFlagImpressions(){return this.store.get(dt("featureFlagImpressions"),{})}async setFeatureFlagImpressions(t){await this.store.set(dt("featureFlagImpressions"),t)}async setStatusUserIdWasChanged(t){await this.store.set(dt("userIdWasChanged"),t)}async getStatusUserIdWasChanged(){return this.store.get(dt("userIdWasChanged"),!1)}async setEmail(t){await this.store.set(dt("email"),t?`${t}`:void 0)}async getEmail(){return this.store.get(dt("email"))}async setStatusEmailWasChanged(t){await this.store.set(dt("emailWasChanged"),t)}async getStatusEmailWasChanged(){return this.store.get(dt("emailWasChanged"),!1)}async setSmsNumber(t){await this.store.set(dt("smsNumber"),t?`${t}`:void 0)}async getSmsNumber(){return this.store.get(dt("smsNumber"))}async setStatusSmsNumberWasChanged(t){await this.store.set(dt("smsNumberWasChanged"),t)}async getStatusSmsNumberWasChanged(){return this.store.get(dt("smsNumberWasChanged"),!1)}async setWhatsAppNumber(t){await this.store.set(dt("whatsAppNumber"),t?`${t}`:void 0)}async getWhatsAppNumber(){return this.store.get(dt("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(t){await this.store.set(dt("whatsAppNumberWasChanged"),t)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(dt("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(t){await this.store.set(dt("isLastPermissionStatus"),t)}async getLastPermissionStatus(){return this.store.get(dt("isLastPermissionStatus"))}async setStatusManualUnsubscribed(t){await this.store.set(dt("isManualUnsubscribed"),t)}getStatusManualUnsubscribed(){return this.store.get(dt("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(t){await this.store.set(dt("isCommunicationDisabled"),t)}getStatusCommunicationDisabled(){return this.store.get(dt("isCommunicationDisabled"),!1)}async setCommunicationEnabled(t){await this.store.set(dt("communicationEnabled"),t)}getCommunicationEnabled(){return this.store.get(dt("communicationEnabled"))}async setStatusDropAllData(t){await this.store.set(dt("isDropAllData"),t)}getStatusDropAllData(){return this.store.get(dt("isDropAllData"),!1)}async setSdkVersion(t){await this.store.set(dt("sdkVersion"),t)}async getSdkVersion(){return this.store.get(dt("sdkVersion"))}async setServiceWorkerVersion(t){await this.store.set(dt("serviceWorkerVersion"),t)}getServiceWorkerVersion(){return this.store.get(dt("serviceWorkerVersion"))}async setServiceWorkerUrl(t){t&&await this.store.set(dt("serviceWorkerUrl"),t)}async getServiceWorkerUrl(){return this.store.get(dt("serviceWorkerUrl"),"/pushwoosh-service-worker.js")}async setServiceWorkerScope(t){t&&await this.store.set(dt("serviceWorkerScope"),t)}async getServiceWorkerScope(){return this.store.get(dt("serviceWorkerScope"))}async setLastOpenMessage(t){await this.store.set(dt("lastOpenMessage"),t)}getLastOpenMessage(){return this.store.get(dt("lastOpenMessage"))}async setLastOpenApplicationTime(t){await this.store.set(dt("lastOpenApplicationTime"),t)}async getLastOpenApplicationTime(){return this.store.get(dt("lastOpenApplicationTime"))}async setFeatures(t){await this.store.set(dt("features"),t)}async getFeatures(){return this.store.get(dt("features"))}async setInitParams(t){await this.store.set(dt("init"),t)}async getInitParams(){return this.store.get(dt("init"))}async setInboxLastRequestCode(t){await this.store.set(dt("inbox.lastRequestCode"),t)}async getInboxLastRequestCode(){return this.store.get(dt("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(t){await this.store.set(dt("inbox.lastRequestTime"),t)}async getInboxLastRequestTime(){return this.store.get(dt("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(t){await this.store.set(dt("inbox.newMessagesCount"),t)}async getInboxNewMessagesCount(){return this.store.get(dt("inbox.newMessagesCount"),0)}async setDelayedEvent(t){await this.store.set(dt("delayedEvent"),t)}getDelayedEvent(){return this.store.get(dt("delayedEvent"))}async setPromptDisplayCount(t){await this.store.set(dt("promptDisplayCount"),t)}async getPromptDisplayCount(){return this.store.get(dt("promptDisplayCount"),0)}async setPromptLastSeenTime(t){await this.store.set(dt("promptLastSeenTime"),t)}async getPromptLastSeenTime(){return this.store.get(dt("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(t){await this.store.set(dt("subscriptionWidgetHistory"),t)}async getSubscriptionWidgetHistory(){return this.store.get(dt("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(t){await this.store.set(dt("logLevel"),t)}async getLogLevel(){return this.store.get(dt("logLevel"),"error")}async getShownWebPopups(){return this.store.get(dt("shownWebPopups"),[])}async addShownWebPopup(t){const e=await this.getShownWebPopups();e.includes(t)||(e.push(t),await this.store.set(dt("shownWebPopups"),e))}async setIsRecurringVisitor(t){await this.store.set(dt("isRecurringVisitor"),t)}async getIsRecurringVisitor(){return this.store.get(dt("isRecurringVisitor"),!1)}}class gt{constructor(t,e=new lt,s=new U){if("data"in t){const e=t;this.payload=e.data}else this.payload=t;this.data=e,this.code=`notificationCode-${Date.now()}-${Math.random().toString(16).slice(2,10)}`,this.dateModule=s}async getIcon(){return this.payload.i||await this.data.getDefaultNotificationImage()}async getTitle(){return this.payload.header||await this.data.getDefaultNotificationTitle()}get silent(){return Boolean(this.payload.silent)}get body(){return this.payload.body}get messageHash(){return this.payload.p||""}get metaData(){return this.payload.md?i(this.payload.md):{}}get image(){return this.payload.image||""}get buttons(){return this.payload.buttons?i(this.payload.buttons):[]}get customData(){return this.payload.u?i(this.payload.u):{}}get campaignCode(){return this.payload.pwcid||""}get link(){return this.payload.l?(t=this.payload.l)&&ht.test(t)?t.replace(ut,t=>ct[t]):t:"/";var t}get inboxId(){return this.payload.pw_inbox||""}get inboxParams(){return this.payload.inbox_params?i(this.payload.inbox_params):{}}get inboxRemovalTime(){return this.inboxParams&&this.inboxParams.rt?this.inboxParams.rt:(this.dateModule.date=new Date,this.dateModule.addDays(1),this.dateModule.getUtcTimestamp().toString())}async getInboxImage(){return this.inboxParams&&this.inboxParams.image?this.inboxParams.image:""}get rootParams(){const{body:t,p:e,header:s,i:a,u:i,l:r,pwcid:n,image:o,buttons:c,pw_inbox:u,inbox_params:h,...d}=this.payload;return d}async getNotificationOptionsPayload(){const t=await this.getTitle(),e=await this.getIcon();return{...this.rootParams,body:this.body,title:t,icon:e,image:this.image,buttons:this.buttons,customData:this.customData,metaData:this.metaData,campaignCode:this.campaignCode,openUrl:this.link,messageHash:this.messageHash}}async getShowNotificationOptions(){const t=await this.getIcon(),e=this.buttons.map((t,e)=>(t.action=t.id||`action-${e}`,t));return{renotify:!0,...this.rootParams,body:this.body,icon:t,tag:JSON.stringify({url:this.link,messageHash:this.messageHash,customData:this.customData,metaData:this.metaData}),data:{code:this.code,buttons:e,image:this.image,campaignCode:this.campaignCode,inboxId:this.inboxId},silent:this.silent,actions:e,image:this.image,buttons:e}}async getInboxMessage(){this.dateModule.date=new Date;const t=this.dateModule.getTimestamp().toString();return{title:this.payload.header||"",image:await this.getInboxImage(),status:1,order:this.dateModule.getInboxFakeOrder(),inbox_id:this.inboxId,send_date:t,rt:this.inboxRemovalTime,text:this.body,action_type:1,action_params:JSON.stringify({l:this.link})}}}function pt(){const{pathname:t}=window.location;try{return decodeURIComponent(t)}catch{return t}}class mt extends Error{constructor(t,e){super(t),this.name="ApiRequestError",this.statusCode=e}}class wt{constructor(t=new lt,e=I){this.data=t,this.logger=e}checkDevice(t){return this.createRequest("checkDevice",t)}getConfig(t){return this.createRequest("getConfig",t)}getPopupForms(t){return this.createRequest("getPopupForms",t)}getPopupFormContent(t){return this.createRequest("getPopupFormContent",t)}recordPopupFormEvent(t){return this.createRequest("recordPopupFormEvent",t)}submitPopupForm(t){return this.createRequest("submitPopupForm",t)}getWebPlacements(t){return this.createRequest("getWebPlacements",t)}trackWebPlacement(t){return this.createRequest("trackWebPlacement",t)}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,e){return this.createRequest("postEvent",t,e)}getInboxMessages(t){return this.createRequest("getInboxMessages",t)}inboxStatus(t,e){return this.createRequest("inboxStatus",t,e)}multiRegisterDevice(t){return this.createRequest("multiRegisterDevice",t)}sdkUsage(t,e){return this.createRequest("sdkUsage",t,e)}async createRequest(t,e,s={}){const a=await this.data.getApiEntrypoint(),i=await this.data.getApiToken(),r=a+t,n=i?{headers:{Authorization:`Token ${i}`,"Content-Type":"text/plain;charset=UTF-8",Origin:globalThis.location.origin},credentials:"include"}:{},o=fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:e}),...n,keepalive:s.keepalive});s.onSent?.();const c=await o,u=await this.checkResponse(c);return u.base_url&&await this.data.setApiEntrypoint(u.base_url),await this.logger.write("apirequest",`${t} call with arguments: ${JSON.stringify(e)} to Pushwoosh has been successful. Result: ${JSON.stringify(u.response)}`),u.response}async checkResponse(t){if(200!==t.status){let e,s=`status: ${t.status}. statusText: ${t.statusText}.`;try{const a=await t.json();a&&"number"==typeof a.status_code&&(e=a.status_code),a&&a.status_message&&(s+=` status_code: ${a.status_code}. status_message: ${a.status_message}.`)}catch(t){}throw new mt(s,e)}const e=await t.json();if(200!==e.status_code)throw new mt(`Error code: ${e.status_code}. Error text: ${e.status_message}`,"number"==typeof e.status_code?e.status_code:void 0);return e}}function yt(t){try{return t?Intl.getCanonicalLocales(t)[0]??"":""}catch{return""}}class bt{constructor(t,e,s){this.api=t,this.data=e,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return"granted"===this.getPermission()}checkIsPermissionDefault(){return"default"===this.getPermission()}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 I.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&&(await this.data.setLastPermissionStatus(e),void 0!==t))return!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=${r()}`),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 ft{constructor(t,e,s){this._canceled=!1,this.showNotificationOptions=t,this.body=e,this.title=s}async show(){if(this._canceled)return;const t=this.showNotificationOptions;t.silent||await self.registration.showNotification(this.title,t)}cancel(){this._canceled=!0}}const vt=new class{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||r(),a=this.handlers[t];return a?(a.forEach(t=>{n(t)&&setTimeout(()=>{t({...e,eventId:s})},0)}),s):s},this.handlers={}}},Pt=new lt,St=new class{constructor(t,e=new lt,s=new wt,a=()=>!1,i=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=o(1e4),this.eventBus=t,this.data=e,this.apiClient=s,this.getIsCommunicationDisabled=a,this.getInitUserId=i,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(t=>{throw this.checkDevicePromise=null,t})),this.checkDevicePromise}async requestCheckDevice(){const t=await this.getRequestParams();return await this.apiClient.checkDevice(t)}async checkDeviceSubscribeForPushNotifications(e=!0){let i=localStorage.getItem(t);if(null===i||!e){const{exist:e,push_token_exist:r}=await this.checkDevice();localStorage.setItem(t,e&&r?s:a),i=localStorage.getItem(t)}return i===s}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(t=>{throw this.ensureDeviceRegisteredPromise=null,t})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:t}=await this.checkDevice();if(t)return!1;const e=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:e,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(e),!0}async reportPushPermissionStatus(t=!1){const s=this.getPushPermissionStatus();if(s&&s!==this.reportingPushPermissionStatus&&s!==localStorage.getItem(e)){this.reportingPushPermissionStatus=s;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!t&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:s,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(s)}finally{this.reportingPushPermissionStatus===s&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(e)}rememberReportedPushPermissionStatus(t){t&&localStorage.setItem(e,t)}async getConfig(t){const e=await this.getRequestParams();return this.apiClient.getConfig({...e,features:t})}async applicationOpen(){const t=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const e=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...t,push_permission_status:e,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(e),s}async registerDevice(){const t=this.requestRegisterDevice();this.registerDevicePromise=t;try{return await t}finally{this.registerDevicePromise===t&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),a=await this.data.getTokens();if(!a.pushToken)throw new Error("Can't register device: pushToken is not exist!");const i=this.getPushPermissionStatus(),r=await this.apiClient.registerDevice({...e,push_permission_status:i,locale:await this.getLocale(),page:pt(),push_token:a.pushToken,auth_token:a.authToken,public_key:a.publicKey});return this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(i),await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(t,s),this.eventBus.dispatchEvent("register",{}),r}async unregisterDevice(){const e=await this.getRequestParams(),s=await this.apiClient.unregisterDevice(e);return this.checkDevicePromise=null,localStorage.setItem(t,a),this.eventBus.dispatchEvent("unsubscribe",{}),s}async deleteDevice(){const e=await this.getRequestParams(),s=await this.apiClient.deleteDevice(e);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(t,a),this.eventBus.dispatchEvent("unsubscribe",{}),s}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={},a){const i=await this.getRequestParams();return await this.apiClient.pushStat({...i,hash:t,metaData:s,...a?{button_id:a}:{}})}async setTags(t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));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 setLanguage(t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:t}))}async setLocale(t){if(!t)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const e=yt(t.trim().replace(/_/g,"-"));e&&(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return yt(await this.data.getLanguage())||void 0}async registerUser(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${t}`,o=await this.data.getUserId(),c=await this.apiClient.registerUser({...i,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),n&&n!==o&&this.eventBus.dispatchEvent("change-user-id",{userId:n}),e&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(t))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),a=await this.apiClient.registerEmail({...s,email:t,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(t),e&&await this.data.setStatusEmailWasChanged(!0),a}async registerSmsNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:a}=await this.getIdentityRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:t,device_type:18});return await this.data.setSmsNumber(t),e&&await this.data.setStatusSmsNumberWasChanged(!0),i}async registerWhatsappNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:a}=await this.getIdentityRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:t,device_type:21});return await this.data.setWhatsAppNumber(t),e&&await this.data.setStatusWhatsAppNumberWasChanged(!0),i}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:t})}async recordPopupFormEvent(t,e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:t,event:e};return this.apiClient.recordPopupFormEvent(3===e?{...s,clickId:r()}:s)}async getWebPlacements(){if(this.getIsCommunicationDisabled())return[];const t=await this.apiClient.getWebPlacements(await this.getRequestParams());return t?.web_placements??[]}async trackWebPlacement(t,e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.trackWebPlacement({...await this.getRequestParams(),hash:t,action:e})}async submitPopupForm(t,e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:t,email:e.email,tags:e.tags,policy_accepted:e.policyAccepted})}async sdkUsage(t,e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams();return this.apiClient.sdkUsage({...s,...t},e)}async postEvent(t,e,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const a=await this.getRequestParams(),i=new Date,r=i.getTime(),n=Math.floor(r/1e3),o=n-i.getTimezoneOffset()/60*3600,c=await this.data.getLastOpenMessage();if(c&&c.expiry>Date.now()){if(e.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));e={...e,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const u=await this.apiClient.postEvent({...a,event:t,timestampUTC:n,timestampCurrent:o,attributes:e},s);return u&&u.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:u.code}),u?.web_placements?.length&&this.eventBus.dispatchEvent("receive-web-placements",{placements:u.web_placements}),u}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,s,a){const i=await this.getRequestParams();return this.apiClient.inboxStatus({...i,inbox_code:t,status:e,time:(new Date).getTime(),...void 0===s?{}:{button_id:s}},a)}async multiRegisterDevice(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const a=await this.data.getApplicationCode(),i=await this.data.getDeviceModel(),r=await this.data.getDeviceType(),n=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),u=await this.data.getHwid();!e.push_devices&&c.pushToken&&await this.requireHwid();const h={application:a,...e};if(e.user_id){h.user_id=String(e.user_id);await this.data.getUserId()!==h.user_id&&(await this.data.setUserId(h.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(e.email){if(!/^\S+@\S+\.\S+$/.test(e.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==e.email&&(await this.data.setEmail(e.email),await this.data.setStatusEmailWasChanged(!0))}if(e.sms_phone_number){if(!/^\+?[0-9]+$/.test(e.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==e.sms_phone_number&&(await this.data.setSmsNumber(e.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(e.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(e.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==e.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(e.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(h.language?(await this.data.setLanguage(h.language),await this.data.setStatusLanguageWasChanged(!0)):h.language=n,!h.timezone){const t=60*-(new Date).getTimezoneOffset();h.timezone=String(t)}if(!h.push_devices&&c.pushToken){const t={hwid:u,platform:r,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||i){const e={};c.publicKey&&(e.public_key=c.publicKey),c.authToken&&(e.auth_token=c.authToken),i&&(e.browser=i),t.platformData=e}h.push_devices=[t]}const d=await this.apiClient.multiRegisterDevice(h);return h.push_devices?.length&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(t,s),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const t=await this.requireHwid(),e=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:t,device_type:e}}async getIdentityRequestParams(){const t=await this.data.getApplicationCode(),e=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),a=await this.data.getDeviceModel(),i=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!e)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:t,userId:s||e,device_model:a,timezone:n,language:i,v:r}}async requireHwid(){const t=await this.data.getHwid();if(!t)throw new Error("Pushwoosh: the SDK storage does not keep the hwid in this browser (in-app webview, private window or insecure context), so this device cannot be identified. Requests that need an hwid are not sent.");return t}}(vt,Pt);Pt.getLogLevel().then(t=>{t&&I.setLevel(t)});const Ct=self.Pushwoosh=new class{constructor(t,e,s){this._listeners={},this.eventBus=t,this.data=e,this.api=s}push(t){Array.isArray(t)&&"onPush"===t[0]&&n(t[1])&&(this._listeners[t[0]]||(this._listeners[t[0]]=[]),this._listeners[t[0]].push(t[1]))}getListeners(t){return this._listeners[t]||[]}async initApi(){return Promise.resolve()}}(vt,Pt,St),xt=[];async function Dt(t){(await self.clients.matchAll()).forEach(e=>e.postMessage(t))}async function It(t){const{notification:e={}}=t,{data:s}=e,a=i(e.tag,{});let r,n="";if(t.action&&Array.isArray(s.buttons)){const e=s.buttons.find(e=>e.action===t.action)||{};n=e.url,r=e.id}else n=a.url;return{title:e.title,body:e.body,icon:e.icon,buttons:s.buttons,image:s.image,code:s.code,campaignCode:s.campaignCode,inboxId:s.inboxId,messageHash:a.messageHash,customData:a.customData,metaData:a.metaData,openUrl:a.url,tag:e.tag,url:n,buttonId:r}}async function kt(t){const e=await Ct.data.getApplicationCode(),s=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onInstallEventHandler",code:"FATAL-SW-001",error:t,applicationCode:e,workerVersion:s})}async function Tt(t){const e=await Ct.data.getApplicationCode(),s=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onActivateEventHandler",code:"FATAL-SW-002",error:t,applicationCode:e,workerVersion:s})}async function Mt(t){const e=await Ct.data.getApplicationCode(),s=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onNotificationClickEventHandler",code:"FATAL-SW-004",error:t,applicationCode:e,workerVersion:s})}async function Rt(t){const e=await Ct.data.getApplicationCode(),s=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onNotificationCloseEventHandler",code:"FATAL-SW-005",error:t,applicationCode:e,workerVersion:s})}async function Et(t){const e=await Ct.data.getApplicationCode(),s=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onPushSubscriptionChange",code:"FATAL-SW-006",error:t,applicationCode:e,workerVersion:s})}return self.addEventListener("install",function(t){return t.waitUntil(async function(){await Promise.all([Ct.data.setServiceWorkerVersion("3.123.0"),I.write("info","install")]),await self.skipWaiting()}().catch(kt))}),self.addEventListener("activate",function(t){t.waitUntil(async function(){await Promise.all([I.write("info","activate")]),await self.clients.claim()}().catch(Tt))}),self.addEventListener("push",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await t.data.json(),s=new gt(e),a=await s.getNotificationOptionsPayload(),i=await s.getShowNotificationOptions(),r=s.messageHash;await I.write("info",JSON.stringify(a),"onPush");const n=new ft(i,s.body,await s.getTitle()),o=Ct.getListeners("onPush");await o.reduce((t,e)=>t.then(()=>e(n)),Promise.resolve());const c=[n.show(),C.add({payload:e,parsedPayload:a,showOptions:i}),Dt({type:"onPushDelivery",payload:a})];if(r&&c.push(Ct.initApi().then(()=>Ct.api.messageDeliveryEvent(r,!0,a.metaData))),""!==s.inboxId){const t=new ot(Ct.eventBus,Ct.data,Ct.api),e=new it(Ct.data,Ct.api,t),a=await s.getInboxMessage(),i=await e.publicMessageBuilder(a);c.push(t.putMessage(a),Dt({type:"onPutNewMessageToInboxStore",payload:i}))}await Promise.all(c)}(t).catch(e=>async function(t,e){const s=await Ct.data.getApplicationCode(),a=await Ct.data.getServiceWorkerVersion();await N({message:"Error in onPushEventHandler",code:"FATAL-SW-003",error:t,applicationCode:s,workerVersion:a}),t instanceof Error||(t=new Error(t));return C.add({error:`${t}`,stack:t.stack,payload:e.data&&e.data.text()})}(e,t)))}),self.addEventListener("notificationclick",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await It(t),{messageHash:s,metaData:a,url:i,buttonId:r,code:n,inboxId:o}=e;if(n&&xt.push(n),""!==o){const t=new ot(Ct.eventBus,Ct.data,Ct.api),e=await t.getMessage(o);e.status=3,await t.putMessage(e)}t.notification.close();const c={type:"onNotificationClick",payload:e};return i&&t.waitUntil(self.clients.matchAll({type:"window"}).then(t=>async function(t,e){const{hostname:s,pathname:a}=new URL(e,self.location.origin),i=t.find(t=>{const{hostname:e,pathname:i}=new URL(t.url);return e===s&&i===a});return i?(await i.focus(),!1):(await self.clients.openWindow(e).then(t=>{t&&t.focus()}),!0)}(t,i)).then(t=>{t&&Ct.data.setDelayedEvent(c)})),Promise.all([Ct.initApi().then(()=>Ct.api.pushStat(s,!0,a,r)),Ct.data.setLastOpenMessage({url:i,messageHash:s,expiry:Date.now()+864e5}),Dt(c)])}(t).catch(Mt))}),self.addEventListener("notificationclose",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await It(t),{code:s}=e;if(t.notification.close(),!s)return;const a=xt.indexOf(s);if(!(a>=0))return Dt({type:"onNotificationClose",payload:e});xt.splice(a,1)}(t).catch(Rt))}),self.addEventListener("pushsubscriptionchange",async function(t){t.waitUntil(async function(t){let e=t.newSubscription;if(!e&&(e=await self.registration.pushManager.getSubscription(),!e))return;const s=new bt(St,Pt,{});await s.subscribe(e)}(t).catch(Et))}),{}})());
|
|
2
2
|
//# sourceMappingURL=service-worker.js.map
|