unetjs 4.0.2 → 5.0.1

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.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).unet={})}(this,(function(e){"use strict";const t="undefined"!=typeof window&&void 0!==window.document,s="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,n="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,r="undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"));"undefined"!=typeof Deno&&Deno.core;const i="open",o="opening";var a;class l{constructor(e={}){let t=e.hostname||"localhost",s=e.port||1100;this._keepAlive=e.keepAlive,this._reconnectTime=e.reconnectTime||5e3,this.url=new URL("tcp://localhost"),this.url.hostname=t,this.url.port=s.toString(),this._buf="",this._firstConn=!0,this._firstReConn=!0,this.pendingOnOpen=[],this.connListeners=[],this.debug=!1,this._sockInit(t,s)}_sendConnEvent(e){this.connListeners.forEach((t=>{t&&"[object Function]"==={}.toString.call(t)&&t(e)}))}_sockInit(e,t){if(a)this._sockSetup(e,t);else try{import("net").then((s=>{a=s.createConnection,this._sockSetup(e,t)}))}catch(e){this.debug&&console.log("Unable to import net module")}}_sockSetup(e,t){if(a)try{this.sock=a({host:e,port:t}),this.sock.setEncoding("utf8"),this.sock.on("connect",this._onSockOpen.bind(this)),this.sock.on("error",this._sockReconnect.bind(this)),this.sock.on("close",(()=>{this._sendConnEvent(!1)})),this.sock.send=e=>{this.sock.write(e)}}catch(e){return void(this.debug&&console.log("Connection failed to ",this.sock.host+":"+this.sock.port))}}_sockReconnect(){!this._firstConn&&this._keepAlive&&this.sock.readyState!=o&&this.sock.readyState!=i&&(this._firstReConn&&this._sendConnEvent(!1),this._firstReConn=!1,setTimeout((()=>{this.pendingOnOpen=[],this._sockSetup(this.url.hostname,this.url.port)}),this._reconnectTime))}_onSockOpen(){this._sendConnEvent(!0),this._firstConn=!1,this.sock.on("close",this._sockReconnect.bind(this)),this.sock.on("data",this._processSockData.bind(this)),this.pendingOnOpen.forEach((e=>e())),this.pendingOnOpen.length=0,this._buf=""}_processSockData(e){this._buf+=e;var t=this._buf.split("\n");t.forEach(((e,s)=>{s<t.length-1?e&&this._onSockRx&&this._onSockRx.call(this,e):this._buf=e}))}toString(){let e="";return e+=(this.sock,this.sock.remoteAddress.toString()+":"+this.sock.remotePort.toString()),e}write(e){return this.sock&&this.sock.readyState!=o?this.sock.readyState==i&&(this.sock.send(e+"\n"),!0):(this.pendingOnOpen.push((()=>{this.sock.send(e+"\n")})),!0)}setReadCallback(e){e&&"[object Function]"==={}.toString.call(e)&&(this._onSockRx=e)}addConnectionListener(e){this.connListeners.push(e)}removeConnectionListener(e){let t=this.connListeners.indexOf(e);return t>=0&&(this.connListeners.splice(t,1),!0)}close(){this.sock&&(this.sock.readyState==o?this.pendingOnOpen.push((()=>{this.sock.send('{"alive": false}\n'),this.sock.removeAllListeners("connect"),this.sock.removeAllListeners("error"),this.sock.removeAllListeners("close"),this.sock.destroy()})):this.sock.readyState==i&&(this.sock.send('{"alive": false}\n'),this.sock.removeAllListeners("connect"),this.sock.removeAllListeners("error"),this.sock.removeAllListeners("close"),this.sock.destroy()))}}class c{constructor(e={}){let t=e.hostname||"localhost",s=e.port||80;this.url=new URL("ws://localhost"),this.url.hostname=t,this.url.port=s.toString(),this.url.pathname=e.pathname||"/",this._keepAlive=e.keepAlive,this._reconnectTime=e.reconnectTime||5e3,this.debug=e.debug||!1,this._firstConn=!0,this._firstReConn=!0,this.pendingOnOpen=[],this.connListeners=[],this._websockSetup(this.url)}_sendConnEvent(e){this.connListeners.forEach((t=>{t&&"[object Function]"==={}.toString.call(t)&&t(e)}))}_websockSetup(e){try{this.sock=new WebSocket(e),this.sock.onerror=this._websockReconnect.bind(this),this.sock.onopen=this._onWebsockOpen.bind(this),this.sock.onclose=()=>{this._sendConnEvent(!1)}}catch(t){return void(this.debug&&console.log("Connection failed to ",e))}}_websockReconnect(){!this._firstConn&&this._keepAlive&&this.sock.readyState!=this.sock.CONNECTING&&this.sock.readyState!=this.sock.OPEN&&(this._firstReConn&&this._sendConnEvent(!1),this._firstReConn=!1,this.debug&&console.log("Reconnecting to ",this.sock.url),setTimeout((()=>{this.pendingOnOpen=[],this._websockSetup(this.sock.url)}),this._reconnectTime))}_onWebsockOpen(){this.debug&&console.log("Connected to ",this.sock.url),this._sendConnEvent(!0),this.sock.onclose=this._websockReconnect.bind(this),this.sock.onmessage=e=>{this._onWebsockRx&&this._onWebsockRx.call(this,e.data)},this._firstConn=!1,this._firstReConn=!0,this.pendingOnOpen.forEach((e=>e())),this.pendingOnOpen.length=0}toString(){let e="";return e+=(this.sock,this.sock.url.toString()),e}write(e){return this.sock&&this.sock.readyState!=this.sock.CONNECTING?this.sock.readyState==this.sock.OPEN&&(this.sock.send(e+"\n"),!0):(this.pendingOnOpen.push((()=>{this.sock.send(e+"\n")})),!0)}setReadCallback(e){e&&"[object Function]"==={}.toString.call(e)&&(this._onWebsockRx=e)}addConnectionListener(e){this.connListeners.push(e)}removeConnectionListener(e){let t=this.connListeners.indexOf(e);return t>=0&&(this.connListeners.splice(t,1),!0)}close(){this.sock&&(this.sock.readyState==this.sock.CONNECTING?this.pendingOnOpen.push((()=>{this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.close()})):this.sock.readyState==this.sock.OPEN&&(this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.close()))}}const h={REQUEST:"REQUEST",AGREE:"AGREE",REFUSE:"REFUSE",FAILURE:"FAILURE",INFORM:"INFORM",CONFIRM:"CONFIRM",DISCONFIRM:"DISCONFIRM",QUERY_IF:"QUERY_IF",NOT_UNDERSTOOD:"NOT_UNDERSTOOD",CFP:"CFP",PROPOSE:"PROPOSE",CANCEL:"CANCEL"};class u{constructor(e,t=!1,s){this.name=e,this.topic=t,this.owner=s}getName(){return this.name}isTopic(){return this.topic}send(e){if(e.recipient=this.toJSON(),!this.owner)throw new Error("Unowned AgentID cannot send messages");this.owner.send(e)}async request(e,t=1e3){if(e.recipient=this.toJSON(),this.owner)return this.owner.request(e,t);throw new Error("Unowned AgentID cannot send messages")}toString(){return this.toJSON()+(this.owner&&this.owner.connector?` on ${this.owner.connector.url}`:"")}toJSON(){return(this.topic?"#":"")+this.name}async set(e,t,s=-1,n=5e3){if(!e)return null;let r=new y;r.recipient=this.name,Array.isArray(e)?(r.param=e.shift(),r.value=t.shift(),r.requests=e.map(((e,s)=>({param:e,value:t[s]}))),e.unshift(r.param)):(r.param=e,r.value=t),r.index=Number.isInteger(s)?s:-1;const i=await this.owner.request(r,n);var o=Array.isArray(e)?new Array(e.length).fill(null):null;if(!i||i.perf!=h.INFORM||!i.param){if(this.owner._returnNullOnFailedResponse)return o;throw new Error(`Unable to set ${this.name}.${e} to ${t}`)}if(Array.isArray(e)){i.values||(i.values={}),i.param&&(i.values[i.param]=i.value);const t=Object.keys(i.values);return e.map((e=>{e.includes(".")&&(e=e.split(".").pop());let s=t.find((t=>(t.includes(".")?t.split(".").pop():t)==e));return s?i.values[s]:void 0}))}return i.value}async get(e,t=-1,s=5e3){let n=new y;n.recipient=this.name,e&&(Array.isArray(e)?(n.param=e.shift(),n.requests=e.map((e=>({param:e}))),e.unshift(n.param)):n.param=e),n.index=Number.isInteger(t)?t:-1;const r=await this.owner.request(n,s);var i=Array.isArray(e)?new Array(e.length).fill(null):null;if(!r||r.perf!=h.INFORM||!r.param){if(this.owner._returnNullOnFailedResponse)return i;throw new Error(`Unable to get ${this.name}.${e}`)}if(e){if(Array.isArray(e)){r.values||(r.values={}),r.param&&(r.values[r.param]=r.value);const t=Object.keys(r.values);return e.map((e=>{e.includes(".")&&(e=e.split(".").pop());let s=t.find((t=>(t.includes(".")?t.split(".").pop():t)==e));return s?r.values[s]:void 0}))}return r.value}return r.values||(r.values={}),r.param&&(r.values[r.param]=r.value),r.values}}class g{constructor(e={msgID:null,sender:null},t=h.INFORM){this.__clazz__="org.arl.fjage.Message",this.msgID=R(8),this.sender=null,this.recipient=e.sender,this.perf=t,this.inReplyTo=e.msgID||null}toString(){let e="",t="";if(!this.__clazz__)return"";let s=this.__clazz__;s=s.replace(/^.*\./,"");let n=this.perf;for(var r in this)r.startsWith("__")||"sender"!=r&&"recipient"!=r&&"msgID"!=r&&"perf"!=r&&"inReplyTo"!=r&&("object"!=typeof this[r]?e+=" "+r+":"+this[r]:t=" ...");return e+=t,s+":"+n+"["+e.replace(/^ /,"")+"]"}_serialize(){return'{ "clazz": "'+(this.__clazz__||"org.arl.fjage.Message")+'", "data": '+JSON.stringify(this,((e,t)=>{if(!e.startsWith("__"))return t}))+" }"}_inflate(e){for(var t in e)this[t]=e[t]}static _deserialize(e){let t=null;if("string"==typeof e)try{t=JSON.parse(e)}catch(e){return null}else t=e;let s=t.clazz,n=s.replace(/^.*\./,""),r=f[n]?new f[n]:new g;return r.__clazz__=s,r._inflate(t.data),r}}class d{constructor(e={}){for(var t in _)null!=e[t]&&""!==e[t]||(e[t]=_[t]);var s=v;s.hostname=e.hostname,s.port=e.port,s.pathname=e.pathname;let n=this._getGWCache(s);if(n)return n;this._timeout=e.timeout,this._keepAlive=e.keepAlive,this._queueSize=e.queueSize,this._returnNullOnFailedResponse=e.returnNullOnFailedResponse,this._cancelPendingOnDisconnect=e.cancelPendingOnDisconnect,this.pending={},this.subscriptions={},this.listeners={},this.eventListeners={},this.queue=[],this.connected=!1,this.debug=!1,this.aid=new u("gateway-"+R(4)),this.connector=this._createConnector(s),this._addGWCache(this)}_sendEvent(e,t){Array.isArray(this.eventListeners[e])&&this.eventListeners[e].forEach((e=>{if(e&&"[object Function]"==={}.toString.call(e))try{e(t)}catch(e){console.warn("Error in event listener : "+e)}}))}_sendReceivers(e){for(var t in this.listeners)try{if(this.listeners[t]&&this.listeners[t](e))return!0}catch(e){console.warn("Error in listener : "+e)}return!1}_onMsgRx(e){var t;this.debug&&console.log("< "+e),this._sendEvent("rx",e);try{t=JSON.parse(e,m)}catch(e){return}if(this._sendEvent("rxp",t),"id"in t&&t.id in this.pending)this.pending[t.id](t),delete this.pending[t.id];else if("send"==t.action){let e=g._deserialize(t.message);if(!e)return;this._sendEvent("rxmsg",e),(e.recipient==this.aid.toJSON()||this.subscriptions[e.recipient])&&(this._sendEvent("message",e),this._sendReceivers(e)||(this.queue.length>=this._queueSize&&this.queue.shift(),this.queue.push(e)))}else{let e={id:t.id,inResponseTo:t.action};switch(t.action){case"agents":e.agentIDs=[this.aid.getName()];break;case"containsAgent":e.answer=t.agentID==this.aid.getName();break;case"services":e.services=[];break;case"agentForService":e.agentID="";break;case"agentsForService":e.agentIDs=[];break;default:e=void 0}e&&this._msgTx(e)}}_msgTx(e){return"string"==typeof e||e instanceof String||(e=JSON.stringify(e)),this.debug&&console.log("> "+e),this._sendEvent("tx",e),this.connector.write(e)}_msgTxRx(e){return e.id=R(8),new Promise((t=>{let s=setTimeout((()=>{delete this.pending[e.id],this.debug&&console.log("Receive Timeout : "+JSON.stringify(e)),t()}),8*this._timeout);this.pending[e.id]=e=>{clearTimeout(s),t(e)},this._msgTx.call(this,e)||(clearTimeout(s),delete this.pending[e.id],this.debug&&console.log("Transmit Timeout : "+JSON.stringify(e)),t())}))}_createConnector(e){let t;if(e.protocol.startsWith("ws"))t=new c({hostname:e.hostname,port:parseInt(e.port),pathname:e.pathname,keepAlive:this._keepAlive,debug:this.debug});else{if(!e.protocol.startsWith("tcp"))return null;t=new l({hostname:e.hostname,port:parseInt(e.port),keepAlive:this._keepAlive,debug:this.debug})}return t.setReadCallback(this._onMsgRx.bind(this)),t.addConnectionListener((e=>{this.connected=!!e,1==e?(this.flush(),this.connector.write('{"alive": true}'),this._update_watch()):this._cancelPendingOnDisconnect&&(this._sendReceivers(null),this.flush()),this._sendEvent("conn",e)})),t}_isConstructor(e){try{return new new Proxy(e,{construct:()=>({})}),!0}catch(e){return!1}}_matchMessage(e,t){if("string"==typeof e||e instanceof String)return"inReplyTo"in t&&t.inReplyTo==e;if(Object.prototype.hasOwnProperty.call(e,"msgID"))return"inReplyTo"in t&&t.inReplyTo==e.msgID;if("Message"==e.__proto__.name||"Message"==e.__proto__.__proto__.name)return e.__clazz__==t.__clazz__;if("function"!=typeof e||this._isConstructor(e))return t instanceof e;try{return e(t)}catch(e){return console.warn("Error in filter : "+e),!1}}_getMessageFromQueue(e){if(!this.queue.length)return;if(!e)return this.queue.shift();let t=this.queue.find((t=>this._matchMessage(e,t)));return t&&this.queue.splice(this.queue.indexOf(t),1),t}_getGWCache(e){if(!S.fjage||!S.fjage.gateways)return null;var t=S.fjage.gateways.filter((t=>t.connector.url.toString()==e.toString()));return t.length?t[0]:null}_addGWCache(e){S.fjage&&S.fjage.gateways&&S.fjage.gateways.push(e)}_removeGWCache(e){if(S.fjage&&S.fjage.gateways){var t=S.fjage.gateways.indexOf(e);null!=t&&S.fjage.gateways.splice(t,1)}}_update_watch(){let e=Object.keys(this.subscriptions);e.push(this.aid.getName());let t={action:"wantsMessagesFor",agentIDs:e};this._msgTx(t)}addEventListener(e,t){Array.isArray(this.eventListeners[e])||(this.eventListeners[e]=[]),this.eventListeners[e].push(t)}removeEventListener(e,t){if(!this.eventListeners[e])return;let s=this.eventListeners[e].indexOf(t);s>=0&&this.eventListeners[e].splice(s,1)}addMessageListener(e){this.addEventListener("message",e)}removeMessageListener(e){this.removeEventListener("message",e)}addConnListener(e){this.addEventListener("conn",e)}removeConnListener(e){this.removeEventListener("conn",e)}getAgentID(){return this.aid}agent(e){return new u(e,!1,this)}topic(e,t){return"string"==typeof e||e instanceof String?new u(e,!0,this):e instanceof u?e.isTopic()?e:new u(e.getName()+(t?"__"+t:"")+"__ntf",!0,this):void 0}subscribe(e){return e.isTopic()||(e=new u(e.getName()+"__ntf",!0,this)),this.subscriptions[e.toJSON()]=!0,this._update_watch(),!0}unsubscribe(e){e.isTopic()||(e=new u(e.getName()+"__ntf",!0,this)),delete this.subscriptions[e.toJSON()],this._update_watch()}async agents(){let e=await this._msgTxRx({action:"agents"});if(!e||!Array.isArray(e.agentIDs))throw new Error("Unable to get agents");return e.agentIDs.map((e=>new u(e,!1,this)))}async containsAgent(e){let t={action:"containsAgent",agentID:e instanceof u?e.getName():e},s=await this._msgTxRx(t);if(!s)throw new Error("Unable to check if agent exists");return!!s.answer}async agentForService(e){let t={action:"agentForService",service:e},s=await this._msgTxRx(t);if(!s){if(this._returnNullOnFailedResponse)return null;throw new Error("Unable to get agent for service")}return s.agentID?new u(s.agentID,!1,this):null}async agentsForService(e){let t={action:"agentsForService",service:e},s=await this._msgTxRx(t),n=[];if(!s){if(this._returnNullOnFailedResponse)return n;throw new Error("Unable to get agents for service")}if(!Array.isArray(s.agentIDs))return n;for(var r=0;r<s.agentIDs.length;r++)n.push(new u(s.agentIDs[r],!1,this));return n}send(e){e.sender=this.aid.toJSON(),""==e.perf&&(e.__clazz__.endsWith("Req")?e.perf=h.REQUEST:e.perf=h.INFORM),this._sendEvent("txmsg",e);let t=JSON.stringify({action:"send",relay:!0,message:"###MSG###"});return t=t.replace('"###MSG###"',e._serialize()),!!this._msgTx(t)}flush(){this.queue.length=0}async request(e,t=1e3){return this.send(e),this.receive(e,t)}async receive(e,t=0){return new Promise((s=>{let n=this._getMessageFromQueue.call(this,e);if(n)return void s(n);if(0==t)return this.debug&&console.log("Receive Timeout : "+e),void s();let r,i=R(8);t>0&&(r=setTimeout((()=>{this.listeners[i]&&delete this.listeners[i],this.debug&&console.log("Receive Timeout : "+e),s()}),t)),this.listeners[i]=t=>!(t&&!this._matchMessage(e,t))&&(r&&clearTimeout(r),this.listeners[i]&&delete this.listeners[i],s(t),!0)}))}close(){this.connector.close(),this._removeGWCache(this)}}const p={SHELL:"org.arl.fjage.shell.Services.SHELL"};function f(e,t=g){let s=e.replace(/^.*\./,"");if(f[s])return f[s];let n=class extends t{constructor(t){if(super(),this.__clazz__=e,t){const e=Object.keys(t);for(let s of e)this[s]=t[s]}e.endsWith("Req")&&(this.perf=h.REQUEST)}};return n.__clazz__=e,f[s]=n,n}function R(e){function t(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}let s=t();for(var n=0;n<e-1;n++)s+=t();return s}function m(e,t){if(null===t)return null;if("object"==typeof t&&"clazz"in t){let e=t.clazz;if(e.startsWith("[")&&2==e.length&&"data"in t){let e=function(e,t,s=!0){let n=S.atob(e),r=n.length,i=new Uint8Array(r);for(var o=0;o<r;o++)i[o]=n.charCodeAt(o);let a=[],l=new DataView(i.buffer);switch(t){case"[B":for(o=0;o<r;o++)a.push(l.getUint8(o));break;case"[S":for(o=0;o<r;o+=2)a.push(l.getInt16(o,s));break;case"[I":for(o=0;o<r;o+=4)a.push(l.getInt32(o,s));break;case"[J":for(o=0;o<r;o+=8)a.push(l.getBigInt64(o,s));break;case"[F":for(o=0;o<r;o+=4)a.push(l.getFloat32(o,s));break;case"[D":for(o=0;o<r;o+=8)a.push(l.getFloat64(o,s));break;default:return}return a}(t.data,t.clazz);e&&(t=e)}}return t}const _={};let v,S={};t||n?(S=window,Object.assign(_,{hostname:S.location.hostname,port:S.location.port,pathname:"/ws/",timeout:1e3,keepAlive:!0,queueSize:128,returnNullOnFailedResponse:!0,cancelPendingOnDisconnect:!1}),v=new URL("ws://localhost"),void 0===S.fjage&&(S.fjage={}),void 0===S.fjage.gateways&&(S.fjage.gateways=[])):(r||s)&&(S=global,Object.assign(_,{hostname:"localhost",port:"1100",pathname:"",timeout:1e3,keepAlive:!0,queueSize:128,returnNullOnFailedResponse:!0,cancelPendingOnDisconnect:!1}),v=new URL("tcp://localhost"),S.atob=e=>Buffer.from(e,"base64").toString("binary"));const y=f("org.arl.fjage.param.ParameterReq"),w=f("org.arl.unet.DatagramReq"),N=f("org.arl.unet.DatagramNtf"),A=f("org.arl.unet.phy.TxFrameReq",w),k=f("org.arl.unet.phy.RxFrameNtf",N),b=f("org.arl.unet.bb.BasebandSignal");Object.assign(p,{NODE_INFO:"org.arl.unet.Services.NODE_INFO",ADDRESS_RESOLUTION:"org.arl.unet.Services.ADDRESS_RESOLUTION",DATAGRAM:"org.arl.unet.Services.DATAGRAM",PHYSICAL:"org.arl.unet.Services.PHYSICAL",RANGING:"org.arl.unet.Services.RANGING",BASEBAND:"org.arl.unet.Services.BASEBAND",LINK:"org.arl.unet.Services.LINK",MAC:"org.arl.unet.Services.MAC",ROUTING:"org.arl.unet.Services.ROUTING",ROUTE_MAINTENANCE:"org.arl.unet.Services.ROUTE_MAINTENANCE",TRANSPORT:"org.arl.unet.Services.TRANSPORT",REMOTE:"org.arl.unet.Services.REMOTE",STATE_MANAGER:"org.arl.unet.Services.STATE_MANAGER",DEVICE_INFO:"org.arl.unet.Services.DEVICE_INFO",DOA:"org.arl.unet.Services.DOA",SCHEDULER:"org.arl.unet.Services.SCHEDULER"});let O={DATA:0,RANGING:1,LINK:2,REMOTE:3,MAC:4,ROUTING:5,TRANSPORT:6,ROUTE_MAINTENANCE:7,LINK2:8,USER:32,MAX:63},T={TestReportNtf:f("org.arl.unet.TestReportNtf"),AbnormalTerminationNtf:f("org.arl.unet.AbnormalTerminationNtf"),CapabilityListRsp:f("org.arl.unet.CapabilityListRsp"),CapabilityReq:f("org.arl.unet.CapabilityReq"),ClearReq:f("org.arl.unet.ClearReq"),DatagramCancelReq:f("org.arl.unet.DatagramCancelReq"),DatagramDeliveryNtf:f("org.arl.unet.DatagramDeliveryNtf"),DatagramFailureNtf:f("org.arl.unet.DatagramFailureNtf"),DatagramNtf:f("org.arl.unet.DatagramNtf"),DatagramProgressNtf:f("org.arl.unet.DatagramProgressNtf"),DatagramReq:f("org.arl.unet.DatagramReq"),ParamChangeNtf:f("org.arl.unet.ParamChangeNtf"),RefuseRsp:f("org.arl.unet.RefuseRsp"),FailureNtf:f("org.arl.unet.FailureNtf"),DatagramTraceReq:f("org.arl.unet.net.DatagramTraceReq"),RouteDiscoveryReq:f("org.arl.unet.net.RouteDiscoveryReq"),RouteTraceReq:f("org.arl.unet.net.RouteTraceReq"),RouteDiscoveryNtf:f("org.arl.unet.net.RouteDiscoveryNtf"),RouteTraceNtf:f("org.arl.unet.net.RouteTraceNtf"),FecDecodeReq:f("org.arl.unet.phy.FecDecodeReq"),RxSWiG1FrameNtf:f("org.arl.unet.phy.RxSWiG1FrameNtf",k),TxSWiG1FrameReq:f("org.arl.unet.phy.TxSWiG1FrameReq",A),RxJanusFrameNtf:f("org.arl.unet.phy.RxJanusFrameNtf",k),TxJanusFrameReq:f("org.arl.unet.phy.TxJanusFrameReq",A),BadFrameNtf:f("org.arl.unet.phy.BadFrameNtf"),BadRangeNtf:f("org.arl.unet.phy.BadRangeNtf"),ClearSyncReq:f("org.arl.unet.phy.ClearSyncReq"),CollisionNtf:f("org.arl.unet.phy.CollisionNtf"),RxFrameNtf:f("org.arl.unet.phy.RxFrameNtf",N),RxFrameStartNtf:f("org.arl.unet.phy.RxFrameStartNtf"),SyncInfoReq:f("org.arl.unet.phy.SyncInfoReq"),SyncInfoRsp:f("org.arl.unet.phy.SyncInfoRsp"),TxFrameNtf:f("org.arl.unet.phy.TxFrameNtf"),TxFrameReq:f("org.arl.unet.phy.TxFrameReq",w),TxFrameStartNtf:f("org.arl.unet.phy.TxFrameStartNtf"),TxRawFrameReq:f("org.arl.unet.phy.TxRawFrameReq"),AddressAllocReq:f("org.arl.unet.addr.AddressAllocReq"),AddressAllocRsp:f("org.arl.unet.addr.AddressAllocRsp"),AddressResolutionReq:f("org.arl.unet.addr.AddressResolutionReq"),AddressResolutionRsp:f("org.arl.unet.addr.AddressResolutionRsp"),BasebandSignal:f("org.arl.unet.bb.BasebandSignal"),RecordBasebandSignalReq:f("org.arl.unet.bb.RecordBasebandSignalReq"),RxBasebandSignalNtf:f("org.arl.unet.bb.RxBasebandSignalNtf",b),TxBasebandSignalReq:f("org.arl.unet.bb.TxBasebandSignalReq",b),LinkStatusNtf:f("org.arl.unet.link.LinkStatusNtf"),RangeNtf:f("org.arl.unet.localization.RangeNtf"),RangeReq:f("org.arl.unet.localization.RangeReq"),BeaconReq:f("org.arl.unet.localization.BeaconReq"),RespondReq:f("org.arl.unet.localization.RespondReq"),InterrogationNtf:f("org.arl.unet.localization.InterrogationNtf"),ReservationAcceptReq:f("org.arl.unet.mac.ReservationAcceptReq"),ReservationCancelReq:f("org.arl.unet.mac.ReservationCancelReq"),ReservationReq:f("org.arl.unet.mac.ReservationReq"),ReservationRsp:f("org.arl.unet.mac.ReservationRsp"),ReservationStatusNtf:f("org.arl.unet.mac.ReservationStatusNtf"),RxAckNtf:f("org.arl.unet.mac.RxAckNtf"),TxAckReq:f("org.arl.unet.mac.TxAckReq"),RemoteExecReq:f("org.arl.unet.remote.RemoteExecReq"),RemoteFailureNtf:f("org.arl.unet.remote.RemoteFailureNtf"),RemoteFileGetReq:f("org.arl.unet.remote.RemoteFileGetReq"),RemoteFileNtf:f("org.arl.unet.remote.RemoteFileNtf"),RemoteFilePutReq:f("org.arl.unet.remote.RemoteFilePutReq"),RemoteSuccessNtf:f("org.arl.unet.remote.RemoteSuccessNtf"),RemoteTextNtf:f("org.arl.unet.remote.RemoteTextNtf"),RemoteTextReq:f("org.arl.unet.remote.RemoteTextReq"),AddScheduledSleepReq:f("org.arl.unet.scheduler.AddScheduledSleepReq"),GetSleepScheduleReq:f("org.arl.unet.scheduler.GetSleepScheduleReq"),RemoveScheduledSleepReq:f("org.arl.unet.scheduler.RemoveScheduledSleepReq"),SleepScheduleRsp:f("org.arl.unet.scheduler.SleepScheduleRsp"),WakeFromSleepNtf:f("org.arl.unet.scheduler.WakeFromSleepNtf"),ClearStateReq:f("org.arl.unet.state.ClearStateReq"),SaveStateReq:f("org.arl.unet.state.SaveStateReq")};function E(e){let t=e*Math.PI/180,s=111132.92-559.82*Math.cos(2*t)+1.175*Math.cos(4*t)-.0023*Math.cos(6*t);return[111412.84*Math.cos(t)-93.5*Math.cos(3*t)+.118*Math.cos(5*t),s]}class C extends u{constructor(e,t,s,n=!0){e instanceof u?super(e.getName(),e.topic,e.owner):super(e,t,s),this.greedy=n,this.cache={},this.specialParams=["name","version"]}async set(e,t,s=-1,n=5e3){let r=await super.set(e,t,s,n);return this._updateCache(e,r,s),r}async get(e,t=-1,s=5e3,n=5e3){if(this._isCached(e,t,n))return this._getCache(e,t);if(!this.greedy||Array.isArray(e)&&0!=[...new Set([...e,...this.specialParams])].length||this.specialParams.includes(e)){let n=await super.get(e,t,s);return this._updateCache(e,n,t),n}{let n=await super.get(null,t,s);if(this._updateCache(null,n,t),!n)return Array.isArray(e)?new Array(e.length).fill(null):null;if(e){if(Array.isArray(e))return e.map((e=>{let t=Object.keys(n).find((t=>this._toNamed(t)===e));return t?n[t]:null}));{let t=Object.keys(n).find((t=>this._toNamed(t)===e));return t?n[t]:null}}return n}}_updateCache(e,t,s){if(null==t||Array.isArray(t)&&t.every((e=>null==e)))return;null==e?(e=Object.keys(t),t=Object.values(t)):Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]),e=e.map(this._toNamed),void 0===this.cache[s.toString()]&&(this.cache[s.toString()]={});let n=this.cache[s.toString()];for(let s=0;s<e.length;s++)void 0===n[e[s]]&&(n[e[s]]={}),n[e[s]].value=t[s],n[e[s]].ctime=Date.now()}_isCached(e,t,s){if(s<=0)return!1;if(null==e)return!1;let n=this.cache[t.toString()];if(!n)return!1;Array.isArray(e)||(e=[e]);return e.every((e=>(e=this._toNamed(e))in n&&Date.now()-n[e].ctime<=s))}_getCache(e,t){let s=this.cache[t.toString()];return s?Array.isArray(e)?e.map((e=>e in s?s[e].value:null)):e in s?s[e].value:null:null}_toNamed(e){const t=e.lastIndexOf(".");return t<0?e:e.slice(t+1)}}const F=T.AddressResolutionReq,q=T.DatagramReq,D=T.DatagramNtf,I=T.RxFrameNtf;e.AgentID=u,e.CachingAgentID=C,e.CachingGateway=class extends d{agent(e,t=!0,s=!0){const n=super.agent(e);return t?new C(n,null,null,s):n}topic(e,t,s=!0,n=!0){const r=super.topic(e,t);return s?new C(r,null,null,n):r}async agentForService(e,t=!0,s=!0){const n=await super.agentForService(e);return n&&t?new C(n,null,null,s):n}async agentsForService(e,t=!0,s=!0){const n=await super.agentsForService(e);return t?n.map((e=>new C(e,null,null,s))):n}},e.Gateway=d,e.Message=g,e.MessageClass=f,e.Performative=h,e.Protocol=O,e.Services=p,e.UnetMessages=T,e.UnetSocket=class{constructor(e,t,s=""){return(async()=>{this.gw=new d({hostname:e,port:t,path:s}),this.localProtocol=-1,this.remoteAddress=-1,this.remoteProtocol=O.DATA,this.timeout=0,this.provider=null;return(await this.gw.agentsForService(p.DATAGRAM)).forEach((e=>{this.gw.subscribe(this.gw.topic(e))})),this})()}close(){this.gw.close(),this.gw=null}isClosed(){return null==this.gw}bind(e){return(e==O.DATA||e>=O.USER&&e<=O.MAX)&&(this.localProtocol=e,!0)}unbind(){this.localProtocol=-1}isBound(){return this.localProtocol>=0}connect(e,t){return e>=0&&(t==O.DATA||t>=O.USER&&t<=O.MAX)&&(this.remoteAddress=e,this.remoteProtocol=t,!0)}disconnect(){this.remoteAddress=-1,this.remoteProtocol=0}isConnected(){return this.remoteAddress>=0}async getLocalAddress(){if(null==this.gw)return-1;const e=await this.gw.agentForService(p.NODE_INFO);if(null==e)return-1;const t=await e.get("address");return null!=t?t:-1}getLocalProtocol(){return this.localProtocol}getRemoteAddress(){return this.remoteAddress}getRemoteProtocol(){return this.remoteProtocol}setTimeout(e){e<0&&(e=0),this.timeout=e}getTimeout(){return this.timeout}async send(e,t=this.remoteAddress,s=this.remoteProtocol){if(t<0||null==this.gw)return!1;var n;if(Array.isArray(e))(n=new q).data=e,n.to=t,n.protocol=s;else{if(!(e instanceof q))return!1;n=e}let r=n.protocol;if(r!=O.DATA&&(r<O.USER||r>O.MAX))return!1;if(null==n.recipient){if(null==this.provider&&(this.provider=await this.gw.agentForService(p.TRANSPORT)),null==this.provider&&(this.provider=await this.gw.agentForService(p.ROUTING)),null==this.provider&&(this.provider=await this.gw.agentForService(p.LINK)),null==this.provider&&(this.provider=await this.gw.agentForService(p.PHYSICAL)),null==this.provider&&(this.provider=await this.gw.agentForService(p.DATAGRAM)),null==this.provider)return!1;n.recipient=this.provider}const i=await this.gw.request(n,1e3);return null!=i&&i.perf==h.AGREE}async receive(){return null==this.gw?null:await this.gw.receive((e=>{if(e.__clazz__!=D.__clazz__&&e.__clazz__!=I.__clazz__)return!1;let t=e.protocol;return(t==O.DATA||t>=O.USER)&&(this.localProtocol<0||this.localProtocol==t)}),this.timeout)}getGateway(){return this.gw}async agentForService(e,t=!0){return null==this.gw?null:await this.gw.agentForService(e,t)}async agentsForService(e,t=!0){return null==this.gw?null:await this.gw.agentsForService(e,t``)}agent(e,t=!0){return null==this.gw?null:this.gw.agent(e,t)}async host(e){const t=await this.agentForService(p.ADDRESS_RESOLUTION);if(null==t)return null;const s=new F(e);s.name=e,s.recipient=t;const n=await this.gw.request(s,1e3);return null!=n&&Object.prototype.hasOwnProperty.call(n,"address")?n.address:null}},e.toGps=function(e,t,s){let n=[],[r,i]=E(e[0]);return n[1]=t/r+e[1],n[0]=s/i+e[0],n},e.toLocal=function(e,t,s){let n=[],[r,i]=E(e[0]);return n[0]=(s-e[1])*r,n[1]=(t-e[0])*i,n}}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).unet={})}(this,function(e){"use strict";const t={REQUEST:"REQUEST",AGREE:"AGREE",REFUSE:"REFUSE",FAILURE:"FAILURE",INFORM:"INFORM",CONFIRM:"CONFIRM",DISCONFIRM:"DISCONFIRM",QUERY_IF:"QUERY_IF",NOT_UNDERSTOOD:"NOT_UNDERSTOOD",CFP:"CFP",PROPOSE:"PROPOSE",CANCEL:"CANCEL"};class s{constructor(e){if(16!==e.length)throw new Error("UUID7 must be constructed with a 16-byte array.");this.bytes=e}static generate(){const e=new Uint8Array(16),t=crypto.getRandomValues(new Uint8Array(10)),n=Date.now(),r=Math.floor(n/65536),i=n%65536;return e[0]=r>>24&255,e[1]=r>>16&255,e[2]=r>>8&255,e[3]=255&r,e[4]=i>>8&255,e[5]=255&i,e.set(t,6),e[6]=15&e[6]|112,e[8]=63&e[8]|128,new s(e)}getTimestamp(){let e=0;return e=this.bytes[0]*2**40,e+=this.bytes[1]*2**32,e+=this.bytes[2]*2**24,e+=65536*this.bytes[3],e+=256*this.bytes[4],e+=this.bytes[5],e}toString(){let e="";for(let t=0;t<16;t++)e+=this.bytes[t].toString(16).padStart(2,"0"),3!==t&&5!==t&&7!==t&&9!==t||(e+="-");return e}}var n="undefined"!=typeof window&&void 0!==window.document,r="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,i="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,o="undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&"userAgent"in navigator&&"string"==typeof navigator.userAgent&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"));"undefined"!=typeof Deno&&void 0!==Deno.version&&Deno.version.deno,"undefined"!=typeof process&&null!=process.versions&&process.versions.bun;const a="open",l="opening";var c;class h{constructor(e={}){let t=e.hostname||"localhost",s=e.port||1100;this._keepAlive=e.keepAlive,this._reconnectTime=e.reconnectTime||5e3,this.url=new URL("tcp://localhost"),this.url.hostname=t,this.url.port=s.toString(),this._buf="",this._firstConn=!0,this._firstReConn=!0,this.pendingOnOpen=[],this.connListeners=[],this.debug=!1,this._sockInit(t,s)}_sendConnEvent(e){this.connListeners.forEach(t=>{t&&"[object Function]"==={}.toString.call(t)&&t(e)})}_sockInit(e,t){if(c)this._sockSetup(e,t);else try{import("net").then(s=>{c=s.createConnection,this._sockSetup(e,t)})}catch(e){this.debug&&console.log("Unable to import net module")}}_sockSetup(e,t){if(c)try{this.sock=c({host:e,port:t}),this.sock.setEncoding("utf8"),this.sock.on("connect",this._onSockOpen.bind(this)),this.sock.on("error",this._sockReconnect.bind(this)),this.sock.on("close",()=>{this._sendConnEvent(!1)}),this.sock.send=e=>{this.sock.write(e)}}catch(e){return void(this.debug&&console.log("Connection failed to ",this.sock.host+":"+this.sock.port))}}_sockReconnect(){!this._firstConn&&this._keepAlive&&this.sock.readyState!=l&&this.sock.readyState!=a&&(this._firstReConn&&this._sendConnEvent(!1),this._firstReConn=!1,setTimeout(()=>{this.pendingOnOpen=[],this._sockSetup(this.url.hostname,this.url.port)},this._reconnectTime))}_onSockOpen(){this._sendConnEvent(!0),this._firstConn=!1,this.sock.on("close",this._sockReconnect.bind(this)),this.sock.on("data",this._processSockData.bind(this)),this.pendingOnOpen.forEach(e=>e()),this.pendingOnOpen.length=0,this._buf=""}_processSockData(e){this._buf+=e;var t=this._buf.split("\n");t.forEach((e,s)=>{s<t.length-1?e&&this._onSockRx&&this._onSockRx.call(this,e):this._buf=e})}toString(){let e="";return e+=(this.sock,this.sock.remoteAddress.toString()+":"+this.sock.remotePort.toString()),e}write(e){return this.sock&&this.sock.readyState!=l?this.sock.readyState==a&&(this.sock.send(e+"\n"),!0):(this.pendingOnOpen.push(()=>{this.sock.send(e+"\n")}),!0)}setReadCallback(e){e&&"[object Function]"==={}.toString.call(e)&&(this._onSockRx=e)}addConnectionListener(e){this.connListeners.push(e)}removeConnectionListener(e){let t=this.connListeners.indexOf(e);return t>=0&&(this.connListeners.splice(t,1),!0)}close(){this.sock&&(this.sock.readyState==l?this.pendingOnOpen.push(()=>{this.sock.send('{"alive": false}\n'),this.sock.removeAllListeners("connect"),this.sock.removeAllListeners("error"),this.sock.removeAllListeners("close"),this.sock.destroy()}):this.sock.readyState==a&&(this.sock.send('{"alive": false}\n'),this.sock.removeAllListeners("connect"),this.sock.removeAllListeners("error"),this.sock.removeAllListeners("close"),this.sock.destroy()))}}class u{constructor(e={}){let t=e.hostname||"localhost",s=e.port||80;this.url=new URL("ws://localhost"),this.url.hostname=t,this.url.port=s.toString(),this.url.pathname=e.pathname||"/",this._keepAlive=e.keepAlive,this._reconnectTime=e.reconnectTime||5e3,this.debug=e.debug||!1,this._firstConn=!0,this._firstReConn=!0,this.pendingOnOpen=[],this.connListeners=[],this._websockSetup(this.url)}_sendConnEvent(e){this.connListeners.forEach(t=>{t&&"[object Function]"==={}.toString.call(t)&&t(e)})}_websockSetup(e){try{this.sock=new WebSocket(e),this.sock.onerror=this._websockReconnect.bind(this),this.sock.onopen=this._onWebsockOpen.bind(this),this.sock.onclose=()=>{this._sendConnEvent(!1)}}catch(t){return void(this.debug&&console.log("Connection failed to ",e))}}_websockReconnect(){!this._firstConn&&this._keepAlive&&this.sock.readyState!=this.sock.CONNECTING&&this.sock.readyState!=this.sock.OPEN&&(this._firstReConn&&this._sendConnEvent(!1),this._firstReConn=!1,this.debug&&console.log("Reconnecting to ",this.sock.url),setTimeout(()=>{this.pendingOnOpen=[],this._websockSetup(this.sock.url)},this._reconnectTime))}_onWebsockOpen(){this.debug&&console.log("Connected to ",this.sock.url),this._sendConnEvent(!0),this.sock.onclose=this._websockReconnect.bind(this),this.sock.onmessage=e=>{this._onWebsockRx&&this._onWebsockRx.call(this,e.data)},this._firstConn=!1,this._firstReConn=!0,this.pendingOnOpen.forEach(e=>e()),this.pendingOnOpen.length=0}toString(){let e="";return e+=(this.sock,this.sock.url.toString()),e}write(e){return this.sock&&this.sock.readyState!=this.sock.CONNECTING?this.sock.readyState==this.sock.OPEN&&(this.sock.send(e+"\n"),!0):(this.pendingOnOpen.push(()=>{this.sock.send(e+"\n")}),!0)}setReadCallback(e){e&&"[object Function]"==={}.toString.call(e)&&(this._onWebsockRx=e)}addConnectionListener(e){this.connListeners.push(e)}removeConnectionListener(e){let t=this.connListeners.indexOf(e);return t>=0&&(this.connListeners.splice(t,1),!0)}close(){this.sock&&(this.sock.readyState==this.sock.CONNECTING?this.pendingOnOpen.push(()=>{this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.close()}):this.sock.readyState==this.sock.OPEN&&(this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.close()))}}class g{constructor(e,t){if(this.id=s.generate().toString(),this.action=null,this.inResponseTo=null,this.agentID=null,this.agentIDs=null,this.agentTypes=null,this.service=null,this.services=null,this.answer=null,this.message=null,this.relay=null,this.creds=null,this.auth=null,this.name=null,e&&"string"==typeof e)try{const s=JSON.parse(e,p);s.message&&(s.message=v.fromJSON(s.message)),s.agentID&&(s.agentID=S.fromJSON(s.agentID,t)),s.agentIDs&&(s.agentIDs=s.agentIDs.map(e=>S.fromJSON(e,t))),Object.assign(this,s)}catch(e){throw new Error("Invalid JSON string: "+e.message)}}static createSend(e,t=!1){if(!(e instanceof v))throw new Error("Invalid message type");const s=new g;return s.action=d.SEND,s.relay=t,s.message=e,s}static createWantsMessagesFor(e){if(!Array.isArray(e)||0===e.length)throw new Error("agentIDNames must be a non-empty array");const t=new g;return t.action=d.WANTS_MESSAGES_FOR,t.agentIDs=e,t}static createAgents(){const e=new g;return e.action=d.AGENTS,e.id=s.generate().toString(),e}static createContainsAgent(e){if(!(e instanceof S))throw new Error("agentID must be an instance of AgentID");const t=new g;return t.action=d.CONTAINS_AGENT,t.id=s.generate().toString(),t.agentID=e,t}static createAgentForService(e){if("string"!=typeof e||0===e.length)throw new Error("service must be a non-empty string");const t=new g;return t.action=d.AGENT_FOR_SERVICE,t.id=s.generate().toString(),t.service=e,t}static createAgentsForService(e){if("string"!=typeof e||0===e.length)throw new Error("service must be a non-empty string");const t=new g;return t.action=d.AGENTS_FOR_SERVICE,t.id=s.generate().toString(),t.service=e,t}toJSON(){if(!this.action&&!this.id)throw new Error("Neither action nor id is set. Cannot serialize JSONMessage.");const e={};return this.id&&(e.id=this.id),this.action&&(e.action=this.action),this.inResponseTo&&(e.inResponseTo=this.inResponseTo),this.agentID&&(e.agentID=this.agentID.toJSON()),this.agentIDs&&(e.agentIDs=this.agentIDs.map(e=>e.toJSON()),0===e.agentIDs.length&&delete e.agentIDs),this.service&&(e.service=this.service),this.services&&(e.services=this.services,0===e.services.length&&delete e.services),null!=this.answer&&(e.answer=this.answer),this.message&&(e.message=this.message),this.relay&&(e.relay=this.relay),this.creds&&(e.creds=this.creds),this.auth&&(e.auth=this.auth),this.name&&(e.name=this.name),JSON.stringify(e)}toString(){return this.toJSON()}}const d={AGENTS:"agents",CONTAINS_AGENT:"containsAgent",AGENT_FOR_SERVICE:"agentForService",AGENTS_FOR_SERVICE:"agentsForService",SEND:"send",WANTS_MESSAGES_FOR:"wantsMessagesFor"};function p(e,t){return null===t?null:"object"==typeof t&&"clazz"in t&&"data"in t&&t.clazz.startsWith("[")&&2==t.clazz.length&&function(e,t,s=!0){let a=function(e){if(n||i)return window.atob(e);if(o||r)return Buffer.from(e,"base64").toString("binary")}(e),l=a.length,c=new Uint8Array(l);for(var h=0;h<l;h++)c[h]=a.charCodeAt(h);let u=[],g=new DataView(c.buffer);switch(t){case"[B":for(h=0;h<l;h++)u.push(g.getUint8(h));break;case"[S":for(h=0;h<l;h+=2)u.push(g.getInt16(h,s));break;case"[I":for(h=0;h<l;h+=4)u.push(g.getInt32(h,s));break;case"[J":for(h=0;h<l;h+=8)u.push(g.getBigInt64(h,s));break;case"[F":for(h=0;h<l;h+=4)u.push(g.getFloat32(h,s));break;case"[D":for(h=0;h<l;h+=8)u.push(g.getFloat64(h,s));break;default:return}return u}(t.data,t.clazz)||t}const f={timeout:1e4,keepAlive:!0,queueSize:128,returnNullOnFailedResponse:!0};let m,_={};class R{constructor(e={}){for(var t in f)null!=e[t]&&""!==e[t]||(e[t]=f[t]);var s=m;s.hostname=e.hostname,s.port=e.port,s.pathname=e.pathname;let n=this._getGWCache(s);if(n)return n;var r;this._timeout=e.timeout,this._keepAlive=e.keepAlive,this._queueSize=e.queueSize,this._returnNullOnFailedResponse=e.returnNullOnFailedResponse,this._cancelPendingOnDisconnect=e.cancelPendingOnDisconnect,this._pending_actions={},this._subscriptions={},this._pending_receives={},this._eventListeners={},this._queue=[],this.connected=!1,this.debug=!1,this.aid=new S("gateway-"+(r=4,Array.from({length:r},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join(""))),this.connector=this._createConnector(s),this._addGWCache(this)}_sendEvent(e,t){Array.isArray(this._eventListeners[e])&&this._eventListeners[e].forEach(e=>{if(e&&"[object Function]"==={}.toString.call(e))try{e(t)}catch(e){console.warn("Error in event listener : "+e)}})}_sendReceivers(e){for(var t in this._pending_receives)try{if(this._pending_receives[t]&&this._pending_receives[t](e))return!0}catch(e){console.warn("Error in listener : "+e)}return!1}_onMsgRx(e){var t;this.debug&&console.log("< "+e),this._sendEvent("rx",e);try{t=new g(e,this)}catch(e){return}if(this._sendEvent("rxp",t),t.id&&t.id in this._pending_actions)this._pending_actions[t.id](t),delete this._pending_actions[t.id];else if(t.action==d.SEND){const e=t.message;if(!e)return;this._sendEvent("rxmsg",e),(e.recipient.toJSON()==this.aid.toJSON()||this._subscriptions[e.recipient.toJSON()])&&(this._sendEvent("message",e),this._sendReceivers(e)||(this._queue.length>=this._queueSize&&this._queue.shift(),this._queue.push(e)))}else{let e=new g;switch(e.id=t.id,e.inResponseTo=t.action,t.action){case"agents":e.agentIDs=[this.aid];break;case"containsAgent":e.answer=t.agentID.toJSON()==this.aid.toJSON();break;case"services":e.services=[];break;case"agentForService":e.agentID="";break;case"agentsForService":e.agentIDs=[];break;default:e=void 0}e&&this._msgTx(e)}}_msgTx(e){const t=e.toJSON();return this.debug&&console.log("> "+t),this._sendEvent("tx",t),this.connector.write(t)}_msgTxRx(e,t=this._timeout){return e.id=s.generate().toString(),new Promise(s=>{let n;t>=0&&(n=setTimeout(()=>{delete this._pending_actions[e.id],this.debug&&console.log("Receive Timeout : "+JSON.stringify(e)),s(null)},t)),this._pending_actions[e.id]=e=>{n&&clearTimeout(n),s(e)},this._msgTx.call(this,e)||(n&&clearTimeout(n),delete this._pending_actions[e.id],this.debug&&console.log("Transmit Failure : "+JSON.stringify(e)),s(null))})}_createConnector(e){let t;if(e.protocol.startsWith("ws"))t=new u({hostname:e.hostname,port:parseInt(e.port),pathname:e.pathname,keepAlive:this._keepAlive,debug:this.debug});else{if(!e.protocol.startsWith("tcp"))return null;t=new h({hostname:e.hostname,port:parseInt(e.port),keepAlive:this._keepAlive,debug:this.debug})}return t.setReadCallback(this._onMsgRx.bind(this)),t.addConnectionListener(e=>{this.connected=!!e,1==e?(this.flush(),this.connector.write('{"alive": true}'),this._update_watch()):this._cancelPendingOnDisconnect&&(this._sendReceivers(null),this.flush()),this._sendEvent("conn",e)}),t}_isConstructor(e){try{return new new Proxy(e,{construct:()=>({})}),!0}catch(e){return!1}}_matchMessage(e,t){if("string"==typeof e||e instanceof String)return"inReplyTo"in t&&t.inReplyTo==e;if(Object.prototype.hasOwnProperty.call(e,"msgID"))return"inReplyTo"in t&&t.inReplyTo==e.msgID;if("Message"==e.__proto__.name||"Message"==e.__proto__.__proto__.name)return e.__clazz__==t.__clazz__;if("function"!=typeof e||this._isConstructor(e))return t instanceof e;try{return e(t)}catch(e){return console.warn("Error in filter : "+e),!1}}_getMessageFromQueue(e){if(!this._queue.length)return;if(!e)return this._queue.shift();let t=this._queue.find(t=>this._matchMessage(e,t));return t&&this._queue.splice(this._queue.indexOf(t),1),t}_getGWCache(e){if(!_.fjage||!_.fjage.gateways)return null;var t=_.fjage.gateways.filter(t=>t.connector.url.toString()==e.toString());return t.length?t[0]:null}_addGWCache(e){_.fjage&&_.fjage.gateways&&_.fjage.gateways.push(e)}_removeGWCache(e){if(_.fjage&&_.fjage.gateways){var t=_.fjage.gateways.indexOf(e);null!=t&&_.fjage.gateways.splice(t,1)}}_update_watch(){let e=Object.keys(this._subscriptions);e.push(this.aid.toJSON());const t=g.createWantsMessagesFor(e.map(e=>S.fromJSON(e)));this._msgTx(t)}addEventListener(e,t){Array.isArray(this._eventListeners[e])||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;let s=this._eventListeners[e].indexOf(t);s>=0&&this._eventListeners[e].splice(s,1)}addMessageListener(e){this.addEventListener("message",e)}removeMessageListener(e){this.removeEventListener("message",e)}addConnListener(e){this.addEventListener("conn",e)}removeConnListener(e){this.removeEventListener("conn",e)}getAgentID(){return this.aid}agent(e){return new S(e,!1,this)}topic(e,t){return"string"==typeof e||e instanceof String?new S(e,!0,this):e instanceof S?e.isTopic()?e:new S(e.getName()+(t?"__"+t:"")+"__ntf",!0,this):void 0}subscribe(e){return e.isTopic()||(e=new S(e.getName()+"__ntf",!0,this)),this._subscriptions[e.toJSON()]=!0,this._update_watch(),!0}unsubscribe(e){e.isTopic()||(e=new S(e.getName()+"__ntf",!0,this)),delete this._subscriptions[e.toJSON()],this._update_watch()}async agents(e=this._timeout){let t=g.createAgents(),s=await this._msgTxRx(t,e);if(!s||!Array.isArray(s.agentIDs))throw new Error("Unable to get agents");return s.agentIDs}async containsAgent(e,t=this._timeout){let s=g.createContainsAgent(e instanceof S?e:new S(e)),n=await this._msgTxRx(s,t);if(!n){if(this._returnNullOnFailedResponse)return null;throw new Error("Unable to check if agent exists")}return!!n.answer}async agentForService(e,t=this._timeout){let s=g.createAgentForService(e),n=await this._msgTxRx(s,t);if(!n){if(this._returnNullOnFailedResponse)return null;throw new Error("Unable to get agent for service")}return n.agentID}async agentsForService(e,t=this._timeout){let s=g.createAgentsForService(e),n=await this._msgTxRx(s,t);if(!n){if(this._returnNullOnFailedResponse)return null;throw new Error("Unable to get agents for service")}return n.agentIDs||[]}send(e){e.sender=this.aid,this._sendEvent("txmsg",e);const t=g.createSend(e,!0);return!!this._msgTx(t)}flush(){this._queue.length=0}async request(e,t=this._timeout){return this.send(e),this.receive(e,t)}async receive(e,t=0){return new Promise(n=>{let r=this._getMessageFromQueue.call(this,e);if(r)return void n(r);if(0==t)return this.debug&&console.log("Receive Timeout : "+e),void n();let i,o=s.generate().toString();t>0&&(i=setTimeout(()=>{this._pending_receives[o]&&delete this._pending_receives[o],this.debug&&console.log("Receive Timeout : "+e),n()},t)),this._pending_receives[o]=t=>!(t&&!this._matchMessage(e,t))&&(i&&clearTimeout(i),this._pending_receives[o]&&delete this._pending_receives[o],n(t),!0)})}close(){this.connector.close(),this._removeGWCache(this)}}class S{constructor(e,t=!1,s){this.name=e,this.topic=t,this.owner=s,this._timeout=s?s._timeout:1e4}getName(){return this.name}isTopic(){return this.topic}send(e){if(e.recipient=this,!this.owner)throw new Error("Unowned AgentID cannot send messages");this.owner.send(e)}async request(e,t=this._timeout){if(e.recipient=this,this.owner)return this.owner.request(e,t);throw new Error("Unowned AgentID cannot send messages")}toString(){return this.toJSON()+(this.owner&&this.owner.connector?` on ${this.owner.connector.url}`:"")}toJSON(){return(this.topic?"#":"")+this.name}static fromJSON(e,t){if("string"!=typeof e)throw new Error("Invalid JSON for AgentID");return(e=e.trim()).startsWith("#")?new S(e.substring(1),!0,t):new S(e,!1,t)}async set(e,s,n=-1,r=this._timeout){if(!e)return null;let i=new y;if(i.recipient=this,Array.isArray(e)){if(e.length!=s.length)throw new Error(`Parameters and values arrays must have the same length: ${e.length} != ${s.length}`);const t=e.slice(),n=s.slice();i.param=t.shift(),i.value=n.shift(),i.requests=t.map((e,t)=>({param:e,value:n[t]}))}else i.param=e,i.value=s;i.index=Number.isInteger(n)?n:-1;const o=await this.owner.request(i,r);var a=Array.isArray(e)?new Array(e.length).fill(null):null;if(!o||o.perf!=t.INFORM||!o.param){if(this.owner._returnNullOnFailedResponse)return a;throw new Error(`Unable to set ${this.name}.${e} to ${s}`)}if(Array.isArray(e)){o.values||(o.values={}),o.param&&(o.values[o.param]=o.value);const t=Object.keys(o.values);return e.map(e=>{e.includes(".")&&(e=e.split(".").pop());let s=t.find(t=>(t.includes(".")?t.split(".").pop():t)==e);return s?o.values[s]:void 0})}return o.value}async get(e,s=-1,n=this._timeout){let r=new y;if(r.recipient=this,e)if(Array.isArray(e)){const t=e.slice();r.param=t.shift(),r.requests=t.map(e=>({param:e}))}else r.param=e;r.index=Number.isInteger(s)?s:-1;const i=await this.owner.request(r,n);var o=Array.isArray(e)?new Array(e.length).fill(null):null;if(!i||i.perf!=t.INFORM||!i.param){if(this.owner._returnNullOnFailedResponse)return o;throw new Error(`Unable to get ${this.name}.${e}`)}if(e){if(Array.isArray(e)){i.values||(i.values={}),i.param&&(i.values[i.param]=i.value);const t=Object.keys(i.values);return e.map(e=>{e.includes(".")&&(e=e.split(".").pop());let s=t.find(t=>(t.includes(".")?t.split(".").pop():t)==e);return s?i.values[s]:void 0})}return i.value}return i.values||(i.values={}),i.param&&(i.values[i.param]=i.value),i.values}}class v{constructor(e,n=t.INFORM){this.__clazz__="org.arl.fjage.Message",this.msgID=s.generate().toString(),this.perf=n,this.sender=null,this.recipient=e?e.sender:null,this.inReplyTo=e?e.msgID:null}toString(){let e=this.perf?this.perf.toString():"MESSAGE";return"org.arl.fjage.Message"==this.__clazz__?e:e+": "+this.__clazz__.replace(/^.*\./,"")}toJSON(){let e={};for(let t in this)t.startsWith("_")||(e[t]=this[t]);return{clazz:this.__clazz__,data:e}}static fromJSON(e){if(!("clazz"in e)||!("data"in e))throw new Error(`Invalid Object for Message : ${e}`);let t=e.clazz,s=t.replace(/^.*\./,""),n=w[s]?new w[s]:new v;for(var r in n.__clazz__=t,e.data)"sender"===r||"recipient"===r?e.data[r]&&"string"==typeof e.data[r]&&(n[r]=S.fromJSON(e.data[r])):n[r]=e.data[r];return n}}function w(e,s=v){let n=e.replace(/^.*\./,"");if(w[n])return w[n];let r=class extends s{constructor(s){if(super(),this.__clazz__=e,s){const e=Object.keys(s);for(let t of e)this[t]=s[t]}e.endsWith("Req")&&(this.perf=t.REQUEST)}};return r.__clazz__=e,w[n]=r,r}const y=w("org.arl.fjage.param.ParameterReq");w("org.arl.fjage.param.ParameterRsp");const N={SHELL:"org.arl.fjage.shell.Services.SHELL"};n||i?(_=window,Object.assign(f,{hostname:_.location.hostname,port:_.location.port,pathname:"/ws/"}),m=new URL("ws://localhost"),void 0===_.fjage&&(_.fjage={}),void 0===_.fjage.gateways&&(_.fjage.gateways=[])):(o||r)&&(_=global,Object.assign(f,{hostname:"localhost",port:"1100",pathname:""}),m=new URL("tcp://localhost"));const A=w("org.arl.unet.DatagramReq"),E=w("org.arl.unet.DatagramNtf"),O=w("org.arl.unet.phy.TxFrameReq",A),b=w("org.arl.unet.phy.RxFrameNtf",E),k=w("org.arl.unet.bb.BasebandSignal");Object.assign(N,{NODE_INFO:"org.arl.unet.Services.NODE_INFO",ADDRESS_RESOLUTION:"org.arl.unet.Services.ADDRESS_RESOLUTION",DATAGRAM:"org.arl.unet.Services.DATAGRAM",PHYSICAL:"org.arl.unet.Services.PHYSICAL",RANGING:"org.arl.unet.Services.RANGING",BASEBAND:"org.arl.unet.Services.BASEBAND",LINK:"org.arl.unet.Services.LINK",MAC:"org.arl.unet.Services.MAC",ROUTING:"org.arl.unet.Services.ROUTING",ROUTE_MAINTENANCE:"org.arl.unet.Services.ROUTE_MAINTENANCE",TRANSPORT:"org.arl.unet.Services.TRANSPORT",REMOTE:"org.arl.unet.Services.REMOTE",STATE_MANAGER:"org.arl.unet.Services.STATE_MANAGER",DEVICE_INFO:"org.arl.unet.Services.DEVICE_INFO",DOA:"org.arl.unet.Services.DOA",SCHEDULER:"org.arl.unet.Services.SCHEDULER"});let T={DATA:0,RANGING:1,LINK:2,REMOTE:3,MAC:4,ROUTING:5,TRANSPORT:6,ROUTE_MAINTENANCE:7,LINK2:8,USER:32,MAX:63},F={TestReportNtf:w("org.arl.unet.TestReportNtf"),AbnormalTerminationNtf:w("org.arl.unet.AbnormalTerminationNtf"),CapabilityListRsp:w("org.arl.unet.CapabilityListRsp"),CapabilityReq:w("org.arl.unet.CapabilityReq"),ClearReq:w("org.arl.unet.ClearReq"),DatagramCancelReq:w("org.arl.unet.DatagramCancelReq"),DatagramDeliveryNtf:w("org.arl.unet.DatagramDeliveryNtf"),DatagramFailureNtf:w("org.arl.unet.DatagramFailureNtf"),DatagramNtf:w("org.arl.unet.DatagramNtf"),DatagramProgressNtf:w("org.arl.unet.DatagramProgressNtf"),DatagramReq:w("org.arl.unet.DatagramReq"),ParamChangeNtf:w("org.arl.unet.ParamChangeNtf"),RefuseRsp:w("org.arl.unet.RefuseRsp"),FailureNtf:w("org.arl.unet.FailureNtf"),DatagramTraceReq:w("org.arl.unet.net.DatagramTraceReq"),RouteDiscoveryReq:w("org.arl.unet.net.RouteDiscoveryReq"),RouteTraceReq:w("org.arl.unet.net.RouteTraceReq"),RouteDiscoveryNtf:w("org.arl.unet.net.RouteDiscoveryNtf"),RouteTraceNtf:w("org.arl.unet.net.RouteTraceNtf"),FecDecodeReq:w("org.arl.unet.phy.FecDecodeReq"),RxSWiG1FrameNtf:w("org.arl.unet.phy.RxSWiG1FrameNtf",b),TxSWiG1FrameReq:w("org.arl.unet.phy.TxSWiG1FrameReq",O),RxJanusFrameNtf:w("org.arl.unet.phy.RxJanusFrameNtf",b),TxJanusFrameReq:w("org.arl.unet.phy.TxJanusFrameReq",O),BadFrameNtf:w("org.arl.unet.phy.BadFrameNtf"),BadRangeNtf:w("org.arl.unet.phy.BadRangeNtf"),ClearSyncReq:w("org.arl.unet.phy.ClearSyncReq"),CollisionNtf:w("org.arl.unet.phy.CollisionNtf"),RxFrameNtf:w("org.arl.unet.phy.RxFrameNtf",E),RxFrameStartNtf:w("org.arl.unet.phy.RxFrameStartNtf"),SyncInfoReq:w("org.arl.unet.phy.SyncInfoReq"),SyncInfoRsp:w("org.arl.unet.phy.SyncInfoRsp"),TxFrameNtf:w("org.arl.unet.phy.TxFrameNtf"),TxFrameReq:w("org.arl.unet.phy.TxFrameReq",A),TxFrameStartNtf:w("org.arl.unet.phy.TxFrameStartNtf"),TxRawFrameReq:w("org.arl.unet.phy.TxRawFrameReq"),AddressAllocReq:w("org.arl.unet.addr.AddressAllocReq"),AddressAllocRsp:w("org.arl.unet.addr.AddressAllocRsp"),AddressResolutionReq:w("org.arl.unet.addr.AddressResolutionReq"),AddressResolutionRsp:w("org.arl.unet.addr.AddressResolutionRsp"),BasebandSignal:w("org.arl.unet.bb.BasebandSignal"),RecordBasebandSignalReq:w("org.arl.unet.bb.RecordBasebandSignalReq"),RxBasebandSignalNtf:w("org.arl.unet.bb.RxBasebandSignalNtf",k),TxBasebandSignalReq:w("org.arl.unet.bb.TxBasebandSignalReq",k),LinkStatusNtf:w("org.arl.unet.link.LinkStatusNtf"),RangeNtf:w("org.arl.unet.localization.RangeNtf"),RangeReq:w("org.arl.unet.localization.RangeReq"),BeaconReq:w("org.arl.unet.localization.BeaconReq"),RespondReq:w("org.arl.unet.localization.RespondReq"),InterrogationNtf:w("org.arl.unet.localization.InterrogationNtf"),ReservationAcceptReq:w("org.arl.unet.mac.ReservationAcceptReq"),ReservationCancelReq:w("org.arl.unet.mac.ReservationCancelReq"),ReservationReq:w("org.arl.unet.mac.ReservationReq"),ReservationRsp:w("org.arl.unet.mac.ReservationRsp"),ReservationStatusNtf:w("org.arl.unet.mac.ReservationStatusNtf"),RxAckNtf:w("org.arl.unet.mac.RxAckNtf"),TxAckReq:w("org.arl.unet.mac.TxAckReq"),RemoteExecReq:w("org.arl.unet.remote.RemoteExecReq"),RemoteFailureNtf:w("org.arl.unet.remote.RemoteFailureNtf"),RemoteFileGetReq:w("org.arl.unet.remote.RemoteFileGetReq"),RemoteFileNtf:w("org.arl.unet.remote.RemoteFileNtf"),RemoteFilePutReq:w("org.arl.unet.remote.RemoteFilePutReq"),RemoteSuccessNtf:w("org.arl.unet.remote.RemoteSuccessNtf"),RemoteTextNtf:w("org.arl.unet.remote.RemoteTextNtf"),RemoteTextReq:w("org.arl.unet.remote.RemoteTextReq"),AddScheduledSleepReq:w("org.arl.unet.scheduler.AddScheduledSleepReq"),GetSleepScheduleReq:w("org.arl.unet.scheduler.GetSleepScheduleReq"),RemoveScheduledSleepReq:w("org.arl.unet.scheduler.RemoveScheduledSleepReq"),SleepScheduleRsp:w("org.arl.unet.scheduler.SleepScheduleRsp"),WakeFromSleepNtf:w("org.arl.unet.scheduler.WakeFromSleepNtf"),ClearStateReq:w("org.arl.unet.state.ClearStateReq"),SaveStateReq:w("org.arl.unet.state.SaveStateReq")};function D(e){let t=e*Math.PI/180,s=111132.92-559.82*Math.cos(2*t)+1.175*Math.cos(4*t)-.0023*Math.cos(6*t);return[111412.84*Math.cos(t)-93.5*Math.cos(3*t)+.118*Math.cos(5*t),s]}class C extends S{constructor(e,t,s,n=!0){e instanceof S?super(e.getName(),e.topic,e.owner):super(e,t,s),this.greedy=n,this.cache={},this.specialParams=["name","version"]}async set(e,t,s=-1,n=5e3){let r=await super.set(e,t,s,n);return this._updateCache(e,r,s),r}async get(e,t=-1,s=5e3,n=5e3){if(this._isCached(e,t,n))return this._getCache(e,t);if(!this.greedy||Array.isArray(e)&&0!=[...new Set([...e,...this.specialParams])].length||this.specialParams.includes(e)){let n=await super.get(e,t,s);return this._updateCache(e,n,t),n}{let n=await super.get(null,t,s);if(this._updateCache(null,n,t),!n)return Array.isArray(e)?new Array(e.length).fill(null):null;if(e){if(Array.isArray(e))return e.map(e=>{let t=Object.keys(n).find(t=>this._toNamed(t)===e);return t?n[t]:null});{let t=Object.keys(n).find(t=>this._toNamed(t)===e);return t?n[t]:null}}return n}}_updateCache(e,t,s){if(null==t||Array.isArray(t)&&t.every(e=>null==e))return;null==e?(e=Object.keys(t),t=Object.values(t)):Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]),e=e.map(this._toNamed),void 0===this.cache[s.toString()]&&(this.cache[s.toString()]={});let n=this.cache[s.toString()];for(let s=0;s<e.length;s++)void 0===n[e[s]]&&(n[e[s]]={}),n[e[s]].value=t[s],n[e[s]].ctime=Date.now()}_isCached(e,t,s){if(s<=0)return!1;if(null==e)return!1;let n=this.cache[t.toString()];if(!n)return!1;Array.isArray(e)||(e=[e]);return e.every(e=>(e=this._toNamed(e))in n&&Date.now()-n[e].ctime<=s)}_getCache(e,t){let s=this.cache[t.toString()];return s?Array.isArray(e)?e.map(e=>e in s?s[e].value:null):e in s?s[e].value:null:null}_toNamed(e){const t=e.lastIndexOf(".");return t<0?e:e.slice(t+1)}}const I=F.AddressResolutionReq,q=F.DatagramReq,x=F.DatagramNtf,L=F.RxFrameNtf;e.AgentID=S,e.CachingAgentID=C,e.CachingGateway=class extends R{agent(e,t=!0,s=!0){const n=super.agent(e);return t?new C(n,null,null,s):n}topic(e,t,s=!0,n=!0){const r=super.topic(e,t);return s?new C(r,null,null,n):r}async agentForService(e,t=!0,s=!0){const n=await super.agentForService(e);return n&&t?new C(n,null,null,s):n}async agentsForService(e,t=!0,s=!0){const n=await super.agentsForService(e);return t?n.map(e=>new C(e,null,null,s)):n}},e.Gateway=R,e.Message=v,e.MessageClass=w,e.Performative=t,e.Protocol=T,e.Services=N,e.UnetMessages=F,e.UnetSocket=class{constructor(e,t,s=""){return(async()=>{this.gw=new R({hostname:e,port:t,path:s}),this.localProtocol=-1,this.remoteAddress=-1,this.remoteProtocol=T.DATA,this.timeout=0,this.provider=null;return(await this.gw.agentsForService(N.DATAGRAM)).forEach(e=>{this.gw.subscribe(this.gw.topic(e))}),this})()}close(){this.gw.close(),this.gw=null}isClosed(){return null==this.gw}bind(e){return(e==T.DATA||e>=T.USER&&e<=T.MAX)&&(this.localProtocol=e,!0)}unbind(){this.localProtocol=-1}isBound(){return this.localProtocol>=0}connect(e,t){return e>=0&&(t==T.DATA||t>=T.USER&&t<=T.MAX)&&(this.remoteAddress=e,this.remoteProtocol=t,!0)}disconnect(){this.remoteAddress=-1,this.remoteProtocol=0}isConnected(){return this.remoteAddress>=0}async getLocalAddress(){if(null==this.gw)return-1;const e=await this.gw.agentForService(N.NODE_INFO);if(null==e)return-1;const t=await e.get("address");return null!=t?t:-1}getLocalProtocol(){return this.localProtocol}getRemoteAddress(){return this.remoteAddress}getRemoteProtocol(){return this.remoteProtocol}setTimeout(e){e<0&&(e=0),this.timeout=e}getTimeout(){return this.timeout}async send(e,s=this.remoteAddress,n=this.remoteProtocol){if(s<0||null==this.gw)return!1;var r;if(Array.isArray(e))(r=new q).data=e,r.to=s,r.protocol=n;else{if(!(e instanceof q))return!1;r=e}let i=r.protocol;if(i!=T.DATA&&(i<T.USER||i>T.MAX))return!1;if(null==r.recipient){if(null==this.provider&&(this.provider=await this.gw.agentForService(N.TRANSPORT)),null==this.provider&&(this.provider=await this.gw.agentForService(N.ROUTING)),null==this.provider&&(this.provider=await this.gw.agentForService(N.LINK)),null==this.provider&&(this.provider=await this.gw.agentForService(N.PHYSICAL)),null==this.provider&&(this.provider=await this.gw.agentForService(N.DATAGRAM)),null==this.provider)return!1;r.recipient=this.provider}const o=await this.gw.request(r,1e3);return null!=o&&o.perf==t.AGREE}async receive(){return null==this.gw?null:await this.gw.receive(e=>{if(e.__clazz__!=x.__clazz__&&e.__clazz__!=L.__clazz__)return!1;let t=e.protocol;return(t==T.DATA||t>=T.USER)&&(this.localProtocol<0||this.localProtocol==t)},this.timeout)}getGateway(){return this.gw}async agentForService(e){return null==this.gw?null:await this.gw.agentForService(e)}async agentsForService(e){return null==this.gw?null:await this.gw.agentsForService(e)}agent(e){return null==this.gw?null:this.gw.agent(e)}async host(e){const t=await this.agentForService(N.ADDRESS_RESOLUTION);if(null==t)return null;const s=new I(e);s.name=e,s.recipient=t;const n=await this.gw.request(s,1e3);return null!=n&&Object.prototype.hasOwnProperty.call(n,"address")?n.address:null}},e.toGps=function(e,t,s){let n=[],[r,i]=D(e[0]);return n[1]=t/r+e[1],n[0]=s/i+e[0],n},e.toLocal=function(e,t,s){let n=[],[r,i]=D(e[0]);return n[0]=(s-e[1])*r,n[1]=(t-e[0])*i,n}});
2
2
  //# sourceMappingURL=unetjs.min.js.map