@alwatr/nanotron-api-server 4.0.0 → 4.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,12 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [4.0.1](https://github.com/Alwatr/nanotron/compare/v4.0.0...v4.0.1) (2024-09-14)
7
+
8
+ ### Miscellaneous Chores
9
+
10
+ * **readme:** remove old docs ([4c4cc79](https://github.com/Alwatr/nanotron/commit/4c4cc79e0f0db9090bd767970f832d104256f3ef)) by @
11
+
6
12
  ## [4.0.0](https://github.com/Alwatr/nanotron/compare/v4.0.0-alpha.3...v4.0.0) (2024-09-14)
7
13
 
8
14
  ### Features
package/README.md CHANGED
@@ -1,140 +1,3 @@
1
1
  # Alwatr Nanotron Api Server
2
2
 
3
3
  Nanotron: Your Lightweight, High-Performance Micro/Nano Service Framework.
4
-
5
- ## Example usage
6
-
7
- ```ts
8
- import {type AlwatrConnection, AlwatrNanoServer} from 'https://esm.run/@alwatr/nano-server';
9
-
10
- const nanoServer = new AlwatrNanoServer();
11
-
12
- nanoServer.route('GET', '/', async (connection: AlwatrConnection) => {
13
- connection.reply({
14
- ok: true,
15
- data: {
16
- app: 'Alwatr Nanoservice Starter Kit',
17
- message: 'Hello ;)',
18
- },
19
- });
20
- });
21
- ```
22
-
23
- ## API
24
-
25
- ### `AlwatrNanoServer(config?: Partial<Config>)`
26
-
27
- Create a server for nanoservice use cases.
28
-
29
- Example:
30
-
31
- ```ts
32
- import {AlwatrNanoServer} from 'https://esm.run/@alwatr/nano-server';
33
- const nanoServer = new AlwatrNanoServer();
34
- ```
35
-
36
- ### `nanoserver.close()`
37
-
38
- Stops the HTTP server from accepting new connections.
39
-
40
- ### `route(method: Methods, route: 'all' |`/${string}`,middleware: (connection: AlwatrConnection) => void)`
41
-
42
- Refers to how an application’s endpoints (URIs) respond to client requests.
43
-
44
- Example:
45
-
46
- ```ts
47
- nanoServer.route('GET', '/', middleware);
48
- ```
49
-
50
- ### `AlwatrConnection(incomingMessage: IncomingMessage, serverResponse: ServerResponse)`
51
-
52
- ????
53
-
54
- ```ts
55
- async function middleware(connection: AlwatrConnection) => {
56
- connection.reply({
57
- ok: true,
58
- data: {
59
- app: 'Alwatr Nanoservice Starter Kit',
60
- message: 'Hello ;)',
61
- },
62
- });
63
- });
64
- ```
65
-
66
- ### `connection.url: URL`
67
-
68
- Request URL.
69
-
70
- ### `connection.method: "ALL" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "CONNECT" | "TRACE" | "OPTIONS" | "PATCH"
71
-
72
- `
73
-
74
- Request method.
75
-
76
- ### `connection.getBody(): Promise<string | null>`
77
-
78
- Get request body for **POST**, **PUT** and **POST** methods..
79
-
80
- Example:
81
-
82
- ```ts
83
- const body = await connection.getBody();
84
- ```
85
-
86
- ### `connection.getToken(): string | null`
87
-
88
- Get the token placed in the request header.
89
-
90
- ### `connection.reply(content: ReplyContent)`
91
-
92
- Example:
93
-
94
- ```ts
95
- nanoServer.route('GET', '/', async (connection) => {
96
- connection.reply({
97
- ok: true,
98
- data: {
99
- app: 'Alwatr Nanoservice Starter Kit',
100
- message: 'Hello ;)',
101
- },
102
- });
103
- });
104
- ```
105
-
106
- ### `connection.requireJsonBody()`
107
-
108
- Parse request body.
109
-
110
- Example:
111
-
112
- ```ts
113
- const bodyData = await connection.requireJsonBody();
114
- if (bodyData == null) return;
115
- ```
116
-
117
- ### `requireToken(validator: ((token: string) => boolean) | Array<string> | string): string | null`
118
-
119
- Parse and validate request token.
120
- Returns request token.
121
-
122
- Example:
123
-
124
- ```ts
125
- const token = connection.requireToken((token) => token.length > 12);
126
- if (token == null) return;
127
- ```
128
-
129
- ### `requireQueryParams<T>(params: Record<string, ParamType>): T | null`
130
-
131
- Parse and validate query params.
132
- Returns query params object.
133
-
134
- Example:
135
-
136
- ```ts
137
- const params = connection.requireQueryParams<{id: string}>({id: 'string'});
138
- if (params == null) return;
139
- console.log(params.id);
140
- ```
package/dist/main.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /* @alwatr/nanotron-api-server v4.0.0 */
1
+ /* @alwatr/nanotron-api-server v4.0.1 */
2
2
  "use strict";var y=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var M=(a,e)=>{for(var t in e)y(a,t,{get:e[t],enumerable:!0})},b=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of T(e))!N.call(a,o)&&o!==t&&y(a,o,{get:()=>e[o],enumerable:!(r=q(e,o))||r.enumerable});return a};var A=a=>b(y({},"__esModule",{value:!0}),a);var H={};M(H,{HttpMethods:()=>O,HttpStatusCodes:()=>i,HttpStatusMessages:()=>d,NanotronApiServer:()=>m});module.exports=A(H);var O={GET:"GET",HEAD:"HEAD",POST:"POST",PUT:"PUT",DELETE:"DELETE",CONNECT:"CONNECT",OPTIONS:"OPTIONS",TRACE:"TRACE",PATCH:"PATCH"},i={Info_100_Continue:100,Info_101_Switching_Protocols:101,Info_102_Processing:102,Info_103_Early_Hints:103,Success_200_OK:200,Success_201_Created:201,Success_202_Accepted:202,Success_203_Non_Authoritative_Information:203,Success_204_No_Content:204,Success_205_Reset_Content:205,Success_206_Partial_Content:206,Success_207_Multi_Status:207,Success_208_Already_Reported:208,Success_226_IM_Used:226,Redirect_300_Multiple_Choices:300,Redirect_301_Moved_Permanently:301,Redirect_302_Found:302,Redirect_303_See_Other:303,Redirect_304_Not_Modified:304,Redirect_305_Use_Proxy:305,Redirect_306_Switch_Proxy:306,Redirect_307_Temporary_Redirect:307,Redirect_308_Permanent_Redirect:308,Error_Client_400_Bad_Request:400,Error_Client_401_Unauthorized:401,Error_Client_402_Payment_Required:402,Error_Client_403_Forbidden:403,Error_Client_404_Not_Found:404,Error_Client_405_Method_Not_Allowed:405,Error_Client_406_Not_Acceptable:406,Error_Client_407_Proxy_Authentication_Required:407,Error_Client_408_Request_Timeout:408,Error_Client_409_Conflict:409,Error_Client_410_Gone:410,Error_Client_411_Length_Required:411,Error_Client_412_Precondition_Failed:412,Error_Client_413_Payload_Too_Large:413,Error_Client_414_URI_Too_Long:414,Error_Client_415_Unsupported_Media_Type:415,Error_Client_416_Range_Not_Satisfiable:416,Error_Client_417_Expectation_Failed:417,Error_Client_421_Misdirected_Request:421,Error_Client_422_Unprocessable_Entity:422,Error_Client_423_Locked:423,Error_Client_424_Failed_Dependency:424,Error_Client_425_Too_Early:425,Error_Client_426_Upgrade_Required:426,Error_Client_428_Precondition_Required:428,Error_Client_429_Too_Many_Requests:429,Error_Client_431_Request_Header_Fields_Too_Large:431,Error_Client_451_Unavailable_For_Legal_Reasons:451,Error_Server_500_Internal_Server_Error:500,Error_Server_501_Not_Implemented:501,Error_Server_502_Bad_Gateway:502,Error_Server_503_Service_Unavailable:503,Error_Server_504_Gateway_Timeout:504,Error_Server_505_HTTP_Version_Not_Supported:505,Error_Server_506_Variant_Also_Negotiates:506,Error_Server_507_Insufficient_Storage:507,Error_Server_508_Loop_Detected:508,Error_Server_510_Not_Extended:510,Error_Server_511_Network_Authentication_Required:511},d={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};var R=require("@alwatr/logger"),h=class{constructor(e,t){this.hasBeenSent_=!1;this.clientRequest=e,this.raw_=t,this.logger_=(0,R.createLogger)(`nt-server-response[${this.clientRequest.remoteAddress}]`),this.logger_.logMethodArgs?.("new",this.clientRequest.url.debugId),this.headers={server:"Alwatr Nanotron","content-type":"text/plain"}}get hasBeenSent(){return this.hasBeenSent_}get statusCode(){return this.raw_.statusCode}set statusCode(e){this.raw_.statusCode=e}applyHeaders_(){this.logger_.logMethodArgs?.("applyHeaders_",this.headers);for(let e in this.headers)this.raw_.setHeader(e,this.headers[e])}replyErrorResponse(e){this.logger_.logMethod?.("replyErrorResponse"),this.clientRequest.terminatedHandlers=!0,this.headers["content-type"]="application/json";let t="";if(e.meta!==void 0){let o=typeof e.meta;o==="string"||o==="number"||o==="boolean"||e.meta===null?t=`,"meta":"${e.meta}"`:o==="object"&&(t=`,"meta":${JSON.stringify(e.meta)}`)}let r=`{"ok":false,"errorCode":"${e.errorCode}","errorMessage":"${e.errorMessage}"${t}}`;this.reply(r)}replyError(e){this.logger_.logMethodArgs?.("replyError",{error:e}),this.clientRequest.terminatedHandlers=!0;let t=this.statusCode;t<i.Error_Client_400_Bad_Request&&(this.statusCode=t=500),e instanceof Error?this.replyErrorResponse({ok:!1,errorCode:e.name==="Error"?"error_"+t:(e.name+"").toLowerCase(),errorMessage:e.message}):typeof e=="string"?this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:e}):typeof e=="object"&&e!==null?this.replyJson(e):this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:d[t]})}replyJson(e){this.logger_.logMethodArgs?.("replyJson",{responseJson:e});let t;try{t=JSON.stringify(e)}catch(r){this.logger_.error("replyJson","reply_json_stringify_failed",r,this.clientRequest.url.debugId),this.statusCode=i.Error_Server_500_Internal_Server_Error,this.replyErrorResponse({ok:!1,errorCode:"reply_json_stringify_failed",errorMessage:"Failed to stringify response JSON."});return}this.headers["content-type"]="application/json",this.reply(t)}reply(e){if(this.logger_.logMethodArgs?.("reply",this.clientRequest.url.debugId),this.raw_.writableFinished&&this.hasBeenSent_===!1&&(this.logger_.accident("reply","server_response_writable_finished_directly"),this.hasBeenSent_=!0),this.hasBeenSent_){this.logger_.accident("reply","reply_already_sent",{url:this.clientRequest.url.debugId,replySent:this.hasBeenSent_,writableFinished:this.raw_.writableFinished});return}this.hasBeenSent_=!0;try{typeof e=="string"&&(e=Buffer.from(e)),this.headers["content-length"]=e.byteLength,this.applyHeaders_(),this.raw_.end(e,"binary")}catch(t){this.logger_.error("reply","server_response_error",t,this.clientRequest.url.debugId),this.hasBeenSent_=!1}}};var C=require("@alwatr/logger"),p=class{constructor(e,t,r,o){this.sharedMeta={};this.raw_=t,this.url=e,this.routeOption=o,this.remoteAddress=this.r(),this.logger_=(0,C.createLogger)(`nt-client-request[${this.remoteAddress}]`),this.logger_.logMethodArgs?.("new",e.debugId),this.serverResponse=new h(this,r)}get headers(){return this.raw_.headers}get queryParams(){if(this.t===void 0){this.t={};for(let[e,t]of this.url.searchParams.entries())this.t[e]=t}return this.t}getBodyRaw(){return new Promise((e,t)=>{let r=this.url.method;if(!(r==="POST"||r==="PUT"||r==="PATCH"))return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_405_Method_Not_Allowed,t(new Error("body_not_allowed"));let o=+this.raw_.headers["content-length"];if(Number.isNaN(o)||o===0)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_411_Length_Required,t(new Error("body_length_required"));if(o>this.routeOption.bodyLimit)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let s=[],n=0,f=l=>{if(n+=l.length,s.push(l),n>this.routeOption.bodyLimit)return this.raw_.removeListener("data",f),this.raw_.removeListener("end",_),this.raw_.removeListener("error",_),s.length=0,this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"))},_=l=>{if(this.raw_.removeListener("data",f),this.raw_.removeListener("end",_),this.raw_.removeListener("error",_),l!==void 0)return s.length=0,this.serverResponse.statusCode=i.Error_Client_400_Bad_Request,t(l);if(n!==o)return s.length=0,this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let w=Buffer.concat(s);e(w)};this.raw_.on("data",f),this.raw_.on("end",_),this.raw_.on("error",_),this.raw_.resume()})}r(){return this.raw_.headers["x-forwarded-for"]?.split(",").pop()?.trim()||this.raw_.socket.remoteAddress||null}};var E=require("node:url"),c=class c extends E.URL{constructor(e,t){let r=e.url??"";t!=="/"&&r.indexOf(t)===0&&(r=r.slice(t.length-1)),r=r.replace(c.versionPattern_,"/"),super(r,"http://hostname/"),this.method=(e.method??"GET").toUpperCase(),this.debugId=`[${this.method}]${this.pathname}`}};c.versionPattern_=new RegExp("^/v[0-9]+/");var u=c;var v=require("node:http"),S=require("@alwatr/logger"),g=class g{constructor(e){this.config_={...g.defaultConfig_,...e},this.logger_=(0,S.createLogger)("nt-api-server"+(this.config_.port!==80?":"+this.config_.port:"")),this.logger_.logMethodArgs?.("new",{config:this.config_}),this.handleClientRequest_=this.handleClientRequest_.bind(this),this.handleServerError_=this.handleServerError_.bind(this),this.handleClientError_=this.handleClientError_.bind(this),this.e={exact:{},startsWith:{}},this.httpServer=(0,v.createServer)({keepAlive:!0,keepAliveInitialDelay:0,noDelay:!0},this.handleClientRequest_),this.httpServer.requestTimeout=this.config_.requestTimeout,this.httpServer.keepAliveTimeout=this.config_.keepAliveTimeout,this.httpServer.headersTimeout=this.config_.headersTimeout,this.httpServer.listen(this.config_.port,this.config_.host,()=>{this.logger_.logOther?.(`listening on ${this.config_.host}:${this.config_.port}`)}),this.httpServer.on("error",this.handleServerError_),this.httpServer.on("clientError",this.handleClientError_)}close(){this.logger_.logMethod?.("close"),this.httpServer.close()}getRouteOption_(e){if(this.logger_.logMethod?.("getRouteOption_"),Object.hasOwn(this.e.exact,e.method)&&Object.hasOwn(this.e.exact[e.method],e.pathname))return this.e.exact[e.method][e.pathname];if(Object.hasOwn(this.e.startsWith,e.method)){let t=this.e.startsWith[e.method];for(let r in t)if(r.indexOf(e.pathname)===0)return t[r]}return this.logger_.incident?.("getRouteOption_","route_not_found",{method:e.method,url:e.pathname}),null}setRouteOption_(e){var r;this.logger_.logMethodArgs?.("setRouteOption_",e);let t=this.e[e.matchType];if(t[r=e.method]??(t[r]={}),Object.hasOwn(t[e.method],e.url))throw this.logger_.error("defineRoute","route_already_exists",e),new Error("route_already_exists");t[e.method][e.url]=e}defineRoute(e){let t={matchType:"exact",preHandlers:[],postHandlers:[],bodyLimit:this.config_.bodyLimit,...e};this.logger_.logMethodArgs?.("defineRoute",t),this.setRouteOption_(t)}handleServerError_(e){e.code==="EADDRINUSE"?this.logger_.error("handleServerError_","address_in_use",e):this.logger_.error("handleServerError_","http_server_error",e)}handleClientError_(e,t){this.logger_.accident("handleClientError_","http_server_client_error",{errCode:e.code,errMessage:e.message});let r=e.code?.toLowerCase()??`error_${i.Error_Client_400_Bad_Request}`,o=e.message??d[i.Error_Client_400_Bad_Request],s=`{"ok":false,"errorCode":"${r}","errorMessage":"${o}"}`,n=[`HTTP/1.1 ${i.Error_Client_400_Bad_Request} ${d[i.Error_Client_400_Bad_Request]}`,"content-type: application/json",`content-length: ${Buffer.byteLength(s)}`,`\r
3
3
  `].join(`\r
4
4
  `);t.end(n+s)}async handleClientRequest_(e,t){if(this.logger_.logMethod?.("handleClientRequest_"),e.url===void 0){this.logger_.accident("handleClientRequest_","http_server_url_undefined");return}let r=new u(e,this.config_.prefix),o=this.getRouteOption_(r),s=new p(r,e,t,o);if(o===null){s.serverResponse.statusCode=i.Error_Client_404_Not_Found,s.serverResponse.replyError();return}try{for(let n of o.preHandlers){if(s.terminatedHandlers===!0)return;await n(s,s.serverResponse,s.sharedMeta)}await o.handler(s,s.serverResponse,s.sharedMeta);for(let n of o.postHandlers){if(s.terminatedHandlers===!0)return;await n(s,s.serverResponse,s.sharedMeta)}}catch(n){this.logger_.error("handleClientRequest_","route_handler_error",n,r.debugId),s.serverResponse.statusCode<i.Error_Client_400_Bad_Request&&(s.serverResponse.statusCode=i.Error_Server_500_Internal_Server_Error),s.serverResponse.replyError(n)}}};g.defaultConfig_={host:"0.0.0.0",port:80,requestTimeout:1e4,headersTimeout:13e4,keepAliveTimeout:12e4,healthRoute:!0,allowAllOrigin:!1,prefix:"/api/",bodyLimit:1048576};var m=g;0&&(module.exports={HttpMethods,HttpStatusCodes,HttpStatusMessages,NanotronApiServer});
package/dist/main.mjs CHANGED
@@ -1,4 +1,4 @@
1
- /* @alwatr/nanotron-api-server v4.0.0 */
1
+ /* @alwatr/nanotron-api-server v4.0.1 */
2
2
  var w={GET:"GET",HEAD:"HEAD",POST:"POST",PUT:"PUT",DELETE:"DELETE",CONNECT:"CONNECT",OPTIONS:"OPTIONS",TRACE:"TRACE",PATCH:"PATCH"},i={Info_100_Continue:100,Info_101_Switching_Protocols:101,Info_102_Processing:102,Info_103_Early_Hints:103,Success_200_OK:200,Success_201_Created:201,Success_202_Accepted:202,Success_203_Non_Authoritative_Information:203,Success_204_No_Content:204,Success_205_Reset_Content:205,Success_206_Partial_Content:206,Success_207_Multi_Status:207,Success_208_Already_Reported:208,Success_226_IM_Used:226,Redirect_300_Multiple_Choices:300,Redirect_301_Moved_Permanently:301,Redirect_302_Found:302,Redirect_303_See_Other:303,Redirect_304_Not_Modified:304,Redirect_305_Use_Proxy:305,Redirect_306_Switch_Proxy:306,Redirect_307_Temporary_Redirect:307,Redirect_308_Permanent_Redirect:308,Error_Client_400_Bad_Request:400,Error_Client_401_Unauthorized:401,Error_Client_402_Payment_Required:402,Error_Client_403_Forbidden:403,Error_Client_404_Not_Found:404,Error_Client_405_Method_Not_Allowed:405,Error_Client_406_Not_Acceptable:406,Error_Client_407_Proxy_Authentication_Required:407,Error_Client_408_Request_Timeout:408,Error_Client_409_Conflict:409,Error_Client_410_Gone:410,Error_Client_411_Length_Required:411,Error_Client_412_Precondition_Failed:412,Error_Client_413_Payload_Too_Large:413,Error_Client_414_URI_Too_Long:414,Error_Client_415_Unsupported_Media_Type:415,Error_Client_416_Range_Not_Satisfiable:416,Error_Client_417_Expectation_Failed:417,Error_Client_421_Misdirected_Request:421,Error_Client_422_Unprocessable_Entity:422,Error_Client_423_Locked:423,Error_Client_424_Failed_Dependency:424,Error_Client_425_Too_Early:425,Error_Client_426_Upgrade_Required:426,Error_Client_428_Precondition_Required:428,Error_Client_429_Too_Many_Requests:429,Error_Client_431_Request_Header_Fields_Too_Large:431,Error_Client_451_Unavailable_For_Legal_Reasons:451,Error_Server_500_Internal_Server_Error:500,Error_Server_501_Not_Implemented:501,Error_Server_502_Bad_Gateway:502,Error_Server_503_Service_Unavailable:503,Error_Server_504_Gateway_Timeout:504,Error_Server_505_HTTP_Version_Not_Supported:505,Error_Server_506_Variant_Also_Negotiates:506,Error_Server_507_Insufficient_Storage:507,Error_Server_508_Loop_Detected:508,Error_Server_510_Not_Extended:510,Error_Server_511_Network_Authentication_Required:511},d={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};import{createLogger as R}from"@alwatr/logger";var l=class{constructor(e,t){this.hasBeenSent_=!1;this.clientRequest=e,this.raw_=t,this.logger_=R(`nt-server-response[${this.clientRequest.remoteAddress}]`),this.logger_.logMethodArgs?.("new",this.clientRequest.url.debugId),this.headers={server:"Alwatr Nanotron","content-type":"text/plain"}}get hasBeenSent(){return this.hasBeenSent_}get statusCode(){return this.raw_.statusCode}set statusCode(e){this.raw_.statusCode=e}applyHeaders_(){this.logger_.logMethodArgs?.("applyHeaders_",this.headers);for(let e in this.headers)this.raw_.setHeader(e,this.headers[e])}replyErrorResponse(e){this.logger_.logMethod?.("replyErrorResponse"),this.clientRequest.terminatedHandlers=!0,this.headers["content-type"]="application/json";let t="";if(e.meta!==void 0){let s=typeof e.meta;s==="string"||s==="number"||s==="boolean"||e.meta===null?t=`,"meta":"${e.meta}"`:s==="object"&&(t=`,"meta":${JSON.stringify(e.meta)}`)}let r=`{"ok":false,"errorCode":"${e.errorCode}","errorMessage":"${e.errorMessage}"${t}}`;this.reply(r)}replyError(e){this.logger_.logMethodArgs?.("replyError",{error:e}),this.clientRequest.terminatedHandlers=!0;let t=this.statusCode;t<i.Error_Client_400_Bad_Request&&(this.statusCode=t=500),e instanceof Error?this.replyErrorResponse({ok:!1,errorCode:e.name==="Error"?"error_"+t:(e.name+"").toLowerCase(),errorMessage:e.message}):typeof e=="string"?this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:e}):typeof e=="object"&&e!==null?this.replyJson(e):this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:d[t]})}replyJson(e){this.logger_.logMethodArgs?.("replyJson",{responseJson:e});let t;try{t=JSON.stringify(e)}catch(r){this.logger_.error("replyJson","reply_json_stringify_failed",r,this.clientRequest.url.debugId),this.statusCode=i.Error_Server_500_Internal_Server_Error,this.replyErrorResponse({ok:!1,errorCode:"reply_json_stringify_failed",errorMessage:"Failed to stringify response JSON."});return}this.headers["content-type"]="application/json",this.reply(t)}reply(e){if(this.logger_.logMethodArgs?.("reply",this.clientRequest.url.debugId),this.raw_.writableFinished&&this.hasBeenSent_===!1&&(this.logger_.accident("reply","server_response_writable_finished_directly"),this.hasBeenSent_=!0),this.hasBeenSent_){this.logger_.accident("reply","reply_already_sent",{url:this.clientRequest.url.debugId,replySent:this.hasBeenSent_,writableFinished:this.raw_.writableFinished});return}this.hasBeenSent_=!0;try{typeof e=="string"&&(e=Buffer.from(e)),this.headers["content-length"]=e.byteLength,this.applyHeaders_(),this.raw_.end(e,"binary")}catch(t){this.logger_.error("reply","server_response_error",t,this.clientRequest.url.debugId),this.hasBeenSent_=!1}}};import{createLogger as C}from"@alwatr/logger";var h=class{constructor(e,t,r,s){this.sharedMeta={};this.raw_=t,this.url=e,this.routeOption=s,this.remoteAddress=this.r(),this.logger_=C(`nt-client-request[${this.remoteAddress}]`),this.logger_.logMethodArgs?.("new",e.debugId),this.serverResponse=new l(this,r)}get headers(){return this.raw_.headers}get queryParams(){if(this.t===void 0){this.t={};for(let[e,t]of this.url.searchParams.entries())this.t[e]=t}return this.t}getBodyRaw(){return new Promise((e,t)=>{let r=this.url.method;if(!(r==="POST"||r==="PUT"||r==="PATCH"))return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_405_Method_Not_Allowed,t(new Error("body_not_allowed"));let s=+this.raw_.headers["content-length"];if(Number.isNaN(s)||s===0)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_411_Length_Required,t(new Error("body_length_required"));if(s>this.routeOption.bodyLimit)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let o=[],n=0,g=_=>{if(n+=_.length,o.push(_),n>this.routeOption.bodyLimit)return this.raw_.removeListener("data",g),this.raw_.removeListener("end",a),this.raw_.removeListener("error",a),o.length=0,this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"))},a=_=>{if(this.raw_.removeListener("data",g),this.raw_.removeListener("end",a),this.raw_.removeListener("error",a),_!==void 0)return o.length=0,this.serverResponse.statusCode=i.Error_Client_400_Bad_Request,t(_);if(n!==s)return o.length=0,this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let m=Buffer.concat(o);e(m)};this.raw_.on("data",g),this.raw_.on("end",a),this.raw_.on("error",a),this.raw_.resume()})}r(){return this.raw_.headers["x-forwarded-for"]?.split(",").pop()?.trim()||this.raw_.socket.remoteAddress||null}};import{URL as E}from"node:url";var u=class u extends E{constructor(e,t){let r=e.url??"";t!=="/"&&r.indexOf(t)===0&&(r=r.slice(t.length-1)),r=r.replace(u.versionPattern_,"/"),super(r,"http://hostname/"),this.method=(e.method??"GET").toUpperCase(),this.debugId=`[${this.method}]${this.pathname}`}};u.versionPattern_=new RegExp("^/v[0-9]+/");var p=u;import{createServer as v}from"node:http";import{createLogger as S}from"@alwatr/logger";var c=class c{constructor(e){this.config_={...c.defaultConfig_,...e},this.logger_=S("nt-api-server"+(this.config_.port!==80?":"+this.config_.port:"")),this.logger_.logMethodArgs?.("new",{config:this.config_}),this.handleClientRequest_=this.handleClientRequest_.bind(this),this.handleServerError_=this.handleServerError_.bind(this),this.handleClientError_=this.handleClientError_.bind(this),this.e={exact:{},startsWith:{}},this.httpServer=v({keepAlive:!0,keepAliveInitialDelay:0,noDelay:!0},this.handleClientRequest_),this.httpServer.requestTimeout=this.config_.requestTimeout,this.httpServer.keepAliveTimeout=this.config_.keepAliveTimeout,this.httpServer.headersTimeout=this.config_.headersTimeout,this.httpServer.listen(this.config_.port,this.config_.host,()=>{this.logger_.logOther?.(`listening on ${this.config_.host}:${this.config_.port}`)}),this.httpServer.on("error",this.handleServerError_),this.httpServer.on("clientError",this.handleClientError_)}close(){this.logger_.logMethod?.("close"),this.httpServer.close()}getRouteOption_(e){if(this.logger_.logMethod?.("getRouteOption_"),Object.hasOwn(this.e.exact,e.method)&&Object.hasOwn(this.e.exact[e.method],e.pathname))return this.e.exact[e.method][e.pathname];if(Object.hasOwn(this.e.startsWith,e.method)){let t=this.e.startsWith[e.method];for(let r in t)if(r.indexOf(e.pathname)===0)return t[r]}return this.logger_.incident?.("getRouteOption_","route_not_found",{method:e.method,url:e.pathname}),null}setRouteOption_(e){var r;this.logger_.logMethodArgs?.("setRouteOption_",e);let t=this.e[e.matchType];if(t[r=e.method]??(t[r]={}),Object.hasOwn(t[e.method],e.url))throw this.logger_.error("defineRoute","route_already_exists",e),new Error("route_already_exists");t[e.method][e.url]=e}defineRoute(e){let t={matchType:"exact",preHandlers:[],postHandlers:[],bodyLimit:this.config_.bodyLimit,...e};this.logger_.logMethodArgs?.("defineRoute",t),this.setRouteOption_(t)}handleServerError_(e){e.code==="EADDRINUSE"?this.logger_.error("handleServerError_","address_in_use",e):this.logger_.error("handleServerError_","http_server_error",e)}handleClientError_(e,t){this.logger_.accident("handleClientError_","http_server_client_error",{errCode:e.code,errMessage:e.message});let r=e.code?.toLowerCase()??`error_${i.Error_Client_400_Bad_Request}`,s=e.message??d[i.Error_Client_400_Bad_Request],o=`{"ok":false,"errorCode":"${r}","errorMessage":"${s}"}`,n=[`HTTP/1.1 ${i.Error_Client_400_Bad_Request} ${d[i.Error_Client_400_Bad_Request]}`,"content-type: application/json",`content-length: ${Buffer.byteLength(o)}`,`\r
3
3
  `].join(`\r
4
4
  `);t.end(n+o)}async handleClientRequest_(e,t){if(this.logger_.logMethod?.("handleClientRequest_"),e.url===void 0){this.logger_.accident("handleClientRequest_","http_server_url_undefined");return}let r=new p(e,this.config_.prefix),s=this.getRouteOption_(r),o=new h(r,e,t,s);if(s===null){o.serverResponse.statusCode=i.Error_Client_404_Not_Found,o.serverResponse.replyError();return}try{for(let n of s.preHandlers){if(o.terminatedHandlers===!0)return;await n(o,o.serverResponse,o.sharedMeta)}await s.handler(o,o.serverResponse,o.sharedMeta);for(let n of s.postHandlers){if(o.terminatedHandlers===!0)return;await n(o,o.serverResponse,o.sharedMeta)}}catch(n){this.logger_.error("handleClientRequest_","route_handler_error",n,r.debugId),o.serverResponse.statusCode<i.Error_Client_400_Bad_Request&&(o.serverResponse.statusCode=i.Error_Server_500_Internal_Server_Error),o.serverResponse.replyError(n)}}};c.defaultConfig_={host:"0.0.0.0",port:80,requestTimeout:1e4,headersTimeout:13e4,keepAliveTimeout:12e4,healthRoute:!0,allowAllOrigin:!1,prefix:"/api/",bodyLimit:1048576};var f=c;export{w as HttpMethods,i as HttpStatusCodes,d as HttpStatusMessages,f as NanotronApiServer};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alwatr/nanotron-api-server",
3
- "version": "4.0.0",
3
+ "version": "4.0.1",
4
4
  "description": "Nanotron: Your Lightweight, High-Performance Micro/Nano Service Framework.",
5
5
  "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
6
6
  "keywords": [
@@ -69,5 +69,5 @@
69
69
  "jest": "^29.7.0",
70
70
  "typescript": "^5.6.2"
71
71
  },
72
- "gitHead": "4fac85b6d696585b70485f2cd171c3eca0b72ea3"
72
+ "gitHead": "2fe620c71481283f2e47a9a0056e51961b11504b"
73
73
  }