diesel-core 0.0.21 → 0.0.23

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.
package/README.md CHANGED
@@ -25,7 +25,8 @@ const app = new Diesel()
25
25
  const port = 3000
26
26
 
27
27
  app.get("/", async (ctx:ContextType) => {
28
- return ctx.status(200).text("Hello world...!")
28
+ return ctx.text("Hello world...!",200)
29
+ // Note :- passing statusCode is optional
29
30
  })
30
31
 
31
32
  // Start the server
@@ -61,21 +62,21 @@ import jwt from 'jsonwebtoken';
61
62
 
62
63
  const app = new Diesel();
63
64
 
64
- async function authJwt (xl:ContextType, server?:Server): Promise<void | Response> {
65
- const token = await xl.getCookie("accessToken"); // Retrieve the JWT token from cookies
65
+ async function authJwt (ctx:ContextType, server?:Server): Promise<void | Response> {
66
+ const token = await ctx.getCookie("accessToken"); // Retrieve the JWT token from cookies
66
67
  if (!token) {
67
- return xl.status(401).json({ message: "Authentication token missing" });
68
+ return ctx.json({ message: "Authentication token missing" },401);
68
69
  }
69
70
  try {
70
71
  // Verify the JWT token using a secret key
71
72
  const user = jwt.verify(token, secret); // Replace with your JWT secret
72
73
  // Set the user data in context
73
- xl.setUser(user);
74
+ ctx.setUser(user);
74
75
 
75
76
  // Proceed to the next middleware/route handler
76
- return xl.next();
77
+ return ctx.next();
77
78
  } catch (error) {
78
- return xl.status(403).json({ message: "Invalid token" });
79
+ return ctx.json({ message: "Invalid token" },403);
79
80
  }
80
81
  }
81
82
 
@@ -87,15 +88,15 @@ app
87
88
  .require(authJwt); // Apply the authJwt middleware to all other routes
88
89
 
89
90
  // Example public route (no auth required)
90
- app.get("/api/user/register", async (xl) => {
91
- return xl.json({ msg: "This is a public route. No authentication needed." });
91
+ app.get("/api/user/register", async (ctx:ContextType) => {
92
+ return ctx.json({ msg: "This is a public route. No authentication needed." });
92
93
  });
93
94
 
94
95
  // Example protected route (requires auth)
95
- app.get("/api/user/profile", async (xl) => {
96
+ app.get("/api/user/profile", async (ctx:ContextType) => {
96
97
  // This route is protected, so the auth middleware will run before this handler
97
- const user = xl.getUser()
98
- return xl.json({
98
+ const user = ctx.getUser()
99
+ return ctx.json({
99
100
  msg: "You are authenticated!" ,
100
101
  user
101
102
  });
@@ -165,21 +166,21 @@ app.addHooks("onRequest",(req,url,server) =>{
165
166
  // you get req,url & server instance in onReq
166
167
 
167
168
  // Define a preHandler hook
168
- app.addHooks("preHandler",(xl) =>{
169
+ app.addHooks("preHandler",(ctx:ContextType) =>{
169
170
  // Check for authentication token
170
- const authToken = xl.req.headers.get("Authorization");
171
+ const authToken = ctx.req.headers.get("Authorization");
171
172
  if (!authToken) {
172
173
  return new Response("Unauthorized", { status: 401 });
173
174
  }
174
175
  })
175
176
 
176
177
  // Define a postHandler hook
177
- app.addHooks('postHandler', async (xl) => {
178
- console.log(`Response sent for: ${xl.req.url}`);
178
+ app.addHooks('postHandler', async (ctx:ContextType) => {
179
+ console.log(`Response sent for: ${ctx.req.url}`);
179
180
  });
180
181
 
181
182
  // Define an onSend hook
182
- app.addHooks('onSend',async (xl, result) => {
183
+ app.addHooks('onSend',async (ctx, result) => {
183
184
  console.log(`Sending response with status: ${result.status}`);
184
185
  return result; // You can modify the response here if needed
185
186
  });
@@ -197,13 +198,13 @@ async function authJwt (ctx:ContextType, server?:Server): Promise<void | Respons
197
198
  try {
198
199
  const token = ctx?.getCookie("accessToken");
199
200
  if (!token) {
200
- return ctx.status(401).json({ message: "Authentication token missing" });
201
+ return ctx.json({ message: "Authentication token missing" },401);
201
202
  }
202
203
  // Verify the JWT token using a secret key
203
204
  const user = jwt.verify(token, secret);
204
205
  ctx.set('user',user);
205
206
  } catch (error) {
206
- return ctx.status(403).json({ message: "Invalid token" });
207
+ return ctx.json({ message: "Invalid token" },403);
207
208
  }
208
209
  }
209
210
 
@@ -218,7 +219,7 @@ app.use("/user",authJWT)
218
219
  # set cookies
219
220
 
220
221
  ```javascript
221
- app.get("/set-cookie", async(xl) => {
222
+ app.get("/set-cookie", async(ctx:ContextType) => {
222
223
  const user = {
223
224
  name: "pk",
224
225
  age: 22,
@@ -236,24 +237,24 @@ app.get("/set-cookie", async(xl) => {
236
237
  path: "/",
237
238
  }
238
239
 
239
- xl
240
+ ctx
240
241
  .setCookie("accessToken", accessToken, options)
241
242
  .setCookie("refreshToken", refreshToken, options)
242
243
 
243
- return xl.json({msg:"setting cookies"})
244
+ return ctx.json({msg:"setting cookies"})
244
245
  })
245
246
  ```
246
247
 
247
248
  # Render a HTML page
248
249
  ```javascript
249
- app.get("/render",async (xl) => {
250
- return xl.html(`${import.meta.dir}/index.html`)
250
+ app.get("/render",async (ctx) => {
251
+ return ctx.file(`${import.meta.dir}/index.html`)
251
252
  })
252
253
  ```
253
254
  # redirect
254
255
  ```javascript
255
- app.get("/redirect",(xl) => {
256
- return xl.redirect("/");
256
+ app.get("/redirect",(ctx:ContextType) => {
257
+ return ctx.redirect("/");
257
258
  })
258
259
  ```
259
260
  # get params
@@ -265,10 +266,10 @@ app.get("/product/:productId/:productName)
265
266
  ```
266
267
 
267
268
  ```javascript
268
- app.get("/hello/:id/",(xl) => {
269
- const id = xl.getParams("id")
270
- const query = xl.getQuery() // you can pass query name also , you wanna get
271
- return xl.json({ msg: "Hello", id });
269
+ app.get("/hello/:id/",(ctx:ContextType) => {
270
+ const id = ctx.getParams("id")
271
+ const query = ctx.getQuery() // you can pass query name also , you wanna get
272
+ return ctx.json({ msg: "Hello", id });
272
273
  })
273
274
  ```
274
275
 
package/build.js CHANGED
@@ -4,7 +4,7 @@ const entryPoints = [
4
4
  './src/ctx.ts',
5
5
  './src/handleRequest.ts',
6
6
  './src/trie.ts',
7
- './src/router.ts',
7
+ // './src/router.ts',
8
8
  './src/utils.ts'
9
9
  ];
10
10
 
package/dist/ctx.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="bun-types" />
1
2
  import { Server } from "bun";
2
3
  import type { ContextType } from "./types";
3
4
  export default function createCtx(req: Request, server: Server, url: URL): ContextType;
package/dist/ctx.js CHANGED
@@ -1 +1 @@
1
- function K(F,L,G){let z=new Headers,M={},U=!1,I,Z=null,$,_,Y=200,x={};return{req:F,server:L,url:G,getUser(){return x},setUser(w){if(w)x=w},status(w){return Y=w,this},getIP(){return this.server.requestIP(this.req)},async getBody(){if(!_)_=await W(F);if(_.error)return new Response(JSON.stringify({error:_.error}),{status:400});return _},setHeader(w,E){return z.set(w,E),this},set(w,E){return M[w]=E,this},get(w){return M[w]||null},setAuth(w){return U=w,this},getAuth(){return U},text(w,E){return new Response(w,{status:E??Y,headers:z})},send(w,E){return new Response(w,{status:E??Y,headers:z})},json(w,E){return new Response(JSON.stringify(w),{status:E??Y,headers:z})},html(w,E){return new Response(Bun.file(w),{status:E??Y,headers:z})},file(w,E){return new Response(Bun.file(w),{status:E??Y,headers:z})},redirect(w,E){return z.set("Location",w),new Response(null,{status:E??302,headers:z})},setCookie(w,E,J={}){let X=`${encodeURIComponent(w)}=${encodeURIComponent(E)}`;if(J.maxAge)X+=`; Max-Age=${J.maxAge}`;if(J.expires)X+=`; Expires=${J.expires.toUTCString()}`;if(J.path)X+=`; Path=${J.path}`;if(J.domain)X+=`; Domain=${J.domain}`;if(J.secure)X+="; Secure";if(J.httpOnly)X+="; HttpOnly";if(J.sameSite)X+=`; SameSite=${J.sameSite}`;return z?.append("Set-Cookie",X),this},getParams(w){if(!$&&F?.routePattern)$=R(F?.routePattern,G?.pathname);return w?$[w]||{}:$},getQuery(w){try{if(!I)I=Object.fromEntries(G.searchParams);return w?I[w]||{}:I}catch(E){return{}}},getCookie(w){if(!Z){let E=F.headers.get("cookie");if(E)Z=O(E);else return null}if(!Z)return null;if(w)return Z[w]??null;else return Z}}}function O(F){let L={},G=F?.split(";");for(let z=0;z<G?.length;z++){let[M,...U]=G[z].trim().split("="),I=U?.join("=").trim();if(M)L[M.trim()]=decodeURIComponent(I)}return L}function R(F,L){let G={},z=F.split("/"),[M]=L.split("?"),U=M.split("/");if(z.length!==U.length)return null;for(let I=0;I<z.length;I++)if(z[I].startsWith(":"))G[z[I].slice(1)]=U[I];return G}async function W(F){let L=F.headers.get("Content-Type");if(!L)return{};try{if(L.startsWith("application/json"))return await F.json();if(L.startsWith("application/x-www-form-urlencoded")){let G=await F.text();return Object.fromEntries(new URLSearchParams(G))}if(L.startsWith("multipart/form-data")){let G=await F.formData(),z={};for(let[M,U]of G.entries())z[M]=U;return z}return{error:"Unknown request body type"}}catch(G){return{error:"Invalid request body format"}}}export{K as default};
1
+ function x(F,L,G){let z=new Headers,M={},U=!1,I,Y=null,_,Z,$={};return{req:F,server:L,url:G,getUser(){return $},setUser(w){if(w)$=w},getIP(){return this.server.requestIP(this.req)},async getBody(){if(!Z)Z=await R(F);if(Z.error)return new Response(JSON.stringify({error:Z.error}),{status:400});return Z},setHeader(w,E){return z.set(w,E),this},set(w,E){if(typeof w!=="string")throw new Error("Key must be string type!");if(!E)throw new Error("value paramter is missing pls pass value after key");return M[w]=E,this},get(w){return w?M[w]:null},setAuth(w){return U=w,this},getAuth(){return U},text(w,E){return new Response(w,{status:E,headers:z})},json(w,E){return new Response(JSON.stringify(w),{status:E,headers:z})},file(w,E){return new Response(Bun.file(w),{status:E,headers:z})},redirect(w,E){return z.set("Location",w),new Response(null,{status:E??302,headers:z})},setCookie(w,E,J={}){let X=`${encodeURIComponent(w)}=${encodeURIComponent(E)}`;if(J.maxAge)X+=`; Max-Age=${J.maxAge}`;if(J.expires)X+=`; Expires=${J.expires.toUTCString()}`;if(J.path)X+=`; Path=${J.path}`;if(J.domain)X+=`; Domain=${J.domain}`;if(J.secure)X+="; Secure";if(J.httpOnly)X+="; HttpOnly";if(J.sameSite)X+=`; SameSite=${J.sameSite}`;return z?.append("Set-Cookie",X),this},getParams(w){if(!_&&F?.routePattern)_=O(F?.routePattern,G?.pathname);return w?_[w]||{}:_},getQuery(w){try{if(!I)I=Object.fromEntries(G.searchParams);return w?I[w]||{}:I}catch(E){return{}}},getCookie(w){if(!Y){let E=F.headers.get("cookie");if(E)Y=K(E);else return null}if(!Y)return null;if(w)return Y[w]??null;else return Y}}}function K(F){let L={},G=F?.split(";");for(let z=0;z<G?.length;z++){let[M,...U]=G[z].trim().split("="),I=U?.join("=").trim();if(M)L[M.trim()]=decodeURIComponent(I)}return L}function O(F,L){let G={},z=F.split("/"),[M]=L.split("?"),U=M.split("/");if(z.length!==U.length)return null;for(let I=0;I<z.length;I++)if(z[I].startsWith(":"))G[z[I].slice(1)]=U[I];return G}async function R(F){let L=F.headers.get("Content-Type");if(!L)return{};try{if(L.startsWith("application/json"))return await F.json();if(L.startsWith("application/x-www-form-urlencoded")){let G=await F.text();return Object.fromEntries(new URLSearchParams(G))}if(L.startsWith("multipart/form-data")){let G=await F.formData(),z={};for(let[M,U]of G.entries())z[M]=U;return z}return{error:"Unknown request body type"}}catch(G){return{error:"Invalid request body format"}}}export{x as default};
@@ -1,3 +1,4 @@
1
+ /// <reference types="bun-types" />
1
2
  import { Server } from "bun";
2
3
  import type { DieselT } from "./types";
3
4
  export default function handleRequest(req: Request, server: Server, url: URL, diesel: DieselT): Promise<Response>;
@@ -1 +1 @@
1
- function D(I,F,G){let z=new Headers,J={},L=!1,Z,U=null,Y,_,$=200,A={};return{req:I,server:F,url:G,getUser(){return A},setUser(E){if(E)A=E},status(E){return $=E,this},getIP(){return this.server.requestIP(this.req)},async getBody(){if(!_)_=await M(I);if(_.error)return new Response(JSON.stringify({error:_.error}),{status:400});return _},setHeader(E,X){return z.set(E,X),this},set(E,X){return J[E]=X,this},get(E){return J[E]||null},setAuth(E){return L=E,this},getAuth(){return L},text(E,X){return new Response(E,{status:X??$,headers:z})},send(E,X){return new Response(E,{status:X??$,headers:z})},json(E,X){return new Response(JSON.stringify(E),{status:X??$,headers:z})},html(E,X){return new Response(Bun.file(E),{status:X??$,headers:z})},file(E,X){return new Response(Bun.file(E),{status:X??$,headers:z})},redirect(E,X){return z.set("Location",E),new Response(null,{status:X??302,headers:z})},setCookie(E,X,K={}){let W=`${encodeURIComponent(E)}=${encodeURIComponent(X)}`;if(K.maxAge)W+=`; Max-Age=${K.maxAge}`;if(K.expires)W+=`; Expires=${K.expires.toUTCString()}`;if(K.path)W+=`; Path=${K.path}`;if(K.domain)W+=`; Domain=${K.domain}`;if(K.secure)W+="; Secure";if(K.httpOnly)W+="; HttpOnly";if(K.sameSite)W+=`; SameSite=${K.sameSite}`;return z?.append("Set-Cookie",W),this},getParams(E){if(!Y&&I?.routePattern)Y=j(I?.routePattern,G?.pathname);return E?Y[E]||{}:Y},getQuery(E){try{if(!Z)Z=Object.fromEntries(G.searchParams);return E?Z[E]||{}:Z}catch(X){return{}}},getCookie(E){if(!U){let X=I.headers.get("cookie");if(X)U=T(X);else return null}if(!U)return null;if(E)return U[E]??null;else return U}}}function T(I){let F={},G=I?.split(";");for(let z=0;z<G?.length;z++){let[J,...L]=G[z].trim().split("="),Z=L?.join("=").trim();if(J)F[J.trim()]=decodeURIComponent(Z)}return F}function j(I,F){let G={},z=I.split("/"),[J]=F.split("?"),L=J.split("/");if(z.length!==L.length)return null;for(let Z=0;Z<z.length;Z++)if(z[Z].startsWith(":"))G[z[Z].slice(1)]=L[Z];return G}async function M(I){let F=I.headers.get("Content-Type");if(!F)return{};try{if(F.startsWith("application/json"))return await I.json();if(F.startsWith("application/x-www-form-urlencoded")){let G=await I.text();return Object.fromEntries(new URLSearchParams(G))}if(F.startsWith("multipart/form-data")){let G=await I.formData(),z={};for(let[J,L]of G.entries())z[J]=L;return z}return{error:"Unknown request body type"}}catch(G){return{error:"Invalid request body format"}}}async function Q(I,F,G,z){let J=z.trie.search(G.pathname,I.method);if(J?.isDynamic)I.routePattern=J.path;let L=D(I,F,G);if(z.corsConfig){let U=V(I,L,z.corsConfig);if(U)return U}if(z.hasOnReqHook&&z.hooks.onRequest)z.hooks.onRequest(I,G,F);if(z.hasFilterEnabled){let U=I.routePattern??G.pathname;if(!z.filters.has(U))if(z.filterFunction)try{let Y=await z.filterFunction(L,F);if(Y)return Y}catch(Y){return console.error("Error in filterFunction:",Y),L.status(500).json({message:"Internal Server Error",error:Y.message})}else return L.status(400).json({message:"Authentication required"})}if(z.hasMiddleware){let U=z.globalMiddlewares;for(let _=0;_<U.length;_++){let $=await U[_](L,F);if($)return $}let Y=z.middlewares.get(G.pathname)||[];for(let _=0;_<Y.length;_++){let $=await Y[_](L,F);if($)return $}}if(!J||J.method!==I.method){let U=J?"Method not allowed":`Route not found for ${G.pathname}`,Y=J?405:404;return new Response(JSON.stringify({message:U}),{status:Y})}if(z.hasPreHandlerHook&&z.hooks.preHandler){let U=await z.hooks.preHandler(L);if(U)return U}let Z=await J.handler(L);if(z.hasPostHandlerHook&&z.hooks.postHandler)await z.hooks.postHandler(L);if(z.hasOnSendHook&&z.hooks.onSend){let U=await z.hooks.onSend(L,Z);if(U)return U}return Z??L.status(204).json({message:"No response from this handler"})}function V(I,F,G={}){let z=I.headers.get("origin")??"*",J=G?.origin,L=G?.allowedHeaders??["Content-Type","Authorization"],Z=G?.methods??["GET","POST","PUT","DELETE","OPTIONS"],U=G?.credentials??!1,Y=G?.exposedHeaders??[];if(F.setHeader("Access-Control-Allow-Methods",Z),F.setHeader("Access-Control-Allow-Headers",L),F.setHeader("Access-Control-Allow-Credentials",U),Y.length)F.setHeader("Access-Control-Expose-Headers",Y);if(J==="*")F.setHeader("Access-Control-Allow-Origin","*");else if(Array.isArray(J))if(z&&J.includes(z))F.setHeader("Access-Control-Allow-Origin",z);else if(J.includes("*"))F.setHeader("Access-Control-Allow-Origin","*");else return F.status(403).json({message:"CORS not allowed"});else if(typeof J==="string")if(z===J)F.setHeader("Access-Control-Allow-Origin",z);else return F.status(403).json({message:"CORS not allowed"});else return F.status(403).json({message:"CORS not allowed"});if(F.setHeader("Access-Control-Allow-Origin",z),I.method==="OPTIONS")return F.setHeader("Access-Control-Max-Age","86400"),F.status(204).text("");return null}export{Q as default};
1
+ function D(I,E,G){let z=new Headers,J={},L=!1,Z,U=null,X,_,K={};return{req:I,server:E,url:G,getUser(){return K},setUser(F){if(F)K=F},getIP(){return this.server.requestIP(this.req)},async getBody(){if(!_)_=await j(I);if(_.error)return new Response(JSON.stringify({error:_.error}),{status:400});return _},setHeader(F,Y){return z.set(F,Y),this},set(F,Y){if(typeof F!=="string")throw new Error("Key must be string type!");if(!Y)throw new Error("value paramter is missing pls pass value after key");return J[F]=Y,this},get(F){return F?J[F]:null},setAuth(F){return L=F,this},getAuth(){return L},text(F,Y){return new Response(F,{status:Y,headers:z})},json(F,Y){return new Response(JSON.stringify(F),{status:Y,headers:z})},file(F,Y){return new Response(Bun.file(F),{status:Y,headers:z})},redirect(F,Y){return z.set("Location",F),new Response(null,{status:Y??302,headers:z})},setCookie(F,Y,$={}){let W=`${encodeURIComponent(F)}=${encodeURIComponent(Y)}`;if($.maxAge)W+=`; Max-Age=${$.maxAge}`;if($.expires)W+=`; Expires=${$.expires.toUTCString()}`;if($.path)W+=`; Path=${$.path}`;if($.domain)W+=`; Domain=${$.domain}`;if($.secure)W+="; Secure";if($.httpOnly)W+="; HttpOnly";if($.sameSite)W+=`; SameSite=${$.sameSite}`;return z?.append("Set-Cookie",W),this},getParams(F){if(!X&&I?.routePattern)X=T(I?.routePattern,G?.pathname);return F?X[F]||{}:X},getQuery(F){try{if(!Z)Z=Object.fromEntries(G.searchParams);return F?Z[F]||{}:Z}catch(Y){return{}}},getCookie(F){if(!U){let Y=I.headers.get("cookie");if(Y)U=A(Y);else return null}if(!U)return null;if(F)return U[F]??null;else return U}}}function A(I){let E={},G=I?.split(";");for(let z=0;z<G?.length;z++){let[J,...L]=G[z].trim().split("="),Z=L?.join("=").trim();if(J)E[J.trim()]=decodeURIComponent(Z)}return E}function T(I,E){let G={},z=I.split("/"),[J]=E.split("?"),L=J.split("/");if(z.length!==L.length)return null;for(let Z=0;Z<z.length;Z++)if(z[Z].startsWith(":"))G[z[Z].slice(1)]=L[Z];return G}async function j(I){let E=I.headers.get("Content-Type");if(!E)return{};try{if(E.startsWith("application/json"))return await I.json();if(E.startsWith("application/x-www-form-urlencoded")){let G=await I.text();return Object.fromEntries(new URLSearchParams(G))}if(E.startsWith("multipart/form-data")){let G=await I.formData(),z={};for(let[J,L]of G.entries())z[J]=L;return z}return{error:"Unknown request body type"}}catch(G){return{error:"Invalid request body format"}}}async function M(I,E,G,z){let J=z.trie.search(G.pathname,I.method);if(J?.isDynamic)I.routePattern=J.path;let L=D(I,E,G);if(z.corsConfig){let U=Q(I,L,z.corsConfig);if(U)return U}if(z.hasOnReqHook&&z.hooks.onRequest)z.hooks.onRequest(I,G,E);if(z.hasFilterEnabled){let U=I.routePattern??G.pathname;if(!z.filters.has(U))if(z.filterFunction)try{let X=await z.filterFunction(L,E);if(X)return X}catch(X){return console.error("Error in filterFunction:",X),L.json({message:"Internal Server Error",error:X.message},500)}else return L.json({message:"Authentication required"},400)}if(z.hasMiddleware){let U=z.globalMiddlewares;for(let _=0;_<U.length;_++){let K=await U[_](L,E);if(K)return K}let X=z.middlewares.get(G.pathname)||[];for(let _=0;_<X.length;_++){let K=await X[_](L,E);if(K)return K}}if(!J||J.method!==I.method){let U=J?"Method not allowed":`Route not found for ${G.pathname}`,X=J?405:404;return new Response(JSON.stringify({message:U}),{status:X})}if(z.hasPreHandlerHook&&z.hooks.preHandler){let U=await z.hooks.preHandler(L);if(U)return U}let Z=await J.handler(L);if(z.hasPostHandlerHook&&z.hooks.postHandler)await z.hooks.postHandler(L);if(z.hasOnSendHook&&z.hooks.onSend){let U=await z.hooks.onSend(L,Z);if(U)return U}return Z??L.json({message:"No response from this handler"},204)}function Q(I,E,G={}){let z=I.headers.get("origin")??"*",J=G?.origin,L=G?.allowedHeaders??["Content-Type","Authorization"],Z=G?.methods??["GET","POST","PUT","DELETE","OPTIONS"],U=G?.credentials??!1,X=G?.exposedHeaders??[];if(E.setHeader("Access-Control-Allow-Methods",Z),E.setHeader("Access-Control-Allow-Headers",L),E.setHeader("Access-Control-Allow-Credentials",U),X.length)E.setHeader("Access-Control-Expose-Headers",X);if(J==="*")E.setHeader("Access-Control-Allow-Origin","*");else if(Array.isArray(J))if(z&&J.includes(z))E.setHeader("Access-Control-Allow-Origin",z);else if(J.includes("*"))E.setHeader("Access-Control-Allow-Origin","*");else return E.json({message:"CORS not allowed"},403);else if(typeof J==="string")if(z===J)E.setHeader("Access-Control-Allow-Origin",z);else return E.json({message:"CORS not allowed"},403);else return E.json({message:"CORS not allowed"},403);if(E.setHeader("Access-Control-Allow-Origin",z),I.method==="OPTIONS")return E.setHeader("Access-Control-Max-Age","86400"),E.text("",204);return null}export{M as default};
package/dist/main.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="bun-types" />
1
2
  import Trie from "./trie.js";
2
3
  import { corsT, FilterMethods, HookFunction, HookType, middlewareFunc, onError, onRequest, type handlerFunction, type Hooks, type HttpMethod } from "./types.js";
3
4
  import { Server } from "bun";
package/dist/main.js CHANGED
@@ -1 +1 @@
1
- class V{children;isEndOfWord;handler;isDynamic;pattern;path;method;subMiddlewares;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class Q{root;constructor(){this.root=new V}insert(F,z){let G=this.root,J=F.split("/").filter(Boolean);if(F==="/"){G.isEndOfWord=!0,G.handler=[z.handler],G.path=F,G.method=[z.method];return}for(let L=0;L<J.length;L++){let U=J[L],Z=!1,X=U;if(U.startsWith(":"))Z=!0,X=":";if(!G.children[X])G.children[X]=new V;if(G=G.children[X],G.isDynamic=Z,G.pattern=U,L===J.length-1)G.handler=[z.handler],G.method=[z.method],G.isEndOfWord=!0,G.path=F}}search(F,z){let G=this.root,J=F.split("/").filter(Boolean);for(let U of J){let Z=U;if(!G.children[Z])if(G.children[":"])G=G.children[":"];else return null;else G=G.children[Z]}let L=G.method.indexOf(z);if(G.isEndOfWord&&L!==-1)return{path:G.path,handler:G.handler[L],isDynamic:G.isDynamic,pattern:G.pattern,method:G.method[L]};return null}}function B(F,z,G){let J=new Headers,L={},U=!1,Z,X=null,_,W,K=200,D={};return{req:F,server:z,url:G,getUser(){return D},setUser(Y){if(Y)D=Y},status(Y){return K=Y,this},getIP(){return this.server.requestIP(this.req)},async getBody(){if(!W)W=await N(F);if(W.error)return new Response(JSON.stringify({error:W.error}),{status:400});return W},setHeader(Y,$){return J.set(Y,$),this},set(Y,$){return L[Y]=$,this},get(Y){return L[Y]||null},setAuth(Y){return U=Y,this},getAuth(){return U},text(Y,$){return new Response(Y,{status:$??K,headers:J})},send(Y,$){return new Response(Y,{status:$??K,headers:J})},json(Y,$){return new Response(JSON.stringify(Y),{status:$??K,headers:J})},html(Y,$){return new Response(Bun.file(Y),{status:$??K,headers:J})},file(Y,$){return new Response(Bun.file(Y),{status:$??K,headers:J})},redirect(Y,$){return J.set("Location",Y),new Response(null,{status:$??302,headers:J})},setCookie(Y,$,E={}){let A=`${encodeURIComponent(Y)}=${encodeURIComponent($)}`;if(E.maxAge)A+=`; Max-Age=${E.maxAge}`;if(E.expires)A+=`; Expires=${E.expires.toUTCString()}`;if(E.path)A+=`; Path=${E.path}`;if(E.domain)A+=`; Domain=${E.domain}`;if(E.secure)A+="; Secure";if(E.httpOnly)A+="; HttpOnly";if(E.sameSite)A+=`; SameSite=${E.sameSite}`;return J?.append("Set-Cookie",A),this},getParams(Y){if(!_&&F?.routePattern)_=T(F?.routePattern,G?.pathname);return Y?_[Y]||{}:_},getQuery(Y){try{if(!Z)Z=Object.fromEntries(G.searchParams);return Y?Z[Y]||{}:Z}catch($){return{}}},getCookie(Y){if(!X){let $=F.headers.get("cookie");if($)X=I($);else return null}if(!X)return null;if(Y)return X[Y]??null;else return X}}}function I(F){let z={},G=F?.split(";");for(let J=0;J<G?.length;J++){let[L,...U]=G[J].trim().split("="),Z=U?.join("=").trim();if(L)z[L.trim()]=decodeURIComponent(Z)}return z}function T(F,z){let G={},J=F.split("/"),[L]=z.split("?"),U=L.split("/");if(J.length!==U.length)return null;for(let Z=0;Z<J.length;Z++)if(J[Z].startsWith(":"))G[J[Z].slice(1)]=U[Z];return G}async function N(F){let z=F.headers.get("Content-Type");if(!z)return{};try{if(z.startsWith("application/json"))return await F.json();if(z.startsWith("application/x-www-form-urlencoded")){let G=await F.text();return Object.fromEntries(new URLSearchParams(G))}if(z.startsWith("multipart/form-data")){let G=await F.formData(),J={};for(let[L,U]of G.entries())J[L]=U;return J}return{error:"Unknown request body type"}}catch(G){return{error:"Invalid request body format"}}}async function j(F,z,G,J){let L=J.trie.search(G.pathname,F.method);if(L?.isDynamic)F.routePattern=L.path;let U=B(F,z,G);if(J.corsConfig){let X=C(F,U,J.corsConfig);if(X)return X}if(J.hasOnReqHook&&J.hooks.onRequest)J.hooks.onRequest(F,G,z);if(J.hasFilterEnabled){let X=F.routePattern??G.pathname;if(!J.filters.has(X))if(J.filterFunction)try{let _=await J.filterFunction(U,z);if(_)return _}catch(_){return console.error("Error in filterFunction:",_),U.status(500).json({message:"Internal Server Error",error:_.message})}else return U.status(400).json({message:"Authentication required"})}if(J.hasMiddleware){let X=J.globalMiddlewares;for(let W=0;W<X.length;W++){let K=await X[W](U,z);if(K)return K}let _=J.middlewares.get(G.pathname)||[];for(let W=0;W<_.length;W++){let K=await _[W](U,z);if(K)return K}}if(!L||L.method!==F.method){let X=L?"Method not allowed":`Route not found for ${G.pathname}`,_=L?405:404;return new Response(JSON.stringify({message:X}),{status:_})}if(J.hasPreHandlerHook&&J.hooks.preHandler){let X=await J.hooks.preHandler(U);if(X)return X}let Z=await L.handler(U);if(J.hasPostHandlerHook&&J.hooks.postHandler)await J.hooks.postHandler(U);if(J.hasOnSendHook&&J.hooks.onSend){let X=await J.hooks.onSend(U,Z);if(X)return X}return Z??U.status(204).json({message:"No response from this handler"})}function C(F,z,G={}){let J=F.headers.get("origin")??"*",L=G?.origin,U=G?.allowedHeaders??["Content-Type","Authorization"],Z=G?.methods??["GET","POST","PUT","DELETE","OPTIONS"],X=G?.credentials??!1,_=G?.exposedHeaders??[];if(z.setHeader("Access-Control-Allow-Methods",Z),z.setHeader("Access-Control-Allow-Headers",U),z.setHeader("Access-Control-Allow-Credentials",X),_.length)z.setHeader("Access-Control-Expose-Headers",_);if(L==="*")z.setHeader("Access-Control-Allow-Origin","*");else if(Array.isArray(L))if(J&&L.includes(J))z.setHeader("Access-Control-Allow-Origin",J);else if(L.includes("*"))z.setHeader("Access-Control-Allow-Origin","*");else return z.status(403).json({message:"CORS not allowed"});else if(typeof L==="string")if(J===L)z.setHeader("Access-Control-Allow-Origin",J);else return z.status(403).json({message:"CORS not allowed"});else return z.status(403).json({message:"CORS not allowed"});if(z.setHeader("Access-Control-Allow-Origin",J),F.method==="OPTIONS")return z.setHeader("Access-Control-Max-Age","86400"),z.status(204).text("");return null}class M{tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;constructor(){this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new Q,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:null,preHandler:null,postHandler:null,onSend:null,onError:null,onClose:null},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=null,this.hasFilterEnabled=!1}filter(){return this.hasFilterEnabled=!0,{routeMatcher:(...F)=>{return this.FilterRoutes=F,this.filter()},permitAll:()=>{for(let F of this?.FilterRoutes)this.filters.add(F);return this.FilterRoutes=null,this.filter()},require:(F)=>{if(F)this.filterFunction=F}}}cors(F){return this.corsConfig=F,this}addHooks(F,z){if(typeof F!=="string")throw new Error("hookName must be a string");if(typeof z!=="function")throw new Error("callback must be a instance of function");switch(F){case"onRequest":this.hooks.onRequest=z,this.hasOnReqHook=!0;break;case"preHandler":this.hooks.preHandler=z,this.hasPreHandlerHook=!0;break;case"postHandler":this.hooks.postHandler=z,this.hasPostHandlerHook=!0;break;case"onSend":this.hooks.onSend=z,this.hasOnSendHook=!0;break;case"onError":this.hooks.onError=z,this.hasOnError=!0;break;case"onClose":this.hooks.onClose=z;break;default:throw new Error(`Unknown hook type: ${F}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[F,z]of this.middlewares.entries())if(z.length>0){this.hasMiddleware=!0;break}if(this.hooks.onRequest)this.hasOnReqHook=!0;if(this.hooks.preHandler)this.hasPreHandlerHook=!0;if(this.hooks.postHandler)this.hasPostHandlerHook=!0;if(this.hooks.onSend)this.hasOnSendHook=!0;if(this.hooks.onError)this.hasOnError=!0;this.tempRoutes=new Map}listen(...F){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let z=3000,G="0.0.0.0",J=void 0,L={};for(let X of F)if(typeof X==="number")z=X;else if(typeof X==="string")G=X;else if(typeof X==="function")J=X;else if(typeof X==="object"&&X!==null)L=X;this.compile();let U={port:z,hostname:G,fetch:async(X,_)=>{let W=new URL(X.url);try{return await j(X,_,W,this)}catch(K){if(this.hasOnError&&this.hooks.onError){let D=await this.hooks.onError(K,X,W,_);if(D)return D}return new Response(JSON.stringify({message:"Internal Server Error",error:K.message}),{status:500})}}};if(L.sslCert&&L.sslKey)U.certFile=L.sslCert,U.keyFile=L.sslKey;let Z=Bun?.serve(U);if(J)return J();if(L.sslCert&&L.sslKey)console.log(`HTTPS server is running on https://localhost:${z}`);else console.log(`HTTP server is running on http://localhost:${z}`);return Z}route(F,z){if(!F||typeof F!=="string")throw new Error("Path must be a string");let G=Object.fromEntries(z.tempRoutes);return Object.entries(G).forEach(([L,U])=>{let Z=`${F}${L}`;if(!this.middlewares.has(Z))this.middlewares.set(Z,[]);U.handlers.slice(0,-1).forEach((K)=>{if(!this.middlewares.get(Z)?.includes(K))this.middlewares.get(Z)?.push(K)});let _=U.handlers[U.handlers.length-1],W=U.method;try{this.trie.insert(Z,{handler:_,method:W})}catch(K){console.error(`Error inserting ${Z}:`,K)}}),z=null,this}register(F,z){return this.route(F,z),this}addRoute(F,z,G){if(typeof z!=="string")throw new Error("Path must be a string");if(typeof F!=="string")throw new Error("Method must be a string");this.tempRoutes.set(z,{method:F,handlers:G});let J=G.slice(0,-1),L=G[G.length-1];if(!this.middlewares.has(z))this.middlewares.set(z,[]);J.forEach((U)=>{if(z==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...J])];else if(!this.middlewares.get(z)?.includes(U))this.middlewares.get(z)?.push(U)});try{this.trie.insert(z,{handler:L,method:F})}catch(U){console.error(`Error inserting ${z}:`,U)}}use(F,...z){if(typeof F==="function"){if(!this.globalMiddlewares.includes(F))this.globalMiddlewares.push(F);z.forEach((J)=>{if(!this.globalMiddlewares.includes(J))this.globalMiddlewares.push(J)});return}let G=F;if(!this.middlewares.has(G))this.middlewares.set(G,[]);if(z)z.forEach((J)=>{if(!this.middlewares.get(G)?.includes(J))this.middlewares.get(G)?.push(J)});return this}get(F,...z){return this.addRoute("GET",F,z),this}post(F,...z){return this.addRoute("POST",F,z),this}put(F,...z){return this.addRoute("PUT",F,z),this}patch(F,...z){return this.addRoute("PATCH",F,z),this}delete(F,...z){return this.addRoute("DELETE",F,z),this}}export{M as default};
1
+ class Q{children;isEndOfWord;handler;isDynamic;pattern;path;method;subMiddlewares;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class D{root;constructor(){this.root=new Q}insert(F,z){let G=this.root,J=F.split("/").filter(Boolean);if(F==="/"){G.isEndOfWord=!0,G.handler=[z.handler],G.path=F,G.method=[z.method];return}for(let L=0;L<J.length;L++){let U=J[L],Z=!1,X=U;if(U.startsWith(":"))Z=!0,X=":";if(!G.children[X])G.children[X]=new Q;if(G=G.children[X],G.isDynamic=Z,G.pattern=U,L===J.length-1)G.handler=[z.handler],G.method=[z.method],G.isEndOfWord=!0,G.path=F}}search(F,z){let G=this.root,J=F.split("/").filter(Boolean);for(let U of J){let Z=U;if(!G.children[Z])if(G.children[":"])G=G.children[":"];else return null;else G=G.children[Z]}let L=G.method.indexOf(z);if(G.isEndOfWord&&L!==-1)return{path:G.path,handler:G.handler[L],isDynamic:G.isDynamic,pattern:G.pattern,method:G.method[L]};return null}}function V(F,z,G){let J=new Headers,L={},U=!1,Z,X=null,_,$,W={};return{req:F,server:z,url:G,getUser(){return W},setUser(Y){if(Y)W=Y},getIP(){return this.server.requestIP(this.req)},async getBody(){if(!$)$=await T(F);if($.error)return new Response(JSON.stringify({error:$.error}),{status:400});return $},setHeader(Y,K){return J.set(Y,K),this},set(Y,K){if(typeof Y!=="string")throw new Error("Key must be string type!");if(!K)throw new Error("value paramter is missing pls pass value after key");return L[Y]=K,this},get(Y){return Y?L[Y]:null},setAuth(Y){return U=Y,this},getAuth(){return U},text(Y,K){return new Response(Y,{status:K,headers:J})},json(Y,K){return new Response(JSON.stringify(Y),{status:K,headers:J})},file(Y,K){return new Response(Bun.file(Y),{status:K,headers:J})},redirect(Y,K){return J.set("Location",Y),new Response(null,{status:K??302,headers:J})},setCookie(Y,K,E={}){let A=`${encodeURIComponent(Y)}=${encodeURIComponent(K)}`;if(E.maxAge)A+=`; Max-Age=${E.maxAge}`;if(E.expires)A+=`; Expires=${E.expires.toUTCString()}`;if(E.path)A+=`; Path=${E.path}`;if(E.domain)A+=`; Domain=${E.domain}`;if(E.secure)A+="; Secure";if(E.httpOnly)A+="; HttpOnly";if(E.sameSite)A+=`; SameSite=${E.sameSite}`;return J?.append("Set-Cookie",A),this},getParams(Y){if(!_&&F?.routePattern)_=I(F?.routePattern,G?.pathname);return Y?_[Y]||{}:_},getQuery(Y){try{if(!Z)Z=Object.fromEntries(G.searchParams);return Y?Z[Y]||{}:Z}catch(K){return{}}},getCookie(Y){if(!X){let K=F.headers.get("cookie");if(K)X=M(K);else return null}if(!X)return null;if(Y)return X[Y]??null;else return X}}}function M(F){let z={},G=F?.split(";");for(let J=0;J<G?.length;J++){let[L,...U]=G[J].trim().split("="),Z=U?.join("=").trim();if(L)z[L.trim()]=decodeURIComponent(Z)}return z}function I(F,z){let G={},J=F.split("/"),[L]=z.split("?"),U=L.split("/");if(J.length!==U.length)return null;for(let Z=0;Z<J.length;Z++)if(J[Z].startsWith(":"))G[J[Z].slice(1)]=U[Z];return G}async function T(F){let z=F.headers.get("Content-Type");if(!z)return{};try{if(z.startsWith("application/json"))return await F.json();if(z.startsWith("application/x-www-form-urlencoded")){let G=await F.text();return Object.fromEntries(new URLSearchParams(G))}if(z.startsWith("multipart/form-data")){let G=await F.formData(),J={};for(let[L,U]of G.entries())J[L]=U;return J}return{error:"Unknown request body type"}}catch(G){return{error:"Invalid request body format"}}}async function B(F,z,G,J){let L=J.trie.search(G.pathname,F.method);if(L?.isDynamic)F.routePattern=L.path;let U=V(F,z,G);if(J.corsConfig){let X=N(F,U,J.corsConfig);if(X)return X}if(J.hasOnReqHook&&J.hooks.onRequest)J.hooks.onRequest(F,G,z);if(J.hasFilterEnabled){let X=F.routePattern??G.pathname;if(!J.filters.has(X))if(J.filterFunction)try{let _=await J.filterFunction(U,z);if(_)return _}catch(_){return console.error("Error in filterFunction:",_),U.json({message:"Internal Server Error",error:_.message},500)}else return U.json({message:"Authentication required"},400)}if(J.hasMiddleware){let X=J.globalMiddlewares;for(let $=0;$<X.length;$++){let W=await X[$](U,z);if(W)return W}let _=J.middlewares.get(G.pathname)||[];for(let $=0;$<_.length;$++){let W=await _[$](U,z);if(W)return W}}if(!L||L.method!==F.method){let X=L?"Method not allowed":`Route not found for ${G.pathname}`,_=L?405:404;return new Response(JSON.stringify({message:X}),{status:_})}if(J.hasPreHandlerHook&&J.hooks.preHandler){let X=await J.hooks.preHandler(U);if(X)return X}let Z=await L.handler(U);if(J.hasPostHandlerHook&&J.hooks.postHandler)await J.hooks.postHandler(U);if(J.hasOnSendHook&&J.hooks.onSend){let X=await J.hooks.onSend(U,Z);if(X)return X}return Z??U.json({message:"No response from this handler"},204)}function N(F,z,G={}){let J=F.headers.get("origin")??"*",L=G?.origin,U=G?.allowedHeaders??["Content-Type","Authorization"],Z=G?.methods??["GET","POST","PUT","DELETE","OPTIONS"],X=G?.credentials??!1,_=G?.exposedHeaders??[];if(z.setHeader("Access-Control-Allow-Methods",Z),z.setHeader("Access-Control-Allow-Headers",U),z.setHeader("Access-Control-Allow-Credentials",X),_.length)z.setHeader("Access-Control-Expose-Headers",_);if(L==="*")z.setHeader("Access-Control-Allow-Origin","*");else if(Array.isArray(L))if(J&&L.includes(J))z.setHeader("Access-Control-Allow-Origin",J);else if(L.includes("*"))z.setHeader("Access-Control-Allow-Origin","*");else return z.json({message:"CORS not allowed"},403);else if(typeof L==="string")if(J===L)z.setHeader("Access-Control-Allow-Origin",J);else return z.json({message:"CORS not allowed"},403);else return z.json({message:"CORS not allowed"},403);if(z.setHeader("Access-Control-Allow-Origin",J),F.method==="OPTIONS")return z.setHeader("Access-Control-Max-Age","86400"),z.text("",204);return null}class j{tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;constructor(){this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new D,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:null,preHandler:null,postHandler:null,onSend:null,onError:null,onClose:null},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=null,this.hasFilterEnabled=!1}filter(){return this.hasFilterEnabled=!0,{routeMatcher:(...F)=>{return this.FilterRoutes=F,this.filter()},permitAll:()=>{for(let F of this?.FilterRoutes)this.filters.add(F);return this.FilterRoutes=null,this.filter()},require:(F)=>{if(F)this.filterFunction=F}}}cors(F){return this.corsConfig=F,this}addHooks(F,z){if(typeof F!=="string")throw new Error("hookName must be a string");if(typeof z!=="function")throw new Error("callback must be a instance of function");switch(F){case"onRequest":this.hooks.onRequest=z,this.hasOnReqHook=!0;break;case"preHandler":this.hooks.preHandler=z,this.hasPreHandlerHook=!0;break;case"postHandler":this.hooks.postHandler=z,this.hasPostHandlerHook=!0;break;case"onSend":this.hooks.onSend=z,this.hasOnSendHook=!0;break;case"onError":this.hooks.onError=z,this.hasOnError=!0;break;case"onClose":this.hooks.onClose=z;break;default:throw new Error(`Unknown hook type: ${F}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[F,z]of this.middlewares.entries())if(z.length>0){this.hasMiddleware=!0;break}if(this.hooks.onRequest)this.hasOnReqHook=!0;if(this.hooks.preHandler)this.hasPreHandlerHook=!0;if(this.hooks.postHandler)this.hasPostHandlerHook=!0;if(this.hooks.onSend)this.hasOnSendHook=!0;if(this.hooks.onError)this.hasOnError=!0;this.tempRoutes=new Map}listen(...F){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let z=3000,G="0.0.0.0",J=void 0,L={};for(let X of F)if(typeof X==="number")z=X;else if(typeof X==="string")G=X;else if(typeof X==="function")J=X;else if(typeof X==="object"&&X!==null)L=X;this.compile();let U={port:z,hostname:G,fetch:async(X,_)=>{let $=new URL(X.url);try{return await B(X,_,$,this)}catch(W){if(this.hasOnError&&this.hooks.onError){let Y=await this.hooks.onError(W,X,$,_);if(Y)return Y}return new Response(JSON.stringify({message:"Internal Server Error",error:W.message}),{status:500})}}};if(L.sslCert&&L.sslKey)U.certFile=L.sslCert,U.keyFile=L.sslKey;let Z=Bun?.serve(U);if(J)return J();if(L.sslCert&&L.sslKey)console.log(`HTTPS server is running on https://localhost:${z}`);else console.log(`HTTP server is running on http://localhost:${z}`);return Z}route(F,z){if(!F||typeof F!=="string")throw new Error("Path must be a string");let G=Object.fromEntries(z.tempRoutes);return Object.entries(G).forEach(([L,U])=>{let Z=`${F}${L}`;if(!this.middlewares.has(Z))this.middlewares.set(Z,[]);U.handlers.slice(0,-1).forEach((W)=>{if(!this.middlewares.get(Z)?.includes(W))this.middlewares.get(Z)?.push(W)});let _=U.handlers[U.handlers.length-1],$=U.method;try{this.trie.insert(Z,{handler:_,method:$})}catch(W){console.error(`Error inserting ${Z}:`,W)}}),z=null,this}register(F,z){return this.route(F,z),this}addRoute(F,z,G){if(typeof z!=="string")throw new Error(`Error in ${G[G.length-1]}: Path must be a string. Received: ${typeof z}`);if(typeof F!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof F}`);this.tempRoutes.set(z,{method:F,handlers:G});let J=G.slice(0,-1),L=G[G.length-1];if(!this.middlewares.has(z))this.middlewares.set(z,[]);J.forEach((U)=>{if(z==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...J])];else if(!this.middlewares.get(z)?.includes(U))this.middlewares.get(z)?.push(U)});try{this.trie.insert(z,{handler:L,method:F})}catch(U){console.error(`Error inserting ${z}:`,U)}}use(F,...z){if(typeof F==="function"){if(!this.globalMiddlewares.includes(F))this.globalMiddlewares.push(F);z.forEach((J)=>{if(!this.globalMiddlewares.includes(J))this.globalMiddlewares.push(J)});return}let G=F;if(!this.middlewares.has(G))this.middlewares.set(G,[]);if(z)z.forEach((J)=>{if(!this.middlewares.get(G)?.includes(J))this.middlewares.get(G)?.push(J)});return this}get(F,...z){return this.addRoute("GET",F,z),this}post(F,...z){return this.addRoute("POST",F,z),this}put(F,...z){return this.addRoute("PUT",F,z),this}patch(F,...z){return this.addRoute("PATCH",F,z),this}delete(F,...z){return this.addRoute("DELETE",F,z),this}}export{j as default};
package/dist/route.d.ts CHANGED
@@ -1,11 +0,0 @@
1
- import Diesel from "./main";
2
- import type { handlerFunction } from "./types";
3
- declare class Router extends Diesel {
4
- constructor();
5
- get(path: string, ...handlers: handlerFunction[]): this;
6
- post(path: string, ...handlers: handlerFunction[]): this;
7
- put(path: string, ...handlers: handlerFunction[]): this;
8
- patch(path: string, ...handlers: handlerFunction[]): this;
9
- delete(path: string, ...handlers: handlerFunction[]): this;
10
- }
11
- export default Router;
package/dist/types.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="bun-types" />
1
2
  import { Server } from "bun";
2
3
  export type listenCalllBackType = () => void;
3
4
  export type handlerFunction = (ctx: ContextType, server?: Server) => Response | Promise<Response | null | void>;
@@ -25,7 +26,6 @@ export interface ContextType {
25
26
  url: URL;
26
27
  setUser: (data?: any) => void;
27
28
  getUser: () => any;
28
- status: (status: number) => this;
29
29
  getIP: () => any;
30
30
  getBody: () => Promise<any>;
31
31
  setHeader: (key: string, value: any) => this;
@@ -35,8 +35,6 @@ export interface ContextType {
35
35
  getAuth: () => boolean;
36
36
  json: (data: Object, status?: number) => Response;
37
37
  text: (data: string, status?: number) => Response;
38
- send: (data: string, status?: number) => Response;
39
- html: (filePath: string, status?: number) => Response;
40
38
  file: (filePath: string, status?: number) => Response;
41
39
  redirect: (path: string, status?: number) => Response;
42
40
  getParams: (props?: any) => any;
package/dist/utils.js CHANGED
@@ -1 +1 @@
1
- function H(v){let{time:z=60000,max:A=100,message:C="Rate limit exceeded. Please try again later."}=v,j=new Map;return(F)=>{let D=new Date,E=F.getIP().address;if(!j.has(E))j.set(E,{count:0,startTime:D});let l=j.get(E);if(l)if(D-l.startTime>z)l.count=1,l.startTime=D;else l.count++;if(l&&l.count>A)return F.status(429).json({error:C})}}var G=(v,z,A,C)=>{if(A>C)return!1;let j=A+(C-A)/2;if(v[j]==z)return!0;if(v[j]>z)return G(v,z,A,j-1);return G(v,z,j+1,C)};export{H as default,G as binaryS};
1
+ function H(v){let{time:z=60000,max:A=100,message:C="Rate limit exceeded. Please try again later."}=v,j=new Map;return(F)=>{let D=new Date,E=F.getIP().address;if(!j.has(E))j.set(E,{count:0,startTime:D});let l=j.get(E);if(l)if(D-l.startTime>z)l.count=1,l.startTime=D;else l.count++;if(l&&l.count>A)return F.json({error:C},429)}}var G=(v,z,A,C)=>{if(A>C)return!1;let j=A+(C-A)/2;if(v[j]==z)return!0;if(v[j]>z)return G(v,z,A,j-1);return G(v,z,j+1,C)};export{H as default,G as binaryS};
package/example/bun.lockb CHANGED
Binary file
package/example/main.ts CHANGED
@@ -2,25 +2,38 @@ import Diesel from "../src/main";
2
2
  import jwt from "jsonwebtoken";
3
3
  import { ContextType, CookieOptions, middlewareFunc } from "../src/types";
4
4
  import { Server } from "bun";
5
- import { userRoute } from "./route";
5
+ import { newRoute, userRoute } from "./route";
6
6
 
7
7
  const app = new Diesel();
8
8
  const SECRET_KEY = "linux";
9
-
9
+ const port = 3000
10
10
  // Authentication Middleware
11
11
  export async function authJwt(ctx: ContextType): Promise<void | null | Response> {
12
12
  const token = ctx.getCookie("accessToken");
13
13
  if (!token) {
14
- return ctx.status(401).json({ message: "Authentication token missing" });
14
+ return ctx.json({ message: "Authentication token missing" },401);
15
15
  }
16
16
  try {
17
17
  const user = jwt.verify(token, SECRET_KEY);
18
18
  ctx.setUser(user);
19
19
  } catch (error) {
20
- return ctx.status(403).json({ message: "Invalid token" });
20
+ return ctx.json({ message: "Invalid token" },403);
21
21
  }
22
22
  }
23
23
 
24
+ const h1 = () => {
25
+ console.log('from h1')
26
+ }
27
+ const h2 = () => {
28
+ console.log('from h2')
29
+ }
30
+
31
+ // app
32
+ // .filter()
33
+ // .routeMatcher("/cookie")
34
+ // .permitAll()
35
+ // .require(authJwt as middlewareFunc)
36
+
24
37
  // Error Handling Hook
25
38
  app.addHooks("onError", (error: any, req: Request, url: URL) => {
26
39
  console.error(`Error occurred: ${error.message}`);
@@ -28,48 +41,61 @@ app.addHooks("onError", (error: any, req: Request, url: URL) => {
28
41
  return new Response("Internal Server Error", { status: 500 });
29
42
  });
30
43
 
44
+ // app.use("/home",h1)
45
+ // app.use(["/home","/user"],[h1,h2])
46
+ // app.use(['/home','/user'],[h1,h2])
47
+
31
48
  // Routes
32
49
  app
33
50
  .get("/", async (ctx) => {
34
- const user = ctx.getUser();
35
- return ctx.json({
36
- msg: "Hello World",
37
- user,
38
- });
39
- })
40
- .get("/error", async () => {
41
- throw new Error("This is a test error to demonstrate error handling");
42
- })
43
- .get("/test/:id/:name", async (ctx) => {
44
- const query = ctx.getQuery();
45
- const params = ctx.getParams();
46
- return ctx.json({ msg: "Hello World", query, params });
51
+ // const user = ctx.getUser();
52
+ return ctx.json({msg:"Hello world"})
47
53
  })
48
- .get("/ok", (ctx) => {
49
- return ctx.status(200).text("How are you?");
50
- })
51
- .get("/cookie", async (ctx) => {
52
- const user = { name: "pk", age: 22 };
54
+ // .get("/:id",async (ctx) => {
55
+ // const id= ctx.getParams("id")
56
+ // return ctx.json({id})
57
+ // })
58
+ // .get("/:name?",(ctx:ContextType) =>{
59
+ // return ctx.text("hello world")
60
+ // })
61
+ // .get("/error", async () => {
62
+ // throw new Error("This is a test error to demonstrate error handling");
63
+ // })
64
+ // .get("/redirect",async(ctx:ContextType) => {
65
+ // return ctx.redirect("/")
66
+ // })
67
+ // .get("/test/:id/:name", async (ctx) => {
68
+ // const query = ctx.getQuery();
69
+ // const params = ctx.getParams();
70
+ // return ctx.json({ msg: "Hello World", query, params });
71
+ // })
72
+ // .get("/ok", (ctx:ContextType) => {
73
+ // return ctx.text("How are you?");
74
+ // })
75
+ // .get("/cookie", async (ctx) => {
76
+ // const user = { name: "pk", age: 22 };
53
77
 
54
- const accessToken = jwt.sign(user, SECRET_KEY, { expiresIn: "1d" });
55
- const refreshToken = jwt.sign(user, SECRET_KEY, { expiresIn: "10d" });
78
+ // const accessToken = jwt.sign(user, SECRET_KEY, { expiresIn: "1d" });
79
+ // const refreshToken = jwt.sign(user, SECRET_KEY, { expiresIn: "10d" });
56
80
 
57
- const cookieOptions: CookieOptions = {
58
- httpOnly: true,
59
- secure: true,
60
- maxAge: 24 * 60 * 60 * 1000,
61
- sameSite: "Strict",
62
- path: "/",
63
- };
81
+ // const cookieOptions: CookieOptions = {
82
+ // httpOnly: true,
83
+ // secure: true,
84
+ // maxAge: 24 * 60 * 60 * 1000,
85
+ // sameSite: "Strict",
86
+ // path: "/",
87
+ // };
64
88
 
65
- return ctx
66
- .setCookie("accessToken", accessToken, cookieOptions)
67
- .setCookie("refreshToken", refreshToken, cookieOptions)
68
- .json({ msg: "Cookies set successfully" });
69
- });
89
+ // return ctx
90
+ // .setCookie("accessToken", accessToken, cookieOptions)
91
+ // .setCookie("refreshToken", refreshToken, cookieOptions)
92
+ // .json({ msg: "Cookies set successfully" });
93
+ // });
70
94
 
71
95
  // Register Additional Routes
72
- app.register("/api/user", userRoute);
96
+ // app.register("/api/user", userRoute);
97
+
98
+ // app.route('/api/route', newRoute)
73
99
 
74
100
  // Start the Server
75
- app.listen(3000)
101
+ app.listen(port)
package/example/route.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import Diesel from "../src/main";
2
- import Router from "../src/route";
2
+ // import Router from "../src/route";
3
3
  import { authJwt } from "./main";
4
4
 
5
- const userRoute = new Router();
5
+ const userRoute = new Diesel();
6
6
 
7
7
  const h = () => {
8
8
  console.log('object');
package/example/tester.js CHANGED
@@ -7,7 +7,7 @@ const secret = "secret";
7
7
  // app.filter().permitAll().require()
8
8
 
9
9
  app.get("/r", (xl) => {
10
- return xl.html(`${import.meta.dir}/index.html`);
10
+ return xl.file(`${import.meta.dir}/index.html`);
11
11
  });
12
12
 
13
13
  // app.use((xl) => {
@@ -39,7 +39,7 @@ app.get("/r", (xl) => {
39
39
  // app.filter()
40
40
 
41
41
  app.get("/", async (xl) => {
42
- return xl.status(200).text("hello d")
42
+ return xl.text("hello d")
43
43
  })
44
44
 
45
45
  app.post("/", async (xl) => {
package/index.js CHANGED
@@ -1,10 +1,9 @@
1
- import Diesel from './src/main'
2
- import Router from './src/route'
3
- import rateLimit from './src/utils'
1
+ import Diesel from './dist/main'
2
+ // import Router from './src/route'
3
+ import rateLimit from './dist/utils'
4
4
 
5
5
 
6
6
  export {
7
7
  Diesel,
8
- Router,
9
8
  rateLimit
10
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "diesel-core",
3
- "version": "0.0.21",
3
+ "version": "0.0.23",
4
4
  "main": "index.js",
5
5
  "types": "index.d.ts",
6
6
  "scripts": {
package/src/ctx.ts CHANGED
@@ -3,9 +3,11 @@ import { Server } from "bun";
3
3
 
4
4
  import type { ContextType, CookieOptions, ParseBodyResult } from "./types";
5
5
 
6
-
7
- export default function createCtx(req: Request, server: Server, url: URL): ContextType {
8
-
6
+ export default function createCtx(
7
+ req: Request,
8
+ server: Server,
9
+ url: URL
10
+ ): ContextType {
9
11
  let headers: Headers = new Headers();
10
12
  let settedValue: Record<string, string> = {};
11
13
  let isAuthenticated: boolean = false;
@@ -13,7 +15,7 @@ export default function createCtx(req: Request, server: Server, url: URL): Conte
13
15
  let parsedCookie: any = null;
14
16
  let parsedParams: any;
15
17
  let parsedBody: ParseBodyResult | null;
16
- let responseStatus: number = 200;
18
+ // let responseStatus: number = 200;
17
19
  let user: any = {};
18
20
 
19
21
  return {
@@ -26,16 +28,16 @@ export default function createCtx(req: Request, server: Server, url: URL): Conte
26
28
  return user;
27
29
  },
28
30
 
29
- setUser(data?: any) : void {
31
+ setUser(data?: any): void {
30
32
  if (data) {
31
33
  user = data;
32
34
  }
33
35
  },
34
36
 
35
- status(status: number): ContextType {
36
- responseStatus = status;
37
- return this;
38
- },
37
+ // status(status: number): ContextType {
38
+ // responseStatus = status;
39
+ // return this;
40
+ // },
39
41
 
40
42
  getIP() {
41
43
  return this.server.requestIP(this.req);
@@ -59,12 +61,15 @@ export default function createCtx(req: Request, server: Server, url: URL): Conte
59
61
  },
60
62
 
61
63
  set(key: string, value: any): ContextType {
64
+ if (typeof key !== "string") throw new Error("Key must be string type!");
65
+ if (!value)
66
+ throw new Error("value paramter is missing pls pass value after key");
62
67
  settedValue[key] = value;
63
68
  return this;
64
69
  },
65
70
 
66
71
  get(key: string): any | null {
67
- return settedValue[key] || null;
72
+ return key ? settedValue[key] : null;
68
73
  },
69
74
 
70
75
  setAuth(authStatus: boolean): ContextType {
@@ -79,35 +84,35 @@ export default function createCtx(req: Request, server: Server, url: URL): Conte
79
84
  // Response methods with optional status
80
85
  text(data: string, status?: number) {
81
86
  return new Response(data, {
82
- status: status ?? responseStatus,
87
+ status,
83
88
  headers,
84
89
  });
85
90
  },
86
91
 
87
- send(data: string, status?: number) {
88
- return new Response(data, {
89
- status: status ?? responseStatus,
90
- headers,
91
- });
92
- },
92
+ // send(data: string, status?: number) {
93
+ // return new Response(data, {
94
+ // status: status ?? responseStatus,
95
+ // headers,
96
+ // });
97
+ // },
93
98
 
94
99
  json(data: any, status?: number): Response {
95
100
  return new Response(JSON.stringify(data), {
96
- status: status ?? responseStatus,
101
+ status,
97
102
  headers,
98
103
  });
99
104
  },
100
105
 
101
- html(filepath: string, status?: number): Response {
102
- return new Response(Bun.file(filepath), {
103
- status: status ?? responseStatus,
104
- headers,
105
- });
106
- },
106
+ // html(filepath: string, status?: number): Response {
107
+ // return new Response(Bun.file(filepath), {
108
+ // status: status ?? responseStatus,
109
+ // headers,
110
+ // });
111
+ // },
107
112
 
108
113
  file(filePath: string, status?: number): Response {
109
114
  return new Response(Bun.file(filePath), {
110
- status: status ?? responseStatus,
115
+ status,
111
116
  headers,
112
117
  });
113
118
  },
@@ -120,7 +125,11 @@ export default function createCtx(req: Request, server: Server, url: URL): Conte
120
125
  });
121
126
  },
122
127
 
123
- setCookie(name: string, value: string, options: CookieOptions = {}) : ContextType {
128
+ setCookie(
129
+ name: string,
130
+ value: string,
131
+ options: CookieOptions = {}
132
+ ): ContextType {
124
133
  let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(
125
134
  value
126
135
  )}`;
@@ -140,12 +149,14 @@ export default function createCtx(req: Request, server: Server, url: URL): Conte
140
149
  return this;
141
150
  },
142
151
 
143
- getParams(props: string) : string | Record<string, string> | {}
144
- {
152
+ getParams(props: string): string | Record<string, string> | {} {
145
153
  if (!parsedParams && req?.routePattern) {
146
154
  parsedParams = extractDynamicParams(req?.routePattern, url?.pathname);
147
155
  }
148
- return props ? parsedParams[props] || {} : parsedParams;
156
+ if (props) {
157
+ return parsedParams[props] ?? {};
158
+ }
159
+ return props;
149
160
  },
150
161
 
151
162
  getQuery(props?: any): string | Record<string, string> | {} {
@@ -163,9 +174,8 @@ export default function createCtx(req: Request, server: Server, url: URL): Conte
163
174
  if (!parsedCookie) {
164
175
  const cookieHeader = req.headers.get("cookie");
165
176
  if (cookieHeader) {
166
- parsedCookie = parseCookie(cookieHeader)
167
- }
168
- else return null;
177
+ parsedCookie = parseCookie(cookieHeader);
178
+ } else return null;
169
179
  }
170
180
  if (!parsedCookie) return null;
171
181
 
@@ -181,14 +191,13 @@ export default function createCtx(req: Request, server: Server, url: URL): Conte
181
191
  function parseCookie(cookieHeader: string | undefined): Record<string, string> {
182
192
  const cookies: Record<string, string> = {};
183
193
 
194
+ const cookiesArray = cookieHeader?.split(";")!;
184
195
 
185
- const cookiesArray = cookieHeader?.split(";")!
186
-
187
- for(let i =0; i < cookiesArray?.length!; i++){
196
+ for (let i = 0; i < cookiesArray?.length!; i++) {
188
197
  const [cookieName, ...cookieValeParts] = cookiesArray[i].trim().split("=");
189
- const cookieVale = cookieValeParts?.join("=").trim()
190
- if (cookieName){
191
- cookies[cookieName.trim()] = decodeURIComponent(cookieVale)
198
+ const cookieVale = cookieValeParts?.join("=").trim();
199
+ if (cookieName) {
200
+ cookies[cookieName.trim()] = decodeURIComponent(cookieVale);
192
201
  }
193
202
  }
194
203
 
@@ -208,7 +217,7 @@ function extractDynamicParams(
208
217
  return null;
209
218
  }
210
219
 
211
- for (let i =0; i<routeSegments.length; i++){
220
+ for (let i = 0; i < routeSegments.length; i++) {
212
221
  if (routeSegments[i].startsWith(":")) {
213
222
  // const dynamicKey = routeSegments[i].slice(1);
214
223
  // object[dynamicKey] = pathSegments[i];
@@ -221,7 +230,7 @@ function extractDynamicParams(
221
230
  }
222
231
 
223
232
  async function parseBody(req: Request): Promise<ParseBodyResult> {
224
- const contentType: string = req.headers.get("Content-Type")!
233
+ const contentType: string = req.headers.get("Content-Type")!;
225
234
 
226
235
  if (!contentType) return {};
227
236
 
@@ -249,4 +258,3 @@ async function parseBody(req: Request): Promise<ParseBodyResult> {
249
258
  return { error: "Invalid request body format" };
250
259
  }
251
260
  }
252
-
@@ -36,13 +36,13 @@ export default async function handleRequest(req: Request, server: Server, url: U
36
36
  if (filterResult) return filterResult
37
37
  } catch (error:any) {
38
38
  console.error("Error in filterFunction:", error);
39
- return ctx.status(500).json({
39
+ return ctx.json({
40
40
  message: "Internal Server Error",
41
41
  error: error.message
42
- });
42
+ },500);
43
43
  }
44
44
  } else {
45
- return ctx.status(400).json({ message: "Authentication required" })
45
+ return ctx.json({ message: "Authentication required" },400)
46
46
  }
47
47
  }
48
48
  }
@@ -93,7 +93,7 @@ export default async function handleRequest(req: Request, server: Server, url: U
93
93
  }
94
94
 
95
95
  // Default Response if Handler is Void
96
- return result ?? ctx.status(204).json({ message:"No response from this handler" })
96
+ return result ?? ctx.json({ message:"No response from this handler" },204)
97
97
 
98
98
  }
99
99
 
@@ -121,24 +121,24 @@ function applyCors(req: Request, ctx: ContextType, config: corsT = {}): Response
121
121
  ctx.setHeader("Access-Control-Allow-Origin", '*')
122
122
  }
123
123
  else {
124
- return ctx.status(403).json({ message: "CORS not allowed" })
124
+ return ctx.json({ message: "CORS not allowed" },403)
125
125
  }
126
126
  } else if (typeof allowedOrigins === 'string') {
127
127
  if (origin === allowedOrigins) {
128
128
  ctx.setHeader("Access-Control-Allow-Origin", origin)
129
129
  }
130
130
  else {
131
- return ctx.status(403).json({ message: "CORS not allowed" });
131
+ return ctx.json({ message: "CORS not allowed" },403);
132
132
  }
133
133
  } else {
134
- return ctx.status(403).json({ message: "CORS not allowed" })
134
+ return ctx.json({ message: "CORS not allowed" },403)
135
135
  }
136
136
 
137
137
  ctx.setHeader("Access-Control-Allow-Origin", origin)
138
138
 
139
139
  if (req.method === 'OPTIONS') {
140
140
  ctx.setHeader('Access-Control-Max-Age', '86400')
141
- return ctx.status(204).text('')
141
+ return ctx.text('',204)
142
142
  }
143
143
 
144
144
  return null
package/src/main.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  FilterMethods,
7
7
  HookFunction,
8
8
  HookType,
9
+ listenArgsT,
9
10
  middlewareFunc,
10
11
  onError,
11
12
  onRequest,
@@ -84,9 +85,9 @@ export default class Diesel {
84
85
  };
85
86
  }
86
87
 
87
- cors(corsConfig: corsT) : this {
88
+ cors(corsConfig: corsT): this {
88
89
  this.corsConfig = corsConfig;
89
- return this
90
+ return this;
90
91
  }
91
92
 
92
93
  addHooks(
@@ -130,7 +131,7 @@ export default class Diesel {
130
131
  return this;
131
132
  }
132
133
 
133
- compile(): void {
134
+ private compile(): void {
134
135
  if (this.globalMiddlewares.length > 0) {
135
136
  this.hasMiddleware = true;
136
137
  }
@@ -150,23 +151,22 @@ export default class Diesel {
150
151
  this.tempRoutes = new Map();
151
152
  }
152
153
 
153
- listen(...args: any): Server | void {
154
+ listen(port:number = 3000, ...args: listenArgsT[]): Server | void {
154
155
  if (typeof Bun === "undefined")
155
156
  throw new Error(".listen() is designed to run on Bun only...");
157
+
158
+ if(!port || typeof port !== "number") throw new Error("port is required and should be a number type")
156
159
 
157
- let port = 3000;
158
160
  let hostname = "0.0.0.0";
159
161
  let callback: (() => void) | undefined = undefined;
160
162
  let options: { sslCert?: string; sslKey?: string } = {};
161
163
 
162
164
  for (const arg of args) {
163
- if (typeof arg === 'number') {
164
- port = arg;
165
- } else if (typeof arg === 'string') {
165
+ if (typeof arg === "string") {
166
166
  hostname = arg;
167
- } else if (typeof arg === 'function') {
167
+ } else if (typeof arg === "function") {
168
168
  callback = arg;
169
- } else if (typeof arg === 'object' && arg !== null) {
169
+ } else if (typeof arg === "object" && arg !== null) {
170
170
  options = arg;
171
171
  }
172
172
  }
@@ -257,21 +257,29 @@ export default class Diesel {
257
257
  });
258
258
 
259
259
  routerInstance = null;
260
- return this
260
+ return this;
261
261
  }
262
262
 
263
263
  register(basePath: string, routerInstance: any): this {
264
264
  this.route(basePath, routerInstance);
265
- return this
265
+ return this;
266
266
  }
267
267
 
268
- addRoute(
268
+ private addRoute(
269
269
  method: HttpMethod,
270
270
  path: string,
271
271
  handlers: handlerFunction[]
272
272
  ): void {
273
- if (typeof path !== "string") throw new Error("Path must be a string");
274
- if (typeof method !== "string") throw new Error("Method must be a string");
273
+ if (typeof path !== "string")
274
+ throw new Error(
275
+ `Error in ${
276
+ handlers[handlers.length - 1]
277
+ }: Path must be a string. Received: ${typeof path}`
278
+ );
279
+ if (typeof method !== "string")
280
+ throw new Error(
281
+ `Error in addRoute: Method must be a string. Received: ${typeof method}`
282
+ );
275
283
 
276
284
  this.tempRoutes.set(path, { method, handlers });
277
285
  const middlewareHandlers = handlers.slice(0, -1) as middlewareFunc[];
@@ -300,35 +308,42 @@ export default class Diesel {
300
308
  }
301
309
 
302
310
  use(
303
- pathORHandler?: string | middlewareFunc,
304
- ...handlers: middlewareFunc[]
311
+ pathORHandler?: string | string[] | middlewareFunc,
312
+ handlers?: middlewareFunc | middlewareFunc[]
305
313
  ): this | void {
314
+
306
315
  if (typeof pathORHandler === "function") {
307
316
  if (!this.globalMiddlewares.includes(pathORHandler)) {
308
317
  this.globalMiddlewares.push(pathORHandler);
309
318
  }
310
- handlers.forEach((handler: middlewareFunc) => {
311
- if (!this.globalMiddlewares.includes(handler)) {
312
- this.globalMiddlewares.push(handler);
313
- }
314
- });
319
+ if (Array.isArray(handlers)) {
320
+ handlers.forEach((handler: middlewareFunc) => {
321
+ if (!this.globalMiddlewares.includes(handler)) {
322
+ this.globalMiddlewares.push(handler);
323
+ }
324
+ });
325
+ }
315
326
  return;
316
327
  }
317
328
 
318
- const path: string = pathORHandler as string;
319
-
320
- if (!this.middlewares.has(path)) {
321
- this.middlewares.set(path, []);
322
- }
329
+ const paths: string[] = Array.isArray(pathORHandler)
330
+ ? pathORHandler.filter((path: string) => typeof path === "string")
331
+ : [pathORHandler].filter((path): path is string => typeof path === "string");
323
332
 
324
- if (handlers) {
325
- handlers.forEach((handler: middlewareFunc) => {
326
- if (!this.middlewares.get(path)?.includes(handler)) {
327
- this.middlewares.get(path)?.push(handler);
328
- }
329
- });
330
- }
331
- return this
333
+ paths.forEach((path: string) => {
334
+ if (!this.middlewares.has(path)) {
335
+ this.middlewares.set(path, []);
336
+ }
337
+ if (handlers) {
338
+ const handlerArray = Array.isArray(handlers) ? handlers : [handlers];
339
+ handlerArray.forEach((handler: middlewareFunc) => {
340
+ if (!this.middlewares.get(path)?.includes(handler)) {
341
+ this.middlewares.get(path)?.push(handler);
342
+ }
343
+ });
344
+ }
345
+ });
346
+ return this;
332
347
  }
333
348
 
334
349
  get(path: string, ...handlers: handlerFunction[]): this {
package/src/types.ts CHANGED
@@ -42,7 +42,7 @@ export interface ContextType {
42
42
  url: URL;
43
43
  setUser: (data?:any) => void
44
44
  getUser: () => any
45
- status: (status: number) => this;
45
+ // status: (status: number) => this;
46
46
  getIP: () => any;
47
47
  getBody: () => Promise<any>;
48
48
  setHeader: (key: string, value: any) => this;
@@ -52,8 +52,8 @@ export interface ContextType {
52
52
  getAuth: () => boolean;
53
53
  json: (data: Object, status?: number) => Response;
54
54
  text: (data: string, status?: number) => Response;
55
- send: (data: string, status?: number) => Response;
56
- html: (filePath: string, status?: number) => Response;
55
+ // send: (data: string, status?: number) => Response;
56
+ // html: (filePath: string, status?: number) => Response;
57
57
  file: (filePath: string, status?: number) => Response;
58
58
  redirect: (path: string, status?: number) => Response;
59
59
  getParams: (props?: any) => any;
@@ -155,4 +155,11 @@ export interface FilterMethods {
155
155
  routeMatcher: (...routes: string[]) => FilterMethods;
156
156
  permitAll: () => FilterMethods;
157
157
  require: (fnc?: middlewareFunc) => Response | void;
158
+ }
159
+
160
+ export type listenArgsT = string | (() => void) | { sslCert?: string; sslKey?: string };
161
+
162
+ interface ListenType {
163
+ port: number;
164
+ args?: listenArgsT
158
165
  }
package/src/utils.ts CHANGED
@@ -27,9 +27,9 @@ export default function rateLimit(props: { time?: number; max?: number; message?
27
27
  }
28
28
 
29
29
  if (requestInfo && requestInfo.count > max) {
30
- return ctx.status(429).json({
30
+ return ctx.json({
31
31
  error: message
32
- })
32
+ },429)
33
33
  }
34
34
 
35
35
  }
package/.prettierignore DELETED
@@ -1,7 +0,0 @@
1
- /.vscode
2
- /node_modules
3
- ./dist
4
-
5
- *.env
6
- .env
7
- .env.*
package/.prettierrc DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "singleQuote": false,
3
- "bracketSpacing": true,
4
- "tabWidth": 2,
5
- "semi": true,
6
- "trailingComma": "es5"
7
- }
package/src/route.ts DELETED
@@ -1,35 +0,0 @@
1
- import Diesel from "./main";
2
- import type { handlerFunction, HttpMethod } from "./types";
3
-
4
- class Router extends Diesel {
5
- constructor() {
6
- super();
7
- }
8
-
9
- get(path:string, ...handlers:handlerFunction[]) {
10
- this.addRoute("GET", path, handlers);
11
- return this
12
- }
13
-
14
- post(path:string, ...handlers:handlerFunction[]) {
15
- this.addRoute("POST", path, handlers);
16
- return this;
17
- }
18
-
19
- put(path:string, ...handlers:handlerFunction[]) {
20
- this.addRoute("PUT", path, handlers);
21
- return this
22
- }
23
-
24
- patch(path:string, ...handlers:handlerFunction[]) {
25
- this.addRoute("PATCH", path, handlers);
26
- return this
27
- }
28
-
29
- delete(path:string, ...handlers:handlerFunction[]) {
30
- this.addRoute("DELETE", path, handlers);
31
- return this;
32
- }
33
- }
34
-
35
- export default Router;