u8-mqtt 0.5.2 → 0.5.3

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 (111) hide show
  1. package/README.md +23 -6
  2. package/cjs/basic-v4.cjs +11 -8
  3. package/cjs/basic-v4.cjs.map +1 -1
  4. package/cjs/basic-v5.cjs +11 -8
  5. package/cjs/basic-v5.cjs.map +1 -1
  6. package/cjs/full-v4.cjs +1532 -0
  7. package/cjs/full-v4.cjs.map +1 -0
  8. package/cjs/full-v5.cjs +1796 -0
  9. package/cjs/full-v5.cjs.map +1 -0
  10. package/cjs/index.cjs +11 -8
  11. package/cjs/index.cjs.map +1 -1
  12. package/cjs/v4.cjs +11 -8
  13. package/cjs/v4.cjs.map +1 -1
  14. package/cjs/v5.cjs +11 -8
  15. package/cjs/v5.cjs.map +1 -1
  16. package/code/base.jsy +2 -2
  17. package/code/core.jsy +5 -5
  18. package/code/full-v4.js +20 -0
  19. package/code/full-v5.js +29 -0
  20. package/esm/basic-v4.js +11 -8
  21. package/esm/basic-v4.js.map +1 -1
  22. package/esm/basic-v5.js +11 -8
  23. package/esm/basic-v5.js.map +1 -1
  24. package/esm/deno/basic-v4.js +11 -8
  25. package/esm/deno/basic-v4.js.map +1 -1
  26. package/esm/deno/basic-v5.js +11 -8
  27. package/esm/deno/basic-v5.js.map +1 -1
  28. package/esm/deno/full-v4.js +1520 -0
  29. package/esm/deno/full-v4.js.map +1 -0
  30. package/esm/deno/full-v5.js +1782 -0
  31. package/esm/deno/full-v5.js.map +1 -0
  32. package/esm/deno/index.js +11 -8
  33. package/esm/deno/index.js.map +1 -1
  34. package/esm/deno/v4.js +11 -8
  35. package/esm/deno/v4.js.map +1 -1
  36. package/esm/deno/v5.js +11 -8
  37. package/esm/deno/v5.js.map +1 -1
  38. package/esm/full-v4.js +1520 -0
  39. package/esm/full-v4.js.map +1 -0
  40. package/esm/full-v5.js +1782 -0
  41. package/esm/full-v5.js.map +1 -0
  42. package/esm/index.js +11 -8
  43. package/esm/index.js.map +1 -1
  44. package/esm/node/basic-v4.js +11 -8
  45. package/esm/node/basic-v4.js.map +1 -1
  46. package/esm/node/basic-v4.mjs +11 -8
  47. package/esm/node/basic-v4.mjs.map +1 -1
  48. package/esm/node/basic-v5.js +11 -8
  49. package/esm/node/basic-v5.js.map +1 -1
  50. package/esm/node/basic-v5.mjs +11 -8
  51. package/esm/node/basic-v5.mjs.map +1 -1
  52. package/esm/node/full-v4.js +1523 -0
  53. package/esm/node/full-v4.js.map +1 -0
  54. package/esm/node/full-v4.mjs +1523 -0
  55. package/esm/node/full-v4.mjs.map +1 -0
  56. package/esm/node/full-v5.js +1785 -0
  57. package/esm/node/full-v5.js.map +1 -0
  58. package/esm/node/full-v5.mjs +1785 -0
  59. package/esm/node/full-v5.mjs.map +1 -0
  60. package/esm/node/index.js +11 -8
  61. package/esm/node/index.js.map +1 -1
  62. package/esm/node/index.mjs +11 -8
  63. package/esm/node/index.mjs.map +1 -1
  64. package/esm/node/v4.js +11 -8
  65. package/esm/node/v4.js.map +1 -1
  66. package/esm/node/v4.mjs +11 -8
  67. package/esm/node/v4.mjs.map +1 -1
  68. package/esm/node/v5.js +11 -8
  69. package/esm/node/v5.js.map +1 -1
  70. package/esm/node/v5.mjs +11 -8
  71. package/esm/node/v5.mjs.map +1 -1
  72. package/esm/v4.js +11 -8
  73. package/esm/v4.js.map +1 -1
  74. package/esm/v5.js +11 -8
  75. package/esm/v5.js.map +1 -1
  76. package/esm/web/basic-v4.js +11 -8
  77. package/esm/web/basic-v4.js.map +1 -1
  78. package/esm/web/basic-v4.min.js +1 -1
  79. package/esm/web/basic-v4.min.js.br +0 -0
  80. package/esm/web/basic-v4.min.js.gz +0 -0
  81. package/esm/web/basic-v5.js +11 -8
  82. package/esm/web/basic-v5.js.map +1 -1
  83. package/esm/web/basic-v5.min.js +1 -1
  84. package/esm/web/basic-v5.min.js.br +0 -0
  85. package/esm/web/basic-v5.min.js.gz +0 -0
  86. package/esm/web/full-v4.js +1520 -0
  87. package/esm/web/full-v4.js.map +1 -0
  88. package/esm/web/full-v4.min.js +1 -0
  89. package/esm/web/full-v4.min.js.br +0 -0
  90. package/esm/web/full-v4.min.js.gz +0 -0
  91. package/esm/web/full-v5.js +1782 -0
  92. package/esm/web/full-v5.js.map +1 -0
  93. package/esm/web/full-v5.min.js +1 -0
  94. package/esm/web/full-v5.min.js.br +0 -0
  95. package/esm/web/full-v5.min.js.gz +0 -0
  96. package/esm/web/index.js +11 -8
  97. package/esm/web/index.js.map +1 -1
  98. package/esm/web/index.min.js +1 -1
  99. package/esm/web/index.min.js.br +0 -0
  100. package/esm/web/index.min.js.gz +0 -0
  101. package/esm/web/v4.js +11 -8
  102. package/esm/web/v4.js.map +1 -1
  103. package/esm/web/v4.min.js +1 -1
  104. package/esm/web/v4.min.js.br +0 -0
  105. package/esm/web/v4.min.js.gz +0 -0
  106. package/esm/web/v5.js +11 -8
  107. package/esm/web/v5.js.map +1 -1
  108. package/esm/web/v5.min.js +1 -1
  109. package/esm/web/v5.min.js.br +0 -0
  110. package/esm/web/v5.min.js.gz +0 -0
  111. package/package.json +3 -3
@@ -0,0 +1,1523 @@
1
+ import { connect } from 'node:net';
2
+ import { connect as connect$1 } from 'node:tls';
3
+
4
+ function encode_varint(n, a=[]) {
5
+ do {
6
+ const ni = n & 0x7f;
7
+ n >>>= 7;
8
+ a.push( ni | (0===n ? 0 : 0x80) );
9
+ } while (n > 0)
10
+ return a
11
+ }
12
+
13
+
14
+ /*
15
+ export function decode_varint_loop(u8, i=0) {
16
+ let i0 = i
17
+ let shift = 0, n = (u8[i] & 0x7f)
18
+ while ( 0x80 & u8[i++] )
19
+ n |= (u8[i] & 0x7f) << (shift += 7)
20
+
21
+ return [n, i, i0]
22
+ }
23
+ */
24
+
25
+
26
+ function decode_varint$1(u8, i=0) {
27
+ let i0 = i;
28
+ // unrolled for a max of 4 chains
29
+ let n = (u8[i] & 0x7f) << 0;
30
+ if ( 0x80 & u8[i++] ) {
31
+ n |= (u8[i] & 0x7f) << 7;
32
+ if ( 0x80 & u8[i++] ) {
33
+ n |= (u8[i] & 0x7f) << 14;
34
+ if ( 0x80 & u8[i++] ) {
35
+ n |= (u8[i] & 0x7f) << 21;
36
+ }
37
+ }
38
+ }
39
+ return [n, i, i0]
40
+ }
41
+
42
+ class U8_Reason extends Number {
43
+ static of(v, pkt_kind, by_kind) {
44
+ let self = new this(v);
45
+ self.reason = by_kind?.[pkt_kind]?.get(v) || pkt_kind;
46
+ return self
47
+ }
48
+ }
49
+
50
+ let mqtt_reader_v4$1 = class mqtt_reader_v4 {
51
+ static of(buf) { return this.prototype.of(buf) }
52
+ of(buf) {
53
+ let step = (width, k) => (k=0|step.k, step.k=k+width, k);
54
+ return {__proto__: this, buf, step}
55
+ }
56
+
57
+ has_more() {
58
+ return this.buf.byteLength > (this.step.k|0)
59
+ }
60
+
61
+ u8() {
62
+ return this.buf[this.step(1)]
63
+ }
64
+
65
+ u16() {
66
+ let {buf, step} = this, i = step(2);
67
+ return (buf[i]<<8) | buf[i+1]
68
+ }
69
+
70
+ u32() {
71
+ let {buf, step} = this, i = step(4);
72
+ return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3]
73
+ }
74
+
75
+ vint() {
76
+ let {buf, step} = this;
77
+ let [n, vi, vi0] = decode_varint$1(buf, step.k|0);
78
+ step(vi - vi0);
79
+ return n
80
+ }
81
+
82
+ bin() {
83
+ let {buf, step} = this, i = step(2);
84
+ let len = (buf[i]<<8) | buf[i+1];
85
+ i = step(len);
86
+ return buf.subarray(i, i+len)
87
+ }
88
+
89
+ utf8() { return new TextDecoder('utf-8').decode(this.bin()) }
90
+ pair() { return [ this.utf8(), this.utf8() ] }
91
+
92
+ flags(FlagsType) { return new FlagsType(this.buf[this.step(1)]) }
93
+
94
+ reason(pkt_kind) {
95
+ let v = this.buf[this.step(1)];
96
+ if (null != v)
97
+ return U8_Reason.of(v, pkt_kind, this._reasons_by)
98
+ }
99
+
100
+ flush() {
101
+ let {buf, step} = this;
102
+ this.step = this.buf = null;
103
+ return buf.subarray(step.k|0)
104
+ }
105
+
106
+ };
107
+
108
+ function mqtt_reader_info(mqtt_reader, ... info_fn_list) {
109
+ mqtt_reader = class extends mqtt_reader {
110
+ static reasons(pkt_type, ...reason_entries) {
111
+ let proto = this.prototype;
112
+ proto._reasons_by = {... proto._reasons_by};
113
+
114
+ let lut = (proto._reasons_by[pkt_type] ||= new Map());
115
+ for (let [u8, reason] of reason_entries)
116
+ lut.set( u8, reason );
117
+
118
+ return this
119
+ }
120
+ };
121
+
122
+ for (let fn_info of info_fn_list)
123
+ fn_info(mqtt_reader);
124
+
125
+ return mqtt_reader
126
+ }
127
+
128
+ class mqtt_writer_v4 {
129
+ static of() { return this.prototype.of() }
130
+ of() { return {__proto__: this, $:[]} }
131
+
132
+ static init() { return this }
133
+
134
+ as_pkt(pkt_id) { return this.pack([pkt_id]) }
135
+
136
+ push(...z) { this.$.push(...z); }
137
+ pack(hdr) {
138
+ let z, i, n=0, parts = this.$;
139
+ this.$ = false;
140
+ for (z of parts) n += z.length;
141
+
142
+ hdr = encode_varint(n, hdr);
143
+ i = hdr.length;
144
+
145
+ let pkt = new Uint8Array(i + n);
146
+ pkt.set(hdr, 0);
147
+ for (z of parts) {
148
+ pkt.set(z, i);
149
+ i += z.length;
150
+ }
151
+ return pkt
152
+ }
153
+
154
+ u8(v) { this.push([ v & 0xff ]); }
155
+ u16(v) { this.push([ (v>>>8) & 0xff, v & 0xff ]); }
156
+ u32(v) { this.push([ (v>>>24) & 0xff, (v>>>16) & 0xff, (v>>>8) & 0xff, v & 0xff ]); }
157
+ vint(v) { this.push( encode_varint(v) );}
158
+
159
+ bin(u8_buf) {
160
+ if (! u8_buf) return this.u16(0)
161
+ if ('string' === typeof u8_buf)
162
+ return this.utf8(u8_buf)
163
+
164
+ if (u8_buf.length !== u8_buf.byteLength)
165
+ u8_buf = new Uint8Array(u8_buf);
166
+
167
+ this.u16(u8_buf.byteLength);
168
+ this.push(u8_buf);
169
+ }
170
+
171
+ utf8(v) {
172
+ let u8_buf = new TextEncoder('utf-8').encode(v);
173
+ this.u16(u8_buf.byteLength);
174
+ this.push(u8_buf);
175
+ }
176
+ pair(k,v) { this.utf8(k); this.utf8(v); }
177
+
178
+ flags(v, enc_flags, b0=0) {
179
+ if (undefined !== v && isNaN(+v))
180
+ v = enc_flags(v, 0);
181
+
182
+ v |= b0;
183
+ this.push([v]);
184
+ return v
185
+ }
186
+
187
+ reason(v) { this.push([v | 0]); }
188
+
189
+ flush(buf) {
190
+ if (null != buf)
191
+ this.push(
192
+ 'string' === typeof buf
193
+ ? new TextEncoder('utf-8').encode(buf)
194
+ : buf );
195
+
196
+ this.push = false;
197
+ }
198
+ }
199
+
200
+ function mqtt_decode_connect(ns, mqtt_reader) {
201
+ class _connect_flags_ extends Number {
202
+ get reserved() { return this & 0x01 !== 0 }
203
+ get clean_start() { return this & 0x02 !== 0 }
204
+ get will_flag() { return this & 0x04 !== 0 }
205
+ get will_qos() { return (this >>> 3) & 0x3 }
206
+ get will_retain() { return this & 0x20 !== 0 }
207
+ get password() { return this & 0x40 !== 0 }
208
+ get username() { return this & 0x80 !== 0 }
209
+ }
210
+
211
+ return ns[0x1] = (pkt, u8_body) => {
212
+ let rdr = mqtt_reader.of(u8_body);
213
+ if ('MQTT' !== rdr.utf8())
214
+ throw new Error('Invalid mqtt_connect packet')
215
+
216
+ pkt._base_.mqtt_level = pkt.mqtt_level = rdr.u8();
217
+
218
+ let flags = pkt.flags =
219
+ rdr.flags(_connect_flags_);
220
+
221
+ pkt.keep_alive = rdr.u16();
222
+
223
+ if (5 <= pkt.mqtt_level)
224
+ pkt.props = rdr.props();
225
+
226
+
227
+
228
+ pkt.client_id = rdr.utf8();
229
+ if (flags.will_flag) {
230
+ let will = pkt.will = {};
231
+ if (5 <= pkt.mqtt_level)
232
+ will.props = rdr.props();
233
+
234
+ will.topic = rdr.utf8();
235
+ will.payload = rdr.bin();
236
+ will.qos = flags.will_qos;
237
+ will.retain = flags.will_retain;
238
+ }
239
+
240
+ if (flags.username)
241
+ pkt.username = rdr.utf8();
242
+
243
+ if (flags.password)
244
+ pkt.password = rdr.bin();
245
+ return pkt }
246
+ }
247
+
248
+ function mqtt_decode_connack(ns, mqtt_reader) {
249
+ class _connack_flags_ extends Number {
250
+ get session_present() { return this & 0x01 !== 0 }
251
+ }
252
+
253
+ return ns[0x2] = (pkt, u8_body) => {
254
+ let rdr = mqtt_reader.of(u8_body);
255
+
256
+ pkt.flags =
257
+ rdr.flags(_connack_flags_);
258
+
259
+ pkt.reason = rdr.reason(pkt.type);
260
+ if (5 <= pkt.mqtt_level)
261
+ pkt.props = rdr.props();
262
+ return pkt }
263
+ }
264
+
265
+
266
+ function _connack_v4(mqtt_reader) {
267
+ mqtt_reader.reasons('connack',
268
+ // MQTT 3.1.1
269
+ [ 0x00, 'Success'],
270
+ [ 0x01, 'Connection refused, unacceptable protocol version'],
271
+ [ 0x02, 'Connection refused, identifier rejected'],
272
+ [ 0x03, 'Connection refused, server unavailable'],
273
+ [ 0x04, 'Connection refused, bad user name or password'],
274
+ [ 0x05, 'Connection refused, not authorized'],
275
+ );
276
+ }
277
+
278
+ function mqtt_decode_publish(ns, mqtt_reader) {
279
+ return ns[0x3] = (pkt, u8_body) => {
280
+ let {hdr} = pkt;
281
+ pkt.dup = Boolean(hdr & 0x8);
282
+ pkt.retain = Boolean(hdr & 0x1);
283
+ let qos = pkt.qos = (hdr>>1) & 0x3;
284
+
285
+ let rdr = mqtt_reader.of(u8_body);
286
+ pkt.topic = rdr.utf8();
287
+ if (0 !== qos)
288
+ pkt.pkt_id = rdr.u16();
289
+
290
+ if (5 <= pkt.mqtt_level)
291
+ pkt.props = rdr.props();
292
+
293
+ pkt.payload = rdr.flush();
294
+ return pkt }
295
+ }
296
+
297
+ function mqtt_decode_puback(ns, mqtt_reader) {
298
+ return ns[0x4] = (pkt, u8_body) => {
299
+ let rdr = mqtt_reader.of(u8_body);
300
+
301
+ pkt.pkt_id = rdr.u16();
302
+ if (5 <= pkt.mqtt_level) {
303
+ pkt.reason = rdr.reason(pkt.type);
304
+ pkt.props = rdr.props();
305
+ }
306
+
307
+ return pkt }
308
+ }
309
+
310
+ function mqtt_decode_pubxxx(ns, mqtt_reader) {
311
+ return ns[0x5] = ns[0x6] = ns[0x7] = (pkt, u8_body) => {
312
+ let rdr = mqtt_reader.of(u8_body);
313
+
314
+ pkt.pkt_id = rdr.u16();
315
+ pkt.reason = rdr.reason('pubxxx', mqtt_reader);
316
+ if (5 <= pkt.mqtt_level)
317
+ pkt.props = rdr.props();
318
+ return pkt }
319
+ }
320
+
321
+ function _pubxxx_v4(mqtt_reader) {
322
+ mqtt_reader.reasons('pubxxx',
323
+ // MQTT 3.1.1
324
+ [ 0x00, 'Success' ],
325
+ [ 0x92, 'Packet Identifier not found' ],
326
+ );
327
+ }
328
+
329
+ function mqtt_decode_subscribe(ns, mqtt_reader) {
330
+ class _subscription_options_ extends Number {
331
+ get qos() { return this & 0x3 }
332
+ get retain() { return this & 0x4 !== 0 }
333
+ get retain_handling() { return (this >> 2) & 0x3 }
334
+ }
335
+
336
+ return ns[0x8] = (pkt, u8_body) => {
337
+ let rdr = mqtt_reader.of(u8_body);
338
+
339
+ pkt.pkt_id = rdr.u16();
340
+ if (5 <= pkt.mqtt_level)
341
+ pkt.props = rdr.props();
342
+
343
+ let topic, opts, topic_list = pkt.topics = [];
344
+ while (rdr.has_more()) {
345
+ topic = rdr.utf8();
346
+ opts = rdr.flags(_subscription_options_);
347
+ topic_list.push({topic, opts});
348
+ }
349
+
350
+ return pkt }
351
+ }
352
+
353
+ function _mqtt_decode_suback(mqtt_reader) {
354
+ return (pkt, u8_body) => {
355
+ let rdr = mqtt_reader.of(u8_body);
356
+
357
+ pkt.pkt_id = rdr.u16();
358
+ if (5 <= pkt.mqtt_level)
359
+ pkt.props = rdr.props();
360
+
361
+ let answers = pkt.answers = [];
362
+ while (rdr.has_more())
363
+ answers.push(
364
+ rdr.reason(pkt.type) );
365
+
366
+ return pkt }
367
+ }
368
+
369
+ function mqtt_decode_suback(ns, mqtt_reader) {
370
+ return ns[0x9] = _mqtt_decode_suback(mqtt_reader)
371
+ }
372
+
373
+ function _suback_v4(mqtt_reader) {
374
+ mqtt_reader.reasons('suback',
375
+ // MQTT 3.1.1
376
+ [ 0x00, 'Granted QoS 0'],
377
+ [ 0x01, 'Granted QoS 1'],
378
+ [ 0x02, 'Granted QoS 2'],
379
+ );
380
+ }
381
+
382
+ function mqtt_decode_unsubscribe(ns, mqtt_reader) {
383
+ return ns[0xa] = (pkt, u8_body) => {
384
+ let rdr = mqtt_reader.of(u8_body);
385
+
386
+ pkt.pkt_id = rdr.u16();
387
+ if (5 <= pkt.mqtt_level)
388
+ pkt.props = rdr.props();
389
+
390
+ let topic_list = pkt.topics = [];
391
+ while (rdr.has_more())
392
+ topic_list.push(rdr.utf8());
393
+
394
+ return pkt }
395
+ }
396
+
397
+ function mqtt_decode_unsuback(ns, mqtt_reader) {
398
+ return ns[0xb] = _mqtt_decode_suback(mqtt_reader)
399
+ }
400
+
401
+ function _unsuback_v4(mqtt_reader) {
402
+ mqtt_reader.reasons('unsuback',
403
+ // MQTT 3.1.1
404
+ [ 0x00, 'Success'],
405
+ [ 0x11, 'No subscription existed'],
406
+ [ 0x80, 'Unspecified error'],
407
+ [ 0x83, 'Implementation specific error'],
408
+ [ 0x87, 'Not authorized'],
409
+ [ 0x8F, 'Topic Filter invalid'],
410
+ [ 0x91, 'Packet Identifier in use'],
411
+ );
412
+ }
413
+
414
+ function mqtt_decode_pingxxx(ns) {
415
+ return ns[0xc] = ns[0xd] = pkt => pkt
416
+ }
417
+
418
+ function mqtt_decode_disconnect(ns, mqtt_reader) {
419
+ return ns[0xe] = (pkt, u8_body) => {
420
+ if (u8_body && 5 <= pkt.mqtt_level) {
421
+ let rdr = mqtt_reader.of(u8_body);
422
+ pkt.reason = rdr.reason(pkt.type);
423
+ pkt.props = rdr.props();
424
+ }
425
+ return pkt }
426
+ }
427
+
428
+ function mqtt_encode_connect(ns, mqtt_writer) {
429
+ const _c_mqtt_proto = new Uint8Array([
430
+ 0, 4, 0x4d, 0x51, 0x54, 0x54 ]);
431
+
432
+ const _enc_flags_connect = flags => 0
433
+ | ( flags.reserved ? 0x01 : 0 )
434
+ | ( (flags.will_qos & 0x3) << 3 )
435
+ | ( flags.clean_start ? 0x02 : 0 )
436
+ | ( flags.will_flag ? 0x04 : 0 )
437
+ | ( flags.will_retain ? 0x20 : 0 )
438
+ | ( flags.password ? 0x40 : 0 )
439
+ | ( flags.username ? 0x80 : 0 );
440
+
441
+ const _enc_flags_will = will => 0x4
442
+ | ( (will.qos & 0x3) << 3 )
443
+ | ( will.retain ? 0x20 : 0 );
444
+
445
+ return ns.connect = ( mqtt_level, pkt ) => {
446
+ let wrt = mqtt_writer.of(pkt);
447
+
448
+ wrt.push(_c_mqtt_proto);
449
+ wrt.u8( mqtt_level );
450
+
451
+ let {will, username, password} = pkt;
452
+ let flags = wrt.flags(
453
+ pkt.flags,
454
+ _enc_flags_connect,
455
+ 0 | (username ? 0x80 : 0)
456
+ | (password ? 0x40 : 0)
457
+ | (will ? _enc_flags_will(will) : 0) );
458
+
459
+ wrt.u16(pkt.keep_alive);
460
+
461
+ if (5 <= mqtt_level)
462
+ wrt.props(pkt.props);
463
+
464
+
465
+ wrt.utf8(pkt.client_id);
466
+ if (flags & 0x04) { // .will_flag
467
+ if (5 <= mqtt_level)
468
+ wrt.props(will.props);
469
+
470
+ wrt.utf8(will.topic);
471
+ wrt.bin(will.payload);
472
+ }
473
+
474
+ if (flags & 0x80) // .username
475
+ wrt.utf8(username);
476
+
477
+ if (flags & 0x40) // .password
478
+ wrt.bin(password);
479
+
480
+ return wrt.as_pkt(0x10)
481
+ }
482
+ }
483
+
484
+ function mqtt_encode_connack(ns, mqtt_writer) {
485
+ const _enc_flags_connack = flags =>
486
+ flags.session_present ? 1 : 0;
487
+
488
+ return ns.connack = (mqtt_level, pkt) => {
489
+ let wrt = mqtt_writer.of(pkt);
490
+
491
+ wrt.flags( pkt.flags, _enc_flags_connack );
492
+
493
+ if (5 <= mqtt_level) {
494
+ wrt.reason( pkt.reason );
495
+ wrt.props( pkt.props );
496
+
497
+ } else {
498
+ wrt.reason( pkt.return_code || pkt.reason );
499
+ }
500
+
501
+ return wrt.as_pkt(0x20)
502
+ }
503
+ }
504
+
505
+ function mqtt_encode_publish(ns, mqtt_writer) {
506
+ return ns.publish = ( mqtt_level, pkt ) => {
507
+ let qos = (pkt.qos & 0x3) << 1;
508
+ let wrt = mqtt_writer.of(pkt);
509
+
510
+ wrt.utf8(pkt.topic);
511
+ if (0 !== qos)
512
+ wrt.u16(pkt.pkt_id);
513
+
514
+ if ( 5 <= mqtt_level) {
515
+ wrt.props(pkt.props);
516
+ wrt.flush(pkt.payload);
517
+ } else {
518
+ wrt.flush(pkt.payload);
519
+ }
520
+
521
+ return wrt.as_pkt(
522
+ 0x30 | qos | (pkt.dup ? 0x8 : 0) | (pkt.retain ? 0x1 : 0) )
523
+ }
524
+ }
525
+
526
+ function mqtt_encode_puback(ns, mqtt_writer) {
527
+ return ns.puback = ( mqtt_level, pkt ) => {
528
+ let wrt = mqtt_writer.of(pkt);
529
+
530
+ wrt.u16(pkt.pkt_id);
531
+ if (5 <= mqtt_level) {
532
+ wrt.reason(pkt.reason);
533
+ wrt.props(pkt.props);
534
+ }
535
+
536
+ return wrt.as_pkt(0x40)
537
+ }
538
+ }
539
+
540
+ function mqtt_encode_pubxxx(ns, mqtt_writer) {
541
+ ns.pubrec = _enc_pubxxx(0x50);
542
+ ns.pubrel = _enc_pubxxx(0x62);
543
+ ns.pubcomp = _enc_pubxxx(0x70);
544
+
545
+
546
+ function _enc_pubxxx(hdr) {
547
+ return ( mqtt_level, pkt ) => {
548
+ let wrt = mqtt_writer.of(pkt);
549
+
550
+ wrt.u16(pkt.pkt_id);
551
+ if (5 <= mqtt_level) {
552
+ wrt.props(pkt.props);
553
+ wrt.reason(pkt.reason);
554
+
555
+ } else {
556
+ wrt.reason( pkt.return_code || pkt.reason );
557
+ }
558
+
559
+ return wrt.as_pkt(hdr)
560
+ }
561
+ }
562
+ }
563
+
564
+ function mqtt_encode_subscribe(ns, mqtt_writer) {
565
+ const _enc_subscribe_flags = opts => 0
566
+ | ( opts.qos & 0x3 )
567
+ | ( opts.retain ? 0x4 : 0 )
568
+ | ( (opts.retain_handling & 0x3) << 2 );
569
+
570
+ return ns.subscribe = ( mqtt_level, pkt ) => {
571
+ let wrt = mqtt_writer.of(pkt);
572
+
573
+ wrt.u16(pkt.pkt_id);
574
+ if (5 <= mqtt_level)
575
+ wrt.props(pkt.props);
576
+
577
+ let f0 = _enc_subscribe_flags(pkt);
578
+ for (let each of pkt.topics) {
579
+ if ('string' === typeof each) {
580
+ wrt.utf8(each);
581
+ wrt.u8(f0);
582
+ } else {
583
+ let [topic, opts] =
584
+ Array.isArray(each) ? each
585
+ : [each.topic, each.opts];
586
+
587
+ wrt.utf8(topic);
588
+ if (undefined === opts) wrt.u8(f0);
589
+ else wrt.flags(opts, _enc_subscribe_flags);
590
+ }
591
+ }
592
+
593
+ return wrt.as_pkt(0x82)
594
+ }
595
+ }
596
+
597
+ function mqtt_encode_xxsuback(ns, mqtt_writer) {
598
+ ns.suback = _enc_xxsuback(0x90);
599
+ ns.unsuback = _enc_xxsuback(0xb0);
600
+
601
+
602
+ function _enc_xxsuback(hdr) {
603
+ return ( mqtt_level, pkt ) => {
604
+ let wrt = mqtt_writer.of(pkt);
605
+
606
+ wrt.u16(pkt.pkt_id);
607
+ if (5 <= mqtt_level)
608
+ wrt.props(pkt.props);
609
+
610
+ for (let ans of pkt.answers)
611
+ wrt.reason(ans);
612
+
613
+ return wrt.as_pkt(hdr)
614
+ }
615
+ }
616
+ }
617
+
618
+ function mqtt_encode_unsubscribe(ns, mqtt_writer) {
619
+ return ns.unsubscribe = ( mqtt_level, pkt ) => {
620
+ let wrt = mqtt_writer.of(pkt);
621
+
622
+ wrt.u16(pkt.pkt_id);
623
+ if (5 <= mqtt_level)
624
+ wrt.props(pkt.props);
625
+
626
+ for (let topic of pkt.topics)
627
+ wrt.utf8(topic);
628
+
629
+ return wrt.as_pkt(0xa2)
630
+ }
631
+ }
632
+
633
+ function mqtt_encode_pingxxx(ns) {
634
+ ns.pingreq = () => new Uint8Array([ 0xc0, 0 ]);
635
+ ns.pingresp = () => new Uint8Array([ 0xd0, 0 ]);
636
+ }
637
+
638
+ function mqtt_encode_disconnect(ns, mqtt_writer) {
639
+ return ns.disconnect = ( mqtt_level, pkt ) => {
640
+ let wrt = mqtt_writer.of(pkt);
641
+
642
+ if (pkt && 5 <= mqtt_level) {
643
+ if (pkt.reason || pkt.props) {
644
+ wrt.reason(pkt.reason);
645
+ wrt.props(pkt.props);
646
+ }
647
+ }
648
+
649
+ return wrt.as_pkt(0xe0)
650
+ }
651
+ }
652
+
653
+ // not a v4 packet: import { mqtt_encode_auth } from './encode/auth.js'
654
+
655
+
656
+ const mqtt_reader_v4 = /* #__PURE__ */
657
+ mqtt_reader_info(
658
+ mqtt_reader_v4$1,
659
+ _connack_v4,
660
+ _pubxxx_v4,
661
+ _suback_v4,
662
+ _unsuback_v4,
663
+ );
664
+
665
+ const mqtt_decode_v4 = [
666
+ mqtt_decode_connect,
667
+ mqtt_decode_connack,
668
+ mqtt_decode_publish,
669
+ mqtt_decode_puback,
670
+ mqtt_decode_pubxxx,
671
+ mqtt_decode_subscribe,
672
+ mqtt_decode_suback,
673
+ mqtt_decode_unsubscribe,
674
+ mqtt_decode_unsuback,
675
+ mqtt_decode_pingxxx,
676
+ mqtt_decode_disconnect,
677
+ ];
678
+
679
+
680
+ const mqtt_encode_v4 = [
681
+ mqtt_encode_connect,
682
+ mqtt_encode_connack,
683
+ mqtt_encode_publish,
684
+ mqtt_encode_puback,
685
+ mqtt_encode_pubxxx,
686
+ mqtt_encode_subscribe,
687
+ mqtt_encode_xxsuback,
688
+ mqtt_encode_unsubscribe,
689
+ mqtt_encode_pingxxx,
690
+ mqtt_encode_disconnect,
691
+ ];
692
+
693
+
694
+ const mqtt_opts_v4 =
695
+ { decode_fns: mqtt_decode_v4,
696
+ mqtt_reader: mqtt_reader_v4,
697
+ encode_fns: mqtt_encode_v4,
698
+ mqtt_writer: mqtt_writer_v4, };
699
+
700
+ function parse(str, loose) {
701
+ if (str instanceof RegExp) return { keys:false, pattern:str };
702
+ var c, o, tmp, ext, keys=[], pattern='', arr = str.split('/');
703
+ arr[0] || arr.shift();
704
+
705
+ while (tmp = arr.shift()) {
706
+ c = tmp[0];
707
+ if (c === '*') {
708
+ keys.push('wild');
709
+ pattern += '/(.*)';
710
+ } else if (c === ':') {
711
+ o = tmp.indexOf('?', 1);
712
+ ext = tmp.indexOf('.', 1);
713
+ keys.push( tmp.substring(1, !!~o ? o : !!~ext ? ext : tmp.length) );
714
+ pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';
715
+ if (!!~ext) pattern += (!!~o ? '?' : '') + '\\' + tmp.substring(ext);
716
+ } else {
717
+ pattern += '/' + tmp;
718
+ }
719
+ }
720
+
721
+ return {
722
+ keys: keys,
723
+ pattern: new RegExp('^' + pattern + (loose ? '(?=$|\/)' : '\/?$'), 'i')
724
+ };
725
+ }
726
+
727
+ /*
728
+ class AbstractTopicRouter ::
729
+ async invoke(pkt, ctx) ::
730
+ add(topic_route, ...args) ::
731
+ remove(topic_route, priority) ::
732
+ clear(priority) ::
733
+ find(topic) :: // optional
734
+ mqtt_topic(topic_route)
735
+ */
736
+
737
+ const with_topic_router = mqtt_topic_router =>
738
+ MQTTKlass => class extends MQTTKlass {
739
+ static _aliases() {
740
+ return super._aliases() +
741
+ ' sub_topic:subscribe_topic unsub_topic:unsubscribe_topic'}
742
+
743
+ _init_router(opt, self, target) {
744
+ this._subs = [];
745
+ let router = this.router = target.router =
746
+ mqtt_topic_router(opt, this, target);
747
+ return router?.invoke}
748
+
749
+ on_sub(suback, pkt) {
750
+ suback.pkt = pkt;
751
+ this._subs.push(suback);
752
+ return suback}
753
+ subs_settled() {
754
+ return Promise.allSettled(
755
+ this._subs.splice(0,Infinity)) }
756
+
757
+ // alias: sub_topic
758
+ subscribe_topic(topic_route, ...args) {
759
+ let router = this.router;
760
+ router.add(topic_route, true, args.pop() );// handler
761
+ let topic = router.mqtt_topic(topic_route);
762
+ this.subscribe(topic, ...args );// ex, topic_prefix
763
+ return this }// fluent api -- return this and track side effects
764
+
765
+ // alias: unsub_topic
766
+ unsubscribe_topic(topic_route, ...args) {
767
+ let router = this.router;
768
+ router.remove(topic_route, true);
769
+ let topic = router.mqtt_topic(topic_route);
770
+ return this.unsubscribe(topic, ...args ) }// topic_prefix
771
+
772
+ // add topic handlers without corresponding subscribe packet
773
+ on_topic(...args) {
774
+ this.router.add(...args);
775
+ return this} };
776
+
777
+ // Use [regexparam][] for url-like topic parsing
778
+ // [regexparam]: https://github.com/lukeed/regexparam
779
+
780
+
781
+ const with_topic_path_router = /* #__PURE__ */
782
+ with_topic_router(mqtt_topic_path_router);
783
+
784
+
785
+ const mqtt_topic = topic_route =>
786
+ topic_route
787
+ .replace(/[*].*$/, '#')
788
+ .replace(/:\w[^\/]*/g, '+');
789
+
790
+ /* From the [MQTT v5 Spec](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Topic_Names_and)
791
+ 4.7.1.2 Multi-level wildcard -- (‘#’ U+0023)
792
+ ... MUST be specified either on its own or following a topic level separator.
793
+ In either case it MUST be the last character specified in the Topic Filter
794
+
795
+ 4.7.1.3 Single-level wildcard -- (‘+’ U+002B)
796
+ ...it MUST occupy an entire level of the filter.
797
+ */
798
+
799
+ const as_topic_path = (topic_route, id) =>(
800
+ id=1,
801
+ topic_route
802
+ .replace(/#$/, '*' )// replace MQTT '#' multi-level wildcard at end
803
+ .replace(/\+/g, () => `:$${id++}` ) );// replace MQTT '+' single-level wildcards
804
+
805
+ function _ignore(pkt, params, ctx) {ctx.done = true;}
806
+
807
+ function mqtt_topic_path_router() {
808
+ let pri_lsts = [[],[]], rm = Symbol();
809
+ let find = topic => _routes_iter(pri_lsts, topic);
810
+
811
+ // return duck-type compatible with AbstractTopicRouter in ./with_topic_router
812
+ return {find, mqtt_topic,
813
+ add(topic_route, ...args) {
814
+ let fn = args.pop();
815
+ let priority = args.pop();
816
+
817
+ if ('function' !== typeof fn) {
818
+ if (fn) {throw new TypeError()}
819
+ fn = _ignore;}
820
+
821
+ let rte = parse(as_topic_path(topic_route));
822
+
823
+ rte.key = topic_route;
824
+ rte.tgt = fn;
825
+ pri_lsts[priority ? 0 : 1].push(rte);
826
+ return this}
827
+
828
+ , remove(topic_route, priority) {
829
+ let lst = pri_lsts[priority ? 0 : 1];
830
+ return _route_remove([lst], topic_route)}
831
+
832
+ , clear(priority) {
833
+ pri_lsts[priority ? 0 : 1] = [];
834
+ if (null == priority) {
835
+ pri_lsts[1] = []; } }// null clears both lists
836
+
837
+ , async invoke(pkt, ctx) {
838
+ ctx.idx = 0;
839
+ ctx.rm = rm;
840
+
841
+ for (let [fn, params] of find(pkt.topic)) {
842
+ let res = await fn(pkt, params, ctx);
843
+
844
+ if (rm === res) {
845
+ _route_remove(pri_lsts, fn);}
846
+
847
+ if (ctx.done) {
848
+ break}
849
+ else ctx.idx++;}
850
+
851
+ if (1 === pkt.qos) {
852
+ await ctx.mqtt.puback(pkt);} } } }
853
+
854
+
855
+ function * _routes_iter(all_route_lists, topic) {
856
+ topic = topic.replace(/^[\/]*/, '/'); // ensure '/' prefix for regexparam library
857
+ for (let route_list of all_route_lists) {
858
+ for (let {keys, pattern, tgt} of route_list) {
859
+ let match = pattern.exec(topic);
860
+ if (match) {
861
+ let params = keys
862
+ ? keys.reduce(
863
+ (o, k, i) => (o[k] = match[1+i], o)
864
+ , {})
865
+ : match.groups ?? match;
866
+ yield [tgt, params];} } } }
867
+
868
+
869
+ function _route_remove(all_route_lists, query) {
870
+ let fn_match = route =>(
871
+ route===query
872
+ || route.tgt===query
873
+ || route.key===query);
874
+ for (let lst of all_route_lists) {
875
+ let i = lst.findIndex(fn_match);
876
+ if (0 <= i) {
877
+ lst.splice(i,1);
878
+ return true} }
879
+ return false}
880
+
881
+ /*
882
+ export function decode_varint_loop(u8, i=0) {
883
+ let i0 = i
884
+ let shift = 0, n = (u8[i] & 0x7f)
885
+ while ( 0x80 & u8[i++] )
886
+ n |= (u8[i] & 0x7f) << (shift += 7)
887
+
888
+ return [n, i, i0]
889
+ }
890
+ */
891
+
892
+
893
+ function decode_varint(u8, i=0) {
894
+ let i0 = i;
895
+ // unrolled for a max of 4 chains
896
+ let n = (u8[i] & 0x7f) << 0;
897
+ if ( 0x80 & u8[i++] ) {
898
+ n |= (u8[i] & 0x7f) << 7;
899
+ if ( 0x80 & u8[i++] ) {
900
+ n |= (u8[i] & 0x7f) << 14;
901
+ if ( 0x80 & u8[i++] ) {
902
+ n |= (u8[i] & 0x7f) << 21;
903
+ }
904
+ }
905
+ }
906
+ return [n, i, i0]
907
+ }
908
+
909
+ function mqtt_raw_dispatch(opt) {
910
+ let u8 = new Uint8Array(0);
911
+ return u8_buf => {
912
+ u8 = 0 === u8.byteLength
913
+ ? u8_buf : _u8_join(u8, u8_buf);
914
+
915
+ let res = [];
916
+ while (1) {
917
+ let [len_body, len_vh] = decode_varint(u8, 1);
918
+ let len_pkt = len_body + len_vh;
919
+
920
+ if ( u8.byteLength < len_pkt )
921
+ return res
922
+
923
+ let b0 = u8[0];
924
+ let u8_body = 0 === len_body ? null
925
+ : u8.subarray(len_vh, len_pkt);
926
+
927
+ u8 = u8.subarray(len_pkt);
928
+
929
+ let pkt = opt.decode_pkt(b0, u8_body, opt);
930
+ if (null != pkt)
931
+ res.push( pkt );
932
+ }
933
+ }
934
+ }
935
+
936
+ function _u8_join(a, b) {
937
+ let alen = a.byteLength, r = new Uint8Array(alen + b.byteLength);
938
+ r.set(a, 0);
939
+ r.set(b, alen);
940
+ return r
941
+ }
942
+
943
+ const _pkt_types = ['~', 'connect', 'connack', 'publish', 'puback', 'pubrec', 'pubrel', 'pubcomp', 'subscribe', 'suback', 'unsubscribe', 'unsuback', 'pingreq', 'pingresp', 'disconnect', 'auth'];
944
+
945
+ function mqtt_pkt_ctx(mqtt_level, opts, pkt_ctx) {
946
+ pkt_ctx = {
947
+ __proto__: pkt_ctx || opts.pkt_ctx,
948
+ mqtt_level,
949
+ get hdr() { return this.b0 & 0xf },
950
+ get id() { return this.b0 >>> 4 },
951
+ get type() { return _pkt_types[this.b0 >>> 4] },
952
+ };
953
+
954
+ let op, _decode_by_id=[], _encode_by_type={};
955
+ for (op of opts.encode_fns)
956
+ op(_encode_by_type, opts.mqtt_writer);
957
+ for (op of opts.decode_fns)
958
+ op(_decode_by_id, opts.mqtt_reader);
959
+
960
+ return {
961
+ pkt_ctx,
962
+
963
+ encode_pkt(type, pkt) {
964
+ return _encode_by_type[type]( mqtt_level, pkt ) },
965
+
966
+ decode_pkt(b0, u8_body) {
967
+ if (b0.map) // Uint8Array in first arg
968
+ return mqtt_raw_dispatch(this)(b0)[0]
969
+
970
+ let fn_decode = _decode_by_id[b0>>>4] || _decode_by_id[0];
971
+ return fn_decode?.({__proto__: this.pkt_ctx, b0}, u8_body) },
972
+
973
+ mqtt_stream() {
974
+ let self = { __proto__: this, pkt_ctx: { __proto__: pkt_ctx } };
975
+ self.pkt_ctx._base_ = self.pkt_ctx;
976
+ self.decode = mqtt_raw_dispatch(self);
977
+ return self
978
+ },
979
+ }
980
+ }
981
+
982
+ function ao_defer_ctx(as_res = (...args) => args) {
983
+ let y,n,_pset = (a,b) => { y=a, n=b; };
984
+ return p =>(
985
+ p = new Promise(_pset)
986
+ , as_res(p, y, n)) }
987
+
988
+ const ao_defer_v = /* #__PURE__ */
989
+ ao_defer_ctx();
990
+
991
+ Promise.resolve({type:'init'});
992
+
993
+ function _mqtt_conn(client, [on_mqtt, pkt_future]) {
994
+ let _q_init = ao_defer_v(), _q_ready = ao_defer_v();
995
+ let _send_ready = async (...args) => (await _q_ready[0])(...args);
996
+ let _send_mqtt_pkt, _has_connected;
997
+ client._send = _send_ready;
998
+
999
+ return {
1000
+ async when_ready() {await _q_ready[0];}
1001
+
1002
+ , ping: _ping_interval (() =>_send_mqtt_pkt?.('pingreq'))
1003
+
1004
+ , reset(err) {
1005
+ if (! _send_mqtt_pkt) {return}
1006
+
1007
+ if (err) {
1008
+ _q_init[2](err);}
1009
+
1010
+ _send_mqtt_pkt = null;
1011
+ _q_init = ao_defer_v();
1012
+ client._send = _send_ready;
1013
+
1014
+ // call client.on_conn_reset in next promise microtask
1015
+ client.conn_emit('on_disconnect', false===err, err);}
1016
+
1017
+ , async send_connect(... args) {
1018
+ if (! _send_mqtt_pkt) {
1019
+ await _q_init[0]; }// _send_mqtt_pkt is set before fulfilled
1020
+
1021
+ // await connack response
1022
+ let res = await _send_mqtt_pkt(...args);
1023
+ if (0 == res[0].reason) {
1024
+ _has_connected = true;
1025
+ // resolve _q_ready[0] with _send_mqtt_pkt closure
1026
+ _q_ready[1](client._send = _send_mqtt_pkt);
1027
+ _q_ready = ao_defer_v();
1028
+ client.conn_emit('on_ready');}
1029
+
1030
+ return res}
1031
+
1032
+ , is_set: (() =>!! _send_mqtt_pkt)
1033
+ , set(mqtt_ctx, send_u8_pkt) {
1034
+ if (_send_mqtt_pkt) {
1035
+ throw new Error('Already connected')}
1036
+
1037
+ mqtt_ctx = mqtt_ctx.mqtt_stream();
1038
+ let sess_ctx = {mqtt: client};
1039
+ let on_mqtt_chunk = u8_buf =>
1040
+ on_mqtt(mqtt_ctx.decode(u8_buf), sess_ctx);
1041
+
1042
+ _send_mqtt_pkt = async (type, pkt, key) => {
1043
+ let res = undefined !== key
1044
+ ? pkt_future(key) : true;
1045
+
1046
+ await send_u8_pkt(
1047
+ mqtt_ctx.encode_pkt(type, pkt));
1048
+
1049
+ return res};
1050
+
1051
+ _q_init[1](_send_mqtt_pkt); // resolve _q_init with _send_mqtt_pkt closure
1052
+
1053
+ // call client.on_live in next promise microtask
1054
+ client.conn_emit('on_live', _has_connected);
1055
+ return on_mqtt_chunk} } }
1056
+
1057
+
1058
+ function _ping_interval(send_ping) {
1059
+ let tid;
1060
+ return (( td ) => {
1061
+ tid = clearInterval(tid);
1062
+ if (td) {
1063
+ tid = setInterval(send_ping, 1000 * td);
1064
+
1065
+
1066
+
1067
+
1068
+ // ensure the interval allows the NodeJS event loop to exit
1069
+ tid.unref?.();
1070
+ return true} }) }
1071
+
1072
+ const _mqtt_cmdid_dispatch ={
1073
+ create(target) {
1074
+ return {__proto__: this, target, hashbelt: [new Map()]} }
1075
+
1076
+ , bind_pkt_future(_pkt_id=100) {
1077
+ let {hashbelt} = this;
1078
+
1079
+ let _tmp_; // use _tmp_ to reuse _by_key closure
1080
+ let _by_key = answer_monad =>
1081
+ hashbelt[0].set(_tmp_, answer_monad);
1082
+
1083
+ return (( pkt_or_key ) => {
1084
+ if ('string' === typeof pkt_or_key) {
1085
+ _tmp_ = pkt_or_key;}
1086
+ else {
1087
+ _pkt_id = (_pkt_id + 1) & 0xffff;
1088
+ _tmp_ = pkt_or_key.pkt_id = _pkt_id;}
1089
+
1090
+ return new Promise(_by_key)}) }
1091
+
1092
+ , answer(key, pkt) {
1093
+ for (let map of this.hashbelt) {
1094
+ let answer_monad = map.get(key);
1095
+ if (undefined !== answer_monad) {
1096
+ map.delete(key);
1097
+
1098
+ answer_monad([pkt, /*err*/]); // option/maybe monad
1099
+ return true} }
1100
+ return false}
1101
+
1102
+ , rotate_belt(n) {
1103
+ let {hashbelt} = this;
1104
+ hashbelt.unshift(new Map());
1105
+ for (let old of hashbelt.splice(n || 5)) {
1106
+ for (let answer_monad of old.values()) {
1107
+ answer_monad([/*pkt*/, 'expired']); } } }// option/maybe monad
1108
+
1109
+ , cmdids: ((() => {
1110
+ return [
1111
+ (() =>{} )// 0x0 reserved
1112
+ , by_evt // 0x1 connect
1113
+ , by_type // 0x2 connack
1114
+ , by_evt // 0x3 publish
1115
+ , by_id // 0x4 puback
1116
+ , by_id // 0x5 pubrec
1117
+ , by_id // 0x6 pubrel
1118
+ , by_id // 0x7 pubcomp
1119
+ , by_evt // 0x8 subscribe
1120
+ , by_id // 0x9 suback
1121
+ , by_evt // 0xa unsubscribe
1122
+ , by_id // 0xb unsuback
1123
+ , by_type // 0xc pingreq
1124
+ , by_type // 0xd pingresp
1125
+ , by_evt // 0xe disconnect
1126
+ , by_type ]// 0xf auth
1127
+
1128
+
1129
+ function by_id(disp, pkt) {
1130
+ disp.answer(pkt.pkt_id, pkt); }
1131
+
1132
+ function by_type(disp, pkt, ctx) {
1133
+ disp.answer(pkt.type, pkt);
1134
+ by_evt(disp, pkt, ctx);}
1135
+
1136
+ async function by_evt({target}, pkt, ctx) {
1137
+ let fn = target[`mqtt_${pkt.type}`]
1138
+ || target.mqtt_pkt;
1139
+
1140
+ await fn?.call(target, pkt, ctx);} })()) };
1141
+
1142
+ /*
1143
+ on_mqtt_type = {
1144
+ mqtt_auth(pkt, ctx) ::
1145
+ mqtt_connect(pkt, ctx) ::
1146
+ mqtt_connack(pkt, ctx) ::
1147
+ mqtt_disconnect(pkt, ctx) ::
1148
+
1149
+ mqtt_publish(pkt, ctx)
1150
+ mqtt_subscribe(pkt, ctx) ::
1151
+ mqtt_unsubscribe(pkt, ctx) ::
1152
+
1153
+ mqtt_pingreq(pkt, ctx) ::
1154
+ mqtt_pingresp(pkt, ctx) ::
1155
+ }
1156
+ */
1157
+
1158
+ function _mqtt_dispatch(opt, target) {
1159
+ let _disp_ = _mqtt_cmdid_dispatch.create(target);
1160
+ let { cmdids } = _disp_;
1161
+
1162
+ // default rotate at 1s across 5 buckets
1163
+ let { td: rotate_td=1000, n: rotate_n=5 } =
1164
+ opt && opt.rotate || {};
1165
+
1166
+ let rotate_ts = rotate_td + Date.now();
1167
+
1168
+ return [on_mqtt,
1169
+ _disp_.bind_pkt_future()]
1170
+
1171
+ function on_mqtt(pkt_list, ctx) {
1172
+ for (let pkt of pkt_list) {
1173
+ cmdids[pkt.id](_disp_, pkt, ctx); }
1174
+
1175
+ if (Date.now() > rotate_ts) {
1176
+ _disp_.rotate_belt(rotate_n);
1177
+ rotate_ts = rotate_td + Date.now();} } }
1178
+
1179
+ class MQTTError extends Error {
1180
+ constructor(mqtt_pkt, reason=mqtt_pkt.reason) {
1181
+ super(`[0x${reason.toString(16)}] ${reason.reason}`);
1182
+ this.mqtt_pkt = mqtt_pkt;
1183
+ this.reason = reason;} }
1184
+
1185
+ class MQTTBase {
1186
+ constructor(opt={}) {
1187
+ this.with(opt);
1188
+ this._conn_ = _mqtt_conn(this,
1189
+ this._init_dispatch(opt, this)); }
1190
+
1191
+ with(fns_ns) {
1192
+ for (let [k,v] of Object.entries(fns_ns)) {
1193
+ if ('function' === typeof v) {this[k] = v;} }
1194
+ return this}
1195
+
1196
+ async conn_emit(evt, arg, err_arg) {
1197
+ this.log_conn?.(evt, arg, err_arg);
1198
+ try {
1199
+ let fn_evt = this[await evt]; // microtask break using `await evt`
1200
+ if (fn_evt) {
1201
+ await fn_evt.call(this, this, arg, err_arg);}
1202
+ else if (err_arg) {throw err_arg} }
1203
+ catch (err) {
1204
+ this.on_error(err, evt);} }
1205
+
1206
+ on_error(err, evt) {
1207
+ console.warn('[[u8-mqtt error: %s]]', evt, err); }
1208
+
1209
+ // Handshaking Packets
1210
+
1211
+ async connect(pkt={}) {
1212
+ let cid = pkt.client_id;
1213
+ if ('string' !== typeof cid) {
1214
+ // see init_client_id implementation in core.jsy
1215
+ pkt.client_id = cid = this.client_id || this.init_client_id(cid);}
1216
+ this.client_id = cid;
1217
+
1218
+ if (null == pkt.keep_alive) {
1219
+ pkt.keep_alive = 60;}
1220
+
1221
+ let res = await this._conn_
1222
+ .send_connect('connect', pkt, 'connack');
1223
+
1224
+ if (0 != res[0].reason) {
1225
+ throw new this.MQTTError(res[0])}
1226
+
1227
+ // TODO: merge with server's keep_alive frequency
1228
+ this._conn_.ping(pkt.keep_alive);
1229
+ return res}
1230
+
1231
+ async disconnect(pkt={}) {
1232
+ let res = await this._send('disconnect', pkt);
1233
+ this._conn_.reset(false);
1234
+ return res}
1235
+
1236
+ auth(pkt={}) {
1237
+ return this._send('auth', pkt, 'auth')}
1238
+
1239
+ ping() {return this._send('pingreq', null, 'pingresp')}
1240
+ puback({pkt_id}) {return this._send('puback', {pkt_id})}
1241
+
1242
+ // alias: sub
1243
+ subscribe(pkt, ex, topic_prefix) {
1244
+ pkt = _as_topics(pkt, ex, topic_prefix);
1245
+ let suback = this._send('subscribe', pkt, pkt);
1246
+ return this.on_sub?.(suback, pkt) ?? suback}
1247
+
1248
+ // alias: unsub
1249
+ unsubscribe(pkt, ex, topic_prefix) {
1250
+ pkt = _as_topics(pkt, ex, topic_prefix);
1251
+ return this._send('unsubscribe', pkt, pkt)}
1252
+
1253
+
1254
+ post(topic, payload, pub_opt) {// qos:0
1255
+ return this.pub({topic, payload, qos:0}, pub_opt)}
1256
+ send(topic, payload, pub_opt) {// qos:1
1257
+ return this.pub({topic, payload, qos:1}, pub_opt)}
1258
+ store(topic, payload, pub_opt) {// qos:1, retain: 1
1259
+ return this.pub({topic, payload, qos:1, retain: 1}, pub_opt)}
1260
+
1261
+ // alias: json_post
1262
+ obj_post(topic, msg, pub_opt) {// qos:0
1263
+ return this.pub({topic, msg, arg: 'msg', qos:0}, pub_opt)}
1264
+ // alias: json_send
1265
+ obj_send(topic, msg, pub_opt) {// qos:1
1266
+ return this.pub({topic, msg, arg: 'msg', qos:1}, pub_opt)}
1267
+ // alias: json_store
1268
+ obj_store(topic, msg, pub_opt) {// qos:1, retain: 1
1269
+ return this.pub({topic, msg, arg: 'msg', qos:1, retain: 1}, pub_opt)}
1270
+
1271
+ // alias: publish -- because 'pub' is shorter for semantic aliases above
1272
+ async pub(pkt, pub_opt) {
1273
+ if (undefined === pkt.payload) {
1274
+ if ('function' === typeof pub_opt) {
1275
+ pub_opt = {fn_encode: pub_opt};}
1276
+
1277
+ let {msg} = pkt;
1278
+ switch (typeof msg) {
1279
+ case 'function':
1280
+ pub_opt = {...pub_opt, fn_encode: msg};
1281
+ // flow into 'undefined' case
1282
+ case 'undefined':
1283
+ // return a single-value closure to publish packets
1284
+ return v => this.pub({...pkt, [pkt.arg || 'payload']: v}, pub_opt)}
1285
+
1286
+ // Encode payload from msg; fn_encode allows alternative to JSON.stringify
1287
+ let {fn_encode} = pub_opt || {};
1288
+ pkt.payload = fn_encode
1289
+ ? await fn_encode(msg)
1290
+ : JSON.stringify(msg);}
1291
+
1292
+ if (pub_opt) {
1293
+ if (pub_opt.props) {
1294
+ pkt.props = pub_opt.props;}
1295
+ if (pub_opt.xform) {
1296
+ pkt = pub_opt.xform(pkt) || pkt;} }
1297
+
1298
+ return this._send('publish', pkt,
1299
+ pkt.qos ? pkt : void 0 ) }// key
1300
+
1301
+
1302
+ // Internal API
1303
+
1304
+ /* async _send(type, pkt) -- provided by _conn_ and transport */
1305
+
1306
+ _init_dispatch(opt) {
1307
+ this.constructor?._once_();
1308
+ let target ={__proto__: opt.on_mqtt_type};
1309
+ target.mqtt_publish ||=
1310
+ this._init_router?.(opt, this, target);
1311
+ return _mqtt_dispatch(this, target)}
1312
+
1313
+ static _aliases() {
1314
+ return ' publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store'}
1315
+
1316
+ static _once_(self=this) {
1317
+ self._once_ = _=>0;
1318
+ let p = self.prototype;
1319
+ p.MQTTError = MQTTError;
1320
+ for (let alias of self._aliases().split(/\s+/)) {
1321
+ alias = alias.split(':');
1322
+ let fn = alias[1] && p[alias[1]];
1323
+ if (fn) {p[alias[0]] = fn;} } } }
1324
+
1325
+
1326
+ function _as_topics(pkt, ex, topic_prefix) {
1327
+ if (ex?.trim) {// string
1328
+ topic_prefix = ex;
1329
+ ex = null;}
1330
+
1331
+ pkt =(
1332
+ pkt.trim // string
1333
+ ? {topics:[pkt], ... ex}
1334
+ : pkt[Symbol.iterator]
1335
+ ? {topics:[... pkt], ... ex}
1336
+ : ex ? {...pkt, ...ex}
1337
+ : pkt);
1338
+
1339
+ if (topic_prefix) {
1340
+ // particularly useful with shared queues, e.g.
1341
+ // topic_prefix = '$share/some-queue-name/'
1342
+ let _prefix_topics = v =>
1343
+ v.trim ? topic_prefix+v : v.map(_prefix_topics);
1344
+
1345
+ pkt.topics = pkt.topics.map(_prefix_topics);}
1346
+ return pkt}
1347
+
1348
+ const pkt_api = {
1349
+ utf8(u8) { return new TextDecoder('utf-8').decode(u8 || this.payload ) },
1350
+ json(u8) { return JSON.parse( this.utf8(u8) || null ) },
1351
+ text(u8) { return this.utf8(u8) },
1352
+ };
1353
+
1354
+ class MQTTCore extends MQTTBase {
1355
+ static mqtt_ctx(mqtt_level, mqtt_opts, pkt_ctx=pkt_api) {
1356
+ let self = class extends this {};
1357
+ self.prototype.mqtt_ctx =
1358
+ mqtt_pkt_ctx(mqtt_level, mqtt_opts, pkt_ctx);
1359
+ return self}
1360
+
1361
+
1362
+ // automatic Client Id for connect()
1363
+ init_client_id(parts=['u8-mqtt--','']) {
1364
+ let sess_stg=this.sess_stg;
1365
+ let key, cid = sess_stg?.getItem(key=parts.join(' '));
1366
+ if (! cid) {
1367
+ cid = parts.join(Math.random().toString(36).slice(2));
1368
+ sess_stg?.setItem(key, cid);}
1369
+ return cid}
1370
+
1371
+ get sess_stg() {return globalThis.sessionStorage}
1372
+
1373
+
1374
+ //on_error(err, evt) ::
1375
+ // console.warn @ '[[u8-mqtt error: %s]]', evt, err
1376
+
1377
+ //log_conn(evt, arg, err_arg) ::
1378
+ // console.info @ '[[u8-mqtt log: %s]]', evt, arg, err_arg
1379
+
1380
+ on_live(client, is_reconnect) {
1381
+ if (is_reconnect) {
1382
+ return client.connect()} }
1383
+
1384
+ // on_ready(client) ::
1385
+ // on_reconnect(client) ::
1386
+ on_disconnect(client, intentional) {
1387
+ if (! intentional) {
1388
+ return client.on_reconnect?.()} }
1389
+
1390
+ _use_conn(fn_reconnect) {
1391
+ return (this.reconnect = fn_reconnect)?.()}
1392
+ with_autoreconnect(opt=2000) {
1393
+ if (opt.toFixed) {opt ={delay: opt};}
1394
+ return this.with({
1395
+ on_reconnect() {
1396
+ this.delay(opt.delay || 2000)
1397
+ .then(this.reconnect)
1398
+ .then(opt.reconnect, opt.error);} }) }
1399
+
1400
+ delay(ms) {
1401
+ return new Promise(done => setTimeout(done, ms)) }
1402
+
1403
+ with_async_iter(async_iter, write_u8_pkt) {
1404
+ let on_mqtt_chunk = this._conn_.set(
1405
+ this.mqtt_ctx,
1406
+ write_u8_pkt);
1407
+
1408
+ this._msg_loop = ((async () => {
1409
+ try {
1410
+ async_iter = await async_iter;
1411
+ for await (let chunk of async_iter)
1412
+ on_mqtt_chunk(chunk);
1413
+ this._conn_.reset();}
1414
+ catch (err) {
1415
+ this._conn_.reset(err);} })());
1416
+
1417
+ return this}
1418
+
1419
+
1420
+
1421
+
1422
+
1423
+
1424
+
1425
+
1426
+
1427
+
1428
+
1429
+
1430
+
1431
+
1432
+
1433
+
1434
+
1435
+
1436
+
1437
+
1438
+
1439
+
1440
+
1441
+
1442
+
1443
+
1444
+
1445
+
1446
+
1447
+
1448
+
1449
+
1450
+ with_tcp(...opt) {
1451
+ opt = this._conn_opt(opt);
1452
+ return this._use_conn (() =>
1453
+ this.with_stream(
1454
+ connect(opt)) ) }
1455
+
1456
+ with_tls(...opt) {
1457
+ opt = this._conn_opt(opt);
1458
+ return this._use_conn (() =>
1459
+ this.with_stream(
1460
+ connect$1(opt)) ) }
1461
+
1462
+ _conn_opt([a0, a1, a2]) {
1463
+ // (port, hostname, options) or (url, options)
1464
+ if (Number.isFinite(a0)) {
1465
+ return {...a2, port: a0, host: a1}}
1466
+ a0 = new URL(a0);
1467
+ return {...a1, port: a0.port, host: a0.hostname}}
1468
+
1469
+
1470
+ with_stream(read_stream, write_stream) {
1471
+ if (undefined === write_stream) {
1472
+ write_stream = read_stream;}
1473
+
1474
+ return this.with_async_iter(read_stream,
1475
+ u8_pkt => write_stream.write(u8_pkt)) }
1476
+
1477
+
1478
+ with_websock(websock) {
1479
+ if (! websock?.send) {
1480
+ websock = new URL(websock || 'ws://127.0.0.1:9001');
1481
+ return this._use_conn (() =>
1482
+ this.with_websock(
1483
+ new WebSocket(websock, ['mqtt'])) ) }
1484
+
1485
+ websock.binaryType = 'arraybuffer';
1486
+
1487
+ let ready, {readyState} = websock;
1488
+ if (1 !== readyState) {
1489
+ if (0 !== readyState) {
1490
+ throw new Error('Invalid WebSocket readyState') }
1491
+
1492
+ ready = new Promise(fn => websock.onopen = fn); }
1493
+
1494
+
1495
+ let {_conn_} = this;
1496
+ let on_mqtt_chunk = _conn_.set(
1497
+ this.mqtt_ctx,
1498
+ async u8_pkt =>(
1499
+ await ready
1500
+ , websock.send(u8_pkt)) );
1501
+
1502
+ websock.onmessage = evt =>(on_mqtt_chunk(new Uint8Array(evt.data)));
1503
+ websock.onclose = evt => {
1504
+ if (! evt.wasClean) {
1505
+ var err = new Error('websocket connection close');
1506
+ err.code = evt.code;
1507
+ err.reason = evt.reason;}
1508
+
1509
+ _conn_.reset(err);};
1510
+
1511
+ return this} }
1512
+
1513
+ const version = '0.5.3-node';
1514
+
1515
+ const MQTTClient_v4 = /* #__PURE__ */
1516
+ with_topic_path_router(
1517
+ MQTTCore.mqtt_ctx(4, mqtt_opts_v4) );
1518
+
1519
+ const mqtt_v4 = opt =>
1520
+ new MQTTClient_v4(opt);
1521
+
1522
+ export { MQTTClient_v4 as MQTTClient, MQTTClient_v4, mqtt_v4 as default, mqtt_v4 as mqtt, mqtt_v4, version };
1523
+ //# sourceMappingURL=full-v4.mjs.map