Socket
Socket
Sign inDemoInstall

@twilio/notifications

Package Overview
Dependencies
14
Maintainers
1
Versions
78
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.1.0-rc.2 to 2.0.0-canary.102

394

builds/browser.js

@@ -35,5 +35,7 @@ /*

var _createClass = require('@babel/runtime/helpers/createClass');
var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
var _inherits = require('@babel/runtime/helpers/inherits');
var _possibleConstructorReturn = require('@babel/runtime/helpers/possibleConstructorReturn');
var _getPrototypeOf = require('@babel/runtime/helpers/getPrototypeOf');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _regeneratorRuntime = require('@babel/runtime/regenerator');

@@ -50,4 +52,2 @@ require('core-js/modules/es.array.iterator.js');

var twilsock = require('twilsock');
var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
require('core-js/modules/es.regexp.to-string.js');

@@ -62,3 +62,3 @@ require('core-js/modules/es.array.from.js');

var logger = require('loglevel');
var uuid = require('uuid');
var nanoid = require('nanoid');
var declarativeTypeValidator = require('@twilio/declarative-type-validator');

@@ -89,18 +89,17 @@

var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits);
var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn);
var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var logger__namespace = /*#__PURE__*/_interopNamespace(logger);
var uuid__namespace = /*#__PURE__*/_interopNamespace(uuid);
function __decorate(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if ((typeof Reflect === "undefined" ? "undefined" : _typeof__default["default"](Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {

@@ -588,7 +587,5 @@ if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;

var log = logger__namespace.getLogger("twilio-notificatiions");
function prepareLine(prefix, args) {
return ["".concat(new Date().toISOString(), " Twilio.Notifications ").concat(prefix, ":")].concat(Array.from(args));
}
var Logger = /*#__PURE__*/function () {

@@ -598,3 +595,2 @@ function Logger() {

}
_createClass__default["default"](Logger, [{

@@ -611,3 +607,2 @@ key: "setLevel",

}
log.trace.apply(null, prepareLine("T", args));

@@ -621,3 +616,2 @@ }

}
log.debug.apply(null, prepareLine("D", args));

@@ -631,3 +625,2 @@ }

}
log.info.apply(null, prepareLine("I", args));

@@ -641,3 +634,2 @@ }

}
log.warn.apply(null, prepareLine("W", args));

@@ -651,16 +643,11 @@ }

}
log.error.apply(null, prepareLine("E", args));
}
}]);
return Logger;
}();
var logInstance = new Logger();
function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var RegistrationState = /*#__PURE__*/_createClass__default["default"](function RegistrationState() {

@@ -670,5 +657,6 @@ var token = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";

var messageTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
_classCallCheck__default["default"](this, RegistrationState);
_defineProperty__default["default"](this, "token", void 0);
_defineProperty__default["default"](this, "notificationId", void 0);
_defineProperty__default["default"](this, "messageTypes", void 0);
this.token = token;

@@ -678,3 +666,2 @@ this.notificationId = notificationId;

});
function setDifference(a, b) {

@@ -687,40 +674,27 @@ return [].concat(_toConsumableArray__default["default"](_toConsumableArray__default["default"](a).filter(function (x) {

}
function hasDifference(a, b) {
var reasons = new Set();
if (a.notificationId !== b.notificationId) {
reasons.add("notificationId");
}
if (a.token !== b.token) {
reasons.add("token");
}
if (setDifference(a.messageTypes, b.messageTypes).length > 0) {
reasons.add("messageType");
}
return [reasons.size > 0, reasons];
}
var Connector = /*#__PURE__*/function (_EventEmitter) {
_inherits__default["default"](Connector, _EventEmitter);
var _super = _createSuper$3(Connector);
// @todo replace with FSM
function Connector(channelType) {
var _this;
_classCallCheck__default["default"](this, Connector);
_this = _super.call(this);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "channelType", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "desiredState", new RegistrationState());
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "currentState", new RegistrationState());
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "_hasActiveAttempt", false);
_this.channelType = channelType;

@@ -734,4 +708,2 @@ return _this;

*/
_createClass__default["default"](Connector, [{

@@ -745,3 +717,2 @@ key: "setNotificationId",

*/
}, {

@@ -759,3 +730,2 @@ key: "isActive",

}
this.desiredState.messageTypes.add(messageType);

@@ -769,3 +739,2 @@ }

}
this.desiredState.messageTypes.delete(messageType);

@@ -782,3 +751,2 @@ }

*/
}, {

@@ -789,3 +757,2 @@ key: "commitChanges",

var _hasDifference, _hasDifference2, needToUpdate, reasons, stateToPersist, persistedState;
return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {

@@ -799,10 +766,7 @@ while (1) {

}
// Concurrent access violation
logInstance.error("One registration attempt is already in progress");
throw new Error("One registration attempt is already in progress");
case 3:
_hasDifference = hasDifference(this.desiredState, this.currentState), _hasDifference2 = _slicedToArray__default["default"](_hasDifference, 2), needToUpdate = _hasDifference2[0], reasons = _hasDifference2[1];
if (needToUpdate) {

@@ -812,5 +776,3 @@ _context.next = 6;

}
return _context.abrupt("return");
case 6:

@@ -820,3 +782,2 @@ if (!this.currentState.notificationId) {

}
logInstance.trace("Persisting ".concat(this.channelType, " registration"), reasons, this.desiredState);

@@ -829,3 +790,2 @@ _context.prev = 8;

stateToPersist.messageTypes = new Set(this.desiredState.messageTypes);
if (!(stateToPersist.messageTypes.size > 0)) {

@@ -835,6 +795,4 @@ _context.next = 24;

}
_context.next = 17;
return this.updateRegistration(stateToPersist, reasons);
case 17:

@@ -844,12 +802,10 @@ persistedState = _context.sent;

this.currentState.notificationId = persistedState.notificationId;
this.currentState.messageTypes = new Set(persistedState.messageTypes); // @todo twilsock emits registered(notificationContextId) when this context is reg'd
this.currentState.messageTypes = new Set(persistedState.messageTypes);
// @todo twilsock emits registered(notificationContextId) when this context is reg'd
this.emit("stateChanged", this.channelType, "registered", this.currentState);
_context.next = 30;
break;
case 24:
_context.next = 26;
return this.removeRegistration();
case 26:

@@ -860,7 +816,5 @@ this.currentState.token = stateToPersist.token;

this.emit("stateChanged", this.channelType, "unregistered", this.currentState);
case 30:
_context.next = 35;
break;
case 32:

@@ -870,3 +824,2 @@ _context.prev = 32;

throw _context.t0;
case 35:

@@ -876,3 +829,2 @@ _context.prev = 35;

return _context.finish(35);
case 38:

@@ -885,11 +837,8 @@ case "end":

}));
function commitChanges() {
return _commitChanges.apply(this, arguments);
}
return commitChanges;
}()
}]);
return Connector;

@@ -899,3 +848,2 @@ }(EventEmitter);

function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

@@ -911,8 +859,5 @@ var retrierConfig = {

*/
var RegistrarConnector = /*#__PURE__*/function (_Connector) {
_inherits__default["default"](RegistrarConnector, _Connector);
var _super = _createSuper$2(RegistrarConnector);
/**

@@ -926,12 +871,12 @@ * Creates new instance of the ERS registrar

*/
function RegistrarConnector(channelType, context, // context is separate from config because it's not shared with other connectors
function RegistrarConnector(channelType, context,
// context is separate from config because it's not shared with other connectors
twilsock, registrarUrl) {
var _this;
_classCallCheck__default["default"](this, RegistrarConnector);
_this = _super.call(this, channelType);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "context", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "twilsock", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "registrarUrl", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "registrationId", null);
_this.context = context;

@@ -942,3 +887,2 @@ _this.twilsock = twilsock;

}
_createClass__default["default"](RegistrarConnector, [{

@@ -949,3 +893,2 @@ key: "updateRegistration",

var _this2 = this;
var registrarRequest, productId, url, headers, response;

@@ -960,6 +903,4 @@ return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {

}
_context.next = 3;
return this.removeRegistration();
case 3:

@@ -970,6 +911,4 @@ if (!(!registration.notificationId || !registration.notificationId.length)) {

}
logInstance.error("No push notification ID for registration");
throw new Error("No push notification ID for registration");
case 6:

@@ -984,4 +923,4 @@ logInstance.trace("Registering", this.channelType, registration);

registration_id: registration.notificationId
} //ttl: 'PT24H' - This is totally ignored by notify, all bindings use PT1Y ttl.
}
//ttl: 'PT24H' - This is totally ignored by notify, all bindings use PT1Y ttl.
};

@@ -991,29 +930,36 @@ productId = this.context.productId;

headers = {
"Content-Type": "application/json" // 'X-Twilio-Token': registration.token
"Content-Type": "application/json"
// 'X-Twilio-Token': registration.token
};
};
logInstance.trace("Creating registration for channel ".concat(this.channelType));
_context.prev = 12;
_context.next = 15;
_context.t0 = JSON;
_context.next = 16;
return new operationRetrier.AsyncRetrier(retrierConfig).run(function () {
return _this2.twilsock.post(url, headers, registrarRequest, productId);
return (
//this.twilsock.post(url, headers, registrarRequest, productId)
_this2.twilsock.post({
url: url,
headers: headers,
body: registrarRequest,
grant: productId
})
);
});
case 15:
response = _context.sent;
this.registrationId = response.body.id;
case 16:
_context.t1 = _context.sent.payload;
response = _context.t0.parse.call(_context.t0, _context.t1);
this.registrationId = response.id;
logInstance.debug("Registration created: ", response);
_context.next = 24;
_context.next = 26;
break;
case 20:
_context.prev = 20;
_context.t0 = _context["catch"](12);
logInstance.error("Registration failed: ", _context.t0);
throw _context.t0;
case 24:
case 22:
_context.prev = 22;
_context.t2 = _context["catch"](12);
logInstance.error("Registration failed: ", _context.t2);
throw _context.t2;
case 26:
return _context.abrupt("return", registration);
case 25:
case 27:
case "end":

@@ -1023,9 +969,7 @@ return _context.stop();

}
}, _callee, this, [[12, 20]]);
}, _callee, this, [[12, 22]]);
}));
function updateRegistration(_x, _x2) {
return _updateRegistration.apply(this, arguments);
}
return updateRegistration;

@@ -1038,3 +982,2 @@ }()

var _this3 = this;
var productId, url, headers;

@@ -1049,5 +992,3 @@ return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) {

}
return _context2.abrupt("return");
case 2:

@@ -1057,5 +998,6 @@ productId = this.context.productId;

headers = {
"Content-Type": "application/json" // 'X-Twilio-Token': this.config.token
"Content-Type": "application/json"
// 'X-Twilio-Token': this.config.token
};
};
logInstance.trace("Removing registration for ".concat(this.channelType));

@@ -1067,6 +1009,10 @@ _context2.prev = 6;

})).run(function () {
return _this3.twilsock.delete(url, headers, {}, productId);
return _this3.twilsock.delete({
url: url,
headers: headers,
grant: productId
});
});
case 9:
// ).run(() => this.twilsock.delete(url, headers, {}, productId));
this.registrationId = null;

@@ -1077,3 +1023,2 @@ this.currentState.notificationId = "";

break;
case 14:

@@ -1084,3 +1029,2 @@ _context2.prev = 14;

throw _context2.t0;
case 18:

@@ -1093,7 +1037,5 @@ case "end":

}));
function removeRegistration() {
return _removeRegistration.apply(this, arguments);
}
return removeRegistration;

@@ -1106,4 +1048,3 @@ }()

var _this4 = this;
var productId, url, headers, payload;
var productId, url, headers, body;
return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) {

@@ -1117,5 +1058,3 @@ while (1) {

}
throw new Error("Empty registration ID");
case 2:

@@ -1125,6 +1064,6 @@ productId = this.context.productId;

headers = {
"Content-Type": "application/json" // @todo Content-Length??
"Content-Type": "application/json"
// @todo Content-Length??
};
payload = {
body = {
binding_type: this.channelType,

@@ -1139,6 +1078,11 @@ address: registrationId

})).run(function () {
return _this4.twilsock.delete(url, headers, payload, productId);
return _this4.twilsock.delete({
url: url,
headers: headers,
body: body,
grant: productId
});
});
case 10:
// ).run(() => this.twilsock.delete(url, headers, payload, productId));
this.registrationId = null;

@@ -1149,3 +1093,2 @@ this.currentState.notificationId = "";

break;
case 15:

@@ -1156,3 +1099,2 @@ _context3.prev = 15;

throw _context3.t0;
case 19:

@@ -1165,11 +1107,8 @@ case "end":

}));
function sendDeviceRemoveRequest(_x3) {
return _sendDeviceRemoveRequest.apply(this, arguments);
}
return sendDeviceRemoveRequest;
}()
}]);
return RegistrarConnector;

@@ -1179,3 +1118,2 @@ }(Connector);

function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

@@ -1185,8 +1123,5 @@ /**

*/
var TwilsockConnector = /*#__PURE__*/function (_Connector) {
_inherits__default["default"](TwilsockConnector, _Connector);
var _super = _createSuper$1(TwilsockConnector);
/**

@@ -1200,9 +1135,8 @@ * Create twilsock registration connector.

var _this;
_classCallCheck__default["default"](this, TwilsockConnector);
_this = _super.call(this, "twilsock");
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "contextId", uuid__namespace.v4());
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "productId", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "platform", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "twilsock", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "contextId", nanoid.nanoid());
_this.productId = productId;

@@ -1213,3 +1147,2 @@ _this.platform = platform;

}
_createClass__default["default"](TwilsockConnector, [{

@@ -1219,3 +1152,3 @@ key: "updateRegistration",

var _updateRegistration = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(registration, reasons) {
var messageTypes, context;
var messageTypes;
return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {

@@ -1229,8 +1162,6 @@ while (1) {

}
return _context.abrupt("return", registration);
case 2:
messageTypes = Array.from(registration.messageTypes);
context = {
({
product_id: this.productId,

@@ -1240,21 +1171,14 @@ notification_protocol_version: 4,

message_types: messageTypes
};
});
_context.prev = 4;
_context.next = 7;
return this.twilsock.setNotificationsContext(this.contextId, context);
_context.next = 11;
break;
case 7:
_context.next = 13;
break;
case 9:
_context.prev = 9;
_context.prev = 7;
_context.t0 = _context["catch"](4);
logInstance.error("Failed to update twilsock notification context: ".concat(_context.t0));
throw _context.t0;
case 13:
case 11:
return _context.abrupt("return", registration);
case 14:
case 12:
case "end":

@@ -1264,9 +1188,7 @@ return _context.stop();

}
}, _callee, this, [[4, 9]]);
}, _callee, this, [[4, 7]]);
}));
function updateRegistration(_x, _x2) {
return _updateRegistration.apply(this, arguments);
}
return updateRegistration;

@@ -1283,16 +1205,10 @@ }()

_context2.prev = 0;
_context2.next = 3;
return this.twilsock.removeNotificationsContext(this.contextId);
_context2.next = 7;
break;
case 3:
_context2.next = 9;
break;
case 5:
_context2.prev = 5;
_context2.prev = 3;
_context2.t0 = _context2["catch"](0);
logInstance.error("Failed to remove twilsock notification context: ".concat(_context2.t0));
throw _context2.t0;
case 9:
case 7:
case "end":

@@ -1302,12 +1218,9 @@ return _context2.stop();

}
}, _callee2, this, [[0, 5]]);
}, _callee2, null, [[0, 3]]);
}));
function removeRegistration() {
return _removeRegistration.apply(this, arguments);
}
return removeRegistration;
}() // eslint-disable-next-line @typescript-eslint/no-unused-vars
}, {

@@ -1327,11 +1240,8 @@ key: "sendDeviceRemoveRequest",

}));
function sendDeviceRemoveRequest(_x3) {
return _sendDeviceRemoveRequest.apply(this, arguments);
}
return sendDeviceRemoveRequest;
}()
}]);
return TwilsockConnector;

@@ -1341,7 +1251,5 @@ }(Connector);

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Client_1;
// For validating Connector.ChannelType - keep synchronized!
var channelTypeRule = declarativeTypeValidator.literal("apn", "fcm", "twilsock");

@@ -1363,18 +1271,13 @@ /**

*/
exports.Notifications = Client_1 = /*#__PURE__*/function (_EventEmitter) {
_inherits__default["default"](Client, _EventEmitter);
var _super = _createSuper(Client);
function Client(token) {
var _options$logLevel, _options$productId, _options$twilsockClie, _options$notification, _ref, _config$region;
var _this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck__default["default"](this, Client);
_this = _super.call(this);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "twilsock", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "connectors", void 0);
options.logLevel = (_options$logLevel = options.logLevel) !== null && _options$logLevel !== void 0 ? _options$logLevel : "error";

@@ -1390,5 +1293,3 @@ logInstance.setLevel(options.logLevel);

_this.connectors = new Map();
var platform = Client_1._detectPlatform();
_this.connectors.set("apn", new RegistrarConnector("apn", {

@@ -1399,3 +1300,2 @@ protocolVersion: 4,

}, twilsock$1, registrarUrl));
_this.connectors.set("fcm", new RegistrarConnector("fcm", {

@@ -1406,30 +1306,28 @@ protocolVersion: 3,

}, twilsock$1, registrarUrl));
_this.connectors.set("twilsock", new TwilsockConnector(productId, platform, twilsock$1));
twilsock$1.on("stateChanged", function (state) {
return _this.emit("transportState", state);
twilsock$1.on("connecting", function () {
return _this.emit("transportState", "connecting");
});
twilsock$1.on("connected", function () {
return _this.emit("transportState", "connected");
});
twilsock$1.on("disconnected", function () {
return _this.emit("transportState", "disconnected");
});
_this._connector("twilsock").on("stateChanged", function (type, value, state) {
return _this.emit("stateChanged", type, value, state);
});
_this._connector("apn").on("stateChanged", function (type, value, state) {
return _this.emit("stateChanged", type, value, state);
});
_this._connector("fcm").on("stateChanged", function (type, value, state) {
return _this.emit("stateChanged", type, value, state);
}); // Router
twilsock$1.on("message", function (type, message) {
});
// Router
twilsock$1.on("targetedMessageReceived", function (type, message) {
return _this._routeMessage(type, message);
});
_this.updateToken(token); // Start only if we created twilsock locally,
_this.updateToken(token);
// Start only if we created twilsock locally,
// otherwise it's the responsibility of whoever created the Twilsock client.
if (startTwilsock) {

@@ -1439,6 +1337,4 @@ twilsock$1.connect();

}
return _this;
}
_createClass__default["default"](Client, [{

@@ -1453,3 +1349,2 @@ key: "shutdown",

this.connectors.clear();
if (!this.twilsock) {

@@ -1459,6 +1354,4 @@ _context.next = 4;

}
_context.next = 4;
return this.twilsock.disconnect();
case 4:

@@ -1471,18 +1364,14 @@ case "end":

}));
function shutdown() {
return _shutdown.apply(this, arguments);
}
return shutdown;
}()
/**
* Set OS-provided APNS/FCM registration binding for the given channel type. Not used for 'twilsock'.
*
* You must call this function once you've received the ID of your device from the underlying OS.
*
* @param {ChannelType} channelType Channel type ('apn'/'fcm').
* @param {string} pushRegistrationId Token received from FCM/APNS system on device.
*/
}() /**
* Set OS-provided APNS/FCM registration binding for the given channel type. Not used for 'twilsock'.
*
* You must call this function once you've received the ID of your device from the underlying OS.
*
* @param {ChannelType} channelType Channel type ('apn'/'fcm').
* @param {string} pushRegistrationId Token received from FCM/APNS system on device.
*/
}, {

@@ -1492,3 +1381,2 @@ key: "setPushRegistrationId",

logInstance.debug("Set ".concat(channelType, " push registration id '").concat(pushRegistrationId, "'"));
this._connector(channelType).setNotificationId(pushRegistrationId);

@@ -1509,3 +1397,2 @@ }

*/
}, {

@@ -1515,3 +1402,2 @@ key: "subscribe",

logInstance.debug("Add ".concat(channelType, " subscriptions for message type ").concat(messageType));
this._connector(channelType).subscribe(messageType);

@@ -1529,3 +1415,2 @@ }

*/
}, {

@@ -1535,3 +1420,2 @@ key: "unsubscribe",

logInstance.debug("Remove ".concat(channelType, " subscriptions for message type ").concat(messageType));
this._connector(channelType).unsubscribe(messageType);

@@ -1547,3 +1431,2 @@ }

*/
}, {

@@ -1560,3 +1443,2 @@ key: "updateToken",

*/
}, {

@@ -1579,3 +1461,2 @@ key: "commitChanges",

return Promise.all(promises);
case 4:

@@ -1588,20 +1469,16 @@ case "end":

}));
function commitChanges() {
return _commitChanges.apply(this, arguments);
}
return commitChanges;
}()
/**
* Clear existing registrations directly using provided device token.
* This is useful to ensure stopped subscriptions without resubscribing.
*
* This function goes completely beside the state machine and removes all registrations.
* Use with caution: if it races with current state machine operations, madness will ensue.
*
* @param {ChannelType} channelType Channel type ('apn'/'fcm').
* @param {string} registrationId Token received from FCM/APNS system on device.
*/
}() /**
* Clear existing registrations directly using provided device token.
* This is useful to ensure stopped subscriptions without resubscribing.
*
* This function goes completely beside the state machine and removes all registrations.
* Use with caution: if it races with current state machine operations, madness will ensue.
*
* @param {ChannelType} channelType Channel type ('apn'/'fcm').
* @param {string} registrationId Token received from FCM/APNS system on device.
*/
}, {

@@ -1617,3 +1494,2 @@ key: "removeRegistrations",

return this._connector(channelType).sendDeviceRemoveRequest(registrationId);
case 2:

@@ -1626,16 +1502,12 @@ case "end":

}));
function removeRegistrations(_x, _x2) {
return _removeRegistrations.apply(this, arguments);
}
return removeRegistrations;
}()
/**
* Handle incoming push notification.
* Client application should call this method when it receives push notifications and pass the received data.
* @param {Object} message push message
* @return {PushNotification} A reformatted payload with extracted message type.
*/
}() /**
* Handle incoming push notification.
* Client application should call this method when it receives push notifications and pass the received data.
* @param {Object} message push message
* @return {PushNotification} A reformatted payload with extracted message type.
*/
}, {

@@ -1652,3 +1524,2 @@ key: "handlePushNotification",

*/
}, {

@@ -1664,3 +1535,2 @@ key: "_routeMessage",

*/
}, {

@@ -1670,7 +1540,5 @@ key: "_connector",

var connector = this.connectors.get(type);
if (!connector) {
throw new Error("Unknown channel type: ".concat(type));
}
return connector;

@@ -1681,3 +1549,2 @@ }

*/
}], [{

@@ -1687,10 +1554,7 @@ key: "_detectPlatform",

var platform = "";
if (typeof navigator !== "undefined") {
platform = "unknown";
if (typeof navigator.product !== "undefined") {
platform = navigator.product;
}
if (typeof navigator.userAgent !== "undefined") {

@@ -1702,21 +1566,13 @@ platform = navigator.userAgent;

}
return platform.substring(0, 128);
}
}]);
return Client;
}(EventEmitter);
__decorate([declarativeTypeValidator.validateTypes(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "setPushRegistrationId", null);
__decorate([declarativeTypeValidator.validateTypes(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "subscribe", null);
__decorate([declarativeTypeValidator.validateTypes(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "unsubscribe", null);
__decorate([declarativeTypeValidator.validateTypes(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "updateToken", null);
__decorate([declarativeTypeValidator.validateTypesAsync(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", Promise)], exports.Notifications.prototype, "removeRegistrations", null);
exports.Notifications = Client_1 = __decorate([declarativeTypeValidator.validateConstructorTypes(declarativeTypeValidator.nonEmptyString, [declarativeTypeValidator.pureObject, "undefined", declarativeTypeValidator.literal(null)]), __metadata("design:paramtypes", [String, Object])], exports.Notifications);
//# sourceMappingURL=browser.js.map

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

/// <reference types="node" />
import { EventEmitter } from "events";
import { TwilsockClient, ConnectionState } from "twilsock";
import { TwilsockClient } from "twilsock";
import { LogLevelDesc } from "loglevel";

@@ -121,2 +122,2 @@ type ChannelType = "twilsock" | "apn" | "fcm";

}
export { Client as Notifications, ChannelType, ConnectionState, PushNotification };
export { Client as Notifications, ChannelType, PushNotification };

@@ -35,5 +35,7 @@ /*

var _createClass = require('@babel/runtime/helpers/createClass');
var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
var _inherits = require('@babel/runtime/helpers/inherits');
var _possibleConstructorReturn = require('@babel/runtime/helpers/possibleConstructorReturn');
var _getPrototypeOf = require('@babel/runtime/helpers/getPrototypeOf');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _regeneratorRuntime = require('@babel/runtime/regenerator');

@@ -51,4 +53,2 @@ require('core-js/modules/es.array.iterator.js');

var twilsock = require('twilsock');
var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
require('core-js/modules/es.regexp.to-string.js');

@@ -63,3 +63,3 @@ require('core-js/modules/es.array.from.js');

var logger = require('loglevel');
var uuid = require('uuid');
var nanoid = require('nanoid');
var declarativeTypeValidator = require('@twilio/declarative-type-validator');

@@ -90,18 +90,17 @@

var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits);
var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn);
var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var logger__namespace = /*#__PURE__*/_interopNamespace(logger);
var uuid__namespace = /*#__PURE__*/_interopNamespace(uuid);
function __decorate(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if ((typeof Reflect === "undefined" ? "undefined" : _typeof__default["default"](Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {

@@ -117,7 +116,5 @@ if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;

var log = logger__namespace.getLogger("twilio-notificatiions");
function prepareLine(prefix, args) {
return ["".concat(new Date().toISOString(), " Twilio.Notifications ").concat(prefix, ":")].concat(Array.from(args));
}
var Logger = /*#__PURE__*/function () {

@@ -127,3 +124,2 @@ function Logger() {

}
_createClass__default["default"](Logger, [{

@@ -140,3 +136,2 @@ key: "setLevel",

}
log.trace.apply(null, prepareLine("T", args));

@@ -150,3 +145,2 @@ }

}
log.debug.apply(null, prepareLine("D", args));

@@ -160,3 +154,2 @@ }

}
log.info.apply(null, prepareLine("I", args));

@@ -170,3 +163,2 @@ }

}
log.warn.apply(null, prepareLine("W", args));

@@ -180,16 +172,11 @@ }

}
log.error.apply(null, prepareLine("E", args));
}
}]);
return Logger;
}();
var logInstance = new Logger();
function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var RegistrationState = /*#__PURE__*/_createClass__default["default"](function RegistrationState() {

@@ -199,5 +186,6 @@ var token = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";

var messageTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
_classCallCheck__default["default"](this, RegistrationState);
_defineProperty__default["default"](this, "token", void 0);
_defineProperty__default["default"](this, "notificationId", void 0);
_defineProperty__default["default"](this, "messageTypes", void 0);
this.token = token;

@@ -207,3 +195,2 @@ this.notificationId = notificationId;

});
function setDifference(a, b) {

@@ -216,40 +203,27 @@ return [].concat(_toConsumableArray__default["default"](_toConsumableArray__default["default"](a).filter(function (x) {

}
function hasDifference(a, b) {
var reasons = new Set();
if (a.notificationId !== b.notificationId) {
reasons.add("notificationId");
}
if (a.token !== b.token) {
reasons.add("token");
}
if (setDifference(a.messageTypes, b.messageTypes).length > 0) {
reasons.add("messageType");
}
return [reasons.size > 0, reasons];
}
var Connector = /*#__PURE__*/function (_EventEmitter) {
_inherits__default["default"](Connector, _EventEmitter);
var _super = _createSuper$3(Connector);
// @todo replace with FSM
function Connector(channelType) {
var _this;
_classCallCheck__default["default"](this, Connector);
_this = _super.call(this);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "channelType", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "desiredState", new RegistrationState());
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "currentState", new RegistrationState());
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "_hasActiveAttempt", false);
_this.channelType = channelType;

@@ -263,4 +237,2 @@ return _this;

*/
_createClass__default["default"](Connector, [{

@@ -274,3 +246,2 @@ key: "setNotificationId",

*/
}, {

@@ -288,3 +259,2 @@ key: "isActive",

}
this.desiredState.messageTypes.add(messageType);

@@ -298,3 +268,2 @@ }

}
this.desiredState.messageTypes.delete(messageType);

@@ -311,3 +280,2 @@ }

*/
}, {

@@ -318,3 +286,2 @@ key: "commitChanges",

var _hasDifference, _hasDifference2, needToUpdate, reasons, stateToPersist, persistedState;
return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {

@@ -328,10 +295,7 @@ while (1) {

}
// Concurrent access violation
logInstance.error("One registration attempt is already in progress");
throw new Error("One registration attempt is already in progress");
case 3:
_hasDifference = hasDifference(this.desiredState, this.currentState), _hasDifference2 = _slicedToArray__default["default"](_hasDifference, 2), needToUpdate = _hasDifference2[0], reasons = _hasDifference2[1];
if (needToUpdate) {

@@ -341,5 +305,3 @@ _context.next = 6;

}
return _context.abrupt("return");
case 6:

@@ -349,3 +311,2 @@ if (!this.currentState.notificationId) {

}
logInstance.trace("Persisting ".concat(this.channelType, " registration"), reasons, this.desiredState);

@@ -358,3 +319,2 @@ _context.prev = 8;

stateToPersist.messageTypes = new Set(this.desiredState.messageTypes);
if (!(stateToPersist.messageTypes.size > 0)) {

@@ -364,6 +324,4 @@ _context.next = 24;

}
_context.next = 17;
return this.updateRegistration(stateToPersist, reasons);
case 17:

@@ -373,12 +331,10 @@ persistedState = _context.sent;

this.currentState.notificationId = persistedState.notificationId;
this.currentState.messageTypes = new Set(persistedState.messageTypes); // @todo twilsock emits registered(notificationContextId) when this context is reg'd
this.currentState.messageTypes = new Set(persistedState.messageTypes);
// @todo twilsock emits registered(notificationContextId) when this context is reg'd
this.emit("stateChanged", this.channelType, "registered", this.currentState);
_context.next = 30;
break;
case 24:
_context.next = 26;
return this.removeRegistration();
case 26:

@@ -389,7 +345,5 @@ this.currentState.token = stateToPersist.token;

this.emit("stateChanged", this.channelType, "unregistered", this.currentState);
case 30:
_context.next = 35;
break;
case 32:

@@ -399,3 +353,2 @@ _context.prev = 32;

throw _context.t0;
case 35:

@@ -405,3 +358,2 @@ _context.prev = 35;

return _context.finish(35);
case 38:

@@ -414,11 +366,8 @@ case "end":

}));
function commitChanges() {
return _commitChanges.apply(this, arguments);
}
return commitChanges;
}()
}]);
return Connector;

@@ -428,3 +377,2 @@ }(events.EventEmitter);

function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

@@ -440,8 +388,5 @@ var retrierConfig = {

*/
var RegistrarConnector = /*#__PURE__*/function (_Connector) {
_inherits__default["default"](RegistrarConnector, _Connector);
var _super = _createSuper$2(RegistrarConnector);
/**

@@ -455,12 +400,12 @@ * Creates new instance of the ERS registrar

*/
function RegistrarConnector(channelType, context, // context is separate from config because it's not shared with other connectors
function RegistrarConnector(channelType, context,
// context is separate from config because it's not shared with other connectors
twilsock, registrarUrl) {
var _this;
_classCallCheck__default["default"](this, RegistrarConnector);
_this = _super.call(this, channelType);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "context", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "twilsock", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "registrarUrl", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "registrationId", null);
_this.context = context;

@@ -471,3 +416,2 @@ _this.twilsock = twilsock;

}
_createClass__default["default"](RegistrarConnector, [{

@@ -478,3 +422,2 @@ key: "updateRegistration",

var _this2 = this;
var registrarRequest, productId, url, headers, response;

@@ -489,6 +432,4 @@ return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {

}
_context.next = 3;
return this.removeRegistration();
case 3:

@@ -499,6 +440,4 @@ if (!(!registration.notificationId || !registration.notificationId.length)) {

}
logInstance.error("No push notification ID for registration");
throw new Error("No push notification ID for registration");
case 6:

@@ -513,4 +452,4 @@ logInstance.trace("Registering", this.channelType, registration);

registration_id: registration.notificationId
} //ttl: 'PT24H' - This is totally ignored by notify, all bindings use PT1Y ttl.
}
//ttl: 'PT24H' - This is totally ignored by notify, all bindings use PT1Y ttl.
};

@@ -520,29 +459,36 @@ productId = this.context.productId;

headers = {
"Content-Type": "application/json" // 'X-Twilio-Token': registration.token
"Content-Type": "application/json"
// 'X-Twilio-Token': registration.token
};
};
logInstance.trace("Creating registration for channel ".concat(this.channelType));
_context.prev = 12;
_context.next = 15;
_context.t0 = JSON;
_context.next = 16;
return new operationRetrier.AsyncRetrier(retrierConfig).run(function () {
return _this2.twilsock.post(url, headers, registrarRequest, productId);
return (
//this.twilsock.post(url, headers, registrarRequest, productId)
_this2.twilsock.post({
url: url,
headers: headers,
body: registrarRequest,
grant: productId
})
);
});
case 15:
response = _context.sent;
this.registrationId = response.body.id;
case 16:
_context.t1 = _context.sent.payload;
response = _context.t0.parse.call(_context.t0, _context.t1);
this.registrationId = response.id;
logInstance.debug("Registration created: ", response);
_context.next = 24;
_context.next = 26;
break;
case 20:
_context.prev = 20;
_context.t0 = _context["catch"](12);
logInstance.error("Registration failed: ", _context.t0);
throw _context.t0;
case 24:
case 22:
_context.prev = 22;
_context.t2 = _context["catch"](12);
logInstance.error("Registration failed: ", _context.t2);
throw _context.t2;
case 26:
return _context.abrupt("return", registration);
case 25:
case 27:
case "end":

@@ -552,9 +498,7 @@ return _context.stop();

}
}, _callee, this, [[12, 20]]);
}, _callee, this, [[12, 22]]);
}));
function updateRegistration(_x, _x2) {
return _updateRegistration.apply(this, arguments);
}
return updateRegistration;

@@ -567,3 +511,2 @@ }()

var _this3 = this;
var productId, url, headers;

@@ -578,5 +521,3 @@ return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) {

}
return _context2.abrupt("return");
case 2:

@@ -586,5 +527,6 @@ productId = this.context.productId;

headers = {
"Content-Type": "application/json" // 'X-Twilio-Token': this.config.token
"Content-Type": "application/json"
// 'X-Twilio-Token': this.config.token
};
};
logInstance.trace("Removing registration for ".concat(this.channelType));

@@ -596,6 +538,10 @@ _context2.prev = 6;

})).run(function () {
return _this3.twilsock.delete(url, headers, {}, productId);
return _this3.twilsock.delete({
url: url,
headers: headers,
grant: productId
});
});
case 9:
// ).run(() => this.twilsock.delete(url, headers, {}, productId));
this.registrationId = null;

@@ -606,3 +552,2 @@ this.currentState.notificationId = "";

break;
case 14:

@@ -613,3 +558,2 @@ _context2.prev = 14;

throw _context2.t0;
case 18:

@@ -622,7 +566,5 @@ case "end":

}));
function removeRegistration() {
return _removeRegistration.apply(this, arguments);
}
return removeRegistration;

@@ -635,4 +577,3 @@ }()

var _this4 = this;
var productId, url, headers, payload;
var productId, url, headers, body;
return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) {

@@ -646,5 +587,3 @@ while (1) {

}
throw new Error("Empty registration ID");
case 2:

@@ -654,6 +593,6 @@ productId = this.context.productId;

headers = {
"Content-Type": "application/json" // @todo Content-Length??
"Content-Type": "application/json"
// @todo Content-Length??
};
payload = {
body = {
binding_type: this.channelType,

@@ -668,6 +607,11 @@ address: registrationId

})).run(function () {
return _this4.twilsock.delete(url, headers, payload, productId);
return _this4.twilsock.delete({
url: url,
headers: headers,
body: body,
grant: productId
});
});
case 10:
// ).run(() => this.twilsock.delete(url, headers, payload, productId));
this.registrationId = null;

@@ -678,3 +622,2 @@ this.currentState.notificationId = "";

break;
case 15:

@@ -685,3 +628,2 @@ _context3.prev = 15;

throw _context3.t0;
case 19:

@@ -694,11 +636,8 @@ case "end":

}));
function sendDeviceRemoveRequest(_x3) {
return _sendDeviceRemoveRequest.apply(this, arguments);
}
return sendDeviceRemoveRequest;
}()
}]);
return RegistrarConnector;

@@ -708,3 +647,2 @@ }(Connector);

function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

@@ -714,8 +652,5 @@ /**

*/
var TwilsockConnector = /*#__PURE__*/function (_Connector) {
_inherits__default["default"](TwilsockConnector, _Connector);
var _super = _createSuper$1(TwilsockConnector);
/**

@@ -729,9 +664,8 @@ * Create twilsock registration connector.

var _this;
_classCallCheck__default["default"](this, TwilsockConnector);
_this = _super.call(this, "twilsock");
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "contextId", uuid__namespace.v4());
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "productId", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "platform", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "twilsock", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "contextId", nanoid.nanoid());
_this.productId = productId;

@@ -742,3 +676,2 @@ _this.platform = platform;

}
_createClass__default["default"](TwilsockConnector, [{

@@ -748,3 +681,3 @@ key: "updateRegistration",

var _updateRegistration = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(registration, reasons) {
var messageTypes, context;
var messageTypes;
return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {

@@ -758,8 +691,6 @@ while (1) {

}
return _context.abrupt("return", registration);
case 2:
messageTypes = Array.from(registration.messageTypes);
context = {
({
product_id: this.productId,

@@ -769,21 +700,14 @@ notification_protocol_version: 4,

message_types: messageTypes
};
});
_context.prev = 4;
_context.next = 7;
return this.twilsock.setNotificationsContext(this.contextId, context);
_context.next = 11;
break;
case 7:
_context.next = 13;
break;
case 9:
_context.prev = 9;
_context.prev = 7;
_context.t0 = _context["catch"](4);
logInstance.error("Failed to update twilsock notification context: ".concat(_context.t0));
throw _context.t0;
case 13:
case 11:
return _context.abrupt("return", registration);
case 14:
case 12:
case "end":

@@ -793,9 +717,7 @@ return _context.stop();

}
}, _callee, this, [[4, 9]]);
}, _callee, this, [[4, 7]]);
}));
function updateRegistration(_x, _x2) {
return _updateRegistration.apply(this, arguments);
}
return updateRegistration;

@@ -812,16 +734,10 @@ }()

_context2.prev = 0;
_context2.next = 3;
return this.twilsock.removeNotificationsContext(this.contextId);
_context2.next = 7;
break;
case 3:
_context2.next = 9;
break;
case 5:
_context2.prev = 5;
_context2.prev = 3;
_context2.t0 = _context2["catch"](0);
logInstance.error("Failed to remove twilsock notification context: ".concat(_context2.t0));
throw _context2.t0;
case 9:
case 7:
case "end":

@@ -831,12 +747,9 @@ return _context2.stop();

}
}, _callee2, this, [[0, 5]]);
}, _callee2, null, [[0, 3]]);
}));
function removeRegistration() {
return _removeRegistration.apply(this, arguments);
}
return removeRegistration;
}() // eslint-disable-next-line @typescript-eslint/no-unused-vars
}, {

@@ -856,11 +769,8 @@ key: "sendDeviceRemoveRequest",

}));
function sendDeviceRemoveRequest(_x3) {
return _sendDeviceRemoveRequest.apply(this, arguments);
}
return sendDeviceRemoveRequest;
}()
}]);
return TwilsockConnector;

@@ -870,7 +780,5 @@ }(Connector);

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Client_1;
// For validating Connector.ChannelType - keep synchronized!
var channelTypeRule = declarativeTypeValidator.literal("apn", "fcm", "twilsock");

@@ -892,18 +800,13 @@ /**

*/
exports.Notifications = Client_1 = /*#__PURE__*/function (_EventEmitter) {
_inherits__default["default"](Client, _EventEmitter);
var _super = _createSuper(Client);
function Client(token) {
var _options$logLevel, _options$productId, _options$twilsockClie, _options$notification, _ref, _config$region;
var _this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck__default["default"](this, Client);
_this = _super.call(this);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "twilsock", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "connectors", void 0);
options.logLevel = (_options$logLevel = options.logLevel) !== null && _options$logLevel !== void 0 ? _options$logLevel : "error";

@@ -919,5 +822,3 @@ logInstance.setLevel(options.logLevel);

_this.connectors = new Map();
var platform = Client_1._detectPlatform();
_this.connectors.set("apn", new RegistrarConnector("apn", {

@@ -928,3 +829,2 @@ protocolVersion: 4,

}, twilsock$1, registrarUrl));
_this.connectors.set("fcm", new RegistrarConnector("fcm", {

@@ -935,30 +835,28 @@ protocolVersion: 3,

}, twilsock$1, registrarUrl));
_this.connectors.set("twilsock", new TwilsockConnector(productId, platform, twilsock$1));
twilsock$1.on("stateChanged", function (state) {
return _this.emit("transportState", state);
twilsock$1.on("connecting", function () {
return _this.emit("transportState", "connecting");
});
twilsock$1.on("connected", function () {
return _this.emit("transportState", "connected");
});
twilsock$1.on("disconnected", function () {
return _this.emit("transportState", "disconnected");
});
_this._connector("twilsock").on("stateChanged", function (type, value, state) {
return _this.emit("stateChanged", type, value, state);
});
_this._connector("apn").on("stateChanged", function (type, value, state) {
return _this.emit("stateChanged", type, value, state);
});
_this._connector("fcm").on("stateChanged", function (type, value, state) {
return _this.emit("stateChanged", type, value, state);
}); // Router
twilsock$1.on("message", function (type, message) {
});
// Router
twilsock$1.on("targetedMessageReceived", function (type, message) {
return _this._routeMessage(type, message);
});
_this.updateToken(token); // Start only if we created twilsock locally,
_this.updateToken(token);
// Start only if we created twilsock locally,
// otherwise it's the responsibility of whoever created the Twilsock client.
if (startTwilsock) {

@@ -968,6 +866,4 @@ twilsock$1.connect();

}
return _this;
}
_createClass__default["default"](Client, [{

@@ -982,3 +878,2 @@ key: "shutdown",

this.connectors.clear();
if (!this.twilsock) {

@@ -988,6 +883,4 @@ _context.next = 4;

}
_context.next = 4;
return this.twilsock.disconnect();
case 4:

@@ -1000,18 +893,14 @@ case "end":

}));
function shutdown() {
return _shutdown.apply(this, arguments);
}
return shutdown;
}()
/**
* Set OS-provided APNS/FCM registration binding for the given channel type. Not used for 'twilsock'.
*
* You must call this function once you've received the ID of your device from the underlying OS.
*
* @param {ChannelType} channelType Channel type ('apn'/'fcm').
* @param {string} pushRegistrationId Token received from FCM/APNS system on device.
*/
}() /**
* Set OS-provided APNS/FCM registration binding for the given channel type. Not used for 'twilsock'.
*
* You must call this function once you've received the ID of your device from the underlying OS.
*
* @param {ChannelType} channelType Channel type ('apn'/'fcm').
* @param {string} pushRegistrationId Token received from FCM/APNS system on device.
*/
}, {

@@ -1021,3 +910,2 @@ key: "setPushRegistrationId",

logInstance.debug("Set ".concat(channelType, " push registration id '").concat(pushRegistrationId, "'"));
this._connector(channelType).setNotificationId(pushRegistrationId);

@@ -1038,3 +926,2 @@ }

*/
}, {

@@ -1044,3 +931,2 @@ key: "subscribe",

logInstance.debug("Add ".concat(channelType, " subscriptions for message type ").concat(messageType));
this._connector(channelType).subscribe(messageType);

@@ -1058,3 +944,2 @@ }

*/
}, {

@@ -1064,3 +949,2 @@ key: "unsubscribe",

logInstance.debug("Remove ".concat(channelType, " subscriptions for message type ").concat(messageType));
this._connector(channelType).unsubscribe(messageType);

@@ -1076,3 +960,2 @@ }

*/
}, {

@@ -1089,3 +972,2 @@ key: "updateToken",

*/
}, {

@@ -1108,3 +990,2 @@ key: "commitChanges",

return Promise.all(promises);
case 4:

@@ -1117,20 +998,16 @@ case "end":

}));
function commitChanges() {
return _commitChanges.apply(this, arguments);
}
return commitChanges;
}()
/**
* Clear existing registrations directly using provided device token.
* This is useful to ensure stopped subscriptions without resubscribing.
*
* This function goes completely beside the state machine and removes all registrations.
* Use with caution: if it races with current state machine operations, madness will ensue.
*
* @param {ChannelType} channelType Channel type ('apn'/'fcm').
* @param {string} registrationId Token received from FCM/APNS system on device.
*/
}() /**
* Clear existing registrations directly using provided device token.
* This is useful to ensure stopped subscriptions without resubscribing.
*
* This function goes completely beside the state machine and removes all registrations.
* Use with caution: if it races with current state machine operations, madness will ensue.
*
* @param {ChannelType} channelType Channel type ('apn'/'fcm').
* @param {string} registrationId Token received from FCM/APNS system on device.
*/
}, {

@@ -1146,3 +1023,2 @@ key: "removeRegistrations",

return this._connector(channelType).sendDeviceRemoveRequest(registrationId);
case 2:

@@ -1155,16 +1031,12 @@ case "end":

}));
function removeRegistrations(_x, _x2) {
return _removeRegistrations.apply(this, arguments);
}
return removeRegistrations;
}()
/**
* Handle incoming push notification.
* Client application should call this method when it receives push notifications and pass the received data.
* @param {Object} message push message
* @return {PushNotification} A reformatted payload with extracted message type.
*/
}() /**
* Handle incoming push notification.
* Client application should call this method when it receives push notifications and pass the received data.
* @param {Object} message push message
* @return {PushNotification} A reformatted payload with extracted message type.
*/
}, {

@@ -1181,3 +1053,2 @@ key: "handlePushNotification",

*/
}, {

@@ -1193,3 +1064,2 @@ key: "_routeMessage",

*/
}, {

@@ -1199,7 +1069,5 @@ key: "_connector",

var connector = this.connectors.get(type);
if (!connector) {
throw new Error("Unknown channel type: ".concat(type));
}
return connector;

@@ -1210,3 +1078,2 @@ }

*/
}], [{

@@ -1216,10 +1083,7 @@ key: "_detectPlatform",

var platform = "";
if (typeof navigator !== "undefined") {
platform = "unknown";
if (typeof navigator.product !== "undefined") {
platform = navigator.product;
}
if (typeof navigator.userAgent !== "undefined") {

@@ -1231,21 +1095,13 @@ platform = navigator.userAgent;

}
return platform.substring(0, 128);
}
}]);
return Client;
}(events.EventEmitter);
__decorate([declarativeTypeValidator.validateTypes(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "setPushRegistrationId", null);
__decorate([declarativeTypeValidator.validateTypes(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "subscribe", null);
__decorate([declarativeTypeValidator.validateTypes(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "unsubscribe", null);
__decorate([declarativeTypeValidator.validateTypes(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", void 0)], exports.Notifications.prototype, "updateToken", null);
__decorate([declarativeTypeValidator.validateTypesAsync(channelTypeRule, declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", Promise)], exports.Notifications.prototype, "removeRegistrations", null);
exports.Notifications = Client_1 = __decorate([declarativeTypeValidator.validateConstructorTypes(declarativeTypeValidator.nonEmptyString, [declarativeTypeValidator.pureObject, "undefined", declarativeTypeValidator.literal(null)]), __metadata("design:paramtypes", [String, Object])], exports.Notifications);
//# sourceMappingURL=lib.js.map

@@ -75,3 +75,5 @@ /*

this.connectors.set("twilsock", new TwilsockConnector.TwilsockConnector(productId, platform, twilsock$1));
twilsock$1.on("stateChanged", (state) => this.emit("transportState", state));
twilsock$1.on("connecting", () => this.emit("transportState", "connecting"));
twilsock$1.on("connected", () => this.emit("transportState", "connected"));
twilsock$1.on("disconnected", () => this.emit("transportState", "disconnected"));
this._connector("twilsock").on("stateChanged", (type, value, state) => this.emit("stateChanged", type, value, state));

@@ -81,3 +83,3 @@ this._connector("apn").on("stateChanged", (type, value, state) => this.emit("stateChanged", type, value, state));

// Router
twilsock$1.on("message", (type, message) => this._routeMessage(type, message));
twilsock$1.on("targetedMessageReceived", (type, message) => this._routeMessage(type, message));
this.updateToken(token);

@@ -84,0 +86,0 @@ // Start only if we created twilsock locally,

@@ -87,4 +87,11 @@ /*

try {
const response = (await new operationRetrier.AsyncRetrier(retrierConfig).run(() => this.twilsock.post(url, headers, registrarRequest, productId)));
this.registrationId = response.body.id;
const response = JSON.parse((await new operationRetrier.AsyncRetrier(retrierConfig).run(() =>
//this.twilsock.post(url, headers, registrarRequest, productId)
this.twilsock.post({
url,
headers,
body: registrarRequest,
grant: productId,
}))).payload);
this.registrationId = response.id;
logger.log.debug("Registration created: ", response);

@@ -111,3 +118,4 @@ }

try {
await new operationRetrier.AsyncRetrier(Object.assign(retrierConfig, { maxAttemptsCount: 3 })).run(() => this.twilsock.delete(url, headers, {}, productId));
await new operationRetrier.AsyncRetrier(Object.assign(retrierConfig, { maxAttemptsCount: 3 })).run(() => this.twilsock.delete({ url, headers, grant: productId }));
// ).run(() => this.twilsock.delete(url, headers, {}, productId));
this.registrationId = null;

@@ -132,3 +140,3 @@ this.currentState.notificationId = "";

};
const payload = {
const body = {
binding_type: this.channelType,

@@ -139,3 +147,4 @@ address: registrationId,

logger.log.trace(`Removing old registrations for ${this.channelType}`);
await new operationRetrier.AsyncRetrier(Object.assign(retrierConfig, { maxAttemptsCount: 3 })).run(() => this.twilsock.delete(url, headers, payload, productId));
await new operationRetrier.AsyncRetrier(Object.assign(retrierConfig, { maxAttemptsCount: 3 })).run(() => this.twilsock.delete({ url, headers, body, grant: productId }));
// ).run(() => this.twilsock.delete(url, headers, payload, productId));
this.registrationId = null;

@@ -142,0 +151,0 @@ this.currentState.notificationId = "";

@@ -30,26 +30,6 @@ /*

var uuid = require('uuid');
var connector = require('./connector.js');
var logger = require('./logger.js');
require('./logger.js');
var nanoid = require('nanoid');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var uuid__namespace = /*#__PURE__*/_interopNamespace(uuid);
/**

@@ -70,3 +50,3 @@ * Registrar connector implementation for twilsock -- @todo Drop twilsock.connector COMPLETELY?!

this.twilsock = twilsock;
this.contextId = uuid__namespace.v4();
this.contextId = nanoid.nanoid();
}

@@ -79,3 +59,3 @@ async updateRegistration(registration, reasons) {

const messageTypes = Array.from(registration.messageTypes);
const context = {
({
product_id: this.productId,

@@ -85,20 +65,6 @@ notification_protocol_version: 4,

message_types: messageTypes,
};
try {
await this.twilsock.setNotificationsContext(this.contextId, context);
}
catch (err) {
logger.log.error(`Failed to update twilsock notification context: ${err}`);
throw err;
}
});
return registration;
}
async removeRegistration() {
try {
await this.twilsock.removeNotificationsContext(this.contextId);
}
catch (err) {
logger.log.error(`Failed to remove twilsock notification context: ${err}`);
throw err;
}
}

@@ -105,0 +71,0 @@ // eslint-disable-next-line @typescript-eslint/no-unused-vars

{
"name": "@twilio/notifications",
"version": "1.1.0-rc.2",
"version": "2.0.0-canary.102+ffa80bf",
"description": "Client library for Twilio Notifications service",

@@ -29,4 +29,4 @@ "author": "Twilio",

"lint:fix": "npx eslint src test --ext .ts --fix",
"test:unit": "env FORCE_COLOR=1 NODE_ENV=test npx jest test/unit",
"test:integration": "env FORCE_COLOR=1 NODE_ENV=test npx jest test/integration",
"test:unit": "env FORCE_COLOR=1 NODE_ENV=test npx jest test/unit --coverageDirectory='coverage/unit'",
"test:integration": "env FORCE_COLOR=1 NODE_ENV=test npx jest test/integration --coverageDirectory='coverage/integration'",
"sourceMapReport:html": "npx source-map-explorer@2.5.2 ./builds/lib.js --html ./builds/lib.report.html",

@@ -43,8 +43,8 @@ "sourceMapReport:json": "npx source-map-explorer@2.5.2 ./builds/lib.js --json ./builds/lib.report.json",

"@babel/runtime": "^7.17.0",
"@twilio/declarative-type-validator": "^0.2.0-rc.0",
"@twilio/operation-retrier": "^4.0.8-rc.1",
"@twilio/declarative-type-validator": "~0.2.1",
"@twilio/operation-retrier": "~4.0.9",
"core-js": "^3.17.3",
"loglevel": "^1.6.3",
"twilsock": "^0.13.0-rc.2",
"uuid": "^3.4.0"
"loglevel": "^1.8.0",
"nanoid": "^3.3.4",
"twilsock": "~0.13.0-canary.102+ffa80bf"
},

@@ -75,7 +75,7 @@ "devDependencies": {

"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-ts": "^2.0.7",
"rollup-plugin-ts": "^3.0.2",
"ts-jest": "^27.0.2",
"tslib": "^2.4.0",
"twilio": "^3.64.0",
"typescript": "^4.3.2"
"typescript": "^4.8.4"
},

@@ -96,3 +96,4 @@ "engines": {

"last 2 UCAndroid versions"
]
],
"gitHead": "ffa80bf0c716eee60adc5e02c846f92c08fe78f8"
}
notifications-js-lib
====================
Notifications JavaScript client library
Notifications JavaScript client library.

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 too big to display

Sorry, the diff of this file is too big to display

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc