vortez 4.1.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.
Files changed (86) hide show
  1. package/.gitignore +13 -0
  2. package/LICENSE +201 -0
  3. package/Notes.md +12 -0
  4. package/README.md +372 -0
  5. package/build/Beta/JwtManager.d.ts +114 -0
  6. package/build/Beta/JwtManager.js +249 -0
  7. package/build/Beta/JwtManager.js.map +1 -0
  8. package/build/Beta/Mail.d.ts +60 -0
  9. package/build/Beta/Mail.js +192 -0
  10. package/build/Beta/Mail.js.map +1 -0
  11. package/build/Config.d.ts +39 -0
  12. package/build/Config.js +33 -0
  13. package/build/Config.js.map +1 -0
  14. package/build/ConsoleUI.d.ts +57 -0
  15. package/build/ConsoleUI.js +110 -0
  16. package/build/ConsoleUI.js.map +1 -0
  17. package/build/Debug.d.ts +154 -0
  18. package/build/Debug.js +256 -0
  19. package/build/Debug.js.map +1 -0
  20. package/build/LoggerManager/Logger.d.ts +23 -0
  21. package/build/LoggerManager/Logger.js +23 -0
  22. package/build/LoggerManager/Logger.js.map +1 -0
  23. package/build/LoggerManager/LoggerManager.d.ts +18 -0
  24. package/build/LoggerManager/LoggerManager.js +30 -0
  25. package/build/LoggerManager/LoggerManager.js.map +1 -0
  26. package/build/Server/BodyParser.d.ts +125 -0
  27. package/build/Server/BodyParser.js +162 -0
  28. package/build/Server/BodyParser.js.map +1 -0
  29. package/build/Server/Cookie.d.ts +72 -0
  30. package/build/Server/Cookie.js +102 -0
  31. package/build/Server/Cookie.js.map +1 -0
  32. package/build/Server/Request.d.ts +61 -0
  33. package/build/Server/Request.js +79 -0
  34. package/build/Server/Request.js.map +1 -0
  35. package/build/Server/Response.d.ts +90 -0
  36. package/build/Server/Response.js +241 -0
  37. package/build/Server/Response.js.map +1 -0
  38. package/build/Server/Rule.d.ts +81 -0
  39. package/build/Server/Rule.js +146 -0
  40. package/build/Server/Rule.js.map +1 -0
  41. package/build/Server/Server.d.ts +157 -0
  42. package/build/Server/Server.js +330 -0
  43. package/build/Server/Server.js.map +1 -0
  44. package/build/Server/Session.d.ts +66 -0
  45. package/build/Server/Session.js +97 -0
  46. package/build/Server/Session.js.map +1 -0
  47. package/build/Server/WebSocket/Chunk.d.ts +36 -0
  48. package/build/Server/WebSocket/Chunk.js +81 -0
  49. package/build/Server/WebSocket/Chunk.js.map +1 -0
  50. package/build/Server/WebSocket/WebSocket.d.ts +70 -0
  51. package/build/Server/WebSocket/WebSocket.js +184 -0
  52. package/build/Server/WebSocket/WebSocket.js.map +1 -0
  53. package/build/Template.d.ts +32 -0
  54. package/build/Template.js +69 -0
  55. package/build/Template.js.map +1 -0
  56. package/build/Utilities/Env.d.ts +75 -0
  57. package/build/Utilities/Env.js +123 -0
  58. package/build/Utilities/Env.js.map +1 -0
  59. package/build/Utilities/Path.d.ts +18 -0
  60. package/build/Utilities/Path.js +27 -0
  61. package/build/Utilities/Path.js.map +1 -0
  62. package/build/Utilities/Utilities.d.ts +147 -0
  63. package/build/Utilities/Utilities.js +110 -0
  64. package/build/Utilities/Utilities.js.map +1 -0
  65. package/build/Vortez.d.ts +20 -0
  66. package/build/Vortez.js +22 -0
  67. package/build/Vortez.js.map +1 -0
  68. package/changes.md +89 -0
  69. package/examples/in-docs.js +96 -0
  70. package/global/Source/Logo_960.png +0 -0
  71. package/global/Source/Logo_SM_960.png +0 -0
  72. package/global/Style/Template/Error.css +30 -0
  73. package/global/Style/Template/Folder.css +77 -0
  74. package/global/Style/Template/Template.css +128 -0
  75. package/global/Template/Error.vhtml +29 -0
  76. package/global/Template/Folder.vhtml +41 -0
  77. package/package.json +47 -0
  78. package/tests/Template/template.js +18 -0
  79. package/tests/Template/template.txt +13 -0
  80. package/tests/Template/template.vhtml +23 -0
  81. package/tests/debug.js +28 -0
  82. package/tests/jwtManager/jwtManager.js +110 -0
  83. package/tests/test.js +129 -0
  84. package/tests/test.vhtml +14 -0
  85. package/tests/utilities.js +28 -0
  86. package/tests/websocket.vhtml +86 -0
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @author NetFeez <codefeez.dev@gmail.com>
3
+ * @description Adds the Request form of `Vortez`.
4
+ * @license Apache-2.0
5
+ */
6
+ import URI from 'url';
7
+ import Cookie from './Cookie.js';
8
+ import Session from './Session.js';
9
+ import _BodyParser from './BodyParser.js';
10
+ export class Request {
11
+ /** Contains the request headers. */
12
+ headers;
13
+ /** Contains the request cookies. */
14
+ cookies;
15
+ /** Contains the POST data sent. */
16
+ searchParams;
17
+ /** Contains the IP address of the requester. */
18
+ ip;
19
+ /** Contains the request method. */
20
+ method;
21
+ /** Contains the POSTParser. */
22
+ session;
23
+ /** Contains the session of the device that made the request. */
24
+ body;
25
+ /** Contains the HTTP request received by the server. */
26
+ httpRequest;
27
+ /** Contains the request URL. */
28
+ url;
29
+ /** The UrlRule parameters */
30
+ ruleParams = {};
31
+ /**
32
+ * Creates the request form for `NetFeez-Labs/Server`.
33
+ * @param httpRequest - The HTTP request received by the server.
34
+ */
35
+ constructor(httpRequest) {
36
+ const forwardedIP = httpRequest.headers['x-forwarded-for'];
37
+ const remoteIP = httpRequest.socket.remoteAddress;
38
+ const method = httpRequest.method ?? 'GET';
39
+ const url = httpRequest.url ?? '/';
40
+ this.httpRequest = httpRequest;
41
+ this.ip = forwardedIP ? forwardedIP : remoteIP ? remoteIP : '0.0.0.0';
42
+ this.method = this.getMethod(method);
43
+ this.url = url.split('?')[0];
44
+ this.url = decodeURI(this.url.endsWith('/') ? this.url : this.url + '/');
45
+ this.headers = httpRequest.headers;
46
+ this.cookies = new Cookie(this.headers.cookie);
47
+ this.session = Session.getInstance(this.cookies);
48
+ this.searchParams = this.getSearchParams(url);
49
+ this.body = new Request.BodyParser(this.headers, this.httpRequest);
50
+ }
51
+ get post() { return this.body.parse(); }
52
+ /**
53
+ * Defines which method was used to make the request.
54
+ * @param method - The method used for the request.
55
+ */
56
+ getMethod(method) {
57
+ return method == 'POST'
58
+ ? 'POST'
59
+ : method == 'PUT' ? 'PUT'
60
+ : method == 'DELETE' ? 'DELETE'
61
+ : 'GET';
62
+ }
63
+ /**
64
+ * Retrieves the data sent via URL QUERY.
65
+ * @param Url - The URL received from the HTTP request.
66
+ */
67
+ getSearchParams(Url) {
68
+ let UrlObject = new URI.URL(`http://x.x${Url}`);
69
+ const searchParams = {};
70
+ UrlObject.searchParams.forEach((value, name) => searchParams[name] = value);
71
+ return searchParams;
72
+ }
73
+ }
74
+ (function (Request) {
75
+ Request.BodyParser = _BodyParser;
76
+ ;
77
+ })(Request || (Request = {}));
78
+ export default Request;
79
+ //# sourceMappingURL=Request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Request.js","sourceRoot":"","sources":["../../src/Server/Request.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,GAAG,MAAM,KAAK,CAAC;AAEtB,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,OAAO,MAAM,cAAc,CAAC;AACnC,OAAO,WAA2B,MAAM,iBAAiB,CAAC;AAE1D,MAAM,OAAO,OAAO;IACnB,oCAAoC;IAC7B,OAAO,CAAkB;IAChC,oCAAoC;IAC7B,OAAO,CAAS;IACvB,mCAAmC;IAC5B,YAAY,CAAuB;IAC1C,gDAAgD;IACzC,EAAE,CAAqB;IAC9B,mCAAmC;IAC5B,MAAM,CAAiB;IAC9B,+BAA+B;IACxB,OAAO,CAAU;IACxB,gEAAgE;IACxD,IAAI,CAAqB;IACjC,wDAAwD;IAChD,WAAW,CAAuB;IAC1C,gCAAgC;IACzB,GAAG,CAAS;IACnB,6BAA6B;IACtB,UAAU,GAAuB,EAAE,CAAC;IAC3C;;;OAGG;IACH,YAAmB,WAAiC;QAC7C,MAAM,WAAW,GAAG,WAAW,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;QAC3D,MAAM,QAAQ,GAAG,WAAW,CAAC,MAAM,CAAC,aAAa,CAAC;QAClD,MAAM,MAAM,GAAG,WAAW,CAAC,MAAM,IAAI,KAAK,CAAC;QAC3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K,CAAC,CAAC,CAAC,KAAK;gBACxB,CAAC,CAAC,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,QAAQ;oBAC/B,CAAC,CAAC,KAAK,CAAC;IACV,CAAC;IACD;;;OAGG;IACK,eAAe,CAAC,GAAW;QAClC,IAAI,SAAS,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,aAAa,GAAG,EAAE,CAAC,CAAC;QAChD,MAAM,YAAY,GAAyB,EAAE,CAAC;QAC9C,SAAS,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;QAC5E,OAAO,YAAY,CAAC;IACrB,CAAC;CACD;AAED,WAAiB,OAAO;IACT,kBAAU,GAAG,WAAW,CAAC;IAMa,CAAC;AAEtD,CAAC,EATgB,OAAO,KAAP,OAAO,QASvB;AAED,eAAe,OAAO,CAAC"}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @author NetFeez <codefeez.dev@gmail.com>
3
+ * @description Adds the response format to `Vortez`.
4
+ * @license Apache-2.0
5
+ */
6
+ import HTTP from 'http';
7
+ import FS from 'fs';
8
+ import Request from './Request.js';
9
+ import Config from '../Config.js';
10
+ export declare class Response {
11
+ /** Contains the request received by the server. */
12
+ request: Request;
13
+ /** Contains the list of server response templates. */
14
+ private templates;
15
+ /** Contains the response to be sent by the server. */
16
+ httpResponse: HTTP.ServerResponse;
17
+ /**
18
+ * Creates the `NetFeez-Labs/Server` response format.
19
+ * @param request - The request received by the server.
20
+ * @param httpResponse - The response to be sent by the server.
21
+ * @param templates - The list of server response templates.
22
+ */
23
+ constructor(request: Request, httpResponse: HTTP.ServerResponse, templates?: Config.Templates);
24
+ /**
25
+ * Generates headers for supported file types.
26
+ * More types will be supported over time.
27
+ * @param extension - The file extension.
28
+ */
29
+ generateHeaders(extension: string): Request.Headers;
30
+ /**
31
+ * Sends response headers.
32
+ * @param code - The HTTP status code.
33
+ * @param headers - The headers to send.
34
+ */
35
+ private sendHeaders;
36
+ /**
37
+ * Sends data as a response.
38
+ * @param data - The data to be sent.
39
+ * @param encode - The encoding used for the response.
40
+ */
41
+ send(data: Response.data, options?: Response.options): void;
42
+ /**
43
+ * Sends a file as a response.
44
+ * @param path - The file path to send.
45
+ * @param options - The response options.
46
+ * @throws If the file does not exist or is not accessible.
47
+ */
48
+ sendFile(path: string, options?: Response.options): Promise<void>;
49
+ /**
50
+ * Sends the listing of a folder as a response.
51
+ * @param basePath - The routing rule base path.
52
+ * @param relativePath - The relative path received in the request.
53
+ * @throws If the folder does not exist or is invalid.
54
+ */
55
+ sendFolder(basePath: string, relativePath: string): Promise<void>;
56
+ /**
57
+ * Sends a `.vhtml` template as a response.
58
+ * @param path - The template file path.
59
+ * @param data - The data to compile the template with.
60
+ * @param options - The response options.
61
+ * @throws If the template cannot be loaded.
62
+ */
63
+ sendTemplate(path: string, data: object, options?: Response.options): Promise<void>;
64
+ /**
65
+ * Sends data in JSON format.
66
+ * @param data - The data to send.
67
+ * @param options - The response options.
68
+ */
69
+ sendJson(data: any, options?: Response.options): void;
70
+ /**
71
+ * Sends an error as a response.
72
+ * @param status - The HTTP status code of the error.
73
+ * @param message - The error message.
74
+ */
75
+ sendError(status: number, message: string): Promise<void>;
76
+ private fileExist;
77
+ }
78
+ export declare namespace Response {
79
+ interface options {
80
+ status?: number;
81
+ headers?: Request.Headers;
82
+ encode?: BufferEncoding;
83
+ }
84
+ interface contentTypeMap {
85
+ [key: string]: string | undefined;
86
+ }
87
+ type data = string | Buffer | FS.ReadStream;
88
+ type Extensions = ('HTML' | 'JS' | 'CSS' | 'JSON' | 'XML' | 'TXT' | 'SVG' | 'PNG' | 'JPG' | 'JPEG' | 'MP3' | 'WAV' | 'MP4');
89
+ }
90
+ export default Response;
@@ -0,0 +1,241 @@
1
+ /**
2
+ * @author NetFeez <codefeez.dev@gmail.com>
3
+ * @description Adds the response format to `Vortez`.
4
+ * @license Apache-2.0
5
+ */
6
+ import FS from 'fs';
7
+ import PATH from 'path';
8
+ import Utilities from '../Utilities/Utilities.js';
9
+ import Template from '../Template.js';
10
+ export class Response {
11
+ /** Contains the request received by the server. */
12
+ request;
13
+ /** Contains the list of server response templates. */
14
+ templates;
15
+ /** Contains the response to be sent by the server. */
16
+ httpResponse;
17
+ /**
18
+ * Creates the `NetFeez-Labs/Server` response format.
19
+ * @param request - The request received by the server.
20
+ * @param httpResponse - The response to be sent by the server.
21
+ * @param templates - The list of server response templates.
22
+ */
23
+ constructor(request, httpResponse, templates = {}) {
24
+ this.request = request;
25
+ this.templates = templates;
26
+ this.httpResponse = httpResponse;
27
+ this.httpResponse.setHeader('X-Powered-By', 'MyNetFeez-Labs Vortez');
28
+ this.httpResponse.setHeader('X-Version', '3.7.0-dev.18');
29
+ }
30
+ /**
31
+ * Generates headers for supported file types.
32
+ * More types will be supported over time.
33
+ * @param extension - The file extension.
34
+ */
35
+ generateHeaders(extension) {
36
+ extension = extension.startsWith('.') ? extension.slice(1) : extension;
37
+ extension = extension.toLowerCase();
38
+ const headers = {};
39
+ const contentTypeMap = {
40
+ 'html': 'text/html',
41
+ 'js': 'text/javascript',
42
+ 'css': 'text/css',
43
+ 'json': 'application/json',
44
+ 'xml': 'application/xml',
45
+ 'txt': 'text/plain',
46
+ 'svg': 'image/svg+xml',
47
+ 'png': 'image/png',
48
+ 'jpg': 'image/jpeg',
49
+ 'jpeg': 'image/jpeg',
50
+ 'mp3': 'audio/mpeg',
51
+ 'wav': 'audio/x-wav',
52
+ 'mp4': 'video/mp4',
53
+ };
54
+ const acceptRangeFormats = [
55
+ 'svg', 'png', 'jpg', 'jpeg', 'mp3', 'wav', 'mp4'
56
+ ];
57
+ const type = contentTypeMap[extension];
58
+ if (type)
59
+ headers['Content-Type'] = type;
60
+ if (acceptRangeFormats.includes(extension)) {
61
+ headers['Accept-Ranges'] = 'bytes';
62
+ }
63
+ return headers;
64
+ }
65
+ /**
66
+ * Sends response headers.
67
+ * @param code - The HTTP status code.
68
+ * @param headers - The headers to send.
69
+ */
70
+ sendHeaders(code, headers) {
71
+ const cookieSetters = this.request.cookies.getSetters();
72
+ if (cookieSetters.length > 0)
73
+ headers['set-cookie'] = cookieSetters;
74
+ this.httpResponse.writeHead(code, headers);
75
+ }
76
+ /**
77
+ * Sends data as a response.
78
+ * @param data - The data to be sent.
79
+ * @param encode - The encoding used for the response.
80
+ */
81
+ send(data, options = {}) {
82
+ const status = options.status ?? 200;
83
+ const encode = options.encode || 'utf-8';
84
+ const headers = options.headers || this.generateHeaders('txt');
85
+ this.sendHeaders(status, headers);
86
+ if (!(data instanceof FS.ReadStream))
87
+ return void this.httpResponse.end(data, encode);
88
+ data.pipe(this.httpResponse);
89
+ }
90
+ /**
91
+ * Sends a file as a response.
92
+ * @param path - The file path to send.
93
+ * @param options - The response options.
94
+ * @throws If the file does not exist or is not accessible.
95
+ */
96
+ async sendFile(path, options = {}) {
97
+ path = Utilities.Path.normalize(path);
98
+ try {
99
+ const details = await FS.promises.stat(path);
100
+ if (!details.isFile())
101
+ return this.sendError(500, '[Response Error] - Provided path is not a file.');
102
+ if (!this.request.headers.range) {
103
+ const stream = FS.createReadStream(path);
104
+ const headers = this.generateHeaders(PATH.extname(path));
105
+ headers['content-length'] = details.size.toString();
106
+ this.send(stream, { status: 200, headers });
107
+ }
108
+ else {
109
+ const info = /bytes=(\d*)?-?(\d*)?/i.exec(this.request.headers.range);
110
+ if (!info)
111
+ return this.sendError(416, 'Requested range exceeds file size');
112
+ const [startString, endString] = info.slice(1);
113
+ if (!startString)
114
+ return this.sendError(416, 'Requested range exceeds file size');
115
+ const start = Number(startString);
116
+ const maxSize = start + 1024 * 1000;
117
+ const end = endString
118
+ ? Number(endString)
119
+ : maxSize >= details.size
120
+ ? details.size - 1
121
+ : maxSize;
122
+ if (start > details.size || end > details.size)
123
+ return this.sendError(416, 'Requested range exceeds file size');
124
+ const size = end - start + 1;
125
+ const stream = FS.createReadStream(path, { start, end });
126
+ const headers = this.generateHeaders(PATH.extname(path));
127
+ headers['content-length'] = size.toString();
128
+ headers['content-range'] = `bytes ${start}-${end}/${details.size}`;
129
+ this.send(stream, { status: 206, headers });
130
+ }
131
+ }
132
+ catch (error) {
133
+ this.sendError(500, error instanceof Error ? error.message : '[Response Error] - File does not exist.');
134
+ }
135
+ }
136
+ /**
137
+ * Sends the listing of a folder as a response.
138
+ * @param basePath - The routing rule base path.
139
+ * @param relativePath - The relative path received in the request.
140
+ * @throws If the folder does not exist or is invalid.
141
+ */
142
+ async sendFolder(basePath, relativePath) {
143
+ basePath = basePath.endsWith('/') ? basePath : basePath + '/';
144
+ relativePath = relativePath.endsWith('/') ? relativePath.slice(0, -1) : relativePath;
145
+ const path = Utilities.Path.normalize(basePath + relativePath);
146
+ try {
147
+ if (!await this.fileExist(path))
148
+ return void this.sendError(404, 'The requested URL was not fount');
149
+ const details = await FS.promises.stat(path);
150
+ if (details.isFile())
151
+ return this.sendFile(path);
152
+ if (!details.isDirectory())
153
+ return this.sendError(404, 'The requested URL was not fount');
154
+ const folder = await FS.promises.readdir(path);
155
+ if (this.templates.folder) {
156
+ this.sendTemplate(this.templates.folder, {
157
+ Url: this.request.url,
158
+ folder
159
+ });
160
+ }
161
+ else {
162
+ this.sendTemplate(Utilities.Path.relative('./global/Template/Folder.vhtml'), {
163
+ Url: this.request.url,
164
+ folder
165
+ });
166
+ }
167
+ }
168
+ catch (error) {
169
+ this.sendError(500, error instanceof Error ? error.message : '[Response Error] - File/Directory does not exist.');
170
+ }
171
+ }
172
+ /**
173
+ * Sends a `.vhtml` template as a response.
174
+ * @param path - The template file path.
175
+ * @param data - The data to compile the template with.
176
+ * @param options - The response options.
177
+ * @throws If the template cannot be loaded.
178
+ */
179
+ async sendTemplate(path, data, options = {}) {
180
+ path = Utilities.Path.normalize(path);
181
+ try {
182
+ const template = await Template.load(path, data);
183
+ const status = options.status ?? 200;
184
+ const headers = options.headers || this.generateHeaders('html');
185
+ this.send(template, { status, headers });
186
+ }
187
+ catch (error) {
188
+ this.sendError(500, error instanceof Error ? error.message : '[Response Error] - Template does not exist.');
189
+ }
190
+ }
191
+ /**
192
+ * Sends data in JSON format.
193
+ * @param data - The data to send.
194
+ * @param options - The response options.
195
+ */
196
+ sendJson(data, options = {}) {
197
+ const json = JSON.stringify(data);
198
+ const status = options.status ?? 200;
199
+ const headers = options.headers || this.generateHeaders('json');
200
+ this.send(json, { status, headers });
201
+ }
202
+ /**
203
+ * Sends an error as a response.
204
+ * @param status - The HTTP status code of the error.
205
+ * @param message - The error message.
206
+ */
207
+ async sendError(status, message) {
208
+ try {
209
+ if (this.templates.error) {
210
+ const template = await Template.load(this.templates.error, {
211
+ status, message
212
+ });
213
+ const headers = this.generateHeaders('html');
214
+ this.send(template, { status: status, headers });
215
+ }
216
+ else {
217
+ const template = await Template.load(Utilities.Path.relative('./global/Template/Error.vhtml'), {
218
+ status, message
219
+ });
220
+ const headers = this.generateHeaders('html');
221
+ this.send(template, { status: status, headers });
222
+ }
223
+ }
224
+ catch (error) {
225
+ console.error(error);
226
+ const headers = this.generateHeaders('txt');
227
+ this.send(`Error: ${status} -> ${message}`, { status: status, headers });
228
+ }
229
+ }
230
+ async fileExist(path) {
231
+ try {
232
+ await FS.promises.stat(path);
233
+ return true;
234
+ }
235
+ catch (error) {
236
+ return false;
237
+ }
238
+ }
239
+ }
240
+ export default Response;
241
+ //# sourceMappingURL=Response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Response.js","sourceRoot":"","sources":["../../src/Server/Response.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAGxB,OAAO,SAAS,MAAM,2BAA2B,CAAC;AAClD,OAAO,QAAQ,MAAM,gBAAgB,CAAC;AAGtC,MAAM,OAAO,QAAQ;IACpB,mDAAmD;IAC5C,OAAO,CAAU;IACxB,sDAAsD;IAC9C,SAAS,CAAmB;IACpC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CAAC;QAAC,CAAC;IAC/B,CAAC;CACD;AAkBD,eAAe,QAAQ,CAAC"}
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @author NetFeez <codefeez.dev@gmail.com>
3
+ * @description Contains routing rule logic for Vortez.
4
+ * @license Apache-2.0
5
+ */
6
+ import Request from './Request.js';
7
+ import Response from './Response.js';
8
+ import WebSocket from './WebSocket/WebSocket.js';
9
+ export declare class Rule<T extends keyof Rule.Type = keyof Rule.Type> {
10
+ /** The type of the routing rule */
11
+ type: T;
12
+ /** The HTTP method accepted by the routing rule */
13
+ method: Request.Method;
14
+ /** The UrlRule with which the routing rule was created */
15
+ urlRule: string;
16
+ /** The authentication function */
17
+ authExec: Rule.AuthExec;
18
+ /** The regular expression for the routing rule */
19
+ expression: RegExp;
20
+ /** The executable content for the routing rule */
21
+ content: Rule.Type[T];
22
+ /**
23
+ * Creates a routing rule for Vortez.
24
+ * @param type - The rule type.
25
+ * @param method - The HTTP method of the rule.
26
+ * @param urlRule - The URL rule adopted by this Rule instance.
27
+ * @param content - The executable content of the rule.
28
+ * @param authExec - The authentication function.
29
+ */
30
+ constructor(type: T, method: Request.Method, urlRule: string, content: Rule.Type[T], authExec?: Rule.AuthExec);
31
+ /**
32
+ * Executes the rule's content.
33
+ * @param request - The Request that matched the rule.
34
+ * @param client - The client that made the request.
35
+ */
36
+ exec(request: Request, client: Rule.ClientType<T>): void;
37
+ /**
38
+ * Checks whether a URL matches this route.
39
+ * Also sets the Request.ruleParams.
40
+ * @param request - The incoming request.
41
+ * @param isWebSocket - Whether to check for a WebSocket route.
42
+ */
43
+ test(request: Request, isWebSocket?: boolean): boolean;
44
+ /**
45
+ * Validates whether the request passes authentication.
46
+ * @param request - The incoming request.
47
+ */
48
+ testAuth(request: Request): boolean;
49
+ /**
50
+ * Retrieves the ruleParams from the routing rule if available.
51
+ * @param path - The URL to resolve.
52
+ */
53
+ getParams(path: string): Rule.ruleParams;
54
+ /**
55
+ * Extracts the surplus URL using the rule's expression.
56
+ * @param url - The full URL to extract from.
57
+ */
58
+ getSurplus(url: string): string;
59
+ /**
60
+ * Creates a regular expression for route matching.
61
+ * @param urlRule - The UrlRule used to form the RegExp.
62
+ * @throws Invalid URL rule format
63
+ */
64
+ private getExpression;
65
+ }
66
+ export declare namespace Rule {
67
+ type AuthExec = (Request: Request) => boolean;
68
+ type ActionExec = (Request: Request, Response: Response) => void;
69
+ type WebSocketExec = (Request: Request, WebSocket: WebSocket) => void;
70
+ type ClientType<T extends keyof Type> = T extends 'WebSocket' ? WebSocket : Response;
71
+ interface ruleParams {
72
+ [name: string]: string | undefined;
73
+ }
74
+ type Type = {
75
+ File: string;
76
+ Folder: string;
77
+ Action: ActionExec;
78
+ WebSocket: WebSocketExec;
79
+ };
80
+ }
81
+ export default Rule;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @author NetFeez <codefeez.dev@gmail.com>
3
+ * @description Contains routing rule logic for Vortez.
4
+ * @license Apache-2.0
5
+ */
6
+ export class Rule {
7
+ /** The type of the routing rule */
8
+ type;
9
+ /** The HTTP method accepted by the routing rule */
10
+ method;
11
+ /** The UrlRule with which the routing rule was created */
12
+ urlRule;
13
+ /** The authentication function */
14
+ authExec;
15
+ /** The regular expression for the routing rule */
16
+ expression;
17
+ /** The executable content for the routing rule */
18
+ content;
19
+ /**
20
+ * Creates a routing rule for Vortez.
21
+ * @param type - The rule type.
22
+ * @param method - The HTTP method of the rule.
23
+ * @param urlRule - The URL rule adopted by this Rule instance.
24
+ * @param content - The executable content of the rule.
25
+ * @param authExec - The authentication function.
26
+ */
27
+ constructor(type, method, urlRule, content, authExec) {
28
+ if (!urlRule.startsWith('/'))
29
+ urlRule = '/' + urlRule;
30
+ if (urlRule.endsWith('/'))
31
+ urlRule = urlRule.slice(0, -1);
32
+ this.urlRule = urlRule;
33
+ this.type = type;
34
+ this.method = method;
35
+ this.expression = this.getExpression(urlRule);
36
+ this.content = content;
37
+ this.authExec = authExec ?? (() => true);
38
+ }
39
+ /**
40
+ * Executes the rule's content.
41
+ * @param request - The Request that matched the rule.
42
+ * @param client - The client that made the request.
43
+ */
44
+ exec(request, client) {
45
+ request.ruleParams = this.getParams(request.url);
46
+ if (this.testAuth(request))
47
+ switch (this.type) {
48
+ case 'Action':
49
+ this.content(request, client);
50
+ break;
51
+ case 'File':
52
+ client.sendFile(this.content);
53
+ break;
54
+ case 'Folder':
55
+ client.sendFolder(this.content, this.getSurplus(request.url));
56
+ break;
57
+ case 'WebSocket':
58
+ this.content(request, client);
59
+ break;
60
+ }
61
+ }
62
+ /**
63
+ * Checks whether a URL matches this route.
64
+ * Also sets the Request.ruleParams.
65
+ * @param request - The incoming request.
66
+ * @param isWebSocket - Whether to check for a WebSocket route.
67
+ */
68
+ test(request, isWebSocket = false) {
69
+ let result = false;
70
+ if (isWebSocket) {
71
+ result = this.type == 'WebSocket'
72
+ ? this.expression.test(request.url)
73
+ : false;
74
+ }
75
+ else {
76
+ result = this.method == request.method || this.method == 'ALL'
77
+ ? this.expression.test(request.url)
78
+ : false;
79
+ }
80
+ return result;
81
+ }
82
+ /**
83
+ * Validates whether the request passes authentication.
84
+ * @param request - The incoming request.
85
+ */
86
+ testAuth(request) {
87
+ return !this.authExec || this.authExec(request);
88
+ }
89
+ /**
90
+ * Retrieves the ruleParams from the routing rule if available.
91
+ * @param path - The URL to resolve.
92
+ */
93
+ getParams(path) {
94
+ const math = this.expression.exec(path);
95
+ if (!math)
96
+ return {};
97
+ return { ...math.groups };
98
+ }
99
+ /**
100
+ * Extracts the surplus URL using the rule's expression.
101
+ * @param url - The full URL to extract from.
102
+ */
103
+ getSurplus(url) {
104
+ if (this.type == 'Folder') {
105
+ const folderExp = new RegExp(this.expression.source.replace(/\.\+\?\$$/, ''));
106
+ return url.replace(folderExp, '');
107
+ }
108
+ else
109
+ return url.replace(this.expression, '');
110
+ }
111
+ /**
112
+ * Creates a regular expression for route matching.
113
+ * @param urlRule - The UrlRule used to form the RegExp.
114
+ * @throws Invalid URL rule format
115
+ */
116
+ getExpression(urlRule) {
117
+ const validators = {
118
+ param: /^\$(?<param>.+)$/,
119
+ scape: /\\(?![\$\[\]\*\+\?\.\(\)\{\}\^\|\-])|(?<!\\)[\$\[\]\*\+\?\.\(\)\{\}\^\|\-]/gi,
120
+ };
121
+ const zones = urlRule.split('/').slice(1);
122
+ let regExpString = '^';
123
+ for (let index = 0; index < zones.length; index++) {
124
+ const zone = zones[index];
125
+ regExpString += '\/';
126
+ if (validators.param.test(zone)) {
127
+ const match = validators.param.exec(zone);
128
+ if (match && match.groups) {
129
+ const param = match.groups['param'].replace(validators.scape, '');
130
+ regExpString += `(?<${param}>[^\/]+?)`;
131
+ }
132
+ }
133
+ else if (zone == '*') {
134
+ regExpString += index < (zones.length - 1)
135
+ ? '(?:[^\/]+)?'
136
+ : '(?:.+)?';
137
+ }
138
+ else
139
+ regExpString += zone;
140
+ }
141
+ regExpString += `\/?${this.type == 'Folder' ? '.+?' : ''}$`;
142
+ return new RegExp(regExpString);
143
+ }
144
+ }
145
+ export default Rule;
146
+ //# sourceMappingURL=Rule.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Rule.js","sourceRoot":"","sources":["../../src/Server/Rule.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAMH,MAAM,OAAO,IAAI;IACb,mCAAmC;IAC5B,IAAI,CAAI;IACf,mDAAmD;IAC5C,MAAM,CAAiB;IAC9B,0DAA0D;IACnD,OAAO,CAAS;IACvB,kCAAkC;IAC3B,QAAQ,CAAgB;IAC/B,kDAAkD;IAC3C,UAAU,CAAS;IAC1B,kDAAkD;IAC3C,OAAO,CAAe;IAC7B;;;;;;;OAOG;IACH,YAAmB,IAAO,EAAE,MAAsB,EAAE,OAAe,EAAE,OAAqB,EAAE,QAAwB;QAChH,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;YAAE,OAAO,GAAG,GAAG,GAAG,OAAO,CAAC;QACtD,IAAI,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC;Y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