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