diesel-core 2.0.1 → 2.0.2

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.
@@ -1,118 +1 @@
1
- var J={reset:"\x1B[0m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[34m",PUT:"\x1B[35m",DELETE:"\x1B[31m",PATCH:"\x1B[36m"}},x=($,F,z)=>{let X=J[$]||J.reset,Z=z?.method?J.method[z.method]||J.reset:J.reset,Q=z?.status?z.status>=500?J.error:z.status>=400?J.warn:J.info:J.reset;console.log(`
2
- ${X}[${$.toUpperCase()}]${J.reset} ${F} - ${Z}${z?.method||""}${J.reset}`);let V={timestamp:new Date().toISOString(),...z,status:z?.status?`${Q}${z.status}${J.reset}`:void 0,method:z?.method?`${Z>X}${z.method}${J.reset}`:void 0};console.log(JSON.stringify(V,null,2)+`
3
- `)},l=($)=>{let{app:F,logger:z,logLevel:X="info",onRequest:Z,onSend:Q,onError:V}=$||{};F?.addHooks("onRequest",(D)=>{D.req.startTime=Date.now(),z?.()??x(X,"Incoming Request",{method:D.req.method,url:D.path,headers:{"user-agent":D.req.headers.get("user-agent"),"content-type":D.req.headers.get("content-type")}}),Z?.(D)}),F?.addHooks("onSend",async(D,G)=>{let W=`${Date.now()-D.req.startTime}ms`;z?.()??x(X,"Response Sent",{method:D.req.method,url:D.url.toString(),status:G.status,duration:W,reqId:D.get?.("requestId"),headers:{"content-type":G.headers.get("content-type")}});let U=await Q?.(D);if(U instanceof Response)return U}),F?.addHooks("onError",async(D,G,W)=>{z?.()??x("error","Unhandled Error",{method:W.method,url:G,status:500,error:D.message});let U=await V?.(D,G,W);if(U instanceof Response)return U})},y=($,F,z,X=0,Z,Q)=>{let V=J.method[F]||J.reset,D=X>=500?J.error:X>=400?J.warn:J.info,G=Q?`[${Q}] `:"",W=$==="<--"?`${$} ${V}${F}${J.reset} ${z} ${G}`:`${$} ${V}${F}${J.reset} ${z} ${D}${X}${J.reset} ${Z??""} ${G}`;console.log(W)},U$=($)=>{let F=Date.now()-$;return F<1000?`${F}ms`:`${Math.round(F/1000)}s`},n=($)=>{let{app:F,log:z,onRequest:X,onSend:Z,onError:Q}=$;F.addHooks("onRequest",(V)=>{let{req:D,path:G}=V;D.startTime=Date.now(),z?.()??y("<--",D.method,G),X?.(D,G)}),F.addHooks("onSend",async(V,D)=>{let{method:G,url:W}=V.req,U=new URL(W).pathname,M=V.get?.("requestId");z?.()??y("-->",G,U,D?.status,U$(V.req.startTime),M);let w=await Z?.(V);return w instanceof Response?w:D}),F.addHooks("onError",async(V,D,G)=>{let W=G.path;z?.()??y(V.message,G.method,W,500);let U=await Q?.(V,W,G);if(U instanceof Response)return U})};function s($,F){if(!$)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(z)=>{try{let X=z.cookies?.accessToken??z.req?.headers?.get("Authorization");if(!X)return z.json({message:"Unauthorized",error:"No token provided"},401);if(X.startsWith("Bearer "))X=X.slice(7);let Z=$?.verify(X,F);if(!Z)return z.json({message:"Unauthorized",error:"Token could not be decoded"},401);z.set("user",Z)}catch(X){let Z="Invalid token";if(X.name==="TokenExpiredError")Z="Token expired";else if(X.name==="JsonWebTokenError")Z="Malformed or tampered token";return z.json({message:"Unauthorized",error:Z},401)}}}function r($,F,z){if(!$)throw Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!F)throw Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(X)=>{try{let Z=X.cookies?.accessToken??X.req?.headers?.get("Authorization");if(!Z)return X.json({message:"Unauthorized",error:"No token provided"},401);if(Z.startsWith("Bearer "))Z=Z.slice(7);let Q=$?.verify(Z,z);if(!Q)return X.json({message:"Unauthorized",error:"Token could not be decoded"},401);let V=await F.findById(Q._id).select("-password -refreshToken");if(!V)return X.json({message:"Unauthorized: User not found"},404);X.set("user",V);return}catch(Z){let Q="Invalid token";if(Z.name==="TokenExpiredError")Q="Token expired";else if(Z.name==="JsonWebTokenError")Q="Malformed or tampered token";return X.json({message:"Unauthorized",error:Q},401)}}}function A($){switch($.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"}}class _{req;server;path;param;env;executionContext;headers;parsedQuery=null;parsedCookies=null;parsedBody=null;contextData=S;urlObject=null;constructor($,F,z,X,Z,Q){this.req=$,this.server=F,this.path=z,this.param=X,this.env=Z,this.executionContext=Q,this.headers=null}setHeader($,F){if(!this.headers)this.headers=new Headers;return this.headers.set($,F),this}removeHeader($){if(this.headers)this.headers.delete($);return this}set($,F){if(this.contextData===S)this.contextData={};return this.contextData[$]=F,this}get($){if(this.contextData===S)return;return this.contextData[$]}get ip(){if(this.server)return this.server.requestIP(this.req)?.address??null;return this.req.headers.get("CF-Connecting-IP")||null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):S;return this.parsedQuery}get params(){return this.param?this.param:S}get body(){if(this.req.method==="GET")return Promise.resolve(S);if(!this.parsedBody)this.parsedBody=(async()=>{try{let $=await J$(this.req);if($.error)throw Error($.error);return Object.keys($).length===0?null:$}catch($){throw Error("Invalid request body format")}})();return this.parsedBody}text($,F=200,z){if(!this.headers){if(!z)return new Response($,{status:F,headers:{"Content-Type":"text/plain; charset=utf-8"}});let X={"Content-Type":"text/plain; charset=utf-8"};return E(z,X),new Response($,{status:F,headers:X})}if(z)P(this.headers,z);if(!this.headers?.has("Content-Type"))this.headers?.set("Content-Type","text/plain; charset=utf-8");return new Response($,{status:F,headers:this.headers})}send($,F=200,z){let X,Z;if($ instanceof Uint8Array||$ instanceof ArrayBuffer)X="application/octet-stream",Z=$;else if($!==null&&typeof $==="object")X="application/json; charset=utf-8",Z=JSON.stringify($);else if(typeof $==="string")X="text/plain; charset=utf-8",Z=$;else X="text/plain; charset=utf-8",Z=String($);if(!this.headers){if(!z)return new Response(Z,{status:F,headers:{"Content-Type":X}});let Q={"Content-Type":X};return E(z,Q),new Response(Z,{status:F,headers:Q})}if(z)P(this.headers,z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",X);return new Response(Z,{status:F,headers:this.headers})}json($,F=200,z){if(!this.headers){if(!z)return Response.json($,{status:F,headers:{"Content-Type":"application/json; charset=utf-8"}});let X={"Content-Type":"application/json; charset=utf-8"};return E(z,X),Response.json($,{status:F,headers:X})}if(z)P(this.headers,z);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify($),{status:F,headers:this.headers})}file($,F,z=200,X){let Z=Bun.file($);if(!this.headers){if(!X)return new Response(Z,{status:z,headers:{"Content-Type":F??A($)}});let Q={"Content-Type":F??A($)};return E(X,Q),new Response(Z,{status:z,headers:Q})}if(X)P(this.headers,X);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",F??A($));return new Response(Z,{status:z,headers:this.headers})}async ejs($,F={},z=200){console.log("this method is diabled now for some time")}redirect($,F=302){if(!this.headers)this.headers=new Headers;return this.headers.set("Location",$),new Response(null,{status:F,headers:this.headers})}setCookie($,F,z={}){if(!this.headers)this.headers=new Headers;let X=`${encodeURIComponent($)}=${encodeURIComponent(F)}`;if(z.maxAge)X+=`; Max-Age=${z.maxAge}`;if(z.expires)X+=`; Expires=${z.expires.toUTCString()}`;if(z.path)X+=`; Path=${z.path}`;if(z.domain)X+=`; Domain=${z.domain}`;if(z.secure)X+="; Secure";if(z.httpOnly)X+="; HttpOnly";if(z.sameSite)X+=`; SameSite=${z.sameSite}`;return this.headers.append("Set-Cookie",X),this}get cookies(){if(!this.parsedCookies){let $=this.req.headers.get("cookie");this.parsedCookies=$?B$($):S}return this.parsedCookies}stream($){let F=new Headers(this.headers??new Headers),z=new ReadableStream({async start(X){await $(X),X.close()}});return new Response(z,{headers:F})}yieldStream($){return new Response}}function P($,F){for(let z in F)$.set(z,F[z])}function E($,F){for(let z in $)F[z]=$[z]}function B$($){return Object.fromEntries($.split(";").map((F)=>{let[z,...X]=F.trim().split("=");return[z,decodeURIComponent(X.join("="))]}))}async function J$($){let F=$.headers.get("Content-Type")||"";if(!F)return{};if($.headers.get("Content-Length")==="0"||!$.body)return{};if(F.startsWith("application/json"))return await $.json();if(F.startsWith("application/x-www-form-urlencoded")){let X=await $.text();return Object.fromEntries(new URLSearchParams(X))}if(F.startsWith("multipart/form-data")){let X=await $.formData(),Z={};for(let[Q,V]of X.entries())Z[Q]=V;return Z}return{error:"Unknown request body type"}}var N=($)=>$!==null&&typeof $==="object"&&typeof $.then==="function",c=($)=>$!==null&&typeof $==="object"&&typeof $.status==="number"&&typeof $.headers==="object";async function f($,F,z){if(!F?.length)return;for(let X=0;X<F.length;X++){let Z=F[X](...z),Q=Z instanceof Promise?await Z:Z;if(Q&&$!=="onRequest")return Q}}async function a($,F,z){for(let X of $){let Z=await X(F,z);if(Z)return Z}}async function t($,F,z){let X=await S$($,F,z),Z=N(X)?await X:X;if(Z)return Z}async function S$($,F,z){if(F.endsWith("/"))F=F.slice(0,-1);if(!$.filters.has(F))if($.filterFunction.length)for(let X of $.filterFunction){let Z=await X(z);if(Z)return Z}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function b($,F,z){if($.staticPath){let D=!0;if($.staticRequestPath)D=z.startsWith($.staticRequestPath);if(D){let G=await Y$($,z,F);if(G)return G}}let Q=($.router.find(F.req.method,"*")?.handler).slice(-1);if(Q.length>0){let D=await Q[0](F);if(c(D))return D}let V=await Promise.resolve($.routeNotFoundFunc(F));return c(V)?V:u(404,`404 Route not found for ${z}`)}function u($,F){return new Response(JSON.stringify({error:F}),{status:$,headers:{"Content-Type":"application/json"}})}async function Y$($,F,z){if(!$.staticPath)return null;let X=`${$.staticPath}${F}`;if(await Bun.file(X).exists()){let Q=A(X);return z.file(X,Q,200)}return null}var m=($)=>$.constructor.name==="AsyncFunction",e=($,F,z,...X)=>{if(F.length>5)$.push(`
4
- for (let i = 0; i < diesel.hooks.${z}.length; i++) {
5
- const result = diesel.hooks.${z}[i](${X});
6
- const finalResult = result instanceof Promise ? await result : result;
7
- if (finalResult && '${z}' !== 'onRequest') return finalResult
8
- }
9
- `);else F?.forEach((Z,Q)=>{if(m(Z))$.push(`
10
- const ${z}${Q}Result = await diesel.hooks.${z}[${Q}](${X})
11
- if (${z}${Q}Result && '${z}' !== 'onRequest') return ${z}${Q}Result
12
- `);else $.push(`
13
- const ${z}${Q}Result = diesel.hooks.${z}[${Q}](${X})
14
- if (${z}${Q}Result && '${z}' !== 'onRequest') return ${z}${Q}Result
15
- `)})},K$=($)=>{$.push(`
16
- let pathname;
17
- const start = req.url.indexOf('/', req.url.indexOf(':') + 4);
18
- let i = start;
19
- for (; i < req.url.length; i++) {
20
- const charCode = req.url.charCodeAt(i);
21
- if (charCode === 37) { // percent-encoded
22
- const queryIndex = req.url.indexOf('?', i);
23
- const path = req.url.slice(start, queryIndex === -1 ? undefined : queryIndex);
24
- pathname = tryDecodeURI(path.includes('%25') ? path.replace(/%25/g, '%2525') : path);
25
- break;
26
- } else if (charCode === 63) { // ?
27
- break;
28
- }
29
- }
30
- if (!pathname) {
31
- pathname = req.url.slice(start, i);
32
- }
33
- `)};var o=($)=>{let F=[],z=$?.hasPreHandlerHook?$.hooks.preHandler:[],X=$?.hasOnSendHook?$.hooks.onSend:[];if(K$(F),F.push(`
34
- const matchedRouteHandler = diesel.router.find(req.method, pathname);
35
- `),F.push(`
36
- const ctx = new Context(
37
- req,
38
- server,
39
- pathname,
40
- matchedRouteHandler?.params,
41
- env,
42
- executionContext
43
- )
44
- `),$.hasFilterEnabled)F.push(`
45
- const filterResponse = await runFilter(diesel, pathname, ctx);
46
- if (filterResponse) return filterResponse;
47
- `);if($.hasPreHandlerHook)e(F,z,"preHandler","ctx");if(F.push(`
48
- let finalResult
49
- const handlers = matchedRouteHandler?.handler;
50
-
51
- if (handlers.length === 1) {
52
- const result = handlers[0](ctx);
53
- finalResult = isPromise(result) ? await result : result;
54
- }
55
- else {
56
- for (let i = 0; i < handlers.length; i++) {
57
- const result = handlers[i](ctx);
58
- finalResult = isPromise(result) ? await result : result;
59
- if (finalResult) break;
60
- }
61
- }
62
- `),$.hasOnSendHook)e(F,X,"onSend","ctx","finalResult");F.push(`
63
- if (finalResult) return finalResult;
64
- `),F.push(`
65
- return await handleRouteNotFound(diesel, ctx, pathname);
66
- `);let Z=`
67
- return async function pipeline(req, diesel, server, env, executionContext) {
68
- ${F.join(`
69
- `)}
70
- }
71
- `;return Function("runFilter","handleRouteNotFound","generateErrorResponse","Context","isPromise",Z)(t,b,u,_,N)},$$=($,F,z,...X)=>{let Z=[],Q;if(typeof X[0]==="string"||typeof X[0]==="object")Q=X[0];let V=X,D=$?.hasMiddleware?$.globalMiddlewares:[],G=$?.hasMiddleware?$.middlewares.get(z)||[]:[],W=[...D,...G],U=$?.hasOnReqHook?$.hooks.onRequest:[],M=$.filters.has(z),w=$.filterFunction;if(U&&U?.length>0)Z.push(`
72
- const onRequestResult = await runHooks(
73
- "onRequest",
74
- onRequestHooks,
75
- [req, "${z}", server]
76
- );
77
- if (onRequestResult) return onRequestResult;
78
- `);if(W.length)Z.push(`
79
- const globalMiddlewareResponse = await executeBunMiddlewares(
80
- allMiddlewares,
81
- req,
82
- server
83
- );
84
- if (globalMiddlewareResponse) return globalMiddlewareResponse;
85
- `);if($.hasFilterEnabled){if(!M)Z.push(`if (${w.length}) {
86
- for (const filterFunction of filterFunctions) {
87
- const filterResult = await filterFunction(req, server);
88
- if (filterResult) return filterResult;
89
- }
90
- } else {
91
- return Response.json({ error: "Protected route, authentication required" }, { status: 401 });
92
- }`)}if(Z.push(`
93
- if ("${F}" !== req.method)
94
- return new Response("Method Not Allowed", { status: 405 });
95
- `),typeof Q<"u")if(typeof Q==="string")Z.push(`
96
- return new Response(${JSON.stringify(Q)});
97
- `);else{let L=JSON.stringify(Q);Z.push(`
98
- return new Response(${JSON.stringify(L)}, {
99
- headers: { "content-type": "application/json; charset=utf-8" }
100
- });
101
- `)}else if(V.length===1){let L=V[0];if(m(L))Z.push(`
102
- const response = await handlers[0](req, server);
103
- if (response instanceof Response) return response;
104
- `);else Z.push(`
105
- const response = handlers[0](req, server);
106
- if (response instanceof Response) return response;
107
- `)}else V.forEach((L,Y)=>{if(m(L))Z.push(`
108
- const response${Y} = await handlers[${Y}](req, server);
109
- if (response${Y} instanceof Response) return response${Y};
110
- `);else Z.push(`
111
- const response${Y} = handlers[${Y}](req, server);
112
- if (response${Y} instanceof Response) return response${Y};
113
- `)});let q=`
114
- return async function(req, server) {
115
- ${Z.join(`
116
- `)}
117
- }
118
- `;return Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",q)(a,V,f,w,U,W)};var w$=($,F)=>{try{return F($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(z)=>{try{return F(z)}catch{return z}})}},L$=($)=>w$($,decodeURI),g=($)=>{let F=$.indexOf("/",$.indexOf(":")+4),z=F;for(;z<$.length;z++){let X=$.charCodeAt(z);if(X===37){let Z=$.indexOf("?",z),Q=$.slice(F,Z===-1?void 0:Z);return L$(Q.includes("%25")?Q.replace(/%25/g,"%2525"):Q)}else if(X===63)break}return $.slice(F,z)};var d=Symbol.for,C=Symbol("kCapture"),Z$=d("events.errorMonitor"),N$=Symbol("events.maxEventTargetListeners"),f$=Symbol("events.maxEventTargetListenersWarned"),F$=d("nodejs.rejection"),C$=d("nodejs.rejection"),z$=Array.prototype.slice,R=10,K=function($){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners??=void 0,this[C]=$?.captureRejections?Boolean($?.captureRejections):B[C])this.emit=O$},B=K.prototype={};B._events=void 0;B._eventsCount=0;B._maxListeners=void 0;B.setMaxListeners=function($){return i($,"setMaxListeners",0),this._maxListeners=$,this};B.constructor=K;B.getMaxListeners=function(){return this?._maxListeners??R};function Q$($,F){var{_events:z}=$;if(F[0]??=Error("Unhandled error."),!z)throw F[0];var X=z[Z$];if(X)for(var Z of z$.call(X))Z.apply($,F);var Q=z.error;if(!Q)throw F[0];for(var Z of z$.call(Q))Z.apply($,F);return!0}function R$($,F,z,X){F.then(void 0,function(Z){queueMicrotask(()=>q$($,Z,z,X))})}function q$($,F,z,X){if(typeof $[F$]==="function")$[F$](F,z,...X);else try{$[C]=!1,$.emit("error",F)}finally{$[C]=!0}}var A$=function($,...F){if($==="error")return Q$(this,F);var{_events:z}=this;if(z===void 0)return!1;var X=z[$];if(X===void 0)return!1;let Z=X.length>1?X.slice():X;for(let Q=0,{length:V}=Z;Q<V;Q++){let D=Z[Q];switch(F.length){case 0:D.call(this);break;case 1:D.call(this,F[0]);break;case 2:D.call(this,F[0],F[1]);break;case 3:D.call(this,F[0],F[1],F[2]);break;default:D.apply(this,F);break}}return!0},O$=function($,...F){if($==="error")return Q$(this,F);var{_events:z}=this;if(z===void 0)return!1;var X=z[$];if(X===void 0)return!1;let Z=X.length>1?X.slice():X;for(let Q=0,{length:V}=Z;Q<V;Q++){let D=Z[Q],G;switch(F.length){case 0:G=D.call(this);break;case 1:G=D.call(this,F[0]);break;case 2:G=D.call(this,F[0],F[1]);break;case 3:G=D.call(this,F[0],F[1],F[2]);break;default:G=D.apply(this,F);break}if(G!==void 0&&typeof G?.then==="function"&&G.then===Promise.prototype.then)R$(this,G,$,F)}return!0};B.emit=A$;B.addListener=function($,F){j(F);var z=this._events;if(!z)z=this._events={__proto__:null},this._eventsCount=0;else if(z.newListener)this.emit("newListener",$,F.listener??F);var X=z[$];if(!X)z[$]=[F],this._eventsCount++;else{X.push(F);var Z=this._maxListeners??R;if(Z>0&&X.length>Z&&!X.warned)V$(this,$,X)}return this};B.on=B.addListener;B.prependListener=function($,F){j(F);var z=this._events;if(!z)z=this._events={__proto__:null},this._eventsCount=0;else if(z.newListener)this.emit("newListener",$,F.listener??F);var X=z[$];if(!X)z[$]=[F],this._eventsCount++;else{X.unshift(F);var Z=this._maxListeners??R;if(Z>0&&X.length>Z&&!X.warned)V$(this,$,X)}return this};function V$($,F,z){z.warned=!0;let X=Error(`Possible EventEmitter memory leak detected. ${z.length} ${String(F)} listeners added to [${$.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);X.name="MaxListenersExceededWarning",X.emitter=$,X.type=F,X.count=z.length,console.warn(X)}function D$($,F,...z){this.removeListener($,F),F.apply(this,z)}B.once=function($,F){j(F);let z=D$.bind(this,$,F);return z.listener=F,this.addListener($,z),this};B.prependOnceListener=function($,F){j(F);let z=D$.bind(this,$,F);return z.listener=F,this.prependListener($,z),this};B.removeListener=function($,F){j(F);var{_events:z}=this;if(!z)return this;var X=z[$];if(!X)return this;var Z=X.length;let Q=-1;for(let V=Z-1;V>=0;V--)if(X[V]===F||X[V].listener===F){Q=V;break}if(Q<0)return this;if(Q===0)X.shift();else X.splice(Q,1);if(X.length===0)delete z[$],this._eventsCount--;return this};B.off=B.removeListener;B.removeAllListeners=function($){var{_events:F}=this;if($&&F){if(F[$])delete F[$],this._eventsCount--}else this._events={__proto__:null};return this};B.listeners=function($){var{_events:F}=this;if(!F)return[];var z=F[$];if(!z)return[];return z.map((X)=>X.listener??X)};B.rawListeners=function($){var{_events:F}=this;if(!F)return[];var z=F[$];if(!z)return[];return z.slice()};B.listenerCount=function($){var{_events:F}=this;if(!F)return 0;return F[$]?.length??0};B.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};B[C]=!1;function I$($,F,z){var X=z?.signal;if(G$(X,"options.signal"),X?.aborted)throw new h(void 0,{cause:X?.reason});let{resolve:Z,reject:Q,promise:V}=$newPromiseCapability(Promise),D=(U)=>{if($.removeListener(F,G),X!=null)k(X,"abort",W);Q(U)},G=(...U)=>{if(typeof $.removeListener==="function")$.removeListener("error",D);if(X!=null)k(X,"abort",W);Z(U)};if(X$($,F,G,{once:!0}),F!=="error"&&typeof $.once==="function")$.once("error",D);function W(){k($,F,G),k($,"error",D),Q(new h(void 0,{cause:X?.reason}))}if(X!=null)X$(X,"abort",W,{once:!0});return V}function M$($,F){return $.listeners(F)}function _$($,...F){i($,"setMaxListeners",0);var z;if(F&&(z=F.length))for(let X=0;X<z;X++)F[X].setMaxListeners($);else R=$}function j$($,F){return $.listenerCount(F)}function k($,F,z,X){if(typeof $.removeListener==="function")$.removeListener(F,z);else $.removeEventListener(F,z,X)}function X$($,F,z,X){if(typeof $.on==="function")if(X.once)$.once(F,z);else $.on(F,z);else $.addEventListener(F,z,X)}class h extends Error{constructor($="The operation was aborted",F=void 0){if(F!==void 0&&typeof F!=="object")throw O("options","Object",F);super($,F);this.code="ABORT_ERR",this.name="AbortError"}}function O($,F,z){let X=TypeError(`The "${$}" argument must be of type ${F}. Received ${z}`);return X.code="ERR_INVALID_ARG_TYPE",X}function T$($,F,z){let X=RangeError(`The "${$}" argument is out of range. It must be ${F}. Received ${z}`);return X.code="ERR_OUT_OF_RANGE",X}function G$($,F){if($!==void 0&&($===null||typeof $!=="object"||!("aborted"in $)))throw O(F,"AbortSignal",$)}function i($,F,z,X){if(typeof $!=="number")throw O(F,"number",$);if(z!=null&&$<z||X!=null&&$>X||(z!=null||X!=null)&&Number.isNaN($))throw T$(F,`${z!=null?`>= ${z}`:""}${z!=null&&X!=null?" && ":""}${X!=null?`<= ${X}`:""}`,$)}function j($){if(typeof $!=="function")throw TypeError("The listener must be a function")}function H$($,F){if(typeof $!=="boolean")throw O(F,"boolean",$)}function P$($){return $?._maxListeners??R}function E$($,F){if($===void 0)throw O("signal","AbortSignal",$);if(G$($,"signal"),typeof F!=="function")throw O("listener","function",F);let z;if($.aborted)queueMicrotask(()=>F());else $.addEventListener("abort",F,{__proto__:null,once:!0}),z=()=>{$.removeEventListener("abort",F)};return{__proto__:null,[Symbol.dispose](){z?.()}}}Object.defineProperties(K,{captureRejections:{get(){return B[C]},set($){H$($,"EventEmitter.captureRejections"),B[C]=$},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return R},set:($)=>{i($,"defaultMaxListeners",0),R=$}},kMaxEventTargetListeners:{value:N$,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:f$,enumerable:!1,configurable:!1,writable:!1}});Object.assign(K,{once:I$,getEventListeners:M$,getMaxListeners:P$,setMaxListeners:_$,EventEmitter:K,usingDomains:!1,captureRejectionSymbol:C$,errorMonitor:Z$,addAbortListener:E$,init:K,listenerCount:j$});class p{static create($){switch($){case"t2":return new T;case"trie":return new T;default:return new T}}}var W$=["GET","POST","PUT","PATCH","DELETE","ANY","ALL","HEAD","OPTIONS","PROPFIND"];var S=Object.freeze({});class I{static instance;routes;tempRoutes;tempMiddlewares=new Map;router;hasOnReqHook;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;compileConfig;#$=!1;emitter;errorFormat;platform="bun";staticPath;staticRequestPath=void 0;get;post;put;patch;delete;any;head;options;propfind;all;constructor($={}){W$.forEach((q)=>{this[q.toLocaleLowerCase()]=(H,...L)=>{return this.addRoute(q,H,L),this}});let{router:F="t2",routerInstance:z,errorFormat:X="json",platform:Z="bun",enableFileRouting:Q=!1,prefixApiUrl:V="",baseApiUrl:D="",jwtSecret:G,idleTimeOut:W=10,pipelineArchitecture:U=!1,logger:M,onError:w}=$;if(z)this.router=z;else this.router=p.create(F);if(this.errorFormat=X,this.platform=Z,!I.instance)I.instance=this;if(U)this.#$=!0;if(this.errorFormat=X,this.emitter=new K,this.prefixApiUrl=V??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=W??10,this.enableFileRouter=Q??!1,this.baseApiUrl=D||"",this.user_jwt_secret=G||process.env.DIESEL_JWT_SECRET||"default_diesel_secret_for_jwt",this.tempRoutes=new Map,this.corsConfig=null,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},w)this.addHooks("onError",(q,H)=>{console.log("Got an exception:",q),console.log("Request Path:",H)});if(M)this.useLogger({app:this});this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={},this.routeNotFoundFunc=()=>{},this.compileConfig=null}static router($){if(!this.instance)this.instance=new I;return new Proxy(this.instance,{get(F,z,X){return(Z,Q)=>{let V=Q,D="";if(typeof Z==="string")D=Z;else if(typeof Z==="function")V=Z;else if(typeof Z!=="string")D="";let G=$+D;return F[z](G,V)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...$)=>{return this.FilterRoutes=$,this.setupFilter()},permitAll:()=>{for(let $ of this?.FilterRoutes){if($.endsWith("/"))$=$.slice(0,-1);this.filters.add($)}return this.setupFilter()},authenticate:($)=>{if($?.length){let F=async(z,X)=>{let Z=z.path;for(let Q of this.filters)if(Z.startsWith(Q))return;for(let Q of $){let V=await Q(z,X);if(V)return V}};this.router.addMiddleware("/",[F])}},authenticateJwt:($)=>{let F=async(z)=>{let X=z.path;for(let Q of this.filters)if(X.startsWith(Q))return;let Z=s($,this.user_jwt_secret)(z);if(Z)return Z};this.router.addMiddleware("/",F)},authenticateJwtDB:($,F)=>{let z=async(X)=>{let Z=X.path;for(let V of this.filters)if(Z.startsWith(V))return;let Q=r($,F,this.user_jwt_secret)(X);if(Q)return Q};this.router.addMiddleware("/",z)}}}redirect($,F,z){return this.any($,(X)=>{let Z=X.params,Q=F;if(Z)for(let D in Z)Q=Q.replace(`:${D}`,Z[D]);let V=X.url.search;if(V)Q+=V;return X.redirect(Q,z)}),this}static($,F){return this.staticPath=$,this.staticRequestPath=F,this}staticHtml($){return this.staticFiles={...this.staticFiles,...$},this}addHooks($,F){if(typeof $!=="string")throw Error("hookName must be a string");if(typeof F!=="function")throw Error("callback must be a instance of function");switch($){case"onRequest":this.hooks.onRequest?.push(F),this.hasOnReqHook=!0;break;case"preHandler":this.hooks.preHandler?.push(F),this.hasPreHandlerHook=!0;break;case"postHandler":this.hooks.postHandler?.push(F),this.hasPostHandlerHook=!0;break;case"onSend":this.hooks.onSend?.push(F),this.hasOnSendHook=!0;break;case"onError":this.hooks.onError?.push(F),this.hasOnError=!0;break;case"onClose":this.hooks.onClose?.push(F);break;default:throw Error(`Unknown hook type: ${$}`)}return this}useLogger($){return n($),this}useAdvancedLogger($){return l($),this}BunRoute($,F,...z){if(!F||typeof F!=="string")throw Error("give a path in string format");let X=$$(this,$.toUpperCase(),F,...z);return this.routes[F]=X,this}listen($,...F){let z="0.0.0.0",X=void 0,Z={};for(let V of F)if(typeof V==="string")z=V;else if(typeof V==="function")X=V;else if(typeof V==="object"&&V!==null)Z=V;let Q={port:$,hostname:z,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)Q.routes=this.routes;if(Z.cert&&Z.key)Q.certFile=Z.cert,Q.keyFile=Z.key;return this.serverInstance=Bun?.serve(Q),X&&X(),this.serverInstance}close($){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,$?$():console.log("Server has been stopped");else console.warn("Server is not running.")}cfFetch(){return this.tempRoutes=null,this.tempMiddlewares=null,($,F,z)=>{return this.#F($,void 0,F,z)}}fetch(){if(this.tempRoutes=null,this.tempMiddlewares=null,this.platform==="cf"||this.platform==="cloudflare"){if(this.#$){let $=o(this);return(F,z,X)=>{return $(F,this,void 0,z,X).catch(async(Z)=>{return this.handleError(Z,g(F.url),F)})}}return($,F,z)=>{return this.#F($,void 0,F,z)}}if(this.#$){let $=o(this);return(F,z)=>{return $(F,this,z,void 0,void 0).catch(async(X)=>{return this.handleError(X,g(F.url),F)})}}return this.#F.bind(this)}async#F($,F,z,X){let Z=g($.url),Q=this.router.find($.method,Z),V=new _($,F,Z,Q?.params||S,z,X);try{if(this.hasOnReqHook)await f("onRequest",this.hooks.onRequest,[V]);if(this.hasPreHandlerHook){let W=await f("preHandler",this.hooks.preHandler,[V]);if(W)return W}let D,G=Q?.handler;if(G.length===1){let W=G[0](V);D=N(W)?await W:W}else for(let W=0;W<G.length;W++){let U=G[W](V);if(D=N(U)?await U:U,D)break}if(this.hasOnSendHook){let W=await f("onSend",this.hooks.onSend,[V,D]);if(W)return W}if(D)return D;return await b(this,V,Z)}catch(D){return this.handleError(D,Z,$)}}async handleError($,F,z){let Z=this.errorFormat,Q=await f("onError",this.hooks.onError,[$,F,z]);if(Q)return Q;if($&&typeof $==="object"&&$.name==="HTTPException"){let G=$;if(console.error(`HTTPException on path: ${F}`,{status:G.status,message:G.message,cause:G.cause,res:G.res,stack:G.stack}),G.res)return G.res;return Z==="json"?Response.json({error:G.message},{status:G.status}):new Response(G.message,{status:G.status})}let V=$ instanceof Error?$.message:"Internal Server Error",D=$ instanceof Error?$.stack:void 0;if(console.error(`Error on path: ${F}`,{message:V,stack:D}),Z==="json"){let G={error:V,...!1,path:F};return Response.json(G,{status:500,headers:{"Content-Type":"application/json"}})}else{let G=`Error: ${V}`;return new Response(G,{headers:{"Content-Type":"text/plain"},status:500})}}mount($,F){let z=$.endsWith("/*")?$.slice(0,-1):$,X=z==="/"?0:z.length;this.any($,(Z)=>{let Q=new URL(Z.req.url);Q.pathname=Q.pathname.slice(X)||"/";let V=new Request(Q,Z.req);return F(V,Z.server,Z.env,Z.executionContext)})}route($,F){$=$&&$.length>0?$:F?.prefixApiUrl;let z=F?.tempRoutes??new Map;for(let[X,Z]of z.entries()){let Q=X.replace(/::\w+$/,""),V=`${$}${Q}`,D=Z.handlers.slice(0,-1);this.router.addMiddleware(V,D);let G=Z.handlers[Z.handlers.length-1],W=Z.method;try{this.router.add(W,V,G)}catch(U){console.error(`Error inserting ${V}:`,U)}}for(let[X,Z]of F?.tempMiddlewares?.entries()){let Q=X==="/"?$||"/":`${$}${X}`;this.router.addMiddleware(Q,Z)}return F=null,this}register($){let F=new I,z=()=>{};return this}sub($,F){let z=F.fetch();return this.mount($,z)}addMiddlewareInRouter($,F){this.router.addMiddleware($,F)}addRoute($,F,z){if(typeof F!=="string")throw Error(`Error in ${z[z.length-1]}: Path must be a string. Received: ${typeof F}`);if(typeof $!=="string")throw Error(`Error in addRoute: Method must be a string. Received: ${typeof $}`);this.tempRoutes?.set(F+"::"+$,{method:$,handlers:z});let X=z.slice(0,-1),Z=z[z.length-1];if(X.length>0)this.addMiddlewareInRouter(F,X);try{if($==="ANY"){let Q=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let V of Q)try{this.router.add(V,F,Z)}catch(D){}}else this.router.add($,F,Z)}catch(Q){console.error(`Error inserting ${F}:`,Q)}}use($,...F){if(typeof $==="string"){let z=$==="/"?"/":$;if(!this.tempMiddlewares?.has(z))this.tempMiddlewares?.set(z,[]);this.tempMiddlewares?.get(z).push(...F),this.router.addMiddleware(z,F)}else if(typeof $==="function"){let z=[$,...F];if(!this.tempMiddlewares?.has("/"))this.tempMiddlewares?.set("/",[]);this.tempMiddlewares?.get("/").push(...F),this.router.addMiddleware("/",z)}return this}routeNotFound($){return this.routeNotFoundFunc=$,this}onMethod($,F,...z){let X=Array.isArray($)?$:[$];for(let Z of X){let Q=Z.toLowerCase();if(Q in this)this[Q](F,...z);else this.addRoute(Z.toUpperCase(),F,z)}return this}on($,F){return this.emitter.on($,F),this}emit($,...F){return this.emitter.emit($,...F),this}}class v{children;handlers;middlewares;params;paramName;constructor(){this.children={},this.handlers={},this.middlewares=[],this.params={},this.paramName=""}}class T{root;globalMiddlewares;constructor(){this.root=new v,this.globalMiddlewares=[]}pushMiddleware($,F){if(!Array.isArray(F))F=[F];if($==="/"){this.globalMiddlewares.push(...F);return}let z=this.root,X=$.split("/").filter(Boolean);for(let Z of X){let Q=Z;if(Z.startsWith(":"))Q=":";else if(Z.startsWith("*"))z.middlewares.push(...F);if(!z.children[Q])z.children[Q]=new v;z=z.children[Q]}z.middlewares.push(...F)}addMiddleware($,F){return this.pushMiddleware($,F)}insert($,F,z){let X=this.root;if(F==="/"){X.handlers[$]=z,X.params=S;return}let Z=F.split("/").filter(Boolean),Q={};for(let V=0;V<Z.length;V++){let D=Z[V],G=D,W="";if(D.startsWith(":"))G=":",W=D.slice(1);if(!X.children[G])X.children[G]=new v;if(X=X.children[G],W)Q[W]=V,X.paramName=W}X.params=Q,X.handlers[$]=z}add($,F,z){return this.insert($,F,z)}search($,F){let z=this.root,X=F.split("/"),Z=this.globalMiddlewares.slice(),Q;for(let V=0;V<X.length;V++){let D=X[V];if(D.length===0)continue;if(z.children[D])z=z.children[D];else if(z.children[":"]){if(z=z.children[":"],!Q)Q={};Q[z.paramName]=D}else if(z.children["*"]){z=z.children["*"];break}else return{params:Q,handler:Z};if(z.middlewares.length>0){let G=z.middlewares;for(let W=0;W<G.length;W++)Z.push(G[W])}}if(z.handlers[$])Z.push(z.handlers[$]);if(z.handlers.ALL)Z.push(z.handlers.ALL);return{params:Q,handler:Z}}find($,F){return this.search($,F)}}export{T as TrieRouter};
1
+ var F=Object.freeze({});class C{children;handlers;middlewares;params;paramName;constructor(){this.children={},this.handlers={},this.middlewares=[],this.params={},this.paramName=""}}class M{root;globalMiddlewares;constructor(){this.root=new C,this.globalMiddlewares=[]}pushMiddleware(D,E){if(!Array.isArray(E))E=[E];if(D==="/"){this.globalMiddlewares.push(...E);return}let A=this.root,L=D.split("/").filter(Boolean);for(let H of L){let x=H;if(H.startsWith(":"))x=":";else if(H.startsWith("*"))A.middlewares.push(...E);if(!A.children[x])A.children[x]=new C;A=A.children[x]}A.middlewares.push(...E)}addMiddleware(D,E){return this.pushMiddleware(D,E)}insert(D,E,A){let L=this.root;if(E==="/"){L.handlers[D]=A,L.params=F;return}let H=E.split("/").filter(Boolean),x={};for(let I=0;I<H.length;I++){let P=H[I],z=P,f="";if(P.startsWith(":"))z=":",f=P.slice(1);if(!L.children[z])L.children[z]=new C;if(L=L.children[z],f)x[f]=I,L.paramName=f}L.params=x,L.handlers[D]=A}add(D,E,A){return this.insert(D,E,A)}search(D,E){let A=this.root,L=E.split("/"),H=this.globalMiddlewares.slice(),x;for(let I=0;I<L.length;I++){let P=L[I];if(P.length===0)continue;if(A.children[P])A=A.children[P];else if(A.children[":"]){if(A=A.children[":"],!x)x={};x[A.paramName]=P}else if(A.children["*"]){A=A.children["*"];break}else return{params:x,handler:H};if(A.middlewares.length>0){let z=A.middlewares;for(let f=0;f<z.length;f++)H.push(z[f])}}if(A.handlers[D])H.push(A.handlers[D]);if(A.handlers.ALL)H.push(A.handlers.ALL);return{params:x,handler:H}}find(D,E){return this.search(D,E)}}export{M as TrieRouter};
package/dist/types.d.ts CHANGED
@@ -1,12 +1,16 @@
1
1
  import { Server } from "bun";
2
2
  import { Router } from "./router/interface";
3
3
  import Diesel from "./main";
4
+ import type { Context } from "./ctx";
5
+ export type { Context };
6
+ export type ContextType = Context;
7
+ export type { Diesel };
4
8
  export type listenCalllBackType = () => void;
5
- export type handlerFunction = (ctx: ContextType) => Response | Promise<Response | undefined>;
9
+ export type handlerFunction = (ctx: Context) => Response | Promise<Response | undefined>;
6
10
  export type RouteHandler = (path: string, ...handlers: handlerFunction[] | middlewareFunc[]) => Diesel;
7
- export type middlewareFunc = (ctx: ContextType | Request | any, server: Server) => void | undefined | Response | Promise<undefined | void | Response>;
8
- export type HookFunction = (ctx: ContextType, result?: Response | null, server?: Server) => undefined | void | null | Response | Promise<void | null | undefined | Response>;
9
- export type RouteNotFoundHandler = (ctx: ContextType) => Response | void | undefined | Promise<Response>;
11
+ export type middlewareFunc = (ctx: Context | Request | any, server: Server) => void | undefined | Response | Promise<undefined | void | Response>;
12
+ export type HookFunction = (ctx: Context, result?: Response | null, server?: Server) => undefined | void | null | Response | Promise<void | null | undefined | Response>;
13
+ export type RouteNotFoundHandler = (ctx: Context) => Response | void | undefined | Promise<Response>;
10
14
  export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "HEAD" | "ANY" | "PROPFIND";
11
15
  export type HttpMethodOfApp = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head' | 'any' | 'propfind';
12
16
  export type HttpMethodLower = Lowercase<HttpMethod>;
@@ -15,10 +19,10 @@ export interface onError {
15
19
  (error: Error, path: string, req: Request): void | null | Response | Promise<void | null | undefined | Response>;
16
20
  }
17
21
  export interface onRequest {
18
- (ctx: ContextType): void;
22
+ (ctx: Context): void;
19
23
  }
20
24
  export interface onSend {
21
- (ctx: ContextType, finalResult: Response): Promise<Response | undefined>;
25
+ (ctx: Context, finalResult: Response): Promise<Response | undefined>;
22
26
  }
23
27
  export interface Hooks {
24
28
  onRequest: onRequest[];
@@ -28,34 +32,6 @@ export interface Hooks {
28
32
  onError: onError[];
29
33
  onClose: HookFunction[];
30
34
  }
31
- export interface ContextType {
32
- req: Request;
33
- server?: Server;
34
- path?: string | undefined;
35
- routePattern?: string | undefined;
36
- env?: Record<string, any>;
37
- executionContext?: any | undefined;
38
- headers: Headers;
39
- setHeader: (key: string, value: string) => this;
40
- json: (data: object, status?: number, customHeaders?: HeadersInit) => Response;
41
- text: (data: string, status?: number, customHeaders?: HeadersInit) => Response;
42
- send: <T>(data: T, status?: number, customHeaders?: HeadersInit) => Response;
43
- file: (filePath: string, mimeType?: string, status?: number, customHeaders?: HeadersInit) => Response;
44
- redirect: (path: string, status?: number) => Response;
45
- setCookie: (name: string, value: string, options?: CookieOptions) => this;
46
- ip: string | null;
47
- url: URL;
48
- query: Record<string, string>;
49
- params: Record<string, string>;
50
- set<T>(key: string, value: T): this;
51
- get<T>(key: string): T | undefined;
52
- body: Promise<any>;
53
- cookies: Record<string, string>;
54
- removeHeader: (key: string) => this;
55
- ejs: (viewPath: string, data: object) => Response | Promise<Response>;
56
- stream: (callback: () => void) => Response;
57
- yieldStream: (callback: () => AsyncIterable<any>) => Response;
58
- }
59
35
  export interface CookieOptions {
60
36
  maxAge?: number;
61
37
  expires?: Date;
@@ -75,37 +51,6 @@ export interface TempRouteEntry {
75
51
  method: string;
76
52
  handlers: handlerFunction[];
77
53
  }
78
- export interface DieselT {
79
- hasOnReqHook: boolean;
80
- hasMiddleware: boolean;
81
- hasPreHandlerHook: boolean;
82
- hasPostHandlerHook: boolean;
83
- hasOnSendHook: boolean;
84
- hasFilterEnabled: boolean;
85
- hooks: {
86
- onRequest: ((req: Request, url: URL, server: Server) => void) | null;
87
- preHandler: ((ctx: ContextType, server?: Server) => Response | Promise<Response>) | null;
88
- postHandler: ((ctx: ContextType, server?: Server) => Response | Promise<Response>) | null;
89
- onSend: ((ctx: ContextType, result?: Response | null, server?: Server) => Response | Promise<Response>) | null;
90
- onError: ((error: Error, req: Request, url: URL, server?: Server) => void | Response | Promise<Response>) | null;
91
- routeNotFound: ((ctx: ContextType) => Response | Promise<Response>) | null;
92
- };
93
- filters: Set<string>;
94
- filterFunction: Array<(ctx: ContextType, server?: Server) => void | Response | Promise<void | Response>>;
95
- corsConfig: corsT | null;
96
- globalMiddlewares: Array<(ctx: ContextType, server?: Server) => void | Promise<void | Response>>;
97
- middlewares: Map<string, Array<(ctx: ContextType, server?: Server) => void | Promise<void | Response>>>;
98
- router: Router;
99
- staticPath: string | null;
100
- staticRequestPath: string | null;
101
- staticFiles: Record<string, string>;
102
- routeNotFoundFunc: RouteNotFoundHandler;
103
- routerInstance: DieselT;
104
- tempRoutes: Map<string, TempRouteEntry>;
105
- routes: Record<string, Function>;
106
- on: () => void;
107
- emit: () => void;
108
- }
109
54
  export type corsT = {
110
55
  origin?: string | string[] | null;
111
56
  methods?: string | string[] | null;
@@ -1,12 +1,12 @@
1
1
  import { Server } from "bun";
2
- import { ContextType, DieselT, HookType } from "../types";
2
+ import { ContextType, HookType } from "../types";
3
3
  import Diesel from "../main";
4
4
  export declare function runHooks<T extends any[]>(label: HookType, hooksArray: any, args: T): Promise<Response | undefined>;
5
- export declare function runMiddlewares(diesel: DieselT, pathname: string, ctx: ContextType): Promise<Response | null>;
5
+ export declare function runMiddlewares(diesel: Diesel, pathname: string, ctx: ContextType): Promise<null>;
6
6
  export declare function executeBunMiddlewares(middlewares: Function[], req: Request, server: Server): Promise<any>;
7
7
  export declare function runFilter(diesel: Diesel, path: string, ctx: ContextType): Promise<any>;
8
8
  export declare function handleFilterRequest(diesel: Diesel, path: string, ctx: ContextType): Promise<any>;
9
- export declare function handleBunFilterRequest(diesel: DieselT, path: string, req: Request, server: Server): Promise<Response | undefined>;
9
+ export declare function handleBunFilterRequest(diesel: Diesel, path: string, req: Request, server: Server): Promise<any>;
10
10
  export declare function handleRouteNotFound(diesel: Diesel, ctx: ContextType, pathname: string): Promise<Response | undefined>;
11
11
  export declare function generateErrorResponse(status: number, error: string): Response;
12
12
  export declare function handleStaticFiles(diesel: Diesel, pathname: string, ctx: ContextType): Promise<Response | null>;
@@ -1 +1 @@
1
- function f(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 l=(e)=>e!==null&&typeof e==="object"&&typeof e.then==="function",u=(e)=>e!==null&&typeof e==="object"&&typeof e.status==="number"&&typeof e.headers==="object";async function R(e,t,o){if(!t?.length)return;for(let n=0;n<t.length;n++){let r=t[n](...o),s=r instanceof Promise?await r:r;if(s&&e!=="onRequest")return s}}async function x(e,t,o){let n=e.globalMiddlewares;if(n.length)for(let s of n){let i=await s(o);if(i)return i}let r=e.middlewares.get(t);if(r&&r.length)for(let s of r){let i=await s(o);if(i)return i}return null}async function T(e,t,o){for(let n of e){let r=await n(t,o);if(r)return r}}async function F(e,t,o){let n=await p(e,t,o),r=l(n)?await n:n;if(r)return r}async function p(e,t,o){if(t.endsWith("/"))t=t.slice(0,-1);if(!e.filters.has(t))if(e.filterFunction.length)for(let n of e.filterFunction){let r=await n(o);if(r)return r}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function P(e,t,o,n){if(!e.filters.has(t))if(e.filterFunction.length)for(let r of e.filterFunction){let s=await r(o,n);if(s)return s}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function j(e,t,o){if(e.staticPath){let a=!0;if(e.staticRequestPath)a=o.startsWith(e.staticRequestPath);if(a){let c=await m(e,o,t);if(c)return c}}let s=(e.router.find(t.req.method,"*")?.handler).slice(-1);if(s.length>0){let a=await s[0](t);if(u(a))return a}let i=await Promise.resolve(e.routeNotFoundFunc(t));return u(i)?i:g(404,`404 Route not found for ${o}`)}function g(e,t){return new Response(JSON.stringify({error:t}),{status:e,headers:{"Content-Type":"application/json"}})}async function m(e,t,o){if(!e.staticPath)return null;let n=`${e.staticPath}${t}`;if(await Bun.file(n).exists()){let s=f(n);return o.file(n,s,200)}return null}export{x as runMiddlewares,R as runHooks,F as runFilter,m as handleStaticFiles,j as handleRouteNotFound,p as handleFilterRequest,P as handleBunFilterRequest,g as generateErrorResponse,T as executeBunMiddlewares};
1
+ function b(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 z=(g)=>g!==null&&typeof g==="object"&&typeof g.then==="function",f=(g)=>g!==null&&typeof g==="object"&&typeof g.status==="number"&&typeof g.headers==="object";async function M(g,n,j){if(!n?.length)return;for(let o=0;o<n.length;o++){let c=n[o](...j),w=c instanceof Promise?await c:c;if(w&&g!=="onRequest")return w}}async function N(g,n,j){return null}async function O(g,n,j){for(let o of g){let c=await o(n,j);if(c)return c}}async function Q(g,n,j){let o=await B(g,n,j),c=z(o)?await o:o;if(c)return c}async function B(g,n,j){if(n.endsWith("/"))n=n.slice(0,-1);if(!g.filters.has(n))if(g.filterFunction.length)for(let o of g.filterFunction){let c=await o(j);if(c)return c}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function U(g,n,j,o){if(!g.filters.has(n))if(g.filterFunction.length)for(let c of g.filterFunction){let w=await c(j,o);if(w)return w}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function V(g,n,j){if(g.staticPath){let y=!0;if(g.staticRequestPath)y=j.startsWith(g.staticRequestPath);if(y){let L=await G(g,j,n);if(L)return L}}let w=(g.router.find(n.req.method,"*")?.handler).slice(-1);if(w.length>0){let y=await w[0](n);if(f(y))return y}let C=await Promise.resolve(g.routeNotFoundFunc(n));return f(C)?C:D(404,`404 Route not found for ${j}`)}function D(g,n){return new Response(JSON.stringify({error:n}),{status:g,headers:{"Content-Type":"application/json"}})}async function G(g,n,j){if(!g.staticPath)return null;let o=`${g.staticPath}${n}`;if(await Bun.file(o).exists()){let w=b(o);return j.file(o,w,200)}return null}export{N as runMiddlewares,M as runHooks,Q as runFilter,G as handleStaticFiles,V as handleRouteNotFound,B as handleFilterRequest,U as handleBunFilterRequest,D as generateErrorResponse,O as executeBunMiddlewares};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "diesel-core",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "Web framework built on Web Standards",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -1,25 +0,0 @@
1
- import { handlerFunction, middlewareFunc } from "../types";
2
- declare class TrieNodes {
3
- children: Record<string, TrieNodes>;
4
- handlers: Record<string, Function>;
5
- middlewares: Function[];
6
- params: Record<string, number>;
7
- constructor();
8
- }
9
- export declare class TrieRouterWithObject {
10
- root: TrieNodes;
11
- globalMiddlewares: Function[];
12
- constructor();
13
- pushMiddleware(path: string, handlers: middlewareFunc | middlewareFunc[]): void;
14
- insert(method: string, path: string, handler: handlerFunction): void;
15
- add(method: string, path: string, handler: handlerFunction): void;
16
- search(method: string, path: string): {
17
- params: Record<string, number>;
18
- handler: Function[];
19
- };
20
- find(method: string, path: string): {
21
- params: Record<string, number>;
22
- handler: Function[];
23
- };
24
- }
25
- export {};