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