u8-mqtt 0.5.1 → 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 +6 -3
@@ -0,0 +1,1785 @@
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
+ let mqtt_reader_v5$1 = class mqtt_reader_v5 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_connect(ns, mqtt_reader) {
323
+ class _connect_flags_ extends Number {
324
+ get reserved() { return this & 0x01 !== 0 }
325
+ get clean_start() { return this & 0x02 !== 0 }
326
+ get will_flag() { return this & 0x04 !== 0 }
327
+ get will_qos() { return (this >>> 3) & 0x3 }
328
+ get will_retain() { return this & 0x20 !== 0 }
329
+ get password() { return this & 0x40 !== 0 }
330
+ get username() { return this & 0x80 !== 0 }
331
+ }
332
+
333
+ return ns[0x1] = (pkt, u8_body) => {
334
+ let rdr = mqtt_reader.of(u8_body);
335
+ if ('MQTT' !== rdr.utf8())
336
+ throw new Error('Invalid mqtt_connect packet')
337
+
338
+ pkt._base_.mqtt_level = pkt.mqtt_level = rdr.u8();
339
+
340
+ let flags = pkt.flags =
341
+ rdr.flags(_connect_flags_);
342
+
343
+ pkt.keep_alive = rdr.u16();
344
+
345
+ if (5 <= pkt.mqtt_level)
346
+ pkt.props = rdr.props();
347
+
348
+
349
+
350
+ pkt.client_id = rdr.utf8();
351
+ if (flags.will_flag) {
352
+ let will = pkt.will = {};
353
+ if (5 <= pkt.mqtt_level)
354
+ will.props = rdr.props();
355
+
356
+ will.topic = rdr.utf8();
357
+ will.payload = rdr.bin();
358
+ will.qos = flags.will_qos;
359
+ will.retain = flags.will_retain;
360
+ }
361
+
362
+ if (flags.username)
363
+ pkt.username = rdr.utf8();
364
+
365
+ if (flags.password)
366
+ pkt.password = rdr.bin();
367
+ return pkt }
368
+ }
369
+
370
+ function mqtt_decode_connack(ns, mqtt_reader) {
371
+ class _connack_flags_ extends Number {
372
+ get session_present() { return this & 0x01 !== 0 }
373
+ }
374
+
375
+ return ns[0x2] = (pkt, u8_body) => {
376
+ let rdr = mqtt_reader.of(u8_body);
377
+
378
+ pkt.flags =
379
+ rdr.flags(_connack_flags_);
380
+
381
+ pkt.reason = rdr.reason(pkt.type);
382
+ if (5 <= pkt.mqtt_level)
383
+ pkt.props = rdr.props();
384
+ return pkt }
385
+ }
386
+
387
+
388
+ function _connack_v4(mqtt_reader) {
389
+ mqtt_reader.reasons('connack',
390
+ // MQTT 3.1.1
391
+ [ 0x00, 'Success'],
392
+ [ 0x01, 'Connection refused, unacceptable protocol version'],
393
+ [ 0x02, 'Connection refused, identifier rejected'],
394
+ [ 0x03, 'Connection refused, server unavailable'],
395
+ [ 0x04, 'Connection refused, bad user name or password'],
396
+ [ 0x05, 'Connection refused, not authorized'],
397
+ );
398
+ }
399
+
400
+ function _connack_v5(mqtt_reader) {
401
+ _connack_v4(mqtt_reader);
402
+
403
+ mqtt_reader.reasons('connack',
404
+ // MQTT 5.0
405
+ [ 0x81, 'Malformed Packet'],
406
+ [ 0x82, 'Protocol Error'],
407
+ [ 0x83, 'Implementation specific error'],
408
+ [ 0x84, 'Unsupported Protocol Version'],
409
+ [ 0x85, 'Client Identifier not valid'],
410
+ [ 0x86, 'Bad User Name or Password'],
411
+ [ 0x87, 'Not authorized'],
412
+ [ 0x88, 'Server unavailable'],
413
+ [ 0x89, 'Server busy'],
414
+ [ 0x8A, 'Banned'],
415
+ [ 0x8C, 'Bad authentication method'],
416
+ [ 0x90, 'Topic Name invalid'],
417
+ [ 0x95, 'Packet too large'],
418
+ [ 0x97, 'Quota exceeded'],
419
+ [ 0x99, 'Payload format invalid'],
420
+ [ 0x9A, 'Retain not supported'],
421
+ [ 0x9B, 'QoS not supported'],
422
+ [ 0x9C, 'Use another server'],
423
+ [ 0x9D, 'Server moved'],
424
+ [ 0x9F, 'Connection rate exceeded'],
425
+ );
426
+ }
427
+
428
+ function mqtt_decode_publish(ns, mqtt_reader) {
429
+ return ns[0x3] = (pkt, u8_body) => {
430
+ let {hdr} = pkt;
431
+ pkt.dup = Boolean(hdr & 0x8);
432
+ pkt.retain = Boolean(hdr & 0x1);
433
+ let qos = pkt.qos = (hdr>>1) & 0x3;
434
+
435
+ let rdr = mqtt_reader.of(u8_body);
436
+ pkt.topic = rdr.utf8();
437
+ if (0 !== qos)
438
+ pkt.pkt_id = rdr.u16();
439
+
440
+ if (5 <= pkt.mqtt_level)
441
+ pkt.props = rdr.props();
442
+
443
+ pkt.payload = rdr.flush();
444
+ return pkt }
445
+ }
446
+
447
+ function mqtt_decode_puback(ns, mqtt_reader) {
448
+ return ns[0x4] = (pkt, u8_body) => {
449
+ let rdr = mqtt_reader.of(u8_body);
450
+
451
+ pkt.pkt_id = rdr.u16();
452
+ if (5 <= pkt.mqtt_level) {
453
+ pkt.reason = rdr.reason(pkt.type);
454
+ pkt.props = rdr.props();
455
+ }
456
+
457
+ return pkt }
458
+ }
459
+
460
+
461
+ function _puback_v5(mqtt_reader) {
462
+ mqtt_reader.reasons('puback',
463
+ // MQTT 5.0
464
+ [ 0x00, 'Success'],
465
+ [ 0x10, 'No matching subscribers'],
466
+ [ 0x80, 'Unspecified error'],
467
+ [ 0x83, 'Implementation specific error'],
468
+ [ 0x87, 'Not authorized'],
469
+ [ 0x90, 'Topic Name invalid'],
470
+ [ 0x91, 'Packet identifier in use'],
471
+ [ 0x97, 'Quota exceeded'],
472
+ [ 0x99, 'Payload format invalid'],
473
+ );
474
+ }
475
+
476
+ function mqtt_decode_pubxxx(ns, mqtt_reader) {
477
+ return ns[0x5] = ns[0x6] = ns[0x7] = (pkt, u8_body) => {
478
+ let rdr = mqtt_reader.of(u8_body);
479
+
480
+ pkt.pkt_id = rdr.u16();
481
+ pkt.reason = rdr.reason('pubxxx', mqtt_reader);
482
+ if (5 <= pkt.mqtt_level)
483
+ pkt.props = rdr.props();
484
+ return pkt }
485
+ }
486
+
487
+ function _pubxxx_v4(mqtt_reader) {
488
+ mqtt_reader.reasons('pubxxx',
489
+ // MQTT 3.1.1
490
+ [ 0x00, 'Success' ],
491
+ [ 0x92, 'Packet Identifier not found' ],
492
+ );
493
+ }
494
+
495
+ function mqtt_decode_subscribe(ns, mqtt_reader) {
496
+ class _subscription_options_ extends Number {
497
+ get qos() { return this & 0x3 }
498
+ get retain() { return this & 0x4 !== 0 }
499
+ get retain_handling() { return (this >> 2) & 0x3 }
500
+ }
501
+
502
+ return ns[0x8] = (pkt, u8_body) => {
503
+ let rdr = mqtt_reader.of(u8_body);
504
+
505
+ pkt.pkt_id = rdr.u16();
506
+ if (5 <= pkt.mqtt_level)
507
+ pkt.props = rdr.props();
508
+
509
+ let topic, opts, topic_list = pkt.topics = [];
510
+ while (rdr.has_more()) {
511
+ topic = rdr.utf8();
512
+ opts = rdr.flags(_subscription_options_);
513
+ topic_list.push({topic, opts});
514
+ }
515
+
516
+ return pkt }
517
+ }
518
+
519
+ function _mqtt_decode_suback(mqtt_reader) {
520
+ return (pkt, u8_body) => {
521
+ let rdr = mqtt_reader.of(u8_body);
522
+
523
+ pkt.pkt_id = rdr.u16();
524
+ if (5 <= pkt.mqtt_level)
525
+ pkt.props = rdr.props();
526
+
527
+ let answers = pkt.answers = [];
528
+ while (rdr.has_more())
529
+ answers.push(
530
+ rdr.reason(pkt.type) );
531
+
532
+ return pkt }
533
+ }
534
+
535
+ function mqtt_decode_suback(ns, mqtt_reader) {
536
+ return ns[0x9] = _mqtt_decode_suback(mqtt_reader)
537
+ }
538
+
539
+ function _suback_v4(mqtt_reader) {
540
+ mqtt_reader.reasons('suback',
541
+ // MQTT 3.1.1
542
+ [ 0x00, 'Granted QoS 0'],
543
+ [ 0x01, 'Granted QoS 1'],
544
+ [ 0x02, 'Granted QoS 2'],
545
+ );
546
+ }
547
+
548
+ function _suback_v5(mqtt_reader) {
549
+ _suback_v4(mqtt_reader);
550
+
551
+ mqtt_reader.reasons('suback',
552
+ // MQTT 5.0
553
+ [ 0x80, 'Unspecified error'],
554
+ [ 0x83, 'Implementation specific error'],
555
+ [ 0x87, 'Not authorized'],
556
+ [ 0x8F, 'Topic Filter invalid'],
557
+ [ 0x91, 'Packet Identifier in use'],
558
+ [ 0x97, 'Quota exceeded'],
559
+ [ 0x9E, 'Shared Subscriptions not supported'],
560
+ [ 0xA1, 'Subscription Identifiers not supported'],
561
+ [ 0xA2, 'Wildcard Subscriptions not supported'],
562
+ );
563
+ }
564
+
565
+ function mqtt_decode_unsubscribe(ns, mqtt_reader) {
566
+ return ns[0xa] = (pkt, u8_body) => {
567
+ let rdr = mqtt_reader.of(u8_body);
568
+
569
+ pkt.pkt_id = rdr.u16();
570
+ if (5 <= pkt.mqtt_level)
571
+ pkt.props = rdr.props();
572
+
573
+ let topic_list = pkt.topics = [];
574
+ while (rdr.has_more())
575
+ topic_list.push(rdr.utf8());
576
+
577
+ return pkt }
578
+ }
579
+
580
+ function mqtt_decode_unsuback(ns, mqtt_reader) {
581
+ return ns[0xb] = _mqtt_decode_suback(mqtt_reader)
582
+ }
583
+
584
+ function _unsuback_v4(mqtt_reader) {
585
+ mqtt_reader.reasons('unsuback',
586
+ // MQTT 3.1.1
587
+ [ 0x00, 'Success'],
588
+ [ 0x11, 'No subscription existed'],
589
+ [ 0x80, 'Unspecified error'],
590
+ [ 0x83, 'Implementation specific error'],
591
+ [ 0x87, 'Not authorized'],
592
+ [ 0x8F, 'Topic Filter invalid'],
593
+ [ 0x91, 'Packet Identifier in use'],
594
+ );
595
+ }
596
+
597
+ function mqtt_decode_pingxxx(ns) {
598
+ return ns[0xc] = ns[0xd] = pkt => pkt
599
+ }
600
+
601
+ function mqtt_decode_disconnect(ns, mqtt_reader) {
602
+ return ns[0xe] = (pkt, u8_body) => {
603
+ if (u8_body && 5 <= pkt.mqtt_level) {
604
+ let rdr = mqtt_reader.of(u8_body);
605
+ pkt.reason = rdr.reason(pkt.type);
606
+ pkt.props = rdr.props();
607
+ }
608
+ return pkt }
609
+ }
610
+
611
+
612
+ function _disconnect_v5(mqtt_reader) {
613
+ mqtt_reader.reasons('disconnect',
614
+ // MQTT 5.0
615
+ [ 0x00, 'Normal disconnection'],
616
+ [ 0x04, 'Disconnect with Will Message'],
617
+ [ 0x80, 'Unspecified error'],
618
+ [ 0x81, 'Malformed Packet'],
619
+ [ 0x82, 'Protocol Error'],
620
+ [ 0x83, 'Implementation specific error'],
621
+ [ 0x87, 'Not authorized'],
622
+ [ 0x89, 'Server busy'],
623
+ [ 0x8B, 'Server shutting down'],
624
+ [ 0x8D, 'Keep Alive timeout'],
625
+ [ 0x8E, 'Session taken over'],
626
+ [ 0x8F, 'Topic Filter invalid'],
627
+ [ 0x90, 'Topic Name invalid'],
628
+ [ 0x93, 'Receive Maximum exceeded'],
629
+ [ 0x94, 'Topic Alias invalid'],
630
+ [ 0x95, 'Packet too large'],
631
+ [ 0x96, 'Message rate too high'],
632
+ [ 0x97, 'Quota exceeded'],
633
+ [ 0x98, 'Administrative action'],
634
+ [ 0x99, 'Payload format invalid'],
635
+ [ 0x9A, 'Retain not supported'],
636
+ [ 0x9B, 'QoS not supported'],
637
+ [ 0x9C, 'Use another server'],
638
+ [ 0x9D, 'Server moved'],
639
+ [ 0x9E, 'Shared Subscriptions not supported'],
640
+ [ 0x9F, 'Connection rate exceeded'],
641
+ [ 0xA0, 'Maximum connect time'],
642
+ [ 0xA1, 'Subscription Identifiers not supported'],
643
+ [ 0xA2, 'Wildcard Subscriptions not supported'],
644
+ );
645
+ }
646
+
647
+ function mqtt_decode_auth(ns, mqtt_reader) {
648
+ return ns[0xf] = (pkt, u8_body) => {
649
+ if ( 5 <= pkt.mqtt_level ) {
650
+ let rdr = mqtt_reader.of(u8_body);
651
+ pkt.reason = rdr.reason(pkt.type);
652
+ pkt.props = rdr.props();
653
+ }
654
+ return pkt }
655
+ }
656
+
657
+
658
+ function _auth_v5(mqtt_reader) {
659
+ mqtt_reader.reasons('auth',
660
+ // MQTT 5.0
661
+ [ 0x00, 'Success' ],
662
+ [ 0x18, 'Continue authentication' ],
663
+ [ 0x19, 'Re-authenticate' ],
664
+ );
665
+ }
666
+
667
+ function mqtt_encode_connect(ns, mqtt_writer) {
668
+ const _c_mqtt_proto = new Uint8Array([
669
+ 0, 4, 0x4d, 0x51, 0x54, 0x54 ]);
670
+
671
+ const _enc_flags_connect = flags => 0
672
+ | ( flags.reserved ? 0x01 : 0 )
673
+ | ( (flags.will_qos & 0x3) << 3 )
674
+ | ( flags.clean_start ? 0x02 : 0 )
675
+ | ( flags.will_flag ? 0x04 : 0 )
676
+ | ( flags.will_retain ? 0x20 : 0 )
677
+ | ( flags.password ? 0x40 : 0 )
678
+ | ( flags.username ? 0x80 : 0 );
679
+
680
+ const _enc_flags_will = will => 0x4
681
+ | ( (will.qos & 0x3) << 3 )
682
+ | ( will.retain ? 0x20 : 0 );
683
+
684
+ return ns.connect = ( mqtt_level, pkt ) => {
685
+ let wrt = mqtt_writer.of(pkt);
686
+
687
+ wrt.push(_c_mqtt_proto);
688
+ wrt.u8( mqtt_level );
689
+
690
+ let {will, username, password} = pkt;
691
+ let flags = wrt.flags(
692
+ pkt.flags,
693
+ _enc_flags_connect,
694
+ 0 | (username ? 0x80 : 0)
695
+ | (password ? 0x40 : 0)
696
+ | (will ? _enc_flags_will(will) : 0) );
697
+
698
+ wrt.u16(pkt.keep_alive);
699
+
700
+ if (5 <= mqtt_level)
701
+ wrt.props(pkt.props);
702
+
703
+
704
+ wrt.utf8(pkt.client_id);
705
+ if (flags & 0x04) { // .will_flag
706
+ if (5 <= mqtt_level)
707
+ wrt.props(will.props);
708
+
709
+ wrt.utf8(will.topic);
710
+ wrt.bin(will.payload);
711
+ }
712
+
713
+ if (flags & 0x80) // .username
714
+ wrt.utf8(username);
715
+
716
+ if (flags & 0x40) // .password
717
+ wrt.bin(password);
718
+
719
+ return wrt.as_pkt(0x10)
720
+ }
721
+ }
722
+
723
+ function mqtt_encode_connack(ns, mqtt_writer) {
724
+ const _enc_flags_connack = flags =>
725
+ flags.session_present ? 1 : 0;
726
+
727
+ return ns.connack = (mqtt_level, pkt) => {
728
+ let wrt = mqtt_writer.of(pkt);
729
+
730
+ wrt.flags( pkt.flags, _enc_flags_connack );
731
+
732
+ if (5 <= mqtt_level) {
733
+ wrt.reason( pkt.reason );
734
+ wrt.props( pkt.props );
735
+
736
+ } else {
737
+ wrt.reason( pkt.return_code || pkt.reason );
738
+ }
739
+
740
+ return wrt.as_pkt(0x20)
741
+ }
742
+ }
743
+
744
+ function mqtt_encode_publish(ns, mqtt_writer) {
745
+ return ns.publish = ( mqtt_level, pkt ) => {
746
+ let qos = (pkt.qos & 0x3) << 1;
747
+ let wrt = mqtt_writer.of(pkt);
748
+
749
+ wrt.utf8(pkt.topic);
750
+ if (0 !== qos)
751
+ wrt.u16(pkt.pkt_id);
752
+
753
+ if ( 5 <= mqtt_level) {
754
+ wrt.props(pkt.props);
755
+ wrt.flush(pkt.payload);
756
+ } else {
757
+ wrt.flush(pkt.payload);
758
+ }
759
+
760
+ return wrt.as_pkt(
761
+ 0x30 | qos | (pkt.dup ? 0x8 : 0) | (pkt.retain ? 0x1 : 0) )
762
+ }
763
+ }
764
+
765
+ function mqtt_encode_puback(ns, mqtt_writer) {
766
+ return ns.puback = ( mqtt_level, pkt ) => {
767
+ let wrt = mqtt_writer.of(pkt);
768
+
769
+ wrt.u16(pkt.pkt_id);
770
+ if (5 <= mqtt_level) {
771
+ wrt.reason(pkt.reason);
772
+ wrt.props(pkt.props);
773
+ }
774
+
775
+ return wrt.as_pkt(0x40)
776
+ }
777
+ }
778
+
779
+ function mqtt_encode_pubxxx(ns, mqtt_writer) {
780
+ ns.pubrec = _enc_pubxxx(0x50);
781
+ ns.pubrel = _enc_pubxxx(0x62);
782
+ ns.pubcomp = _enc_pubxxx(0x70);
783
+
784
+
785
+ function _enc_pubxxx(hdr) {
786
+ return ( mqtt_level, pkt ) => {
787
+ let wrt = mqtt_writer.of(pkt);
788
+
789
+ wrt.u16(pkt.pkt_id);
790
+ if (5 <= mqtt_level) {
791
+ wrt.props(pkt.props);
792
+ wrt.reason(pkt.reason);
793
+
794
+ } else {
795
+ wrt.reason( pkt.return_code || pkt.reason );
796
+ }
797
+
798
+ return wrt.as_pkt(hdr)
799
+ }
800
+ }
801
+ }
802
+
803
+ function mqtt_encode_subscribe(ns, mqtt_writer) {
804
+ const _enc_subscribe_flags = opts => 0
805
+ | ( opts.qos & 0x3 )
806
+ | ( opts.retain ? 0x4 : 0 )
807
+ | ( (opts.retain_handling & 0x3) << 2 );
808
+
809
+ return ns.subscribe = ( mqtt_level, pkt ) => {
810
+ let wrt = mqtt_writer.of(pkt);
811
+
812
+ wrt.u16(pkt.pkt_id);
813
+ if (5 <= mqtt_level)
814
+ wrt.props(pkt.props);
815
+
816
+ let f0 = _enc_subscribe_flags(pkt);
817
+ for (let each of pkt.topics) {
818
+ if ('string' === typeof each) {
819
+ wrt.utf8(each);
820
+ wrt.u8(f0);
821
+ } else {
822
+ let [topic, opts] =
823
+ Array.isArray(each) ? each
824
+ : [each.topic, each.opts];
825
+
826
+ wrt.utf8(topic);
827
+ if (undefined === opts) wrt.u8(f0);
828
+ else wrt.flags(opts, _enc_subscribe_flags);
829
+ }
830
+ }
831
+
832
+ return wrt.as_pkt(0x82)
833
+ }
834
+ }
835
+
836
+ function mqtt_encode_xxsuback(ns, mqtt_writer) {
837
+ ns.suback = _enc_xxsuback(0x90);
838
+ ns.unsuback = _enc_xxsuback(0xb0);
839
+
840
+
841
+ function _enc_xxsuback(hdr) {
842
+ return ( mqtt_level, pkt ) => {
843
+ let wrt = mqtt_writer.of(pkt);
844
+
845
+ wrt.u16(pkt.pkt_id);
846
+ if (5 <= mqtt_level)
847
+ wrt.props(pkt.props);
848
+
849
+ for (let ans of pkt.answers)
850
+ wrt.reason(ans);
851
+
852
+ return wrt.as_pkt(hdr)
853
+ }
854
+ }
855
+ }
856
+
857
+ function mqtt_encode_unsubscribe(ns, mqtt_writer) {
858
+ return ns.unsubscribe = ( mqtt_level, pkt ) => {
859
+ let wrt = mqtt_writer.of(pkt);
860
+
861
+ wrt.u16(pkt.pkt_id);
862
+ if (5 <= mqtt_level)
863
+ wrt.props(pkt.props);
864
+
865
+ for (let topic of pkt.topics)
866
+ wrt.utf8(topic);
867
+
868
+ return wrt.as_pkt(0xa2)
869
+ }
870
+ }
871
+
872
+ function mqtt_encode_pingxxx(ns) {
873
+ ns.pingreq = () => new Uint8Array([ 0xc0, 0 ]);
874
+ ns.pingresp = () => new Uint8Array([ 0xd0, 0 ]);
875
+ }
876
+
877
+ function mqtt_encode_disconnect(ns, mqtt_writer) {
878
+ return ns.disconnect = ( mqtt_level, pkt ) => {
879
+ let wrt = mqtt_writer.of(pkt);
880
+
881
+ if (pkt && 5 <= mqtt_level) {
882
+ if (pkt.reason || pkt.props) {
883
+ wrt.reason(pkt.reason);
884
+ wrt.props(pkt.props);
885
+ }
886
+ }
887
+
888
+ return wrt.as_pkt(0xe0)
889
+ }
890
+ }
891
+
892
+ function mqtt_encode_auth(ns, mqtt_writer) {
893
+ return ns.auth = ( mqtt_level, pkt ) => {
894
+ if (5 > mqtt_level)
895
+ throw new Error('Auth packets are only available after MQTT 5.x')
896
+
897
+ let wrt = mqtt_writer.of(pkt);
898
+
899
+ wrt.reason(pkt.reason);
900
+ wrt.props(pkt.props);
901
+
902
+ return wrt.as_pkt(0xf0)
903
+ }
904
+ }
905
+
906
+ const mqtt_reader_v5 = /* #__PURE__ */
907
+ mqtt_reader_info(
908
+ mqtt_reader_v5$1,
909
+ _connack_v5,
910
+ _puback_v5,
911
+ _pubxxx_v4,
912
+ _suback_v5,
913
+ _unsuback_v4,
914
+ _disconnect_v5,
915
+ _auth_v5,
916
+ );
917
+
918
+ const mqtt_decode_v5 = [
919
+ mqtt_decode_connect,
920
+ mqtt_decode_connack,
921
+ mqtt_decode_publish,
922
+ mqtt_decode_puback,
923
+ mqtt_decode_pubxxx,
924
+ mqtt_decode_subscribe,
925
+ mqtt_decode_suback,
926
+ mqtt_decode_unsubscribe,
927
+ mqtt_decode_unsuback,
928
+ mqtt_decode_pingxxx,
929
+ mqtt_decode_disconnect,
930
+ mqtt_decode_auth,
931
+ ];
932
+
933
+
934
+ const mqtt_encode_v5 = [
935
+ mqtt_encode_connect,
936
+ mqtt_encode_connack,
937
+ mqtt_encode_publish,
938
+ mqtt_encode_puback,
939
+ mqtt_encode_pubxxx,
940
+ mqtt_encode_subscribe,
941
+ mqtt_encode_xxsuback,
942
+ mqtt_encode_unsubscribe,
943
+ mqtt_encode_pingxxx,
944
+ mqtt_encode_disconnect,
945
+ mqtt_encode_auth,
946
+ ];
947
+
948
+
949
+ const mqtt_opts_v5 =
950
+ { decode_fns: mqtt_decode_v5,
951
+ mqtt_reader: mqtt_reader_v5,
952
+ encode_fns: mqtt_encode_v5,
953
+ mqtt_writer: mqtt_writer_v5, };
954
+
955
+ function parse(str, loose) {
956
+ if (str instanceof RegExp) return { keys:false, pattern:str };
957
+ var c, o, tmp, ext, keys=[], pattern='', arr = str.split('/');
958
+ arr[0] || arr.shift();
959
+
960
+ while (tmp = arr.shift()) {
961
+ c = tmp[0];
962
+ if (c === '*') {
963
+ keys.push('wild');
964
+ pattern += '/(.*)';
965
+ } else if (c === ':') {
966
+ o = tmp.indexOf('?', 1);
967
+ ext = tmp.indexOf('.', 1);
968
+ keys.push( tmp.substring(1, !!~o ? o : !!~ext ? ext : tmp.length) );
969
+ pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';
970
+ if (!!~ext) pattern += (!!~o ? '?' : '') + '\\' + tmp.substring(ext);
971
+ } else {
972
+ pattern += '/' + tmp;
973
+ }
974
+ }
975
+
976
+ return {
977
+ keys: keys,
978
+ pattern: new RegExp('^' + pattern + (loose ? '(?=$|\/)' : '\/?$'), 'i')
979
+ };
980
+ }
981
+
982
+ /*
983
+ class AbstractTopicRouter ::
984
+ async invoke(pkt, ctx) ::
985
+ add(topic_route, ...args) ::
986
+ remove(topic_route, priority) ::
987
+ clear(priority) ::
988
+ find(topic) :: // optional
989
+ mqtt_topic(topic_route)
990
+ */
991
+
992
+ const with_topic_router = mqtt_topic_router =>
993
+ MQTTKlass => class extends MQTTKlass {
994
+ static _aliases() {
995
+ return super._aliases() +
996
+ ' sub_topic:subscribe_topic unsub_topic:unsubscribe_topic'}
997
+
998
+ _init_router(opt, self, target) {
999
+ this._subs = [];
1000
+ let router = this.router = target.router =
1001
+ mqtt_topic_router(opt, this, target);
1002
+ return router?.invoke}
1003
+
1004
+ on_sub(suback, pkt) {
1005
+ suback.pkt = pkt;
1006
+ this._subs.push(suback);
1007
+ return suback}
1008
+ subs_settled() {
1009
+ return Promise.allSettled(
1010
+ this._subs.splice(0,Infinity)) }
1011
+
1012
+ // alias: sub_topic
1013
+ subscribe_topic(topic_route, ...args) {
1014
+ let router = this.router;
1015
+ router.add(topic_route, true, args.pop() );// handler
1016
+ let topic = router.mqtt_topic(topic_route);
1017
+ this.subscribe(topic, ...args );// ex, topic_prefix
1018
+ return this }// fluent api -- return this and track side effects
1019
+
1020
+ // alias: unsub_topic
1021
+ unsubscribe_topic(topic_route, ...args) {
1022
+ let router = this.router;
1023
+ router.remove(topic_route, true);
1024
+ let topic = router.mqtt_topic(topic_route);
1025
+ return this.unsubscribe(topic, ...args ) }// topic_prefix
1026
+
1027
+ // add topic handlers without corresponding subscribe packet
1028
+ on_topic(...args) {
1029
+ this.router.add(...args);
1030
+ return this} };
1031
+
1032
+ // Use [regexparam][] for url-like topic parsing
1033
+ // [regexparam]: https://github.com/lukeed/regexparam
1034
+
1035
+
1036
+ const with_topic_path_router = /* #__PURE__ */
1037
+ with_topic_router(mqtt_topic_path_router);
1038
+
1039
+
1040
+ const mqtt_topic = topic_route =>
1041
+ topic_route
1042
+ .replace(/[*].*$/, '#')
1043
+ .replace(/:\w[^\/]*/g, '+');
1044
+
1045
+ /* From the [MQTT v5 Spec](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Topic_Names_and)
1046
+ 4.7.1.2 Multi-level wildcard -- (‘#’ U+0023)
1047
+ ... MUST be specified either on its own or following a topic level separator.
1048
+ In either case it MUST be the last character specified in the Topic Filter
1049
+
1050
+ 4.7.1.3 Single-level wildcard -- (‘+’ U+002B)
1051
+ ...it MUST occupy an entire level of the filter.
1052
+ */
1053
+
1054
+ const as_topic_path = (topic_route, id) =>(
1055
+ id=1,
1056
+ topic_route
1057
+ .replace(/#$/, '*' )// replace MQTT '#' multi-level wildcard at end
1058
+ .replace(/\+/g, () => `:$${id++}` ) );// replace MQTT '+' single-level wildcards
1059
+
1060
+ function _ignore(pkt, params, ctx) {ctx.done = true;}
1061
+
1062
+ function mqtt_topic_path_router() {
1063
+ let pri_lsts = [[],[]], rm = Symbol();
1064
+ let find = topic => _routes_iter(pri_lsts, topic);
1065
+
1066
+ // return duck-type compatible with AbstractTopicRouter in ./with_topic_router
1067
+ return {find, mqtt_topic,
1068
+ add(topic_route, ...args) {
1069
+ let fn = args.pop();
1070
+ let priority = args.pop();
1071
+
1072
+ if ('function' !== typeof fn) {
1073
+ if (fn) {throw new TypeError()}
1074
+ fn = _ignore;}
1075
+
1076
+ let rte = parse(as_topic_path(topic_route));
1077
+
1078
+ rte.key = topic_route;
1079
+ rte.tgt = fn;
1080
+ pri_lsts[priority ? 0 : 1].push(rte);
1081
+ return this}
1082
+
1083
+ , remove(topic_route, priority) {
1084
+ let lst = pri_lsts[priority ? 0 : 1];
1085
+ return _route_remove([lst], topic_route)}
1086
+
1087
+ , clear(priority) {
1088
+ pri_lsts[priority ? 0 : 1] = [];
1089
+ if (null == priority) {
1090
+ pri_lsts[1] = []; } }// null clears both lists
1091
+
1092
+ , async invoke(pkt, ctx) {
1093
+ ctx.idx = 0;
1094
+ ctx.rm = rm;
1095
+
1096
+ for (let [fn, params] of find(pkt.topic)) {
1097
+ let res = await fn(pkt, params, ctx);
1098
+
1099
+ if (rm === res) {
1100
+ _route_remove(pri_lsts, fn);}
1101
+
1102
+ if (ctx.done) {
1103
+ break}
1104
+ else ctx.idx++;}
1105
+
1106
+ if (1 === pkt.qos) {
1107
+ await ctx.mqtt.puback(pkt);} } } }
1108
+
1109
+
1110
+ function * _routes_iter(all_route_lists, topic) {
1111
+ topic = topic.replace(/^[\/]*/, '/'); // ensure '/' prefix for regexparam library
1112
+ for (let route_list of all_route_lists) {
1113
+ for (let {keys, pattern, tgt} of route_list) {
1114
+ let match = pattern.exec(topic);
1115
+ if (match) {
1116
+ let params = keys
1117
+ ? keys.reduce(
1118
+ (o, k, i) => (o[k] = match[1+i], o)
1119
+ , {})
1120
+ : match.groups ?? match;
1121
+ yield [tgt, params];} } } }
1122
+
1123
+
1124
+ function _route_remove(all_route_lists, query) {
1125
+ let fn_match = route =>(
1126
+ route===query
1127
+ || route.tgt===query
1128
+ || route.key===query);
1129
+ for (let lst of all_route_lists) {
1130
+ let i = lst.findIndex(fn_match);
1131
+ if (0 <= i) {
1132
+ lst.splice(i,1);
1133
+ return true} }
1134
+ return false}
1135
+
1136
+ /*
1137
+ export function decode_varint_loop(u8, i=0) {
1138
+ let i0 = i
1139
+ let shift = 0, n = (u8[i] & 0x7f)
1140
+ while ( 0x80 & u8[i++] )
1141
+ n |= (u8[i] & 0x7f) << (shift += 7)
1142
+
1143
+ return [n, i, i0]
1144
+ }
1145
+ */
1146
+
1147
+
1148
+ function decode_varint(u8, i=0) {
1149
+ let i0 = i;
1150
+ // unrolled for a max of 4 chains
1151
+ let n = (u8[i] & 0x7f) << 0;
1152
+ if ( 0x80 & u8[i++] ) {
1153
+ n |= (u8[i] & 0x7f) << 7;
1154
+ if ( 0x80 & u8[i++] ) {
1155
+ n |= (u8[i] & 0x7f) << 14;
1156
+ if ( 0x80 & u8[i++] ) {
1157
+ n |= (u8[i] & 0x7f) << 21;
1158
+ }
1159
+ }
1160
+ }
1161
+ return [n, i, i0]
1162
+ }
1163
+
1164
+ function mqtt_raw_dispatch(opt) {
1165
+ let u8 = new Uint8Array(0);
1166
+ return u8_buf => {
1167
+ u8 = 0 === u8.byteLength
1168
+ ? u8_buf : _u8_join(u8, u8_buf);
1169
+
1170
+ let res = [];
1171
+ while (1) {
1172
+ let [len_body, len_vh] = decode_varint(u8, 1);
1173
+ let len_pkt = len_body + len_vh;
1174
+
1175
+ if ( u8.byteLength < len_pkt )
1176
+ return res
1177
+
1178
+ let b0 = u8[0];
1179
+ let u8_body = 0 === len_body ? null
1180
+ : u8.subarray(len_vh, len_pkt);
1181
+
1182
+ u8 = u8.subarray(len_pkt);
1183
+
1184
+ let pkt = opt.decode_pkt(b0, u8_body, opt);
1185
+ if (null != pkt)
1186
+ res.push( pkt );
1187
+ }
1188
+ }
1189
+ }
1190
+
1191
+ function _u8_join(a, b) {
1192
+ let alen = a.byteLength, r = new Uint8Array(alen + b.byteLength);
1193
+ r.set(a, 0);
1194
+ r.set(b, alen);
1195
+ return r
1196
+ }
1197
+
1198
+ const _pkt_types = ['~', 'connect', 'connack', 'publish', 'puback', 'pubrec', 'pubrel', 'pubcomp', 'subscribe', 'suback', 'unsubscribe', 'unsuback', 'pingreq', 'pingresp', 'disconnect', 'auth'];
1199
+
1200
+ function mqtt_pkt_ctx(mqtt_level, opts, pkt_ctx) {
1201
+ pkt_ctx = {
1202
+ __proto__: pkt_ctx || opts.pkt_ctx,
1203
+ mqtt_level,
1204
+ get hdr() { return this.b0 & 0xf },
1205
+ get id() { return this.b0 >>> 4 },
1206
+ get type() { return _pkt_types[this.b0 >>> 4] },
1207
+ };
1208
+
1209
+ let op, _decode_by_id=[], _encode_by_type={};
1210
+ for (op of opts.encode_fns)
1211
+ op(_encode_by_type, opts.mqtt_writer);
1212
+ for (op of opts.decode_fns)
1213
+ op(_decode_by_id, opts.mqtt_reader);
1214
+
1215
+ return {
1216
+ pkt_ctx,
1217
+
1218
+ encode_pkt(type, pkt) {
1219
+ return _encode_by_type[type]( mqtt_level, pkt ) },
1220
+
1221
+ decode_pkt(b0, u8_body) {
1222
+ if (b0.map) // Uint8Array in first arg
1223
+ return mqtt_raw_dispatch(this)(b0)[0]
1224
+
1225
+ let fn_decode = _decode_by_id[b0>>>4] || _decode_by_id[0];
1226
+ return fn_decode?.({__proto__: this.pkt_ctx, b0}, u8_body) },
1227
+
1228
+ mqtt_stream() {
1229
+ let self = { __proto__: this, pkt_ctx: { __proto__: pkt_ctx } };
1230
+ self.pkt_ctx._base_ = self.pkt_ctx;
1231
+ self.decode = mqtt_raw_dispatch(self);
1232
+ return self
1233
+ },
1234
+ }
1235
+ }
1236
+
1237
+ function ao_defer_ctx(as_res = (...args) => args) {
1238
+ let y,n,_pset = (a,b) => { y=a, n=b; };
1239
+ return p =>(
1240
+ p = new Promise(_pset)
1241
+ , as_res(p, y, n)) }
1242
+
1243
+ const ao_defer_v = /* #__PURE__ */
1244
+ ao_defer_ctx();
1245
+
1246
+ Promise.resolve({type:'init'});
1247
+
1248
+ function _mqtt_conn(client, [on_mqtt, pkt_future]) {
1249
+ let _q_init = ao_defer_v(), _q_ready = ao_defer_v();
1250
+ let _send_ready = async (...args) => (await _q_ready[0])(...args);
1251
+ let _send_mqtt_pkt, _has_connected;
1252
+ client._send = _send_ready;
1253
+
1254
+ return {
1255
+ async when_ready() {await _q_ready[0];}
1256
+
1257
+ , ping: _ping_interval (() =>_send_mqtt_pkt?.('pingreq'))
1258
+
1259
+ , reset(err) {
1260
+ if (! _send_mqtt_pkt) {return}
1261
+
1262
+ if (err) {
1263
+ _q_init[2](err);}
1264
+
1265
+ _send_mqtt_pkt = null;
1266
+ _q_init = ao_defer_v();
1267
+ client._send = _send_ready;
1268
+
1269
+ // call client.on_conn_reset in next promise microtask
1270
+ client.conn_emit('on_disconnect', false===err, err);}
1271
+
1272
+ , async send_connect(... args) {
1273
+ if (! _send_mqtt_pkt) {
1274
+ await _q_init[0]; }// _send_mqtt_pkt is set before fulfilled
1275
+
1276
+ // await connack response
1277
+ let res = await _send_mqtt_pkt(...args);
1278
+ if (0 == res[0].reason) {
1279
+ _has_connected = true;
1280
+ // resolve _q_ready[0] with _send_mqtt_pkt closure
1281
+ _q_ready[1](client._send = _send_mqtt_pkt);
1282
+ _q_ready = ao_defer_v();
1283
+ client.conn_emit('on_ready');}
1284
+
1285
+ return res}
1286
+
1287
+ , is_set: (() =>!! _send_mqtt_pkt)
1288
+ , set(mqtt_ctx, send_u8_pkt) {
1289
+ if (_send_mqtt_pkt) {
1290
+ throw new Error('Already connected')}
1291
+
1292
+ mqtt_ctx = mqtt_ctx.mqtt_stream();
1293
+ let sess_ctx = {mqtt: client};
1294
+ let on_mqtt_chunk = u8_buf =>
1295
+ on_mqtt(mqtt_ctx.decode(u8_buf), sess_ctx);
1296
+
1297
+ _send_mqtt_pkt = async (type, pkt, key) => {
1298
+ let res = undefined !== key
1299
+ ? pkt_future(key) : true;
1300
+
1301
+ await send_u8_pkt(
1302
+ mqtt_ctx.encode_pkt(type, pkt));
1303
+
1304
+ return res};
1305
+
1306
+ _q_init[1](_send_mqtt_pkt); // resolve _q_init with _send_mqtt_pkt closure
1307
+
1308
+ // call client.on_live in next promise microtask
1309
+ client.conn_emit('on_live', _has_connected);
1310
+ return on_mqtt_chunk} } }
1311
+
1312
+
1313
+ function _ping_interval(send_ping) {
1314
+ let tid;
1315
+ return (( td ) => {
1316
+ tid = clearInterval(tid);
1317
+ if (td) {
1318
+ tid = setInterval(send_ping, 1000 * td);
1319
+
1320
+
1321
+
1322
+
1323
+ // ensure the interval allows the NodeJS event loop to exit
1324
+ tid.unref?.();
1325
+ return true} }) }
1326
+
1327
+ const _mqtt_cmdid_dispatch ={
1328
+ create(target) {
1329
+ return {__proto__: this, target, hashbelt: [new Map()]} }
1330
+
1331
+ , bind_pkt_future(_pkt_id=100) {
1332
+ let {hashbelt} = this;
1333
+
1334
+ let _tmp_; // use _tmp_ to reuse _by_key closure
1335
+ let _by_key = answer_monad =>
1336
+ hashbelt[0].set(_tmp_, answer_monad);
1337
+
1338
+ return (( pkt_or_key ) => {
1339
+ if ('string' === typeof pkt_or_key) {
1340
+ _tmp_ = pkt_or_key;}
1341
+ else {
1342
+ _pkt_id = (_pkt_id + 1) & 0xffff;
1343
+ _tmp_ = pkt_or_key.pkt_id = _pkt_id;}
1344
+
1345
+ return new Promise(_by_key)}) }
1346
+
1347
+ , answer(key, pkt) {
1348
+ for (let map of this.hashbelt) {
1349
+ let answer_monad = map.get(key);
1350
+ if (undefined !== answer_monad) {
1351
+ map.delete(key);
1352
+
1353
+ answer_monad([pkt, /*err*/]); // option/maybe monad
1354
+ return true} }
1355
+ return false}
1356
+
1357
+ , rotate_belt(n) {
1358
+ let {hashbelt} = this;
1359
+ hashbelt.unshift(new Map());
1360
+ for (let old of hashbelt.splice(n || 5)) {
1361
+ for (let answer_monad of old.values()) {
1362
+ answer_monad([/*pkt*/, 'expired']); } } }// option/maybe monad
1363
+
1364
+ , cmdids: ((() => {
1365
+ return [
1366
+ (() =>{} )// 0x0 reserved
1367
+ , by_evt // 0x1 connect
1368
+ , by_type // 0x2 connack
1369
+ , by_evt // 0x3 publish
1370
+ , by_id // 0x4 puback
1371
+ , by_id // 0x5 pubrec
1372
+ , by_id // 0x6 pubrel
1373
+ , by_id // 0x7 pubcomp
1374
+ , by_evt // 0x8 subscribe
1375
+ , by_id // 0x9 suback
1376
+ , by_evt // 0xa unsubscribe
1377
+ , by_id // 0xb unsuback
1378
+ , by_type // 0xc pingreq
1379
+ , by_type // 0xd pingresp
1380
+ , by_evt // 0xe disconnect
1381
+ , by_type ]// 0xf auth
1382
+
1383
+
1384
+ function by_id(disp, pkt) {
1385
+ disp.answer(pkt.pkt_id, pkt); }
1386
+
1387
+ function by_type(disp, pkt, ctx) {
1388
+ disp.answer(pkt.type, pkt);
1389
+ by_evt(disp, pkt, ctx);}
1390
+
1391
+ async function by_evt({target}, pkt, ctx) {
1392
+ let fn = target[`mqtt_${pkt.type}`]
1393
+ || target.mqtt_pkt;
1394
+
1395
+ await fn?.call(target, pkt, ctx);} })()) };
1396
+
1397
+ /*
1398
+ on_mqtt_type = {
1399
+ mqtt_auth(pkt, ctx) ::
1400
+ mqtt_connect(pkt, ctx) ::
1401
+ mqtt_connack(pkt, ctx) ::
1402
+ mqtt_disconnect(pkt, ctx) ::
1403
+
1404
+ mqtt_publish(pkt, ctx)
1405
+ mqtt_subscribe(pkt, ctx) ::
1406
+ mqtt_unsubscribe(pkt, ctx) ::
1407
+
1408
+ mqtt_pingreq(pkt, ctx) ::
1409
+ mqtt_pingresp(pkt, ctx) ::
1410
+ }
1411
+ */
1412
+
1413
+ function _mqtt_dispatch(opt, target) {
1414
+ let _disp_ = _mqtt_cmdid_dispatch.create(target);
1415
+ let { cmdids } = _disp_;
1416
+
1417
+ // default rotate at 1s across 5 buckets
1418
+ let { td: rotate_td=1000, n: rotate_n=5 } =
1419
+ opt && opt.rotate || {};
1420
+
1421
+ let rotate_ts = rotate_td + Date.now();
1422
+
1423
+ return [on_mqtt,
1424
+ _disp_.bind_pkt_future()]
1425
+
1426
+ function on_mqtt(pkt_list, ctx) {
1427
+ for (let pkt of pkt_list) {
1428
+ cmdids[pkt.id](_disp_, pkt, ctx); }
1429
+
1430
+ if (Date.now() > rotate_ts) {
1431
+ _disp_.rotate_belt(rotate_n);
1432
+ rotate_ts = rotate_td + Date.now();} } }
1433
+
1434
+ class MQTTError extends Error {
1435
+ constructor(mqtt_pkt, reason=mqtt_pkt.reason) {
1436
+ super(`[0x${reason.toString(16)}] ${reason.reason}`);
1437
+ this.mqtt_pkt = mqtt_pkt;
1438
+ this.reason = reason;} }
1439
+
1440
+ class MQTTBase {
1441
+ constructor(opt={}) {
1442
+ this.with(opt);
1443
+ this._conn_ = _mqtt_conn(this,
1444
+ this._init_dispatch(opt, this)); }
1445
+
1446
+ with(fns_ns) {
1447
+ for (let [k,v] of Object.entries(fns_ns)) {
1448
+ if ('function' === typeof v) {this[k] = v;} }
1449
+ return this}
1450
+
1451
+ async conn_emit(evt, arg, err_arg) {
1452
+ this.log_conn?.(evt, arg, err_arg);
1453
+ try {
1454
+ let fn_evt = this[await evt]; // microtask break using `await evt`
1455
+ if (fn_evt) {
1456
+ await fn_evt.call(this, this, arg, err_arg);}
1457
+ else if (err_arg) {throw err_arg} }
1458
+ catch (err) {
1459
+ this.on_error(err, evt);} }
1460
+
1461
+ on_error(err, evt) {
1462
+ console.warn('[[u8-mqtt error: %s]]', evt, err); }
1463
+
1464
+ // Handshaking Packets
1465
+
1466
+ async connect(pkt={}) {
1467
+ let cid = pkt.client_id;
1468
+ if ('string' !== typeof cid) {
1469
+ // see init_client_id implementation in core.jsy
1470
+ pkt.client_id = cid = this.client_id || this.init_client_id(cid);}
1471
+ this.client_id = cid;
1472
+
1473
+ if (null == pkt.keep_alive) {
1474
+ pkt.keep_alive = 60;}
1475
+
1476
+ let res = await this._conn_
1477
+ .send_connect('connect', pkt, 'connack');
1478
+
1479
+ if (0 != res[0].reason) {
1480
+ throw new this.MQTTError(res[0])}
1481
+
1482
+ // TODO: merge with server's keep_alive frequency
1483
+ this._conn_.ping(pkt.keep_alive);
1484
+ return res}
1485
+
1486
+ async disconnect(pkt={}) {
1487
+ let res = await this._send('disconnect', pkt);
1488
+ this._conn_.reset(false);
1489
+ return res}
1490
+
1491
+ auth(pkt={}) {
1492
+ return this._send('auth', pkt, 'auth')}
1493
+
1494
+ ping() {return this._send('pingreq', null, 'pingresp')}
1495
+ puback({pkt_id}) {return this._send('puback', {pkt_id})}
1496
+
1497
+ // alias: sub
1498
+ subscribe(pkt, ex, topic_prefix) {
1499
+ pkt = _as_topics(pkt, ex, topic_prefix);
1500
+ let suback = this._send('subscribe', pkt, pkt);
1501
+ return this.on_sub?.(suback, pkt) ?? suback}
1502
+
1503
+ // alias: unsub
1504
+ unsubscribe(pkt, ex, topic_prefix) {
1505
+ pkt = _as_topics(pkt, ex, topic_prefix);
1506
+ return this._send('unsubscribe', pkt, pkt)}
1507
+
1508
+
1509
+ post(topic, payload, pub_opt) {// qos:0
1510
+ return this.pub({topic, payload, qos:0}, pub_opt)}
1511
+ send(topic, payload, pub_opt) {// qos:1
1512
+ return this.pub({topic, payload, qos:1}, pub_opt)}
1513
+ store(topic, payload, pub_opt) {// qos:1, retain: 1
1514
+ return this.pub({topic, payload, qos:1, retain: 1}, pub_opt)}
1515
+
1516
+ // alias: json_post
1517
+ obj_post(topic, msg, pub_opt) {// qos:0
1518
+ return this.pub({topic, msg, arg: 'msg', qos:0}, pub_opt)}
1519
+ // alias: json_send
1520
+ obj_send(topic, msg, pub_opt) {// qos:1
1521
+ return this.pub({topic, msg, arg: 'msg', qos:1}, pub_opt)}
1522
+ // alias: json_store
1523
+ obj_store(topic, msg, pub_opt) {// qos:1, retain: 1
1524
+ return this.pub({topic, msg, arg: 'msg', qos:1, retain: 1}, pub_opt)}
1525
+
1526
+ // alias: publish -- because 'pub' is shorter for semantic aliases above
1527
+ async pub(pkt, pub_opt) {
1528
+ if (undefined === pkt.payload) {
1529
+ if ('function' === typeof pub_opt) {
1530
+ pub_opt = {fn_encode: pub_opt};}
1531
+
1532
+ let {msg} = pkt;
1533
+ switch (typeof msg) {
1534
+ case 'function':
1535
+ pub_opt = {...pub_opt, fn_encode: msg};
1536
+ // flow into 'undefined' case
1537
+ case 'undefined':
1538
+ // return a single-value closure to publish packets
1539
+ return v => this.pub({...pkt, [pkt.arg || 'payload']: v}, pub_opt)}
1540
+
1541
+ // Encode payload from msg; fn_encode allows alternative to JSON.stringify
1542
+ let {fn_encode} = pub_opt || {};
1543
+ pkt.payload = fn_encode
1544
+ ? await fn_encode(msg)
1545
+ : JSON.stringify(msg);}
1546
+
1547
+ if (pub_opt) {
1548
+ if (pub_opt.props) {
1549
+ pkt.props = pub_opt.props;}
1550
+ if (pub_opt.xform) {
1551
+ pkt = pub_opt.xform(pkt) || pkt;} }
1552
+
1553
+ return this._send('publish', pkt,
1554
+ pkt.qos ? pkt : void 0 ) }// key
1555
+
1556
+
1557
+ // Internal API
1558
+
1559
+ /* async _send(type, pkt) -- provided by _conn_ and transport */
1560
+
1561
+ _init_dispatch(opt) {
1562
+ this.constructor?._once_();
1563
+ let target ={__proto__: opt.on_mqtt_type};
1564
+ target.mqtt_publish ||=
1565
+ this._init_router?.(opt, this, target);
1566
+ return _mqtt_dispatch(this, target)}
1567
+
1568
+ static _aliases() {
1569
+ return ' publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store'}
1570
+
1571
+ static _once_(self=this) {
1572
+ self._once_ = _=>0;
1573
+ let p = self.prototype;
1574
+ p.MQTTError = MQTTError;
1575
+ for (let alias of self._aliases().split(/\s+/)) {
1576
+ alias = alias.split(':');
1577
+ let fn = alias[1] && p[alias[1]];
1578
+ if (fn) {p[alias[0]] = fn;} } } }
1579
+
1580
+
1581
+ function _as_topics(pkt, ex, topic_prefix) {
1582
+ if (ex?.trim) {// string
1583
+ topic_prefix = ex;
1584
+ ex = null;}
1585
+
1586
+ pkt =(
1587
+ pkt.trim // string
1588
+ ? {topics:[pkt], ... ex}
1589
+ : pkt[Symbol.iterator]
1590
+ ? {topics:[... pkt], ... ex}
1591
+ : ex ? {...pkt, ...ex}
1592
+ : pkt);
1593
+
1594
+ if (topic_prefix) {
1595
+ // particularly useful with shared queues, e.g.
1596
+ // topic_prefix = '$share/some-queue-name/'
1597
+ let _prefix_topics = v =>
1598
+ v.trim ? topic_prefix+v : v.map(_prefix_topics);
1599
+
1600
+ pkt.topics = pkt.topics.map(_prefix_topics);}
1601
+ return pkt}
1602
+
1603
+ const pkt_api = {
1604
+ utf8(u8) { return new TextDecoder('utf-8').decode(u8 || this.payload ) },
1605
+ json(u8) { return JSON.parse( this.utf8(u8) || null ) },
1606
+ text(u8) { return this.utf8(u8) },
1607
+ };
1608
+
1609
+ class MQTTCore extends MQTTBase {
1610
+ static mqtt_ctx(mqtt_level, mqtt_opts, pkt_ctx=pkt_api) {
1611
+ let self = class extends this {};
1612
+ self.prototype.mqtt_ctx =
1613
+ mqtt_pkt_ctx(mqtt_level, mqtt_opts, pkt_ctx);
1614
+ return self}
1615
+
1616
+
1617
+ // automatic Client Id for connect()
1618
+ init_client_id(parts=['u8-mqtt--','']) {
1619
+ let sess_stg=this.sess_stg;
1620
+ let key, cid = sess_stg?.getItem(key=parts.join(' '));
1621
+ if (! cid) {
1622
+ cid = parts.join(Math.random().toString(36).slice(2));
1623
+ sess_stg?.setItem(key, cid);}
1624
+ return cid}
1625
+
1626
+ get sess_stg() {return globalThis.sessionStorage}
1627
+
1628
+
1629
+ //on_error(err, evt) ::
1630
+ // console.warn @ '[[u8-mqtt error: %s]]', evt, err
1631
+
1632
+ //log_conn(evt, arg, err_arg) ::
1633
+ // console.info @ '[[u8-mqtt log: %s]]', evt, arg, err_arg
1634
+
1635
+ on_live(client, is_reconnect) {
1636
+ if (is_reconnect) {
1637
+ return client.connect()} }
1638
+
1639
+ // on_ready(client) ::
1640
+ // on_reconnect(client) ::
1641
+ on_disconnect(client, intentional) {
1642
+ if (! intentional) {
1643
+ return client.on_reconnect?.()} }
1644
+
1645
+ _use_conn(fn_reconnect) {
1646
+ return (this.reconnect = fn_reconnect)?.()}
1647
+ with_autoreconnect(opt=2000) {
1648
+ if (opt.toFixed) {opt ={delay: opt};}
1649
+ return this.with({
1650
+ on_reconnect() {
1651
+ this.delay(opt.delay || 2000)
1652
+ .then(this.reconnect)
1653
+ .then(opt.reconnect, opt.error);} }) }
1654
+
1655
+ delay(ms) {
1656
+ return new Promise(done => setTimeout(done, ms)) }
1657
+
1658
+ with_async_iter(async_iter, write_u8_pkt) {
1659
+ let on_mqtt_chunk = this._conn_.set(
1660
+ this.mqtt_ctx,
1661
+ write_u8_pkt);
1662
+
1663
+ this._msg_loop = ((async () => {
1664
+ try {
1665
+ async_iter = await async_iter;
1666
+ for await (let chunk of async_iter)
1667
+ on_mqtt_chunk(chunk);
1668
+ this._conn_.reset();}
1669
+ catch (err) {
1670
+ this._conn_.reset(err);} })());
1671
+
1672
+ return this}
1673
+
1674
+
1675
+
1676
+
1677
+
1678
+
1679
+
1680
+
1681
+
1682
+
1683
+
1684
+
1685
+
1686
+
1687
+
1688
+
1689
+
1690
+
1691
+
1692
+
1693
+
1694
+
1695
+
1696
+
1697
+
1698
+
1699
+
1700
+
1701
+
1702
+
1703
+
1704
+
1705
+ with_tcp(...opt) {
1706
+ opt = this._conn_opt(opt);
1707
+ return this._use_conn (() =>
1708
+ this.with_stream(
1709
+ connect(opt)) ) }
1710
+
1711
+ with_tls(...opt) {
1712
+ opt = this._conn_opt(opt);
1713
+ return this._use_conn (() =>
1714
+ this.with_stream(
1715
+ connect$1(opt)) ) }
1716
+
1717
+ _conn_opt([a0, a1, a2]) {
1718
+ // (port, hostname, options) or (url, options)
1719
+ if (Number.isFinite(a0)) {
1720
+ return {...a2, port: a0, host: a1}}
1721
+ a0 = new URL(a0);
1722
+ return {...a1, port: a0.port, host: a0.hostname}}
1723
+
1724
+
1725
+ with_stream(read_stream, write_stream) {
1726
+ if (undefined === write_stream) {
1727
+ write_stream = read_stream;}
1728
+
1729
+ return this.with_async_iter(read_stream,
1730
+ u8_pkt => write_stream.write(u8_pkt)) }
1731
+
1732
+
1733
+ with_websock(websock) {
1734
+ if (! websock?.send) {
1735
+ websock = new URL(websock || 'ws://127.0.0.1:9001');
1736
+ return this._use_conn (() =>
1737
+ this.with_websock(
1738
+ new WebSocket(websock, ['mqtt'])) ) }
1739
+
1740
+ websock.binaryType = 'arraybuffer';
1741
+
1742
+ let ready, {readyState} = websock;
1743
+ if (1 !== readyState) {
1744
+ if (0 !== readyState) {
1745
+ throw new Error('Invalid WebSocket readyState') }
1746
+
1747
+ ready = new Promise(fn => websock.onopen = fn); }
1748
+
1749
+
1750
+ let {_conn_} = this;
1751
+ let on_mqtt_chunk = _conn_.set(
1752
+ this.mqtt_ctx,
1753
+ async u8_pkt =>(
1754
+ await ready
1755
+ , websock.send(u8_pkt)) );
1756
+
1757
+ websock.onmessage = evt =>(on_mqtt_chunk(new Uint8Array(evt.data)));
1758
+ websock.onclose = evt => {
1759
+ if (! evt.wasClean) {
1760
+ var err = new Error('websocket connection close');
1761
+ err.code = evt.code;
1762
+ err.reason = evt.reason;}
1763
+
1764
+ _conn_.reset(err);};
1765
+
1766
+ return this} }
1767
+
1768
+ const version = '0.5.3-node';
1769
+
1770
+ const MQTTClient_v4 = /* #__PURE__ */
1771
+ with_topic_path_router(
1772
+ MQTTCore.mqtt_ctx(4, mqtt_opts_v5) );
1773
+
1774
+ const MQTTClient_v5 = /* #__PURE__ */
1775
+ with_topic_path_router(
1776
+ MQTTCore.mqtt_ctx(5, mqtt_opts_v5) );
1777
+
1778
+ const mqtt_v4 = opt =>
1779
+ new MQTTClient_v4(opt);
1780
+
1781
+ const mqtt_v5 = opt =>
1782
+ new MQTTClient_v5(opt);
1783
+
1784
+ export { MQTTClient_v5 as MQTTClient, MQTTClient_v4, MQTTClient_v5, mqtt_v5 as default, mqtt_v5 as mqtt, mqtt_v4, mqtt_v5, version };
1785
+ //# sourceMappingURL=full-v5.mjs.map