web-push-notifications 3.117.0 → 3.118.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "web-push-notifications",
3
- "version": "3.117.0",
3
+ "version": "3.118.0",
4
4
  "description": "Pushwoosh web push notifications",
5
5
  "main": "npm.js",
6
6
  "types": "npm.d.ts",
package/service-worker.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var a in s)("object"==typeof exports?exports:e)[a]=s[a]}}(this,()=>(()=>{"use strict";const e="deviceRegistrationStatus",t="reportedPushPermissionStatus",s="registered",a="unregistered";function i(e,t){if("string"==typeof e)try{return JSON.parse(e)}catch(e){console.log(e)}return void 0===e&&void 0!==t?t:e}function r(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const n=e=>"function"==typeof e;function o(e){const t=new WeakSet;return async s=>{if(t.has(s))return!1;const a=await function(e,t){let s;const a=new Promise(e=>{s=setTimeout(()=>e(!1),t)}),i=e.then(()=>!0,()=>!0);return Promise.race([i,a]).finally(()=>clearTimeout(s))}(s,e);return a||t.add(s),a}}const c="keyValue",u="messages",h="inboxMessages";function d(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const l=[d(c,function(e){e.createObjectStore(c,{keyPath:"key"})}),d("log",function(e){const t=e.createObjectStore("log",{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),d(u,function(e){e.createObjectStore(u,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),d(h,function(e){const t="status",s=e.createObjectStore(h,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class g{get all(){return l}}class p{constructor(e,t=new g){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function m(e,t){console.info("onversionchange",t),e.close()}let w;function y(){return w||(w=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const a=s.target.result;a.onversionchange=m.bind(null,a,t),e(a)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=m.bind(null,s,t);new p(s).applyMigrations()}})),w}function b(e){return y().then(t=>new Promise((s,a)=>e(t,s,a)))}class f{_add(e){return b((t,s,a)=>{const i=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);i.onsuccess=()=>{s(e)},i.onerror=()=>{a(i.error)}}).then(e=>this.getAll().then(t=>{if(Array.isArray(t)){const s=t.map(e=>e.id).sort((e,t)=>e==t?0:e<t?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(e=>this.delete(e))).then(()=>e)}return e}))}delete(e){return b((t,s,a)=>{const i=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);i.onsuccess=()=>{s(i.result)},i.onerror=()=>{a(i.error)}})}getAll(){return b((e,t,s)=>{const a=[],i=e.transaction(this.name).objectStore(this.name).openCursor();i.onsuccess=e=>{const s=e.target.result;s?(s.value&&a.push(s.value),s.continue()):t(a)},i.onerror=()=>{s(i.error)}})}}const v=(P=c,{get:(e,t)=>b((s,a,i)=>{const r=s.transaction(P).objectStore(P).get(e);let n,o=!1,c=!1;const u=()=>{clearTimeout(n),o?a(r.result?.value||t):c?i(r.error):n=setTimeout(u,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,u()}),getAll:()=>b((e,t,s)=>{const a={},i=e.transaction(P).objectStore(P).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(a):o?s(i.error):r=setTimeout(c,0)};i.onsuccess=e=>{const t=e.target.result;t?(a[t.key]=t.value.value,t.continue()):n=!0},i.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...a}=t;await this.set(e,{...s,...a})},set:(e,t)=>b((s,a,i)=>{const r=s.transaction([P],"readwrite").objectStore(P).put({key:e,value:t});let n,o=!1,c=!1;const u=()=>{clearTimeout(n),o?a(e):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(e,t,s){const a={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(a.stack=t.stack),s&&(a.additional=s),this._add(a)}},C=new class extends f{constructor(){super(...arguments),this.name=u,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},x={error:1,info:2,debug:3};let D=3;const I={setLevel(e){x[e]||(e="error"),D=x[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),S.add(e,t,s)}};Object.keys(x).forEach(e=>{const t=x[e];I[e]=(...s)=>{t<=D&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});const k="silent",T="fatal",M="error",R="warn",E="info",W="debug",_={[k]:0,[T]:10,[M]:20,[R]:30,[E]:40,[W]:50};function A(e){const{code:t,text:s,type:a}=e,i=function(e){switch(e){case"fatal":case"error":return console.error;case"warn":case"info":case"debug":return console.log}}(a);console.groupCollapsed(a),i(t?`${t}: ${s}`:s),console.groupEnd()}const q=new class{constructor(e){this.relations=_,this.level=e&&void 0!==e.level?e.level:"error",this.applicationType=e&&void 0!==e.applicationType?e.applicationType:"sdk",this.subscribers=e&&void 0!==e.subscribers?e.subscribers:[]}updateLogLevel(e){this.level=e}updateApplicationType(e){this.applicationType=e}updateApplicationCode(e){this.applicationCode=e}updateDomain(e){this.domain=e}updateDeviceInfo(e){this.deviceInfo=e}subscribe(e,t){this.subscribers.push({handler:t,level:e})}async log(e){const t=[],{options:s,...a}=e;let i=a;if(s){const{handler:e,...t}=s;i={...a,...t}}const r=this.getMessage(i);this.subscribers.forEach(s=>{s.level===e.type&&this.relations[s.level]<=this.relations[this.level]&&t.push(s.handler.call(null,r))}),s&&s.handler&&"silent"!==this.level&&s.handler.call(null,r),await Promise.all(t)}async debug(e,t){return this.log({type:"debug",text:e,options:t})}async info(e,t){return this.log({type:"info",text:e,options:t})}async warn(e,t,s){return this.log({type:"warn",text:e,code:t,options:s})}async error(e,t,s){return this.log({type:"error",text:e,code:t,options:s})}async fatal(e,t,s){return this.log({type:"fatal",text:e,code:t,options:s})}async errorAndThrow(e,t,s){return this.logAndThrow({type:"error",text:e,code:t,options:s})}async errorAndReject(e,t,s,a){return this.logAndReject(e,{type:"error",text:t,code:s,options:a})}async fatalAndThrow(e,t,s){return this.logAndThrow({type:"fatal",text:e,code:t,options:s})}async fatalAndReject(e,t,s,a){return this.logAndReject(e,{type:"fatal",text:t,code:s,options:a})}async logAndThrow(e){await this.log(e);const t=new Error(e.text);throw e.code&&(t.code=e.code),t}async logAndReject(e,t){await this.log(t);const s=new Error(t.text);t.code&&(s.code=t.code),e(s)}getMessage(e){return{applicationCode:this.applicationCode,domain:this.domain,applicationType:this.applicationType,deviceInfo:this.deviceInfo,...e}}}({level:"error",subscribers:[{level:"fatal",handler:A},{level:"error",handler:A}]});async function N(e){const t=L(e);return q.fatal(t.text,t.code,t.options)}function L(e){const{message:t,code:s,error:a,...i}=e,r=function(e){let t=new Error("unknown error");"string"!=typeof e&&"number"!=typeof e&&"boolean"!=typeof e||(t.message=e.toString());e instanceof Error&&(t=e);return t}(a);return{text:t,code:s,options:{...i,errorText:r.message,errorStack:r.stack}}}class U{constructor(e=new Date){this._date=e}set date(e){this._date=e}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const e=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(e)}addDays(e){const t=this._date.getTime()+24*e*60*60*1e3;this._date=new Date(t)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}const O=["classic","captioned","banner","carousel"];function F(e){return(Array.isArray(e)?e:[]).filter(e=>!!e&&!!e.imageUrl).slice(0,5)}const j=/^(?:javascript|vbscript|data|blob|file):/i,V=/^[a-z][a-z\d+\-.]*:/i;function B(e){return e.split("").filter(e=>e.charCodeAt(0)>32&&127!==e.charCodeAt(0)).join("")}function H(e){const t=B(e);return V.test(t)&&!j.test(t)}function $(e,t){return t||e.image||""}function K(e){const t=["displayType","carousel","image"];return Object.keys(e).filter(e=>-1===t.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}class z{constructor(e,t,s,a={},i=()=>Promise.resolve(void 0),r=new U){this.data=e,this.api=t,this.inboxModel=s,this.moduleRegistry=a,this.loadWebPopups=i,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(e){try{return JSON.parse(e)||{}}catch(t){return I.write("error",`Pushwoosh: cannot parse inbox action_params: ${e}`,t),{}}}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const a=[],i=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,a.push(t),i.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(a),await Promise.all(i)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:a,send_date:i,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(t),u=function(e){const t=e?.u;if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)||{}}catch{return{}}return"object"==typeof t?t:{}}(c),h=function(e){return(Array.isArray(e.carousel)?e.carousel:[]).filter(e=>!!e&&!!e.image).slice(0,5).map(e=>({imageUrl:e.image,caption:e.title||"",link:e.url&&H(e.url)?e.url:""}))}(u),d=function(e,t,s){return e?.b||s||t.image||""}(c,u,s),l=function(e){const t=!!e.title,s=!!e.body,a=function(e){return e.bannerUrl||e.iconUrl||""}(e);let i=e.layoutType;switch(O.includes(i)||(i=e.bannerUrl&&!t?"banner":e.bannerUrl&&t&&s?"captioned":"classic"),i){case"banner":return a?"banner":"classic";case"captioned":return a&&t&&s?"captioned":"classic";case"carousel":return t&&s&&F(e.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:a,body:n,iconUrl:$(u,s),bannerUrl:c.b,layoutType:u.displayType,carousel:h}),g=$(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:K(u),webPopupCode:c.wp||"",code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,c),link:c?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10)).sort((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=this.parseActionParams(t.action_params),a=this.messageTypeFactory(t.action_type,s),i=2===a||3===a;var r;!await this.showWebPopup(s.wp)&&i&&null!=s.l&&((r=s.l)&&!j.test(B(r)))&&(document.location.href=s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async showWebPopup(e){if(!e)return!1;try{const t=this.moduleRegistry.webPopups??await this.loadWebPopups();return t?await t.show(e):(I.write("error",`Pushwoosh: inbox message opens web popup "${e}", but the web popups widget could not be loaded`),!1)}catch(t){return I.write("error",`Pushwoosh: failed to open web popup "${e}" from inbox`,t),!1}}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class J{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise((s,a)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{a(e.error)}})}readRequestPromise(e,t){return new Promise((s,a)=>{e.onsuccess=e=>{const a=e.target;s(a.result||t)},e.onerror=()=>{a(e.error)}})}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise((s,a)=>{e.onsuccess=e=>{const a=e.target.result;a?(t.push(a.value),a.continue()):s(t)},e.onerror=()=>{a(e.error)}})}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class G{getDB(){return y()}async put(e,t,s){const a=await this.getDB();return new J(a,e).put(t,s)}async delete(e,t){const s=await this.getDB();return new J(s,e).delete(t)}async get(e,t,s){const a=await this.getDB();return new J(a,e).get(t,s)}async getAll(e){const t=await this.getDB(),s=new J(t,e);return await s.getAll()||[]}async count(e,t){const s=await this.getDB();return new J(s,e).count(t)}async countByIndex(e,t,s){const a=await this.getDB(),i=new J(a,e);return i.index=t,i.countByIndex(s)}}class Y{constructor(e,t,s,a=new G,i=new U){this.eventBus=e,this.data=t,this.api=s,this.storage=a,this.storeName="inboxMessages",this.dateModule=i}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map(async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)});return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map(e=>this.putMessage(e));return Promise.all(t)}deleteMessages(e){const t=e.map(e=>this.storage.delete(this.storeName,e));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter(t=>t.rt<e).map(e=>e.inbox_id);return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>2===e.status||3===e.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>1===e.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new z(this.data,this.api,this)})}}const Q={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},X=/&(?:amp|lt|gt|quot|#39);/g,Z=RegExp(X.source);const ee=e=>`params.${e}`;class te{constructor(e=v){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const t of e)await this.store.set(ee(t),void 0)}async setApplicationCode(e){await this.store.set(ee("applicationCode"),e)}async getApplicationCode(){return this.store.get(ee("applicationCode"))}async setApiToken(e){return await this.store.set(ee("apiToken"),e)}async getApiToken(){return this.store.get(ee("apiToken"))}async setHwid(e){await this.store.set(ee("hwid"),e)}async getHwid(){return this.store.get(ee("hwid"))}async setDeviceType(e){await this.store.set(ee("deviceType"),e)}async getDeviceType(){return this.store.get(ee("deviceType"))}async setFormFactor(e){await this.store.set(ee("formFactor"),e)}async getFormFactor(){return this.store.get(ee("formFactor"))}async setDeviceModel(e){await this.store.set(ee("deviceModel"),e)}async getDeviceModel(){return this.store.get(ee("deviceModel"))}async setLanguage(e){await this.store.set(ee("language"),e)}async getLanguage(){return this.store.get(ee("language"),"en")}async setStatusLanguageWasChanged(e){await this.store.set(ee("languageWasChanged"),e)}async getStatusLanguageWasChanged(){return this.store.get(ee("languageWasChanged"),!1)}async setApiEntrypoint(e){await this.store.set(ee("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(ee("apiEntrypoint"),"https://api.pushwoosh.com/json/1.3/")}async setTokens(e){await this.store.set(ee("tokens"),e)}getTokens(){return this.store.get(ee("tokens"))}async setApplicationServerKey(e){await this.store.set(ee("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(ee("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(ee("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(ee("isVapidChanged"),!1)}async setWebVapidConfigured(e){await this.store.set(ee("webVapidConfigured"),e)}async getWebVapidConfigured(){return this.store.get(ee("webVapidConfigured"),!1)}async setWebSitePushId(e){await this.store.set(ee("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(ee("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(ee("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(ee("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(ee("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(ee("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(ee("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(ee("userId"))}async getFeatureFlags(){return this.store.get(ee("featureFlags"))}async setFeatureFlags(e){await this.store.set(ee("featureFlags"),e)}async getFeatureFlagImpressions(){return this.store.get(ee("featureFlagImpressions"),{})}async setFeatureFlagImpressions(e){await this.store.set(ee("featureFlagImpressions"),e)}async setStatusUserIdWasChanged(e){await this.store.set(ee("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(ee("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(ee("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(ee("email"))}async setStatusEmailWasChanged(e){await this.store.set(ee("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(ee("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(ee("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(ee("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(ee("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(ee("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(ee("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(ee("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(ee("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(ee("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(ee("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(ee("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(ee("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(ee("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(ee("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(ee("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(ee("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(ee("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(ee("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(ee("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(ee("sdkVersion"),e)}async getSdkVersion(){return this.store.get(ee("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(ee("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(ee("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(ee("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(ee("serviceWorkerUrl"),"/pushwoosh-service-worker.js")}async setServiceWorkerScope(e){e&&await this.store.set(ee("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(ee("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(ee("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(ee("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(ee("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(ee("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(ee("features"),e)}async getFeatures(){return this.store.get(ee("features"))}async setInitParams(e){await this.store.set(ee("init"),e)}async getInitParams(){return this.store.get(ee("init"))}async setInboxLastRequestCode(e){await this.store.set(ee("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(ee("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(ee("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(ee("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(ee("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(ee("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(ee("delayedEvent"),e)}getDelayedEvent(){return this.store.get(ee("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(ee("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(ee("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(ee("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(ee("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(e){await this.store.set(ee("subscriptionWidgetHistory"),e)}async getSubscriptionWidgetHistory(){return this.store.get(ee("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(e){await this.store.set(ee("logLevel"),e)}async getLogLevel(){return this.store.get(ee("logLevel"),"error")}async getShownWebPopups(){return this.store.get(ee("shownWebPopups"),[])}async addShownWebPopup(e){const t=await this.getShownWebPopups();t.includes(e)||(t.push(e),await this.store.set(ee("shownWebPopups"),t))}async setIsRecurringVisitor(e){await this.store.set(ee("isRecurringVisitor"),e)}async getIsRecurringVisitor(){return this.store.get(ee("isRecurringVisitor"),!1)}}class se{constructor(e,t=new te,s=new U){if("data"in e){const t=e;this.payload=t.data}else this.payload=e;this.data=t,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?(e=this.payload.l)&&Z.test(e)?e.replace(X,e=>Q[e]):e:"/";var e}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:e,p:t,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 e=await this.getTitle(),t=await this.getIcon();return{...this.rootParams,body:this.body,title:e,icon:t,image:this.image,buttons:this.buttons,customData:this.customData,metaData:this.metaData,campaignCode:this.campaignCode,openUrl:this.link,messageHash:this.messageHash}}async getShowNotificationOptions(){const e=await this.getIcon(),t=this.buttons.map((e,t)=>(e.action=e.id||`action-${t}`,e));return{renotify:!0,...this.rootParams,body:this.body,icon:e,tag:JSON.stringify({url:this.link,messageHash:this.messageHash,customData:this.customData,metaData:this.metaData}),data:{code:this.code,buttons:t,image:this.image,campaignCode:this.campaignCode,inboxId:this.inboxId},silent:this.silent,actions:t,image:this.image,buttons:t}}async getInboxMessage(){this.dateModule.date=new Date;const e=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:e,rt:this.inboxRemovalTime,text:this.body,action_type:1,action_params:JSON.stringify({l:this.link})}}}function ae(){const{pathname:e}=window.location;try{return decodeURIComponent(e)}catch{return e}}class ie extends Error{constructor(e,t){super(e),this.name="ApiRequestError",this.statusCode=t}}class re{constructor(e=new te,t=I){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}getPopupForms(e){return this.createRequest("getPopupForms",e)}getPopupFormContent(e){return this.createRequest("getPopupFormContent",e)}recordPopupFormEvent(e){return this.createRequest("recordPopupFormEvent",e)}submitPopupForm(e){return this.createRequest("submitPopupForm",e)}getWebPlacements(e){return this.createRequest("getWebPlacements",e)}trackWebPlacement(e){return this.createRequest("trackWebPlacement",e)}applicationOpen(e){return this.createRequest("applicationOpen",e)}registerDevice(e){return this.createRequest("registerDevice",e)}unregisterDevice(e){return this.createRequest("unregisterDevice",e)}deleteDevice(e){return this.createRequest("deleteDevice",e)}messageDeliveryEvent(e){return this.createRequest("messageDeliveryEvent",e)}pushStat(e){return this.createRequest("pushStat",e)}setTags(e){return this.createRequest("setTags",e)}getTags(e){return this.createRequest("getTags",e)}registerUser(e){return this.createRequest("registerUser",e)}registerEmail(e){return this.createRequest("registerEmail",e)}registerEmailUser(e){return this.createRequest("registerEmailUser",e)}setEmailTags(e){return this.createRequest("setEmailTags",e)}postEvent(e,t){return this.createRequest("postEvent",e,t)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e){return this.createRequest("inboxStatus",e)}multiRegisterDevice(e){return this.createRequest("multiRegisterDevice",e)}sdkUsage(e,t){return this.createRequest("sdkUsage",e,t)}async createRequest(e,t,s={}){const a=await this.data.getApiEntrypoint(),i=await this.data.getApiToken(),r=a+e,n=i?{headers:{Authorization:`Token ${i}`,"Content-Type":"text/plain;charset=UTF-8",Origin:globalThis.location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n,keepalive:s.keepalive}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(e){if(200!==e.status){let t,s=`status: ${e.status}. statusText: ${e.statusText}.`;try{const a=await e.json();a&&"number"==typeof a.status_code&&(t=a.status_code),a&&a.status_message&&(s+=` status_code: ${a.status_code}. status_message: ${a.status_message}.`)}catch(e){}throw new ie(s,t)}const t=await e.json();if(200!==t.status_code)throw new ie(`Error code: ${t.status_code}. Error text: ${t.status_message}`,"number"==typeof t.status_code?t.status_code:void 0);return t}}function ne(e){try{return e?Intl.getCanonicalLocales(e)[0]??"":""}catch{return""}}class oe{constructor(e,t,s){this.api=e,this.data=t,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(e){const t=e||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void I.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),a=t.getKey("p256dh"),i=t.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:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t&&(await this.data.setLastPermissionStatus(t),void 0!==e))return!0;const s=await this.getCredentials(),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 e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${r()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),a=new Uint8Array(s.length);for(let e=0;e<s.length;++e)a[e]=s.charCodeAt(e);return a}}class ce{constructor(e,t,s){this._canceled=!1,this.showNotificationOptions=e,this.body=t,this.title=s}async show(){if(this._canceled)return;const e=this.showNotificationOptions;e.silent||await self.registration.showNotification(this.title,e)}cancel(){this._canceled=!0}}const ue=new class{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter(e=>e!==t))},this.dispatchEvent=(e,t)=>{const s=t.eventId||r(),a=this.handlers[e];return a?(a.forEach(e=>{n(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}},he=new te,de=new class{constructor(e,t=new te,s=new re,a=()=>!1,i=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=o(1e4),this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=a,this.getInitUserId=i,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(e=>{throw this.checkDevicePromise=null,e})),this.checkDevicePromise}async requestCheckDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(t=!0){let i=localStorage.getItem(e);if(null===i||!t){const{exist:t,push_token_exist:r}=await this.checkDevice();localStorage.setItem(e,t&&r?s:a),i=localStorage.getItem(e)}return i===s}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(e=>{throw this.ensureDeviceRegisteredPromise=null,e})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:e}=await this.checkDevice();if(e)return!1;const t=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t),!0}async reportPushPermissionStatus(e=!1){const s=this.getPushPermissionStatus();if(s&&s!==this.reportingPushPermissionStatus&&s!==localStorage.getItem(t)){this.reportingPushPermissionStatus=s;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!e&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status: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(t)}rememberReportedPushPermissionStatus(e){e&&localStorage.setItem(t,e)}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const t=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...e,push_permission_status:t,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(t),s}async registerDevice(){const e=this.requestRegisterDevice();this.registerDevicePromise=e;try{return await e}finally{this.registerDevicePromise===e&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const t=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({...t,push_permission_status:i,locale:await this.getLocale(),page:ae(),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(e,s),this.eventBus.dispatchEvent("register",{}),r}async unregisterDevice(){const t=await this.getRequestParams(),s=await this.apiClient.unregisterDevice(t);return this.checkDevicePromise=null,localStorage.setItem(e,a),this.eventBus.dispatchEvent("unsubscribe",{}),s}async deleteDevice(){const t=await this.getRequestParams(),s=await this.apiClient.deleteDevice(t);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(e,a),this.eventBus.dispatchEvent("unsubscribe",{}),s}async messageDeliveryEvent(e,t,s={}){const a=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...a,hash:e,metaData:s})}async pushStat(e,t,s={},a){const i=await this.getRequestParams();return await this.apiClient.pushStat({...i,hash:e,metaData:s,...a?{button_id:a}:{}})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getEmail();return i&&await this.apiClient.setEmailTags({...a,email:i,tags:e}),this.apiClient.setTags({...a,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async setLanguage(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:e}))}async setLocale(e){if(!e)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const t=ne(e.trim().replace(/_/g,"-"));t&&(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return ne(await this.data.getLanguage())||void 0}async registerUser(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${e}`,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}),t&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),a=await this.apiClient.registerEmail({...s,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),a}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:a}=await this.getIdentityRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),i}async registerWhatsappNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:a}=await this.getIdentityRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),i}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:e})}async recordPopupFormEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:e,event:t};return this.apiClient.recordPopupFormEvent(3===t?{...s,clickId:r()}:s)}async getWebPlacements(){if(this.getIsCommunicationDisabled())return[];const e=await this.apiClient.getWebPlacements(await this.getRequestParams());return e?.web_placements??[]}async trackWebPlacement(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.trackWebPlacement({...await this.getRequestParams(),hash:e,action:t})}async submitPopupForm(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:e,email:t.email,tags:t.tags,policy_accepted:t.policyAccepted})}async sdkUsage(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams();return this.apiClient.sdkUsage({...s,...e},t)}async postEvent(e,t,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const 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(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const u=await this.apiClient.postEvent({...a,event:e,timestampUTC:n,timestampCurrent:o,attributes:t},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(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),a=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:a})}async inboxStatus(e,t){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:e,status:t,time:(new Date).getTime()})}async multiRegisterDevice(t){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();!t.push_devices&&c.pushToken&&await this.requireHwid();const h={application:a,...t};if(t.user_id){h.user_id=String(t.user_id);await this.data.getUserId()!==h.user_id&&(await this.data.setUserId(h.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(t.email){if(!/^\S+@\S+\.\S+$/.test(t.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==t.email&&(await this.data.setEmail(t.email),await this.data.setStatusEmailWasChanged(!0))}if(t.sms_phone_number){if(!/^\+?[0-9]+$/.test(t.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==t.sms_phone_number&&(await this.data.setSmsNumber(t.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(t.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(t.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==t.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(t.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 e=60*-(new Date).getTimezoneOffset();h.timezone=String(e)}if(!h.push_devices&&c.pushToken){const e={hwid:u,platform:r,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||i){const t={};c.publicKey&&(t.public_key=c.publicKey),c.authToken&&(t.auth_token=c.authToken),i&&(t.browser=i),e.platformData=t}h.push_devices=[e]}const d=await this.apiClient.multiRegisterDevice(h);return h.push_devices?.length&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(e,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 e=await this.requireHwid(),t=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:e,device_type:t}}async getIdentityRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),a=await this.data.getDeviceModel(),i=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!t)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:e,userId:s||t,device_model:a,timezone:n,language:i,v:r}}async requireHwid(){const e=await this.data.getHwid();if(!e)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 e}}(ue,he);he.getLogLevel().then(e=>{e&&I.setLevel(e)});const le=self.Pushwoosh=new class{constructor(e,t,s){this._listeners={},this.eventBus=e,this.data=t,this.api=s}push(e){Array.isArray(e)&&"onPush"===e[0]&&n(e[1])&&(this._listeners[e[0]]||(this._listeners[e[0]]=[]),this._listeners[e[0]].push(e[1]))}getListeners(e){return this._listeners[e]||[]}async initApi(){return Promise.resolve()}}(ue,he,de),ge=[];async function pe(e){(await self.clients.matchAll()).forEach(t=>t.postMessage(e))}async function me(e){const{notification:t={}}=e,{data:s}=t,a=i(t.tag,{});let r,n="";if(e.action&&Array.isArray(s.buttons)){const t=s.buttons.find(t=>t.action===e.action)||{};n=t.url,r=t.id}else n=a.url;return{title:t.title,body:t.body,icon:t.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:t.tag,url:n,buttonId:r}}async function we(e){const t=await le.data.getApplicationCode(),s=await le.data.getServiceWorkerVersion();await N({message:"Error in onInstallEventHandler",code:"FATAL-SW-001",error:e,applicationCode:t,workerVersion:s})}async function ye(e){const t=await le.data.getApplicationCode(),s=await le.data.getServiceWorkerVersion();await N({message:"Error in onActivateEventHandler",code:"FATAL-SW-002",error:e,applicationCode:t,workerVersion:s})}async function be(e){const t=await le.data.getApplicationCode(),s=await le.data.getServiceWorkerVersion();await N({message:"Error in onNotificationClickEventHandler",code:"FATAL-SW-004",error:e,applicationCode:t,workerVersion:s})}async function fe(e){const t=await le.data.getApplicationCode(),s=await le.data.getServiceWorkerVersion();await N({message:"Error in onNotificationCloseEventHandler",code:"FATAL-SW-005",error:e,applicationCode:t,workerVersion:s})}async function ve(e){const t=await le.data.getApplicationCode(),s=await le.data.getServiceWorkerVersion();await N({message:"Error in onPushSubscriptionChange",code:"FATAL-SW-006",error:e,applicationCode:t,workerVersion:s})}return self.addEventListener("install",function(e){return e.waitUntil(async function(){await Promise.all([le.data.setServiceWorkerVersion("3.117.0"),I.write("info","install")]),await self.skipWaiting()}().catch(we))}),self.addEventListener("activate",function(e){e.waitUntil(async function(){await Promise.all([I.write("info","activate")]),await self.clients.claim()}().catch(ye))}),self.addEventListener("push",function(e){e.waitUntil(async function(e){await self.clients.claim();const t=await e.data.json(),s=new se(t),a=await s.getNotificationOptionsPayload(),i=await s.getShowNotificationOptions(),r=s.messageHash;await I.write("info",JSON.stringify(a),"onPush");const n=new ce(i,s.body,await s.getTitle()),o=le.getListeners("onPush");await o.reduce((e,t)=>e.then(()=>t(n)),Promise.resolve());const c=[n.show(),C.add({payload:t,parsedPayload:a,showOptions:i}),pe({type:"onPushDelivery",payload:a})];if(r&&c.push(le.initApi().then(()=>le.api.messageDeliveryEvent(r,!0,a.metaData))),""!==s.inboxId){const e=new Y(le.eventBus,le.data,le.api),t=new z(le.data,le.api,e),a=await s.getInboxMessage(),i=await t.publicMessageBuilder(a);c.push(e.putMessage(a),pe({type:"onPutNewMessageToInboxStore",payload:i}))}await Promise.all(c)}(e).catch(t=>async function(e,t){const s=await le.data.getApplicationCode(),a=await le.data.getServiceWorkerVersion();await N({message:"Error in onPushEventHandler",code:"FATAL-SW-003",error:e,applicationCode:s,workerVersion:a}),e instanceof Error||(e=new Error(e));return C.add({error:`${e}`,stack:e.stack,payload:t.data&&t.data.text()})}(t,e)))}),self.addEventListener("notificationclick",function(e){e.waitUntil(async function(e){await self.clients.claim();const t=await me(e),{messageHash:s,metaData:a,url:i,buttonId:r,code:n,inboxId:o}=t;if(n&&ge.push(n),""!==o){const e=new Y(le.eventBus,le.data,le.api),t=await e.getMessage(o);t.status=3,await e.putMessage(t)}e.notification.close();const c={type:"onNotificationClick",payload:t};return i&&e.waitUntil(self.clients.matchAll({type:"window"}).then(e=>async function(e,t){const{hostname:s,pathname:a}=new URL(t,self.location.origin),i=e.find(e=>{const{hostname:t,pathname:i}=new URL(e.url);return t===s&&i===a});return i?(await i.focus(),!1):(await self.clients.openWindow(t).then(e=>{e&&e.focus()}),!0)}(e,i)).then(e=>{e&&le.data.setDelayedEvent(c)})),Promise.all([le.initApi().then(()=>le.api.pushStat(s,!0,a,r)),le.data.setLastOpenMessage({url:i,messageHash:s,expiry:Date.now()+864e5}),pe(c)])}(e).catch(be))}),self.addEventListener("notificationclose",function(e){e.waitUntil(async function(e){await self.clients.claim();const t=await me(e),{code:s}=t;if(e.notification.close(),!s)return;const a=ge.indexOf(s);if(!(a>=0))return pe({type:"onNotificationClose",payload:t});ge.splice(a,1)}(e).catch(fe))}),self.addEventListener("pushsubscriptionchange",async function(e){e.waitUntil(async function(e){let t=e.newSubscription;if(!t&&(t=await self.registration.pushManager.getSubscription(),!t))return;const s=new oe(de,he,{});await s.subscribe(t)}(e).catch(ve))}),{}})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var a in s)("object"==typeof exports?exports:e)[a]=s[a]}}(this,()=>(()=>{"use strict";const e="deviceRegistrationStatus",t="reportedPushPermissionStatus",s="registered",a="unregistered";function i(e,t){if("string"==typeof e)try{return JSON.parse(e)}catch(e){console.log(e)}return void 0===e&&void 0!==t?t:e}function r(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const n=e=>"function"==typeof e;function o(e){const t=new WeakSet;return async s=>{if(t.has(s))return!1;const a=await function(e,t){let s;const a=new Promise(e=>{s=setTimeout(()=>e(!1),t)}),i=e.then(()=>!0,()=>!0);return Promise.race([i,a]).finally(()=>clearTimeout(s))}(s,e);return a||t.add(s),a}}const c="keyValue",u="messages",h="inboxMessages";function d(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const l=[d(c,function(e){e.createObjectStore(c,{keyPath:"key"})}),d("log",function(e){const t=e.createObjectStore("log",{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),d(u,function(e){e.createObjectStore(u,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),d(h,function(e){const t="status",s=e.createObjectStore(h,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class g{get all(){return l}}class p{constructor(e,t=new g){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function m(e,t){console.info("onversionchange",t),e.close()}let w;function y(){return w||(w=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const a=s.target.result;a.onversionchange=m.bind(null,a,t),e(a)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=m.bind(null,s,t);new p(s).applyMigrations()}})),w}function b(e){return y().then(t=>new Promise((s,a)=>e(t,s,a)))}class f{_add(e){return b((t,s,a)=>{const i=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);i.onsuccess=()=>{s(e)},i.onerror=()=>{a(i.error)}}).then(e=>this.getAll().then(t=>{if(Array.isArray(t)){const s=t.map(e=>e.id).sort((e,t)=>e==t?0:e<t?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(e=>this.delete(e))).then(()=>e)}return e}))}delete(e){return b((t,s,a)=>{const i=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);i.onsuccess=()=>{s(i.result)},i.onerror=()=>{a(i.error)}})}getAll(){return b((e,t,s)=>{const a=[],i=e.transaction(this.name).objectStore(this.name).openCursor();i.onsuccess=e=>{const s=e.target.result;s?(s.value&&a.push(s.value),s.continue()):t(a)},i.onerror=()=>{s(i.error)}})}}const v=(P=c,{get:(e,t)=>b((s,a,i)=>{const r=s.transaction(P).objectStore(P).get(e);let n,o=!1,c=!1;const u=()=>{clearTimeout(n),o?a(r.result?.value||t):c?i(r.error):n=setTimeout(u,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,u()}),getAll:()=>b((e,t,s)=>{const a={},i=e.transaction(P).objectStore(P).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(a):o?s(i.error):r=setTimeout(c,0)};i.onsuccess=e=>{const t=e.target.result;t?(a[t.key]=t.value.value,t.continue()):n=!0},i.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...a}=t;await this.set(e,{...s,...a})},set:(e,t)=>b((s,a,i)=>{const r=s.transaction([P],"readwrite").objectStore(P).put({key:e,value:t});let n,o=!1,c=!1;const u=()=>{clearTimeout(n),o?a(e):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(e,t,s){const a={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(a.stack=t.stack),s&&(a.additional=s),this._add(a)}},C=new class extends f{constructor(){super(...arguments),this.name=u,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},x={error:1,info:2,debug:3};let D=3;const I={setLevel(e){x[e]||(e="error"),D=x[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),S.add(e,t,s)}};Object.keys(x).forEach(e=>{const t=x[e];I[e]=(...s)=>{t<=D&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});const k="silent",T="fatal",M="error",R="warn",E="info",W="debug",_={[k]:0,[T]:10,[M]:20,[R]:30,[E]:40,[W]:50};function A(e){const{code:t,text:s,type:a}=e,i=function(e){switch(e){case"fatal":case"error":return console.error;case"warn":case"info":case"debug":return console.log}}(a);console.groupCollapsed(a),i(t?`${t}: ${s}`:s),console.groupEnd()}const q=new class{constructor(e){this.relations=_,this.level=e&&void 0!==e.level?e.level:"error",this.applicationType=e&&void 0!==e.applicationType?e.applicationType:"sdk",this.subscribers=e&&void 0!==e.subscribers?e.subscribers:[]}updateLogLevel(e){this.level=e}updateApplicationType(e){this.applicationType=e}updateApplicationCode(e){this.applicationCode=e}updateDomain(e){this.domain=e}updateDeviceInfo(e){this.deviceInfo=e}subscribe(e,t){this.subscribers.push({handler:t,level:e})}async log(e){const t=[],{options:s,...a}=e;let i=a;if(s){const{handler:e,...t}=s;i={...a,...t}}const r=this.getMessage(i);this.subscribers.forEach(s=>{s.level===e.type&&this.relations[s.level]<=this.relations[this.level]&&t.push(s.handler.call(null,r))}),s&&s.handler&&"silent"!==this.level&&s.handler.call(null,r),await Promise.all(t)}async debug(e,t){return this.log({type:"debug",text:e,options:t})}async info(e,t){return this.log({type:"info",text:e,options:t})}async warn(e,t,s){return this.log({type:"warn",text:e,code:t,options:s})}async error(e,t,s){return this.log({type:"error",text:e,code:t,options:s})}async fatal(e,t,s){return this.log({type:"fatal",text:e,code:t,options:s})}async errorAndThrow(e,t,s){return this.logAndThrow({type:"error",text:e,code:t,options:s})}async errorAndReject(e,t,s,a){return this.logAndReject(e,{type:"error",text:t,code:s,options:a})}async fatalAndThrow(e,t,s){return this.logAndThrow({type:"fatal",text:e,code:t,options:s})}async fatalAndReject(e,t,s,a){return this.logAndReject(e,{type:"fatal",text:t,code:s,options:a})}async logAndThrow(e){await this.log(e);const t=new Error(e.text);throw e.code&&(t.code=e.code),t}async logAndReject(e,t){await this.log(t);const s=new Error(t.text);t.code&&(s.code=t.code),e(s)}getMessage(e){return{applicationCode:this.applicationCode,domain:this.domain,applicationType:this.applicationType,deviceInfo:this.deviceInfo,...e}}}({level:"error",subscribers:[{level:"fatal",handler:A},{level:"error",handler:A}]});async function N(e){const t=L(e);return q.fatal(t.text,t.code,t.options)}function L(e){const{message:t,code:s,error:a,...i}=e,r=function(e){let t=new Error("unknown error");"string"!=typeof e&&"number"!=typeof e&&"boolean"!=typeof e||(t.message=e.toString());e instanceof Error&&(t=e);return t}(a);return{text:t,code:s,options:{...i,errorText:r.message,errorStack:r.stack}}}class U{constructor(e=new Date){this._date=e}set date(e){this._date=e}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const e=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(e)}addDays(e){const t=this._date.getTime()+24*e*60*60*1e3;this._date=new Date(t)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}const O=["classic","captioned","banner","carousel"];function F(e){return(Array.isArray(e)?e:[]).filter(e=>!!e&&!!e.imageUrl).slice(0,5)}const j=/^(?:javascript|vbscript|data|blob|file):/i,V=/^[a-z][a-z\d+\-.]*:/i;function B(e){return e.split("").filter(e=>e.charCodeAt(0)>32&&127!==e.charCodeAt(0)).join("")}function H(e){const t=B(e);return V.test(t)&&!j.test(t)}function $(e,t){return t||e.image||""}function K(e){const t=["displayType","carousel","image"];return Object.keys(e).filter(e=>-1===t.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}class z{constructor(e,t,s,a={},i=()=>Promise.resolve(void 0),r=new U){this.data=e,this.api=t,this.inboxModel=s,this.moduleRegistry=a,this.loadWebPopups=i,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(e){try{return JSON.parse(e)||{}}catch(t){return I.write("error",`Pushwoosh: cannot parse inbox action_params: ${e}`,t),{}}}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const a=[],i=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,a.push(t),i.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(a),await Promise.all(i)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:a,send_date:i,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(t),u=function(e){const t=e?.u;if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)||{}}catch{return{}}return"object"==typeof t?t:{}}(c),h=function(e){return(Array.isArray(e.carousel)?e.carousel:[]).filter(e=>!!e&&!!e.image).slice(0,5).map(e=>({imageUrl:e.image,caption:e.title||"",link:e.url&&H(e.url)?e.url:""}))}(u),d=function(e,t,s){return e?.b||s||t.image||""}(c,u,s),l=function(e){const t=!!e.title,s=!!e.body,a=function(e){return e.bannerUrl||e.iconUrl||""}(e);let i=e.layoutType;switch(O.includes(i)||(i=e.bannerUrl&&!t?"banner":e.bannerUrl&&t&&s?"captioned":"classic"),i){case"banner":return a?"banner":"classic";case"captioned":return a&&t&&s?"captioned":"classic";case"carousel":return t&&s&&F(e.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:a,body:n,iconUrl:$(u,s),bannerUrl:c.b,layoutType:u.displayType,carousel:h}),g=$(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:K(u),webPopupCode:c.wp||"",code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,c),link:c?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10)).sort((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=this.parseActionParams(t.action_params),a=this.messageTypeFactory(t.action_type,s),i=2===a||3===a;var r;!await this.showWebPopup(s.wp)&&i&&null!=s.l&&((r=s.l)&&!j.test(B(r)))&&(document.location.href=s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async showWebPopup(e){if(!e)return!1;try{const t=this.moduleRegistry.webPopups??await this.loadWebPopups();return t?await t.show(e):(I.write("error",`Pushwoosh: inbox message opens web popup "${e}", but the web popups widget could not be loaded`),!1)}catch(t){return I.write("error",`Pushwoosh: failed to open web popup "${e}" from inbox`,t),!1}}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class J{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise((s,a)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{a(e.error)}})}readRequestPromise(e,t){return new Promise((s,a)=>{e.onsuccess=e=>{const a=e.target;s(a.result||t)},e.onerror=()=>{a(e.error)}})}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise((s,a)=>{e.onsuccess=e=>{const a=e.target.result;a?(t.push(a.value),a.continue()):s(t)},e.onerror=()=>{a(e.error)}})}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class G{getDB(){return y()}async put(e,t,s){const a=await this.getDB();return new J(a,e).put(t,s)}async delete(e,t){const s=await this.getDB();return new J(s,e).delete(t)}async get(e,t,s){const a=await this.getDB();return new J(a,e).get(t,s)}async getAll(e){const t=await this.getDB(),s=new J(t,e);return await s.getAll()||[]}async count(e,t){const s=await this.getDB();return new J(s,e).count(t)}async countByIndex(e,t,s){const a=await this.getDB(),i=new J(a,e);return i.index=t,i.countByIndex(s)}}class Y{constructor(e,t,s,a=new G,i=new U){this.eventBus=e,this.data=t,this.api=s,this.storage=a,this.storeName="inboxMessages",this.dateModule=i}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map(async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)});return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map(e=>this.putMessage(e));return Promise.all(t)}deleteMessages(e){const t=e.map(e=>this.storage.delete(this.storeName,e));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter(t=>t.rt<e).map(e=>e.inbox_id);return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>2===e.status||3===e.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>1===e.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new z(this.data,this.api,this)})}}const Q={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},X=/&(?:amp|lt|gt|quot|#39);/g,Z=RegExp(X.source);const ee=e=>`params.${e}`;class te{constructor(e=v){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const t of e)await this.store.set(ee(t),void 0)}async setApplicationCode(e){await this.store.set(ee("applicationCode"),e)}async getApplicationCode(){return this.store.get(ee("applicationCode"))}async setApiToken(e){return await this.store.set(ee("apiToken"),e)}async getApiToken(){return this.store.get(ee("apiToken"))}async setHwid(e){await this.store.set(ee("hwid"),e)}async getHwid(){return this.store.get(ee("hwid"))}async setDeviceType(e){await this.store.set(ee("deviceType"),e)}async getDeviceType(){return this.store.get(ee("deviceType"))}async setFormFactor(e){await this.store.set(ee("formFactor"),e)}async getFormFactor(){return this.store.get(ee("formFactor"))}async setDeviceModel(e){await this.store.set(ee("deviceModel"),e)}async getDeviceModel(){return this.store.get(ee("deviceModel"))}async setLanguage(e){await this.store.set(ee("language"),e)}async getLanguage(){return this.store.get(ee("language"),"en")}async setStatusLanguageWasChanged(e){await this.store.set(ee("languageWasChanged"),e)}async getStatusLanguageWasChanged(){return this.store.get(ee("languageWasChanged"),!1)}async setApiEntrypoint(e){await this.store.set(ee("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(ee("apiEntrypoint"),"https://api.pushwoosh.com/json/1.3/")}async setTokens(e){await this.store.set(ee("tokens"),e)}getTokens(){return this.store.get(ee("tokens"))}async setApplicationServerKey(e){await this.store.set(ee("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(ee("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(ee("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(ee("isVapidChanged"),!1)}async setWebVapidConfigured(e){await this.store.set(ee("webVapidConfigured"),e)}async getWebVapidConfigured(){return this.store.get(ee("webVapidConfigured"),!1)}async setWebSitePushId(e){await this.store.set(ee("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(ee("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(ee("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(ee("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(ee("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(ee("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(ee("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(ee("userId"))}async getFeatureFlags(){return this.store.get(ee("featureFlags"))}async setFeatureFlags(e){await this.store.set(ee("featureFlags"),e)}async getFeatureFlagImpressions(){return this.store.get(ee("featureFlagImpressions"),{})}async setFeatureFlagImpressions(e){await this.store.set(ee("featureFlagImpressions"),e)}async setStatusUserIdWasChanged(e){await this.store.set(ee("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(ee("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(ee("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(ee("email"))}async setStatusEmailWasChanged(e){await this.store.set(ee("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(ee("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(ee("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(ee("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(ee("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(ee("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(ee("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(ee("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(ee("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(ee("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(ee("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(ee("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(ee("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(ee("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(ee("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(ee("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(ee("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(ee("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(ee("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(ee("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(ee("sdkVersion"),e)}async getSdkVersion(){return this.store.get(ee("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(ee("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(ee("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(ee("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(ee("serviceWorkerUrl"),"/pushwoosh-service-worker.js")}async setServiceWorkerScope(e){e&&await this.store.set(ee("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(ee("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(ee("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(ee("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(ee("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(ee("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(ee("features"),e)}async getFeatures(){return this.store.get(ee("features"))}async setInitParams(e){await this.store.set(ee("init"),e)}async getInitParams(){return this.store.get(ee("init"))}async setInboxLastRequestCode(e){await this.store.set(ee("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(ee("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(ee("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(ee("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(ee("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(ee("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(ee("delayedEvent"),e)}getDelayedEvent(){return this.store.get(ee("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(ee("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(ee("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(ee("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(ee("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(e){await this.store.set(ee("subscriptionWidgetHistory"),e)}async getSubscriptionWidgetHistory(){return this.store.get(ee("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(e){await this.store.set(ee("logLevel"),e)}async getLogLevel(){return this.store.get(ee("logLevel"),"error")}async getShownWebPopups(){return this.store.get(ee("shownWebPopups"),[])}async addShownWebPopup(e){const t=await this.getShownWebPopups();t.includes(e)||(t.push(e),await this.store.set(ee("shownWebPopups"),t))}async setIsRecurringVisitor(e){await this.store.set(ee("isRecurringVisitor"),e)}async getIsRecurringVisitor(){return this.store.get(ee("isRecurringVisitor"),!1)}}class se{constructor(e,t=new te,s=new U){if("data"in e){const t=e;this.payload=t.data}else this.payload=e;this.data=t,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?(e=this.payload.l)&&Z.test(e)?e.replace(X,e=>Q[e]):e:"/";var e}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:e,p:t,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 e=await this.getTitle(),t=await this.getIcon();return{...this.rootParams,body:this.body,title:e,icon:t,image:this.image,buttons:this.buttons,customData:this.customData,metaData:this.metaData,campaignCode:this.campaignCode,openUrl:this.link,messageHash:this.messageHash}}async getShowNotificationOptions(){const e=await this.getIcon(),t=this.buttons.map((e,t)=>(e.action=e.id||`action-${t}`,e));return{renotify:!0,...this.rootParams,body:this.body,icon:e,tag:JSON.stringify({url:this.link,messageHash:this.messageHash,customData:this.customData,metaData:this.metaData}),data:{code:this.code,buttons:t,image:this.image,campaignCode:this.campaignCode,inboxId:this.inboxId},silent:this.silent,actions:t,image:this.image,buttons:t}}async getInboxMessage(){this.dateModule.date=new Date;const e=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:e,rt:this.inboxRemovalTime,text:this.body,action_type:1,action_params:JSON.stringify({l:this.link})}}}function ae(){const{pathname:e}=window.location;try{return decodeURIComponent(e)}catch{return e}}class ie extends Error{constructor(e,t){super(e),this.name="ApiRequestError",this.statusCode=t}}class re{constructor(e=new te,t=I){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}getPopupForms(e){return this.createRequest("getPopupForms",e)}getPopupFormContent(e){return this.createRequest("getPopupFormContent",e)}recordPopupFormEvent(e){return this.createRequest("recordPopupFormEvent",e)}submitPopupForm(e){return this.createRequest("submitPopupForm",e)}getWebPlacements(e){return this.createRequest("getWebPlacements",e)}trackWebPlacement(e){return this.createRequest("trackWebPlacement",e)}applicationOpen(e){return this.createRequest("applicationOpen",e)}registerDevice(e){return this.createRequest("registerDevice",e)}unregisterDevice(e){return this.createRequest("unregisterDevice",e)}deleteDevice(e){return this.createRequest("deleteDevice",e)}messageDeliveryEvent(e){return this.createRequest("messageDeliveryEvent",e)}pushStat(e){return this.createRequest("pushStat",e)}setTags(e){return this.createRequest("setTags",e)}getTags(e){return this.createRequest("getTags",e)}registerUser(e){return this.createRequest("registerUser",e)}registerEmail(e){return this.createRequest("registerEmail",e)}registerEmailUser(e){return this.createRequest("registerEmailUser",e)}setEmailTags(e){return this.createRequest("setEmailTags",e)}postEvent(e,t){return this.createRequest("postEvent",e,t)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e){return this.createRequest("inboxStatus",e)}multiRegisterDevice(e){return this.createRequest("multiRegisterDevice",e)}sdkUsage(e,t){return this.createRequest("sdkUsage",e,t)}async createRequest(e,t,s={}){const a=await this.data.getApiEntrypoint(),i=await this.data.getApiToken(),r=a+e,n=i?{headers:{Authorization:`Token ${i}`,"Content-Type":"text/plain;charset=UTF-8",Origin:globalThis.location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n,keepalive:s.keepalive}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(e){if(200!==e.status){let t,s=`status: ${e.status}. statusText: ${e.statusText}.`;try{const a=await e.json();a&&"number"==typeof a.status_code&&(t=a.status_code),a&&a.status_message&&(s+=` status_code: ${a.status_code}. status_message: ${a.status_message}.`)}catch(e){}throw new ie(s,t)}const t=await e.json();if(200!==t.status_code)throw new ie(`Error code: ${t.status_code}. Error text: ${t.status_message}`,"number"==typeof t.status_code?t.status_code:void 0);return t}}function ne(e){try{return e?Intl.getCanonicalLocales(e)[0]??"":""}catch{return""}}class oe{constructor(e,t,s){this.api=e,this.data=t,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(e){const t=e||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void I.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),a=t.getKey("p256dh"),i=t.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:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t&&(await this.data.setLastPermissionStatus(t),void 0!==e))return!0;const s=await this.getCredentials(),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 e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${r()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),a=new Uint8Array(s.length);for(let e=0;e<s.length;++e)a[e]=s.charCodeAt(e);return a}}class ce{constructor(e,t,s){this._canceled=!1,this.showNotificationOptions=e,this.body=t,this.title=s}async show(){if(this._canceled)return;const e=this.showNotificationOptions;e.silent||await self.registration.showNotification(this.title,e)}cancel(){this._canceled=!0}}const ue=new class{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter(e=>e!==t))},this.dispatchEvent=(e,t)=>{const s=t.eventId||r(),a=this.handlers[e];return a?(a.forEach(e=>{n(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}},he=new te,de=new class{constructor(e,t=new te,s=new re,a=()=>!1,i=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=o(1e4),this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=a,this.getInitUserId=i,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(e=>{throw this.checkDevicePromise=null,e})),this.checkDevicePromise}async requestCheckDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(t=!0){let i=localStorage.getItem(e);if(null===i||!t){const{exist:t,push_token_exist:r}=await this.checkDevice();localStorage.setItem(e,t&&r?s:a),i=localStorage.getItem(e)}return i===s}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(e=>{throw this.ensureDeviceRegisteredPromise=null,e})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:e}=await this.checkDevice();if(e)return!1;const t=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t),!0}async reportPushPermissionStatus(e=!1){const s=this.getPushPermissionStatus();if(s&&s!==this.reportingPushPermissionStatus&&s!==localStorage.getItem(t)){this.reportingPushPermissionStatus=s;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!e&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status: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(t)}rememberReportedPushPermissionStatus(e){e&&localStorage.setItem(t,e)}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const t=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...e,push_permission_status:t,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(t),s}async registerDevice(){const e=this.requestRegisterDevice();this.registerDevicePromise=e;try{return await e}finally{this.registerDevicePromise===e&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const t=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({...t,push_permission_status:i,locale:await this.getLocale(),page:ae(),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(e,s),this.eventBus.dispatchEvent("register",{}),r}async unregisterDevice(){const t=await this.getRequestParams(),s=await this.apiClient.unregisterDevice(t);return this.checkDevicePromise=null,localStorage.setItem(e,a),this.eventBus.dispatchEvent("unsubscribe",{}),s}async deleteDevice(){const t=await this.getRequestParams(),s=await this.apiClient.deleteDevice(t);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(e,a),this.eventBus.dispatchEvent("unsubscribe",{}),s}async messageDeliveryEvent(e,t,s={}){const a=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...a,hash:e,metaData:s})}async pushStat(e,t,s={},a){const i=await this.getRequestParams();return await this.apiClient.pushStat({...i,hash:e,metaData:s,...a?{button_id:a}:{}})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getEmail();return i&&await this.apiClient.setEmailTags({...a,email:i,tags:e}),this.apiClient.setTags({...a,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async setLanguage(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:e}))}async setLocale(e){if(!e)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const t=ne(e.trim().replace(/_/g,"-"));t&&(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return ne(await this.data.getLanguage())||void 0}async registerUser(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${e}`,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}),t&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),a=await this.apiClient.registerEmail({...s,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),a}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:a}=await this.getIdentityRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),i}async registerWhatsappNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:a}=await this.getIdentityRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),i}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:e})}async recordPopupFormEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:e,event:t};return this.apiClient.recordPopupFormEvent(3===t?{...s,clickId:r()}:s)}async getWebPlacements(){if(this.getIsCommunicationDisabled())return[];const e=await this.apiClient.getWebPlacements(await this.getRequestParams());return e?.web_placements??[]}async trackWebPlacement(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.trackWebPlacement({...await this.getRequestParams(),hash:e,action:t})}async submitPopupForm(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:e,email:t.email,tags:t.tags,policy_accepted:t.policyAccepted})}async sdkUsage(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams();return this.apiClient.sdkUsage({...s,...e},t)}async postEvent(e,t,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const 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(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const u=await this.apiClient.postEvent({...a,event:e,timestampUTC:n,timestampCurrent:o,attributes:t},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(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),a=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:a})}async inboxStatus(e,t){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:e,status:t,time:(new Date).getTime()})}async multiRegisterDevice(t){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();!t.push_devices&&c.pushToken&&await this.requireHwid();const h={application:a,...t};if(t.user_id){h.user_id=String(t.user_id);await this.data.getUserId()!==h.user_id&&(await this.data.setUserId(h.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(t.email){if(!/^\S+@\S+\.\S+$/.test(t.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==t.email&&(await this.data.setEmail(t.email),await this.data.setStatusEmailWasChanged(!0))}if(t.sms_phone_number){if(!/^\+?[0-9]+$/.test(t.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==t.sms_phone_number&&(await this.data.setSmsNumber(t.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(t.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(t.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==t.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(t.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 e=60*-(new Date).getTimezoneOffset();h.timezone=String(e)}if(!h.push_devices&&c.pushToken){const e={hwid:u,platform:r,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||i){const t={};c.publicKey&&(t.public_key=c.publicKey),c.authToken&&(t.auth_token=c.authToken),i&&(t.browser=i),e.platformData=t}h.push_devices=[e]}const d=await this.apiClient.multiRegisterDevice(h);return h.push_devices?.length&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(e,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 e=await this.requireHwid(),t=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:e,device_type:t}}async getIdentityRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),a=await this.data.getDeviceModel(),i=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!t)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:e,userId:s||t,device_model:a,timezone:n,language:i,v:r}}async requireHwid(){const e=await this.data.getHwid();if(!e)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 e}}(ue,he);he.getLogLevel().then(e=>{e&&I.setLevel(e)});const le=self.Pushwoosh=new class{constructor(e,t,s){this._listeners={},this.eventBus=e,this.data=t,this.api=s}push(e){Array.isArray(e)&&"onPush"===e[0]&&n(e[1])&&(this._listeners[e[0]]||(this._listeners[e[0]]=[]),this._listeners[e[0]].push(e[1]))}getListeners(e){return this._listeners[e]||[]}async initApi(){return Promise.resolve()}}(ue,he,de),ge=[];async function pe(e){(await self.clients.matchAll()).forEach(t=>t.postMessage(e))}async function me(e){const{notification:t={}}=e,{data:s}=t,a=i(t.tag,{});let r,n="";if(e.action&&Array.isArray(s.buttons)){const t=s.buttons.find(t=>t.action===e.action)||{};n=t.url,r=t.id}else n=a.url;return{title:t.title,body:t.body,icon:t.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:t.tag,url:n,buttonId:r}}async function we(e){const t=await le.data.getApplicationCode(),s=await le.data.getServiceWorkerVersion();await N({message:"Error in onInstallEventHandler",code:"FATAL-SW-001",error:e,applicationCode:t,workerVersion:s})}async function ye(e){const t=await le.data.getApplicationCode(),s=await le.data.getServiceWorkerVersion();await N({message:"Error in onActivateEventHandler",code:"FATAL-SW-002",error:e,applicationCode:t,workerVersion:s})}async function be(e){const t=await le.data.getApplicationCode(),s=await le.data.getServiceWorkerVersion();await N({message:"Error in onNotificationClickEventHandler",code:"FATAL-SW-004",error:e,applicationCode:t,workerVersion:s})}async function fe(e){const t=await le.data.getApplicationCode(),s=await le.data.getServiceWorkerVersion();await N({message:"Error in onNotificationCloseEventHandler",code:"FATAL-SW-005",error:e,applicationCode:t,workerVersion:s})}async function ve(e){const t=await le.data.getApplicationCode(),s=await le.data.getServiceWorkerVersion();await N({message:"Error in onPushSubscriptionChange",code:"FATAL-SW-006",error:e,applicationCode:t,workerVersion:s})}return self.addEventListener("install",function(e){return e.waitUntil(async function(){await Promise.all([le.data.setServiceWorkerVersion("3.118.0"),I.write("info","install")]),await self.skipWaiting()}().catch(we))}),self.addEventListener("activate",function(e){e.waitUntil(async function(){await Promise.all([I.write("info","activate")]),await self.clients.claim()}().catch(ye))}),self.addEventListener("push",function(e){e.waitUntil(async function(e){await self.clients.claim();const t=await e.data.json(),s=new se(t),a=await s.getNotificationOptionsPayload(),i=await s.getShowNotificationOptions(),r=s.messageHash;await I.write("info",JSON.stringify(a),"onPush");const n=new ce(i,s.body,await s.getTitle()),o=le.getListeners("onPush");await o.reduce((e,t)=>e.then(()=>t(n)),Promise.resolve());const c=[n.show(),C.add({payload:t,parsedPayload:a,showOptions:i}),pe({type:"onPushDelivery",payload:a})];if(r&&c.push(le.initApi().then(()=>le.api.messageDeliveryEvent(r,!0,a.metaData))),""!==s.inboxId){const e=new Y(le.eventBus,le.data,le.api),t=new z(le.data,le.api,e),a=await s.getInboxMessage(),i=await t.publicMessageBuilder(a);c.push(e.putMessage(a),pe({type:"onPutNewMessageToInboxStore",payload:i}))}await Promise.all(c)}(e).catch(t=>async function(e,t){const s=await le.data.getApplicationCode(),a=await le.data.getServiceWorkerVersion();await N({message:"Error in onPushEventHandler",code:"FATAL-SW-003",error:e,applicationCode:s,workerVersion:a}),e instanceof Error||(e=new Error(e));return C.add({error:`${e}`,stack:e.stack,payload:t.data&&t.data.text()})}(t,e)))}),self.addEventListener("notificationclick",function(e){e.waitUntil(async function(e){await self.clients.claim();const t=await me(e),{messageHash:s,metaData:a,url:i,buttonId:r,code:n,inboxId:o}=t;if(n&&ge.push(n),""!==o){const e=new Y(le.eventBus,le.data,le.api),t=await e.getMessage(o);t.status=3,await e.putMessage(t)}e.notification.close();const c={type:"onNotificationClick",payload:t};return i&&e.waitUntil(self.clients.matchAll({type:"window"}).then(e=>async function(e,t){const{hostname:s,pathname:a}=new URL(t,self.location.origin),i=e.find(e=>{const{hostname:t,pathname:i}=new URL(e.url);return t===s&&i===a});return i?(await i.focus(),!1):(await self.clients.openWindow(t).then(e=>{e&&e.focus()}),!0)}(e,i)).then(e=>{e&&le.data.setDelayedEvent(c)})),Promise.all([le.initApi().then(()=>le.api.pushStat(s,!0,a,r)),le.data.setLastOpenMessage({url:i,messageHash:s,expiry:Date.now()+864e5}),pe(c)])}(e).catch(be))}),self.addEventListener("notificationclose",function(e){e.waitUntil(async function(e){await self.clients.claim();const t=await me(e),{code:s}=t;if(e.notification.close(),!s)return;const a=ge.indexOf(s);if(!(a>=0))return pe({type:"onNotificationClose",payload:t});ge.splice(a,1)}(e).catch(fe))}),self.addEventListener("pushsubscriptionchange",async function(e){e.waitUntil(async function(e){let t=e.newSubscription;if(!t&&(t=await self.registration.pushManager.getSubscription(),!t))return;const s=new oe(de,he,{});await s.subscribe(t)}(e).catch(ve))}),{}})());
2
2
  //# sourceMappingURL=service-worker.js.map
@@ -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 o=e();for(var i in o)("object"==typeof exports?exports:t)[i]=o[i]}}(this,()=>(()=>{"use strict";const t={d:(e,o)=>{for(var i in o)t.o(o,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:o[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{Object.defineProperties(t,{[Symbol.toStringTag]:{value:"Module"},__esModule:{value:!0}})}};let e={};t.r(e),t.d(e,{PWSubscriptionButtonWidget:()=>d});const o="granted",i="default",s="bottomRight",n="bottomLeft",r="topRight",a="topLeft",p={position:n,bgColor:"#12AE7E",bellColor:"white",bellStrokeColor:"#08754f",bellButtonBorder:"1px solid #379676",shadow:"0px 0px 6px rgba(0, 0, 0, 0.75)",size:"48px",indent:"20px",zIndex:"999999",tooltipText:{successSubscribe:"You are successfully subscribed!",needSubscribe:"Get notifications about important news!",blockSubscribe:"Click to see how to get notifications",alreadySubscribed:"You are already subscribed"}};class c{static getBellPosition(t,e){let o;switch(t){case s:o={top:"auto",left:"auto",bottom:e,right:e};break;case n:o={top:"auto",left:e,bottom:e,right:"auto"};break;case a:o={top:e,left:e,bottom:"auto",right:"auto"};break;case r:o={top:e,left:"auto",bottom:"auto",right:e};break;default:o={top:"auto",left:"auto",bottom:e,right:e}}return o}static getTooltipPosition(t,e){let o,i;const r=parseInt(e)+12+"px";switch(t){case s:o={right:r},i="right";break;case n:case a:o={left:r},i="left";break;default:o={right:r},i="right"}return[o,i]}static getPopoverPosition(t,e){let o,i;const p=parseInt(e)+15+"px";switch(t){case s:o={bottom:p,right:"0",left:"auto",top:"auto"},i="bottom";break;case n:o={bottom:p,left:"0",right:"auto",top:"auto"},i="bottom";break;case a:o={top:p,left:"0",right:"auto",bottom:"auto"},i="top";break;case r:o={top:p,right:"0",left:"auto",bottom:"auto"},i="top";break;default:o={bottom:p,right:"0",left:"auto",top:"auto"},i="bottom"}return[o,i]}static getPopoverArrowPosition(t,e){let o;switch(t){case s:o="\n.pushwoosh-subscribe-widget__popover__bottom:after {left: auto; right: "+(parseInt(e)/2-4+"px");break;case n:o="\n.pushwoosh-subscribe-widget__popover__bottom:after {right: auto; left: "+(parseInt(e)/2-12+"px");break;case a:o="\n.pushwoosh-subscribe-widget__popover__top:after {right: auto; left: "+(parseInt(e)/2-12+"px");break;case r:o="\n.pushwoosh-subscribe-widget__popover__top:after {left: auto; right: "+(parseInt(e)/2-4+"px");break;default:o="\n.pushwoosh-subscribe-widget__popover__bottom:after {left: auto; right: "+(parseInt(e)/2-4+"px")}return o}}class d{constructor(t){if(this.pw=t,!t.platformChecker.isAvailableNotifications)return void console.warn("Browser does not support push notifications");this.clickBell=this.clickBell.bind(this),this.onSubscribeEvent=this.onSubscribeEvent.bind(this),this.onUnsubscribeEvent=this.onUnsubscribeEvent.bind(this),this.onPermissionDeniedEvent=this.onPermissionDeniedEvent.bind(this),this.clickOutOfPopover=this.clickOutOfPopover.bind(this);const e=Object.assign(p.tooltipText,t.initParams.subscribeWidget.tooltipText);this.config=Object.assign({},p,t.initParams.subscribeWidget),this.config.tooltipText=e}async run(){if(!this.pw.isPushAvailable())return;await this.pw.isSubscribed()||await this.render()}addStylesToElement(t,e){Object.keys(t).forEach(o=>{e.style[o]=t[o]})}createContainer(){const t=document.createElement("div");t.id="pushwooshBellWidget",t.className="pushwoosh-subscribe-widget";const e=c.getBellPosition(this.config.position,this.config.indent),o=Object.assign({zIndex:this.config.zIndex},e);return this.addStylesToElement(o,t),t}createStyle(){const t=document.createElement("style");return t.innerHTML='/* Widget */\n.pushwoosh-subscribe-widget {\n position: fixed;\n display: block;\n transform: translate3d(0, 0, 0);\n}\n\n.pushwoosh-subscribe-widget__subscribed {\n display: none;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__bell-button {\n border-radius: 50%;\n cursor: pointer;\n font-size: 0;\n text-align: center;\n transform: scale(0.9) translate3d(0, 0, 0);\n transition: transform .3s ease-in-out;\n position: relative;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__bell-button:hover {\n transform: scale(1);\n}\n\n/* Tooltip */\n.pushwoosh-subscribe-widget__tooltip {\n position: absolute;\n height: 48px;\n max-width: 300px;\n min-width: 200px;\n padding: 5px 7px;\n background-color: #3b444b;\n color: #ffffff;\n text-align: center;\n vertical-align: middle;\n box-sizing: border-box;\n line-height: 38px;\n font-size: 0;\n font-weight: normal;\n visibility: hidden;\n opacity: 0;\n transition: visibility 0s ease-in .3s,\n opacity .3s ease-in;\n top: 50%;\n transform: translate(0, -50%);\n box-shadow: 1px 1px 5px 0 rgba(0,0,0,0.5);\n}\n\n.pushwoosh-subscribe-widget__tooltip__right:after,\n.pushwoosh-subscribe-widget__tooltip__left:after {\n content: "";\n top: 50%;\n height: 0;\n width: 0;\n position: absolute;\n pointer-events: none;\n border-top: 5px solid transparent;\n border-bottom: 5px solid transparent;\n background: #3b444b;\n}\n\n.pushwoosh-subscribe-widget__tooltip__right:after {\n left: calc(100% - 7px);\n border-top: 5px solid #3b444b;\n border-left: 5px solid #3b444b;\n border-right: 5px solid transparent;\n box-sizing: border-box;\n transform-origin: 0 0;\n transform: rotate(-45deg);\n box-shadow: 2px 2px 2px 0 rgba(0, 0, 0, 0.25);\n}\n\n.pushwoosh-subscribe-widget__tooltip__left:after {\n left: -7px;\n border-top: 5px solid #3b444b;\n border-right: 5px solid #3b444b;\n border-left: 5px solid transparent;\n box-sizing: border-box;\n transform-origin: 0 0;\n transform: rotate(-45deg);\n box-shadow: -2px -2px 2px 0 rgba(0, 0, 0, 0.25);\n}\n\n.pushwoosh-subscribe-widget__bell-button:hover + .pushwoosh-subscribe-widget__tooltip,\n.pushwoosh-subscribe-widget__tooltip.pushwoosh-subscribe-widget__tooltip__visible {\n display: block;\n visibility: visible;\n opacity: 1;\n transition-delay: 0s;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__tooltip-content {\n display: inline-block;\n vertical-align: middle;\n font-size: 14px;\n line-height: 1.4;\n white-space: nowrap;\n overflow: hidden;\n padding-right: 5px;\n text-overflow: ellipsis;\n max-width: 100%;\n}\n\n/* Popover */\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover {\n position: absolute;\n right: auto;\n box-shadow: 1px 1px 5px 0 rgba(0, 0, 0, 0.5);\n box-sizing: border-box;\n background: #9ca8b1;\n visibility: hidden;\n opacity: 0;\n transition: visibility 0s ease-in .5s,\n opacity .5s ease-in;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover__visible {\n display: block;\n visibility: visible;\n opacity: 1;\n transition-delay: 0s;\n}\n\n.pushwoosh-subscribe-widget__popover__bottom:after,\n.pushwoosh-subscribe-widget__popover__top:after {\n content: "";\n height: 0;\n width: 0;\n position: absolute;\n pointer-events: none;\n border-right: 8px solid transparent;\n border-left: 8px solid #9ca8b1;\n background: #9ca8b1;\n transform-origin: 0 0;\n transform: rotate(-45deg);\n}\n\n.pushwoosh-subscribe-widget__popover__bottom:after {\n border-bottom: 8px solid #9ca8b1;\n border-top: 8px solid transparent;\n box-sizing: border-box;\n box-shadow: -2px 2px 1px 0 rgba(0, 0, 0, 0.25);\n bottom: -16px;\n}\n\n.pushwoosh-subscribe-widget__popover__top:after {\n top: 0;\n border-top: 8px solid #9ca8b1;\n border-bottom: 8px solid transparent;\n box-sizing: border-box;\n box-shadow: 1px -1px 1px 0 rgba(0, 0, 0, 0.25);\n}\n\n.pushwoosh-subscribe-widget__popover-content-wrapper {\n overflow: auto;\n max-width: 100%;\n}\n\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover-content {\n display: flex;\n flex-direction: column;\n padding: 14px;\n box-sizing: border-box;\n float: left;\n min-width: 100%;\n align-items: center;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img {\n display: block;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img:first-child {\n margin-bottom: 14px;\n}\n\n@media (max-width: 767px) and (orientation: portrait) {\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover-content {\n flex-direction: column;\n }\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img {\n max-width: 280px;\n height: auto;\n }\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img:first-child {\n margin-right: 0;\n margin-bottom: 14px;\n }\n}\n@media (max-width: 767px) and (orientation: landscape) {\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover-content {\n flex-direction: row;\n }\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img {\n max-width: 280px;\n height: auto;\n }\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img:first-child {\n margin-right: 14px;\n margin-bottom: 0;\n }\n}\n',t}createBell(){const{config:t}=this;let e;var o,i;return t.buttonImage?(e=document.createElement("img"),e.src=t.buttonImage):(e=document.createElement("div"),this.addStylesToElement({backgroundColor:t.bgColor,boxShadow:t.shadow,lineHeight:t.size,border:t.bellButtonBorder},e),e.innerHTML=(o=t.bellColor,i=t.bellStrokeColor,`<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg\n xmlns:dc="http://purl.org/dc/elements/1.1/"\n xmlns:cc="http://creativecommons.org/ns#"\n xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"\n xmlns:svg="http://www.w3.org/2000/svg"\n xmlns="http://www.w3.org/2000/svg"\n xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"\n xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n version="1.1"\n id="Capa_1"\n x="0px"\n y="0px"\n viewBox="0 0 346.013 346.013"\n style="enable-background:new 0 0 346.013 346.013;width: 80%; height: auto; vertical-align: middle;"\n xml:space="preserve"\n inkscape:version="0.91 r13725"\n sodipodi:docname="alarm_white.svg"><metadata\n id="metadata51"><rdf:RDF><cc:Work\n rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type\n rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs\n id="defs49" /><sodipodi:namedview\n borderopacity="1"\n objecttolerance="10"\n gridtolerance="10"\n guidetolerance="10"\n inkscape:pageopacity="0"\n inkscape:pageshadow="2"\n inkscape:window-width="1618"\n inkscape:window-height="828"\n id="namedview47"\n showgrid="false"\n inkscape:zoom="0.6820553"\n inkscape:cx="173.0065"\n inkscape:cy="173.0065"\n inkscape:window-x="0"\n inkscape:window-y="0"\n inkscape:window-maximized="0"\n inkscape:current-layer="g3" /><g\n id="g3"><path\n d="m 256.76227,220.19006 c -1.77513,-2.69766 -3.45154,-5.24564 -3.98966,-7.46382 -0.042,-0.17861 -0.0911,-0.36128 -0.16237,-0.61436 -2.28354,-7.67647 0.69147,-24.43921 2.46886,-34.45124 0.26788,-1.50394 0.52274,-2.94197 0.75286,-4.29035 0.0232,-0.13675 0.044,-0.27211 0.0724,-0.48006 1.95582,-15.28051 2.58811,-37.91956 -5.51044,-58.99147 -5.6032,-14.57978 -14.45978,-25.82612 -26.3559,-33.48393 1.26598,-9.812938 -4.85967,-19.343691 -14.66682,-22.0511 -9.80715,-2.70741 -19.95724,2.33226 -23.90298,11.405413 -14.1382,0.467533 -27.51111,5.577097 -39.80114,15.219267 -17.76129,13.9298 -28.83431,33.68757 -34.99389,47.80757 l -0.0479,0.11335 c -0.0512,0.12175 -0.0998,0.24114 -0.13249,0.32962 -0.49733,1.28292 -1.01552,2.64514 -1.55689,4.07255 -3.61311,9.51043 -9.66004,25.42824 -15.611995,30.89342 -0.106524,0.10027 -0.208228,0.20187 -0.362362,0.35435 -1.636243,1.66563 -4.382941,2.99463 -7.288979,4.40101 -7.145531,3.45301 -22.013613,10.64166 -17.206389,31.67844 0.929154,4.07105 4.008437,7.29057 8.033861,8.40185 l 167.570804,46.2604 c 4.02253,1.11048 8.31521,-0.0729 11.2052,-3.08958 14.91617,-15.58874 5.84693,-29.38668 1.48625,-36.02133 z"\n id="path5"\n inkscape:connector-curvature="0"\n vector-effect="non-scaling-stroke"\n style="fill:${o}; stroke: ${i}; stroke-width: 1; " /><path\n vector-effect="non-scaling-stroke"\n d="m 174.26737,259.72378 -38.76399,-10.70137 c -1.59243,-0.43962 -3.28183,-0.15596 -4.63548,0.7754 -2.53909,1.7494 -2.84182,4.93159 -3.02304,6.83188 l -0.0151,0.15247 c -1.22819,12.67106 6.79854,24.33046 19.08688,27.72284 12.51583,3.45518 25.8324,-2.91586 30.9681,-14.80385 l 0.0935,-0.19205 c 0.52305,-1.06418 1.74613,-3.55554 0.50882,-6.31116 -0.44302,-0.98439 -1.5794,-2.74529 -4.21964,-3.47416 z"\n id="path7"\n inkscape:connector-curvature="0"\n style="fill:${o}; stroke: ${i}; stroke-width: 1;" /></g><g\n id="g17" /><g\n id="g19" /><g\n id="g21" /><g\n id="g23" /><g\n id="g25" /><g\n id="g27" /><g\n id="g29" /><g\n id="g31" /><g\n id="g33" /><g\n id="g35" /><g\n id="g37" /><g\n id="g39" /><g\n id="g41" /><g\n id="g43" /><g\n id="g45" /></svg>`)),this.addStylesToElement({width:t.size,height:t.size},e),e.className="pushwoosh-subscribe-widget__bell-button",e}async createTooltip(){const t=document.createElement("div"),[e,o]=c.getTooltipPosition(this.config.position,this.config.size);return t.className=`pushwoosh-subscribe-widget__tooltip pushwoosh-subscribe-widget__tooltip__${o}`,this.addStylesToElement(e,t),t.appendChild(await this.createTooltipContent()),t}async createTooltipContent(){const t=document.createElement("div");return t.innerText=await this.tooltipTextFactory(),t.className="pushwoosh-subscribe-widget__tooltip-content",t}async tooltipTextFactory(){const t=this.pw.driver?.getPermission(),{tooltipText:e}=this.config,s=await this.pw.data.getStatusManualUnsubscribed();switch(t){case o:return s?e.needSubscribe:e.alreadySubscribed;case i:return e.needSubscribe;case"denied":return e.blockSubscribe;default:return e.needSubscribe}}createPopover(){const t=document.createElement("div"),e=document.createElement("div"),[o,i]=c.getPopoverPosition(this.config.position,this.config.size);e.className=`pushwoosh-subscribe-widget__popover pushwoosh-subscribe-widget__popover__${i}`,t.className="pushwoosh-subscribe-widget__popover-content-wrapper",this.style.innerHTML+=c.getPopoverArrowPosition(this.config.position,this.config.size);const s=Object.assign({maxWidth:`calc(100vw - ${this.config.indent} - ${this.config.indent})`},o);return this.addStylesToElement(s,e),t.appendChild(this.createPopoverContent()),e.appendChild(t),e}getBrowserName(){const{browser:t}=this.pw.platformChecker;return"opera"===t.name||"firefox"===t.name?t.name:"safari"===t.name?"safari":/Android/i.test(navigator.userAgent)?"mobileChrome":"chrome"}createPopoverContent(){const{config:t}=this,e=document.createElement("div");e.className="pushwoosh-subscribe-widget__popover-content";const o=this.getBrowserName(),i=t.contentImages&&t.contentImages[o];if(i){const t=document.createElement("img");t.src=i,e.appendChild(t)}else{const t={opera:"opera",mobileChrome:"mobile_chrome",firefox:"FF",safari:"safari"}[o]||"chrome";[{src:this.getImageSrc(t),width:500,height:130},{src:this.getImageSrc(`${t}_unlock`),width:500,height:230}].forEach(t=>{const o=document.createElement("img");Object.assign(o,t),e.appendChild(o)})}return e}getImageSrc(t){return`https://cdn.pushwoosh.com/webpush/img/${t}.jpg`}async render(){this.widget=this.createContainer(),this.style=this.createStyle();const t=this.createBell();this.tooltip=await this.createTooltip(),this.popover=await this.createPopover(),this.widget.appendChild(this.style),this.widget.appendChild(t),this.widget.appendChild(this.tooltip),this.widget.appendChild(this.popover),document.body.appendChild(this.widget),this.pw.push(["onSubscribe",this.onSubscribeEvent]),this.pw.push(["onUnsubscribe",this.onUnsubscribeEvent]),this.pw.push(["onPermissionDenied",this.onPermissionDeniedEvent]),this.addEventListeners()}addEventListeners(){this.widget.addEventListener("click",this.clickBell),window.addEventListener("click",this.clickOutOfPopover)}toggleHelpPopover(){this.popover.classList.toggle("pushwoosh-subscribe-widget__popover__visible")}async clickBell(){const t=this.pw.driver?.getPermission();switch(t){case o:case i:await this.pw.subscribe();break;case"denied":this.toggleHelpPopover();break;default:console.warn("Unknown browser notification permission")}}async onSubscribeEvent(){const t=this.tooltip.querySelector("div");null!==t&&(t.innerText=this.config.tooltipText.successSubscribe,this.tooltip.classList.add("pushwoosh-subscribe-widget__tooltip__visible"),setTimeout(async()=>{this.tooltip.classList.remove("pushwoosh-subscribe-widget__tooltip__visible"),t.innerText=await this.tooltipTextFactory(),this.widget.classList.add("pushwoosh-subscribe-widget__subscribed")},2e3))}async onPermissionDeniedEvent(){this.addEventListeners();const t=this.tooltip.querySelector("div");null!==t&&(t.innerText=await this.tooltipTextFactory())}clickOutOfPopover(t){this.popover.classList.contains("pushwoosh-subscribe-widget__popover__visible")&&!t.target.classList.contains("pushwoosh-subscribe-widget__popover")&&null===t.target.closest(".pushwoosh-subscribe-widget__popover")&&!t.target.classList.contains("pushwoosh-subscribe-widget__bell-button")&&null===t.target.closest(".pushwoosh-subscribe-widget__bell-button")&&this.popover.classList.remove("pushwoosh-subscribe-widget__popover__visible")}async onUnsubscribeEvent(){const t=this.tooltip.querySelector("div");null!==t&&(t.innerText=await this.tooltipTextFactory())}}return e})());
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 o=e();for(var i in o)("object"==typeof exports?exports:t)[i]=o[i]}}(this,()=>(()=>{"use strict";const t={d:(e,o)=>{for(var i in o)t.o(o,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:o[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{Object.defineProperties(t,{[Symbol.toStringTag]:{value:"Module"},__esModule:{value:!0}})}};let e={};t.r(e),t.d(e,{PWSubscriptionButtonWidget:()=>d});const o="granted",i="default",s="bottomRight",n="bottomLeft",r="topRight",a="topLeft",p={position:n,bgColor:"#12AE7E",bellColor:"white",bellStrokeColor:"#08754f",bellButtonBorder:"1px solid #379676",shadow:"0px 0px 6px rgba(0, 0, 0, 0.75)",size:"48px",indent:"20px",zIndex:"999999",tooltipText:{successSubscribe:"You are successfully subscribed!",needSubscribe:"Get notifications about important news!",blockSubscribe:"Click to see how to get notifications",alreadySubscribed:"You are already subscribed"}};class c{static getBellPosition(t,e){let o;switch(t){case s:o={top:"auto",left:"auto",bottom:e,right:e};break;case n:o={top:"auto",left:e,bottom:e,right:"auto"};break;case a:o={top:e,left:e,bottom:"auto",right:"auto"};break;case r:o={top:e,left:"auto",bottom:"auto",right:e};break;default:o={top:"auto",left:"auto",bottom:e,right:e}}return o}static getTooltipPosition(t,e){let o,i;const r=parseInt(e)+12+"px";switch(t){case s:o={right:r},i="right";break;case n:case a:o={left:r},i="left";break;default:o={right:r},i="right"}return[o,i]}static getPopoverPosition(t,e){let o,i;const p=parseInt(e)+15+"px";switch(t){case s:o={bottom:p,right:"0",left:"auto",top:"auto"},i="bottom";break;case n:o={bottom:p,left:"0",right:"auto",top:"auto"},i="bottom";break;case a:o={top:p,left:"0",right:"auto",bottom:"auto"},i="top";break;case r:o={top:p,right:"0",left:"auto",bottom:"auto"},i="top";break;default:o={bottom:p,right:"0",left:"auto",top:"auto"},i="bottom"}return[o,i]}static getPopoverArrowPosition(t,e){let o;switch(t){case s:o="\n.pushwoosh-subscribe-widget__popover__bottom:after {left: auto; right: "+(parseInt(e)/2-4+"px");break;case n:o="\n.pushwoosh-subscribe-widget__popover__bottom:after {right: auto; left: "+(parseInt(e)/2-12+"px");break;case a:o="\n.pushwoosh-subscribe-widget__popover__top:after {right: auto; left: "+(parseInt(e)/2-12+"px");break;case r:o="\n.pushwoosh-subscribe-widget__popover__top:after {left: auto; right: "+(parseInt(e)/2-4+"px");break;default:o="\n.pushwoosh-subscribe-widget__popover__bottom:after {left: auto; right: "+(parseInt(e)/2-4+"px")}return o}}class d{constructor(t){if(this.pw=t,!(e=t.environment.capabilities).webPush&&!e.safariLegacy)return void console.warn("Browser does not support push notifications");var e;this.clickBell=this.clickBell.bind(this),this.onSubscribeEvent=this.onSubscribeEvent.bind(this),this.onUnsubscribeEvent=this.onUnsubscribeEvent.bind(this),this.onPermissionDeniedEvent=this.onPermissionDeniedEvent.bind(this),this.clickOutOfPopover=this.clickOutOfPopover.bind(this);const o=Object.assign(p.tooltipText,t.initParams.subscribeWidget.tooltipText);this.config=Object.assign({},p,t.initParams.subscribeWidget),this.config.tooltipText=o}async run(){if(!this.pw.isPushAvailable())return;await this.pw.isSubscribed()||await this.render()}addStylesToElement(t,e){Object.keys(t).forEach(o=>{e.style[o]=t[o]})}createContainer(){const t=document.createElement("div");t.id="pushwooshBellWidget",t.className="pushwoosh-subscribe-widget";const e=c.getBellPosition(this.config.position,this.config.indent),o=Object.assign({zIndex:this.config.zIndex},e);return this.addStylesToElement(o,t),t}createStyle(){const t=document.createElement("style");return t.innerHTML='/* Widget */\n.pushwoosh-subscribe-widget {\n position: fixed;\n display: block;\n transform: translate3d(0, 0, 0);\n}\n\n.pushwoosh-subscribe-widget__subscribed {\n display: none;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__bell-button {\n border-radius: 50%;\n cursor: pointer;\n font-size: 0;\n text-align: center;\n transform: scale(0.9) translate3d(0, 0, 0);\n transition: transform .3s ease-in-out;\n position: relative;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__bell-button:hover {\n transform: scale(1);\n}\n\n/* Tooltip */\n.pushwoosh-subscribe-widget__tooltip {\n position: absolute;\n height: 48px;\n max-width: 300px;\n min-width: 200px;\n padding: 5px 7px;\n background-color: #3b444b;\n color: #ffffff;\n text-align: center;\n vertical-align: middle;\n box-sizing: border-box;\n line-height: 38px;\n font-size: 0;\n font-weight: normal;\n visibility: hidden;\n opacity: 0;\n transition: visibility 0s ease-in .3s,\n opacity .3s ease-in;\n top: 50%;\n transform: translate(0, -50%);\n box-shadow: 1px 1px 5px 0 rgba(0,0,0,0.5);\n}\n\n.pushwoosh-subscribe-widget__tooltip__right:after,\n.pushwoosh-subscribe-widget__tooltip__left:after {\n content: "";\n top: 50%;\n height: 0;\n width: 0;\n position: absolute;\n pointer-events: none;\n border-top: 5px solid transparent;\n border-bottom: 5px solid transparent;\n background: #3b444b;\n}\n\n.pushwoosh-subscribe-widget__tooltip__right:after {\n left: calc(100% - 7px);\n border-top: 5px solid #3b444b;\n border-left: 5px solid #3b444b;\n border-right: 5px solid transparent;\n box-sizing: border-box;\n transform-origin: 0 0;\n transform: rotate(-45deg);\n box-shadow: 2px 2px 2px 0 rgba(0, 0, 0, 0.25);\n}\n\n.pushwoosh-subscribe-widget__tooltip__left:after {\n left: -7px;\n border-top: 5px solid #3b444b;\n border-right: 5px solid #3b444b;\n border-left: 5px solid transparent;\n box-sizing: border-box;\n transform-origin: 0 0;\n transform: rotate(-45deg);\n box-shadow: -2px -2px 2px 0 rgba(0, 0, 0, 0.25);\n}\n\n.pushwoosh-subscribe-widget__bell-button:hover + .pushwoosh-subscribe-widget__tooltip,\n.pushwoosh-subscribe-widget__tooltip.pushwoosh-subscribe-widget__tooltip__visible {\n display: block;\n visibility: visible;\n opacity: 1;\n transition-delay: 0s;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__tooltip-content {\n display: inline-block;\n vertical-align: middle;\n font-size: 14px;\n line-height: 1.4;\n white-space: nowrap;\n overflow: hidden;\n padding-right: 5px;\n text-overflow: ellipsis;\n max-width: 100%;\n}\n\n/* Popover */\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover {\n position: absolute;\n right: auto;\n box-shadow: 1px 1px 5px 0 rgba(0, 0, 0, 0.5);\n box-sizing: border-box;\n background: #9ca8b1;\n visibility: hidden;\n opacity: 0;\n transition: visibility 0s ease-in .5s,\n opacity .5s ease-in;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover__visible {\n display: block;\n visibility: visible;\n opacity: 1;\n transition-delay: 0s;\n}\n\n.pushwoosh-subscribe-widget__popover__bottom:after,\n.pushwoosh-subscribe-widget__popover__top:after {\n content: "";\n height: 0;\n width: 0;\n position: absolute;\n pointer-events: none;\n border-right: 8px solid transparent;\n border-left: 8px solid #9ca8b1;\n background: #9ca8b1;\n transform-origin: 0 0;\n transform: rotate(-45deg);\n}\n\n.pushwoosh-subscribe-widget__popover__bottom:after {\n border-bottom: 8px solid #9ca8b1;\n border-top: 8px solid transparent;\n box-sizing: border-box;\n box-shadow: -2px 2px 1px 0 rgba(0, 0, 0, 0.25);\n bottom: -16px;\n}\n\n.pushwoosh-subscribe-widget__popover__top:after {\n top: 0;\n border-top: 8px solid #9ca8b1;\n border-bottom: 8px solid transparent;\n box-sizing: border-box;\n box-shadow: 1px -1px 1px 0 rgba(0, 0, 0, 0.25);\n}\n\n.pushwoosh-subscribe-widget__popover-content-wrapper {\n overflow: auto;\n max-width: 100%;\n}\n\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover-content {\n display: flex;\n flex-direction: column;\n padding: 14px;\n box-sizing: border-box;\n float: left;\n min-width: 100%;\n align-items: center;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img {\n display: block;\n}\n\n.pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img:first-child {\n margin-bottom: 14px;\n}\n\n@media (max-width: 767px) and (orientation: portrait) {\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover-content {\n flex-direction: column;\n }\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img {\n max-width: 280px;\n height: auto;\n }\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img:first-child {\n margin-right: 0;\n margin-bottom: 14px;\n }\n}\n@media (max-width: 767px) and (orientation: landscape) {\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover-content {\n flex-direction: row;\n }\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img {\n max-width: 280px;\n height: auto;\n }\n .pushwoosh-subscribe-widget .pushwoosh-subscribe-widget__popover img:first-child {\n margin-right: 14px;\n margin-bottom: 0;\n }\n}\n',t}createBell(){const{config:t}=this;let e;var o,i;return t.buttonImage?(e=document.createElement("img"),e.src=t.buttonImage):(e=document.createElement("div"),this.addStylesToElement({backgroundColor:t.bgColor,boxShadow:t.shadow,lineHeight:t.size,border:t.bellButtonBorder},e),e.innerHTML=(o=t.bellColor,i=t.bellStrokeColor,`<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg\n xmlns:dc="http://purl.org/dc/elements/1.1/"\n xmlns:cc="http://creativecommons.org/ns#"\n xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"\n xmlns:svg="http://www.w3.org/2000/svg"\n xmlns="http://www.w3.org/2000/svg"\n xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"\n xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n version="1.1"\n id="Capa_1"\n x="0px"\n y="0px"\n viewBox="0 0 346.013 346.013"\n style="enable-background:new 0 0 346.013 346.013;width: 80%; height: auto; vertical-align: middle;"\n xml:space="preserve"\n inkscape:version="0.91 r13725"\n sodipodi:docname="alarm_white.svg"><metadata\n id="metadata51"><rdf:RDF><cc:Work\n rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type\n rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs\n id="defs49" /><sodipodi:namedview\n borderopacity="1"\n objecttolerance="10"\n gridtolerance="10"\n guidetolerance="10"\n inkscape:pageopacity="0"\n inkscape:pageshadow="2"\n inkscape:window-width="1618"\n inkscape:window-height="828"\n id="namedview47"\n showgrid="false"\n inkscape:zoom="0.6820553"\n inkscape:cx="173.0065"\n inkscape:cy="173.0065"\n inkscape:window-x="0"\n inkscape:window-y="0"\n inkscape:window-maximized="0"\n inkscape:current-layer="g3" /><g\n id="g3"><path\n d="m 256.76227,220.19006 c -1.77513,-2.69766 -3.45154,-5.24564 -3.98966,-7.46382 -0.042,-0.17861 -0.0911,-0.36128 -0.16237,-0.61436 -2.28354,-7.67647 0.69147,-24.43921 2.46886,-34.45124 0.26788,-1.50394 0.52274,-2.94197 0.75286,-4.29035 0.0232,-0.13675 0.044,-0.27211 0.0724,-0.48006 1.95582,-15.28051 2.58811,-37.91956 -5.51044,-58.99147 -5.6032,-14.57978 -14.45978,-25.82612 -26.3559,-33.48393 1.26598,-9.812938 -4.85967,-19.343691 -14.66682,-22.0511 -9.80715,-2.70741 -19.95724,2.33226 -23.90298,11.405413 -14.1382,0.467533 -27.51111,5.577097 -39.80114,15.219267 -17.76129,13.9298 -28.83431,33.68757 -34.99389,47.80757 l -0.0479,0.11335 c -0.0512,0.12175 -0.0998,0.24114 -0.13249,0.32962 -0.49733,1.28292 -1.01552,2.64514 -1.55689,4.07255 -3.61311,9.51043 -9.66004,25.42824 -15.611995,30.89342 -0.106524,0.10027 -0.208228,0.20187 -0.362362,0.35435 -1.636243,1.66563 -4.382941,2.99463 -7.288979,4.40101 -7.145531,3.45301 -22.013613,10.64166 -17.206389,31.67844 0.929154,4.07105 4.008437,7.29057 8.033861,8.40185 l 167.570804,46.2604 c 4.02253,1.11048 8.31521,-0.0729 11.2052,-3.08958 14.91617,-15.58874 5.84693,-29.38668 1.48625,-36.02133 z"\n id="path5"\n inkscape:connector-curvature="0"\n vector-effect="non-scaling-stroke"\n style="fill:${o}; stroke: ${i}; stroke-width: 1; " /><path\n vector-effect="non-scaling-stroke"\n d="m 174.26737,259.72378 -38.76399,-10.70137 c -1.59243,-0.43962 -3.28183,-0.15596 -4.63548,0.7754 -2.53909,1.7494 -2.84182,4.93159 -3.02304,6.83188 l -0.0151,0.15247 c -1.22819,12.67106 6.79854,24.33046 19.08688,27.72284 12.51583,3.45518 25.8324,-2.91586 30.9681,-14.80385 l 0.0935,-0.19205 c 0.52305,-1.06418 1.74613,-3.55554 0.50882,-6.31116 -0.44302,-0.98439 -1.5794,-2.74529 -4.21964,-3.47416 z"\n id="path7"\n inkscape:connector-curvature="0"\n style="fill:${o}; stroke: ${i}; stroke-width: 1;" /></g><g\n id="g17" /><g\n id="g19" /><g\n id="g21" /><g\n id="g23" /><g\n id="g25" /><g\n id="g27" /><g\n id="g29" /><g\n id="g31" /><g\n id="g33" /><g\n id="g35" /><g\n id="g37" /><g\n id="g39" /><g\n id="g41" /><g\n id="g43" /><g\n id="g45" /></svg>`)),this.addStylesToElement({width:t.size,height:t.size},e),e.className="pushwoosh-subscribe-widget__bell-button",e}async createTooltip(){const t=document.createElement("div"),[e,o]=c.getTooltipPosition(this.config.position,this.config.size);return t.className=`pushwoosh-subscribe-widget__tooltip pushwoosh-subscribe-widget__tooltip__${o}`,this.addStylesToElement(e,t),t.appendChild(await this.createTooltipContent()),t}async createTooltipContent(){const t=document.createElement("div");return t.innerText=await this.tooltipTextFactory(),t.className="pushwoosh-subscribe-widget__tooltip-content",t}async tooltipTextFactory(){const t=this.pw.driver?.getPermission(),{tooltipText:e}=this.config,s=await this.pw.data.getStatusManualUnsubscribed();switch(t){case o:return s?e.needSubscribe:e.alreadySubscribed;case i:return e.needSubscribe;case"denied":return e.blockSubscribe;default:return e.needSubscribe}}createPopover(){const t=document.createElement("div"),e=document.createElement("div"),[o,i]=c.getPopoverPosition(this.config.position,this.config.size);e.className=`pushwoosh-subscribe-widget__popover pushwoosh-subscribe-widget__popover__${i}`,t.className="pushwoosh-subscribe-widget__popover-content-wrapper",this.style.innerHTML+=c.getPopoverArrowPosition(this.config.position,this.config.size);const s=Object.assign({maxWidth:`calc(100vw - ${this.config.indent} - ${this.config.indent})`},o);return this.addStylesToElement(s,e),t.appendChild(this.createPopoverContent()),e.appendChild(t),e}getBrowserName(){const{browser:t}=this.pw.environment;return"opera"===t.name||"firefox"===t.name?t.name:"safari"===t.name?"safari":/Android/i.test(navigator.userAgent)?"mobileChrome":"chrome"}createPopoverContent(){const{config:t}=this,e=document.createElement("div");e.className="pushwoosh-subscribe-widget__popover-content";const o=this.getBrowserName(),i=t.contentImages&&t.contentImages[o];if(i){const t=document.createElement("img");t.src=i,e.appendChild(t)}else{const t={opera:"opera",mobileChrome:"mobile_chrome",firefox:"FF",safari:"safari"}[o]||"chrome";[{src:this.getImageSrc(t),width:500,height:130},{src:this.getImageSrc(`${t}_unlock`),width:500,height:230}].forEach(t=>{const o=document.createElement("img");Object.assign(o,t),e.appendChild(o)})}return e}getImageSrc(t){return`https://cdn.pushwoosh.com/webpush/img/${t}.jpg`}async render(){this.widget=this.createContainer(),this.style=this.createStyle();const t=this.createBell();this.tooltip=await this.createTooltip(),this.popover=await this.createPopover(),this.widget.appendChild(this.style),this.widget.appendChild(t),this.widget.appendChild(this.tooltip),this.widget.appendChild(this.popover),document.body.appendChild(this.widget),this.pw.push(["onSubscribe",this.onSubscribeEvent]),this.pw.push(["onUnsubscribe",this.onUnsubscribeEvent]),this.pw.push(["onPermissionDenied",this.onPermissionDeniedEvent]),this.addEventListeners()}addEventListeners(){this.widget.addEventListener("click",this.clickBell),window.addEventListener("click",this.clickOutOfPopover)}toggleHelpPopover(){this.popover.classList.toggle("pushwoosh-subscribe-widget__popover__visible")}async clickBell(){const t=this.pw.driver?.getPermission();switch(t){case o:case i:await this.pw.subscribe();break;case"denied":this.toggleHelpPopover();break;default:console.warn("Unknown browser notification permission")}}async onSubscribeEvent(){const t=this.tooltip.querySelector("div");null!==t&&(t.innerText=this.config.tooltipText.successSubscribe,this.tooltip.classList.add("pushwoosh-subscribe-widget__tooltip__visible"),setTimeout(async()=>{this.tooltip.classList.remove("pushwoosh-subscribe-widget__tooltip__visible"),t.innerText=await this.tooltipTextFactory(),this.widget.classList.add("pushwoosh-subscribe-widget__subscribed")},2e3))}async onPermissionDeniedEvent(){this.addEventListeners();const t=this.tooltip.querySelector("div");null!==t&&(t.innerText=await this.tooltipTextFactory())}clickOutOfPopover(t){this.popover.classList.contains("pushwoosh-subscribe-widget__popover__visible")&&!t.target.classList.contains("pushwoosh-subscribe-widget__popover")&&null===t.target.closest(".pushwoosh-subscribe-widget__popover")&&!t.target.classList.contains("pushwoosh-subscribe-widget__bell-button")&&null===t.target.closest(".pushwoosh-subscribe-widget__bell-button")&&this.popover.classList.remove("pushwoosh-subscribe-widget__popover__visible")}async onUnsubscribeEvent(){const t=this.tooltip.querySelector("div");null!==t&&(t.innerText=await this.tooltipTextFactory())}}return e})());
2
2
  //# sourceMappingURL=widget-subscription-button.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"widget-subscription-button.js","mappings":"CAAA,SAAAA,EAAAC,GACA,oBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,SACA,sBAAAG,QAAAA,OAAAC,IACAD,OAAA,GAAAH,OACA,CACA,IAAAK,EAAAL,IACA,QAAAM,KAAAD,GAAA,iBAAAJ,QAAAA,QAAAF,GAAAO,GAAAD,EAAAC,EACA,CACC,CATD,CASCC,KAAA,uBCRD,MAAAC,EAAA,CCAAA,EAAA,CAAAP,EAAAQ,KACA,QAAAC,KAAAD,EACAD,EAAAG,EAAAF,EAAAC,KAAAF,EAAAG,EAAAV,EAAAS,IACAE,OAAAC,eAAAZ,EAAAS,EAAA,CAAyCI,YAAA,EAAAC,IAAAN,EAAAC,MCJzCF,EAAA,CAAAQ,EAAAC,IAAAL,OAAAM,UAAAC,eAAAC,KAAAJ,EAAAC,GCCAT,EAAAP,IACAW,OAAAS,iBAAApB,EAAA,CAAoC,CAAAqB,OAAAC,aAAA,CAAwBC,MAAA,UAAiBC,WAAA,CAAgBD,OAAA,iECFtF,MAyBME,EAAqB,UACrBC,EAAoB,UCvBpBC,EAA6B,cAC7BC,EAA4B,aAC5BC,EAA0B,WAC1BC,EAAyB,UAKzBC,EA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Q4B,UAAUS,SAAS,kDAC3CD,EAAGE,OAAeV,UAAUS,SAAS,wCACgC,OAAtED,EAAGE,OAAeC,QAAQ,0CACzBH,EAAGE,OAAeV,UAAUS,SAAS,4CACoC,OAA1ED,EAAGE,OAAeC,QAAQ,6CAEjBjK,KAAK0H,QAAQ4B,UAAUO,OAAO,+CAC/C,CAEQ,wBAAM1F,GACZ,MAAM4C,EAAiB/G,KAAK2G,QAAQ8C,cAAc,OAE3B,OAAnB1C,IAIJA,EAAeC,gBAAkBhH,KAAKiH,qBACxC","sources":["webpack://web-push-notifications/webpack/universalModuleDefinition","webpack://web-push-notifications/webpack/bootstrap","webpack://web-push-notifications/webpack/runtime/define property getters","webpack://web-push-notifications/webpack/runtime/hasOwnProperty shorthand","webpack://web-push-notifications/webpack/runtime/make namespace object","webpack://web-push-notifications/./src/core/constants.ts","webpack://web-push-notifications/./src/widgets/SubscriptionButton/constants.ts","webpack://web-push-notifications/./src/widgets/SubscriptionButton/positioning.ts","webpack://web-push-notifications/./src/widgets/SubscriptionButton/index.ts","webpack://web-push-notifications/./src/widgets/SubscriptionButton/bell.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, () => {\nreturn ","// The require scope\nconst __webpack_require__ = {};\n\n","// define getter/value functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop));","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tObject.defineProperties(exports, { [Symbol.toStringTag]: { value: 'Module' }, __esModule: { value: true } });\n};","export const DEFAULT_SERVICE_WORKER_URL = '/pushwoosh-service-worker.js';\nexport const DEFAULT_API_URL = 'https://api.pushwoosh.com/json/1.3/';\n\nexport const PERIOD_SEND_APP_OPEN = 3600000;\nexport const PERIOD_GOAL_EVENT = 86400000;\n\nexport const DEFAULT_NOTIFICATION_TITLE = 'Pushwoosh notification';\nexport const DEFAULT_NOTIFICATION_IMAGE = 'https://cp.pushwoosh.com/img/logo-medium.png';\n\n// Keys\nexport const KEY_SHOW_SUBSCRIBE_WIDGET = 'WIDGET_SHOWED';\nexport const KEY_CLICK_SUBSCRIBE_WIDGET = 'WIDGET_CLICKED';\n\n// Local storage keys\nexport const KEY_DEVICE_REGISTRATION_STATUS: string = 'deviceRegistrationStatus';\nexport const KEY_REPORTED_PUSH_PERMISSION_STATUS: string = 'reportedPushPermissionStatus';\nexport const KEY_SAFARI_PREVIOUS_PERMISSION = 'safariPreviousPermission';\nexport const MANUAL_SET_LOGGER_LEVEL = 'PW_SET_LOGGER_LEVEL';\n\n// Device registration status\nexport const DEVICE_REGISTRATION_STATUS_REGISTERED: string = 'registered';\nexport const DEVICE_REGISTRATION_STATUS_UNREGISTERED: string = 'unregistered';\n\n// Permissions\nexport const PERMISSION_DENIED = 'denied';\nexport const PERMISSION_GRANTED = 'granted';\nexport const PERMISSION_PROMPT = 'default';\n\n// Events\nexport const LEGACY_EVENT_ON_LOAD = 'onLoad';\nexport const LEGACY_EVENT_ON_READY = 'onReady';\nexport const LEGACY_EVENT_ON_SUBSCRIBE = 'onSubscribe';\nexport const LEGACY_EVENT_ON_UNSUBSCRIBE = 'onUnsubscribe';\nexport const LEGACY_EVENT_ON_REGISTER = 'onRegister';\nexport const LEGACY_EVENT_ON_PERMISSION_PROMPT = 'onPermissionPrompt';\nexport const LEGACY_EVENT_ON_PERMISSION_DENIED = 'onPermissionDenied';\nexport const LEGACY_EVENT_ON_PERMISSION_GRANTED = 'onPermissionGranted';\nexport const LEGACY_EVENT_ON_SW_INIT_ERROR = 'onSWInitError';\nexport const LEGACY_EVENT_ON_PUSH_DELIVERY = 'onPushDelivery';\nexport const LEGACY_EVENT_ON_NOTIFICATION_CLICK = 'onNotificationClick';\nexport const LEGACY_EVENT_ON_NOTIFICATION_CLOSE = 'onNotificationClose';\nexport const LEGACY_EVENT_ON_CHANGE_COMMUNICATION_ENABLED = 'onChangeCommunicationEnabled';\nexport const LEGACY_EVENT_ON_PUT_NEW_MESSAGE_TO_INBOX_STORE = 'onPutNewMessageToInboxStore';\nexport const LEGACY_EVENT_ON_UPDATE_INBOX_MESSAGES = 'onUpdateInboxMessages';\nexport const LEGACY_EVENT_ON_SHOW_NOTIFICATION_PERMISSION_DIALOG = 'onShowNotificationPermissionDialog';\nexport const LEGACY_EVENT_ON_HIDE_NOTIFICATION_PERMISSION_DIALOG = 'onHideNotificationPermissionDialog';\n\nexport const LEGACY_EVENT_ON_SHOW_SUBSCRIPTION_WIDGET = 'onShowSubscriptionWidget';\nexport const LEGACY_EVENT_ON_HIDE_SUBSCRIPTION_WIDGET = 'onHideSubscriptionWidget';\n\n// Post Events\nexport const EVENT_SHOW_SUBSCRIBE_BUTTON = 'showSubscribeButton';\nexport const EVENT_CLICK_SUBSCRIBE_BUTTON = 'clickSubscribeButton';\nexport const EVENT_GDPR_CONSENT = 'GDPRConsent';\nexport const EVENT_GDPR_DELETE = 'GDPRDelete';\nexport const EVENT_PW_SITE_OPENED = 'PW_SiteOpened'; // for default events\n\n// Storage that keeps no hwid (in-app webview, private window, insecure context)\n// leaves the device unidentifiable, and the backend rejects such requests.\nexport const HWID_UNAVAILABLE_MESSAGE = 'Pushwoosh: the SDK storage does not keep the hwid in this browser '\n + '(in-app webview, private window or insecure context), so this device cannot be identified. '\n + 'Requests that need an hwid are not sent.';\n\nexport const IDENTITY_UNAVAILABLE_MESSAGE = 'Pushwoosh: neither a userId nor an hwid is available, '\n + 'so there is nothing to register the email, SMS or WhatsApp channel to. '\n + 'Pass a userId in the init params.';\n\n// A rejected application code is a configuration error, not a failure: no\n// request of the SDK can succeed after it, so init stops instead of retrying.\nexport const API_STATUS_CODE_INVALID_APPLICATION = 210;\nexport const FATAL_API_STATUS_CODES: number[] = [API_STATUS_CODE_INVALID_APPLICATION];\n\n// How long an inbox tap waits for a widget bundle before falling back to the message link.\nexport const WIDGET_LOAD_TIMEOUT_MS = 10000;\n\n// A browser subscription can hang; the permission-change report stops waiting for it after this.\nexport const SUBSCRIPTION_WAIT_TIMEOUT_MS: number = 10000;\n","// Bell\nimport { type TBellConfig } from './subscribe_widget.types';\n\nexport const BELL_POSITION_BOTTOM_RIGHT = 'bottomRight';\nexport const BELL_POSITION_BOTTOM_LEFT = 'bottomLeft';\nexport const BELL_POSITION_TOP_RIGHT = 'topRight';\nexport const BELL_POSITION_TOP_LEFT = 'topLeft';\n\n// Common\nexport const WIDGET_CONTAINER_ID = 'pushwooshBellWidget';\n\nexport const SUBSCRIBE_WIDGET_DEFAULT_CONFIG: TBellConfig = {\n position: BELL_POSITION_BOTTOM_LEFT,\n bgColor: '#12AE7E',\n bellColor: 'white',\n bellStrokeColor: '#08754f',\n bellButtonBorder: '1px solid #379676',\n shadow: '0px 0px 6px rgba(0, 0, 0, 0.75)',\n size: '48px',\n indent: '20px',\n zIndex: '999999',\n tooltipText: {\n successSubscribe: 'You are successfully subscribed!',\n needSubscribe: 'Get notifications about important news!',\n blockSubscribe: 'Click to see how to get notifications',\n alreadySubscribed: 'You are already subscribed',\n },\n};\n","import {\n BELL_POSITION_TOP_RIGHT,\n BELL_POSITION_TOP_LEFT,\n BELL_POSITION_BOTTOM_LEFT,\n BELL_POSITION_BOTTOM_RIGHT,\n} from './constants';\nimport { type TBellPosition, type TPositionStyles } from './subscribe_widget.types';\n\nexport default class Positioning {\n public static getBellPosition(position: TBellPosition, indent: string): TPositionStyles {\n let positionStyles: TPositionStyles;\n\n switch (position) {\n case BELL_POSITION_BOTTOM_RIGHT:\n positionStyles = {\n top: 'auto',\n left: 'auto',\n bottom: indent,\n right: indent,\n };\n break;\n case BELL_POSITION_BOTTOM_LEFT:\n positionStyles = {\n top: 'auto',\n left: indent,\n bottom: indent,\n right: 'auto',\n };\n break;\n case BELL_POSITION_TOP_LEFT:\n positionStyles = {\n top: indent,\n left: indent,\n bottom: 'auto',\n right: 'auto',\n };\n break;\n case BELL_POSITION_TOP_RIGHT:\n positionStyles = {\n top: indent,\n left: 'auto',\n bottom: 'auto',\n right: indent,\n };\n break;\n default:\n positionStyles = {\n top: 'auto',\n left: 'auto',\n bottom: indent,\n right: indent,\n };\n }\n\n return positionStyles;\n }\n\n public static getTooltipPosition(bellPosition: TBellPosition, bellSize: string): [{ left: string } | { right: string }, string] {\n let positionStyles;\n let tooltipModification;\n const increaseIndent = (parseInt(bellSize) + 12) + 'px';\n\n switch (bellPosition) {\n case BELL_POSITION_BOTTOM_RIGHT:\n positionStyles = { right: increaseIndent };\n tooltipModification = 'right';\n break;\n case BELL_POSITION_BOTTOM_LEFT:\n positionStyles = { left: increaseIndent };\n tooltipModification = 'left';\n break;\n case BELL_POSITION_TOP_LEFT:\n positionStyles = { left: increaseIndent };\n tooltipModification = 'left';\n break;\n case BELL_POSITION_TOP_RIGHT:\n positionStyles = { right: increaseIndent };\n tooltipModification = 'right';\n break;\n default:\n positionStyles = { right: increaseIndent };\n tooltipModification = 'right';\n }\n\n return [positionStyles, tooltipModification];\n }\n\n public static getPopoverPosition(bellPosition: TBellPosition, bellSize: string): [TPositionStyles, string] {\n let positionStyles;\n let popoverModification;\n const increaseIndent = (parseInt(bellSize) + 15) + 'px';\n\n switch (bellPosition) {\n case BELL_POSITION_BOTTOM_RIGHT:\n positionStyles = {\n bottom: increaseIndent,\n right: '0',\n left: 'auto',\n top: 'auto',\n };\n popoverModification = 'bottom';\n break;\n case BELL_POSITION_BOTTOM_LEFT:\n positionStyles = {\n bottom: increaseIndent,\n left: '0',\n right: 'auto',\n top: 'auto',\n };\n popoverModification = 'bottom';\n break;\n case BELL_POSITION_TOP_LEFT:\n positionStyles = {\n top: increaseIndent,\n left: '0',\n right: 'auto',\n bottom: 'auto',\n };\n popoverModification = 'top';\n break;\n case BELL_POSITION_TOP_RIGHT:\n positionStyles = {\n top: increaseIndent,\n right: '0',\n left: 'auto',\n bottom: 'auto',\n };\n popoverModification = 'top';\n break;\n default:\n positionStyles = {\n bottom: increaseIndent,\n right: '0',\n left: 'auto',\n top: 'auto',\n };\n popoverModification = 'bottom';\n }\n\n return [positionStyles, popoverModification];\n }\n\n public static getPopoverArrowPosition(bellPosition: TBellPosition, bellSize: string) {\n let arrowAdditionalStyles;\n\n switch (bellPosition) {\n case BELL_POSITION_BOTTOM_RIGHT:\n arrowAdditionalStyles = `\\n.pushwoosh-subscribe-widget__popover__bottom:after {left: auto; right: ${(parseInt(bellSize) / 2 - 4) + 'px'}`;\n break;\n case BELL_POSITION_BOTTOM_LEFT:\n arrowAdditionalStyles = `\\n.pushwoosh-subscribe-widget__popover__bottom:after {right: auto; left: ${(parseInt(bellSize) / 2 - 12) + 'px'}`;\n break;\n case BELL_POSITION_TOP_LEFT:\n arrowAdditionalStyles = `\\n.pushwoosh-subscribe-widget__popover__top:after {right: auto; left: ${(parseInt(bellSize) / 2 - 12) + 'px'}`;\n break;\n case BELL_POSITION_TOP_RIGHT:\n arrowAdditionalStyles = `\\n.pushwoosh-subscribe-widget__popover__top:after {left: auto; right: ${(parseInt(bellSize) / 2 - 4) + 'px'}`;\n break;\n default:\n arrowAdditionalStyles = `\\n.pushwoosh-subscribe-widget__popover__bottom:after {left: auto; right: ${(parseInt(bellSize) / 2 - 4) + 'px'}`;\n }\n\n return arrowAdditionalStyles;\n }\n}\n","import {\n PERMISSION_GRANTED,\n PERMISSION_DENIED,\n PERMISSION_PROMPT,\n} from '../../core/constants';\nimport mainCss from './assets/css/main.css';\nimport bellSVG from './bell';\nimport {\n SUBSCRIBE_WIDGET_DEFAULT_CONFIG,\n WIDGET_CONTAINER_ID,\n} from './constants';\nimport Positioning from './positioning';\nimport { type TBellConfig, type TCSSStylesObject, type TStyleKeys } from './subscribe_widget.types';\nimport { type Pushwoosh } from '../../core/Pushwoosh';\n\nexport class PWSubscriptionButtonWidget {\n widget: HTMLElement;\n tooltip: HTMLElement;\n popover: HTMLElement;\n style: HTMLElement;\n pw: Pushwoosh;\n config: TBellConfig;\n\n constructor(pw: Pushwoosh) {\n // Set Pushwoosh object\n this.pw = pw;\n if (!pw.platformChecker.isAvailableNotifications) {\n console.warn('Browser does not support push notifications');\n return;\n }\n\n // Bindings\n this.clickBell = this.clickBell.bind(this);\n this.onSubscribeEvent = this.onSubscribeEvent.bind(this);\n this.onUnsubscribeEvent = this.onUnsubscribeEvent.bind(this);\n this.onPermissionDeniedEvent = this.onPermissionDeniedEvent.bind(this);\n this.clickOutOfPopover = this.clickOutOfPopover.bind(this);\n\n // Config\n const tooltipText = Object.assign(SUBSCRIBE_WIDGET_DEFAULT_CONFIG.tooltipText, pw.initParams.subscribeWidget!.tooltipText);\n this.config = Object.assign({}, SUBSCRIBE_WIDGET_DEFAULT_CONFIG, pw.initParams.subscribeWidget);\n this.config.tooltipText = tooltipText;\n }\n\n public async run() {\n // Nothing to subscribe to when push is unavailable, and the constructor\n // leaves the config unset in that case — so keep this before any render.\n if (!this.pw.isPushAvailable()) {\n return;\n }\n\n const isSubscribed = await this.pw.isSubscribed();\n if (!isSubscribed) {\n await this.render();\n }\n }\n\n /**\n * Apply styles to element\n * @param styles\n * @param {HTMLElement} element\n */\n private addStylesToElement(styles: TCSSStylesObject, element: HTMLElement) {\n Object.keys(styles).forEach((st: TStyleKeys) => {\n element.style[st] = styles[st];\n });\n }\n\n /**\n * Create container element\n * @returns {HTMLElement}\n */\n private createContainer(): HTMLElement {\n const container = document.createElement('div');\n container.id = WIDGET_CONTAINER_ID;\n container.className = 'pushwoosh-subscribe-widget';\n const position = Positioning.getBellPosition(this.config.position, this.config.indent);\n const styles = Object.assign({\n zIndex: this.config.zIndex,\n }, position);\n this.addStylesToElement(styles, container);\n return container;\n }\n\n /**\n * Create styles element\n * @returns {HTMLElement}\n */\n private createStyle(): HTMLElement {\n const styleNode = document.createElement('style');\n styleNode.innerHTML = mainCss;\n return styleNode;\n }\n\n /**\n * Create cell button element\n * @returns {HTMLElement}\n */\n private createBell(): HTMLElement {\n const { config } = this;\n let bell;\n if (config.buttonImage) {\n bell = document.createElement('img') as HTMLImageElement;\n bell.src = config.buttonImage;\n } else {\n bell = document.createElement('div');\n this.addStylesToElement({\n backgroundColor: config.bgColor,\n boxShadow: config.shadow,\n lineHeight: config.size,\n border: config.bellButtonBorder,\n }, bell);\n\n bell.innerHTML = bellSVG(config.bellColor, config.bellStrokeColor);\n }\n this.addStylesToElement({\n width: config.size,\n height: config.size,\n }, bell);\n bell.className = 'pushwoosh-subscribe-widget__bell-button';\n return bell;\n }\n\n /**\n * Create tooltip element\n * @returns {Promise<HTMLElement>}\n */\n private async createTooltip(): Promise<HTMLElement> {\n const tooltip = document.createElement('div');\n const [position, modification] = Positioning.getTooltipPosition(this.config.position, this.config.size);\n tooltip.className = `pushwoosh-subscribe-widget__tooltip pushwoosh-subscribe-widget__tooltip__${modification}`;\n this.addStylesToElement(position, tooltip);\n\n tooltip.appendChild(await this.createTooltipContent());\n return tooltip;\n }\n\n /**\n * Create tooltip content element\n * @returns {Promise<HTMLElement>}\n */\n private async createTooltipContent(): Promise<HTMLElement> {\n const tooltipContent = document.createElement('div');\n tooltipContent.innerText = await this.tooltipTextFactory();\n tooltipContent.className = 'pushwoosh-subscribe-widget__tooltip-content';\n return tooltipContent;\n }\n\n /**\n * Tooltip text content depending of the permissions\n * @returns {Promise<string>}\n */\n private async tooltipTextFactory(): Promise<string> {\n const permission = this.pw.driver?.getPermission();\n const { tooltipText } = this.config;\n const isManuallyUnsubscribed = await this.pw.data.getStatusManualUnsubscribed();\n\n switch (permission) {\n case PERMISSION_GRANTED:\n return isManuallyUnsubscribed ? tooltipText.needSubscribe : tooltipText.alreadySubscribed;\n case PERMISSION_PROMPT:\n return tooltipText.needSubscribe;\n case PERMISSION_DENIED:\n return tooltipText.blockSubscribe;\n default:\n return tooltipText.needSubscribe;\n }\n }\n\n /**\n * Create permission denied popover element\n * @returns {HTMLElement}\n */\n private createPopover(): HTMLElement {\n const popoverContentWrapper = document.createElement('div');\n const popover = document.createElement('div');\n const [position, modification] = Positioning.getPopoverPosition(this.config.position, this.config.size);\n popover.className = `pushwoosh-subscribe-widget__popover pushwoosh-subscribe-widget__popover__${modification}`;\n popoverContentWrapper.className = 'pushwoosh-subscribe-widget__popover-content-wrapper';\n\n this.style.innerHTML += Positioning.getPopoverArrowPosition(this.config.position, this.config.size);\n\n const styles = Object.assign({\n maxWidth: `calc(100vw - ${this.config.indent} - ${this.config.indent})`,\n }, position);\n this.addStylesToElement(styles, popover);\n\n popoverContentWrapper.appendChild(this.createPopoverContent());\n popover.appendChild(popoverContentWrapper);\n return popover;\n }\n\n private getBrowserName(): string {\n const { browser } = this.pw.platformChecker;\n\n if (browser.name === 'opera' || browser.name === 'firefox') {\n return browser.name;\n }\n\n if (browser.name === 'safari') {\n return 'safari';\n }\n\n return /Android/i.test(navigator.userAgent) ? 'mobileChrome' : 'chrome';\n }\n\n /**\n * Create permission denied popover content element\n * @returns {HTMLElement}\n */\n private createPopoverContent(): HTMLElement {\n const { config } = this;\n const popoverContent = document.createElement('div');\n popoverContent.className = 'pushwoosh-subscribe-widget__popover-content';\n\n const browser = this.getBrowserName();\n\n const userImageSrc = config.contentImages && config.contentImages[browser];\n if (userImageSrc) {\n const image = document.createElement('img') as HTMLImageElement;\n image.src = userImageSrc;\n popoverContent.appendChild(image);\n } else {\n const standardImagesMap: Record<string, string> = {\n opera: 'opera',\n mobileChrome: 'mobile_chrome',\n firefox: 'FF',\n safari: 'safari',\n };\n const standardImage = standardImagesMap[browser] || 'chrome';\n [{\n src: this.getImageSrc(standardImage),\n width: 500,\n height: 130,\n }, {\n src: this.getImageSrc(`${standardImage}_unlock`),\n width: 500,\n height: 230,\n }].forEach((imageAttrs) => {\n const image = document.createElement('img');\n Object.assign(image, imageAttrs);\n popoverContent.appendChild(image);\n });\n }\n\n return popoverContent;\n }\n\n /**\n * Return source of help images depending of the browser\n * @returns {string}\n */\n getImageSrc(img: string): string {\n return `https://cdn.pushwoosh.com/webpush/img/${img}.jpg`;\n }\n\n private async render() {\n this.widget = this.createContainer();\n this.style = this.createStyle();\n const bell = this.createBell();\n this.tooltip = await this.createTooltip();\n this.popover = await this.createPopover();\n\n this.widget.appendChild(this.style);\n this.widget.appendChild(bell);\n this.widget.appendChild(this.tooltip);\n this.widget.appendChild(this.popover);\n\n document.body.appendChild(this.widget);\n\n this.pw.push(['onSubscribe', this.onSubscribeEvent]);\n this.pw.push(['onUnsubscribe', this.onUnsubscribeEvent]);\n this.pw.push(['onPermissionDenied', this.onPermissionDeniedEvent]);\n\n this.addEventListeners();\n }\n\n addEventListeners() {\n this.widget.addEventListener('click', this.clickBell);\n window.addEventListener('click', this.clickOutOfPopover);\n }\n\n /**\n * Toggle visibility of popover\n */\n toggleHelpPopover() {\n this.popover.classList.toggle('pushwoosh-subscribe-widget__popover__visible');\n }\n\n /**\n * Click bell button event callback\n * @returns {Promise<void>}\n */\n private async clickBell() {\n const permission = this.pw.driver?.getPermission();\n\n switch (permission) {\n case PERMISSION_GRANTED:\n await this.pw.subscribe();\n\n break;\n case PERMISSION_PROMPT:\n await this.pw.subscribe();\n\n break;\n case PERMISSION_DENIED:\n this.toggleHelpPopover();\n\n break;\n default:\n console.warn('Unknown browser notification permission');\n }\n }\n\n /**\n * On subscribe event callback\n * @returns {Promise<void>}\n */\n private async onSubscribeEvent() {\n const tooltipContent = this.tooltip.querySelector('div');\n\n if (tooltipContent === null) {\n return;\n }\n\n tooltipContent.innerText = this.config.tooltipText.successSubscribe;\n this.tooltip.classList.add('pushwoosh-subscribe-widget__tooltip__visible');\n\n setTimeout(async () => {\n this.tooltip.classList.remove('pushwoosh-subscribe-widget__tooltip__visible');\n tooltipContent.innerText = await this.tooltipTextFactory();\n\n this.widget.classList.add('pushwoosh-subscribe-widget__subscribed');\n }, 2000);\n }\n\n /**\n * On permission denied event\n * @returns {Promise<void>}\n */\n private async onPermissionDeniedEvent(): Promise<void> {\n this.addEventListeners();\n\n const tooltipContent = this.tooltip.querySelector('div');\n if (tooltipContent === null) return;\n tooltipContent.innerText = await this.tooltipTextFactory();\n }\n\n /**\n * Out of popover click event\n * @param {MessageEvent} ev\n */\n clickOutOfPopover(ev: MessageEvent) {\n const closeRule = this.popover.classList.contains('pushwoosh-subscribe-widget__popover__visible')\n && !(ev.target as any).classList.contains('pushwoosh-subscribe-widget__popover')\n && (ev.target as any).closest('.pushwoosh-subscribe-widget__popover') === null\n && !(ev.target as any).classList.contains('pushwoosh-subscribe-widget__bell-button')\n && (ev.target as any).closest('.pushwoosh-subscribe-widget__bell-button') === null;\n\n if (closeRule) this.popover.classList.remove('pushwoosh-subscribe-widget__popover__visible');\n }\n\n private async onUnsubscribeEvent() {\n const tooltipContent = this.tooltip.querySelector('div');\n\n if (tooltipContent === null) {\n return;\n }\n\n tooltipContent.innerText = await this.tooltipTextFactory();\n }\n}\n","export default (fillColor: string, strokeColor: string) => {\n return '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\\n'\n + '<svg\\n'\n + ' xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\\n'\n + ' xmlns:cc=\"http://creativecommons.org/ns#\"\\n'\n + ' xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\\n'\n + ' xmlns:svg=\"http://www.w3.org/2000/svg\"\\n'\n + ' xmlns=\"http://www.w3.org/2000/svg\"\\n'\n + ' xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"\\n'\n + ' xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"\\n'\n + ' version=\"1.1\"\\n'\n + ' id=\"Capa_1\"\\n'\n + ' x=\"0px\"\\n'\n + ' y=\"0px\"\\n'\n + ' viewBox=\"0 0 346.013 346.013\"\\n'\n + ' style=\"enable-background:new 0 0 346.013 346.013;width: 80%; height: auto; vertical-align: middle;\"\\n'\n + ' xml:space=\"preserve\"\\n'\n + ' inkscape:version=\"0.91 r13725\"\\n'\n + ' sodipodi:docname=\"alarm_white.svg\"><metadata\\n'\n + ' id=\"metadata51\"><rdf:RDF><cc:Work\\n'\n + ' rdf:about=\"\"><dc:format>image/svg+xml</dc:format><dc:type\\n'\n + ' rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs\\n'\n + ' id=\"defs49\" /><sodipodi:namedview\\n'\n + ' borderopacity=\"1\"\\n'\n + ' objecttolerance=\"10\"\\n'\n + ' gridtolerance=\"10\"\\n'\n + ' guidetolerance=\"10\"\\n'\n + ' inkscape:pageopacity=\"0\"\\n'\n + ' inkscape:pageshadow=\"2\"\\n'\n + ' inkscape:window-width=\"1618\"\\n'\n + ' inkscape:window-height=\"828\"\\n'\n + ' id=\"namedview47\"\\n'\n + ' showgrid=\"false\"\\n'\n + ' inkscape:zoom=\"0.6820553\"\\n'\n + ' inkscape:cx=\"173.0065\"\\n'\n + ' inkscape:cy=\"173.0065\"\\n'\n + ' inkscape:window-x=\"0\"\\n'\n + ' inkscape:window-y=\"0\"\\n'\n + ' inkscape:window-maximized=\"0\"\\n'\n + ' inkscape:current-layer=\"g3\" /><g\\n'\n + ' id=\"g3\"><path\\n'\n + ' d=\"m 256.76227,220.19006 c -1.77513,-2.69766 -3.45154,-5.24564 -3.98966,-7.46382 -0.042,-0.17861 -0.0911,-0.36128 -0.16237,-0.61436 -2.28354,-7.67647 0.69147,-24.43921 2.46886,-34.45124 0.26788,-1.50394 0.52274,-2.94197 0.75286,-4.29035 0.0232,-0.13675 0.044,-0.27211 0.0724,-0.48006 1.95582,-15.28051 2.58811,-37.91956 -5.51044,-58.99147 -5.6032,-14.57978 -14.45978,-25.82612 -26.3559,-33.48393 1.26598,-9.812938 -4.85967,-19.343691 -14.66682,-22.0511 -9.80715,-2.70741 -19.95724,2.33226 -23.90298,11.405413 -14.1382,0.467533 -27.51111,5.577097 -39.80114,15.219267 -17.76129,13.9298 -28.83431,33.68757 -34.99389,47.80757 l -0.0479,0.11335 c -0.0512,0.12175 -0.0998,0.24114 -0.13249,0.32962 -0.49733,1.28292 -1.01552,2.64514 -1.55689,4.07255 -3.61311,9.51043 -9.66004,25.42824 -15.611995,30.89342 -0.106524,0.10027 -0.208228,0.20187 -0.362362,0.35435 -1.636243,1.66563 -4.382941,2.99463 -7.288979,4.40101 -7.145531,3.45301 -22.013613,10.64166 -17.206389,31.67844 0.929154,4.07105 4.008437,7.29057 8.033861,8.40185 l 167.570804,46.2604 c 4.02253,1.11048 8.31521,-0.0729 11.2052,-3.08958 14.91617,-15.58874 5.84693,-29.38668 1.48625,-36.02133 z\"\\n'\n + ' id=\"path5\"\\n'\n + ' inkscape:connector-curvature=\"0\"\\n'\n + ' vector-effect=\"non-scaling-stroke\"\\n'\n + ` style=\"fill:${fillColor}; stroke: ${strokeColor}; stroke-width: 1; \" /><path\\n`\n + ' vector-effect=\"non-scaling-stroke\"\\n'\n + ' d=\"m 174.26737,259.72378 -38.76399,-10.70137 c -1.59243,-0.43962 -3.28183,-0.15596 -4.63548,0.7754 -2.53909,1.7494 -2.84182,4.93159 -3.02304,6.83188 l -0.0151,0.15247 c -1.22819,12.67106 6.79854,24.33046 19.08688,27.72284 12.51583,3.45518 25.8324,-2.91586 30.9681,-14.80385 l 0.0935,-0.19205 c 0.52305,-1.06418 1.74613,-3.55554 0.50882,-6.31116 -0.44302,-0.98439 -1.5794,-2.74529 -4.21964,-3.47416 z\"\\n'\n + ' id=\"path7\"\\n'\n + ' inkscape:connector-curvature=\"0\"\\n'\n + ` style=\"fill:${fillColor}; stroke: ${strokeColor}; stroke-width: 1;\" /></g><g\\n`\n + ' id=\"g17\" /><g\\n'\n + ' id=\"g19\" /><g\\n'\n + ' id=\"g21\" /><g\\n'\n + ' id=\"g23\" /><g\\n'\n + ' id=\"g25\" /><g\\n'\n + ' id=\"g27\" /><g\\n'\n + ' id=\"g29\" /><g\\n'\n + ' id=\"g31\" /><g\\n'\n + ' id=\"g33\" /><g\\n'\n + ' id=\"g35\" /><g\\n'\n + ' id=\"g37\" /><g\\n'\n + ' id=\"g39\" /><g\\n'\n + ' id=\"g41\" /><g\\n'\n + ' id=\"g43\" /><g\\n'\n + ' id=\"g45\" /></svg>';\n};\n"],"names":["root","factory","exports","module","define","amd","a","i","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","defineProperties","Symbol","toStringTag","value","__esModule","PERMISSION_GRANTED","PERMISSION_PROMPT","BELL_POSITION_BOTTOM_RIGHT","BELL_POSITION_BOTTOM_LEFT","BELL_POSITION_TOP_RIGHT","BELL_POSITION_TOP_LEFT","SUBSCRIBE_WIDGET_DEFAULT_CONFIG","position","bgColor","bellColor","bellStrokeColor","bellButtonBorder","shadow","size","indent","zIndex","tooltipText","successSubscribe","needSubscribe","blockSubscribe","alreadySubscribed","Positioning","getBellPosition","positionStyles","top","left","bottom","right","getTooltipPosition","bellPosition","bellSize","tooltipModification","increaseIndent","parseInt","getPopoverPosition","popoverModification","getPopoverArrowPosition","arrowAdditionalStyles","PWSubscriptionButtonWidget","constructor","pw","platformChecker","isAvailableNotifications","console","warn","clickBell","bind","onSubscribeEvent","onUnsubscribeEvent","onPermissionDeniedEvent","clickOutOfPopover","assign","initParams","subscribeWidget","config","run","isPushAvailable","isSubscribed","render","addStylesToElement","styles","element","keys","forEach","st","style","createContainer","container","document","createElement","id","className","createStyle","styleNode","innerHTML","createBell","bell","fillColor","strokeColor","buttonImage","src","backgroundColor","boxShadow","lineHeight","border","width","height","createTooltip","tooltip","modification","appendChild","createTooltipContent","tooltipContent","innerText","tooltipTextFactory","permission","driver","getPermission","isManuallyUnsubscribed","data","getStatusManualUnsubscribed","createPopover","popoverContentWrapper","popover","maxWidth","createPopoverContent","getBrowserName","browser","name","test","navigator","userAgent","popoverContent","userImageSrc","contentImages","image","standardImage","opera","mobileChrome","firefox","safari","getImageSrc","imageAttrs","img","widget","body","push","addEventListeners","addEventListener","window","toggleHelpPopover","classList","toggle","subscribe","querySelector","add","setTimeout","async","remove","ev","contains","target","closest"],"sourceRoot":""}
1
+ {"version":3,"file":"widget-subscription-button.js","mappings":"CAAA,SAAAA,EAAAC,GACA,oBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,SACA,sBAAAG,QAAAA,OAAAC,IACAD,OAAA,GAAAH,OACA,CACA,IAAAK,EAAAL,IACA,QAAAM,KAAAD,GAAA,iBAAAJ,QAAAA,QAAAF,GAAAO,GAAAD,EAAAC,EACA,CACC,CATD,CASCC,KAAA,uBCRD,MAAAC,EAAA,CCAAA,EAAA,CAAAP,EAAAQ,KACA,QAAAC,KAAAD,EACAD,EAAAG,EAAAF,EAAAC,KAAAF,EAAAG,EAAAV,EAAAS,IACAE,OAAAC,eAAAZ,EAAAS,EAAA,CAAyCI,YAAA,EAAAC,IAAAN,EAAAC,MCJzCF,EAAA,CAAAQ,EAAAC,IAAAL,OAAAM,UAAAC,eAAAC,KAAAJ,EAAAC,GCCAT,EAAAP,IACAW,OAAAS,iBAAApB,EAAA,CAAoC,CAAAqB,OAAAC,aAAA,CAAwBC,MAAA,UAAiBC,WAAA,CAAgBD,OAAA,iECFtF,MAyBME,EAAqB,UACrBC,EAAoB,UCvBpBC,EAA6B,cAC7BC,EAA4B,aAC5BC,EAA0B,WAC1BC,EAAyB,UAKzBC,EAA+C,CAC1DC,SAAUJ,EACVK,QAAS,UACTC,UAAW,QACXC,gBAAiB,UACjBC,iBAAkB,oBAClBC,OAAQ,kCACRC,KAAM,OACNC,OAAQ,OACRC,OAAQ,SACRC,YAAa,CACXC,iBAAkB,mCAClBC,cAAe,0CACfC,eAAgB,wCAChBC,kBAAmB,+BCjBR,MAAMC,EACZ,sBAAOC,CAAgBf,EAAyBO,GACrD,I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CAC/C,CAEQ,wBAAM1F,GACZ,MAAM4C,EAAiBjH,KAAK6G,QAAQ8C,cAAc,OAE3B,OAAnB1C,IAIJA,EAAeC,gBAAkBlH,KAAKmH,qBACxC","sources":["webpack://web-push-notifications/webpack/universalModuleDefinition","webpack://web-push-notifications/webpack/bootstrap","webpack://web-push-notifications/webpack/runtime/define property getters","webpack://web-push-notifications/webpack/runtime/hasOwnProperty shorthand","webpack://web-push-notifications/webpack/runtime/make namespace object","webpack://web-push-notifications/./src/core/constants.ts","webpack://web-push-notifications/./src/widgets/SubscriptionButton/constants.ts","webpack://web-push-notifications/./src/widgets/SubscriptionButton/positioning.ts","webpack://web-push-notifications/./src/widgets/SubscriptionButton/index.ts","webpack://web-push-notifications/./src/modules/PlatformChecker/detectEnvironment.ts","webpack://web-push-notifications/./src/widgets/SubscriptionButton/bell.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, () => {\nreturn ","// The require scope\nconst __webpack_require__ = {};\n\n","// define getter/value functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop));","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tObject.defineProperties(exports, { [Symbol.toStringTag]: { value: 'Module' }, __esModule: { value: true } });\n};","export const DEFAULT_SERVICE_WORKER_URL = '/pushwoosh-service-worker.js';\nexport const DEFAULT_API_URL = 'https://api.pushwoosh.com/json/1.3/';\n\nexport const PERIOD_SEND_APP_OPEN = 3600000;\nexport const PERIOD_GOAL_EVENT = 86400000;\n\nexport const DEFAULT_NOTIFICATION_TITLE = 'Pushwoosh notification';\nexport const DEFAULT_NOTIFICATION_IMAGE = 'https://cp.pushwoosh.com/img/logo-medium.png';\n\n// Keys\nexport const KEY_SHOW_SUBSCRIBE_WIDGET = 'WIDGET_SHOWED';\nexport const KEY_CLICK_SUBSCRIBE_WIDGET = 'WIDGET_CLICKED';\n\n// Local storage keys\nexport const KEY_DEVICE_REGISTRATION_STATUS: string = 'deviceRegistrationStatus';\nexport const KEY_REPORTED_PUSH_PERMISSION_STATUS: string = 'reportedPushPermissionStatus';\nexport const KEY_SAFARI_PREVIOUS_PERMISSION = 'safariPreviousPermission';\nexport const MANUAL_SET_LOGGER_LEVEL = 'PW_SET_LOGGER_LEVEL';\n\n// Device registration status\nexport const DEVICE_REGISTRATION_STATUS_REGISTERED: string = 'registered';\nexport const DEVICE_REGISTRATION_STATUS_UNREGISTERED: string = 'unregistered';\n\n// Permissions\nexport const PERMISSION_DENIED = 'denied';\nexport const PERMISSION_GRANTED = 'granted';\nexport const PERMISSION_PROMPT = 'default';\n\n// Events\nexport const LEGACY_EVENT_ON_LOAD = 'onLoad';\nexport const LEGACY_EVENT_ON_READY = 'onReady';\nexport const LEGACY_EVENT_ON_SUBSCRIBE = 'onSubscribe';\nexport const LEGACY_EVENT_ON_UNSUBSCRIBE = 'onUnsubscribe';\nexport const LEGACY_EVENT_ON_REGISTER = 'onRegister';\nexport const LEGACY_EVENT_ON_PERMISSION_PROMPT = 'onPermissionPrompt';\nexport const LEGACY_EVENT_ON_PERMISSION_DENIED = 'onPermissionDenied';\nexport const LEGACY_EVENT_ON_PERMISSION_GRANTED = 'onPermissionGranted';\nexport const LEGACY_EVENT_ON_SW_INIT_ERROR = 'onSWInitError';\nexport const LEGACY_EVENT_ON_PUSH_DELIVERY = 'onPushDelivery';\nexport const LEGACY_EVENT_ON_NOTIFICATION_CLICK = 'onNotificationClick';\nexport const LEGACY_EVENT_ON_NOTIFICATION_CLOSE = 'onNotificationClose';\nexport const LEGACY_EVENT_ON_CHANGE_COMMUNICATION_ENABLED = 'onChangeCommunicationEnabled';\nexport const LEGACY_EVENT_ON_PUT_NEW_MESSAGE_TO_INBOX_STORE = 'onPutNewMessageToInboxStore';\nexport const LEGACY_EVENT_ON_UPDATE_INBOX_MESSAGES = 'onUpdateInboxMessages';\nexport const LEGACY_EVENT_ON_SHOW_NOTIFICATION_PERMISSION_DIALOG = 'onShowNotificationPermissionDialog';\nexport const LEGACY_EVENT_ON_HIDE_NOTIFICATION_PERMISSION_DIALOG = 'onHideNotificationPermissionDialog';\n\nexport const LEGACY_EVENT_ON_SHOW_SUBSCRIPTION_WIDGET = 'onShowSubscriptionWidget';\nexport const LEGACY_EVENT_ON_HIDE_SUBSCRIPTION_WIDGET = 'onHideSubscriptionWidget';\n\n// Post Events\nexport const EVENT_SHOW_SUBSCRIBE_BUTTON = 'showSubscribeButton';\nexport const EVENT_CLICK_SUBSCRIBE_BUTTON = 'clickSubscribeButton';\nexport const EVENT_GDPR_CONSENT = 'GDPRConsent';\nexport const EVENT_GDPR_DELETE = 'GDPRDelete';\nexport const EVENT_PW_SITE_OPENED = 'PW_SiteOpened'; // for default events\n\n// Storage that keeps no hwid (in-app webview, private window, insecure context)\n// leaves the device unidentifiable, and the backend rejects such requests.\nexport const HWID_UNAVAILABLE_MESSAGE = 'Pushwoosh: the SDK storage does not keep the hwid in this browser '\n + '(in-app webview, private window or insecure context), so this device cannot be identified. '\n + 'Requests that need an hwid are not sent.';\n\nexport const IDENTITY_UNAVAILABLE_MESSAGE = 'Pushwoosh: neither a userId nor an hwid is available, '\n + 'so there is nothing to register the email, SMS or WhatsApp channel to. '\n + 'Pass a userId in the init params.';\n\n// A rejected application code is a configuration error, not a failure: no\n// request of the SDK can succeed after it, so init stops instead of retrying.\nexport const API_STATUS_CODE_INVALID_APPLICATION = 210;\nexport const FATAL_API_STATUS_CODES: number[] = [API_STATUS_CODE_INVALID_APPLICATION];\n\n// How long an inbox tap waits for a widget bundle before falling back to the message link.\nexport const WIDGET_LOAD_TIMEOUT_MS = 10000;\n\n// A browser subscription can hang; the permission-change report stops waiting for it after this.\nexport const SUBSCRIPTION_WAIT_TIMEOUT_MS: number = 10000;\n","// Bell\nimport { type TBellConfig } from './subscribe_widget.types';\n\nexport const BELL_POSITION_BOTTOM_RIGHT = 'bottomRight';\nexport const BELL_POSITION_BOTTOM_LEFT = 'bottomLeft';\nexport const BELL_POSITION_TOP_RIGHT = 'topRight';\nexport const BELL_POSITION_TOP_LEFT = 'topLeft';\n\n// Common\nexport const WIDGET_CONTAINER_ID = 'pushwooshBellWidget';\n\nexport const SUBSCRIBE_WIDGET_DEFAULT_CONFIG: TBellConfig = {\n position: BELL_POSITION_BOTTOM_LEFT,\n bgColor: '#12AE7E',\n bellColor: 'white',\n bellStrokeColor: '#08754f',\n bellButtonBorder: '1px solid #379676',\n shadow: '0px 0px 6px rgba(0, 0, 0, 0.75)',\n size: '48px',\n indent: '20px',\n zIndex: '999999',\n tooltipText: {\n successSubscribe: 'You are successfully subscribed!',\n needSubscribe: 'Get notifications about important news!',\n blockSubscribe: 'Click to see how to get notifications',\n alreadySubscribed: 'You are already subscribed',\n },\n};\n","import {\n BELL_POSITION_TOP_RIGHT,\n BELL_POSITION_TOP_LEFT,\n BELL_POSITION_BOTTOM_LEFT,\n BELL_POSITION_BOTTOM_RIGHT,\n} from './constants';\nimport { type TBellPosition, type TPositionStyles } from './subscribe_widget.types';\n\nexport default class Positioning {\n public static getBellPosition(position: TBellPosition, indent: string): TPositionStyles {\n let positionStyles: TPositionStyles;\n\n switch (position) {\n case BELL_POSITION_BOTTOM_RIGHT:\n positionStyles = {\n top: 'auto',\n left: 'auto',\n bottom: indent,\n right: indent,\n };\n break;\n case BELL_POSITION_BOTTOM_LEFT:\n positionStyles = {\n top: 'auto',\n left: indent,\n bottom: indent,\n right: 'auto',\n };\n break;\n case BELL_POSITION_TOP_LEFT:\n positionStyles = {\n top: indent,\n left: indent,\n bottom: 'auto',\n right: 'auto',\n };\n break;\n case BELL_POSITION_TOP_RIGHT:\n positionStyles = {\n top: indent,\n left: 'auto',\n bottom: 'auto',\n right: indent,\n };\n break;\n default:\n positionStyles = {\n top: 'auto',\n left: 'auto',\n bottom: indent,\n right: indent,\n };\n }\n\n return positionStyles;\n }\n\n public static getTooltipPosition(bellPosition: TBellPosition, bellSize: string): [{ left: string } | { right: string }, string] {\n let positionStyles;\n let tooltipModification;\n const increaseIndent = (parseInt(bellSize) + 12) + 'px';\n\n switch (bellPosition) {\n case BELL_POSITION_BOTTOM_RIGHT:\n positionStyles = { right: increaseIndent };\n tooltipModification = 'right';\n break;\n case BELL_POSITION_BOTTOM_LEFT:\n positionStyles = { left: increaseIndent };\n tooltipModification = 'left';\n break;\n case BELL_POSITION_TOP_LEFT:\n positionStyles = { left: increaseIndent };\n tooltipModification = 'left';\n break;\n case BELL_POSITION_TOP_RIGHT:\n positionStyles = { right: increaseIndent };\n tooltipModification = 'right';\n break;\n default:\n positionStyles = { right: increaseIndent };\n tooltipModification = 'right';\n }\n\n return [positionStyles, tooltipModification];\n }\n\n public static getPopoverPosition(bellPosition: TBellPosition, bellSize: string): [TPositionStyles, string] {\n let positionStyles;\n let popoverModification;\n const increaseIndent = (parseInt(bellSize) + 15) + 'px';\n\n switch (bellPosition) {\n case BELL_POSITION_BOTTOM_RIGHT:\n positionStyles = {\n bottom: increaseIndent,\n right: '0',\n left: 'auto',\n top: 'auto',\n };\n popoverModification = 'bottom';\n break;\n case BELL_POSITION_BOTTOM_LEFT:\n positionStyles = {\n bottom: increaseIndent,\n left: '0',\n right: 'auto',\n top: 'auto',\n };\n popoverModification = 'bottom';\n break;\n case BELL_POSITION_TOP_LEFT:\n positionStyles = {\n top: increaseIndent,\n left: '0',\n right: 'auto',\n bottom: 'auto',\n };\n popoverModification = 'top';\n break;\n case BELL_POSITION_TOP_RIGHT:\n positionStyles = {\n top: increaseIndent,\n right: '0',\n left: 'auto',\n bottom: 'auto',\n };\n popoverModification = 'top';\n break;\n default:\n positionStyles = {\n bottom: increaseIndent,\n right: '0',\n left: 'auto',\n top: 'auto',\n };\n popoverModification = 'bottom';\n }\n\n return [positionStyles, popoverModification];\n }\n\n public static getPopoverArrowPosition(bellPosition: TBellPosition, bellSize: string) {\n let arrowAdditionalStyles;\n\n switch (bellPosition) {\n case BELL_POSITION_BOTTOM_RIGHT:\n arrowAdditionalStyles = `\\n.pushwoosh-subscribe-widget__popover__bottom:after {left: auto; right: ${(parseInt(bellSize) / 2 - 4) + 'px'}`;\n break;\n case BELL_POSITION_BOTTOM_LEFT:\n arrowAdditionalStyles = `\\n.pushwoosh-subscribe-widget__popover__bottom:after {right: auto; left: ${(parseInt(bellSize) / 2 - 12) + 'px'}`;\n break;\n case BELL_POSITION_TOP_LEFT:\n arrowAdditionalStyles = `\\n.pushwoosh-subscribe-widget__popover__top:after {right: auto; left: ${(parseInt(bellSize) / 2 - 12) + 'px'}`;\n break;\n case BELL_POSITION_TOP_RIGHT:\n arrowAdditionalStyles = `\\n.pushwoosh-subscribe-widget__popover__top:after {left: auto; right: ${(parseInt(bellSize) / 2 - 4) + 'px'}`;\n break;\n default:\n arrowAdditionalStyles = `\\n.pushwoosh-subscribe-widget__popover__bottom:after {left: auto; right: ${(parseInt(bellSize) / 2 - 4) + 'px'}`;\n }\n\n return arrowAdditionalStyles;\n }\n}\n","import {\n PERMISSION_GRANTED,\n PERMISSION_DENIED,\n PERMISSION_PROMPT,\n} from '../../core/constants';\nimport mainCss from './assets/css/main.css';\nimport bellSVG from './bell';\nimport {\n SUBSCRIBE_WIDGET_DEFAULT_CONFIG,\n WIDGET_CONTAINER_ID,\n} from './constants';\nimport Positioning from './positioning';\nimport { type TBellConfig, type TCSSStylesObject, type TStyleKeys } from './subscribe_widget.types';\nimport { type Pushwoosh } from '../../core/Pushwoosh';\nimport { canReceivePush } from '../../modules/PlatformChecker';\n\nexport class PWSubscriptionButtonWidget {\n widget: HTMLElement;\n tooltip: HTMLElement;\n popover: HTMLElement;\n style: HTMLElement;\n pw: Pushwoosh;\n config: TBellConfig;\n\n constructor(pw: Pushwoosh) {\n // Set Pushwoosh object\n this.pw = pw;\n if (!canReceivePush(pw.environment.capabilities)) {\n console.warn('Browser does not support push notifications');\n return;\n }\n\n // Bindings\n this.clickBell = this.clickBell.bind(this);\n this.onSubscribeEvent = this.onSubscribeEvent.bind(this);\n this.onUnsubscribeEvent = this.onUnsubscribeEvent.bind(this);\n this.onPermissionDeniedEvent = this.onPermissionDeniedEvent.bind(this);\n this.clickOutOfPopover = this.clickOutOfPopover.bind(this);\n\n // Config\n const tooltipText = Object.assign(SUBSCRIBE_WIDGET_DEFAULT_CONFIG.tooltipText, pw.initParams.subscribeWidget!.tooltipText);\n this.config = Object.assign({}, SUBSCRIBE_WIDGET_DEFAULT_CONFIG, pw.initParams.subscribeWidget);\n this.config.tooltipText = tooltipText;\n }\n\n public async run() {\n // Nothing to subscribe to when push is unavailable, and the constructor\n // leaves the config unset in that case — so keep this before any render.\n if (!this.pw.isPushAvailable()) {\n return;\n }\n\n const isSubscribed = await this.pw.isSubscribed();\n if (!isSubscribed) {\n await this.render();\n }\n }\n\n /**\n * Apply styles to element\n * @param styles\n * @param {HTMLElement} element\n */\n private addStylesToElement(styles: TCSSStylesObject, element: HTMLElement) {\n Object.keys(styles).forEach((st: TStyleKeys) => {\n element.style[st] = styles[st];\n });\n }\n\n /**\n * Create container element\n * @returns {HTMLElement}\n */\n private createContainer(): HTMLElement {\n const container = document.createElement('div');\n container.id = WIDGET_CONTAINER_ID;\n container.className = 'pushwoosh-subscribe-widget';\n const position = Positioning.getBellPosition(this.config.position, this.config.indent);\n const styles = Object.assign({\n zIndex: this.config.zIndex,\n }, position);\n this.addStylesToElement(styles, container);\n return container;\n }\n\n /**\n * Create styles element\n * @returns {HTMLElement}\n */\n private createStyle(): HTMLElement {\n const styleNode = document.createElement('style');\n styleNode.innerHTML = mainCss;\n return styleNode;\n }\n\n /**\n * Create cell button element\n * @returns {HTMLElement}\n */\n private createBell(): HTMLElement {\n const { config } = this;\n let bell;\n if (config.buttonImage) {\n bell = document.createElement('img') as HTMLImageElement;\n bell.src = config.buttonImage;\n } else {\n bell = document.createElement('div');\n this.addStylesToElement({\n backgroundColor: config.bgColor,\n boxShadow: config.shadow,\n lineHeight: config.size,\n border: config.bellButtonBorder,\n }, bell);\n\n bell.innerHTML = bellSVG(config.bellColor, config.bellStrokeColor);\n }\n this.addStylesToElement({\n width: config.size,\n height: config.size,\n }, bell);\n bell.className = 'pushwoosh-subscribe-widget__bell-button';\n return bell;\n }\n\n /**\n * Create tooltip element\n * @returns {Promise<HTMLElement>}\n */\n private async createTooltip(): Promise<HTMLElement> {\n const tooltip = document.createElement('div');\n const [position, modification] = Positioning.getTooltipPosition(this.config.position, this.config.size);\n tooltip.className = `pushwoosh-subscribe-widget__tooltip pushwoosh-subscribe-widget__tooltip__${modification}`;\n this.addStylesToElement(position, tooltip);\n\n tooltip.appendChild(await this.createTooltipContent());\n return tooltip;\n }\n\n /**\n * Create tooltip content element\n * @returns {Promise<HTMLElement>}\n */\n private async createTooltipContent(): Promise<HTMLElement> {\n const tooltipContent = document.createElement('div');\n tooltipContent.innerText = await this.tooltipTextFactory();\n tooltipContent.className = 'pushwoosh-subscribe-widget__tooltip-content';\n return tooltipContent;\n }\n\n /**\n * Tooltip text content depending of the permissions\n * @returns {Promise<string>}\n */\n private async tooltipTextFactory(): Promise<string> {\n const permission = this.pw.driver?.getPermission();\n const { tooltipText } = this.config;\n const isManuallyUnsubscribed = await this.pw.data.getStatusManualUnsubscribed();\n\n switch (permission) {\n case PERMISSION_GRANTED:\n return isManuallyUnsubscribed ? tooltipText.needSubscribe : tooltipText.alreadySubscribed;\n case PERMISSION_PROMPT:\n return tooltipText.needSubscribe;\n case PERMISSION_DENIED:\n return tooltipText.blockSubscribe;\n default:\n return tooltipText.needSubscribe;\n }\n }\n\n /**\n * Create permission denied popover element\n * @returns {HTMLElement}\n */\n private createPopover(): HTMLElement {\n const popoverContentWrapper = document.createElement('div');\n const popover = document.createElement('div');\n const [position, modification] = Positioning.getPopoverPosition(this.config.position, this.config.size);\n popover.className = `pushwoosh-subscribe-widget__popover pushwoosh-subscribe-widget__popover__${modification}`;\n popoverContentWrapper.className = 'pushwoosh-subscribe-widget__popover-content-wrapper';\n\n this.style.innerHTML += Positioning.getPopoverArrowPosition(this.config.position, this.config.size);\n\n const styles = Object.assign({\n maxWidth: `calc(100vw - ${this.config.indent} - ${this.config.indent})`,\n }, position);\n this.addStylesToElement(styles, popover);\n\n popoverContentWrapper.appendChild(this.createPopoverContent());\n popover.appendChild(popoverContentWrapper);\n return popover;\n }\n\n private getBrowserName(): string {\n const { browser } = this.pw.environment;\n\n if (browser.name === 'opera' || browser.name === 'firefox') {\n return browser.name;\n }\n\n if (browser.name === 'safari') {\n return 'safari';\n }\n\n return /Android/i.test(navigator.userAgent) ? 'mobileChrome' : 'chrome';\n }\n\n /**\n * Create permission denied popover content element\n * @returns {HTMLElement}\n */\n private createPopoverContent(): HTMLElement {\n const { config } = this;\n const popoverContent = document.createElement('div');\n popoverContent.className = 'pushwoosh-subscribe-widget__popover-content';\n\n const browser = this.getBrowserName();\n\n const userImageSrc = config.contentImages && config.contentImages[browser];\n if (userImageSrc) {\n const image = document.createElement('img') as HTMLImageElement;\n image.src = userImageSrc;\n popoverContent.appendChild(image);\n } else {\n const standardImagesMap: Record<string, string> = {\n opera: 'opera',\n mobileChrome: 'mobile_chrome',\n firefox: 'FF',\n safari: 'safari',\n };\n const standardImage = standardImagesMap[browser] || 'chrome';\n [{\n src: this.getImageSrc(standardImage),\n width: 500,\n height: 130,\n }, {\n src: this.getImageSrc(`${standardImage}_unlock`),\n width: 500,\n height: 230,\n }].forEach((imageAttrs) => {\n const image = document.createElement('img');\n Object.assign(image, imageAttrs);\n popoverContent.appendChild(image);\n });\n }\n\n return popoverContent;\n }\n\n /**\n * Return source of help images depending of the browser\n * @returns {string}\n */\n getImageSrc(img: string): string {\n return `https://cdn.pushwoosh.com/webpush/img/${img}.jpg`;\n }\n\n private async render() {\n this.widget = this.createContainer();\n this.style = this.createStyle();\n const bell = this.createBell();\n this.tooltip = await this.createTooltip();\n this.popover = await this.createPopover();\n\n this.widget.appendChild(this.style);\n this.widget.appendChild(bell);\n this.widget.appendChild(this.tooltip);\n this.widget.appendChild(this.popover);\n\n document.body.appendChild(this.widget);\n\n this.pw.push(['onSubscribe', this.onSubscribeEvent]);\n this.pw.push(['onUnsubscribe', this.onUnsubscribeEvent]);\n this.pw.push(['onPermissionDenied', this.onPermissionDeniedEvent]);\n\n this.addEventListeners();\n }\n\n addEventListeners() {\n this.widget.addEventListener('click', this.clickBell);\n window.addEventListener('click', this.clickOutOfPopover);\n }\n\n /**\n * Toggle visibility of popover\n */\n toggleHelpPopover() {\n this.popover.classList.toggle('pushwoosh-subscribe-widget__popover__visible');\n }\n\n /**\n * Click bell button event callback\n * @returns {Promise<void>}\n */\n private async clickBell() {\n const permission = this.pw.driver?.getPermission();\n\n switch (permission) {\n case PERMISSION_GRANTED:\n await this.pw.subscribe();\n\n break;\n case PERMISSION_PROMPT:\n await this.pw.subscribe();\n\n break;\n case PERMISSION_DENIED:\n this.toggleHelpPopover();\n\n break;\n default:\n console.warn('Unknown browser notification permission');\n }\n }\n\n /**\n * On subscribe event callback\n * @returns {Promise<void>}\n */\n private async onSubscribeEvent() {\n const tooltipContent = this.tooltip.querySelector('div');\n\n if (tooltipContent === null) {\n return;\n }\n\n tooltipContent.innerText = this.config.tooltipText.successSubscribe;\n this.tooltip.classList.add('pushwoosh-subscribe-widget__tooltip__visible');\n\n setTimeout(async () => {\n this.tooltip.classList.remove('pushwoosh-subscribe-widget__tooltip__visible');\n tooltipContent.innerText = await this.tooltipTextFactory();\n\n this.widget.classList.add('pushwoosh-subscribe-widget__subscribed');\n }, 2000);\n }\n\n /**\n * On permission denied event\n * @returns {Promise<void>}\n */\n private async onPermissionDeniedEvent(): Promise<void> {\n this.addEventListeners();\n\n const tooltipContent = this.tooltip.querySelector('div');\n if (tooltipContent === null) return;\n tooltipContent.innerText = await this.tooltipTextFactory();\n }\n\n /**\n * Out of popover click event\n * @param {MessageEvent} ev\n */\n clickOutOfPopover(ev: MessageEvent) {\n const closeRule = this.popover.classList.contains('pushwoosh-subscribe-widget__popover__visible')\n && !(ev.target as any).classList.contains('pushwoosh-subscribe-widget__popover')\n && (ev.target as any).closest('.pushwoosh-subscribe-widget__popover') === null\n && !(ev.target as any).classList.contains('pushwoosh-subscribe-widget__bell-button')\n && (ev.target as any).closest('.pushwoosh-subscribe-widget__bell-button') === null;\n\n if (closeRule) this.popover.classList.remove('pushwoosh-subscribe-widget__popover__visible');\n }\n\n private async onUnsubscribeEvent() {\n const tooltipContent = this.tooltip.querySelector('div');\n\n if (tooltipContent === null) {\n return;\n }\n\n tooltipContent.innerText = await this.tooltipTextFactory();\n }\n}\n","import { detectBrowser } from './detectBrowser';\nimport { getFormFactor } from './getFormFactor';\nimport { getPushCapabilities } from './getPushCapabilities';\nimport { type IEnvironment, type IPushCapabilities } from './PlatformChecker.types';\n\nexport function detectEnvironment(global: typeof globalThis): IEnvironment {\n return {\n browser: detectBrowser(global.navigator),\n capabilities: getPushCapabilities(global),\n formFactor: getFormFactor(global.navigator),\n };\n}\n\nexport function canReceivePush(capabilities: IPushCapabilities): boolean {\n return capabilities.webPush || capabilities.safariLegacy;\n}\n","export default (fillColor: string, strokeColor: string) => {\n return '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\\n'\n + '<svg\\n'\n + ' xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\\n'\n + ' xmlns:cc=\"http://creativecommons.org/ns#\"\\n'\n + ' xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\\n'\n + ' xmlns:svg=\"http://www.w3.org/2000/svg\"\\n'\n + ' xmlns=\"http://www.w3.org/2000/svg\"\\n'\n + ' xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"\\n'\n + ' xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"\\n'\n + ' version=\"1.1\"\\n'\n + ' id=\"Capa_1\"\\n'\n + ' x=\"0px\"\\n'\n + ' y=\"0px\"\\n'\n + ' viewBox=\"0 0 346.013 346.013\"\\n'\n + ' style=\"enable-background:new 0 0 346.013 346.013;width: 80%; height: auto; vertical-align: middle;\"\\n'\n + ' xml:space=\"preserve\"\\n'\n + ' inkscape:version=\"0.91 r13725\"\\n'\n + ' sodipodi:docname=\"alarm_white.svg\"><metadata\\n'\n + ' id=\"metadata51\"><rdf:RDF><cc:Work\\n'\n + ' rdf:about=\"\"><dc:format>image/svg+xml</dc:format><dc:type\\n'\n + ' rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs\\n'\n + ' id=\"defs49\" /><sodipodi:namedview\\n'\n + ' borderopacity=\"1\"\\n'\n + ' objecttolerance=\"10\"\\n'\n + ' gridtolerance=\"10\"\\n'\n + ' guidetolerance=\"10\"\\n'\n + ' inkscape:pageopacity=\"0\"\\n'\n + ' inkscape:pageshadow=\"2\"\\n'\n + ' inkscape:window-width=\"1618\"\\n'\n + ' inkscape:window-height=\"828\"\\n'\n + ' id=\"namedview47\"\\n'\n + ' showgrid=\"false\"\\n'\n + ' inkscape:zoom=\"0.6820553\"\\n'\n + ' inkscape:cx=\"173.0065\"\\n'\n + ' inkscape:cy=\"173.0065\"\\n'\n + ' inkscape:window-x=\"0\"\\n'\n + ' inkscape:window-y=\"0\"\\n'\n + ' inkscape:window-maximized=\"0\"\\n'\n + ' inkscape:current-layer=\"g3\" /><g\\n'\n + ' id=\"g3\"><path\\n'\n + ' d=\"m 256.76227,220.19006 c -1.77513,-2.69766 -3.45154,-5.24564 -3.98966,-7.46382 -0.042,-0.17861 -0.0911,-0.36128 -0.16237,-0.61436 -2.28354,-7.67647 0.69147,-24.43921 2.46886,-34.45124 0.26788,-1.50394 0.52274,-2.94197 0.75286,-4.29035 0.0232,-0.13675 0.044,-0.27211 0.0724,-0.48006 1.95582,-15.28051 2.58811,-37.91956 -5.51044,-58.99147 -5.6032,-14.57978 -14.45978,-25.82612 -26.3559,-33.48393 1.26598,-9.812938 -4.85967,-19.343691 -14.66682,-22.0511 -9.80715,-2.70741 -19.95724,2.33226 -23.90298,11.405413 -14.1382,0.467533 -27.51111,5.577097 -39.80114,15.219267 -17.76129,13.9298 -28.83431,33.68757 -34.99389,47.80757 l -0.0479,0.11335 c -0.0512,0.12175 -0.0998,0.24114 -0.13249,0.32962 -0.49733,1.28292 -1.01552,2.64514 -1.55689,4.07255 -3.61311,9.51043 -9.66004,25.42824 -15.611995,30.89342 -0.106524,0.10027 -0.208228,0.20187 -0.362362,0.35435 -1.636243,1.66563 -4.382941,2.99463 -7.288979,4.40101 -7.145531,3.45301 -22.013613,10.64166 -17.206389,31.67844 0.929154,4.07105 4.008437,7.29057 8.033861,8.40185 l 167.570804,46.2604 c 4.02253,1.11048 8.31521,-0.0729 11.2052,-3.08958 14.91617,-15.58874 5.84693,-29.38668 1.48625,-36.02133 z\"\\n'\n + ' id=\"path5\"\\n'\n + ' inkscape:connector-curvature=\"0\"\\n'\n + ' vector-effect=\"non-scaling-stroke\"\\n'\n + ` style=\"fill:${fillColor}; stroke: ${strokeColor}; stroke-width: 1; \" /><path\\n`\n + ' vector-effect=\"non-scaling-stroke\"\\n'\n + ' d=\"m 174.26737,259.72378 -38.76399,-10.70137 c -1.59243,-0.43962 -3.28183,-0.15596 -4.63548,0.7754 -2.53909,1.7494 -2.84182,4.93159 -3.02304,6.83188 l -0.0151,0.15247 c -1.22819,12.67106 6.79854,24.33046 19.08688,27.72284 12.51583,3.45518 25.8324,-2.91586 30.9681,-14.80385 l 0.0935,-0.19205 c 0.52305,-1.06418 1.74613,-3.55554 0.50882,-6.31116 -0.44302,-0.98439 -1.5794,-2.74529 -4.21964,-3.47416 z\"\\n'\n + ' id=\"path7\"\\n'\n + ' inkscape:connector-curvature=\"0\"\\n'\n + ` style=\"fill:${fillColor}; stroke: ${strokeColor}; stroke-width: 1;\" /></g><g\\n`\n + ' id=\"g17\" /><g\\n'\n + ' id=\"g19\" /><g\\n'\n + ' id=\"g21\" /><g\\n'\n + ' id=\"g23\" /><g\\n'\n + ' id=\"g25\" /><g\\n'\n + ' id=\"g27\" /><g\\n'\n + ' id=\"g29\" /><g\\n'\n + ' id=\"g31\" /><g\\n'\n + ' id=\"g33\" /><g\\n'\n + ' id=\"g35\" /><g\\n'\n + ' id=\"g37\" /><g\\n'\n + ' id=\"g39\" /><g\\n'\n + ' id=\"g41\" /><g\\n'\n + ' id=\"g43\" /><g\\n'\n + ' id=\"g45\" /></svg>';\n};\n"],"names":["root","factory","exports","module","define","amd","a","i","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","defineProperties","Symbol","toStringTag","value","__esModule","PERMISSION_GRANTED","PERMISSION_PROMPT","BELL_POSITION_BOTTOM_RIGHT","BELL_POSITION_BOTTOM_LEFT","BELL_POSITION_TOP_RIGHT","BELL_POSITION_TOP_LEFT","SUBSCRIBE_WIDGET_DEFAULT_CONFIG","position","bgColor","bellColor","bellStrokeColor","bellButtonBorder","shadow","size","indent","zIndex","tooltipText","successSubscribe","needSubscribe","blockSubscribe","alreadySubscribed","Positioning","getBellPosition","positionStyles","top","left","bottom","right","getTooltipPosition","bellPosition","bellSize","tooltipModification","increaseIndent","parseInt","getPopoverPosition","popoverModification","getPopoverArrowPosition","arrowAdditionalStyles","PWSubscriptionButtonWidget","constructor","pw","capabilities","environment","webPush","safariLegacy","console","warn","clickBell","bind","onSubscribeEvent","onUnsubscribeEvent","onPermissionDeniedEvent","clickOutOfPopover","assign","initParams","subscribeWidget","config","run","isPushAvailable","isSubscribed","render","addStylesToElement","styles","element","keys","forEach","st","style","createContainer","container","document","createElement","id","className","createStyle","styleNode","innerHTML","createBell","bell","fillColor","strokeColor","buttonImage","src","backgroundColor","boxShadow","lineHeight","border","width","height","createTooltip","tooltip","modification","appendChild","createTooltipContent","tooltipContent","innerText","tooltipTextFactory","permission","driver","getPermission","isManuallyUnsubscribed","data","getStatusManualUnsubscribed","createPopover","popoverContentWrapper","popover","maxWidth","createPopoverContent","getBrowserName","browser","name","test","navigator","userAgent","popoverContent","userImageSrc","contentImages","image","standardImage","opera","mobileChrome","firefox","safari","getImageSrc","imageAttrs","img","widget","body","push","addEventListeners","addEventListener","window","toggleHelpPopover","classList","toggle","subscribe","querySelector","add","setTimeout","async","remove","ev","contains","target","closest"],"sourceRoot":""}