u8-mqtt 0.4.1 → 0.5.1

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 (81) hide show
  1. package/cjs/basic-v4.cjs +103 -137
  2. package/cjs/basic-v4.cjs.map +1 -1
  3. package/cjs/basic-v5.cjs +102 -136
  4. package/cjs/basic-v5.cjs.map +1 -1
  5. package/cjs/index.cjs +144 -189
  6. package/cjs/index.cjs.map +1 -1
  7. package/cjs/v4.cjs +145 -190
  8. package/cjs/v4.cjs.map +1 -1
  9. package/cjs/v5.cjs +144 -189
  10. package/cjs/v5.cjs.map +1 -1
  11. package/code/_dispatch.jsy +16 -0
  12. package/code/base.jsy +68 -124
  13. package/code/core.jsy +15 -9
  14. package/code/router_path.jsy +24 -43
  15. package/code/with_topic_router.jsy +18 -10
  16. package/esm/basic-v4.js +1154 -0
  17. package/esm/basic-v4.js.map +1 -0
  18. package/esm/basic-v5.js +1416 -0
  19. package/esm/basic-v5.js.map +1 -0
  20. package/esm/deno/basic-v4.js +103 -137
  21. package/esm/deno/basic-v4.js.map +1 -1
  22. package/esm/deno/basic-v5.js +102 -136
  23. package/esm/deno/basic-v5.js.map +1 -1
  24. package/esm/deno/index.js +144 -189
  25. package/esm/deno/index.js.map +1 -1
  26. package/esm/deno/v4.js +145 -190
  27. package/esm/deno/v4.js.map +1 -1
  28. package/esm/deno/v5.js +144 -189
  29. package/esm/deno/v5.js.map +1 -1
  30. package/esm/index.js +1599 -0
  31. package/esm/index.js.map +1 -0
  32. package/esm/node/basic-v4.js +103 -137
  33. package/esm/node/basic-v4.js.map +1 -1
  34. package/esm/node/basic-v4.mjs +103 -137
  35. package/esm/node/basic-v4.mjs.map +1 -1
  36. package/esm/node/basic-v5.js +102 -136
  37. package/esm/node/basic-v5.js.map +1 -1
  38. package/esm/node/basic-v5.mjs +102 -136
  39. package/esm/node/basic-v5.mjs.map +1 -1
  40. package/esm/node/index.js +144 -189
  41. package/esm/node/index.js.map +1 -1
  42. package/esm/node/index.mjs +144 -189
  43. package/esm/node/index.mjs.map +1 -1
  44. package/esm/node/v4.js +145 -190
  45. package/esm/node/v4.js.map +1 -1
  46. package/esm/node/v4.mjs +145 -190
  47. package/esm/node/v4.mjs.map +1 -1
  48. package/esm/node/v5.js +144 -189
  49. package/esm/node/v5.js.map +1 -1
  50. package/esm/node/v5.mjs +144 -189
  51. package/esm/node/v5.mjs.map +1 -1
  52. package/esm/v4.js +1336 -0
  53. package/esm/v4.js.map +1 -0
  54. package/esm/v5.js +1599 -0
  55. package/esm/v5.js.map +1 -0
  56. package/esm/web/basic-v4.js +103 -137
  57. package/esm/web/basic-v4.js.map +1 -1
  58. package/esm/web/basic-v4.min.js +1 -1
  59. package/esm/web/basic-v4.min.js.br +0 -0
  60. package/esm/web/basic-v4.min.js.gz +0 -0
  61. package/esm/web/basic-v5.js +102 -136
  62. package/esm/web/basic-v5.js.map +1 -1
  63. package/esm/web/basic-v5.min.js +1 -1
  64. package/esm/web/basic-v5.min.js.br +0 -0
  65. package/esm/web/basic-v5.min.js.gz +0 -0
  66. package/esm/web/index.js +144 -189
  67. package/esm/web/index.js.map +1 -1
  68. package/esm/web/index.min.js +1 -1
  69. package/esm/web/index.min.js.br +0 -0
  70. package/esm/web/index.min.js.gz +0 -0
  71. package/esm/web/v4.js +145 -190
  72. package/esm/web/v4.js.map +1 -1
  73. package/esm/web/v4.min.js +1 -1
  74. package/esm/web/v4.min.js.br +0 -0
  75. package/esm/web/v4.min.js.gz +0 -0
  76. package/esm/web/v5.js +144 -189
  77. package/esm/web/v5.js.map +1 -1
  78. package/esm/web/v5.min.js +1 -1
  79. package/esm/web/v5.min.js.br +0 -0
  80. package/esm/web/v5.min.js.gz +0 -0
  81. package/package.json +14 -9
@@ -0,0 +1,1154 @@
1
+ function encode_varint(n, a=[]) {
2
+ do {
3
+ const ni = n & 0x7f;
4
+ n >>>= 7;
5
+ a.push( ni | (0===n ? 0 : 0x80) );
6
+ } while (n > 0)
7
+ return a
8
+ }
9
+
10
+
11
+ /*
12
+ export function decode_varint_loop(u8, i=0) {
13
+ let i0 = i
14
+ let shift = 0, n = (u8[i] & 0x7f)
15
+ while ( 0x80 & u8[i++] )
16
+ n |= (u8[i] & 0x7f) << (shift += 7)
17
+
18
+ return [n, i, i0]
19
+ }
20
+ */
21
+
22
+
23
+ function decode_varint$1(u8, i=0) {
24
+ let i0 = i;
25
+ // unrolled for a max of 4 chains
26
+ let n = (u8[i] & 0x7f) << 0;
27
+ if ( 0x80 & u8[i++] ) {
28
+ n |= (u8[i] & 0x7f) << 7;
29
+ if ( 0x80 & u8[i++] ) {
30
+ n |= (u8[i] & 0x7f) << 14;
31
+ if ( 0x80 & u8[i++] ) {
32
+ n |= (u8[i] & 0x7f) << 21;
33
+ }
34
+ }
35
+ }
36
+ return [n, i, i0]
37
+ }
38
+
39
+ class U8_Reason extends Number {
40
+ static of(v, pkt_kind, by_kind) {
41
+ let self = new this(v);
42
+ self.reason = by_kind?.[pkt_kind]?.get(v) || pkt_kind;
43
+ return self
44
+ }
45
+ }
46
+
47
+ let mqtt_reader_v4$1 = class mqtt_reader_v4 {
48
+ static of(buf) { return this.prototype.of(buf) }
49
+ of(buf) {
50
+ let step = (width, k) => (k=0|step.k, step.k=k+width, k);
51
+ return {__proto__: this, buf, step}
52
+ }
53
+
54
+ has_more() {
55
+ return this.buf.byteLength > (this.step.k|0)
56
+ }
57
+
58
+ u8() {
59
+ return this.buf[this.step(1)]
60
+ }
61
+
62
+ u16() {
63
+ let {buf, step} = this, i = step(2);
64
+ return (buf[i]<<8) | buf[i+1]
65
+ }
66
+
67
+ u32() {
68
+ let {buf, step} = this, i = step(4);
69
+ return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3]
70
+ }
71
+
72
+ vint() {
73
+ let {buf, step} = this;
74
+ let [n, vi, vi0] = decode_varint$1(buf, step.k|0);
75
+ step(vi - vi0);
76
+ return n
77
+ }
78
+
79
+ bin() {
80
+ let {buf, step} = this, i = step(2);
81
+ let len = (buf[i]<<8) | buf[i+1];
82
+ i = step(len);
83
+ return buf.subarray(i, i+len)
84
+ }
85
+
86
+ utf8() { return new TextDecoder('utf-8').decode(this.bin()) }
87
+ pair() { return [ this.utf8(), this.utf8() ] }
88
+
89
+ flags(FlagsType) { return new FlagsType(this.buf[this.step(1)]) }
90
+
91
+ reason(pkt_kind) {
92
+ let v = this.buf[this.step(1)];
93
+ if (null != v)
94
+ return U8_Reason.of(v, pkt_kind, this._reasons_by)
95
+ }
96
+
97
+ flush() {
98
+ let {buf, step} = this;
99
+ this.step = this.buf = null;
100
+ return buf.subarray(step.k|0)
101
+ }
102
+
103
+ };
104
+
105
+ function mqtt_reader_info(mqtt_reader, ... info_fn_list) {
106
+ mqtt_reader = class extends mqtt_reader {
107
+ static reasons(pkt_type, ...reason_entries) {
108
+ let proto = this.prototype;
109
+ proto._reasons_by = {... proto._reasons_by};
110
+
111
+ let lut = (proto._reasons_by[pkt_type] ||= new Map());
112
+ for (let [u8, reason] of reason_entries)
113
+ lut.set( u8, reason );
114
+
115
+ return this
116
+ }
117
+ };
118
+
119
+ for (let fn_info of info_fn_list)
120
+ fn_info(mqtt_reader);
121
+
122
+ return mqtt_reader
123
+ }
124
+
125
+ class mqtt_writer_v4 {
126
+ static of() { return this.prototype.of() }
127
+ of() { return {__proto__: this, $:[]} }
128
+
129
+ static init() { return this }
130
+
131
+ as_pkt(pkt_id) { return this.pack([pkt_id]) }
132
+
133
+ push(...z) { this.$.push(...z); }
134
+ pack(hdr) {
135
+ let z, i, n=0, parts = this.$;
136
+ this.$ = false;
137
+ for (z of parts) n += z.length;
138
+
139
+ hdr = encode_varint(n, hdr);
140
+ i = hdr.length;
141
+
142
+ let pkt = new Uint8Array(i + n);
143
+ pkt.set(hdr, 0);
144
+ for (z of parts) {
145
+ pkt.set(z, i);
146
+ i += z.length;
147
+ }
148
+ return pkt
149
+ }
150
+
151
+ u8(v) { this.push([ v & 0xff ]); }
152
+ u16(v) { this.push([ (v>>>8) & 0xff, v & 0xff ]); }
153
+ u32(v) { this.push([ (v>>>24) & 0xff, (v>>>16) & 0xff, (v>>>8) & 0xff, v & 0xff ]); }
154
+ vint(v) { this.push( encode_varint(v) );}
155
+
156
+ bin(u8_buf) {
157
+ if (! u8_buf) return this.u16(0)
158
+ if ('string' === typeof u8_buf)
159
+ return this.utf8(u8_buf)
160
+
161
+ if (u8_buf.length !== u8_buf.byteLength)
162
+ u8_buf = new Uint8Array(u8_buf);
163
+
164
+ this.u16(u8_buf.byteLength);
165
+ this.push(u8_buf);
166
+ }
167
+
168
+ utf8(v) {
169
+ let u8_buf = new TextEncoder('utf-8').encode(v);
170
+ this.u16(u8_buf.byteLength);
171
+ this.push(u8_buf);
172
+ }
173
+ pair(k,v) { this.utf8(k); this.utf8(v); }
174
+
175
+ flags(v, enc_flags, b0=0) {
176
+ if (undefined !== v && isNaN(+v))
177
+ v = enc_flags(v, 0);
178
+
179
+ v |= b0;
180
+ this.push([v]);
181
+ return v
182
+ }
183
+
184
+ reason(v) { this.push([v | 0]); }
185
+
186
+ flush(buf) {
187
+ if (null != buf)
188
+ this.push(
189
+ 'string' === typeof buf
190
+ ? new TextEncoder('utf-8').encode(buf)
191
+ : buf );
192
+
193
+ this.push = false;
194
+ }
195
+ }
196
+
197
+ function mqtt_decode_connack(ns, mqtt_reader) {
198
+ class _connack_flags_ extends Number {
199
+ get session_present() { return this & 0x01 !== 0 }
200
+ }
201
+
202
+ return ns[0x2] = (pkt, u8_body) => {
203
+ let rdr = mqtt_reader.of(u8_body);
204
+
205
+ pkt.flags =
206
+ rdr.flags(_connack_flags_);
207
+
208
+ pkt.reason = rdr.reason(pkt.type);
209
+ if (5 <= pkt.mqtt_level)
210
+ pkt.props = rdr.props();
211
+ return pkt }
212
+ }
213
+
214
+
215
+ function _connack_v4(mqtt_reader) {
216
+ mqtt_reader.reasons('connack',
217
+ // MQTT 3.1.1
218
+ [ 0x00, 'Success'],
219
+ [ 0x01, 'Connection refused, unacceptable protocol version'],
220
+ [ 0x02, 'Connection refused, identifier rejected'],
221
+ [ 0x03, 'Connection refused, server unavailable'],
222
+ [ 0x04, 'Connection refused, bad user name or password'],
223
+ [ 0x05, 'Connection refused, not authorized'],
224
+ );
225
+ }
226
+
227
+ function mqtt_decode_publish(ns, mqtt_reader) {
228
+ return ns[0x3] = (pkt, u8_body) => {
229
+ let {hdr} = pkt;
230
+ pkt.dup = Boolean(hdr & 0x8);
231
+ pkt.retain = Boolean(hdr & 0x1);
232
+ let qos = pkt.qos = (hdr>>1) & 0x3;
233
+
234
+ let rdr = mqtt_reader.of(u8_body);
235
+ pkt.topic = rdr.utf8();
236
+ if (0 !== qos)
237
+ pkt.pkt_id = rdr.u16();
238
+
239
+ if (5 <= pkt.mqtt_level)
240
+ pkt.props = rdr.props();
241
+
242
+ pkt.payload = rdr.flush();
243
+ return pkt }
244
+ }
245
+
246
+ function mqtt_decode_puback(ns, mqtt_reader) {
247
+ return ns[0x4] = (pkt, u8_body) => {
248
+ let rdr = mqtt_reader.of(u8_body);
249
+
250
+ pkt.pkt_id = rdr.u16();
251
+ if (5 <= pkt.mqtt_level) {
252
+ pkt.reason = rdr.reason(pkt.type);
253
+ pkt.props = rdr.props();
254
+ }
255
+
256
+ return pkt }
257
+ }
258
+
259
+ function _mqtt_decode_suback(mqtt_reader) {
260
+ return (pkt, u8_body) => {
261
+ let rdr = mqtt_reader.of(u8_body);
262
+
263
+ pkt.pkt_id = rdr.u16();
264
+ if (5 <= pkt.mqtt_level)
265
+ pkt.props = rdr.props();
266
+
267
+ let answers = pkt.answers = [];
268
+ while (rdr.has_more())
269
+ answers.push(
270
+ rdr.reason(pkt.type) );
271
+
272
+ return pkt }
273
+ }
274
+
275
+ function mqtt_decode_suback(ns, mqtt_reader) {
276
+ return ns[0x9] = _mqtt_decode_suback(mqtt_reader)
277
+ }
278
+
279
+ function _suback_v4(mqtt_reader) {
280
+ mqtt_reader.reasons('suback',
281
+ // MQTT 3.1.1
282
+ [ 0x00, 'Granted QoS 0'],
283
+ [ 0x01, 'Granted QoS 1'],
284
+ [ 0x02, 'Granted QoS 2'],
285
+ );
286
+ }
287
+
288
+ function mqtt_decode_unsuback(ns, mqtt_reader) {
289
+ return ns[0xb] = _mqtt_decode_suback(mqtt_reader)
290
+ }
291
+
292
+ function _unsuback_v4(mqtt_reader) {
293
+ mqtt_reader.reasons('unsuback',
294
+ // MQTT 3.1.1
295
+ [ 0x00, 'Success'],
296
+ [ 0x11, 'No subscription existed'],
297
+ [ 0x80, 'Unspecified error'],
298
+ [ 0x83, 'Implementation specific error'],
299
+ [ 0x87, 'Not authorized'],
300
+ [ 0x8F, 'Topic Filter invalid'],
301
+ [ 0x91, 'Packet Identifier in use'],
302
+ );
303
+ }
304
+
305
+ function mqtt_decode_pingxxx(ns) {
306
+ return ns[0xc] = ns[0xd] = pkt => pkt
307
+ }
308
+
309
+ function mqtt_decode_disconnect(ns, mqtt_reader) {
310
+ return ns[0xe] = (pkt, u8_body) => {
311
+ if (u8_body && 5 <= pkt.mqtt_level) {
312
+ let rdr = mqtt_reader.of(u8_body);
313
+ pkt.reason = rdr.reason(pkt.type);
314
+ pkt.props = rdr.props();
315
+ }
316
+ return pkt }
317
+ }
318
+
319
+ function mqtt_encode_connect(ns, mqtt_writer) {
320
+ const _c_mqtt_proto = new Uint8Array([
321
+ 0, 4, 0x4d, 0x51, 0x54, 0x54 ]);
322
+
323
+ const _enc_flags_connect = flags => 0
324
+ | ( flags.reserved ? 0x01 : 0 )
325
+ | ( (flags.will_qos & 0x3) << 3 )
326
+ | ( flags.clean_start ? 0x02 : 0 )
327
+ | ( flags.will_flag ? 0x04 : 0 )
328
+ | ( flags.will_retain ? 0x20 : 0 )
329
+ | ( flags.password ? 0x40 : 0 )
330
+ | ( flags.username ? 0x80 : 0 );
331
+
332
+ const _enc_flags_will = will => 0x4
333
+ | ( (will.qos & 0x3) << 3 )
334
+ | ( will.retain ? 0x20 : 0 );
335
+
336
+ return ns.connect = ( mqtt_level, pkt ) => {
337
+ let wrt = mqtt_writer.of(pkt);
338
+
339
+ wrt.push(_c_mqtt_proto);
340
+ wrt.u8( mqtt_level );
341
+
342
+ let {will, username, password} = pkt;
343
+ let flags = wrt.flags(
344
+ pkt.flags,
345
+ _enc_flags_connect,
346
+ 0 | (username ? 0x80 : 0)
347
+ | (password ? 0x40 : 0)
348
+ | (will ? _enc_flags_will(will) : 0) );
349
+
350
+ wrt.u16(pkt.keep_alive);
351
+
352
+ if (5 <= mqtt_level)
353
+ wrt.props(pkt.props);
354
+
355
+
356
+ wrt.utf8(pkt.client_id);
357
+ if (flags & 0x04) { // .will_flag
358
+ if (5 <= mqtt_level)
359
+ wrt.props(will.props);
360
+
361
+ wrt.utf8(will.topic);
362
+ wrt.bin(will.payload);
363
+ }
364
+
365
+ if (flags & 0x80) // .username
366
+ wrt.utf8(username);
367
+
368
+ if (flags & 0x40) // .password
369
+ wrt.bin(password);
370
+
371
+ return wrt.as_pkt(0x10)
372
+ }
373
+ }
374
+
375
+ function mqtt_encode_publish(ns, mqtt_writer) {
376
+ return ns.publish = ( mqtt_level, pkt ) => {
377
+ let qos = (pkt.qos & 0x3) << 1;
378
+ let wrt = mqtt_writer.of(pkt);
379
+
380
+ wrt.utf8(pkt.topic);
381
+ if (0 !== qos)
382
+ wrt.u16(pkt.pkt_id);
383
+
384
+ if ( 5 <= mqtt_level) {
385
+ wrt.props(pkt.props);
386
+ wrt.flush(pkt.payload);
387
+ } else {
388
+ wrt.flush(pkt.payload);
389
+ }
390
+
391
+ return wrt.as_pkt(
392
+ 0x30 | qos | (pkt.dup ? 0x8 : 0) | (pkt.retain ? 0x1 : 0) )
393
+ }
394
+ }
395
+
396
+ function mqtt_encode_puback(ns, mqtt_writer) {
397
+ return ns.puback = ( mqtt_level, pkt ) => {
398
+ let wrt = mqtt_writer.of(pkt);
399
+
400
+ wrt.u16(pkt.pkt_id);
401
+ if (5 <= mqtt_level) {
402
+ wrt.reason(pkt.reason);
403
+ wrt.props(pkt.props);
404
+ }
405
+
406
+ return wrt.as_pkt(0x40)
407
+ }
408
+ }
409
+
410
+ function mqtt_encode_subscribe(ns, mqtt_writer) {
411
+ const _enc_subscribe_flags = opts => 0
412
+ | ( opts.qos & 0x3 )
413
+ | ( opts.retain ? 0x4 : 0 )
414
+ | ( (opts.retain_handling & 0x3) << 2 );
415
+
416
+ return ns.subscribe = ( mqtt_level, pkt ) => {
417
+ let wrt = mqtt_writer.of(pkt);
418
+
419
+ wrt.u16(pkt.pkt_id);
420
+ if (5 <= mqtt_level)
421
+ wrt.props(pkt.props);
422
+
423
+ let f0 = _enc_subscribe_flags(pkt);
424
+ for (let each of pkt.topics) {
425
+ if ('string' === typeof each) {
426
+ wrt.utf8(each);
427
+ wrt.u8(f0);
428
+ } else {
429
+ let [topic, opts] =
430
+ Array.isArray(each) ? each
431
+ : [each.topic, each.opts];
432
+
433
+ wrt.utf8(topic);
434
+ if (undefined === opts) wrt.u8(f0);
435
+ else wrt.flags(opts, _enc_subscribe_flags);
436
+ }
437
+ }
438
+
439
+ return wrt.as_pkt(0x82)
440
+ }
441
+ }
442
+
443
+ function mqtt_encode_unsubscribe(ns, mqtt_writer) {
444
+ return ns.unsubscribe = ( mqtt_level, pkt ) => {
445
+ let wrt = mqtt_writer.of(pkt);
446
+
447
+ wrt.u16(pkt.pkt_id);
448
+ if (5 <= mqtt_level)
449
+ wrt.props(pkt.props);
450
+
451
+ for (let topic of pkt.topics)
452
+ wrt.utf8(topic);
453
+
454
+ return wrt.as_pkt(0xa2)
455
+ }
456
+ }
457
+
458
+ function mqtt_encode_pingxxx(ns) {
459
+ ns.pingreq = () => new Uint8Array([ 0xc0, 0 ]);
460
+ ns.pingresp = () => new Uint8Array([ 0xd0, 0 ]);
461
+ }
462
+
463
+ function mqtt_encode_disconnect(ns, mqtt_writer) {
464
+ return ns.disconnect = ( mqtt_level, pkt ) => {
465
+ let wrt = mqtt_writer.of(pkt);
466
+
467
+ if (pkt && 5 <= mqtt_level) {
468
+ if (pkt.reason || pkt.props) {
469
+ wrt.reason(pkt.reason);
470
+ wrt.props(pkt.props);
471
+ }
472
+ }
473
+
474
+ return wrt.as_pkt(0xe0)
475
+ }
476
+ }
477
+
478
+ // not a v4 packet: import { mqtt_encode_auth } from './encode/auth.js'
479
+
480
+
481
+ const mqtt_decode_v4 = [
482
+ mqtt_decode_connack,
483
+ mqtt_decode_publish,
484
+ mqtt_decode_puback,
485
+ mqtt_decode_suback,
486
+ mqtt_decode_unsuback,
487
+ mqtt_decode_pingxxx,
488
+ mqtt_decode_disconnect,
489
+ ];
490
+
491
+
492
+ const mqtt_encode_v4 = [
493
+ mqtt_encode_connect,
494
+ mqtt_encode_puback,
495
+ mqtt_encode_publish,
496
+ mqtt_encode_subscribe,
497
+ mqtt_encode_unsubscribe,
498
+ mqtt_encode_pingxxx,
499
+ mqtt_encode_disconnect,
500
+ ];
501
+
502
+ const mqtt_reader_v4 = /* #__PURE__ */
503
+ mqtt_reader_info(
504
+ mqtt_reader_v4$1,
505
+ _connack_v4,
506
+ _suback_v4,
507
+ _unsuback_v4,
508
+ );
509
+
510
+ const mqtt_opts_v4 =
511
+ { decode_fns: mqtt_decode_v4,
512
+ mqtt_reader: mqtt_reader_v4,
513
+ encode_fns: mqtt_encode_v4,
514
+ mqtt_writer: mqtt_writer_v4, };
515
+
516
+ /*
517
+ export function decode_varint_loop(u8, i=0) {
518
+ let i0 = i
519
+ let shift = 0, n = (u8[i] & 0x7f)
520
+ while ( 0x80 & u8[i++] )
521
+ n |= (u8[i] & 0x7f) << (shift += 7)
522
+
523
+ return [n, i, i0]
524
+ }
525
+ */
526
+
527
+
528
+ function decode_varint(u8, i=0) {
529
+ let i0 = i;
530
+ // unrolled for a max of 4 chains
531
+ let n = (u8[i] & 0x7f) << 0;
532
+ if ( 0x80 & u8[i++] ) {
533
+ n |= (u8[i] & 0x7f) << 7;
534
+ if ( 0x80 & u8[i++] ) {
535
+ n |= (u8[i] & 0x7f) << 14;
536
+ if ( 0x80 & u8[i++] ) {
537
+ n |= (u8[i] & 0x7f) << 21;
538
+ }
539
+ }
540
+ }
541
+ return [n, i, i0]
542
+ }
543
+
544
+ function mqtt_raw_dispatch(opt) {
545
+ let u8 = new Uint8Array(0);
546
+ return u8_buf => {
547
+ u8 = 0 === u8.byteLength
548
+ ? u8_buf : _u8_join(u8, u8_buf);
549
+
550
+ let res = [];
551
+ while (1) {
552
+ let [len_body, len_vh] = decode_varint(u8, 1);
553
+ let len_pkt = len_body + len_vh;
554
+
555
+ if ( u8.byteLength < len_pkt )
556
+ return res
557
+
558
+ let b0 = u8[0];
559
+ let u8_body = 0 === len_body ? null
560
+ : u8.subarray(len_vh, len_pkt);
561
+
562
+ u8 = u8.subarray(len_pkt);
563
+
564
+ let pkt = opt.decode_pkt(b0, u8_body, opt);
565
+ if (null != pkt)
566
+ res.push( pkt );
567
+ }
568
+ }
569
+ }
570
+
571
+ function _u8_join(a, b) {
572
+ let alen = a.byteLength, r = new Uint8Array(alen + b.byteLength);
573
+ r.set(a, 0);
574
+ r.set(b, alen);
575
+ return r
576
+ }
577
+
578
+ const _pkt_types = ['~', 'connect', 'connack', 'publish', 'puback', 'pubrec', 'pubrel', 'pubcomp', 'subscribe', 'suback', 'unsubscribe', 'unsuback', 'pingreq', 'pingresp', 'disconnect', 'auth'];
579
+
580
+ function mqtt_pkt_ctx(mqtt_level, opts, pkt_ctx) {
581
+ pkt_ctx = {
582
+ __proto__: pkt_ctx || opts.pkt_ctx,
583
+ mqtt_level,
584
+ get hdr() { return this.b0 & 0xf },
585
+ get id() { return this.b0 >>> 4 },
586
+ get type() { return _pkt_types[this.b0 >>> 4] },
587
+ };
588
+
589
+ let op, _decode_by_id=[], _encode_by_type={};
590
+ for (op of opts.encode_fns)
591
+ op(_encode_by_type, opts.mqtt_writer);
592
+ for (op of opts.decode_fns)
593
+ op(_decode_by_id, opts.mqtt_reader);
594
+
595
+ return {
596
+ pkt_ctx,
597
+
598
+ encode_pkt(type, pkt) {
599
+ return _encode_by_type[type]( mqtt_level, pkt ) },
600
+
601
+ decode_pkt(b0, u8_body) {
602
+ let fn_decode = _decode_by_id[b0>>>4] || _decode_by_id[0];
603
+ return fn_decode?.({__proto__: this.pkt_ctx, b0}, u8_body) },
604
+
605
+ mqtt_stream() {
606
+ let self = { __proto__: this, pkt_ctx: { __proto__: pkt_ctx } };
607
+ self.pkt_ctx._base_ = self.pkt_ctx;
608
+ self.decode = mqtt_raw_dispatch(self);
609
+ return self
610
+ },
611
+ }
612
+ }
613
+
614
+ function ao_defer_ctx(as_res = (...args) => args) {
615
+ let y,n,_pset = (a,b) => { y=a, n=b; };
616
+ return p =>(
617
+ p = new Promise(_pset)
618
+ , as_res(p, y, n)) }
619
+
620
+ const ao_defer_v = /* #__PURE__ */
621
+ ao_defer_ctx();
622
+
623
+ Promise.resolve({type:'init'});
624
+
625
+ function _mqtt_conn(client, [on_mqtt, pkt_future]) {
626
+ let _q_init = ao_defer_v(), _q_ready = ao_defer_v();
627
+ let _send_ready = async (...args) => (await _q_ready[0])(...args);
628
+ let _send_mqtt_pkt, _has_connected;
629
+ client._send = _send_ready;
630
+
631
+ return {
632
+ async when_ready() {await _q_ready[0];}
633
+
634
+ , ping: _ping_interval (() =>_send_mqtt_pkt?.('pingreq'))
635
+
636
+ , reset(err) {
637
+ if (! _send_mqtt_pkt) {return}
638
+
639
+ if (err) {
640
+ _q_init[2](err);}
641
+
642
+ _send_mqtt_pkt = null;
643
+ _q_init = ao_defer_v();
644
+ client._send = _send_ready;
645
+
646
+ // call client.on_conn_reset in next promise microtask
647
+ client.conn_emit('on_disconnect', false===err, err);}
648
+
649
+ , async send_connect(... args) {
650
+ if (! _send_mqtt_pkt) {
651
+ await _q_init[0]; }// _send_mqtt_pkt is set before fulfilled
652
+
653
+ // await connack response
654
+ let res = await _send_mqtt_pkt(...args);
655
+ if (0 == res[0].reason) {
656
+ _has_connected = true;
657
+ // resolve _q_ready[0] with _send_mqtt_pkt closure
658
+ _q_ready[1](client._send = _send_mqtt_pkt);
659
+ _q_ready = ao_defer_v();
660
+ client.conn_emit('on_ready');}
661
+
662
+ return res}
663
+
664
+ , is_set: (() =>!! _send_mqtt_pkt)
665
+ , set(mqtt_ctx, send_u8_pkt) {
666
+ if (_send_mqtt_pkt) {
667
+ throw new Error('Already connected')}
668
+
669
+ mqtt_ctx = mqtt_ctx.mqtt_stream();
670
+ let sess_ctx = {mqtt: client};
671
+ let on_mqtt_chunk = u8_buf =>
672
+ on_mqtt(mqtt_ctx.decode(u8_buf), sess_ctx);
673
+
674
+ _send_mqtt_pkt = async (type, pkt, key) => {
675
+ let res = undefined !== key
676
+ ? pkt_future(key) : true;
677
+
678
+ await send_u8_pkt(
679
+ mqtt_ctx.encode_pkt(type, pkt));
680
+
681
+ return res};
682
+
683
+ _q_init[1](_send_mqtt_pkt); // resolve _q_init with _send_mqtt_pkt closure
684
+
685
+ // call client.on_live in next promise microtask
686
+ client.conn_emit('on_live', _has_connected);
687
+ return on_mqtt_chunk} } }
688
+
689
+
690
+ function _ping_interval(send_ping) {
691
+ let tid;
692
+ return (( td ) => {
693
+ tid = clearInterval(tid);
694
+ if (td) {
695
+ tid = setInterval(send_ping, 1000 * td);
696
+
697
+
698
+
699
+
700
+ // ensure the interval allows the NodeJS event loop to exit
701
+ tid.unref?.();
702
+ return true} }) }
703
+
704
+ const _mqtt_cmdid_dispatch ={
705
+ create(target) {
706
+ return {__proto__: this, target, hashbelt: [new Map()]} }
707
+
708
+ , bind_pkt_future(_pkt_id=100) {
709
+ let {hashbelt} = this;
710
+
711
+ let _tmp_; // use _tmp_ to reuse _by_key closure
712
+ let _by_key = answer_monad =>
713
+ hashbelt[0].set(_tmp_, answer_monad);
714
+
715
+ return (( pkt_or_key ) => {
716
+ if ('string' === typeof pkt_or_key) {
717
+ _tmp_ = pkt_or_key;}
718
+ else {
719
+ _pkt_id = (_pkt_id + 1) & 0xffff;
720
+ _tmp_ = pkt_or_key.pkt_id = _pkt_id;}
721
+
722
+ return new Promise(_by_key)}) }
723
+
724
+ , answer(key, pkt) {
725
+ for (let map of this.hashbelt) {
726
+ let answer_monad = map.get(key);
727
+ if (undefined !== answer_monad) {
728
+ map.delete(key);
729
+
730
+ answer_monad([pkt, /*err*/]); // option/maybe monad
731
+ return true} }
732
+ return false}
733
+
734
+ , rotate_belt(n) {
735
+ let {hashbelt} = this;
736
+ hashbelt.unshift(new Map());
737
+ for (let old of hashbelt.splice(n || 5)) {
738
+ for (let answer_monad of old.values()) {
739
+ answer_monad([/*pkt*/, 'expired']); } } }// option/maybe monad
740
+
741
+ , cmdids: ((() => {
742
+ return [
743
+ (() =>{} )// 0x0 reserved
744
+ , by_evt // 0x1 connect
745
+ , by_type // 0x2 connack
746
+ , by_evt // 0x3 publish
747
+ , by_id // 0x4 puback
748
+ , by_id // 0x5 pubrec
749
+ , by_id // 0x6 pubrel
750
+ , by_id // 0x7 pubcomp
751
+ , by_evt // 0x8 subscribe
752
+ , by_id // 0x9 suback
753
+ , by_evt // 0xa unsubscribe
754
+ , by_id // 0xb unsuback
755
+ , by_type // 0xc pingreq
756
+ , by_type // 0xd pingresp
757
+ , by_evt // 0xe disconnect
758
+ , by_type ]// 0xf auth
759
+
760
+
761
+ function by_id(disp, pkt) {
762
+ disp.answer(pkt.pkt_id, pkt); }
763
+
764
+ function by_type(disp, pkt, ctx) {
765
+ disp.answer(pkt.type, pkt);
766
+ by_evt(disp, pkt, ctx);}
767
+
768
+ async function by_evt({target}, pkt, ctx) {
769
+ let fn = target[`mqtt_${pkt.type}`]
770
+ || target.mqtt_pkt;
771
+
772
+ await fn?.call(target, pkt, ctx);} })()) };
773
+
774
+ /*
775
+ on_mqtt_type = {
776
+ mqtt_auth(pkt, ctx) ::
777
+ mqtt_connect(pkt, ctx) ::
778
+ mqtt_connack(pkt, ctx) ::
779
+ mqtt_disconnect(pkt, ctx) ::
780
+
781
+ mqtt_publish(pkt, ctx)
782
+ mqtt_subscribe(pkt, ctx) ::
783
+ mqtt_unsubscribe(pkt, ctx) ::
784
+
785
+ mqtt_pingreq(pkt, ctx) ::
786
+ mqtt_pingresp(pkt, ctx) ::
787
+ }
788
+ */
789
+
790
+ function _mqtt_dispatch(opt, target) {
791
+ let _disp_ = _mqtt_cmdid_dispatch.create(target);
792
+ let { cmdids } = _disp_;
793
+
794
+ // default rotate at 1s across 5 buckets
795
+ let { td: rotate_td=1000, n: rotate_n=5 } =
796
+ opt && opt.rotate || {};
797
+
798
+ let rotate_ts = rotate_td + Date.now();
799
+
800
+ return [on_mqtt,
801
+ _disp_.bind_pkt_future()]
802
+
803
+ function on_mqtt(pkt_list, ctx) {
804
+ for (let pkt of pkt_list) {
805
+ cmdids[pkt.id](_disp_, pkt, ctx); }
806
+
807
+ if (Date.now() > rotate_ts) {
808
+ _disp_.rotate_belt(rotate_n);
809
+ rotate_ts = rotate_td + Date.now();} } }
810
+
811
+ class MQTTError extends Error {
812
+ constructor(mqtt_pkt, reason=mqtt_pkt.reason) {
813
+ super(`[0x${reason.toString(16)}] ${reason.reason}`);
814
+ this.mqtt_pkt = mqtt_pkt;
815
+ this.reason = reason;} }
816
+
817
+ class MQTTBase {
818
+ constructor(opt={}) {
819
+ this.with(opt);
820
+ this._conn_ = _mqtt_conn(this,
821
+ this._init_dispatch(opt, this)); }
822
+
823
+ with(fns_ns) {
824
+ for (let [k,v] of Object.entries(fns_ns)) {
825
+ if ('function' === typeof v) {this[k] = v;} }
826
+ return this}
827
+
828
+ async conn_emit(evt, arg, err_arg) {
829
+ this.log_conn?.(evt, arg, err_arg);
830
+ try {
831
+ let fn_evt = this[await evt]; // microtask break using `await evt`
832
+ if (fn_evt) {
833
+ await fn_evt.call(this, this, arg, err_arg);}
834
+ else if (err_arg) {throw err_arg} }
835
+ catch (err) {
836
+ this.on_error(err, evt);} }
837
+
838
+ on_error(err, evt) {
839
+ console.warn('[[u8-mqtt error: %s]]', evt, err); }
840
+
841
+ // Handshaking Packets
842
+
843
+ async connect(pkt={}) {
844
+ let cid = pkt.client_id || this.client_id;
845
+ if ('string' !== typeof cid) {
846
+ // see init_client_id implementation in core.jsy
847
+ pkt.client_id = cid = this.init_client_id(cid);}
848
+ this.client_id = cid;
849
+
850
+ if (null == pkt.keep_alive) {
851
+ pkt.keep_alive = 60;}
852
+
853
+ let res = await this._conn_
854
+ .send_connect('connect', pkt, 'connack');
855
+
856
+ if (0 != res[0].reason) {
857
+ throw new this.MQTTError(res[0])}
858
+
859
+ // TODO: merge with server's keep_alive frequency
860
+ this._conn_.ping(pkt.keep_alive);
861
+ return res}
862
+
863
+ async disconnect(pkt={}) {
864
+ let res = await this._send('disconnect', pkt);
865
+ this._conn_.reset(false);
866
+ return res}
867
+
868
+ auth(pkt={}) {
869
+ return this._send('auth', pkt, 'auth')}
870
+
871
+ ping() {return this._send('pingreq', null, 'pingresp')}
872
+ puback({pkt_id}) {return this._send('puback', {pkt_id})}
873
+
874
+ // alias: sub
875
+ subscribe(pkt, ex, topic_prefix) {
876
+ pkt = _as_topics(pkt, ex, topic_prefix);
877
+ let suback = this._send('subscribe', pkt, pkt);
878
+ return this.on_sub?.(suback, pkt) ?? suback}
879
+
880
+ // alias: unsub
881
+ unsubscribe(pkt, ex, topic_prefix) {
882
+ pkt = _as_topics(pkt, ex, topic_prefix);
883
+ return this._send('unsubscribe', pkt, pkt)}
884
+
885
+
886
+ post(topic, payload, pub_opt) {// qos:0
887
+ return this.pub({topic, payload, qos:0}, pub_opt)}
888
+ send(topic, payload, pub_opt) {// qos:1
889
+ return this.pub({topic, payload, qos:1}, pub_opt)}
890
+ store(topic, payload, pub_opt) {// qos:1, retain: 1
891
+ return this.pub({topic, payload, qos:1, retain: 1}, pub_opt)}
892
+
893
+ // alias: json_post
894
+ obj_post(topic, msg, pub_opt) {// qos:0
895
+ return this.pub({topic, msg, arg: 'msg', qos:0}, pub_opt)}
896
+ // alias: json_send
897
+ obj_send(topic, msg, pub_opt) {// qos:1
898
+ return this.pub({topic, msg, arg: 'msg', qos:1}, pub_opt)}
899
+ // alias: json_store
900
+ obj_store(topic, msg, pub_opt) {// qos:1, retain: 1
901
+ return this.pub({topic, msg, arg: 'msg', qos:1, retain: 1}, pub_opt)}
902
+
903
+ // alias: publish -- because 'pub' is shorter for semantic aliases above
904
+ async pub(pkt, pub_opt) {
905
+ if (undefined === pkt.payload) {
906
+ if ('function' === typeof pub_opt) {
907
+ pub_opt = {fn_encode: pub_opt};}
908
+
909
+ let {msg} = pkt;
910
+ switch (typeof msg) {
911
+ case 'function':
912
+ pub_opt = {...pub_opt, fn_encode: msg};
913
+ // flow into 'undefined' case
914
+ case 'undefined':
915
+ // return a single-value closure to publish packets
916
+ return v => this.pub({...pkt, [pkt.arg || 'payload']: v}, pub_opt)}
917
+
918
+ // Encode payload from msg; fn_encode allows alternative to JSON.stringify
919
+ let {fn_encode} = pub_opt || {};
920
+ pkt.payload = fn_encode
921
+ ? await fn_encode(msg)
922
+ : JSON.stringify(msg);}
923
+
924
+ if (pub_opt) {
925
+ if (pub_opt.props) {
926
+ pkt.props = pub_opt.props;}
927
+ if (pub_opt.xform) {
928
+ pkt = pub_opt.xform(pkt) || pkt;} }
929
+
930
+ return this._send('publish', pkt,
931
+ pkt.qos ? pkt : void 0 ) }// key
932
+
933
+
934
+ // Internal API
935
+
936
+ /* async _send(type, pkt) -- provided by _conn_ and transport */
937
+
938
+ _init_dispatch(opt) {
939
+ this.constructor?._once_();
940
+ let target ={__proto__: opt.on_mqtt_type};
941
+ target.mqtt_publish ||=
942
+ this._init_router?.(opt, this, target);
943
+ return _mqtt_dispatch(this, target)}
944
+
945
+ static _aliases() {
946
+ return ' publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store'}
947
+
948
+ static _once_(self=this) {
949
+ self._once_ = _=>0;
950
+ let p = self.prototype;
951
+ p.MQTTError = MQTTError;
952
+ for (let alias of self._aliases().split(/\s+/)) {
953
+ alias = alias.split(':');
954
+ let fn = alias[1] && p[alias[1]];
955
+ if (fn) {p[alias[0]] = fn;} } } }
956
+
957
+
958
+ function _as_topics(pkt, ex, topic_prefix) {
959
+ if (ex?.trim) {// string
960
+ topic_prefix = ex;
961
+ ex = null;}
962
+
963
+ pkt =(
964
+ pkt.trim // string
965
+ ? {topics:[pkt], ... ex}
966
+ : pkt[Symbol.iterator]
967
+ ? {topics:[... pkt], ... ex}
968
+ : ex ? {...pkt, ...ex}
969
+ : pkt);
970
+
971
+ if (topic_prefix) {
972
+ // particularly useful with shared queues, e.g.
973
+ // topic_prefix = '$share/some-queue-name/'
974
+ let _prefix_topics = v =>
975
+ v.trim ? topic_prefix+v : v.map(_prefix_topics);
976
+
977
+ pkt.topics = pkt.topics.map(_prefix_topics);}
978
+ return pkt}
979
+
980
+ const pkt_api = {
981
+ utf8(u8) { return new TextDecoder('utf-8').decode(u8 || this.payload ) },
982
+ json(u8) { return JSON.parse( this.utf8(u8) || null ) },
983
+ text(u8) { return this.utf8(u8) },
984
+ };
985
+
986
+ class MQTTCore extends MQTTBase {
987
+ static mqtt_ctx(mqtt_level, mqtt_opts, pkt_ctx=pkt_api) {
988
+ let self = class extends this {};
989
+ self.prototype.mqtt_ctx =
990
+ mqtt_pkt_ctx(mqtt_level, mqtt_opts, pkt_ctx);
991
+ return self}
992
+
993
+
994
+ // automatic Client Id for connect()
995
+ init_client_id(parts=['u8-mqtt--','']) {
996
+ let sess_stg=this.sess_stg;
997
+ let key, cid = sess_stg?.getItem(key=parts.join(' '));
998
+ if (! cid) {
999
+ cid = parts.join(Math.random().toString(36).slice(2));
1000
+ sess_stg?.setItem(key, cid);}
1001
+ return cid}
1002
+
1003
+ get sess_stg() {return globalThis.sessionStorage}
1004
+
1005
+
1006
+ //on_error(err, evt) ::
1007
+ // console.warn @ '[[u8-mqtt error: %s]]', evt, err
1008
+
1009
+ //log_conn(evt, arg, err_arg) ::
1010
+ // console.info @ '[[u8-mqtt log: %s]]', evt, arg, err_arg
1011
+
1012
+ on_live(client, is_reconnect) {
1013
+ if (is_reconnect) {
1014
+ return client.connect()} }
1015
+
1016
+ //on_reconnect(client) ::
1017
+
1018
+ _use_conn(fn_reconnect) {
1019
+ return (this.reconnect = fn_reconnect)?.()}
1020
+ with_autoreconnect(opt=2000) {
1021
+ if (opt.toFixed) {opt ={delay: opt};}
1022
+ return this.with({
1023
+ on_reconnect() {
1024
+ this.delay(opt.delay || 2000)
1025
+ .then(this.reconnect)
1026
+ .then(opt.reconnect, opt.error);} }) }
1027
+
1028
+ on_disconnect(client, intentional) {
1029
+ if (! intentional) {
1030
+ return client.on_reconnect?.()} }
1031
+
1032
+ delay(ms) {
1033
+ return new Promise(done => setTimeout(done, ms)) }
1034
+
1035
+ with_async_iter(async_iter, write_u8_pkt) {
1036
+ let on_mqtt_chunk = this._conn_.set(
1037
+ this.mqtt_ctx,
1038
+ write_u8_pkt);
1039
+
1040
+ this._msg_loop = ((async () => {
1041
+ try {
1042
+ async_iter = await async_iter;
1043
+ for await (let chunk of async_iter)
1044
+ on_mqtt_chunk(chunk);
1045
+ this._conn_.reset();}
1046
+ catch (err) {
1047
+ this._conn_.reset(err);} })());
1048
+
1049
+ return this}
1050
+
1051
+
1052
+
1053
+
1054
+
1055
+
1056
+
1057
+
1058
+
1059
+
1060
+
1061
+
1062
+
1063
+
1064
+
1065
+
1066
+
1067
+
1068
+
1069
+
1070
+
1071
+
1072
+
1073
+
1074
+
1075
+
1076
+
1077
+
1078
+
1079
+
1080
+
1081
+
1082
+
1083
+
1084
+
1085
+
1086
+
1087
+
1088
+
1089
+
1090
+
1091
+
1092
+
1093
+
1094
+
1095
+
1096
+
1097
+
1098
+
1099
+
1100
+
1101
+
1102
+ with_stream(read_stream, write_stream) {
1103
+ if (undefined === write_stream) {
1104
+ write_stream = read_stream;}
1105
+
1106
+ return this.with_async_iter(read_stream,
1107
+ u8_pkt => write_stream.write(u8_pkt)) }
1108
+
1109
+
1110
+ with_websock(websock) {
1111
+ if (! websock?.send) {
1112
+ websock = new URL(websock || 'ws://127.0.0.1:9001');
1113
+ return this._use_conn (() =>
1114
+ this.with_websock(
1115
+ new WebSocket(websock, ['mqtt'])) ) }
1116
+
1117
+ websock.binaryType = 'arraybuffer';
1118
+
1119
+ let ready, {readyState} = websock;
1120
+ if (1 !== readyState) {
1121
+ if (0 !== readyState) {
1122
+ throw new Error('Invalid WebSocket readyState') }
1123
+
1124
+ ready = new Promise(fn => websock.onopen = fn); }
1125
+
1126
+
1127
+ let {_conn_} = this;
1128
+ let on_mqtt_chunk = _conn_.set(
1129
+ this.mqtt_ctx,
1130
+ async u8_pkt =>(
1131
+ await ready
1132
+ , websock.send(u8_pkt)) );
1133
+
1134
+ websock.onmessage = evt =>(on_mqtt_chunk(new Uint8Array(evt.data)));
1135
+ websock.onclose = evt => {
1136
+ if (! evt.wasClean) {
1137
+ var err = new Error('websocket connection close');
1138
+ err.code = evt.code;
1139
+ err.reason = evt.reason;}
1140
+
1141
+ _conn_.reset(err);};
1142
+
1143
+ return this} }
1144
+
1145
+ const version = '0.5.1';
1146
+
1147
+ const MQTTClient_v4 = /* #__PURE__ */
1148
+ MQTTCore.mqtt_ctx(4, mqtt_opts_v4);
1149
+
1150
+ const mqtt_v4 = opt =>
1151
+ new MQTTClient_v4(opt);
1152
+
1153
+ export { MQTTClient_v4 as MQTTClient, MQTTClient_v4, mqtt_v4 as default, mqtt_v4 as mqtt, mqtt_v4, version };
1154
+ //# sourceMappingURL=basic-v4.js.map