UNPKG

ampjs

Version:

A Javascript(NodeJS) framework for handling the AMP protocol

1 lines 10.1 kB
var net=require("net");class AmpDate extends Date{constructor(a=void 0){a==null?super():super(a)}toAmpDate(){let a=super.toISOString(),b=super.getTimezoneOffset();a=a.substring(0,a.length-1),a+="000",b=Math.abs(b);let c,d=Math.floor(b/60)+"",e=b%60+"";return c=0<b?"+":"-",1==d.length&&(d="0"+d),1==e.length&&(e="0"+e),a=a+c+d+":"+e,a}}class CommandLocator{constructor(a,b){this.commands=a,this.callback=b}createcommand(a,b){try{return new this.commands[a](b,this.callback[a])}catch{return console.log("Invalid command: something happen over the wire"),0}}}class Command{constructor(a,b,c,d){this.fn=d,this.arguments=a,this.response=b;var e=this.checkerror(a,b,c);if(e);else{var f=this.checkarguments(c);!0==f?this.setarguments(c):(console.log("[Error] - arguments does not match"),this.seterror("120","arguments does not match"))}}seterror(a,b){errorObj.set_code(a),errorObj.set_description(b)}checkerror(a,b,c){var d=MapExt.isEmpty(c),e=MapExt.isEmpty(MapExt),f=!1,g=!1,h=Array.from(b.keys());return("_error"==h[0]||"_error_code"==h[1]||"_error_description"==h[2])&&(f=!0),!0==d&&!0==e&&!0==f&&(g=!0),g}checkresponse(a){return MapExt.compareMapsKeys(this.response,a)}checkarguments(a){return MapExt.compareMapsKeys(this.arguments,a)}setarguments(a){for(var[b,c]of a){var d=this.arguments.get(b),e=this.parsetype(d,c);this.arguments.set(b,e)}}setresponse(a,b){var c=new Map([...a,...b]);for(var[d,e]of c){var f=this.response.get(d);this.response.set(d,e+"")}}parsetype(a,b){if("integer"==a)var b=parseInt(b);else if("string"==a)var b=b+"";else if("float"==a)var b=parseFloat(b);else if("boolean"==a){if("false"==b||"0"==b)var b=!1;else var b=!0;}else if("datetime"==a){if(32==b.length)var b=b;else console.log("Not the right format for the datetime value"),this.seterror("160","Not the right format for the datetime value");}else if("list[string]"==a)var b=b+"";else if("amplist"==a)var b=parseFloat(b);else console.log("[Error] - not a valid valuetype"),this.seterror("150","not a valid valuetype");return b}}var factory={factorycommands:"",factorycallbacks:""};function CreateController(a){var b=new Controller(a,factory.factorycommands,factory.factorycallbacks);""==errorObj.code?(answer=b.run_responder(),b.from_command(answer)):b.to_error(errorObj.code,errorObj.description)}class Controller{constructor(a,b,c){this._data=a,this._ask=void 0,this._answer=void 0,this._command=void 0,this._error=void 0,this._error_code=void 0,this._error_description=void 0,this.factorycommands=b,this.factorycallbacks=c,this.arguments=new Map,this.parsedata(),this.locator=this.to_command()}get data(){return this._data}set data(a){this._data=a}get ask(){return this._ask}set ask(a){this._ask=a}get answer(){return this._answer}set answer(a){this._answer=a}get command(){return this._command}set command(a){this._command=a}get error(){return this._error}set error(a){this._error=a}get error_code(){return this._error_code}set error_code(a){this._error_code=a}get error_description(){return this._error_description}set error_description(a){this._error_description=a}parsedata(){Object.entries(this.data).forEach(a=>{let b=a[0],c=a[1];"_ask"==b?this.ask=c:"_answer"==b?this.answer=c:"_command"==b?this.command=c:"_error"==b?(this.error=c,this.command="error"):"_error_code"==b?this.error_code=c:"_error_description"==b?this.error_description=c:this.arguments.set(b,c)})}checkkey(a,b){return!!this.arguments.has(a)&&(value1=this.arguments.get(a),Array.isArray(value1)?(value1.push(b),this.arguments.set(a,value1)):(valuearray=[value1,b],this.arguments.set(a,valuearray)),!0)}run_responder(){return this.locator.responder(this.locator.arguments)}to_command(){let a=new CommandLocator(this.factorycommands,this.factorycallbacks),b=a.createcommand(this.command,this.arguments);return 0==b?void this.to_error("111","the incoming data has been corrupted"):b}from_command(a){this.answer=this.ask+"";var b=new Map;b.set("_answer",this.answer);var c=this.locator.checkresponse(a);if(!0==c)this.locator.setresponse(b,a);else return console.log("[Error] - the responds arguments does not match"),void this.to_error("101","the response arguments does not match");this.to_box()}dict_reverse(a){var b={};let c=Object.keys(a).reverse();return c.forEach(function(c){b[c]=a[c]}),b}to_error(a,b){this.error=this.ask+"",this.error_code=a,this.error_description=b;var c=new Map([["_error",this.error],["_error_code",this.error_code],["_error_description",this.error_description]]),d={};d._error=Buffer.alloc((this.error+"").length,this.error+"","utf8"),d._error_code=Buffer.alloc((this.error_code+"").length,this.error_code+"","utf8"),d._error_description=Buffer.alloc((this.error_description+"").length,this.error_description+"","utf8"),server.reply(d)}to_box(a){var b=this.locator.response,c={};for(var[d,e]of b)c[d]=Buffer.alloc((e+"").length,e+"","utf8");var f=this.dict_reverse(c);const g=Object.entries(f);console.log("replycall => "+g),server.reply(f)}from_box(a){}}class MapExt extends Map{static reverseMap(a){return new Map([...a].reverse())}static invertMap(a){let b=new Map;for(let[c,d]of a){let d=a.get(c);b.set(d,c)}return b}static isEmpty(a){return 0!=a.size}static compareMapSize(a,b){return!(a.size!==b.size)}static compareMaps(a,b){var c;if(!MapExt.compareMapSize(a,b))return!1;for(var[d,e]of a)if(c=b.get(d),c!==e||void 0===c&&!b.has(d))return!1;return!0}static compareMapsKeys(a,b){if(!MapExt.compareMapSize(a,b))return!1;for(var[c,d]of a)if(!b.has(c))return!1;return!0}static mergeMaps(a,b){return new Map([...a,...b])}}function ReceiverBox(a){this.box={},this._unprocessed=Buffer.alloc(0),this._nextKey=null,this.receiveBox=a||function(a){console.log(a)}}ReceiverBox.prototype.dataReceived=function(a){this._unprocessed=Buffer.concat([this._unprocessed,a]);for(var b=0,c=0,d=!0,e=[];d;){var f=this._unprocessed.length,g=this._unprocessed.readInt16BE(b,b+2);if(e.push(g),f<g+2||f<c)return;c=b+g+2;try{var h=this._unprocessed.readInt16BE(c,c+2)}catch{return}0==h&&(d=!1),b=c}b=2,keystate=0;for(var j=0;j<e.length;j++)0==keystate?(key=this._unprocessed.slice(b,e[j]+b),keystate=1):(value=this._unprocessed.slice(b,e[j]+b),this.box[key]=value,keystate=0),b=b+e[j]+2;this.receiveBox(this.box),this.box={},this._unprocessed=Buffer.alloc(0)};function BoxSender(a){function b(a){var b=d._wireBuffers.length;d._wireBuffers.push(Buffer.alloc(2)),0<a.length&&d._wireBuffers.push(a),d._wireBuffers[b].writeInt16BE(a.length,0)}var c,d=this;d.box=a,d._wireBuffers=[],c=Object.keys(d.box);for(var e=0;e<c.length;e++)b(Buffer.from(c[e],"utf8")),b(d.box[c[e]]);b(Buffer.alloc(0))}BoxSender.prototype.writeToTransport=function(a){for(var b=this,c=0;c<b._wireBuffers.length;c++)a(b._wireBuffers[c])};var callback={fname:"",connected:"",received:"",setcallback:function(a){this.fname=a},getcallback:function(){return this.fname},setconnected:function(a){this.connected=a},getconnected:function(){return this.connected},setreceived:function(a){this.received=a},getreceived:function(){return this.received}},errorObj={code:"",description:"",set_code:function(a){this.code=a},get_code:function(){return this.code},set_description:function(a){this.description=a},get_description:function(){return this.description},reset_error:function(){this.code="",this.description=""}};const ask={ask:0,get_ask:function(){return this.ask+=1,256<this.ask&&(this.ask=1),this.ask}};var server=net.createServer(function(a){console.log("server connected"),this.callback=callback.getcallback(),br=new ReceiverBox(this.callback),this.reply=function(b){return bx=new BoxSender(b),console.log("sending AMP box"),void bx.writeToTransport(function(b){a.write(b.toString("utf8"))})},a.on("error",function(a){console.log("An error has occured => "+a)}),a.on("end",function(){console.log(br.box),console.log("client has disconnected")}),a.on("close",function(){console.log(br.box),console.log("server has closed")}),a.on("data",function(a){br.dataReceived(a)})}),client=new function(){this.clientport="",this.clientaddress="",this.connected="",this.received="",this.remoteCall="",this.printInfo=function(){console.log(this.clientport),console.log(this.clientaddress),console.log(this.connected),console.log(this.received)},this.remoteCall=function(a){mapdata=commandmapping(a);var b={};for(var[c,d]of mapdata)b[c]=Buffer.alloc((d+"").length,d+"","utf8");const e=Object.entries(b);console.log("Outgoing Data => "+e);var f=new BoxSender(b);console.log("sending AMP box"),f.writeToTransport(function(a){client.connection.write(a.toString("utf8"))})},this.start=function(){this.connection=net.createConnection(this.clientport,this.clientaddress,function(){this.br=new ReceiverBox(checklist)}),this.connection.on("connect",function(){console.log("Connect to the server"),client.connected()}),this.connection.on("data",function(a){this.br.dataReceived(a)}),this.connection.on("end",function(){console.log(br.box),console.log("server disconnected")})}};function checklist(a){for(const b in a)if("_answer"!=b){if(temp=a[b],tempbuf=Buffer.from(temp),2>tempbuf.length)break;len1=tempbuf.readInt16BE(0,2),len1+2<tempbuf.length&&(arr=toArray(a[b]),a[b]=arr)}client.received(a)}function toArray(a){var b=a.length;for(offset=0,flag=!0,dataarray=[];flag;)len1=a.readInt16BE(offset,offset+2),word=a.slice(offset+2,len1+offset+2),dataarray.push(word+""),offset=offset+2+len1,offset>=b&&(flag=!1);return dataarray}function fromArray(a){var b=Buffer.alloc(0);for(len=a.length,i=0;i<len;i++){data=a[i],lendata=data.length;var c=Buffer.alloc(2),d=Buffer.from(data);c.writeInt16BE(lendata,0),c=Buffer.concat([c,d]),b=Buffer.concat([b,c])}return b.toString()}function commandmapping(a){resultmap=new Map;var b=ask.get_ask()+"";resultmap.set("_ask",b);for(var[c,d]of a)"command"==c.toLowerCase()?resultmap.set("_command",d):(d="object"==typeof d?fromArray(d):d+"",resultmap.set(c,d));return resultmap}module.exports={server:server,callback:callback,errorObj:errorObj,client:client,BoxSender:BoxSender,ReceiverBox:ReceiverBox,Controller:Controller,CreateController:CreateController,factory:factory,AmpDate:AmpDate,CommandLocator:CommandLocator,Command:Command};