Skip to content

Commit 7aa7597

Browse files
committed
Changed from commonJS module to ESM.
1 parent f4ba922 commit 7aa7597

22 files changed

+812
-854
lines changed

Diff for: .eslintrc

+5-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
"env": {
44
"es6": true
55
},
6+
"parserOptions": {
7+
"sourceType": "module"
8+
},
69
"rules": {
710
"no-var": 2,
811
"no-const-assign": 2,
@@ -11,12 +14,12 @@
1114
"vars-on-top": 0,
1215
"no-use-before-define": 0,
1316
"space-before-function-paren": 0,
14-
"max-len": [1, 120, 2, {"ignoreComments": true, "ignoreUrls": true}],
17+
"max-len": [1, 120, 2, { "ignoreComments": true, "ignoreUrls": true }],
1518
"no-param-reassign": 0,
1619
"quote-props": 0,
1720
"wrap-iife": [2, "inside"],
1821
"import/no-unresolved": 0,
1922
"indent": 0,
20-
"no-buffer-constructor": 0, // We still support Node v4.
23+
"no-buffer-constructor": 0 // We still support Node v4.
2124
}
2225
}

Diff for: package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
"name": "web-push",
33
"version": "3.6.6",
44
"description": "Web Push library for Node.js",
5-
"main": "src/index.js",
5+
"type": "module",
6+
"exports": "./src/index.js",
67
"bin": {
78
"web-push": "src/cli.js"
89
},

Diff for: src/cli.js

+35-33
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
#! /usr/bin/env node
22
/* eslint consistent-return:0 */
3-
4-
'use strict';
5-
6-
const webPush = require('../src/index.js');
3+
import * as webPush from '../src/index.js';
4+
import minimist from 'minimist';
75

86
const printUsageDetails = () => {
97
const actions = [
@@ -50,9 +48,9 @@ const generateVapidKeys = returnJson => {
5048
} else {
5149
const outputLine = '\n=======================================\n';
5250
outputText = outputLine + '\n'
53-
+ 'Public Key:\n' + vapidKeys.publicKey + '\n\n'
54-
+ 'Private Key:\n' + vapidKeys.privateKey + '\n'
55-
+ outputLine;
51+
+ 'Public Key:\n' + vapidKeys.publicKey + '\n\n'
52+
+ 'Private Key:\n' + vapidKeys.privateKey + '\n'
53+
+ outputLine;
5654
}
5755

5856
console.log(outputText);
@@ -80,7 +78,7 @@ const sendNotification = args => {
8078
options.TTL = args.ttl;
8179
}
8280

83-
if (argv['vapid-subject'] || argv['vapid-pubkey'] || argv['vapid-pvtkey']) {
81+
if (args['vapid-subject'] || args['vapid-pubkey'] || args['vapid-pvtkey']) {
8482
options.vapidDetails = {
8583
subject: args['vapid-subject'] || null,
8684
publicKey: args['vapid-pubkey'] || null,
@@ -101,31 +99,35 @@ const sendNotification = args => {
10199
}
102100

103101
webPush.sendNotification(subscription, payload, options)
104-
.then(() => {
105-
console.log('Push message sent.');
106-
}, err => {
107-
console.log('Error sending push message: ');
108-
console.log(err);
109-
})
110-
.then(() => {
111-
process.exit(0);
112-
});
102+
.then(() => {
103+
console.log('Push message sent.');
104+
}, err => {
105+
console.log('Error sending push message: ');
106+
console.log(err);
107+
})
108+
.then(() => {
109+
process.exit(0);
110+
});
113111
};
114112

115-
const action = process.argv[2];
116-
const argv = require('minimist')(process.argv.slice(3));
117-
switch (action) {
118-
case 'send-notification':
119-
if (!argv.endpoint) {
120-
return printUsageDetails();
121-
}
113+
const executeCliAction = () => {
114+
const action = process.argv[2];
115+
const argv = minimist(process.argv.slice(3));
116+
switch (action) {
117+
case 'send-notification':
118+
if (!argv.endpoint) {
119+
return printUsageDetails();
120+
}
121+
122+
sendNotification(argv);
123+
break;
124+
case 'generate-vapid-keys':
125+
generateVapidKeys(argv.json || false);
126+
break;
127+
default:
128+
printUsageDetails();
129+
break;
130+
}
131+
};
122132

123-
sendNotification(argv);
124-
break;
125-
case 'generate-vapid-keys':
126-
generateVapidKeys(argv.json || false);
127-
break;
128-
default:
129-
printUsageDetails();
130-
break;
131-
}
133+
executeCliAction();

Diff for: src/encryption-helper.js

+5-11
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
'use strict';
1+
import crypto from 'crypto';
2+
import ece from 'http_ece';
23

3-
const crypto = require('crypto');
4-
const ece = require('http_ece');
5-
6-
const encrypt = function(userPublicKey, userAuth, payload, contentEncoding) {
4+
export function encrypt(userPublicKey, userAuth, payload, contentEncoding) {
75
if (!userPublicKey) {
86
throw new Error('No user public key provided for encryption.');
97
}
@@ -26,7 +24,7 @@ const encrypt = function(userPublicKey, userAuth, payload, contentEncoding) {
2624

2725
if (Buffer.from(userAuth, 'base64url').length < 16) {
2826
throw new Error('The subscription auth key should be at least 16 '
29-
+ 'bytes long');
27+
+ 'bytes long');
3028
}
3129

3230
if (typeof payload !== 'string' && !Buffer.isBuffer(payload)) {
@@ -55,8 +53,4 @@ const encrypt = function(userPublicKey, userAuth, payload, contentEncoding) {
5553
salt: salt,
5654
cipherText: cipherText
5755
};
58-
};
59-
60-
module.exports = {
61-
encrypt: encrypt
62-
};
56+
}

Diff for: src/index.js

+20-17
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,24 @@
1-
'use strict';
2-
3-
const vapidHelper = require('./vapid-helper.js');
4-
const encryptionHelper = require('./encryption-helper.js');
5-
const WebPushLib = require('./web-push-lib.js');
6-
const WebPushError = require('./web-push-error.js');
7-
const WebPushConstants = require('./web-push-constants.js');
1+
import { getVapidHeaders, generateVAPIDKeys } from './vapid-helper.js';
2+
import { encrypt } from './encryption-helper.js';
3+
import { WebPushLib } from './web-push-lib.js';
4+
import WebPushError from './web-push-error.js';
5+
import WebPushConstants from './web-push-constants.js';
86

97
const webPush = new WebPushLib();
108

11-
module.exports = {
12-
WebPushError: WebPushError,
13-
supportedContentEncodings: WebPushConstants.supportedContentEncodings,
14-
encrypt: encryptionHelper.encrypt,
15-
getVapidHeaders: vapidHelper.getVapidHeaders,
16-
generateVAPIDKeys: vapidHelper.generateVAPIDKeys,
17-
setGCMAPIKey: webPush.setGCMAPIKey,
18-
setVapidDetails: webPush.setVapidDetails,
19-
generateRequestDetails: webPush.generateRequestDetails,
20-
sendNotification: webPush.sendNotification.bind(webPush)
9+
const { supportedContentEncodings } = WebPushConstants;
10+
const { setGCMAPIKey, setVapidDetails, generateRequestDetails } = webPush;
11+
const sendNotification = webPush.sendNotification.bind(webPush);
12+
13+
// Exporting variables and functions
14+
export {
15+
WebPushError,
16+
supportedContentEncodings,
17+
encrypt, // renaming for clarity
18+
getVapidHeaders,
19+
generateVAPIDKeys,
20+
setGCMAPIKey,
21+
setVapidDetails,
22+
generateRequestDetails,
23+
sendNotification
2124
};

Diff for: src/urlsafe-base64-helper.js

+1-7
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
1-
'use strict';
2-
31
/**
42
* @param {string} base64
53
* @returns {boolean}
64
*/
7-
function validate(base64) {
5+
export function validate(base64) {
86
return /^[A-Za-z0-9\-_]+$/.test(base64);
97
}
10-
11-
module.exports = {
12-
validate: validate
13-
};

Diff for: src/vapid-helper.js

+19-31
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
'use strict';
1+
import crypto from 'crypto';
2+
import asn1 from 'asn1.js';
3+
import jws from 'jws';
4+
import { URL } from 'url';
25

3-
const crypto = require('crypto');
4-
const asn1 = require('asn1.js');
5-
const jws = require('jws');
6-
const { URL } = require('url');
7-
8-
const WebPushConstants = require('./web-push-constants.js');
9-
const urlBase64Helper = require('./urlsafe-base64-helper');
6+
import WebPushConstants from './web-push-constants.js';
7+
import * as urlBase64Helper from './urlsafe-base64-helper.js';
108

119
/**
1210
* DEFAULT_EXPIRATION is set to seconds in 12 hours
@@ -16,7 +14,7 @@ const DEFAULT_EXPIRATION_SECONDS = 12 * 60 * 60;
1614
// Maximum expiration is 24 hours according. (See VAPID spec)
1715
const MAX_EXPIRATION_SECONDS = 24 * 60 * 60;
1816

19-
const ECPrivateKeyASN = asn1.define('ECPrivateKey', function() {
17+
const ECPrivateKeyASN = asn1.define('ECPrivateKey', function () {
2018
this.seq().obj(
2119
this.key('version').int(),
2220
this.key('privateKey').octstr(),
@@ -37,7 +35,7 @@ function toPEM(key) {
3735
});
3836
}
3937

40-
function generateVAPIDKeys() {
38+
export function generateVAPIDKeys() {
4139
const curve = crypto.createECDH('prime256v1');
4240
curve.generateKeys();
4341

@@ -65,14 +63,14 @@ function generateVAPIDKeys() {
6563
};
6664
}
6765

68-
function validateSubject(subject) {
66+
export function validateSubject(subject) {
6967
if (!subject) {
7068
throw new Error('No subject set in vapidDetails.subject.');
7169
}
7270

7371
if (typeof subject !== 'string' || subject.length === 0) {
7472
throw new Error('The subject value must be a string containing an https: URL or '
75-
+ 'mailto: address. ' + subject);
73+
+ 'mailto: address. ' + subject);
7674
}
7775

7876
let subjectParseResult = null;
@@ -88,17 +86,17 @@ function validateSubject(subject) {
8886
console.warn('Vapid subject points to a localhost web URI, which is unsupported by '
8987
+ 'Apple\'s push notification server and will result in a BadJwtToken error when '
9088
+ 'sending notifications.');
91-
}
89+
}
9290
}
9391

94-
function validatePublicKey(publicKey) {
92+
export function validatePublicKey(publicKey) {
9593
if (!publicKey) {
9694
throw new Error('No key set vapidDetails.publicKey');
9795
}
9896

9997
if (typeof publicKey !== 'string') {
10098
throw new Error('Vapid public key is must be a URL safe Base 64 '
101-
+ 'encoded string.');
99+
+ 'encoded string.');
102100
}
103101

104102
if (!urlBase64Helper.validate(publicKey)) {
@@ -112,14 +110,14 @@ function validatePublicKey(publicKey) {
112110
}
113111
}
114112

115-
function validatePrivateKey(privateKey) {
113+
export function validatePrivateKey(privateKey) {
116114
if (!privateKey) {
117115
throw new Error('No key set in vapidDetails.privateKey');
118116
}
119117

120118
if (typeof privateKey !== 'string') {
121119
throw new Error('Vapid private key must be a URL safe Base 64 '
122-
+ 'encoded string.');
120+
+ 'encoded string.');
123121
}
124122

125123
if (!urlBase64Helper.validate(privateKey)) {
@@ -141,7 +139,7 @@ function validatePrivateKey(privateKey) {
141139
* @param {Number} numSeconds Number of seconds to be added
142140
* @return {Number} Future expiration in seconds
143141
*/
144-
function getFutureExpirationTimestamp(numSeconds) {
142+
export function getFutureExpirationTimestamp(numSeconds) {
145143
const futureExp = new Date();
146144
futureExp.setSeconds(futureExp.getSeconds() + numSeconds);
147145
return Math.floor(futureExp.getTime() / 1000);
@@ -153,7 +151,7 @@ function getFutureExpirationTimestamp(numSeconds) {
153151
*
154152
* @param {Number} expiration Expiration seconds from Epoch to be validated
155153
*/
156-
function validateExpiration(expiration) {
154+
export function validateExpiration(expiration) {
157155
if (!Number.isInteger(expiration)) {
158156
throw new Error('`expiration` value must be a number');
159157
}
@@ -184,14 +182,14 @@ function validateExpiration(expiration) {
184182
* @return {Object} Returns an Object with the Authorization and
185183
* 'Crypto-Key' values to be used as headers.
186184
*/
187-
function getVapidHeaders(audience, subject, publicKey, privateKey, contentEncoding, expiration) {
185+
export function getVapidHeaders(audience, subject, publicKey, privateKey, contentEncoding, expiration) {
188186
if (!audience) {
189187
throw new Error('No audience could be generated for VAPID.');
190188
}
191189

192190
if (typeof audience !== 'string' || audience.length === 0) {
193191
throw new Error('The audience value must be a string containing the '
194-
+ 'origin of a push service. ' + audience);
192+
+ 'origin of a push service. ' + audience);
195193
}
196194

197195
try {
@@ -243,13 +241,3 @@ function getVapidHeaders(audience, subject, publicKey, privateKey, contentEncodi
243241

244242
throw new Error('Unsupported encoding type specified.');
245243
}
246-
247-
module.exports = {
248-
generateVAPIDKeys: generateVAPIDKeys,
249-
getFutureExpirationTimestamp: getFutureExpirationTimestamp,
250-
getVapidHeaders: getVapidHeaders,
251-
validateSubject: validateSubject,
252-
validatePublicKey: validatePublicKey,
253-
validatePrivateKey: validatePrivateKey,
254-
validateExpiration: validateExpiration
255-
};

Diff for: src/web-push-constants.js

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
'use strict';
2-
31
const WebPushConstants = {};
42

53
WebPushConstants.supportedContentEncodings = {
@@ -14,4 +12,4 @@ WebPushConstants.supportedUrgency = {
1412
HIGH: 'high'
1513
};
1614

17-
module.exports = WebPushConstants;
15+
export default WebPushConstants;

Diff for: src/web-push-error.js

+3-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
'use strict';
1+
import util from 'util';
22

3-
function WebPushError(message, statusCode, headers, body, endpoint) {
3+
export default function WebPushError(message, statusCode, headers, body, endpoint) {
44
Error.captureStackTrace(this, this.constructor);
55

66
this.name = this.constructor.name;
@@ -11,6 +11,4 @@ function WebPushError(message, statusCode, headers, body, endpoint) {
1111
this.endpoint = endpoint;
1212
}
1313

14-
require('util').inherits(WebPushError, Error);
15-
16-
module.exports = WebPushError;
14+
util.inherits(WebPushError, Error);

0 commit comments

Comments
 (0)