clear-router 2.4.0 → 2.5.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.
@@ -0,0 +1,244 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_router = require('../router-CHg0pZUO.cjs');
3
+ const require_responses = require('../responses-r-O3jS-S.cjs');
4
+
5
+ //#region src/koa/router.ts
6
+ /**
7
+ * @class clear-router Koa Router
8
+ * @description Laravel-style routing system for Koa using @koa/router and shared clear-router core
9
+ * @author 3m1n3nc3
10
+ * @repository https://github.com/toneflix/clear-router
11
+ */
12
+ var Router = class Router extends require_router.CoreRouter {
13
+ static routerStateNamespace = "clear-router:koa";
14
+ static bodyCache = /* @__PURE__ */ new WeakMap();
15
+ static async readBodyCached(ctx) {
16
+ if (this.bodyCache.has(ctx)) {
17
+ const cached = this.bodyCache.get(ctx) || {};
18
+ ctx.request.getBody = () => cached;
19
+ return cached;
20
+ }
21
+ let body = ctx.request.body && typeof ctx.request.body === "object" ? ctx.request.body : {};
22
+ if (!Object.keys(body).length && !["GET", "HEAD"].includes(ctx.method.toUpperCase())) body = await this.readBody(ctx);
23
+ ctx.request.getBody = () => body;
24
+ this.bodyCache.set(ctx, body);
25
+ return body;
26
+ }
27
+ static async readBody(ctx) {
28
+ const contentType = String(ctx.get("content-type") || "").toLowerCase();
29
+ const chunks = [];
30
+ for await (const chunk of ctx.req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
31
+ const raw = Buffer.concat(chunks).toString("utf8");
32
+ if (!raw) return {};
33
+ if (contentType.includes("application/json")) return JSON.parse(raw);
34
+ if (contentType.includes("application/x-www-form-urlencoded")) return Object.fromEntries(new URLSearchParams(raw));
35
+ return {};
36
+ }
37
+ static async sendReturnValue(ctx, value, method, path) {
38
+ if (ctx.respond === false || ctx.headerSent) return value;
39
+ const meta = require_responses.resolveResponseMeta(value, {
40
+ headers: ctx.headers,
41
+ method,
42
+ path,
43
+ status: ctx.status && ctx.status !== 404 ? ctx.status : void 0
44
+ });
45
+ if (!meta) return void 0;
46
+ ctx.status = meta.status;
47
+ if (require_responses.isFetchResponse(meta.body)) {
48
+ meta.body.headers.forEach((headerValue, key) => {
49
+ ctx.set(key, headerValue);
50
+ });
51
+ ctx.status = meta.body.status;
52
+ ctx.body = Buffer.from(await meta.body.arrayBuffer());
53
+ return ctx.body;
54
+ }
55
+ if (meta.contentType) ctx.type = meta.contentType;
56
+ ctx.body = meta.isEmpty ? null : meta.body;
57
+ return ctx.body;
58
+ }
59
+ /**
60
+ * Adds a new route to the router.
61
+ *
62
+ * @param methods
63
+ * @param path
64
+ * @param handler
65
+ * @param middlewares
66
+ */
67
+ static add(methods, path, handler, middlewares) {
68
+ super.add(methods, path, handler, middlewares);
69
+ }
70
+ /**
71
+ * Define a resourceful API controller with standard CRUD routes
72
+ *
73
+ * @param basePath
74
+ * @param controller
75
+ * @param options
76
+ */
77
+ static apiResource(basePath, controller, options) {
78
+ super.apiResource(basePath, controller, options);
79
+ }
80
+ /**
81
+ * Define a GET route
82
+ *
83
+ * @param path
84
+ * @param handler
85
+ * @param middlewares
86
+ */
87
+ static get(path, handler, middlewares) {
88
+ super.get(path, handler, middlewares);
89
+ }
90
+ /**
91
+ * Define a POST route
92
+ *
93
+ * @param path
94
+ * @param handler
95
+ * @param middlewares
96
+ */
97
+ static post(path, handler, middlewares) {
98
+ super.post(path, handler, middlewares);
99
+ }
100
+ /**
101
+ * Define a PUT route
102
+ *
103
+ * @param path
104
+ * @param handler
105
+ * @param middlewares
106
+ */
107
+ static put(path, handler, middlewares) {
108
+ super.put(path, handler, middlewares);
109
+ }
110
+ /**
111
+ * Define a DELETE route
112
+ *
113
+ * @param path
114
+ * @param handler
115
+ * @param middlewares
116
+ */
117
+ static delete(path, handler, middlewares) {
118
+ super.delete(path, handler, middlewares);
119
+ }
120
+ /**
121
+ * Define a PATCH route
122
+ *
123
+ * @param path
124
+ * @param handler
125
+ * @param middlewares
126
+ */
127
+ static patch(path, handler, middlewares) {
128
+ super.patch(path, handler, middlewares);
129
+ }
130
+ /**
131
+ * Define an OPTIONS route
132
+ *
133
+ * @param path
134
+ * @param handler
135
+ * @param middlewares
136
+ */
137
+ static options(path, handler, middlewares) {
138
+ super.options(path, handler, middlewares);
139
+ }
140
+ /**
141
+ * Adds a new HEAD route to the router.
142
+ *
143
+ * @param this
144
+ * @param path
145
+ * @param handler
146
+ * @param middlewares
147
+ */
148
+ static head(path, handler, middlewares) {
149
+ super.head(path, handler, middlewares);
150
+ }
151
+ /**
152
+ * Defines a group of routes with a common prefix.
153
+ *
154
+ * @param prefix
155
+ * @param callback
156
+ * @param middlewares
157
+ */
158
+ static async group(prefix, callback, middlewares) {
159
+ await super.group(prefix, callback, middlewares);
160
+ }
161
+ /**
162
+ * Apply middlewares to a group of routes defined within the callback
163
+ *
164
+ * @param middlewares - Middleware or array of middlewares to apply
165
+ * @param callback - Function that defines the routes to which the middlewares will be applied
166
+ */
167
+ static middleware(middlewares, callback) {
168
+ super.middleware(middlewares, callback);
169
+ }
170
+ static allRoutes(type) {
171
+ return super.allRoutes(type);
172
+ }
173
+ /**
174
+ * Apply the defined routes to a @koa/router instance
175
+ *
176
+ * @param router @koa/router instance
177
+ * @returns The @koa/router instance with the applied routes
178
+ */
179
+ static apply(router) {
180
+ for (const route of this.routes) {
181
+ let handlerFunction = null;
182
+ let instance = null;
183
+ try {
184
+ const resolved = this.resolveHandler(route);
185
+ handlerFunction = resolved.handlerFunction;
186
+ instance = resolved.instance;
187
+ } catch (error) {
188
+ console.error(`[ROUTES] Error setting up route ${route.path}:`, error.message);
189
+ throw error;
190
+ }
191
+ if (!handlerFunction) continue;
192
+ for (const method of route.methods) {
193
+ const allowedMethods = [
194
+ "get",
195
+ "post",
196
+ "put",
197
+ "delete",
198
+ "patch",
199
+ "options",
200
+ "head"
201
+ ];
202
+ if (method === "options" && route.methods.length > 1) continue;
203
+ if (!allowedMethods.includes(method)) throw new Error(`Invalid HTTP method: ${method} for route: ${route.path}`);
204
+ router[method](route.path, ...route.middlewares || [], async (context, next) => {
205
+ const ctx = context;
206
+ const reqBody = await Router.readBodyCached(ctx);
207
+ const override = Router.resolveMethodOverride(ctx.method, ctx.headers, reqBody);
208
+ if (method === "post" && override && override !== "post") return next();
209
+ const inst = instance ?? route;
210
+ Router.bindRequestToInstance(ctx, inst, route, {
211
+ body: reqBody,
212
+ query: ctx.query,
213
+ params: ctx.params ?? {}
214
+ });
215
+ const result = handlerFunction(ctx, inst.clearRequest);
216
+ const resolved = await Promise.resolve(result);
217
+ return Router.sendReturnValue(ctx, resolved, method, route.path);
218
+ });
219
+ if ([
220
+ "put",
221
+ "patch",
222
+ "delete"
223
+ ].includes(method)) router.post(route.path, ...route.middlewares || [], async (context, next) => {
224
+ const ctx = context;
225
+ const reqBody = await Router.readBodyCached(ctx);
226
+ if (Router.resolveMethodOverride(ctx.method, ctx.headers, reqBody) !== method) return next();
227
+ const inst = instance ?? route;
228
+ Router.bindRequestToInstance(ctx, inst, route, {
229
+ body: reqBody,
230
+ query: ctx.query,
231
+ params: ctx.params ?? {}
232
+ });
233
+ const result = handlerFunction(ctx, inst.clearRequest);
234
+ const resolved = await Promise.resolve(result);
235
+ return Router.sendReturnValue(ctx, resolved, method, route.path);
236
+ });
237
+ }
238
+ }
239
+ return router;
240
+ }
241
+ };
242
+
243
+ //#endregion
244
+ exports.Router = Router;
@@ -0,0 +1,147 @@
1
+ import { d as ApiResourceMiddleware, f as ControllerAction, m as HttpMethod, n as ClearRequest, p as ControllerHandler, r as Route, t as CoreRouter } from "../router-CS_2XQ7I.cjs";
2
+ import Koa from "koa";
3
+ import Router$1 from "@koa/router";
4
+
5
+ //#region types/koa.d.ts
6
+ interface RequestWithGetBody extends Koa.Request {
7
+ getBody: () => Record<string, any>;
8
+ body?: any;
9
+ }
10
+ interface HttpContext extends Koa.Context {
11
+ request: RequestWithGetBody;
12
+ params: Record<string, any>;
13
+ query: Record<string, any>;
14
+ }
15
+ type RouteHandler = (ctx: HttpContext, req: ClearRequest) => any | Promise<any>;
16
+ type Handler = RouteHandler | ControllerHandler;
17
+ type Middleware = Koa.Middleware<any, any>;
18
+ type KoaRouterApp = Router$1<any, any>;
19
+ //#endregion
20
+ //#region src/koa/router.d.ts
21
+ /**
22
+ * @class clear-router Koa Router
23
+ * @description Laravel-style routing system for Koa using @koa/router and shared clear-router core
24
+ * @author 3m1n3nc3
25
+ * @repository https://github.com/toneflix/clear-router
26
+ */
27
+ declare class Router extends CoreRouter {
28
+ protected static routerStateNamespace: string;
29
+ private static readonly bodyCache;
30
+ private static readBodyCached;
31
+ private static readBody;
32
+ private static sendReturnValue;
33
+ /**
34
+ * Adds a new route to the router.
35
+ *
36
+ * @param methods
37
+ * @param path
38
+ * @param handler
39
+ * @param middlewares
40
+ */
41
+ static add(methods: HttpMethod | HttpMethod[], path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
42
+ /**
43
+ * Define a resourceful API controller with standard CRUD routes
44
+ *
45
+ * @param basePath
46
+ * @param controller
47
+ * @param options
48
+ */
49
+ static apiResource(basePath: string, controller: any, options?: {
50
+ only?: ControllerAction[];
51
+ except?: ControllerAction[];
52
+ middlewares?: ApiResourceMiddleware<Middleware>;
53
+ }): void;
54
+ /**
55
+ * Define a GET route
56
+ *
57
+ * @param path
58
+ * @param handler
59
+ * @param middlewares
60
+ */
61
+ static get(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
62
+ /**
63
+ * Define a POST route
64
+ *
65
+ * @param path
66
+ * @param handler
67
+ * @param middlewares
68
+ */
69
+ static post(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
70
+ /**
71
+ * Define a PUT route
72
+ *
73
+ * @param path
74
+ * @param handler
75
+ * @param middlewares
76
+ */
77
+ static put(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
78
+ /**
79
+ * Define a DELETE route
80
+ *
81
+ * @param path
82
+ * @param handler
83
+ * @param middlewares
84
+ */
85
+ static delete(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
86
+ /**
87
+ * Define a PATCH route
88
+ *
89
+ * @param path
90
+ * @param handler
91
+ * @param middlewares
92
+ */
93
+ static patch(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
94
+ /**
95
+ * Define an OPTIONS route
96
+ *
97
+ * @param path
98
+ * @param handler
99
+ * @param middlewares
100
+ */
101
+ static options(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
102
+ /**
103
+ * Adds a new HEAD route to the router.
104
+ *
105
+ * @param this
106
+ * @param path
107
+ * @param handler
108
+ * @param middlewares
109
+ */
110
+ static head(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
111
+ /**
112
+ * Defines a group of routes with a common prefix.
113
+ *
114
+ * @param prefix
115
+ * @param callback
116
+ * @param middlewares
117
+ */
118
+ static group(prefix: string, callback: () => void | Promise<void>, middlewares?: Middleware[]): Promise<void>;
119
+ /**
120
+ * Apply middlewares to a group of routes defined within the callback
121
+ *
122
+ * @param middlewares - Middleware or array of middlewares to apply
123
+ * @param callback - Function that defines the routes to which the middlewares will be applied
124
+ */
125
+ static middleware(middlewares: Middleware[], callback: () => void): void;
126
+ /**
127
+ * Get all defined routes, optionally organized by path or method
128
+ */
129
+ static allRoutes(): Array<Route<HttpContext, Middleware, Handler>>;
130
+ /**
131
+ * @param type - 'path' to get routes organized by path
132
+ */
133
+ static allRoutes(type: 'path'): Record<string, Route<HttpContext, Middleware, Handler>>;
134
+ /**
135
+ * @param type - 'method' to get routes organized by method
136
+ */
137
+ static allRoutes(type: 'method'): { [method in Uppercase<HttpMethod>]?: Array<Route<HttpContext, Middleware, Handler>> };
138
+ /**
139
+ * Apply the defined routes to a @koa/router instance
140
+ *
141
+ * @param router @koa/router instance
142
+ * @returns The @koa/router instance with the applied routes
143
+ */
144
+ static apply(router: KoaRouterApp): KoaRouterApp;
145
+ }
146
+ //#endregion
147
+ export { Router };
@@ -0,0 +1,147 @@
1
+ import { d as ApiResourceMiddleware, f as ControllerAction, m as HttpMethod, n as ClearRequest, p as ControllerHandler, r as Route, t as CoreRouter } from "../router-_w2VzMQF.mjs";
2
+ import Koa from "koa";
3
+ import Router$1 from "@koa/router";
4
+
5
+ //#region types/koa.d.ts
6
+ interface RequestWithGetBody extends Koa.Request {
7
+ getBody: () => Record<string, any>;
8
+ body?: any;
9
+ }
10
+ interface HttpContext extends Koa.Context {
11
+ request: RequestWithGetBody;
12
+ params: Record<string, any>;
13
+ query: Record<string, any>;
14
+ }
15
+ type RouteHandler = (ctx: HttpContext, req: ClearRequest) => any | Promise<any>;
16
+ type Handler = RouteHandler | ControllerHandler;
17
+ type Middleware = Koa.Middleware<any, any>;
18
+ type KoaRouterApp = Router$1<any, any>;
19
+ //#endregion
20
+ //#region src/koa/router.d.ts
21
+ /**
22
+ * @class clear-router Koa Router
23
+ * @description Laravel-style routing system for Koa using @koa/router and shared clear-router core
24
+ * @author 3m1n3nc3
25
+ * @repository https://github.com/toneflix/clear-router
26
+ */
27
+ declare class Router extends CoreRouter {
28
+ protected static routerStateNamespace: string;
29
+ private static readonly bodyCache;
30
+ private static readBodyCached;
31
+ private static readBody;
32
+ private static sendReturnValue;
33
+ /**
34
+ * Adds a new route to the router.
35
+ *
36
+ * @param methods
37
+ * @param path
38
+ * @param handler
39
+ * @param middlewares
40
+ */
41
+ static add(methods: HttpMethod | HttpMethod[], path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
42
+ /**
43
+ * Define a resourceful API controller with standard CRUD routes
44
+ *
45
+ * @param basePath
46
+ * @param controller
47
+ * @param options
48
+ */
49
+ static apiResource(basePath: string, controller: any, options?: {
50
+ only?: ControllerAction[];
51
+ except?: ControllerAction[];
52
+ middlewares?: ApiResourceMiddleware<Middleware>;
53
+ }): void;
54
+ /**
55
+ * Define a GET route
56
+ *
57
+ * @param path
58
+ * @param handler
59
+ * @param middlewares
60
+ */
61
+ static get(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
62
+ /**
63
+ * Define a POST route
64
+ *
65
+ * @param path
66
+ * @param handler
67
+ * @param middlewares
68
+ */
69
+ static post(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
70
+ /**
71
+ * Define a PUT route
72
+ *
73
+ * @param path
74
+ * @param handler
75
+ * @param middlewares
76
+ */
77
+ static put(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
78
+ /**
79
+ * Define a DELETE route
80
+ *
81
+ * @param path
82
+ * @param handler
83
+ * @param middlewares
84
+ */
85
+ static delete(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
86
+ /**
87
+ * Define a PATCH route
88
+ *
89
+ * @param path
90
+ * @param handler
91
+ * @param middlewares
92
+ */
93
+ static patch(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
94
+ /**
95
+ * Define an OPTIONS route
96
+ *
97
+ * @param path
98
+ * @param handler
99
+ * @param middlewares
100
+ */
101
+ static options(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
102
+ /**
103
+ * Adds a new HEAD route to the router.
104
+ *
105
+ * @param this
106
+ * @param path
107
+ * @param handler
108
+ * @param middlewares
109
+ */
110
+ static head(path: string, handler: Handler, middlewares?: Middleware[] | Middleware): void;
111
+ /**
112
+ * Defines a group of routes with a common prefix.
113
+ *
114
+ * @param prefix
115
+ * @param callback
116
+ * @param middlewares
117
+ */
118
+ static group(prefix: string, callback: () => void | Promise<void>, middlewares?: Middleware[]): Promise<void>;
119
+ /**
120
+ * Apply middlewares to a group of routes defined within the callback
121
+ *
122
+ * @param middlewares - Middleware or array of middlewares to apply
123
+ * @param callback - Function that defines the routes to which the middlewares will be applied
124
+ */
125
+ static middleware(middlewares: Middleware[], callback: () => void): void;
126
+ /**
127
+ * Get all defined routes, optionally organized by path or method
128
+ */
129
+ static allRoutes(): Array<Route<HttpContext, Middleware, Handler>>;
130
+ /**
131
+ * @param type - 'path' to get routes organized by path
132
+ */
133
+ static allRoutes(type: 'path'): Record<string, Route<HttpContext, Middleware, Handler>>;
134
+ /**
135
+ * @param type - 'method' to get routes organized by method
136
+ */
137
+ static allRoutes(type: 'method'): { [method in Uppercase<HttpMethod>]?: Array<Route<HttpContext, Middleware, Handler>> };
138
+ /**
139
+ * Apply the defined routes to a @koa/router instance
140
+ *
141
+ * @param router @koa/router instance
142
+ * @returns The @koa/router instance with the applied routes
143
+ */
144
+ static apply(router: KoaRouterApp): KoaRouterApp;
145
+ }
146
+ //#endregion
147
+ export { Router };