u8-mqtt 0.5.0 → 0.5.2

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 (46) hide show
  1. package/cjs/basic-v4.cjs +1 -1
  2. package/cjs/basic-v5.cjs +1 -1
  3. package/cjs/index.cjs +1 -1
  4. package/cjs/v4.cjs +1 -1
  5. package/cjs/v5.cjs +1 -1
  6. package/esm/basic-v4.js +1 -1
  7. package/esm/basic-v5.js +1 -1
  8. package/esm/deno/basic-v4.js +1 -1
  9. package/esm/deno/basic-v5.js +1 -1
  10. package/esm/deno/index.js +1 -1
  11. package/esm/deno/v4.js +1 -1
  12. package/esm/deno/v5.js +1 -1
  13. package/esm/index.js +1 -1
  14. package/esm/node/basic-v4.js +1 -1
  15. package/esm/node/basic-v4.mjs +1 -1
  16. package/esm/node/basic-v5.js +1 -1
  17. package/esm/node/basic-v5.mjs +1 -1
  18. package/esm/node/index.js +1 -1
  19. package/esm/node/index.mjs +1 -1
  20. package/esm/node/v4.js +1 -1
  21. package/esm/node/v4.mjs +1 -1
  22. package/esm/node/v5.js +1 -1
  23. package/esm/node/v5.mjs +1 -1
  24. package/esm/v4.js +1 -1
  25. package/esm/v5.js +1 -1
  26. package/esm/web/basic-v4.js +1 -1
  27. package/esm/web/basic-v4.min.js +1 -1
  28. package/esm/web/basic-v4.min.js.br +0 -0
  29. package/esm/web/basic-v4.min.js.gz +0 -0
  30. package/esm/web/basic-v5.js +1 -1
  31. package/esm/web/basic-v5.min.js +1 -1
  32. package/esm/web/basic-v5.min.js.br +0 -0
  33. package/esm/web/basic-v5.min.js.gz +0 -0
  34. package/esm/web/index.js +1 -1
  35. package/esm/web/index.min.js +1 -1
  36. package/esm/web/index.min.js.br +0 -0
  37. package/esm/web/index.min.js.gz +0 -0
  38. package/esm/web/v4.js +1 -1
  39. package/esm/web/v4.min.js +1 -1
  40. package/esm/web/v4.min.js.br +0 -0
  41. package/esm/web/v4.min.js.gz +0 -0
  42. package/esm/web/v5.js +1 -1
  43. package/esm/web/v5.min.js +1 -1
  44. package/esm/web/v5.min.js.br +0 -0
  45. package/esm/web/v5.min.js.gz +0 -0
  46. package/package.json +11 -2
package/cjs/basic-v4.cjs CHANGED
@@ -1149,7 +1149,7 @@ class MQTTCore extends MQTTBase {
1149
1149
 
1150
1150
  return this} }
1151
1151
 
1152
- const version = '0.5.0';
1152
+ const version = '0.5.2-node';
1153
1153
 
1154
1154
  const MQTTClient_v4 = /* #__PURE__ */
1155
1155
  MQTTCore.mqtt_ctx(4, mqtt_opts_v4);
package/cjs/basic-v5.cjs CHANGED
@@ -1405,7 +1405,7 @@ class MQTTCore extends MQTTBase {
1405
1405
 
1406
1406
  return this} }
1407
1407
 
1408
- const version = '0.5.0';
1408
+ const version = '0.5.2-node';
1409
1409
 
1410
1410
  const MQTTClient_v4 = /* #__PURE__ */
1411
1411
  MQTTCore.mqtt_ctx(4, mqtt_opts_v5);
package/cjs/index.cjs CHANGED
@@ -1586,7 +1586,7 @@ class MQTTCore extends MQTTBase {
1586
1586
 
1587
1587
  return this} }
1588
1588
 
1589
- const version = '0.5.0';
1589
+ const version = '0.5.2-node';
1590
1590
 
1591
1591
  const MQTTClient_v4 = /* #__PURE__ */
1592
1592
  with_topic_path_router(
package/cjs/v4.cjs CHANGED
@@ -1330,7 +1330,7 @@ class MQTTCore extends MQTTBase {
1330
1330
 
1331
1331
  return this} }
1332
1332
 
1333
- const version = '0.5.0';
1333
+ const version = '0.5.2-node';
1334
1334
 
1335
1335
  const MQTTClient_v4 = /* #__PURE__ */
1336
1336
  with_topic_path_router(
package/cjs/v5.cjs CHANGED
@@ -1586,7 +1586,7 @@ class MQTTCore extends MQTTBase {
1586
1586
 
1587
1587
  return this} }
1588
1588
 
1589
- const version = '0.5.0';
1589
+ const version = '0.5.2-node';
1590
1590
 
1591
1591
  const MQTTClient_v4 = /* #__PURE__ */
1592
1592
  with_topic_path_router(
package/esm/basic-v4.js CHANGED
@@ -1142,7 +1142,7 @@ class MQTTCore extends MQTTBase {
1142
1142
 
1143
1143
  return this} }
1144
1144
 
1145
- const version = '0.5.0';
1145
+ const version = '0.5.2';
1146
1146
 
1147
1147
  const MQTTClient_v4 = /* #__PURE__ */
1148
1148
  MQTTCore.mqtt_ctx(4, mqtt_opts_v4);
package/esm/basic-v5.js CHANGED
@@ -1398,7 +1398,7 @@ class MQTTCore extends MQTTBase {
1398
1398
 
1399
1399
  return this} }
1400
1400
 
1401
- const version = '0.5.0';
1401
+ const version = '0.5.2';
1402
1402
 
1403
1403
  const MQTTClient_v4 = /* #__PURE__ */
1404
1404
  MQTTCore.mqtt_ctx(4, mqtt_opts_v5);
@@ -1142,7 +1142,7 @@ class MQTTCore extends MQTTBase {
1142
1142
 
1143
1143
  return this} }
1144
1144
 
1145
- const version = '0.5.0';
1145
+ const version = '0.5.2-deno';
1146
1146
 
1147
1147
  const MQTTClient_v4 = /* #__PURE__ */
1148
1148
  MQTTCore.mqtt_ctx(4, mqtt_opts_v4);
@@ -1398,7 +1398,7 @@ class MQTTCore extends MQTTBase {
1398
1398
 
1399
1399
  return this} }
1400
1400
 
1401
- const version = '0.5.0';
1401
+ const version = '0.5.2-deno';
1402
1402
 
1403
1403
  const MQTTClient_v4 = /* #__PURE__ */
1404
1404
  MQTTCore.mqtt_ctx(4, mqtt_opts_v5);
package/esm/deno/index.js CHANGED
@@ -1579,7 +1579,7 @@ class MQTTCore extends MQTTBase {
1579
1579
 
1580
1580
  return this} }
1581
1581
 
1582
- const version = '0.5.0';
1582
+ const version = '0.5.2-deno';
1583
1583
 
1584
1584
  const MQTTClient_v4 = /* #__PURE__ */
1585
1585
  with_topic_path_router(
package/esm/deno/v4.js CHANGED
@@ -1323,7 +1323,7 @@ class MQTTCore extends MQTTBase {
1323
1323
 
1324
1324
  return this} }
1325
1325
 
1326
- const version = '0.5.0';
1326
+ const version = '0.5.2-deno';
1327
1327
 
1328
1328
  const MQTTClient_v4 = /* #__PURE__ */
1329
1329
  with_topic_path_router(
package/esm/deno/v5.js CHANGED
@@ -1579,7 +1579,7 @@ class MQTTCore extends MQTTBase {
1579
1579
 
1580
1580
  return this} }
1581
1581
 
1582
- const version = '0.5.0';
1582
+ const version = '0.5.2-deno';
1583
1583
 
1584
1584
  const MQTTClient_v4 = /* #__PURE__ */
1585
1585
  with_topic_path_router(
package/esm/index.js CHANGED
@@ -1579,7 +1579,7 @@ class MQTTCore extends MQTTBase {
1579
1579
 
1580
1580
  return this} }
1581
1581
 
1582
- const version = '0.5.0';
1582
+ const version = '0.5.2';
1583
1583
 
1584
1584
  const MQTTClient_v4 = /* #__PURE__ */
1585
1585
  with_topic_path_router(
@@ -1145,7 +1145,7 @@ class MQTTCore extends MQTTBase {
1145
1145
 
1146
1146
  return this} }
1147
1147
 
1148
- const version = '0.5.0';
1148
+ const version = '0.5.2-node';
1149
1149
 
1150
1150
  const MQTTClient_v4 = /* #__PURE__ */
1151
1151
  MQTTCore.mqtt_ctx(4, mqtt_opts_v4);
@@ -1145,7 +1145,7 @@ class MQTTCore extends MQTTBase {
1145
1145
 
1146
1146
  return this} }
1147
1147
 
1148
- const version = '0.5.0';
1148
+ const version = '0.5.2-node';
1149
1149
 
1150
1150
  const MQTTClient_v4 = /* #__PURE__ */
1151
1151
  MQTTCore.mqtt_ctx(4, mqtt_opts_v4);
@@ -1401,7 +1401,7 @@ class MQTTCore extends MQTTBase {
1401
1401
 
1402
1402
  return this} }
1403
1403
 
1404
- const version = '0.5.0';
1404
+ const version = '0.5.2-node';
1405
1405
 
1406
1406
  const MQTTClient_v4 = /* #__PURE__ */
1407
1407
  MQTTCore.mqtt_ctx(4, mqtt_opts_v5);
@@ -1401,7 +1401,7 @@ class MQTTCore extends MQTTBase {
1401
1401
 
1402
1402
  return this} }
1403
1403
 
1404
- const version = '0.5.0';
1404
+ const version = '0.5.2-node';
1405
1405
 
1406
1406
  const MQTTClient_v4 = /* #__PURE__ */
1407
1407
  MQTTCore.mqtt_ctx(4, mqtt_opts_v5);
package/esm/node/index.js CHANGED
@@ -1582,7 +1582,7 @@ class MQTTCore extends MQTTBase {
1582
1582
 
1583
1583
  return this} }
1584
1584
 
1585
- const version = '0.5.0';
1585
+ const version = '0.5.2-node';
1586
1586
 
1587
1587
  const MQTTClient_v4 = /* #__PURE__ */
1588
1588
  with_topic_path_router(
@@ -1582,7 +1582,7 @@ class MQTTCore extends MQTTBase {
1582
1582
 
1583
1583
  return this} }
1584
1584
 
1585
- const version = '0.5.0';
1585
+ const version = '0.5.2-node';
1586
1586
 
1587
1587
  const MQTTClient_v4 = /* #__PURE__ */
1588
1588
  with_topic_path_router(
package/esm/node/v4.js CHANGED
@@ -1326,7 +1326,7 @@ class MQTTCore extends MQTTBase {
1326
1326
 
1327
1327
  return this} }
1328
1328
 
1329
- const version = '0.5.0';
1329
+ const version = '0.5.2-node';
1330
1330
 
1331
1331
  const MQTTClient_v4 = /* #__PURE__ */
1332
1332
  with_topic_path_router(
package/esm/node/v4.mjs CHANGED
@@ -1326,7 +1326,7 @@ class MQTTCore extends MQTTBase {
1326
1326
 
1327
1327
  return this} }
1328
1328
 
1329
- const version = '0.5.0';
1329
+ const version = '0.5.2-node';
1330
1330
 
1331
1331
  const MQTTClient_v4 = /* #__PURE__ */
1332
1332
  with_topic_path_router(
package/esm/node/v5.js CHANGED
@@ -1582,7 +1582,7 @@ class MQTTCore extends MQTTBase {
1582
1582
 
1583
1583
  return this} }
1584
1584
 
1585
- const version = '0.5.0';
1585
+ const version = '0.5.2-node';
1586
1586
 
1587
1587
  const MQTTClient_v4 = /* #__PURE__ */
1588
1588
  with_topic_path_router(
package/esm/node/v5.mjs CHANGED
@@ -1582,7 +1582,7 @@ class MQTTCore extends MQTTBase {
1582
1582
 
1583
1583
  return this} }
1584
1584
 
1585
- const version = '0.5.0';
1585
+ const version = '0.5.2-node';
1586
1586
 
1587
1587
  const MQTTClient_v4 = /* #__PURE__ */
1588
1588
  with_topic_path_router(
package/esm/v4.js CHANGED
@@ -1323,7 +1323,7 @@ class MQTTCore extends MQTTBase {
1323
1323
 
1324
1324
  return this} }
1325
1325
 
1326
- const version = '0.5.0';
1326
+ const version = '0.5.2';
1327
1327
 
1328
1328
  const MQTTClient_v4 = /* #__PURE__ */
1329
1329
  with_topic_path_router(
package/esm/v5.js CHANGED
@@ -1579,7 +1579,7 @@ class MQTTCore extends MQTTBase {
1579
1579
 
1580
1580
  return this} }
1581
1581
 
1582
- const version = '0.5.0';
1582
+ const version = '0.5.2';
1583
1583
 
1584
1584
  const MQTTClient_v4 = /* #__PURE__ */
1585
1585
  with_topic_path_router(
@@ -1142,7 +1142,7 @@ class MQTTCore extends MQTTBase {
1142
1142
 
1143
1143
  return this} }
1144
1144
 
1145
- const version = '0.5.0';
1145
+ const version = '0.5.2-web';
1146
1146
 
1147
1147
  const MQTTClient_v4 = /* #__PURE__ */
1148
1148
  MQTTCore.mqtt_ctx(4, mqtt_opts_v4);
@@ -1 +1 @@
1
- function t(t,e=[]){do{const n=127&t;t>>>=7,e.push(n|(0===t?0:128))}while(t>0);return e}class e extends Number{static of(t,e,n){let r=new this(t);return r.reason=n?.[e]?.get(t)||e,r}}let n=class{static of(t){return this.prototype.of(t)}of(t){let e=(t,n)=>(n=0|e.k,e.k=n+t,n);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,n=e(2);return t[n]<<8|t[n+1]}u32(){let{buf:t,step:e}=this,n=e(4);return t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3]}vint(){let{buf:t,step:e}=this,[n,r,s]=function(t,e=0){let n=e,r=(127&t[e])<<0;return 128&t[e++]&&(r|=(127&t[e])<<7,128&t[e++]&&(r|=(127&t[e])<<14,128&t[e++]&&(r|=(127&t[e])<<21))),[r,e,n]}(t,0|e.k);return e(r-s),n}bin(){let{buf:t,step:e}=this,n=e(2),r=t[n]<<8|t[n+1];return n=e(r),t.subarray(n,n+r)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let n=this.buf[this.step(1)];if(null!=n)return e.of(n,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}};function r(t,...e){t=class extends t{static reasons(t,...e){let n=this.prototype;n._reasons_by={...n._reasons_by};let r=n._reasons_by[t]||=new Map;for(let[t,n]of e)r.set(t,n);return this}};for(let n of e)n(t);return t}function s(t){t.reasons("connack",[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"])}function o(t){return(e,n)=>{let r=t.of(n);e.pkt_id=r.u16(),5<=e.mqtt_level&&(e.props=r.props());let s=e.answers=[];for(;r.has_more();)s.push(r.reason(e.type));return e}}function i(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}function u(t){t.reasons("unsuback",[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"])}const a=[function(t,e){const n=new Uint8Array([0,4,77,81,84,84]),r=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,s)=>{let o=e.of(s);o.push(n),o.u8(t);let{will:i,username:u,password:a}=s,c=o.flags(s.flags,r,0|(u?128:0)|(a?64:0)|(i?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(i):0));return o.u16(s.keep_alive),5<=t&&o.props(s.props),o.utf8(s.client_id),4&c&&(5<=t&&o.props(i.props),o.utf8(i.topic),o.bin(i.payload)),128&c&&o.utf8(u),64&c&&o.bin(a),o.as_pkt(16)}},function(t,e){return t.puback=(t,n)=>{let r=e.of(n);return r.u16(n.pkt_id),5<=t&&(r.reason(n.reason),r.props(n.props)),r.as_pkt(64)}},function(t,e){return t.publish=(t,n)=>{let r=(3&n.qos)<<1,s=e.of(n);return s.utf8(n.topic),0!==r&&s.u16(n.pkt_id),5<=t?(s.props(n.props),s.flush(n.payload)):s.flush(n.payload),s.as_pkt(48|r|(n.dup?8:0)|(n.retain?1:0))}},function(t,e){const n=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,r)=>{let s=e.of(r);s.u16(r.pkt_id),5<=t&&s.props(r.props);let o=n(r);for(let t of r.topics)if("string"==typeof t)s.utf8(t),s.u8(o);else{let[e,r]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===r?s.u8(o):s.flags(r,n)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,n)=>{let r=e.of(n);r.u16(n.pkt_id),5<=t&&r.props(n.props);for(let t of n.topics)r.utf8(t);return r.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,n)=>{let r=e.of(n);return n&&5<=t&&(n.reason||n.props)&&(r.reason(n.reason),r.props(n.props)),r.as_pkt(224)}}],c={decode_fns:[function(t,e){class n extends Number{get session_present(){return!0&this}}return t[2]=(t,r)=>{let s=e.of(r);return t.flags=s.flags(n),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,n)=>{let{hdr:r}=t;t.dup=Boolean(8&r),t.retain=Boolean(1&r);let s=t.qos=r>>1&3,o=e.of(n);return t.topic=o.utf8(),0!==s&&(t.pkt_id=o.u16()),5<=t.mqtt_level&&(t.props=o.props()),t.payload=o.flush(),t}},function(t,e){return t[4]=(t,n)=>{let r=e.of(n);return t.pkt_id=r.u16(),5<=t.mqtt_level&&(t.reason=r.reason(t.type),t.props=r.props()),t}},function(t,e){return t[9]=o(e)},function(t,e){return t[11]=o(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,n)=>{if(n&&5<=t.mqtt_level){let r=e.of(n);t.reason=r.reason(t.type),t.props=r.props()}return t}}],mqtt_reader:r(n,s,i,u),encode_fns:a,mqtt_writer:class{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let n,r,s=0,o=this.$;for(n of(this.$=!1,o))s+=n.length;r=(e=t(s,e)).length;let i=new Uint8Array(r+s);for(n of(i.set(e,0),o))i.set(n,r),r+=n.length;return i}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,n=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=n,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}};function p(t,e=0){let n=e,r=(127&t[e])<<0;return 128&t[e++]&&(r|=(127&t[e])<<7,128&t[e++]&&(r|=(127&t[e])<<14,128&t[e++]&&(r|=(127&t[e])<<21))),[r,e,n]}function l(t){let e=new Uint8Array(0);return n=>{e=0===e.byteLength?n:function(t,e){let n=t.byteLength,r=new Uint8Array(n+e.byteLength);return r.set(t,0),r.set(e,n),r}(e,n);let r=[];for(;;){let[n,s]=p(e,1),o=n+s;if(e.byteLength<o)return r;let i=e[0],u=0===n?null:e.subarray(s,o);e=e.subarray(o);let a=t.decode_pkt(i,u,t);null!=a&&r.push(a)}}}const _=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function h(t=((...t)=>t)){let e,n,r=(t,r)=>{e=t,n=r};return s=>(s=new Promise(r),t(s,e,n))}const f=h();function d(t){let e;return n=>{if(e=clearInterval(e),n)return e=setInterval(t,1e3*n),e.unref?.(),!0}}Promise.resolve({type:"init"});const b={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:n}=this,r=t=>n[0].set(e,t);return n=>("string"==typeof n?e=n:(t=t+1&65535,e=n.pkt_id=t),new Promise(r))},answer(t,e){for(let n of this.hashbelt){let r=n.get(t);if(void 0!==r)return n.delete(t),r([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let n of e.splice(t||5))for(let t of n.values())t([,"expired"])},cmdids:(()=>{return[()=>{},n,e,n,t,t,t,t,n,t,n,t,e,e,n,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,r){t.answer(e.type,e),n(t,e,r)}async function n({target:t},e,n){let r=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(r?.call(t,e,n))}})()};class y extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class w{constructor(t={}){this.with(t),this._conn_=function(t,[e,n]){let r,s,o=f(),i=f(),u=async(...t)=>(await i[0])(...t);return t._send=u,{async when_ready(){await i[0]},ping:d((()=>r?.("pingreq"))),reset(e){r&&(e&&o[2](e),r=null,o=f(),t._send=u,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){r||await o[0];let n=await r(...e);return 0==n[0].reason&&(s=!0,i[1](t._send=r),i=f(),t.conn_emit("on_ready")),n},is_set:()=>!!r,set(i,u){if(r)throw new Error("Already connected");i=i.mqtt_stream();let a={mqtt:t};return r=async(t,e,r)=>{let s=void 0===r||n(r);return await u(i.encode_pkt(t,e)),s},o[1](r),t.conn_emit("on_live",s),t=>e(i.decode(t),a)}}}(this,this._init_dispatch(t,this))}with(t){for(let[e,n]of Object.entries(t))"function"==typeof n&&(this[e]=n);return this}async conn_emit(t,e,n){this.log_conn?.(t,e,n);try{let r=this[await t];if(r)await r.call(this,this,e,n);else if(n)throw n}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||this.client_id;"string"!=typeof e&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let n=await this._conn_.send_connect("connect",t,"connack");if(0!=n[0].reason)throw new this.MQTTError(n[0]);return this._conn_.ping(t.keep_alive),n}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,n){t=m(t,e,n);let r=this._send("subscribe",t,t);return this.on_sub?.(r,t)??r}unsubscribe(t,e,n){return t=m(t,e,n),this._send("unsubscribe",t,t)}post(t,e,n){return this.pub({topic:t,payload:e,qos:0},n)}send(t,e,n){return this.pub({topic:t,payload:e,qos:1},n)}store(t,e,n){return this.pub({topic:t,payload:e,qos:1,retain:1},n)}obj_post(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:0},n)}obj_send(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:1},n)}obj_store(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},n)}async pub(t,e){if(void 0===t.payload){"function"==typeof e&&(e={fn_encode:e});let{msg:n}=t;switch(typeof n){case"function":e={...e,fn_encode:n};case"undefined":return n=>this.pub({...t,[t.arg||"payload"]:n},e)}let{fn_encode:r}=e||{};t.payload=r?await r(n):JSON.stringify(n)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:void 0)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),function(t,e){let n=b.create(e),{cmdids:r}=n,{td:s=1e3,n:o=5}=t&&t.rotate||{},i=s+Date.now();return[function(t,e){for(let s of t)r[s.id](n,s,e);Date.now()>i&&(n.rotate_belt(o),i=s+Date.now())},n.bind_pkt_future()]}(this,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;let e=t.prototype;e.MQTTError=y;for(let n of t._aliases().split(/\s+/)){n=n.split(":");let t=n[1]&&e[n[1]];t&&(e[n[0]]=t)}}}function m(t,e,n){if(e?.trim&&(n=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,n){let e=t=>t.trim?n+t:t.map(e);t.topics=t.topics.map(e)}return t}const g={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};const k="0.5.0",q=class extends w{static mqtt_ctx(t,e,n=g){let r=class extends(this){};return r.prototype.mqtt_ctx=function(t,e,n){n={__proto__:n||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return _[this.b0>>>4]}};let r,s=[],o={};for(r of e.encode_fns)r(o,e.mqtt_writer);for(r of e.decode_fns)r(s,e.mqtt_reader);return{pkt_ctx:n,encode_pkt:(e,n)=>o[e](t,n),decode_pkt(t,e){let n=s[t>>>4]||s[0];return n?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:n}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=l(t),t}}}(t,e,n),r}init_client_id(t=["u8-mqtt--",""]){let e,n=this.sess_stg,r=n?.getItem(e=t.join(" "));return r||(r=t.join(Math.random().toString(36).slice(2)),n?.setItem(e,r)),r}get sess_stg(){return globalThis.sessionStorage}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let n=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)n(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:n}=t;if(1!==n){if(0!==n)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:r}=this,s=r.set(this.mqtt_ctx,(async n=>(await e,t.send(n))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}r.reset(e)},this}}.mqtt_ctx(4,c),v=t=>new q(t);export{q as MQTTClient,q as MQTTClient_v4,v as default,v as mqtt,v as mqtt_v4,k as version};
1
+ function t(t,e=[]){do{const n=127&t;t>>>=7,e.push(n|(0===t?0:128))}while(t>0);return e}class e extends Number{static of(t,e,n){let r=new this(t);return r.reason=n?.[e]?.get(t)||e,r}}let n=class{static of(t){return this.prototype.of(t)}of(t){let e=(t,n)=>(n=0|e.k,e.k=n+t,n);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,n=e(2);return t[n]<<8|t[n+1]}u32(){let{buf:t,step:e}=this,n=e(4);return t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3]}vint(){let{buf:t,step:e}=this,[n,r,s]=function(t,e=0){let n=e,r=(127&t[e])<<0;return 128&t[e++]&&(r|=(127&t[e])<<7,128&t[e++]&&(r|=(127&t[e])<<14,128&t[e++]&&(r|=(127&t[e])<<21))),[r,e,n]}(t,0|e.k);return e(r-s),n}bin(){let{buf:t,step:e}=this,n=e(2),r=t[n]<<8|t[n+1];return n=e(r),t.subarray(n,n+r)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let n=this.buf[this.step(1)];if(null!=n)return e.of(n,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}};function r(t,...e){t=class extends t{static reasons(t,...e){let n=this.prototype;n._reasons_by={...n._reasons_by};let r=n._reasons_by[t]||=new Map;for(let[t,n]of e)r.set(t,n);return this}};for(let n of e)n(t);return t}function s(t){t.reasons("connack",[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"])}function o(t){return(e,n)=>{let r=t.of(n);e.pkt_id=r.u16(),5<=e.mqtt_level&&(e.props=r.props());let s=e.answers=[];for(;r.has_more();)s.push(r.reason(e.type));return e}}function i(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}function u(t){t.reasons("unsuback",[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"])}const a=[function(t,e){const n=new Uint8Array([0,4,77,81,84,84]),r=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,s)=>{let o=e.of(s);o.push(n),o.u8(t);let{will:i,username:u,password:a}=s,c=o.flags(s.flags,r,0|(u?128:0)|(a?64:0)|(i?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(i):0));return o.u16(s.keep_alive),5<=t&&o.props(s.props),o.utf8(s.client_id),4&c&&(5<=t&&o.props(i.props),o.utf8(i.topic),o.bin(i.payload)),128&c&&o.utf8(u),64&c&&o.bin(a),o.as_pkt(16)}},function(t,e){return t.puback=(t,n)=>{let r=e.of(n);return r.u16(n.pkt_id),5<=t&&(r.reason(n.reason),r.props(n.props)),r.as_pkt(64)}},function(t,e){return t.publish=(t,n)=>{let r=(3&n.qos)<<1,s=e.of(n);return s.utf8(n.topic),0!==r&&s.u16(n.pkt_id),5<=t?(s.props(n.props),s.flush(n.payload)):s.flush(n.payload),s.as_pkt(48|r|(n.dup?8:0)|(n.retain?1:0))}},function(t,e){const n=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,r)=>{let s=e.of(r);s.u16(r.pkt_id),5<=t&&s.props(r.props);let o=n(r);for(let t of r.topics)if("string"==typeof t)s.utf8(t),s.u8(o);else{let[e,r]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===r?s.u8(o):s.flags(r,n)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,n)=>{let r=e.of(n);r.u16(n.pkt_id),5<=t&&r.props(n.props);for(let t of n.topics)r.utf8(t);return r.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,n)=>{let r=e.of(n);return n&&5<=t&&(n.reason||n.props)&&(r.reason(n.reason),r.props(n.props)),r.as_pkt(224)}}],c={decode_fns:[function(t,e){class n extends Number{get session_present(){return!0&this}}return t[2]=(t,r)=>{let s=e.of(r);return t.flags=s.flags(n),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,n)=>{let{hdr:r}=t;t.dup=Boolean(8&r),t.retain=Boolean(1&r);let s=t.qos=r>>1&3,o=e.of(n);return t.topic=o.utf8(),0!==s&&(t.pkt_id=o.u16()),5<=t.mqtt_level&&(t.props=o.props()),t.payload=o.flush(),t}},function(t,e){return t[4]=(t,n)=>{let r=e.of(n);return t.pkt_id=r.u16(),5<=t.mqtt_level&&(t.reason=r.reason(t.type),t.props=r.props()),t}},function(t,e){return t[9]=o(e)},function(t,e){return t[11]=o(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,n)=>{if(n&&5<=t.mqtt_level){let r=e.of(n);t.reason=r.reason(t.type),t.props=r.props()}return t}}],mqtt_reader:r(n,s,i,u),encode_fns:a,mqtt_writer:class{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let n,r,s=0,o=this.$;for(n of(this.$=!1,o))s+=n.length;r=(e=t(s,e)).length;let i=new Uint8Array(r+s);for(n of(i.set(e,0),o))i.set(n,r),r+=n.length;return i}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,n=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=n,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}};function p(t,e=0){let n=e,r=(127&t[e])<<0;return 128&t[e++]&&(r|=(127&t[e])<<7,128&t[e++]&&(r|=(127&t[e])<<14,128&t[e++]&&(r|=(127&t[e])<<21))),[r,e,n]}function l(t){let e=new Uint8Array(0);return n=>{e=0===e.byteLength?n:function(t,e){let n=t.byteLength,r=new Uint8Array(n+e.byteLength);return r.set(t,0),r.set(e,n),r}(e,n);let r=[];for(;;){let[n,s]=p(e,1),o=n+s;if(e.byteLength<o)return r;let i=e[0],u=0===n?null:e.subarray(s,o);e=e.subarray(o);let a=t.decode_pkt(i,u,t);null!=a&&r.push(a)}}}const _=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function h(t=((...t)=>t)){let e,n,r=(t,r)=>{e=t,n=r};return s=>(s=new Promise(r),t(s,e,n))}const f=h();function d(t){let e;return n=>{if(e=clearInterval(e),n)return e=setInterval(t,1e3*n),e.unref?.(),!0}}Promise.resolve({type:"init"});const b={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:n}=this,r=t=>n[0].set(e,t);return n=>("string"==typeof n?e=n:(t=t+1&65535,e=n.pkt_id=t),new Promise(r))},answer(t,e){for(let n of this.hashbelt){let r=n.get(t);if(void 0!==r)return n.delete(t),r([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let n of e.splice(t||5))for(let t of n.values())t([,"expired"])},cmdids:(()=>{return[()=>{},n,e,n,t,t,t,t,n,t,n,t,e,e,n,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,r){t.answer(e.type,e),n(t,e,r)}async function n({target:t},e,n){let r=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(r?.call(t,e,n))}})()};class y extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class w{constructor(t={}){this.with(t),this._conn_=function(t,[e,n]){let r,s,o=f(),i=f(),u=async(...t)=>(await i[0])(...t);return t._send=u,{async when_ready(){await i[0]},ping:d((()=>r?.("pingreq"))),reset(e){r&&(e&&o[2](e),r=null,o=f(),t._send=u,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){r||await o[0];let n=await r(...e);return 0==n[0].reason&&(s=!0,i[1](t._send=r),i=f(),t.conn_emit("on_ready")),n},is_set:()=>!!r,set(i,u){if(r)throw new Error("Already connected");i=i.mqtt_stream();let a={mqtt:t};return r=async(t,e,r)=>{let s=void 0===r||n(r);return await u(i.encode_pkt(t,e)),s},o[1](r),t.conn_emit("on_live",s),t=>e(i.decode(t),a)}}}(this,this._init_dispatch(t,this))}with(t){for(let[e,n]of Object.entries(t))"function"==typeof n&&(this[e]=n);return this}async conn_emit(t,e,n){this.log_conn?.(t,e,n);try{let r=this[await t];if(r)await r.call(this,this,e,n);else if(n)throw n}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||this.client_id;"string"!=typeof e&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let n=await this._conn_.send_connect("connect",t,"connack");if(0!=n[0].reason)throw new this.MQTTError(n[0]);return this._conn_.ping(t.keep_alive),n}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,n){t=m(t,e,n);let r=this._send("subscribe",t,t);return this.on_sub?.(r,t)??r}unsubscribe(t,e,n){return t=m(t,e,n),this._send("unsubscribe",t,t)}post(t,e,n){return this.pub({topic:t,payload:e,qos:0},n)}send(t,e,n){return this.pub({topic:t,payload:e,qos:1},n)}store(t,e,n){return this.pub({topic:t,payload:e,qos:1,retain:1},n)}obj_post(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:0},n)}obj_send(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:1},n)}obj_store(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},n)}async pub(t,e){if(void 0===t.payload){"function"==typeof e&&(e={fn_encode:e});let{msg:n}=t;switch(typeof n){case"function":e={...e,fn_encode:n};case"undefined":return n=>this.pub({...t,[t.arg||"payload"]:n},e)}let{fn_encode:r}=e||{};t.payload=r?await r(n):JSON.stringify(n)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:void 0)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),function(t,e){let n=b.create(e),{cmdids:r}=n,{td:s=1e3,n:o=5}=t&&t.rotate||{},i=s+Date.now();return[function(t,e){for(let s of t)r[s.id](n,s,e);Date.now()>i&&(n.rotate_belt(o),i=s+Date.now())},n.bind_pkt_future()]}(this,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;let e=t.prototype;e.MQTTError=y;for(let n of t._aliases().split(/\s+/)){n=n.split(":");let t=n[1]&&e[n[1]];t&&(e[n[0]]=t)}}}function m(t,e,n){if(e?.trim&&(n=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,n){let e=t=>t.trim?n+t:t.map(e);t.topics=t.topics.map(e)}return t}const g={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};const k="0.5.2-web",q=class extends w{static mqtt_ctx(t,e,n=g){let r=class extends(this){};return r.prototype.mqtt_ctx=function(t,e,n){n={__proto__:n||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return _[this.b0>>>4]}};let r,s=[],o={};for(r of e.encode_fns)r(o,e.mqtt_writer);for(r of e.decode_fns)r(s,e.mqtt_reader);return{pkt_ctx:n,encode_pkt:(e,n)=>o[e](t,n),decode_pkt(t,e){let n=s[t>>>4]||s[0];return n?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:n}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=l(t),t}}}(t,e,n),r}init_client_id(t=["u8-mqtt--",""]){let e,n=this.sess_stg,r=n?.getItem(e=t.join(" "));return r||(r=t.join(Math.random().toString(36).slice(2)),n?.setItem(e,r)),r}get sess_stg(){return globalThis.sessionStorage}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let n=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)n(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:n}=t;if(1!==n){if(0!==n)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:r}=this,s=r.set(this.mqtt_ctx,(async n=>(await e,t.send(n))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}r.reset(e)},this}}.mqtt_ctx(4,c),v=t=>new q(t);export{q as MQTTClient,q as MQTTClient_v4,v as default,v as mqtt,v as mqtt_v4,k as version};
Binary file
Binary file
@@ -1398,7 +1398,7 @@ class MQTTCore extends MQTTBase {
1398
1398
 
1399
1399
  return this} }
1400
1400
 
1401
- const version = '0.5.0';
1401
+ const version = '0.5.2-web';
1402
1402
 
1403
1403
  const MQTTClient_v4 = /* #__PURE__ */
1404
1404
  MQTTCore.mqtt_ctx(4, mqtt_opts_v5);
@@ -1 +1 @@
1
- function t(t,e=[]){do{const r=127&t;t>>>=7,e.push(r|(0===t?0:128))}while(t>0);return e}function e(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}const r=n();function n(){let t=new Map,e=[[1,"u8","payload_format_indicator"],[2,"u32","message_expiry_interval"],[3,"utf8","content_type"],[8,"utf8","response_topic"],[9,"bin","correlation_data"],[11,"vint","subscription_identifier"],[17,"u32","session_expiry_interval"],[18,"utf8","assigned_client_identifier"],[19,"u16","server_keep_alive"],[21,"utf8","authentication_method"],[22,"bin","authentication_data"],[23,"u8","request_problem_information"],[24,"u32","will_delay_interval"],[25,"u8","request_response_information"],[26,"utf8","response_information"],[28,"utf8","server_reference"],[31,"utf8","reason_string"],[33,"u16","receive_maximum"],[34,"u16","topic_alias_maximum"],[35,"u16","topic_alias"],[36,"u8","maximum_qos"],[37,"u8","retain_available"],[38,"pair","user_properties",{op:"kv_obj"}],[39,"u32","maximum_packet_size"],[40,"u8","wildcard_subscription_available"],[41,"u8","subscription_identifiers_available",{op:"u8_vec"}],[42,"u8","shared_subscription_available"]];for(let[r,n,s,i]of e){let e={id:r,type:n,name:s,...i};t.set(e.id,e),t.set(e.name,e)}return t}class s extends Number{static of(t,e,r){let n=new this(t);return n.reason=r?.[e]?.get(t)||e,n}}class i{static of(t){return this.prototype.of(t)}of(t){let e=(t,r)=>(r=0|e.k,e.k=r+t,r);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,r=e(2);return t[r]<<8|t[r+1]}u32(){let{buf:t,step:e}=this,r=e(4);return t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]}vint(){let{buf:t,step:r}=this,[n,s,i]=e(t,0|r.k);return r(s-i),n}bin(){let{buf:t,step:e}=this,r=e(2),n=t[r]<<8|t[r+1];return r=e(n),t.subarray(r,r+n)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let e=this.buf[this.step(1)];if(null!=e)return s.of(e,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}}let o=class extends i{props(){let{buf:t,step:n}=this,[s,i,o]=e(t,0|n.k);if(n(s+i-o),0===s)return null;let a={},u=this.of(t.subarray(i,0|n.k));for(;u.has_more();){let t=r.get(u.u8()),e=u[t.type]();a[t.name]=t.op?u[t.op](a[t.name],e):e}return a}kv_obj(t=Object.create(null),[e,r]){return t[e]=r,t}u8_vec(t=[],e){return t.push(e),t}};function a(t,...e){t=class extends t{static reasons(t,...e){let r=this.prototype;r._reasons_by={...r._reasons_by};let n=r._reasons_by[t]||=new Map;for(let[t,r]of e)n.set(t,r);return this}};for(let r of e)r(t);return t}class u{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let r,n,s=0,i=this.$;for(r of(this.$=!1,i))s+=r.length;n=(e=t(s,e)).length;let o=new Uint8Array(n+s);for(r of(o.set(e,0),i))o.set(r,n),n+=r.length;return o}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,r=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=r,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}function c(t){!function(t){t.reasons("connack",[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"])}(t),t.reasons("connack",[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[132,"Unsupported Protocol Version"],[133,"Client Identifier not valid"],[134,"Bad User Name or Password"],[135,"Not authorized"],[136,"Server unavailable"],[137,"Server busy"],[138,"Banned"],[140,"Bad authentication method"],[144,"Topic Name invalid"],[149,"Packet too large"],[151,"Quota exceeded"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[159,"Connection rate exceeded"])}function p(t){t.reasons("puback",[0,"Success"],[16,"No matching subscribers"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[144,"Topic Name invalid"],[145,"Packet identifier in use"],[151,"Quota exceeded"],[153,"Payload format invalid"])}function l(t){return(e,r)=>{let n=t.of(r);e.pkt_id=n.u16(),5<=e.mqtt_level&&(e.props=n.props());let s=e.answers=[];for(;n.has_more();)s.push(n.reason(e.type));return e}}function _(t){!function(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}(t),t.reasons("suback",[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"],[151,"Quota exceeded"],[158,"Shared Subscriptions not supported"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function f(t){t.reasons("unsuback",[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"])}function d(t){t.reasons("disconnect",[0,"Normal disconnection"],[4,"Disconnect with Will Message"],[128,"Unspecified error"],[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[135,"Not authorized"],[137,"Server busy"],[139,"Server shutting down"],[141,"Keep Alive timeout"],[142,"Session taken over"],[143,"Topic Filter invalid"],[144,"Topic Name invalid"],[147,"Receive Maximum exceeded"],[148,"Topic Alias invalid"],[149,"Packet too large"],[150,"Message rate too high"],[151,"Quota exceeded"],[152,"Administrative action"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[158,"Shared Subscriptions not supported"],[159,"Connection rate exceeded"],[160,"Maximum connect time"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function h(t){t.reasons("auth",[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"])}const b=[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,s)=>{let i=e.of(s);i.push(r),i.u8(t);let{will:o,username:a,password:u}=s,c=i.flags(s.flags,n,0|(a?128:0)|(u?64:0)|(o?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(o):0));return i.u16(s.keep_alive),5<=t&&i.props(s.props),i.utf8(s.client_id),4&c&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&c&&i.utf8(a),64&c&&i.bin(u),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.of(r);return n.u16(r.pkt_id),5<=t&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(64)}},function(t,e){return t.publish=(t,r)=>{let n=(3&r.qos)<<1,s=e.of(r);return s.utf8(r.topic),0!==n&&s.u16(r.pkt_id),5<=t?(s.props(r.props),s.flush(r.payload)):s.flush(r.payload),s.as_pkt(48|n|(r.dup?8:0)|(r.retain?1:0))}},function(t,e){const r=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.of(n);s.u16(n.pkt_id),5<=t&&s.props(n.props);let i=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(i);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(i):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,r)=>{let n=e.of(r);n.u16(r.pkt_id),5<=t&&n.props(r.props);for(let t of r.topics)n.utf8(t);return n.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,r)=>{let n=e.of(r);return r&&5<=t&&(r.reason||r.props)&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(224)}},function(t,e){return t.auth=(t,r)=>{if(5>t)throw new Error("Auth packets are only available after MQTT 5.x");let n=e.of(r);return n.reason(r.reason),n.props(r.props),n.as_pkt(240)}}],m={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.of(n);return t.flags=s.flags(r),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,r)=>{let{hdr:n}=t;t.dup=Boolean(8&n),t.retain=Boolean(1&n);let s=t.qos=n>>1&3,i=e.of(r);return t.topic=i.utf8(),0!==s&&(t.pkt_id=i.u16()),5<=t.mqtt_level&&(t.props=i.props()),t.payload=i.flush(),t}},function(t,e){return t[4]=(t,r)=>{let n=e.of(r);return t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.reason=n.reason(t.type),t.props=n.props()),t}},function(t,e){return t[9]=l(e)},function(t,e){return t[11]=l(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,r)=>{if(r&&5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}},function(t,e){return t[15]=(t,r)=>{if(5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}}],mqtt_reader:a(o,c,p,_,f,d,h),encode_fns:b,mqtt_writer:class extends u{props(t){if(!t)return this.u8(0);if(Array.isArray(t)||(t=t.entries?Array.from(t.entries()):Object.entries(t)),0===t.length)return this.u8(0);let e=this.of();for(let[n,s]of t){let t=r.get(n);e[t.op||"one"](s,t)}this.push(e.pack())}one(t,e){this.u8(e.id),this[e.type](t)}kv_obj(t,e){for(let r of Object.entries(t))this.u8(e.id),this.pair(r)}u8_vec(t,e){for(let r of t)this.u8(e.id),this.u8(r)}}};function y(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}function w(t){let e=new Uint8Array(0);return r=>{e=0===e.byteLength?r:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,r);let n=[];for(;;){let[r,s]=y(e,1),i=r+s;if(e.byteLength<i)return n;let o=e[0],a=0===r?null:e.subarray(s,i);e=e.subarray(i);let u=t.decode_pkt(o,a,t);null!=u&&n.push(u)}}}const g=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function k(t=((...t)=>t)){let e,r,n=(t,n)=>{e=t,r=n};return s=>(s=new Promise(n),t(s,e,r))}const v=k();function q(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}Promise.resolve({type:"init"});const x={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:r}=this,n=t=>r[0].set(e,t);return r=>("string"==typeof r?e=r:(t=t+1&65535,e=r.pkt_id=t),new Promise(n))},answer(t,e){for(let r of this.hashbelt){let n=r.get(t);if(void 0!==n)return r.delete(t),n([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let r of e.splice(t||5))for(let t of r.values())t([,"expired"])},cmdids:(()=>{return[()=>{},r,e,r,t,t,t,t,r,t,r,t,e,e,r,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,n){t.answer(e.type,e),r(t,e,n)}async function r({target:t},e,r){let n=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(n?.call(t,e,r))}})()};class S extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class T{constructor(t={}){this.with(t),this._conn_=function(t,[e,r]){let n,s,i=v(),o=v(),a=async(...t)=>(await o[0])(...t);return t._send=a,{async when_ready(){await o[0]},ping:q((()=>n?.("pingreq"))),reset(e){n&&(e&&i[2](e),n=null,i=v(),t._send=a,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){n||await i[0];let r=await n(...e);return 0==r[0].reason&&(s=!0,o[1](t._send=n),o=v(),t.conn_emit("on_ready")),r},is_set:()=>!!n,set(o,a){if(n)throw new Error("Already connected");o=o.mqtt_stream();let u={mqtt:t};return n=async(t,e,n)=>{let s=void 0===n||r(n);return await a(o.encode_pkt(t,e)),s},i[1](n),t.conn_emit("on_live",s),t=>e(o.decode(t),u)}}}(this,this._init_dispatch(t,this))}with(t){for(let[e,r]of Object.entries(t))"function"==typeof r&&(this[e]=r);return this}async conn_emit(t,e,r){this.log_conn?.(t,e,r);try{let n=this[await t];if(n)await n.call(this,this,e,r);else if(r)throw r}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||this.client_id;"string"!=typeof e&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._conn_.send_connect("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this._conn_.ping(t.keep_alive),r}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,r){t=j(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=j(t,e,r),this._send("unsubscribe",t,t)}post(t,e,r){return this.pub({topic:t,payload:e,qos:0},r)}send(t,e,r){return this.pub({topic:t,payload:e,qos:1},r)}store(t,e,r){return this.pub({topic:t,payload:e,qos:1,retain:1},r)}obj_post(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:0},r)}obj_send(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1},r)}obj_store(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},r)}async pub(t,e){if(void 0===t.payload){"function"==typeof e&&(e={fn_encode:e});let{msg:r}=t;switch(typeof r){case"function":e={...e,fn_encode:r};case"undefined":return r=>this.pub({...t,[t.arg||"payload"]:r},e)}let{fn_encode:n}=e||{};t.payload=n?await n(r):JSON.stringify(r)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:void 0)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),function(t,e){let r=x.create(e),{cmdids:n}=r,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)n[s.id](r,s,e);Date.now()>o&&(r.rotate_belt(i),o=s+Date.now())},r.bind_pkt_future()]}(this,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;let e=t.prototype;e.MQTTError=S;for(let r of t._aliases().split(/\s+/)){r=r.split(":");let t=r[1]&&e[r[1]];t&&(e[r[0]]=t)}}}function j(t,e,r){if(e?.trim&&(r=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,r){let e=t=>t.trim?r+t:t.map(e);t.topics=t.topics.map(e)}return t}const P={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};class A extends T{static mqtt_ctx(t,e,r=P){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r){r={__proto__:r||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return g[this.b0>>>4]}};let n,s=[],i={};for(n of e.encode_fns)n(i,e.mqtt_writer);for(n of e.decode_fns)n(s,e.mqtt_reader);return{pkt_ctx:r,encode_pkt:(e,r)=>i[e](t,r),decode_pkt(t,e){let r=s[t>>>4]||s[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:r}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=w(t),t}}}(t,e,r),n}init_client_id(t=["u8-mqtt--",""]){let e,r=this.sess_stg,n=r?.getItem(e=t.join(" "));return n||(n=t.join(Math.random().toString(36).slice(2)),r?.setItem(e,n)),n}get sess_stg(){return globalThis.sessionStorage}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let r=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)r(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:r}=t;if(1!==r){if(0!==r)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:n}=this,s=n.set(this.mqtt_ctx,(async r=>(await e,t.send(r))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}n.reset(e)},this}}const N="0.5.0",U=A.mqtt_ctx(4,m),I=A.mqtt_ctx(5,m),M=t=>new U(t),Q=t=>new I(t);export{I as MQTTClient,U as MQTTClient_v4,I as MQTTClient_v5,Q as default,Q as mqtt,M as mqtt_v4,Q as mqtt_v5,N as version};
1
+ function t(t,e=[]){do{const r=127&t;t>>>=7,e.push(r|(0===t?0:128))}while(t>0);return e}function e(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}const r=n();function n(){let t=new Map,e=[[1,"u8","payload_format_indicator"],[2,"u32","message_expiry_interval"],[3,"utf8","content_type"],[8,"utf8","response_topic"],[9,"bin","correlation_data"],[11,"vint","subscription_identifier"],[17,"u32","session_expiry_interval"],[18,"utf8","assigned_client_identifier"],[19,"u16","server_keep_alive"],[21,"utf8","authentication_method"],[22,"bin","authentication_data"],[23,"u8","request_problem_information"],[24,"u32","will_delay_interval"],[25,"u8","request_response_information"],[26,"utf8","response_information"],[28,"utf8","server_reference"],[31,"utf8","reason_string"],[33,"u16","receive_maximum"],[34,"u16","topic_alias_maximum"],[35,"u16","topic_alias"],[36,"u8","maximum_qos"],[37,"u8","retain_available"],[38,"pair","user_properties",{op:"kv_obj"}],[39,"u32","maximum_packet_size"],[40,"u8","wildcard_subscription_available"],[41,"u8","subscription_identifiers_available",{op:"u8_vec"}],[42,"u8","shared_subscription_available"]];for(let[r,n,s,i]of e){let e={id:r,type:n,name:s,...i};t.set(e.id,e),t.set(e.name,e)}return t}class s extends Number{static of(t,e,r){let n=new this(t);return n.reason=r?.[e]?.get(t)||e,n}}class i{static of(t){return this.prototype.of(t)}of(t){let e=(t,r)=>(r=0|e.k,e.k=r+t,r);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,r=e(2);return t[r]<<8|t[r+1]}u32(){let{buf:t,step:e}=this,r=e(4);return t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]}vint(){let{buf:t,step:r}=this,[n,s,i]=e(t,0|r.k);return r(s-i),n}bin(){let{buf:t,step:e}=this,r=e(2),n=t[r]<<8|t[r+1];return r=e(n),t.subarray(r,r+n)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let e=this.buf[this.step(1)];if(null!=e)return s.of(e,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}}let o=class extends i{props(){let{buf:t,step:n}=this,[s,i,o]=e(t,0|n.k);if(n(s+i-o),0===s)return null;let a={},u=this.of(t.subarray(i,0|n.k));for(;u.has_more();){let t=r.get(u.u8()),e=u[t.type]();a[t.name]=t.op?u[t.op](a[t.name],e):e}return a}kv_obj(t=Object.create(null),[e,r]){return t[e]=r,t}u8_vec(t=[],e){return t.push(e),t}};function a(t,...e){t=class extends t{static reasons(t,...e){let r=this.prototype;r._reasons_by={...r._reasons_by};let n=r._reasons_by[t]||=new Map;for(let[t,r]of e)n.set(t,r);return this}};for(let r of e)r(t);return t}class u{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let r,n,s=0,i=this.$;for(r of(this.$=!1,i))s+=r.length;n=(e=t(s,e)).length;let o=new Uint8Array(n+s);for(r of(o.set(e,0),i))o.set(r,n),n+=r.length;return o}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,r=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=r,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}function c(t){!function(t){t.reasons("connack",[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"])}(t),t.reasons("connack",[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[132,"Unsupported Protocol Version"],[133,"Client Identifier not valid"],[134,"Bad User Name or Password"],[135,"Not authorized"],[136,"Server unavailable"],[137,"Server busy"],[138,"Banned"],[140,"Bad authentication method"],[144,"Topic Name invalid"],[149,"Packet too large"],[151,"Quota exceeded"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[159,"Connection rate exceeded"])}function p(t){t.reasons("puback",[0,"Success"],[16,"No matching subscribers"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[144,"Topic Name invalid"],[145,"Packet identifier in use"],[151,"Quota exceeded"],[153,"Payload format invalid"])}function l(t){return(e,r)=>{let n=t.of(r);e.pkt_id=n.u16(),5<=e.mqtt_level&&(e.props=n.props());let s=e.answers=[];for(;n.has_more();)s.push(n.reason(e.type));return e}}function _(t){!function(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}(t),t.reasons("suback",[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"],[151,"Quota exceeded"],[158,"Shared Subscriptions not supported"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function f(t){t.reasons("unsuback",[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"])}function d(t){t.reasons("disconnect",[0,"Normal disconnection"],[4,"Disconnect with Will Message"],[128,"Unspecified error"],[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[135,"Not authorized"],[137,"Server busy"],[139,"Server shutting down"],[141,"Keep Alive timeout"],[142,"Session taken over"],[143,"Topic Filter invalid"],[144,"Topic Name invalid"],[147,"Receive Maximum exceeded"],[148,"Topic Alias invalid"],[149,"Packet too large"],[150,"Message rate too high"],[151,"Quota exceeded"],[152,"Administrative action"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[158,"Shared Subscriptions not supported"],[159,"Connection rate exceeded"],[160,"Maximum connect time"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function h(t){t.reasons("auth",[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"])}const b=[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,s)=>{let i=e.of(s);i.push(r),i.u8(t);let{will:o,username:a,password:u}=s,c=i.flags(s.flags,n,0|(a?128:0)|(u?64:0)|(o?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(o):0));return i.u16(s.keep_alive),5<=t&&i.props(s.props),i.utf8(s.client_id),4&c&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&c&&i.utf8(a),64&c&&i.bin(u),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.of(r);return n.u16(r.pkt_id),5<=t&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(64)}},function(t,e){return t.publish=(t,r)=>{let n=(3&r.qos)<<1,s=e.of(r);return s.utf8(r.topic),0!==n&&s.u16(r.pkt_id),5<=t?(s.props(r.props),s.flush(r.payload)):s.flush(r.payload),s.as_pkt(48|n|(r.dup?8:0)|(r.retain?1:0))}},function(t,e){const r=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.of(n);s.u16(n.pkt_id),5<=t&&s.props(n.props);let i=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(i);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(i):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,r)=>{let n=e.of(r);n.u16(r.pkt_id),5<=t&&n.props(r.props);for(let t of r.topics)n.utf8(t);return n.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,r)=>{let n=e.of(r);return r&&5<=t&&(r.reason||r.props)&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(224)}},function(t,e){return t.auth=(t,r)=>{if(5>t)throw new Error("Auth packets are only available after MQTT 5.x");let n=e.of(r);return n.reason(r.reason),n.props(r.props),n.as_pkt(240)}}],m={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.of(n);return t.flags=s.flags(r),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,r)=>{let{hdr:n}=t;t.dup=Boolean(8&n),t.retain=Boolean(1&n);let s=t.qos=n>>1&3,i=e.of(r);return t.topic=i.utf8(),0!==s&&(t.pkt_id=i.u16()),5<=t.mqtt_level&&(t.props=i.props()),t.payload=i.flush(),t}},function(t,e){return t[4]=(t,r)=>{let n=e.of(r);return t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.reason=n.reason(t.type),t.props=n.props()),t}},function(t,e){return t[9]=l(e)},function(t,e){return t[11]=l(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,r)=>{if(r&&5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}},function(t,e){return t[15]=(t,r)=>{if(5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}}],mqtt_reader:a(o,c,p,_,f,d,h),encode_fns:b,mqtt_writer:class extends u{props(t){if(!t)return this.u8(0);if(Array.isArray(t)||(t=t.entries?Array.from(t.entries()):Object.entries(t)),0===t.length)return this.u8(0);let e=this.of();for(let[n,s]of t){let t=r.get(n);e[t.op||"one"](s,t)}this.push(e.pack())}one(t,e){this.u8(e.id),this[e.type](t)}kv_obj(t,e){for(let r of Object.entries(t))this.u8(e.id),this.pair(r)}u8_vec(t,e){for(let r of t)this.u8(e.id),this.u8(r)}}};function y(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}function w(t){let e=new Uint8Array(0);return r=>{e=0===e.byteLength?r:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,r);let n=[];for(;;){let[r,s]=y(e,1),i=r+s;if(e.byteLength<i)return n;let o=e[0],a=0===r?null:e.subarray(s,i);e=e.subarray(i);let u=t.decode_pkt(o,a,t);null!=u&&n.push(u)}}}const g=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function k(t=((...t)=>t)){let e,r,n=(t,n)=>{e=t,r=n};return s=>(s=new Promise(n),t(s,e,r))}const v=k();function q(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}Promise.resolve({type:"init"});const x={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:r}=this,n=t=>r[0].set(e,t);return r=>("string"==typeof r?e=r:(t=t+1&65535,e=r.pkt_id=t),new Promise(n))},answer(t,e){for(let r of this.hashbelt){let n=r.get(t);if(void 0!==n)return r.delete(t),n([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let r of e.splice(t||5))for(let t of r.values())t([,"expired"])},cmdids:(()=>{return[()=>{},r,e,r,t,t,t,t,r,t,r,t,e,e,r,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,n){t.answer(e.type,e),r(t,e,n)}async function r({target:t},e,r){let n=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(n?.call(t,e,r))}})()};class S extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class T{constructor(t={}){this.with(t),this._conn_=function(t,[e,r]){let n,s,i=v(),o=v(),a=async(...t)=>(await o[0])(...t);return t._send=a,{async when_ready(){await o[0]},ping:q((()=>n?.("pingreq"))),reset(e){n&&(e&&i[2](e),n=null,i=v(),t._send=a,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){n||await i[0];let r=await n(...e);return 0==r[0].reason&&(s=!0,o[1](t._send=n),o=v(),t.conn_emit("on_ready")),r},is_set:()=>!!n,set(o,a){if(n)throw new Error("Already connected");o=o.mqtt_stream();let u={mqtt:t};return n=async(t,e,n)=>{let s=void 0===n||r(n);return await a(o.encode_pkt(t,e)),s},i[1](n),t.conn_emit("on_live",s),t=>e(o.decode(t),u)}}}(this,this._init_dispatch(t,this))}with(t){for(let[e,r]of Object.entries(t))"function"==typeof r&&(this[e]=r);return this}async conn_emit(t,e,r){this.log_conn?.(t,e,r);try{let n=this[await t];if(n)await n.call(this,this,e,r);else if(r)throw r}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||this.client_id;"string"!=typeof e&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._conn_.send_connect("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this._conn_.ping(t.keep_alive),r}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,r){t=j(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=j(t,e,r),this._send("unsubscribe",t,t)}post(t,e,r){return this.pub({topic:t,payload:e,qos:0},r)}send(t,e,r){return this.pub({topic:t,payload:e,qos:1},r)}store(t,e,r){return this.pub({topic:t,payload:e,qos:1,retain:1},r)}obj_post(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:0},r)}obj_send(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1},r)}obj_store(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},r)}async pub(t,e){if(void 0===t.payload){"function"==typeof e&&(e={fn_encode:e});let{msg:r}=t;switch(typeof r){case"function":e={...e,fn_encode:r};case"undefined":return r=>this.pub({...t,[t.arg||"payload"]:r},e)}let{fn_encode:n}=e||{};t.payload=n?await n(r):JSON.stringify(r)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:void 0)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),function(t,e){let r=x.create(e),{cmdids:n}=r,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)n[s.id](r,s,e);Date.now()>o&&(r.rotate_belt(i),o=s+Date.now())},r.bind_pkt_future()]}(this,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;let e=t.prototype;e.MQTTError=S;for(let r of t._aliases().split(/\s+/)){r=r.split(":");let t=r[1]&&e[r[1]];t&&(e[r[0]]=t)}}}function j(t,e,r){if(e?.trim&&(r=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,r){let e=t=>t.trim?r+t:t.map(e);t.topics=t.topics.map(e)}return t}const P={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};class A extends T{static mqtt_ctx(t,e,r=P){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r){r={__proto__:r||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return g[this.b0>>>4]}};let n,s=[],i={};for(n of e.encode_fns)n(i,e.mqtt_writer);for(n of e.decode_fns)n(s,e.mqtt_reader);return{pkt_ctx:r,encode_pkt:(e,r)=>i[e](t,r),decode_pkt(t,e){let r=s[t>>>4]||s[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:r}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=w(t),t}}}(t,e,r),n}init_client_id(t=["u8-mqtt--",""]){let e,r=this.sess_stg,n=r?.getItem(e=t.join(" "));return n||(n=t.join(Math.random().toString(36).slice(2)),r?.setItem(e,n)),n}get sess_stg(){return globalThis.sessionStorage}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let r=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)r(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:r}=t;if(1!==r){if(0!==r)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:n}=this,s=n.set(this.mqtt_ctx,(async r=>(await e,t.send(r))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}n.reset(e)},this}}const N="0.5.2-web",U=A.mqtt_ctx(4,m),I=A.mqtt_ctx(5,m),M=t=>new U(t),Q=t=>new I(t);export{I as MQTTClient,U as MQTTClient_v4,I as MQTTClient_v5,Q as default,Q as mqtt,M as mqtt_v4,Q as mqtt_v5,N as version};
Binary file
Binary file
package/esm/web/index.js CHANGED
@@ -1579,7 +1579,7 @@ class MQTTCore extends MQTTBase {
1579
1579
 
1580
1580
  return this} }
1581
1581
 
1582
- const version = '0.5.0';
1582
+ const version = '0.5.2-web';
1583
1583
 
1584
1584
  const MQTTClient_v4 = /* #__PURE__ */
1585
1585
  with_topic_path_router(
@@ -1 +1 @@
1
- function t(t,e=[]){do{const r=127&t;t>>>=7,e.push(r|(0===t?0:128))}while(t>0);return e}function e(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}const r=n();function n(){let t=new Map,e=[[1,"u8","payload_format_indicator"],[2,"u32","message_expiry_interval"],[3,"utf8","content_type"],[8,"utf8","response_topic"],[9,"bin","correlation_data"],[11,"vint","subscription_identifier"],[17,"u32","session_expiry_interval"],[18,"utf8","assigned_client_identifier"],[19,"u16","server_keep_alive"],[21,"utf8","authentication_method"],[22,"bin","authentication_data"],[23,"u8","request_problem_information"],[24,"u32","will_delay_interval"],[25,"u8","request_response_information"],[26,"utf8","response_information"],[28,"utf8","server_reference"],[31,"utf8","reason_string"],[33,"u16","receive_maximum"],[34,"u16","topic_alias_maximum"],[35,"u16","topic_alias"],[36,"u8","maximum_qos"],[37,"u8","retain_available"],[38,"pair","user_properties",{op:"kv_obj"}],[39,"u32","maximum_packet_size"],[40,"u8","wildcard_subscription_available"],[41,"u8","subscription_identifiers_available",{op:"u8_vec"}],[42,"u8","shared_subscription_available"]];for(let[r,n,s,i]of e){let e={id:r,type:n,name:s,...i};t.set(e.id,e),t.set(e.name,e)}return t}class s extends Number{static of(t,e,r){let n=new this(t);return n.reason=r?.[e]?.get(t)||e,n}}class i{static of(t){return this.prototype.of(t)}of(t){let e=(t,r)=>(r=0|e.k,e.k=r+t,r);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,r=e(2);return t[r]<<8|t[r+1]}u32(){let{buf:t,step:e}=this,r=e(4);return t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]}vint(){let{buf:t,step:r}=this,[n,s,i]=e(t,0|r.k);return r(s-i),n}bin(){let{buf:t,step:e}=this,r=e(2),n=t[r]<<8|t[r+1];return r=e(n),t.subarray(r,r+n)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let e=this.buf[this.step(1)];if(null!=e)return s.of(e,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}}let o=class extends i{props(){let{buf:t,step:n}=this,[s,i,o]=e(t,0|n.k);if(n(s+i-o),0===s)return null;let u={},a=this.of(t.subarray(i,0|n.k));for(;a.has_more();){let t=r.get(a.u8()),e=a[t.type]();u[t.name]=t.op?a[t.op](u[t.name],e):e}return u}kv_obj(t=Object.create(null),[e,r]){return t[e]=r,t}u8_vec(t=[],e){return t.push(e),t}};function u(t,...e){t=class extends t{static reasons(t,...e){let r=this.prototype;r._reasons_by={...r._reasons_by};let n=r._reasons_by[t]||=new Map;for(let[t,r]of e)n.set(t,r);return this}};for(let r of e)r(t);return t}class a{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let r,n,s=0,i=this.$;for(r of(this.$=!1,i))s+=r.length;n=(e=t(s,e)).length;let o=new Uint8Array(n+s);for(r of(o.set(e,0),i))o.set(r,n),n+=r.length;return o}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,r=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=r,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}function c(t){!function(t){t.reasons("connack",[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"])}(t),t.reasons("connack",[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[132,"Unsupported Protocol Version"],[133,"Client Identifier not valid"],[134,"Bad User Name or Password"],[135,"Not authorized"],[136,"Server unavailable"],[137,"Server busy"],[138,"Banned"],[140,"Bad authentication method"],[144,"Topic Name invalid"],[149,"Packet too large"],[151,"Quota exceeded"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[159,"Connection rate exceeded"])}function p(t){t.reasons("puback",[0,"Success"],[16,"No matching subscribers"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[144,"Topic Name invalid"],[145,"Packet identifier in use"],[151,"Quota exceeded"],[153,"Payload format invalid"])}function l(t){return(e,r)=>{let n=t.of(r);e.pkt_id=n.u16(),5<=e.mqtt_level&&(e.props=n.props());let s=e.answers=[];for(;n.has_more();)s.push(n.reason(e.type));return e}}function _(t){!function(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}(t),t.reasons("suback",[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"],[151,"Quota exceeded"],[158,"Shared Subscriptions not supported"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function f(t){t.reasons("unsuback",[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"])}function d(t){t.reasons("disconnect",[0,"Normal disconnection"],[4,"Disconnect with Will Message"],[128,"Unspecified error"],[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[135,"Not authorized"],[137,"Server busy"],[139,"Server shutting down"],[141,"Keep Alive timeout"],[142,"Session taken over"],[143,"Topic Filter invalid"],[144,"Topic Name invalid"],[147,"Receive Maximum exceeded"],[148,"Topic Alias invalid"],[149,"Packet too large"],[150,"Message rate too high"],[151,"Quota exceeded"],[152,"Administrative action"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[158,"Shared Subscriptions not supported"],[159,"Connection rate exceeded"],[160,"Maximum connect time"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function h(t){t.reasons("auth",[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"])}const b=[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,s)=>{let i=e.of(s);i.push(r),i.u8(t);let{will:o,username:u,password:a}=s,c=i.flags(s.flags,n,0|(u?128:0)|(a?64:0)|(o?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(o):0));return i.u16(s.keep_alive),5<=t&&i.props(s.props),i.utf8(s.client_id),4&c&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&c&&i.utf8(u),64&c&&i.bin(a),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.of(r);return n.u16(r.pkt_id),5<=t&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(64)}},function(t,e){return t.publish=(t,r)=>{let n=(3&r.qos)<<1,s=e.of(r);return s.utf8(r.topic),0!==n&&s.u16(r.pkt_id),5<=t?(s.props(r.props),s.flush(r.payload)):s.flush(r.payload),s.as_pkt(48|n|(r.dup?8:0)|(r.retain?1:0))}},function(t,e){const r=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.of(n);s.u16(n.pkt_id),5<=t&&s.props(n.props);let i=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(i);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(i):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,r)=>{let n=e.of(r);n.u16(r.pkt_id),5<=t&&n.props(r.props);for(let t of r.topics)n.utf8(t);return n.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,r)=>{let n=e.of(r);return r&&5<=t&&(r.reason||r.props)&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(224)}},function(t,e){return t.auth=(t,r)=>{if(5>t)throw new Error("Auth packets are only available after MQTT 5.x");let n=e.of(r);return n.reason(r.reason),n.props(r.props),n.as_pkt(240)}}],m={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.of(n);return t.flags=s.flags(r),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,r)=>{let{hdr:n}=t;t.dup=Boolean(8&n),t.retain=Boolean(1&n);let s=t.qos=n>>1&3,i=e.of(r);return t.topic=i.utf8(),0!==s&&(t.pkt_id=i.u16()),5<=t.mqtt_level&&(t.props=i.props()),t.payload=i.flush(),t}},function(t,e){return t[4]=(t,r)=>{let n=e.of(r);return t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.reason=n.reason(t.type),t.props=n.props()),t}},function(t,e){return t[9]=l(e)},function(t,e){return t[11]=l(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,r)=>{if(r&&5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}},function(t,e){return t[15]=(t,r)=>{if(5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}}],mqtt_reader:u(o,c,p,_,f,d,h),encode_fns:b,mqtt_writer:class extends a{props(t){if(!t)return this.u8(0);if(Array.isArray(t)||(t=t.entries?Array.from(t.entries()):Object.entries(t)),0===t.length)return this.u8(0);let e=this.of();for(let[n,s]of t){let t=r.get(n);e[t.op||"one"](s,t)}this.push(e.pack())}one(t,e){this.u8(e.id),this[e.type](t)}kv_obj(t,e){for(let r of Object.entries(t))this.u8(e.id),this.pair(r)}u8_vec(t,e){for(let r of t)this.u8(e.id),this.u8(r)}}};const y=t=>e=>class extends e{static _aliases(){return super._aliases()+" sub_topic:subscribe_topic unsub_topic:unsubscribe_topic"}_init_router(e,r,n){this._subs=[];let s=this.router=n.router=t(e,this,n);return s?.invoke}on_sub(t,e){return t.pkt=e,this._subs.push(t),t}subs_settled(){return Promise.allSettled(this._subs.splice(0,1/0))}subscribe_topic(t,...e){let r=this.router;r.add(t,!0,e.pop());let n=r.mqtt_topic(t);return this.subscribe(n,...e),this}unsubscribe_topic(t,...e){let r=this.router;r.remove(t,!0);let n=r.mqtt_topic(t);return this.unsubscribe(n,...e)}on_topic(...t){return this.router.add(...t),this}},w=y(x),g=t=>t.replace(/[*].*$/,"#").replace(/:\w[^\/]*/g,"+"),k=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function v(t,e,r){r.done=!0}function x(){let t=[[],[]],e=Symbol(),r=e=>function*(t,e){e=e.replace(/^[\/]*/,"/");for(let r of t)for(let{keys:t,pattern:n,tgt:s}of r){let r=n.exec(e);if(r){let e=t?t.reduce(((t,e,n)=>(t[e]=r[1+n],t)),{}):r.groups??r;yield[s,e]}}}(t,e);return{find:r,mqtt_topic:g,add(e,...r){let n=r.pop(),s=r.pop();if("function"!=typeof n){if(n)throw new TypeError;n=v}let i=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var r,n,s,i,o=[],u="",a=t.split("/");for(a[0]||a.shift();s=a.shift();)"*"===(r=s[0])?(o.push("wild"),u+="/(.*)"):":"===r?(n=s.indexOf("?",1),i=s.indexOf(".",1),o.push(s.substring(1,~n?n:~i?i:s.length)),u+=~n&&!~i?"(?:/([^/]+?))?":"/([^/]+?)",~i&&(u+=(~n?"?":"")+"\\"+s.substring(i))):u+="/"+s;return{keys:o,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(k(e));return i.key=e,i.tgt=n,t[s?0:1].push(i),this},remove:(e,r)=>q([t[r?0:1]],e),clear(e){t[e?0:1]=[],null==e&&(t[1]=[])},async invoke(n,s){s.idx=0,s.rm=e;for(let[i,o]of r(n.topic)){let r=await i(n,o,s);if(e===r&&q(t,i),s.done)break;s.idx++}1===n.qos&&await s.mqtt.puback(n)}}}function q(t,e){let r=t=>t===e||t.tgt===e||t.key===e;for(let e of t){let t=e.findIndex(r);if(0<=t)return e.splice(t,1),!0}return!1}function S(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}function T(t){let e=new Uint8Array(0);return r=>{e=0===e.byteLength?r:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,r);let n=[];for(;;){let[r,s]=S(e,1),i=r+s;if(e.byteLength<i)return n;let o=e[0],u=0===r?null:e.subarray(s,i);e=e.subarray(i);let a=t.decode_pkt(o,u,t);null!=a&&n.push(a)}}}const j=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function P(t=((...t)=>t)){let e,r,n=(t,n)=>{e=t,r=n};return s=>(s=new Promise(n),t(s,e,r))}const A=P();function N(t,[e,r]){let n,s,i=A(),o=A(),u=async(...t)=>(await o[0])(...t);return t._send=u,{async when_ready(){await o[0]},ping:U((()=>n?.("pingreq"))),reset(e){n&&(e&&i[2](e),n=null,i=A(),t._send=u,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){n||await i[0];let r=await n(...e);return 0==r[0].reason&&(s=!0,o[1](t._send=n),o=A(),t.conn_emit("on_ready")),r},is_set:()=>!!n,set(o,u){if(n)throw new Error("Already connected");o=o.mqtt_stream();let a={mqtt:t};return n=async(t,e,n)=>{let s=void 0===n||r(n);return await u(o.encode_pkt(t,e)),s},i[1](n),t.conn_emit("on_live",s),t=>e(o.decode(t),a)}}}function U(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}Promise.resolve({type:"init"});const I={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:r}=this,n=t=>r[0].set(e,t);return r=>("string"==typeof r?e=r:(t=t+1&65535,e=r.pkt_id=t),new Promise(n))},answer(t,e){for(let r of this.hashbelt){let n=r.get(t);if(void 0!==n)return r.delete(t),n([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let r of e.splice(t||5))for(let t of r.values())t([,"expired"])},cmdids:(()=>{return[()=>{},r,e,r,t,t,t,t,r,t,r,t,e,e,r,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,n){t.answer(e.type,e),r(t,e,n)}async function r({target:t},e,r){let n=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(n?.call(t,e,r))}})()};function E(t,e){let r=I.create(e),{cmdids:n}=r,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)n[s.id](r,s,e);Date.now()>o&&(r.rotate_belt(i),o=s+Date.now())},r.bind_pkt_future()]}class M extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class Q{constructor(t={}){this.with(t),this._conn_=N(this,this._init_dispatch(t,this))}with(t){for(let[e,r]of Object.entries(t))"function"==typeof r&&(this[e]=r);return this}async conn_emit(t,e,r){this.log_conn?.(t,e,r);try{let n=this[await t];if(n)await n.call(this,this,e,r);else if(r)throw r}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||this.client_id;"string"!=typeof e&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._conn_.send_connect("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this._conn_.ping(t.keep_alive),r}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,r){t=$(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=$(t,e,r),this._send("unsubscribe",t,t)}post(t,e,r){return this.pub({topic:t,payload:e,qos:0},r)}send(t,e,r){return this.pub({topic:t,payload:e,qos:1},r)}store(t,e,r){return this.pub({topic:t,payload:e,qos:1,retain:1},r)}obj_post(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:0},r)}obj_send(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1},r)}obj_store(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},r)}async pub(t,e){if(void 0===t.payload){"function"==typeof e&&(e={fn_encode:e});let{msg:r}=t;switch(typeof r){case"function":e={...e,fn_encode:r};case"undefined":return r=>this.pub({...t,[t.arg||"payload"]:r},e)}let{fn_encode:n}=e||{};t.payload=n?await n(r):JSON.stringify(r)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:void 0)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),E(this,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;let e=t.prototype;e.MQTTError=M;for(let r of t._aliases().split(/\s+/)){r=r.split(":");let t=r[1]&&e[r[1]];t&&(e[r[0]]=t)}}}function $(t,e,r){if(e?.trim&&(r=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,r){let e=t=>t.trim?r+t:t.map(e);t.topics=t.topics.map(e)}return t}const C={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};class L extends Q{static mqtt_ctx(t,e,r=C){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r){r={__proto__:r||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return j[this.b0>>>4]}};let n,s=[],i={};for(n of e.encode_fns)n(i,e.mqtt_writer);for(n of e.decode_fns)n(s,e.mqtt_reader);return{pkt_ctx:r,encode_pkt:(e,r)=>i[e](t,r),decode_pkt(t,e){let r=s[t>>>4]||s[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:r}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=T(t),t}}}(t,e,r),n}init_client_id(t=["u8-mqtt--",""]){let e,r=this.sess_stg,n=r?.getItem(e=t.join(" "));return n||(n=t.join(Math.random().toString(36).slice(2)),r?.setItem(e,n)),n}get sess_stg(){return globalThis.sessionStorage}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let r=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)r(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:r}=t;if(1!==r){if(0!==r)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:n}=this,s=n.set(this.mqtt_ctx,(async r=>(await e,t.send(r))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}n.reset(e)},this}}const O="0.5.0",z=w(L.mqtt_ctx(4,m)),R=w(L.mqtt_ctx(5,m)),D=t=>new z(t),B=t=>new R(t);export{Q as MQTTBase,z as MQTTClient_v4,R as MQTTClient_v5,L as MQTTCore,M as MQTTError,I as _mqtt_cmdid_dispatch,N as _mqtt_conn,E as _mqtt_dispatch,A as ao_defer_v,k as as_topic_path,D as default,D as mqtt_v4,B as mqtt_v5,O as version,w as with_topic_path_router,y as with_topic_router};
1
+ function t(t,e=[]){do{const r=127&t;t>>>=7,e.push(r|(0===t?0:128))}while(t>0);return e}function e(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}const r=n();function n(){let t=new Map,e=[[1,"u8","payload_format_indicator"],[2,"u32","message_expiry_interval"],[3,"utf8","content_type"],[8,"utf8","response_topic"],[9,"bin","correlation_data"],[11,"vint","subscription_identifier"],[17,"u32","session_expiry_interval"],[18,"utf8","assigned_client_identifier"],[19,"u16","server_keep_alive"],[21,"utf8","authentication_method"],[22,"bin","authentication_data"],[23,"u8","request_problem_information"],[24,"u32","will_delay_interval"],[25,"u8","request_response_information"],[26,"utf8","response_information"],[28,"utf8","server_reference"],[31,"utf8","reason_string"],[33,"u16","receive_maximum"],[34,"u16","topic_alias_maximum"],[35,"u16","topic_alias"],[36,"u8","maximum_qos"],[37,"u8","retain_available"],[38,"pair","user_properties",{op:"kv_obj"}],[39,"u32","maximum_packet_size"],[40,"u8","wildcard_subscription_available"],[41,"u8","subscription_identifiers_available",{op:"u8_vec"}],[42,"u8","shared_subscription_available"]];for(let[r,n,s,i]of e){let e={id:r,type:n,name:s,...i};t.set(e.id,e),t.set(e.name,e)}return t}class s extends Number{static of(t,e,r){let n=new this(t);return n.reason=r?.[e]?.get(t)||e,n}}class i{static of(t){return this.prototype.of(t)}of(t){let e=(t,r)=>(r=0|e.k,e.k=r+t,r);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,r=e(2);return t[r]<<8|t[r+1]}u32(){let{buf:t,step:e}=this,r=e(4);return t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]}vint(){let{buf:t,step:r}=this,[n,s,i]=e(t,0|r.k);return r(s-i),n}bin(){let{buf:t,step:e}=this,r=e(2),n=t[r]<<8|t[r+1];return r=e(n),t.subarray(r,r+n)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let e=this.buf[this.step(1)];if(null!=e)return s.of(e,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}}let o=class extends i{props(){let{buf:t,step:n}=this,[s,i,o]=e(t,0|n.k);if(n(s+i-o),0===s)return null;let u={},a=this.of(t.subarray(i,0|n.k));for(;a.has_more();){let t=r.get(a.u8()),e=a[t.type]();u[t.name]=t.op?a[t.op](u[t.name],e):e}return u}kv_obj(t=Object.create(null),[e,r]){return t[e]=r,t}u8_vec(t=[],e){return t.push(e),t}};function u(t,...e){t=class extends t{static reasons(t,...e){let r=this.prototype;r._reasons_by={...r._reasons_by};let n=r._reasons_by[t]||=new Map;for(let[t,r]of e)n.set(t,r);return this}};for(let r of e)r(t);return t}class a{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let r,n,s=0,i=this.$;for(r of(this.$=!1,i))s+=r.length;n=(e=t(s,e)).length;let o=new Uint8Array(n+s);for(r of(o.set(e,0),i))o.set(r,n),n+=r.length;return o}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,r=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=r,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}function c(t){!function(t){t.reasons("connack",[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"])}(t),t.reasons("connack",[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[132,"Unsupported Protocol Version"],[133,"Client Identifier not valid"],[134,"Bad User Name or Password"],[135,"Not authorized"],[136,"Server unavailable"],[137,"Server busy"],[138,"Banned"],[140,"Bad authentication method"],[144,"Topic Name invalid"],[149,"Packet too large"],[151,"Quota exceeded"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[159,"Connection rate exceeded"])}function p(t){t.reasons("puback",[0,"Success"],[16,"No matching subscribers"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[144,"Topic Name invalid"],[145,"Packet identifier in use"],[151,"Quota exceeded"],[153,"Payload format invalid"])}function l(t){return(e,r)=>{let n=t.of(r);e.pkt_id=n.u16(),5<=e.mqtt_level&&(e.props=n.props());let s=e.answers=[];for(;n.has_more();)s.push(n.reason(e.type));return e}}function _(t){!function(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}(t),t.reasons("suback",[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"],[151,"Quota exceeded"],[158,"Shared Subscriptions not supported"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function f(t){t.reasons("unsuback",[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"])}function d(t){t.reasons("disconnect",[0,"Normal disconnection"],[4,"Disconnect with Will Message"],[128,"Unspecified error"],[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[135,"Not authorized"],[137,"Server busy"],[139,"Server shutting down"],[141,"Keep Alive timeout"],[142,"Session taken over"],[143,"Topic Filter invalid"],[144,"Topic Name invalid"],[147,"Receive Maximum exceeded"],[148,"Topic Alias invalid"],[149,"Packet too large"],[150,"Message rate too high"],[151,"Quota exceeded"],[152,"Administrative action"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[158,"Shared Subscriptions not supported"],[159,"Connection rate exceeded"],[160,"Maximum connect time"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function h(t){t.reasons("auth",[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"])}const b=[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,s)=>{let i=e.of(s);i.push(r),i.u8(t);let{will:o,username:u,password:a}=s,c=i.flags(s.flags,n,0|(u?128:0)|(a?64:0)|(o?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(o):0));return i.u16(s.keep_alive),5<=t&&i.props(s.props),i.utf8(s.client_id),4&c&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&c&&i.utf8(u),64&c&&i.bin(a),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.of(r);return n.u16(r.pkt_id),5<=t&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(64)}},function(t,e){return t.publish=(t,r)=>{let n=(3&r.qos)<<1,s=e.of(r);return s.utf8(r.topic),0!==n&&s.u16(r.pkt_id),5<=t?(s.props(r.props),s.flush(r.payload)):s.flush(r.payload),s.as_pkt(48|n|(r.dup?8:0)|(r.retain?1:0))}},function(t,e){const r=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.of(n);s.u16(n.pkt_id),5<=t&&s.props(n.props);let i=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(i);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(i):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,r)=>{let n=e.of(r);n.u16(r.pkt_id),5<=t&&n.props(r.props);for(let t of r.topics)n.utf8(t);return n.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,r)=>{let n=e.of(r);return r&&5<=t&&(r.reason||r.props)&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(224)}},function(t,e){return t.auth=(t,r)=>{if(5>t)throw new Error("Auth packets are only available after MQTT 5.x");let n=e.of(r);return n.reason(r.reason),n.props(r.props),n.as_pkt(240)}}],m={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.of(n);return t.flags=s.flags(r),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,r)=>{let{hdr:n}=t;t.dup=Boolean(8&n),t.retain=Boolean(1&n);let s=t.qos=n>>1&3,i=e.of(r);return t.topic=i.utf8(),0!==s&&(t.pkt_id=i.u16()),5<=t.mqtt_level&&(t.props=i.props()),t.payload=i.flush(),t}},function(t,e){return t[4]=(t,r)=>{let n=e.of(r);return t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.reason=n.reason(t.type),t.props=n.props()),t}},function(t,e){return t[9]=l(e)},function(t,e){return t[11]=l(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,r)=>{if(r&&5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}},function(t,e){return t[15]=(t,r)=>{if(5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}}],mqtt_reader:u(o,c,p,_,f,d,h),encode_fns:b,mqtt_writer:class extends a{props(t){if(!t)return this.u8(0);if(Array.isArray(t)||(t=t.entries?Array.from(t.entries()):Object.entries(t)),0===t.length)return this.u8(0);let e=this.of();for(let[n,s]of t){let t=r.get(n);e[t.op||"one"](s,t)}this.push(e.pack())}one(t,e){this.u8(e.id),this[e.type](t)}kv_obj(t,e){for(let r of Object.entries(t))this.u8(e.id),this.pair(r)}u8_vec(t,e){for(let r of t)this.u8(e.id),this.u8(r)}}};const y=t=>e=>class extends e{static _aliases(){return super._aliases()+" sub_topic:subscribe_topic unsub_topic:unsubscribe_topic"}_init_router(e,r,n){this._subs=[];let s=this.router=n.router=t(e,this,n);return s?.invoke}on_sub(t,e){return t.pkt=e,this._subs.push(t),t}subs_settled(){return Promise.allSettled(this._subs.splice(0,1/0))}subscribe_topic(t,...e){let r=this.router;r.add(t,!0,e.pop());let n=r.mqtt_topic(t);return this.subscribe(n,...e),this}unsubscribe_topic(t,...e){let r=this.router;r.remove(t,!0);let n=r.mqtt_topic(t);return this.unsubscribe(n,...e)}on_topic(...t){return this.router.add(...t),this}},w=y(x),g=t=>t.replace(/[*].*$/,"#").replace(/:\w[^\/]*/g,"+"),k=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function v(t,e,r){r.done=!0}function x(){let t=[[],[]],e=Symbol(),r=e=>function*(t,e){e=e.replace(/^[\/]*/,"/");for(let r of t)for(let{keys:t,pattern:n,tgt:s}of r){let r=n.exec(e);if(r){let e=t?t.reduce(((t,e,n)=>(t[e]=r[1+n],t)),{}):r.groups??r;yield[s,e]}}}(t,e);return{find:r,mqtt_topic:g,add(e,...r){let n=r.pop(),s=r.pop();if("function"!=typeof n){if(n)throw new TypeError;n=v}let i=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var r,n,s,i,o=[],u="",a=t.split("/");for(a[0]||a.shift();s=a.shift();)"*"===(r=s[0])?(o.push("wild"),u+="/(.*)"):":"===r?(n=s.indexOf("?",1),i=s.indexOf(".",1),o.push(s.substring(1,~n?n:~i?i:s.length)),u+=~n&&!~i?"(?:/([^/]+?))?":"/([^/]+?)",~i&&(u+=(~n?"?":"")+"\\"+s.substring(i))):u+="/"+s;return{keys:o,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(k(e));return i.key=e,i.tgt=n,t[s?0:1].push(i),this},remove:(e,r)=>q([t[r?0:1]],e),clear(e){t[e?0:1]=[],null==e&&(t[1]=[])},async invoke(n,s){s.idx=0,s.rm=e;for(let[i,o]of r(n.topic)){let r=await i(n,o,s);if(e===r&&q(t,i),s.done)break;s.idx++}1===n.qos&&await s.mqtt.puback(n)}}}function q(t,e){let r=t=>t===e||t.tgt===e||t.key===e;for(let e of t){let t=e.findIndex(r);if(0<=t)return e.splice(t,1),!0}return!1}function S(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}function T(t){let e=new Uint8Array(0);return r=>{e=0===e.byteLength?r:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,r);let n=[];for(;;){let[r,s]=S(e,1),i=r+s;if(e.byteLength<i)return n;let o=e[0],u=0===r?null:e.subarray(s,i);e=e.subarray(i);let a=t.decode_pkt(o,u,t);null!=a&&n.push(a)}}}const j=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function P(t=((...t)=>t)){let e,r,n=(t,n)=>{e=t,r=n};return s=>(s=new Promise(n),t(s,e,r))}const A=P();function N(t,[e,r]){let n,s,i=A(),o=A(),u=async(...t)=>(await o[0])(...t);return t._send=u,{async when_ready(){await o[0]},ping:U((()=>n?.("pingreq"))),reset(e){n&&(e&&i[2](e),n=null,i=A(),t._send=u,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){n||await i[0];let r=await n(...e);return 0==r[0].reason&&(s=!0,o[1](t._send=n),o=A(),t.conn_emit("on_ready")),r},is_set:()=>!!n,set(o,u){if(n)throw new Error("Already connected");o=o.mqtt_stream();let a={mqtt:t};return n=async(t,e,n)=>{let s=void 0===n||r(n);return await u(o.encode_pkt(t,e)),s},i[1](n),t.conn_emit("on_live",s),t=>e(o.decode(t),a)}}}function U(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}Promise.resolve({type:"init"});const I={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:r}=this,n=t=>r[0].set(e,t);return r=>("string"==typeof r?e=r:(t=t+1&65535,e=r.pkt_id=t),new Promise(n))},answer(t,e){for(let r of this.hashbelt){let n=r.get(t);if(void 0!==n)return r.delete(t),n([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let r of e.splice(t||5))for(let t of r.values())t([,"expired"])},cmdids:(()=>{return[()=>{},r,e,r,t,t,t,t,r,t,r,t,e,e,r,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,n){t.answer(e.type,e),r(t,e,n)}async function r({target:t},e,r){let n=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(n?.call(t,e,r))}})()};function E(t,e){let r=I.create(e),{cmdids:n}=r,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)n[s.id](r,s,e);Date.now()>o&&(r.rotate_belt(i),o=s+Date.now())},r.bind_pkt_future()]}class M extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class Q{constructor(t={}){this.with(t),this._conn_=N(this,this._init_dispatch(t,this))}with(t){for(let[e,r]of Object.entries(t))"function"==typeof r&&(this[e]=r);return this}async conn_emit(t,e,r){this.log_conn?.(t,e,r);try{let n=this[await t];if(n)await n.call(this,this,e,r);else if(r)throw r}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||this.client_id;"string"!=typeof e&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._conn_.send_connect("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this._conn_.ping(t.keep_alive),r}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,r){t=$(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=$(t,e,r),this._send("unsubscribe",t,t)}post(t,e,r){return this.pub({topic:t,payload:e,qos:0},r)}send(t,e,r){return this.pub({topic:t,payload:e,qos:1},r)}store(t,e,r){return this.pub({topic:t,payload:e,qos:1,retain:1},r)}obj_post(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:0},r)}obj_send(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1},r)}obj_store(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},r)}async pub(t,e){if(void 0===t.payload){"function"==typeof e&&(e={fn_encode:e});let{msg:r}=t;switch(typeof r){case"function":e={...e,fn_encode:r};case"undefined":return r=>this.pub({...t,[t.arg||"payload"]:r},e)}let{fn_encode:n}=e||{};t.payload=n?await n(r):JSON.stringify(r)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:void 0)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),E(this,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;let e=t.prototype;e.MQTTError=M;for(let r of t._aliases().split(/\s+/)){r=r.split(":");let t=r[1]&&e[r[1]];t&&(e[r[0]]=t)}}}function $(t,e,r){if(e?.trim&&(r=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,r){let e=t=>t.trim?r+t:t.map(e);t.topics=t.topics.map(e)}return t}const C={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};class L extends Q{static mqtt_ctx(t,e,r=C){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r){r={__proto__:r||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return j[this.b0>>>4]}};let n,s=[],i={};for(n of e.encode_fns)n(i,e.mqtt_writer);for(n of e.decode_fns)n(s,e.mqtt_reader);return{pkt_ctx:r,encode_pkt:(e,r)=>i[e](t,r),decode_pkt(t,e){let r=s[t>>>4]||s[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:r}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=T(t),t}}}(t,e,r),n}init_client_id(t=["u8-mqtt--",""]){let e,r=this.sess_stg,n=r?.getItem(e=t.join(" "));return n||(n=t.join(Math.random().toString(36).slice(2)),r?.setItem(e,n)),n}get sess_stg(){return globalThis.sessionStorage}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let r=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)r(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:r}=t;if(1!==r){if(0!==r)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:n}=this,s=n.set(this.mqtt_ctx,(async r=>(await e,t.send(r))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}n.reset(e)},this}}const O="0.5.2-web",z=w(L.mqtt_ctx(4,m)),R=w(L.mqtt_ctx(5,m)),D=t=>new z(t),B=t=>new R(t);export{Q as MQTTBase,z as MQTTClient_v4,R as MQTTClient_v5,L as MQTTCore,M as MQTTError,I as _mqtt_cmdid_dispatch,N as _mqtt_conn,E as _mqtt_dispatch,A as ao_defer_v,k as as_topic_path,D as default,D as mqtt_v4,B as mqtt_v5,O as version,w as with_topic_path_router,y as with_topic_router};
Binary file
Binary file
package/esm/web/v4.js CHANGED
@@ -1323,7 +1323,7 @@ class MQTTCore extends MQTTBase {
1323
1323
 
1324
1324
  return this} }
1325
1325
 
1326
- const version = '0.5.0';
1326
+ const version = '0.5.2-web';
1327
1327
 
1328
1328
  const MQTTClient_v4 = /* #__PURE__ */
1329
1329
  with_topic_path_router(
package/esm/web/v4.min.js CHANGED
@@ -1 +1 @@
1
- function t(t,e=[]){do{const n=127&t;t>>>=7,e.push(n|(0===t?0:128))}while(t>0);return e}class e extends Number{static of(t,e,n){let r=new this(t);return r.reason=n?.[e]?.get(t)||e,r}}let n=class{static of(t){return this.prototype.of(t)}of(t){let e=(t,n)=>(n=0|e.k,e.k=n+t,n);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,n=e(2);return t[n]<<8|t[n+1]}u32(){let{buf:t,step:e}=this,n=e(4);return t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3]}vint(){let{buf:t,step:e}=this,[n,r,s]=function(t,e=0){let n=e,r=(127&t[e])<<0;return 128&t[e++]&&(r|=(127&t[e])<<7,128&t[e++]&&(r|=(127&t[e])<<14,128&t[e++]&&(r|=(127&t[e])<<21))),[r,e,n]}(t,0|e.k);return e(r-s),n}bin(){let{buf:t,step:e}=this,n=e(2),r=t[n]<<8|t[n+1];return n=e(r),t.subarray(n,n+r)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let n=this.buf[this.step(1)];if(null!=n)return e.of(n,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}};function r(t,...e){t=class extends t{static reasons(t,...e){let n=this.prototype;n._reasons_by={...n._reasons_by};let r=n._reasons_by[t]||=new Map;for(let[t,n]of e)r.set(t,n);return this}};for(let n of e)n(t);return t}function s(t){t.reasons("connack",[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"])}function i(t){return(e,n)=>{let r=t.of(n);e.pkt_id=r.u16(),5<=e.mqtt_level&&(e.props=r.props());let s=e.answers=[];for(;r.has_more();)s.push(r.reason(e.type));return e}}function o(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}function u(t){t.reasons("unsuback",[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"])}const c=[function(t,e){const n=new Uint8Array([0,4,77,81,84,84]),r=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,s)=>{let i=e.of(s);i.push(n),i.u8(t);let{will:o,username:u,password:c}=s,a=i.flags(s.flags,r,0|(u?128:0)|(c?64:0)|(o?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(o):0));return i.u16(s.keep_alive),5<=t&&i.props(s.props),i.utf8(s.client_id),4&a&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&a&&i.utf8(u),64&a&&i.bin(c),i.as_pkt(16)}},function(t,e){return t.puback=(t,n)=>{let r=e.of(n);return r.u16(n.pkt_id),5<=t&&(r.reason(n.reason),r.props(n.props)),r.as_pkt(64)}},function(t,e){return t.publish=(t,n)=>{let r=(3&n.qos)<<1,s=e.of(n);return s.utf8(n.topic),0!==r&&s.u16(n.pkt_id),5<=t?(s.props(n.props),s.flush(n.payload)):s.flush(n.payload),s.as_pkt(48|r|(n.dup?8:0)|(n.retain?1:0))}},function(t,e){const n=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,r)=>{let s=e.of(r);s.u16(r.pkt_id),5<=t&&s.props(r.props);let i=n(r);for(let t of r.topics)if("string"==typeof t)s.utf8(t),s.u8(i);else{let[e,r]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===r?s.u8(i):s.flags(r,n)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,n)=>{let r=e.of(n);r.u16(n.pkt_id),5<=t&&r.props(n.props);for(let t of n.topics)r.utf8(t);return r.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,n)=>{let r=e.of(n);return n&&5<=t&&(n.reason||n.props)&&(r.reason(n.reason),r.props(n.props)),r.as_pkt(224)}}],a={decode_fns:[function(t,e){class n extends Number{get session_present(){return!0&this}}return t[2]=(t,r)=>{let s=e.of(r);return t.flags=s.flags(n),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,n)=>{let{hdr:r}=t;t.dup=Boolean(8&r),t.retain=Boolean(1&r);let s=t.qos=r>>1&3,i=e.of(n);return t.topic=i.utf8(),0!==s&&(t.pkt_id=i.u16()),5<=t.mqtt_level&&(t.props=i.props()),t.payload=i.flush(),t}},function(t,e){return t[4]=(t,n)=>{let r=e.of(n);return t.pkt_id=r.u16(),5<=t.mqtt_level&&(t.reason=r.reason(t.type),t.props=r.props()),t}},function(t,e){return t[9]=i(e)},function(t,e){return t[11]=i(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,n)=>{if(n&&5<=t.mqtt_level){let r=e.of(n);t.reason=r.reason(t.type),t.props=r.props()}return t}}],mqtt_reader:r(n,s,o,u),encode_fns:c,mqtt_writer:class{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let n,r,s=0,i=this.$;for(n of(this.$=!1,i))s+=n.length;r=(e=t(s,e)).length;let o=new Uint8Array(r+s);for(n of(o.set(e,0),i))o.set(n,r),r+=n.length;return o}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,n=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=n,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}};const p=(t=>e=>class extends e{static _aliases(){return super._aliases()+" sub_topic:subscribe_topic unsub_topic:unsubscribe_topic"}_init_router(e,n,r){this._subs=[];let s=this.router=r.router=t(e,this,r);return s?.invoke}on_sub(t,e){return t.pkt=e,this._subs.push(t),t}subs_settled(){return Promise.allSettled(this._subs.splice(0,1/0))}subscribe_topic(t,...e){let n=this.router;n.add(t,!0,e.pop());let r=n.mqtt_topic(t);return this.subscribe(r,...e),this}unsubscribe_topic(t,...e){let n=this.router;n.remove(t,!0);let r=n.mqtt_topic(t);return this.unsubscribe(r,...e)}on_topic(...t){return this.router.add(...t),this}})(f),l=t=>t.replace(/[*].*$/,"#").replace(/:\w[^\/]*/g,"+"),_=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function h(t,e,n){n.done=!0}function f(){let t=[[],[]],e=Symbol(),n=e=>function*(t,e){e=e.replace(/^[\/]*/,"/");for(let n of t)for(let{keys:t,pattern:r,tgt:s}of n){let n=r.exec(e);if(n){let e=t?t.reduce(((t,e,r)=>(t[e]=n[1+r],t)),{}):n.groups??n;yield[s,e]}}}(t,e);return{find:n,mqtt_topic:l,add(e,...n){let r=n.pop(),s=n.pop();if("function"!=typeof r){if(r)throw new TypeError;r=h}let i=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var n,r,s,i,o=[],u="",c=t.split("/");for(c[0]||c.shift();s=c.shift();)"*"===(n=s[0])?(o.push("wild"),u+="/(.*)"):":"===n?(r=s.indexOf("?",1),i=s.indexOf(".",1),o.push(s.substring(1,~r?r:~i?i:s.length)),u+=~r&&!~i?"(?:/([^/]+?))?":"/([^/]+?)",~i&&(u+=(~r?"?":"")+"\\"+s.substring(i))):u+="/"+s;return{keys:o,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(_(e));return i.key=e,i.tgt=r,t[s?0:1].push(i),this},remove:(e,n)=>d([t[n?0:1]],e),clear(e){t[e?0:1]=[],null==e&&(t[1]=[])},async invoke(r,s){s.idx=0,s.rm=e;for(let[i,o]of n(r.topic)){let n=await i(r,o,s);if(e===n&&d(t,i),s.done)break;s.idx++}1===r.qos&&await s.mqtt.puback(r)}}}function d(t,e){let n=t=>t===e||t.tgt===e||t.key===e;for(let e of t){let t=e.findIndex(n);if(0<=t)return e.splice(t,1),!0}return!1}function b(t,e=0){let n=e,r=(127&t[e])<<0;return 128&t[e++]&&(r|=(127&t[e])<<7,128&t[e++]&&(r|=(127&t[e])<<14,128&t[e++]&&(r|=(127&t[e])<<21))),[r,e,n]}function y(t){let e=new Uint8Array(0);return n=>{e=0===e.byteLength?n:function(t,e){let n=t.byteLength,r=new Uint8Array(n+e.byteLength);return r.set(t,0),r.set(e,n),r}(e,n);let r=[];for(;;){let[n,s]=b(e,1),i=n+s;if(e.byteLength<i)return r;let o=e[0],u=0===n?null:e.subarray(s,i);e=e.subarray(i);let c=t.decode_pkt(o,u,t);null!=c&&r.push(c)}}}const w=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function m(t=((...t)=>t)){let e,n,r=(t,r)=>{e=t,n=r};return s=>(s=new Promise(r),t(s,e,n))}const g=m();function k(t){let e;return n=>{if(e=clearInterval(e),n)return e=setInterval(t,1e3*n),e.unref?.(),!0}}Promise.resolve({type:"init"});const q={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:n}=this,r=t=>n[0].set(e,t);return n=>("string"==typeof n?e=n:(t=t+1&65535,e=n.pkt_id=t),new Promise(r))},answer(t,e){for(let n of this.hashbelt){let r=n.get(t);if(void 0!==r)return n.delete(t),r([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let n of e.splice(t||5))for(let t of n.values())t([,"expired"])},cmdids:(()=>{return[()=>{},n,e,n,t,t,t,t,n,t,n,t,e,e,n,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,r){t.answer(e.type,e),n(t,e,r)}async function n({target:t},e,n){let r=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(r?.call(t,e,n))}})()};class v extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class x{constructor(t={}){this.with(t),this._conn_=function(t,[e,n]){let r,s,i=g(),o=g(),u=async(...t)=>(await o[0])(...t);return t._send=u,{async when_ready(){await o[0]},ping:k((()=>r?.("pingreq"))),reset(e){r&&(e&&i[2](e),r=null,i=g(),t._send=u,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){r||await i[0];let n=await r(...e);return 0==n[0].reason&&(s=!0,o[1](t._send=r),o=g(),t.conn_emit("on_ready")),n},is_set:()=>!!r,set(o,u){if(r)throw new Error("Already connected");o=o.mqtt_stream();let c={mqtt:t};return r=async(t,e,r)=>{let s=void 0===r||n(r);return await u(o.encode_pkt(t,e)),s},i[1](r),t.conn_emit("on_live",s),t=>e(o.decode(t),c)}}}(this,this._init_dispatch(t,this))}with(t){for(let[e,n]of Object.entries(t))"function"==typeof n&&(this[e]=n);return this}async conn_emit(t,e,n){this.log_conn?.(t,e,n);try{let r=this[await t];if(r)await r.call(this,this,e,n);else if(n)throw n}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||this.client_id;"string"!=typeof e&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let n=await this._conn_.send_connect("connect",t,"connack");if(0!=n[0].reason)throw new this.MQTTError(n[0]);return this._conn_.ping(t.keep_alive),n}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,n){t=S(t,e,n);let r=this._send("subscribe",t,t);return this.on_sub?.(r,t)??r}unsubscribe(t,e,n){return t=S(t,e,n),this._send("unsubscribe",t,t)}post(t,e,n){return this.pub({topic:t,payload:e,qos:0},n)}send(t,e,n){return this.pub({topic:t,payload:e,qos:1},n)}store(t,e,n){return this.pub({topic:t,payload:e,qos:1,retain:1},n)}obj_post(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:0},n)}obj_send(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:1},n)}obj_store(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},n)}async pub(t,e){if(void 0===t.payload){"function"==typeof e&&(e={fn_encode:e});let{msg:n}=t;switch(typeof n){case"function":e={...e,fn_encode:n};case"undefined":return n=>this.pub({...t,[t.arg||"payload"]:n},e)}let{fn_encode:r}=e||{};t.payload=r?await r(n):JSON.stringify(n)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:void 0)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),function(t,e){let n=q.create(e),{cmdids:r}=n,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)r[s.id](n,s,e);Date.now()>o&&(n.rotate_belt(i),o=s+Date.now())},n.bind_pkt_future()]}(this,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;let e=t.prototype;e.MQTTError=v;for(let n of t._aliases().split(/\s+/)){n=n.split(":");let t=n[1]&&e[n[1]];t&&(e[n[0]]=t)}}}function S(t,e,n){if(e?.trim&&(n=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,n){let e=t=>t.trim?n+t:t.map(e);t.topics=t.topics.map(e)}return t}const T={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};const j="0.5.0",$=p(class extends x{static mqtt_ctx(t,e,n=T){let r=class extends(this){};return r.prototype.mqtt_ctx=function(t,e,n){n={__proto__:n||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return w[this.b0>>>4]}};let r,s=[],i={};for(r of e.encode_fns)r(i,e.mqtt_writer);for(r of e.decode_fns)r(s,e.mqtt_reader);return{pkt_ctx:n,encode_pkt:(e,n)=>i[e](t,n),decode_pkt(t,e){let n=s[t>>>4]||s[0];return n?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:n}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=y(t),t}}}(t,e,n),r}init_client_id(t=["u8-mqtt--",""]){let e,n=this.sess_stg,r=n?.getItem(e=t.join(" "));return r||(r=t.join(Math.random().toString(36).slice(2)),n?.setItem(e,r)),r}get sess_stg(){return globalThis.sessionStorage}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let n=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)n(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:n}=t;if(1!==n){if(0!==n)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:r}=this,s=r.set(this.mqtt_ctx,(async n=>(await e,t.send(n))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}r.reset(e)},this}}.mqtt_ctx(4,a)),A=t=>new $(t);export{$ as MQTTClient,$ as MQTTClient_v4,A as default,A as mqtt,A as mqtt_v4,j as version};
1
+ function t(t,e=[]){do{const n=127&t;t>>>=7,e.push(n|(0===t?0:128))}while(t>0);return e}class e extends Number{static of(t,e,n){let r=new this(t);return r.reason=n?.[e]?.get(t)||e,r}}let n=class{static of(t){return this.prototype.of(t)}of(t){let e=(t,n)=>(n=0|e.k,e.k=n+t,n);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,n=e(2);return t[n]<<8|t[n+1]}u32(){let{buf:t,step:e}=this,n=e(4);return t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3]}vint(){let{buf:t,step:e}=this,[n,r,s]=function(t,e=0){let n=e,r=(127&t[e])<<0;return 128&t[e++]&&(r|=(127&t[e])<<7,128&t[e++]&&(r|=(127&t[e])<<14,128&t[e++]&&(r|=(127&t[e])<<21))),[r,e,n]}(t,0|e.k);return e(r-s),n}bin(){let{buf:t,step:e}=this,n=e(2),r=t[n]<<8|t[n+1];return n=e(r),t.subarray(n,n+r)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let n=this.buf[this.step(1)];if(null!=n)return e.of(n,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}};function r(t,...e){t=class extends t{static reasons(t,...e){let n=this.prototype;n._reasons_by={...n._reasons_by};let r=n._reasons_by[t]||=new Map;for(let[t,n]of e)r.set(t,n);return this}};for(let n of e)n(t);return t}function s(t){t.reasons("connack",[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"])}function i(t){return(e,n)=>{let r=t.of(n);e.pkt_id=r.u16(),5<=e.mqtt_level&&(e.props=r.props());let s=e.answers=[];for(;r.has_more();)s.push(r.reason(e.type));return e}}function o(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}function u(t){t.reasons("unsuback",[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"])}const c=[function(t,e){const n=new Uint8Array([0,4,77,81,84,84]),r=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,s)=>{let i=e.of(s);i.push(n),i.u8(t);let{will:o,username:u,password:c}=s,a=i.flags(s.flags,r,0|(u?128:0)|(c?64:0)|(o?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(o):0));return i.u16(s.keep_alive),5<=t&&i.props(s.props),i.utf8(s.client_id),4&a&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&a&&i.utf8(u),64&a&&i.bin(c),i.as_pkt(16)}},function(t,e){return t.puback=(t,n)=>{let r=e.of(n);return r.u16(n.pkt_id),5<=t&&(r.reason(n.reason),r.props(n.props)),r.as_pkt(64)}},function(t,e){return t.publish=(t,n)=>{let r=(3&n.qos)<<1,s=e.of(n);return s.utf8(n.topic),0!==r&&s.u16(n.pkt_id),5<=t?(s.props(n.props),s.flush(n.payload)):s.flush(n.payload),s.as_pkt(48|r|(n.dup?8:0)|(n.retain?1:0))}},function(t,e){const n=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,r)=>{let s=e.of(r);s.u16(r.pkt_id),5<=t&&s.props(r.props);let i=n(r);for(let t of r.topics)if("string"==typeof t)s.utf8(t),s.u8(i);else{let[e,r]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===r?s.u8(i):s.flags(r,n)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,n)=>{let r=e.of(n);r.u16(n.pkt_id),5<=t&&r.props(n.props);for(let t of n.topics)r.utf8(t);return r.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,n)=>{let r=e.of(n);return n&&5<=t&&(n.reason||n.props)&&(r.reason(n.reason),r.props(n.props)),r.as_pkt(224)}}],a={decode_fns:[function(t,e){class n extends Number{get session_present(){return!0&this}}return t[2]=(t,r)=>{let s=e.of(r);return t.flags=s.flags(n),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,n)=>{let{hdr:r}=t;t.dup=Boolean(8&r),t.retain=Boolean(1&r);let s=t.qos=r>>1&3,i=e.of(n);return t.topic=i.utf8(),0!==s&&(t.pkt_id=i.u16()),5<=t.mqtt_level&&(t.props=i.props()),t.payload=i.flush(),t}},function(t,e){return t[4]=(t,n)=>{let r=e.of(n);return t.pkt_id=r.u16(),5<=t.mqtt_level&&(t.reason=r.reason(t.type),t.props=r.props()),t}},function(t,e){return t[9]=i(e)},function(t,e){return t[11]=i(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,n)=>{if(n&&5<=t.mqtt_level){let r=e.of(n);t.reason=r.reason(t.type),t.props=r.props()}return t}}],mqtt_reader:r(n,s,o,u),encode_fns:c,mqtt_writer:class{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let n,r,s=0,i=this.$;for(n of(this.$=!1,i))s+=n.length;r=(e=t(s,e)).length;let o=new Uint8Array(r+s);for(n of(o.set(e,0),i))o.set(n,r),r+=n.length;return o}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,n=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=n,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}};const p=(t=>e=>class extends e{static _aliases(){return super._aliases()+" sub_topic:subscribe_topic unsub_topic:unsubscribe_topic"}_init_router(e,n,r){this._subs=[];let s=this.router=r.router=t(e,this,r);return s?.invoke}on_sub(t,e){return t.pkt=e,this._subs.push(t),t}subs_settled(){return Promise.allSettled(this._subs.splice(0,1/0))}subscribe_topic(t,...e){let n=this.router;n.add(t,!0,e.pop());let r=n.mqtt_topic(t);return this.subscribe(r,...e),this}unsubscribe_topic(t,...e){let n=this.router;n.remove(t,!0);let r=n.mqtt_topic(t);return this.unsubscribe(r,...e)}on_topic(...t){return this.router.add(...t),this}})(f),l=t=>t.replace(/[*].*$/,"#").replace(/:\w[^\/]*/g,"+"),_=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function h(t,e,n){n.done=!0}function f(){let t=[[],[]],e=Symbol(),n=e=>function*(t,e){e=e.replace(/^[\/]*/,"/");for(let n of t)for(let{keys:t,pattern:r,tgt:s}of n){let n=r.exec(e);if(n){let e=t?t.reduce(((t,e,r)=>(t[e]=n[1+r],t)),{}):n.groups??n;yield[s,e]}}}(t,e);return{find:n,mqtt_topic:l,add(e,...n){let r=n.pop(),s=n.pop();if("function"!=typeof r){if(r)throw new TypeError;r=h}let i=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var n,r,s,i,o=[],u="",c=t.split("/");for(c[0]||c.shift();s=c.shift();)"*"===(n=s[0])?(o.push("wild"),u+="/(.*)"):":"===n?(r=s.indexOf("?",1),i=s.indexOf(".",1),o.push(s.substring(1,~r?r:~i?i:s.length)),u+=~r&&!~i?"(?:/([^/]+?))?":"/([^/]+?)",~i&&(u+=(~r?"?":"")+"\\"+s.substring(i))):u+="/"+s;return{keys:o,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(_(e));return i.key=e,i.tgt=r,t[s?0:1].push(i),this},remove:(e,n)=>d([t[n?0:1]],e),clear(e){t[e?0:1]=[],null==e&&(t[1]=[])},async invoke(r,s){s.idx=0,s.rm=e;for(let[i,o]of n(r.topic)){let n=await i(r,o,s);if(e===n&&d(t,i),s.done)break;s.idx++}1===r.qos&&await s.mqtt.puback(r)}}}function d(t,e){let n=t=>t===e||t.tgt===e||t.key===e;for(let e of t){let t=e.findIndex(n);if(0<=t)return e.splice(t,1),!0}return!1}function b(t,e=0){let n=e,r=(127&t[e])<<0;return 128&t[e++]&&(r|=(127&t[e])<<7,128&t[e++]&&(r|=(127&t[e])<<14,128&t[e++]&&(r|=(127&t[e])<<21))),[r,e,n]}function y(t){let e=new Uint8Array(0);return n=>{e=0===e.byteLength?n:function(t,e){let n=t.byteLength,r=new Uint8Array(n+e.byteLength);return r.set(t,0),r.set(e,n),r}(e,n);let r=[];for(;;){let[n,s]=b(e,1),i=n+s;if(e.byteLength<i)return r;let o=e[0],u=0===n?null:e.subarray(s,i);e=e.subarray(i);let c=t.decode_pkt(o,u,t);null!=c&&r.push(c)}}}const w=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function m(t=((...t)=>t)){let e,n,r=(t,r)=>{e=t,n=r};return s=>(s=new Promise(r),t(s,e,n))}const g=m();function k(t){let e;return n=>{if(e=clearInterval(e),n)return e=setInterval(t,1e3*n),e.unref?.(),!0}}Promise.resolve({type:"init"});const q={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:n}=this,r=t=>n[0].set(e,t);return n=>("string"==typeof n?e=n:(t=t+1&65535,e=n.pkt_id=t),new Promise(r))},answer(t,e){for(let n of this.hashbelt){let r=n.get(t);if(void 0!==r)return n.delete(t),r([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let n of e.splice(t||5))for(let t of n.values())t([,"expired"])},cmdids:(()=>{return[()=>{},n,e,n,t,t,t,t,n,t,n,t,e,e,n,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,r){t.answer(e.type,e),n(t,e,r)}async function n({target:t},e,n){let r=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(r?.call(t,e,n))}})()};class v extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class x{constructor(t={}){this.with(t),this._conn_=function(t,[e,n]){let r,s,i=g(),o=g(),u=async(...t)=>(await o[0])(...t);return t._send=u,{async when_ready(){await o[0]},ping:k((()=>r?.("pingreq"))),reset(e){r&&(e&&i[2](e),r=null,i=g(),t._send=u,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){r||await i[0];let n=await r(...e);return 0==n[0].reason&&(s=!0,o[1](t._send=r),o=g(),t.conn_emit("on_ready")),n},is_set:()=>!!r,set(o,u){if(r)throw new Error("Already connected");o=o.mqtt_stream();let c={mqtt:t};return r=async(t,e,r)=>{let s=void 0===r||n(r);return await u(o.encode_pkt(t,e)),s},i[1](r),t.conn_emit("on_live",s),t=>e(o.decode(t),c)}}}(this,this._init_dispatch(t,this))}with(t){for(let[e,n]of Object.entries(t))"function"==typeof n&&(this[e]=n);return this}async conn_emit(t,e,n){this.log_conn?.(t,e,n);try{let r=this[await t];if(r)await r.call(this,this,e,n);else if(n)throw n}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||this.client_id;"string"!=typeof e&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let n=await this._conn_.send_connect("connect",t,"connack");if(0!=n[0].reason)throw new this.MQTTError(n[0]);return this._conn_.ping(t.keep_alive),n}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,n){t=S(t,e,n);let r=this._send("subscribe",t,t);return this.on_sub?.(r,t)??r}unsubscribe(t,e,n){return t=S(t,e,n),this._send("unsubscribe",t,t)}post(t,e,n){return this.pub({topic:t,payload:e,qos:0},n)}send(t,e,n){return this.pub({topic:t,payload:e,qos:1},n)}store(t,e,n){return this.pub({topic:t,payload:e,qos:1,retain:1},n)}obj_post(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:0},n)}obj_send(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:1},n)}obj_store(t,e,n){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},n)}async pub(t,e){if(void 0===t.payload){"function"==typeof e&&(e={fn_encode:e});let{msg:n}=t;switch(typeof n){case"function":e={...e,fn_encode:n};case"undefined":return n=>this.pub({...t,[t.arg||"payload"]:n},e)}let{fn_encode:r}=e||{};t.payload=r?await r(n):JSON.stringify(n)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:void 0)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),function(t,e){let n=q.create(e),{cmdids:r}=n,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)r[s.id](n,s,e);Date.now()>o&&(n.rotate_belt(i),o=s+Date.now())},n.bind_pkt_future()]}(this,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;let e=t.prototype;e.MQTTError=v;for(let n of t._aliases().split(/\s+/)){n=n.split(":");let t=n[1]&&e[n[1]];t&&(e[n[0]]=t)}}}function S(t,e,n){if(e?.trim&&(n=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,n){let e=t=>t.trim?n+t:t.map(e);t.topics=t.topics.map(e)}return t}const T={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};const j="0.5.2-web",$=p(class extends x{static mqtt_ctx(t,e,n=T){let r=class extends(this){};return r.prototype.mqtt_ctx=function(t,e,n){n={__proto__:n||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return w[this.b0>>>4]}};let r,s=[],i={};for(r of e.encode_fns)r(i,e.mqtt_writer);for(r of e.decode_fns)r(s,e.mqtt_reader);return{pkt_ctx:n,encode_pkt:(e,n)=>i[e](t,n),decode_pkt(t,e){let n=s[t>>>4]||s[0];return n?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:n}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=y(t),t}}}(t,e,n),r}init_client_id(t=["u8-mqtt--",""]){let e,n=this.sess_stg,r=n?.getItem(e=t.join(" "));return r||(r=t.join(Math.random().toString(36).slice(2)),n?.setItem(e,r)),r}get sess_stg(){return globalThis.sessionStorage}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let n=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)n(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:n}=t;if(1!==n){if(0!==n)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:r}=this,s=r.set(this.mqtt_ctx,(async n=>(await e,t.send(n))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}r.reset(e)},this}}.mqtt_ctx(4,a)),A=t=>new $(t);export{$ as MQTTClient,$ as MQTTClient_v4,A as default,A as mqtt,A as mqtt_v4,j as version};
Binary file
Binary file
package/esm/web/v5.js CHANGED
@@ -1579,7 +1579,7 @@ class MQTTCore extends MQTTBase {
1579
1579
 
1580
1580
  return this} }
1581
1581
 
1582
- const version = '0.5.0';
1582
+ const version = '0.5.2-web';
1583
1583
 
1584
1584
  const MQTTClient_v4 = /* #__PURE__ */
1585
1585
  with_topic_path_router(
package/esm/web/v5.min.js CHANGED
@@ -1 +1 @@
1
- function t(t,e=[]){do{const r=127&t;t>>>=7,e.push(r|(0===t?0:128))}while(t>0);return e}function e(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}const r=n();function n(){let t=new Map,e=[[1,"u8","payload_format_indicator"],[2,"u32","message_expiry_interval"],[3,"utf8","content_type"],[8,"utf8","response_topic"],[9,"bin","correlation_data"],[11,"vint","subscription_identifier"],[17,"u32","session_expiry_interval"],[18,"utf8","assigned_client_identifier"],[19,"u16","server_keep_alive"],[21,"utf8","authentication_method"],[22,"bin","authentication_data"],[23,"u8","request_problem_information"],[24,"u32","will_delay_interval"],[25,"u8","request_response_information"],[26,"utf8","response_information"],[28,"utf8","server_reference"],[31,"utf8","reason_string"],[33,"u16","receive_maximum"],[34,"u16","topic_alias_maximum"],[35,"u16","topic_alias"],[36,"u8","maximum_qos"],[37,"u8","retain_available"],[38,"pair","user_properties",{op:"kv_obj"}],[39,"u32","maximum_packet_size"],[40,"u8","wildcard_subscription_available"],[41,"u8","subscription_identifiers_available",{op:"u8_vec"}],[42,"u8","shared_subscription_available"]];for(let[r,n,s,i]of e){let e={id:r,type:n,name:s,...i};t.set(e.id,e),t.set(e.name,e)}return t}class s extends Number{static of(t,e,r){let n=new this(t);return n.reason=r?.[e]?.get(t)||e,n}}class i{static of(t){return this.prototype.of(t)}of(t){let e=(t,r)=>(r=0|e.k,e.k=r+t,r);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,r=e(2);return t[r]<<8|t[r+1]}u32(){let{buf:t,step:e}=this,r=e(4);return t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]}vint(){let{buf:t,step:r}=this,[n,s,i]=e(t,0|r.k);return r(s-i),n}bin(){let{buf:t,step:e}=this,r=e(2),n=t[r]<<8|t[r+1];return r=e(n),t.subarray(r,r+n)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let e=this.buf[this.step(1)];if(null!=e)return s.of(e,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}}let o=class extends i{props(){let{buf:t,step:n}=this,[s,i,o]=e(t,0|n.k);if(n(s+i-o),0===s)return null;let u={},a=this.of(t.subarray(i,0|n.k));for(;a.has_more();){let t=r.get(a.u8()),e=a[t.type]();u[t.name]=t.op?a[t.op](u[t.name],e):e}return u}kv_obj(t=Object.create(null),[e,r]){return t[e]=r,t}u8_vec(t=[],e){return t.push(e),t}};function u(t,...e){t=class extends t{static reasons(t,...e){let r=this.prototype;r._reasons_by={...r._reasons_by};let n=r._reasons_by[t]||=new Map;for(let[t,r]of e)n.set(t,r);return this}};for(let r of e)r(t);return t}class a{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let r,n,s=0,i=this.$;for(r of(this.$=!1,i))s+=r.length;n=(e=t(s,e)).length;let o=new Uint8Array(n+s);for(r of(o.set(e,0),i))o.set(r,n),n+=r.length;return o}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,r=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=r,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}function c(t){!function(t){t.reasons("connack",[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"])}(t),t.reasons("connack",[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[132,"Unsupported Protocol Version"],[133,"Client Identifier not valid"],[134,"Bad User Name or Password"],[135,"Not authorized"],[136,"Server unavailable"],[137,"Server busy"],[138,"Banned"],[140,"Bad authentication method"],[144,"Topic Name invalid"],[149,"Packet too large"],[151,"Quota exceeded"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[159,"Connection rate exceeded"])}function p(t){t.reasons("puback",[0,"Success"],[16,"No matching subscribers"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[144,"Topic Name invalid"],[145,"Packet identifier in use"],[151,"Quota exceeded"],[153,"Payload format invalid"])}function l(t){return(e,r)=>{let n=t.of(r);e.pkt_id=n.u16(),5<=e.mqtt_level&&(e.props=n.props());let s=e.answers=[];for(;n.has_more();)s.push(n.reason(e.type));return e}}function _(t){!function(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}(t),t.reasons("suback",[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"],[151,"Quota exceeded"],[158,"Shared Subscriptions not supported"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function f(t){t.reasons("unsuback",[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"])}function d(t){t.reasons("disconnect",[0,"Normal disconnection"],[4,"Disconnect with Will Message"],[128,"Unspecified error"],[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[135,"Not authorized"],[137,"Server busy"],[139,"Server shutting down"],[141,"Keep Alive timeout"],[142,"Session taken over"],[143,"Topic Filter invalid"],[144,"Topic Name invalid"],[147,"Receive Maximum exceeded"],[148,"Topic Alias invalid"],[149,"Packet too large"],[150,"Message rate too high"],[151,"Quota exceeded"],[152,"Administrative action"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[158,"Shared Subscriptions not supported"],[159,"Connection rate exceeded"],[160,"Maximum connect time"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function h(t){t.reasons("auth",[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"])}const b=[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,s)=>{let i=e.of(s);i.push(r),i.u8(t);let{will:o,username:u,password:a}=s,c=i.flags(s.flags,n,0|(u?128:0)|(a?64:0)|(o?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(o):0));return i.u16(s.keep_alive),5<=t&&i.props(s.props),i.utf8(s.client_id),4&c&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&c&&i.utf8(u),64&c&&i.bin(a),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.of(r);return n.u16(r.pkt_id),5<=t&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(64)}},function(t,e){return t.publish=(t,r)=>{let n=(3&r.qos)<<1,s=e.of(r);return s.utf8(r.topic),0!==n&&s.u16(r.pkt_id),5<=t?(s.props(r.props),s.flush(r.payload)):s.flush(r.payload),s.as_pkt(48|n|(r.dup?8:0)|(r.retain?1:0))}},function(t,e){const r=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.of(n);s.u16(n.pkt_id),5<=t&&s.props(n.props);let i=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(i);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(i):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,r)=>{let n=e.of(r);n.u16(r.pkt_id),5<=t&&n.props(r.props);for(let t of r.topics)n.utf8(t);return n.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,r)=>{let n=e.of(r);return r&&5<=t&&(r.reason||r.props)&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(224)}},function(t,e){return t.auth=(t,r)=>{if(5>t)throw new Error("Auth packets are only available after MQTT 5.x");let n=e.of(r);return n.reason(r.reason),n.props(r.props),n.as_pkt(240)}}],m={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.of(n);return t.flags=s.flags(r),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,r)=>{let{hdr:n}=t;t.dup=Boolean(8&n),t.retain=Boolean(1&n);let s=t.qos=n>>1&3,i=e.of(r);return t.topic=i.utf8(),0!==s&&(t.pkt_id=i.u16()),5<=t.mqtt_level&&(t.props=i.props()),t.payload=i.flush(),t}},function(t,e){return t[4]=(t,r)=>{let n=e.of(r);return t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.reason=n.reason(t.type),t.props=n.props()),t}},function(t,e){return t[9]=l(e)},function(t,e){return t[11]=l(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,r)=>{if(r&&5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}},function(t,e){return t[15]=(t,r)=>{if(5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}}],mqtt_reader:u(o,c,p,_,f,d,h),encode_fns:b,mqtt_writer:class extends a{props(t){if(!t)return this.u8(0);if(Array.isArray(t)||(t=t.entries?Array.from(t.entries()):Object.entries(t)),0===t.length)return this.u8(0);let e=this.of();for(let[n,s]of t){let t=r.get(n);e[t.op||"one"](s,t)}this.push(e.pack())}one(t,e){this.u8(e.id),this[e.type](t)}kv_obj(t,e){for(let r of Object.entries(t))this.u8(e.id),this.pair(r)}u8_vec(t,e){for(let r of t)this.u8(e.id),this.u8(r)}}};const y=(t=>e=>class extends e{static _aliases(){return super._aliases()+" sub_topic:subscribe_topic unsub_topic:unsubscribe_topic"}_init_router(e,r,n){this._subs=[];let s=this.router=n.router=t(e,this,n);return s?.invoke}on_sub(t,e){return t.pkt=e,this._subs.push(t),t}subs_settled(){return Promise.allSettled(this._subs.splice(0,1/0))}subscribe_topic(t,...e){let r=this.router;r.add(t,!0,e.pop());let n=r.mqtt_topic(t);return this.subscribe(n,...e),this}unsubscribe_topic(t,...e){let r=this.router;r.remove(t,!0);let n=r.mqtt_topic(t);return this.unsubscribe(n,...e)}on_topic(...t){return this.router.add(...t),this}})(v),w=t=>t.replace(/[*].*$/,"#").replace(/:\w[^\/]*/g,"+"),g=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function k(t,e,r){r.done=!0}function v(){let t=[[],[]],e=Symbol(),r=e=>function*(t,e){e=e.replace(/^[\/]*/,"/");for(let r of t)for(let{keys:t,pattern:n,tgt:s}of r){let r=n.exec(e);if(r){let e=t?t.reduce(((t,e,n)=>(t[e]=r[1+n],t)),{}):r.groups??r;yield[s,e]}}}(t,e);return{find:r,mqtt_topic:w,add(e,...r){let n=r.pop(),s=r.pop();if("function"!=typeof n){if(n)throw new TypeError;n=k}let i=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var r,n,s,i,o=[],u="",a=t.split("/");for(a[0]||a.shift();s=a.shift();)"*"===(r=s[0])?(o.push("wild"),u+="/(.*)"):":"===r?(n=s.indexOf("?",1),i=s.indexOf(".",1),o.push(s.substring(1,~n?n:~i?i:s.length)),u+=~n&&!~i?"(?:/([^/]+?))?":"/([^/]+?)",~i&&(u+=(~n?"?":"")+"\\"+s.substring(i))):u+="/"+s;return{keys:o,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(g(e));return i.key=e,i.tgt=n,t[s?0:1].push(i),this},remove:(e,r)=>x([t[r?0:1]],e),clear(e){t[e?0:1]=[],null==e&&(t[1]=[])},async invoke(n,s){s.idx=0,s.rm=e;for(let[i,o]of r(n.topic)){let r=await i(n,o,s);if(e===r&&x(t,i),s.done)break;s.idx++}1===n.qos&&await s.mqtt.puback(n)}}}function x(t,e){let r=t=>t===e||t.tgt===e||t.key===e;for(let e of t){let t=e.findIndex(r);if(0<=t)return e.splice(t,1),!0}return!1}function q(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}function S(t){let e=new Uint8Array(0);return r=>{e=0===e.byteLength?r:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,r);let n=[];for(;;){let[r,s]=q(e,1),i=r+s;if(e.byteLength<i)return n;let o=e[0],u=0===r?null:e.subarray(s,i);e=e.subarray(i);let a=t.decode_pkt(o,u,t);null!=a&&n.push(a)}}}const T=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function j(t=((...t)=>t)){let e,r,n=(t,n)=>{e=t,r=n};return s=>(s=new Promise(n),t(s,e,r))}const P=j();function A(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}Promise.resolve({type:"init"});const N={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:r}=this,n=t=>r[0].set(e,t);return r=>("string"==typeof r?e=r:(t=t+1&65535,e=r.pkt_id=t),new Promise(n))},answer(t,e){for(let r of this.hashbelt){let n=r.get(t);if(void 0!==n)return r.delete(t),n([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let r of e.splice(t||5))for(let t of r.values())t([,"expired"])},cmdids:(()=>{return[()=>{},r,e,r,t,t,t,t,r,t,r,t,e,e,r,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,n){t.answer(e.type,e),r(t,e,n)}async function r({target:t},e,r){let n=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(n?.call(t,e,r))}})()};class U extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class I{constructor(t={}){this.with(t),this._conn_=function(t,[e,r]){let n,s,i=P(),o=P(),u=async(...t)=>(await o[0])(...t);return t._send=u,{async when_ready(){await o[0]},ping:A((()=>n?.("pingreq"))),reset(e){n&&(e&&i[2](e),n=null,i=P(),t._send=u,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){n||await i[0];let r=await n(...e);return 0==r[0].reason&&(s=!0,o[1](t._send=n),o=P(),t.conn_emit("on_ready")),r},is_set:()=>!!n,set(o,u){if(n)throw new Error("Already connected");o=o.mqtt_stream();let a={mqtt:t};return n=async(t,e,n)=>{let s=void 0===n||r(n);return await u(o.encode_pkt(t,e)),s},i[1](n),t.conn_emit("on_live",s),t=>e(o.decode(t),a)}}}(this,this._init_dispatch(t,this))}with(t){for(let[e,r]of Object.entries(t))"function"==typeof r&&(this[e]=r);return this}async conn_emit(t,e,r){this.log_conn?.(t,e,r);try{let n=this[await t];if(n)await n.call(this,this,e,r);else if(r)throw r}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||this.client_id;"string"!=typeof e&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._conn_.send_connect("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this._conn_.ping(t.keep_alive),r}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,r){t=M(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=M(t,e,r),this._send("unsubscribe",t,t)}post(t,e,r){return this.pub({topic:t,payload:e,qos:0},r)}send(t,e,r){return this.pub({topic:t,payload:e,qos:1},r)}store(t,e,r){return this.pub({topic:t,payload:e,qos:1,retain:1},r)}obj_post(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:0},r)}obj_send(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1},r)}obj_store(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},r)}async pub(t,e){if(void 0===t.payload){"function"==typeof e&&(e={fn_encode:e});let{msg:r}=t;switch(typeof r){case"function":e={...e,fn_encode:r};case"undefined":return r=>this.pub({...t,[t.arg||"payload"]:r},e)}let{fn_encode:n}=e||{};t.payload=n?await n(r):JSON.stringify(r)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:void 0)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),function(t,e){let r=N.create(e),{cmdids:n}=r,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)n[s.id](r,s,e);Date.now()>o&&(r.rotate_belt(i),o=s+Date.now())},r.bind_pkt_future()]}(this,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;let e=t.prototype;e.MQTTError=U;for(let r of t._aliases().split(/\s+/)){r=r.split(":");let t=r[1]&&e[r[1]];t&&(e[r[0]]=t)}}}function M(t,e,r){if(e?.trim&&(r=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,r){let e=t=>t.trim?r+t:t.map(e);t.topics=t.topics.map(e)}return t}const E={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};class Q extends I{static mqtt_ctx(t,e,r=E){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r){r={__proto__:r||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return T[this.b0>>>4]}};let n,s=[],i={};for(n of e.encode_fns)n(i,e.mqtt_writer);for(n of e.decode_fns)n(s,e.mqtt_reader);return{pkt_ctx:r,encode_pkt:(e,r)=>i[e](t,r),decode_pkt(t,e){let r=s[t>>>4]||s[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:r}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=S(t),t}}}(t,e,r),n}init_client_id(t=["u8-mqtt--",""]){let e,r=this.sess_stg,n=r?.getItem(e=t.join(" "));return n||(n=t.join(Math.random().toString(36).slice(2)),r?.setItem(e,n)),n}get sess_stg(){return globalThis.sessionStorage}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let r=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)r(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:r}=t;if(1!==r){if(0!==r)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:n}=this,s=n.set(this.mqtt_ctx,(async r=>(await e,t.send(r))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}n.reset(e)},this}}const $="0.5.0",C=y(Q.mqtt_ctx(4,m)),L=y(Q.mqtt_ctx(5,m)),O=t=>new C(t),z=t=>new L(t);export{L as MQTTClient,C as MQTTClient_v4,L as MQTTClient_v5,z as default,z as mqtt,O as mqtt_v4,z as mqtt_v5,$ as version};
1
+ function t(t,e=[]){do{const r=127&t;t>>>=7,e.push(r|(0===t?0:128))}while(t>0);return e}function e(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}const r=n();function n(){let t=new Map,e=[[1,"u8","payload_format_indicator"],[2,"u32","message_expiry_interval"],[3,"utf8","content_type"],[8,"utf8","response_topic"],[9,"bin","correlation_data"],[11,"vint","subscription_identifier"],[17,"u32","session_expiry_interval"],[18,"utf8","assigned_client_identifier"],[19,"u16","server_keep_alive"],[21,"utf8","authentication_method"],[22,"bin","authentication_data"],[23,"u8","request_problem_information"],[24,"u32","will_delay_interval"],[25,"u8","request_response_information"],[26,"utf8","response_information"],[28,"utf8","server_reference"],[31,"utf8","reason_string"],[33,"u16","receive_maximum"],[34,"u16","topic_alias_maximum"],[35,"u16","topic_alias"],[36,"u8","maximum_qos"],[37,"u8","retain_available"],[38,"pair","user_properties",{op:"kv_obj"}],[39,"u32","maximum_packet_size"],[40,"u8","wildcard_subscription_available"],[41,"u8","subscription_identifiers_available",{op:"u8_vec"}],[42,"u8","shared_subscription_available"]];for(let[r,n,s,i]of e){let e={id:r,type:n,name:s,...i};t.set(e.id,e),t.set(e.name,e)}return t}class s extends Number{static of(t,e,r){let n=new this(t);return n.reason=r?.[e]?.get(t)||e,n}}class i{static of(t){return this.prototype.of(t)}of(t){let e=(t,r)=>(r=0|e.k,e.k=r+t,r);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,r=e(2);return t[r]<<8|t[r+1]}u32(){let{buf:t,step:e}=this,r=e(4);return t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]}vint(){let{buf:t,step:r}=this,[n,s,i]=e(t,0|r.k);return r(s-i),n}bin(){let{buf:t,step:e}=this,r=e(2),n=t[r]<<8|t[r+1];return r=e(n),t.subarray(r,r+n)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let e=this.buf[this.step(1)];if(null!=e)return s.of(e,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}}let o=class extends i{props(){let{buf:t,step:n}=this,[s,i,o]=e(t,0|n.k);if(n(s+i-o),0===s)return null;let u={},a=this.of(t.subarray(i,0|n.k));for(;a.has_more();){let t=r.get(a.u8()),e=a[t.type]();u[t.name]=t.op?a[t.op](u[t.name],e):e}return u}kv_obj(t=Object.create(null),[e,r]){return t[e]=r,t}u8_vec(t=[],e){return t.push(e),t}};function u(t,...e){t=class extends t{static reasons(t,...e){let r=this.prototype;r._reasons_by={...r._reasons_by};let n=r._reasons_by[t]||=new Map;for(let[t,r]of e)n.set(t,r);return this}};for(let r of e)r(t);return t}class a{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let r,n,s=0,i=this.$;for(r of(this.$=!1,i))s+=r.length;n=(e=t(s,e)).length;let o=new Uint8Array(n+s);for(r of(o.set(e,0),i))o.set(r,n),n+=r.length;return o}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,r=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=r,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}function c(t){!function(t){t.reasons("connack",[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"])}(t),t.reasons("connack",[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[132,"Unsupported Protocol Version"],[133,"Client Identifier not valid"],[134,"Bad User Name or Password"],[135,"Not authorized"],[136,"Server unavailable"],[137,"Server busy"],[138,"Banned"],[140,"Bad authentication method"],[144,"Topic Name invalid"],[149,"Packet too large"],[151,"Quota exceeded"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[159,"Connection rate exceeded"])}function p(t){t.reasons("puback",[0,"Success"],[16,"No matching subscribers"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[144,"Topic Name invalid"],[145,"Packet identifier in use"],[151,"Quota exceeded"],[153,"Payload format invalid"])}function l(t){return(e,r)=>{let n=t.of(r);e.pkt_id=n.u16(),5<=e.mqtt_level&&(e.props=n.props());let s=e.answers=[];for(;n.has_more();)s.push(n.reason(e.type));return e}}function _(t){!function(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}(t),t.reasons("suback",[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"],[151,"Quota exceeded"],[158,"Shared Subscriptions not supported"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function f(t){t.reasons("unsuback",[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"])}function d(t){t.reasons("disconnect",[0,"Normal disconnection"],[4,"Disconnect with Will Message"],[128,"Unspecified error"],[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[135,"Not authorized"],[137,"Server busy"],[139,"Server shutting down"],[141,"Keep Alive timeout"],[142,"Session taken over"],[143,"Topic Filter invalid"],[144,"Topic Name invalid"],[147,"Receive Maximum exceeded"],[148,"Topic Alias invalid"],[149,"Packet too large"],[150,"Message rate too high"],[151,"Quota exceeded"],[152,"Administrative action"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[158,"Shared Subscriptions not supported"],[159,"Connection rate exceeded"],[160,"Maximum connect time"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"])}function h(t){t.reasons("auth",[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"])}const b=[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,s)=>{let i=e.of(s);i.push(r),i.u8(t);let{will:o,username:u,password:a}=s,c=i.flags(s.flags,n,0|(u?128:0)|(a?64:0)|(o?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(o):0));return i.u16(s.keep_alive),5<=t&&i.props(s.props),i.utf8(s.client_id),4&c&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&c&&i.utf8(u),64&c&&i.bin(a),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.of(r);return n.u16(r.pkt_id),5<=t&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(64)}},function(t,e){return t.publish=(t,r)=>{let n=(3&r.qos)<<1,s=e.of(r);return s.utf8(r.topic),0!==n&&s.u16(r.pkt_id),5<=t?(s.props(r.props),s.flush(r.payload)):s.flush(r.payload),s.as_pkt(48|n|(r.dup?8:0)|(r.retain?1:0))}},function(t,e){const r=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.of(n);s.u16(n.pkt_id),5<=t&&s.props(n.props);let i=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(i);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(i):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,r)=>{let n=e.of(r);n.u16(r.pkt_id),5<=t&&n.props(r.props);for(let t of r.topics)n.utf8(t);return n.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,r)=>{let n=e.of(r);return r&&5<=t&&(r.reason||r.props)&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(224)}},function(t,e){return t.auth=(t,r)=>{if(5>t)throw new Error("Auth packets are only available after MQTT 5.x");let n=e.of(r);return n.reason(r.reason),n.props(r.props),n.as_pkt(240)}}],m={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.of(n);return t.flags=s.flags(r),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,r)=>{let{hdr:n}=t;t.dup=Boolean(8&n),t.retain=Boolean(1&n);let s=t.qos=n>>1&3,i=e.of(r);return t.topic=i.utf8(),0!==s&&(t.pkt_id=i.u16()),5<=t.mqtt_level&&(t.props=i.props()),t.payload=i.flush(),t}},function(t,e){return t[4]=(t,r)=>{let n=e.of(r);return t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.reason=n.reason(t.type),t.props=n.props()),t}},function(t,e){return t[9]=l(e)},function(t,e){return t[11]=l(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,r)=>{if(r&&5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}},function(t,e){return t[15]=(t,r)=>{if(5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}}],mqtt_reader:u(o,c,p,_,f,d,h),encode_fns:b,mqtt_writer:class extends a{props(t){if(!t)return this.u8(0);if(Array.isArray(t)||(t=t.entries?Array.from(t.entries()):Object.entries(t)),0===t.length)return this.u8(0);let e=this.of();for(let[n,s]of t){let t=r.get(n);e[t.op||"one"](s,t)}this.push(e.pack())}one(t,e){this.u8(e.id),this[e.type](t)}kv_obj(t,e){for(let r of Object.entries(t))this.u8(e.id),this.pair(r)}u8_vec(t,e){for(let r of t)this.u8(e.id),this.u8(r)}}};const y=(t=>e=>class extends e{static _aliases(){return super._aliases()+" sub_topic:subscribe_topic unsub_topic:unsubscribe_topic"}_init_router(e,r,n){this._subs=[];let s=this.router=n.router=t(e,this,n);return s?.invoke}on_sub(t,e){return t.pkt=e,this._subs.push(t),t}subs_settled(){return Promise.allSettled(this._subs.splice(0,1/0))}subscribe_topic(t,...e){let r=this.router;r.add(t,!0,e.pop());let n=r.mqtt_topic(t);return this.subscribe(n,...e),this}unsubscribe_topic(t,...e){let r=this.router;r.remove(t,!0);let n=r.mqtt_topic(t);return this.unsubscribe(n,...e)}on_topic(...t){return this.router.add(...t),this}})(v),w=t=>t.replace(/[*].*$/,"#").replace(/:\w[^\/]*/g,"+"),g=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function k(t,e,r){r.done=!0}function v(){let t=[[],[]],e=Symbol(),r=e=>function*(t,e){e=e.replace(/^[\/]*/,"/");for(let r of t)for(let{keys:t,pattern:n,tgt:s}of r){let r=n.exec(e);if(r){let e=t?t.reduce(((t,e,n)=>(t[e]=r[1+n],t)),{}):r.groups??r;yield[s,e]}}}(t,e);return{find:r,mqtt_topic:w,add(e,...r){let n=r.pop(),s=r.pop();if("function"!=typeof n){if(n)throw new TypeError;n=k}let i=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var r,n,s,i,o=[],u="",a=t.split("/");for(a[0]||a.shift();s=a.shift();)"*"===(r=s[0])?(o.push("wild"),u+="/(.*)"):":"===r?(n=s.indexOf("?",1),i=s.indexOf(".",1),o.push(s.substring(1,~n?n:~i?i:s.length)),u+=~n&&!~i?"(?:/([^/]+?))?":"/([^/]+?)",~i&&(u+=(~n?"?":"")+"\\"+s.substring(i))):u+="/"+s;return{keys:o,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(g(e));return i.key=e,i.tgt=n,t[s?0:1].push(i),this},remove:(e,r)=>x([t[r?0:1]],e),clear(e){t[e?0:1]=[],null==e&&(t[1]=[])},async invoke(n,s){s.idx=0,s.rm=e;for(let[i,o]of r(n.topic)){let r=await i(n,o,s);if(e===r&&x(t,i),s.done)break;s.idx++}1===n.qos&&await s.mqtt.puback(n)}}}function x(t,e){let r=t=>t===e||t.tgt===e||t.key===e;for(let e of t){let t=e.findIndex(r);if(0<=t)return e.splice(t,1),!0}return!1}function q(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}function S(t){let e=new Uint8Array(0);return r=>{e=0===e.byteLength?r:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,r);let n=[];for(;;){let[r,s]=q(e,1),i=r+s;if(e.byteLength<i)return n;let o=e[0],u=0===r?null:e.subarray(s,i);e=e.subarray(i);let a=t.decode_pkt(o,u,t);null!=a&&n.push(a)}}}const T=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function j(t=((...t)=>t)){let e,r,n=(t,n)=>{e=t,r=n};return s=>(s=new Promise(n),t(s,e,r))}const P=j();function A(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}Promise.resolve({type:"init"});const N={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:r}=this,n=t=>r[0].set(e,t);return r=>("string"==typeof r?e=r:(t=t+1&65535,e=r.pkt_id=t),new Promise(n))},answer(t,e){for(let r of this.hashbelt){let n=r.get(t);if(void 0!==n)return r.delete(t),n([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let r of e.splice(t||5))for(let t of r.values())t([,"expired"])},cmdids:(()=>{return[()=>{},r,e,r,t,t,t,t,r,t,r,t,e,e,r,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,n){t.answer(e.type,e),r(t,e,n)}async function r({target:t},e,r){let n=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(n?.call(t,e,r))}})()};class U extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class I{constructor(t={}){this.with(t),this._conn_=function(t,[e,r]){let n,s,i=P(),o=P(),u=async(...t)=>(await o[0])(...t);return t._send=u,{async when_ready(){await o[0]},ping:A((()=>n?.("pingreq"))),reset(e){n&&(e&&i[2](e),n=null,i=P(),t._send=u,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){n||await i[0];let r=await n(...e);return 0==r[0].reason&&(s=!0,o[1](t._send=n),o=P(),t.conn_emit("on_ready")),r},is_set:()=>!!n,set(o,u){if(n)throw new Error("Already connected");o=o.mqtt_stream();let a={mqtt:t};return n=async(t,e,n)=>{let s=void 0===n||r(n);return await u(o.encode_pkt(t,e)),s},i[1](n),t.conn_emit("on_live",s),t=>e(o.decode(t),a)}}}(this,this._init_dispatch(t,this))}with(t){for(let[e,r]of Object.entries(t))"function"==typeof r&&(this[e]=r);return this}async conn_emit(t,e,r){this.log_conn?.(t,e,r);try{let n=this[await t];if(n)await n.call(this,this,e,r);else if(r)throw r}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||this.client_id;"string"!=typeof e&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._conn_.send_connect("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this._conn_.ping(t.keep_alive),r}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,r){t=M(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=M(t,e,r),this._send("unsubscribe",t,t)}post(t,e,r){return this.pub({topic:t,payload:e,qos:0},r)}send(t,e,r){return this.pub({topic:t,payload:e,qos:1},r)}store(t,e,r){return this.pub({topic:t,payload:e,qos:1,retain:1},r)}obj_post(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:0},r)}obj_send(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1},r)}obj_store(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},r)}async pub(t,e){if(void 0===t.payload){"function"==typeof e&&(e={fn_encode:e});let{msg:r}=t;switch(typeof r){case"function":e={...e,fn_encode:r};case"undefined":return r=>this.pub({...t,[t.arg||"payload"]:r},e)}let{fn_encode:n}=e||{};t.payload=n?await n(r):JSON.stringify(r)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:void 0)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),function(t,e){let r=N.create(e),{cmdids:n}=r,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)n[s.id](r,s,e);Date.now()>o&&(r.rotate_belt(i),o=s+Date.now())},r.bind_pkt_future()]}(this,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;let e=t.prototype;e.MQTTError=U;for(let r of t._aliases().split(/\s+/)){r=r.split(":");let t=r[1]&&e[r[1]];t&&(e[r[0]]=t)}}}function M(t,e,r){if(e?.trim&&(r=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,r){let e=t=>t.trim?r+t:t.map(e);t.topics=t.topics.map(e)}return t}const E={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};class Q extends I{static mqtt_ctx(t,e,r=E){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r){r={__proto__:r||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return T[this.b0>>>4]}};let n,s=[],i={};for(n of e.encode_fns)n(i,e.mqtt_writer);for(n of e.decode_fns)n(s,e.mqtt_reader);return{pkt_ctx:r,encode_pkt:(e,r)=>i[e](t,r),decode_pkt(t,e){let r=s[t>>>4]||s[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:r}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=S(t),t}}}(t,e,r),n}init_client_id(t=["u8-mqtt--",""]){let e,r=this.sess_stg,n=r?.getItem(e=t.join(" "));return n||(n=t.join(Math.random().toString(36).slice(2)),r?.setItem(e,n)),n}get sess_stg(){return globalThis.sessionStorage}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let r=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)r(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:r}=t;if(1!==r){if(0!==r)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:n}=this,s=n.set(this.mqtt_ctx,(async r=>(await e,t.send(r))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}n.reset(e)},this}}const $="0.5.2-web",C=y(Q.mqtt_ctx(4,m)),L=y(Q.mqtt_ctx(5,m)),O=t=>new C(t),z=t=>new L(t);export{L as MQTTClient,C as MQTTClient_v4,L as MQTTClient_v5,z as default,z as mqtt,O as mqtt_v4,z as mqtt_v5,$ as version};
Binary file
Binary file
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "u8-mqtt",
3
3
  "description": "MQTT client using Uint8Array -- suitable for use in the Browser, NodeJS, and Deno.land.",
4
- "version": "0.5.0",
4
+ "version": "0.5.2",
5
5
  "license": "BSD-2-Clause",
6
6
  "author": "Shane Holloway <shane.holloway@ieee.org>",
7
7
  "homepage": "https://github.com/shanewholloway/js-u8-mqtt#readme",
@@ -18,14 +18,23 @@
18
18
  "esm/"
19
19
  ],
20
20
  "type": "module",
21
+ "main": "./cjs/index.cjs",
22
+ "module": "./esm/index.js",
23
+ "browser": "./esm/web/index.min.js",
21
24
  "exports": {
22
25
  "./esm/*": "./esm/*",
23
26
  "./cjs/*": "./cjs/*",
27
+ "./web": "./esm/web/index.js",
28
+ "./deno": "./esm/deno/index.js",
29
+ "./node": "./esm/node/index.js",
30
+ "./core": "./esm/index.js",
24
31
  ".": {
25
32
  "browser": "./esm/web/index.js",
26
33
  "deno": "./esm/deno/index.js",
34
+ "require": "./cjs/index.cjs",
27
35
  "node": "./esm/node/index.js",
28
- "require": "./cjs/index.cjs"
36
+ "import": "./esm/index.js",
37
+ "default": "./esm/index.js"
29
38
  }
30
39
  },
31
40
  "workspaces": [