clear-router 2.7.5 → 2.7.7

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 (107) hide show
  1. package/dist/ClearRequest.cjs +23 -0
  2. package/dist/ClearRequest.d.cts +28 -0
  3. package/dist/ClearRequest.d.mts +28 -0
  4. package/dist/ClearRequest.mjs +22 -0
  5. package/dist/Contracts.d.cts +12 -0
  6. package/dist/Contracts.d.mts +12 -0
  7. package/dist/Controller.cjs +12 -0
  8. package/dist/Controller.d.cts +14 -0
  9. package/dist/Controller.d.mts +14 -0
  10. package/dist/Controller.mjs +11 -0
  11. package/dist/{Request-DKXwa_W0.d.mts → Request-BhTJDR_5.d.mts} +5 -5
  12. package/dist/Route.cjs +58 -0
  13. package/dist/Route.d.cts +35 -0
  14. package/dist/Route.d.mts +35 -0
  15. package/dist/Route.mjs +57 -0
  16. package/dist/core/Request.cjs +35 -0
  17. package/dist/core/Request.d.cts +25 -0
  18. package/dist/core/Request.d.mts +25 -0
  19. package/dist/core/Request.mjs +35 -0
  20. package/dist/core/Response.cjs +59 -0
  21. package/dist/core/Response.d.cts +24 -0
  22. package/dist/core/Response.d.mts +24 -0
  23. package/dist/core/Response.mjs +58 -0
  24. package/dist/{bindings-CLsZjOEy.cjs → core/bindings.cjs} +10 -160
  25. package/dist/{bindings-CNL7bpz5.d.mts → core/bindings.d.cts} +1 -1
  26. package/dist/{bindings-CxvtC8XS.d.cts → core/bindings.d.mts} +1 -1
  27. package/dist/{bindings-XLDXFpHZ.mjs → core/bindings.mjs} +3 -110
  28. package/dist/core/index.cjs +4 -20
  29. package/dist/core/index.d.cts +4 -1
  30. package/dist/core/index.d.mts +4 -1
  31. package/dist/core/index.mjs +4 -14
  32. package/dist/core/plugins.cjs +14 -0
  33. package/dist/core/plugins.d.cts +109 -0
  34. package/dist/core/plugins.d.mts +109 -0
  35. package/dist/core/plugins.mjs +13 -0
  36. package/dist/{responses-Bvnk0uvc.cjs → core/responses.cjs} +5 -20
  37. package/dist/{responses-BvETUeDL.mjs → core/responses.mjs} +2 -2
  38. package/dist/{router-C6W-k6sS.cjs → core/router.cjs} +11 -69
  39. package/dist/core/router.d.cts +274 -0
  40. package/dist/core/router.d.mts +274 -0
  41. package/dist/{router-Dc9w86Wn.mjs → core/router.mjs} +5 -58
  42. package/dist/decorators/index.cjs +1 -1
  43. package/dist/decorators/index.d.cts +1 -1
  44. package/dist/decorators/index.d.mts +1 -1
  45. package/dist/decorators/index.mjs +1 -1
  46. package/dist/decorators/setup.cjs +2 -2
  47. package/dist/decorators/setup.d.cts +1 -1
  48. package/dist/decorators/setup.d.mts +1 -1
  49. package/dist/decorators/setup.mjs +2 -2
  50. package/dist/express/index.cjs +2 -265
  51. package/dist/express/index.d.cts +1 -127
  52. package/dist/express/index.d.mts +1 -127
  53. package/dist/express/index.mjs +1 -264
  54. package/dist/express/router.cjs +265 -0
  55. package/dist/express/router.d.cts +131 -0
  56. package/dist/express/router.d.mts +131 -0
  57. package/dist/express/router.mjs +265 -0
  58. package/dist/fastify/index.cjs +2 -254
  59. package/dist/fastify/index.d.cts +1 -125
  60. package/dist/fastify/index.d.mts +1 -125
  61. package/dist/fastify/index.mjs +1 -253
  62. package/dist/fastify/router.cjs +254 -0
  63. package/dist/fastify/router.d.cts +129 -0
  64. package/dist/fastify/router.d.mts +129 -0
  65. package/dist/fastify/router.mjs +254 -0
  66. package/dist/h3/index.cjs +2 -260
  67. package/dist/h3/index.d.cts +1 -128
  68. package/dist/h3/index.d.mts +1 -128
  69. package/dist/h3/index.mjs +1 -259
  70. package/dist/h3/router.cjs +260 -0
  71. package/dist/h3/router.d.cts +132 -0
  72. package/dist/h3/router.d.mts +132 -0
  73. package/dist/h3/router.mjs +260 -0
  74. package/dist/hono/index.cjs +2 -251
  75. package/dist/hono/index.d.cts +1 -130
  76. package/dist/hono/index.d.mts +1 -130
  77. package/dist/hono/index.mjs +1 -250
  78. package/dist/hono/router.cjs +251 -0
  79. package/dist/hono/router.d.cts +134 -0
  80. package/dist/hono/router.d.mts +134 -0
  81. package/dist/hono/router.mjs +251 -0
  82. package/dist/index.cjs +16 -1097
  83. package/dist/index.d.cts +9 -563
  84. package/dist/index.d.mts +9 -563
  85. package/dist/index.mjs +8 -1089
  86. package/dist/koa/index.cjs +2 -261
  87. package/dist/koa/index.d.cts +1 -131
  88. package/dist/koa/index.d.mts +1 -131
  89. package/dist/koa/index.mjs +1 -260
  90. package/dist/koa/router.cjs +261 -0
  91. package/dist/koa/router.d.cts +135 -0
  92. package/dist/koa/router.d.mts +135 -0
  93. package/dist/koa/router.mjs +261 -0
  94. package/dist/types/basic.d.cts +43 -0
  95. package/dist/types/express.d.cts +44 -0
  96. package/dist/types/express.d.mts +4 -2
  97. package/dist/types/fastify.d.cts +23 -0
  98. package/dist/types/fastify.d.mts +4 -2
  99. package/dist/types/h3.d.cts +41 -0
  100. package/dist/types/h3.d.mts +5 -6
  101. package/dist/types/hono.d.cts +21 -0
  102. package/dist/types/hono.d.mts +5 -5
  103. package/dist/types/koa.d.cts +25 -0
  104. package/dist/types/koa.d.mts +5 -5
  105. package/package.json +1 -1
  106. package/dist/router-CYBshGMl.d.mts +0 -652
  107. package/dist/router-tpnSi_Y7.d.cts +0 -652
@@ -0,0 +1,274 @@
1
+ import { ApiResourceMiddleware, ControllerAction, HttpMethod, RouterConfig } from "../types/basic.mjs";
2
+ import { Response } from "./Response.mjs";
3
+ import { Route } from "../Route.mjs";
4
+ import { Request } from "./Request.mjs";
5
+ import { ClearRouterPluginArgumentsContext, ClearRouterPluginInput, ClearRouterPluginRequestContext, PluginArgumentsResolver, PluginBind } from "./plugins.mjs";
6
+ import { Controller } from "../Controller.mjs";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+
9
+ //#region src/core/router.d.ts
10
+ /**
11
+ * @class clear-router CoreRouter
12
+ * @description Core routing logic for clear-router, shared between all supported adapters (Express.js, H3, etc.)
13
+ * @author 3m1n3nc3
14
+ * @repository https://github.com/arkstack-tmp/clear-router
15
+ */
16
+ declare abstract class CoreRouter {
17
+ protected static routerStateNamespace: string;
18
+ private static readonly stateStoreKey;
19
+ private static readonly stateBoundKey;
20
+ private static readonly defaultConfigKey;
21
+ private static readonly pluginStoreKey;
22
+ private static readonly pluginPendingKey;
23
+ private static readonly pluginHttpCtxResolversKey;
24
+ private static readonly pluginArgumentResolversKey;
25
+ private static requestProvider?;
26
+ private static responseProvider?;
27
+ static config: RouterConfig;
28
+ protected static groupContext: AsyncLocalStorage<{
29
+ prefix: string;
30
+ groupMiddlewares: any[];
31
+ }>;
32
+ protected static pluginRequestContext: AsyncLocalStorage<ClearRouterPluginRequestContext<any>>;
33
+ static routes: Set<Route<any, any, any>>;
34
+ static routesByPathMethod: Map<string, Route<any, any, any>>;
35
+ static routesByMethod: Map<"GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "HEAD", Route<any, any, any>[]>;
36
+ static routesByName: Map<string, Route<any, any, any>>;
37
+ static prefix: string;
38
+ static groupMiddlewares: any[];
39
+ static globalMiddlewares: any[];
40
+ /**
41
+ * Resets the router to it's default state
42
+ */
43
+ static reset(): typeof CoreRouter;
44
+ protected static createBaseConfig(): RouterConfig;
45
+ protected static mergeConfig(target: RouterConfig, source?: RouterConfig): RouterConfig;
46
+ protected static getDefaultConfig(): RouterConfig;
47
+ protected static resolveStateNamespace(): string;
48
+ protected static getStateStore(): Record<string, any>;
49
+ protected static getPluginStore(): Set<string>;
50
+ protected static getPluginPendingStore(): Set<Promise<void>>;
51
+ protected static getPluginArgumentResolvers(): Set<PluginArgumentsResolver>;
52
+ protected static getPluginHttpCtxResolvers(): Set<PluginArgumentsResolver>;
53
+ protected static createDefaultState(): {
54
+ config: RouterConfig;
55
+ groupContext: AsyncLocalStorage<{
56
+ prefix: string;
57
+ groupMiddlewares: any[];
58
+ }>;
59
+ routes: Set<never>;
60
+ routesByPathMethod: Map<any, any>;
61
+ routesByMethod: Map<any, any>;
62
+ routesByName: Map<any, any>;
63
+ prefix: string;
64
+ groupMiddlewares: any[];
65
+ globalMiddlewares: any[];
66
+ };
67
+ protected static bindStateAccessors(): void;
68
+ protected static createDefaultOptionsHandler(): any;
69
+ /**
70
+ * Default configuration used for everytime the router is reset
71
+ *
72
+ * @param options
73
+ */
74
+ static configureDefaults(options?: RouterConfig): void;
75
+ /**
76
+ * Use a registered plugin
77
+ *
78
+ * @param this
79
+ * @param plugin
80
+ * @param options
81
+ * @returns
82
+ */
83
+ static use<Options = any>(plugin: ClearRouterPluginInput<Options>, options?: Options): Promise<void>;
84
+ protected static pluginsReady(): Promise<void>;
85
+ protected static getCurrentPluginRequestContext(): ClearRouterPluginRequestContext | undefined;
86
+ protected static createPluginRequestContext(ctx: any): ClearRouterPluginRequestContext;
87
+ protected static createPluginBind(): PluginBind;
88
+ protected static resolvePluginArguments(ctx: any, routeContext: Omit<ClearRouterPluginArgumentsContext, keyof ClearRouterPluginRequestContext>): Promise<any[] | undefined>;
89
+ protected static resolvePluginHttpCtx(ctx: any): Promise<void>;
90
+ protected static ensureState(): void;
91
+ /**
92
+ * Normalizes a path by ensuring it starts with a single slash and does not have trailing
93
+ * slashes, while preserving dynamic segments and parameters.
94
+ *
95
+ * @param path The path to normalize.
96
+ * @returns The normalized path.
97
+ */
98
+ static normalizePath(path: string): string;
99
+ protected static parseRouteParameters(path: string): Array<{
100
+ name: string;
101
+ field?: string;
102
+ optional: boolean;
103
+ }>;
104
+ protected static expandRoutePath(path: string): string[];
105
+ protected static routeRegistrationPaths(path: string): string[];
106
+ /**
107
+ * Configures the router with the given options, such as method override settings.
108
+ *
109
+ * @param this
110
+ * @param options
111
+ * @returns
112
+ */
113
+ static configure(this: any, options?: RouterConfig): void;
114
+ protected static resolveMethodOverride(method: string, headers: Headers | Record<string, any>, body: unknown): HttpMethod | null;
115
+ /**
116
+ * Adds a new route to the router.
117
+ *
118
+ * @param this
119
+ * @param methods
120
+ * @param path
121
+ * @param handler
122
+ * @param middlewares
123
+ */
124
+ static add(methods: HttpMethod | HttpMethod[], path: string, handler: any, middlewares?: any[] | any): Route<any, any, any>;
125
+ /**
126
+ * Define a resourceful API controller with standard CRUD routes.
127
+ *
128
+ * @param this
129
+ * @param basePath
130
+ * @param controller
131
+ * @param options
132
+ */
133
+ static apiResource(basePath: string, controller: any, options?: {
134
+ only?: ControllerAction[];
135
+ except?: ControllerAction[];
136
+ middlewares?: ApiResourceMiddleware<any>;
137
+ }): void;
138
+ /**
139
+ * Adds a new GET route to the router.
140
+ *
141
+ * @param this The router instance.
142
+ * @param path The path for the GET route.
143
+ * @param handler The handler function for the GET route.
144
+ * @param middlewares Optional middlewares to apply to the GET route.
145
+ */
146
+ static get(path: string, handler: any, middlewares?: any[] | any): Route<any, any, any>;
147
+ /**
148
+ * Adds a new POST route to the router.
149
+ *
150
+ * @param this
151
+ * @param path
152
+ * @param handler
153
+ * @param middlewares
154
+ */
155
+ static post(path: string, handler: any, middlewares?: any[] | any): Route<any, any, any>;
156
+ /**
157
+ * Adds a new PUT route to the router.
158
+ *
159
+ * @param this
160
+ * @param path
161
+ * @param handler
162
+ * @param middlewares
163
+ */
164
+ static put(path: string, handler: any, middlewares?: any[] | any): Route<any, any, any>;
165
+ /**
166
+ * Adds a new DELETE route to the router.
167
+ *
168
+ * @param this
169
+ * @param path
170
+ * @param handler
171
+ * @param middlewares
172
+ */
173
+ static delete(path: string, handler: any, middlewares?: any[] | any): Route<any, any, any>;
174
+ /**
175
+ * Adds a new PATCH route to the router.
176
+ *
177
+ * @param this
178
+ * @param path
179
+ * @param handler
180
+ * @param middlewares
181
+ */
182
+ static patch(path: string, handler: any, middlewares?: any[] | any): Route<any, any, any>;
183
+ /**
184
+ * Adds a new OPTIONS route to the router.
185
+ *
186
+ * @param this
187
+ * @param path
188
+ * @param handler
189
+ * @param middlewares
190
+ */
191
+ static options(path: string, handler: any, middlewares?: any[] | any): Route<any, any, any>;
192
+ /**
193
+ * Adds a new HEAD route to the router.
194
+ *
195
+ * @param this
196
+ * @param path
197
+ * @param handler
198
+ * @param middlewares
199
+ */
200
+ static head(path: string, handler: any, middlewares?: any[] | any): Route<any, any, any>;
201
+ /**
202
+ * Defines a group of routes with a common prefix.
203
+ *
204
+ * @param this
205
+ * @param prefix
206
+ * @param callback
207
+ * @param middlewares
208
+ */
209
+ static group(prefix: string, callback: () => void | Promise<void>, middlewares?: any[]): Promise<void>;
210
+ /**
211
+ * Adds global middlewares to the router, which will be applied to all routes.
212
+ *
213
+ * @param this
214
+ * @param middlewares
215
+ * @param callback
216
+ */
217
+ static middleware(middlewares: any[], callback: () => void): void;
218
+ /**
219
+ * Retrieves all registered routes in the router, optionally organized by path or method
220
+ * for easier access and management.
221
+ *
222
+ * @param this
223
+ */
224
+ static allRoutes(): Array<Route<any, any, any>>;
225
+ /**
226
+ * @param this
227
+ * @param type - 'path' to get routes organized by path
228
+ */
229
+ static allRoutes(type: 'path'): Record<string, Route<any, any, any>>;
230
+ /**
231
+ * @param this
232
+ * @param type - 'method' to get routes organized by method
233
+ */
234
+ static allRoutes(type: 'method'): { [method in Uppercase<HttpMethod>]?: Array<Route<any, any, any>> };
235
+ static allRoutes(type: 'name'): Record<string, Route<any, any, any>>;
236
+ static route(name: string): Route<any, any, any> | undefined;
237
+ static url(name: string, params?: Record<string, any>): string | undefined;
238
+ /**
239
+ * Provide a class that will overide the base Request instance
240
+ *
241
+ * @param provider
242
+ */
243
+ static setRequestProvider(provider: typeof Request): void;
244
+ /**
245
+ * Provide a class that will overide the base Response instance
246
+ *
247
+ * @param provider
248
+ */
249
+ static setResponseProvider(provider: typeof Response): void;
250
+ private static hasPackageInstalled;
251
+ /**
252
+ * Provide a class that will overide the base Response instance
253
+ *
254
+ * @param provider
255
+ */
256
+ private static initializeInstance;
257
+ protected static resolveHandler(route: Route<any, any, any>): {
258
+ handlerFunction: ((ctx: any, req: Request) => any | Promise<any>) | null;
259
+ instance: Controller<any> | null;
260
+ bindingTarget?: object;
261
+ bindingMethod?: PropertyKey;
262
+ bindingHandler?: object;
263
+ bindingMetadata?: object;
264
+ };
265
+ protected static callHandler(handlerFunction: (ctx: any, req: Request) => any | Promise<any>, ctx: any, bindingTarget?: object, bindingMethod?: PropertyKey, bindingHandler?: object, bindingMetadata?: object): Promise<any>;
266
+ protected static bindRequestToInstance(ctx: any, instance: Controller<any> | Route<any, any, any> | null, route: Route<any, any, any>, payload: {
267
+ body: Record<string, any>;
268
+ query: Record<string, any>;
269
+ params: Record<string, any>;
270
+ method?: HttpMethod | string;
271
+ }): void;
272
+ }
273
+ //#endregion
274
+ export { CoreRouter };
@@ -1,63 +1,10 @@
1
- import { a as getStandardMetadata, c as Request, i as getDesignParamTypes, n as Container, o as isClass, r as getBindingMetadataFromTargets, s as Response } from "./bindings-XLDXFpHZ.mjs";
1
+ import { Request } from "./Request.mjs";
2
+ import { Response } from "./Response.mjs";
3
+ import { Container, getBindingMetadataFromTargets, getDesignParamTypes, getStandardMetadata, isClass } from "./bindings.mjs";
4
+ import { Route } from "../Route.mjs";
2
5
  import { createRequire } from "node:module";
3
6
  import { AsyncLocalStorage } from "node:async_hooks";
4
7
 
5
- //#region src/Route.ts
6
- var Route = class {
7
- ctx;
8
- body = {};
9
- query = {};
10
- params = {};
11
- clearRequest;
12
- methods;
13
- path;
14
- registrationPaths;
15
- parameters;
16
- routeName;
17
- handler;
18
- middlewares;
19
- controllerName;
20
- actionName;
21
- handlerType;
22
- middlewareCount;
23
- constructor(methods, path, handler, middlewares = [], options = {}) {
24
- this.methods = methods;
25
- this.path = path;
26
- this.registrationPaths = options.registrationPaths || [path];
27
- this.parameters = options.parameters || [];
28
- this.handler = handler;
29
- this.middlewares = middlewares;
30
- this.handlerType = Array.isArray(handler) ? "controller" : "function";
31
- this.middlewareCount = middlewares.length;
32
- this.controllerName = Array.isArray(handler) ? handler[0]?.name : void 0;
33
- this.actionName = Array.isArray(handler) ? handler[1] : typeof handler === "function" ? handler.constructor.name ?? handler.name : void 0;
34
- this.onName = options.onName;
35
- }
36
- onName;
37
- name(name) {
38
- const previousName = this.routeName;
39
- this.routeName = name;
40
- this.onName?.(name, this, previousName);
41
- return this;
42
- }
43
- toPath(params = {}) {
44
- return this.path.replace(/\/?\{([^{}]+)\}/g, (segment, raw) => {
45
- const optional = raw.endsWith("?");
46
- const [rawName, rawField] = (optional ? raw.slice(0, -1) : raw).split(":", 2);
47
- const name = rawName.trim();
48
- const field = rawField?.trim();
49
- const value = params[name];
50
- const resolved = field && value && typeof value === "object" ? value[field] : value;
51
- if (typeof resolved === "undefined" || resolved === null || resolved === "") {
52
- if (optional) return "";
53
- throw new Error(`Missing required route parameter: ${name}`);
54
- }
55
- return `${segment.startsWith("/") ? "/" : ""}${encodeURIComponent(String(resolved))}`;
56
- }) || "/";
57
- }
58
- };
59
-
60
- //#endregion
61
8
  //#region src/core/router.ts
62
9
  /**
63
10
  * @class clear-router CoreRouter
@@ -856,4 +803,4 @@ var CoreRouter = class {
856
803
  };
857
804
 
858
805
  //#endregion
859
- export { CoreRouter as t };
806
+ export { CoreRouter };
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_bindings = require('../bindings-CLsZjOEy.cjs');
2
+ const require_bindings = require('../core/bindings.cjs');
3
3
 
4
4
  exports.Bind = require_bindings.Bind;
5
5
  exports.Container = require_bindings.Container;
@@ -1,2 +1,2 @@
1
- import { a as BindValue, i as BindToken, n as BindDecorator, o as Container, r as BindFactory, t as Bind } from "../bindings-CxvtC8XS.cjs";
1
+ import { Bind, BindDecorator, BindFactory, BindToken, BindValue, Container } from "../core/bindings.cjs";
2
2
  export { Bind, type BindDecorator, type BindFactory, type BindToken, type BindValue, Container };
@@ -1,2 +1,2 @@
1
- import { a as BindValue, i as BindToken, n as BindDecorator, o as Container, r as BindFactory, t as Bind } from "../bindings-CNL7bpz5.mjs";
1
+ import { Bind, BindDecorator, BindFactory, BindToken, BindValue, Container } from "../core/bindings.mjs";
2
2
  export { Bind, type BindDecorator, type BindFactory, type BindToken, type BindValue, Container };
@@ -1,3 +1,3 @@
1
- import { n as Container, t as Bind } from "../bindings-XLDXFpHZ.mjs";
1
+ import { Bind, Container } from "../core/bindings.mjs";
2
2
 
3
3
  export { Bind, Container };
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_bindings = require('../bindings-CLsZjOEy.cjs');
3
- const require_router = require('../router-C6W-k6sS.cjs');
2
+ const require_bindings = require('../core/bindings.cjs');
3
+ const require_router = require('../core/router.cjs');
4
4
  require('./index.cjs');
5
5
  require("reflect-metadata");
6
6
 
@@ -1,2 +1,2 @@
1
- import { a as BindValue, i as BindToken, n as BindDecorator, o as Container, r as BindFactory, t as Bind } from "../bindings-CxvtC8XS.cjs";
1
+ import { Bind, BindDecorator, BindFactory, BindToken, BindValue, Container } from "../core/bindings.cjs";
2
2
  export { Bind, BindDecorator, BindFactory, BindToken, BindValue, Container };
@@ -1,3 +1,3 @@
1
- import { a as BindValue, i as BindToken, n as BindDecorator, o as Container, r as BindFactory, t as Bind } from "../bindings-CNL7bpz5.mjs";
1
+ import { Bind, BindDecorator, BindFactory, BindToken, BindValue, Container } from "../core/bindings.mjs";
2
2
  import "reflect-metadata";
3
3
  export { Bind, BindDecorator, BindFactory, BindToken, BindValue, Container };
@@ -1,5 +1,5 @@
1
- import { n as Container, t as Bind } from "../bindings-XLDXFpHZ.mjs";
2
- import { t as CoreRouter } from "../router-Dc9w86Wn.mjs";
1
+ import { Bind, Container } from "../core/bindings.mjs";
2
+ import { CoreRouter } from "../core/router.mjs";
3
3
  import "./index.mjs";
4
4
  import "reflect-metadata";
5
5
 
@@ -1,267 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- require('../bindings-CLsZjOEy.cjs');
3
- const require_router = require('../router-C6W-k6sS.cjs');
4
- const require_responses = require('../responses-Bvnk0uvc.cjs');
2
+ const require_router = require('./router.cjs');
5
3
 
6
- //#region src/express/router.ts
7
- /**
8
- * @class clear-router Express Router
9
- * @description Laravel-style routing system for Express.js and H3 with support for CommonJS, ESM, and TypeScript
10
- * @author Refkinscallv
11
- * @author 3m1n3nc3
12
- * @repository https://github.com/arkstack-tmp/clear-router
13
- */
14
- var Router = class Router extends require_router.CoreRouter {
15
- static routerStateNamespace = "clear-router:express";
16
- static ensureRequestBodyAccessor(req) {
17
- if (typeof req.getBody !== "function") req.getBody = () => req.body ?? {};
18
- }
19
- static async sendReturnValue(ctx, value, method, path) {
20
- const { req, res } = ctx;
21
- if (require_responses.responseWasSent(res) || value === res || require_responses.responseWasSent(value)) return;
22
- const meta = require_responses.resolveResponseMeta(value, {
23
- headers: req.headers,
24
- method,
25
- path
26
- });
27
- if (!meta) return;
28
- res.status(meta.status);
29
- meta.headers?.forEach((headerValue, key) => {
30
- res.setHeader(key, headerValue);
31
- });
32
- if (require_responses.isFetchResponse(meta.body)) {
33
- meta.body.headers.forEach((headerValue, key) => {
34
- res.setHeader(key, headerValue);
35
- });
36
- res.status(meta.body.status);
37
- const body = Buffer.from(await meta.body.arrayBuffer());
38
- res.send(body);
39
- return;
40
- }
41
- if (meta.contentType && !res.getHeader("Content-Type")) res.setHeader("Content-Type", meta.contentType);
42
- if (meta.isEmpty) {
43
- res.sendStatus(meta.status);
44
- return;
45
- }
46
- res.send(meta.body);
47
- }
48
- /**
49
- * Adds a new route to the router.
50
- *
51
- * @param methods
52
- * @param path
53
- * @param handler
54
- * @param middlewares
55
- */
56
- static add(methods, path, handler, middlewares) {
57
- return super.add(methods, path, handler, middlewares);
58
- }
59
- /**
60
- * Define a resourceful API controller with standard CRUD routes
61
- *
62
- * @param basePath
63
- * @param controller
64
- * @param options
65
- */
66
- static apiResource(basePath, controller, options) {
67
- super.apiResource(basePath, controller, options);
68
- }
69
- /**
70
- * Adds a new GET route to the router.
71
- *
72
- * @param path
73
- * @param handler
74
- * @param middlewares
75
- */
76
- static get(path, handler, middlewares) {
77
- return super.get(path, handler, middlewares);
78
- }
79
- /**
80
- * Adds a new POST route to the router.
81
- *
82
- * @param path
83
- * @param handler
84
- * @param middlewares
85
- */
86
- static post(path, handler, middlewares) {
87
- return super.post(path, handler, middlewares);
88
- }
89
- /**
90
- * Adds a new PUT route to the router.
91
- *
92
- * @param path
93
- * @param handler
94
- * @param middlewares
95
- */
96
- static put(path, handler, middlewares) {
97
- return super.put(path, handler, middlewares);
98
- }
99
- /**
100
- * Adds a new DELETE route to the router.
101
- *
102
- * @param path
103
- * @param handler
104
- * @param middlewares
105
- */
106
- static delete(path, handler, middlewares) {
107
- return super.delete(path, handler, middlewares);
108
- }
109
- /**
110
- * Adds a new PATCH route to the router.
111
- *
112
- * @param path
113
- * @param handler
114
- * @param middlewares
115
- */
116
- static patch(path, handler, middlewares) {
117
- return super.patch(path, handler, middlewares);
118
- }
119
- /**
120
- * Adds a new OPTIONS route to the router.
121
- *
122
- * @param path
123
- * @param handler
124
- * @param middlewares
125
- */
126
- static options(path, handler, middlewares) {
127
- return super.options(path, handler, middlewares);
128
- }
129
- /**
130
- * Adds a new HEAD route to the router.
131
- *
132
- * @param path
133
- * @param handler
134
- * @param middlewares
135
- */
136
- static head(path, handler, middlewares) {
137
- return super.head(path, handler, middlewares);
138
- }
139
- /**
140
- * Defines a group of routes with a common prefix.
141
- *
142
- * @param prefix
143
- * @param callback
144
- * @param middlewares
145
- */
146
- static async group(prefix, callback, middlewares) {
147
- await super.group(prefix, callback, middlewares);
148
- }
149
- /**
150
- * Adds global middlewares to the router, which will be applied to all routes.
151
- *
152
- * @param middlewares
153
- * @param callback
154
- */
155
- static middleware(middlewares, callback) {
156
- super.middleware(middlewares, callback);
157
- }
158
- static allRoutes(type) {
159
- return super.allRoutes(type);
160
- }
161
- static route(name) {
162
- return super.route(name);
163
- }
164
- static async apply(router) {
165
- for (const route of Array.from(this.routes)) {
166
- let handlerFunction = null;
167
- let instance = null;
168
- let bindingTarget;
169
- let bindingMethod;
170
- let bindingHandler;
171
- let bindingMetadata;
172
- try {
173
- const resolved = this.resolveHandler(route);
174
- handlerFunction = resolved.handlerFunction;
175
- instance = resolved.instance;
176
- bindingTarget = resolved.bindingTarget;
177
- bindingMethod = resolved.bindingMethod;
178
- bindingHandler = resolved.bindingHandler;
179
- bindingMetadata = resolved.bindingMetadata;
180
- } catch (error) {
181
- console.error(`[ROUTES] Error setting up route ${route.path}:`, error.message);
182
- throw error;
183
- }
184
- if (!handlerFunction) continue;
185
- for (const method of route.methods) {
186
- const allowedMethods = [
187
- "get",
188
- "post",
189
- "put",
190
- "delete",
191
- "patch",
192
- "options",
193
- "head"
194
- ];
195
- if (method === "options" && route.methods.length > 1) continue;
196
- if (!allowedMethods.includes(method)) {
197
- const error = /* @__PURE__ */ new Error(`Invalid HTTP method: ${method} for route: ${route.path}`);
198
- console.error("[ROUTES]", error.message);
199
- throw error;
200
- }
201
- for (const registrationPath of route.registrationPaths) router[method](registrationPath, (req, _res, next) => {
202
- Router.ensureRequestBodyAccessor(req);
203
- const override = Router.resolveMethodOverride(req.method, req.headers, req.body);
204
- if (method === "post" && override && override !== "post") return next("route");
205
- return next();
206
- }, ...route.middlewares || [], async (req, res, next) => {
207
- try {
208
- Router.ensureRequestBodyAccessor(req);
209
- const ctx = {
210
- req,
211
- res,
212
- next
213
- };
214
- const inst = instance ?? route;
215
- Router.bindRequestToInstance(ctx, inst, route, {
216
- body: ctx.req.getBody(),
217
- query: ctx.req.query,
218
- params: ctx.req.params,
219
- method
220
- });
221
- const result = await Router.callHandler(handlerFunction, ctx, bindingTarget, bindingMethod, bindingHandler, bindingMetadata);
222
- const resolved = await Promise.resolve(result);
223
- const outgoing = typeof resolved === "undefined" && ctx.clearResponse?.sent ? ctx.clearResponse : resolved;
224
- await Router.sendReturnValue(ctx, outgoing, method, route.path);
225
- } catch (error) {
226
- next(error);
227
- }
228
- });
229
- if ([
230
- "put",
231
- "patch",
232
- "delete"
233
- ].includes(method)) for (const registrationPath of route.registrationPaths) router.post(registrationPath, (req, _res, next) => {
234
- Router.ensureRequestBodyAccessor(req);
235
- if (Router.resolveMethodOverride(req.method, req.headers, req.body) !== method) return next("route");
236
- req.method = method.toUpperCase();
237
- return next();
238
- }, ...route.middlewares || [], async (req, res, next) => {
239
- try {
240
- Router.ensureRequestBodyAccessor(req);
241
- const ctx = {
242
- req,
243
- res,
244
- next
245
- };
246
- const inst = instance ?? route;
247
- Router.bindRequestToInstance(ctx, inst, route, {
248
- body: ctx.req.getBody(),
249
- query: ctx.req.query,
250
- params: ctx.req.params,
251
- method
252
- });
253
- const result = await Router.callHandler(handlerFunction, ctx, bindingTarget, bindingMethod, bindingHandler, bindingMetadata);
254
- const resolved = await Promise.resolve(result);
255
- const outgoing = typeof resolved === "undefined" && ctx.clearResponse?.sent ? ctx.clearResponse : resolved;
256
- await Router.sendReturnValue(ctx, outgoing, method, route.path);
257
- } catch (error) {
258
- next(error);
259
- }
260
- });
261
- }
262
- }
263
- }
264
- };
265
-
266
- //#endregion
267
- exports.Router = Router;
4
+ exports.Router = require_router;