diesel-core 1.3.6 → 1.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ctx.js CHANGED
@@ -1 +1 @@
1
- var I=Object.create;var{getPrototypeOf:M,defineProperty:X,getOwnPropertyNames:N}=Object;var R=Object.prototype.hasOwnProperty;var U=(w,A,E)=>{E=w!=null?I(M(w)):{};let z=A||!w||!w.__esModule?X(E,"default",{value:w,enumerable:!0}):E;for(let F of N(w))if(!R.call(z,F))X(z,F,{get:()=>w[F],enumerable:!0});return z};var V=((w)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(w,{get:(A,E)=>(typeof require!=="undefined"?require:A)[E]}):w)(function(w){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+w+'" is not supported')});function Y(w){switch(w.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"}}function W(w,A,E){let z=null,F=null,J=null,G=null,O={},Z=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]);return{req:w,server:A,url:E,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(f,g){return this.headers.set(f,g),this},removeHeader(f){return this.headers.delete(f),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!z)try{z=Object.fromEntries(this.url.searchParams)}catch(f){throw new Error("Failed to parse query parameters")}return z},get params(){if(!F&&this.req.routePattern)try{F=B(this.req.routePattern,this.url.pathname)}catch(f){throw new Error("Failed to extract route parameters")}return F??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!G)G=(async()=>{let f=await C(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f})();return G},set(f,g){return O[f]=g,this},get(f){return O[f]},text(f,g){if(g)this.status=g;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(f,{status:this.status,headers:this.headers})},send(f,g){if(g)this.status=g;let x;if(f instanceof Uint8Array)x="Uint8Array";else if(f instanceof ArrayBuffer)x="ArrayBuffer";else x=typeof f;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",Z.get(x)??"text/plain; charset=utf-8");let L=x==="object"&&f!==null?JSON.stringify(f):f;return new Response(L,{status:this.status,headers:this.headers})},json(f,g){if(g)this.status=g;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(f,{status:this.status,headers:this.headers})},file(f,g,x){if(x)this.status=x;let L=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",g??Y(f));return new Response(L,{status:this.status,headers:this.headers})},async ejs(f,g={},x){if(x)this.status=x;let L;try{L=await import("ejs"),L=L.default||L}catch(K){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let K=await Bun.file(f).text(),$=L.render(K,g),j=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response($,{status:this.status,headers:j})}catch(K){return console.error("EJS Rendering Error:",K),new Response("Error rendering template",{status:500})}},redirect(f,g){if(g)this.status=g;else this.status=302;return this.headers.set("Location",f),new Response(null,{status:this.status,headers:this.headers})},stream(f){let g=new Headers(this.headers),x=new ReadableStream({async start(L){await f(L),L.close()}});return new Response(x,{headers:g})},yieldStream(f){return new Response({async*[Symbol.asyncIterator](){yield*f()}},{headers:this.headers})},setCookie(f,g,x={}){let L=`${encodeURIComponent(f)}=${encodeURIComponent(g)}`;if(x.maxAge)L+=`; Max-Age=${x.maxAge}`;if(x.expires)L+=`; Expires=${x.expires.toUTCString()}`;if(x.path)L+=`; Path=${x.path}`;if(x.domain)L+=`; Domain=${x.domain}`;if(x.secure)L+="; Secure";if(x.httpOnly)L+="; HttpOnly";if(x.sameSite)L+=`; SameSite=${x.sameSite}`;return this.headers.append("Set-Cookie",L),this},get cookies(){if(!J){let f=this.req.headers.get("cookie");J=f?_(f):{}}return J}}}function _(w){return Object.fromEntries(w.split(";").map((A)=>{let[E,...z]=A.trim().split("=");return[E,decodeURIComponent(z.join("="))]}))}function B(w,A){let E={},z=w.split("/"),[F]=A.split("?"),J=F.split("/");if(z.length!==J.length)return null;for(let G=0;G<z.length;G++)if(z[G].startsWith(":"))E[z[G].slice(1)]=J[G];return E}async function C(w){let A=w.headers.get("Content-Type");if(!A)return{};if(w.headers.get("Content-Length")==="0"||!w.body)return{};try{if(A.startsWith("application/json"))return await w.json();if(A.startsWith("application/x-www-form-urlencoded")){let z=await w.text();return Object.fromEntries(new URLSearchParams(z))}if(A.startsWith("multipart/form-data")){let z=await w.formData(),F={};for(let[J,G]of z.entries())F[J]=G;return F}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}export{W as default};
1
+ var j=Object.create;var{getPrototypeOf:I,defineProperty:X,getOwnPropertyNames:M}=Object;var N=Object.prototype.hasOwnProperty;var R=(w,A,E)=>{E=w!=null?j(I(w)):{};let z=A||!w||!w.__esModule?X(E,"default",{value:w,enumerable:!0}):E;for(let F of M(w))if(!N.call(z,F))X(z,F,{get:()=>w[F],enumerable:!0});return z};var U=((w)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(w,{get:(A,E)=>(typeof require!=="undefined"?require:A)[E]}):w)(function(w){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+w+'" is not supported')});function Y(w){switch(w.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"}}function V(w,A,E){let z=null,F=null,J=null,G=null,O={};return{req:w,server:A,url:E,status:200,headers:new Headers,setHeader(f,g){return this.headers.set(f,g),this},removeHeader(f){return this.headers.delete(f),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!z)try{z=Object.fromEntries(this.url.searchParams)}catch(f){throw new Error("Failed to parse query parameters")}return z},get params(){if(!F&&this.req.routePattern)try{F=_(this.req.routePattern,this.url.pathname)}catch(f){throw new Error("Failed to extract route parameters")}return F??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!G)G=(async()=>{let f=await B(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f})();return G},set(f,g){return O[f]=g,this},get(f){return O[f]},text(f,g){if(g)this.status=g;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(f,{status:this.status,headers:this.headers})},send(f,g){if(g)this.status=g;let L=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),x;if(f instanceof Uint8Array)x="Uint8Array";else if(f instanceof ArrayBuffer)x="ArrayBuffer";else x=typeof f;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",L.get(x)??"text/plain; charset=utf-8");let K=x==="object"&&f!==null?JSON.stringify(f):f;return new Response(K,{status:this.status,headers:this.headers})},json(f,g){if(g)this.status=g;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(f,{status:this.status,headers:this.headers})},file(f,g,L){if(L)this.status=L;let x=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",g??Y(f));return new Response(x,{status:this.status,headers:this.headers})},async ejs(f,g={},L){if(L)this.status=L;let x;try{x=await import("ejs"),x=x.default||x}catch(K){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let K=await Bun.file(f).text(),Z=x.render(K,g),$=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(Z,{status:this.status,headers:$})}catch(K){return console.error("EJS Rendering Error:",K),new Response("Error rendering template",{status:500})}},redirect(f,g){if(g)this.status=g;else this.status=302;return this.headers.set("Location",f),new Response(null,{status:this.status,headers:this.headers})},stream(f){let g=new Headers(this.headers),L=new ReadableStream({async start(x){await f(x),x.close()}});return new Response(L,{headers:g})},yieldStream(f){return new Response({async*[Symbol.asyncIterator](){yield*f()}},{headers:this.headers})},setCookie(f,g,L={}){let x=`${encodeURIComponent(f)}=${encodeURIComponent(g)}`;if(L.maxAge)x+=`; Max-Age=${L.maxAge}`;if(L.expires)x+=`; Expires=${L.expires.toUTCString()}`;if(L.path)x+=`; Path=${L.path}`;if(L.domain)x+=`; Domain=${L.domain}`;if(L.secure)x+="; Secure";if(L.httpOnly)x+="; HttpOnly";if(L.sameSite)x+=`; SameSite=${L.sameSite}`;return this.headers.append("Set-Cookie",x),this},get cookies(){if(!J){let f=this.req.headers.get("cookie");J=f?W(f):{}}return J}}}function W(w){return Object.fromEntries(w.split(";").map((A)=>{let[E,...z]=A.trim().split("=");return[E,decodeURIComponent(z.join("="))]}))}function _(w,A){let E={},z=w.split("/"),[F]=A.split("?"),J=F.split("/");if(z.length!==J.length)return null;for(let G=0;G<z.length;G++)if(z[G].startsWith(":"))E[z[G].slice(1)]=J[G];return E}async function B(w){let A=w.headers.get("Content-Type");if(!A)return{};if(w.headers.get("Content-Length")==="0"||!w.body)return{};try{if(A.startsWith("application/json"))return await w.json();if(A.startsWith("application/x-www-form-urlencoded")){let z=await w.text();return Object.fromEntries(new URLSearchParams(z))}if(A.startsWith("multipart/form-data")){let z=await w.formData(),F={};for(let[J,G]of z.entries())F[J]=G;return F}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}export{V as default};
@@ -1 +1 @@
1
- var D=Object.create;var{getPrototypeOf:M,defineProperty:Q,getOwnPropertyNames:A}=Object;var F=Object.prototype.hasOwnProperty;var w=(L,G,O)=>{O=L!=null?D(M(L)):{};let z=G||!L||!L.__esModule?Q(O,"default",{value:L,enumerable:!0}):O;for(let J of A(L))if(!F.call(z,J))Q(z,J,{get:()=>L[J],enumerable:!0});return z};var H=((L)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(L,{get:(G,O)=>(typeof require!=="undefined"?require:G)[O]}):L)(function(L){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+L+'" is not supported')});function W(L){switch(L.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"}}function _(L,G,O){let z=null,J=null,X=null,j=null,U={},I=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]);return{req:L,server:G,url:O,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(K,Z){return this.headers.set(K,Z),this},removeHeader(K){return this.headers.delete(K),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!z)try{z=Object.fromEntries(this.url.searchParams)}catch(K){throw new Error("Failed to parse query parameters")}return z},get params(){if(!J&&this.req.routePattern)try{J=f(this.req.routePattern,this.url.pathname)}catch(K){throw new Error("Failed to extract route parameters")}return J??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!j)j=(async()=>{let K=await S(this.req);if(K.error)throw new Error(K.error);return Object.keys(K).length===0?null:K})();return j},set(K,Z){return U[K]=Z,this},get(K){return U[K]},text(K,Z){if(Z)this.status=Z;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(K,{status:this.status,headers:this.headers})},send(K,Z){if(Z)this.status=Z;let Y;if(K instanceof Uint8Array)Y="Uint8Array";else if(K instanceof ArrayBuffer)Y="ArrayBuffer";else Y=typeof K;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",I.get(Y)??"text/plain; charset=utf-8");let $=Y==="object"&&K!==null?JSON.stringify(K):K;return new Response($,{status:this.status,headers:this.headers})},json(K,Z){if(Z)this.status=Z;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(K,{status:this.status,headers:this.headers})},file(K,Z,Y){if(Y)this.status=Y;let $=Bun.file(K);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",Z??W(K));return new Response($,{status:this.status,headers:this.headers})},async ejs(K,Z={},Y){if(Y)this.status=Y;let $;try{$=await import("ejs"),$=$.default||$}catch(V){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let V=await Bun.file(K).text(),B=$.render(V,Z),C=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(B,{status:this.status,headers:C})}catch(V){return console.error("EJS Rendering Error:",V),new Response("Error rendering template",{status:500})}},redirect(K,Z){if(Z)this.status=Z;else this.status=302;return this.headers.set("Location",K),new Response(null,{status:this.status,headers:this.headers})},stream(K){let Z=new Headers(this.headers),Y=new ReadableStream({async start($){await K($),$.close()}});return new Response(Y,{headers:Z})},yieldStream(K){return new Response({async*[Symbol.asyncIterator](){yield*K()}},{headers:this.headers})},setCookie(K,Z,Y={}){let $=`${encodeURIComponent(K)}=${encodeURIComponent(Z)}`;if(Y.maxAge)$+=`; Max-Age=${Y.maxAge}`;if(Y.expires)$+=`; Expires=${Y.expires.toUTCString()}`;if(Y.path)$+=`; Path=${Y.path}`;if(Y.domain)$+=`; Domain=${Y.domain}`;if(Y.secure)$+="; Secure";if(Y.httpOnly)$+="; HttpOnly";if(Y.sameSite)$+=`; SameSite=${Y.sameSite}`;return this.headers.append("Set-Cookie",$),this},get cookies(){if(!X){let K=this.req.headers.get("cookie");X=K?b(K):{}}return X}}}function b(L){return Object.fromEntries(L.split(";").map((G)=>{let[O,...z]=G.trim().split("=");return[O,decodeURIComponent(z.join("="))]}))}function f(L,G){let O={},z=L.split("/"),[J]=G.split("?"),X=J.split("/");if(z.length!==X.length)return null;for(let j=0;j<z.length;j++)if(z[j].startsWith(":"))O[z[j].slice(1)]=X[j];return O}async function S(L){let G=L.headers.get("Content-Type");if(!G)return{};if(L.headers.get("Content-Length")==="0"||!L.body)return{};try{if(G.startsWith("application/json"))return await L.json();if(G.startsWith("application/x-www-form-urlencoded")){let z=await L.text();return Object.fromEntries(new URLSearchParams(z))}if(G.startsWith("multipart/form-data")){let z=await L.formData(),J={};for(let[X,j]of z.entries())J[X]=j;return J}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}async function T(L,G,O,z){let J=_(L,G,O),X=z.trie.search(O.pathname,L.method);L.routePattern=X?.path;try{if(z.hooks.onRequest)await N("onRequest",z.hooks.onRequest,[L,O,G]);if(z.hasMiddleware){let I=await P(z,O.pathname,J,G);if(I)return I}if(z.hasFilterEnabled){let I=L.routePattern??O.pathname,K=await R(z,I,J,G);if(K)return K}if(!X)return await q(z,J,O.pathname);if(z.hooks.preHandler){let I=await N("preHandler",z.hooks.preHandler,[J,G]);if(I)return I}let j=X.handler(J),U=j instanceof Promise?await j:j;if(z.hasOnSendHook){let I=await N("onSend",z.hooks.onSend,[J,U,G]);if(I)return I}if(U instanceof Response)return U;return E(500,"No response returned from handler.")}catch(j){return await N("onError",z.hooks.onError,[j,L,O,G])||E(500,"Internal Server Error")}}async function N(L,G,O){if(!G?.length)return;for(let z=0;z<G.length;z++){let J=G[z](...O),X=J instanceof Promise?await J:J;if(X&&L!=="onRequest")return X}}async function P(L,G,O,z){if(L.globalMiddlewares.length){let X=await g(L.globalMiddlewares,O,z);if(X)return X}let J=L.middlewares.get(G)||[];if(J.length){let X=await g(J,O,z);if(X)return X}return null}async function g(L,G,O){for(let z of L){let J=await z(G,O);if(J)return J}return null}async function n(L,G,O){for(let z of L){let J=await z(G,O);if(J)return J}}async function R(L,G,O,z){let J=await x(L,G,O,z),X=J instanceof Promise?await J:J;if(X)return X}async function x(L,G,O,z){if(G.endsWith("/"))G=G.slice(0,-1);if(!L.filters.has(G))if(L.filterFunction.length)for(let J of L.filterFunction){let X=await J(O,z);if(X)return X}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function u(L,G,O,z){if(!L.filters.has(G))if(L.filterFunction.length)for(let J of L.filterFunction){let X=await J(O,z);if(X)return X}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function q(L,G,O){if(L.staticPath){let J=await v(L,O,G);if(J)return J;let X=L.trie.search("*",G.req.method);if(X?.handler)return await X.handler(G)}return L.routeNotFoundFunc(G)||E(404,`Route not found for ${O}`)}function E(L,G){return new Response(JSON.stringify({error:G}),{status:L,headers:{"Content-Type":"application/json"}})}async function v(L,G,O){if(!L.staticPath)return null;let z=`${L.staticPath}${G}`;if(await Bun.file(z).exists()){let X=W(z);return O.file(z,X,200)}return null}export{v as handleStaticFiles,x as handleFilterRequest,u as handleBunFilterRequest,E as generateErrorResponse,g as executeMiddlewares,n as executeBunMiddlewares,T as default};
1
+ var C=Object.create;var{getPrototypeOf:D,defineProperty:E,getOwnPropertyNames:M}=Object;var A=Object.prototype.hasOwnProperty;var F=(L,J,O)=>{O=L!=null?C(D(L)):{};let z=J||!L||!L.__esModule?E(O,"default",{value:L,enumerable:!0}):O;for(let K of M(L))if(!A.call(z,K))E(z,K,{get:()=>L[K],enumerable:!0});return z};var w=((L)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(L,{get:(J,O)=>(typeof require!=="undefined"?require:J)[O]}):L)(function(L){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+L+'" is not supported')});function V(L){switch(L.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"}}function N(L,J,O){let z=null,K=null,X=null,j=null,I={};return{req:L,server:J,url:O,status:200,headers:new Headers,setHeader(G,Y){return this.headers.set(G,Y),this},removeHeader(G){return this.headers.delete(G),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!z)try{z=Object.fromEntries(this.url.searchParams)}catch(G){throw new Error("Failed to parse query parameters")}return z},get params(){if(!K&&this.req.routePattern)try{K=b(this.req.routePattern,this.url.pathname)}catch(G){throw new Error("Failed to extract route parameters")}return K??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!j)j=(async()=>{let G=await f(this.req);if(G.error)throw new Error(G.error);return Object.keys(G).length===0?null:G})();return j},set(G,Y){return I[G]=Y,this},get(G){return I[G]},text(G,Y){if(Y)this.status=Y;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(G,{status:this.status,headers:this.headers})},send(G,Y){if(Y)this.status=Y;let $=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),Z;if(G instanceof Uint8Array)Z="Uint8Array";else if(G instanceof ArrayBuffer)Z="ArrayBuffer";else Z=typeof G;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",$.get(Z)??"text/plain; charset=utf-8");let U=Z==="object"&&G!==null?JSON.stringify(G):G;return new Response(U,{status:this.status,headers:this.headers})},json(G,Y){if(Y)this.status=Y;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(G,{status:this.status,headers:this.headers})},file(G,Y,$){if($)this.status=$;let Z=Bun.file(G);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",Y??V(G));return new Response(Z,{status:this.status,headers:this.headers})},async ejs(G,Y={},$){if($)this.status=$;let Z;try{Z=await import("ejs"),Z=Z.default||Z}catch(U){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let U=await Bun.file(G).text(),g=Z.render(U,Y),B=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(g,{status:this.status,headers:B})}catch(U){return console.error("EJS Rendering Error:",U),new Response("Error rendering template",{status:500})}},redirect(G,Y){if(Y)this.status=Y;else this.status=302;return this.headers.set("Location",G),new Response(null,{status:this.status,headers:this.headers})},stream(G){let Y=new Headers(this.headers),$=new ReadableStream({async start(Z){await G(Z),Z.close()}});return new Response($,{headers:Y})},yieldStream(G){return new Response({async*[Symbol.asyncIterator](){yield*G()}},{headers:this.headers})},setCookie(G,Y,$={}){let Z=`${encodeURIComponent(G)}=${encodeURIComponent(Y)}`;if($.maxAge)Z+=`; Max-Age=${$.maxAge}`;if($.expires)Z+=`; Expires=${$.expires.toUTCString()}`;if($.path)Z+=`; Path=${$.path}`;if($.domain)Z+=`; Domain=${$.domain}`;if($.secure)Z+="; Secure";if($.httpOnly)Z+="; HttpOnly";if($.sameSite)Z+=`; SameSite=${$.sameSite}`;return this.headers.append("Set-Cookie",Z),this},get cookies(){if(!X){let G=this.req.headers.get("cookie");X=G?H(G):{}}return X}}}function H(L){return Object.fromEntries(L.split(";").map((J)=>{let[O,...z]=J.trim().split("=");return[O,decodeURIComponent(z.join("="))]}))}function b(L,J){let O={},z=L.split("/"),[K]=J.split("?"),X=K.split("/");if(z.length!==X.length)return null;for(let j=0;j<z.length;j++)if(z[j].startsWith(":"))O[z[j].slice(1)]=X[j];return O}async function f(L){let J=L.headers.get("Content-Type");if(!J)return{};if(L.headers.get("Content-Length")==="0"||!L.body)return{};try{if(J.startsWith("application/json"))return await L.json();if(J.startsWith("application/x-www-form-urlencoded")){let z=await L.text();return Object.fromEntries(new URLSearchParams(z))}if(J.startsWith("multipart/form-data")){let z=await L.formData(),K={};for(let[X,j]of z.entries())K[X]=j;return K}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}async function S(L,J,O,z){let K=N(L,J,O),X=z.trie.search(O.pathname,L.method);L.routePattern=X?.path;try{if(z.hooks.onRequest)await W("onRequest",z.hooks.onRequest,[L,O,J]);if(z.hasMiddleware){let G=await T(z,O.pathname,K,J);if(G)return G}if(z.hasFilterEnabled){let G=L.routePattern??O.pathname,Y=await P(z,G,K,J);if(Y)return Y}if(!X)return await x(z,K,O.pathname);if(z.hooks.preHandler){let G=await W("preHandler",z.hooks.preHandler,[K,J]);if(G)return G}let j=X.handler(K),I=j instanceof Promise?await j:j;if(z.hasOnSendHook){let G=await W("onSend",z.hooks.onSend,[K,I,J]);if(G)return G}if(I instanceof Response)return I;return _(500,"No response returned from handler.")}catch(j){return await W("onError",z.hooks.onError,[j,L,O,J])||_(500,"Internal Server Error")}}async function W(L,J,O){if(!J?.length)return;for(let z=0;z<J.length;z++){let K=J[z](...O),X=K instanceof Promise?await K:K;if(X&&L!=="onRequest")return X}}async function T(L,J,O,z){if(L.globalMiddlewares.length){let X=await Q(L.globalMiddlewares,O,z);if(X)return X}let K=L.middlewares.get(J)||[];if(K.length){let X=await Q(K,O,z);if(X)return X}return null}async function Q(L,J,O){for(let z of L){let K=await z(J,O);if(K)return K}return null}async function p(L,J,O){for(let z of L){let K=await z(J,O);if(K)return K}}async function P(L,J,O,z){let K=await R(L,J,O,z),X=K instanceof Promise?await K:K;if(X)return X}async function R(L,J,O,z){if(J.endsWith("/"))J=J.slice(0,-1);if(!L.filters.has(J))if(L.filterFunction.length)for(let K of L.filterFunction){let X=await K(O,z);if(X)return X}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function n(L,J,O,z){if(!L.filters.has(J))if(L.filterFunction.length)for(let K of L.filterFunction){let X=await K(O,z);if(X)return X}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function x(L,J,O){if(L.staticPath){let K=await q(L,O,J);if(K)return K;let X=L.trie.search("*",J.req.method);if(X?.handler)return await X.handler(J)}return L.routeNotFoundFunc(J)||_(404,`Route not found for ${O}`)}function _(L,J){return new Response(JSON.stringify({error:J}),{status:L,headers:{"Content-Type":"application/json"}})}async function q(L,J,O){if(!L.staticPath)return null;let z=`${L.staticPath}${J}`;if(await Bun.file(z).exists()){let X=V(z);return O.file(z,X,200)}return null}export{q as handleStaticFiles,R as handleFilterRequest,n as handleBunFilterRequest,_ as generateErrorResponse,Q as executeMiddlewares,p as executeBunMiddlewares,S as default};
package/dist/main.d.ts CHANGED
@@ -5,7 +5,7 @@ import { AdvancedLoggerOptions, LoggerOptions } from "./middlewares/logger/logge
5
5
  import { ServerOptions } from "http";
6
6
  export default class Diesel {
7
7
  private static instance;
8
- fecth: ServerOptions['fecth'];
8
+ fecth: ServerOptions['fetch'];
9
9
  routes: Record<string, Function>;
10
10
  private tempRoutes;
11
11
  globalMiddlewares: middlewareFunc[];
@@ -32,14 +32,20 @@ export default class Diesel {
32
32
  idleTimeOut: number;
33
33
  routeNotFoundFunc: (c: ContextType) => void | Promise<void> | Promise<Response> | Response;
34
34
  private prefixApiUrl;
35
- constructor({ jwtSecret, baseApiUrl, enableFileRouting, idleTimeOut, prefixApiUrl }?: {
35
+ constructor({ jwtSecret, baseApiUrl, enableFileRouting, idleTimeOut, prefixApiUrl, }?: {
36
36
  jwtSecret?: string;
37
37
  baseApiUrl?: string;
38
38
  enableFileRouting?: boolean;
39
39
  idleTimeOut?: number;
40
40
  prefixApiUrl?: string;
41
41
  });
42
- static router(apiPath: string): Diesel;
42
+ static router(prefix: string): Diesel;
43
+ /**
44
+ this filter is like user once specify which routes needs to be public and for rest routes use a global
45
+ auth middleware .
46
+
47
+ and this provides built in middleware to authenticate using jwt
48
+ */
43
49
  setupFilter(): FilterMethods;
44
50
  redirect(incomingPath: string, redirectPath: string, statusCode?: 302): this;
45
51
  serveStatic(filePath: string): this;
@@ -61,7 +67,7 @@ export default class Diesel {
61
67
  * const userRoute = new Diesel();
62
68
  * app.route("/api/v1/user", userRoute);
63
69
  */
64
- route(basePath?: string | undefined, routerInstance: Diesel): this;
70
+ route(basePath: string | undefined, routerInstance: Diesel | null): this;
65
71
  /**
66
72
  * Registers a router instance for subrouting.
67
73
  * Allows defining subroutes like:
package/dist/main.js CHANGED
@@ -1,3 +1,3 @@
1
- var k=Object.create;var{getPrototypeOf:u,defineProperty:j,getOwnPropertyNames:x}=Object;var i=Object.prototype.hasOwnProperty;var o=(g,f,L)=>{L=g!=null?k(u(g)):{};let $=f||!g||!g.__esModule?j(L,"default",{value:g,enumerable:!0}):L;for(let A of x(g))if(!i.call($,A))j($,A,{get:()=>g[A],enumerable:!0});return $};var l=((g)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(g,{get:(f,L)=>(typeof require!=="undefined"?require:f)[L]}):g)(function(g){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+g+'" is not supported')});class Q{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 W{root;constructor(){this.root=new Q}insert(g,f){let L=this.root,$=g.split("/").filter(Boolean);if(g==="/"){L.isEndOfWord=!0,L.handler.push(f.handler),L.path=g,L.method.push(f.method);return}for(let A of $){let C=!1,E=A;if(A.startsWith(":"))C=!0,E=":";if(!L.children[E])L.children[E]=new Q;L=L.children[E],L.isDynamic=C,L.pattern=A}L.isEndOfWord=!0,L.path=g,L.method.push(f.method),L.handler.push(f.handler)}search(g,f){let L=this.root,$=g.split("/").filter(Boolean),A=$.length;for(let n of $){let S=n;if(!L.children[S])if(L.children[":"])L=L.children[":"];else return null;else L=L.children[S]}let C=L.path.split("/").filter(Boolean);if(A!==C.length)return null;let E=L.method.indexOf(f);if(E!==-1)return{path:L.path,handler:L.handler[E],isDynamic:L.isDynamic,pattern:L.pattern,method:L.method[E]};return null}}function J(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"}}function F(g,f,L){let $=null,A=null,C=null,E=null,n={},S=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]);return{req:g,server:f,url:L,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(G,U){return this.headers.set(G,U),this},removeHeader(G){return this.headers.delete(G),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!$)try{$=Object.fromEntries(this.url.searchParams)}catch(G){throw new Error("Failed to parse query parameters")}return $},get params(){if(!A&&this.req.routePattern)try{A=r(this.req.routePattern,this.url.pathname)}catch(G){throw new Error("Failed to extract route parameters")}return A??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!E)E=(async()=>{let G=await p(this.req);if(G.error)throw new Error(G.error);return Object.keys(G).length===0?null:G})();return E},set(G,U){return n[G]=U,this},get(G){return n[G]},text(G,U){if(U)this.status=U;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(G,{status:this.status,headers:this.headers})},send(G,U){if(U)this.status=U;let v;if(G instanceof Uint8Array)v="Uint8Array";else if(G instanceof ArrayBuffer)v="ArrayBuffer";else v=typeof G;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",S.get(v)??"text/plain; charset=utf-8");let K=v==="object"&&G!==null?JSON.stringify(G):G;return new Response(K,{status:this.status,headers:this.headers})},json(G,U){if(U)this.status=U;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(G,{status:this.status,headers:this.headers})},file(G,U,v){if(v)this.status=v;let K=Bun.file(G);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",U??J(G));return new Response(K,{status:this.status,headers:this.headers})},async ejs(G,U={},v){if(v)this.status=v;let K;try{K=await import("ejs"),K=K.default||K}catch(Y){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let Y=await Bun.file(G).text(),P=K.render(Y,U),c=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(P,{status:this.status,headers:c})}catch(Y){return console.error("EJS Rendering Error:",Y),new Response("Error rendering template",{status:500})}},redirect(G,U){if(U)this.status=U;else this.status=302;return this.headers.set("Location",G),new Response(null,{status:this.status,headers:this.headers})},stream(G){let U=new Headers(this.headers),v=new ReadableStream({async start(K){await G(K),K.close()}});return new Response(v,{headers:U})},yieldStream(G){return new Response({async*[Symbol.asyncIterator](){yield*G()}},{headers:this.headers})},setCookie(G,U,v={}){let K=`${encodeURIComponent(G)}=${encodeURIComponent(U)}`;if(v.maxAge)K+=`; Max-Age=${v.maxAge}`;if(v.expires)K+=`; Expires=${v.expires.toUTCString()}`;if(v.path)K+=`; Path=${v.path}`;if(v.domain)K+=`; Domain=${v.domain}`;if(v.secure)K+="; Secure";if(v.httpOnly)K+="; HttpOnly";if(v.sameSite)K+=`; SameSite=${v.sameSite}`;return this.headers.append("Set-Cookie",K),this},get cookies(){if(!C){let G=this.req.headers.get("cookie");C=G?s(G):{}}return C}}}function s(g){return Object.fromEntries(g.split(";").map((f)=>{let[L,...$]=f.trim().split("=");return[L,decodeURIComponent($.join("="))]}))}function r(g,f){let L={},$=g.split("/"),[A]=f.split("?"),C=A.split("/");if($.length!==C.length)return null;for(let E=0;E<$.length;E++)if($[E].startsWith(":"))L[$[E].slice(1)]=C[E];return L}async function p(g){let f=g.headers.get("Content-Type");if(!f)return{};if(g.headers.get("Content-Length")==="0"||!g.body)return{};try{if(f.startsWith("application/json"))return await g.json();if(f.startsWith("application/x-www-form-urlencoded")){let $=await g.text();return Object.fromEntries(new URLSearchParams($))}if(f.startsWith("multipart/form-data")){let $=await g.formData(),A={};for(let[C,E]of $.entries())A[C]=E;return A}return{error:"Unknown request body type"}}catch($){return{error:"Invalid request body format"}}}async function B(g,f,L,$){let A=F(g,f,L),C=$.trie.search(L.pathname,g.method);g.routePattern=C?.path;try{if($.hooks.onRequest)await I("onRequest",$.hooks.onRequest,[g,L,f]);if($.hasMiddleware){let S=await d($,L.pathname,A,f);if(S)return S}if($.hasFilterEnabled){let S=g.routePattern??L.pathname,G=await h($,S,A,f);if(G)return G}if(!C)return await a($,A,L.pathname);if($.hooks.preHandler){let S=await I("preHandler",$.hooks.preHandler,[A,f]);if(S)return S}let E=C.handler(A),n=E instanceof Promise?await E:E;if($.hasOnSendHook){let S=await I("onSend",$.hooks.onSend,[A,n,f]);if(S)return S}if(n instanceof Response)return n;return _(500,"No response returned from handler.")}catch(E){return await I("onError",$.hooks.onError,[E,g,L,f])||_(500,"Internal Server Error")}}async function I(g,f,L){if(!f?.length)return;for(let $=0;$<f.length;$++){let A=f[$](...L),C=A instanceof Promise?await A:A;if(C&&g!=="onRequest")return C}}async function d(g,f,L,$){if(g.globalMiddlewares.length){let C=await H(g.globalMiddlewares,L,$);if(C)return C}let A=g.middlewares.get(f)||[];if(A.length){let C=await H(A,L,$);if(C)return C}return null}async function H(g,f,L){for(let $ of g){let A=await $(f,L);if(A)return A}return null}async function z(g,f,L){for(let $ of g){let A=await $(f,L);if(A)return A}}async function h(g,f,L,$){let A=await t(g,f,L,$),C=A instanceof Promise?await A:A;if(C)return C}async function t(g,f,L,$){if(f.endsWith("/"))f=f.slice(0,-1);if(!g.filters.has(f))if(g.filterFunction.length)for(let A of g.filterFunction){let C=await A(L,$);if(C)return C}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function I1(g,f,L,$){if(!g.filters.has(f))if(g.filterFunction.length)for(let A of g.filterFunction){let C=await A(L,$);if(C)return C}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function a(g,f,L){if(g.staticPath){let A=await e(g,L,f);if(A)return A;let C=g.trie.search("*",f.req.method);if(C?.handler)return await C.handler(f)}return g.routeNotFoundFunc(f)||_(404,`Route not found for ${L}`)}function _(g,f){return new Response(JSON.stringify({error:f}),{status:g,headers:{"Content-Type":"application/json"}})}async function e(g,f,L){if(!g.staticPath)return null;let $=`${g.staticPath}${f}`;if(await Bun.file($).exists()){let C=J($);return L.file($,C,200)}return null}function Z(g){if(typeof g!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(g))}function R(g,f){var L="",$=0,A=-1,C=0,E;for(var n=0;n<=g.length;++n){if(n<g.length)E=g.charCodeAt(n);else if(E===47)break;else E=47;if(E===47){if(A===n-1||C===1);else if(A!==n-1&&C===2){if(L.length<2||$!==2||L.charCodeAt(L.length-1)!==46||L.charCodeAt(L.length-2)!==46){if(L.length>2){var S=L.lastIndexOf("/");if(S!==L.length-1){if(S===-1)L="",$=0;else L=L.slice(0,S),$=L.length-1-L.lastIndexOf("/");A=n,C=0;continue}}else if(L.length===2||L.length===1){L="",$=0,A=n,C=0;continue}}if(f){if(L.length>0)L+="/..";else L="..";$=2}}else{if(L.length>0)L+="/"+g.slice(A+1,n);else L=g.slice(A+1,n);$=n-A-1}A=n,C=0}else if(E===46&&C!==-1)++C;else C=-1}return L}function g1(g,f){var L=f.dir||f.root,$=f.base||(f.name||"")+(f.ext||"");if(!L)return $;if(L===f.root)return L+$;return L+g+$}function N(){var g="",f=!1,L;for(var $=arguments.length-1;$>=-1&&!f;$--){var A;if($>=0)A=arguments[$];else{if(L===void 0)L=process.cwd();A=L}if(Z(A),A.length===0)continue;g=A+"/"+g,f=A.charCodeAt(0)===47}if(g=R(g,!f),f)if(g.length>0)return"/"+g;else return"/";else if(g.length>0)return g;else return"."}function y(g){if(Z(g),g.length===0)return".";var f=g.charCodeAt(0)===47,L=g.charCodeAt(g.length-1)===47;if(g=R(g,!f),g.length===0&&!f)g=".";if(g.length>0&&L)g+="/";if(f)return"/"+g;return g}function f1(g){return Z(g),g.length>0&&g.charCodeAt(0)===47}function L1(){if(arguments.length===0)return".";var g;for(var f=0;f<arguments.length;++f){var L=arguments[f];if(Z(L),L.length>0)if(g===void 0)g=L;else g+="/"+L}if(g===void 0)return".";return y(g)}function $1(g,f){if(Z(g),Z(f),g===f)return"";if(g=N(g),f=N(f),g===f)return"";var L=1;for(;L<g.length;++L)if(g.charCodeAt(L)!==47)break;var $=g.length,A=$-L,C=1;for(;C<f.length;++C)if(f.charCodeAt(C)!==47)break;var E=f.length,n=E-C,S=A<n?A:n,G=-1,U=0;for(;U<=S;++U){if(U===S){if(n>S){if(f.charCodeAt(C+U)===47)return f.slice(C+U+1);else if(U===0)return f.slice(C+U)}else if(A>S){if(g.charCodeAt(L+U)===47)G=U;else if(U===0)G=0}break}var v=g.charCodeAt(L+U),K=f.charCodeAt(C+U);if(v!==K)break;else if(v===47)G=U}var Y="";for(U=L+G+1;U<=$;++U)if(U===$||g.charCodeAt(U)===47)if(Y.length===0)Y+="..";else Y+="/..";if(Y.length>0)return Y+f.slice(C+G);else{if(C+=G,f.charCodeAt(C)===47)++C;return f.slice(C)}}function C1(g){return g}function A1(g){if(Z(g),g.length===0)return".";var f=g.charCodeAt(0),L=f===47,$=-1,A=!0;for(var C=g.length-1;C>=1;--C)if(f=g.charCodeAt(C),f===47){if(!A){$=C;break}}else A=!1;if($===-1)return L?"/":".";if(L&&$===1)return"//";return g.slice(0,$)}function E1(g,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');Z(g);var L=0,$=-1,A=!0,C;if(f!==void 0&&f.length>0&&f.length<=g.length){if(f.length===g.length&&f===g)return"";var E=f.length-1,n=-1;for(C=g.length-1;C>=0;--C){var S=g.charCodeAt(C);if(S===47){if(!A){L=C+1;break}}else{if(n===-1)A=!1,n=C+1;if(E>=0)if(S===f.charCodeAt(E)){if(--E===-1)$=C}else E=-1,$=n}}if(L===$)$=n;else if($===-1)$=g.length;return g.slice(L,$)}else{for(C=g.length-1;C>=0;--C)if(g.charCodeAt(C)===47){if(!A){L=C+1;break}}else if($===-1)A=!1,$=C+1;if($===-1)return"";return g.slice(L,$)}}function n1(g){Z(g);var f=-1,L=0,$=-1,A=!0,C=0;for(var E=g.length-1;E>=0;--E){var n=g.charCodeAt(E);if(n===47){if(!A){L=E+1;break}continue}if($===-1)A=!1,$=E+1;if(n===46){if(f===-1)f=E;else if(C!==1)C=1}else if(f!==-1)C=-1}if(f===-1||$===-1||C===0||C===1&&f===$-1&&f===L+1)return"";return g.slice(f,$)}function G1(g){if(g===null||typeof g!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof g);return g1("/",g)}function S1(g){Z(g);var f={root:"",dir:"",base:"",ext:"",name:""};if(g.length===0)return f;var L=g.charCodeAt(0),$=L===47,A;if($)f.root="/",A=1;else A=0;var C=-1,E=0,n=-1,S=!0,G=g.length-1,U=0;for(;G>=A;--G){if(L=g.charCodeAt(G),L===47){if(!S){E=G+1;break}continue}if(n===-1)S=!1,n=G+1;if(L===46){if(C===-1)C=G;else if(U!==1)U=1}else if(C!==-1)U=-1}if(C===-1||n===-1||U===0||U===1&&C===n-1&&C===E+1){if(n!==-1)if(E===0&&$)f.base=f.name=g.slice(1,n);else f.base=f.name=g.slice(E,n)}else{if(E===0&&$)f.name=g.slice(1,C),f.base=g.slice(1,n);else f.name=g.slice(E,C),f.base=g.slice(E,n);f.ext=g.slice(C,n)}if(E>0)f.dir=g.slice(0,E-1);else if($)f.dir="/";return f}var U1="/",v1=":",K1=((g)=>(g.posix=g,g))({resolve:N,normalize:y,isAbsolute:f1,join:L1,relative:$1,_makeLong:C1,dirname:A1,basename:E1,extname:n1,format:G1,parse:S1,sep:U1,delimiter:v1,win32:null,posix:null}),V=K1;var{default:b}=(()=>({}));var X={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"}},T=(g,f,L)=>{let $=X[g]||X.reset,A=L?.method?X.method[L.method]||X.reset:X.reset,C=L?.status?L.status>=500?X.error:L.status>=400?X.warn:X.info:X.reset;console.log(`
1
+ var c=Object.create;var{getPrototypeOf:k,defineProperty:R,getOwnPropertyNames:u}=Object;var x=Object.prototype.hasOwnProperty;var i=(g,f,L)=>{L=g!=null?c(k(g)):{};let $=f||!g||!g.__esModule?R(L,"default",{value:g,enumerable:!0}):L;for(let A of u(g))if(!x.call($,A))R($,A,{get:()=>g[A],enumerable:!0});return $};var o=((g)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(g,{get:(f,L)=>(typeof require!=="undefined"?require:f)[L]}):g)(function(g){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+g+'" is not supported')});class Q{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 D{root;constructor(){this.root=new Q}insert(g,f){let L=this.root,$=g.split("/").filter(Boolean);if(g==="/"){L.isEndOfWord=!0,L.handler.push(f.handler),L.path=g,L.method.push(f.method);return}for(let A of $){let C=!1,E=A;if(A.startsWith(":"))C=!0,E=":";if(!L.children[E])L.children[E]=new Q;L=L.children[E],L.isDynamic=C,L.pattern=A}L.isEndOfWord=!0,L.path=g,L.method.push(f.method),L.handler.push(f.handler)}search(g,f){let L=this.root,$=g.split("/").filter(Boolean),A=$.length;for(let G of $){let v=G;if(!L.children[v])if(L.children[":"])L=L.children[":"];else return null;else L=L.children[v]}let C=L.path.split("/").filter(Boolean);if(A!==C.length)return null;let E=L.method.indexOf(f);if(E!==-1)return{path:L.path,handler:L.handler[E],isDynamic:L.isDynamic,pattern:L.pattern,method:L.method[E]};return null}}function W(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"}}function I(g,f,L){let $=null,A=null,C=null,E=null,G={};return{req:g,server:f,url:L,status:200,headers:new Headers,setHeader(v,S){return this.headers.set(v,S),this},removeHeader(v){return this.headers.delete(v),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!$)try{$=Object.fromEntries(this.url.searchParams)}catch(v){throw new Error("Failed to parse query parameters")}return $},get params(){if(!A&&this.req.routePattern)try{A=s(this.req.routePattern,this.url.pathname)}catch(v){throw new Error("Failed to extract route parameters")}return A??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!E)E=(async()=>{let v=await r(this.req);if(v.error)throw new Error(v.error);return Object.keys(v).length===0?null:v})();return E},set(v,S){return G[v]=S,this},get(v){return G[v]},text(v,S){if(S)this.status=S;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(v,{status:this.status,headers:this.headers})},send(v,S){if(S)this.status=S;let U=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),K;if(v instanceof Uint8Array)K="Uint8Array";else if(v instanceof ArrayBuffer)K="ArrayBuffer";else K=typeof v;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",U.get(K)??"text/plain; charset=utf-8");let Z=K==="object"&&v!==null?JSON.stringify(v):v;return new Response(Z,{status:this.status,headers:this.headers})},json(v,S){if(S)this.status=S;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(v,{status:this.status,headers:this.headers})},file(v,S,U){if(U)this.status=U;let K=Bun.file(v);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",S??W(v));return new Response(K,{status:this.status,headers:this.headers})},async ejs(v,S={},U){if(U)this.status=U;let K;try{K=await import("ejs"),K=K.default||K}catch(Z){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let Z=await Bun.file(v).text(),z=K.render(Z,S),P=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(z,{status:this.status,headers:P})}catch(Z){return console.error("EJS Rendering Error:",Z),new Response("Error rendering template",{status:500})}},redirect(v,S){if(S)this.status=S;else this.status=302;return this.headers.set("Location",v),new Response(null,{status:this.status,headers:this.headers})},stream(v){let S=new Headers(this.headers),U=new ReadableStream({async start(K){await v(K),K.close()}});return new Response(U,{headers:S})},yieldStream(v){return new Response({async*[Symbol.asyncIterator](){yield*v()}},{headers:this.headers})},setCookie(v,S,U={}){let K=`${encodeURIComponent(v)}=${encodeURIComponent(S)}`;if(U.maxAge)K+=`; Max-Age=${U.maxAge}`;if(U.expires)K+=`; Expires=${U.expires.toUTCString()}`;if(U.path)K+=`; Path=${U.path}`;if(U.domain)K+=`; Domain=${U.domain}`;if(U.secure)K+="; Secure";if(U.httpOnly)K+="; HttpOnly";if(U.sameSite)K+=`; SameSite=${U.sameSite}`;return this.headers.append("Set-Cookie",K),this},get cookies(){if(!C){let v=this.req.headers.get("cookie");C=v?l(v):{}}return C}}}function l(g){return Object.fromEntries(g.split(";").map((f)=>{let[L,...$]=f.trim().split("=");return[L,decodeURIComponent($.join("="))]}))}function s(g,f){let L={},$=g.split("/"),[A]=f.split("?"),C=A.split("/");if($.length!==C.length)return null;for(let E=0;E<$.length;E++)if($[E].startsWith(":"))L[$[E].slice(1)]=C[E];return L}async function r(g){let f=g.headers.get("Content-Type");if(!f)return{};if(g.headers.get("Content-Length")==="0"||!g.body)return{};try{if(f.startsWith("application/json"))return await g.json();if(f.startsWith("application/x-www-form-urlencoded")){let $=await g.text();return Object.fromEntries(new URLSearchParams($))}if(f.startsWith("multipart/form-data")){let $=await g.formData(),A={};for(let[C,E]of $.entries())A[C]=E;return A}return{error:"Unknown request body type"}}catch($){return{error:"Invalid request body format"}}}async function F(g,f,L,$){let A=I(g,f,L),C=$.trie.search(L.pathname,g.method);g.routePattern=C?.path;try{if($.hooks.onRequest)await J("onRequest",$.hooks.onRequest,[g,L,f]);if($.hasMiddleware){let v=await p($,L.pathname,A,f);if(v)return v}if($.hasFilterEnabled){let v=g.routePattern??L.pathname,S=await d($,v,A,f);if(S)return S}if(!C)return await t($,A,L.pathname);if($.hooks.preHandler){let v=await J("preHandler",$.hooks.preHandler,[A,f]);if(v)return v}let E=C.handler(A),G=E instanceof Promise?await E:E;if($.hasOnSendHook){let v=await J("onSend",$.hooks.onSend,[A,G,f]);if(v)return v}if(G instanceof Response)return G;return B(500,"No response returned from handler.")}catch(E){return await J("onError",$.hooks.onError,[E,g,L,f])||B(500,"Internal Server Error")}}async function J(g,f,L){if(!f?.length)return;for(let $=0;$<f.length;$++){let A=f[$](...L),C=A instanceof Promise?await A:A;if(C&&g!=="onRequest")return C}}async function p(g,f,L,$){if(g.globalMiddlewares.length){let C=await H(g.globalMiddlewares,L,$);if(C)return C}let A=g.middlewares.get(f)||[];if(A.length){let C=await H(A,L,$);if(C)return C}return null}async function H(g,f,L){for(let $ of g){let A=await $(f,L);if(A)return A}return null}async function _(g,f,L){for(let $ of g){let A=await $(f,L);if(A)return A}}async function d(g,f,L,$){let A=await h(g,f,L,$),C=A instanceof Promise?await A:A;if(C)return C}async function h(g,f,L,$){if(f.endsWith("/"))f=f.slice(0,-1);if(!g.filters.has(f))if(g.filterFunction.length)for(let A of g.filterFunction){let C=await A(L,$);if(C)return C}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function J1(g,f,L,$){if(!g.filters.has(f))if(g.filterFunction.length)for(let A of g.filterFunction){let C=await A(L,$);if(C)return C}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function t(g,f,L){if(g.staticPath){let A=await a(g,L,f);if(A)return A;let C=g.trie.search("*",f.req.method);if(C?.handler)return await C.handler(f)}return g.routeNotFoundFunc(f)||B(404,`Route not found for ${L}`)}function B(g,f){return new Response(JSON.stringify({error:f}),{status:g,headers:{"Content-Type":"application/json"}})}async function a(g,f,L){if(!g.staticPath)return null;let $=`${g.staticPath}${f}`;if(await Bun.file($).exists()){let C=W($);return L.file($,C,200)}return null}function Y(g){if(typeof g!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(g))}function M(g,f){var L="",$=0,A=-1,C=0,E;for(var G=0;G<=g.length;++G){if(G<g.length)E=g.charCodeAt(G);else if(E===47)break;else E=47;if(E===47){if(A===G-1||C===1);else if(A!==G-1&&C===2){if(L.length<2||$!==2||L.charCodeAt(L.length-1)!==46||L.charCodeAt(L.length-2)!==46){if(L.length>2){var v=L.lastIndexOf("/");if(v!==L.length-1){if(v===-1)L="",$=0;else L=L.slice(0,v),$=L.length-1-L.lastIndexOf("/");A=G,C=0;continue}}else if(L.length===2||L.length===1){L="",$=0,A=G,C=0;continue}}if(f){if(L.length>0)L+="/..";else L="..";$=2}}else{if(L.length>0)L+="/"+g.slice(A+1,G);else L=g.slice(A+1,G);$=G-A-1}A=G,C=0}else if(E===46&&C!==-1)++C;else C=-1}return L}function e(g,f){var L=f.dir||f.root,$=f.base||(f.name||"")+(f.ext||"");if(!L)return $;if(L===f.root)return L+$;return L+g+$}function N(){var g="",f=!1,L;for(var $=arguments.length-1;$>=-1&&!f;$--){var A;if($>=0)A=arguments[$];else{if(L===void 0)L=process.cwd();A=L}if(Y(A),A.length===0)continue;g=A+"/"+g,f=A.charCodeAt(0)===47}if(g=M(g,!f),f)if(g.length>0)return"/"+g;else return"/";else if(g.length>0)return g;else return"."}function j(g){if(Y(g),g.length===0)return".";var f=g.charCodeAt(0)===47,L=g.charCodeAt(g.length-1)===47;if(g=M(g,!f),g.length===0&&!f)g=".";if(g.length>0&&L)g+="/";if(f)return"/"+g;return g}function g1(g){return Y(g),g.length>0&&g.charCodeAt(0)===47}function f1(){if(arguments.length===0)return".";var g;for(var f=0;f<arguments.length;++f){var L=arguments[f];if(Y(L),L.length>0)if(g===void 0)g=L;else g+="/"+L}if(g===void 0)return".";return j(g)}function L1(g,f){if(Y(g),Y(f),g===f)return"";if(g=N(g),f=N(f),g===f)return"";var L=1;for(;L<g.length;++L)if(g.charCodeAt(L)!==47)break;var $=g.length,A=$-L,C=1;for(;C<f.length;++C)if(f.charCodeAt(C)!==47)break;var E=f.length,G=E-C,v=A<G?A:G,S=-1,U=0;for(;U<=v;++U){if(U===v){if(G>v){if(f.charCodeAt(C+U)===47)return f.slice(C+U+1);else if(U===0)return f.slice(C+U)}else if(A>v){if(g.charCodeAt(L+U)===47)S=U;else if(U===0)S=0}break}var K=g.charCodeAt(L+U),Z=f.charCodeAt(C+U);if(K!==Z)break;else if(K===47)S=U}var z="";for(U=L+S+1;U<=$;++U)if(U===$||g.charCodeAt(U)===47)if(z.length===0)z+="..";else z+="/..";if(z.length>0)return z+f.slice(C+S);else{if(C+=S,f.charCodeAt(C)===47)++C;return f.slice(C)}}function $1(g){return g}function C1(g){if(Y(g),g.length===0)return".";var f=g.charCodeAt(0),L=f===47,$=-1,A=!0;for(var C=g.length-1;C>=1;--C)if(f=g.charCodeAt(C),f===47){if(!A){$=C;break}}else A=!1;if($===-1)return L?"/":".";if(L&&$===1)return"//";return g.slice(0,$)}function A1(g,f){if(f!==void 0&&typeof f!=="string")throw new TypeError('"ext" argument must be a string');Y(g);var L=0,$=-1,A=!0,C;if(f!==void 0&&f.length>0&&f.length<=g.length){if(f.length===g.length&&f===g)return"";var E=f.length-1,G=-1;for(C=g.length-1;C>=0;--C){var v=g.charCodeAt(C);if(v===47){if(!A){L=C+1;break}}else{if(G===-1)A=!1,G=C+1;if(E>=0)if(v===f.charCodeAt(E)){if(--E===-1)$=C}else E=-1,$=G}}if(L===$)$=G;else if($===-1)$=g.length;return g.slice(L,$)}else{for(C=g.length-1;C>=0;--C)if(g.charCodeAt(C)===47){if(!A){L=C+1;break}}else if($===-1)A=!1,$=C+1;if($===-1)return"";return g.slice(L,$)}}function E1(g){Y(g);var f=-1,L=0,$=-1,A=!0,C=0;for(var E=g.length-1;E>=0;--E){var G=g.charCodeAt(E);if(G===47){if(!A){L=E+1;break}continue}if($===-1)A=!1,$=E+1;if(G===46){if(f===-1)f=E;else if(C!==1)C=1}else if(f!==-1)C=-1}if(f===-1||$===-1||C===0||C===1&&f===$-1&&f===L+1)return"";return g.slice(f,$)}function v1(g){if(g===null||typeof g!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof g);return e("/",g)}function G1(g){Y(g);var f={root:"",dir:"",base:"",ext:"",name:""};if(g.length===0)return f;var L=g.charCodeAt(0),$=L===47,A;if($)f.root="/",A=1;else A=0;var C=-1,E=0,G=-1,v=!0,S=g.length-1,U=0;for(;S>=A;--S){if(L=g.charCodeAt(S),L===47){if(!v){E=S+1;break}continue}if(G===-1)v=!1,G=S+1;if(L===46){if(C===-1)C=S;else if(U!==1)U=1}else if(C!==-1)U=-1}if(C===-1||G===-1||U===0||U===1&&C===G-1&&C===E+1){if(G!==-1)if(E===0&&$)f.base=f.name=g.slice(1,G);else f.base=f.name=g.slice(E,G)}else{if(E===0&&$)f.name=g.slice(1,C),f.base=g.slice(1,G);else f.name=g.slice(E,C),f.base=g.slice(E,G);f.ext=g.slice(C,G)}if(E>0)f.dir=g.slice(0,E-1);else if($)f.dir="/";return f}var S1="/",U1=":",K1=((g)=>(g.posix=g,g))({resolve:N,normalize:j,isAbsolute:g1,join:f1,relative:L1,_makeLong:$1,dirname:C1,basename:A1,extname:E1,format:v1,parse:G1,sep:S1,delimiter:U1,win32:null,posix:null}),V=K1;var{default:b}=(()=>({}));var X={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"}},T=(g,f,L)=>{let $=X[g]||X.reset,A=L?.method?X.method[L.method]||X.reset:X.reset,C=L?.status?L.status>=500?X.error:L.status>=400?X.warn:X.info:X.reset;console.log(`
2
2
  ${$}[${g.toUpperCase()}]${X.reset} ${f} - ${A}${L?.method||""}${X.reset}`);let E={timestamp:new Date().toISOString(),...L,status:L?.status?`${C}${L.status}${X.reset}`:void 0,method:L?.method?`${A>$}${L.method}${X.reset}`:void 0};console.log(JSON.stringify(E,null,2)+`
3
- `)},M=(g)=>{let{app:f,logger:L,logLevel:$="info",onRequest:A,onSend:C,onError:E}=g||{};f?.addHooks("onRequest",(n,S)=>{n.startTime=Date.now(),L?.()??T($,"Incoming Request",{method:n.method,url:S.toString(),headers:{"user-agent":n.headers.get("user-agent"),"content-type":n.headers.get("content-type")}}),A?.(n,S)}),f?.addHooks("onSend",async(n)=>{let S=`${Date.now()-n.req.startTime}ms`;L?.()??T($,"Response Sent",{method:n.req.method,url:n.url.toString(),status:n.status,duration:S,reqId:n.get?.("requestId"),headers:{"content-type":n.headers.get("content-type")}});let G=await C?.(n);if(G instanceof Response)return G}),f?.addHooks("onError",async(n,S,G)=>{L?.()??T("error","Unhandled Error",{method:S.method,url:G.toString(),status:500,error:n.message});let U=await E?.(n,S,G);if(U instanceof Response)return U})},O=(g,f,L,$=0,A,C)=>{let E=X.method[f]||X.reset,n=$>=500?X.error:$>=400?X.warn:X.info,S=C?`[${C}] `:"",G=g==="<--"?`${g} ${E}${f}${X.reset} ${L} ${S}`:`${g} ${E}${f}${X.reset} ${L} ${n}${$}${X.reset} ${A??""} ${S}`;console.log(G)},X1=(g)=>{let f=Date.now()-g;return f<1000?`${f}ms`:`${Math.round(f/1000)}s`},q=(g)=>{let{app:f,log:L,onRequest:$,onSend:A,onError:C}=g;f.addHooks("onRequest",(E,n)=>{E.startTime=Date.now(),L?.()??O("<--",E.method,n.pathname),$?.(E,n)}),f.addHooks("onSend",async(E)=>{let{method:n,url:S}=E.req,G=new URL(S).pathname,U=E.get?.("requestId");L?.()??O("-->",n,G,E.status,X1(E.req.startTime),U);let v=await A?.(E);if(v instanceof Response)return v}),f.addHooks("onError",async(E,n,S)=>{L?.()??O(E.message,n.method,S.toString(),500);let G=await C?.(E,n,S);if(G instanceof Response)return G})};function m(g,f){if(!g)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(L)=>{try{let $=L.cookies?.accessToken??L.req?.headers?.get("Authorization");if(!$)return L.json({message:"Unauthorized",error:"No token provided"},401);if($.startsWith("Bearer "))$=$.slice(7);let A=g?.verify($,f);if(!A)return L.json({message:"Unauthorized",error:"Token could not be decoded"},401);L.set("user",A)}catch($){let A="Invalid token";if($.name==="TokenExpiredError")A="Token expired";else if($.name==="JsonWebTokenError")A="Malformed or tampered token";return L.json({message:"Unauthorized",error:A},401)}}}function w(g,f,L){if(!g)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!f)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async($)=>{try{let A=$.cookies?.accessToken??$.req?.headers?.get("Authorization");if(!A)return $.json({message:"Unauthorized",error:"No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let C=g?.verify(A,L);if(!C)return $.json({message:"Unauthorized",error:"Token could not be decoded"},401);let E=await f.findById(C._id).select("-password -refreshToken");if(!E)return $.json({message:"Unauthorized: User not found"},404);$.set("user",E);return}catch(A){let C="Invalid token";if(A.name==="TokenExpiredError")C="Token expired";else if(A.name==="JsonWebTokenError")C="Malformed or tampered token";return $.json({message:"Unauthorized",error:C},401)}}}class D{static instance;fecth;routes;tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;constructor({jwtSecret:g,baseApiUrl:f,enableFileRouting:L,idleTimeOut:$,prefixApiUrl:A}={}){if(!D.instance)D.instance=this;this.prefixApiUrl=A??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=$??10,this.enableFileRouter=L??!1,this.baseApiUrl=f||"",this.user_jwt_secret=g||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new W,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={},this.routeNotFoundFunc=()=>{}}static router(g){if(this.instance.prefixApiUrl=g,!this.instance)console.log("no instance"),this.instance=new D;return this.instance}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...g)=>{return this.FilterRoutes=g,this.setupFilter()},permitAll:()=>{for(let g of this?.FilterRoutes){if(g.endsWith("/"))g=g.slice(0,-1);this.filters.add(g)}return this.FilterRoutes=null,this.setupFilter()},authenticate:(g)=>{if(g?.length)for(let f of g)this.filterFunction.push(f)},authenticateJwt:(g)=>{this.filterFunction.push(m(g,this.user_jwt_secret))},authenticateJwtDB:(g,f)=>{this.filterFunction.push(w(g,f,this.user_jwt_secret))}}}redirect(g,f,L){return this.any(g,($)=>{let A=$.params,C=f;if(A)for(let n in A)C=C.replace(`:${n}`,A[n]);let E=$.url.search;if(E)C+=E;return $.redirect(C,L)}),this}serveStatic(g){return this.staticPath=g,this}static(g){return this.staticPath=g,this}staticHtml(g){return this.staticFiles={...this.staticFiles,...g},this}addHooks(g,f){if(typeof g!=="string")throw new Error("hookName must be a string");if(typeof f!=="function")throw new Error("callback must be a instance of function");switch(g){case"onRequest":this.hooks.onRequest?.push(f);break;case"preHandler":this.hooks.preHandler?.push(f);break;case"postHandler":this.hooks.postHandler?.push(f);break;case"onSend":this.hooks.onSend?.push(f);break;case"onError":this.hooks.onError?.push(f);break;case"onClose":this.hooks.onClose?.push(f);break;default:throw new Error(`Unknown hook type: ${g}`)}return this}compile(){if(this?.globalMiddlewares?.length>0)this.hasMiddleware=!0;for(let[g,f]of this?.middlewares.entries())if(f.length>0){this.hasMiddleware=!0;break}if(this?.enableFileRouter){let g=process.cwd(),f=V.join(g,"src","routes");if(b?.existsSync(f))this.loadRoutes(f,"")}setTimeout(()=>{this.tempRoutes=null},2000)}async registerFileRoutes(g,f,L){let $=await import(g),A;if(L===".ts")A=V.basename(g,".ts");else if(L===".js")A=V.basename(g,".js");let C=f+"/"+A;if(C.endsWith("/index"))C=f;else if(C.endsWith("/api"))C=f;C=C.replace(/\[(.*?)\]/g,":$1");let E=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let n of E)if($[n]){let S=n.toLowerCase(),G=$[n];this[S](`${this.baseApiUrl}${C}`,G)}}async loadRoutes(g,f){let L=await b.promises.readdir(g);for(let $ of L){let A=V.join(g,$);if((await b.promises.stat(A)).isDirectory())this.loadRoutes(A,f+"/"+$);else if($.endsWith(".ts"))this.registerFileRoutes(A,f,".ts");else if($.endsWith(".js"))this.registerFileRoutes(A,f,".js")}}useLogger(g){return q(g),this}useAdvancedLogger(g){return M(g),this}BunRoute(g,f,...L){if(!f||typeof f!=="string")throw new Error("give a path in string format");if(L.length===1){let $=L[0];this.routes[f]=async(A,C)=>{if(this.hasMiddleware){if(this.globalMiddlewares.length){let S=await z(this.globalMiddlewares,A,C);if(S)return S}let n=this.middlewares.get(f)||[];if(n?.length){let S=await z(n,A,C);if(S)return S}}if(g!==A.method)return new Response("Method Not Allowed",{status:405});let E=await $(A,C);if(E instanceof Promise)return await E??new Response("Not Found",{status:404});return E??new Response("Not Found",{status:404})}}else this.routes[f]=async($,A)=>{if(this.hasMiddleware){if(this.globalMiddlewares.length){let E=await z(this.globalMiddlewares,$,A);if(E)return E}let C=this.middlewares.get(f)||[];if(C?.length){let E=await z(C,$,A);if(E)return E}}if(g!==$.method)return new Response("Method Not Allowed",{status:405});for(let C=0;C<L.length;C++){let E=L[C]($,A);if(E instanceof Promise)return await E??new Response("Not Found",{status:404});return E??new Response("Not Found",{status:404})}}}listen(g,...f){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let L="0.0.0.0",$=void 0,A={};for(let E of f)if(typeof E==="string")L=E;else if(typeof E==="function")$=E;else if(typeof E==="object"&&E!==null)A=E;this.compile();let C={port:g,hostname:L,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)C.routes=this.routes;if(A.cert&&A.key)C.certFile=A.cert,C.keyFile=A.key;if(this.serverInstance=Bun?.serve(C),$)return $();return this.serverInstance}fetch(){return this.compile(),async(g,f)=>{let L=new URL(g.url);return B(g,f,L,this)}}close(g){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,g?g():console.log("Server has been stopped");else console.warn("Server is not running.")}route(g,f){g=g&&g.length>0?g:f?.prefixApiUrl;let L=Object.fromEntries(f.tempRoutes);return Object.entries(L).forEach(([A,C])=>{let E=A.replace(/::\w+$/,""),n=`${g}${E}`;if(!this.middlewares.has(n))this.middlewares.set(n,[]);C.handlers.slice(0,-1).forEach((v)=>{if(!this.middlewares.get(n)?.includes(v))this.middlewares.get(n)?.push(v)});let G=C.handlers[C.handlers.length-1],U=C.method;try{this.trie.insert(n,{handler:G,method:U})}catch(v){console.error(`Error inserting ${n}:`,v)}}),this}register(g,f){return this.route(g,f)}addRoute(g,f,L){if(typeof f!=="string")throw new Error(`Error in ${L[L.length-1]}: Path must be a string. Received: ${typeof f}`);if(typeof g!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof g}`);this.tempRoutes?.set(f+"::"+g,{method:g,handlers:L});let $=L.slice(0,-1),A=L[L.length-1];if(!this.middlewares.has(f))this.middlewares.set(f,[]);$.forEach((C)=>{if(f==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...$])];else if(!this.middlewares.get(f)?.includes(C))this.middlewares.get(f)?.push(C)});try{if(g==="ANY"){let C=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let E of C)this.trie.insert(f,{handler:A,method:E})}this.trie.insert(f,{handler:A,method:g})}catch(C){console.error(`Error inserting ${f}:`,C)}}use(g,f){if(Array.isArray(g))g.forEach(($)=>{if(typeof $==="function")this.globalMiddlewares.push($)});if(typeof g==="function"){if(this.globalMiddlewares.push(g),Array.isArray(f))f.forEach(($)=>{this.globalMiddlewares.push($)});return this}return(Array.isArray(g)?g.filter(($)=>typeof $==="string"):[g].filter(($)=>typeof $==="string")).forEach(($)=>{if(!this.middlewares.has($))this.middlewares.set($,[]);if(f)(Array.isArray(f)?f:[f]).forEach((C)=>{this.middlewares.get($)?.push(C)})}),this}get(g,...f){return this.addRoute("GET",g,f),this}post(g,...f){return this.addRoute("POST",g,f),this}put(g,...f){return this.addRoute("PUT",g,f),this}patch(g,...f){return this.addRoute("PATCH",g,f),this}delete(g,...f){return this.addRoute("DELETE",g,f),this}any(g,...f){return this.addRoute("ANY",g,f),this}head(g,...f){return this.addRoute("HEAD",g,f),this}options(g,...f){return this.addRoute("OPTIONS",g,f),this}propfind(g,...f){return this.addRoute("PROPFIND",g,f),this}routeNotFound(g){return this.routeNotFoundFunc=g,this}on(g,f,...L){let $=Array.isArray(g)?g:[g];for(let A of $){let C=A.toUpperCase();if(C.toLocaleLowerCase()in this)this[C.toLocaleLowerCase()](f,...L);else this.addRoute(C,f,L)}}}export{D as default};
3
+ `)},q=(g)=>{let{app:f,logger:L,logLevel:$="info",onRequest:A,onSend:C,onError:E}=g||{};f?.addHooks("onRequest",(G,v)=>{G.startTime=Date.now(),L?.()??T($,"Incoming Request",{method:G.method,url:v.toString(),headers:{"user-agent":G.headers.get("user-agent"),"content-type":G.headers.get("content-type")}}),A?.(G,v)}),f?.addHooks("onSend",async(G)=>{let v=`${Date.now()-G.req.startTime}ms`;L?.()??T($,"Response Sent",{method:G.req.method,url:G.url.toString(),status:G.status,duration:v,reqId:G.get?.("requestId"),headers:{"content-type":G.headers.get("content-type")}});let S=await C?.(G);if(S instanceof Response)return S}),f?.addHooks("onError",async(G,v,S)=>{L?.()??T("error","Unhandled Error",{method:v.method,url:S.toString(),status:500,error:G.message});let U=await E?.(G,v,S);if(U instanceof Response)return U})},O=(g,f,L,$=0,A,C)=>{let E=X.method[f]||X.reset,G=$>=500?X.error:$>=400?X.warn:X.info,v=C?`[${C}] `:"",S=g==="<--"?`${g} ${E}${f}${X.reset} ${L} ${v}`:`${g} ${E}${f}${X.reset} ${L} ${G}${$}${X.reset} ${A??""} ${v}`;console.log(S)},X1=(g)=>{let f=Date.now()-g;return f<1000?`${f}ms`:`${Math.round(f/1000)}s`},y=(g)=>{let{app:f,log:L,onRequest:$,onSend:A,onError:C}=g;f.addHooks("onRequest",(E,G)=>{E.startTime=Date.now(),L?.()??O("<--",E.method,G.pathname),$?.(E,G)}),f.addHooks("onSend",async(E)=>{let{method:G,url:v}=E.req,S=new URL(v).pathname,U=E.get?.("requestId");L?.()??O("-->",G,S,E.status,X1(E.req.startTime),U);let K=await A?.(E);if(K instanceof Response)return K}),f.addHooks("onError",async(E,G,v)=>{L?.()??O(E.message,G.method,v.toString(),500);let S=await C?.(E,G,v);if(S instanceof Response)return S})};function w(g,f){if(!g)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(L)=>{try{let $=L.cookies?.accessToken??L.req?.headers?.get("Authorization");if(!$)return L.json({message:"Unauthorized",error:"No token provided"},401);if($.startsWith("Bearer "))$=$.slice(7);let A=g?.verify($,f);if(!A)return L.json({message:"Unauthorized",error:"Token could not be decoded"},401);L.set("user",A)}catch($){let A="Invalid token";if($.name==="TokenExpiredError")A="Token expired";else if($.name==="JsonWebTokenError")A="Malformed or tampered token";return L.json({message:"Unauthorized",error:A},401)}}}function m(g,f,L){if(!g)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!f)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async($)=>{try{let A=$.cookies?.accessToken??$.req?.headers?.get("Authorization");if(!A)return $.json({message:"Unauthorized",error:"No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let C=g?.verify(A,L);if(!C)return $.json({message:"Unauthorized",error:"Token could not be decoded"},401);let E=await f.findById(C._id).select("-password -refreshToken");if(!E)return $.json({message:"Unauthorized: User not found"},404);$.set("user",E);return}catch(A){let C="Invalid token";if(A.name==="TokenExpiredError")C="Token expired";else if(A.name==="JsonWebTokenError")C="Malformed or tampered token";return $.json({message:"Unauthorized",error:C},401)}}}class n{static instance;fecth;routes;tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;constructor({jwtSecret:g,baseApiUrl:f,enableFileRouting:L,idleTimeOut:$,prefixApiUrl:A}={}){if(!n.instance)n.instance=this;this.prefixApiUrl=A??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=$??10,this.enableFileRouter=L??!1,this.baseApiUrl=f||"",this.user_jwt_secret=g||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",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:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={},this.routeNotFoundFunc=()=>{}}static router(g){if(!this.instance)console.log("no instance"),this.instance=new n;return new Proxy(this.instance,{get(f,L,$){return(A,C)=>{let E=g+A;return f[L](E,C)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...g)=>{return this.FilterRoutes=g,this.setupFilter()},permitAll:()=>{for(let g of this?.FilterRoutes){if(g.endsWith("/"))g=g.slice(0,-1);this.filters.add(g)}return this.FilterRoutes=null,this.setupFilter()},authenticate:(g)=>{if(g?.length)for(let f of g)this.filterFunction.push(f)},authenticateJwt:(g)=>{this.filterFunction.push(w(g,this.user_jwt_secret))},authenticateJwtDB:(g,f)=>{this.filterFunction.push(m(g,f,this.user_jwt_secret))}}}redirect(g,f,L){return this.any(g,($)=>{let A=$.params,C=f;if(A)for(let G in A)C=C.replace(`:${G}`,A[G]);let E=$.url.search;if(E)C+=E;return $.redirect(C,L)}),this}serveStatic(g){return this.staticPath=g,this}static(g){return this.staticPath=g,this}staticHtml(g){return this.staticFiles={...this.staticFiles,...g},this}addHooks(g,f){if(typeof g!=="string")throw new Error("hookName must be a string");if(typeof f!=="function")throw new Error("callback must be a instance of function");switch(g){case"onRequest":this.hooks.onRequest?.push(f);break;case"preHandler":this.hooks.preHandler?.push(f);break;case"postHandler":this.hooks.postHandler?.push(f);break;case"onSend":this.hooks.onSend?.push(f);break;case"onError":this.hooks.onError?.push(f);break;case"onClose":this.hooks.onClose?.push(f);break;default:throw new Error(`Unknown hook type: ${g}`)}return this}compile(){if(this?.globalMiddlewares?.length>0)this.hasMiddleware=!0;for(let[g,f]of this?.middlewares?.entries())if(f.length>0){this.hasMiddleware=!0;break}if(this?.enableFileRouter){let g=process.cwd(),f=V.join(g,"src","routes");if(b?.existsSync(f))this.loadRoutes(f,"")}setTimeout(()=>{this.tempRoutes=null},2000)}async registerFileRoutes(g,f,L){let $=await import(g),A;if(L===".ts")A=V.basename(g,".ts");else if(L===".js")A=V.basename(g,".js");let C=f+"/"+A;if(C.endsWith("/index"))C=f;else if(C.endsWith("/api"))C=f;C=C.replace(/\[(.*?)\]/g,":$1");let E=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let G of E)if($[G]){let v=G.toLowerCase(),S=$[G];this[v](`${this.baseApiUrl}${C}`,S)}}async loadRoutes(g,f){let L=await b.promises.readdir(g);for(let $ of L){let A=V.join(g,$);if((await b.promises.stat(A)).isDirectory())await this.loadRoutes(A,f+"/"+$);else if($.endsWith(".ts"))await this.registerFileRoutes(A,f,".ts");else if($.endsWith(".js"))await this.registerFileRoutes(A,f,".js")}}useLogger(g){return y(g),this}useAdvancedLogger(g){return q(g),this}BunRoute(g,f,...L){if(!f||typeof f!=="string")throw new Error("give a path in string format");this.routes[f]=async($,A)=>{if(this.hasMiddleware){if(this.globalMiddlewares.length){let E=await _(this.globalMiddlewares,$,A);if(E)return E}let C=this.middlewares.get(f)||[];if(C?.length){let E=await _(C,$,A);if(E)return E}}if(g!==$.method)return new Response("Method Not Allowed",{status:405});if(L.length===1){let C=L[0]($,A);if(C instanceof Promise)return await C??new Response("Not Found",{status:404});if(C instanceof Response)return C}else for(let C=0;C<L.length;C++){let E=L[C]($,A);if(E instanceof Promise)return await E??new Response("Not Found",{status:404});if(E instanceof Response)return E}}}listen(g,...f){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let L="0.0.0.0",$=void 0,A={};for(let E of f)if(typeof E==="string")L=E;else if(typeof E==="function")$=E;else if(typeof E==="object"&&E!==null)A=E;let C={port:g,hostname:L,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)C.routes=this.routes;if(A.cert&&A.key)C.certFile=A.cert,C.keyFile=A.key;if(this.serverInstance=Bun?.serve(C),$)$();return this.serverInstance}fetch(){return this.compile(),async(g,f)=>{let L=new URL(g.url);return F(g,f,L,this)}}close(g){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,g?g():console.log("Server has been stopped");else console.warn("Server is not running.")}route(g,f){g=g&&g.length>0?g:f?.prefixApiUrl;let L=f?.tempRoutes??new Map;for(let[$,A]of L.entries()){let C=$.replace(/::\w+$/,""),E=`${g}${C}`;if(!this.middlewares.has(E))this.middlewares.set(E,[]);A.handlers.slice(0,-1).forEach((U)=>{let K=this.middlewares.get(E);if(!K.includes(U))K.push(U)});let v=A.handlers[A.handlers.length-1],S=A.method;try{this.trie.insert(E,{handler:v,method:S})}catch(U){console.error(`Error inserting ${E}:`,U)}}return f=null,this}register(g,f){return this.route(g,f)}addRoute(g,f,L){if(typeof f!=="string")throw new Error(`Error in ${L[L.length-1]}: Path must be a string. Received: ${typeof f}`);if(typeof g!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof g}`);this.tempRoutes?.set(f+"::"+g,{method:g,handlers:L});let $=L.slice(0,-1),A=L[L.length-1];if(!this.middlewares.has(f))this.middlewares.set(f,[]);$.forEach((C)=>{if(f==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...$])];else if(!this.middlewares.get(f)?.includes(C))this.middlewares.get(f)?.push(C)});try{if(g==="ANY"){let C=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let E of C)this.trie.insert(f,{handler:A,method:E})}this.trie.insert(f,{handler:A,method:g})}catch(C){console.error(`Error inserting ${f}:`,C)}}use(g,f){if(Array.isArray(g))g.forEach(($)=>{if(typeof $==="function")this.globalMiddlewares.push($)});if(typeof g==="function"){if(this.globalMiddlewares.push(g),Array.isArray(f))f.forEach(($)=>{this.globalMiddlewares.push($)});return this}return(Array.isArray(g)?g.filter(($)=>typeof $==="string"):[g].filter(($)=>typeof $==="string")).forEach(($)=>{if(!this.middlewares.has($))this.middlewares.set($,[]);if(f)(Array.isArray(f)?f:[f]).forEach((C)=>{this.middlewares.get($)?.push(C)})}),this}get(g,...f){return this.addRoute("GET",g,f),this}post(g,...f){return this.addRoute("POST",g,f),this}put(g,...f){return this.addRoute("PUT",g,f),this}patch(g,...f){return this.addRoute("PATCH",g,f),this}delete(g,...f){return this.addRoute("DELETE",g,f),this}any(g,...f){return this.addRoute("ANY",g,f),this}head(g,...f){return this.addRoute("HEAD",g,f),this}options(g,...f){return this.addRoute("OPTIONS",g,f),this}propfind(g,...f){return this.addRoute("PROPFIND",g,f),this}routeNotFound(g){return this.routeNotFoundFunc=g,this}on(g,f,...L){let $=Array.isArray(g)?g:[g];for(let A of $){let C=A.toUpperCase();if(C.toLocaleLowerCase()in this)this[C.toLocaleLowerCase()](f,...L);else this.addRoute(C,f,L)}}}export{n as default};
package/dist/types.d.ts CHANGED
@@ -96,6 +96,8 @@ export interface DieselT {
96
96
  };
97
97
  staticPath: string | null;
98
98
  routeNotFoundFunc: (c: ContextType) => void | Promise<void> | Promise<Response> | Response;
99
+ routerInstance: DieselT;
100
+ tempRoutes: Map<string, TempRouteEntry>;
99
101
  }
100
102
  export interface RouteCache {
101
103
  [key: string]: RouteHandlerT | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "diesel-core",
3
- "version": "1.3.6",
3
+ "version": "1.3.7",
4
4
  "description": "Web framework built on Web Standards",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -40,31 +40,31 @@
40
40
  "import": "./dist/middlewares/ratelimit/rate-limit.js",
41
41
  "require": "./dist/middlewares/ratelimit/rate-limit.js"
42
42
  },
43
- "./redisStore": {
43
+ "./redisStore":{
44
44
  "types": "./dist/middlewares/ratelimit/implementation.d.ts",
45
45
  "import": "./dist/middlewares/ratelimit/implementation.js",
46
46
  "require": "./dist/middlewares/ratelimit/implementation.js"
47
47
  },
48
- "./dicedbStore": {
48
+ "./dicedbStore":{
49
49
  "types": "./dist/middlewares/ratelimit/implementation.d.ts",
50
50
  "import": "./dist/middlewares/ratelimit/implementation.js",
51
51
  "require": "./dist/middlewares/ratelimit/implementation.js"
52
52
  },
53
- "./jwt": {
53
+ "./jwt":{
54
54
  "types": "./dist/middlewares/jwt/index.d.ts",
55
55
  "import": "./dist/middlewares/jwt/index.js",
56
- "require": "./dist/middlewares/jwt/index.js"
56
+ "require": "./dist/middlewares/jwt/index.js"
57
57
  },
58
- "./powered-by": {
58
+ "./powered-by":{
59
59
  "types": "./dist/middlewares/powered-by/index.d.ts",
60
60
  "import": "./dist/middlewares/powered-by/index.js",
61
- "require": "./dist/middlewares/powered-by/index.js"
61
+ "require": "./dist/middlewares/powered-by/index.js"
62
62
  },
63
- "./requestid": {
64
- "types": "./dist/middlewares/request-id/index.d.ts",
65
- "import": "./dist/middlewares/request-id/index.js",
66
- "require": "./dist/middlewares/request-id/index.js"
67
- }
63
+ "./requestid":{
64
+ "types": "./dist/middlewares/request-id/index.d.ts",
65
+ "import": "./dist/middlewares/request-id/index.js",
66
+ "require": "./dist/middlewares/request-id/index.js"
67
+ }
68
68
  },
69
69
  "scripts": {
70
70
  "build": "bun run build.js",