pushilka 1.0.12 → 2.0.1

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/dist/app.js CHANGED
@@ -1 +1 @@
1
- function Pushilka(e){var n,a=d(),s={endpoint:"https://swarmpush.com/push_subscription.php",eventEndpoint:"https://swarmpush.com/event",serviceWorker:"/serviceWorker.js",serviceWorkerOptions:{scope:"/"},applicationServerKey:"BCmIwkLHxJNPccoVf2UXDjd7kDuiyJpKsSOqSHCtGBMfBkjfHLCq4-d8eNtabNlCNKFF8CZIzeDwOo3OvNCQAns",source:"",var1:"",var2:"",var3:"",var4:"",useDialog:!1,visitorCookie:"pushilka_vid",dialog:{ttl:30,message:"We'd like to send you notifications for the latest news and updates.",allowText:"Allow",cancelText:"No thanks",icon:"https://swarmpush.com/s/pushilka/bell.webp",style:"https://swarmpush.com/s/pushilka/app.css",template:'<div id="pushilka-dialog" class="pushilka-dialog"><div class="pushilka-icon"><img width="80" src="{ICON_URL}" alt=""></div><div class="pushilka-message">{MESSAGE}</div><div class="pushilka-buttons"><a href="" id="pushilka-agree-button" class="pushilka-agree-button">{ALLOW_TEXT}</a><a href="" id="pushilka-cancel-button" class="pushilka-cancel-button">{CANCEL_TEXT}</a></div></div>'},done:function(){},success:function(){},decline:function(){}};for(var t in e)if(e.hasOwnProperty(t)&&"dialog"===t)for(var o in e[t])e[t].hasOwnProperty(o)&&s[t].hasOwnProperty(o)&&(s[t][o]=e[t][o]);else e.hasOwnProperty(t)&&s.hasOwnProperty(t)&&(s[t]=e[t]);function i(e){fetch(s.eventEndpoint,{method:"POST",body:JSON.stringify({event:e,source:s.source,visitorId:l(),sessionId:a,var1:s.var1,var2:s.var2,var3:s.var3,var4:s.var4})}).catch()}function r(e,n,t){var o=new Date;o.setTime(o.getTime()+60*t*1e3),t="; expires="+o.toUTCString(),document.cookie=e+"="+(n||"")+t+"; path=/"}function c(e){var n=document.cookie.split(";"),t=e+"=";for(var o in n){var i=n[o].trimLeft();if(0===i.indexOf(t))return i.substring(t.length)}return null}function u(){navigator.serviceWorker.ready.then(function(e){return i("sys_push_invoked"),e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){for(var n=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),t=window.atob(n),o=new Uint8Array(t.length),i=0;i<t.length;++i)o[i]=t.charCodeAt(i);return o}(s.applicationServerKey)})}).then(function(e){return p(e,"POST")}).catch(function(){i("sys_push_blocked"),s.decline(),s.done()})}function d(){for(var e=[],n=0;n<2;n++)e.push(Math.floor(4294967295*Math.random()).toString(36));return e.join("-")}function l(){var e=window.localStorage;return n=n||e.getItem("visitorId")||c(s.visitorCookie)||d(),e.setItem("visitorId",n),r(s.visitorCookie,n,365),n}function p(e,n){var t,o=e.getKey("p256dh"),i=e.getKey("auth"),r=(PushManager.supportedContentEncodings||["aesgcm"])[0];return fetch((t=s.endpoint,t+"?vid="+encodeURIComponent(l())+"&sid="+encodeURIComponent(a)+"&s="+encodeURIComponent(s.source.toString())+"&var1="+encodeURIComponent(s.var1.toString())+"&var2="+encodeURIComponent(s.var2.toString())+"&var3="+encodeURIComponent(s.var3.toString())+"&var4="+encodeURIComponent(s.var4.toString())),{method:n,body:JSON.stringify({endpoint:e.endpoint,publicKey:o?btoa(String.fromCharCode.apply(null,new Uint8Array(o))):null,authToken:i?btoa(String.fromCharCode.apply(null,new Uint8Array(i))):null,contentEncoding:r})}).then(function(){return s.success(),s.done(),e}).catch(function(){s.success(),s.done()})}this.ready=function(e){"interactive"===document.readyState||"complete"===document.readyState?e():document.addEventListener("DOMContentLoaded",e)},this.run=function(){this.ready(function(){return"showNotification"in ServiceWorkerRegistration.prototype==!1?(console.debug("Push messaging is not supported."),i("push_not_supported"),s.decline(),void s.done()):"denied"===Notification.permission?(console.debug("User has blocked notifications."),i("sys_push_blocked"),s.decline(),void s.done()):void navigator.serviceWorker.register(s.serviceWorker,s.serviceWorkerOptions).then(function(){navigator.serviceWorker.ready.then(function(e){return e.pushManager.getSubscription()}).then(function(e){return e?p(e,"PUT"):s.useDialog?function(){if(null===c("pushilka-dialog")){i("push_invoked");var e=s.dialog,n=document.createElement("link");n.rel="stylesheet",n.href=e.style,document.body.appendChild(n);var t=document.createElement("div");t.innerHTML=e.template.replace("{ICON_URL}",e.icon).replace("{MESSAGE}",e.message).replace("{ALLOW_TEXT}",e.allowText).replace("{CANCEL_TEXT}",e.cancelText),document.body.appendChild(t);var o={agreeButton:document.getElementById("pushilka-agree-button"),cancelButton:document.getElementById("pushilka-cancel-button"),dialog:document.getElementById("pushilka-dialog")};o.agreeButton.addEventListener("click",function(e){e.preventDefault(),o.dialog.remove(),u()}),o.cancelButton.addEventListener("click",function(e){e.preventDefault(),i("push_blocked"),r("pushilka-dialog","1",s.dialog.ttl),o.dialog.remove()})}else i("push_blocked")}():u()})}).catch(function(){i("sys_push_subscribe_error"),s.decline(),s.done()})})}}
1
+ export default class Pushilka{sessionId=null;visitorId=null;params=null;constructor(e){for(var t in this.sessionId=this.genRandomString(),this.params={endpoint:"https://swarmpush.com/push_subscription.php",eventEndpoint:"https://swarmpush.com/event",serviceWorker:"/serviceWorker.js",serviceWorkerOptions:{scope:"/"},applicationServerKey:"BCmIwkLHxJNPccoVf2UXDjd7kDuiyJpKsSOqSHCtGBMfBkjfHLCq4-d8eNtabNlCNKFF8CZIzeDwOo3OvNCQAns",source:"",var1:"",var2:"",var3:"",var4:"",var5:"",var6:"",var7:"",var8:"",var9:"",var10:"",useDialog:!1,visitorCookie:"pushilka_vid",dialog:{ttl:30,message:"We'd like to send you notifications for the latest news and updates.",allowText:"Allow",cancelText:"No thanks",icon:"https://swarmpush.com/s/pushilka/bell.webp",style:"https://swarmpush.com/s/pushilka/app.css",template:'<div id="pushilka-dialog" class="pushilka-dialog"><div class="pushilka-icon"><img width="80" src="{ICON_URL}" alt=""></div><div class="pushilka-message">{MESSAGE}</div><div class="pushilka-buttons"><a href="" id="pushilka-agree-button" class="pushilka-agree-button">{ALLOW_TEXT}</a><a href="" id="pushilka-cancel-button" class="pushilka-cancel-button">{CANCEL_TEXT}</a></div></div>'},done:function(){},success:function(){},decline:function(){}},e)if(e.hasOwnProperty(t)&&"dialog"===t)for(var r in e[t])e[t].hasOwnProperty(r)&&this.params[t].hasOwnProperty(r)&&(this.params[t][r]=e[t][r]);else e.hasOwnProperty(t)&&this.params.hasOwnProperty(t)&&(this.params[t]=e[t])}urlBase64ToUint8Array(e){var e=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),t=window.atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;++e)r[e]=t.charCodeAt(e);return r}sendEvent(e){fetch(this.params.eventEndpoint,{method:"POST",body:JSON.stringify({event:e,source:this.params.source,visitorId:this.getVisitorId(),sessionId:this.sessionId,var1:this.params.var1,var2:this.params.var2,var3:this.params.var3,var4:this.params.var4,var5:this.params.var5,var6:this.params.var6,var7:this.params.var7,var8:this.params.var8,var9:this.params.var9,var10:this.params.var10})}).catch()}setCookie(e,t,r){var s=new Date;s.setTime(s.getTime()+60*r*1e3),r="; expires="+s.toUTCString(),document.cookie=e+"="+(t||"")+r+"; path=/"}getCookie(e){var t,r=document.cookie.split(";"),s=e+"=";for(t in r){var a=r[t].trimStart();if(0===a.indexOf(s))return a.substring(s.length)}return null}showDialog(){let r=this;if(null!==this.getCookie("pushilka-dialog"))this.sendEvent("push_blocked");else{this.sendEvent("push_invoked");var e=this.params.dialog,s=document.createElement("link"),s=(s.rel="stylesheet",s.href=e.style,document.body.appendChild(s),document.createElement("div"));s.innerHTML=e.template.replace("{ICON_URL}",e.icon).replace("{MESSAGE}",e.message).replace("{ALLOW_TEXT}",e.allowText).replace("{CANCEL_TEXT}",e.cancelText),document.body.appendChild(s);let t={agreeButton:document.getElementById("pushilka-agree-button"),cancelButton:document.getElementById("pushilka-cancel-button"),dialog:document.getElementById("pushilka-dialog")};t.agreeButton.addEventListener("click",function(e){e.preventDefault(),t.dialog.remove(),r.subscribe()}),t.cancelButton.addEventListener("click",function(e){e.preventDefault(),r.sendEvent("push_blocked"),r.setCookie("pushilka-dialog","1",r.params.dialog.ttl),t.dialog.remove()})}}subscribe(){let t=this;navigator.serviceWorker.ready.then(function(e){return t.sendEvent("sys_push_invoked"),e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t.urlBase64ToUint8Array(t.params.applicationServerKey)})}).then(function(e){return t.sendSubscriptionToServer(e,"POST")}).catch(function(){t.sendEvent("sys_push_blocked"),t.params.decline(),t.params.done()})}genRandomString(){var t=[];for(let e=0;e<2;e++)t.push(Math.floor(4294967295*Math.random()).toString(36));return t.join("-")}getVisitorId(){var e=window.localStorage;return this.visitorId=this.visitorId||e.getItem("visitorId")||this.getCookie(this.params.visitorCookie)||this.genRandomString(),e.setItem("visitorId",this.visitorId),this.setCookie(this.params.visitorCookie,this.visitorId,365),this.visitorId}getTimezone(){let e="";try{e=Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){console.error(e)}return e}getEndpoint(e){return e+"?vid="+encodeURIComponent(this.getVisitorId())+"&sid="+encodeURIComponent(this.sessionId)+"&s="+encodeURIComponent(this.params.source.toString())+"&var1="+encodeURIComponent(this.params.var1.toString())+"&var2="+encodeURIComponent(this.params.var2.toString())+"&var3="+encodeURIComponent(this.params.var3.toString())+"&var4="+encodeURIComponent(this.params.var4.toString())+"&var5="+encodeURIComponent(this.params.var5.toString())+"&var6="+encodeURIComponent(this.params.var6.toString())+"&var7="+encodeURIComponent(this.params.var7.toString())+"&var8="+encodeURIComponent(this.params.var8.toString())+"&var9="+encodeURIComponent(this.params.var9.toString())+"&var10="+encodeURIComponent(this.params.var10.toString())+"&timezone="+encodeURIComponent(this.getTimezone())}sendSubscriptionToServer(e,t){let r=this;var s=e.getKey("p256dh"),a=e.getKey("auth"),n=(PushManager.supportedContentEncodings||["aesgcm"])[0];return fetch(r.getEndpoint(r.params.endpoint),{method:t,body:JSON.stringify({endpoint:e.endpoint,publicKey:s?btoa(String.fromCharCode.apply(null,new Uint8Array(s))):null,authToken:a?btoa(String.fromCharCode.apply(null,new Uint8Array(a))):null,contentEncoding:n})}).then(function(){return r.params.success(),r.params.done(),e}).catch(function(){r.params.success(),r.params.done()})}ready(e){"interactive"===document.readyState||"complete"===document.readyState?e():document.addEventListener("DOMContentLoaded",e)}run(){let t=this;t.ready(function(){"showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(console.debug("User has blocked notifications."),t.sendEvent("sys_push_blocked"),t.params.decline(),t.params.done()):navigator.serviceWorker.register(t.params.serviceWorker,t.params.serviceWorkerOptions).then(function(){navigator.serviceWorker.ready.then(function(e){return e.pushManager.getSubscription()}).then(function(e){return e?t.sendSubscriptionToServer(e,"PUT"):t.params.useDialog?t.showDialog():t.subscribe()})}).catch(function(){t.sendEvent("sys_push_subscribe_error"),t.params.decline(),t.params.done()}):(console.debug("Push messaging is not supported."),t.sendEvent("push_not_supported"),t.params.decline(),t.params.done())})}}
package/dist/bell.webp CHANGED
Binary file
@@ -1 +1 @@
1
- self.addEventListener("push",function(i){if(self.Notification&&"granted"===self.Notification.permission){var t;if(i.data){var n=i.data.json();i.waitUntil((t=n,self.registration.showNotification(t.title,{body:t.body,icon:t.icon,badge:t.badge,image:t.image,vibrate:t.vibrate,sound:t.sound,sticky:!0,noscreen:!1,requireInteraction:!1,timestamp:t.timestamp,data:{url:t.url,msg_id:t.hasOwnProperty("msg_id")?t.msg_id:""}})))}}}),self.addEventListener("notificationclick",function(i){i.notification.close(),i.waitUntil(clients.openWindow(i.notification.data.url))});
1
+ self.addEventListener("push",function(i){var t;self.Notification&&"granted"===self.Notification.permission&&i.data&&(t=i.data.json(),i.waitUntil((i=t,self.registration.showNotification(i.title,{body:i.body,icon:i.icon,badge:i.badge,image:i.image,vibrate:i.vibrate,sound:i.sound,sticky:!0,noscreen:!1,requireInteraction:!1,timestamp:i.timestamp,data:{url:i.url,msg_id:i.hasOwnProperty("msg_id")?i.msg_id:""}}))))}),self.addEventListener("notificationclick",function(i){i.notification.close(),i.waitUntil(clients.openWindow(i.notification.data.url))});
package/gulpfile.js CHANGED
@@ -1,29 +1,22 @@
1
- var gulp = require('gulp'),
2
- uglify = require('gulp-uglify'),
3
- uglifycss = require('gulp-uglifycss'),
4
- pump = require('pump');
1
+ let gulp = require('gulp');
2
+ let uglify = require('gulp-uglify');
3
+ let uglifycss = require('gulp-uglifycss');
5
4
 
6
- gulp.task('scripts', function(cb) {
7
- return pump([
8
- gulp.src('src/*.js'),
9
- uglify(),
10
- gulp.dest('dist/')
11
- ]);
12
- });
5
+ function scripts() {
6
+ return gulp.src('src/*.js')
7
+ .pipe(uglify())
8
+ .pipe(gulp.dest('dist/'));
9
+ }
13
10
 
14
- gulp.task('css', function(cb) {
15
- return pump([
16
- gulp.src('src/*.css'),
17
- uglifycss(),
18
- gulp.dest('dist/')
19
- ]);
20
- });
11
+ function css() {
12
+ return gulp.src('src/*.css')
13
+ .pipe(uglifycss())
14
+ .pipe(gulp.dest('dist/'))
15
+ }
21
16
 
22
- gulp.task('images', function(cb) {
23
- return pump([
24
- gulp.src('src/*.{webp,jpg,png,gif}'),
25
- gulp.dest('dist/')
26
- ]);
27
- });
17
+ function images() {
18
+ return gulp.src('src/*.{webp,jpg,png,gif}')
19
+ .pipe(gulp.dest('dist/'));
20
+ }
28
21
 
29
- gulp.task('default', gulp.series('scripts', 'css', 'images'));
22
+ exports.default = gulp.series(scripts, css, images)
package/package.json CHANGED
@@ -1,14 +1,12 @@
1
1
  {
2
2
  "name": "pushilka",
3
- "version": "1.0.12",
3
+ "version": "2.0.1",
4
4
  "description": "Web push client",
5
5
  "main": "./dist/app.js",
6
- "dependencies": {},
7
6
  "devDependencies": {
8
- "gulp": "^4.0.2",
9
- "gulp-uglify": "^3.0.0",
10
- "gulp-uglifycss": "^1.1.0",
11
- "pump": "^3.0.0"
7
+ "gulp": "^5.0.0",
8
+ "gulp-uglify": "^3.0.2",
9
+ "gulp-uglifycss": "^1.1.0"
12
10
  },
13
11
  "scripts": {
14
12
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -22,5 +20,9 @@
22
20
  "bugs": {
23
21
  "url": "https://github.com/pushilka/pushilka/issues"
24
22
  },
23
+ "engines": {
24
+ "npm": ">=10.0.0 <11.0.0",
25
+ "node": ">=22.0.0 <23.0.0"
26
+ },
25
27
  "homepage": "https://github.com/pushilka/pushilka#readme"
26
28
  }
package/src/app.js CHANGED
@@ -1,95 +1,111 @@
1
- function Pushilka(options) {
2
- var sessionId = genRandomString(),
3
- visitorId;
4
-
5
- var params = {
6
- endpoint: "https://swarmpush.com/push_subscription.php",
7
- eventEndpoint: "https://swarmpush.com/event",
8
- serviceWorker: "/serviceWorker.js",
9
- serviceWorkerOptions: {scope: "/"},
10
- applicationServerKey: "BCmIwkLHxJNPccoVf2UXDjd7kDuiyJpKsSOqSHCtGBMfBkjfHLCq4-d8eNtabNlCNKFF8CZIzeDwOo3OvNCQAns",
11
- source: "",
12
- var1: "",
13
- var2: "",
14
- var3: "",
15
- var4: "",
16
- useDialog: false,
17
- visitorCookie: 'pushilka_vid',
18
- dialog: {
19
- ttl: 30,
20
- message: "We'd like to send you notifications for the latest news and updates.",
21
- allowText: "Allow",
22
- cancelText: "No thanks",
23
- icon: 'https://swarmpush.com/s/pushilka/bell.webp',
24
- style: 'https://swarmpush.com/s/pushilka/app.css',
25
- template: '<div id="pushilka-dialog" class="pushilka-dialog"><div class="pushilka-icon">'
26
- + '<img width="80" src="{ICON_URL}" alt=""></div><div class="pushilka-message">{MESSAGE}</div>'
27
- + '<div class="pushilka-buttons"><a href="" id="pushilka-agree-button" class="pushilka-agree-button">{ALLOW_TEXT}</a>'
28
- + '<a href="" id="pushilka-cancel-button" class="pushilka-cancel-button">{CANCEL_TEXT}</a></div></div>'
29
- },
30
- done: function () {
31
- },
32
- success: function () {
33
- },
34
- decline: function () {
35
- }
36
- };
1
+ export default class Pushilka {
2
+ sessionId = null;
3
+ visitorId = null;
4
+ params = null;
37
5
 
38
- for (var i in options) {
39
- if (options.hasOwnProperty(i) && i === 'dialog') {
40
- for (var j in options[i]) {
41
- if (options[i].hasOwnProperty(j) && params[i].hasOwnProperty(j)) {
42
- params[i][j] = options[i][j];
6
+ constructor(options) {
7
+ this.sessionId = this.genRandomString();
8
+ this.params = {
9
+ endpoint: "https://swarmpush.com/push_subscription.php",
10
+ eventEndpoint: "https://swarmpush.com/event",
11
+ serviceWorker: "/serviceWorker.js",
12
+ serviceWorkerOptions: {scope: "/"},
13
+ applicationServerKey: "BCmIwkLHxJNPccoVf2UXDjd7kDuiyJpKsSOqSHCtGBMfBkjfHLCq4-d8eNtabNlCNKFF8CZIzeDwOo3OvNCQAns",
14
+ source: "",
15
+ var1: "",
16
+ var2: "",
17
+ var3: "",
18
+ var4: "",
19
+ var5: "",
20
+ var6: "",
21
+ var7: "",
22
+ var8: "",
23
+ var9: "",
24
+ var10: "",
25
+ useDialog: false,
26
+ visitorCookie: 'pushilka_vid',
27
+ dialog: {
28
+ ttl: 30,
29
+ message: "We'd like to send you notifications for the latest news and updates.",
30
+ allowText: "Allow",
31
+ cancelText: "No thanks",
32
+ icon: 'https://swarmpush.com/s/pushilka/bell.webp',
33
+ style: 'https://swarmpush.com/s/pushilka/app.css',
34
+ template: '<div id="pushilka-dialog" class="pushilka-dialog"><div class="pushilka-icon">'
35
+ + '<img width="80" src="{ICON_URL}" alt=""></div><div class="pushilka-message">{MESSAGE}</div>'
36
+ + '<div class="pushilka-buttons"><a href="" id="pushilka-agree-button" class="pushilka-agree-button">{ALLOW_TEXT}</a>'
37
+ + '<a href="" id="pushilka-cancel-button" class="pushilka-cancel-button">{CANCEL_TEXT}</a></div></div>'
38
+ },
39
+ done: function () {
40
+ },
41
+ success: function () {
42
+ },
43
+ decline: function () {
44
+ }
45
+ };
46
+
47
+ for (let i in options) {
48
+ if (options.hasOwnProperty(i) && i === 'dialog') {
49
+ for (let j in options[i]) {
50
+ if (options[i].hasOwnProperty(j) && this.params[i].hasOwnProperty(j)) {
51
+ this.params[i][j] = options[i][j];
52
+ }
43
53
  }
54
+ } else if (options.hasOwnProperty(i) && this.params.hasOwnProperty(i)) {
55
+ this.params[i] = options[i];
44
56
  }
45
- } else if (options.hasOwnProperty(i) && params.hasOwnProperty(i)) {
46
- params[i] = options[i];
47
57
  }
48
58
  }
49
59
 
50
- function urlBase64ToUint8Array(base64String) {
51
- var padding = '='.repeat((4 - base64String.length % 4) % 4);
52
- var base64 = (base64String + padding)
60
+ urlBase64ToUint8Array(base64String) {
61
+ let padding = '='.repeat((4 - base64String.length % 4) % 4);
62
+ let base64 = (base64String + padding)
53
63
  .replace(/-/g, '+')
54
64
  .replace(/_/g, '/');
55
65
 
56
- var rawData = window.atob(base64);
57
- var outputArray = new Uint8Array(rawData.length);
66
+ let rawData = window.atob(base64);
67
+ let outputArray = new Uint8Array(rawData.length);
58
68
 
59
- for (var i = 0; i < rawData.length; ++i) {
69
+ for (let i = 0; i < rawData.length; ++i) {
60
70
  outputArray[i] = rawData.charCodeAt(i);
61
71
  }
62
72
  return outputArray;
63
73
  }
64
74
 
65
- function sendEvent(event) {
66
- fetch(params.eventEndpoint, {
75
+ sendEvent(event) {
76
+ fetch(this.params.eventEndpoint, {
67
77
  method: 'POST',
68
78
  body: JSON.stringify({
69
79
  event: event,
70
- source: params.source,
71
- visitorId: getVisitorId(),
72
- sessionId: sessionId,
73
- var1: params.var1,
74
- var2: params.var2,
75
- var3: params.var3,
76
- var4: params.var4
80
+ source: this.params.source,
81
+ visitorId: this.getVisitorId(),
82
+ sessionId: this.sessionId,
83
+ var1: this.params.var1,
84
+ var2: this.params.var2,
85
+ var3: this.params.var3,
86
+ var4: this.params.var4,
87
+ var5: this.params.var5,
88
+ var6: this.params.var6,
89
+ var7: this.params.var7,
90
+ var8: this.params.var8,
91
+ var9: this.params.var9,
92
+ var10: this.params.var10,
77
93
  })
78
94
  }).catch();
79
95
  }
80
96
 
81
- function setCookie(name, value, expires) {
82
- var date = new Date;
97
+ setCookie(name, value, expires) {
98
+ let date = new Date;
83
99
  date.setTime(date.getTime() + 60 * expires * 1000);
84
100
  expires = "; expires=" + date.toUTCString();
85
101
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
86
102
  }
87
103
 
88
- function getCookie(name) {
89
- var parts = document.cookie.split(";"),
104
+ getCookie(name) {
105
+ let parts = document.cookie.split(";"),
90
106
  prefix = name + "=";
91
- for (var i in parts) {
92
- var part = parts[i].trimLeft();
107
+ for (let i in parts) {
108
+ let part = parts[i].trimStart();
93
109
  if (part.indexOf(prefix) === 0) {
94
110
  return part.substring(prefix.length);
95
111
  }
@@ -98,22 +114,24 @@ function Pushilka(options) {
98
114
  return null;
99
115
  }
100
116
 
101
- function showDialog() {
102
- if (getCookie("pushilka-dialog") !== null) {
103
- sendEvent("push_blocked");
117
+ showDialog() {
118
+ let self = this;
119
+
120
+ if (this.getCookie("pushilka-dialog") !== null) {
121
+ this.sendEvent("push_blocked");
104
122
  return;
105
123
  }
106
124
 
107
- sendEvent("push_invoked");
125
+ this.sendEvent("push_invoked");
108
126
 
109
- var dialog = params.dialog;
127
+ let dialog = this.params.dialog;
110
128
 
111
- var s = document.createElement('link');
129
+ let s = document.createElement('link');
112
130
  s.rel = "stylesheet";
113
131
  s.href = dialog.style;
114
132
  document.body.appendChild(s);
115
133
 
116
- var d = document.createElement('div');
134
+ let d = document.createElement('div');
117
135
  d.innerHTML = dialog.template
118
136
  .replace('{ICON_URL}', dialog.icon)
119
137
  .replace('{MESSAGE}', dialog.message)
@@ -121,7 +139,7 @@ function Pushilka(options) {
121
139
  .replace('{CANCEL_TEXT}', dialog.cancelText);
122
140
  document.body.appendChild(d);
123
141
 
124
- var els = {
142
+ let els = {
125
143
  agreeButton: document.getElementById("pushilka-agree-button"),
126
144
  cancelButton: document.getElementById("pushilka-cancel-button"),
127
145
  dialog: document.getElementById("pushilka-dialog")
@@ -131,71 +149,91 @@ function Pushilka(options) {
131
149
  e.preventDefault();
132
150
 
133
151
  els.dialog.remove();
134
- subscribe();
152
+ self.subscribe();
135
153
  });
136
154
  els.cancelButton.addEventListener("click", function (e) {
137
155
  e.preventDefault();
138
156
 
139
- sendEvent("push_blocked");
140
- setCookie("pushilka-dialog", "1", params.dialog.ttl);
157
+ self.sendEvent("push_blocked");
158
+ self.setCookie("pushilka-dialog", "1", self.params.dialog.ttl);
141
159
  els.dialog.remove();
142
160
  });
143
161
  }
144
162
 
145
- function subscribe() {
163
+ subscribe() {
164
+ let self = this;
146
165
  navigator.serviceWorker.ready
147
166
  .then(function (serviceWorkerRegistration) {
148
- sendEvent("sys_push_invoked");
167
+ self.sendEvent("sys_push_invoked");
149
168
  return serviceWorkerRegistration.pushManager
150
169
  .subscribe({
151
170
  userVisibleOnly: true,
152
- applicationServerKey: urlBase64ToUint8Array(params.applicationServerKey)
171
+ applicationServerKey: self.urlBase64ToUint8Array(self.params.applicationServerKey)
153
172
  });
154
173
  })
155
174
  .then(function (subscription) {
156
- return sendSubscriptionToServer(subscription, 'POST');
175
+ return self.sendSubscriptionToServer(subscription, 'POST');
157
176
  })
158
177
  .catch(function () {
159
- sendEvent("sys_push_blocked");
160
- params.decline();
161
- params.done();
178
+ self.sendEvent("sys_push_blocked");
179
+ self.params.decline();
180
+ self.params.done();
162
181
  });
163
182
  }
164
183
 
165
- function genRandomString() {
166
- var s = [];
167
- for (var i = 0; i < 2; i++) {
184
+ genRandomString() {
185
+ let s = [];
186
+ for (let i = 0; i < 2; i++) {
168
187
  s.push(Math.floor(Math.random() * 0xFFFFFFFF).toString(36));
169
188
  }
170
189
  return s.join("-");
171
190
  }
172
191
 
173
- function getVisitorId() {
174
- var st = window.localStorage;
175
- visitorId = visitorId || st.getItem("visitorId") || getCookie(params.visitorCookie) || genRandomString();
176
- st.setItem("visitorId", visitorId);
177
- setCookie(params.visitorCookie, visitorId, 365);
192
+ getVisitorId() {
193
+ let st = window.localStorage;
194
+ this.visitorId = this.visitorId || st.getItem("visitorId") || this.getCookie(this.params.visitorCookie) || this.genRandomString();
195
+ st.setItem("visitorId", this.visitorId);
196
+ this.setCookie(this.params.visitorCookie, this.visitorId, 365);
178
197
 
179
- return visitorId;
198
+ return this.visitorId;
180
199
  }
181
200
 
182
- function getEndpoint(endpoint) {
201
+ getTimezone() {
202
+ let timezone = "";
203
+ try {
204
+ timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
205
+ } catch (error) {
206
+ console.error(error);
207
+ }
208
+
209
+ return timezone;
210
+ }
211
+
212
+ getEndpoint(endpoint) {
183
213
  return endpoint + '?'
184
- + 'vid=' + encodeURIComponent(getVisitorId())
185
- + '&sid=' + encodeURIComponent(sessionId)
186
- + '&s=' + encodeURIComponent(params.source.toString())
187
- + '&var1=' + encodeURIComponent(params.var1.toString())
188
- + '&var2=' + encodeURIComponent(params.var2.toString())
189
- + '&var3=' + encodeURIComponent(params.var3.toString())
190
- + '&var4=' + encodeURIComponent(params.var4.toString());
214
+ + 'vid=' + encodeURIComponent(this.getVisitorId())
215
+ + '&sid=' + encodeURIComponent(this.sessionId)
216
+ + '&s=' + encodeURIComponent(this.params.source.toString())
217
+ + '&var1=' + encodeURIComponent(this.params.var1.toString())
218
+ + '&var2=' + encodeURIComponent(this.params.var2.toString())
219
+ + '&var3=' + encodeURIComponent(this.params.var3.toString())
220
+ + '&var4=' + encodeURIComponent(this.params.var4.toString())
221
+ + '&var5=' + encodeURIComponent(this.params.var5.toString())
222
+ + '&var6=' + encodeURIComponent(this.params.var6.toString())
223
+ + '&var7=' + encodeURIComponent(this.params.var7.toString())
224
+ + '&var8=' + encodeURIComponent(this.params.var8.toString())
225
+ + '&var9=' + encodeURIComponent(this.params.var9.toString())
226
+ + '&var10=' + encodeURIComponent(this.params.var10.toString())
227
+ + '&timezone=' + encodeURIComponent(this.getTimezone());
191
228
  }
192
229
 
193
- function sendSubscriptionToServer(subscription, method) {
194
- var key = subscription.getKey('p256dh');
195
- var token = subscription.getKey('auth');
196
- var contentEncoding = (PushManager.supportedContentEncodings || ['aesgcm'])[0];
230
+ sendSubscriptionToServer(subscription, method) {
231
+ let self = this;
232
+ let key = subscription.getKey('p256dh');
233
+ let token = subscription.getKey('auth');
234
+ let contentEncoding = (PushManager.supportedContentEncodings || ['aesgcm'])[0];
197
235
 
198
- return fetch(getEndpoint(params.endpoint), {
236
+ return fetch(self.getEndpoint(self.params.endpoint), {
199
237
  method: method,
200
238
  body: JSON.stringify({
201
239
  endpoint: subscription.endpoint,
@@ -205,43 +243,44 @@ function Pushilka(options) {
205
243
  })
206
244
  })
207
245
  .then(function () {
208
- params.success();
209
- params.done();
246
+ self.params.success();
247
+ self.params.done();
210
248
  return subscription;
211
249
  })
212
250
  .catch(function () {
213
- params.success();
214
- params.done();
251
+ self.params.success();
252
+ self.params.done();
215
253
  });
216
254
  }
217
255
 
218
- this.ready = function (callback) {
256
+ ready(callback) {
219
257
  if (document.readyState === 'interactive' || document.readyState === 'complete') {
220
258
  callback();
221
259
  } else {
222
260
  document.addEventListener("DOMContentLoaded", callback);
223
261
  }
224
- };
262
+ }
225
263
 
226
- this.run = function () {
227
- this.ready(function () {
228
- if ("showNotification" in ServiceWorkerRegistration.prototype === false) {
264
+ run() {
265
+ let self = this;
266
+ self.ready(function () {
267
+ if (!("showNotification" in ServiceWorkerRegistration.prototype)) {
229
268
  console.debug("Push messaging is not supported.");
230
- sendEvent("push_not_supported");
231
- params.decline();
232
- params.done();
269
+ self.sendEvent("push_not_supported");
270
+ self.params.decline();
271
+ self.params.done();
233
272
  return;
234
273
  }
235
274
 
236
275
  if (Notification.permission === "denied") {
237
276
  console.debug("User has blocked notifications.");
238
- sendEvent("sys_push_blocked");
239
- params.decline();
240
- params.done();
277
+ self.sendEvent("sys_push_blocked");
278
+ self.params.decline();
279
+ self.params.done();
241
280
  return;
242
281
  }
243
282
 
244
- navigator.serviceWorker.register(params.serviceWorker, params.serviceWorkerOptions)
283
+ navigator.serviceWorker.register(self.params.serviceWorker, self.params.serviceWorkerOptions)
245
284
  .then(function () {
246
285
  navigator.serviceWorker.ready
247
286
  .then(function (serviceWorkerRegistration) {
@@ -249,17 +288,17 @@ function Pushilka(options) {
249
288
  })
250
289
  .then(function (subscription) {
251
290
  if (!subscription) {
252
- return params.useDialog ? showDialog() : subscribe();
291
+ return self.params.useDialog ? self.showDialog() : self.subscribe();
253
292
  } else {
254
- return sendSubscriptionToServer(subscription, 'PUT');
293
+ return self.sendSubscriptionToServer(subscription, 'PUT');
255
294
  }
256
295
  });
257
296
  })
258
297
  .catch(function () {
259
- sendEvent("sys_push_subscribe_error");
260
- params.decline();
261
- params.done();
298
+ self.sendEvent("sys_push_subscribe_error");
299
+ self.params.decline();
300
+ self.params.done();
262
301
  });
263
302
  });
264
303
  }
265
- }
304
+ }
package/src/.DS_Store DELETED
Binary file