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 0.1.3 to 1.0.0

4

dist/index.d.ts

@@ -0,1 +1,4 @@

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

@@ -8,2 +11,3 @@ * Request permission to send push notifications and post the subscription to the MagicBell API.

host?: string;
serviceWorkerPath?: string;
}): Promise<void>;

2

dist/index.js
/**
* @license @magicbell/webpush v0.1.3
* @license @magicbell/webpush v1.0.0
*

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

/**
* @license @magicbell/webpush v0.1.3
* @license @magicbell/webpush v1.0.0
*

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

};
async function registerServiceWorker({ path = "/sw.js" }) {
if (navigator.serviceWorker.controller)
return navigator.serviceWorker.ready;
await navigator.serviceWorker.register(path);
return navigator.serviceWorker.ready;
}
async function subscribe(options) {

@@ -73,3 +79,3 @@ const requestOptions = __spreadProps(__spreadValues({}, options), { baseURL: options.host || location.origin });

}
const subscription = !("PushManager" in window) ? await createSafariPushSubscription(config) : await createPushSubscription(config);
const subscription = !("PushManager" in window) ? await createSafariPushSubscription(config) : await createPushSubscription(__spreadValues(__spreadValues({}, options), config));
if (!("endpoint" in subscription))

@@ -80,4 +86,3 @@ return;

async function createPushSubscription(config) {
await navigator.serviceWorker.register("/sw.js");
const registration = await navigator.serviceWorker.ready;
const registration = await registerServiceWorker({ path: config.serviceWorkerPath });
const applicationServerKey = stringToUint8Array(config.project.vapid_public_key);

@@ -113,3 +118,4 @@ const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey });

}
exports.registerServiceWorker = registerServiceWorker;
exports.subscribe = subscribe;
//# sourceMappingURL=magicbell-webpush.cjs.js.map
/**
* @license @magicbell/webpush v0.1.3
* @license @magicbell/webpush v1.0.0
*

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

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

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

};
async function registerServiceWorker({ path = "/sw.js" }) {
if (navigator.serviceWorker.controller)
return navigator.serviceWorker.ready;
await navigator.serviceWorker.register(path);
return navigator.serviceWorker.ready;
}
async function subscribe(options) {

@@ -71,3 +77,3 @@ const requestOptions = __spreadProps(__spreadValues({}, options), { baseURL: options.host || location.origin });

}
const subscription = !("PushManager" in window) ? await createSafariPushSubscription(config) : await createPushSubscription(config);
const subscription = !("PushManager" in window) ? await createSafariPushSubscription(config) : await createPushSubscription(__spreadValues(__spreadValues({}, options), config));
if (!("endpoint" in subscription))

@@ -78,4 +84,3 @@ return;

async function createPushSubscription(config) {
await navigator.serviceWorker.register("/sw.js");
const registration = await navigator.serviceWorker.ready;
const registration = await registerServiceWorker({ path: config.serviceWorkerPath });
const applicationServerKey = stringToUint8Array(config.project.vapid_public_key);

@@ -112,4 +117,5 @@ const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey });

export {
registerServiceWorker,
subscribe
};
//# sourceMappingURL=magicbell-webpush.esm.js.map
/**
* @license @magicbell/webpush v0.1.3
* @license @magicbell/webpush v1.0.0
*

@@ -14,19 +14,19 @@ * Copyright (c) MagicBell Inc. and its affiliates.

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

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

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

@@ -49,40 +49,42 @@ headers: {

web_push_subscription: {
data: n
data: t
}
})
}).then((s) => s.json()).then((s) => s.web_push_subscription);
}).then((n) => n.json()).then((n) => n.web_push_subscription);
}
};
async function P(i) {
const e = a(o({}, i), { baseURL: i.host || location.origin }), t = await u.getConfig(e);
async function g({ path: e = "/sw.js" }) {
return navigator.serviceWorker.controller || await navigator.serviceWorker.register(e), 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))
throw new Error("Push notifications are not supported in this browser");
const n = "PushManager" in window ? await g(t) : await y(t);
"endpoint" in n && await u.updateSubscription(e, n);
const t = "PushManager" in window ? await y(o(o({}, e), r)) : await l(r);
"endpoint" in t && await p.updateSubscription(i, t);
}
async function g(i) {
await navigator.serviceWorker.register("/sw.js");
const e = await navigator.serviceWorker.ready, t = _(i.project.vapid_public_key);
return (await e.pushManager.subscribe({ userVisibleOnly: !0, applicationServerKey: t })).toJSON();
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 y(i) {
const e = "safari" in window ? window.safari : void 0;
if (!e)
async function l(e) {
const i = "safari" in window ? window.safari : void 0;
if (!i)
throw new Error("This is not Safari");
const t = e.pushNotification.permission(i.website_push_id);
if (t.permission === "granted")
return t;
if (t.permission === "denied")
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(n, s) {
e.pushNotification.requestPermission(
i.safariPushURL,
i.website_push_id,
{ authenticationToken: i.user.id },
(r) => {
if (!r.deviceToken)
return s(new Error("permission denied"));
n({
endpoint: r.deviceToken,
keys: { websitePushID: i.website_push_id },
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"

@@ -95,4 +97,5 @@ });

export {
P as subscribe
g as registerServiceWorker,
k as subscribe
};
//# sourceMappingURL=magicbell-webpush.esm.min.js.map
{
"name": "@magicbell/webpush",
"version": "0.1.3",
"version": "1.0.0",
"description": "MagicBell WebPush SDK",

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

@@ -21,2 +21,4 @@ # MagicBell WebPush Library

### Subscribe
```js

@@ -28,6 +30,8 @@ import { subscribe } from '@magicbell/webpush';

host: 'https://api.magicbell.com',
project: 'string',
serviceWorkerPath: '/sw.js',
});
```
### Options
#### Options

@@ -42,2 +46,34 @@ **token** _String_

**project** _String_
The random subdomain that MagicBell generated for your service worker registration.
**serviceWorkerPath** _String_
The path to the service worker file. Defaults to `/sw.js`.
### Register a service worker
A helper that can be used to register a service worker, prior to calling `subscribe`. This preflight allows for a faster
subscription process. If this method isn't used, registration will be done during `subscribe`.
Registration will be skipped if a service worker is already registered. In which case, the
active registration will be returned.
The returned promise resolves when the registration is ready.
```js
import { registerServiceWorker } from '@magicbell/webpush';
registerServiceWorker({
path: '/sw.js',
});
```
#### Options
**path** _String_
The path to the service worker file. Defaults to `/sw.js`.
## Support

@@ -44,0 +80,0 @@

@@ -27,2 +27,3 @@ function stringToUint8Array(plainString: string) {

safariPushURL: string;
serviceWorkerPath?: string;
};

@@ -61,6 +62,18 @@

export async function registerServiceWorker({ path = '/sw.js' }: { path: string }) {
// don't register a service-worker if there's already one
if (navigator.serviceWorker.controller) return navigator.serviceWorker.ready;
await navigator.serviceWorker.register(path);
return navigator.serviceWorker.ready;
}
/**
* Request permission to send push notifications and post the subscription to the MagicBell API.
*/
export async function subscribe(options: { token: string; project: string; host?: string }) {
export async function subscribe(options: {
token: string;
project: string;
host?: string;
serviceWorkerPath?: string;
}) {
const requestOptions = { ...options, baseURL: options.host || location.origin };

@@ -75,3 +88,3 @@ const config = await api.getConfig(requestOptions);

? await createSafariPushSubscription(config)
: await createPushSubscription(config);
: await createPushSubscription({ ...options, ...config });

@@ -83,5 +96,3 @@ if (!('endpoint' in subscription)) return;

async function createPushSubscription(config: Config): Promise<PushSubscriptionJSON> {
await navigator.serviceWorker.register('/sw.js');
const registration = await navigator.serviceWorker.ready;
const registration = await registerServiceWorker({ path: config.serviceWorkerPath });
const applicationServerKey = stringToUint8Array(config.project.vapid_public_key);

@@ -88,0 +99,0 @@ const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey });

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