@devbro/neko-router 0.1.0

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 (58) hide show
  1. package/README.md +47 -0
  2. package/dist/CompiledRoute.d.mts +23 -0
  3. package/dist/CompiledRoute.d.ts +23 -0
  4. package/dist/CompiledRoute.js +162 -0
  5. package/dist/CompiledRoute.js.map +1 -0
  6. package/dist/CompiledRoute.mjs +138 -0
  7. package/dist/CompiledRoute.mjs.map +1 -0
  8. package/dist/Controller.d.mts +38 -0
  9. package/dist/Controller.d.ts +38 -0
  10. package/dist/Controller.js +146 -0
  11. package/dist/Controller.js.map +1 -0
  12. package/dist/Controller.mjs +115 -0
  13. package/dist/Controller.mjs.map +1 -0
  14. package/dist/Middleware-BjWt0Uml.d.mts +29 -0
  15. package/dist/Middleware-BjWt0Uml.d.ts +29 -0
  16. package/dist/Middleware.d.mts +2 -0
  17. package/dist/Middleware.d.ts +2 -0
  18. package/dist/Middleware.js +35 -0
  19. package/dist/Middleware.js.map +1 -0
  20. package/dist/Middleware.mjs +11 -0
  21. package/dist/Middleware.mjs.map +1 -0
  22. package/dist/MiddlewareFactory.d.mts +8 -0
  23. package/dist/MiddlewareFactory.d.ts +8 -0
  24. package/dist/MiddlewareFactory.js +42 -0
  25. package/dist/MiddlewareFactory.js.map +1 -0
  26. package/dist/MiddlewareFactory.mjs +18 -0
  27. package/dist/MiddlewareFactory.mjs.map +1 -0
  28. package/dist/Route.d.mts +39 -0
  29. package/dist/Route.d.ts +39 -0
  30. package/dist/Route.js +135 -0
  31. package/dist/Route.js.map +1 -0
  32. package/dist/Route.mjs +111 -0
  33. package/dist/Route.mjs.map +1 -0
  34. package/dist/Router.d.mts +17 -0
  35. package/dist/Router.d.ts +17 -0
  36. package/dist/Router.js +106 -0
  37. package/dist/Router.js.map +1 -0
  38. package/dist/Router.mjs +72 -0
  39. package/dist/Router.mjs.map +1 -0
  40. package/dist/helpers.d.mts +6 -0
  41. package/dist/helpers.d.ts +6 -0
  42. package/dist/helpers.js +70 -0
  43. package/dist/helpers.js.map +1 -0
  44. package/dist/helpers.mjs +46 -0
  45. package/dist/helpers.mjs.map +1 -0
  46. package/dist/index.d.mts +8 -0
  47. package/dist/index.d.ts +8 -0
  48. package/dist/index.js +37 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/index.mjs +9 -0
  51. package/dist/index.mjs.map +1 -0
  52. package/dist/types.d.mts +2 -0
  53. package/dist/types.d.ts +2 -0
  54. package/dist/types.js +17 -0
  55. package/dist/types.js.map +1 -0
  56. package/dist/types.mjs +1 -0
  57. package/dist/types.mjs.map +1 -0
  58. package/package.json +63 -0
@@ -0,0 +1,115 @@
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
8
+ }
9
+ };
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
15
+ }
16
+ };
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
19
+ });
20
+ };
21
+ class BaseController {
22
+ static getInstance() {
23
+ return new this();
24
+ }
25
+ }
26
+ BaseController.routes = [];
27
+ BaseController.basePath = "";
28
+ function Controller(path, options = {}) {
29
+ return function(target) {
30
+ target.routes = target.routes || [];
31
+ target.basePath = path;
32
+ target.baseMiddlewares = options.middlewares || [];
33
+ };
34
+ }
35
+ function createHttpDecorator(data) {
36
+ return function(target, propertyKey, descriptor) {
37
+ if (!target.constructor.routes) {
38
+ target.constructor.routes = [];
39
+ }
40
+ target.constructor.routes.push({
41
+ methods: data.methods,
42
+ path: data.path,
43
+ handler: propertyKey,
44
+ middlewares: data.middlewares || []
45
+ });
46
+ const originalMethod = descriptor.value;
47
+ const paramKeys = Reflect.ownKeys(target);
48
+ descriptor.value = function(...args) {
49
+ return __async(this, null, function* () {
50
+ const paramCustomKeys = paramKeys.filter(
51
+ (key) => typeof key === "string" && key.endsWith(":custom")
52
+ );
53
+ for (const paramKey of paramCustomKeys) {
54
+ const paramIndex = parseInt(paramKey.split(":")[1]);
55
+ let method = Reflect.get(target, paramKey.toString());
56
+ if (typeof paramIndex === "number" && typeof method === "function") {
57
+ args[paramIndex] = yield method();
58
+ }
59
+ }
60
+ return originalMethod.apply(this, args);
61
+ });
62
+ };
63
+ };
64
+ }
65
+ function Get(data = {}) {
66
+ return createHttpDecorator({
67
+ methods: ["GET", "HEAD"],
68
+ path: data.path || "/",
69
+ middlewares: data.middlewares || []
70
+ });
71
+ }
72
+ function Post(data = {}) {
73
+ return createHttpDecorator({
74
+ methods: ["POST"],
75
+ path: data.path || "/",
76
+ middlewares: data.middlewares || []
77
+ });
78
+ }
79
+ function Put(data = {}) {
80
+ return createHttpDecorator({
81
+ methods: ["PUT"],
82
+ path: data.path || "/",
83
+ middlewares: data.middlewares || []
84
+ });
85
+ }
86
+ function Patch(data = {}) {
87
+ return createHttpDecorator({
88
+ methods: ["PATCH"],
89
+ path: data.path || "/",
90
+ middlewares: data.middlewares || []
91
+ });
92
+ }
93
+ function Delete(data = {}) {
94
+ return createHttpDecorator({
95
+ methods: ["DELETE"],
96
+ path: data.path || "/",
97
+ middlewares: data.middlewares || []
98
+ });
99
+ }
100
+ function createParamDecorator(func) {
101
+ return function MyParamDecorator(target, propertyKey, parameterIndex) {
102
+ Reflect.set(target, `${propertyKey == null ? void 0 : propertyKey.toString()}:${parameterIndex}:custom`, func);
103
+ };
104
+ }
105
+ export {
106
+ BaseController,
107
+ Controller,
108
+ Delete,
109
+ Get,
110
+ Patch,
111
+ Post,
112
+ Put,
113
+ createParamDecorator
114
+ };
115
+ //# sourceMappingURL=Controller.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Controller.ts"],"sourcesContent":["import { ControllerDecoratorOptions, MiddlewareProvider } from './types';\nimport { Middleware } from './Middleware';\n\nexport class BaseController {\n static routes: {\n methods: string[];\n path: string;\n handler: string;\n middlewares: MiddlewareProvider[];\n }[] = [];\n static basePath: string = '';\n static baseMiddlewares: MiddlewareProvider[];\n\n static getInstance() {\n return new this();\n }\n}\n\nexport function Controller(path: string, options: ControllerDecoratorOptions = {}): ClassDecorator {\n return function (target: any) {\n (target as any).routes = (target as any).routes || [];\n (target as any).basePath = path;\n (target as any).baseMiddlewares = options.middlewares || [];\n };\n}\n\nfunction createHttpDecorator(data: {\n methods: string[];\n path: string;\n middlewares: MiddlewareProvider[];\n}): MethodDecorator {\n return function (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {\n if (!target.constructor.routes) {\n target.constructor.routes = [];\n }\n target.constructor.routes.push({\n methods: data.methods,\n path: data.path,\n handler: propertyKey,\n middlewares: data.middlewares || [],\n });\n\n const originalMethod = descriptor.value!;\n const paramKeys = Reflect.ownKeys(target);\n\n descriptor.value = async function (...args: any[]) {\n const paramCustomKeys = paramKeys.filter(\n (key) => typeof key === 'string' && key.endsWith(':custom')\n );\n for (const paramKey of paramCustomKeys) {\n const paramIndex = parseInt((paramKey as string).split(':')[1]);\n let method = Reflect.get(target, paramKey.toString());\n if (typeof paramIndex === 'number' && typeof method === 'function') {\n args[paramIndex] = await method();\n }\n }\n\n return originalMethod.apply(this, args);\n };\n };\n}\n\nexport function Get(\n data: { path?: string; middlewares?: MiddlewareProvider[] } = {}\n): MethodDecorator {\n return createHttpDecorator({\n methods: ['GET', 'HEAD'],\n path: data.path || '/',\n middlewares: data.middlewares || [],\n });\n}\n\nexport function Post(\n data: { path?: string; middlewares?: MiddlewareProvider[] } = {}\n): MethodDecorator {\n return createHttpDecorator({\n methods: ['POST'],\n path: data.path || '/',\n middlewares: data.middlewares || [],\n });\n}\n\nexport function Put(\n data: { path?: string; middlewares?: MiddlewareProvider[] } = {}\n): MethodDecorator {\n return createHttpDecorator({\n methods: ['PUT'],\n path: data.path || '/',\n middlewares: data.middlewares || [],\n });\n}\n\nexport function Patch(\n data: { path?: string; middlewares?: MiddlewareProvider[] } = {}\n): MethodDecorator {\n return createHttpDecorator({\n methods: ['PATCH'],\n path: data.path || '/',\n middlewares: data.middlewares || [],\n });\n}\n\nexport function Delete(\n data: { path?: string; middlewares?: MiddlewareProvider[] } = {}\n): MethodDecorator {\n return createHttpDecorator({\n methods: ['DELETE'],\n path: data.path || '/',\n middlewares: data.middlewares || [],\n });\n}\n\nexport function createParamDecorator(func: () => Promise<any> | (() => any)): ParameterDecorator {\n return function MyParamDecorator(\n target: Object,\n propertyKey: string | symbol | undefined,\n parameterIndex: number\n ) {\n Reflect.set(target, `${propertyKey?.toString()}:${parameterIndex}:custom`, func);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAGO,MAAM,eAAe;AAAA,EAU1B,OAAO,cAAc;AACnB,WAAO,IAAI,KAAK;AAAA,EAClB;AACF;AAba,eACJ,SAKD,CAAC;AANI,eAOJ,WAAmB;AAQrB,SAAS,WAAW,MAAc,UAAsC,CAAC,GAAmB;AACjG,SAAO,SAAU,QAAa;AAC5B,IAAC,OAAe,SAAU,OAAe,UAAU,CAAC;AACpD,IAAC,OAAe,WAAW;AAC3B,IAAC,OAAe,kBAAkB,QAAQ,eAAe,CAAC;AAAA,EAC5D;AACF;AAEA,SAAS,oBAAoB,MAIT;AAClB,SAAO,SAAU,QAAa,aAA8B,YAAgC;AAC1F,QAAI,CAAC,OAAO,YAAY,QAAQ;AAC9B,aAAO,YAAY,SAAS,CAAC;AAAA,IAC/B;AACA,WAAO,YAAY,OAAO,KAAK;AAAA,MAC7B,SAAS,KAAK;AAAA,MACd,MAAM,KAAK;AAAA,MACX,SAAS;AAAA,MACT,aAAa,KAAK,eAAe,CAAC;AAAA,IACpC,CAAC;AAED,UAAM,iBAAiB,WAAW;AAClC,UAAM,YAAY,QAAQ,QAAQ,MAAM;AAExC,eAAW,QAAQ,YAAmB,MAAa;AAAA;AACjD,cAAM,kBAAkB,UAA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,QAAQ;AAAA,IACnB,aAAa,KAAK,eAAe,CAAC;AAAA,EACpC,CAAC;AACH;AAEO,SAAS,qBAAqB,MAA4D;AAC/F,SAAO,SAAS,iBACd,QACA,aACA,gBACA;AACA,YAAQ,IAAI,QAAQ,GAAG,2CAAa,UAAU,IAAI,cAAc,WAAW,IAAI;AAAA,EACjF;AACF;","names":[]}
@@ -0,0 +1,29 @@
1
+ import { IncomingMessage, ServerResponse } from 'http';
2
+
3
+ type Request = IncomingMessage & {
4
+ params: any;
5
+ method: string;
6
+ headers?: Record<string, string>;
7
+ body?: any;
8
+ raw_body?: any;
9
+ files?: any;
10
+ query?: Record<string, string>;
11
+ };
12
+ type Response = ServerResponse;
13
+ type LexerToken = {
14
+ type: string;
15
+ value: string;
16
+ };
17
+ type HandlerType = (req: Request, res: Response, next?: (() => any) | undefined) => Promise<any> | any;
18
+ type ControllerDecoratorOptions = {
19
+ middlewares?: MiddlewareProvider[];
20
+ };
21
+ type MiddlewareProvider = typeof Middleware | Middleware | ((request: Request, response: Response, next: () => Promise<void>) => Promise<void>);
22
+
23
+ declare abstract class Middleware {
24
+ protected constructor(params?: any);
25
+ static getInstance(params: any): Middleware;
26
+ abstract call(req: Request, res: Response, next: () => Promise<void>): Promise<void>;
27
+ }
28
+
29
+ export { type ControllerDecoratorOptions as C, type HandlerType as H, type LexerToken as L, type MiddlewareProvider as M, type Request as R, type Response as a, Middleware as b };
@@ -0,0 +1,29 @@
1
+ import { IncomingMessage, ServerResponse } from 'http';
2
+
3
+ type Request = IncomingMessage & {
4
+ params: any;
5
+ method: string;
6
+ headers?: Record<string, string>;
7
+ body?: any;
8
+ raw_body?: any;
9
+ files?: any;
10
+ query?: Record<string, string>;
11
+ };
12
+ type Response = ServerResponse;
13
+ type LexerToken = {
14
+ type: string;
15
+ value: string;
16
+ };
17
+ type HandlerType = (req: Request, res: Response, next?: (() => any) | undefined) => Promise<any> | any;
18
+ type ControllerDecoratorOptions = {
19
+ middlewares?: MiddlewareProvider[];
20
+ };
21
+ type MiddlewareProvider = typeof Middleware | Middleware | ((request: Request, response: Response, next: () => Promise<void>) => Promise<void>);
22
+
23
+ declare abstract class Middleware {
24
+ protected constructor(params?: any);
25
+ static getInstance(params: any): Middleware;
26
+ abstract call(req: Request, res: Response, next: () => Promise<void>): Promise<void>;
27
+ }
28
+
29
+ export { type ControllerDecoratorOptions as C, type HandlerType as H, type LexerToken as L, type MiddlewareProvider as M, type Request as R, type Response as a, Middleware as b };
@@ -0,0 +1,2 @@
1
+ export { b as Middleware } from './Middleware-BjWt0Uml.mjs';
2
+ import 'http';
@@ -0,0 +1,2 @@
1
+ export { b as Middleware } from './Middleware-BjWt0Uml.js';
2
+ import 'http';
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var Middleware_exports = {};
20
+ __export(Middleware_exports, {
21
+ Middleware: () => Middleware
22
+ });
23
+ module.exports = __toCommonJS(Middleware_exports);
24
+ class Middleware {
25
+ constructor(params = {}) {
26
+ }
27
+ static getInstance(params) {
28
+ throw new Error("Method not implemented. Please implement a static getInstance method.");
29
+ }
30
+ }
31
+ // Annotate the CommonJS export names for ESM import in node:
32
+ 0 && (module.exports = {
33
+ Middleware
34
+ });
35
+ //# sourceMappingURL=Middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Middleware.ts"],"sourcesContent":["import { LexerToken, Request, Response } from './types';\n\nexport abstract class Middleware {\n protected constructor(params: any = {}) {}\n static getInstance(params: any): Middleware {\n throw new Error('Method not implemented. Please implement a static getInstance method.');\n }\n\n abstract call(req: Request, res: Response, next: () => Promise<void>): Promise<void>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEO,MAAe,WAAW;AAAA,EACrB,YAAY,SAAc,CAAC,GAAG;AAAA,EAAC;AAAA,EACzC,OAAO,YAAY,QAAyB;AAC1C,UAAM,IAAI,MAAM,uEAAuE;AAAA,EACzF;AAGF;","names":[]}
@@ -0,0 +1,11 @@
1
+ class Middleware {
2
+ constructor(params = {}) {
3
+ }
4
+ static getInstance(params) {
5
+ throw new Error("Method not implemented. Please implement a static getInstance method.");
6
+ }
7
+ }
8
+ export {
9
+ Middleware
10
+ };
11
+ //# sourceMappingURL=Middleware.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Middleware.ts"],"sourcesContent":["import { LexerToken, Request, Response } from './types';\n\nexport abstract class Middleware {\n protected constructor(params: any = {}) {}\n static getInstance(params: any): Middleware {\n throw new Error('Method not implemented. Please implement a static getInstance method.');\n }\n\n abstract call(req: Request, res: Response, next: () => Promise<void>): Promise<void>;\n}\n"],"mappings":"AAEO,MAAe,WAAW;AAAA,EACrB,YAAY,SAAc,CAAC,GAAG;AAAA,EAAC;AAAA,EACzC,OAAO,YAAY,QAAyB;AAC1C,UAAM,IAAI,MAAM,uEAAuE;AAAA,EACzF;AAGF;","names":[]}
@@ -0,0 +1,8 @@
1
+ import { H as HandlerType, b as Middleware } from './Middleware-BjWt0Uml.mjs';
2
+ import 'http';
3
+
4
+ declare class MiddlewareFactory {
5
+ static create(func: HandlerType): Middleware;
6
+ }
7
+
8
+ export { MiddlewareFactory };
@@ -0,0 +1,8 @@
1
+ import { H as HandlerType, b as Middleware } from './Middleware-BjWt0Uml.js';
2
+ import 'http';
3
+
4
+ declare class MiddlewareFactory {
5
+ static create(func: HandlerType): Middleware;
6
+ }
7
+
8
+ export { MiddlewareFactory };
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var MiddlewareFactory_exports = {};
20
+ __export(MiddlewareFactory_exports, {
21
+ MiddlewareFactory: () => MiddlewareFactory
22
+ });
23
+ module.exports = __toCommonJS(MiddlewareFactory_exports);
24
+ var import_Middleware = require("./Middleware");
25
+ class MiddlewareFactory {
26
+ static create(func) {
27
+ const cls = class extends import_Middleware.Middleware {
28
+ call(req, res, next) {
29
+ return func(req, res, next);
30
+ }
31
+ constructor(params = {}) {
32
+ super(params);
33
+ }
34
+ };
35
+ return new cls();
36
+ }
37
+ }
38
+ // Annotate the CommonJS export names for ESM import in node:
39
+ 0 && (module.exports = {
40
+ MiddlewareFactory
41
+ });
42
+ //# sourceMappingURL=MiddlewareFactory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/MiddlewareFactory.ts"],"sourcesContent":["import { Middleware } from './Middleware';\nimport { HandlerType, LexerToken, Request, Response } from './types';\n\nexport class MiddlewareFactory {\n public static create(func: HandlerType): Middleware {\n const cls = class extends Middleware {\n call(req: Request, res: Response, next: () => Promise<void>): Promise<void> {\n return func(req, res, next);\n }\n constructor(params: any = {}) {\n super(params);\n }\n };\n\n return new cls();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAA2B;AAGpB,MAAM,kBAAkB;AAAA,EAC7B,OAAc,OAAO,MAA+B;AAClD,UAAM,MAAM,cAAc,6BAAW;AAAA,MACnC,KAAK,KAAc,KAAe,MAA0C;AAC1E,eAAO,KAAK,KAAK,KAAK,IAAI;AAAA,MAC5B;AAAA,MACA,YAAY,SAAc,CAAC,GAAG;AAC5B,cAAM,MAAM;AAAA,MACd;AAAA,IACF;AAEA,WAAO,IAAI,IAAI;AAAA,EACjB;AACF;","names":[]}
@@ -0,0 +1,18 @@
1
+ import { Middleware } from "./Middleware";
2
+ class MiddlewareFactory {
3
+ static create(func) {
4
+ const cls = class extends Middleware {
5
+ call(req, res, next) {
6
+ return func(req, res, next);
7
+ }
8
+ constructor(params = {}) {
9
+ super(params);
10
+ }
11
+ };
12
+ return new cls();
13
+ }
14
+ }
15
+ export {
16
+ MiddlewareFactory
17
+ };
18
+ //# sourceMappingURL=MiddlewareFactory.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/MiddlewareFactory.ts"],"sourcesContent":["import { Middleware } from './Middleware';\nimport { HandlerType, LexerToken, Request, Response } from './types';\n\nexport class MiddlewareFactory {\n public static create(func: HandlerType): Middleware {\n const cls = class extends Middleware {\n call(req: Request, res: Response, next: () => Promise<void>): Promise<void> {\n return func(req, res, next);\n }\n constructor(params: any = {}) {\n super(params);\n }\n };\n\n return new cls();\n }\n}\n"],"mappings":"AAAA,SAAS,kBAAkB;AAGpB,MAAM,kBAAkB;AAAA,EAC7B,OAAc,OAAO,MAA+B;AAClD,UAAM,MAAM,cAAc,WAAW;AAAA,MACnC,KAAK,KAAc,KAAe,MAA0C;AAC1E,eAAO,KAAK,KAAK,KAAK,IAAI;AAAA,MAC5B;AAAA,MACA,YAAY,SAAc,CAAC,GAAG;AAC5B,cAAM,MAAM;AAAA,MACd;AAAA,IACF;AAEA,WAAO,IAAI,IAAI;AAAA,EACjB;AACF;","names":[]}
@@ -0,0 +1,39 @@
1
+ import { H as HandlerType, L as LexerToken, R as Request, M as MiddlewareProvider, a as Response } from './Middleware-BjWt0Uml.mjs';
2
+ import 'http';
3
+
4
+ declare class Route {
5
+ methods: string[];
6
+ path: string;
7
+ handler: HandlerType;
8
+ private middlewares;
9
+ private urlRegex;
10
+ constructor(methods: string[], path: string, handler: HandlerType);
11
+ pathToRegex(path: string): RegExp;
12
+ lexUrlPath(path: string): {
13
+ type: string;
14
+ value: string;
15
+ }[];
16
+ tokensToRegex(tokens: LexerToken[]): RegExp;
17
+ /**
18
+ * to evaludate if request is a match for this route
19
+ * @param request http request
20
+ * @returns return true if route is a match for this request
21
+ */
22
+ test(request: Request): boolean;
23
+ /**
24
+ * returns details of the match, otherwise it returns false
25
+ * @param request the request to match
26
+ * @returns object cotaining details of match including matched params
27
+ */
28
+ match(request: Request): false | {
29
+ url: URL;
30
+ params: {
31
+ [key: string]: string;
32
+ };
33
+ };
34
+ addMiddleware(middlewares: MiddlewareProvider | MiddlewareProvider[]): this;
35
+ getMiddlewares(): MiddlewareProvider[];
36
+ callHanlder(request: Request, response: Response): any;
37
+ }
38
+
39
+ export { Route };
@@ -0,0 +1,39 @@
1
+ import { H as HandlerType, L as LexerToken, R as Request, M as MiddlewareProvider, a as Response } from './Middleware-BjWt0Uml.js';
2
+ import 'http';
3
+
4
+ declare class Route {
5
+ methods: string[];
6
+ path: string;
7
+ handler: HandlerType;
8
+ private middlewares;
9
+ private urlRegex;
10
+ constructor(methods: string[], path: string, handler: HandlerType);
11
+ pathToRegex(path: string): RegExp;
12
+ lexUrlPath(path: string): {
13
+ type: string;
14
+ value: string;
15
+ }[];
16
+ tokensToRegex(tokens: LexerToken[]): RegExp;
17
+ /**
18
+ * to evaludate if request is a match for this route
19
+ * @param request http request
20
+ * @returns return true if route is a match for this request
21
+ */
22
+ test(request: Request): boolean;
23
+ /**
24
+ * returns details of the match, otherwise it returns false
25
+ * @param request the request to match
26
+ * @returns object cotaining details of match including matched params
27
+ */
28
+ match(request: Request): false | {
29
+ url: URL;
30
+ params: {
31
+ [key: string]: string;
32
+ };
33
+ };
34
+ addMiddleware(middlewares: MiddlewareProvider | MiddlewareProvider[]): this;
35
+ getMiddlewares(): MiddlewareProvider[];
36
+ callHanlder(request: Request, response: Response): any;
37
+ }
38
+
39
+ export { Route };
package/dist/Route.js ADDED
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var Route_exports = {};
20
+ __export(Route_exports, {
21
+ Route: () => Route
22
+ });
23
+ module.exports = __toCommonJS(Route_exports);
24
+ class Route {
25
+ constructor(methods, path, handler) {
26
+ this.methods = methods;
27
+ this.path = path;
28
+ this.handler = handler;
29
+ this.middlewares = [];
30
+ this.urlRegex = this.pathToRegex(path);
31
+ }
32
+ pathToRegex(path) {
33
+ const lex = this.lexUrlPath(path);
34
+ return this.tokensToRegex(lex);
35
+ }
36
+ lexUrlPath(path) {
37
+ const tokens = [];
38
+ let i = 0;
39
+ while (i < path.length) {
40
+ const char = path[i];
41
+ if (char === "/") {
42
+ tokens.push({ type: "SLASH", value: "/" });
43
+ i++;
44
+ } else if (char === ":") {
45
+ let start = i + 1;
46
+ while (start < path.length && /[a-zA-Z0-9_]/.test(path[start])) {
47
+ start++;
48
+ }
49
+ tokens.push({ type: "PARAM", value: path.slice(i + 1, start) });
50
+ i = start;
51
+ } else if (char === "*") {
52
+ let start = i + 1;
53
+ while (start < path.length && /[a-zA-Z0-9_]/.test(path[start])) {
54
+ start++;
55
+ }
56
+ tokens.push({ type: "WILDCARD", value: path.slice(i + 1, start) });
57
+ i = start;
58
+ } else {
59
+ let start = i;
60
+ while (start < path.length && !["/", ":", "*"].includes(path[start])) {
61
+ start++;
62
+ }
63
+ tokens.push({ type: "TEXT", value: path.slice(i, start) });
64
+ i = start;
65
+ }
66
+ }
67
+ return tokens;
68
+ }
69
+ tokensToRegex(tokens) {
70
+ const regexParts = [];
71
+ for (const token of tokens) {
72
+ if (token.type === "SLASH") {
73
+ regexParts.push("\\/");
74
+ } else if (token.type === "PARAM") {
75
+ regexParts.push(`(?<${token.value}>[^\\/]+)`);
76
+ } else if (token.type === "WILDCARD") {
77
+ regexParts.push("(.+)");
78
+ } else if (token.type === "TEXT") {
79
+ regexParts.push(token.value.replace(/[-\/\\^$.*+?()[\]{}|]/g, "\\$&"));
80
+ }
81
+ }
82
+ if (regexParts.length > 0 && regexParts[regexParts.length - 1] === "\\/") {
83
+ regexParts[regexParts.length - 1] = "\\/?";
84
+ } else {
85
+ regexParts.push("\\/?");
86
+ }
87
+ return new RegExp(`^${regexParts.join("")}$`);
88
+ }
89
+ /**
90
+ * to evaludate if request is a match for this route
91
+ * @param request http request
92
+ * @returns return true if route is a match for this request
93
+ */
94
+ test(request) {
95
+ if (this.methods.indexOf(request.method) === -1) {
96
+ return false;
97
+ }
98
+ const url = new URL(request.url || "/", "http://localhost");
99
+ return this.urlRegex.test(url.pathname);
100
+ }
101
+ /**
102
+ * returns details of the match, otherwise it returns false
103
+ * @param request the request to match
104
+ * @returns object cotaining details of match including matched params
105
+ */
106
+ match(request) {
107
+ if (this.methods.indexOf(request.method) === -1) {
108
+ return false;
109
+ }
110
+ const url = new URL(request.url || "/", "http://localhost");
111
+ const r = this.urlRegex.exec(url.pathname);
112
+ if (!r) {
113
+ return false;
114
+ }
115
+ return {
116
+ url,
117
+ params: r.groups || {}
118
+ };
119
+ }
120
+ addMiddleware(middlewares) {
121
+ this.middlewares = this.middlewares.concat(middlewares);
122
+ return this;
123
+ }
124
+ getMiddlewares() {
125
+ return this.middlewares;
126
+ }
127
+ callHanlder(request, response) {
128
+ return this.handler(request, response);
129
+ }
130
+ }
131
+ // Annotate the CommonJS export names for ESM import in node:
132
+ 0 && (module.exports = {
133
+ Route
134
+ });
135
+ //# sourceMappingURL=Route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Route.ts"],"sourcesContent":["import { Middleware } from './Middleware';\nimport { MiddlewareFactory } from './MiddlewareFactory';\nimport { HandlerType, MiddlewareProvider } from './types';\nimport { LexerToken, Request, Response } from './types';\n\nexport class Route {\n private middlewares: MiddlewareProvider[] = [];\n private urlRegex: RegExp;\n constructor(\n public methods: string[],\n public path: string,\n public handler: HandlerType\n ) {\n this.urlRegex = this.pathToRegex(path);\n }\n pathToRegex(path: string): RegExp {\n const lex = this.lexUrlPath(path);\n return this.tokensToRegex(lex);\n }\n\n lexUrlPath(path: string) {\n const tokens = [];\n let i = 0;\n\n while (i < path.length) {\n const char = path[i];\n\n if (char === '/') {\n tokens.push({ type: 'SLASH', value: '/' });\n i++;\n } else if (char === ':') {\n let start = i + 1;\n while (start < path.length && /[a-zA-Z0-9_]/.test(path[start])) {\n start++;\n }\n tokens.push({ type: 'PARAM', value: path.slice(i + 1, start) });\n i = start;\n } else if (char === '*') {\n let start = i + 1;\n while (start < path.length && /[a-zA-Z0-9_]/.test(path[start])) {\n start++;\n }\n tokens.push({ type: 'WILDCARD', value: path.slice(i + 1, start) });\n i = start;\n } else {\n let start = i;\n while (start < path.length && !['/', ':', '*'].includes(path[start])) {\n start++;\n }\n tokens.push({ type: 'TEXT', value: path.slice(i, start) });\n i = start;\n }\n }\n\n return tokens;\n }\n tokensToRegex(tokens: LexerToken[]) {\n const regexParts = [];\n\n for (const token of tokens) {\n if (token.type === 'SLASH') {\n regexParts.push('\\\\/');\n } else if (token.type === 'PARAM') {\n regexParts.push(`(?<${token.value}>[^\\\\/]+)`);\n } else if (token.type === 'WILDCARD') {\n regexParts.push('(.+)');\n } else if (token.type === 'TEXT') {\n regexParts.push(token.value.replace(/[-\\/\\\\^$.*+?()[\\]{}|]/g, '\\\\$&'));\n }\n }\n\n if (regexParts.length > 0 && regexParts[regexParts.length - 1] === '\\\\/') {\n regexParts[regexParts.length - 1] = '\\\\/?';\n } else {\n regexParts.push('\\\\/?');\n }\n\n return new RegExp(`^${regexParts.join('')}$`);\n }\n\n /**\n * to evaludate if request is a match for this route\n * @param request http request\n * @returns return true if route is a match for this request\n */\n test(request: Request) {\n if (this.methods.indexOf(request.method) === -1) {\n return false;\n }\n const url = new URL(request.url || '/', 'http://localhost');\n\n return this.urlRegex.test(url.pathname);\n }\n\n /**\n * returns details of the match, otherwise it returns false\n * @param request the request to match\n * @returns object cotaining details of match including matched params\n */\n match(request: Request) {\n if (this.methods.indexOf(request.method) === -1) {\n return false;\n }\n\n const url = new URL(request.url || '/', 'http://localhost');\n\n const r = this.urlRegex.exec(url.pathname);\n if (!r) {\n return false;\n }\n\n return {\n url,\n params: r.groups || {},\n };\n }\n\n addMiddleware(middlewares: MiddlewareProvider | MiddlewareProvider[]) {\n this.middlewares = this.middlewares.concat(middlewares);\n return this;\n }\n\n getMiddlewares() {\n return this.middlewares;\n }\n\n callHanlder(request: Request, response: Response) {\n return this.handler(request, response);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAKO,MAAM,MAAM;AAAA,EA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