qiscus-sdk-core 2.12.4 → 2.12.6-logger

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.
@@ -1,207 +1,214 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  Object.defineProperty(exports, "__esModule", {
6
5
  value: true
7
6
  });
8
7
  exports["default"] = void 0;
9
-
10
8
  var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
11
-
12
9
  var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
13
-
14
10
  var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
15
-
16
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
17
-
18
11
  var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
19
-
20
12
  var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
21
-
22
13
  var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
23
-
24
14
  var _match2 = require("../match");
25
-
26
15
  var _mitt = _interopRequireDefault(require("mitt"));
27
-
28
16
  var _connect = _interopRequireDefault(require("mqtt/lib/connect"));
29
-
30
17
  var _superagent = _interopRequireDefault(require("superagent"));
31
-
32
18
  var _lodash = _interopRequireDefault(require("lodash.debounce"));
33
-
34
19
  var _util = require("../util");
35
-
36
- var MqttAdapter = /*#__PURE__*/function () {
20
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
21
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } // import {connect} from 'mqtt'
22
+ var MqttAdapter = exports["default"] = /*#__PURE__*/function () {
37
23
  /**
38
24
  * @typedef {Function} GetClientId
39
25
  * @return {string}
40
26
  */
41
-
42
27
  /**
43
28
  * @typedef {Object} MqttAdapterParams
44
29
  * @property {boolean} shouldConnect
45
30
  * @property {string} brokerLbUrl
46
31
  * @property {boolean} enableLb
47
32
  * @property {GetClientId} getClientId
33
+ * @property {import('../../logger.js').Logger} logger
48
34
  */
49
-
50
35
  /**
51
36
  * @param {string} url
52
- * @param {QiscusSDK} core
37
+ * @param {import('../../index').default} core
53
38
  * @param {boolean} login
54
39
  * @param {MqttAdapterParams} obj
55
40
  */
56
41
  function MqttAdapter(_url, core, login, _ref) {
57
- var _this = this,
58
- _match;
59
-
42
+ var _this = this;
60
43
  var _ref$shouldConnect = _ref.shouldConnect,
61
- shouldConnect = _ref$shouldConnect === void 0 ? true : _ref$shouldConnect,
62
- brokerLbUrl = _ref.brokerLbUrl,
63
- enableLb = _ref.enableLb,
64
- getClientId = _ref.getClientId;
44
+ shouldConnect = _ref$shouldConnect === void 0 ? true : _ref$shouldConnect,
45
+ brokerLbUrl = _ref.brokerLbUrl,
46
+ enableLb = _ref.enableLb,
47
+ getClientId = _ref.getClientId,
48
+ logger = _ref.logger;
65
49
  (0, _classCallCheck2["default"])(this, MqttAdapter);
50
+ /**
51
+ * @type {import('pino').Logger}
52
+ */
53
+ (0, _defineProperty2["default"])(this, "logger", void 0);
54
+ /**
55
+ * @type {import('mqtt').MqttClient | null}
56
+ */
57
+ (0, _defineProperty2["default"])(this, "mqtt", null);
66
58
  (0, _defineProperty2["default"])(this, "_getClientId", function () {
67
- if (_this.getClientId == null) return "".concat(_this.core.AppId, "_").concat(_this.core.user_id, "_").concat(Date.now());
68
- return _this.getClientId();
59
+ var clientId;
60
+ if (_this.getClientId == null) {
61
+ clientId = "".concat(_this.core.AppId, "_").concat(_this.core.user_id, "_").concat(Date.now());
62
+ } else {
63
+ clientId = _this.getClientId();
64
+ }
65
+ _this.logger.debug('Generated clientId', {
66
+ clientId: clientId
67
+ });
68
+ return clientId;
69
69
  });
70
70
  (0, _defineProperty2["default"])(this, "__mqtt_connected_handler", function () {
71
+ _this.logger.debug('connected');
71
72
  _this.emitter.emit('connected');
72
73
  });
73
74
  (0, _defineProperty2["default"])(this, "__mqtt_reconnect_handler", function () {
75
+ _this.logger.debug('reconnecting');
74
76
  _this.emitter.emit('reconnect');
75
77
  });
76
78
  (0, _defineProperty2["default"])(this, "__mqtt_closed_handler", function () {
77
79
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
78
80
  args[_key] = arguments[_key];
79
81
  }
80
-
82
+ _this.logger.debug('closed', {
83
+ args: args
84
+ });
81
85
  _this.emitter.emit('close', args);
82
86
  });
83
87
  (0, _defineProperty2["default"])(this, "__mqtt_message_handler", function (t, m) {
88
+ _this.logger.debug('message', {
89
+ t: t,
90
+ m: JSON.stringify(m)
91
+ });
84
92
  var message = m.toString();
85
-
86
93
  var func = _this.matcher(t);
87
-
88
- _this.logger('message', t, m);
89
-
90
94
  if (func != null) func(message);
91
95
  });
92
96
  (0, _defineProperty2["default"])(this, "__mqtt_error_handler", function (err) {
97
+ _this.logger.debug('error', {
98
+ err: err
99
+ });
93
100
  if (err && err.message === 'client disconnecting') return;
94
-
95
101
  _this.emitter.emit('error', err.message);
96
-
97
- _this.logger('error', err.message);
98
102
  });
99
103
  (0, _defineProperty2["default"])(this, "__mqtt_conneck", function (brokerUrl) {
104
+ var _this$mqtt;
100
105
  var topics = [];
106
+ /**
107
+ * @type {import('mqtt').IClientOptions}
108
+ */
101
109
  var opts = {
102
110
  will: {
103
111
  topic: "u/".concat(_this.core.user_id, "/s"),
104
- payload: 0,
105
- retain: true
112
+ payload: '0',
113
+ retain: true,
114
+ qos: 1
106
115
  },
107
- clientId: _this._getClientId() // reconnectPeriod: 0,
116
+ clientId: _this._getClientId()
117
+ // reconnectPeriod: 0,
108
118
  // connectTimeout: 1 * 1000,
109
-
110
119
  };
120
+ _this.logger.debug('Connecting to', {
121
+ brokerUrl: brokerUrl,
122
+ cachedRealtimeURL: _this.cacheRealtimeURL,
123
+ existingTopics: (_this$mqtt = _this.mqtt) !== null && _this$mqtt !== void 0 && _this$mqtt._resubscribeTopics ? Object.keys(_this.mqtt._resubscribeTopics) : []
124
+ });
111
125
  if (brokerUrl == null) brokerUrl = _this.cacheRealtimeURL;
112
-
113
126
  if (_this.mqtt != null) {
114
- var _topics = Object.keys(_this.mqtt._resubscribeTopics);
115
-
116
- topics.push.apply(topics, (0, _toConsumableArray2["default"])(_topics));
117
-
127
+ var _this$mqtt$_resubscri;
128
+ var _topics = Object.keys((_this$mqtt$_resubscri = _this.mqtt._resubscribeTopics) !== null && _this$mqtt$_resubscri !== void 0 ? _this$mqtt$_resubscri : {});
129
+ topics.push.apply(topics, _topics);
118
130
  _this.mqtt.removeAllListeners();
119
-
120
131
  _this.mqtt.end(true);
121
-
122
- delete _this.mqtt;
132
+ // delete this.mqtt
123
133
  _this.mqtt = null;
124
134
  }
135
+ var mqtt = (0, _connect["default"])(brokerUrl, opts);
125
136
 
126
- var mqtt = (0, _connect["default"])(brokerUrl, opts); // #region Mqtt Listener
127
-
137
+ // #region Mqtt Listener
128
138
  mqtt.addListener('connect', _this.__mqtt_connected_handler);
129
139
  mqtt.addListener('reconnect', _this.__mqtt_reconnect_handler);
130
140
  mqtt.addListener('close', _this.__mqtt_closed_handler);
131
141
  mqtt.addListener('error', _this.__mqtt_error_handler);
132
- mqtt.addListener('message', _this.__mqtt_message_handler); // #endregion
133
-
134
- _this.logger("resubscribe to old topics ".concat(topics));
142
+ mqtt.addListener('message', _this.__mqtt_message_handler);
143
+ // #endregion
135
144
 
145
+ _this.logger.debug("resubscribe to old topics ".concat(topics));
136
146
  topics.forEach(function (topic) {
137
147
  return mqtt.subscribe(topic);
138
148
  });
139
149
  return mqtt;
140
150
  });
141
- (0, _defineProperty2["default"])(this, "_on_close_handler", (0, _lodash["default"])( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
151
+ (0, _defineProperty2["default"])(this, "_on_close_handler", (0, _lodash["default"])(/*#__PURE__*/(0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee() {
142
152
  var shouldReconnect, _yield$wrapP, _yield$wrapP2, url, err;
143
-
144
- return _regenerator["default"].wrap(function _callee$(_context) {
145
- while (1) {
146
- switch (_context.prev = _context.next) {
147
- case 0:
148
- shouldReconnect = _this.enableLb === true && // appConfig enabling realtime lb
149
- _this.core.isLogin === true && // is logged in
150
- _this.shouldConnect === true && // should reconnect?
151
- !_this.willConnectToRealtime; // is there still reconnect process in progress?
152
-
153
- if (_this.logEnabled) {
154
- console.group('@mqtt.closed');
155
- console.log("this.enableLb(".concat(_this.enableLb, ")"));
156
- console.log("this.core.isLogin(".concat(_this.core.isLogin, ")"));
157
- console.log("this.shouldConnect(".concat(_this.shouldConnect, ")"));
158
- console.log("this.willConnectToRealtime(".concat(_this.willConnectToRealtime, ")"));
159
- console.log("shouldReconnect(".concat(shouldReconnect, ")"));
160
- console.groupEnd();
161
- }
162
-
163
- if (shouldReconnect) {
164
- _context.next = 4;
165
- break;
166
- }
167
-
168
- return _context.abrupt("return");
169
-
170
- case 4:
171
- _this.willConnectToRealtime = true;
172
- _context.next = 7;
173
- return (0, _util.wrapP)(_this.getMqttNode());
174
-
175
- case 7:
176
- _yield$wrapP = _context.sent;
177
- _yield$wrapP2 = (0, _slicedToArray2["default"])(_yield$wrapP, 2);
178
- url = _yield$wrapP2[0];
179
- err = _yield$wrapP2[1];
180
-
181
- if (err) {
182
- _this.logger("cannot get new brokerURL, using old url instead (".concat(_this.cacheRealtimeURL, ")"));
183
-
184
- _this.mqtt = _this.__mqtt_conneck(_this.cacheRealtimeURL);
185
- } else {
186
- _this.cacheRealtimeURL = url;
187
-
188
- _this.logger('trying to reconnect to', url);
189
-
190
- _this.mqtt = _this.__mqtt_conneck(url);
191
- }
192
-
193
- _this.willConnectToRealtime = false;
194
-
195
- case 13:
196
- case "end":
197
- return _context.stop();
198
- }
153
+ return _regenerator["default"].wrap(function (_context) {
154
+ while (1) switch (_context.prev = _context.next) {
155
+ case 0:
156
+ shouldReconnect = _this.enableLb === true &&
157
+ // appConfig enabling realtime lb
158
+ _this.core.isLogin === true &&
159
+ // is logged in
160
+ _this.shouldConnect === true &&
161
+ // should reconnect?
162
+ !_this.willConnectToRealtime; // is there still reconnect process in progress?
163
+ _this.logger.debug('closed', {
164
+ enableLb: _this.enableLb,
165
+ isLogin: _this.core.isLogin,
166
+ shouldConnect: _this.shouldConnect,
167
+ willConnectToRealtime: _this.willConnectToRealtime,
168
+ shouldReconnect: shouldReconnect
169
+ });
170
+ if (shouldReconnect) {
171
+ _context.next = 1;
172
+ break;
173
+ }
174
+ return _context.abrupt("return");
175
+ case 1:
176
+ _this.willConnectToRealtime = true;
177
+ _context.next = 2;
178
+ return (0, _util.wrapP)(_this.getMqttNode());
179
+ case 2:
180
+ _yield$wrapP = _context.sent;
181
+ _yield$wrapP2 = (0, _slicedToArray2["default"])(_yield$wrapP, 2);
182
+ url = _yield$wrapP2[0];
183
+ err = _yield$wrapP2[1];
184
+ if (err) {
185
+ _this.logger.debug("cannot get new brokerURL (through ".concat(_this.brokerLbUrl, "), using old url instead (").concat(_this.cacheRealtimeURL, ")"));
186
+ _this.mqtt = _this.__mqtt_conneck(_this.cacheRealtimeURL);
187
+ } else {
188
+ _this.cacheRealtimeURL = url;
189
+ _this.logger.debug('trying to reconnect to', url);
190
+ _this.mqtt = _this.__mqtt_conneck(url);
191
+ }
192
+ _this.willConnectToRealtime = false;
193
+ case 3:
194
+ case "end":
195
+ return _context.stop();
199
196
  }
200
197
  }, _callee);
201
198
  })), 1000));
199
+ /**
200
+ * @type {[string, import('mqtt').IClientSubscribeOptions][]}
201
+ */
202
202
  (0, _defineProperty2["default"])(this, "subscribtionBuffer", []);
203
+ /**
204
+ * @type {[string, import('mqtt').IClientSubscribeOptions][]}
205
+ */
203
206
  (0, _defineProperty2["default"])(this, "unsubscribtionBuffer", []);
207
+ /**
208
+ * @type {Array<{topic: string, payload: string | Buffer, options: import('mqtt').IClientPublishOptions}>}
209
+ */
204
210
  (0, _defineProperty2["default"])(this, "publishBuffer", []);
211
+ this.logger = logger.child('MqttAdapter');
205
212
  this.emitter = (0, _mitt["default"])();
206
213
  this.core = core;
207
214
  this.mqtt = null;
@@ -209,240 +216,345 @@ var MqttAdapter = /*#__PURE__*/function () {
209
216
  this.getClientId = getClientId;
210
217
  this.enableLb = enableLb;
211
218
  this.shouldConnect = shouldConnect;
212
- this.matcher = (0, _match2.match)((_match = {}, (0, _defineProperty2["default"])(_match, (0, _match2.when)(this.reNewMessage), function (topic) {
219
+ this.matcher = (0, _match2.match)((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])({}, (0, _match2.when)(this.reNewMessage), function (topic) {
213
220
  return _this.newMessageHandler.bind(_this, topic);
214
- }), (0, _defineProperty2["default"])(_match, (0, _match2.when)(this.reNotification), function (topic) {
221
+ }), (0, _match2.when)(this.reNotification), function (topic) {
215
222
  return _this.notificationHandler.bind(_this, topic);
216
- }), (0, _defineProperty2["default"])(_match, (0, _match2.when)(this.reTyping), function (topic) {
223
+ }), (0, _match2.when)(this.reTyping), function (topic) {
217
224
  return _this.typingHandler.bind(_this, topic);
218
- }), (0, _defineProperty2["default"])(_match, (0, _match2.when)(this.reDelivery), function (topic) {
225
+ }), (0, _match2.when)(this.reDelivery), function (topic) {
219
226
  return _this.deliveryReceiptHandler.bind(_this, topic);
220
- }), (0, _defineProperty2["default"])(_match, (0, _match2.when)(this.reRead), function (topic) {
227
+ }), (0, _match2.when)(this.reRead), function (topic) {
221
228
  return _this.readReceiptHandler.bind(_this, topic);
222
- }), (0, _defineProperty2["default"])(_match, (0, _match2.when)(this.reOnlineStatus), function (topic) {
229
+ }), (0, _match2.when)(this.reOnlineStatus), function (topic) {
223
230
  return _this.onlinePresenceHandler.bind(_this, topic);
224
- }), (0, _defineProperty2["default"])(_match, (0, _match2.when)(this.reChannelMessage), function (topic) {
231
+ }), (0, _match2.when)(this.reChannelMessage), function (topic) {
225
232
  return _this.channelMessageHandler.bind(_this, topic);
226
- }), (0, _defineProperty2["default"])(_match, (0, _match2.when)(this.reMessageUpdated), function (topic) {
233
+ }), (0, _match2.when)(this.reMessageUpdated), function (topic) {
227
234
  return _this.messageUpdatedHandler.bind(_this, topic);
228
- }), (0, _defineProperty2["default"])(_match, (0, _match2.when)(), function (topic) {
229
- return _this.logger('topic not handled', topic);
230
- }), _match));
231
-
235
+ }), (0, _match2.when)(), function (topic) {
236
+ return _this.logger.debug('topic not handled', topic);
237
+ }));
232
238
  var _mqtt = this.__mqtt_conneck(_url);
239
+ this.mqtt = _mqtt;
233
240
 
234
- this.mqtt = _mqtt; // if appConfig set realtimeEnabled to false,
241
+ // if appConfig set realtimeEnabled to false,
235
242
  // we intentionally end mqtt connection here.
236
243
  // TODO: Make a better way to not connect
237
244
  // to broker, but still having mqtt client initiated.
238
-
239
245
  if (!shouldConnect) _mqtt.end(true);
240
- this.willConnectToRealtime = false; // handle load balencer
246
+ this.willConnectToRealtime = false;
241
247
 
242
- this.emitter.on('close', this._on_close_handler); // this.emitter.on('connected', () => {
243
- // this.willConnectToRealtime = false
244
- // })
248
+ // handle load balancer
249
+ this.emitter.on('close', this._on_close_handler);
245
250
  }
246
-
247
- (0, _createClass2["default"])(MqttAdapter, [{
251
+ return (0, _createClass2["default"])(MqttAdapter, [{
252
+ key: "cacheRealtimeURL",
253
+ get: function get() {
254
+ return this.core.mqttURL;
255
+ },
256
+ set: function set(url) {
257
+ this.core.mqttURL = url;
258
+ }
259
+ }, {
248
260
  key: "connect",
249
261
  value: function connect() {
250
262
  this.mqtt = this.__mqtt_conneck();
251
263
  }
264
+
252
265
  /**
253
- * @return {Promise<boolean}
266
+ * @return {Promise<boolean>}
254
267
  */
255
-
256
268
  }, {
257
269
  key: "openConnection",
258
- value: function () {
259
- var _openConnection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
260
- return _regenerator["default"].wrap(function _callee2$(_context2) {
261
- while (1) {
262
- switch (_context2.prev = _context2.next) {
263
- case 0:
264
- this.shouldConnect = true;
265
-
266
- this.__mqtt_conneck();
267
-
268
- case 2:
269
- case "end":
270
- return _context2.stop();
271
- }
270
+ value: (function () {
271
+ var _openConnection = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee2() {
272
+ return _regenerator["default"].wrap(function (_context2) {
273
+ while (1) switch (_context2.prev = _context2.next) {
274
+ case 0:
275
+ this.shouldConnect = true;
276
+ this.__mqtt_conneck();
277
+ return _context2.abrupt("return", true);
278
+ case 1:
279
+ case "end":
280
+ return _context2.stop();
272
281
  }
273
282
  }, _callee2, this);
274
283
  }));
275
-
276
284
  function openConnection() {
277
285
  return _openConnection.apply(this, arguments);
278
286
  }
279
-
280
287
  return openConnection;
281
288
  }()
282
289
  /**
283
290
  * @return {Promise<boolean>}
284
291
  */
285
-
292
+ )
286
293
  }, {
287
294
  key: "closeConnection",
288
- value: function () {
289
- var _closeConnection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
290
- return _regenerator["default"].wrap(function _callee3$(_context3) {
291
- while (1) {
292
- switch (_context3.prev = _context3.next) {
293
- case 0:
294
- this.shouldConnect = false;
295
- this.mqtt.end(true);
296
-
297
- case 2:
298
- case "end":
299
- return _context3.stop();
300
- }
295
+ value: (function () {
296
+ var _closeConnection = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee3() {
297
+ var _this$mqtt2;
298
+ return _regenerator["default"].wrap(function (_context3) {
299
+ while (1) switch (_context3.prev = _context3.next) {
300
+ case 0:
301
+ this.shouldConnect = false;
302
+ (_this$mqtt2 = this.mqtt) === null || _this$mqtt2 === void 0 || _this$mqtt2.end(true);
303
+ return _context3.abrupt("return", true);
304
+ case 1:
305
+ case "end":
306
+ return _context3.stop();
301
307
  }
302
308
  }, _callee3, this);
303
309
  }));
304
-
305
310
  function closeConnection() {
306
311
  return _closeConnection.apply(this, arguments);
307
312
  }
308
-
309
313
  return closeConnection;
310
- }()
314
+ }())
311
315
  }, {
312
316
  key: "getMqttNode",
313
317
  value: function () {
314
- var _getMqttNode = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
318
+ var _getMqttNode = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee4() {
315
319
  var res, url, port;
316
- return _regenerator["default"].wrap(function _callee4$(_context4) {
317
- while (1) {
318
- switch (_context4.prev = _context4.next) {
319
- case 0:
320
- _context4.next = 2;
321
- return _superagent["default"].get(this.brokerLbUrl);
322
-
323
- case 2:
324
- res = _context4.sent;
325
- url = res.body.data.url;
326
- port = res.body.data.wss_port;
327
- return _context4.abrupt("return", "wss://".concat(url, ":").concat(port, "/mqtt"));
328
-
329
- case 6:
330
- case "end":
331
- return _context4.stop();
332
- }
320
+ return _regenerator["default"].wrap(function (_context4) {
321
+ while (1) switch (_context4.prev = _context4.next) {
322
+ case 0:
323
+ _context4.next = 1;
324
+ return _superagent["default"].get(this.brokerLbUrl);
325
+ case 1:
326
+ res = _context4.sent;
327
+ url = res.body.data.url;
328
+ port = res.body.data.wss_port;
329
+ return _context4.abrupt("return", "wss://".concat(url, ":").concat(port, "/mqtt"));
330
+ case 2:
331
+ case "end":
332
+ return _context4.stop();
333
333
  }
334
334
  }, _callee4, this);
335
335
  }));
336
-
337
336
  function getMqttNode() {
338
337
  return _getMqttNode.apply(this, arguments);
339
338
  }
340
-
341
339
  return getMqttNode;
342
340
  }()
341
+ }, {
342
+ key: "connected",
343
+ get: function get() {
344
+ if (this.mqtt == null) return false;
345
+ return this.mqtt.connected;
346
+ }
343
347
  }, {
344
348
  key: "subscribe",
345
- value: function subscribe() {
349
+ value:
350
+ /**
351
+ * Subscribe to a topic.
352
+ * @param {[string, import('mqtt').IClientSubscribeOptions]} args - The topic to subscribe to.
353
+ */
354
+ function subscribe() {
355
+ var _this2 = this;
346
356
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
347
357
  args[_key2] = arguments[_key2];
348
358
  }
349
-
350
- this.logger('subscribe to', args);
359
+ this.logger.debug('subscribe', _objectSpread({}, args));
351
360
  this.subscribtionBuffer.push(args);
352
-
353
361
  if (this.mqtt != null) {
354
- do {
355
- var _this$mqtt;
356
-
357
- var subs = this.subscribtionBuffer.shift();
358
- if (subs != null) (_this$mqtt = this.mqtt).subscribe.apply(_this$mqtt, args);
359
- } while (this.subscribtionBuffer.length > 0);
362
+ var _loop = function _loop() {
363
+ var subs = _this2.subscribtionBuffer.shift();
364
+ if (subs != null) _this2.mqtt.subscribe(subs[0], subs[1], function (err, granted) {
365
+ if (err) {
366
+ _this2.logger.error('subscribe.error', {
367
+ err: err,
368
+ topic: subs[0]
369
+ });
370
+ } else {
371
+ _this2.logger.debug('subscribe.success', {
372
+ granted: granted,
373
+ topic: subs[0]
374
+ });
375
+ }
376
+ });
377
+ };
378
+ while (this.subscribtionBuffer.length > 0) {
379
+ _loop();
380
+ }
360
381
  }
361
382
  }
362
383
  }, {
363
384
  key: "unsubscribe",
364
- value: function unsubscribe() {
385
+ value:
386
+ /**
387
+ * @param {[string, import('mqtt').IClientSubscribeOptions]} args
388
+ */
389
+ function unsubscribe() {
390
+ var _this3 = this;
365
391
  for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
366
392
  args[_key3] = arguments[_key3];
367
393
  }
368
-
369
- this.logger('unsubscribe from', args);
394
+ this.logger.debug('unsubscribe', _objectSpread({}, args));
370
395
  this.unsubscribtionBuffer.push(args);
371
-
372
396
  if (this.mqtt != null) {
373
- do {
374
- var subs = this.unsubscribtionBuffer.shift();
375
-
397
+ var _loop2 = function _loop2() {
398
+ var subs = _this3.unsubscribtionBuffer.shift();
376
399
  if (subs != null) {
377
- var _this$mqtt2;
378
-
379
- (_this$mqtt2 = this.mqtt).unsubscribe.apply(_this$mqtt2, (0, _toConsumableArray2["default"])(subs));
400
+ _this3.mqtt.unsubscribe(subs[0], subs[1], function (err, packet) {
401
+ if (err) {
402
+ _this3.logger.error('unsubscribe.error', {
403
+ err: err,
404
+ topic: subs[0]
405
+ });
406
+ } else {
407
+ _this3.logger.debug('unsubscribe.success', {
408
+ packet: packet,
409
+ topic: subs[0]
410
+ });
411
+ }
412
+ });
380
413
  }
381
- } while (this.unsubscribtionBuffer.length > 0);
414
+ };
415
+ while (this.unsubscribtionBuffer.length > 0) {
416
+ _loop2();
417
+ }
382
418
  }
383
419
  }
384
420
  }, {
385
421
  key: "publish",
386
- value: function publish(topic, payload) {
422
+ value:
423
+ /**
424
+ * Publish a message to a topic.
425
+ * @param {string} topic - The topic to publish to.
426
+ * @param {string | Buffer} payload - The message to publish.
427
+ * @param {import('mqtt').IClientPublishOptions} [options] - Options for publishing.
428
+ */
429
+ function publish(topic, payload) {
430
+ var _this4 = this;
387
431
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
388
432
  this.publishBuffer.push({
389
433
  topic: topic,
390
434
  payload: payload,
391
435
  options: options
392
436
  });
393
-
394
- do {
395
- var data = this.publishBuffer.shift();
396
-
397
- if (data != null) {
398
- return this.mqtt.publish(data.topic, data.payload.toString(), data.options);
437
+ if (this.mqtt != null) {
438
+ var _loop3 = function _loop3() {
439
+ var data = _this4.publishBuffer.shift();
440
+ if (data == null) return 1; // continue
441
+ _this4.logger.debug('publish', {
442
+ topic: data.topic,
443
+ payload: data.payload.toString(),
444
+ options: data.options
445
+ });
446
+ _this4.mqtt.publish(data.topic, data.payload.toString(), data.options, function (err, packet) {
447
+ if (err) {
448
+ _this4.logger.error('publish.error', {
449
+ err: err,
450
+ topic: data.topic
451
+ });
452
+ } else {
453
+ _this4.logger.debug('publish.success', {
454
+ packet: packet,
455
+ topic: data.topic
456
+ });
457
+ }
458
+ });
459
+ };
460
+ while (this.publishBuffer.length > 0) {
461
+ if (_loop3()) continue;
399
462
  }
400
- } while (this.publishBuffer.length > 0);
463
+ }
401
464
  }
465
+
466
+ /**
467
+ * Emit an event with the given arguments.
468
+ * @param {[string, any]} args - The arguments to emit.
469
+ */
402
470
  }, {
403
471
  key: "emit",
404
472
  value: function emit() {
405
473
  var _this$emitter;
406
-
407
474
  (_this$emitter = this.emitter).emit.apply(_this$emitter, arguments);
408
475
  }
476
+
477
+ /**
478
+ * @param {[string, mitt.Handler]} args
479
+ */
409
480
  }, {
410
481
  key: "on",
411
482
  value: function on() {
412
483
  var _this$emitter2;
413
-
414
484
  (_this$emitter2 = this.emitter).on.apply(_this$emitter2, arguments);
415
485
  }
486
+ /**
487
+ * @param {[string, mitt.Handler]} args
488
+ */
416
489
  }, {
417
490
  key: "off",
418
491
  value: function off() {
419
492
  var _this$emitter3;
420
-
421
493
  (_this$emitter3 = this.emitter).off.apply(_this$emitter3, arguments);
422
494
  }
495
+
496
+ // #region regexp
423
497
  }, {
424
- key: "noop",
498
+ key: "reNewMessage",
499
+ get: function get() {
500
+ return /^(.+)\/c$/i;
501
+ }
502
+ }, {
503
+ key: "reNotification",
504
+ get: function get() {
505
+ return /^(.+)\/n$/i;
506
+ }
507
+ }, {
508
+ key: "reTyping",
509
+ get: function get() {
510
+ return /^r\/([\d]+)\/([\d]+)\/(.+)\/t$/i;
511
+ }
512
+ }, {
513
+ key: "reDelivery",
514
+ get: function get() {
515
+ return /^r\/([\d]+)\/([\d]+)\/(.+)\/d$/i;
516
+ }
517
+ }, {
518
+ key: "reRead",
519
+ get: function get() {
520
+ return /^r\/([\d]+)\/([\d]+)\/(.+)\/r$/i;
521
+ }
522
+ }, {
523
+ key: "reOnlineStatus",
524
+ get: function get() {
525
+ return /^u\/(.+)\/s$/i;
526
+ }
527
+ }, {
528
+ key: "reChannelMessage",
529
+ get: function get() {
530
+ return /^(.+)\/(.+)\/c$/i;
531
+ }
532
+ }, {
533
+ key: "reMessageUpdated",
534
+ get: function get() {
535
+ return /^(.+)\/update$/i;
536
+ }
425
537
  // #endregion
538
+ }, {
539
+ key: "noop",
426
540
  value: function noop() {}
427
541
  }, {
428
542
  key: "newMessageHandler",
429
543
  value: function newMessageHandler(topic, message) {
430
544
  message = JSON.parse(message);
431
- this.logger('on:new-message', message);
545
+ this.logger.debug('on:new-message', message);
432
546
  this.emit('new-message', message);
433
547
  }
434
548
  }, {
435
549
  key: "notificationHandler",
436
550
  value: function notificationHandler(topic, message) {
437
- var _this2 = this;
438
-
439
- this.logger('on:notification', message);
551
+ var _this5 = this;
552
+ this.logger.debug('on:notification', message);
440
553
  message = JSON.parse(message);
441
554
  var data = message.payload.data;
442
-
443
555
  if ('deleted_messages' in data) {
444
556
  data.deleted_messages.forEach(function (message) {
445
- _this2.emit('comment-deleted', {
557
+ _this5.emit('comment-deleted', {
446
558
  roomId: message.room_id,
447
559
  commentUniqueIds: message.message_unique_ids,
448
560
  isForEveryone: true,
@@ -450,18 +562,17 @@ var MqttAdapter = /*#__PURE__*/function () {
450
562
  });
451
563
  });
452
564
  }
453
-
454
565
  if ('deleted_rooms' in data) {
455
566
  data.deleted_rooms.forEach(function (room) {
456
- _this2.emit('room-cleared', room);
567
+ _this5.emit('room-cleared', room);
457
568
  });
458
569
  }
459
570
  }
460
571
  }, {
461
572
  key: "typingHandler",
462
573
  value: function typingHandler(t, message) {
463
- this.logger('on:typing', t); // r/{roomId}/{roomId}/{userId}/t
464
-
574
+ this.logger.debug('on:typing', t);
575
+ // r/{roomId}/{roomId}/{userId}/t
465
576
  var topic = t.match(this.reTyping);
466
577
  if (topic[3] === this.core.user_id) return;
467
578
  var userId = topic[3];
@@ -470,11 +581,11 @@ var MqttAdapter = /*#__PURE__*/function () {
470
581
  message: message,
471
582
  userId: userId,
472
583
  roomId: roomId
473
- }); // TODO: Don't allow side-effect
474
- // it should be handled in the UI not core
584
+ });
475
585
 
586
+ // TODO: Don't allow side-effect
587
+ // it should be handled in the UI not core
476
588
  if (this.core.selected == null) return;
477
-
478
589
  if (message === '1' && roomId === this.core.selected.id) {
479
590
  var actor = this.core.selected.participants.find(function (it) {
480
591
  return it.email === userId;
@@ -483,14 +594,14 @@ var MqttAdapter = /*#__PURE__*/function () {
483
594
  var displayName = actor.username;
484
595
  this.core.isTypingStatus = "".concat(displayName, " is typing ...");
485
596
  } else {
486
- this.core.isTypingStatus = null;
597
+ this.core.isTypingStatus = '';
487
598
  }
488
599
  }
489
600
  }, {
490
601
  key: "deliveryReceiptHandler",
491
602
  value: function deliveryReceiptHandler(t, message) {
492
- this.logger('on:delivered', t, message); // r/{roomId}/{roomId}/{userId}/d
493
-
603
+ this.logger.debug('on:delivered', t, message);
604
+ // r/{roomId}/{roomId}/{userId}/d
494
605
  var topic = t.match(this.reDelivery);
495
606
  var data = message.split(':');
496
607
  var commentId = Number(data[0]);
@@ -505,8 +616,8 @@ var MqttAdapter = /*#__PURE__*/function () {
505
616
  }, {
506
617
  key: "readReceiptHandler",
507
618
  value: function readReceiptHandler(t, message) {
508
- this.logger('on:read', t, message); // r/{roomId}/{roomId}/{userId}/r
509
-
619
+ this.logger.debug('on:read', t, message);
620
+ // r/{roomId}/{roomId}/{userId}/r
510
621
  var topic = t.match(this.reRead);
511
622
  var data = message.split(':');
512
623
  var commentId = Number(data[0]);
@@ -521,10 +632,10 @@ var MqttAdapter = /*#__PURE__*/function () {
521
632
  }, {
522
633
  key: "onlinePresenceHandler",
523
634
  value: function onlinePresenceHandler(topic, message) {
524
- this.logger('on:online-presence', topic, message); // u/guest-1002/s
525
-
635
+ this.logger.debug('on:online-presence', topic, message);
636
+ // u/guest-1002/s
526
637
  var topicData = this.reOnlineStatus.exec(topic);
527
- var userId = topicData[1];
638
+ var userId = topicData === null || topicData === void 0 ? void 0 : topicData[1];
528
639
  this.emit('presence', {
529
640
  message: message,
530
641
  userId: userId
@@ -533,17 +644,18 @@ var MqttAdapter = /*#__PURE__*/function () {
533
644
  }, {
534
645
  key: "channelMessageHandler",
535
646
  value: function channelMessageHandler(topic, message) {
536
- this.logger('on:channel-message', topic, message);
647
+ this.logger.debug('on:channel-message', topic, message);
537
648
  this.emit('new-message', JSON.parse(message));
538
649
  }
539
650
  }, {
540
651
  key: "messageUpdatedHandler",
541
652
  value: function messageUpdatedHandler(topic, message) {
542
653
  message = JSON.parse(message);
543
- this.logger('on:message-updated', topic, message);
654
+ this.logger.debug('on:message-updated', topic, message);
544
655
  this.emit('message:updated', message);
545
- } // #region old-methods
656
+ }
546
657
 
658
+ // #region old-methods
547
659
  }, {
548
660
  key: "subscribeChannel",
549
661
  value: function subscribeChannel(appId, uniqueId) {
@@ -567,20 +679,36 @@ var MqttAdapter = /*#__PURE__*/function () {
567
679
  this.unsubscribe("r/".concat(roomId, "/").concat(roomId, "/+/d"));
568
680
  this.unsubscribe("r/".concat(roomId, "/").concat(roomId, "/+/r"));
569
681
  }
682
+ }, {
683
+ key: "subscribeTyping",
684
+ get: function get() {
685
+ return this.subscribeRoom.bind(this);
686
+ }
687
+ }, {
688
+ key: "unsubscribeTyping",
689
+ get: function get() {
690
+ return this.unsubscribeRoom.bind(this);
691
+ }
570
692
  }, {
571
693
  key: "subscribeUserChannel",
572
694
  value: function subscribeUserChannel() {
573
- this.subscribe("".concat(this.core.userData.token, "/c"));
574
- this.subscribe("".concat(this.core.userData.token, "/n"));
575
- this.subscribe("".concat(this.core.userData.token, "/update"));
695
+ this.subscribe("".concat(this.core.userData.token, "/c"), {
696
+ qos: 1
697
+ });
698
+ this.subscribe("".concat(this.core.userData.token, "/n"), {
699
+ qos: 1
700
+ });
701
+ this.subscribe("".concat(this.core.userData.token, "/update"), {
702
+ qos: 1
703
+ });
576
704
  }
577
705
  }, {
578
706
  key: "publishPresence",
579
707
  value: function publishPresence(userId) {
580
708
  var isOnline = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
581
- isOnline ? this.publish("u/".concat(userId, "/s"), 1, {
709
+ isOnline ? this.publish("u/".concat(userId, "/s"), '1', {
582
710
  retain: true
583
- }) : this.publish("u/".concat(userId, "/s"), 0, {
711
+ }) : this.publish("u/".concat(userId, "/s"), '0', {
584
712
  retain: true
585
713
  });
586
714
  }
@@ -600,91 +728,6 @@ var MqttAdapter = /*#__PURE__*/function () {
600
728
  value: function unsubscribeUserPresence(userId) {
601
729
  this.unsubscribe("u/".concat(userId, "/s"));
602
730
  }
603
- }, {
604
- key: "publishTyping",
605
- value: function publishTyping(status) {
606
- if (this.core.selected == null) return;
607
- var roomId = this.core.selected.id;
608
- var userId = this.core.user_id;
609
- this.publish("r/".concat(roomId, "/").concat(roomId, "/").concat(userId, "/t"), status);
610
- } // #endregion
611
-
612
- }, {
613
- key: "cacheRealtimeURL",
614
- get: function get() {
615
- return this.core.mqttURL;
616
- },
617
- set: function set(url) {
618
- this.core.mqttURL = url;
619
- }
620
- }, {
621
- key: "connected",
622
- get: function get() {
623
- if (this.mqtt == null) return false;
624
- return this.mqtt.connected;
625
- }
626
- }, {
627
- key: "logEnabled",
628
- get: function get() {
629
- return this.core.debugMQTTMode;
630
- }
631
- }, {
632
- key: "logger",
633
- get: function get() {
634
- if (!this.core.debugMQTTMode) return this.noop;
635
- return console.log.bind(console, 'QRealtime ->');
636
- } // #region regexp
637
-
638
- }, {
639
- key: "reNewMessage",
640
- get: function get() {
641
- return /^(.+)\/c$/i;
642
- }
643
- }, {
644
- key: "reNotification",
645
- get: function get() {
646
- return /^(.+)\/n$/i;
647
- }
648
- }, {
649
- key: "reTyping",
650
- get: function get() {
651
- return /^r\/([\d]+)\/([\d]+)\/(.+)\/t$/i;
652
- }
653
- }, {
654
- key: "reDelivery",
655
- get: function get() {
656
- return /^r\/([\d]+)\/([\d]+)\/(.+)\/d$/i;
657
- }
658
- }, {
659
- key: "reRead",
660
- get: function get() {
661
- return /^r\/([\d]+)\/([\d]+)\/(.+)\/r$/i;
662
- }
663
- }, {
664
- key: "reOnlineStatus",
665
- get: function get() {
666
- return /^u\/(.+)\/s$/i;
667
- }
668
- }, {
669
- key: "reChannelMessage",
670
- get: function get() {
671
- return /^(.+)\/(.+)\/c$/i;
672
- }
673
- }, {
674
- key: "reMessageUpdated",
675
- get: function get() {
676
- return /^(.+)\/update$/i;
677
- }
678
- }, {
679
- key: "subscribeTyping",
680
- get: function get() {
681
- return this.subscribeRoom.bind(this);
682
- }
683
- }, {
684
- key: "unsubscribeTyping",
685
- get: function get() {
686
- return this.unsubscribeRoom.bind(this);
687
- }
688
731
  }, {
689
732
  key: "subscribeRoomPresence",
690
733
  get: function get() {
@@ -695,9 +738,16 @@ var MqttAdapter = /*#__PURE__*/function () {
695
738
  get: function get() {
696
739
  return this.unsubscribeUserPresence.bind(this);
697
740
  }
741
+ }, {
742
+ key: "publishTyping",
743
+ value: function publishTyping(status) {
744
+ if (this.core.selected == null) return;
745
+ var roomId = this.core.selected.id;
746
+ var userId = this.core.user_id;
747
+ this.publish("r/".concat(roomId, "/").concat(roomId, "/").concat(userId, "/t"), status);
748
+ }
749
+
750
+ // #endregion
698
751
  }]);
699
- return MqttAdapter;
700
752
  }();
701
-
702
- exports["default"] = MqttAdapter;
703
753
  module.exports = exports.default;