u8-mqtt 0.6.1 → 0.6.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.
- package/cjs/basic-v4.cjs +1 -1
- package/cjs/basic-v4.cjs.map +1 -1
- package/cjs/basic-v5.cjs +22 -22
- package/cjs/basic-v5.cjs.map +1 -1
- package/cjs/full-v4.cjs +1 -1
- package/cjs/full-v4.cjs.map +1 -1
- package/cjs/full-v5.cjs +22 -22
- package/cjs/full-v5.cjs.map +1 -1
- package/cjs/index.cjs +22 -22
- package/cjs/index.cjs.map +1 -1
- package/cjs/v4.cjs +1 -1
- package/cjs/v4.cjs.map +1 -1
- package/cjs/v5.cjs +22 -22
- package/cjs/v5.cjs.map +1 -1
- package/esm/basic-v4.js +1 -1
- package/esm/basic-v4.js.map +1 -1
- package/esm/basic-v5.js +22 -22
- package/esm/basic-v5.js.map +1 -1
- package/esm/deno/basic-v4.js +1 -1
- package/esm/deno/basic-v4.js.map +1 -1
- package/esm/deno/basic-v5.js +22 -22
- package/esm/deno/basic-v5.js.map +1 -1
- package/esm/deno/full-v4.js +1 -1
- package/esm/deno/full-v4.js.map +1 -1
- package/esm/deno/full-v5.js +22 -22
- package/esm/deno/full-v5.js.map +1 -1
- package/esm/deno/index.js +22 -22
- package/esm/deno/index.js.map +1 -1
- package/esm/deno/v4.js +1 -1
- package/esm/deno/v4.js.map +1 -1
- package/esm/deno/v5.js +22 -22
- package/esm/deno/v5.js.map +1 -1
- package/esm/full-v4.js +1 -1
- package/esm/full-v4.js.map +1 -1
- package/esm/full-v5.js +22 -22
- package/esm/full-v5.js.map +1 -1
- package/esm/index.js +22 -22
- package/esm/index.js.map +1 -1
- package/esm/node/basic-v4.js +1 -1
- package/esm/node/basic-v4.js.map +1 -1
- package/esm/node/basic-v4.mjs +1 -1
- package/esm/node/basic-v4.mjs.map +1 -1
- package/esm/node/basic-v5.js +22 -22
- package/esm/node/basic-v5.js.map +1 -1
- package/esm/node/basic-v5.mjs +22 -22
- package/esm/node/basic-v5.mjs.map +1 -1
- package/esm/node/full-v4.js +1 -1
- package/esm/node/full-v4.js.map +1 -1
- package/esm/node/full-v4.mjs +1 -1
- package/esm/node/full-v4.mjs.map +1 -1
- package/esm/node/full-v5.js +22 -22
- package/esm/node/full-v5.js.map +1 -1
- package/esm/node/full-v5.mjs +22 -22
- package/esm/node/full-v5.mjs.map +1 -1
- package/esm/node/index.js +22 -22
- package/esm/node/index.js.map +1 -1
- package/esm/node/index.mjs +22 -22
- package/esm/node/index.mjs.map +1 -1
- package/esm/node/v4.js +1 -1
- package/esm/node/v4.js.map +1 -1
- package/esm/node/v4.mjs +1 -1
- package/esm/node/v4.mjs.map +1 -1
- package/esm/node/v5.js +22 -22
- package/esm/node/v5.js.map +1 -1
- package/esm/node/v5.mjs +22 -22
- package/esm/node/v5.mjs.map +1 -1
- package/esm/v4.js +1 -1
- package/esm/v4.js.map +1 -1
- package/esm/v5.js +22 -22
- package/esm/v5.js.map +1 -1
- package/esm/web/basic-v4.js +1 -1
- package/esm/web/basic-v4.js.map +1 -1
- package/esm/web/basic-v4.min.js +1 -1
- package/esm/web/basic-v4.min.js.br +0 -0
- package/esm/web/basic-v4.min.js.gz +0 -0
- package/esm/web/basic-v5.js +22 -22
- package/esm/web/basic-v5.js.map +1 -1
- package/esm/web/basic-v5.min.js +1 -1
- package/esm/web/basic-v5.min.js.br +0 -0
- package/esm/web/basic-v5.min.js.gz +0 -0
- package/esm/web/full-v4.js +1 -1
- package/esm/web/full-v4.js.map +1 -1
- package/esm/web/full-v4.min.js +1 -1
- package/esm/web/full-v4.min.js.br +0 -0
- package/esm/web/full-v4.min.js.gz +0 -0
- package/esm/web/full-v5.js +22 -22
- package/esm/web/full-v5.js.map +1 -1
- package/esm/web/full-v5.min.js +1 -1
- package/esm/web/full-v5.min.js.br +0 -0
- package/esm/web/full-v5.min.js.gz +0 -0
- package/esm/web/index.js +22 -22
- package/esm/web/index.js.map +1 -1
- package/esm/web/index.min.js +1 -1
- package/esm/web/index.min.js.br +0 -0
- package/esm/web/index.min.js.gz +0 -0
- package/esm/web/v4.js +1 -1
- package/esm/web/v4.js.map +1 -1
- package/esm/web/v4.min.js +1 -1
- package/esm/web/v4.min.js.br +0 -0
- package/esm/web/v4.min.js.gz +0 -0
- package/esm/web/v5.js +22 -22
- package/esm/web/v5.js.map +1 -1
- package/esm/web/v5.min.js +1 -1
- package/esm/web/v5.min.js.br +0 -0
- package/esm/web/v5.min.js.gz +0 -0
- package/package.json +2 -2
package/esm/web/full-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,o]of e){let e={id:r,type:n,name:s,...o};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 o{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,o]=e(t,0|r.k);return r(s-o),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 i=class extends o{props(){let{buf:t,step:n}=this,[s,o,i]=e(t,0|n.k);if(n(s+o-i),0===s)return null;let u={},a=this.of(t.subarray(o,0|n.k));for(;a.has_more();){let t,e=a.u8(),n=r.get(e);if(!n)return u.error=`Unknown mqtt_prop enum ${e}`,u;t=a[n.type](),n.op&&(t=a[n.op](u[n.name],t)),u[n.name]=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}};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,o=this.$;for(r of(this.$=!1,o))s+=r.length;n=(e=t(s,e)).length;let i=new Uint8Array(n+s);for(r of(i.set(e,0),o))i.set(r,n),n+=r.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,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 p(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 c(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){t.reasons("pubxxx",[0,"Success"],[146,"Packet Identifier not found"])}function f(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 d(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 h(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 b(t){t.reasons("auth",[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"])}const m={decode_fns:[function(t,e){class r extends Number{get reserved(){return!0&this}get clean_start(){return!0&this}get will_flag(){return!0&this}get will_qos(){return this>>>3&3}get will_retain(){return!0&this}get password(){return!0&this}get username(){return!0&this}}return t[1]=(t,n)=>{let s=e.of(n);if("MQTT"!==s.utf8())throw new Error("Invalid mqtt_connect packet");t._base_.mqtt_level=t.mqtt_level=s.u8();let o=t.flags=s.flags(r);if(t.keep_alive=s.u16(),5<=t.mqtt_level&&(t.props=s.props()),t.client_id=s.utf8(),o.will_flag){let e=t.will={};5<=t.mqtt_level&&(e.props=s.props()),e.topic=s.utf8(),e.payload=s.bin(),e.qos=o.will_qos,e.retain=o.will_retain}return o.username&&(t.username=s.utf8()),o.password&&(t.password=s.bin()),t}},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,o=e.of(r);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,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[5]=t[6]=t[7]=(t,r)=>{let n=e.of(r);return t.pkt_id=n.u16(),t.reason=n.reason("pubxxx",e),5<=t.mqtt_level&&(t.props=n.props()),t}},function(t,e){class r extends Number{get qos(){return 3&this}get retain(){return!0&this}get retain_handling(){return this>>2&3}}return t[8]=(t,n)=>{let s=e.of(n);t.pkt_id=s.u16(),5<=t.mqtt_level&&(t.props=s.props());let o,i,u=t.topics=[];for(;s.has_more();)o=s.utf8(),i=s.flags(r),u.push({topic:o,opts:i});return t}},function(t,e){return t[9]=f(e)},function(t,e){return t[10]=(t,r)=>{let n=e.of(r);t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.props=n.props());let s=t.topics=[];for(;n.has_more();)s.push(n.utf8());return t}},function(t,e){return t[11]=f(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(i,p,c,l,_,d,h,b),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 o=e.of(s);o.push(r),o.u8(t);let{will:i,username:u,password:a}=s,p=o.flags(s.flags,n,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&p&&(5<=t&&o.props(i.props),o.utf8(i.topic),o.bin(i.payload)),128&p&&o.utf8(u),64&p&&o.bin(a),o.as_pkt(16)}},function(t,e){const r=t=>t.session_present?1:0;return t.connack=(t,n)=>{let s=e.of(n);return s.flags(n.flags,r),5<=t?(s.reason(n.reason),s.props(n.props)):s.reason(n.return_code||n.reason),s.as_pkt(32)}},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){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){function r(t){return(r,n)=>{let s=e.of(n);return s.u16(n.pkt_id),5<=r?(s.props(n.props),s.reason(n.reason)):s.reason(n.return_code||n.reason),s.as_pkt(t)}}t.pubrec=r(80),t.pubrel=r(98),t.pubcomp=r(112)},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 o=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(o);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(o):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){function r(t){return(r,n)=>{let s=e.of(n);s.u16(n.pkt_id),5<=r&&s.props(n.props);for(let t of n.answers)s.reason(t);return s.as_pkt(t)}}t.suback=r(144),t.unsuback=r(176)},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)}}],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);if(!t)throw new Error(`Unknown mqtt_prop "${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=>"function"==typeof t,w=t=>"string"==typeof t;const g=(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}})(x),k=t=>t.replace(/[*].*$/,"#").replace(/:\w[^\/]*/g,"+"),v=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function q(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:k,add(e,...r){let n=r.pop(),s=r.pop();if(!y(n)){if(n)throw new TypeError;n=q}let o=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var r,n,s,o,i=[],u="",a=t.split("/");for(a[0]||a.shift();s=a.shift();)"*"===(r=s[0])?(i.push("wild"),u+="/(.*)"):":"===r?(n=s.indexOf("?",1),o=s.indexOf(".",1),i.push(s.substring(1,~n?n:~o?o:s.length)),u+=~n&&!~o?"(?:/([^/]+?))?":"/([^/]+?)",~o&&(u+=(~n?"?":"")+"\\"+s.substring(o))):u+="/"+s;return{keys:i,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(v(e));return o.key=e,o.tgt=n,t[s?0:1].push(o),this},remove:(e,r)=>S([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[o,i]of r(n.topic)){let r=await o(n,i,s);if(e===r&&S(t,o),s.done)break;s.idx++}1===n.qos&&await s.mqtt.puback(n)}}}function S(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 T(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 P(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]=T(e,1),o=r+s;if(e.byteLength<o)return n;let i=e[0],u=0===r?null:e.subarray(s,o);e=e.subarray(o);let a=t.decode_pkt(i,u,t);null!=a&&n.push(a)}}}const j=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];async function N(t,e,r,n){let s=t[`mqtt_${r.type}`]||t.mqtt_pkt;await(s?.call(t,r,n))}function U(t,e,r,n){e(r.type,r),N(t,0,r,n)}function A(t,e,r){e(r.pkt_id,r)}const E=[t=>{},N,U,N,A,A,A,A,N,A,N,A,U,U,N,U];class I extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class M{async connect(t={}){let e=t.client_id;w(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=Q(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=Q(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){y(e)&&(e={fn_encode:e});let r=t.msg,n=e?.fn_encode;if(null==r||y(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:o=1e3,n:i=5}=t?.rotate||{},u=100,a=t=>n[0].set(r,t);return c([]),[c,function(t){return w(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)E[n.id](e,p,n,r);let u=Date.now();if(u>s)for(s=o+u,n.unshift(new Map);n.length>i;)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=I,t._aliases().split(/\s+/)))[e,r]=e.split(":"),n[e]=n[r]}}function Q(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 $=t=>(t.p=new Promise(((e,r)=>{t.a=e,t.e=r})),t);function C(t,e,r){let n={set:o},s=async(...t)=>(await n.p)(...t);return o();function o(){return s!==t[e]&&($(n).p.then(r,(t=>0)),t[e]=s),n}}function L(t,e,[r,n]){let s,o=C(e,"_send0",(t=>e.conn_emit("on_live",a.has_connected))),i=C(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)=>(i.a(o.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&&o.e(t),s.e(t),delete a.is_set,a.ready=p(),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=>r(u.decode(e),t)),a)}s=await s,o.a((async(t,e,r)=>{let o=void 0===r||n(r);return await s(u.encode_pkt(t,e)),o}))}});return a.ready=p(),a;async function p(){s=$({}),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 O={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)}},z={sess_stg:globalThis.sessionStorage};class R extends M{constructor(t){t={...z,...t},super(),this.with(t),this.sess_stg=t.sess_stg,this.conn=L(t,this,this._init_dispatch(t))}with(t){for(let[e,r]of Object.entries(t))y(r)&&(this[e]=r);return this}static mqtt_ctx(t,e,r=O){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=[],o={};for(n of e.encode_fns)n(o,e.mqtt_writer);for(n of e.decode_fns)n(s,e.mqtt_reader);return{pkt_ctx:r,encode_pkt:(e,r)=>o[e](t,r),decode_pkt(t,e){if(t.map)return P(this)(t)[0];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=P(t),t}}}(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 B="0.6.1-web",W=g(R.mqtt_ctx(4,m)),D=g(R.mqtt_ctx(5,m)),F=t=>new W(t),G=t=>new D(t);export{D as MQTTClient,W as MQTTClient_v4,D as MQTTClient_v5,G as default,G as mqtt,F as mqtt_v4,G as mqtt_v5,B 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=()=>function(t,e){for(let[r,n,s,o]of e)o={id:r,type:n,name:s,...o},t.set(r,o).set(s,o);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{static of(t,e,r){let n=new this(t);return n.reason=r?.[e]?.get(t)||e,n}}class o{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,o]=e(t,0|r.k);return r(s-o),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 i=class extends o{props(){let{buf:t,step:r}=this,[s,o,i]=e(t,0|r.k);if(r(s+o-i),0===s)return null;let u={},a=this.of(t.subarray(o,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}warn(t){console.warn("[u8-mqtt-packet] "+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,o=this.$;for(r of(this.$=!1,o))s+=r.length;n=(e=t(s,e)).length;let i=new Uint8Array(n+s);for(r of(i.set(e,0),o))i.set(r,n),n+=r.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,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 p(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 c(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){t.reasons("pubxxx",[0,"Success"],[146,"Packet Identifier not found"])}function f(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 d(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 h(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 b(t){t.reasons("auth",[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"])}const m={decode_fns:[function(t,e){class r extends Number{get reserved(){return!0&this}get clean_start(){return!0&this}get will_flag(){return!0&this}get will_qos(){return this>>>3&3}get will_retain(){return!0&this}get password(){return!0&this}get username(){return!0&this}}return t[1]=(t,n)=>{let s=e.of(n);if("MQTT"!==s.utf8())throw new Error("Invalid mqtt_connect packet");t._base_.mqtt_level=t.mqtt_level=s.u8();let o=t.flags=s.flags(r);if(t.keep_alive=s.u16(),5<=t.mqtt_level&&(t.props=s.props()),t.client_id=s.utf8(),o.will_flag){let e=t.will={};5<=t.mqtt_level&&(e.props=s.props()),e.topic=s.utf8(),e.payload=s.bin(),e.qos=o.will_qos,e.retain=o.will_retain}return o.username&&(t.username=s.utf8()),o.password&&(t.password=s.bin()),t}},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,o=e.of(r);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,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[5]=t[6]=t[7]=(t,r)=>{let n=e.of(r);return t.pkt_id=n.u16(),t.reason=n.reason("pubxxx",e),5<=t.mqtt_level&&(t.props=n.props()),t}},function(t,e){class r extends Number{get qos(){return 3&this}get retain(){return!0&this}get retain_handling(){return this>>2&3}}return t[8]=(t,n)=>{let s=e.of(n);t.pkt_id=s.u16(),5<=t.mqtt_level&&(t.props=s.props());let o,i,u=t.topics=[];for(;s.has_more();)o=s.utf8(),i=s.flags(r),u.push({topic:o,opts:i});return t}},function(t,e){return t[9]=f(e)},function(t,e){return t[10]=(t,r)=>{let n=e.of(r);t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.props=n.props());let s=t.topics=[];for(;n.has_more();)s.push(n.utf8());return t}},function(t,e){return t[11]=f(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(i,p,c,l,_,d,h,b),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 o=e.of(s);o.push(r),o.u8(t);let{will:i,username:u,password:a}=s,p=o.flags(s.flags,n,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&p&&(5<=t&&o.props(i.props),o.utf8(i.topic),o.bin(i.payload)),128&p&&o.utf8(u),64&p&&o.bin(a),o.as_pkt(16)}},function(t,e){const r=t=>t.session_present?1:0;return t.connack=(t,n)=>{let s=e.of(n);return s.flags(n.flags,r),5<=t?(s.reason(n.reason),s.props(n.props)):s.reason(n.return_code||n.reason),s.as_pkt(32)}},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){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){function r(t){return(r,n)=>{let s=e.of(n);return s.u16(n.pkt_id),5<=r?(s.props(n.props),s.reason(n.reason)):s.reason(n.return_code||n.reason),s.as_pkt(t)}}t.pubrec=r(80),t.pubrel=r(98),t.pubcomp=r(112)},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 o=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(o);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(o):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){function r(t){return(r,n)=>{let s=e.of(n);s.u16(n.pkt_id),5<=r&&s.props(n.props);for(let t of n.answers)s.reason(t);return s.as_pkt(t)}}t.suback=r(144),t.unsuback=r(176)},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)}}],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[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)}}};const y=t=>"function"==typeof t,w=t=>"string"==typeof t;const k=(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}})(x),g=t=>t.replace(/[*].*$/,"#").replace(/:\w[^\/]*/g,"+"),v=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function q(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(!y(n)){if(n)throw new TypeError;n=q}let o=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var r,n,s,o,i=[],u="",a=t.split("/");for(a[0]||a.shift();s=a.shift();)"*"===(r=s[0])?(i.push("wild"),u+="/(.*)"):":"===r?(n=s.indexOf("?",1),o=s.indexOf(".",1),i.push(s.substring(1,~n?n:~o?o:s.length)),u+=~n&&!~o?"(?:/([^/]+?))?":"/([^/]+?)",~o&&(u+=(~n?"?":"")+"\\"+s.substring(o))):u+="/"+s;return{keys:i,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(v(e));return o.key=e,o.tgt=n,t[s?0:1].push(o),this},remove:(e,r)=>S([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[o,i]of r(n.topic)){let r=await o(n,i,s);if(e===r&&S(t,o),s.done)break;s.idx++}1===n.qos&&await s.mqtt.puback(n)}}}function S(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 T(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 P(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]=T(e,1),o=r+s;if(e.byteLength<o)return n;let i=e[0],u=0===r?null:e.subarray(s,o);e=e.subarray(o);let a=t.decode_pkt(i,u,t);null!=a&&n.push(a)}}}const j=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];async function N(t,e,r,n){let s=t[`mqtt_${r.type}`]||t.mqtt_pkt;await(s?.call(t,r,n))}function A(t,e,r,n){e(r.type,r),N(t,0,r,n)}function E(t,e,r){e(r.pkt_id,r)}const I=[t=>{},N,A,N,E,E,E,E,N,E,N,E,A,A,N,A];class M extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class U{async connect(t={}){let e=t.client_id;w(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=Q(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=Q(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){y(e)&&(e={fn_encode:e});let r=t.msg,n=e?.fn_encode;if(null==r||y(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:o=1e3,n:i=5}=t?.rotate||{},u=100,a=t=>n[0].set(r,t);return c([]),[c,function(t){return w(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)I[n.id](e,p,n,r);let u=Date.now();if(u>s)for(s=o+u,n.unshift(new Map);n.length>i;)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=M,t._aliases().split(/\s+/)))[e,r]=e.split(":"),n[e]=n[r]}}function Q(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 $=t=>(t.p=new Promise(((e,r)=>{t.a=e,t.e=r})),t);function C(t,e,r){let n={set:o},s=async(...t)=>(await n.p)(...t);return o();function o(){return s!==t[e]&&($(n).p.then(r,(t=>0)),t[e]=s),n}}function L(t,e,[r,n]){let s,o=C(e,"_send0",(t=>e.conn_emit("on_live",a.has_connected))),i=C(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)=>(i.a(o.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&&o.e(t),s.e(t),delete a.is_set,a.ready=p(),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=>r(u.decode(e),t)),a)}s=await s,o.a((async(t,e,r)=>{let o=void 0===r||n(r);return await s(u.encode_pkt(t,e)),o}))}});return a.ready=p(),a;async function p(){s=$({}),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 O={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)}},z={sess_stg:globalThis.sessionStorage};class R extends U{constructor(t){t={...z,...t},super(),this.with(t),this.sess_stg=t.sess_stg,this.conn=L(t,this,this._init_dispatch(t))}with(t){for(let[e,r]of Object.entries(t))y(r)&&(this[e]=r);return this}static mqtt_ctx(t,e,r=O){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=[],o={};for(n of e.encode_fns)n(o,e.mqtt_writer);for(n of e.decode_fns)n(s,e.mqtt_reader);return{pkt_ctx:r,encode_pkt:(e,r)=>o[e](t,r),decode_pkt(t,e){if(t.map)return P(this)(t)[0];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=P(t),t}}}(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 B="0.6.2-web",W=k(R.mqtt_ctx(4,m)),D=k(R.mqtt_ctx(5,m)),F=t=>new W(t),G=t=>new D(t);export{D as MQTTClient,W as MQTTClient_v4,D as MQTTClient_v5,G as default,G as mqtt,F as mqtt_v4,G as mqtt_v5,B as version};
|
|
Binary file
|
|
Binary file
|
package/esm/web/index.js
CHANGED
|
@@ -36,13 +36,17 @@ function decode_varint$1(u8, i=0) {
|
|
|
36
36
|
return [n, i, i0]
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
function add_mqtt_props(mqtt_props, entries) {
|
|
40
|
+
for (let [id, type, name, obj] of entries) {
|
|
41
|
+
obj = {id, type, name, ...obj};
|
|
42
|
+
mqtt_props.set(id, obj).set(name, obj);
|
|
43
|
+
}
|
|
44
|
+
return mqtt_props
|
|
45
|
+
}
|
|
41
46
|
|
|
42
|
-
function init_mqtt_props() {
|
|
43
|
-
let mqtt_props = new Map();
|
|
44
47
|
|
|
45
|
-
|
|
48
|
+
const init_mqtt_props = () =>
|
|
49
|
+
add_mqtt_props(new Map(), [
|
|
46
50
|
[ 0x01, 'u8', 'payload_format_indicator'],
|
|
47
51
|
[ 0x02, 'u32', 'message_expiry_interval'],
|
|
48
52
|
[ 0x03, 'utf8', 'content_type'],
|
|
@@ -70,16 +74,11 @@ function init_mqtt_props() {
|
|
|
70
74
|
[ 0x28, 'u8', 'wildcard_subscription_available'],
|
|
71
75
|
[ 0x29, 'u8', 'subscription_identifiers_available', {op: 'u8_vec'}],
|
|
72
76
|
[ 0x2A, 'u8', 'shared_subscription_available'],
|
|
73
|
-
];
|
|
77
|
+
]);
|
|
74
78
|
|
|
75
|
-
for (let [id, type, name, extra] of entries) {
|
|
76
|
-
let prop_obj = {id, type, name, ...extra};
|
|
77
|
-
mqtt_props.set(prop_obj.id, prop_obj);
|
|
78
|
-
mqtt_props.set(prop_obj.name, prop_obj);
|
|
79
|
-
}
|
|
80
79
|
|
|
81
|
-
|
|
82
|
-
|
|
80
|
+
const mqtt_props = /* #__PURE__ */
|
|
81
|
+
init_mqtt_props();
|
|
83
82
|
|
|
84
83
|
class U8_Reason extends Number {
|
|
85
84
|
static of(v, pkt_kind, by_kind) {
|
|
@@ -157,17 +156,15 @@ let mqtt_reader_v5$1 = class mqtt_reader_v5 extends mqtt_reader_v4 {
|
|
|
157
156
|
let res={}, fork = this.of(buf.subarray(vi, step.k|0));
|
|
158
157
|
while (fork.has_more()) {
|
|
159
158
|
let v, pk = fork.u8(), pt = mqtt_props.get( pk );
|
|
160
|
-
|
|
161
159
|
if (!pt) {
|
|
162
|
-
res.
|
|
163
|
-
|
|
160
|
+
res._unknown_ = pk;
|
|
161
|
+
this.warn(`unknown property: ${pk}`);
|
|
162
|
+
break
|
|
164
163
|
}
|
|
165
164
|
|
|
166
165
|
v = fork[pt.type]();
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
res[pt.name] = v;
|
|
166
|
+
res[pt.name] = !pt.op ? v
|
|
167
|
+
: fork[pt.op](res[pt.name], v); // accumulate operation
|
|
171
168
|
}
|
|
172
169
|
return res
|
|
173
170
|
}
|
|
@@ -181,6 +178,8 @@ let mqtt_reader_v5$1 = class mqtt_reader_v5 extends mqtt_reader_v4 {
|
|
|
181
178
|
return vec
|
|
182
179
|
}
|
|
183
180
|
|
|
181
|
+
warn(msg) { console.warn('[u8-mqtt-packet] '+msg); }
|
|
182
|
+
|
|
184
183
|
/*
|
|
185
184
|
vbuf() {
|
|
186
185
|
let {buf, step} = this
|
|
@@ -302,7 +301,8 @@ class mqtt_writer_v5 extends mqtt_writer_v4 {
|
|
|
302
301
|
for (let [name, value] of props) {
|
|
303
302
|
let pt = mqtt_props.get(name);
|
|
304
303
|
if (!pt)
|
|
305
|
-
throw new Error(`
|
|
304
|
+
throw new Error(`MQTT unknown property "${name}"`)
|
|
305
|
+
|
|
306
306
|
fork[pt.op || 'one'](value, pt);
|
|
307
307
|
}
|
|
308
308
|
this.push(fork.pack());
|
|
@@ -1598,7 +1598,7 @@ class MQTTCore extends MQTTBase {
|
|
|
1598
1598
|
|
|
1599
1599
|
return this} }
|
|
1600
1600
|
|
|
1601
|
-
const version = '0.6.
|
|
1601
|
+
const version = '0.6.2-web';
|
|
1602
1602
|
|
|
1603
1603
|
const MQTTClient_v4 = /* #__PURE__ */
|
|
1604
1604
|
with_topic_path_router(
|