diesel-core 1.0.13 → 1.0.14

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "diesel-core",
3
- "version": "1.0.13",
3
+ "version": "1.0.14",
4
4
  "description": "Web framework built on Web Standards",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -12,16 +12,16 @@
12
12
  "exports": {
13
13
  ".": {
14
14
  "types": "./index.d.ts",
15
- "import": "./index.js",
16
- "require": "./index.js"
15
+ "import": "./index.js",
16
+ "require": "./index.js"
17
17
  },
18
18
  "./cors": {
19
- "types":"./dist/middlewares/cors/cors.d.ts",
19
+ "types": "./dist/middlewares/cors/cors.d.ts",
20
20
  "import": "./src/middlewares/cors/cors.js",
21
21
  "require": "./dist/middlewares/cors/cors.js"
22
22
  },
23
23
  "./security": {
24
- "types":"./dist/middlewares/security/security.d.ts",
24
+ "types": "./dist/middlewares/security/security.d.ts",
25
25
  "import": "./src/middlewares/security/security.js",
26
26
  "require": "./dist/middlewares/security/security.js"
27
27
  }
package/dist/ctx.d.ts DELETED
@@ -1,3 +0,0 @@
1
- import { Server } from "bun";
2
- import type { ContextType } from "./types";
3
- export default function createCtx(req: Request, server: Server, url: URL): ContextType;
package/dist/ctx.js DELETED
@@ -1 +0,0 @@
1
- function V(E){let{time:F=60000,max:O=100,message:z="Rate limit exceeded. Please try again later."}=E,G=new Map;return(Y)=>{let K=new Date,$=Y.ip;if(!G.has($))G.set($,{count:0,startTime:K});let Z=G.get($);if(Z)if(K-Z.startTime>F)Z.count=1,Z.startTime=K;else Z.count++;if(Z&&Z.count>O)return Y.json({error:z},429)}}function R(E){switch(E.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var N=(E,F,O,z)=>{if(O>z)return!1;let G=O+(z-O)/2;if(E[G]==F)return!0;if(E[G]>F)return N(E,F,O,G-1);return N(E,F,G+1,z)};function W(E,F,O){let z=new Headers({"Cache-Control":"no-cache"}),G=null,Y=null,K=null,$=null,Z={};return{req:E,server:F,url:O,setHeader(A,L){return z.set(A,L),this},removeHeader(A){return z.delete(A),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!G)try{G=Object.fromEntries(this.url.searchParams)}catch(A){throw new Error("Failed to parse query parameters")}return G},get params(){if(!Y&&this.req.routePattern)try{Y=w(this.req.routePattern,this.url.pathname)}catch(A){throw new Error("Failed to extract route parameters")}return Y??{}},get body(){if(!$)$=(async()=>{let A=await _(this.req);if(A.error)throw new Error(A.error);return Object.keys(A).length===0?null:A})();return $},set(A,L){return Z[A]=L,this},get(A){return Z[A]},text(A,L=200){if(!z.has("Content-Type"))z.set("Content-Type","text/plain; charset=utf-8");return new Response(A,{status:L,headers:z})},send(A,L=200){let J=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),X=A instanceof Uint8Array?"Uint8Array":A instanceof ArrayBuffer?"ArrayBuffer":typeof A;if(!z.has("Content-Type"))z.set("Content-Type",J.get(X)??"text/plain; charset=utf-8");let U=X==="object"&&A!==null?JSON.stringify(A):A;return new Response(U,{status:L,headers:z})},json(A,L=200){if(!z.has("Content-Type"))z.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(A),{status:L,headers:z})},file(A,L=200,J){let X=Bun.file(A);if(!z.has("Content-Type"))z.set("Content-Type",J??R(A));return new Response(X,{status:L,headers:z})},redirect(A,L=302){return z.set("Location",A),new Response(null,{status:L,headers:z})},setCookie(A,L,J={}){let X=`${encodeURIComponent(A)}=${encodeURIComponent(L)}`;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},get cookies(){if(!K){let A=this.req.headers.get("cookie");K=A?j(A):{}}return K}}}function j(E){return Object.fromEntries(E.split(";").map((F)=>{let[O,...z]=F.trim().split("=");return[O,decodeURIComponent(z.join("="))]}))}function w(E,F){let O={},z=E.split("/"),[G]=F.split("?"),Y=G.split("/");if(z.length!==Y.length)return null;for(let K=0;K<z.length;K++)if(z[K].startsWith(":"))O[z[K].slice(1)]=Y[K];return O}async function _(E){let F=E.headers.get("Content-Type");if(!F)return{};if(E.headers.get("Content-Length")==="0"||!E.body)return{};try{if(F.startsWith("application/json"))return await E.json();if(F.startsWith("application/x-www-form-urlencoded")){let z=await E.text();return Object.fromEntries(new URLSearchParams(z))}if(F.startsWith("multipart/form-data")){let z=await E.formData(),G={};for(let[Y,K]of z.entries())G[Y]=K;return G}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}export{W as default};
@@ -1,6 +0,0 @@
1
- import { Server } from "bun";
2
- import type { ContextType, DieselT } from "./types";
3
- export default function handleRequest(req: Request, server: Server, url: URL, diesel: DieselT): Promise<Response>;
4
- export declare function handleFilterRequest(diesel: DieselT, path: string, ctx: ContextType, server: Server): Promise<Response | undefined>;
5
- export declare function generateErrorResponse(status: number, message: string): Response;
6
- export declare function handleStaticFiles(diesel: DieselT, pathname: string, ctx: ContextType): Promise<Response | null>;
@@ -1 +0,0 @@
1
- function F(G){let{time:J=60000,max:L=100,message:z="Rate limit exceeded. Please try again later."}=G,K=new Map;return(X)=>{let N=new Date,U=X.ip;if(!K.has(U))K.set(U,{count:0,startTime:N});let Y=K.get(U);if(Y)if(N-Y.startTime>J)Y.count=1,Y.startTime=N;else Y.count++;if(Y&&Y.count>L)return X.json({error:z},429)}}function V(G){switch(G.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var _=(G,J,L,z)=>{if(L>z)return!1;let K=L+(z-L)/2;if(G[K]==J)return!0;if(G[K]>J)return _(G,J,L,K-1);return _(G,J,K+1,z)};function W(G,J,L){let z=new Headers({"Cache-Control":"no-cache"}),K=null,X=null,N=null,U=null,Y={};return{req:G,server:J,url:L,setHeader(A,Z){return z.set(A,Z),this},removeHeader(A){return z.delete(A),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!K)try{K=Object.fromEntries(this.url.searchParams)}catch(A){throw new Error("Failed to parse query parameters")}return K},get params(){if(!X&&this.req.routePattern)try{X=B(this.req.routePattern,this.url.pathname)}catch(A){throw new Error("Failed to extract route parameters")}return X??{}},get body(){if(!U)U=(async()=>{let A=await D(this.req);if(A.error)throw new Error(A.error);return Object.keys(A).length===0?null:A})();return U},set(A,Z){return Y[A]=Z,this},get(A){return Y[A]},text(A,Z=200){if(!z.has("Content-Type"))z.set("Content-Type","text/plain; charset=utf-8");return new Response(A,{status:Z,headers:z})},send(A,Z=200){let $=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),O=A instanceof Uint8Array?"Uint8Array":A instanceof ArrayBuffer?"ArrayBuffer":typeof A;if(!z.has("Content-Type"))z.set("Content-Type",$.get(O)??"text/plain; charset=utf-8");let E=O==="object"&&A!==null?JSON.stringify(A):A;return new Response(E,{status:Z,headers:z})},json(A,Z=200){if(!z.has("Content-Type"))z.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(A),{status:Z,headers:z})},file(A,Z=200,$){let O=Bun.file(A);if(!z.has("Content-Type"))z.set("Content-Type",$??V(A));return new Response(O,{status:Z,headers:z})},redirect(A,Z=302){return z.set("Location",A),new Response(null,{status:Z,headers:z})},setCookie(A,Z,$={}){let O=`${encodeURIComponent(A)}=${encodeURIComponent(Z)}`;if($.maxAge)O+=`; Max-Age=${$.maxAge}`;if($.expires)O+=`; Expires=${$.expires.toUTCString()}`;if($.path)O+=`; Path=${$.path}`;if($.domain)O+=`; Domain=${$.domain}`;if($.secure)O+="; Secure";if($.httpOnly)O+="; HttpOnly";if($.sameSite)O+=`; SameSite=${$.sameSite}`;return z.append("Set-Cookie",O),this},get cookies(){if(!N){let A=this.req.headers.get("cookie");N=A?Q(A):{}}return N}}}function Q(G){return Object.fromEntries(G.split(";").map((J)=>{let[L,...z]=J.trim().split("=");return[L,decodeURIComponent(z.join("="))]}))}function B(G,J){let L={},z=G.split("/"),[K]=J.split("?"),X=K.split("/");if(z.length!==X.length)return null;for(let N=0;N<z.length;N++)if(z[N].startsWith(":"))L[z[N].slice(1)]=X[N];return L}async function D(G){let J=G.headers.get("Content-Type");if(!J)return{};if(G.headers.get("Content-Length")==="0"||!G.body)return{};try{if(J.startsWith("application/json"))return await G.json();if(J.startsWith("application/x-www-form-urlencoded")){let z=await G.text();return Object.fromEntries(new URLSearchParams(z))}if(J.startsWith("multipart/form-data")){let z=await G.formData(),K={};for(let[X,N]of z.entries())K[X]=N;return K}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}async function w(G,J,L,z){let K=z.trie.search(L.pathname,G.method);G.routePattern=K?.path;let X=W(G,J,L);if(z.hasFilterEnabled){let Y=G.routePattern??L.pathname,A=await C(z,Y,X,J);if(A)return A}if(z.hasMiddleware){let Y=z.globalMiddlewares;for(let Z=0;Z<Y.length;Z++){let $=await Y[Z](X,J);if($)return $}let A=z.middlewares.get(L.pathname)||[];for(let Z=0;Z<A.length;Z++){let $=await A[Z](X,J);if($)return $}}if(!K?.handler||K.method!==G.method){let Y=z.trie.search("*",G.method);if(Y){let A=await M(z,L.pathname,X);if(A)return A;return await Y.handler(X)}if(z.hooks.routeNotFound){let A=await z.hooks.routeNotFound(X);if(A)return A}if(!K||!K.handler.length)return j(404,`Route not found for ${L.pathname}`);return j(405,"Method not allowed")}if(z.hooks.preHandler){let Y=await z.hooks.preHandler(X);if(Y)return Y}let N=K.handler(X),U=N instanceof Promise?await N:N;if(z.hooks.postHandler)await z.hooks.postHandler(X);if(z.hooks.onSend){let Y=await z.hooks.onSend(X,U);if(Y)return Y}return U??j(204,"No response from this handler")}async function C(G,J,L,z){if(!G.filters.has(J))if(G.filterFunction.length)for(let K of G.filterFunction){let X=await K(L,z);if(X)return X}else return L.json({error:!0,message:"Protected route, authentication required",status:401},401)}function j(G,J){return new Response(JSON.stringify({error:!0,message:J,status:G}),{status:G,headers:{"Content-Type":"application/json"}})}async function M(G,J,L){if(!G.UseStaticFiles)throw new Error("Static files directory is not configured.");let z=`${G.UseStaticFiles}${J}`;if(/\.(js|css|html)$/.test(J)){let K=V(z);return L.file(z,200,K)}return null}export{M as handleStaticFiles,C as handleFilterRequest,j as generateErrorResponse,w as default};
package/dist/main.d.ts DELETED
@@ -1,71 +0,0 @@
1
- import Trie from "./trie.js";
2
- import { corsT, FilterMethods, HookFunction, HookType, listenArgsT, middlewareFunc, onError, onRequest, type handlerFunction, type Hooks } from "./types.js";
3
- import { Server } from "bun";
4
- export default class Diesel {
5
- private tempRoutes;
6
- globalMiddlewares: middlewareFunc[];
7
- middlewares: Map<string, middlewareFunc[]>;
8
- trie: Trie;
9
- hasOnReqHook: boolean;
10
- hasMiddleware: boolean;
11
- hasPreHandlerHook: boolean;
12
- hasPostHandlerHook: boolean;
13
- hasOnSendHook: boolean;
14
- hasOnError: boolean;
15
- hooks: Hooks;
16
- corsConfig: corsT;
17
- FilterRoutes: string[] | null | undefined;
18
- filters: Set<string>;
19
- filterFunction: middlewareFunc[];
20
- hasFilterEnabled: boolean;
21
- private serverInstance;
22
- UseStaticFiles: any;
23
- staticFiles: any;
24
- constructor();
25
- setupFilter(): FilterMethods;
26
- UseStatic(filePath: string): void;
27
- static(route: string | string[], filePath: string | string[]): this;
28
- addHooks(typeOfHook: HookType, fnc: HookFunction | onError | onRequest): this;
29
- private compile;
30
- listen(port?: number, ...args: listenArgsT[]): Server | void;
31
- close(callback?: () => void): void;
32
- /**
33
- * Registers a router instance for subrouting.
34
- * Allows defining subroutes like:
35
- * const userRoute = new Diesel();
36
- * app.route("/api/v1/user", userRoute);
37
- */
38
- route(basePath: string, routerInstance: any): this;
39
- /**
40
- * Registers a router instance for subrouting.
41
- * Allows defining subroutes like:
42
- * const userRoute = new Diesel();
43
- * userRoute.post("/login",handlerFunction)
44
- * userRoute.post("/register", handlerFunction)
45
- * app.register("/api/v1/user", userRoute);
46
- */
47
- register(basePath: string, routerInstance: any): this;
48
- private addRoute;
49
- /**
50
- * Adds middleware to the application.
51
- * - Middlewares are executed in the order they are added.
52
- * - Duplicate middleware functions will run multiple times if explicitly included.
53
- *
54
- * Examples:
55
- * - app.use(h1) -> Adds a single global middleware.
56
- * - app.use([h1, h2]) -> Adds multiple global middlewares.
57
- * - app.use("/home", h1) -> Adds `h1` middleware to the `/home` path.
58
- * - app.use(["/home", "/user"], [h1, h2]) -> Adds `h1` and `h2` to `/home` and `/user`.
59
- * - app.use(h1, [h2, h1]) -> Runs `h1`, then `h2`, and `h1` again as specified.
60
- */
61
- use(pathORHandler?: string | string[] | middlewareFunc | middlewareFunc[], handlers?: middlewareFunc | middlewareFunc[]): this | void;
62
- get(path: string, ...handlers: handlerFunction[]): this;
63
- post(path: string, ...handlers: handlerFunction[]): this;
64
- put(path: string, ...handlers: handlerFunction[]): this;
65
- patch(path: string, ...handlers: handlerFunction[]): this;
66
- delete(path: string, ...handlers: handlerFunction[]): this;
67
- any(path: string, ...handlers: handlerFunction[]): this;
68
- head(path: string, ...handlers: handlerFunction[]): this;
69
- options(path: string, ...handlers: handlerFunction[]): this;
70
- propfind(path: string, ...handlers: handlerFunction[]): this;
71
- }
package/dist/main.js DELETED
@@ -1 +0,0 @@
1
- class F{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class _{root;constructor(){this.root=new F}insert(z,A){let J=this.root,G=z.split("/").filter(Boolean);if(z==="/"){J.isEndOfWord=!0,J.handler.push(A.handler),J.path=z,J.method.push(A.method);return}for(let X of G){let Y=!1,L=X;if(X.startsWith(":"))Y=!0,L=":";if(!J.children[L])J.children[L]=new F;J=J.children[L],J.isDynamic=Y,J.pattern=X,J.method.push(A.method),J.handler.push(A.handler),J.path=z}J.isEndOfWord=!0,J.method.push(A.method),J.handler.push(A.handler),J.path=z}search(z,A){let J=this.root,G=z.split("/").filter(Boolean),X=G.length;for(let V of G){let Z=V;if(!J.children[Z])if(J.children[":"])J=J.children[":"];else return null;else J=J.children[Z]}let Y=J.path.split("/").filter(Boolean);if(X!==Y.length)return null;let L=J.method.indexOf(A);if(L!==-1)return{path:J.path,handler:J.handler[L],isDynamic:J.isDynamic,pattern:J.pattern,method:J.method[L]};return{path:J.path,handler:J.handler,isDynamic:J.isDynamic,pattern:J.pattern,method:J.method[L]}}}function M(z){let{time:A=60000,max:J=100,message:G="Rate limit exceeded. Please try again later."}=z,X=new Map;return(Y)=>{let L=new Date,V=Y.ip;if(!X.has(V))X.set(V,{count:0,startTime:L});let Z=X.get(V);if(Z)if(L-Z.startTime>A)Z.count=1,Z.startTime=L;else Z.count++;if(Z&&Z.count>J)return Y.json({error:G},429)}}function E(z){switch(z.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var N=(z,A,J,G)=>{if(J>G)return!1;let X=J+(G-J)/2;if(z[X]==A)return!0;if(z[X]>A)return N(z,A,J,X-1);return N(z,A,X+1,G)};function Q(z,A,J){let G=new Headers({"Cache-Control":"no-cache"}),X=null,Y=null,L=null,V=null,Z={};return{req:z,server:A,url:J,setHeader(K,$){return G.set(K,$),this},removeHeader(K){return G.delete(K),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!X)try{X=Object.fromEntries(this.url.searchParams)}catch(K){throw new Error("Failed to parse query parameters")}return X},get params(){if(!Y&&this.req.routePattern)try{Y=w(this.req.routePattern,this.url.pathname)}catch(K){throw new Error("Failed to extract route parameters")}return Y??{}},get body(){if(!V)V=(async()=>{let K=await I(this.req);if(K.error)throw new Error(K.error);return Object.keys(K).length===0?null:K})();return V},set(K,$){return Z[K]=$,this},get(K){return Z[K]},text(K,$=200){if(!G.has("Content-Type"))G.set("Content-Type","text/plain; charset=utf-8");return new Response(K,{status:$,headers:G})},send(K,$=200){let U=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),W=K instanceof Uint8Array?"Uint8Array":K instanceof ArrayBuffer?"ArrayBuffer":typeof K;if(!G.has("Content-Type"))G.set("Content-Type",U.get(W)??"text/plain; charset=utf-8");let C=W==="object"&&K!==null?JSON.stringify(K):K;return new Response(C,{status:$,headers:G})},json(K,$=200){if(!G.has("Content-Type"))G.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(K),{status:$,headers:G})},file(K,$=200,U){let W=Bun.file(K);if(!G.has("Content-Type"))G.set("Content-Type",U??E(K));return new Response(W,{status:$,headers:G})},redirect(K,$=302){return G.set("Location",K),new Response(null,{status:$,headers:G})},setCookie(K,$,U={}){let W=`${encodeURIComponent(K)}=${encodeURIComponent($)}`;if(U.maxAge)W+=`; Max-Age=${U.maxAge}`;if(U.expires)W+=`; Expires=${U.expires.toUTCString()}`;if(U.path)W+=`; Path=${U.path}`;if(U.domain)W+=`; Domain=${U.domain}`;if(U.secure)W+="; Secure";if(U.httpOnly)W+="; HttpOnly";if(U.sameSite)W+=`; SameSite=${U.sameSite}`;return G.append("Set-Cookie",W),this},get cookies(){if(!L){let K=this.req.headers.get("cookie");L=K?T(K):{}}return L}}}function T(z){return Object.fromEntries(z.split(";").map((A)=>{let[J,...G]=A.trim().split("=");return[J,decodeURIComponent(G.join("="))]}))}function w(z,A){let J={},G=z.split("/"),[X]=A.split("?"),Y=X.split("/");if(G.length!==Y.length)return null;for(let L=0;L<G.length;L++)if(G[L].startsWith(":"))J[G[L].slice(1)]=Y[L];return J}async function I(z){let A=z.headers.get("Content-Type");if(!A)return{};if(z.headers.get("Content-Length")==="0"||!z.body)return{};try{if(A.startsWith("application/json"))return await z.json();if(A.startsWith("application/x-www-form-urlencoded")){let G=await z.text();return Object.fromEntries(new URLSearchParams(G))}if(A.startsWith("multipart/form-data")){let G=await z.formData(),X={};for(let[Y,L]of G.entries())X[Y]=L;return X}return{error:"Unknown request body type"}}catch(G){return{error:"Invalid request body format"}}}async function B(z,A,J,G){let X=G.trie.search(J.pathname,z.method);z.routePattern=X?.path;let Y=Q(z,A,J);if(G.hasFilterEnabled){let Z=z.routePattern??J.pathname,K=await O(G,Z,Y,A);if(K)return K}if(G.hasMiddleware){let Z=G.globalMiddlewares;for(let $=0;$<Z.length;$++){let U=await Z[$](Y,A);if(U)return U}let K=G.middlewares.get(J.pathname)||[];for(let $=0;$<K.length;$++){let U=await K[$](Y,A);if(U)return U}}if(!X?.handler||X.method!==z.method){let Z=G.trie.search("*",z.method);if(Z){let K=await S(G,J.pathname,Y);if(K)return K;return await Z.handler(Y)}if(G.hooks.routeNotFound){let K=await G.hooks.routeNotFound(Y);if(K)return K}if(!X||!X.handler.length)return j(404,`Route not found for ${J.pathname}`);return j(405,"Method not allowed")}if(G.hooks.preHandler){let Z=await G.hooks.preHandler(Y);if(Z)return Z}let L=X.handler(Y),V=L instanceof Promise?await L:L;if(G.hooks.postHandler)await G.hooks.postHandler(Y);if(G.hooks.onSend){let Z=await G.hooks.onSend(Y,V);if(Z)return Z}return V??j(204,"No response from this handler")}async function O(z,A,J,G){if(!z.filters.has(A))if(z.filterFunction.length)for(let X of z.filterFunction){let Y=await X(J,G);if(Y)return Y}else return J.json({error:!0,message:"Protected route, authentication required",status:401},401)}function j(z,A){return new Response(JSON.stringify({error:!0,message:A,status:z}),{status:z,headers:{"Content-Type":"application/json"}})}async function S(z,A,J){if(!z.UseStaticFiles)throw new Error("Static files directory is not configured.");let G=`${z.UseStaticFiles}${A}`;if(/\.(js|css|html)$/.test(A)){let X=E(G);return J.file(G,200,X)}return null}class D{tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;UseStaticFiles;staticFiles;constructor(){this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new _,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,routeNotFound:null},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.UseStaticFiles=null,this.staticFiles={}}setupFilter(){return this.hasFilterEnabled=!0,{routeMatcher:(...z)=>{return this.FilterRoutes=z,this.setupFilter()},permitAll:()=>{for(let z of this?.FilterRoutes)this.filters.add(z);return this.FilterRoutes=null,this.setupFilter()},authenticate:(z)=>{if(z?.length)for(let A of z)this.filterFunction.push(A)}}}UseStatic(z){this.UseStaticFiles=z}static(z,A){if(!Array.isArray(z)&&!Array.isArray(A))this.staticFiles[z]=A;else for(let J=0;J<z.length;J++)this.staticFiles[z[J]]=A[J];return this}addHooks(z,A){if(typeof z!=="string")throw new Error("hookName must be a string");if(typeof A!=="function")throw new Error("callback must be a instance of function");switch(z){case"onRequest":this.hooks.onRequest=A;break;case"preHandler":this.hooks.preHandler=A;break;case"postHandler":this.hooks.postHandler=A;break;case"onSend":this.hooks.onSend=A;break;case"onError":this.hooks.onError=A;break;case"onClose":this.hooks.onClose=A;break;case"routeNotFound":this.hooks.routeNotFound=A;break;default:throw new Error(`Unknown hook type: ${z}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[z,A]of this.middlewares.entries())if(A.length>0){this.hasMiddleware=!0;break}this.tempRoutes=new Map}listen(z=3000,...A){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");if(!z||typeof z!=="number")throw new Error("port is required and should be a number type");let J="0.0.0.0",G=void 0,X={};for(let L of A)if(typeof L==="string")J=L;else if(typeof L==="function")G=L;else if(typeof L==="object"&&L!==null)X=L;let Y={port:z,hostname:J,fetch:async(L,V)=>{let Z=new URL(L.url);try{if(this.hooks.onRequest)this.hooks.onRequest(L,Z,V);return await B(L,V,Z,this)}catch(K){return this.hooks.onError?this.hooks.onError(K,L,Z,V):new Response(JSON.stringify({message:"Internal Server Error",error:K.message,status:500}),{status:500})}},static:this.staticFiles,development:!0};if(X.sslCert&&X.sslKey)Y.certFile=X.sslCert,Y.keyFile=X.sslKey;if(this.compile(),this.serverInstance=Bun?.serve(Y),G)return G();if(X.sslCert&&X.sslKey)console.log(`HTTPS server is running on https://localhost:${z}`);else console.log(`HTTP server is running on http://localhost:${z}`);return this.serverInstance}close(z){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,z?z():console.log("Server has been stopped");else console.warn("Server is not running.")}route(z,A){if(!z||typeof z!=="string")throw new Error("Path must be a string");let J=Object.fromEntries(A.tempRoutes);return Object.entries(J).forEach(([X,Y])=>{let L=`${z}${X}`;if(!this.middlewares.has(L))this.middlewares.set(L,[]);Y.handlers.slice(0,-1).forEach(($)=>{if(!this.middlewares.get(L)?.includes($))this.middlewares.get(L)?.push($)});let Z=Y.handlers[Y.handlers.length-1],K=Y.method;try{this.trie.insert(L,{handler:Z,method:K})}catch($){console.error(`Error inserting ${L}:`,$)}}),A=null,this}register(z,A){return this.route(z,A)}addRoute(z,A,J){if(typeof A!=="string")throw new Error(`Error in ${J[J.length-1]}: Path must be a string. Received: ${typeof A}`);if(typeof z!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof z}`);this.tempRoutes.set(A,{method:z,handlers:J});let G=J.slice(0,-1),X=J[J.length-1];if(!this.middlewares.has(A))this.middlewares.set(A,[]);G.forEach((Y)=>{if(A==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...G])];else if(!this.middlewares.get(A)?.includes(Y))this.middlewares.get(A)?.push(Y)});try{if(z==="ANY"){let Y=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let L of Y)this.trie.insert(A,{handler:X,method:L})}this.trie.insert(A,{handler:X,method:z})}catch(Y){console.error(`Error inserting ${A}:`,Y)}}use(z,A){if(Array.isArray(z))z.forEach((G)=>{if(typeof G==="function")this.globalMiddlewares.push(G)});if(typeof z==="function"){if(this.globalMiddlewares.push(z),Array.isArray(A))A.forEach((G)=>{this.globalMiddlewares.push(G)});return}return(Array.isArray(z)?z.filter((G)=>typeof G==="string"):[z].filter((G)=>typeof G==="string")).forEach((G)=>{if(!this.middlewares.has(G))this.middlewares.set(G,[]);if(A)(Array.isArray(A)?A:[A]).forEach((Y)=>{this.middlewares.get(G)?.push(Y)})}),this}get(z,...A){return this.addRoute("GET",z,A),this}post(z,...A){return this.addRoute("POST",z,A),this}put(z,...A){return this.addRoute("PUT",z,A),this}patch(z,...A){return this.addRoute("PATCH",z,A),this}delete(z,...A){return this.addRoute("DELETE",z,A),this}any(z,...A){return this.addRoute("ANY",z,A),this}head(z,...A){return this.addRoute("HEAD",z,A),this}options(z,...A){return this.addRoute("OPTIONS",z,A),this}propfind(z,...A){return this.addRoute("PROPFIND",z,A),this}}export{D as default};
@@ -1,10 +0,0 @@
1
- import { middlewareFunc } from "../../types";
2
- export interface CorsOptions {
3
- origin?: string | string[];
4
- methods?: string[];
5
- allowedHeaders?: string[];
6
- exposedHeaders?: string[];
7
- credentials?: boolean;
8
- maxAge?: number;
9
- }
10
- export declare const cors: (config: CorsOptions) => middlewareFunc;
@@ -1 +0,0 @@
1
- var d=["GET","POST","PUT","DELETE","OPTIONS"],A=["Content-Type","Authorization"],g=(s)=>{return async function(e){let o=e.req.headers.get("origin")??"*",r=s.origin,t=s.allowedHeaders??A,a=s.methods??d,i=s.credentials??!1,n=s.exposedHeaders??[],l=s.maxAge;if(e.setHeader("Access-Control-Allow-Methods",a.join(",")),e.setHeader("Access-Control-Allow-Headers",t.join(",")),e.setHeader("Access-Control-Allow-Credentials",i.toString()),n.length>0)e.setHeader("Access-Control-Expose-Headers",n.join(","));if(r==="*"||o==="*")e.setHeader("Access-Control-Allow-Origin","*");else if(Array.isArray(r))if(o&&r.includes(o))e.setHeader("Access-Control-Allow-Origin",o);else if(r.includes("*"))e.setHeader("Access-Control-Allow-Origin","*");else return e.json({message:"CORS not allowed"},403);else if(typeof r==="string")if(o===r)e.setHeader("Access-Control-Allow-Origin",o);else return e.json({message:"CORS not allowed"},403);else return e.json({message:"CORS not allowed"},403);if(e.req.method==="OPTIONS"){if(l)e.setHeader("Access-Control-Max-Age",l.toString());return e.text("",204)}return null}};export{g as cors};
@@ -1,2 +0,0 @@
1
- import { ContextType } from "../../types";
2
- export declare const securityMiddleware: (ctx: ContextType) => void;
@@ -1 +0,0 @@
1
- var t=(e)=>{e.setHeader("Strict-Transport-Security","max-age=31536000; includeSubDomains"),e.setHeader("Content-Security-Policy","default-src 'self'"),e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("X-Frame-Options","DENY")};export{t as securityMiddleware};
package/dist/trie.d.ts DELETED
@@ -1,30 +0,0 @@
1
- import type { handlerFunction, HttpMethod, RouteT } from "./types";
2
- declare class TrieNode {
3
- children: Record<string, TrieNode>;
4
- isEndOfWord: boolean;
5
- handler: handlerFunction[];
6
- isDynamic: boolean;
7
- pattern: string;
8
- path: string;
9
- method: string[];
10
- constructor();
11
- }
12
- export default class Trie {
13
- root: TrieNode;
14
- constructor();
15
- insert(path: string, route: RouteT): void;
16
- search(path: string, method: HttpMethod): {
17
- path: string;
18
- handler: handlerFunction;
19
- isDynamic: boolean;
20
- pattern: string;
21
- method: string;
22
- } | {
23
- path: string;
24
- handler: handlerFunction[];
25
- isDynamic: boolean;
26
- pattern: string;
27
- method: string;
28
- } | null;
29
- }
30
- export {};
package/dist/trie.js DELETED
@@ -1 +0,0 @@
1
- class E{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class G{root;constructor(){this.root=new E}insert(w,v){let j=this.root,A=w.split("/").filter(Boolean);if(w==="/"){j.isEndOfWord=!0,j.handler.push(v.handler),j.path=w,j.method.push(v.method);return}for(let z of A){let B=!1,q=z;if(z.startsWith(":"))B=!0,q=":";if(!j.children[q])j.children[q]=new E;j=j.children[q],j.isDynamic=B,j.pattern=z,j.method.push(v.method),j.handler.push(v.handler),j.path=w}j.isEndOfWord=!0,j.method.push(v.method),j.handler.push(v.handler),j.path=w}search(w,v){let j=this.root,A=w.split("/").filter(Boolean),z=A.length;for(let H of A){let F=H;if(!j.children[F])if(j.children[":"])j=j.children[":"];else return null;else j=j.children[F]}let B=j.path.split("/").filter(Boolean);if(z!==B.length)return null;let q=j.method.indexOf(v);if(q!==-1)return{path:j.path,handler:j.handler[q],isDynamic:j.isDynamic,pattern:j.pattern,method:j.method[q]};return{path:j.path,handler:j.handler,isDynamic:j.isDynamic,pattern:j.pattern,method:j.method[q]}}}export{G as default};
package/dist/types.d.ts DELETED
@@ -1,123 +0,0 @@
1
- import { Server } from "bun";
2
- export type listenCalllBackType = () => void;
3
- export type handlerFunction = (ctx: ContextType, server?: Server) => Response | Promise<Response | null | void>;
4
- export type middlewareFunc = (ctx: ContextType, server?: Server | undefined) => null | void | Response | Promise<Response | void | null>;
5
- export type HookFunction = (ctx: ContextType, result?: Response | null | void, server?: Server) => Response | Promise<Response | null | void> | void;
6
- export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "HEAD" | "ANY" | "PROPFIND";
7
- export type HookType = 'routeNotFound' | 'onRequest' | 'preHandler' | 'postHandler' | 'onSend' | 'onError' | 'onClose';
8
- export interface onError {
9
- (error: Error, req: Request, url: URL, server: Server): void | null | Response | Promise<Response | null | void>;
10
- }
11
- export interface onRequest {
12
- (req: Request, url: URL, server: Server): void | null | Response | Promise<Response | null | void>;
13
- }
14
- export interface Hooks {
15
- onRequest: onRequest | null;
16
- preHandler: HookFunction | null;
17
- postHandler: HookFunction | null;
18
- onSend: HookFunction | null;
19
- onError: onError | null;
20
- onClose: HookFunction | null;
21
- routeNotFound: HookFunction | null;
22
- }
23
- export interface ContextType {
24
- req: Request;
25
- server: Server;
26
- url: URL;
27
- setHeader: (key: string, value: any) => this;
28
- json: (data: Object, status?: number) => Response;
29
- text: (data: string, status?: number) => Response;
30
- send: (data: string, status?: number) => Response;
31
- file: (filePath: string, status?: number, mimeType?: string) => Response;
32
- redirect: (path: string, status?: number) => Response;
33
- setCookie: (name: string, value: string, options?: CookieOptions) => this;
34
- ip: string | null;
35
- query: Record<string, string>;
36
- params: Record<string, string>;
37
- set<T>(key: string, value: T): this;
38
- get<T>(key: string): T | undefined;
39
- body: Promise<any>;
40
- cookies: any;
41
- removeHeader: (key: string) => this;
42
- }
43
- export interface CookieOptions {
44
- maxAge?: number;
45
- expires?: Date;
46
- path?: string;
47
- domain?: string;
48
- secure?: boolean;
49
- httpOnly?: boolean;
50
- sameSite?: "Strict" | "Lax" | "None";
51
- }
52
- export interface RouteNodeType {
53
- path: string;
54
- handler: Function[];
55
- method: string[];
56
- }
57
- export interface RouteHandlerT {
58
- method: string;
59
- handler: (ctx: ContextType) => Promise<Response | null | void>;
60
- isDynamic?: boolean;
61
- path?: string;
62
- }
63
- export interface DieselT {
64
- hasOnReqHook: boolean;
65
- hasMiddleware: boolean;
66
- hasPreHandlerHook: boolean;
67
- hasPostHandlerHook: boolean;
68
- hasOnSendHook: boolean;
69
- hooks: {
70
- onRequest: ((req: Request, url: URL, serer: Server) => void) | null;
71
- preHandler: ((ctx: ContextType, serer?: Server) => Response | Promise<Response | void | null>) | null;
72
- postHandler: ((ctx: ContextType, serer?: Server) => Response | Promise<Response | void | null>) | null;
73
- onSend: ((ctx?: ContextType, result?: Response | null | void, serer?: Server) => Response | Promise<Response | void | null>) | null;
74
- onError: ((error: Error, req: Request, url: URL, server?: Server) => void | Response | Promise<Response | null | void>) | null;
75
- routeNotFound: ((ctx: ContextType) => Response | Promise<Response | null | void>) | null;
76
- };
77
- filters: Set<string>;
78
- hasFilterEnabled: boolean;
79
- filterFunction: Array<(ctx: ContextType, serer?: Server) => void | Response | Promise<Response | void | null>>;
80
- corsConfig: corsT | null;
81
- globalMiddlewares: Array<(ctx: ContextType, serer?: Server) => void | Promise<Response | null | void>>;
82
- middlewares: Map<string, Array<(ctx: ContextType, serer?: Server) => void | Promise<Response | null | void>>>;
83
- trie: {
84
- search: (pathname: string, method: string) => RouteHandlerT | undefined;
85
- };
86
- UseStaticFiles: string | null;
87
- }
88
- export interface RouteCache {
89
- [key: string]: RouteHandlerT | undefined;
90
- }
91
- declare global {
92
- interface Request {
93
- routePattern?: string;
94
- [key: string]: any;
95
- }
96
- }
97
- export interface ParseBodyResult {
98
- error?: string;
99
- data?: any;
100
- }
101
- export interface RouteT {
102
- method: string;
103
- handler: handlerFunction;
104
- }
105
- export type corsT = {
106
- origin?: string | string[] | null;
107
- methods?: string | string[] | null;
108
- allowedHeaders?: string | string[] | null;
109
- exposedHeaders?: string | string[] | null;
110
- credentials?: boolean | null;
111
- maxAge?: number;
112
- preflightContinue?: boolean;
113
- optionsSuccessStatus?: number;
114
- } | null;
115
- export interface FilterMethods {
116
- routeMatcher: (...routes: string[]) => FilterMethods;
117
- permitAll: () => FilterMethods;
118
- authenticate: (fnc?: middlewareFunc[]) => Response | Promise<Response | null> | void;
119
- }
120
- export type listenArgsT = string | (() => void) | {
121
- sslCert?: string;
122
- sslKey?: string;
123
- };
package/dist/utils.d.ts DELETED
@@ -1,8 +0,0 @@
1
- import { ContextType } from "./types";
2
- export default function rateLimit(props: {
3
- time?: number;
4
- max?: number;
5
- message?: string;
6
- }): (ctx: ContextType) => void | Response;
7
- export declare function getMimeType(filePath: string): string;
8
- export declare const binaryS: (arr: string[], target: string, start: number, end: number) => boolean;
package/dist/utils.js DELETED
@@ -1 +0,0 @@
1
- function J(j){let{time:z=60000,max:C=100,message:D="Rate limit exceeded. Please try again later."}=j,v=new Map;return(G)=>{let E=new Date,F=G.ip;if(!v.has(F))v.set(F,{count:0,startTime:E});let A=v.get(F);if(A)if(E-A.startTime>z)A.count=1,A.startTime=E;else A.count++;if(A&&A.count>C)return G.json({error:D},429)}}function K(j){switch(j.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var H=(j,z,C,D)=>{if(C>D)return!1;let v=C+(D-C)/2;if(j[v]==z)return!0;if(j[v]>z)return H(j,z,C,v-1);return H(j,z,v+1,D)};export{K as getMimeType,J as default,H as binaryS};