@trycourier/transport 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Courier
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.Transport = exports.CourierTransport = void 0;
7
+ var connectMock = jest.fn();
8
+ var renewSessionMock = jest.fn();
9
+ var CourierTransport = jest.fn().mockImplementation(function () {
10
+ return {
11
+ connect: connectMock,
12
+ renewSession: renewSessionMock
13
+ };
14
+ });
15
+ exports.CourierTransport = CourierTransport;
16
+ var transportMock = jest.fn();
17
+ var Transport = transportMock;
18
+ exports.Transport = Transport;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.WS = exports.mockRenewSession = exports.mockSend = exports.mockConnect = void 0;
7
+ var mockConnect = jest.fn();
8
+ exports.mockConnect = mockConnect;
9
+ var mockSend = jest.fn();
10
+ exports.mockSend = mockSend;
11
+ var mockRenewSession = jest.fn();
12
+ exports.mockRenewSession = mockRenewSession;
13
+ var mock = jest.fn().mockImplementation(function () {
14
+ return {
15
+ connect: mockConnect,
16
+ send: mockSend,
17
+ renewSession: mockRenewSession
18
+ };
19
+ });
20
+ var WS = mock;
21
+ exports.WS = WS;
package/dist/base.js ADDED
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.Transport = void 0;
9
+
10
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
11
+
12
+ var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
13
+
14
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
15
+
16
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
17
+
18
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
19
+
20
+ var ListenerType;
21
+
22
+ (function (ListenerType) {
23
+ ListenerType["message"] = "message";
24
+ ListenerType["event"] = "event";
25
+ })(ListenerType || (ListenerType = {}));
26
+
27
+ var Transport = function Transport() {
28
+ var _this = this;
29
+
30
+ (0, _classCallCheck2["default"])(this, Transport);
31
+
32
+ this.emit = function (courierEvent) {
33
+ var _courierEvent$type;
34
+
35
+ var eventType = (_courierEvent$type = courierEvent.type) !== null && _courierEvent$type !== void 0 ? _courierEvent$type : "message";
36
+ var listeners = _this.listeners[eventType];
37
+
38
+ if (!listeners.length) {
39
+ console.warn("No Listeners Registered");
40
+ return;
41
+ }
42
+
43
+ var _iterator = _createForOfIteratorHelper(listeners),
44
+ _step;
45
+
46
+ try {
47
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
48
+ var listener = _step.value.listener;
49
+ listener(courierEvent);
50
+ }
51
+ } catch (err) {
52
+ _iterator.e(err);
53
+ } finally {
54
+ _iterator.f();
55
+ }
56
+ };
57
+
58
+ this.listen = function (listener) {
59
+ var _listener$type;
60
+
61
+ var didReplaceListener = false;
62
+ var eventType = (_listener$type = listener.type) !== null && _listener$type !== void 0 ? _listener$type : "message";
63
+ var listeners = _this.listeners[eventType];
64
+ listeners = listeners.map(function (l) {
65
+ if (l.id === listener.id) {
66
+ didReplaceListener = true;
67
+ return listener;
68
+ }
69
+
70
+ return l;
71
+ });
72
+
73
+ if (didReplaceListener) {
74
+ _this.listeners[eventType] = listeners;
75
+ return;
76
+ }
77
+
78
+ _this.listeners[eventType] = [].concat((0, _toConsumableArray2["default"])(_this.listeners[eventType]), [listener]);
79
+ };
80
+
81
+ this.intercept = function (cb) {
82
+ _this.interceptor = cb;
83
+ };
84
+
85
+ this.listeners = {
86
+ message: [],
87
+ event: []
88
+ };
89
+ this.interceptor = undefined;
90
+ }
91
+ /** Callback for emitted events */
92
+
93
+ /** Wrapper method for emitted events */
94
+
95
+ /** Setter method for a listener */
96
+ ;
97
+
98
+ exports.Transport = Transport;
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.CourierTransport = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
13
+
14
+ var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
15
+
16
+ var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
17
+
18
+ var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
19
+
20
+ var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
21
+
22
+ var _ws = require("../ws");
23
+
24
+ var _base = require("../base");
25
+
26
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
27
+
28
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
29
+
30
+ function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
31
+
32
+ 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; } }
33
+
34
+ var CourierTransport = /*#__PURE__*/function (_Transport) {
35
+ (0, _inherits2["default"])(CourierTransport, _Transport);
36
+
37
+ var _super = _createSuper(CourierTransport);
38
+
39
+ function CourierTransport(options) {
40
+ var _options$wsOptions;
41
+
42
+ var _this;
43
+
44
+ (0, _classCallCheck2["default"])(this, CourierTransport);
45
+ _this = _super.call(this);
46
+ var clientKeyOptions = options;
47
+ var jwtOptions = options;
48
+
49
+ if (!clientKeyOptions.clientKey && !jwtOptions.authorization) {
50
+ throw new Error("Missing Authorization");
51
+ }
52
+
53
+ _this.authorization = jwtOptions.authorization;
54
+ _this.clientSourceId = options.clientSourceId;
55
+ _this.clientKey = clientKeyOptions.clientKey;
56
+ _this.userSignature = clientKeyOptions.userSignature;
57
+ _this.ws = new _ws.CourierWS({
58
+ tenantId: options.tenantId,
59
+ authorization: jwtOptions.authorization,
60
+ clientSourceId: options.clientSourceId,
61
+ clientKey: clientKeyOptions.clientKey,
62
+ options: options.wsOptions,
63
+ userSignature: clientKeyOptions.userSignature
64
+ });
65
+
66
+ if ((_options$wsOptions = options.wsOptions) !== null && _options$wsOptions !== void 0 && _options$wsOptions.onReconnect) {
67
+ var _options$wsOptions2;
68
+
69
+ _this.ws.onReconnection({
70
+ id: "propReconnect",
71
+ callback: (_options$wsOptions2 = options.wsOptions) === null || _options$wsOptions2 === void 0 ? void 0 : _options$wsOptions2.onReconnect
72
+ });
73
+ }
74
+
75
+ return _this;
76
+ }
77
+
78
+ (0, _createClass2["default"])(CourierTransport, [{
79
+ key: "closeConnection",
80
+ value: function closeConnection() {
81
+ this.ws.close();
82
+ }
83
+ }, {
84
+ key: "connect",
85
+ value: function connect() {
86
+ this.ws.connect();
87
+ }
88
+ }, {
89
+ key: "isConnected",
90
+ value: function isConnected() {
91
+ return this.ws.connected;
92
+ }
93
+ }, {
94
+ key: "keepAlive",
95
+ value: function keepAlive() {
96
+ this.ws.send({
97
+ action: "keepAlive"
98
+ });
99
+ }
100
+ }, {
101
+ key: "send",
102
+ value: function send(message) {
103
+ this.ws.send(_objectSpread(_objectSpread({}, message), {}, {
104
+ data: _objectSpread(_objectSpread({}, message.data), {}, {
105
+ clientKey: this.clientKey
106
+ })
107
+ }));
108
+ }
109
+ }, {
110
+ key: "subscribe",
111
+ value: function subscribe(channel, event) {
112
+ var _this2 = this;
113
+
114
+ this.ws.subscribe(channel, event !== null && event !== void 0 ? event : "*", function (_ref) {
115
+ var _courierEvent$type;
116
+
117
+ var courierEvent = _ref.data;
118
+
119
+ if (_this2.interceptor) {
120
+ courierEvent = _this2.interceptor(courierEvent);
121
+ }
122
+
123
+ if (!courierEvent) {
124
+ return;
125
+ }
126
+
127
+ _this2.emit({
128
+ type: (_courierEvent$type = courierEvent.type) !== null && _courierEvent$type !== void 0 ? _courierEvent$type : "message",
129
+ data: courierEvent
130
+ });
131
+ });
132
+ }
133
+ }, {
134
+ key: "unsubscribe",
135
+ value: function unsubscribe(channel, event) {
136
+ this.ws.unsubscribe(channel, event !== null && event !== void 0 ? event : "*");
137
+ }
138
+ }, {
139
+ key: "onReconnection",
140
+ value: function onReconnection(handler) {
141
+ this.ws.onReconnection(handler);
142
+ }
143
+ }, {
144
+ key: "renewSession",
145
+ value: function renewSession(token) {
146
+ this.ws.renewSession(token);
147
+ }
148
+ }]);
149
+ return CourierTransport;
150
+ }(_base.Transport);
151
+
152
+ exports.CourierTransport = CourierTransport;
@@ -0,0 +1 @@
1
+ "use strict";
package/dist/index.js ADDED
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+
7
+ var _courier = require("./courier");
8
+
9
+ Object.keys(_courier).forEach(function (key) {
10
+ if (key === "default" || key === "__esModule") return;
11
+ if (key in exports && exports[key] === _courier[key]) return;
12
+ Object.defineProperty(exports, key, {
13
+ enumerable: true,
14
+ get: function get() {
15
+ return _courier[key];
16
+ }
17
+ });
18
+ });
19
+
20
+ var _base = require("./base");
21
+
22
+ Object.keys(_base).forEach(function (key) {
23
+ if (key === "default" || key === "__esModule") return;
24
+ if (key in exports && exports[key] === _base[key]) return;
25
+ Object.defineProperty(exports, key, {
26
+ enumerable: true,
27
+ get: function get() {
28
+ return _base[key];
29
+ }
30
+ });
31
+ });
32
+
33
+ var _types = require("./types");
34
+
35
+ Object.keys(_types).forEach(function (key) {
36
+ if (key === "default" || key === "__esModule") return;
37
+ if (key in exports && exports[key] === _types[key]) return;
38
+ Object.defineProperty(exports, key, {
39
+ enumerable: true,
40
+ get: function get() {
41
+ return _types[key];
42
+ }
43
+ });
44
+ });
45
+
46
+ var _ws = require("./ws");
47
+
48
+ Object.keys(_ws).forEach(function (key) {
49
+ if (key === "default" || key === "__esModule") return;
50
+ if (key in exports && exports[key] === _ws[key]) return;
51
+ Object.defineProperty(exports, key, {
52
+ enumerable: true,
53
+ get: function get() {
54
+ return _ws[key];
55
+ }
56
+ });
57
+ });
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";
package/dist/ws.js ADDED
@@ -0,0 +1,305 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.CourierWS = void 0;
9
+
10
+ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
11
+
12
+ var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
13
+
14
+ var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
15
+
16
+ var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
17
+
18
+ var _reconnectingWebsocket = _interopRequireDefault(require("reconnecting-websocket"));
19
+
20
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
21
+
22
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
23
+
24
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
25
+
26
+ var SUBSCRIPTION_VERSION = 5;
27
+
28
+ var CourierWS = /*#__PURE__*/function () {
29
+ function CourierWS(_ref) {
30
+ var tenantId = _ref.tenantId,
31
+ authorization = _ref.authorization,
32
+ clientKey = _ref.clientKey,
33
+ options = _ref.options,
34
+ clientSourceId = _ref.clientSourceId,
35
+ userSignature = _ref.userSignature;
36
+ (0, _classCallCheck2["default"])(this, CourierWS);
37
+ this.tenantId = tenantId;
38
+ this.connectionCount = 0;
39
+ this.authorization = authorization;
40
+ this.messageCallback = null;
41
+ this.connection = undefined;
42
+ this.connected = false;
43
+ this.url = (options === null || options === void 0 ? void 0 : options.url) || "" || "wss://realtime.courier.com";
44
+ this.clientSourceId = clientSourceId;
45
+ this.clientKey = clientKey;
46
+ this.userSignature = userSignature;
47
+ this.subscriptions = [];
48
+ this.onReconnectionHandlers = [];
49
+ this.connectionTimeout = options === null || options === void 0 ? void 0 : options.connectionTimeout;
50
+ this.onError = options === null || options === void 0 ? void 0 : options.onError;
51
+ this.onClose = options === null || options === void 0 ? void 0 : options.onClose;
52
+ }
53
+
54
+ (0, _createClass2["default"])(CourierWS, [{
55
+ key: "close",
56
+ value: function close() {
57
+ if (!this.connected || !this.connection) {
58
+ return;
59
+ }
60
+
61
+ this.connection.close();
62
+ }
63
+ }, {
64
+ key: "getUrl",
65
+ value: function getUrl() {
66
+ return "".concat(this.url, "/?").concat(this.authorization ? "auth=".concat(this.authorization) : "clientKey=".concat(this.clientKey));
67
+ }
68
+ }, {
69
+ key: "connect",
70
+ value: function connect() {
71
+ var url = this.getUrl.bind(this);
72
+ this.connection = new _reconnectingWebsocket["default"](url, [], {
73
+ connectionTimeout: this.connectionTimeout
74
+ });
75
+ this.connection.onopen = this._onOpen.bind(this);
76
+ this.connection.onclose = this._onClose.bind(this);
77
+ this.connection.onerror = this._onError.bind(this);
78
+ this.connection.onmessage = this._onMessage.bind(this);
79
+ }
80
+ }, {
81
+ key: "_onError",
82
+ value: function _onError(event) {
83
+ var _this$connection;
84
+
85
+ if (this.onError) {
86
+ this.onError(event);
87
+ } else {
88
+ console.error("Error Connecting to Courier Push");
89
+ }
90
+
91
+ (_this$connection = this.connection) === null || _this$connection === void 0 ? void 0 : _this$connection.close();
92
+ }
93
+ }, {
94
+ key: "_onClose",
95
+ value: function _onClose() {
96
+ this.connected = false;
97
+
98
+ if (this.onClose) {
99
+ this.onClose();
100
+ }
101
+ }
102
+ }, {
103
+ key: "_onOpen",
104
+ value: function _onOpen() {
105
+ this.connected = true;
106
+ this.connectionCount++;
107
+
108
+ if (this.connectionCount > 1) {
109
+ var _iterator = _createForOfIteratorHelper(this.onReconnectionHandlers),
110
+ _step;
111
+
112
+ try {
113
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
114
+ var reconnectHandler = _step.value;
115
+ reconnectHandler.callback();
116
+ }
117
+ } catch (err) {
118
+ _iterator.e(err);
119
+ } finally {
120
+ _iterator.f();
121
+ }
122
+ }
123
+
124
+ var _iterator2 = _createForOfIteratorHelper(this.subscriptions),
125
+ _step2;
126
+
127
+ try {
128
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
129
+ var sub = _step2.value;
130
+ this.send({
131
+ action: "subscribe",
132
+ data: {
133
+ // [HACK] map tenantId to accountId in order to keep this backwards compatible
134
+ accountId: this.tenantId,
135
+ channel: sub.channel,
136
+ clientSourceId: this.clientSourceId,
137
+ clientKey: this.clientKey,
138
+ event: sub.event,
139
+ userSignature: this.userSignature,
140
+ version: SUBSCRIPTION_VERSION
141
+ }
142
+ });
143
+ }
144
+ } catch (err) {
145
+ _iterator2.e(err);
146
+ } finally {
147
+ _iterator2.f();
148
+ }
149
+ }
150
+ }, {
151
+ key: "_onMessage",
152
+ value: function _onMessage(_ref2) {
153
+ var data = _ref2.data;
154
+ var message;
155
+
156
+ try {
157
+ message = JSON.parse(data);
158
+ } catch (_unused) {
159
+ console.error("Error Parsing Courier Message");
160
+ return;
161
+ }
162
+
163
+ if (message.error) {
164
+ console.error(message.error);
165
+ return;
166
+ }
167
+
168
+ var _iterator3 = _createForOfIteratorHelper(this.subscriptions),
169
+ _step3;
170
+
171
+ try {
172
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
173
+ var _message, _message$type;
174
+
175
+ var sub = _step3.value;
176
+
177
+ if (sub.event !== "*" && sub.event !== ((_message = message) === null || _message === void 0 ? void 0 : _message.event)) {
178
+ continue;
179
+ }
180
+
181
+ sub.callback({
182
+ type: (_message$type = message.type) !== null && _message$type !== void 0 ? _message$type : "message",
183
+ data: message
184
+ });
185
+ }
186
+ } catch (err) {
187
+ _iterator3.e(err);
188
+ } finally {
189
+ _iterator3.f();
190
+ }
191
+ }
192
+ }, {
193
+ key: "subscribe",
194
+ value: function () {
195
+ var _subscribe = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(channel, event, callback) {
196
+ return _regenerator["default"].wrap(function _callee$(_context) {
197
+ while (1) {
198
+ switch (_context.prev = _context.next) {
199
+ case 0:
200
+ this.subscriptions.push({
201
+ channel: channel,
202
+ event: event,
203
+ callback: callback
204
+ });
205
+
206
+ if (this.connected) {
207
+ this.send({
208
+ action: "subscribe",
209
+ data: {
210
+ // [HACK] map tenantId to accountId in order to keep this backwards compatible
211
+ accountId: this.tenantId,
212
+ channel: channel,
213
+ clientKey: this.clientKey,
214
+ clientSourceId: this.clientSourceId,
215
+ event: event,
216
+ userSignature: this.userSignature,
217
+ version: SUBSCRIPTION_VERSION
218
+ }
219
+ });
220
+ }
221
+
222
+ case 2:
223
+ case "end":
224
+ return _context.stop();
225
+ }
226
+ }
227
+ }, _callee, this);
228
+ }));
229
+
230
+ function subscribe(_x, _x2, _x3) {
231
+ return _subscribe.apply(this, arguments);
232
+ }
233
+
234
+ return subscribe;
235
+ }()
236
+ }, {
237
+ key: "send",
238
+ value: function send(message) {
239
+ if (!this.connected || !this.connection) {
240
+ console.warn("WS Not Connected");
241
+ return;
242
+ }
243
+
244
+ this.connection.send(JSON.stringify(message));
245
+ }
246
+ }, {
247
+ key: "unsubscribe",
248
+ value: function unsubscribe(channel, event) {
249
+ this.subscriptions = this.subscriptions.filter(function (sub) {
250
+ return !(sub.channel === channel && sub.event === event);
251
+ });
252
+ this.send({
253
+ action: "unsubscribe",
254
+ data: {
255
+ channel: channel,
256
+ clientKey: this.clientKey,
257
+ event: event,
258
+ userSignature: this.userSignature,
259
+ version: SUBSCRIPTION_VERSION
260
+ }
261
+ });
262
+ }
263
+ }, {
264
+ key: "renewSession",
265
+ value: function renewSession(newAuthorization) {
266
+ this.authorization = newAuthorization;
267
+
268
+ if (!this.connected || !this.connection) {
269
+ this.connect();
270
+ return;
271
+ }
272
+
273
+ this.send({
274
+ action: "renewSession",
275
+ data: {
276
+ auth: newAuthorization,
277
+ version: SUBSCRIPTION_VERSION
278
+ }
279
+ });
280
+ }
281
+ }, {
282
+ key: "onReconnection",
283
+ value: function onReconnection(handler) {
284
+ if (this.onReconnectionHandlers.find(function (h) {
285
+ return h.id === handler.id;
286
+ })) {
287
+ var _this$onReconnectionH;
288
+
289
+ this.onReconnectionHandlers = (_this$onReconnectionH = this.onReconnectionHandlers) === null || _this$onReconnectionH === void 0 ? void 0 : _this$onReconnectionH.map(function (h) {
290
+ if (h.id === handler.id) {
291
+ return handler;
292
+ }
293
+
294
+ return h;
295
+ });
296
+ return;
297
+ }
298
+
299
+ this.onReconnectionHandlers.push(handler);
300
+ }
301
+ }]);
302
+ return CourierWS;
303
+ }();
304
+
305
+ exports.CourierWS = CourierWS;
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "@trycourier/transport",
3
+ "version": "6.0.0",
4
+ "description": "",
5
+ "main": "dist/index.js",
6
+ "types": "typings/index.d.ts",
7
+ "scripts": {
8
+ "babel": "babel src -d dist --extensions \".ts\" --ignore \"src/**/__tests__/**\"",
9
+ "build:watch": "yarn babel --watch",
10
+ "build": "rimraf dist && yarn babel",
11
+ "clean": "rimraf dist && rimraf typings",
12
+ "type-check": "tsc --noEmit",
13
+ "types": "tsc --emitDeclarationOnly"
14
+ },
15
+ "license": "ISC",
16
+ "dependencies": {
17
+ "@trycourier/core": "^6.0.0",
18
+ "jwt-decode": "^3.1.2",
19
+ "reconnecting-websocket": "^4.4.0",
20
+ "rimraf": "^3.0.2"
21
+ },
22
+ "files": [
23
+ "dist/",
24
+ "typings/"
25
+ ],
26
+ "gitHead": "6d8dcf0cb9af3709d2b19e0e60188fc03fdccba7"
27
+ }
@@ -0,0 +1,4 @@
1
+ /// <reference types="jest" />
2
+ export declare const CourierTransport: jest.Mock<any, any>;
3
+ export declare const Transport: jest.Mock<any, any>;
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/__mocks__/index.ts"],"names":[],"mappings":";AAGA,eAAO,MAAM,gBAAgB,qBAK3B,CAAC;AAGH,eAAO,MAAM,SAAS,qBAAgB,CAAC"}
@@ -0,0 +1,6 @@
1
+ /// <reference types="jest" />
2
+ export declare const mockConnect: jest.Mock<any, any>;
3
+ export declare const mockSend: jest.Mock<any, any>;
4
+ export declare const mockRenewSession: jest.Mock<any, any>;
5
+ export declare const WS: jest.Mock<any, any>;
6
+ //# sourceMappingURL=ws.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../../src/__mocks__/ws.ts"],"names":[],"mappings":";AAAA,eAAO,MAAM,WAAW,qBAAY,CAAC;AACrC,eAAO,MAAM,QAAQ,qBAAY,CAAC;AAClC,eAAO,MAAM,gBAAgB,qBAAY,CAAC;AAU1C,eAAO,MAAM,EAAE,qBAAO,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { ICourierEvent, Interceptor } from "@trycourier/core";
2
+ declare enum ListenerType {
3
+ message = "message",
4
+ event = "event"
5
+ }
6
+ export declare class Transport {
7
+ constructor();
8
+ /** Callback for emitted events */
9
+ protected listeners: {
10
+ [key in ListenerType]: Array<{
11
+ id: string;
12
+ listener: (courierEvent: ICourierEvent) => void;
13
+ }>;
14
+ };
15
+ protected interceptor?: Interceptor;
16
+ /** Wrapper method for emitted events */
17
+ protected emit: (courierEvent: ICourierEvent) => void;
18
+ /** Setter method for a listener */
19
+ listen: (listener: {
20
+ id: string;
21
+ type?: "message" | "event" | undefined;
22
+ listener: (courierEvent: ICourierEvent) => void;
23
+ }) => void;
24
+ intercept: (cb: Interceptor) => void;
25
+ }
26
+ export {};
27
+ //# sourceMappingURL=base.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../src/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE9D,aAAK,YAAY;IACf,OAAO,YAAY;IACnB,KAAK,UAAU;CAChB;AACD,qBAAa,SAAS;;IASpB,mCAAmC;IACnC,SAAS,CAAC,SAAS,EAAE;SAClB,GAAG,IAAI,YAAY,GAAG,KAAK,CAAC;YAC3B,EAAE,EAAE,MAAM,CAAC;YACX,QAAQ,EAAE,CAAC,YAAY,EAAE,aAAa,KAAK,IAAI,CAAC;SACjD,CAAC;KACH,CAAC;IAEF,SAAS,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC;IACpC,yCAAyC;IACzC,SAAS,CAAC,IAAI,iBAAkB,aAAa,KAAG,IAAI,CAYlD;IAEF,mCAAmC;IACnC,MAAM;YACA,MAAM;;iCAEe,aAAa,KAAK,IAAI;UAC7C,IAAI,CAoBN;IAEF,SAAS,OAAQ,WAAW,KAAG,IAAI,CAEjC;CACH"}
@@ -0,0 +1,27 @@
1
+ import { CourierWS } from "../ws";
2
+ import { Transport } from "../base";
3
+ import { Interceptor } from "@trycourier/core";
4
+ import { TransportOptions } from "./types";
5
+ export declare class CourierTransport extends Transport {
6
+ protected tenantId?: string;
7
+ protected authorization?: string;
8
+ protected clientSourceId?: string;
9
+ protected clientKey?: string;
10
+ protected interceptor?: Interceptor;
11
+ protected userSignature?: string;
12
+ protected ws: CourierWS;
13
+ constructor(options: TransportOptions);
14
+ closeConnection(): void;
15
+ connect(): void;
16
+ isConnected(): boolean;
17
+ keepAlive(): void;
18
+ send(message: any): void;
19
+ subscribe(channel: string, event?: string): void;
20
+ unsubscribe(channel: string, event?: string): void;
21
+ onReconnection(handler: {
22
+ id: string;
23
+ callback: () => void;
24
+ }): void;
25
+ renewSession(token: string): void;
26
+ }
27
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/courier/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAkC,MAAM,SAAS,CAAC;AAE3E,qBAAa,gBAAiB,SAAQ,SAAS;IAC7C,SAAS,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC5B,SAAS,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IACjC,SAAS,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IAClC,SAAS,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC7B,UAAkB,WAAW,CAAC,EAAE,WAAW,CAAC;IAC5C,SAAS,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IACjC,SAAS,CAAC,EAAE,EAAE,SAAS,CAAC;gBAEZ,OAAO,EAAE,gBAAgB;IAgCrC,eAAe,IAAI,IAAI;IAIvB,OAAO,IAAI,IAAI;IAIf,WAAW,IAAI,OAAO;IAItB,SAAS,IAAI,IAAI;IAMjB,IAAI,CAAC,OAAO,KAAA,GAAG,IAAI;IAUnB,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAchD,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAIlD,cAAc,CAAC,OAAO,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,IAAI,CAAA;KAAE,GAAG,IAAI;IAInE,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;CAGlC"}
@@ -0,0 +1,15 @@
1
+ import { WSOptions } from "~/types";
2
+ export interface IBaseOptions {
3
+ tenantId?: string;
4
+ clientSourceId?: string;
5
+ wsOptions?: WSOptions;
6
+ }
7
+ export interface IClientKeyOptions extends IBaseOptions {
8
+ clientKey: string;
9
+ userSignature?: string;
10
+ }
11
+ export interface IJWTOptions extends IBaseOptions {
12
+ authorization: string;
13
+ }
14
+ export declare type TransportOptions = IClientKeyOptions | IJWTOptions;
15
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/courier/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEpC,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,CAAC,EAAE,SAAS,CAAC;CACvB;AACD,MAAM,WAAW,iBAAkB,SAAQ,YAAY;IACrD,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,WAAY,SAAQ,YAAY;IAC/C,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,oBAAY,gBAAgB,GAAG,iBAAiB,GAAG,WAAW,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { TransportOptions } from "./courier/types";
2
+ export * from "./courier";
3
+ export * from "./base";
4
+ export * from "./types";
5
+ export * from "./ws";
6
+ export type { TransportOptions };
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,cAAc,WAAW,CAAC;AAC1B,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,MAAM,CAAC;AAErB,YAAY,EAAE,gBAAgB,EAAE,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { ErrorEvent } from "reconnecting-websocket";
2
+ export declare type ErrorEventHandler = (event: ErrorEvent) => void;
3
+ export declare type WSOptions = {
4
+ url?: string;
5
+ onError?: ErrorEventHandler;
6
+ onClose?: () => void;
7
+ onReconnect?: () => void;
8
+ connectionTimeout?: number;
9
+ };
10
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,oBAAY,iBAAiB,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,CAAC;AAE5D,oBAAY,SAAS,GAAG;IACtB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAC5B,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC"}
@@ -0,0 +1,46 @@
1
+ import { ICourierEventCallback } from "@trycourier/core";
2
+ import ReconnectingWebSocket from "reconnecting-websocket";
3
+ import { WSOptions } from "./types";
4
+ export declare class CourierWS {
5
+ connection?: ReconnectingWebSocket;
6
+ connected: boolean;
7
+ private subscriptions;
8
+ private tenantId?;
9
+ private clientSourceId?;
10
+ private authorization?;
11
+ private clientKey?;
12
+ private connectionTimeout?;
13
+ private onError?;
14
+ private onClose?;
15
+ private onReconnectionHandlers;
16
+ private url;
17
+ private userSignature?;
18
+ private connectionCount;
19
+ protected messageCallback: any;
20
+ constructor({ tenantId, authorization, clientKey, options, clientSourceId, userSignature, }: {
21
+ tenantId?: string;
22
+ authorization?: string;
23
+ clientSourceId?: string;
24
+ clientKey?: string;
25
+ options?: WSOptions;
26
+ userSignature?: string;
27
+ });
28
+ close(): void;
29
+ getUrl(): string;
30
+ connect(): void;
31
+ private _onError;
32
+ private _onClose;
33
+ private _onOpen;
34
+ private _onMessage;
35
+ subscribe(channel: string, event: string, callback: ICourierEventCallback): Promise<void>;
36
+ send(message: {
37
+ [key: string]: any;
38
+ }): void;
39
+ unsubscribe(channel: string, event: string): void;
40
+ renewSession(newAuthorization: string): void;
41
+ onReconnection(handler: {
42
+ id: string;
43
+ callback: () => void;
44
+ }): void;
45
+ }
46
+ //# sourceMappingURL=ws.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../src/ws.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EAGtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,qBAAqC,MAAM,wBAAwB,CAAC;AAC3E,OAAO,EAAqB,SAAS,EAAE,MAAM,SAAS,CAAC;AAGvD,qBAAa,SAAS;IACb,UAAU,CAAC,EAAE,qBAAqB,CAAC;IACnC,SAAS,EAAE,OAAO,CAAC;IAE1B,OAAO,CAAC,aAAa,CAIlB;IACH,OAAO,CAAC,QAAQ,CAAC,CAAS;IAC1B,OAAO,CAAC,cAAc,CAAC,CAAS;IAChC,OAAO,CAAC,aAAa,CAAC,CAAS;IAC/B,OAAO,CAAC,SAAS,CAAC,CAAS;IAC3B,OAAO,CAAC,iBAAiB,CAAC,CAAS;IACnC,OAAO,CAAC,OAAO,CAAC,CAAoB;IACpC,OAAO,CAAC,OAAO,CAAC,CAAa;IAC7B,OAAO,CAAC,sBAAsB,CAG3B;IACH,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,aAAa,CAAC,CAAS;IAC/B,OAAO,CAAC,eAAe,CAAS;IAChC,SAAS,CAAC,eAAe,MAAC;gBAEd,EACV,QAAQ,EACR,aAAa,EACb,SAAS,EACT,OAAO,EACP,cAAc,EACd,aAAa,GACd,EAAE;QACD,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,OAAO,CAAC,EAAE,SAAS,CAAC;QACpB,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB;IAqBD,KAAK,IAAI,IAAI;IAQb,MAAM,IAAI,MAAM;IAQhB,OAAO,IAAI,IAAI;IAYf,OAAO,CAAC,QAAQ;IAUhB,OAAO,CAAC,QAAQ;IAOhB,OAAO,CAAC,OAAO;IA2Bf,OAAO,CAAC,UAAU;IA2BZ,SAAS,CACb,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,qBAAqB,GAC9B,OAAO,CAAC,IAAI,CAAC;IAwBhB,IAAI,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,GAAG,IAAI;IAS3C,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAiBjD,YAAY,CAAC,gBAAgB,EAAE,MAAM,GAAG,IAAI;IAgB5C,cAAc,CAAC,OAAO,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,IAAI,CAAA;KAAE,GAAG,IAAI;CAcpE"}