@jwn-js/common 2.1.15 → 2.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/ApiError.d.ts +1 -29
  2. package/ApiError.js +1 -39
  3. package/ApiError.mjs +1 -0
  4. package/Jwt-7tQL-rwa.js +1 -0
  5. package/Jwt-CDdbxwvH.js +1 -0
  6. package/Jwt.js +1 -44
  7. package/Jwt.mjs +1 -0
  8. package/Memcached.js +9 -124
  9. package/Memcached.mjs +9 -0
  10. package/Server.d.ts +2 -2
  11. package/Server.js +1 -239
  12. package/Server.mjs +1 -0
  13. package/cookieParse.js +1 -27
  14. package/cookieParse.mjs +1 -0
  15. package/cookieString.js +1 -24
  16. package/cookieString.mjs +1 -0
  17. package/docs/assets/highlight.css +19 -5
  18. package/docs/assets/main.js +59 -52
  19. package/docs/assets/navigation.js +1 -0
  20. package/docs/assets/search.js +1 -1
  21. package/docs/assets/style.css +826 -826
  22. package/docs/classes/ApiError.html +22 -17
  23. package/docs/classes/AsyncJwt.html +16 -17
  24. package/docs/classes/Controller.html +42 -24
  25. package/docs/classes/Jwt.html +16 -17
  26. package/docs/classes/Memcached.html +31 -38
  27. package/docs/classes/Model.html +24 -7
  28. package/docs/classes/Server.html +25 -25
  29. package/docs/classes/Ssr.html +13 -11
  30. package/docs/classes/Web.html +10 -3
  31. package/docs/functions/action.html +2 -0
  32. package/docs/functions/body.html +2 -0
  33. package/docs/functions/codeToStatus.html +2 -0
  34. package/docs/functions/config.html +2 -0
  35. package/docs/functions/connection.html +2 -0
  36. package/docs/functions/context.html +2 -0
  37. package/docs/functions/controller-1.html +2 -0
  38. package/docs/functions/cookies.html +2 -0
  39. package/docs/functions/db.html +2 -0
  40. package/docs/functions/headers.html +2 -0
  41. package/docs/functions/home.html +2 -0
  42. package/docs/functions/hostname.html +2 -0
  43. package/docs/functions/http.html +4 -0
  44. package/docs/functions/init.html +2 -0
  45. package/docs/functions/json.html +3 -0
  46. package/docs/functions/logerror.html +3 -0
  47. package/docs/functions/method.html +2 -0
  48. package/docs/functions/mixin.html +5 -0
  49. package/docs/functions/mount.html +2 -0
  50. package/docs/functions/pool.html +2 -0
  51. package/docs/functions/protocol.html +2 -0
  52. package/docs/functions/request.html +2 -0
  53. package/docs/functions/selectControllersSchema.html +1 -0
  54. package/docs/functions/stream.html +2 -0
  55. package/docs/functions/subaction.html +2 -0
  56. package/docs/functions/url.html +2 -0
  57. package/docs/functions/xml.html +3 -0
  58. package/docs/index.html +8 -16
  59. package/docs/interfaces/ApiErrorMessage.html +6 -1
  60. package/docs/interfaces/ContextSsr.html +22 -19
  61. package/docs/interfaces/ContextWeb.html +7 -1
  62. package/docs/interfaces/OptionsSsr.html +3 -1
  63. package/docs/interfaces/OptionsWeb.html +6 -1
  64. package/docs/interfaces/ResponseOptions.html +4 -1
  65. package/docs/interfaces/Route.html +4 -1
  66. package/docs/interfaces/Schema.html +3 -1
  67. package/docs/interfaces/ServerHandler.html +4 -1
  68. package/docs/interfaces/ServerOptions.html +8 -1
  69. package/docs/interfaces/ServerWebsocket.html +4 -1
  70. package/docs/modules.html +50 -85
  71. package/docs/types/ServerRoutes.html +1 -0
  72. package/docs/variables/helpers.html +31 -0
  73. package/index.d.ts +30 -109
  74. package/index.js +4 -1965
  75. package/index.mjs +57 -0
  76. package/jsonBody.js +1 -27
  77. package/jsonBody.mjs +1 -0
  78. package/multipartBody.d.ts +1 -1
  79. package/multipartBody.js +1 -48
  80. package/multipartBody.mjs +1 -0
  81. package/package.json +11 -18
  82. package/readConfig.js +1 -17
  83. package/readConfig.mjs +1 -0
  84. package/readConfigSync.js +1 -18
  85. package/readConfigSync.mjs +1 -0
  86. package/staticBody.js +1 -207
  87. package/staticBody.mjs +1 -0
  88. package/urlencodedBody.js +1 -32
  89. package/urlencodedBody.mjs +1 -0
  90. package/ApiError-b517f53a.js +0 -37
  91. package/cookieParse-49f1da46.js +0 -25
  92. package/decoders-ee9f4396.js +0 -18
  93. package/docs/assets/icons.css +0 -1043
  94. package/docs/assets/icons.png +0 -0
  95. package/docs/assets/icons@2x.png +0 -0
  96. package/docs/assets/widgets.png +0 -0
  97. package/docs/assets/widgets@2x.png +0 -0
package/ApiError.d.ts CHANGED
@@ -1,6 +1,3 @@
1
- /**
2
- * Input params of error
3
- */
4
1
  interface ApiErrorMessage {
5
2
  message?: string;
6
3
  code?: number;
@@ -8,43 +5,18 @@ interface ApiErrorMessage {
8
5
  data?: any;
9
6
  headers?: Record<string, string>;
10
7
  }
11
- /**
12
- * @class Api Error
13
- * @description Base error class for @jwn-js
14
- */
15
8
  declare class ApiError<T extends any = Record<string, any>> extends Error {
16
9
  statusCode: number;
17
10
  code: number;
18
11
  data: T;
19
12
  headers: Record<string, string>;
20
- /**
21
- * @constructor
22
- * @param message
23
- * @param code
24
- * @param statusCode
25
- */
26
13
  constructor(message?: string, code?: number, statusCode?: number);
27
14
  constructor(params: ApiErrorMessage | string, code?: number, statusCode?: number);
28
- /**
29
- * Get error message
30
- */
31
15
  getMessage(): string;
32
- /**
33
- * Get internal status code
34
- */
35
16
  getStatusCode(): number;
36
- /**
37
- * Get internal error code
38
- */
39
17
  getCode(): number;
40
- /**
41
- * Get error data
42
- */
43
18
  getData(): T;
44
- /**
45
- * Get error headers
46
- */
47
19
  getHeaders(): Record<string, string>;
48
20
  }
49
21
 
50
- export { ApiError, ApiErrorMessage };
22
+ export { ApiError, type ApiErrorMessage };
package/ApiError.js CHANGED
@@ -1,39 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- class ApiError extends Error {
6
- constructor(params = "", code = 0, statusCode = 404) {
7
- super();
8
- let paramsObj = {};
9
- if (typeof params === "string") {
10
- paramsObj.message = params;
11
- paramsObj.code = code;
12
- paramsObj.statusCode = statusCode;
13
- } else {
14
- paramsObj = params;
15
- }
16
- this.statusCode = paramsObj.statusCode ?? 404;
17
- this.code = paramsObj.code ?? 0;
18
- this.message = paramsObj.message ?? "";
19
- this.data = paramsObj.data ?? {};
20
- this.headers = paramsObj.headers ?? {};
21
- }
22
- getMessage() {
23
- return this.message;
24
- }
25
- getStatusCode() {
26
- return this.statusCode;
27
- }
28
- getCode() {
29
- return this.code;
30
- }
31
- getData() {
32
- return this.data;
33
- }
34
- getHeaders() {
35
- return this.headers;
36
- }
37
- }
38
-
39
- exports.ApiError = ApiError;
1
+ "use strict";class a extends Error{constructor(t="",s=0,r=404){super();let e={};typeof t=="string"?(e.message=t,e.code=s,e.statusCode=r):e=t,this.statusCode=e.statusCode??404,this.code=e.code??0,this.message=e.message??"",this.data=e.data??{},this.headers=e.headers??{}}getMessage(){return this.message}getStatusCode(){return this.statusCode}getCode(){return this.code}getData(){return this.data}getHeaders(){return this.headers}}exports.ApiError=a;
package/ApiError.mjs ADDED
@@ -0,0 +1 @@
1
+ class a extends Error{constructor(t="",s=0,r=404){super();let e={};typeof t=="string"?(e.message=t,e.code=s,e.statusCode=r):e=t,this.statusCode=e.statusCode??404,this.code=e.code??0,this.message=e.message??"",this.data=e.data??{},this.headers=e.headers??{}}getMessage(){return this.message}getStatusCode(){return this.statusCode}getCode(){return this.code}getData(){return this.data}getHeaders(){return this.headers}}export{a as ApiError};
@@ -0,0 +1 @@
1
+ import l from"crypto";const i=e=>e.replace(/\+/ig,"-").replace(/\//ig,"_").replace(/=+$/,""),h=e=>e.replace(/-/ig,"+").replace(/_/ig,"/"),o=e=>i(Buffer.from(JSON.stringify(e)).toString("base64")),c=e=>JSON.parse(Buffer.from(h(e),"base64").toString());class g{constructor(r,t){this.algorithm="SHA256",this.secret=r,this.algorithm=t?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","")}verify(r){if(!r)return!1;const t=r.split(".");return i(l.createHmac(this.algorithm,this.secret).update(`${t[0]}.${t[1]}`).digest("base64"))===t[2]}sign(r){const t=o({alg:this.algorithm.replace("SHA","HS"),typ:"JWT"}),s=o(r),a=i(l.createHmac(this.algorithm,this.secret).update(`${t}.${s}`).digest("base64"));return`${t}.${s}.${a}`}decode(r){const t=(r||"").split("."),s=c(t[0]),a=c(t[1]);return{head:s,body:a}}}export{g as J,c as f,o as t,i as u};
@@ -0,0 +1 @@
1
+ "use strict";var c=require("crypto");const i=t=>t.replace(/\+/ig,"-").replace(/\//ig,"_").replace(/=+$/,""),h=t=>t.replace(/-/ig,"+").replace(/_/ig,"/"),o=t=>i(Buffer.from(JSON.stringify(t)).toString("base64")),l=t=>JSON.parse(Buffer.from(h(t),"base64").toString());class g{constructor(r,e){this.algorithm="SHA256",this.secret=r,this.algorithm=e?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","")}verify(r){if(!r)return!1;const e=r.split(".");return i(c.createHmac(this.algorithm,this.secret).update(`${e[0]}.${e[1]}`).digest("base64"))===e[2]}sign(r){const e=o({alg:this.algorithm.replace("SHA","HS"),typ:"JWT"}),s=o(r),a=i(c.createHmac(this.algorithm,this.secret).update(`${e}.${s}`).digest("base64"));return`${e}.${s}.${a}`}decode(r){const e=(r||"").split("."),s=l(e[0]),a=l(e[1]);return{head:s,body:a}}}exports.Jwt=g,exports.fromBase64url=l,exports.toBase64url=o,exports.urlEncode=i;
package/Jwt.js CHANGED
@@ -1,44 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var crypto = require('crypto');
6
- var decoders = require('./decoders-ee9f4396.js');
7
-
8
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
-
10
- var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
11
-
12
- class Jwt {
13
- constructor(secret, opt) {
14
- this.algorithm = "SHA256";
15
- this.secret = secret;
16
- this.algorithm = opt?.algorithm || this.algorithm;
17
- this.algorithm = this.algorithm.replace("-", "");
18
- }
19
- verify(jwt) {
20
- if (!jwt) {
21
- return false;
22
- }
23
- const parts = jwt.split(".");
24
- const signature = decoders.urlEncode(crypto__default["default"].createHmac(this.algorithm, this.secret).update(`${parts[0]}.${parts[1]}`).digest("base64"));
25
- return signature === parts[2];
26
- }
27
- sign(data) {
28
- const head = decoders.toBase64url({
29
- alg: this.algorithm.replace("SHA", "HS"),
30
- typ: "JWT"
31
- });
32
- const body = decoders.toBase64url(data);
33
- const signature = decoders.urlEncode(crypto__default["default"].createHmac(this.algorithm, this.secret).update(`${head}.${body}`).digest("base64"));
34
- return `${head}.${body}.${signature}`;
35
- }
36
- decode(jwt) {
37
- const parts = (jwt || "").split(".");
38
- const head = decoders.fromBase64url(parts[0]);
39
- const body = decoders.fromBase64url(parts[1]);
40
- return { head, body };
41
- }
42
- }
43
-
44
- exports.Jwt = Jwt;
1
+ "use strict";require("crypto");var r=require("./Jwt-CDdbxwvH.js");exports.Jwt=r.Jwt;
package/Jwt.mjs ADDED
@@ -0,0 +1 @@
1
+ import"crypto";import{J as m}from"./Jwt-7tQL-rwa.js";export{m as Jwt};
package/Memcached.js CHANGED
@@ -1,124 +1,9 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- class Memcached {
6
- constructor(memjs, specialHeaders = { "x-cache": "memcached-js" }, maxKeyLength = 160, debug = 0) {
7
- this.prefix = "";
8
- this.memjs = memjs;
9
- this.specialHeaders = specialHeaders;
10
- this.maxKeyLength = maxKeyLength;
11
- this.debug = debug;
12
- this.prefix = process.env.NODE_ENV !== "production" ? "dev::" : "";
13
- }
14
- isClient() {
15
- return !!this.memjs;
16
- }
17
- isConnectedServers() {
18
- if (!this.isClient()) {
19
- return false;
20
- }
21
- const servers = this.memjs?.servers || [];
22
- for (const server of servers) {
23
- if (server.connected) {
24
- return true;
25
- }
26
- }
27
- return false;
28
- }
29
- async setValue(key, value, expires) {
30
- if ((expires || expires === 0) && key.length <= this.maxKeyLength && this.memjs) {
31
- try {
32
- await this.memjs.set(`${this.prefix}${key}`, Buffer.from(value), { expires });
33
- } catch (e) {
34
- if (this.debug) {
35
- console.log(e);
36
- }
37
- }
38
- }
39
- }
40
- async getValue(key) {
41
- if (key.length <= this.maxKeyLength && this.memjs) {
42
- try {
43
- const obj = await this.memjs.get(`${this.prefix}${key}`);
44
- const result = typeof obj === "object" ? obj?.value : obj;
45
- if (!result) {
46
- return null;
47
- }
48
- return result;
49
- } catch (e) {
50
- if (this.debug) {
51
- console.log(e);
52
- }
53
- }
54
- }
55
- return null;
56
- }
57
- async deleteValue(key) {
58
- if (key.length <= this.maxKeyLength && this.memjs) {
59
- try {
60
- return this.memjs.delete(`${this.prefix}${key}`);
61
- } catch (e) {
62
- if (this.debug) {
63
- console.log(e);
64
- }
65
- }
66
- }
67
- return false;
68
- }
69
- async setPage(url, headers, data, expires) {
70
- if ((expires || expires === 0) && url.length <= this.maxKeyLength && this.memjs) {
71
- try {
72
- headers = this.objectKeysToLower(headers);
73
- delete headers["set-cookie"];
74
- const headersString = Object.entries(headers).map((v) => v.join(":")).join("\r\n");
75
- const memjsHeaders = "EXTRACT_HEADERS\r\n" + headersString + "\r\n\r\n";
76
- const toMamcache = Buffer.concat([Buffer.from(memjsHeaders), Buffer.from(data)]);
77
- const key = /^http/.test(url) ? url : `${this.prefix}${url}`;
78
- await this.memjs.set(key, toMamcache, { expires });
79
- } catch (e) {
80
- if (this.debug) {
81
- console.log(e);
82
- }
83
- }
84
- }
85
- }
86
- async getPage(url) {
87
- if (url.length <= this.maxKeyLength && this.memjs) {
88
- try {
89
- let headers = {};
90
- const key = /^http/.test(url) ? url : `${this.prefix}${url}`;
91
- const obj = await this.memjs.get(key);
92
- const result = typeof obj === "object" ? obj?.value : obj;
93
- if (!result) {
94
- return null;
95
- }
96
- const memData = Buffer.from(result);
97
- const start = memData.indexOf(Buffer.from("EXTRACT_HEADERS\r\n"));
98
- const end = memData.indexOf(Buffer.from("\r\n\r\n"));
99
- if (start < 0 || end < 0) {
100
- return null;
101
- }
102
- const arr = memData.subarray(start, end).toString().split("\r\n");
103
- arr.shift();
104
- arr.map((row) => {
105
- const [index, value] = row.split(":");
106
- headers[index] = value;
107
- });
108
- headers = Object.assign(headers, this.specialHeaders);
109
- const data = memData.subarray(end + 4);
110
- return { headers, data };
111
- } catch (e) {
112
- if (this.debug) {
113
- console.log(e);
114
- }
115
- }
116
- }
117
- return null;
118
- }
119
- objectKeysToLower(o) {
120
- return Object.keys(o).reduce((c, k) => (c[k.toLowerCase()] = o[k], c), {});
121
- }
122
- }
123
-
124
- exports.Memcached = Memcached;
1
+ "use strict";class u{constructor(t,e={"x-cache":"memcached-js"},s=160,r=0){this.prefix="",this.memjs=t,this.specialHeaders=e,this.maxKeyLength=s,this.debug=r,this.prefix=process.env.NODE_ENV!=="production"?"dev::":""}isClient(){return!!this.memjs}isConnectedServers(){if(!this.isClient())return!1;const t=this.memjs?.servers||[];for(const e of t)if(e.connected)return!0;return!1}async setValue(t,e,s){if((s||s===0)&&t.length<=this.maxKeyLength&&this.memjs)try{await this.memjs.set(`${this.prefix}${t}`,Buffer.from(e),{expires:s})}catch(r){this.debug&&console.log(r)}}async getValue(t){if(t.length<=this.maxKeyLength&&this.memjs)try{const e=await this.memjs.get(`${this.prefix}${t}`);return(typeof e=="object"?e?.value:e)||null}catch(e){this.debug&&console.log(e)}return null}async deleteValue(t){if(t.length<=this.maxKeyLength&&this.memjs)try{return this.memjs.delete(`${this.prefix}${t}`)}catch(e){this.debug&&console.log(e)}return!1}async setPage(t,e,s,r){if((r||r===0)&&t.length<=this.maxKeyLength&&this.memjs)try{e=this.objectKeysToLower(e),delete e["set-cookie"];const i=`EXTRACT_HEADERS\r
2
+ `+Object.entries(e).map(h=>h.join(":")).join(`\r
3
+ `)+`\r
4
+ \r
5
+ `,n=Buffer.concat([Buffer.from(i),Buffer.from(s)]),c=/^http/.test(t)?t:`${this.prefix}${t}`;await this.memjs.set(c,n,{expires:r})}catch(i){this.debug&&console.log(i)}}async getPage(t){if(t.length<=this.maxKeyLength&&this.memjs)try{let e={};const s=/^http/.test(t)?t:`${this.prefix}${t}`,r=await this.memjs.get(s),i=typeof r=="object"?r?.value:r;if(!i)return null;const n=Buffer.from(i),c=n.indexOf(Buffer.from(`EXTRACT_HEADERS\r
6
+ `)),h=n.indexOf(Buffer.from(`\r
7
+ \r
8
+ `));if(c<0||h<0)return null;const o=n.subarray(c,h).toString().split(`\r
9
+ `);o.shift(),o.map(m=>{const[f,l]=m.split(":");e[f]=l}),e=Object.assign(e,this.specialHeaders);const a=n.subarray(h+4);return{headers:e,data:a}}catch(e){this.debug&&console.log(e)}return null}objectKeysToLower(t){return Object.keys(t).reduce((e,s)=>(e[s.toLowerCase()]=t[s],e),{})}}exports.Memcached=u;
package/Memcached.mjs ADDED
@@ -0,0 +1,9 @@
1
+ class u{constructor(t,e={"x-cache":"memcached-js"},s=160,r=0){this.prefix="",this.memjs=t,this.specialHeaders=e,this.maxKeyLength=s,this.debug=r,this.prefix=process.env.NODE_ENV!=="production"?"dev::":""}isClient(){return!!this.memjs}isConnectedServers(){if(!this.isClient())return!1;const t=this.memjs?.servers||[];for(const e of t)if(e.connected)return!0;return!1}async setValue(t,e,s){if((s||s===0)&&t.length<=this.maxKeyLength&&this.memjs)try{await this.memjs.set(`${this.prefix}${t}`,Buffer.from(e),{expires:s})}catch(r){this.debug&&console.log(r)}}async getValue(t){if(t.length<=this.maxKeyLength&&this.memjs)try{const e=await this.memjs.get(`${this.prefix}${t}`);return(typeof e=="object"?e?.value:e)||null}catch(e){this.debug&&console.log(e)}return null}async deleteValue(t){if(t.length<=this.maxKeyLength&&this.memjs)try{return this.memjs.delete(`${this.prefix}${t}`)}catch(e){this.debug&&console.log(e)}return!1}async setPage(t,e,s,r){if((r||r===0)&&t.length<=this.maxKeyLength&&this.memjs)try{e=this.objectKeysToLower(e),delete e["set-cookie"];const i=`EXTRACT_HEADERS\r
2
+ `+Object.entries(e).map(h=>h.join(":")).join(`\r
3
+ `)+`\r
4
+ \r
5
+ `,n=Buffer.concat([Buffer.from(i),Buffer.from(s)]),o=/^http/.test(t)?t:`${this.prefix}${t}`;await this.memjs.set(o,n,{expires:r})}catch(i){this.debug&&console.log(i)}}async getPage(t){if(t.length<=this.maxKeyLength&&this.memjs)try{let e={};const s=/^http/.test(t)?t:`${this.prefix}${t}`,r=await this.memjs.get(s),i=typeof r=="object"?r?.value:r;if(!i)return null;const n=Buffer.from(i),o=n.indexOf(Buffer.from(`EXTRACT_HEADERS\r
6
+ `)),h=n.indexOf(Buffer.from(`\r
7
+ \r
8
+ `));if(o<0||h<0)return null;const c=n.subarray(o,h).toString().split(`\r
9
+ `);c.shift(),c.map(m=>{const[f,l]=m.split(":");e[f]=l}),e=Object.assign(e,this.specialHeaders);const a=n.subarray(h+4);return{headers:e,data:a}}catch(e){this.debug&&console.log(e)}return null}objectKeysToLower(t){return Object.keys(t).reduce((e,s)=>(e[s.toLowerCase()]=t[s],e),{})}}export{u as Memcached};
package/Server.d.ts CHANGED
@@ -5,7 +5,7 @@ declare module 'uWebSockets.js' {
5
5
  cookies: Record<string, any>;
6
6
  }
7
7
  }
8
- declare type HandlerFunction = (res: HttpResponse, req: HttpRequest, next: CallableFunction) => void | Promise<void | boolean | Error | string>;
8
+ type HandlerFunction = (res: HttpResponse, req: HttpRequest, next: CallableFunction) => void | Promise<void | boolean | Error | string>;
9
9
  interface Handler {
10
10
  method?: 'any' | 'connect' | 'del' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace';
11
11
  pattern?: RecognizedString;
@@ -142,4 +142,4 @@ declare class Server {
142
142
  private _lookup;
143
143
  }
144
144
 
145
- export { Handler, HandlerFunction, Options, Routes, Server, WebSocket, codeToStatus };
145
+ export { type Handler, type HandlerFunction, type Options, type Routes, Server, type WebSocket, codeToStatus };
package/Server.js CHANGED
@@ -1,239 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var dns = require('dns');
6
- var uws = require('uWebSockets.js');
7
- var cookieParse = require('./cookieParse-49f1da46.js');
8
-
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
-
11
- var dns__default = /*#__PURE__*/_interopDefaultLegacy(dns);
12
- var uws__default = /*#__PURE__*/_interopDefaultLegacy(uws);
13
-
14
- const status = {
15
- 100: "100 Continue",
16
- 101: "101 Switching Protocols",
17
- 200: "200 OK",
18
- 201: "201 Created",
19
- 202: "202 Accepted",
20
- 203: "203 Non-Authoritative Information",
21
- 204: "No Content",
22
- 205: "205 Reset Content",
23
- 206: "206 Partial Content",
24
- 300: "300 Multiple Choices",
25
- 301: "301 Moved Permanently",
26
- 302: "302 Found",
27
- 303: "303 See Other",
28
- 304: "304 Not Modified",
29
- 305: "305 Use Proxy",
30
- 306: "306 (Unused)",
31
- 307: "307 Temporary Redirect",
32
- 400: "400 Bad Request",
33
- 401: "401 Unauthorized",
34
- 402: "402 Payment Required",
35
- 403: "403 Forbidden",
36
- 404: "404 Not Found",
37
- 405: "405 Method Not Allowed",
38
- 406: "406 Not Acceptable",
39
- 407: "407 Proxy Authentication Required",
40
- 408: "408 Request Timeout",
41
- 409: "409 Conflict",
42
- 410: "410 Gone",
43
- 411: "411 Length Required",
44
- 412: "412 Precondition Failed",
45
- 413: "413 Request Entity Too Large",
46
- 414: "414 Request-URI Too Long",
47
- 415: "415 Unsupported Media Type",
48
- 416: "416 Requested Range Not Satisfiable",
49
- 417: "417 Expectation Failed",
50
- 500: "500 Internal Server Error",
51
- 501: "501 Not Implemented",
52
- 502: "502 Bad Gateway",
53
- 503: "503 Service Unavailable",
54
- 504: "504 Gateway Timeout",
55
- 505: "505 HTTP Version Not Supported"
56
- };
57
- const codeToStatus = (code) => {
58
- return status.hasOwnProperty(code) ? status[code] : `${code}`;
59
- };
60
- class Server {
61
- constructor(options) {
62
- this._logLevel = "info";
63
- this._socket = null;
64
- this._timeout = 0;
65
- this._routes = [];
66
- this._host = "localhost";
67
- this._port = 3e3;
68
- this._mode = "production";
69
- this._appOptions = {};
70
- this._defaultRoute = {
71
- method: "get",
72
- pattern: "/*",
73
- handler: (res, req, next) => next()
74
- };
75
- this._routes = options.routes || this._routes;
76
- this._host = options.host || this._host;
77
- this._port = options.port || this._port;
78
- this._timeout = options.timeout || this._timeout;
79
- this._mode = options.mode || this._mode;
80
- this._appOptions = options.appOptions || this._appOptions;
81
- this._logLevel = options.logLevel || this._logLevel;
82
- }
83
- getApp() {
84
- return this._app;
85
- }
86
- app() {
87
- this._protocol = "http";
88
- this._app = uws__default["default"].App(this._appOptions);
89
- return this;
90
- }
91
- sslApp() {
92
- this._protocol = "https";
93
- this._app = uws__default["default"].SSLApp(this._appOptions);
94
- return this;
95
- }
96
- push(route) {
97
- this._routes.push(route);
98
- return this;
99
- }
100
- unshift(route) {
101
- this._routes.unshift(route);
102
- return this;
103
- }
104
- listen(host, port, fn = () => {
105
- }) {
106
- if (typeof port === "number") {
107
- this._port = port;
108
- this._host = host;
109
- } else if (typeof host === "number") {
110
- if (typeof port === "function") {
111
- fn = port;
112
- }
113
- this._port = host;
114
- } else if (typeof host === "function") {
115
- fn = host;
116
- }
117
- if (!this._app) {
118
- throw new Error("Create app or sslApp first");
119
- }
120
- this._lookup(this._host, (ip) => {
121
- for (let route of this._routes) {
122
- route = typeof route === "function" ? { handler: route } : route;
123
- route = Object.assign({}, this._defaultRoute, route);
124
- switch (route.method) {
125
- case "ws":
126
- this._app[route.method](route.pattern, route.behavior);
127
- break;
128
- default:
129
- const routeHandler = route;
130
- this._app[routeHandler.method](route.pattern, (res, req) => {
131
- res.redirect = (url, code = 307) => this.constructor._redirect(res, req, url, code);
132
- req.cookies = cookieParse.cookieParse(req.getHeader("cookie"));
133
- Promise.race([
134
- this._abortTimeout(res, req),
135
- this._createHandler(res, req, routeHandler.handler)
136
- ]);
137
- });
138
- }
139
- }
140
- this._app.listen(ip, this._port, (listenSocket) => {
141
- fn(listenSocket);
142
- if (listenSocket) {
143
- this._socket = listenSocket;
144
- if (this._mode === "development") {
145
- ["info"].includes(this._logLevel) && console.log(`Listening ${this._protocol}://${this._host}:${this._port}`);
146
- }
147
- } else {
148
- ["info", "warn", "error"].includes(this._logLevel) && console.error(`Error start server on ${this._protocol}://${this._host}:${this._port}`);
149
- }
150
- });
151
- });
152
- return this;
153
- }
154
- async close() {
155
- if (this._socket) {
156
- await uws__default["default"].us_listen_socket_close(this._socket);
157
- while (true) {
158
- await new Promise((resolve) => setTimeout(resolve, 50));
159
- if (await this.socketPort() < 0) {
160
- break;
161
- }
162
- }
163
- this._socket = null;
164
- }
165
- return this;
166
- }
167
- async socketPort() {
168
- if (!this._socket) {
169
- return -1;
170
- }
171
- return uws__default["default"].us_socket_local_port(this._socket);
172
- }
173
- _createHandler(res, req, fn) {
174
- return new Promise(async (resolve) => {
175
- const end = () => {
176
- clearTimeout(this._timeoutId);
177
- resolve();
178
- };
179
- try {
180
- const next = (param, code = 307) => {
181
- if (typeof param === "boolean") {
182
- req.setYield(param);
183
- }
184
- if (param instanceof Error) {
185
- throw param;
186
- }
187
- if (typeof param === "string") {
188
- res.redirect(param, code);
189
- }
190
- end();
191
- };
192
- const result = fn(res, req, next);
193
- if (result instanceof Promise) {
194
- next(await result);
195
- }
196
- } catch (e) {
197
- ["info", "warn", "error"].includes(this._logLevel) && console.error(e);
198
- const body = this._mode === "development" ? e.message : "";
199
- try {
200
- res.writeStatus("404 Not Found").end(body);
201
- } catch (e2) {
202
- }
203
- end();
204
- }
205
- });
206
- }
207
- static _redirect(res, req, url, code = 307) {
208
- let status2 = "307 Temporary Redirect";
209
- if (code === 301) {
210
- status2 = "301 Moved Permanently";
211
- }
212
- res.writeStatus(status2).writeHeader("location", url).end();
213
- }
214
- _abortTimeout(res, req) {
215
- return new Promise((resolve) => {
216
- if (this._timeout && !req.getHeader("x-no-timeout")) {
217
- this._timeoutId = setTimeout(() => {
218
- try {
219
- res.writeStatus("408 Request Timeout").end();
220
- resolve();
221
- } catch (e) {
222
- }
223
- }, this._timeout);
224
- }
225
- });
226
- }
227
- _lookup(host, resolve) {
228
- dns__default["default"].lookup(this._host, (err, addresses) => {
229
- if (err) {
230
- ["info", "warn", "error"].includes(this._logLevel) && console.log(`${this._host} error: ${err.message}`);
231
- } else {
232
- resolve(Buffer.from(addresses));
233
- }
234
- });
235
- }
236
- }
237
-
238
- exports.Server = Server;
239
- exports.codeToStatus = codeToStatus;
1
+ "use strict";var l=require("dns"),p=require("uWebSockets.js"),d=require("./cookieParse.js");const c={100:"100 Continue",101:"101 Switching Protocols",200:"200 OK",201:"201 Created",202:"202 Accepted",203:"203 Non-Authoritative Information",204:"No Content",205:"205 Reset Content",206:"206 Partial Content",300:"300 Multiple Choices",301:"301 Moved Permanently",302:"302 Found",303:"303 See Other",304:"304 Not Modified",305:"305 Use Proxy",306:"306 (Unused)",307:"307 Temporary Redirect",400:"400 Bad Request",401:"401 Unauthorized",402:"402 Payment Required",403:"403 Forbidden",404:"404 Not Found",405:"405 Method Not Allowed",406:"406 Not Acceptable",407:"407 Proxy Authentication Required",408:"408 Request Timeout",409:"409 Conflict",410:"410 Gone",411:"411 Length Required",412:"412 Precondition Failed",413:"413 Request Entity Too Large",414:"414 Request-URI Too Long",415:"415 Unsupported Media Type",416:"416 Requested Range Not Satisfiable",417:"417 Expectation Failed",500:"500 Internal Server Error",501:"501 Not Implemented",502:"502 Bad Gateway",503:"503 Service Unavailable",504:"504 Gateway Timeout",505:"505 HTTP Version Not Supported"},m=a=>c.hasOwnProperty(a)?c[a]:`${a}`;class f{constructor(t){this._logLevel="info",this._socket=null,this._timeout=0,this._routes=[],this._host="localhost",this._port=3e3,this._mode="production",this._appOptions={},this._defaultRoute={method:"get",pattern:"/*",handler:(o,s,r)=>r()},this._routes=t.routes||this._routes,this._host=t.host||this._host,this._port=t.port||this._port,this._timeout=t.timeout||this._timeout,this._mode=t.mode||this._mode,this._appOptions=t.appOptions||this._appOptions,this._logLevel=t.logLevel||this._logLevel}getApp(){return this._app}app(){return this._protocol="http",this._app=p.App(this._appOptions),this}sslApp(){return this._protocol="https",this._app=p.SSLApp(this._appOptions),this}push(t){return this._routes.push(t),this}unshift(t){return this._routes.unshift(t),this}listen(t,o,s=()=>{}){if(typeof o=="number"?(this._port=o,this._host=t):typeof t=="number"?(typeof o=="function"&&(s=o),this._port=t):typeof t=="function"&&(s=t),!this._app)throw new Error("Create app or sslApp first");return this._lookup(this._host,r=>{for(let e of this._routes)switch(e=typeof e=="function"?{handler:e}:e,e=Object.assign({},this._defaultRoute,e),e.method){case"ws":this._app[e.method](e.pattern,e.behavior);break;default:const h=e;this._app[h.method](e.pattern,(n,i)=>{n.redirect=(u,_=307)=>this.constructor._redirect(n,i,u,_),i.cookies=d.cookieParse(i.getHeader("cookie")),Promise.race([this._abortTimeout(n,i),this._createHandler(n,i,h.handler)])})}this._app.listen(r,this._port,e=>{s(e),e?(this._socket=e,this._mode==="development"&&["info"].includes(this._logLevel)&&console.log(`Listening ${this._protocol}://${this._host}:${this._port}`)):["info","warn","error"].includes(this._logLevel)&&console.error(`Error start server on ${this._protocol}://${this._host}:${this._port}`)})}),this}async close(){if(this._socket){for(await p.us_listen_socket_close(this._socket);await new Promise(t=>setTimeout(t,50)),!(await this.socketPort()<0););this._socket=null}return this}async socketPort(){return this._socket?p.us_socket_local_port(this._socket):-1}_createHandler(t,o,s){return new Promise(async r=>{const e=()=>{clearTimeout(this._timeoutId),r()};try{const h=(i,u=307)=>{if(typeof i=="boolean"&&o.setYield(i),i instanceof Error)throw i;typeof i=="string"&&t.redirect(i,u),e()},n=s(t,o,h);n instanceof Promise&&h(await n)}catch(h){["info","warn","error"].includes(this._logLevel)&&console.error(h);const n=this._mode==="development"?h.message:"";try{t.writeStatus("404 Not Found").end(n)}catch{}e()}})}static _redirect(t,o,s,r=307){let e="307 Temporary Redirect";r===301&&(e="301 Moved Permanently"),t.writeStatus(e).writeHeader("location",s).end()}_abortTimeout(t,o){return new Promise(s=>{this._timeout&&!o.getHeader("x-no-timeout")&&(this._timeoutId=setTimeout(()=>{try{t.writeStatus("408 Request Timeout").end(),s()}catch{}},this._timeout))})}_lookup(t,o){l.lookup(this._host,(s,r)=>{s?["info","warn","error"].includes(this._logLevel)&&console.log(`${this._host} error: ${s.message}`):o(Buffer.from(r))})}}exports.Server=f,exports.codeToStatus=m;
package/Server.mjs ADDED
@@ -0,0 +1 @@
1
+ import l from"dns";import p from"uWebSockets.js";import{cookieParse as d}from"./cookieParse.mjs";const c={100:"100 Continue",101:"101 Switching Protocols",200:"200 OK",201:"201 Created",202:"202 Accepted",203:"203 Non-Authoritative Information",204:"No Content",205:"205 Reset Content",206:"206 Partial Content",300:"300 Multiple Choices",301:"301 Moved Permanently",302:"302 Found",303:"303 See Other",304:"304 Not Modified",305:"305 Use Proxy",306:"306 (Unused)",307:"307 Temporary Redirect",400:"400 Bad Request",401:"401 Unauthorized",402:"402 Payment Required",403:"403 Forbidden",404:"404 Not Found",405:"405 Method Not Allowed",406:"406 Not Acceptable",407:"407 Proxy Authentication Required",408:"408 Request Timeout",409:"409 Conflict",410:"410 Gone",411:"411 Length Required",412:"412 Precondition Failed",413:"413 Request Entity Too Large",414:"414 Request-URI Too Long",415:"415 Unsupported Media Type",416:"416 Requested Range Not Satisfiable",417:"417 Expectation Failed",500:"500 Internal Server Error",501:"501 Not Implemented",502:"502 Bad Gateway",503:"503 Service Unavailable",504:"504 Gateway Timeout",505:"505 HTTP Version Not Supported"},m=a=>c.hasOwnProperty(a)?c[a]:`${a}`;class f{constructor(t){this._logLevel="info",this._socket=null,this._timeout=0,this._routes=[],this._host="localhost",this._port=3e3,this._mode="production",this._appOptions={},this._defaultRoute={method:"get",pattern:"/*",handler:(o,s,r)=>r()},this._routes=t.routes||this._routes,this._host=t.host||this._host,this._port=t.port||this._port,this._timeout=t.timeout||this._timeout,this._mode=t.mode||this._mode,this._appOptions=t.appOptions||this._appOptions,this._logLevel=t.logLevel||this._logLevel}getApp(){return this._app}app(){return this._protocol="http",this._app=p.App(this._appOptions),this}sslApp(){return this._protocol="https",this._app=p.SSLApp(this._appOptions),this}push(t){return this._routes.push(t),this}unshift(t){return this._routes.unshift(t),this}listen(t,o,s=()=>{}){if(typeof o=="number"?(this._port=o,this._host=t):typeof t=="number"?(typeof o=="function"&&(s=o),this._port=t):typeof t=="function"&&(s=t),!this._app)throw new Error("Create app or sslApp first");return this._lookup(this._host,r=>{for(let e of this._routes)switch(e=typeof e=="function"?{handler:e}:e,e=Object.assign({},this._defaultRoute,e),e.method){case"ws":this._app[e.method](e.pattern,e.behavior);break;default:const h=e;this._app[h.method](e.pattern,(n,i)=>{n.redirect=(u,_=307)=>this.constructor._redirect(n,i,u,_),i.cookies=d(i.getHeader("cookie")),Promise.race([this._abortTimeout(n,i),this._createHandler(n,i,h.handler)])})}this._app.listen(r,this._port,e=>{s(e),e?(this._socket=e,this._mode==="development"&&["info"].includes(this._logLevel)&&console.log(`Listening ${this._protocol}://${this._host}:${this._port}`)):["info","warn","error"].includes(this._logLevel)&&console.error(`Error start server on ${this._protocol}://${this._host}:${this._port}`)})}),this}async close(){if(this._socket){for(await p.us_listen_socket_close(this._socket);await new Promise(t=>setTimeout(t,50)),!(await this.socketPort()<0););this._socket=null}return this}async socketPort(){return this._socket?p.us_socket_local_port(this._socket):-1}_createHandler(t,o,s){return new Promise(async r=>{const e=()=>{clearTimeout(this._timeoutId),r()};try{const h=(i,u=307)=>{if(typeof i=="boolean"&&o.setYield(i),i instanceof Error)throw i;typeof i=="string"&&t.redirect(i,u),e()},n=s(t,o,h);n instanceof Promise&&h(await n)}catch(h){["info","warn","error"].includes(this._logLevel)&&console.error(h);const n=this._mode==="development"?h.message:"";try{t.writeStatus("404 Not Found").end(n)}catch{}e()}})}static _redirect(t,o,s,r=307){let e="307 Temporary Redirect";r===301&&(e="301 Moved Permanently"),t.writeStatus(e).writeHeader("location",s).end()}_abortTimeout(t,o){return new Promise(s=>{this._timeout&&!o.getHeader("x-no-timeout")&&(this._timeoutId=setTimeout(()=>{try{t.writeStatus("408 Request Timeout").end(),s()}catch{}},this._timeout))})}_lookup(t,o){l.lookup(this._host,(s,r)=>{s?["info","warn","error"].includes(this._logLevel)&&console.log(`${this._host} error: ${s.message}`):o(Buffer.from(r))})}}export{f as Server,m as codeToStatus};
package/cookieParse.js CHANGED
@@ -1,27 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const cookieParse = (str) => {
6
- if (!str) {
7
- return {};
8
- }
9
- return str.split(/; */).reduce((obj, str2) => {
10
- if (str2 === "") {
11
- return obj;
12
- }
13
- const eq = str2.indexOf("=");
14
- const key = eq > 0 ? str2.slice(0, eq) : str2;
15
- let val = eq > 0 ? str2.slice(eq + 1) : null;
16
- if (val != null) {
17
- try {
18
- val = decodeURIComponent(val);
19
- } catch (ex) {
20
- }
21
- }
22
- obj[key] = val;
23
- return obj;
24
- }, {});
25
- };
26
-
27
- exports.cookieParse = cookieParse;
1
+ "use strict";const s=c=>c?c.split(/; */).reduce((r,e)=>{if(e==="")return r;const t=e.indexOf("="),o=t>0?e.slice(0,t):e;let n=t>0?e.slice(t+1):null;if(n!=null)try{n=decodeURIComponent(n)}catch{}return r[o]=n,r},{}):{};exports.cookieParse=s;
@@ -0,0 +1 @@
1
+ const c=l=>l?l.split(/; */).reduce((r,t)=>{if(t==="")return r;const e=t.indexOf("="),o=e>0?t.slice(0,e):t;let n=e>0?t.slice(e+1):null;if(n!=null)try{n=decodeURIComponent(n)}catch{}return r[o]=n,r},{}):{};export{c as cookieParse};
package/cookieString.js CHANGED
@@ -1,24 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const cookieString = (name, value, options = {}) => {
6
- options = {
7
- path: "/",
8
- ...options
9
- };
10
- if (options.expires instanceof Date) {
11
- options.expires = options.expires.toUTCString();
12
- }
13
- let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);
14
- for (const optionKey in options) {
15
- updatedCookie += "; " + optionKey;
16
- const optionValue = options[optionKey];
17
- if (optionValue !== true) {
18
- updatedCookie += "=" + optionValue;
19
- }
20
- }
21
- return updatedCookie;
22
- };
23
-
24
- exports.cookieString = cookieString;
1
+ "use strict";const c=(i,r,n={})=>{n={path:"/",...n},n.expires instanceof Date&&(n.expires=n.expires.toUTCString());let t=encodeURIComponent(i)+"="+encodeURIComponent(r);for(const o in n){t+="; "+o;const e=n[o];e!==!0&&(t+="="+e)}return t};exports.cookieString=c;
@@ -0,0 +1 @@
1
+ const c=(r,i,n={})=>{n={path:"/",...n},n.expires instanceof Date&&(n.expires=n.expires.toUTCString());let o=encodeURIComponent(r)+"="+encodeURIComponent(i);for(const t in n){o+="; "+t;const e=n[t];e!==!0&&(o+="="+e)}return o};export{c as cookieString};