u8-mqtt 0.6.4 → 0.6.6

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 (96) hide show
  1. package/cjs/basic-v4.cjs +1 -1
  2. package/cjs/basic-v5.cjs +1 -1
  3. package/cjs/full-v4.cjs +46 -25
  4. package/cjs/full-v4.cjs.map +1 -1
  5. package/cjs/full-v5.cjs +46 -25
  6. package/cjs/full-v5.cjs.map +1 -1
  7. package/cjs/index.cjs +46 -25
  8. package/cjs/index.cjs.map +1 -1
  9. package/cjs/v4.cjs +46 -25
  10. package/cjs/v4.cjs.map +1 -1
  11. package/cjs/v5.cjs +46 -25
  12. package/cjs/v5.cjs.map +1 -1
  13. package/code/router_path.jsy +34 -21
  14. package/code/with_topic_router.jsy +3 -0
  15. package/esm/basic-v4.js +1 -1
  16. package/esm/basic-v5.js +1 -1
  17. package/esm/deno/basic-v4.js +1 -1
  18. package/esm/deno/basic-v5.js +1 -1
  19. package/esm/deno/full-v4.js +46 -25
  20. package/esm/deno/full-v4.js.map +1 -1
  21. package/esm/deno/full-v5.js +46 -25
  22. package/esm/deno/full-v5.js.map +1 -1
  23. package/esm/deno/index.js +46 -25
  24. package/esm/deno/index.js.map +1 -1
  25. package/esm/deno/v4.js +46 -25
  26. package/esm/deno/v4.js.map +1 -1
  27. package/esm/deno/v5.js +46 -25
  28. package/esm/deno/v5.js.map +1 -1
  29. package/esm/full-v4.js +46 -25
  30. package/esm/full-v4.js.map +1 -1
  31. package/esm/full-v5.js +46 -25
  32. package/esm/full-v5.js.map +1 -1
  33. package/esm/index.js +46 -25
  34. package/esm/index.js.map +1 -1
  35. package/esm/node/basic-v4.js +1 -1
  36. package/esm/node/basic-v4.mjs +1 -1
  37. package/esm/node/basic-v5.js +1 -1
  38. package/esm/node/basic-v5.mjs +1 -1
  39. package/esm/node/full-v4.js +46 -25
  40. package/esm/node/full-v4.js.map +1 -1
  41. package/esm/node/full-v4.mjs +46 -25
  42. package/esm/node/full-v4.mjs.map +1 -1
  43. package/esm/node/full-v5.js +46 -25
  44. package/esm/node/full-v5.js.map +1 -1
  45. package/esm/node/full-v5.mjs +46 -25
  46. package/esm/node/full-v5.mjs.map +1 -1
  47. package/esm/node/index.js +46 -25
  48. package/esm/node/index.js.map +1 -1
  49. package/esm/node/index.mjs +46 -25
  50. package/esm/node/index.mjs.map +1 -1
  51. package/esm/node/v4.js +46 -25
  52. package/esm/node/v4.js.map +1 -1
  53. package/esm/node/v4.mjs +46 -25
  54. package/esm/node/v4.mjs.map +1 -1
  55. package/esm/node/v5.js +46 -25
  56. package/esm/node/v5.js.map +1 -1
  57. package/esm/node/v5.mjs +46 -25
  58. package/esm/node/v5.mjs.map +1 -1
  59. package/esm/v4.js +46 -25
  60. package/esm/v4.js.map +1 -1
  61. package/esm/v5.js +46 -25
  62. package/esm/v5.js.map +1 -1
  63. package/esm/web/basic-v4.js +1 -1
  64. package/esm/web/basic-v4.min.js +1 -1
  65. package/esm/web/basic-v4.min.js.br +0 -0
  66. package/esm/web/basic-v4.min.js.gz +0 -0
  67. package/esm/web/basic-v5.js +1 -1
  68. package/esm/web/basic-v5.min.js +1 -1
  69. package/esm/web/basic-v5.min.js.br +0 -0
  70. package/esm/web/basic-v5.min.js.gz +0 -0
  71. package/esm/web/full-v4.js +46 -25
  72. package/esm/web/full-v4.js.map +1 -1
  73. package/esm/web/full-v4.min.js +1 -1
  74. package/esm/web/full-v4.min.js.br +0 -0
  75. package/esm/web/full-v4.min.js.gz +0 -0
  76. package/esm/web/full-v5.js +46 -25
  77. package/esm/web/full-v5.js.map +1 -1
  78. package/esm/web/full-v5.min.js +1 -1
  79. package/esm/web/full-v5.min.js.br +0 -0
  80. package/esm/web/full-v5.min.js.gz +0 -0
  81. package/esm/web/index.js +46 -25
  82. package/esm/web/index.js.map +1 -1
  83. package/esm/web/index.min.js +1 -1
  84. package/esm/web/index.min.js.br +0 -0
  85. package/esm/web/index.min.js.gz +0 -0
  86. package/esm/web/v4.js +46 -25
  87. package/esm/web/v4.js.map +1 -1
  88. package/esm/web/v4.min.js +1 -1
  89. package/esm/web/v4.min.js.br +0 -0
  90. package/esm/web/v4.min.js.gz +0 -0
  91. package/esm/web/v5.js +46 -25
  92. package/esm/web/v5.js.map +1 -1
  93. package/esm/web/v5.min.js +1 -1
  94. package/esm/web/v5.min.js.br +0 -0
  95. package/esm/web/v5.min.js.gz +0 -0
  96. package/package.json +2 -2
@@ -1 +1 @@
1
- function t(t,e=[]){for(e.push((t<128?0:128)|127&t);(t>>>=7)>0;)e.push((t<128?0:128)|127&t);return e}class e extends Number{constructor(t,e){super(t),this.reason=`:${(this.ok=t<128)?"ok":"fail"}:${e}`}}function n(t,e){for(let[t,n]of Object.entries(e))e[t]=new Map(n);return class extends t{_reason_for(t,n){return e[n]?.get(t)||e.all.get(t)}warn(t){let e=this.pkt;e.warn?e.warn(t,e):console.warn("[u8-mqtt-packet] "+t)}}}const r=n(class{static for(t,e){return(new this).of(e,{pkt:t})}of(t,e){let n=(t,e)=>(e=0|n.k,n.k=e+t,e);return{__proto__:this,buf:t,step:n,...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,n){let r=0,s=e,o=t[s++],i=127&o;for(;128&o;)i|=(127&(o=t[s++]))<<(r+=7);return t.length<s?[n,e,e]:[i,s,e]}(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 new e(n,this._reason_for?.(n,t))}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}},{connack:[[1,"conn refused: unacceptable protocol version"],[2,"conn refused: identifier rejected"],[3,"conn refused: server unavailable"],[4,"conn refused: bad user name or password"],[5,"conn refused: not authorized"]],suback:[[0,"qos=0"],[1,"qos=1"],[2,"qos=2"]],unsuback:[[17,"no subscription existed"]],puback:[[16,"no matching subscribers"]],all:[[0,""],[128,"unspecified error"],[131,"implementation specific error"],[135,"not authorized"],[143,"topic filter invalid"],[145,"packet identifier in use"],[146,"packet identifier not found"]]});const s={decode_fns:[function(t,e){class n extends Number{get session_present(){return!0&this}}return t[2]=(t,r)=>{let s=e.for(t,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.for(t,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.for(t,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]=t[11]=(t,n)=>{let r=e.for(t,n);t.pkt_id=r.u16(),5<=t.mqtt_level&&(t.props=r.props());let s=t.answers=[];for(;r.has_more();)s.push(r.reason(t.type));return t}},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.for(t,n);t.reason=r.reason(t.type),t.props=r.props()}return t}}],mqtt_reader:r,encode_fns:[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.for(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.for(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.for(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.for(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.for(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.for(n);return n&&5<=t&&(n.reason||n.props)&&(r.reason(n.reason),r.props(n.props)),r.as_pkt(224)}}],mqtt_writer:class{static for(t){return(new this).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 o(t,e=0,n){let r=0,s=e,o=t[s++],i=127&o;for(;128&o;)i|=(127&(o=t[s++]))<<(r+=7);return t.length<s?[n,e,e]:[i,s,e]}function i(t){let e=new Uint8Array(0),n=0;return r=>{e=0===e.byteLength?r:function(t,e){let n=t.byteLength,r=new Uint8Array(n+e.byteLength);return r.set(t,0),r.set(e,n),r}(e,r);let s=[];for(;e.byteLength>=n;){let[r,i]=o(e,1,NaN),u=r+i;if(!(u<=e.byteLength)){n=u||0;break}let a=e[0],c=0===r?null:e.subarray(i,u);e=e.subarray(u);let p=t.decode_pkt(a,c,t);null!=p&&s.push(p)}return s}}const u=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];const a=t=>"function"==typeof t,c=t=>"string"==typeof t;async function p(t,e,n,r){let s=t[`mqtt_${n.type}`]||t.mqtt_pkt;await(s?.call(t,n,r))}function l(t,e,n,r){e(n.type,n),p(t,0,n,r)}function h(t,e,n){e(n.pkt_id,n)}const _=[t=>{},p,l,p,h,h,h,h,p,h,p,h,l,l,p,l];class f extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class d{async connect(t={}){let e=t.client_id;c(e)||(t.client_id=e=this.client_id||this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let n=await this._send0("connect",t,"connack");if(0!=n[0].reason)throw new this.MQTTError(n[0]);return this.conn.on_conn(t,n)}async disconnect(t={}){let e=await this._send0("disconnect",t);return this.conn.on_dis(t,e)}async auth(t={}){let e=await this._send0("auth",t,"auth");if(e[0].reason)throw new this.MQTTError(e[0]);return this.conn.on_auth(t,e)}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,n){t=b(t,e,n);let r=this._send("subscribe",t,t);return this.on_sub?.(r,t)??r}unsubscribe(t,e,n){return t=b(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){a(e)&&(e={fn_encode:e});let n=t.msg,r=e?.fn_encode;if(null==n||a(n))return n&&(e={...e,fn_encode:n}),n=>this.pub({...t,[t.arg||"payload"]:n},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:null)}_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,r=[],s=0,{td:o=1e3,n:i=5}=t?.rotate||{},u=100,a=t=>r[0].set(n,t);return l([]),[l,function(t){return c(t)?n=t:(u=u+1&65535,n=t.pkt_id=u),new Promise(a)}];function p(t,e){for(let n of r){let r=n.get(t);if(r)return n.delete(t),r([e]),!0}return!1}function l(t,n){for(let r of t)_[r.id](e,p,r,n);let u=Date.now();if(u>s)for(s=o+u,r.unshift(new Map);r.length>i;)for(let t of r.pop().values())t([,"expired"])}}(t,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;var e,n,r=t.prototype;for(e of(r.MQTTError=f,t._aliases().split(/\s+/)))[e,n]=e.split(":"),r[e]=r[n]}}function b(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 w=t=>(t.p=new Promise(((e,n)=>{t.a=e,t.e=n})),t);function y(t,e,n){let r={set:o},s=async(...t)=>(await r.p)(...t);return o();function o(){return s!==t[e]&&(w(r).p.then(n,(t=>0)),t[e]=s),r}}function m(t,e,[n,r]){let s,o=y(e,"_send0",(t=>e.conn_emit("on_live",a.has_connected))),i=y(e,"_send",(t=>e.conn_emit("on_ready"))),u=function(t){let e;return n=>{if(e=clearInterval(e),n)return e=setInterval(t,1e3*n),e.unref?.(),!0}}((()=>e._send0("pingreq"))),a=Object.create({ping:(t=a.keep_alive)=>u(t),on_conn:(n,r)=>(a.has_connected=!0,a.keep_alive=t.keep_alive||r[0].props?.server_keep_alive||n.keep_alive,e.conn_emit("on_conn"),t.use_auth?r:a.on_auth(null,r)),on_auth:(n,r)=>(i.a(o.p),0!=t.keep_alive&&a.ping(),e.conn_emit("on_auth",!n),r),on_dis:(t,e)=>(a.reset(!1),e),reset(t){t&&o.e(t),s.e(t),delete a.is_set,a.ready=c(),e.conn_emit("on_disconnect",!1===t,t)},abort:()=>(i.e(err),a.reset(err)),async setup(t,s,i){if(a.is_set)throw new Error;a.is_set=!0,await t;let u=e.mqtt_ctx.mqtt_stream();{let t={mqtt:e};i((e=>n(u.decode(e),t)),a)}s=await s,o.a((async(t,e,n)=>{let o=void 0===n||r(n);return await s(u.encode_pkt(t,e)),o}))}});return a.ready=c(),a;async function c(){s=w({}),u(0),o.set(),i.set();try{return e._send0=await Promise.race([o.p,s.p]),e._send=await Promise.race([i.p,s.p]),!0}catch(t){return!1}}}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)}},k={sess_stg:globalThis.sessionStorage};const q="0.6.4-web",v=class extends d{constructor(t){t={...k,...t},super(),this.with(t),this.sess_stg=t.sess_stg,this.conn=m(t,this,this._init_dispatch(t))}with(t){for(let[e,n]of Object.entries(t))a(n)&&(this[e]=n);return this}static mqtt_ctx(t,e,n=g){let r=class extends(this){};return r.prototype.mqtt_ctx=function(t,e,n=e.pkt_ctx){let r,s=e=>({__proto__:e,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return u[this.b0>>>4]},mqtt_level:t}),o=[],a={};for(r of e.encode_fns)r(a,e.mqtt_writer);for(r of e.decode_fns)r(o,e.mqtt_reader);return{pkt_api:n,pkt_ctx:s(n),encode_pkt:(e,n)=>a[e](t,n),decode_pkt(t,e){if(t.map)return i(this)(t)[0];let n=o[t>>>4]||o[0];return n?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(t=this.pkt_api){let e={__proto__:this,pkt_ctx:s(t)};return e.decode=i(e),e}}}(t,e,n),r}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)}log_conn(t,e,n){console.info("[[u8-mqtt conn: %s]]",t,e,n)}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}on_live(t,e){if(e)return t.connect()}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}_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)}})}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){return this.conn.setup(t,e,(async(e,n)=>{try{t=await t;for await(let n of t)e(n);n.reset()}catch(t){n.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,n=t.readyState;if(1!==n){if(0!==n)throw new Error("WS readyState");e=new Promise((e=>t.onopen=e))}return this.conn.setup(e,(e=>t.send(e)),((e,n)=>{t.onmessage=t=>e(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket close");e.code=t.code,e.reason=t.reason}n.reset(e)}})),this}}.mqtt_ctx(4,s),x=t=>new v(t);export{v as MQTTClient,v as MQTTClient_v4,x as default,x as mqtt,x as mqtt_v4,q as version};
1
+ function t(t,e=[]){for(e.push((t<128?0:128)|127&t);(t>>>=7)>0;)e.push((t<128?0:128)|127&t);return e}class e extends Number{constructor(t,e){super(t),this.reason=`:${(this.ok=t<128)?"ok":"fail"}:${e}`}}function n(t,e){for(let[t,n]of Object.entries(e))e[t]=new Map(n);return class extends t{_reason_for(t,n){return e[n]?.get(t)||e.all.get(t)}warn(t){let e=this.pkt;e.warn?e.warn(t,e):console.warn("[u8-mqtt-packet] "+t)}}}const r=n(class{static for(t,e){return(new this).of(e,{pkt:t})}of(t,e){let n=(t,e)=>(e=0|n.k,n.k=e+t,e);return{__proto__:this,buf:t,step:n,...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,n){let r=0,s=e,o=t[s++],i=127&o;for(;128&o;)i|=(127&(o=t[s++]))<<(r+=7);return t.length<s?[n,e,e]:[i,s,e]}(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 new e(n,this._reason_for?.(n,t))}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}},{connack:[[1,"conn refused: unacceptable protocol version"],[2,"conn refused: identifier rejected"],[3,"conn refused: server unavailable"],[4,"conn refused: bad user name or password"],[5,"conn refused: not authorized"]],suback:[[0,"qos=0"],[1,"qos=1"],[2,"qos=2"]],unsuback:[[17,"no subscription existed"]],puback:[[16,"no matching subscribers"]],all:[[0,""],[128,"unspecified error"],[131,"implementation specific error"],[135,"not authorized"],[143,"topic filter invalid"],[145,"packet identifier in use"],[146,"packet identifier not found"]]});const s={decode_fns:[function(t,e){class n extends Number{get session_present(){return!0&this}}return t[2]=(t,r)=>{let s=e.for(t,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.for(t,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.for(t,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]=t[11]=(t,n)=>{let r=e.for(t,n);t.pkt_id=r.u16(),5<=t.mqtt_level&&(t.props=r.props());let s=t.answers=[];for(;r.has_more();)s.push(r.reason(t.type));return t}},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.for(t,n);t.reason=r.reason(t.type),t.props=r.props()}return t}}],mqtt_reader:r,encode_fns:[function(t,e){const n=new Uint8Array([0,4,77,81,84,84]),r=t=>(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.for(s);o.push(n),o.u8(t);let{will:i,username:u,password:a}=s,c=o.flags(s.flags,r,(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.for(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.for(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=>3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,r)=>{let s=e.for(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.for(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.for(n);return n&&5<=t&&(n.reason||n.props)&&(r.reason(n.reason),r.props(n.props)),r.as_pkt(224)}}],mqtt_writer:class{static for(t){return(new this).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 o(t,e=0,n){let r=0,s=e,o=t[s++],i=127&o;for(;128&o;)i|=(127&(o=t[s++]))<<(r+=7);return t.length<s?[n,e,e]:[i,s,e]}function i(t){let e=new Uint8Array(0),n=0;return r=>{e=0===e.byteLength?r:function(t,e){let n=t.byteLength,r=new Uint8Array(n+e.byteLength);return r.set(t,0),r.set(e,n),r}(e,r);let s=[];for(;e.byteLength>=n;){let[r,i]=o(e,1,NaN),u=r+i;if(!(u<=e.byteLength)){n=u||0;break}let a=e[0],c=0===r?null:e.subarray(i,u);e=e.subarray(u);let p=t.decode_pkt(a,c,t);null!=p&&s.push(p)}return s}}const u=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];const a=t=>"function"==typeof t,c=t=>"string"==typeof t;async function p(t,e,n,r){let s=t[`mqtt_${n.type}`]||t.mqtt_pkt;await(s?.call(t,n,r))}function l(t,e,n,r){e(n.type,n),p(t,0,n,r)}function h(t,e,n){e(n.pkt_id,n)}const _=[t=>{},p,l,p,h,h,h,h,p,h,p,h,l,l,p,l];class f extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class d{async connect(t={}){let e=t.client_id;c(e)||(t.client_id=e=this.client_id||this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let n=await this._send0("connect",t,"connack");if(0!=n[0].reason)throw new this.MQTTError(n[0]);return this.conn.on_conn(t,n)}async disconnect(t={}){let e=await this._send0("disconnect",t);return this.conn.on_dis(t,e)}async auth(t={}){let e=await this._send0("auth",t,"auth");if(e[0].reason)throw new this.MQTTError(e[0]);return this.conn.on_auth(t,e)}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,n){t=b(t,e,n);let r=this._send("subscribe",t,t);return this.on_sub?.(r,t)??r}unsubscribe(t,e,n){return t=b(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){a(e)&&(e={fn_encode:e});let n=t.msg,r=e?.fn_encode;if(null==n||a(n))return n&&(e={...e,fn_encode:n}),n=>this.pub({...t,[t.arg||"payload"]:n},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:null)}_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,r=[],s=0,{td:o=1e3,n:i=5}=t?.rotate||{},u=100,a=t=>r[0].set(n,t);return l([]),[l,function(t){return c(t)?n=t:(u=u+1&65535,n=t.pkt_id=u),new Promise(a)}];function p(t,e){for(let n of r){let r=n.get(t);if(r)return n.delete(t),r([e]),!0}return!1}function l(t,n){for(let r of t)_[r.id](e,p,r,n);let u=Date.now();if(u>s)for(s=o+u,r.unshift(new Map);r.length>i;)for(let t of r.pop().values())t([,"expired"])}}(t,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;var e,n,r=t.prototype;for(e of(r.MQTTError=f,t._aliases().split(/\s+/)))[e,n]=e.split(":"),r[e]=r[n]}}function b(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 w=t=>(t.p=new Promise(((e,n)=>{t.a=e,t.e=n})),t);function y(t,e,n){let r={set:o},s=async(...t)=>(await r.p)(...t);return o();function o(){return s!==t[e]&&(w(r).p.then(n,(t=>0)),t[e]=s),r}}function m(t,e,[n,r]){let s,o=y(e,"_send0",(t=>e.conn_emit("on_live",a.has_connected))),i=y(e,"_send",(t=>e.conn_emit("on_ready"))),u=function(t){let e;return n=>{if(e=clearInterval(e),n)return e=setInterval(t,1e3*n),e.unref?.(),!0}}((()=>e._send0("pingreq"))),a=Object.create({ping:(t=a.keep_alive)=>u(t),on_conn:(n,r)=>(a.has_connected=!0,a.keep_alive=t.keep_alive||r[0].props?.server_keep_alive||n.keep_alive,e.conn_emit("on_conn"),t.use_auth?r:a.on_auth(null,r)),on_auth:(n,r)=>(i.a(o.p),0!=t.keep_alive&&a.ping(),e.conn_emit("on_auth",!n),r),on_dis:(t,e)=>(a.reset(!1),e),reset(t){t&&o.e(t),s.e(t),delete a.is_set,a.ready=c(),e.conn_emit("on_disconnect",!1===t,t)},abort:()=>(i.e(err),a.reset(err)),async setup(t,s,i){if(a.is_set)throw new Error;a.is_set=!0,await t;let u=e.mqtt_ctx.mqtt_stream();{let t={mqtt:e};i((e=>n(u.decode(e),t)),a)}s=await s,o.a((async(t,e,n)=>{let o=void 0===n||r(n);return await s(u.encode_pkt(t,e)),o}))}});return a.ready=c(),a;async function c(){s=w({}),u(0),o.set(),i.set();try{return e._send0=await Promise.race([o.p,s.p]),e._send=await Promise.race([i.p,s.p]),!0}catch(t){return!1}}}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)}},k={sess_stg:globalThis.sessionStorage};const q="0.6.6-web",v=class extends d{constructor(t){t={...k,...t},super(),this.with(t),this.sess_stg=t.sess_stg,this.conn=m(t,this,this._init_dispatch(t))}with(t){for(let[e,n]of Object.entries(t))a(n)&&(this[e]=n);return this}static mqtt_ctx(t,e,n=g){let r=class extends(this){};return r.prototype.mqtt_ctx=function(t,e,n=e.pkt_ctx){let r,s=e=>({__proto__:e,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return u[this.b0>>>4]},mqtt_level:t}),o=[],a={};for(r of e.encode_fns)r(a,e.mqtt_writer);for(r of e.decode_fns)r(o,e.mqtt_reader);return{pkt_api:n,pkt_ctx:s(n),encode_pkt:(e,n)=>a[e](t,n),decode_pkt(t,e){if(t.map)return i(this)(t)[0];let n=o[t>>>4]||o[0];return n?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(t=this.pkt_api){let e={__proto__:this,pkt_ctx:s(t)};return e.decode=i(e),e}}}(t,e,n),r}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)}log_conn(t,e,n){console.info("[[u8-mqtt conn: %s]]",t,e,n)}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}on_live(t,e){if(e)return t.connect()}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}_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)}})}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){return this.conn.setup(t,e,(async(e,n)=>{try{t=await t;for await(let n of t)e(n);n.reset()}catch(t){n.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,n=t.readyState;if(1!==n){if(0!==n)throw new Error("WS readyState");e=new Promise((e=>t.onopen=e))}return this.conn.setup(e,(e=>t.send(e)),((e,n)=>{t.onmessage=t=>e(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket close");e.code=t.code,e.reason=t.reason}n.reset(e)}})),this}}.mqtt_ctx(4,s),x=t=>new v(t);export{v as MQTTClient,v as MQTTClient_v4,x as default,x as mqtt,x as mqtt_v4,q as version};
Binary file
Binary file
@@ -1296,7 +1296,7 @@ class MQTTCore extends MQTTBase {
1296
1296
 
1297
1297
  return this} }
1298
1298
 
1299
- const version = '0.6.4-web';
1299
+ const version = '0.6.6-web';
1300
1300
 
1301
1301
  const MQTTClient_v4 = /* #__PURE__ */
1302
1302
  MQTTCore.mqtt_ctx(4, mqtt_opts_v5);
@@ -1 +1 @@
1
- function t(t,e=[]){for(e.push((t<128?0:128)|127&t);(t>>>=7)>0;)e.push((t<128?0:128)|127&t);return e}function e(t,e=0,r){let n=0,s=e,i=t[s++],o=127&i;for(;128&i;)o|=(127&(i=t[s++]))<<(n+=7);return t.length<s?[r,e,e]:[o,s,e]}const r=()=>function(t,e){for(let[r,n,s,i]of e)i={id:r,type:n,name:s,...i},t.set(r,i).set(s,i);return t}(new Map,[[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"]]),n=r();class s extends Number{constructor(t,e){super(t),this.reason=`:${(this.ok=t<128)?"ok":"fail"}:${e}`}}class i{static for(t,e){return(new this).of(e,{pkt:t})}of(t,e){let r=(t,e)=>(e=0|r.k,r.k=e+t,e);return{__proto__:this,buf:t,step:r,...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 new s(e,this._reason_for?.(e,t))}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}}function o(t,e){for(let[t,r]of Object.entries(e))e[t]=new Map(r);return class extends t{_reason_for(t,r){return e[r]?.get(t)||e.all.get(t)}warn(t){let e=this.pkt;e.warn?e.warn(t,e):console.warn("[u8-mqtt-packet] "+t)}}}const u={connack:[[1,"conn refused: unacceptable protocol version"],[2,"conn refused: identifier rejected"],[3,"conn refused: server unavailable"],[4,"conn refused: bad user name or password"],[5,"conn refused: not authorized"]],suback:[[0,"qos=0"],[1,"qos=1"],[2,"qos=2"]],unsuback:[[17,"no subscription existed"]],puback:[[16,"no matching subscribers"]],all:[[0,""],[128,"unspecified error"],[131,"implementation specific error"],[135,"not authorized"],[143,"topic filter invalid"],[145,"packet identifier in use"],[146,"packet identifier not found"]]},a=o(class extends i{props(){let{buf:t,step:r}=this,[s,i,o]=e(t,0|r.k,0);if(r(s+i-o),0===s)return null;let u={},a=this.of(t.subarray(i,0|r.k));for(;a.has_more();){let t,e=a.u8(),r=n.get(e);if(!r){u._unknown_=e,this.warn?.(`unknown property: ${e}`);break}t=a[r.type](),u[r.name]=r.op?a[r.op](u[r.name],t):t}return u}kv_obj(t=Object.create(null),[e,r]){return t[e]=r,t}u8_vec(t=[],e){return t.push(e),t}},{...u,auth:[[24,"continue authentication"],[25,"re-authenticate"]],disconnect:[[4,"disconnect with will message"]],all:[...u.all,[129,"malformed packet"],[130,"protocol error"],[132,"unsupported protocol version"],[133,"client identifier not valid"],[134,"bad user name or password"],[136,"server unavailable"],[137,"server busy"],[138,"banned"],[139,"server shutting down"],[140,"bad authentication method"],[141,"keep alive timeout"],[142,"session taken over"],[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"]]});class p{static for(t){return(new this).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}}const c={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.for(t,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.for(t,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.for(t,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]=t[11]=(t,r)=>{let n=e.for(t,r);t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.props=n.props());let s=t.answers=[];for(;n.has_more();)s.push(n.reason(t.type));return t}},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.for(t,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,encode_fns:[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.for(s);i.push(r),i.u8(t);let{will:o,username:u,password:a}=s,p=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&p&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&p&&i.utf8(u),64&p&&i.bin(a),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.for(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.for(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.for(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.for(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.for(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)}}],mqtt_writer:class extends p{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[r,s]of t){let t=n.get(r);if(!t)throw new Error(`MQTT unknown property "${r}"`);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 l(t,e=0,r){let n=0,s=e,i=t[s++],o=127&i;for(;128&i;)o|=(127&(i=t[s++]))<<(n+=7);return t.length<s?[r,e,e]:[o,s,e]}function _(t){let e=new Uint8Array(0),r=0;return n=>{e=0===e.byteLength?n:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,n);let s=[];for(;e.byteLength>=r;){let[n,i]=l(e,1,NaN),o=n+i;if(!(o<=e.byteLength)){r=o||0;break}let u=e[0],a=0===n?null:e.subarray(i,o);e=e.subarray(o);let p=t.decode_pkt(u,a,t);null!=p&&s.push(p)}return s}}const h=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];const f=t=>"function"==typeof t,d=t=>"string"==typeof t;async function b(t,e,r,n){let s=t[`mqtt_${r.type}`]||t.mqtt_pkt;await(s?.call(t,r,n))}function m(t,e,r,n){e(r.type,r),b(t,0,r,n)}function w(t,e,r){e(r.pkt_id,r)}const y=[t=>{},b,m,b,w,w,w,w,b,w,b,w,m,m,b,m];class k extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class g{async connect(t={}){let e=t.client_id;d(e)||(t.client_id=e=this.client_id||this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._send0("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this.conn.on_conn(t,r)}async disconnect(t={}){let e=await this._send0("disconnect",t);return this.conn.on_dis(t,e)}async auth(t={}){let e=await this._send0("auth",t,"auth");if(e[0].reason)throw new this.MQTTError(e[0]);return this.conn.on_auth(t,e)}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,r){t=v(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=v(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){f(e)&&(e={fn_encode:e});let r=t.msg,n=e?.fn_encode;if(null==r||f(r))return r&&(e={...e,fn_encode:r}),r=>this.pub({...t,[t.arg||"payload"]:r},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:null)}_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=[],s=0,{td:i=1e3,n:o=5}=t?.rotate||{},u=100,a=t=>n[0].set(r,t);return c([]),[c,function(t){return d(t)?r=t:(u=u+1&65535,r=t.pkt_id=u),new Promise(a)}];function p(t,e){for(let r of n){let n=r.get(t);if(n)return r.delete(t),n([e]),!0}return!1}function c(t,r){for(let n of t)y[n.id](e,p,n,r);let u=Date.now();if(u>s)for(s=i+u,n.unshift(new Map);n.length>o;)for(let t of n.pop().values())t([,"expired"])}}(t,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;var e,r,n=t.prototype;for(e of(n.MQTTError=k,t._aliases().split(/\s+/)))[e,r]=e.split(":"),n[e]=n[r]}}function v(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 q=t=>(t.p=new Promise(((e,r)=>{t.a=e,t.e=r})),t);function x(t,e,r){let n={set:i},s=async(...t)=>(await n.p)(...t);return i();function i(){return s!==t[e]&&(q(n).p.then(r,(t=>0)),t[e]=s),n}}function j(t,e,[r,n]){let s,i=x(e,"_send0",(t=>e.conn_emit("on_live",a.has_connected))),o=x(e,"_send",(t=>e.conn_emit("on_ready"))),u=function(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}((()=>e._send0("pingreq"))),a=Object.create({ping:(t=a.keep_alive)=>u(t),on_conn:(r,n)=>(a.has_connected=!0,a.keep_alive=t.keep_alive||n[0].props?.server_keep_alive||r.keep_alive,e.conn_emit("on_conn"),t.use_auth?n:a.on_auth(null,n)),on_auth:(r,n)=>(o.a(i.p),0!=t.keep_alive&&a.ping(),e.conn_emit("on_auth",!r),n),on_dis:(t,e)=>(a.reset(!1),e),reset(t){t&&i.e(t),s.e(t),delete a.is_set,a.ready=p(),e.conn_emit("on_disconnect",!1===t,t)},abort:()=>(o.e(err),a.reset(err)),async setup(t,s,o){if(a.is_set)throw new Error;a.is_set=!0,await t;let u=e.mqtt_ctx.mqtt_stream();{let t={mqtt:e};o((e=>r(u.decode(e),t)),a)}s=await s,i.a((async(t,e,r)=>{let i=void 0===r||n(r);return await s(u.encode_pkt(t,e)),i}))}});return a.ready=p(),a;async function p(){s=q({}),u(0),i.set(),o.set();try{return e._send0=await Promise.race([i.p,s.p]),e._send=await Promise.race([o.p,s.p]),!0}catch(t){return!1}}}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)}},A={sess_stg:globalThis.sessionStorage};class E extends g{constructor(t){t={...A,...t},super(),this.with(t),this.sess_stg=t.sess_stg,this.conn=j(t,this,this._init_dispatch(t))}with(t){for(let[e,r]of Object.entries(t))f(r)&&(this[e]=r);return this}static mqtt_ctx(t,e,r=T){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r=e.pkt_ctx){let n,s=e=>({__proto__:e,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return h[this.b0>>>4]},mqtt_level:t}),i=[],o={};for(n of e.encode_fns)n(o,e.mqtt_writer);for(n of e.decode_fns)n(i,e.mqtt_reader);return{pkt_api:r,pkt_ctx:s(r),encode_pkt:(e,r)=>o[e](t,r),decode_pkt(t,e){if(t.map)return _(this)(t)[0];let r=i[t>>>4]||i[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(t=this.pkt_api){let e={__proto__:this,pkt_ctx:s(t)};return e.decode=_(e),e}}}(t,e,r),n}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)}log_conn(t,e,r){console.info("[[u8-mqtt conn: %s]]",t,e,r)}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}on_live(t,e){if(e)return t.connect()}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}_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)}})}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){return this.conn.setup(t,e,(async(e,r)=>{try{t=await t;for await(let r of t)e(r);r.reset()}catch(t){r.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,r=t.readyState;if(1!==r){if(0!==r)throw new Error("WS readyState");e=new Promise((e=>t.onopen=e))}return this.conn.setup(e,(e=>t.send(e)),((e,r)=>{t.onmessage=t=>e(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket close");e.code=t.code,e.reason=t.reason}r.reset(e)}})),this}}const S="0.6.4-web",$=E.mqtt_ctx(4,c),L=E.mqtt_ctx(5,c),M=t=>new $(t),U=t=>new L(t);export{L as MQTTClient,$ as MQTTClient_v4,L as MQTTClient_v5,U as default,U as mqtt,M as mqtt_v4,U as mqtt_v5,S as version};
1
+ function t(t,e=[]){for(e.push((t<128?0:128)|127&t);(t>>>=7)>0;)e.push((t<128?0:128)|127&t);return e}function e(t,e=0,r){let n=0,s=e,i=t[s++],o=127&i;for(;128&i;)o|=(127&(i=t[s++]))<<(n+=7);return t.length<s?[r,e,e]:[o,s,e]}const r=()=>function(t,e){for(let[r,n,s,i]of e)i={id:r,type:n,name:s,...i},t.set(r,i).set(s,i);return t}(new Map,[[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"]]),n=r();class s extends Number{constructor(t,e){super(t),this.reason=`:${(this.ok=t<128)?"ok":"fail"}:${e}`}}class i{static for(t,e){return(new this).of(e,{pkt:t})}of(t,e){let r=(t,e)=>(e=0|r.k,r.k=e+t,e);return{__proto__:this,buf:t,step:r,...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 new s(e,this._reason_for?.(e,t))}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}}function o(t,e){for(let[t,r]of Object.entries(e))e[t]=new Map(r);return class extends t{_reason_for(t,r){return e[r]?.get(t)||e.all.get(t)}warn(t){let e=this.pkt;e.warn?e.warn(t,e):console.warn("[u8-mqtt-packet] "+t)}}}const u={connack:[[1,"conn refused: unacceptable protocol version"],[2,"conn refused: identifier rejected"],[3,"conn refused: server unavailable"],[4,"conn refused: bad user name or password"],[5,"conn refused: not authorized"]],suback:[[0,"qos=0"],[1,"qos=1"],[2,"qos=2"]],unsuback:[[17,"no subscription existed"]],puback:[[16,"no matching subscribers"]],all:[[0,""],[128,"unspecified error"],[131,"implementation specific error"],[135,"not authorized"],[143,"topic filter invalid"],[145,"packet identifier in use"],[146,"packet identifier not found"]]},a=o(class extends i{props(){let{buf:t,step:r}=this,[s,i,o]=e(t,0|r.k,0);if(r(s+i-o),0===s)return null;let u={},a=this.of(t.subarray(i,0|r.k));for(;a.has_more();){let t,e=a.u8(),r=n.get(e);if(!r){u._unknown_=e,this.warn?.(`unknown property: ${e}`);break}t=a[r.type](),u[r.name]=r.op?a[r.op](u[r.name],t):t}return u}kv_obj(t=Object.create(null),[e,r]){return t[e]=r,t}u8_vec(t=[],e){return t.push(e),t}},{...u,auth:[[24,"continue authentication"],[25,"re-authenticate"]],disconnect:[[4,"disconnect with will message"]],all:[...u.all,[129,"malformed packet"],[130,"protocol error"],[132,"unsupported protocol version"],[133,"client identifier not valid"],[134,"bad user name or password"],[136,"server unavailable"],[137,"server busy"],[138,"banned"],[139,"server shutting down"],[140,"bad authentication method"],[141,"keep alive timeout"],[142,"session taken over"],[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"]]});class p{static for(t){return(new this).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}}const c={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.for(t,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.for(t,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.for(t,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]=t[11]=(t,r)=>{let n=e.for(t,r);t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.props=n.props());let s=t.answers=[];for(;n.has_more();)s.push(n.reason(t.type));return t}},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.for(t,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,encode_fns:[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=t=>(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.for(s);i.push(r),i.u8(t);let{will:o,username:u,password:a}=s,p=i.flags(s.flags,n,(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&p&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&p&&i.utf8(u),64&p&&i.bin(a),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.for(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.for(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=>3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.for(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.for(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.for(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)}}],mqtt_writer:class extends p{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[r,s]of t){let t=n.get(r);if(!t)throw new Error(`MQTT unknown property "${r}"`);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 l(t,e=0,r){let n=0,s=e,i=t[s++],o=127&i;for(;128&i;)o|=(127&(i=t[s++]))<<(n+=7);return t.length<s?[r,e,e]:[o,s,e]}function _(t){let e=new Uint8Array(0),r=0;return n=>{e=0===e.byteLength?n:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,n);let s=[];for(;e.byteLength>=r;){let[n,i]=l(e,1,NaN),o=n+i;if(!(o<=e.byteLength)){r=o||0;break}let u=e[0],a=0===n?null:e.subarray(i,o);e=e.subarray(o);let p=t.decode_pkt(u,a,t);null!=p&&s.push(p)}return s}}const h=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];const f=t=>"function"==typeof t,d=t=>"string"==typeof t;async function b(t,e,r,n){let s=t[`mqtt_${r.type}`]||t.mqtt_pkt;await(s?.call(t,r,n))}function m(t,e,r,n){e(r.type,r),b(t,0,r,n)}function w(t,e,r){e(r.pkt_id,r)}const y=[t=>{},b,m,b,w,w,w,w,b,w,b,w,m,m,b,m];class k extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class g{async connect(t={}){let e=t.client_id;d(e)||(t.client_id=e=this.client_id||this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._send0("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this.conn.on_conn(t,r)}async disconnect(t={}){let e=await this._send0("disconnect",t);return this.conn.on_dis(t,e)}async auth(t={}){let e=await this._send0("auth",t,"auth");if(e[0].reason)throw new this.MQTTError(e[0]);return this.conn.on_auth(t,e)}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,r){t=v(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=v(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){f(e)&&(e={fn_encode:e});let r=t.msg,n=e?.fn_encode;if(null==r||f(r))return r&&(e={...e,fn_encode:r}),r=>this.pub({...t,[t.arg||"payload"]:r},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:null)}_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=[],s=0,{td:i=1e3,n:o=5}=t?.rotate||{},u=100,a=t=>n[0].set(r,t);return c([]),[c,function(t){return d(t)?r=t:(u=u+1&65535,r=t.pkt_id=u),new Promise(a)}];function p(t,e){for(let r of n){let n=r.get(t);if(n)return r.delete(t),n([e]),!0}return!1}function c(t,r){for(let n of t)y[n.id](e,p,n,r);let u=Date.now();if(u>s)for(s=i+u,n.unshift(new Map);n.length>o;)for(let t of n.pop().values())t([,"expired"])}}(t,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;var e,r,n=t.prototype;for(e of(n.MQTTError=k,t._aliases().split(/\s+/)))[e,r]=e.split(":"),n[e]=n[r]}}function v(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 q=t=>(t.p=new Promise(((e,r)=>{t.a=e,t.e=r})),t);function x(t,e,r){let n={set:i},s=async(...t)=>(await n.p)(...t);return i();function i(){return s!==t[e]&&(q(n).p.then(r,(t=>0)),t[e]=s),n}}function j(t,e,[r,n]){let s,i=x(e,"_send0",(t=>e.conn_emit("on_live",a.has_connected))),o=x(e,"_send",(t=>e.conn_emit("on_ready"))),u=function(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}((()=>e._send0("pingreq"))),a=Object.create({ping:(t=a.keep_alive)=>u(t),on_conn:(r,n)=>(a.has_connected=!0,a.keep_alive=t.keep_alive||n[0].props?.server_keep_alive||r.keep_alive,e.conn_emit("on_conn"),t.use_auth?n:a.on_auth(null,n)),on_auth:(r,n)=>(o.a(i.p),0!=t.keep_alive&&a.ping(),e.conn_emit("on_auth",!r),n),on_dis:(t,e)=>(a.reset(!1),e),reset(t){t&&i.e(t),s.e(t),delete a.is_set,a.ready=p(),e.conn_emit("on_disconnect",!1===t,t)},abort:()=>(o.e(err),a.reset(err)),async setup(t,s,o){if(a.is_set)throw new Error;a.is_set=!0,await t;let u=e.mqtt_ctx.mqtt_stream();{let t={mqtt:e};o((e=>r(u.decode(e),t)),a)}s=await s,i.a((async(t,e,r)=>{let i=void 0===r||n(r);return await s(u.encode_pkt(t,e)),i}))}});return a.ready=p(),a;async function p(){s=q({}),u(0),i.set(),o.set();try{return e._send0=await Promise.race([i.p,s.p]),e._send=await Promise.race([o.p,s.p]),!0}catch(t){return!1}}}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)}},A={sess_stg:globalThis.sessionStorage};class E extends g{constructor(t){t={...A,...t},super(),this.with(t),this.sess_stg=t.sess_stg,this.conn=j(t,this,this._init_dispatch(t))}with(t){for(let[e,r]of Object.entries(t))f(r)&&(this[e]=r);return this}static mqtt_ctx(t,e,r=T){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r=e.pkt_ctx){let n,s=e=>({__proto__:e,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return h[this.b0>>>4]},mqtt_level:t}),i=[],o={};for(n of e.encode_fns)n(o,e.mqtt_writer);for(n of e.decode_fns)n(i,e.mqtt_reader);return{pkt_api:r,pkt_ctx:s(r),encode_pkt:(e,r)=>o[e](t,r),decode_pkt(t,e){if(t.map)return _(this)(t)[0];let r=i[t>>>4]||i[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(t=this.pkt_api){let e={__proto__:this,pkt_ctx:s(t)};return e.decode=_(e),e}}}(t,e,r),n}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)}log_conn(t,e,r){console.info("[[u8-mqtt conn: %s]]",t,e,r)}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}on_live(t,e){if(e)return t.connect()}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}_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)}})}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){return this.conn.setup(t,e,(async(e,r)=>{try{t=await t;for await(let r of t)e(r);r.reset()}catch(t){r.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,r=t.readyState;if(1!==r){if(0!==r)throw new Error("WS readyState");e=new Promise((e=>t.onopen=e))}return this.conn.setup(e,(e=>t.send(e)),((e,r)=>{t.onmessage=t=>e(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket close");e.code=t.code,e.reason=t.reason}r.reset(e)}})),this}}const S="0.6.6-web",$=E.mqtt_ctx(4,c),L=E.mqtt_ctx(5,c),M=t=>new $(t),U=t=>new L(t);export{L as MQTTClient,$ as MQTTClient_v4,L as MQTTClient_v5,U as default,U as mqtt,M as mqtt_v4,U as mqtt_v5,S as version};
Binary file
Binary file
@@ -646,16 +646,20 @@ const mqtt_opts_v4 =
646
646
  encode_fns: mqtt_encode_v4,
647
647
  mqtt_writer: mqtt_writer_v4, };
648
648
 
649
- function parse(str, loose) {
650
- if (str instanceof RegExp) return { keys:false, pattern:str };
651
- var c, o, tmp, ext, keys=[], pattern='', arr = str.split('/');
649
+ /**
650
+ * @param {string|RegExp} input The route pattern
651
+ * @param {boolean} [loose] Allow open-ended matching. Ignored with `RegExp` input.
652
+ */
653
+ function parse(input, loose) {
654
+ if (input instanceof RegExp) return { keys:false, pattern:input };
655
+ var c, o, tmp, ext, keys=[], pattern='', arr = input.split('/');
652
656
  arr[0] || arr.shift();
653
657
 
654
658
  while (tmp = arr.shift()) {
655
659
  c = tmp[0];
656
660
  if (c === '*') {
657
- keys.push('wild');
658
- pattern += '/(.*)';
661
+ keys.push(c);
662
+ pattern += tmp[1] === '?' ? '(?:/(.*))?' : '/(.*)';
659
663
  } else if (c === ':') {
660
664
  o = tmp.indexOf('?', 1);
661
665
  ext = tmp.indexOf('.', 1);
@@ -695,6 +699,7 @@ class AbstractTopicRouter ::
695
699
  async invoke(pkt, ctx) ::
696
700
  add(topic_route, ...args) ::
697
701
  remove(topic_route, priority) ::
702
+ count(topic_route) ::
698
703
  clear(priority) ::
699
704
  find(topic) :: // optional
700
705
  mqtt_topic(topic_route)
@@ -734,6 +739,8 @@ const with_topic_router = mqtt_topic_router =>
734
739
 
735
740
  let fn = args.at(-1)?.call ? args.pop() : null;
736
741
  router.remove(topic_route, true, fn);
742
+ if (0 !== router.count(topic_route) ) {
743
+ return null}
737
744
 
738
745
  let topic = router.mqtt_topic(topic_route);
739
746
  return this.unsubscribe(topic, ...args ) }// topic_prefix
@@ -802,6 +809,17 @@ function mqtt_topic_path_router() {
802
809
  query ={topic: query, tgt: args.pop()}; }
803
810
  return _route_remove(lst, query)}
804
811
 
812
+ , count(topic_route) {
813
+ if (! topic_route) {
814
+ return pri_lsts.reduce((r,l) => r+l.length, 0)}
815
+
816
+ let count = 0;
817
+ for (let lst of pri_lsts) {
818
+ for (let route of lst) {
819
+ if (topic_route === route.topic) {
820
+ count++;} } }
821
+ return count}
822
+
805
823
  , clear(priority) {
806
824
  if (null == priority) {
807
825
  pri_lsts = [[],[]]; }// null clears both lists
@@ -825,38 +843,41 @@ function mqtt_topic_path_router() {
825
843
  await ctx.mqtt.puback(pkt);} } } }
826
844
 
827
845
 
846
+ const _regexparam ={
847
+ get wild() {return this['*']}
848
+ , set wild(v) {return this['*']=wild} };
849
+
828
850
  function * _routes_iter(all_route_lists, topic) {
829
851
  topic = topic.replace(/^[\/]*/, '/'); // ensure '/' prefix for regexparam library
830
- for (let route_list of all_route_lists) {
831
- for (let route of route_list) {
832
- let match = route.pattern.exec(topic);
833
- if (match) {
834
- let params = route.keys
835
- ? route.keys.reduce(
836
- (o, k, i) => (o[k] = match[1+i], o)
837
- , {})
838
- : match.groups ?? match;
839
- yield [route.tgt, params, route];} } } }
852
+ for (let route of all_route_lists.flat()) {
853
+ let match = route?.pattern.exec(topic);
854
+ if (match) {
855
+ let keys = route.keys;
856
+ if (keys) {
857
+ let k, i=0, params={__proto__:_regexparam};
858
+ for (k of keys) {
859
+ params[k] = match[++i];}
860
+ yield [route.tgt, params, route];}
861
+ else {
862
+ yield [route.tgt, match.groups ?? match, route];} } } }
840
863
 
841
864
 
842
865
  function _route_remove(all_route_lists, query) {
843
- let ans = false;
866
+ let n_removed = 0;
844
867
  for (let lst of all_route_lists) {
845
868
  let idx_tip = 0;
846
869
  for (let route of lst) {
847
- // skip matching routes to remove from compacted list
848
- if (route === query) continue
849
870
  if (route.topic === query.topic) {
850
- if (null == query.tgt) continue
851
- if (route.tgt === query.tgt) continue}
871
+ if (null == query.tgt || route.tgt === query.tgt) {
872
+ // skip matching routes to remove from compacted list
873
+ n_removed++;
874
+ continue} }
852
875
 
853
876
  lst[idx_tip++] = route;}
854
877
 
855
878
  // truncate remaining list
856
- if (lst.splice(idx_tip).length)
857
- ans = true;}
858
-
859
- return ans}
879
+ lst.length = idx_tip;}
880
+ return n_removed}
860
881
 
861
882
  function decode_varint(u8, i0=0, invalid) {
862
883
  let shift=0, i=i0, b=u8[i++], n=(b & 0x7f);
@@ -1471,7 +1492,7 @@ class MQTTCore extends MQTTBase {
1471
1492
 
1472
1493
  return this} }
1473
1494
 
1474
- const version = '0.6.4-web';
1495
+ const version = '0.6.6-web';
1475
1496
 
1476
1497
  const MQTTClient_v4 = /* #__PURE__ */
1477
1498
  with_topic_path_router(