Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@magicbell/webpush

Package Overview
Dependencies
Maintainers
2
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@magicbell/webpush - npm Package Compare versions

Comparing version 1.0.0 to 1.1.0

4

dist/index.d.ts

@@ -1,3 +0,3 @@

export declare function registerServiceWorker({ path }: {
path: string;
export declare function registerServiceWorker({ path }?: {
path?: string;
}): Promise<ServiceWorkerRegistration>;

@@ -4,0 +4,0 @@ /**

/**
* @license @magicbell/webpush v1.0.0
* @license @magicbell/webpush v1.1.0
*

@@ -4,0 +4,0 @@ * Copyright (c) MagicBell Inc. and its affiliates.

/**
* @license @magicbell/webpush v1.0.0
* @license @magicbell/webpush v1.1.0
*

@@ -31,12 +31,2 @@ * Copyright (c) MagicBell Inc. and its affiliates.

Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
function stringToUint8Array(plainString) {
const padding = "=".repeat((4 - plainString.length % 4) % 4);
const base64 = (plainString + padding).replace(/-/g, "+").replace(/_/g, "/");
const rawData = atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
const api = {

@@ -50,3 +40,3 @@ async getConfig({ token, project, baseURL }) {

}
}).then((x) => x.json()).then((x) => __spreadProps(__spreadValues({}, x.push_subscription), { baseURL, safariPushURL: `${baseURL}/safari/push` }));
}).then((x) => x.json()).then((x) => __spreadProps(__spreadValues({}, x.push_subscription), { baseURL }));
},

@@ -68,3 +58,3 @@ async updateSubscription({ token, project, baseURL }, subscription) {

};
async function registerServiceWorker({ path = "/sw.js" }) {
async function registerServiceWorker({ path = "/sw.js" } = {}) {
if (navigator.serviceWorker.controller)

@@ -76,46 +66,21 @@ return navigator.serviceWorker.ready;

async function subscribe(options) {
const requestOptions = __spreadProps(__spreadValues({}, options), { baseURL: options.host || location.origin });
const config = await api.getConfig(requestOptions);
if (!("PushManager" in window) && !("safari" in window)) {
if (!("PushManager" in window)) {
throw new Error("Push notifications are not supported in this browser");
}
const subscription = !("PushManager" in window) ? await createSafariPushSubscription(config) : await createPushSubscription(__spreadValues(__spreadValues({}, options), config));
if (!("endpoint" in subscription))
return;
await api.updateSubscription(requestOptions, subscription);
const baseURL = options.host || location.origin;
const config = await api.getConfig(__spreadProps(__spreadValues({}, options), { baseURL }));
const registration = await registerServiceWorker({ path: options.serviceWorkerPath });
const activeSubscription = await registration.pushManager.getSubscription();
if (activeSubscription) {
await activeSubscription.unsubscribe().catch(() => void 0);
}
const applicationServerKey = config.project.vapid_public_key.replace(/=/g, "");
const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey }).then((x) => x.toJSON());
if (!("endpoint" in subscription)) {
throw new Error("Failed to subscribe to push notifications, browser did not return an subscription endpoint.");
}
await api.updateSubscription(__spreadProps(__spreadValues({}, options), { baseURL }), subscription);
}
async function createPushSubscription(config) {
const registration = await registerServiceWorker({ path: config.serviceWorkerPath });
const applicationServerKey = stringToUint8Array(config.project.vapid_public_key);
const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey });
return subscription.toJSON();
}
async function createSafariPushSubscription(config) {
const safari = "safari" in window ? window["safari"] : void 0;
if (!safari)
throw new Error("This is not Safari");
const permissionData = safari.pushNotification.permission(config.website_push_id);
if (permissionData.permission === "granted")
return permissionData;
if (permissionData.permission === "denied")
throw new Error("permission denied");
return new Promise(function(resolve, reject) {
safari.pushNotification.requestPermission(
config.safariPushURL,
config.website_push_id,
{ authenticationToken: config.user.id },
(permissionData2) => {
if (!permissionData2.deviceToken)
return reject(new Error("permission denied"));
resolve({
endpoint: permissionData2.deviceToken,
keys: { websitePushID: config.website_push_id },
platform: "safari"
});
}
);
});
}
exports.registerServiceWorker = registerServiceWorker;
exports.subscribe = subscribe;
//# sourceMappingURL=magicbell-webpush.cjs.js.map
/**
* @license @magicbell/webpush v1.0.0
* @license @magicbell/webpush v1.1.0
*

@@ -10,3 +10,3 @@ * Copyright (c) MagicBell Inc. and its affiliates.

"use strict";var d=Object.defineProperty,w=Object.defineProperties;var b=Object.getOwnPropertyDescriptors;var c=Object.getOwnPropertySymbols;var f=Object.prototype.hasOwnProperty,g=Object.prototype.propertyIsEnumerable;var u=(e,i,r)=>i in e?d(e,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[i]=r,o=(e,i)=>{for(var r in i||(i={}))f.call(i,r)&&u(e,r,i[r]);if(c)for(var r of c(i))g.call(i,r)&&u(e,r,i[r]);return e},a=(e,i)=>w(e,b(i));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});function l(e){const i="=".repeat((4-e.length%4)%4),r=(e+i).replace(/-/g,"+").replace(/_/g,"/"),t=atob(r),n=new Uint8Array(t.length);for(let s=0;s<t.length;++s)n[s]=t.charCodeAt(s);return n}const p={async getConfig({token:e,project:i,baseURL:r}){return fetch(`${r}/web_push_subscriptions?access_token=${e}&project=${i}`,{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"}}).then(t=>t.json()).then(t=>a(o({},t.push_subscription),{baseURL:r,safariPushURL:`${r}/safari/push`}))},async updateSubscription({token:e,project:i,baseURL:r},t){return fetch(`${r}/web_push_subscriptions?access_token=${e}&project=${i}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({web_push_subscription:{data:t}})}).then(n=>n.json()).then(n=>n.web_push_subscription)}};async function h({path:e="/sw.js"}){return navigator.serviceWorker.controller||await navigator.serviceWorker.register(e),navigator.serviceWorker.ready}async function _(e){const i=a(o({},e),{baseURL:e.host||location.origin}),r=await p.getConfig(i);if(!("PushManager"in window)&&!("safari"in window))throw new Error("Push notifications are not supported in this browser");const t="PushManager"in window?await y(o(o({},e),r)):await v(r);"endpoint"in t&&await p.updateSubscription(i,t)}async function y(e){const i=await h({path:e.serviceWorkerPath}),r=l(e.project.vapid_public_key);return(await i.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:r})).toJSON()}async function v(e){const i="safari"in window?window.safari:void 0;if(!i)throw new Error("This is not Safari");const r=i.pushNotification.permission(e.website_push_id);if(r.permission==="granted")return r;if(r.permission==="denied")throw new Error("permission denied");return new Promise(function(t,n){i.pushNotification.requestPermission(e.safariPushURL,e.website_push_id,{authenticationToken:e.user.id},s=>{if(!s.deviceToken)return n(new Error("permission denied"));t({endpoint:s.deviceToken,keys:{websitePushID:e.website_push_id},platform:"safari"})})})}exports.registerServiceWorker=h;exports.subscribe=_;
"use strict";var g=Object.defineProperty,w=Object.defineProperties;var l=Object.getOwnPropertyDescriptors;var c=Object.getOwnPropertySymbols;var v=Object.prototype.hasOwnProperty,f=Object.prototype.propertyIsEnumerable;var u=(e,t,i)=>t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,s=(e,t)=>{for(var i in t||(t={}))v.call(t,i)&&u(e,i,t[i]);if(c)for(var i of c(t))f.call(t,i)&&u(e,i,t[i]);return e},o=(e,t)=>w(e,l(t));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const p={async getConfig({token:e,project:t,baseURL:i}){return fetch(`${i}/web_push_subscriptions?access_token=${e}&project=${t}`,{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"}}).then(r=>r.json()).then(r=>o(s({},r.push_subscription),{baseURL:i}))},async updateSubscription({token:e,project:t,baseURL:i},r){return fetch(`${i}/web_push_subscriptions?access_token=${e}&project=${t}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({web_push_subscription:{data:r}})}).then(n=>n.json()).then(n=>n.web_push_subscription)}};async function b({path:e="/sw.js"}={}){return navigator.serviceWorker.controller||await navigator.serviceWorker.register(e),navigator.serviceWorker.ready}async function _(e){if(!("PushManager"in window))throw new Error("Push notifications are not supported in this browser");const t=e.host||location.origin,i=await p.getConfig(o(s({},e),{baseURL:t})),r=await b({path:e.serviceWorkerPath}),n=await r.pushManager.getSubscription();n&&await n.unsubscribe().catch(()=>{});const h=i.project.vapid_public_key.replace(/=/g,""),a=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:h}).then(d=>d.toJSON());if(!("endpoint"in a))throw new Error("Failed to subscribe to push notifications, browser did not return an subscription endpoint.");await p.updateSubscription(o(s({},e),{baseURL:t}),a)}exports.registerServiceWorker=b;exports.subscribe=_;
//# sourceMappingURL=magicbell-webpush.cjs.min.js.map
/**
* @license @magicbell/webpush v1.0.0
* @license @magicbell/webpush v1.1.0
*

@@ -29,12 +29,2 @@ * Copyright (c) MagicBell Inc. and its affiliates.

var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
function stringToUint8Array(plainString) {
const padding = "=".repeat((4 - plainString.length % 4) % 4);
const base64 = (plainString + padding).replace(/-/g, "+").replace(/_/g, "/");
const rawData = atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
const api = {

@@ -48,3 +38,3 @@ async getConfig({ token, project, baseURL }) {

}
}).then((x) => x.json()).then((x) => __spreadProps(__spreadValues({}, x.push_subscription), { baseURL, safariPushURL: `${baseURL}/safari/push` }));
}).then((x) => x.json()).then((x) => __spreadProps(__spreadValues({}, x.push_subscription), { baseURL }));
},

@@ -66,3 +56,3 @@ async updateSubscription({ token, project, baseURL }, subscription) {

};
async function registerServiceWorker({ path = "/sw.js" }) {
async function registerServiceWorker({ path = "/sw.js" } = {}) {
if (navigator.serviceWorker.controller)

@@ -74,44 +64,19 @@ return navigator.serviceWorker.ready;

async function subscribe(options) {
const requestOptions = __spreadProps(__spreadValues({}, options), { baseURL: options.host || location.origin });
const config = await api.getConfig(requestOptions);
if (!("PushManager" in window) && !("safari" in window)) {
if (!("PushManager" in window)) {
throw new Error("Push notifications are not supported in this browser");
}
const subscription = !("PushManager" in window) ? await createSafariPushSubscription(config) : await createPushSubscription(__spreadValues(__spreadValues({}, options), config));
if (!("endpoint" in subscription))
return;
await api.updateSubscription(requestOptions, subscription);
const baseURL = options.host || location.origin;
const config = await api.getConfig(__spreadProps(__spreadValues({}, options), { baseURL }));
const registration = await registerServiceWorker({ path: options.serviceWorkerPath });
const activeSubscription = await registration.pushManager.getSubscription();
if (activeSubscription) {
await activeSubscription.unsubscribe().catch(() => void 0);
}
const applicationServerKey = config.project.vapid_public_key.replace(/=/g, "");
const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey }).then((x) => x.toJSON());
if (!("endpoint" in subscription)) {
throw new Error("Failed to subscribe to push notifications, browser did not return an subscription endpoint.");
}
await api.updateSubscription(__spreadProps(__spreadValues({}, options), { baseURL }), subscription);
}
async function createPushSubscription(config) {
const registration = await registerServiceWorker({ path: config.serviceWorkerPath });
const applicationServerKey = stringToUint8Array(config.project.vapid_public_key);
const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey });
return subscription.toJSON();
}
async function createSafariPushSubscription(config) {
const safari = "safari" in window ? window["safari"] : void 0;
if (!safari)
throw new Error("This is not Safari");
const permissionData = safari.pushNotification.permission(config.website_push_id);
if (permissionData.permission === "granted")
return permissionData;
if (permissionData.permission === "denied")
throw new Error("permission denied");
return new Promise(function(resolve, reject) {
safari.pushNotification.requestPermission(
config.safariPushURL,
config.website_push_id,
{ authenticationToken: config.user.id },
(permissionData2) => {
if (!permissionData2.deviceToken)
return reject(new Error("permission denied"));
resolve({
endpoint: permissionData2.deviceToken,
keys: { websitePushID: config.website_push_id },
platform: "safari"
});
}
);
});
}
export {

@@ -118,0 +83,0 @@ registerServiceWorker,

/**
* @license @magicbell/webpush v1.0.0
* @license @magicbell/webpush v1.1.0
*

@@ -10,23 +10,17 @@ * Copyright (c) MagicBell Inc. and its affiliates.

var h = Object.defineProperty, w = Object.defineProperties;
var d = Object.getOwnPropertyDescriptors;
var w = Object.defineProperty, d = Object.defineProperties;
var g = Object.getOwnPropertyDescriptors;
var c = Object.getOwnPropertySymbols;
var b = Object.prototype.hasOwnProperty, f = Object.prototype.propertyIsEnumerable;
var u = (e, i, r) => i in e ? h(e, i, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[i] = r, o = (e, i) => {
for (var r in i || (i = {}))
b.call(i, r) && u(e, r, i[r]);
var f = Object.prototype.hasOwnProperty, v = Object.prototype.propertyIsEnumerable;
var p = (t, e, i) => e in t ? w(t, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[e] = i, s = (t, e) => {
for (var i in e || (e = {}))
f.call(e, i) && p(t, i, e[i]);
if (c)
for (var r of c(i))
f.call(i, r) && u(e, r, i[r]);
return e;
}, a = (e, i) => w(e, d(i));
function _(e) {
const i = "=".repeat((4 - e.length % 4) % 4), r = (e + i).replace(/-/g, "+").replace(/_/g, "/"), t = atob(r), n = new Uint8Array(t.length);
for (let s = 0; s < t.length; ++s)
n[s] = t.charCodeAt(s);
return n;
}
const p = {
async getConfig({ token: e, project: i, baseURL: r }) {
return fetch(`${r}/web_push_subscriptions?access_token=${e}&project=${i}`, {
for (var i of c(e))
v.call(e, i) && p(t, i, e[i]);
return t;
}, o = (t, e) => d(t, g(e));
const u = {
async getConfig({ token: t, project: e, baseURL: i }) {
return fetch(`${i}/web_push_subscriptions?access_token=${t}&project=${e}`, {
method: "GET",

@@ -37,6 +31,6 @@ headers: {

}
}).then((t) => t.json()).then((t) => a(o({}, t.push_subscription), { baseURL: r, safariPushURL: `${r}/safari/push` }));
}).then((r) => r.json()).then((r) => o(s({}, r.push_subscription), { baseURL: i }));
},
async updateSubscription({ token: e, project: i, baseURL: r }, t) {
return fetch(`${r}/web_push_subscriptions?access_token=${e}&project=${i}`, {
async updateSubscription({ token: t, project: e, baseURL: i }, r) {
return fetch(`${i}/web_push_subscriptions?access_token=${t}&project=${e}`, {
method: "POST",

@@ -49,3 +43,3 @@ headers: {

web_push_subscription: {
data: t
data: r
}

@@ -56,46 +50,20 @@ })

};
async function g({ path: e = "/sw.js" }) {
return navigator.serviceWorker.controller || await navigator.serviceWorker.register(e), navigator.serviceWorker.ready;
async function l({ path: t = "/sw.js" } = {}) {
return navigator.serviceWorker.controller || await navigator.serviceWorker.register(t), navigator.serviceWorker.ready;
}
async function k(e) {
const i = a(o({}, e), { baseURL: e.host || location.origin }), r = await p.getConfig(i);
if (!("PushManager" in window) && !("safari" in window))
async function _(t) {
if (!("PushManager" in window))
throw new Error("Push notifications are not supported in this browser");
const t = "PushManager" in window ? await y(o(o({}, e), r)) : await l(r);
"endpoint" in t && await p.updateSubscription(i, t);
}
async function y(e) {
const i = await g({ path: e.serviceWorkerPath }), r = _(e.project.vapid_public_key);
return (await i.pushManager.subscribe({ userVisibleOnly: !0, applicationServerKey: r })).toJSON();
}
async function l(e) {
const i = "safari" in window ? window.safari : void 0;
if (!i)
throw new Error("This is not Safari");
const r = i.pushNotification.permission(e.website_push_id);
if (r.permission === "granted")
return r;
if (r.permission === "denied")
throw new Error("permission denied");
return new Promise(function(t, n) {
i.pushNotification.requestPermission(
e.safariPushURL,
e.website_push_id,
{ authenticationToken: e.user.id },
(s) => {
if (!s.deviceToken)
return n(new Error("permission denied"));
t({
endpoint: s.deviceToken,
keys: { websitePushID: e.website_push_id },
platform: "safari"
});
}
);
const e = t.host || location.origin, i = await u.getConfig(o(s({}, t), { baseURL: e })), r = await l({ path: t.serviceWorkerPath }), n = await r.pushManager.getSubscription();
n && await n.unsubscribe().catch(() => {
});
const b = i.project.vapid_public_key.replace(/=/g, ""), a = await r.pushManager.subscribe({ userVisibleOnly: !0, applicationServerKey: b }).then((h) => h.toJSON());
if (!("endpoint" in a))
throw new Error("Failed to subscribe to push notifications, browser did not return an subscription endpoint.");
await u.updateSubscription(o(s({}, t), { baseURL: e }), a);
}
export {
g as registerServiceWorker,
k as subscribe
l as registerServiceWorker,
_ as subscribe
};
//# sourceMappingURL=magicbell-webpush.esm.min.js.map
{
"name": "@magicbell/webpush",
"version": "1.0.0",
"version": "1.1.0",
"description": "MagicBell WebPush SDK",

@@ -5,0 +5,0 @@ "author": "MagicBell <bot@magicbell.io> (https://magicbell.com)",

@@ -1,15 +0,1 @@

function stringToUint8Array(plainString: string) {
const padding = '='.repeat((4 - (plainString.length % 4)) % 4);
const base64 = (plainString + padding).replace(/-/g, '+').replace(/_/g, '/');
const rawData = atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
type RequestOptions = {

@@ -25,5 +11,2 @@ token: string;

website_push_id: string;
baseURL: string;
safariPushURL: string;
serviceWorkerPath?: string;
};

@@ -40,4 +23,4 @@

})
.then((x) => x.json() as Promise<{ push_subscription: Omit<Config, 'baseURL' | 'safariPushURL'> }>)
.then((x) => ({ ...x.push_subscription, baseURL, safariPushURL: `${baseURL}/safari/push` }));
.then((x) => x.json() as Promise<{ push_subscription: Config }>)
.then((x) => ({ ...x.push_subscription, baseURL }));
},

@@ -63,3 +46,3 @@

export async function registerServiceWorker({ path = '/sw.js' }: { path: string }) {
export async function registerServiceWorker({ path = '/sw.js' }: { path?: string } = {}) {
// don't register a service-worker if there's already one

@@ -80,48 +63,28 @@ if (navigator.serviceWorker.controller) return navigator.serviceWorker.ready;

}) {
const requestOptions = { ...options, baseURL: options.host || location.origin };
const config = await api.getConfig(requestOptions);
if (!('PushManager' in window) && !('safari' in window)) {
if (!('PushManager' in window)) {
throw new Error('Push notifications are not supported in this browser');
}
const subscription = !('PushManager' in window)
? await createSafariPushSubscription(config)
: await createPushSubscription({ ...options, ...config });
const baseURL = options.host || location.origin;
const config = await api.getConfig({ ...options, baseURL });
const registration = await registerServiceWorker({ path: options.serviceWorkerPath });
if (!('endpoint' in subscription)) return;
await api.updateSubscription(requestOptions, subscription);
}
// remove active subscription if there's any
const activeSubscription = await registration.pushManager.getSubscription();
if (activeSubscription) {
await activeSubscription.unsubscribe().catch(() => void 0);
}
async function createPushSubscription(config: Config): Promise<PushSubscriptionJSON> {
const registration = await registerServiceWorker({ path: config.serviceWorkerPath });
const applicationServerKey = stringToUint8Array(config.project.vapid_public_key);
const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey });
return subscription.toJSON();
}
// strip the base64 padding, it's either that or convert to uint8array
const applicationServerKey = config.project.vapid_public_key.replace(/=/g, '');
async function createSafariPushSubscription(config: Config): Promise<PushSubscriptionJSON> {
const safari = 'safari' in window ? (window['safari'] as any) : undefined;
if (!safari) throw new Error('This is not Safari');
const subscription = await registration.pushManager
.subscribe({ userVisibleOnly: true, applicationServerKey })
.then((x) => x.toJSON());
const permissionData = safari.pushNotification.permission(config.website_push_id);
if (permissionData.permission === 'granted') return permissionData;
if (permissionData.permission === 'denied') throw new Error('permission denied');
if (!('endpoint' in subscription)) {
throw new Error('Failed to subscribe to push notifications, browser did not return an subscription endpoint.');
}
return new Promise<PushSubscriptionJSON & { platform: string }>(function (resolve, reject) {
safari.pushNotification.requestPermission(
config.safariPushURL,
config.website_push_id,
{ authenticationToken: config.user.id },
(permissionData: { deviceToken: string }) => {
if (!permissionData.deviceToken) return reject(new Error('permission denied'));
resolve({
endpoint: permissionData.deviceToken,
keys: { websitePushID: config.website_push_id },
platform: 'safari',
});
},
);
});
await api.updateSubscription({ ...options, baseURL }, subscription);
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc