web-push-notifications 3.110.0 → 3.115.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/core/Pushwoosh.d.ts +3 -0
- package/core/Pushwoosh.types.d.ts +1 -0
- package/core/elementPickerRequest.d.ts +8 -0
- package/models/NotificationPayload.types.d.ts +1 -0
- package/models/__tests__/NotificationPayload.buttons.test.d.ts +1 -0
- package/modules/Api/Api.d.ts +1 -1
- package/modules/ApiClient/ApiClient.types.d.ts +2 -0
- package/npm.js +1 -1
- package/npm.js.map +1 -1
- package/package.json +1 -1
- package/service-worker.js +1 -1
- package/service-worker.js.map +1 -1
- package/widget-inbox.js +1 -1
- package/widget-inbox.js.map +1 -1
- package/widget-recommendations.js +1 -1
- package/widget-recommendations.js.map +1 -1
- package/widget-subscribe-popup.js +1 -1
- package/widget-subscribe-popup.js.map +1 -1
- package/widget-subscription-button.js +1 -1
- package/widget-subscription-button.js.map +1 -1
- package/widget-subscription-prompt.js +1 -1
- package/widget-subscription-prompt.js.map +1 -1
- package/widget-subscription.js +1 -1
- package/widget-subscription.js.map +1 -1
- package/widget-web-popups.js +1 -1
- package/widget-web-popups.js.map +1 -1
- package/widgets/ElementPicker/ElementPicker.d.ts +48 -0
- package/widgets/ElementPicker/__tests__/elementPicker.test.d.ts +1 -0
- package/widgets/ElementPicker/__tests__/selector.test.d.ts +1 -0
- package/widgets/ElementPicker/selector.d.ts +16 -0
- package/widgets/WebPopups/WebPopupsWidget.d.ts +10 -2
- package/widgets/WebPopups/__tests__/clickTrigger.test.d.ts +1 -0
- package/widgets/WebPopups/__tests__/exitIntentTrigger.test.d.ts +1 -0
- package/widgets/WebPopups/clickTrigger.d.ts +5 -0
- package/widgets/WebPopups/exitIntent.d.ts +6 -0
- package/widgets/WebPopups/types.d.ts +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,71 @@ the same mapping is in the
|
|
|
9
9
|
Entries for 3.71.0 through 3.78.0 are grouped under version headings, which is how this file was
|
|
10
10
|
kept before the version moved to the tag; earlier versions live only in the git history.
|
|
11
11
|
|
|
12
|
+
## feat(push): report which action button of a web push was tapped
|
|
13
|
+
|
|
14
|
+
- A notification button that carries `id` in the payload now uses it as its action instead of `action-N`, and a tap on
|
|
15
|
+
it sends `button_id` with `pushStat`, so the server counts taps per button. A button without `id` keeps the `action-N`
|
|
16
|
+
action by its position and sends no `button_id`.
|
|
17
|
+
- The `onNotificationClick` payload gets `buttonId`, the id of the tapped button; it is absent for a tap on the
|
|
18
|
+
notification body or on a button without `id`.
|
|
19
|
+
|
|
20
|
+
## feat(api): send the subscription page path with registerDevice
|
|
21
|
+
|
|
22
|
+
- `registerDevice` with a push token now carries `page`, the decoded path of the current page (no domain, query or
|
|
23
|
+
hash), the same value `PW_SiteOpened` reports. The server stores it in the `Push Subscription Page` system tag next
|
|
24
|
+
to `Push Subscription Date`. The tokenless `registerDevice` does not send it.
|
|
25
|
+
|
|
26
|
+
## fix(web-popups): start the element picker without waiting for the SDK init
|
|
27
|
+
|
|
28
|
+
- On a page opened by the Control Panel's "Select element" the CDN loader now fetches the picker bundle right after
|
|
29
|
+
reading the init command, and the picker starts at once. It used to wait for `ready`, so a browser where the SDK init
|
|
30
|
+
stalls or fails (a stuck registration, a blocked API) never answered the panel, which reported "No answer from your
|
|
31
|
+
site". The application code in the picker messages is read when each message is sent.
|
|
32
|
+
|
|
33
|
+
## feat(web-popups): pick a site element for a popup campaign with the mouse
|
|
34
|
+
|
|
35
|
+
- The Control Panel's "Select element" opens the site with `#pw-picker=<nonce>` (`:embedded` for an inline campaign). The
|
|
36
|
+
CDN loader then loads only the new `pushwoosh-widget-element-picker.js` bundle and no other widget, removes the marker
|
|
37
|
+
from the URL and keeps the request in `sessionStorage`, so the marketer can walk the site to the page with the element.
|
|
38
|
+
- The picker outlines the element under the cursor and blocks the page's clicks, links and forms. A click picks the
|
|
39
|
+
element and shows its selector and how many elements it matches; "Parent" (or ↑) widens it, "All similar elements"
|
|
40
|
+
switches to a class shared with its look-alikes, Esc goes back or cancels. The selector prefers a stable id, then
|
|
41
|
+
test and label attributes, a link target, non-generated classes, and only then a `>` path with `:nth-of-type`; an
|
|
42
|
+
inline campaign gets one simple compound selector or none.
|
|
43
|
+
- "Use this selector" posts `{source: 'pushwoosh-element-picker', type, nonce, applicationCode, selector}` to the
|
|
44
|
+
opener and closes the tab; without an opener (the site sets `Cross-Origin-Opener-Policy`) the selector is copied by
|
|
45
|
+
hand. The npm build does not run the picker.
|
|
46
|
+
|
|
47
|
+
## feat(web-popups): open a popup on a click on a site element
|
|
48
|
+
|
|
49
|
+
- A campaign with the `CLICK` trigger opens on every click (a tap on a phone) on an element its `css_selector` matches,
|
|
50
|
+
or inside one; the selector may be a list (`#promo, .gift`). Elements rendered after the page load, in modals or
|
|
51
|
+
after SPA navigation count too: one capture listener on the document checks each click. The click's default action
|
|
52
|
+
is cancelled, so a link does not navigate away from under the popup; the site's own click handlers still run.
|
|
53
|
+
- It goes through the same page rules, device type, visitor type, push permission status and countdown as the other
|
|
54
|
+
triggers, but its `delay` and `frequency` are not read: the visitor asked for it. It never waits or queues, so it is
|
|
55
|
+
absent from `getState()`'s `waiting` and `queued`, and a click while any popup is on screen opens nothing. VISIT is
|
|
56
|
+
recorded with the first opening on a page. `autoShow: false` turns it off like the other automatic triggers.
|
|
57
|
+
- SDK versions before this one never open a `CLICK` campaign by themselves; `show()` works in all.
|
|
58
|
+
|
|
59
|
+
## ci(github): fill GitHub release notes from CHANGELOG.md
|
|
60
|
+
|
|
61
|
+
- A GitHub release now carries the `CHANGELOG.md` sections added since the previous tag with the same suffix; with
|
|
62
|
+
none, the titles of the merged MRs. The body used to be the GitLab tag message, and release tags have none.
|
|
63
|
+
|
|
64
|
+
## feat(web-popups): show a popup when the visitor is about to leave
|
|
65
|
+
|
|
66
|
+
- A campaign with the `EXIT_INTENT` trigger shows by itself on the first sign the visitor is leaving the page. On a
|
|
67
|
+
desktop: the cursor leaves the window through its top edge. On a phone: the visitor comes back from another tab or
|
|
68
|
+
app, flicks the page quickly back to its first screen with a finger (a "back to top" button does not count), or
|
|
69
|
+
presses Back in the browser or on the device — the first Back shows the popup, the next one leaves. The Back guard
|
|
70
|
+
is a history entry for the same URL with the page's own state, pushed on the first tap or key press, as browsers
|
|
71
|
+
skip entries pushed without a gesture; it is taken off again when the popup fires another way or stops waiting, and
|
|
72
|
+
a Back that could show nothing goes on back.
|
|
73
|
+
- It goes through the same conditions, VISIT and queue as `PAGE_LOAD`, but its `delay` is not read. Until then it is
|
|
74
|
+
`waiting` in `getState()`; leaving for a page the campaign does not match, `show()` and `hideAll()` drop its
|
|
75
|
+
listeners. SDK versions before this one never show an `EXIT_INTENT` campaign by themselves; `show()` works in all.
|
|
76
|
+
|
|
12
77
|
## feat(web-popups): show a popup once the page is scrolled to its depth (DEV-1054)
|
|
13
78
|
|
|
14
79
|
- A campaign with the `SCROLL` trigger shows by itself once the middle of the screen reaches `scroll_depth` percent of
|
package/core/Pushwoosh.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ElementPickerRequest } from './elementPickerRequest';
|
|
1
2
|
import { type EventHandlerMap, type EventName } from './events.types';
|
|
2
3
|
import { type IInitParams, type IModuleRegistry, type PWInput } from './Pushwoosh.types';
|
|
3
4
|
import { Api } from '../modules/Api/Api';
|
|
@@ -38,6 +39,8 @@ export declare class Pushwoosh {
|
|
|
38
39
|
/** Onsite product recommendations: headless `fetch` and `trackClick`, the widget renders through them. */
|
|
39
40
|
readonly recommendations: Recommendations;
|
|
40
41
|
widgetLoader?: (widgetName: string) => Promise<boolean>;
|
|
42
|
+
/** Set by the CDN loader when the page was opened by the Control Panel's "Select element". */
|
|
43
|
+
elementPickerRequest?: ElementPickerRequest;
|
|
41
44
|
constructor();
|
|
42
45
|
/** Placements a postEvent response carried before the web popups widget took over delivery. */
|
|
43
46
|
private pendingWebPlacements;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type ElementPickerMode = 'click' | 'embedded';
|
|
2
|
+
export type ElementPickerRequest = {
|
|
3
|
+
nonce: string;
|
|
4
|
+
mode: ElementPickerMode;
|
|
5
|
+
};
|
|
6
|
+
/** The pending element picker request of this tab: from the URL on the first page, then from sessionStorage. */
|
|
7
|
+
export declare function takeElementPickerRequest(win?: Window): ElementPickerRequest | null;
|
|
8
|
+
export declare function endElementPickerRequest(win?: Window): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/modules/Api/Api.d.ts
CHANGED
|
@@ -39,7 +39,7 @@ export declare class Api {
|
|
|
39
39
|
}): Promise<IMapResponse['messageDeliveryEvent']>;
|
|
40
40
|
pushStat(hash: string, isTrackingLogOnFailure?: boolean, metaData?: {
|
|
41
41
|
[key: string]: any;
|
|
42
|
-
}): Promise<IMapResponse['pushStat']>;
|
|
42
|
+
}, buttonId?: string): Promise<IMapResponse['pushStat']>;
|
|
43
43
|
setTags(tags: {
|
|
44
44
|
[key: string]: any;
|
|
45
45
|
}): Promise<IMapResponse['setTags']>;
|
|
@@ -73,6 +73,7 @@ interface IRequestApplicationOpen extends IRequest {
|
|
|
73
73
|
interface IRequestRegisterDevice extends IRequest {
|
|
74
74
|
push_permission_status?: TPushPermissionStatus;
|
|
75
75
|
locale?: string;
|
|
76
|
+
page?: string;
|
|
76
77
|
push_token?: string;
|
|
77
78
|
public_key?: string;
|
|
78
79
|
auth_token?: string;
|
|
@@ -119,6 +120,7 @@ interface IRequestPushStat extends IRequest {
|
|
|
119
120
|
metaData: {
|
|
120
121
|
[key: string]: any;
|
|
121
122
|
};
|
|
123
|
+
button_id?: string;
|
|
122
124
|
}
|
|
123
125
|
interface IRequestSetTags extends IRequest {
|
|
124
126
|
tags: {
|
package/npm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var i in s)("object"==typeof exports?exports:e)[i]=s[i]}}(this,()=>(()=>{"use strict";const e={d:(t,s)=>{for(var i in s)e.o(s,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:s[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}};let t={};e.r(t),e.d(t,{Pushwoosh:()=>Je});const s="/pushwoosh-service-worker.js",i="https://api.pushwoosh.com/json/1.3/",a="deviceRegistrationStatus",r="reportedPushPermissionStatus",n="registered",o="unregistered",c="granted",h="default",u="onReady",d="onSubscribe",l="onUnsubscribe",g="onRegister",p="onPermissionPrompt",m="onPermissionDenied",w="onPermissionGranted",b="onSWInitError",f="onPushDelivery",y="onNotificationClick",v="onNotificationClose",P="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",C="onUpdateInboxMessages",k="onShowNotificationPermissionDialog",I="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",E="onHideSubscriptionWidget",W="PW_SiteOpened",_="Pushwoosh: the SDK storage does not keep the hwid in this browser (in-app webview, private window or insecure context), so this device cannot be identified. Requests that need an hwid are not sent.",x=[210],T={autoSubscribe:!0,serviceWorkerUrl:s};function A(){return globalThis}function R(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const M=e=>"function"==typeof e;function N(e){const t=new WeakSet;return async s=>{if(t.has(s))return!1;const i=await function(e,t){let s;const i=new Promise(e=>{s=setTimeout(()=>e(!1),t)}),a=e.then(()=>!0,()=>!0);return Promise.race([a,i]).finally(()=>clearTimeout(s))}(s,e);return i||t.add(s),i}}const L={[g]:{name:"register"},[d]:{name:"subscribe"},[l]:{name:"unsubscribe"},[b]:{name:"initialize-service-worker-error",prop:"error"},[f]:{name:"receive-push",prop:"notification"},[y]:{name:"open-notification",prop:"notification"},[v]:{name:"hide-notification",prop:"notification"},[P]:{name:"change-enabled-communication",prop:"isEnabled"},[S]:{name:"receive-inbox-message",prop:"message"},[C]:{name:"update-inbox-messages",prop:"messages"},[k]:{name:"show-notification-permission-dialog"},[I]:{name:"hide-notification-permission-dialog",prop:"permission"},[D]:{name:"show-subscription-widget"},[E]:{name:"hide-subscription-widget"},[m]:{name:"permission-denied"},[p]:{name:"permission-default"},[w]:{name:"permission-granted"}},F="keyValue",U="messages",O="inboxMessages";function q(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const B=[q(F,function(e){e.createObjectStore(F,{keyPath:"key"})}),q("log",function(e){const t=e.createObjectStore("log",{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),q(U,function(e){e.createObjectStore(U,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),q(O,function(e){const t="status",s=e.createObjectStore(O,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class j{get all(){return B}}class V{constructor(e,t=new j){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function $(e,t){console.info("onversionchange",t),e.close()}let H;function K(){return H||(H=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=$.bind(null,i,t),e(i)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=$.bind(null,s,t);new V(s).applyMigrations()}})),H}function z(e){return K().then(t=>new Promise((s,i)=>e(t,s,i)))}class G{_add(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);a.onsuccess=()=>{s(e)},a.onerror=()=>{i(a.error)}}).then(e=>this.getAll().then(t=>{if(Array.isArray(t)){const s=t.map(e=>e.id).sort((e,t)=>e==t?0:e<t?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(e=>this.delete(e))).then(()=>e)}return e}))}delete(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);a.onsuccess=()=>{s(a.result)},a.onerror=()=>{i(a.error)}})}getAll(){return z((e,t,s)=>{const i=[],a=e.transaction(this.name).objectStore(this.name).openCursor();a.onsuccess=e=>{const s=e.target.result;s?(s.value&&i.push(s.value),s.continue()):t(i)},a.onerror=()=>{s(a.error)}})}}const J=(Y=F,{get:(e,t)=>z((s,i,a)=>{const r=s.transaction(Y).objectStore(Y).get(e);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(r.result?.value||t):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}),getAll:()=>z((e,t,s)=>{const i={},a=e.transaction(Y).objectStore(Y).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(i):o?s(a.error):r=setTimeout(c,0)};a.onsuccess=e=>{const t=e.target.result;t?(i[t.key]=t.value.value,t.continue()):n=!0},a.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...i}=t;await this.set(e,{...s,...i})},set:(e,t)=>z((s,i,a)=>{const r=s.transaction([Y],"readwrite").objectStore(Y).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(e):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})});var Y;const X=new class extends G{constructor(){super(...arguments),this.name="log",this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const i={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(i.stack=t.stack),s&&(i.additional=s),this._add(i)}},Q=new class extends G{constructor(){super(...arguments),this.name=U,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Z={error:1,info:2,debug:3};let ee=3;const te={setLevel(e){Z[e]||(e="error"),ee=Z[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),X.add(e,t,s)}};Object.keys(Z).forEach(e=>{const t=Z[e];te[e]=(...s)=>{t<=ee&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class se{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter(e=>e!==t))},this.dispatchEvent=(e,t)=>{const s=t.eventId||R(),i=this.handlers[e];return i?(i.forEach(e=>{M(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}const ie=["autoSubscribe","defaultNotificationTitle","defaultNotificationImage","safariWebsitePushID","unifiedPlatform","subscriptionWidget"];function ae(e,t){if(t)return{...e,...t}}const re=[...Object.keys({applicationCode:!0,apiToken:!0,communicationEnabled:!0,serviceWorkerUrl:!0,safariWebsitePushID:!0,autoSubscribe:!0,pushNotifications:!0,pushwooshUrl:!0,defaultNotificationImage:!0,defaultNotificationTitle:!0,logLevel:!0,userId:!0,email:!0,smsNumber:!0,whatsAppNumber:!0,scope:!0,tags:!0,subscribeWidget:!0,inboxWidget:!0,subscribePopup:!0,subscriptionWidget:!0,webPopups:!0,webPlacements:!0,recommendations:!0,webSDKPath:!0,unifiedPlatform:!0}),"pushwooshApiUrl"],ne=["subscribeWidget","subscribePopup","inboxWidget","webPopups","webPlacements"],oe=e=>{const t=e.toLowerCase();let s,i=3;return re.forEach(e=>{const a=((e,t)=>{let s=Array.from({length:t.length+1},(e,t)=>t);for(let i=1;i<=e.length;i++){const a=[i];for(let r=1;r<=t.length;r++)a[r]=Math.min(s[r]+1,a[r-1]+1,s[r-1]+(e[i-1]===t[r-1]?0:1));s=a}return s[t.length]})(t,e.toLowerCase());a<i&&(s=e,i=a)}),s};function ce(e){const t=[];return Object.entries(e).forEach(([e,s])=>{re.includes(e)?ne.includes(e)&&(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(s)&&"enabled"in s&&!("enable"in s)&&t.push({key:`${e}.enabled`,suggestion:`${e}.enable`}):t.push({key:e,suggestion:oe(e)})}),t}class he{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 ue=["classic","captioned","banner","carousel"];function de(e){return(Array.isArray(e)?e:[]).filter(e=>!!e&&!!e.imageUrl).slice(0,5)}const le=/^(?:javascript|vbscript|data|blob|file):/i,ge=/^[a-z][a-z\d+\-.]*:/i;function pe(e){return e.split("").filter(e=>e.charCodeAt(0)>32&&127!==e.charCodeAt(0)).join("")}function me(e){const t=pe(e);return ge.test(t)&&!le.test(t)}function we(e,t){return t||e.image||""}function be(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 fe{constructor(e,t,s,i={},a=()=>Promise.resolve(void 0),r=new he){this.data=e,this.api=t,this.inboxModel=s,this.moduleRegistry=i,this.loadWebPopups=a,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(e){try{return JSON.parse(e)||{}}catch(t){return te.write("error",`Pushwoosh: cannot parse inbox action_params: ${e}`,t),{}}}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const i=[],a=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,i.push(t),a.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(i),await Promise.all(a)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:i,send_date:a,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(t),h=function(e){const t=e?.u;if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)||{}}catch{return{}}return"object"==typeof t?t:{}}(c),u=function(e){return(Array.isArray(e.carousel)?e.carousel:[]).filter(e=>!!e&&!!e.image).slice(0,5).map(e=>({imageUrl:e.image,caption:e.title||"",link:e.url&&me(e.url)?e.url:""}))}(h),d=function(e,t,s){return e?.b||s||t.image||""}(c,h,s),l=function(e){const t=!!e.title,s=!!e.body,i=function(e){return e.bannerUrl||e.iconUrl||""}(e);let a=e.layoutType;switch(ue.includes(a)||(a=e.bannerUrl&&!t?"banner":e.bannerUrl&&t&&s?"captioned":"classic"),a){case"banner":return i?"banner":"classic";case"captioned":return i&&t&&s?"captioned":"classic";case"carousel":return t&&s&&de(e.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:i,body:n,iconUrl:we(h,s),bannerUrl:c.b,layoutType:h.displayType,carousel:u}),g=we(h,s)||await this.data.getDefaultNotificationImage(),p=i||await this.data.getDefaultNotificationTitle();return this.dateModule.date=new Date(1e3*parseInt(a)),{title:p,imageUrl:g,iconUrl:g,heroUrl:d,layout:l,carousel:u,customData:be(h),webPopupCode:c.wp||"",code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,c),link:c?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10)).sort((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=this.parseActionParams(t.action_params),i=this.messageTypeFactory(t.action_type,s),a=2===i||3===i;var r;!await this.showWebPopup(s.wp)&&a&&null!=s.l&&((r=s.l)&&!le.test(pe(r)))&&(document.location.href=s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async showWebPopup(e){if(!e)return!1;try{const t=this.moduleRegistry.webPopups??await this.loadWebPopups();return t?await t.show(e):(te.write("error",`Pushwoosh: inbox message opens web popup "${e}", but the web popups widget could not be loaded`),!1)}catch(t){return te.write("error",`Pushwoosh: failed to open web popup "${e}" from inbox`,t),!1}}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class ye{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{i(e.error)}})}readRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target;s(i.result||t)},e.onerror=()=>{i(e.error)}})}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target.result;i?(t.push(i.value),i.continue()):s(t)},e.onerror=()=>{i(e.error)}})}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class ve{getDB(){return K()}async put(e,t,s){const i=await this.getDB();return new ye(i,e).put(t,s)}async delete(e,t){const s=await this.getDB();return new ye(s,e).delete(t)}async get(e,t,s){const i=await this.getDB();return new ye(i,e).get(t,s)}async getAll(e){const t=await this.getDB(),s=new ye(t,e);return await s.getAll()||[]}async count(e,t){const s=await this.getDB();return new ye(s,e).count(t)}async countByIndex(e,t,s){const i=await this.getDB(),a=new ye(i,e);return a.index=t,a.countByIndex(s)}}class Pe{constructor(e,t,s,i=new ve,a=new he){this.eventBus=e,this.data=t,this.api=s,this.storage=i,this.storeName="inboxMessages",this.dateModule=a}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map(async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)});return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map(e=>this.putMessage(e));return Promise.all(t)}deleteMessages(e){const t=e.map(e=>this.storage.delete(this.storeName,e));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter(t=>t.rt<e).map(e=>e.inbox_id);return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>2===e.status||3===e.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>1===e.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new fe(this.data,this.api,this)})}}class Se extends Error{constructor(e,t){super(e),this.name="ApiRequestError",this.statusCode=t}}const Ce=e=>`params.${e}`;class ke{constructor(e=J){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const t of e)await this.store.set(Ce(t),void 0)}async setApplicationCode(e){await this.store.set(Ce("applicationCode"),e)}async getApplicationCode(){return this.store.get(Ce("applicationCode"))}async setApiToken(e){return await this.store.set(Ce("apiToken"),e)}async getApiToken(){return this.store.get(Ce("apiToken"))}async setHwid(e){await this.store.set(Ce("hwid"),e)}async getHwid(){return this.store.get(Ce("hwid"))}async setDeviceType(e){await this.store.set(Ce("deviceType"),e)}async getDeviceType(){return this.store.get(Ce("deviceType"))}async setFormFactor(e){await this.store.set(Ce("formFactor"),e)}async getFormFactor(){return this.store.get(Ce("formFactor"))}async setDeviceModel(e){await this.store.set(Ce("deviceModel"),e)}async getDeviceModel(){return this.store.get(Ce("deviceModel"))}async setLanguage(e){await this.store.set(Ce("language"),e)}async getLanguage(){return this.store.get(Ce("language"),"en")}async setStatusLanguageWasChanged(e){await this.store.set(Ce("languageWasChanged"),e)}async getStatusLanguageWasChanged(){return this.store.get(Ce("languageWasChanged"),!1)}async setApiEntrypoint(e){await this.store.set(Ce("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(Ce("apiEntrypoint"),i)}async setTokens(e){await this.store.set(Ce("tokens"),e)}getTokens(){return this.store.get(Ce("tokens"))}async setApplicationServerKey(e){await this.store.set(Ce("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(Ce("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(Ce("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(Ce("isVapidChanged"),!1)}async setWebVapidConfigured(e){await this.store.set(Ce("webVapidConfigured"),e)}async getWebVapidConfigured(){return this.store.get(Ce("webVapidConfigured"),!1)}async setWebSitePushId(e){await this.store.set(Ce("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(Ce("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(Ce("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(Ce("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(Ce("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(Ce("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(Ce("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(Ce("userId"))}async getFeatureFlags(){return this.store.get(Ce("featureFlags"))}async setFeatureFlags(e){await this.store.set(Ce("featureFlags"),e)}async getFeatureFlagImpressions(){return this.store.get(Ce("featureFlagImpressions"),{})}async setFeatureFlagImpressions(e){await this.store.set(Ce("featureFlagImpressions"),e)}async setStatusUserIdWasChanged(e){await this.store.set(Ce("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(Ce("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(Ce("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(Ce("email"))}async setStatusEmailWasChanged(e){await this.store.set(Ce("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(Ce("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(Ce("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(Ce("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(Ce("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(Ce("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(Ce("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(Ce("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(Ce("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(Ce("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(Ce("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(Ce("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(Ce("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(Ce("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(Ce("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(Ce("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(Ce("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(Ce("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(Ce("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(Ce("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(Ce("sdkVersion"),e)}async getSdkVersion(){return this.store.get(Ce("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(Ce("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(Ce("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(Ce("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(Ce("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(Ce("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(Ce("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(Ce("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(Ce("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(Ce("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(Ce("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(Ce("features"),e)}async getFeatures(){return this.store.get(Ce("features"))}async setInitParams(e){await this.store.set(Ce("init"),e)}async getInitParams(){return this.store.get(Ce("init"))}async setInboxLastRequestCode(e){await this.store.set(Ce("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(Ce("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(Ce("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(Ce("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(Ce("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(Ce("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(Ce("delayedEvent"),e)}getDelayedEvent(){return this.store.get(Ce("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(Ce("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(Ce("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(Ce("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(Ce("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(e){await this.store.set(Ce("subscriptionWidgetHistory"),e)}async getSubscriptionWidgetHistory(){return this.store.get(Ce("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(e){await this.store.set(Ce("logLevel"),e)}async getLogLevel(){return this.store.get(Ce("logLevel"),"error")}async getShownWebPopups(){return this.store.get(Ce("shownWebPopups"),[])}async addShownWebPopup(e){const t=await this.getShownWebPopups();t.includes(e)||(t.push(e),await this.store.set(Ce("shownWebPopups"),t))}async setIsRecurringVisitor(e){await this.store.set(Ce("isRecurringVisitor"),e)}async getIsRecurringVisitor(){return this.store.get(Ce("isRecurringVisitor"),!1)}}class Ie{constructor(e=new ke,t=te){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}getPopupForms(e){return this.createRequest("getPopupForms",e)}getPopupFormContent(e){return this.createRequest("getPopupFormContent",e)}recordPopupFormEvent(e){return this.createRequest("recordPopupFormEvent",e)}submitPopupForm(e){return this.createRequest("submitPopupForm",e)}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 i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=i+e,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:A().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n,keepalive:s.keepalive}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(e){if(200!==e.status){let t,s=`status: ${e.status}. statusText: ${e.statusText}.`;try{const i=await e.json();i&&"number"==typeof i.status_code&&(t=i.status_code),i&&i.status_message&&(s+=` status_code: ${i.status_code}. status_message: ${i.status_message}.`)}catch(e){}throw new Se(s,t)}const t=await e.json();if(200!==t.status_code)throw new Se(`Error code: ${t.status_code}. Error text: ${t.status_message}`,"number"==typeof t.status_code?t.status_code:void 0);return t}}class De{constructor(e,t=new ke,s=new Ie,i=()=>!1,a=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=N(1e4),this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=i,this.getInitUserId=a,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(e=>{throw this.checkDevicePromise=null,e})),this.checkDevicePromise}async requestCheckDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(a);if(null===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,e&&s?n:o),t=localStorage.getItem(a)}return t===n}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(e=>{throw this.ensureDeviceRegisteredPromise=null,e})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:e}=await this.checkDevice();if(e)return!1;const t=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t),!0}async reportPushPermissionStatus(e=!1){const t=this.getPushPermissionStatus();if(t&&t!==this.reportingPushPermissionStatus&&t!==localStorage.getItem(r)){this.reportingPushPermissionStatus=t;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!e&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t)}finally{this.reportingPushPermissionStatus===t&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(r)}rememberReportedPushPermissionStatus(e){e&&localStorage.setItem(r,e)}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const t=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...e,push_permission_status:t,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(t),s}async registerDevice(){const e=this.requestRegisterDevice();this.registerDevicePromise=e;try{return await e}finally{this.registerDevicePromise===e&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),t=await this.data.getTokens();if(!t.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=this.getPushPermissionStatus(),i=await this.apiClient.registerDevice({...e,push_permission_status:s,locale:await this.getLocale(),push_token:t.pushToken,auth_token:t.authToken,public_key:t.publicKey});return this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(s),await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{}),i}async unregisterDevice(){const e=await this.getRequestParams(),t=await this.apiClient.unregisterDevice(e);return this.checkDevicePromise=null,localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...i,hash:e,metaData:s})}async pushStat(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.pushStat({...i,hash:e,metaData:s})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...i}=await this.getRequestParams(),a=await this.data.getEmail();return a&&await this.apiClient.setEmailTags({...i,email:a,tags:e}),this.apiClient.setTags({...i,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async setLanguage(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:e}))}async setLocale(e){if(!e)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const t=Ee(e.trim().replace(/_/g,"-"));t&&(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return Ee(await this.data.getLanguage())||void 0}async registerUser(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:i,...a}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${e}`,o=await this.data.getUserId(),c=await this.apiClient.registerUser({...a,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),n&&n!==o&&this.eventBus.dispatchEvent("change-user-id",{userId:n}),t&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),i=await this.apiClient.registerEmail({...s,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),i}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),a}async registerWhatsappNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),a}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:e})}async recordPopupFormEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:e,event:t};return this.apiClient.recordPopupFormEvent(3===t?{...s,clickId:R()}:s)}async 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 i=await this.getRequestParams(),a=new Date,r=a.getTime(),n=Math.floor(r/1e3),o=n-a.getTimezoneOffset()/60*3600,c=await this.data.getLastOpenMessage();if(c&&c.expiry>Date.now()){if(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const h=await this.apiClient.postEvent({...i,event:e,timestampUTC:n,timestampCurrent:o,attributes:t},s);return h&&h.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:h.code}),h?.web_placements?.length&&this.eventBus.dispatchEvent("receive-web-placements",{placements:h.web_placements}),h}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),i=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:i})}async inboxStatus(e,t){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:e,status:t,time:(new Date).getTime()})}async multiRegisterDevice(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const t=await this.data.getApplicationCode(),s=await this.data.getDeviceModel(),i=await this.data.getDeviceType(),r=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),h=await this.data.getHwid();!e.push_devices&&c.pushToken&&await this.requireHwid();const u={application:t,...e};if(e.user_id){u.user_id=String(e.user_id);await this.data.getUserId()!==u.user_id&&(await this.data.setUserId(u.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(e.email){if(!/^\S+@\S+\.\S+$/.test(e.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==e.email&&(await this.data.setEmail(e.email),await this.data.setStatusEmailWasChanged(!0))}if(e.sms_phone_number){if(!/^\+?[0-9]+$/.test(e.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==e.sms_phone_number&&(await this.data.setSmsNumber(e.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(e.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(e.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==e.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(e.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(u.language?(await this.data.setLanguage(u.language),await this.data.setStatusLanguageWasChanged(!0)):u.language=r,!u.timezone){const e=60*-(new Date).getTimezoneOffset();u.timezone=String(e)}if(!u.push_devices&&c.pushToken){const e={hwid:h,platform:i,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||s){const t={};c.publicKey&&(t.public_key=c.publicKey),c.authToken&&(t.auth_token=c.authToken),s&&(t.browser=s),e.platformData=t}u.push_devices=[e]}const d=await this.apiClient.multiRegisterDevice(u);return u.push_devices?.length&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const e=await this.requireHwid(),t=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:e,device_type:t}}async getIdentityRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),i=await this.data.getDeviceModel(),a=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!t)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:e,userId:s||t,device_model:i,timezone:n,language:a,v:r}}async requireHwid(){const e=await this.data.getHwid();if(!e)throw new Error(_);return e}}function Ee(e){try{return e?Intl.getCanonicalLocales(e)[0]??"":""}catch{return""}}class We{constructor(e,t,s,i){this.key=e,this.enabled=t,this.ruleId=s,this.properties=i}getString(e,t){const s=this.properties[e];return"string"==typeof s?s:t}getNumber(e,t){const s=this.properties[e];return"number"==typeof s&&Number.isFinite(s)?s:t}getBool(e,t){const s=this.properties[e];return"boolean"==typeof s?s:t}getJson(e,t){const s=this.properties[e];return s??t}getProperties(){return{...this.properties}}}class _e extends Error{constructor(e,t){super(e),this.name="FeatureFlagsError",this.httpStatus=t}}const xe=/json\/1\.3\/?$/,Te="api/v2/device-api/getFeatureFlags";const Ae=18e5;class Re{constructor(e){this.listeners=new Set,this.pageImpressions=new Set,this.isMemoryOnly=!1,this.applicationCode="",this.userId="",this.lastRequestAt=0,this.lastSentUnregistered=!1,this.generation=0,this.isStarted=!1,this.isLoaded=!1,this.isActivated=!1,this.userChangedWhileLoading=!1,this.deps={fetch:(e,t)=>fetch(e,t),now:()=>Date.now(),...e},this.deps.eventBus.addEventHandler("change-user-id",({userId:e})=>this.onUserChanged(e)),this.deps.eventBus.addEventHandler("register",()=>this.onRegistered())}async start(){if(this.isStarted)return;this.isStarted=!0,this.applicationCode=await this.deps.data.getApplicationCode()||"";const e=await this.deps.data.getUserId()||"";this.userChangedWhileLoading||(this.userId=e);const t=await this.deps.data.getFeatureFlags();t&&t.applicationCode===this.applicationCode&&(this.cache=t),this.isLoaded=!0,this.isActivated&&(""!==this.visibleSnapshot()&&this.notify(),this.refreshOnPageLoad())}get(e){if(this.activate(),!this.cache||!this.hasValidCache())return null;const t=this.cache.flags[e];return t?new We(e,t.enabled,t.rule_id,t.properties):null}isEnabled(e,t){const s=this.get(e);return s?s.enabled:t}refresh(){return this.activate(),this.hasValidCache()&&this.deps.now()-this.lastRequestAt<3e5?Promise.resolve():this.send()}reset(){clearTimeout(this.timer),this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.isStarted=!1,this.isLoaded=!1,this.userChangedWhileLoading=!1}addUpdateListener(e){this.activate(),this.listeners.add(e)}removeUpdateListener(e){this.listeners.delete(e)}async logImpression(e){const t=this.get(e);if(!t||this.deps.isCommunicationDisabled())return;const s=`${e}|${t.ruleId}|${t.enabled}`;if(!this.pageImpressions.has(s)){this.pageImpressions.add(s);try{await this.sendImpression(t,s)}catch(e){this.pageImpressions.delete(s),te.error(e,"Pushwoosh: feature flag impression was not sent")}}}async sendImpression(e,t){const s=this.deps.now(),i=await this.deps.data.getFeatureFlagImpressions();if(!(void 0!==i[t]&&s-i[t]<Ae)){await this.deps.data.setFeatureFlagImpressions({...Le(i,s),[t]:s});try{await this.deps.postEvent("PW_FeatureFlagImpression",{flag_key:e.key,rule_id:e.ruleId,enabled:e.enabled})}catch(e){const s=await this.deps.data.getFeatureFlagImpressions().catch(()=>{});throw s&&(delete s[t],await this.deps.data.setFeatureFlagImpressions(s).catch(()=>{})),e}}}onUserChanged(e){if(!this.isLoaded)return this.userId=e,void(this.userChangedWhileLoading=!0);e!==this.userId&&(this.userId=e,this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.deps.data.setFeatureFlags(void 0),this.isActivated&&this.sendAfterInFlight())}onRegistered(){const e=!!this.cache&&!!this.cache.sentUnregistered;this.isLoaded&&this.isActivated&&(this.lastSentUnregistered||e)&&this.sendAfterInFlight()}activate(){this.isActivated||(this.isActivated=!0,this.isLoaded&&this.refreshOnPageLoad())}refreshOnPageLoad(){const e=this.cache?this.deps.now()-this.cache.fetchedAt:1/0,t=!!this.cache&&!!this.cache.sentUnregistered&&this.deps.isDeviceRegistered();!this.hasValidCache()||e>9e5||t?this.sendInBackground():this.schedulePeriodicRefresh()}sendAfterInFlight(){(this.inFlight||Promise.resolve()).catch(()=>{}).then(()=>this.sendInBackground())}sendInBackground(){this.send().catch(e=>te.error(e,"Pushwoosh: feature flags refresh failed"))}send(){return this.inFlight||(this.inFlight=this.request().finally(()=>{this.inFlight=void 0,this.schedulePeriodicRefresh()})),this.inFlight}async request(){if(this.lastRequestAt=this.deps.now(),this.deps.isCommunicationDisabled())throw new _e("Communication is disabled",0);const e=this.generation,t=await this.deps.data.getHwid();if(!t||!this.applicationCode)throw new _e("Pushwoosh SDK is not initialized",0);const s={application:this.applicationCode,hwid:t};this.cache&&this.hasValidCache()&&this.cache.etag&&(s.etag=this.cache.etag);const a=function(e){const t=e||i;if(xe.test(t))return t.replace(xe,Te);try{return`${new URL(t).origin}/${Te}`}catch(e){return i.replace(xe,Te)}}(await this.deps.data.getApiEntrypoint()),r=await this.deps.data.getApiToken(),n={method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",...r?{Authorization:`Token ${r}`}:{}},body:JSON.stringify(s),...r?{credentials:"include"}:{}};let o,c;this.lastSentUnregistered=!this.deps.isDeviceRegistered();try{o=await this.deps.fetch(a,n)}catch(e){throw new _e(`getFeatureFlags request failed: ${e instanceof Error?e.message:String(e)}`,0)}if(200!==o.status)throw new _e(`getFeatureFlags answered HTTP ${o.status}`,o.status);try{c=await o.json()}catch(e){throw new _e("getFeatureFlags answered an unreadable body",o.status)}if(!c||200!==c.status_code||!Me(c.response))throw new _e(`getFeatureFlags answered status_code ${String(c&&c.status_code)}`,o.status);e===this.generation&&await this.apply(c.response)}async apply(e){const t=this.visibleSnapshot(),s=this.deps.now();if(!0===e.not_modified){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return;this.cache={...this.cache,fetchedAt:s,sentUnregistered:this.lastSentUnregistered},this.isMemoryOnly||await this.deps.data.setFeatureFlags(this.cache)}else if(!0===e.partial){if(this.hasValidCache())return;this.cache=this.newCache(e,"",s),this.isMemoryOnly=!0}else this.cache=this.newCache(e,"string"==typeof e.etag?e.etag:"",s),this.isMemoryOnly=!1,await this.deps.data.setFeatureFlags(this.cache);this.visibleSnapshot()!==t&&this.notify()}newCache(e,t,s){return{applicationCode:this.applicationCode,userId:this.userId,flags:Ne(e.flags),etag:t,fetchedAt:s,sentUnregistered:this.lastSentUnregistered}}notify(){this.listeners.forEach(e=>{try{e()}catch(e){te.error(e,"Pushwoosh: feature flags update listener failed")}})}schedulePeriodicRefresh(){if(!this.isLoaded)return;clearTimeout(this.timer);const e=Math.max(this.lastRequestAt,this.cache?this.cache.fetchedAt:0),t=Math.max(0,e+36e5-this.deps.now());this.timer=setTimeout(()=>this.sendInBackground(),t)}hasValidCache(){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return!1;const e=this.deps.now()-this.cache.fetchedAt;return e>=0&&e<=864e5}isCacheOfCurrentUser(e){return e.applicationCode===this.applicationCode&&e.userId===this.userId}visibleSnapshot(){return this.cache&&this.hasValidCache()?Fe(this.cache.flags):""}}function Me(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ne(e){const t={};return Me(e)?(Object.keys(e).forEach(s=>{const i=e[s];Me(i)&&"boolean"==typeof i.enabled&&(t[s]={enabled:i.enabled,rule_id:"string"==typeof i.rule_id?i.rule_id:"",properties:Me(i.properties)?i.properties:{}})}),t):t}function Le(e,t){const s={};return Object.keys(e).forEach(i=>{t-e[i]<Ae&&(s[i]=e[i])}),s}function Fe(e){return Array.isArray(e)?`[${e.map(Fe).join(",")}]`:Me(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Fe(e[t])}`).join(",")}}`:JSON.stringify(e)}class Ue{constructor(e){this.global=e,this._isSafari=this.isSafariBrowser(),this._isOpera=this.isOperaBrowser(),this._isEdge=this.isEdgeBrowser(),this._isFirefox=this.isFirefoxBrowser(),this._isChrome=this.isChromeBrowser(),this._isMacOS=this.isMacOS(),this._isAvailableServiceWorker=this.canUseServiceWorkers(),this._isAvailableNotifications=this.canReceiveNotifications(),this._platform=this.getPlatformType(),this._browserVersion=this.getBrowserVersion(),this._formFactor=this.getFormFactor()}get isEdge(){return this._isEdge}get isSafari(){return this._isSafari}get isOpera(){return this._isOpera}get isAvailableServiceWorker(){return this._isAvailableServiceWorker}get isAvailableNotifications(){return this._isAvailableNotifications}get platform(){return this._platform}get browserVersion(){return this._browserVersion}get formFactor(){return this._formFactor}get isMobile(){return"MOBILE"===this._formFactor}get isDesktop(){return"DESKTOP"===this._formFactor}isSafariBrowser(){return"safari"in this.global&&navigator.userAgent.indexOf("Safari")>-1}isOperaBrowser(){return-1!==navigator.userAgent.indexOf("Opera")||-1!==navigator.userAgent.indexOf("OPR")}isEdgeBrowser(){return navigator.userAgent.indexOf("Edge")>-1}isFirefoxBrowser(){return-1!==navigator.userAgent.toLowerCase().indexOf("firefox")}isChromeBrowser(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!this._isOpera&&!this._isEdge}isMacOS(){return"platform"in navigator&&-1!==navigator.platform.toLowerCase().indexOf("mac")}canUseServiceWorkers(){return!!navigator.serviceWorker&&"PushManager"in this.global&&"Notification"in this.global}canReceiveNotifications(){return this._isSafari&&this._isMacOS||this._isAvailableServiceWorker&&!this._isEdge}getPlatformType(){let e=11;switch(!0){case this._isSafari:e=10;break;case this._isOpera||this._isChrome:e=11;break;case this._isFirefox:e=12;break;case this._isEdge:e=150}return e}getFormFactor(){const e=navigator.userAgentData;if(e&&"boolean"==typeof e.mobile)return e.mobile?"MOBILE":"DESKTOP";return/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?"MOBILE":"DESKTOP"}getBrowserVersion(){const{userAgent:e}=navigator,t=e.match(/\bOPR\/(\d+)/);if(null!==t)return`Opera ${t[1]}`;const s=e.match(/\bEdge\/(\d+)/);if(null!==s)return`Edge ${s[1]}`;const i=e.match(/\bEdg\/(\d+)/);if(null!==i)return`Edge ${i[1]}`;let a=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[];const[,r=""]=a;a=a[2]?[r,a[2]]:[navigator.appName,navigator.appVersion,"-?"];const n=e.match(/version\/([.\d]+)/i);return null!==n&&a.splice(1,1,n[1]),a.join(" ")}}const Oe="pushwoosh-recommendations-views";function qe(){try{if("undefined"!=typeof sessionStorage)return sessionStorage}catch{}const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,s)=>{e.set(t,s)}}}class Be{constructor(e){this.deps={fetch:(...e)=>fetch(...e),now:Date.now,storage:qe(),...e}}async trackProductView(e){!e?.id||this.deps.isCommunicationDisabled()||this.seenRecently(String(e.id))||await this.deps.postEvent("PW_ProductView",{productId:String(e.id),name:e.name,price:e.price,currency:e.currency,category:e.category,productUrl:e.url,imageUrl:e.imageUrl})}async fetch(e){const t=new URLSearchParams({application:await this.deps.getApplicationCode(),strategy:e.strategy});e.fallback&&t.set("fallback",e.fallback),e.limit&&t.set("limit",String(e.limit)),e.productId&&t.set("product_id",e.productId),e.exclude?.length&&t.set("exclude",e.exclude.join(",")),e.block&&t.set("block",e.block);const s={},i=this.deps.isCommunicationDisabled()?"":await this.deps.getHwid();i&&(s["X-PW-HWID"]=i);const a=(this.deps.getEndpoint()||"https://recommender-onsite.svc-nue.pushwoosh.com").replace(/\/+$/,""),r=await this.deps.fetch(`${a}/feed/v1/onsite/products.json?${t}`,{headers:s});if(!r.ok)throw new Error(`Pushwoosh: recommendations request failed with status ${r.status}`);return r.json()}async trackClick(e){e?.productId&&!this.deps.isCommunicationDisabled()&&await this.deps.postEvent("PW_RecommendationClick",{block:e.block,strategy:e.strategy,recoProductId:String(e.productId),position:e.position},{keepalive:!0})}seenRecently(e){const t=this.deps.now(),s=function(e){try{const t=JSON.parse(e||"{}");return null===t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,e])=>"number"==typeof e))}catch{return{}}}(this.deps.storage.getItem(Oe));if(t-(s[e]??-1/0)<3e4)return!0;const i={[e]:t};Object.keys(s).forEach(e=>{t-s[e]<3e4&&(i[e]=s[e])});try{this.deps.storage.setItem(Oe,JSON.stringify(i))}catch{}return!1}}const je="sdkUsageReportedOn";class Ve{constructor(){this.initKeys=new Set,this.events=new Set,this.legacyEvents=new Set,this.isListening=!1}recordInitParams(e){Object.entries(e).forEach(([e,t])=>{this.initKeys.add(e),(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(t)&&Object.keys(t).forEach(t=>this.initKeys.add(`${e}.${t}`))})}recordEvent(e){this.events.add(e)}recordLegacyEvent(e){this.legacyEvents.add(e)}listen(e){if(this.isListening)return;this.isListening=!0;const t=()=>this.flush(e);document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&t()}),window.addEventListener("pagehide",t)}flush(e){const t=(new Date).toISOString().slice(0,10);try{if(localStorage.getItem(je)===t)return;localStorage.setItem(je,t)}catch{return}e({init_keys:[...this.initKeys],events:[...this.events],legacy_events:[...this.legacyEvents]},{keepalive:!0}).catch(()=>{})}}function $e(e){switch(e){case c:return"granted_explicit";case"denied":return"denied";default:return"not_determined"}}function He(e){return"safari"in e?e.safari?.pushNotification:void 0}function Ke(e,t){try{return He(e)?.permission(t)}catch{return}}class ze{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return this.data.getStatusManualUnsubscribed()}async askPermission(){await Notification.requestPermission()}async getTokens(){return this.data.getTokens()}async subscribe(e){const t=e||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),i=t.getKey("p256dh"),a=t.getKey("auth");if(!i||!a)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(i))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(a)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t&&(await this.data.setLastPermissionStatus(t),void 0!==e))return!0;const s=await this.getCredentials(),i=this.getPushToken(s),a=await this.data.getTokens(),r=i===(a&&a.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${R()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),i=new Uint8Array(s.length);for(let e=0;e<s.length;++e)i[e]=s.charCodeAt(e);return i}}class Ge{constructor(e,t,s){this.api=e,this.config=s,this.data=t}getPermission(){const{permission:e}=this.getPermissionInfo();return e}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const e={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise(t=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,e,()=>t())})}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const{deviceToken:e}=this.getPermissionInfo();await this.data.setTokens({pushToken:e}),await this.api.registerDevice()}async unsubscribe(){await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getWebSitePushId(),t=void 0!==e&&this.config.webSitePushId!==e;await this.data.setWebSitePushId(this.config.webSitePushId);const s=await this.data.getLastPermissionStatus(),i=this.getPermission();return s!==i&&(await this.data.setLastPermissionStatus(i),void 0!==s)||t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class Je{constructor(){this.ready=!1,this.rawInitParams={},this.isPushDisabled=!1,this.isInitAborted=!1,this.isPushPermissionWatched=!1,this.subscriptionInFlight=null,this.isWebVapidConfigured=!1,this.isLegacySafari=!1,this.waitForPermissionWork=N(1e4),this.moduleRegistry={},this.sdkUsage=new Ve,this.pendingWebPlacements=[],this.webPlacementsSink=null,this.addEventHandler=(e,t)=>{this.sdkUsage.recordEvent(e),this.eventBus.addEventHandler(e,t)},this.addSdkEventHandler=(e,t)=>this.eventBus.addEventHandler(e,t),this.removeEventHandler=(e,t)=>this.eventBus.removeEventHandler(e,t),this.dispatchEvent=(e,t)=>this.eventBus.dispatchEvent(e,t),this.debug={async showLog(){const e=await X.getAll();console.log(e)},async showKeyValues(){const e=await J.getAll();console.log(e)},async showMessages(){(await Q.getAll()).forEach(e=>console.log(e))}},this.eventBus=new se,this.data=new ke,this.apiClient=new Ie(this.data),this.api=new De(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled,()=>this.getInitUserId(),()=>this.getPushPermissionStatus()),this.featureFlags=new Re({eventBus:this.eventBus,data:this.data,postEvent:(e,t)=>this.api.postEvent(e,t),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,isDeviceRegistered:()=>this.isDeviceRegistered()}),this.recommendations=new Be({postEvent:(e,t,s)=>this.api.postEvent(e,t,s),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,getApplicationCode:()=>this.data.getApplicationCode(),getHwid:()=>this.data.getHwid(),getEndpoint:()=>this.initParams?.recommendations?.endpoint}),this.platformChecker=new Ue(A()),this.inboxModel=new Pe(this.eventBus,this.data,this.api),this.pwinbox=new fe(this.data,this.api,this.inboxModel,this.moduleRegistry,()=>this.loadWebPopupsWidget()),this.eventBus.addEventHandler("receive-web-placements",({placements:e})=>this.deliverWebPlacements(e))}takeWebPlacements(){const e=this.pendingWebPlacements;return this.pendingWebPlacements=[],e}deliverWebPlacements(e){!1!==this.initParams?.webPlacements?.enable&&(this.webPlacementsSink?this.webPlacementsSink(e):(this.pendingWebPlacements.push(...e),this.loadWebPopupsWidget().catch(e=>{te.error(e,"Pushwoosh: failed to load the web popups widget for journey placements")})))}async loadWebPopupsWidget(){if(this.moduleRegistry.webPopups||!this.widgetLoader||!1===this.initParams?.webPopups?.enable)return this.moduleRegistry.webPopups;let e;const t=new Promise(t=>{e=setTimeout(()=>t(!1),1e4)});return await Promise.race([this.widgetLoader("web-popups"),t]),clearTimeout(e),this.moduleRegistry.webPopups}push(e){if(M(e))this.subscribeToLegacyEvents(u,e);else{if(!Array.isArray(e))throw new Error("Invalid command!");if("init"===e[0])this.initialize(e[1]).catch(e=>{console.error("Pushwoosh: Error during initialization",e)});else if(!this.subscribeToLegacyEvents(e[0],e[1]))throw console.log("Pushwoosh: Unknown command",e),new Error("Unknown command!")}}async subscribe(e=!0){const t=this.runSubscribe(e);this.subscriptionInFlight=t;try{await t}finally{this.subscriptionInFlight===t&&(this.subscriptionInFlight=null)}}async runSubscribe(e){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.isPushDisabled)throw new Error('Push notifications are disabled by the "pushNotifications" init param!');const t=this.requireDriver();if(t.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await t.askPermission();const e=t.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e}),e!==h&&this.announcePermissionChange(e)}const s=t.getPermission(),i=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(s===c){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!i||e)&&await t.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if("denied"===s)return this.eventBus.dispatchEvent("permission-denied",{}),a&&await t.unsubscribe(),void this.reportPushPermissionChangeInBackground()}async unsubscribe(){try{await this.requireDriver().unsubscribe()}catch(e){throw te.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===n}isDeviceUnregistered(){return localStorage.getItem(a)===o}async isSubscribed(){return this.api.checkDeviceSubscribeForPushNotifications()}async isCommunicationEnabled(){return!await this.data.getStatusCommunicationDisabled()}async setCommunicationEnabled(e=!0){if(await this.data.setCommunicationEnabled(e),e){this.isCommunicationDisabled=!1,await this.data.setStatusDropAllData(!1),await this.finishInit();const e=this.driver?.checkIsPermissionGranted();e&&(await this.api.registerDevice(),await this.sendData())}else this.featureFlags.reset(),await this.api.unregisterDevice();this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:e});const t=await this.data.getDeviceType();await this.api.postEvent("GDPRConsent",{channel:e,device_type:t})}async removeAllDeviceData(){const e=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:e}),await this.api.deleteDevice(),await this.data.clearAll(),this.featureFlags.reset(),await this.data.setStatusDropAllData(!0)}trackProductView(e){return this.recommendations.trackProductView(e)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:e}=await this.data.getTokens();return e}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return this.platformChecker.isAvailableNotifications}isPushAvailable(){return!!this.driver&&!this.isPushDisabled}requireDriver(){if(!this.driver)throw new Error("Push notifications are not available: the browser does not support them, or the application has no push configuration. Web popups, inbox, events and tags do not require it.");return this.driver}async initialize(e){this.rawInitParams={...e},this.sdkUsage.recordInitParams(e),function(e){ce(e).forEach(({key:e,suggestion:t})=>{const s=t?` Did you mean "${t}"?`:"";console.warn(`Pushwoosh: unknown init parameter "${e}" is ignored.${s}`)})}(e),this.initParams={...T,...e},this.isInitAborted=!1;const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(te.setLevel(t||e.logLevel||"error"),e.logLevel&&await this.data.setLogLevel(e.logLevel),this.isPushDisabled=!1===e.pushNotifications,this.isAvailableNotifications()||te.info("Pushwoosh: push notifications are not available in this browser, initializing without them"),!e.applicationCode)throw new Error("Can't find application code!");const s=!1===e.communicationEnabled,i=await this.data.getCommunicationEnabled(),a=await this.data.getStatusCommunicationDisabled();(s&&!0!==i||!1===i||a)&&(this.isCommunicationDisabled=!0);const r=await this.data.getApplicationCode(),n=await this.isUserIdChanged();(!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail(),await this.data.setStatusLanguageWasChanged(!1)),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.resolvePlatformType()),await this.data.setFormFactor(this.platformChecker.formFactor),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion());if(await this.data.getStatusLanguageWasChanged()||await this.data.setLanguage(e.tags?.Language||navigator.language),await this.data.setApiEntrypoint(e.pushwooshUrl||""),await this.data.setApiToken(e.apiToken||""),await this.data.setSdkVersion("3.110.0"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{if(await this.finishInit(),this.isInitAborted)return;try{this.initParams.inboxWidget?.enable&&await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}catch(e){te.write("error",e)}const e=await this.data.getDelayedEvent();if(e){const{type:t,payload:s}=e;this.emitLegacyEventsFromServiceWorker(t,s),await this.data.setDelayedEvent(null)}if(this.isLegacySafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){if(await this.ensureHwid(),await this.data.setInitParams(this.initParams),await this.initStep("loadConfig",()=>this.loadConfig()),await this.data.setDeviceType(this.resolvePlatformType()),await this.initStep("applicationOpen",()=>this.open()),await this.initStep("sendData",()=>this.sendData()),!this.isInitAborted){if(this.isAvailableNotifications()){await this.data.getApplicationServerKey()?await this.initStep("initPushNotifications",()=>this.initPushNotifications(this.initParams)):te.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.knownPermission=this.readPermission(),await this.initStep("watchPushPermission",()=>this.watchPushPermission())}await this.featureFlags.start().catch(e=>te.error(e,"Pushwoosh: feature flags failed to start")),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),this.sdkUsage.listen((e,t)=>this.api.sdkUsage(e,t)),"serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=e=>this.onServiceWorkerMessage(e)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}}))}}async initStep(e,t){if(!this.isInitAborted)try{await t()}catch(t){const s=function(e){const t=e?.statusCode;return"number"==typeof t?t:void 0}(t);if(void 0!==s&&-1!==x.indexOf(s))return void this.abortInit(s);te.error(t,`Pushwoosh: init step "${e}" failed`)}}abortInit(e){this.isInitAborted=!0,te.error(`Pushwoosh: initialization stopped. The Pushwoosh API rejected the application code "${this.initParams.applicationCode}" (status_code: ${e}). Check the applicationCode init param against the application in your Pushwoosh Control Panel.`)}resolvePlatformType(){this.isLegacySafari=this.detectLegacySafari();return!this.isLegacySafari&&(this.initParams.unifiedPlatform||this.platformChecker.isSafari)?11:this.platformChecker.getPlatformType()}detectLegacySafari(){if(!this.platformChecker.isSafari)return!1;if(!this.platformChecker.isAvailableServiceWorker)return!0;const{safariWebsitePushID:e,unifiedPlatform:t}=this.initParams??{};return!!function(e,t){const s=t?Ke(e,t):void 0;return s?.permission===c&&!!s.deviceToken}(A(),e)||!t&&!this.isWebVapidConfigured}async ensureHwid(e=!1){if(await this.readHwid()&&!e)return;const t=this.initParams.applicationCode+"_"+R();try{await this.data.setHwid(t),await this.data.getHwid()!==t&&te.info(_)}catch(e){te.info(e,_)}}async readHwid(){try{return await this.data.getHwid()}catch{return""}}getInitUserId(){const{userId:e}=this.initParams||{};return e&&"user_id"!==e?e:void 0}async isUserIdChanged(){const{userId:e}=this.initParams,t=await this.data.getUserId(),s=await this.data.getStatusUserIdWasChanged();return!!e&&"user_id"!==e&&e!==t&&!s}async defaultProcess(){const e=this.requireDriver(),t=e.getPermission();"granted"===t&&await this.data.setLastPermissionStatus(t);const s=await this.data.getStatusCommunicationDisabled(),i=await this.data.getStatusDropAllData(),a=await e.checkIsNeedResubscribe();if(s||i)return void await this.unsubscribe();a&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const r=await this.data.getStatusManualUnsubscribed(),n=!a&&await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(t){case h:this.eventBus.dispatchEvent("permission-default",{}),n&&await this.unsubscribe();break;case"denied":this.eventBus.dispatchEvent("permission-denied",{}),n&&await this.unsubscribe();break;case c:this.eventBus.dispatchEvent("permission-granted",{}),r&&n&&await this.unsubscribe(),(!n&&!r||a)&&await this.subscribe(!0)}this.reportPushPermissionChangeInBackground()}onServiceWorkerMessage(e){const{data:t={}}=e||{},{type:s="",payload:i={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,i)}async open(e){let t=await this.data.getLastOpenApplicationTime();const s=Date.now();t||(t=0);(e||!(s-t<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}getPushPermissionStatus(){return this.driver?$e(this.driver.getPermission()):function(e,t){const s=He(e);if(s&&t){const s=Ke(e,t);return s?$e(s.permission):"unsupported"}return"PushManager"in e&&"Notification"in e?$e(e.Notification.permission):s?"not_determined":"unsupported"}(A(),this.isLegacySafari?this.initParams?.safariWebsitePushID:void 0)}readPermission(){try{if(this.driver)return this.driver.getPermission();const e=A();return"Notification"in e?e.Notification.permission:void 0}catch{return}}announcePermissionChange(e){e!==this.knownPermission&&(this.knownPermission=e,this.eventBus.dispatchEvent("change-permission",{permission:e}))}async reportPushPermissionChange(){const e=null!==this.subscriptionInFlight&&!await this.waitForPermissionWork(this.subscriptionInFlight);if(this.isCommunicationDisabled||!this.driver||this.api.isPushPermissionStatusReported())return;const t=this.driver.getPermission(),s=await this.api.checkDeviceSubscribeForPushNotifications();let i=!1;if(t===c)s||e||this.isPushDisabled||await this.data.getStatusManualUnsubscribed()||(this.subscribe(!1).catch(e=>te.error(e,"Pushwoosh: re-subscribe after a permission grant failed")),this.subscriptionInFlight&&await this.waitForPermissionWork(this.subscriptionInFlight));else if(s){const e=this.dropRevokedSubscription(t).catch(e=>te.error(e,"Pushwoosh: unsubscribe after a permission revoke failed"));i=!await this.waitForPermissionWork(e)}await this.api.reportPushPermissionStatus(i)}async dropRevokedSubscription(e){await this.data.setLastPermissionStatus(e),await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1)}reportPushPermissionChangeInBackground(){this.reportPushPermissionChange().catch(e=>te.error(e,"Pushwoosh: registerDevice after a permission change failed"))}async watchPushPermission(){if(!this.isPushPermissionWatched&&"function"==typeof navigator.permissions?.query)try{(await navigator.permissions.query({name:"notifications"})).addEventListener("change",()=>{const e=this.readPermission();e&&this.announcePermissionChange(e),this.reportPushPermissionChangeInBackground()}),this.isPushPermissionWatched=!0}catch(e){te.info(e,"Pushwoosh: notifications permission can not be watched")}}async sendData(){const e=this.initParams,t=await this.data.getUserId();if(e.userId&&"user_id"!==e.userId&&e.userId!==t)try{await this.api.registerUser(e.userId,!1)}catch(e){te.error(e,"Pushwoosh: registerUser failed")}const s=[{test:async()=>{if(await this.data.getStatusEmailWasChanged())return!1;const t=await this.data.getEmail();return!!e.email&&e.email!==t},task:async()=>{await this.api.registerEmail(e.email,!1)}},{test:async()=>{if(await this.data.getStatusSmsNumberWasChanged())return!1;const t=await this.data.getSmsNumber();return!!e.smsNumber&&e.smsNumber!==t},task:async()=>{await this.api.registerSmsNumber(e.smsNumber,!1)}},{test:async()=>{if(await this.data.getStatusWhatsAppNumberWasChanged())return!1;const t=await this.data.getWhatsAppNumber();return!!e.whatsAppNumber&&e.whatsAppNumber!==t},task:async()=>{await this.api.registerWhatsappNumber(e.whatsAppNumber,!1)}},{test:async()=>!!e.tags||await this.data.getStatusLanguageWasChanged(),task:async()=>{const t=await this.data.getLanguage(),s={...e.tags||{},Language:t};await this.api.setTags(s)}}];await Promise.all(s.map(async e=>{try{await e.test()&&await e.task()}catch(e){console.error("Pushwoosh: Error during data registration",e)}}))}async loadConfig(){this.isWebVapidConfigured=await this.data.getWebVapidConfigured();const e=await this.api.getConfig(["vapid_key","web_vapid_configured","events","subscription_prompt","popup_forms","web_placements","web_sdk","web_sdk_modules"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(await this.applyServerInitParams(function(e){if(void 0!==e?.web_sdk)return e.web_sdk;const t=e?.web_sdk_modules;return void 0!==t?{inboxWidget:t.inboxWidget,webPopups:t.webPopups}:void 0}(t)),t.events&&t.events.length){t.events.some(e=>e===W)&&this.sendPostEventVisitedPage()}if(t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),void 0!==e&&e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}const e=t.web_vapid_configured??this.isWebVapidConfigured;e!==this.isWebVapidConfigured&&(this.isWebVapidConfigured=e,await this.data.setWebVapidConfigured(e))}}async applyServerInitParams(e){const t=function(e,t){if(!t)return{};const s={};if(ie.forEach(e=>{void 0!==t[e]&&(s[e]=t[e])}),void 0!==t.inboxWidget&&(s.inboxWidget={...e.inboxWidget,...t.inboxWidget}),void 0!==t.webPopups&&(s.webPopups={...e.webPopups,...t.webPopups}),void 0!==t.subscriptionWidget){const i=ae(e.subscribeWidget,t.subscribeWidget)??e.subscribeWidget;return s.subscribeWidget={...i,enable:!1},s.subscribePopup={...e.subscribePopup,enable:!1},s}const i=ae(e.subscribeWidget,t.subscribeWidget);return i&&(s.subscribeWidget=i),s}(this.rawInitParams,e);0!==Object.keys(t).length&&(this.initParams={...this.initParams,...t},await this.data.setInitParams(this.initParams))}async initPushNotifications(e){if(await this.data.setDefaultNotificationImage(e.defaultNotificationImage),await this.data.setDefaultNotificationTitle(e.defaultNotificationTitle),await this.data.setServiceWorkerUrl(e.serviceWorkerUrl),await this.data.setServiceWorkerScope(e.scope),await this.initDriver(),this.driver){if(this.isPushDisabled)return te.info('Pushwoosh: push notifications are disabled by the "pushNotifications" init param'),void await this.warnAboutKeptSubscription();try{await this.defaultProcess()}catch(e){te.error(e,"Internal error: defaultProcess fail")}}else te.info("Pushwoosh: push service driver was not created, skipping push initialization")}async warnAboutKeptSubscription(){const{pushToken:e}=await this.data.getTokens();e&&te.error('Pushwoosh: push notifications are disabled by the "pushNotifications" init param, but this device is still subscribed and will keep receiving notifications. Call Pushwoosh.unsubscribe() to unsubscribe it.')}async initDriver(){if(this.isLegacySafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new Ge(this.api,this.data,{webSitePushId:e})):void te.info("Safari push needs safariWebsitePushID in initParams; Safari 16+ can use web VAPID keys of the application instead.")}te.info({isAvailableServiceWorker:this.platformChecker.isAvailableServiceWorker}),this.platformChecker.isAvailableServiceWorker&&(this.driver=new ze(this.api,this.data,{}))}async sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window,s=function(){const{pathname:e}=window.location;try{return decodeURIComponent(e)}catch{return e}}(),i=await this.data.getDeviceType();this.api.postEvent(W,{url:t,path:s,title:e,device_type:i})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===u:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in L:this.eventBus.addEventHandler(L[e].name,s=>{const{prop:i}=L[e];t(this.api,i?s[i]:void 0)});break;default:s=!1}return s&&this.sdkUsage.recordLegacyEvent(e),s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case f:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case y:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case v:this.eventBus.dispatchEvent("hide-notification",{notification:t});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:t})}}}return t})());
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var i in s)("object"==typeof exports?exports:e)[i]=s[i]}}(this,()=>(()=>{"use strict";const e={d:(t,s)=>{for(var i in s)e.o(s,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:s[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Object.defineProperties(e,{[Symbol.toStringTag]:{value:"Module"},__esModule:{value:!0}})}};let t={};e.r(t),e.d(t,{Pushwoosh:()=>Ye});const s="/pushwoosh-service-worker.js",i="https://api.pushwoosh.com/json/1.3/",a="deviceRegistrationStatus",r="reportedPushPermissionStatus",n="registered",o="unregistered",c="granted",h="default",u="onReady",d="onSubscribe",l="onUnsubscribe",g="onRegister",p="onPermissionPrompt",m="onPermissionDenied",w="onPermissionGranted",b="onSWInitError",f="onPushDelivery",y="onNotificationClick",v="onNotificationClose",P="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",C="onUpdateInboxMessages",k="onShowNotificationPermissionDialog",I="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",E="onHideSubscriptionWidget",W="PW_SiteOpened",_="Pushwoosh: the SDK storage does not keep the hwid in this browser (in-app webview, private window or insecure context), so this device cannot be identified. Requests that need an hwid are not sent.",x=[210],T={autoSubscribe:!0,serviceWorkerUrl:s};function A(){return globalThis}function R(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const M=e=>"function"==typeof e;function N(e){const t=new WeakSet;return async s=>{if(t.has(s))return!1;const i=await function(e,t){let s;const i=new Promise(e=>{s=setTimeout(()=>e(!1),t)}),a=e.then(()=>!0,()=>!0);return Promise.race([a,i]).finally(()=>clearTimeout(s))}(s,e);return i||t.add(s),i}}const L={[g]:{name:"register"},[d]:{name:"subscribe"},[l]:{name:"unsubscribe"},[b]:{name:"initialize-service-worker-error",prop:"error"},[f]:{name:"receive-push",prop:"notification"},[y]:{name:"open-notification",prop:"notification"},[v]:{name:"hide-notification",prop:"notification"},[P]:{name:"change-enabled-communication",prop:"isEnabled"},[S]:{name:"receive-inbox-message",prop:"message"},[C]:{name:"update-inbox-messages",prop:"messages"},[k]:{name:"show-notification-permission-dialog"},[I]:{name:"hide-notification-permission-dialog",prop:"permission"},[D]:{name:"show-subscription-widget"},[E]:{name:"hide-subscription-widget"},[m]:{name:"permission-denied"},[p]:{name:"permission-default"},[w]:{name:"permission-granted"}},F="keyValue",U="messages",O="inboxMessages";function q(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const B=[q(F,function(e){e.createObjectStore(F,{keyPath:"key"})}),q("log",function(e){const t=e.createObjectStore("log",{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),q(U,function(e){e.createObjectStore(U,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),q(O,function(e){const t="status",s=e.createObjectStore(O,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class j{get all(){return B}}class V{constructor(e,t=new j){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function $(e,t){console.info("onversionchange",t),e.close()}let H;function K(){return H||(H=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=$.bind(null,i,t),e(i)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=$.bind(null,s,t);new V(s).applyMigrations()}})),H}function z(e){return K().then(t=>new Promise((s,i)=>e(t,s,i)))}class G{_add(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);a.onsuccess=()=>{s(e)},a.onerror=()=>{i(a.error)}}).then(e=>this.getAll().then(t=>{if(Array.isArray(t)){const s=t.map(e=>e.id).sort((e,t)=>e==t?0:e<t?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(e=>this.delete(e))).then(()=>e)}return e}))}delete(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);a.onsuccess=()=>{s(a.result)},a.onerror=()=>{i(a.error)}})}getAll(){return z((e,t,s)=>{const i=[],a=e.transaction(this.name).objectStore(this.name).openCursor();a.onsuccess=e=>{const s=e.target.result;s?(s.value&&i.push(s.value),s.continue()):t(i)},a.onerror=()=>{s(a.error)}})}}const J=(Y=F,{get:(e,t)=>z((s,i,a)=>{const r=s.transaction(Y).objectStore(Y).get(e);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(r.result?.value||t):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}),getAll:()=>z((e,t,s)=>{const i={},a=e.transaction(Y).objectStore(Y).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(i):o?s(a.error):r=setTimeout(c,0)};a.onsuccess=e=>{const t=e.target.result;t?(i[t.key]=t.value.value,t.continue()):n=!0},a.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...i}=t;await this.set(e,{...s,...i})},set:(e,t)=>z((s,i,a)=>{const r=s.transaction([Y],"readwrite").objectStore(Y).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(e):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})});var Y;const X=new class extends G{constructor(){super(...arguments),this.name="log",this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const i={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(i.stack=t.stack),s&&(i.additional=s),this._add(i)}},Q=new class extends G{constructor(){super(...arguments),this.name=U,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Z={error:1,info:2,debug:3};let ee=3;const te={setLevel(e){Z[e]||(e="error"),ee=Z[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),X.add(e,t,s)}};Object.keys(Z).forEach(e=>{const t=Z[e];te[e]=(...s)=>{t<=ee&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class se{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter(e=>e!==t))},this.dispatchEvent=(e,t)=>{const s=t.eventId||R(),i=this.handlers[e];return i?(i.forEach(e=>{M(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}const ie=["autoSubscribe","defaultNotificationTitle","defaultNotificationImage","safariWebsitePushID","unifiedPlatform","subscriptionWidget"];function ae(e,t){if(t)return{...e,...t}}const re=[...Object.keys({applicationCode:!0,apiToken:!0,communicationEnabled:!0,serviceWorkerUrl:!0,safariWebsitePushID:!0,autoSubscribe:!0,pushNotifications:!0,pushwooshUrl:!0,defaultNotificationImage:!0,defaultNotificationTitle:!0,logLevel:!0,userId:!0,email:!0,smsNumber:!0,whatsAppNumber:!0,scope:!0,tags:!0,subscribeWidget:!0,inboxWidget:!0,subscribePopup:!0,subscriptionWidget:!0,webPopups:!0,webPlacements:!0,recommendations:!0,webSDKPath:!0,unifiedPlatform:!0}),"pushwooshApiUrl"],ne=["subscribeWidget","subscribePopup","inboxWidget","webPopups","webPlacements"],oe=e=>{const t=e.toLowerCase();let s,i=3;return re.forEach(e=>{const a=((e,t)=>{let s=Array.from({length:t.length+1},(e,t)=>t);for(let i=1;i<=e.length;i++){const a=[i];for(let r=1;r<=t.length;r++)a[r]=Math.min(s[r]+1,a[r-1]+1,s[r-1]+(e[i-1]===t[r-1]?0:1));s=a}return s[t.length]})(t,e.toLowerCase());a<i&&(s=e,i=a)}),s};function ce(e){const t=[];return Object.entries(e).forEach(([e,s])=>{re.includes(e)?ne.includes(e)&&(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(s)&&"enabled"in s&&!("enable"in s)&&t.push({key:`${e}.enabled`,suggestion:`${e}.enable`}):t.push({key:e,suggestion:oe(e)})}),t}function he(){const{pathname:e}=window.location;try{return decodeURIComponent(e)}catch{return e}}class ue{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 de=["classic","captioned","banner","carousel"];function le(e){return(Array.isArray(e)?e:[]).filter(e=>!!e&&!!e.imageUrl).slice(0,5)}const ge=/^(?:javascript|vbscript|data|blob|file):/i,pe=/^[a-z][a-z\d+\-.]*:/i;function me(e){return e.split("").filter(e=>e.charCodeAt(0)>32&&127!==e.charCodeAt(0)).join("")}function we(e){const t=me(e);return pe.test(t)&&!ge.test(t)}function be(e,t){return t||e.image||""}function fe(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 ye{constructor(e,t,s,i={},a=()=>Promise.resolve(void 0),r=new ue){this.data=e,this.api=t,this.inboxModel=s,this.moduleRegistry=i,this.loadWebPopups=a,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(e){try{return JSON.parse(e)||{}}catch(t){return te.write("error",`Pushwoosh: cannot parse inbox action_params: ${e}`,t),{}}}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const i=[],a=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,i.push(t),a.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(i),await Promise.all(a)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:i,send_date:a,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(t),h=function(e){const t=e?.u;if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)||{}}catch{return{}}return"object"==typeof t?t:{}}(c),u=function(e){return(Array.isArray(e.carousel)?e.carousel:[]).filter(e=>!!e&&!!e.image).slice(0,5).map(e=>({imageUrl:e.image,caption:e.title||"",link:e.url&&we(e.url)?e.url:""}))}(h),d=function(e,t,s){return e?.b||s||t.image||""}(c,h,s),l=function(e){const t=!!e.title,s=!!e.body,i=function(e){return e.bannerUrl||e.iconUrl||""}(e);let a=e.layoutType;switch(de.includes(a)||(a=e.bannerUrl&&!t?"banner":e.bannerUrl&&t&&s?"captioned":"classic"),a){case"banner":return i?"banner":"classic";case"captioned":return i&&t&&s?"captioned":"classic";case"carousel":return t&&s&&le(e.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:i,body:n,iconUrl:be(h,s),bannerUrl:c.b,layoutType:h.displayType,carousel:u}),g=be(h,s)||await this.data.getDefaultNotificationImage(),p=i||await this.data.getDefaultNotificationTitle();return this.dateModule.date=new Date(1e3*parseInt(a)),{title:p,imageUrl:g,iconUrl:g,heroUrl:d,layout:l,carousel:u,customData:fe(h),webPopupCode:c.wp||"",code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,c),link:c?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10)).sort((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=this.parseActionParams(t.action_params),i=this.messageTypeFactory(t.action_type,s),a=2===i||3===i;var r;!await this.showWebPopup(s.wp)&&a&&null!=s.l&&((r=s.l)&&!ge.test(me(r)))&&(document.location.href=s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async showWebPopup(e){if(!e)return!1;try{const t=this.moduleRegistry.webPopups??await this.loadWebPopups();return t?await t.show(e):(te.write("error",`Pushwoosh: inbox message opens web popup "${e}", but the web popups widget could not be loaded`),!1)}catch(t){return te.write("error",`Pushwoosh: failed to open web popup "${e}" from inbox`,t),!1}}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class ve{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{i(e.error)}})}readRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target;s(i.result||t)},e.onerror=()=>{i(e.error)}})}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target.result;i?(t.push(i.value),i.continue()):s(t)},e.onerror=()=>{i(e.error)}})}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class Pe{getDB(){return K()}async put(e,t,s){const i=await this.getDB();return new ve(i,e).put(t,s)}async delete(e,t){const s=await this.getDB();return new ve(s,e).delete(t)}async get(e,t,s){const i=await this.getDB();return new ve(i,e).get(t,s)}async getAll(e){const t=await this.getDB(),s=new ve(t,e);return await s.getAll()||[]}async count(e,t){const s=await this.getDB();return new ve(s,e).count(t)}async countByIndex(e,t,s){const i=await this.getDB(),a=new ve(i,e);return a.index=t,a.countByIndex(s)}}class Se{constructor(e,t,s,i=new Pe,a=new ue){this.eventBus=e,this.data=t,this.api=s,this.storage=i,this.storeName="inboxMessages",this.dateModule=a}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map(async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)});return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map(e=>this.putMessage(e));return Promise.all(t)}deleteMessages(e){const t=e.map(e=>this.storage.delete(this.storeName,e));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter(t=>t.rt<e).map(e=>e.inbox_id);return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>2===e.status||3===e.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>1===e.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new ye(this.data,this.api,this)})}}class Ce extends Error{constructor(e,t){super(e),this.name="ApiRequestError",this.statusCode=t}}const ke=e=>`params.${e}`;class Ie{constructor(e=J){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const t of e)await this.store.set(ke(t),void 0)}async setApplicationCode(e){await this.store.set(ke("applicationCode"),e)}async getApplicationCode(){return this.store.get(ke("applicationCode"))}async setApiToken(e){return await this.store.set(ke("apiToken"),e)}async getApiToken(){return this.store.get(ke("apiToken"))}async setHwid(e){await this.store.set(ke("hwid"),e)}async getHwid(){return this.store.get(ke("hwid"))}async setDeviceType(e){await this.store.set(ke("deviceType"),e)}async getDeviceType(){return this.store.get(ke("deviceType"))}async setFormFactor(e){await this.store.set(ke("formFactor"),e)}async getFormFactor(){return this.store.get(ke("formFactor"))}async setDeviceModel(e){await this.store.set(ke("deviceModel"),e)}async getDeviceModel(){return this.store.get(ke("deviceModel"))}async setLanguage(e){await this.store.set(ke("language"),e)}async getLanguage(){return this.store.get(ke("language"),"en")}async setStatusLanguageWasChanged(e){await this.store.set(ke("languageWasChanged"),e)}async getStatusLanguageWasChanged(){return this.store.get(ke("languageWasChanged"),!1)}async setApiEntrypoint(e){await this.store.set(ke("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(ke("apiEntrypoint"),i)}async setTokens(e){await this.store.set(ke("tokens"),e)}getTokens(){return this.store.get(ke("tokens"))}async setApplicationServerKey(e){await this.store.set(ke("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(ke("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(ke("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(ke("isVapidChanged"),!1)}async setWebVapidConfigured(e){await this.store.set(ke("webVapidConfigured"),e)}async getWebVapidConfigured(){return this.store.get(ke("webVapidConfigured"),!1)}async setWebSitePushId(e){await this.store.set(ke("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(ke("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(ke("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(ke("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(ke("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(ke("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(ke("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(ke("userId"))}async getFeatureFlags(){return this.store.get(ke("featureFlags"))}async setFeatureFlags(e){await this.store.set(ke("featureFlags"),e)}async getFeatureFlagImpressions(){return this.store.get(ke("featureFlagImpressions"),{})}async setFeatureFlagImpressions(e){await this.store.set(ke("featureFlagImpressions"),e)}async setStatusUserIdWasChanged(e){await this.store.set(ke("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(ke("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(ke("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(ke("email"))}async setStatusEmailWasChanged(e){await this.store.set(ke("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(ke("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(ke("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(ke("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(ke("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(ke("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(ke("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(ke("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(ke("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(ke("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(ke("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(ke("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(ke("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(ke("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(ke("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(ke("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(ke("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(ke("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(ke("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(ke("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(ke("sdkVersion"),e)}async getSdkVersion(){return this.store.get(ke("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(ke("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(ke("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(ke("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(ke("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(ke("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(ke("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(ke("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(ke("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(ke("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(ke("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(ke("features"),e)}async getFeatures(){return this.store.get(ke("features"))}async setInitParams(e){await this.store.set(ke("init"),e)}async getInitParams(){return this.store.get(ke("init"))}async setInboxLastRequestCode(e){await this.store.set(ke("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(ke("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(ke("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(ke("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(ke("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(ke("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(ke("delayedEvent"),e)}getDelayedEvent(){return this.store.get(ke("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(ke("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(ke("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(ke("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(ke("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(e){await this.store.set(ke("subscriptionWidgetHistory"),e)}async getSubscriptionWidgetHistory(){return this.store.get(ke("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(e){await this.store.set(ke("logLevel"),e)}async getLogLevel(){return this.store.get(ke("logLevel"),"error")}async getShownWebPopups(){return this.store.get(ke("shownWebPopups"),[])}async addShownWebPopup(e){const t=await this.getShownWebPopups();t.includes(e)||(t.push(e),await this.store.set(ke("shownWebPopups"),t))}async setIsRecurringVisitor(e){await this.store.set(ke("isRecurringVisitor"),e)}async getIsRecurringVisitor(){return this.store.get(ke("isRecurringVisitor"),!1)}}class De{constructor(e=new Ie,t=te){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}getPopupForms(e){return this.createRequest("getPopupForms",e)}getPopupFormContent(e){return this.createRequest("getPopupFormContent",e)}recordPopupFormEvent(e){return this.createRequest("recordPopupFormEvent",e)}submitPopupForm(e){return this.createRequest("submitPopupForm",e)}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 i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=i+e,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:A().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n,keepalive:s.keepalive}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(e){if(200!==e.status){let t,s=`status: ${e.status}. statusText: ${e.statusText}.`;try{const i=await e.json();i&&"number"==typeof i.status_code&&(t=i.status_code),i&&i.status_message&&(s+=` status_code: ${i.status_code}. status_message: ${i.status_message}.`)}catch(e){}throw new Ce(s,t)}const t=await e.json();if(200!==t.status_code)throw new Ce(`Error code: ${t.status_code}. Error text: ${t.status_message}`,"number"==typeof t.status_code?t.status_code:void 0);return t}}class Ee{constructor(e,t=new Ie,s=new De,i=()=>!1,a=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=N(1e4),this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=i,this.getInitUserId=a,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(e=>{throw this.checkDevicePromise=null,e})),this.checkDevicePromise}async requestCheckDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(a);if(null===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,e&&s?n:o),t=localStorage.getItem(a)}return t===n}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(e=>{throw this.ensureDeviceRegisteredPromise=null,e})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:e}=await this.checkDevice();if(e)return!1;const t=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t),!0}async reportPushPermissionStatus(e=!1){const t=this.getPushPermissionStatus();if(t&&t!==this.reportingPushPermissionStatus&&t!==localStorage.getItem(r)){this.reportingPushPermissionStatus=t;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!e&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t)}finally{this.reportingPushPermissionStatus===t&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(r)}rememberReportedPushPermissionStatus(e){e&&localStorage.setItem(r,e)}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const t=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...e,push_permission_status:t,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(t),s}async registerDevice(){const e=this.requestRegisterDevice();this.registerDevicePromise=e;try{return await e}finally{this.registerDevicePromise===e&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),t=await this.data.getTokens();if(!t.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=this.getPushPermissionStatus(),i=await this.apiClient.registerDevice({...e,push_permission_status:s,locale:await this.getLocale(),page:he(),push_token:t.pushToken,auth_token:t.authToken,public_key:t.publicKey});return this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(s),await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{}),i}async unregisterDevice(){const e=await this.getRequestParams(),t=await this.apiClient.unregisterDevice(e);return this.checkDevicePromise=null,localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...i,hash:e,metaData:s})}async pushStat(e,t,s={},i){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:e,metaData:s,...i?{button_id:i}:{}})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...i}=await this.getRequestParams(),a=await this.data.getEmail();return a&&await this.apiClient.setEmailTags({...i,email:a,tags:e}),this.apiClient.setTags({...i,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async setLanguage(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:e}))}async setLocale(e){if(!e)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const t=We(e.trim().replace(/_/g,"-"));t&&(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return We(await this.data.getLanguage())||void 0}async registerUser(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:i,...a}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${e}`,o=await this.data.getUserId(),c=await this.apiClient.registerUser({...a,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),n&&n!==o&&this.eventBus.dispatchEvent("change-user-id",{userId:n}),t&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),i=await this.apiClient.registerEmail({...s,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),i}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),a}async registerWhatsappNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),a}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:e})}async recordPopupFormEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:e,event:t};return this.apiClient.recordPopupFormEvent(3===t?{...s,clickId:R()}:s)}async 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 i=await this.getRequestParams(),a=new Date,r=a.getTime(),n=Math.floor(r/1e3),o=n-a.getTimezoneOffset()/60*3600,c=await this.data.getLastOpenMessage();if(c&&c.expiry>Date.now()){if(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const h=await this.apiClient.postEvent({...i,event:e,timestampUTC:n,timestampCurrent:o,attributes:t},s);return h&&h.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:h.code}),h?.web_placements?.length&&this.eventBus.dispatchEvent("receive-web-placements",{placements:h.web_placements}),h}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),i=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:i})}async inboxStatus(e,t){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:e,status:t,time:(new Date).getTime()})}async multiRegisterDevice(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const t=await this.data.getApplicationCode(),s=await this.data.getDeviceModel(),i=await this.data.getDeviceType(),r=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),h=await this.data.getHwid();!e.push_devices&&c.pushToken&&await this.requireHwid();const u={application:t,...e};if(e.user_id){u.user_id=String(e.user_id);await this.data.getUserId()!==u.user_id&&(await this.data.setUserId(u.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(e.email){if(!/^\S+@\S+\.\S+$/.test(e.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==e.email&&(await this.data.setEmail(e.email),await this.data.setStatusEmailWasChanged(!0))}if(e.sms_phone_number){if(!/^\+?[0-9]+$/.test(e.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==e.sms_phone_number&&(await this.data.setSmsNumber(e.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(e.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(e.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==e.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(e.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(u.language?(await this.data.setLanguage(u.language),await this.data.setStatusLanguageWasChanged(!0)):u.language=r,!u.timezone){const e=60*-(new Date).getTimezoneOffset();u.timezone=String(e)}if(!u.push_devices&&c.pushToken){const e={hwid:h,platform:i,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||s){const t={};c.publicKey&&(t.public_key=c.publicKey),c.authToken&&(t.auth_token=c.authToken),s&&(t.browser=s),e.platformData=t}u.push_devices=[e]}const d=await this.apiClient.multiRegisterDevice(u);return u.push_devices?.length&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const e=await this.requireHwid(),t=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:e,device_type:t}}async getIdentityRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),i=await this.data.getDeviceModel(),a=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!t)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:e,userId:s||t,device_model:i,timezone:n,language:a,v:r}}async requireHwid(){const e=await this.data.getHwid();if(!e)throw new Error(_);return e}}function We(e){try{return e?Intl.getCanonicalLocales(e)[0]??"":""}catch{return""}}class _e{constructor(e,t,s,i){this.key=e,this.enabled=t,this.ruleId=s,this.properties=i}getString(e,t){const s=this.properties[e];return"string"==typeof s?s:t}getNumber(e,t){const s=this.properties[e];return"number"==typeof s&&Number.isFinite(s)?s:t}getBool(e,t){const s=this.properties[e];return"boolean"==typeof s?s:t}getJson(e,t){const s=this.properties[e];return s??t}getProperties(){return{...this.properties}}}class xe extends Error{constructor(e,t){super(e),this.name="FeatureFlagsError",this.httpStatus=t}}const Te=/json\/1\.3\/?$/,Ae="api/v2/device-api/getFeatureFlags";const Re=18e5;class Me{constructor(e){this.listeners=new Set,this.pageImpressions=new Set,this.isMemoryOnly=!1,this.applicationCode="",this.userId="",this.lastRequestAt=0,this.lastSentUnregistered=!1,this.generation=0,this.isStarted=!1,this.isLoaded=!1,this.isActivated=!1,this.userChangedWhileLoading=!1,this.deps={fetch:(e,t)=>fetch(e,t),now:()=>Date.now(),...e},this.deps.eventBus.addEventHandler("change-user-id",({userId:e})=>this.onUserChanged(e)),this.deps.eventBus.addEventHandler("register",()=>this.onRegistered())}async start(){if(this.isStarted)return;this.isStarted=!0,this.applicationCode=await this.deps.data.getApplicationCode()||"";const e=await this.deps.data.getUserId()||"";this.userChangedWhileLoading||(this.userId=e);const t=await this.deps.data.getFeatureFlags();t&&t.applicationCode===this.applicationCode&&(this.cache=t),this.isLoaded=!0,this.isActivated&&(""!==this.visibleSnapshot()&&this.notify(),this.refreshOnPageLoad())}get(e){if(this.activate(),!this.cache||!this.hasValidCache())return null;const t=this.cache.flags[e];return t?new _e(e,t.enabled,t.rule_id,t.properties):null}isEnabled(e,t){const s=this.get(e);return s?s.enabled:t}refresh(){return this.activate(),this.hasValidCache()&&this.deps.now()-this.lastRequestAt<3e5?Promise.resolve():this.send()}reset(){clearTimeout(this.timer),this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.isStarted=!1,this.isLoaded=!1,this.userChangedWhileLoading=!1}addUpdateListener(e){this.activate(),this.listeners.add(e)}removeUpdateListener(e){this.listeners.delete(e)}async logImpression(e){const t=this.get(e);if(!t||this.deps.isCommunicationDisabled())return;const s=`${e}|${t.ruleId}|${t.enabled}`;if(!this.pageImpressions.has(s)){this.pageImpressions.add(s);try{await this.sendImpression(t,s)}catch(e){this.pageImpressions.delete(s),te.error(e,"Pushwoosh: feature flag impression was not sent")}}}async sendImpression(e,t){const s=this.deps.now(),i=await this.deps.data.getFeatureFlagImpressions();if(!(void 0!==i[t]&&s-i[t]<Re)){await this.deps.data.setFeatureFlagImpressions({...Fe(i,s),[t]:s});try{await this.deps.postEvent("PW_FeatureFlagImpression",{flag_key:e.key,rule_id:e.ruleId,enabled:e.enabled})}catch(e){const s=await this.deps.data.getFeatureFlagImpressions().catch(()=>{});throw s&&(delete s[t],await this.deps.data.setFeatureFlagImpressions(s).catch(()=>{})),e}}}onUserChanged(e){if(!this.isLoaded)return this.userId=e,void(this.userChangedWhileLoading=!0);e!==this.userId&&(this.userId=e,this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.deps.data.setFeatureFlags(void 0),this.isActivated&&this.sendAfterInFlight())}onRegistered(){const e=!!this.cache&&!!this.cache.sentUnregistered;this.isLoaded&&this.isActivated&&(this.lastSentUnregistered||e)&&this.sendAfterInFlight()}activate(){this.isActivated||(this.isActivated=!0,this.isLoaded&&this.refreshOnPageLoad())}refreshOnPageLoad(){const e=this.cache?this.deps.now()-this.cache.fetchedAt:1/0,t=!!this.cache&&!!this.cache.sentUnregistered&&this.deps.isDeviceRegistered();!this.hasValidCache()||e>9e5||t?this.sendInBackground():this.schedulePeriodicRefresh()}sendAfterInFlight(){(this.inFlight||Promise.resolve()).catch(()=>{}).then(()=>this.sendInBackground())}sendInBackground(){this.send().catch(e=>te.error(e,"Pushwoosh: feature flags refresh failed"))}send(){return this.inFlight||(this.inFlight=this.request().finally(()=>{this.inFlight=void 0,this.schedulePeriodicRefresh()})),this.inFlight}async request(){if(this.lastRequestAt=this.deps.now(),this.deps.isCommunicationDisabled())throw new xe("Communication is disabled",0);const e=this.generation,t=await this.deps.data.getHwid();if(!t||!this.applicationCode)throw new xe("Pushwoosh SDK is not initialized",0);const s={application:this.applicationCode,hwid:t};this.cache&&this.hasValidCache()&&this.cache.etag&&(s.etag=this.cache.etag);const a=function(e){const t=e||i;if(Te.test(t))return t.replace(Te,Ae);try{return`${new URL(t).origin}/${Ae}`}catch(e){return i.replace(Te,Ae)}}(await this.deps.data.getApiEntrypoint()),r=await this.deps.data.getApiToken(),n={method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",...r?{Authorization:`Token ${r}`}:{}},body:JSON.stringify(s),...r?{credentials:"include"}:{}};let o,c;this.lastSentUnregistered=!this.deps.isDeviceRegistered();try{o=await this.deps.fetch(a,n)}catch(e){throw new xe(`getFeatureFlags request failed: ${e instanceof Error?e.message:String(e)}`,0)}if(200!==o.status)throw new xe(`getFeatureFlags answered HTTP ${o.status}`,o.status);try{c=await o.json()}catch(e){throw new xe("getFeatureFlags answered an unreadable body",o.status)}if(!c||200!==c.status_code||!Ne(c.response))throw new xe(`getFeatureFlags answered status_code ${String(c&&c.status_code)}`,o.status);e===this.generation&&await this.apply(c.response)}async apply(e){const t=this.visibleSnapshot(),s=this.deps.now();if(!0===e.not_modified){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return;this.cache={...this.cache,fetchedAt:s,sentUnregistered:this.lastSentUnregistered},this.isMemoryOnly||await this.deps.data.setFeatureFlags(this.cache)}else if(!0===e.partial){if(this.hasValidCache())return;this.cache=this.newCache(e,"",s),this.isMemoryOnly=!0}else this.cache=this.newCache(e,"string"==typeof e.etag?e.etag:"",s),this.isMemoryOnly=!1,await this.deps.data.setFeatureFlags(this.cache);this.visibleSnapshot()!==t&&this.notify()}newCache(e,t,s){return{applicationCode:this.applicationCode,userId:this.userId,flags:Le(e.flags),etag:t,fetchedAt:s,sentUnregistered:this.lastSentUnregistered}}notify(){this.listeners.forEach(e=>{try{e()}catch(e){te.error(e,"Pushwoosh: feature flags update listener failed")}})}schedulePeriodicRefresh(){if(!this.isLoaded)return;clearTimeout(this.timer);const e=Math.max(this.lastRequestAt,this.cache?this.cache.fetchedAt:0),t=Math.max(0,e+36e5-this.deps.now());this.timer=setTimeout(()=>this.sendInBackground(),t)}hasValidCache(){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return!1;const e=this.deps.now()-this.cache.fetchedAt;return e>=0&&e<=864e5}isCacheOfCurrentUser(e){return e.applicationCode===this.applicationCode&&e.userId===this.userId}visibleSnapshot(){return this.cache&&this.hasValidCache()?Ue(this.cache.flags):""}}function Ne(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Le(e){const t={};return Ne(e)?(Object.keys(e).forEach(s=>{const i=e[s];Ne(i)&&"boolean"==typeof i.enabled&&(t[s]={enabled:i.enabled,rule_id:"string"==typeof i.rule_id?i.rule_id:"",properties:Ne(i.properties)?i.properties:{}})}),t):t}function Fe(e,t){const s={};return Object.keys(e).forEach(i=>{t-e[i]<Re&&(s[i]=e[i])}),s}function Ue(e){return Array.isArray(e)?`[${e.map(Ue).join(",")}]`:Ne(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ue(e[t])}`).join(",")}}`:JSON.stringify(e)}class Oe{constructor(e){this.global=e,this._isSafari=this.isSafariBrowser(),this._isOpera=this.isOperaBrowser(),this._isEdge=this.isEdgeBrowser(),this._isFirefox=this.isFirefoxBrowser(),this._isChrome=this.isChromeBrowser(),this._isMacOS=this.isMacOS(),this._isAvailableServiceWorker=this.canUseServiceWorkers(),this._isAvailableNotifications=this.canReceiveNotifications(),this._platform=this.getPlatformType(),this._browserVersion=this.getBrowserVersion(),this._formFactor=this.getFormFactor()}get isEdge(){return this._isEdge}get isSafari(){return this._isSafari}get isOpera(){return this._isOpera}get isAvailableServiceWorker(){return this._isAvailableServiceWorker}get isAvailableNotifications(){return this._isAvailableNotifications}get platform(){return this._platform}get browserVersion(){return this._browserVersion}get formFactor(){return this._formFactor}get isMobile(){return"MOBILE"===this._formFactor}get isDesktop(){return"DESKTOP"===this._formFactor}isSafariBrowser(){return"safari"in this.global&&navigator.userAgent.indexOf("Safari")>-1}isOperaBrowser(){return-1!==navigator.userAgent.indexOf("Opera")||-1!==navigator.userAgent.indexOf("OPR")}isEdgeBrowser(){return navigator.userAgent.indexOf("Edge")>-1}isFirefoxBrowser(){return-1!==navigator.userAgent.toLowerCase().indexOf("firefox")}isChromeBrowser(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!this._isOpera&&!this._isEdge}isMacOS(){return"platform"in navigator&&-1!==navigator.platform.toLowerCase().indexOf("mac")}canUseServiceWorkers(){return!!navigator.serviceWorker&&"PushManager"in this.global&&"Notification"in this.global}canReceiveNotifications(){return this._isSafari&&this._isMacOS||this._isAvailableServiceWorker&&!this._isEdge}getPlatformType(){let e=11;switch(!0){case this._isSafari:e=10;break;case this._isOpera||this._isChrome:e=11;break;case this._isFirefox:e=12;break;case this._isEdge:e=150}return e}getFormFactor(){const e=navigator.userAgentData;if(e&&"boolean"==typeof e.mobile)return e.mobile?"MOBILE":"DESKTOP";return/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?"MOBILE":"DESKTOP"}getBrowserVersion(){const{userAgent:e}=navigator,t=e.match(/\bOPR\/(\d+)/);if(null!==t)return`Opera ${t[1]}`;const s=e.match(/\bEdge\/(\d+)/);if(null!==s)return`Edge ${s[1]}`;const i=e.match(/\bEdg\/(\d+)/);if(null!==i)return`Edge ${i[1]}`;let a=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[];const[,r=""]=a;a=a[2]?[r,a[2]]:[navigator.appName,navigator.appVersion,"-?"];const n=e.match(/version\/([.\d]+)/i);return null!==n&&a.splice(1,1,n[1]),a.join(" ")}}const qe="pushwoosh-recommendations-views";function Be(){try{if("undefined"!=typeof sessionStorage)return sessionStorage}catch{}const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,s)=>{e.set(t,s)}}}class je{constructor(e){this.deps={fetch:(...e)=>fetch(...e),now:Date.now,storage:Be(),...e}}async trackProductView(e){!e?.id||this.deps.isCommunicationDisabled()||this.seenRecently(String(e.id))||await this.deps.postEvent("PW_ProductView",{productId:String(e.id),name:e.name,price:e.price,currency:e.currency,category:e.category,productUrl:e.url,imageUrl:e.imageUrl})}async fetch(e){const t=new URLSearchParams({application:await this.deps.getApplicationCode(),strategy:e.strategy});e.fallback&&t.set("fallback",e.fallback),e.limit&&t.set("limit",String(e.limit)),e.productId&&t.set("product_id",e.productId),e.exclude?.length&&t.set("exclude",e.exclude.join(",")),e.block&&t.set("block",e.block);const s={},i=this.deps.isCommunicationDisabled()?"":await this.deps.getHwid();i&&(s["X-PW-HWID"]=i);const a=(this.deps.getEndpoint()||"https://recommender-onsite.svc-nue.pushwoosh.com").replace(/\/+$/,""),r=await this.deps.fetch(`${a}/feed/v1/onsite/products.json?${t}`,{headers:s});if(!r.ok)throw new Error(`Pushwoosh: recommendations request failed with status ${r.status}`);return r.json()}async trackClick(e){e?.productId&&!this.deps.isCommunicationDisabled()&&await this.deps.postEvent("PW_RecommendationClick",{block:e.block,strategy:e.strategy,recoProductId:String(e.productId),position:e.position},{keepalive:!0})}seenRecently(e){const t=this.deps.now(),s=function(e){try{const t=JSON.parse(e||"{}");return null===t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,e])=>"number"==typeof e))}catch{return{}}}(this.deps.storage.getItem(qe));if(t-(s[e]??-1/0)<3e4)return!0;const i={[e]:t};Object.keys(s).forEach(e=>{t-s[e]<3e4&&(i[e]=s[e])});try{this.deps.storage.setItem(qe,JSON.stringify(i))}catch{}return!1}}const Ve="sdkUsageReportedOn";class $e{constructor(){this.initKeys=new Set,this.events=new Set,this.legacyEvents=new Set,this.isListening=!1}recordInitParams(e){Object.entries(e).forEach(([e,t])=>{this.initKeys.add(e),(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(t)&&Object.keys(t).forEach(t=>this.initKeys.add(`${e}.${t}`))})}recordEvent(e){this.events.add(e)}recordLegacyEvent(e){this.legacyEvents.add(e)}listen(e){if(this.isListening)return;this.isListening=!0;const t=()=>this.flush(e);document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&t()}),window.addEventListener("pagehide",t)}flush(e){const t=(new Date).toISOString().slice(0,10);try{if(localStorage.getItem(Ve)===t)return;localStorage.setItem(Ve,t)}catch{return}e({init_keys:[...this.initKeys],events:[...this.events],legacy_events:[...this.legacyEvents]},{keepalive:!0}).catch(()=>{})}}function He(e){switch(e){case c:return"granted_explicit";case"denied":return"denied";default:return"not_determined"}}function Ke(e){return"safari"in e?e.safari?.pushNotification:void 0}function ze(e,t){try{return Ke(e)?.permission(t)}catch{return}}class Ge{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return this.data.getStatusManualUnsubscribed()}async askPermission(){await Notification.requestPermission()}async getTokens(){return this.data.getTokens()}async subscribe(e){const t=e||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),i=t.getKey("p256dh"),a=t.getKey("auth");if(!i||!a)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(i))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(a)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t&&(await this.data.setLastPermissionStatus(t),void 0!==e))return!0;const s=await this.getCredentials(),i=this.getPushToken(s),a=await this.data.getTokens(),r=i===(a&&a.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${R()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),i=new Uint8Array(s.length);for(let e=0;e<s.length;++e)i[e]=s.charCodeAt(e);return i}}class Je{constructor(e,t,s){this.api=e,this.config=s,this.data=t}getPermission(){const{permission:e}=this.getPermissionInfo();return e}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const e={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise(t=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,e,()=>t())})}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const{deviceToken:e}=this.getPermissionInfo();await this.data.setTokens({pushToken:e}),await this.api.registerDevice()}async unsubscribe(){await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getWebSitePushId(),t=void 0!==e&&this.config.webSitePushId!==e;await this.data.setWebSitePushId(this.config.webSitePushId);const s=await this.data.getLastPermissionStatus(),i=this.getPermission();return s!==i&&(await this.data.setLastPermissionStatus(i),void 0!==s)||t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class Ye{constructor(){this.ready=!1,this.rawInitParams={},this.isPushDisabled=!1,this.isInitAborted=!1,this.isPushPermissionWatched=!1,this.subscriptionInFlight=null,this.isWebVapidConfigured=!1,this.isLegacySafari=!1,this.waitForPermissionWork=N(1e4),this.moduleRegistry={},this.sdkUsage=new $e,this.pendingWebPlacements=[],this.webPlacementsSink=null,this.addEventHandler=(e,t)=>{this.sdkUsage.recordEvent(e),this.eventBus.addEventHandler(e,t)},this.addSdkEventHandler=(e,t)=>this.eventBus.addEventHandler(e,t),this.removeEventHandler=(e,t)=>this.eventBus.removeEventHandler(e,t),this.dispatchEvent=(e,t)=>this.eventBus.dispatchEvent(e,t),this.debug={async showLog(){const e=await X.getAll();console.log(e)},async showKeyValues(){const e=await J.getAll();console.log(e)},async showMessages(){(await Q.getAll()).forEach(e=>console.log(e))}},this.eventBus=new se,this.data=new Ie,this.apiClient=new De(this.data),this.api=new Ee(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled,()=>this.getInitUserId(),()=>this.getPushPermissionStatus()),this.featureFlags=new Me({eventBus:this.eventBus,data:this.data,postEvent:(e,t)=>this.api.postEvent(e,t),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,isDeviceRegistered:()=>this.isDeviceRegistered()}),this.recommendations=new je({postEvent:(e,t,s)=>this.api.postEvent(e,t,s),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,getApplicationCode:()=>this.data.getApplicationCode(),getHwid:()=>this.data.getHwid(),getEndpoint:()=>this.initParams?.recommendations?.endpoint}),this.platformChecker=new Oe(A()),this.inboxModel=new Se(this.eventBus,this.data,this.api),this.pwinbox=new ye(this.data,this.api,this.inboxModel,this.moduleRegistry,()=>this.loadWebPopupsWidget()),this.eventBus.addEventHandler("receive-web-placements",({placements:e})=>this.deliverWebPlacements(e))}takeWebPlacements(){const e=this.pendingWebPlacements;return this.pendingWebPlacements=[],e}deliverWebPlacements(e){!1!==this.initParams?.webPlacements?.enable&&(this.webPlacementsSink?this.webPlacementsSink(e):(this.pendingWebPlacements.push(...e),this.loadWebPopupsWidget().catch(e=>{te.error(e,"Pushwoosh: failed to load the web popups widget for journey placements")})))}async loadWebPopupsWidget(){if(this.moduleRegistry.webPopups||!this.widgetLoader||!1===this.initParams?.webPopups?.enable)return this.moduleRegistry.webPopups;let e;const t=new Promise(t=>{e=setTimeout(()=>t(!1),1e4)});return await Promise.race([this.widgetLoader("web-popups"),t]),clearTimeout(e),this.moduleRegistry.webPopups}push(e){if(M(e))this.subscribeToLegacyEvents(u,e);else{if(!Array.isArray(e))throw new Error("Invalid command!");if("init"===e[0])this.initialize(e[1]).catch(e=>{console.error("Pushwoosh: Error during initialization",e)});else if(!this.subscribeToLegacyEvents(e[0],e[1]))throw console.log("Pushwoosh: Unknown command",e),new Error("Unknown command!")}}async subscribe(e=!0){const t=this.runSubscribe(e);this.subscriptionInFlight=t;try{await t}finally{this.subscriptionInFlight===t&&(this.subscriptionInFlight=null)}}async runSubscribe(e){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.isPushDisabled)throw new Error('Push notifications are disabled by the "pushNotifications" init param!');const t=this.requireDriver();if(t.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await t.askPermission();const e=t.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e}),e!==h&&this.announcePermissionChange(e)}const s=t.getPermission(),i=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(s===c){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!i||e)&&await t.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if("denied"===s)return this.eventBus.dispatchEvent("permission-denied",{}),a&&await t.unsubscribe(),void this.reportPushPermissionChangeInBackground()}async unsubscribe(){try{await this.requireDriver().unsubscribe()}catch(e){throw te.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===n}isDeviceUnregistered(){return localStorage.getItem(a)===o}async isSubscribed(){return this.api.checkDeviceSubscribeForPushNotifications()}async isCommunicationEnabled(){return!await this.data.getStatusCommunicationDisabled()}async setCommunicationEnabled(e=!0){if(await this.data.setCommunicationEnabled(e),e){this.isCommunicationDisabled=!1,await this.data.setStatusDropAllData(!1),await this.finishInit();const e=this.driver?.checkIsPermissionGranted();e&&(await this.api.registerDevice(),await this.sendData())}else this.featureFlags.reset(),await this.api.unregisterDevice();this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:e});const t=await this.data.getDeviceType();await this.api.postEvent("GDPRConsent",{channel:e,device_type:t})}async removeAllDeviceData(){const e=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:e}),await this.api.deleteDevice(),await this.data.clearAll(),this.featureFlags.reset(),await this.data.setStatusDropAllData(!0)}trackProductView(e){return this.recommendations.trackProductView(e)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:e}=await this.data.getTokens();return e}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return this.platformChecker.isAvailableNotifications}isPushAvailable(){return!!this.driver&&!this.isPushDisabled}requireDriver(){if(!this.driver)throw new Error("Push notifications are not available: the browser does not support them, or the application has no push configuration. Web popups, inbox, events and tags do not require it.");return this.driver}async initialize(e){this.rawInitParams={...e},this.sdkUsage.recordInitParams(e),function(e){ce(e).forEach(({key:e,suggestion:t})=>{const s=t?` Did you mean "${t}"?`:"";console.warn(`Pushwoosh: unknown init parameter "${e}" is ignored.${s}`)})}(e),this.initParams={...T,...e},this.isInitAborted=!1;const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(te.setLevel(t||e.logLevel||"error"),e.logLevel&&await this.data.setLogLevel(e.logLevel),this.isPushDisabled=!1===e.pushNotifications,this.isAvailableNotifications()||te.info("Pushwoosh: push notifications are not available in this browser, initializing without them"),!e.applicationCode)throw new Error("Can't find application code!");const s=!1===e.communicationEnabled,i=await this.data.getCommunicationEnabled(),a=await this.data.getStatusCommunicationDisabled();(s&&!0!==i||!1===i||a)&&(this.isCommunicationDisabled=!0);const r=await this.data.getApplicationCode(),n=await this.isUserIdChanged();(!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail(),await this.data.setStatusLanguageWasChanged(!1)),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.resolvePlatformType()),await this.data.setFormFactor(this.platformChecker.formFactor),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion());if(await this.data.getStatusLanguageWasChanged()||await this.data.setLanguage(e.tags?.Language||navigator.language),await this.data.setApiEntrypoint(e.pushwooshUrl||""),await this.data.setApiToken(e.apiToken||""),await this.data.setSdkVersion("3.115.0"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{if(await this.finishInit(),this.isInitAborted)return;try{this.initParams.inboxWidget?.enable&&await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}catch(e){te.write("error",e)}const e=await this.data.getDelayedEvent();if(e){const{type:t,payload:s}=e;this.emitLegacyEventsFromServiceWorker(t,s),await this.data.setDelayedEvent(null)}if(this.isLegacySafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){if(await this.ensureHwid(),await this.data.setInitParams(this.initParams),await this.initStep("loadConfig",()=>this.loadConfig()),await this.data.setDeviceType(this.resolvePlatformType()),await this.initStep("applicationOpen",()=>this.open()),await this.initStep("sendData",()=>this.sendData()),!this.isInitAborted){if(this.isAvailableNotifications()){await this.data.getApplicationServerKey()?await this.initStep("initPushNotifications",()=>this.initPushNotifications(this.initParams)):te.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.knownPermission=this.readPermission(),await this.initStep("watchPushPermission",()=>this.watchPushPermission())}await this.featureFlags.start().catch(e=>te.error(e,"Pushwoosh: feature flags failed to start")),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),this.sdkUsage.listen((e,t)=>this.api.sdkUsage(e,t)),"serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=e=>this.onServiceWorkerMessage(e)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}}))}}async initStep(e,t){if(!this.isInitAborted)try{await t()}catch(t){const s=function(e){const t=e?.statusCode;return"number"==typeof t?t:void 0}(t);if(void 0!==s&&-1!==x.indexOf(s))return void this.abortInit(s);te.error(t,`Pushwoosh: init step "${e}" failed`)}}abortInit(e){this.isInitAborted=!0,te.error(`Pushwoosh: initialization stopped. The Pushwoosh API rejected the application code "${this.initParams.applicationCode}" (status_code: ${e}). Check the applicationCode init param against the application in your Pushwoosh Control Panel.`)}resolvePlatformType(){this.isLegacySafari=this.detectLegacySafari();return!this.isLegacySafari&&(this.initParams.unifiedPlatform||this.platformChecker.isSafari)?11:this.platformChecker.getPlatformType()}detectLegacySafari(){if(!this.platformChecker.isSafari)return!1;if(!this.platformChecker.isAvailableServiceWorker)return!0;const{safariWebsitePushID:e,unifiedPlatform:t}=this.initParams??{};return!!function(e,t){const s=t?ze(e,t):void 0;return s?.permission===c&&!!s.deviceToken}(A(),e)||!t&&!this.isWebVapidConfigured}async ensureHwid(e=!1){if(await this.readHwid()&&!e)return;const t=this.initParams.applicationCode+"_"+R();try{await this.data.setHwid(t),await this.data.getHwid()!==t&&te.info(_)}catch(e){te.info(e,_)}}async readHwid(){try{return await this.data.getHwid()}catch{return""}}getInitUserId(){const{userId:e}=this.initParams||{};return e&&"user_id"!==e?e:void 0}async isUserIdChanged(){const{userId:e}=this.initParams,t=await this.data.getUserId(),s=await this.data.getStatusUserIdWasChanged();return!!e&&"user_id"!==e&&e!==t&&!s}async defaultProcess(){const e=this.requireDriver(),t=e.getPermission();"granted"===t&&await this.data.setLastPermissionStatus(t);const s=await this.data.getStatusCommunicationDisabled(),i=await this.data.getStatusDropAllData(),a=await e.checkIsNeedResubscribe();if(s||i)return void await this.unsubscribe();a&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const r=await this.data.getStatusManualUnsubscribed(),n=!a&&await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(t){case h:this.eventBus.dispatchEvent("permission-default",{}),n&&await this.unsubscribe();break;case"denied":this.eventBus.dispatchEvent("permission-denied",{}),n&&await this.unsubscribe();break;case c:this.eventBus.dispatchEvent("permission-granted",{}),r&&n&&await this.unsubscribe(),(!n&&!r||a)&&await this.subscribe(!0)}this.reportPushPermissionChangeInBackground()}onServiceWorkerMessage(e){const{data:t={}}=e||{},{type:s="",payload:i={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,i)}async open(e){let t=await this.data.getLastOpenApplicationTime();const s=Date.now();t||(t=0);(e||!(s-t<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}getPushPermissionStatus(){return this.driver?He(this.driver.getPermission()):function(e,t){const s=Ke(e);if(s&&t){const s=ze(e,t);return s?He(s.permission):"unsupported"}return"PushManager"in e&&"Notification"in e?He(e.Notification.permission):s?"not_determined":"unsupported"}(A(),this.isLegacySafari?this.initParams?.safariWebsitePushID:void 0)}readPermission(){try{if(this.driver)return this.driver.getPermission();const e=A();return"Notification"in e?e.Notification.permission:void 0}catch{return}}announcePermissionChange(e){e!==this.knownPermission&&(this.knownPermission=e,this.eventBus.dispatchEvent("change-permission",{permission:e}))}async reportPushPermissionChange(){const e=null!==this.subscriptionInFlight&&!await this.waitForPermissionWork(this.subscriptionInFlight);if(this.isCommunicationDisabled||!this.driver||this.api.isPushPermissionStatusReported())return;const t=this.driver.getPermission(),s=await this.api.checkDeviceSubscribeForPushNotifications();let i=!1;if(t===c)s||e||this.isPushDisabled||await this.data.getStatusManualUnsubscribed()||(this.subscribe(!1).catch(e=>te.error(e,"Pushwoosh: re-subscribe after a permission grant failed")),this.subscriptionInFlight&&await this.waitForPermissionWork(this.subscriptionInFlight));else if(s){const e=this.dropRevokedSubscription(t).catch(e=>te.error(e,"Pushwoosh: unsubscribe after a permission revoke failed"));i=!await this.waitForPermissionWork(e)}await this.api.reportPushPermissionStatus(i)}async dropRevokedSubscription(e){await this.data.setLastPermissionStatus(e),await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1)}reportPushPermissionChangeInBackground(){this.reportPushPermissionChange().catch(e=>te.error(e,"Pushwoosh: registerDevice after a permission change failed"))}async watchPushPermission(){if(!this.isPushPermissionWatched&&"function"==typeof navigator.permissions?.query)try{(await navigator.permissions.query({name:"notifications"})).addEventListener("change",()=>{const e=this.readPermission();e&&this.announcePermissionChange(e),this.reportPushPermissionChangeInBackground()}),this.isPushPermissionWatched=!0}catch(e){te.info(e,"Pushwoosh: notifications permission can not be watched")}}async sendData(){const e=this.initParams,t=await this.data.getUserId();if(e.userId&&"user_id"!==e.userId&&e.userId!==t)try{await this.api.registerUser(e.userId,!1)}catch(e){te.error(e,"Pushwoosh: registerUser failed")}const s=[{test:async()=>{if(await this.data.getStatusEmailWasChanged())return!1;const t=await this.data.getEmail();return!!e.email&&e.email!==t},task:async()=>{await this.api.registerEmail(e.email,!1)}},{test:async()=>{if(await this.data.getStatusSmsNumberWasChanged())return!1;const t=await this.data.getSmsNumber();return!!e.smsNumber&&e.smsNumber!==t},task:async()=>{await this.api.registerSmsNumber(e.smsNumber,!1)}},{test:async()=>{if(await this.data.getStatusWhatsAppNumberWasChanged())return!1;const t=await this.data.getWhatsAppNumber();return!!e.whatsAppNumber&&e.whatsAppNumber!==t},task:async()=>{await this.api.registerWhatsappNumber(e.whatsAppNumber,!1)}},{test:async()=>!!e.tags||await this.data.getStatusLanguageWasChanged(),task:async()=>{const t=await this.data.getLanguage(),s={...e.tags||{},Language:t};await this.api.setTags(s)}}];await Promise.all(s.map(async e=>{try{await e.test()&&await e.task()}catch(e){console.error("Pushwoosh: Error during data registration",e)}}))}async loadConfig(){this.isWebVapidConfigured=await this.data.getWebVapidConfigured();const e=await this.api.getConfig(["vapid_key","web_vapid_configured","events","subscription_prompt","popup_forms","web_placements","web_sdk","web_sdk_modules"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(await this.applyServerInitParams(function(e){if(void 0!==e?.web_sdk)return e.web_sdk;const t=e?.web_sdk_modules;return void 0!==t?{inboxWidget:t.inboxWidget,webPopups:t.webPopups}:void 0}(t)),t.events&&t.events.length){t.events.some(e=>e===W)&&this.sendPostEventVisitedPage()}if(t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),void 0!==e&&e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}const e=t.web_vapid_configured??this.isWebVapidConfigured;e!==this.isWebVapidConfigured&&(this.isWebVapidConfigured=e,await this.data.setWebVapidConfigured(e))}}async applyServerInitParams(e){const t=function(e,t){if(!t)return{};const s={};if(ie.forEach(e=>{void 0!==t[e]&&(s[e]=t[e])}),void 0!==t.inboxWidget&&(s.inboxWidget={...e.inboxWidget,...t.inboxWidget}),void 0!==t.webPopups&&(s.webPopups={...e.webPopups,...t.webPopups}),void 0!==t.subscriptionWidget){const i=ae(e.subscribeWidget,t.subscribeWidget)??e.subscribeWidget;return s.subscribeWidget={...i,enable:!1},s.subscribePopup={...e.subscribePopup,enable:!1},s}const i=ae(e.subscribeWidget,t.subscribeWidget);return i&&(s.subscribeWidget=i),s}(this.rawInitParams,e);0!==Object.keys(t).length&&(this.initParams={...this.initParams,...t},await this.data.setInitParams(this.initParams))}async initPushNotifications(e){if(await this.data.setDefaultNotificationImage(e.defaultNotificationImage),await this.data.setDefaultNotificationTitle(e.defaultNotificationTitle),await this.data.setServiceWorkerUrl(e.serviceWorkerUrl),await this.data.setServiceWorkerScope(e.scope),await this.initDriver(),this.driver){if(this.isPushDisabled)return te.info('Pushwoosh: push notifications are disabled by the "pushNotifications" init param'),void await this.warnAboutKeptSubscription();try{await this.defaultProcess()}catch(e){te.error(e,"Internal error: defaultProcess fail")}}else te.info("Pushwoosh: push service driver was not created, skipping push initialization")}async warnAboutKeptSubscription(){const{pushToken:e}=await this.data.getTokens();e&&te.error('Pushwoosh: push notifications are disabled by the "pushNotifications" init param, but this device is still subscribed and will keep receiving notifications. Call Pushwoosh.unsubscribe() to unsubscribe it.')}async initDriver(){if(this.isLegacySafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new Je(this.api,this.data,{webSitePushId:e})):void te.info("Safari push needs safariWebsitePushID in initParams; Safari 16+ can use web VAPID keys of the application instead.")}te.info({isAvailableServiceWorker:this.platformChecker.isAvailableServiceWorker}),this.platformChecker.isAvailableServiceWorker&&(this.driver=new Ge(this.api,this.data,{}))}async sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window,s=he(),i=await this.data.getDeviceType();this.api.postEvent(W,{url:t,path:s,title:e,device_type:i})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===u:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in L:this.eventBus.addEventHandler(L[e].name,s=>{const{prop:i}=L[e];t(this.api,i?s[i]:void 0)});break;default:s=!1}return s&&this.sdkUsage.recordLegacyEvent(e),s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case f:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case y:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case v:this.eventBus.dispatchEvent("hide-notification",{notification:t});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:t})}}}return t})());
|
|
2
2
|
//# sourceMappingURL=npm.js.map
|