mqtt 5.0.0-beta.3 → 5.0.0-beta.4

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.
Files changed (126) hide show
  1. package/README.md +8 -4
  2. package/build/package.json +162 -0
  3. package/build/src/bin/mqtt.d.ts +2 -0
  4. package/build/src/bin/mqtt.js +27 -0
  5. package/build/src/bin/mqtt.js.map +1 -0
  6. package/build/src/bin/pub.d.ts +2 -0
  7. package/build/src/bin/pub.js +146 -0
  8. package/build/src/bin/pub.js.map +1 -0
  9. package/build/src/bin/sub.d.ts +2 -0
  10. package/build/src/bin/sub.js +121 -0
  11. package/build/src/bin/sub.js.map +1 -0
  12. package/build/src/lib/TypedEmitter.d.ts +11 -0
  13. package/build/src/lib/TypedEmitter.js +13 -0
  14. package/build/src/lib/TypedEmitter.js.map +1 -0
  15. package/build/src/lib/client.d.ts +266 -0
  16. package/build/src/lib/client.js +1147 -0
  17. package/build/src/lib/client.js.map +1 -0
  18. package/build/src/lib/connect/ali.d.ts +3 -0
  19. package/build/src/lib/connect/ali.js +113 -0
  20. package/build/src/lib/connect/ali.js.map +1 -0
  21. package/build/src/lib/connect/index.d.ts +5 -0
  22. package/build/src/lib/connect/index.js +134 -0
  23. package/build/src/lib/connect/index.js.map +1 -0
  24. package/build/src/lib/connect/tcp.d.ts +3 -0
  25. package/build/src/lib/connect/tcp.js +18 -0
  26. package/build/src/lib/connect/tcp.js.map +1 -0
  27. package/build/src/lib/connect/tls.d.ts +3 -0
  28. package/build/src/lib/connect/tls.js +38 -0
  29. package/build/src/lib/connect/tls.js.map +1 -0
  30. package/build/src/lib/connect/ws.d.ts +3 -0
  31. package/build/src/lib/connect/ws.js +212 -0
  32. package/build/src/lib/connect/ws.js.map +1 -0
  33. package/build/src/lib/connect/wx.d.ts +3 -0
  34. package/build/src/lib/connect/wx.js +117 -0
  35. package/build/src/lib/connect/wx.js.map +1 -0
  36. package/build/src/lib/default-message-id-provider.d.ts +16 -0
  37. package/build/src/lib/default-message-id-provider.js +24 -0
  38. package/build/src/lib/default-message-id-provider.js.map +1 -0
  39. package/build/src/lib/handlers/ack.d.ts +48 -0
  40. package/build/src/lib/handlers/ack.js +129 -0
  41. package/build/src/lib/handlers/ack.js.map +1 -0
  42. package/build/src/lib/handlers/auth.d.ts +3 -0
  43. package/build/src/lib/handlers/auth.js +30 -0
  44. package/build/src/lib/handlers/auth.js.map +1 -0
  45. package/build/src/lib/handlers/connack.d.ts +3 -0
  46. package/build/src/lib/handlers/connack.js +48 -0
  47. package/build/src/lib/handlers/connack.js.map +1 -0
  48. package/build/src/lib/handlers/index.d.ts +3 -0
  49. package/build/src/lib/handlers/index.js +64 -0
  50. package/build/src/lib/handlers/index.js.map +1 -0
  51. package/build/src/lib/handlers/publish.d.ts +3 -0
  52. package/build/src/lib/handlers/publish.js +106 -0
  53. package/build/src/lib/handlers/publish.js.map +1 -0
  54. package/build/src/lib/handlers/pubrel.d.ts +3 -0
  55. package/build/src/lib/handlers/pubrel.js +25 -0
  56. package/build/src/lib/handlers/pubrel.js.map +1 -0
  57. package/build/src/lib/is-browser.d.ts +2 -0
  58. package/build/src/lib/is-browser.js +8 -0
  59. package/build/src/lib/is-browser.js.map +1 -0
  60. package/build/src/lib/shared.d.ts +17 -0
  61. package/build/src/lib/shared.js +35 -0
  62. package/build/src/lib/shared.js.map +1 -0
  63. package/build/src/lib/store.d.ts +24 -0
  64. package/build/src/lib/store.js +80 -0
  65. package/build/src/lib/store.js.map +1 -0
  66. package/build/src/lib/topic-alias-recv.d.ts +9 -0
  67. package/build/src/lib/topic-alias-recv.js +24 -0
  68. package/build/src/lib/topic-alias-recv.js.map +1 -0
  69. package/build/src/lib/topic-alias-send.d.ts +13 -0
  70. package/build/src/lib/topic-alias-send.js +56 -0
  71. package/build/src/lib/topic-alias-send.js.map +1 -0
  72. package/build/src/lib/unique-message-id-provider.d.ts +10 -0
  73. package/build/src/lib/unique-message-id-provider.js +26 -0
  74. package/build/src/lib/unique-message-id-provider.js.map +1 -0
  75. package/build/src/lib/validations.d.ts +2 -0
  76. package/build/src/lib/validations.js +32 -0
  77. package/build/src/lib/validations.js.map +1 -0
  78. package/build/src/mqtt.d.ts +8 -0
  79. package/build/src/mqtt.js +33 -0
  80. package/build/src/mqtt.js.map +1 -0
  81. package/build/tsconfig.build.tsbuildinfo +1 -0
  82. package/dist/mqtt.js +2626 -3501
  83. package/dist/mqtt.min.js +4 -4
  84. package/package.json +49 -29
  85. package/{bin/mqtt.js → src/bin/mqtt.ts} +11 -6
  86. package/src/bin/pub.ts +171 -0
  87. package/src/bin/sub.ts +146 -0
  88. package/src/lib/TypedEmitter.ts +45 -0
  89. package/{lib/client.js → src/lib/client.ts} +854 -243
  90. package/{lib/connect/ali.js → src/lib/connect/ali.ts} +14 -12
  91. package/{lib/connect/index.js → src/lib/connect/index.ts} +43 -38
  92. package/src/lib/connect/tcp.ts +23 -0
  93. package/{lib/connect/tls.js → src/lib/connect/tls.ts} +12 -8
  94. package/{lib/connect/ws.js → src/lib/connect/ws.ts} +53 -36
  95. package/{lib/connect/wx.js → src/lib/connect/wx.ts} +19 -10
  96. package/src/lib/default-message-id-provider.ts +99 -0
  97. package/{lib/handlers/ack.js → src/lib/handlers/ack.ts} +17 -19
  98. package/src/lib/handlers/auth.ts +44 -0
  99. package/{lib/handlers/connack.js → src/lib/handlers/connack.ts} +15 -11
  100. package/{lib/handlers/index.js → src/lib/handlers/index.ts} +8 -7
  101. package/{lib/handlers/publish.js → src/lib/handlers/publish.ts} +73 -57
  102. package/src/lib/handlers/pubrel.ts +27 -0
  103. package/{lib/is-browser.js → src/lib/is-browser.ts} +5 -4
  104. package/src/lib/shared.ts +73 -0
  105. package/{lib/store.js → src/lib/store.ts} +61 -16
  106. package/{lib/topic-alias-recv.js → src/lib/topic-alias-recv.ts} +10 -6
  107. package/{lib/topic-alias-send.js → src/lib/topic-alias-send.ts} +19 -11
  108. package/{lib/unique-message-id-provider.js → src/lib/unique-message-id-provider.ts} +8 -6
  109. package/{lib/validations.js → src/lib/validations.ts} +2 -6
  110. package/src/mqtt.ts +23 -0
  111. package/bin/pub.js +0 -159
  112. package/bin/sub.js +0 -141
  113. package/lib/connect/tcp.js +0 -19
  114. package/lib/default-message-id-provider.js +0 -63
  115. package/lib/handlers/auth.js +0 -34
  116. package/lib/handlers/pubrel.js +0 -24
  117. package/mqtt.js +0 -21
  118. package/types/index.d.ts +0 -30
  119. package/types/lib/client-options.d.ts +0 -224
  120. package/types/lib/client.d.ts +0 -273
  121. package/types/lib/connect/index.d.ts +0 -19
  122. package/types/lib/default-message-id-provider.d.ts +0 -49
  123. package/types/lib/message-id-provider.d.ts +0 -40
  124. package/types/lib/store-options.d.ts +0 -6
  125. package/types/lib/store.d.ts +0 -46
  126. package/types/lib/unique-message-id-provider.d.ts +0 -48
@@ -0,0 +1,1147 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const topic_alias_recv_1 = __importDefault(require("./topic-alias-recv"));
30
+ const mqtt_packet_1 = __importDefault(require("mqtt-packet"));
31
+ const default_message_id_provider_1 = __importDefault(require("./default-message-id-provider"));
32
+ const readable_stream_1 = require("readable-stream");
33
+ const reinterval_1 = __importDefault(require("reinterval"));
34
+ const default_1 = __importDefault(require("rfdc/default"));
35
+ const validations = __importStar(require("./validations"));
36
+ const debug_1 = __importDefault(require("debug"));
37
+ const store_1 = __importDefault(require("./store"));
38
+ const handlers_1 = __importDefault(require("./handlers"));
39
+ const TypedEmitter_1 = require("./TypedEmitter");
40
+ const nextTick = process
41
+ ? process.nextTick
42
+ : (callback) => {
43
+ setTimeout(callback, 0);
44
+ };
45
+ const setImmediate = global.setImmediate ||
46
+ ((...args) => {
47
+ const callback = args.shift();
48
+ nextTick(() => {
49
+ callback(...args);
50
+ });
51
+ });
52
+ const defaultConnectOptions = {
53
+ keepalive: 60,
54
+ reschedulePings: true,
55
+ protocolId: 'MQTT',
56
+ protocolVersion: 4,
57
+ reconnectPeriod: 1000,
58
+ connectTimeout: 30 * 1000,
59
+ clean: true,
60
+ resubscribe: true,
61
+ writeCache: true,
62
+ };
63
+ const socketErrors = [
64
+ 'ECONNREFUSED',
65
+ 'EADDRINUSE',
66
+ 'ECONNRESET',
67
+ 'ENOTFOUND',
68
+ 'ETIMEDOUT',
69
+ ];
70
+ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
71
+ static defaultId() {
72
+ return `mqttjs_${Math.random().toString(16).substr(2, 8)}`;
73
+ }
74
+ constructor(streamBuilder, options) {
75
+ super();
76
+ this.options = options || {};
77
+ for (const k in defaultConnectOptions) {
78
+ if (typeof this.options[k] === 'undefined') {
79
+ this.options[k] = defaultConnectOptions[k];
80
+ }
81
+ else {
82
+ this.options[k] = options[k];
83
+ }
84
+ }
85
+ this.log = this.options.log || (0, debug_1.default)('mqttjs:client');
86
+ this.noop = this._noop.bind(this);
87
+ this.log('MqttClient :: options.protocol', options.protocol);
88
+ this.log('MqttClient :: options.protocolVersion', options.protocolVersion);
89
+ this.log('MqttClient :: options.username', options.username);
90
+ this.log('MqttClient :: options.keepalive', options.keepalive);
91
+ this.log('MqttClient :: options.reconnectPeriod', options.reconnectPeriod);
92
+ this.log('MqttClient :: options.rejectUnauthorized', options.rejectUnauthorized);
93
+ this.log('MqttClient :: options.properties.topicAliasMaximum', options.properties
94
+ ? options.properties.topicAliasMaximum
95
+ : undefined);
96
+ this.options.clientId =
97
+ typeof options.clientId === 'string'
98
+ ? options.clientId
99
+ : MqttClient.defaultId();
100
+ this.log('MqttClient :: clientId', this.options.clientId);
101
+ this.options.customHandleAcks =
102
+ options.protocolVersion === 5 && options.customHandleAcks
103
+ ? options.customHandleAcks
104
+ : (...args) => {
105
+ args[3](null, 0);
106
+ };
107
+ if (!this.options.writeCache) {
108
+ mqtt_packet_1.default.writeToStream.cacheNumbers = false;
109
+ }
110
+ this.streamBuilder = streamBuilder;
111
+ this.messageIdProvider =
112
+ typeof this.options.messageIdProvider === 'undefined'
113
+ ? new default_message_id_provider_1.default()
114
+ : this.options.messageIdProvider;
115
+ this.outgoingStore = options.outgoingStore || new store_1.default();
116
+ this.incomingStore = options.incomingStore || new store_1.default();
117
+ this.queueQoSZero =
118
+ options.queueQoSZero === undefined ? true : options.queueQoSZero;
119
+ this._resubscribeTopics = {};
120
+ this.messageIdToTopic = {};
121
+ this.pingTimer = null;
122
+ this.connected = false;
123
+ this.disconnecting = false;
124
+ this.queue = [];
125
+ this.connackTimer = null;
126
+ this.reconnectTimer = null;
127
+ this._storeProcessing = false;
128
+ this._packetIdsDuringStoreProcessing = {};
129
+ this._storeProcessingQueue = [];
130
+ this.outgoing = {};
131
+ this._firstConnection = true;
132
+ if (options.properties && options.properties.topicAliasMaximum > 0) {
133
+ if (options.properties.topicAliasMaximum > 0xffff) {
134
+ this.log('MqttClient :: options.properties.topicAliasMaximum is out of range');
135
+ }
136
+ else {
137
+ this.topicAliasRecv = new topic_alias_recv_1.default(options.properties.topicAliasMaximum);
138
+ }
139
+ }
140
+ this.on('connect', () => {
141
+ const { queue } = this;
142
+ const deliver = () => {
143
+ const entry = queue.shift();
144
+ this.log('deliver :: entry %o', entry);
145
+ let packet = null;
146
+ if (!entry) {
147
+ this._resubscribe();
148
+ return;
149
+ }
150
+ packet = entry.packet;
151
+ this.log('deliver :: call _sendPacket for %o', packet);
152
+ let send = true;
153
+ if (packet.messageId && packet.messageId !== 0) {
154
+ if (!this.messageIdProvider.register(packet.messageId)) {
155
+ send = false;
156
+ }
157
+ }
158
+ if (send) {
159
+ this._sendPacket(packet, (err) => {
160
+ if (entry.cb) {
161
+ entry.cb(err);
162
+ }
163
+ deliver();
164
+ });
165
+ }
166
+ else {
167
+ this.log('messageId: %d has already used. The message is skipped and removed.', packet.messageId);
168
+ deliver();
169
+ }
170
+ };
171
+ this.log('connect :: sending queued packets');
172
+ deliver();
173
+ });
174
+ this.on('close', () => {
175
+ this.log('close :: connected set to `false`');
176
+ this.connected = false;
177
+ this.log('close :: clearing connackTimer');
178
+ clearTimeout(this.connackTimer);
179
+ this.log('close :: clearing ping timer');
180
+ if (this.pingTimer !== null) {
181
+ this.pingTimer.clear();
182
+ this.pingTimer = null;
183
+ }
184
+ if (this.topicAliasRecv) {
185
+ this.topicAliasRecv.clear();
186
+ }
187
+ this.log('close :: calling _setupReconnect');
188
+ this._setupReconnect();
189
+ });
190
+ if (!this.options.manualConnect) {
191
+ this.log('MqttClient :: setting up stream');
192
+ this.connect();
193
+ }
194
+ }
195
+ handleAuth(packet, callback) {
196
+ callback();
197
+ }
198
+ handleMessage(packet, callback) {
199
+ callback();
200
+ }
201
+ _nextId() {
202
+ return this.messageIdProvider.allocate();
203
+ }
204
+ getLastMessageId() {
205
+ return this.messageIdProvider.getLastAllocated();
206
+ }
207
+ connect() {
208
+ const writable = new readable_stream_1.Writable();
209
+ const parser = mqtt_packet_1.default.parser(this.options);
210
+ let completeParse = null;
211
+ const packets = [];
212
+ this.log('connect :: calling method to clear reconnect');
213
+ this._clearReconnect();
214
+ this.log('connect :: using streamBuilder provided to client to create stream');
215
+ this.stream = this.streamBuilder(this);
216
+ parser.on('packet', (packet) => {
217
+ this.log('parser :: on packet push to packets array.');
218
+ packets.push(packet);
219
+ });
220
+ const work = () => {
221
+ this.log('work :: getting next packet in queue');
222
+ const packet = packets.shift();
223
+ if (packet) {
224
+ this.log('work :: packet pulled from queue');
225
+ (0, handlers_1.default)(this, packet, nextTickWork);
226
+ }
227
+ else {
228
+ this.log('work :: no packets in queue');
229
+ const done = completeParse;
230
+ completeParse = null;
231
+ this.log('work :: done flag is %s', !!done);
232
+ if (done)
233
+ done();
234
+ }
235
+ };
236
+ const nextTickWork = () => {
237
+ if (packets.length) {
238
+ nextTick(work);
239
+ }
240
+ else {
241
+ const done = completeParse;
242
+ completeParse = null;
243
+ done();
244
+ }
245
+ };
246
+ writable._write = (buf, enc, done) => {
247
+ completeParse = done;
248
+ this.log('writable stream :: parsing buffer');
249
+ parser.parse(buf);
250
+ work();
251
+ };
252
+ const streamErrorHandler = (error) => {
253
+ this.log('streamErrorHandler :: error', error.message);
254
+ if (socketErrors.includes(error.code)) {
255
+ this.log('streamErrorHandler :: emitting error');
256
+ this.emit('error', error);
257
+ }
258
+ else {
259
+ this.noop(error);
260
+ }
261
+ };
262
+ this.log('connect :: pipe stream to writable stream');
263
+ this.stream.pipe(writable);
264
+ this.stream.on('error', streamErrorHandler);
265
+ this.stream.on('close', () => {
266
+ this.log('(%s)stream :: on close', this.options.clientId);
267
+ this._flushVolatile();
268
+ this.log('stream: emit close to MqttClient');
269
+ this.emit('close');
270
+ });
271
+ this.log('connect: sending packet `connect`');
272
+ const connectPacket = Object.create(this.options);
273
+ connectPacket.cmd = 'connect';
274
+ if (this.topicAliasRecv) {
275
+ if (!connectPacket.properties) {
276
+ connectPacket.properties = {};
277
+ }
278
+ if (this.topicAliasRecv) {
279
+ connectPacket.properties.topicAliasMaximum =
280
+ this.topicAliasRecv.max;
281
+ }
282
+ }
283
+ this._writePacket(connectPacket);
284
+ parser.on('error', this.emit.bind(this, 'error'));
285
+ if (this.options.properties) {
286
+ if (!this.options.properties.authenticationMethod &&
287
+ this.options.properties.authenticationData) {
288
+ this.end(() => this.emit('error', new Error('Packet has no Authentication Method')));
289
+ return this;
290
+ }
291
+ if (this.options.properties.authenticationMethod &&
292
+ this.options.authPacket &&
293
+ typeof this.options.authPacket === 'object') {
294
+ const authPacket = Object.assign({ cmd: 'auth', reasonCode: 0 }, this.options.authPacket);
295
+ this._writePacket(authPacket);
296
+ }
297
+ }
298
+ this.stream.setMaxListeners(1000);
299
+ clearTimeout(this.connackTimer);
300
+ this.connackTimer = setTimeout(() => {
301
+ this.log('!!connectTimeout hit!! Calling _cleanUp with force `true`');
302
+ this._cleanUp(true);
303
+ }, this.options.connectTimeout);
304
+ return this;
305
+ }
306
+ publish(topic, message, opts, callback) {
307
+ this.log('publish :: message `%s` to topic `%s`', message, topic);
308
+ const { options } = this;
309
+ if (typeof opts === 'function') {
310
+ callback = opts;
311
+ opts = {};
312
+ }
313
+ const defaultOpts = {
314
+ qos: 0,
315
+ retain: false,
316
+ dup: false,
317
+ };
318
+ opts = Object.assign(Object.assign({}, defaultOpts), opts);
319
+ const { qos, retain, dup, properties, cbStorePut } = opts;
320
+ if (this._checkDisconnecting(callback)) {
321
+ return this;
322
+ }
323
+ const publishProc = () => {
324
+ let messageId = 0;
325
+ if (qos === 1 || qos === 2) {
326
+ messageId = this._nextId();
327
+ if (messageId === null) {
328
+ this.log('No messageId left');
329
+ return false;
330
+ }
331
+ }
332
+ const packet = {
333
+ cmd: 'publish',
334
+ topic,
335
+ payload: message,
336
+ qos,
337
+ retain,
338
+ messageId,
339
+ dup,
340
+ };
341
+ if (options.protocolVersion === 5) {
342
+ packet.properties = properties;
343
+ }
344
+ this.log('publish :: qos', qos);
345
+ switch (qos) {
346
+ case 1:
347
+ case 2:
348
+ this.outgoing[packet.messageId] = {
349
+ volatile: false,
350
+ cb: callback || this.noop,
351
+ };
352
+ this.log('MqttClient:publish: packet cmd: %s', packet.cmd);
353
+ this._sendPacket(packet, undefined, cbStorePut);
354
+ break;
355
+ default:
356
+ this.log('MqttClient:publish: packet cmd: %s', packet.cmd);
357
+ this._sendPacket(packet, callback, cbStorePut);
358
+ break;
359
+ }
360
+ return true;
361
+ };
362
+ if (this._storeProcessing ||
363
+ this._storeProcessingQueue.length > 0 ||
364
+ !publishProc()) {
365
+ this._storeProcessingQueue.push({
366
+ invoke: publishProc,
367
+ cbStorePut: opts.cbStorePut,
368
+ callback,
369
+ });
370
+ }
371
+ return this;
372
+ }
373
+ subscribe(topicObject, opts, callback) {
374
+ const version = this.options.protocolVersion;
375
+ if (typeof opts === 'function') {
376
+ callback = opts;
377
+ }
378
+ callback = callback || this.noop;
379
+ let resubscribe = false;
380
+ let topicsList = [];
381
+ if (typeof topicObject === 'string') {
382
+ topicObject = [topicObject];
383
+ topicsList = topicObject;
384
+ }
385
+ else if (Array.isArray(topicObject)) {
386
+ topicsList = topicObject;
387
+ }
388
+ else if (typeof topicObject === 'object') {
389
+ resubscribe = topicObject.resubscribe;
390
+ delete topicObject.resubscribe;
391
+ topicsList = Object.keys(topicObject);
392
+ }
393
+ const invalidTopic = validations.validateTopics(topicsList);
394
+ if (invalidTopic !== null) {
395
+ setImmediate(callback, new Error(`Invalid topic ${invalidTopic}`));
396
+ return this;
397
+ }
398
+ if (this._checkDisconnecting(callback)) {
399
+ this.log('subscribe: discconecting true');
400
+ return this;
401
+ }
402
+ const defaultOpts = {
403
+ qos: 0,
404
+ };
405
+ if (version === 5) {
406
+ defaultOpts.nl = false;
407
+ defaultOpts.rap = false;
408
+ defaultOpts.rh = 0;
409
+ }
410
+ opts = Object.assign(Object.assign({}, defaultOpts), opts);
411
+ const properties = opts.properties;
412
+ const subs = [];
413
+ const parseSub = (topic, subOptions) => {
414
+ subOptions = (subOptions || opts);
415
+ if (!Object.prototype.hasOwnProperty.call(this._resubscribeTopics, topic) ||
416
+ this._resubscribeTopics[topic].qos < subOptions.qos ||
417
+ resubscribe) {
418
+ const currentOpts = {
419
+ topic,
420
+ qos: subOptions.qos,
421
+ };
422
+ if (version === 5) {
423
+ currentOpts.nl = subOptions.nl;
424
+ currentOpts.rap = subOptions.rap;
425
+ currentOpts.rh = subOptions.rh;
426
+ currentOpts.properties = properties;
427
+ }
428
+ this.log('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos);
429
+ subs.push(currentOpts);
430
+ }
431
+ };
432
+ if (Array.isArray(topicObject)) {
433
+ topicObject.forEach((topic) => {
434
+ this.log('subscribe: array topic %s', topic);
435
+ parseSub(topic);
436
+ });
437
+ }
438
+ else {
439
+ Object.keys(topicObject).forEach((topic) => {
440
+ this.log('subscribe: object topic %s, %o', topic, topicObject[topic]);
441
+ parseSub(topic, topicObject[topic]);
442
+ });
443
+ }
444
+ if (!subs.length) {
445
+ callback(null, []);
446
+ return this;
447
+ }
448
+ const subscribeProc = () => {
449
+ const messageId = this._nextId();
450
+ if (messageId === null) {
451
+ this.log('No messageId left');
452
+ return false;
453
+ }
454
+ const packet = {
455
+ cmd: 'subscribe',
456
+ subscriptions: subs,
457
+ messageId,
458
+ };
459
+ if (properties) {
460
+ packet.properties = properties;
461
+ }
462
+ if (this.options.resubscribe) {
463
+ this.log('subscribe :: resubscribe true');
464
+ const topics = [];
465
+ subs.forEach((sub) => {
466
+ if (this.options.reconnectPeriod > 0) {
467
+ const topic = { qos: sub.qos };
468
+ if (version === 5) {
469
+ topic.nl = sub.nl || false;
470
+ topic.rap = sub.rap || false;
471
+ topic.rh = sub.rh || 0;
472
+ topic.properties = sub.properties;
473
+ }
474
+ this._resubscribeTopics[sub.topic] = topic;
475
+ topics.push(sub.topic);
476
+ }
477
+ });
478
+ this.messageIdToTopic[packet.messageId] = topics;
479
+ }
480
+ this.outgoing[packet.messageId] = {
481
+ volatile: true,
482
+ cb(err, packet2) {
483
+ if (!err) {
484
+ const { granted } = packet2;
485
+ for (let i = 0; i < granted.length; i += 1) {
486
+ subs[i].qos = granted[i];
487
+ }
488
+ }
489
+ callback(err, subs);
490
+ },
491
+ };
492
+ this.log('subscribe :: call _sendPacket');
493
+ this._sendPacket(packet);
494
+ return true;
495
+ };
496
+ if (this._storeProcessing ||
497
+ this._storeProcessingQueue.length > 0 ||
498
+ !subscribeProc()) {
499
+ this._storeProcessingQueue.push({
500
+ invoke: subscribeProc,
501
+ callback,
502
+ });
503
+ }
504
+ return this;
505
+ }
506
+ unsubscribe(topic, opts, callback) {
507
+ if (typeof topic === 'string') {
508
+ topic = [topic];
509
+ }
510
+ if (typeof opts === 'function') {
511
+ callback = opts;
512
+ }
513
+ callback = callback || this.noop;
514
+ const invalidTopic = validations.validateTopics(topic);
515
+ if (invalidTopic !== null) {
516
+ setImmediate(callback, new Error(`Invalid topic ${invalidTopic}`));
517
+ return this;
518
+ }
519
+ if (this._checkDisconnecting(callback)) {
520
+ return this;
521
+ }
522
+ const unsubscribeProc = () => {
523
+ const messageId = this._nextId();
524
+ if (messageId === null) {
525
+ this.log('No messageId left');
526
+ return false;
527
+ }
528
+ const packet = {
529
+ cmd: 'unsubscribe',
530
+ messageId,
531
+ unsubscriptions: [],
532
+ };
533
+ if (typeof topic === 'string') {
534
+ packet.unsubscriptions = [topic];
535
+ }
536
+ else if (Array.isArray(topic)) {
537
+ packet.unsubscriptions = topic;
538
+ }
539
+ if (this.options.resubscribe) {
540
+ packet.unsubscriptions.forEach((topic2) => {
541
+ delete this._resubscribeTopics[topic2];
542
+ });
543
+ }
544
+ if (typeof opts === 'object' && opts.properties) {
545
+ packet.properties = opts.properties;
546
+ }
547
+ this.outgoing[packet.messageId] = {
548
+ volatile: true,
549
+ cb: callback,
550
+ };
551
+ this.log('unsubscribe: call _sendPacket');
552
+ this._sendPacket(packet);
553
+ return true;
554
+ };
555
+ if (this._storeProcessing ||
556
+ this._storeProcessingQueue.length > 0 ||
557
+ !unsubscribeProc()) {
558
+ this._storeProcessingQueue.push({
559
+ invoke: unsubscribeProc,
560
+ callback,
561
+ });
562
+ }
563
+ return this;
564
+ }
565
+ end(force, opts, cb) {
566
+ this.log('end :: (%s)', this.options.clientId);
567
+ if (force == null || typeof force !== 'boolean') {
568
+ cb = (opts || this.noop);
569
+ opts = force;
570
+ force = false;
571
+ if (typeof opts !== 'object') {
572
+ cb = opts;
573
+ opts = null;
574
+ if (typeof cb !== 'function') {
575
+ cb = this.noop;
576
+ }
577
+ }
578
+ }
579
+ if (typeof opts !== 'object') {
580
+ cb = opts;
581
+ opts = null;
582
+ }
583
+ this.log('end :: cb? %s', !!cb);
584
+ cb = cb || this.noop;
585
+ const closeStores = () => {
586
+ this.log('end :: closeStores: closing incoming and outgoing stores');
587
+ this.disconnected = true;
588
+ this.incomingStore.close((e1) => {
589
+ this.outgoingStore.close((e2) => {
590
+ this.log('end :: closeStores: emitting end');
591
+ this.emit('end');
592
+ if (cb) {
593
+ const err = e1 || e2;
594
+ this.log('end :: closeStores: invoking callback with args');
595
+ cb(err);
596
+ }
597
+ });
598
+ });
599
+ if (this._deferredReconnect) {
600
+ this._deferredReconnect();
601
+ }
602
+ };
603
+ const finish = () => {
604
+ this.log('end :: (%s) :: finish :: calling _cleanUp with force %s', this.options.clientId, force);
605
+ this._cleanUp(force, () => {
606
+ this.log('end :: finish :: calling process.nextTick on closeStores');
607
+ nextTick(closeStores);
608
+ }, opts);
609
+ };
610
+ if (this.disconnecting) {
611
+ cb();
612
+ return this;
613
+ }
614
+ this._clearReconnect();
615
+ this.disconnecting = true;
616
+ if (!force && Object.keys(this.outgoing).length > 0) {
617
+ this.log('end :: (%s) :: calling finish in 10ms once outgoing is empty', this.options.clientId);
618
+ this.once('outgoingEmpty', setTimeout.bind(null, finish, 10));
619
+ }
620
+ else {
621
+ this.log('end :: (%s) :: immediately calling finish', this.options.clientId);
622
+ finish();
623
+ }
624
+ return this;
625
+ }
626
+ removeOutgoingMessage(messageId) {
627
+ if (this.outgoing[messageId]) {
628
+ const { cb } = this.outgoing[messageId];
629
+ this._removeOutgoingAndStoreMessage(messageId, () => {
630
+ cb(new Error('Message removed'));
631
+ });
632
+ }
633
+ return this;
634
+ }
635
+ reconnect(opts) {
636
+ this.log('client reconnect');
637
+ const f = () => {
638
+ if (opts) {
639
+ this.options.incomingStore = opts.incomingStore;
640
+ this.options.outgoingStore = opts.outgoingStore;
641
+ }
642
+ else {
643
+ this.options.incomingStore = null;
644
+ this.options.outgoingStore = null;
645
+ }
646
+ this.incomingStore = this.options.incomingStore || new store_1.default();
647
+ this.outgoingStore = this.options.outgoingStore || new store_1.default();
648
+ this.disconnecting = false;
649
+ this.disconnected = false;
650
+ this._deferredReconnect = null;
651
+ this._reconnect();
652
+ };
653
+ if (this.disconnecting && !this.disconnected) {
654
+ this._deferredReconnect = f;
655
+ }
656
+ else {
657
+ f();
658
+ }
659
+ return this;
660
+ }
661
+ _flushVolatile() {
662
+ if (this.outgoing) {
663
+ this.log('_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function');
664
+ Object.keys(this.outgoing).forEach((messageId) => {
665
+ if (this.outgoing[messageId].volatile &&
666
+ typeof this.outgoing[messageId].cb === 'function') {
667
+ this.outgoing[messageId].cb(new Error('Connection closed'));
668
+ delete this.outgoing[messageId];
669
+ }
670
+ });
671
+ }
672
+ }
673
+ _flush() {
674
+ if (this.outgoing) {
675
+ this.log('_flush: queue exists? %b', !!this.outgoing);
676
+ Object.keys(this.outgoing).forEach((messageId) => {
677
+ if (typeof this.outgoing[messageId].cb === 'function') {
678
+ this.outgoing[messageId].cb(new Error('Connection closed'));
679
+ delete this.outgoing[messageId];
680
+ }
681
+ });
682
+ }
683
+ }
684
+ _removeTopicAliasAndRecoverTopicName(packet) {
685
+ let alias;
686
+ if (packet.properties) {
687
+ alias = packet.properties.topicAlias;
688
+ }
689
+ let topic = packet.topic.toString();
690
+ this.log('_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o', alias, topic);
691
+ if (topic.length === 0) {
692
+ if (typeof alias === 'undefined') {
693
+ return new Error('Unregistered Topic Alias');
694
+ }
695
+ topic = this.topicAliasSend.getTopicByAlias(alias);
696
+ if (typeof topic === 'undefined') {
697
+ return new Error('Unregistered Topic Alias');
698
+ }
699
+ packet.topic = topic;
700
+ }
701
+ if (alias) {
702
+ delete packet.properties.topicAlias;
703
+ }
704
+ }
705
+ _checkDisconnecting(callback) {
706
+ if (this.disconnecting) {
707
+ if (callback && callback !== this.noop) {
708
+ callback(new Error('client disconnecting'));
709
+ }
710
+ else {
711
+ this.emit('error', new Error('client disconnecting'));
712
+ }
713
+ }
714
+ return this.disconnecting;
715
+ }
716
+ _reconnect() {
717
+ this.log('_reconnect: emitting reconnect to client');
718
+ this.emit('reconnect');
719
+ if (this.connected) {
720
+ this.end(() => {
721
+ this.connect();
722
+ });
723
+ this.log('client already connected. disconnecting first.');
724
+ }
725
+ else {
726
+ this.log('_reconnect: calling connect');
727
+ this.connect();
728
+ }
729
+ }
730
+ _setupReconnect() {
731
+ if (!this.disconnecting &&
732
+ !this.reconnectTimer &&
733
+ this.options.reconnectPeriod > 0) {
734
+ if (!this.reconnecting) {
735
+ this.log('_setupReconnect :: emit `offline` state');
736
+ this.emit('offline');
737
+ this.log('_setupReconnect :: set `reconnecting` to `true`');
738
+ this.reconnecting = true;
739
+ }
740
+ this.log('_setupReconnect :: setting reconnectTimer for %d ms', this.options.reconnectPeriod);
741
+ this.reconnectTimer = setInterval(() => {
742
+ this.log('reconnectTimer :: reconnect triggered!');
743
+ this._reconnect();
744
+ }, this.options.reconnectPeriod);
745
+ }
746
+ else {
747
+ this.log('_setupReconnect :: doing nothing...');
748
+ }
749
+ }
750
+ _clearReconnect() {
751
+ this.log('_clearReconnect : clearing reconnect timer');
752
+ if (this.reconnectTimer) {
753
+ clearInterval(this.reconnectTimer);
754
+ this.reconnectTimer = null;
755
+ }
756
+ }
757
+ _cleanUp(forced, done, opts = {}) {
758
+ if (done) {
759
+ this.log('_cleanUp :: done callback provided for on stream close');
760
+ this.stream.on('close', done);
761
+ }
762
+ this.log('_cleanUp :: forced? %s', forced);
763
+ if (forced) {
764
+ if (this.options.reconnectPeriod === 0 && this.options.clean) {
765
+ this._flush();
766
+ }
767
+ this.log('_cleanUp :: (%s) :: destroying stream', this.options.clientId);
768
+ this.stream.destroy();
769
+ }
770
+ else {
771
+ const packet = Object.assign({ cmd: 'disconnect' }, opts);
772
+ this.log('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId);
773
+ this._sendPacket(packet, () => {
774
+ this.log('_cleanUp :: (%s) :: destroying stream', this.options.clientId);
775
+ setImmediate(() => {
776
+ this.stream.end(() => {
777
+ this.log('_cleanUp :: (%s) :: stream destroyed', this.options.clientId);
778
+ });
779
+ });
780
+ });
781
+ }
782
+ if (!this.disconnecting) {
783
+ this.log('_cleanUp :: client not disconnecting. Clearing and resetting reconnect.');
784
+ this._clearReconnect();
785
+ this._setupReconnect();
786
+ }
787
+ if (this.pingTimer !== null) {
788
+ this.log('_cleanUp :: clearing pingTimer');
789
+ this.pingTimer.clear();
790
+ this.pingTimer = null;
791
+ }
792
+ if (done && !this.connected) {
793
+ this.log('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId);
794
+ this.stream.removeListener('close', done);
795
+ done();
796
+ }
797
+ }
798
+ _storeAndSend(packet, cb, cbStorePut) {
799
+ this.log('storeAndSend :: store packet with cmd %s to outgoingStore', packet.cmd);
800
+ let storePacket = packet;
801
+ let err;
802
+ if (storePacket.cmd === 'publish') {
803
+ storePacket = (0, default_1.default)(packet);
804
+ err = this._removeTopicAliasAndRecoverTopicName(storePacket);
805
+ if (err) {
806
+ return cb && cb(err);
807
+ }
808
+ }
809
+ this.outgoingStore.put(storePacket, (err2) => {
810
+ if (err2) {
811
+ return cb && cb(err2);
812
+ }
813
+ cbStorePut();
814
+ this._writePacket(packet, cb);
815
+ });
816
+ }
817
+ _applyTopicAlias(packet) {
818
+ if (this.options.protocolVersion === 5) {
819
+ if (packet.cmd === 'publish') {
820
+ let alias;
821
+ if (packet.properties) {
822
+ alias = packet.properties.topicAlias;
823
+ }
824
+ const topic = packet.topic.toString();
825
+ if (this.topicAliasSend) {
826
+ if (alias) {
827
+ if (topic.length !== 0) {
828
+ this.log('applyTopicAlias :: register topic: %s - alias: %d', topic, alias);
829
+ if (!this.topicAliasSend.put(topic, alias)) {
830
+ this.log('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias);
831
+ return new Error('Sending Topic Alias out of range');
832
+ }
833
+ }
834
+ }
835
+ else if (topic.length !== 0) {
836
+ if (this.options.autoAssignTopicAlias) {
837
+ alias = this.topicAliasSend.getAliasByTopic(topic);
838
+ if (alias) {
839
+ packet.topic = '';
840
+ packet.properties = Object.assign(Object.assign({}, packet.properties), { topicAlias: alias });
841
+ this.log('applyTopicAlias :: auto assign(use) topic: %s - alias: %d', topic, alias);
842
+ }
843
+ else {
844
+ alias = this.topicAliasSend.getLruAlias();
845
+ this.topicAliasSend.put(topic, alias);
846
+ packet.properties = Object.assign(Object.assign({}, packet.properties), { topicAlias: alias });
847
+ this.log('applyTopicAlias :: auto assign topic: %s - alias: %d', topic, alias);
848
+ }
849
+ }
850
+ else if (this.options.autoUseTopicAlias) {
851
+ alias = this.topicAliasSend.getAliasByTopic(topic);
852
+ if (alias) {
853
+ packet.topic = '';
854
+ packet.properties = Object.assign(Object.assign({}, packet.properties), { topicAlias: alias });
855
+ this.log('applyTopicAlias :: auto use topic: %s - alias: %d', topic, alias);
856
+ }
857
+ }
858
+ }
859
+ }
860
+ else if (alias) {
861
+ this.log('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias);
862
+ return new Error('Sending Topic Alias out of range');
863
+ }
864
+ }
865
+ }
866
+ }
867
+ _noop(err) {
868
+ this.log('noop ::', err);
869
+ }
870
+ _writePacket(packet, cb) {
871
+ this.log('_writePacket :: packet: %O', packet);
872
+ this.log('_writePacket :: emitting `packetsend`');
873
+ this.emit('packetsend', packet);
874
+ this._shiftPingInterval();
875
+ this.log('_writePacket :: writing to stream');
876
+ const result = mqtt_packet_1.default.writeToStream(packet, this.stream, this.options);
877
+ this.log('_writePacket :: writeToStream result %s', result);
878
+ if (!result && cb && cb !== this.noop) {
879
+ this.log('_writePacket :: handle events on `drain` once through callback.');
880
+ this.stream.once('drain', cb);
881
+ }
882
+ else if (cb) {
883
+ this.log('_writePacket :: invoking cb');
884
+ cb();
885
+ }
886
+ }
887
+ _sendPacket(packet, cb, cbStorePut, noStore) {
888
+ this.log('_sendPacket :: (%s) :: start', this.options.clientId);
889
+ cbStorePut = cbStorePut || this.noop;
890
+ cb = cb || this.noop;
891
+ const err = this._applyTopicAlias(packet);
892
+ if (err) {
893
+ cb(err);
894
+ return;
895
+ }
896
+ if (!this.connected) {
897
+ if (packet.cmd === 'auth') {
898
+ this._writePacket(packet, cb);
899
+ return;
900
+ }
901
+ this.log('_sendPacket :: client not connected. Storing packet offline.');
902
+ this._storePacket(packet, cb, cbStorePut);
903
+ return;
904
+ }
905
+ if (noStore) {
906
+ this._writePacket(packet, cb);
907
+ return;
908
+ }
909
+ switch (packet.cmd) {
910
+ case 'publish':
911
+ break;
912
+ case 'pubrel':
913
+ this._storeAndSend(packet, cb, cbStorePut);
914
+ return;
915
+ default:
916
+ this._writePacket(packet, cb);
917
+ return;
918
+ }
919
+ switch (packet.qos) {
920
+ case 2:
921
+ case 1:
922
+ this._storeAndSend(packet, cb, cbStorePut);
923
+ break;
924
+ case 0:
925
+ default:
926
+ this._writePacket(packet, cb);
927
+ break;
928
+ }
929
+ this.log('_sendPacket :: (%s) :: end', this.options.clientId);
930
+ }
931
+ _storePacket(packet, cb, cbStorePut) {
932
+ this.log('_storePacket :: packet: %o', packet);
933
+ this.log('_storePacket :: cb? %s', !!cb);
934
+ cbStorePut = cbStorePut || this.noop;
935
+ let storePacket = packet;
936
+ if (storePacket.cmd === 'publish') {
937
+ storePacket = (0, default_1.default)(packet);
938
+ const err = this._removeTopicAliasAndRecoverTopicName(storePacket);
939
+ if (err) {
940
+ return cb && cb(err);
941
+ }
942
+ }
943
+ const qos = storePacket.qos || 0;
944
+ if ((qos === 0 && this.queueQoSZero) || storePacket.cmd !== 'publish') {
945
+ this.queue.push({ packet: storePacket, cb });
946
+ }
947
+ else if (qos > 0) {
948
+ cb = this.outgoing[storePacket.messageId]
949
+ ? this.outgoing[storePacket.messageId].cb
950
+ : null;
951
+ this.outgoingStore.put(storePacket, (err) => {
952
+ if (err) {
953
+ return cb && cb(err);
954
+ }
955
+ cbStorePut();
956
+ });
957
+ }
958
+ else if (cb) {
959
+ cb(new Error('No connection to broker'));
960
+ }
961
+ }
962
+ _setupPingTimer() {
963
+ this.log('_setupPingTimer :: keepalive %d (seconds)', this.options.keepalive);
964
+ if (!this.pingTimer && this.options.keepalive) {
965
+ this.pingResp = true;
966
+ this.pingTimer = (0, reinterval_1.default)(() => {
967
+ this._checkPing();
968
+ }, this.options.keepalive * 1000);
969
+ }
970
+ }
971
+ _shiftPingInterval() {
972
+ if (this.pingTimer &&
973
+ this.options.keepalive &&
974
+ this.options.reschedulePings) {
975
+ this.pingTimer.reschedule(this.options.keepalive * 1000);
976
+ }
977
+ }
978
+ _checkPing() {
979
+ this.log('_checkPing :: checking ping...');
980
+ if (this.pingResp) {
981
+ this.log('_checkPing :: ping response received. Clearing flag and sending `pingreq`');
982
+ this.pingResp = false;
983
+ this._sendPacket({ cmd: 'pingreq' });
984
+ }
985
+ else {
986
+ this.log('_checkPing :: calling _cleanUp with force true');
987
+ this._cleanUp(true);
988
+ }
989
+ }
990
+ _resubscribe() {
991
+ this.log('_resubscribe');
992
+ const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics);
993
+ if (!this._firstConnection &&
994
+ (this.options.clean ||
995
+ (this.options.protocolVersion === 5 &&
996
+ !this.connackPacket.sessionPresent)) &&
997
+ _resubscribeTopicsKeys.length > 0) {
998
+ if (this.options.resubscribe) {
999
+ if (this.options.protocolVersion === 5) {
1000
+ this.log('_resubscribe: protocolVersion 5');
1001
+ for (let topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {
1002
+ const resubscribeTopic = {};
1003
+ resubscribeTopic[_resubscribeTopicsKeys[topicI]] =
1004
+ this._resubscribeTopics[_resubscribeTopicsKeys[topicI]];
1005
+ resubscribeTopic.resubscribe = true;
1006
+ this.subscribe(resubscribeTopic, {
1007
+ properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]]
1008
+ .properties,
1009
+ });
1010
+ }
1011
+ }
1012
+ else {
1013
+ this._resubscribeTopics.resubscribe = true;
1014
+ this.subscribe(this._resubscribeTopics);
1015
+ }
1016
+ }
1017
+ else {
1018
+ this._resubscribeTopics = {};
1019
+ }
1020
+ }
1021
+ this._firstConnection = false;
1022
+ }
1023
+ _onConnect(packet) {
1024
+ if (this.disconnected) {
1025
+ this.emit('connect', packet);
1026
+ return;
1027
+ }
1028
+ this.connackPacket = packet;
1029
+ this.messageIdProvider.clear();
1030
+ this._setupPingTimer();
1031
+ this.connected = true;
1032
+ const startStreamProcess = () => {
1033
+ let outStore = this.outgoingStore.createStream();
1034
+ const remove = () => {
1035
+ outStore.destroy();
1036
+ outStore = null;
1037
+ this._flushStoreProcessingQueue();
1038
+ clearStoreProcessing();
1039
+ };
1040
+ const clearStoreProcessing = () => {
1041
+ this._storeProcessing = false;
1042
+ this._packetIdsDuringStoreProcessing = {};
1043
+ };
1044
+ this.once('close', remove);
1045
+ outStore.on('error', (err) => {
1046
+ clearStoreProcessing();
1047
+ this._flushStoreProcessingQueue();
1048
+ this.removeListener('close', remove);
1049
+ this.emit('error', err);
1050
+ });
1051
+ const storeDeliver = () => {
1052
+ if (!outStore) {
1053
+ return;
1054
+ }
1055
+ const packet2 = outStore.read(1);
1056
+ let cb;
1057
+ if (!packet2) {
1058
+ outStore.once('readable', storeDeliver);
1059
+ return;
1060
+ }
1061
+ this._storeProcessing = true;
1062
+ if (this._packetIdsDuringStoreProcessing[packet2.messageId]) {
1063
+ storeDeliver();
1064
+ return;
1065
+ }
1066
+ if (!this.disconnecting && !this.reconnectTimer) {
1067
+ cb = this.outgoing[packet2.messageId]
1068
+ ? this.outgoing[packet2.messageId].cb
1069
+ : null;
1070
+ this.outgoing[packet2.messageId] = {
1071
+ volatile: false,
1072
+ cb(err, status) {
1073
+ if (cb) {
1074
+ cb(err, status);
1075
+ }
1076
+ storeDeliver();
1077
+ },
1078
+ };
1079
+ this._packetIdsDuringStoreProcessing[packet2.messageId] =
1080
+ true;
1081
+ if (this.messageIdProvider.register(packet2.messageId)) {
1082
+ this._sendPacket(packet2, undefined, undefined, true);
1083
+ }
1084
+ else {
1085
+ this.log('messageId: %d has already used.', packet2.messageId);
1086
+ }
1087
+ }
1088
+ else if (outStore.destroy) {
1089
+ outStore.destroy();
1090
+ }
1091
+ };
1092
+ outStore.on('end', () => {
1093
+ let allProcessed = true;
1094
+ for (const id in this._packetIdsDuringStoreProcessing) {
1095
+ if (!this._packetIdsDuringStoreProcessing[id]) {
1096
+ allProcessed = false;
1097
+ break;
1098
+ }
1099
+ }
1100
+ if (allProcessed) {
1101
+ clearStoreProcessing();
1102
+ this.removeListener('close', remove);
1103
+ this._invokeAllStoreProcessingQueue();
1104
+ this.emit('connect', packet);
1105
+ }
1106
+ else {
1107
+ startStreamProcess();
1108
+ }
1109
+ });
1110
+ storeDeliver();
1111
+ };
1112
+ startStreamProcess();
1113
+ }
1114
+ _invokeStoreProcessingQueue() {
1115
+ if (!this._storeProcessing && this._storeProcessingQueue.length > 0) {
1116
+ const f = this._storeProcessingQueue[0];
1117
+ if (f && f.invoke()) {
1118
+ this._storeProcessingQueue.shift();
1119
+ return true;
1120
+ }
1121
+ }
1122
+ return false;
1123
+ }
1124
+ _invokeAllStoreProcessingQueue() {
1125
+ while (this._invokeStoreProcessingQueue()) {
1126
+ }
1127
+ }
1128
+ _flushStoreProcessingQueue() {
1129
+ for (const f of this._storeProcessingQueue) {
1130
+ if (f.cbStorePut)
1131
+ f.cbStorePut(new Error('Connection closed'));
1132
+ if (f.callback)
1133
+ f.callback(new Error('Connection closed'));
1134
+ }
1135
+ this._storeProcessingQueue.splice(0);
1136
+ }
1137
+ _removeOutgoingAndStoreMessage(messageId, cb) {
1138
+ delete this.outgoing[messageId];
1139
+ this.outgoingStore.del({ messageId }, (err, packet) => {
1140
+ cb(err, packet);
1141
+ this.messageIdProvider.deallocate(messageId);
1142
+ this._invokeStoreProcessingQueue();
1143
+ });
1144
+ }
1145
+ }
1146
+ exports.default = MqttClient;
1147
+ //# sourceMappingURL=client.js.map