@stacksjs/bun-router 0.1.17 → 0.1.20

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/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{J}from"./chunk-7s1kcj7w.js";import g from"process";import{CLI as ue}from"@stacksjs/clapp";var F="0.1.17";import f from"fs/promises";import I from"path";import T from"process";var p={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"},o={red:(e)=>`${p.red}${e}${p.reset}`,green:(e)=>`${p.green}${e}${p.reset}`,yellow:(e)=>`${p.yellow}${e}${p.reset}`,blue:(e)=>`${p.blue}${e}${p.reset}`,cyan:(e)=>`${p.cyan}${e}${p.reset}`,white:(e)=>`${p.white}${e}${p.reset}`,gray:(e)=>`${p.gray}${e}${p.reset}`,bold:(e)=>`${p.bold}${e}${p.reset}`,dim:(e)=>`${p.dim}${e}${p.reset}`,hex:(e)=>(t)=>t};async function v(e){let t=Object.entries(J).map(([n,c])=>({name:n,className:c.constructor.name})),r=`/**
3
+ import{Me}from"./chunk-mpyfk9k4.js";import g from"process";import{CLI as ce}from"@stacksjs/clapp";var F="0.1.20";import f from"fs/promises";import I from"path";import T from"process";var p={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"},o={red:(e)=>`${p.red}${e}${p.reset}`,green:(e)=>`${p.green}${e}${p.reset}`,yellow:(e)=>`${p.yellow}${e}${p.reset}`,blue:(e)=>`${p.blue}${e}${p.reset}`,cyan:(e)=>`${p.cyan}${e}${p.reset}`,white:(e)=>`${p.white}${e}${p.reset}`,gray:(e)=>`${p.gray}${e}${p.reset}`,bold:(e)=>`${p.bold}${e}${p.reset}`,dim:(e)=>`${p.dim}${e}${p.reset}`,hex:(e)=>(t)=>t};async function v(e){let t=Object.entries(Me).map(([n,c])=>({name:n,className:c.constructor.name})),r=`/**
4
4
  * This file is auto-generated.
5
5
  * DO NOT EDIT THIS FILE DIRECTLY.
6
6
  * To update, run 'bun router middleware:types'
@@ -31,7 +31,7 @@ export type MiddlewareConfig = MiddlewareName | ${t.map((n)=>n.className).join("
31
31
  export function isValidMiddleware(name: string): name is MiddlewareName {
32
32
  return [${t.map((n)=>`'${n.name}'`).join(", ")}].includes(name)
33
33
  }
34
- `;await f.writeFile(e,r)}async function k(e){let t=[],r=await f.readdir(e,{withFileTypes:!0});for(let n of r){let c=I.join(e,n.name);if(n.isDirectory())t.push(...await k(c));else if(n.isFile()&&n.name.endsWith(".ts"))t.push(c)}return t}async function Q(e){let t=[];try{let r=await f.readFile(e,"utf-8"),n=/export\s+(?:default\s+)?class\s+(\w+)\s+(?:implements\s+Middleware|\{[\s\S]*?handle\s*\([\s\S]*?\))/g,c=null;while(c=n.exec(r)){let a=c[1];if(a.includes("Middleware")||c[0].includes("implements Middleware")){let l=I.relative(T.cwd(),e).replace(/\.ts$/,"");t.push({name:a,path:l})}}}catch(r){console.warn(o.yellow(`Error scanning file ${e}: ${r}`))}return t}async function M(e,t){console.log(o.blue(`Scanning directory: ${e} for middleware classes...`));try{let r=await k(e),n=[];for(let i of r){let d=await Q(i);n.push(...d)}if(n.length===0){console.warn(o.yellow("No middleware classes found in the specified directory."));return}let c=n.map((i)=>`import { ${i.name} } from '${i.path}'`).join(`
34
+ `;await f.writeFile(e,r)}async function k(e){let t=[],r=await f.readdir(e,{withFileTypes:!0});for(let n of r){let c=I.join(e,n.name);if(n.isDirectory())t.push(...await k(c));else if(n.isFile()&&n.name.endsWith(".ts"))t.push(c)}return t}async function K(e){let t=[];try{let r=await f.readFile(e,"utf-8"),n=/export\s+(?:default\s+)?class\s+(\w+)\s+(?:implements\s+Middleware|\{[\s\S]*?handle\s*\([\s\S]*?\))/g,c=null;while(c=n.exec(r)){let a=c[1];if(a.includes("Middleware")||c[0].includes("implements Middleware")){let l=I.relative(T.cwd(),e).replace(/\.ts$/,"");t.push({name:a,path:l})}}}catch(r){console.warn(o.yellow(`Error scanning file ${e}: ${r}`))}return t}async function M(e,t){console.log(o.blue(`Scanning directory: ${e} for middleware classes...`));try{let r=await k(e),n=[];for(let i of r){let d=await K(i);n.push(...d)}if(n.length===0){console.warn(o.yellow("No middleware classes found in the specified directory."));return}let c=n.map((i)=>`import { ${i.name} } from '${i.path}'`).join(`
35
35
  `),a=n.map((i)=>` ${i.name}: typeof ${i.name}`).join(`
36
36
  `),s=n.map((i)=>i.name).join(" | "),l=`/**
37
37
  * This file is auto-generated.
@@ -65,7 +65,7 @@ export const middlewareMap: MiddlewareMap = {
65
65
  ${n.map((i)=>` ${i.name}: ${i.name}`).join(`,
66
66
  `)}
67
67
  }
68
- `;await f.writeFile(t,l),console.log(o.green(`\u2728 Middleware map generated at ${t} with ${n.length} middleware classes`)),console.log(o.blue("Found middleware classes:"));for(let i of n)console.log(o.cyan(` - ${i.name} (${i.path})`))}catch(r){throw console.error(o.red(`Error generating middleware map: ${r}`)),r}}async function A(e,t){try{await f.access(e)}catch{console.error(o.red(`Directory not found at ${e}`)),T.exit(1)}await M(e,t),console.log(o.blue(`Watching for changes in ${e}...`));let r=null,n=f.watch(e,{recursive:!0});for await(let c of n){if(r)clearTimeout(r);r=setTimeout(async()=>{console.log(o.yellow("Changes detected. Regenerating middleware map..."));try{await M(e,t)}catch(a){console.error(o.red(`Error regenerating middleware map: ${a.message}`))}r=null},500)}}async function D(e){let t=I.join(T.cwd(),"src","middleware");try{await f.access(t)}catch{console.error(o.red(`Middleware directory not found at ${t}`)),T.exit(1)}await v(e),console.log(o.green(`\u2728 Middleware types generated at ${e}`)),console.log(o.blue(`Watching for changes in ${t}...`));let r=null,n=f.watch(t,{recursive:!0});for await(let c of n){if(r)clearTimeout(r);r=setTimeout(async()=>{console.log(o.yellow("Changes detected in middleware directory. Regenerating types..."));try{await v(e),console.log(o.green(`\u2728 Middleware types regenerated at ${e}`))}catch(a){console.error(o.red(`Error regenerating types: ${a.message}`))}r=null},500)}}import X from"fs/promises";import P from"process";async function L(e){try{let t=`${P.cwd()}/routes/index.ts`,{router:r}=await import(t);if(!r)console.error(o.red(`Could not find router instance in ${t}.`)),P.exit(1);let n=r.routes||[];if(n.length===0)console.log(o.yellow("No routes defined. Creating empty OpenAPI specification."));let c=n.filter((i)=>i.type==="api"||i.path.startsWith("/api")),a={openapi:"3.0.3",info:{title:e.title||"API Documentation",version:e.version||"1.0.0",description:e.description||"Generated API documentation"},servers:Z(e),paths:{},components:{schemas:{},securitySchemes:{}},tags:[]},s=new Set;for(let i of c){let d=a.paths[i.path]||{},m="";if(e.tags!==!1)m=i.tag||ee(i.path),s.add(m);let R={summary:i.summary||`${i.method.toUpperCase()} ${i.path}`,description:i.description||"",operationId:i.name||te(i.method,i.path),parameters:re(i),responses:ne(i)};if(m)R.tags=[m];if(["post","put","patch"].includes(i.method.toLowerCase()))R.requestBody=se(i);if(e.security!==!1&&i.middleware){let N=ie(i.middleware);if(N.length>0)R.security=N}d[i.method.toLowerCase()]=R,a.paths[i.path]=d}if(e.tags!==!1)a.tags=Array.from(s).map((i)=>({name:i,description:`Operations related to ${i}`}));let l=e.output||"openapi.json";await X.writeFile(l,JSON.stringify(a,null,2)),console.log(o.green(`\u2728 OpenAPI specification generated at ${l}`)),console.log(o.blue("Import this file into Postman, Swagger UI, or other API tools to explore your API."))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(o.red(`Routes file not found at ${P.cwd()}/routes/index.ts`)),console.error(o.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(o.red(`Error generating OpenAPI specification: ${t.message}`));throw t}}function Z(e){let t=[];if(e.servers){let r=e.servers.split(",").map((n)=>n.trim());for(let n of r)t.push({url:n,description:`Server ${t.length+1}`})}if(t.length===0)t.push({url:e.basePath||"/",description:"Default server"});return t}function ee(e){let t=e.split("/").filter(Boolean);if(t.length>0){if(t[0].toLowerCase()==="api"&&t.length>1)return t[1];return t[0]}return"default"}function te(e,t){let n=t.replace(/\{([^}]+)\}/g,"_$1").split("/").filter(Boolean);if(n.length===0)return e.toLowerCase();let c=e.toLowerCase();for(let a of n)c+=a.charAt(0).toUpperCase()+a.slice(1);return c}function re(e){let t=[],r=e.path.match(/\{([^}]+)\}/g);if(r)for(let n of r){let c=n.slice(1,-1);t.push({name:c,in:"path",required:!0,schema:{type:"string"},description:`Path parameter: ${c}`})}if(e.params&&e.params.query)for(let[n,c]of Object.entries(e.params.query))t.push({name:n,in:"query",schema:oe(c),required:c.required===!0,description:c.description||`Query parameter: ${n}`});return t}function oe(e){if(!e||typeof e!=="object")return{type:"string"};let t={};if(e.type)t.type=e.type;if(e.format)t.format=e.format;if(e.enum)t.enum=e.enum;if(e.default!==void 0)t.default=e.default;return t}function ne(e){let t={200:{description:"Successful response",content:{"application/json":{schema:{}}}}};if(t["400"]={description:"Bad request",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},t["401"]={description:"Unauthorized",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},t["404"]={description:"Not found",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},t["500"]={description:"Server error",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},e.responses)for(let[r,n]of Object.entries(e.responses))t[r]={description:n.description||`Response with status ${r}`,content:{"application/json":{schema:n.schema||{}}}};return t}function se(e){let t={required:!0,content:{"application/json":{schema:{type:"object"}}}};if(e.params&&e.params.body)t.content["application/json"].schema=e.params.body;return t}function ie(e){let t=[];for(let r of e){let n=typeof r==="string"?r:r.name;if(n&&n.toLowerCase().includes("auth"))if(n.toLowerCase().includes("jwt"))t.push({BearerAuth:[]});else if(n.toLowerCase().includes("apikey"))t.push({ApiKeyAuth:[]});else if(n.toLowerCase().includes("basic"))t.push({BasicAuth:[]});else t.push({[n]:[]})}return t}import E from"fs/promises";import z from"path";import y from"process";async function C(e){try{let t=`${y.cwd()}/routes/index.ts`,{router:r}=await import(t);if(!r)console.error(o.red(`Could not find router instance in ${t}.`)),y.exit(1);let n=Object.getOwnPropertyNames(Object.getPrototypeOf(r)).filter((s)=>!s.startsWith("_")&&s!=="constructor"&&typeof r[s]==="function"),c=Object.keys(r).filter((s)=>!["routes","middleware","hooks","config"].includes(s)&&typeof s==="string"&&!s.startsWith("_")),a=`/**
68
+ `;await f.writeFile(t,l),console.log(o.green(`\u2728 Middleware map generated at ${t} with ${n.length} middleware classes`)),console.log(o.blue("Found middleware classes:"));for(let i of n)console.log(o.cyan(` - ${i.name} (${i.path})`))}catch(r){throw console.error(o.red(`Error generating middleware map: ${r}`)),r}}async function A(e,t){try{await f.access(e)}catch{console.error(o.red(`Directory not found at ${e}`)),T.exit(1)}await M(e,t),console.log(o.blue(`Watching for changes in ${e}...`));let r=null,n=f.watch(e,{recursive:!0});for await(let c of n){if(r)clearTimeout(r);r=setTimeout(async()=>{console.log(o.yellow("Changes detected. Regenerating middleware map..."));try{await M(e,t)}catch(a){console.error(o.red(`Error regenerating middleware map: ${a.message}`))}r=null},500)}}async function D(e){let t=I.join(T.cwd(),"src","middleware");try{await f.access(t)}catch{console.error(o.red(`Middleware directory not found at ${t}`)),T.exit(1)}await v(e),console.log(o.green(`\u2728 Middleware types generated at ${e}`)),console.log(o.blue(`Watching for changes in ${t}...`));let r=null,n=f.watch(t,{recursive:!0});for await(let c of n){if(r)clearTimeout(r);r=setTimeout(async()=>{console.log(o.yellow("Changes detected in middleware directory. Regenerating types..."));try{await v(e),console.log(o.green(`\u2728 Middleware types regenerated at ${e}`))}catch(a){console.error(o.red(`Error regenerating types: ${a.message}`))}r=null},500)}}import Q from"fs/promises";import P from"process";async function L(e){try{let t=`${P.cwd()}/routes/index.ts`,{router:r}=await import(t);if(!r)console.error(o.red(`Could not find router instance in ${t}.`)),P.exit(1);let n=r.routes||[];if(n.length===0)console.log(o.yellow("No routes defined. Creating empty OpenAPI specification."));let c=n.filter((i)=>i.type==="api"||i.path.startsWith("/api")),a={openapi:"3.0.3",info:{title:e.title||"API Documentation",version:e.version||"1.0.0",description:e.description||"Generated API documentation"},servers:X(e),paths:{},components:{schemas:{},securitySchemes:{}},tags:[]},s=new Set;for(let i of c){let d=a.paths[i.path]||{},m="";if(e.tags!==!1)m=i.tag||Z(i.path),s.add(m);let R={summary:i.summary||`${i.method.toUpperCase()} ${i.path}`,description:i.description||"",operationId:i.name||ee(i.method,i.path),parameters:te(i),responses:oe(i)};if(m)R.tags=[m];if(["post","put","patch"].includes(i.method.toLowerCase()))R.requestBody=ne(i);if(e.security!==!1&&i.middleware){let N=se(i.middleware);if(N.length>0)R.security=N}d[i.method.toLowerCase()]=R,a.paths[i.path]=d}if(e.tags!==!1)a.tags=Array.from(s).map((i)=>({name:i,description:`Operations related to ${i}`}));let l=e.output||"openapi.json";await Q.writeFile(l,JSON.stringify(a,null,2)),console.log(o.green(`\u2728 OpenAPI specification generated at ${l}`)),console.log(o.blue("Import this file into Postman, Swagger UI, or other API tools to explore your API."))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(o.red(`Routes file not found at ${P.cwd()}/routes/index.ts`)),console.error(o.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(o.red(`Error generating OpenAPI specification: ${t.message}`));throw t}}function X(e){let t=[];if(e.servers){let r=e.servers.split(",").map((n)=>n.trim());for(let n of r)t.push({url:n,description:`Server ${t.length+1}`})}if(t.length===0)t.push({url:e.basePath||"/",description:"Default server"});return t}function Z(e){let t=e.split("/").filter(Boolean);if(t.length>0){if(t[0].toLowerCase()==="api"&&t.length>1)return t[1];return t[0]}return"default"}function ee(e,t){let n=t.replace(/\{([^}]+)\}/g,"_$1").split("/").filter(Boolean);if(n.length===0)return e.toLowerCase();let c=e.toLowerCase();for(let a of n)c+=a.charAt(0).toUpperCase()+a.slice(1);return c}function te(e){let t=[],r=e.path.match(/\{([^}]+)\}/g);if(r)for(let n of r){let c=n.slice(1,-1);t.push({name:c,in:"path",required:!0,schema:{type:"string"},description:`Path parameter: ${c}`})}if(e.params&&e.params.query)for(let[n,c]of Object.entries(e.params.query))t.push({name:n,in:"query",schema:re(c),required:c.required===!0,description:c.description||`Query parameter: ${n}`});return t}function re(e){if(!e||typeof e!=="object")return{type:"string"};let t={};if(e.type)t.type=e.type;if(e.format)t.format=e.format;if(e.enum)t.enum=e.enum;if(e.default!==void 0)t.default=e.default;return t}function oe(e){let t={200:{description:"Successful response",content:{"application/json":{schema:{}}}}};if(t["400"]={description:"Bad request",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},t["401"]={description:"Unauthorized",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},t["404"]={description:"Not found",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},t["500"]={description:"Server error",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},e.responses)for(let[r,n]of Object.entries(e.responses))t[r]={description:n.description||`Response with status ${r}`,content:{"application/json":{schema:n.schema||{}}}};return t}function ne(e){let t={required:!0,content:{"application/json":{schema:{type:"object"}}}};if(e.params&&e.params.body)t.content["application/json"].schema=e.params.body;return t}function se(e){let t=[];for(let r of e){let n=typeof r==="string"?r:r.name;if(n&&n.toLowerCase().includes("auth"))if(n.toLowerCase().includes("jwt"))t.push({BearerAuth:[]});else if(n.toLowerCase().includes("apikey"))t.push({ApiKeyAuth:[]});else if(n.toLowerCase().includes("basic"))t.push({BasicAuth:[]});else t.push({[n]:[]})}return t}import E from"fs/promises";import z from"path";import y from"process";async function C(e){try{let t=`${y.cwd()}/routes/index.ts`,{router:r}=await import(t);if(!r)console.error(o.red(`Could not find router instance in ${t}.`)),y.exit(1);let n=Object.getOwnPropertyNames(Object.getPrototypeOf(r)).filter((s)=>!s.startsWith("_")&&s!=="constructor"&&typeof r[s]==="function"),c=Object.keys(r).filter((s)=>!["routes","middleware","hooks","config"].includes(s)&&typeof s==="string"&&!s.startsWith("_")),a=`/**
69
69
  * This file is auto-generated.
70
70
  * DO NOT EDIT THIS FILE DIRECTLY.
71
71
  * To update, run 'bun router router:types'
@@ -110,8 +110,8 @@ export type RouterExtension = {
110
110
  * \`\`\`
111
111
  */
112
112
  export type ExtendRouter<T extends RouterExtension> = Router & T
113
- `;await E.writeFile(e,a),console.log(o.green(`\u2728 Router types generated at ${e}`))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(o.red(`Routes file not found at ${y.cwd()}/routes/index.ts`)),console.error(o.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(o.red(`Error generating router types: ${t.message}`));throw t}}async function U(e){let t=[z.join(y.cwd(),"routes"),z.join(y.cwd(),"src")],r=!1;for(let c of t)try{await E.access(c),r=!0;break}catch{}if(!r)console.error(o.red("No valid source directories found to watch.")),y.exit(1);await C(e),console.log(o.green(`\u2728 Router types generated at ${e}`)),console.log(o.blue("Watching for changes in router files..."));let n=null;for(let c of t)try{let a=E.watch(c,{recursive:!0});(async()=>{for await(let s of a){if(n)clearTimeout(n);n=setTimeout(async()=>{console.log(o.yellow("Changes detected in router files. Regenerating types..."));try{await C(e),console.log(o.green(`\u2728 Router types regenerated at ${e}`))}catch(l){console.error(o.red(`Error regenerating types: ${l.message}`))}n=null},500)}})()}catch{}}import S from"fs/promises";import ae from"path";import h from"process";async function B(e){try{let t=`${h.cwd()}/routes/index.ts`,{router:r}=await import(t);if(!r)console.error(o.red(`Could not find router instance in ${t}.`)),h.exit(1);let n=r.routes||[];if(n.length===0){console.log(o.yellow("No routes defined."));return}let c=n;if(e.path)c=c.filter((a)=>a.path.startsWith(e.path));console.log(o.bold(`
114
- Routes:`)),console.log(o.dim("+-----------------+-------------------------+------------------+----------------+")),console.log(o.dim("| ")+o.bold("Method")+o.dim(" | ")+o.bold("URI")+o.dim(" | ")+o.bold("Name")+o.dim(" | ")+o.bold("Handler")+o.dim(" |")),console.log(o.dim("+-----------------+-------------------------+------------------+----------------+")),c.forEach((a)=>{let s=O(a.method,15),l=O(a.path,23),i=O(a.name||"",16),d;if(typeof a.handler==="string")d=a.handler;else if(typeof a.handler==="function")d=a.handler.name?`${a.handler.name}()`:"Anonymous Function";else d="Class Handler";if(d=O(d,14),console.log(o.dim("| ")+le(a.method)(s)+o.dim(" | ")+o.green(l)+o.dim(" | ")+o.yellow(i)+o.dim(" | ")+o.blue(d)+o.dim(" |")),e.verbose&&a.middleware&&a.middleware.length>0)console.log(o.dim("| | ")+o.dim("Middleware: ")+a.middleware.map((m)=>typeof m==="string"?m:m.name||"Anonymous").join(", ")+o.dim(" |"))}),console.log(o.dim("+-----------------+-------------------------+------------------+----------------+")),console.log(`
113
+ `;await E.writeFile(e,a),console.log(o.green(`\u2728 Router types generated at ${e}`))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(o.red(`Routes file not found at ${y.cwd()}/routes/index.ts`)),console.error(o.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(o.red(`Error generating router types: ${t.message}`));throw t}}async function U(e){let t=[z.join(y.cwd(),"routes"),z.join(y.cwd(),"src")],r=!1;for(let c of t)try{await E.access(c),r=!0;break}catch{}if(!r)console.error(o.red("No valid source directories found to watch.")),y.exit(1);await C(e),console.log(o.green(`\u2728 Router types generated at ${e}`)),console.log(o.blue("Watching for changes in router files..."));let n=null;for(let c of t)try{let a=E.watch(c,{recursive:!0});(async()=>{for await(let s of a){if(n)clearTimeout(n);n=setTimeout(async()=>{console.log(o.yellow("Changes detected in router files. Regenerating types..."));try{await C(e),console.log(o.green(`\u2728 Router types regenerated at ${e}`))}catch(l){console.error(o.red(`Error regenerating types: ${l.message}`))}n=null},500)}})()}catch{}}import S from"fs/promises";import ie from"path";import h from"process";async function B(e){try{let t=`${h.cwd()}/routes/index.ts`,{router:r}=await import(t);if(!r)console.error(o.red(`Could not find router instance in ${t}.`)),h.exit(1);let n=r.routes||[];if(n.length===0){console.log(o.yellow("No routes defined."));return}let c=n;if(e.path)c=c.filter((a)=>a.path.startsWith(e.path));console.log(o.bold(`
114
+ Routes:`)),console.log(o.dim("+-----------------+-------------------------+------------------+----------------+")),console.log(o.dim("| ")+o.bold("Method")+o.dim(" | ")+o.bold("URI")+o.dim(" | ")+o.bold("Name")+o.dim(" | ")+o.bold("Handler")+o.dim(" |")),console.log(o.dim("+-----------------+-------------------------+------------------+----------------+")),c.forEach((a)=>{let s=O(a.method,15),l=O(a.path,23),i=O(a.name||"",16),d;if(typeof a.handler==="string")d=a.handler;else if(typeof a.handler==="function")d=a.handler.name?`${a.handler.name}()`:"Anonymous Function";else d="Class Handler";if(d=O(d,14),console.log(o.dim("| ")+ae(a.method)(s)+o.dim(" | ")+o.green(l)+o.dim(" | ")+o.yellow(i)+o.dim(" | ")+o.blue(d)+o.dim(" |")),e.verbose&&a.middleware&&a.middleware.length>0)console.log(o.dim("| | ")+o.dim("Middleware: ")+a.middleware.map((m)=>typeof m==="string"?m:m.name||"Anonymous").join(", ")+o.dim(" |"))}),console.log(o.dim("+-----------------+-------------------------+------------------+----------------+")),console.log(`
115
115
  Showing ${c.length} routes`)}catch(t){throw console.error(o.red(`Error: ${t.message}`)),console.error(o.yellow(`Make sure your routes are defined in ${h.cwd()}/routes/index.ts and export a 'router' instance.`)),t}}async function j(e){try{let t=`${h.cwd()}/routes/index.ts`,{router:r}=await import(t);if(!r)console.error(o.red(`Could not find router instance in ${t}.`)),h.exit(1);let n=r.routes||[];if(n.length===0)console.log(o.yellow("No routes defined. Creating empty types file."));let c=n.map((l)=>{if(l.name)return l.name;let i=l.method.toLowerCase(),d=l.path.replace(/^\//,"").replace(/\//g,".").replace(/\{([^}]+)\}/g,":$1");return d?`${i}.${d}`:i}),a=[...new Set(c)],s=`/**
116
116
  * This file is auto-generated.
117
117
  * DO NOT EDIT THIS FILE DIRECTLY.
@@ -142,11 +142,11 @@ export type RouteFunction = <T extends RouteName>(name: T, params?: Record<strin
142
142
  export function isValidRouteName(name: string): name is RouteName {
143
143
  return [${a.map((l)=>`'${l}'`).join(", ")}].includes(name)
144
144
  }
145
- `;await S.writeFile(e,s),console.log(o.green(`\u2728 Route types generated at ${e}`))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(o.red(`Routes file not found at ${h.cwd()}/routes/index.ts`)),console.error(o.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(o.red(`Error generating route types: ${t.message}`));throw t}}async function H(e){let t=ae.join(h.cwd(),"routes");try{await S.access(t)}catch{console.error(o.red(`Routes directory not found at ${t}`)),h.exit(1)}await j(e),console.log(o.green(`\u2728 Route types generated at ${e}`)),console.log(o.blue(`Watching for changes in ${t}...`));let r=null,n=S.watch(t,{recursive:!0});for await(let c of n){if(r)clearTimeout(r);r=setTimeout(async()=>{console.log(o.yellow("Changes detected in routes directory. Regenerating types..."));try{await j(e),console.log(o.green(`\u2728 Route types regenerated at ${e}`))}catch(a){console.error(o.red(`Error regenerating types: ${a.message}`))}r=null},500)}}function O(e,t){return(e+" ".repeat(t)).substring(0,t)}function le(e){switch(e.toUpperCase()){case"GET":return o.cyan;case"POST":return o.green;case"PUT":return o.yellow;case"PATCH":return o.yellow;case"DELETE":return o.red;case"OPTIONS":return o.gray;default:return o.white}}import x from"process";var w={success:(e)=>o.green(`\u2728 ${e}`),info:(e)=>o.blue(e),warning:(e)=>o.yellow(e),error:(e)=>o.red(e),dim:(e)=>o.dim(e),bold:(e)=>o.bold(e)},u={success:(e)=>console.log(w.success(e)),info:(e)=>console.log(w.info(e)),warning:(e)=>console.log(w.warning(e)),error:(e)=>console.error(w.error(e)),debug:(e)=>console.debug(w.dim(e))};async function b(){try{let e=`${x.cwd()}/routes/index.ts`,{router:t}=await import(e);if(!t)u.error(`Could not find router instance in ${e}.`),x.exit(1);return t}catch(e){if(e.code==="ERR_MODULE_NOT_FOUND")u.error(`Routes file not found at ${x.cwd()}/routes/index.ts`),u.warning('Make sure your routes are defined and exported as "router" in routes/index.ts');else u.error(`Error loading router: ${e.message}`);throw e}}function ce(e){switch(e.toUpperCase()){case"GET":return o.cyan.toString();case"POST":return o.green.toString();case"PUT":return o.yellow.toString();case"PATCH":return o.yellow.toString();case"DELETE":return o.red.toString();case"OPTIONS":return o.gray.toString();default:return o.white.toString()}}async function G(e){u.info("\uD83D\uDD0D Checking router health...");try{let t=await b(),r=t.routes||[],n=t.globalMiddleware||[],c=t.namedRoutes||new Map,a={totalRoutes:r.length,namedRoutes:c.size,globalMiddleware:n.length,routesByMethod:{},duplicateRoutes:[],routesWithMiddleware:0,staticRoutes:0,dynamicRoutes:0},s=new Map;for(let l of r){let i=`${l.method}:${l.path}`;if(a.routesByMethod[l.method]=(a.routesByMethod[l.method]||0)+1,!s.has(i))s.set(i,[]);if(s.get(i).push(l.path),s.get(i).length>1)a.duplicateRoutes.push({path:l.path,method:l.method});if(l.middleware&&l.middleware.length>0)a.routesWithMiddleware++;if(l.path.includes("{")||l.path.includes("*"))a.dynamicRoutes++;else a.staticRoutes++}if(u.success("Router health check completed"),console.log(`\uD83D\uDCCA Routes: ${a.totalRoutes} total (${a.staticRoutes} static, ${a.dynamicRoutes} dynamic)`),console.log(`\uD83D\uDCDB Named routes: ${a.namedRoutes}`),console.log(`\uD83D\uDEE1\uFE0F Global middleware: ${a.globalMiddleware}`),console.log(`\uD83D\uDD27 Routes with middleware: ${a.routesWithMiddleware}`),e.verbose){console.log(`
146
- \uD83D\uDCC8 Routes by method:`);for(let[i,d]of Object.entries(a.routesByMethod)){let m=ce(i);console.log(` ${o.hex(m)(i.padEnd(8))}: ${d}`)}if(a.duplicateRoutes.length>0){u.warning(`
145
+ `;await S.writeFile(e,s),console.log(o.green(`\u2728 Route types generated at ${e}`))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(o.red(`Routes file not found at ${h.cwd()}/routes/index.ts`)),console.error(o.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(o.red(`Error generating route types: ${t.message}`));throw t}}async function H(e){let t=ie.join(h.cwd(),"routes");try{await S.access(t)}catch{console.error(o.red(`Routes directory not found at ${t}`)),h.exit(1)}await j(e),console.log(o.green(`\u2728 Route types generated at ${e}`)),console.log(o.blue(`Watching for changes in ${t}...`));let r=null,n=S.watch(t,{recursive:!0});for await(let c of n){if(r)clearTimeout(r);r=setTimeout(async()=>{console.log(o.yellow("Changes detected in routes directory. Regenerating types..."));try{await j(e),console.log(o.green(`\u2728 Route types regenerated at ${e}`))}catch(a){console.error(o.red(`Error regenerating types: ${a.message}`))}r=null},500)}}function O(e,t){return(e+" ".repeat(t)).substring(0,t)}function ae(e){switch(e.toUpperCase()){case"GET":return o.cyan;case"POST":return o.green;case"PUT":return o.yellow;case"PATCH":return o.yellow;case"DELETE":return o.red;case"OPTIONS":return o.gray;default:return o.white}}import x from"process";var w={success:(e)=>o.green(`\u2728 ${e}`),info:(e)=>o.blue(e),warning:(e)=>o.yellow(e),error:(e)=>o.red(e),dim:(e)=>o.dim(e),bold:(e)=>o.bold(e)},u={success:(e)=>console.log(w.success(e)),info:(e)=>console.log(w.info(e)),warning:(e)=>console.log(w.warning(e)),error:(e)=>console.error(w.error(e)),debug:(e)=>console.debug(w.dim(e))};async function b(){try{let e=`${x.cwd()}/routes/index.ts`,{router:t}=await import(e);if(!t)u.error(`Could not find router instance in ${e}.`),x.exit(1);return t}catch(e){if(e.code==="ERR_MODULE_NOT_FOUND")u.error(`Routes file not found at ${x.cwd()}/routes/index.ts`),u.warning('Make sure your routes are defined and exported as "router" in routes/index.ts');else u.error(`Error loading router: ${e.message}`);throw e}}function le(e){switch(e.toUpperCase()){case"GET":return o.cyan.toString();case"POST":return o.green.toString();case"PUT":return o.yellow.toString();case"PATCH":return o.yellow.toString();case"DELETE":return o.red.toString();case"OPTIONS":return o.gray.toString();default:return o.white.toString()}}async function G(e){u.info("\uD83D\uDD0D Checking router health...");try{let t=await b(),r=t.routes||[],n=t.globalMiddleware||[],c=t.namedRoutes||new Map,a={totalRoutes:r.length,namedRoutes:c.size,globalMiddleware:n.length,routesByMethod:{},duplicateRoutes:[],routesWithMiddleware:0,staticRoutes:0,dynamicRoutes:0},s=new Map;for(let l of r){let i=`${l.method}:${l.path}`;if(a.routesByMethod[l.method]=(a.routesByMethod[l.method]||0)+1,!s.has(i))s.set(i,[]);if(s.get(i).push(l.path),s.get(i).length>1)a.duplicateRoutes.push({path:l.path,method:l.method});if(l.middleware&&l.middleware.length>0)a.routesWithMiddleware++;if(l.path.includes("{")||l.path.includes("*"))a.dynamicRoutes++;else a.staticRoutes++}if(u.success("Router health check completed"),console.log(`\uD83D\uDCCA Routes: ${a.totalRoutes} total (${a.staticRoutes} static, ${a.dynamicRoutes} dynamic)`),console.log(`\uD83D\uDCDB Named routes: ${a.namedRoutes}`),console.log(`\uD83D\uDEE1\uFE0F Global middleware: ${a.globalMiddleware}`),console.log(`\uD83D\uDD27 Routes with middleware: ${a.routesWithMiddleware}`),e.verbose){console.log(`
146
+ \uD83D\uDCC8 Routes by method:`);for(let[i,d]of Object.entries(a.routesByMethod)){let m=le(i);console.log(` ${o.hex(m)(i.padEnd(8))}: ${d}`)}if(a.duplicateRoutes.length>0){u.warning(`
147
147
  \u26A0\uFE0F Found ${a.duplicateRoutes.length} duplicate route(s):`);for(let i of a.duplicateRoutes)console.log(` ${i.method} ${i.path}`)}let l=[];if(a.totalRoutes===0)l.push("No routes defined");if(a.duplicateRoutes.length>0)l.push(`${a.duplicateRoutes.length} duplicate routes`);if(a.routesWithMiddleware===0&&a.globalMiddleware===0)l.push("No middleware configured");if(l.length>0){u.warning(`
148
148
  \u26A0\uFE0F Potential issues:`);for(let i of l)console.log(` \u2022 ${i}`)}else u.success(`
149
149
  \u2705 No issues detected`)}}catch(t){throw u.error(`Health check failed: ${t.message}`),t}}async function _(e){let t=e.baseUrl||"http://localhost:3000",r=e.timeout||5000,n=e.method?e.method.split(",").map((c)=>c.trim().toUpperCase()):null;u.info(`\uD83E\uDDEA Testing routes at ${t}...`);try{let a=(await b()).routes||[],s=a;if(e.filter){let i=new RegExp(e.filter.replace(/\*/g,".*"));s=a.filter((d)=>i.test(d.path))}if(n)s=s.filter((i)=>n.includes(i.method));if(s.length===0){u.warning("No routes match the specified filters");return}u.info(`Testing ${s.length} routes...`);let l={total:0,passed:0,failed:0,errors:[]};for(let i of s){if(l.total++,i.path.includes("{")){u.debug(`Skipping parameterized route: ${i.method} ${i.path}`);continue}try{let d=`${t}${i.path}`,m=await fetch(d,{method:i.method,signal:AbortSignal.timeout(r)});if(m.status<500)l.passed++,u.debug(`\u2705 ${i.method} ${i.path} \u2192 ${m.status}`);else l.failed++,l.errors.push({route:`${i.method} ${i.path}`,error:`HTTP ${m.status}`})}catch(d){l.failed++,l.errors.push({route:`${i.method} ${i.path}`,error:d.message})}}if(console.log(`
150
150
  \uD83D\uDCCA Test Results:`),console.log(` Total: ${l.total}`),console.log(` Passed: ${o.green(String(l.passed))}`),console.log(` Failed: ${o.red(String(l.failed))}`),l.errors.length>0){console.log(`
151
151
  \u274C Failures:`);for(let i of l.errors)console.log(` ${i.route}: ${i.error}`)}if(l.failed>0)x.exit(1);else u.success("All tests passed!")}catch(c){throw u.error(`Route testing failed: ${c.message}`),c}}async function W(e,t){let r=t.method?.toUpperCase()||"GET";u.info(`\uD83D\uDD0D Debugging route matching for: ${r} ${e}`);try{let n=await b(),c=n.matchRoute?n.matchRoute(e,r):null;if(c){if(u.success("\u2705 Route matched!"),console.log(` Route: ${c.route.method} ${c.route.path}`),console.log(` Handler: ${typeof c.route.handler}`),Object.keys(c.params||{}).length>0){console.log(" Parameters:");for(let[a,s]of Object.entries(c.params))console.log(` ${a}: ${s}`)}if(c.route.middleware&&c.route.middleware.length>0)console.log(` Middleware: ${c.route.middleware.length} handler(s)`);if(c.route.name)console.log(` Named route: ${c.route.name}`)}else if(u.error(`\u274C No route matched for ${r} ${e}`),t.verbose){console.log(`
152
- \uD83D\uDCCB Available routes:`);let s=(n.routes||[]).filter((l)=>l.method===r);if(s.length===0)console.log(` No routes defined for ${r} method`);else for(let l of s)console.log(` ${l.method} ${l.path}`)}}catch(n){throw u.error(`Route debugging failed: ${n.message}`),n}}async function q(e){u.info("\uD83D\uDDD1\uFE0F Clearing route caches...");try{let t=await b();if(e.stats){if(t.getCacheStats){let r=t.getCacheStats();console.log("\uD83D\uDCCA Cache statistics before clearing:"),console.log(` Hit rate: ${r.hitRate}%`),console.log(` Total hits: ${r.hits}`),console.log(` Total misses: ${r.misses}`),console.log(` Cache size: ${r.size}`)}if(t.routeCache)console.log(` Route cache entries: ${t.routeCache.size}`);if(t.templateCache)console.log(` Template cache entries: ${t.templateCache.size}`)}if(t.clearRouteCache)t.clearRouteCache();if(t.routeCache&&t.routeCache.clear)t.routeCache.clear();if(t.templateCache&&t.templateCache.clear)t.templateCache.clear();if(t.clearModelCache)t.clearModelCache();u.success("\u2705 Caches cleared successfully")}catch(t){throw u.error(`Cache clearing failed: ${t.message}`),t}}async function V(e){u.info("\uD83D\uDD0D Validating route definitions...");try{let r=(await b()).routes||[],n=[],c=[];for(let s of r){if(!s.method)n.push(`Route missing method: ${s.path}`);if(!s.path)n.push(`Route missing path: ${s.method||"UNKNOWN"}`);if(!s.handler)n.push(`Route missing handler: ${s.method} ${s.path}`);if(s.path&&!s.path.startsWith("/"))n.push(`Route path should start with '/': ${s.method} ${s.path}`);if(s.path&&s.path.includes("{")){let l=s.path.match(/\{[^}]+\}/g)||[];for(let i of l)if(!i.match(/^\{[a-z_]\w*(\?|:[^}]+)?\}$/i))n.push(`Invalid parameter syntax in ${s.method} ${s.path}: ${i}`)}if(e.strict){if(!s.name&&!s.path.includes("{")&&s.path!=="/")c.push(`Consider adding a name to route: ${s.method} ${s.path}`);if(s.path.includes("/admin")&&(!s.middleware||s.middleware.length===0))c.push(`Admin route missing middleware: ${s.method} ${s.path}`)}}let a=new Map;for(let s of r){let l=`${s.method}:${s.path}`;a.set(l,(a.get(l)||0)+1)}for(let[s,l]of a.entries())if(l>1)n.push(`Duplicate route detected: ${s} (${l} times)`);if(n.length===0&&c.length===0){u.success("\u2705 All route definitions are valid");return}if(n.length>0){u.error(`\u274C Found ${n.length} validation error(s):`);for(let s of n)console.log(` \u2022 ${s}`)}if(c.length>0){u.warning(`\u26A0\uFE0F Found ${c.length} warning(s):`);for(let s of c)console.log(` \u2022 ${s}`)}if(e.fix)u.info("\uD83D\uDD27 Auto-fixing is not yet implemented");if(n.length>0)x.exit(1)}catch(t){throw u.error(`Route validation failed: ${t.message}`),t}}function Y(){let e=new ue("router");return e.version(F),de(e),pe(e),me(e),ge(e),fe(e),e.help(),e}function de(e){e.command("route:list","List all registered routes").option("-v, --verbose","Show detailed information including middleware").option("-vv, --extra-verbose","Show very detailed information").option("--path <path>","Filter routes by path prefix").option("--except-vendor","Exclude vendor routes").option("--only-vendor","Show only vendor routes").example("router route:list").example("router route:list -v").example("router route:list --path=/api").action(async(t)=>{try{await B(t)}catch(r){console.error(`Failed to list routes: ${r.message}`),g.exit(1)}}),e.command("route:types","Generate TypeScript types for route names").option("--output <file>","Output file path",{default:"route-types.ts"}).option("--watch","Watch for changes in routes directory").example("router route:types").example("router route:types --output src/types/routes.ts").example("router route:types --watch").action(async(t)=>{try{let r=t.output||"route-types.ts";if(t.watch)await H(r);else await j(r)}catch(r){console.error(`Failed to generate route types: ${r.message}`),g.exit(1)}})}function pe(e){e.command("middleware:types","Generate TypeScript types for middleware configurations").option("--output <file>","Output file path",{default:"middleware-types.ts"}).option("--watch","Watch for changes in middleware directory").example("router middleware:types").example("router middleware:types --output src/types/middleware.ts").example("router middleware:types --watch").action(async(t)=>{try{let r=t.output||"middleware-types.ts";if(t.watch)await D(r);else await v(r)}catch(r){console.error(`Failed to generate middleware types: ${r.message}`),g.exit(1)}}),e.command("middleware:map","Generate TypeScript types for all middleware in the project").option("--dir <directory>","Directory to scan for middleware classes",{default:"src"}).option("--output <file>","Output file path",{default:"middleware-map.ts"}).option("--watch","Watch for changes in the specified directory").example("router middleware:map").example("router middleware:map --dir app").example("router middleware:map --output src/types/project-middleware.ts").example("router middleware:map --watch").action(async(t)=>{try{let r=t.output||"middleware-map.ts",n=t.dir||"src";if(t.watch)await A(n,r);else await M(n,r)}catch(r){console.error(`Failed to generate middleware map: ${r.message}`),g.exit(1)}})}function me(e){e.command("router:types","Generate TypeScript types for router extensions").option("--output <file>","Output file path",{default:"router-types.ts"}).option("--watch","Watch for changes in router files").example("router router:types").example("router router:types --output src/types/router.ts").example("router router:types --watch").action(async(t)=>{try{let r=t.output||"router-types.ts";if(t.watch)await U(r);else await C(r)}catch(r){console.error(`Failed to generate router types: ${r.message}`),g.exit(1)}})}function ge(e){e.command("openapi","Generate OpenAPI specification for API routes").option("--output <file>","Output file path",{default:"openapi.json"}).option("--title <title>","API title",{default:"API Documentation"}).option("--version <version>","API version",{default:"1.0.0"}).option("--description <description>","API description").option("--base-path <path>","Base API path",{default:"/"}).option("--servers <urls>","Comma-separated list of server URLs").option("--tags","Group endpoints by tags",{default:!0}).option("--security","Include security schemes if available",{default:!0}).example("router openapi").example("router openapi --output api-spec.json").example('router openapi --title "My API" --version 2.0').example("router openapi --servers http://localhost:3000,https://api.example.com").action(async(t)=>{try{await L(t)}catch(r){console.error(`Failed to generate OpenAPI specification: ${r.message}`),g.exit(1)}})}function fe(e){e.command("health","Check router health and configuration").option("--verbose","Show detailed health information").example("router health").example("router health --verbose").action(async(t)=>{try{await G(t)}catch(r){console.error(`Health check failed: ${r.message}`),g.exit(1)}}),e.command("test:routes","Test routes by making HTTP requests").option("--base-url <url>","Base URL for testing",{default:"http://localhost:3000"}).option("--filter <pattern>","Filter routes by path pattern").option("--method <methods>","Test only specific HTTP methods (comma-separated)").option("--timeout <ms>","Request timeout in milliseconds",{default:5000}).example("router test:routes").example("router test:routes --base-url http://localhost:8080").example('router test:routes --filter "/api/*"').example("router test:routes --method GET,POST").action(async(t)=>{try{await _(t)}catch(r){console.error(`Route testing failed: ${r.message}`),g.exit(1)}}),e.command("debug:route <path>","Debug route matching for a specific path").option("--method <method>","HTTP method to test",{default:"GET"}).option("--verbose","Show detailed matching information").example("router debug:route /api/users/123").example("router debug:route /api/users/123 --method POST --verbose").action(async(t,r)=>{try{await W(t,r)}catch(n){console.error(`Route debugging failed: ${n.message}`),g.exit(1)}}),e.command("cache:clear","Clear route caches").option("--stats","Show cache statistics before clearing").example("router cache:clear").example("router cache:clear --stats").action(async(t)=>{try{await q(t)}catch(r){console.error(`Cache clearing failed: ${r.message}`),g.exit(1)}}),e.command("validate","Validate route definitions and configuration").option("--strict","Use strict validation rules").option("--fix","Automatically fix simple issues").example("router validate").example("router validate --strict --fix").action(async(t)=>{try{await V(t)}catch(r){console.error(`Route validation failed: ${r.message}`),g.exit(1)}})}var he=Y();he.parse();
152
+ \uD83D\uDCCB Available routes:`);let s=(n.routes||[]).filter((l)=>l.method===r);if(s.length===0)console.log(` No routes defined for ${r} method`);else for(let l of s)console.log(` ${l.method} ${l.path}`)}}catch(n){throw u.error(`Route debugging failed: ${n.message}`),n}}async function q(e){u.info("\uD83D\uDDD1\uFE0F Clearing route caches...");try{let t=await b();if(e.stats){if(t.getCacheStats){let r=t.getCacheStats();console.log("\uD83D\uDCCA Cache statistics before clearing:"),console.log(` Hit rate: ${r.hitRate}%`),console.log(` Total hits: ${r.hits}`),console.log(` Total misses: ${r.misses}`),console.log(` Cache size: ${r.size}`)}if(t.routeCache)console.log(` Route cache entries: ${t.routeCache.size}`);if(t.templateCache)console.log(` Template cache entries: ${t.templateCache.size}`)}if(t.clearRouteCache)t.clearRouteCache();if(t.routeCache&&t.routeCache.clear)t.routeCache.clear();if(t.templateCache&&t.templateCache.clear)t.templateCache.clear();if(t.clearModelCache)t.clearModelCache();u.success("\u2705 Caches cleared successfully")}catch(t){throw u.error(`Cache clearing failed: ${t.message}`),t}}async function V(e){u.info("\uD83D\uDD0D Validating route definitions...");try{let r=(await b()).routes||[],n=[],c=[];for(let s of r){if(!s.method)n.push(`Route missing method: ${s.path}`);if(!s.path)n.push(`Route missing path: ${s.method||"UNKNOWN"}`);if(!s.handler)n.push(`Route missing handler: ${s.method} ${s.path}`);if(s.path&&!s.path.startsWith("/"))n.push(`Route path should start with '/': ${s.method} ${s.path}`);if(s.path&&s.path.includes("{")){let l=s.path.match(/\{[^}]+\}/g)||[];for(let i of l)if(!i.match(/^\{[a-z_]\w*(\?|:[^}]+)?\}$/i))n.push(`Invalid parameter syntax in ${s.method} ${s.path}: ${i}`)}if(e.strict){if(!s.name&&!s.path.includes("{")&&s.path!=="/")c.push(`Consider adding a name to route: ${s.method} ${s.path}`);if(s.path.includes("/admin")&&(!s.middleware||s.middleware.length===0))c.push(`Admin route missing middleware: ${s.method} ${s.path}`)}}let a=new Map;for(let s of r){let l=`${s.method}:${s.path}`;a.set(l,(a.get(l)||0)+1)}for(let[s,l]of a.entries())if(l>1)n.push(`Duplicate route detected: ${s} (${l} times)`);if(n.length===0&&c.length===0){u.success("\u2705 All route definitions are valid");return}if(n.length>0){u.error(`\u274C Found ${n.length} validation error(s):`);for(let s of n)console.log(` \u2022 ${s}`)}if(c.length>0){u.warning(`\u26A0\uFE0F Found ${c.length} warning(s):`);for(let s of c)console.log(` \u2022 ${s}`)}if(e.fix)u.info("\uD83D\uDD27 Auto-fixing is not yet implemented");if(n.length>0)x.exit(1)}catch(t){throw u.error(`Route validation failed: ${t.message}`),t}}function Y(){let e=new ce("router");return e.version(F),ue(e),de(e),pe(e),me(e),ge(e),e.help(),e}function ue(e){e.command("route:list","List all registered routes").option("-v, --verbose","Show detailed information including middleware").option("-vv, --extra-verbose","Show very detailed information").option("--path <path>","Filter routes by path prefix").option("--except-vendor","Exclude vendor routes").option("--only-vendor","Show only vendor routes").example("router route:list").example("router route:list -v").example("router route:list --path=/api").action(async(t)=>{try{await B(t)}catch(r){console.error(`Failed to list routes: ${r.message}`),g.exit(1)}}),e.command("route:types","Generate TypeScript types for route names").option("--output <file>","Output file path",{default:"route-types.ts"}).option("--watch","Watch for changes in routes directory").example("router route:types").example("router route:types --output src/types/routes.ts").example("router route:types --watch").action(async(t)=>{try{let r=t.output||"route-types.ts";if(t.watch)await H(r);else await j(r)}catch(r){console.error(`Failed to generate route types: ${r.message}`),g.exit(1)}})}function de(e){e.command("middleware:types","Generate TypeScript types for middleware configurations").option("--output <file>","Output file path",{default:"middleware-types.ts"}).option("--watch","Watch for changes in middleware directory").example("router middleware:types").example("router middleware:types --output src/types/middleware.ts").example("router middleware:types --watch").action(async(t)=>{try{let r=t.output||"middleware-types.ts";if(t.watch)await D(r);else await v(r)}catch(r){console.error(`Failed to generate middleware types: ${r.message}`),g.exit(1)}}),e.command("middleware:map","Generate TypeScript types for all middleware in the project").option("--dir <directory>","Directory to scan for middleware classes",{default:"src"}).option("--output <file>","Output file path",{default:"middleware-map.ts"}).option("--watch","Watch for changes in the specified directory").example("router middleware:map").example("router middleware:map --dir app").example("router middleware:map --output src/types/project-middleware.ts").example("router middleware:map --watch").action(async(t)=>{try{let r=t.output||"middleware-map.ts",n=t.dir||"src";if(t.watch)await A(n,r);else await M(n,r)}catch(r){console.error(`Failed to generate middleware map: ${r.message}`),g.exit(1)}})}function pe(e){e.command("router:types","Generate TypeScript types for router extensions").option("--output <file>","Output file path",{default:"router-types.ts"}).option("--watch","Watch for changes in router files").example("router router:types").example("router router:types --output src/types/router.ts").example("router router:types --watch").action(async(t)=>{try{let r=t.output||"router-types.ts";if(t.watch)await U(r);else await C(r)}catch(r){console.error(`Failed to generate router types: ${r.message}`),g.exit(1)}})}function me(e){e.command("openapi","Generate OpenAPI specification for API routes").option("--output <file>","Output file path",{default:"openapi.json"}).option("--title <title>","API title",{default:"API Documentation"}).option("--version <version>","API version",{default:"1.0.0"}).option("--description <description>","API description").option("--base-path <path>","Base API path",{default:"/"}).option("--servers <urls>","Comma-separated list of server URLs").option("--tags","Group endpoints by tags",{default:!0}).option("--security","Include security schemes if available",{default:!0}).example("router openapi").example("router openapi --output api-spec.json").example('router openapi --title "My API" --version 2.0').example("router openapi --servers http://localhost:3000,https://api.example.com").action(async(t)=>{try{await L(t)}catch(r){console.error(`Failed to generate OpenAPI specification: ${r.message}`),g.exit(1)}})}function ge(e){e.command("health","Check router health and configuration").option("--verbose","Show detailed health information").example("router health").example("router health --verbose").action(async(t)=>{try{await G(t)}catch(r){console.error(`Health check failed: ${r.message}`),g.exit(1)}}),e.command("test:routes","Test routes by making HTTP requests").option("--base-url <url>","Base URL for testing",{default:"http://localhost:3000"}).option("--filter <pattern>","Filter routes by path pattern").option("--method <methods>","Test only specific HTTP methods (comma-separated)").option("--timeout <ms>","Request timeout in milliseconds",{default:5000}).example("router test:routes").example("router test:routes --base-url http://localhost:8080").example('router test:routes --filter "/api/*"').example("router test:routes --method GET,POST").action(async(t)=>{try{await _(t)}catch(r){console.error(`Route testing failed: ${r.message}`),g.exit(1)}}),e.command("debug:route <path>","Debug route matching for a specific path").option("--method <method>","HTTP method to test",{default:"GET"}).option("--verbose","Show detailed matching information").example("router debug:route /api/users/123").example("router debug:route /api/users/123 --method POST --verbose").action(async(t,r)=>{try{await W(t,r)}catch(n){console.error(`Route debugging failed: ${n.message}`),g.exit(1)}}),e.command("cache:clear","Clear route caches").option("--stats","Show cache statistics before clearing").example("router cache:clear").example("router cache:clear --stats").action(async(t)=>{try{await q(t)}catch(r){console.error(`Cache clearing failed: ${r.message}`),g.exit(1)}}),e.command("validate","Validate route definitions and configuration").option("--strict","Use strict validation rules").option("--fix","Automatically fix simple issues").example("router validate").example("router validate --strict --fix").action(async(t)=>{try{await V(t)}catch(r){console.error(`Route validation failed: ${r.message}`),g.exit(1)}})}var fe=Y();fe.parse();
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{L,o,M,k,a,_,we,be,Re,z,ve,ue,lt,ut,l,xe,de,dt,pt,ht,mt,gt,ft,yt,Te,V,Ce,Se,Ee,Pe,Me,ke,$e,Ae,Oe,Ie,Fe,De,Ne,pe,he}from"../chunk-sccx6r6k.js";var y=Symbol("controller"),p=Symbol("route"),u=Symbol("middleware"),c=Symbol("param");function D(t={}){return(e)=>(e[L]=t,e)}function b(t,e){return function(n,r,s){let i=n.constructor===Function?n:n.constructor;if(!i[o])i[o]=[];let g={token:t,optional:e?.optional,tags:e?.tags,when:e?.when};i[o][s]=g}}function x(){return(t,e,n)=>{if(!t[M])t[M]=[];t[M][n]=!0}}function T(t){return function(e,n,r){if(!e[k])e[k]=[];e[k][r]=t}}function E(t,e){return function(n){let r={prefix:t||"",middleware:e?.middleware||[],tags:e?.tags||[]};return n[y]=r,n}}function P(t="",e){return d("GET",t,e)}function h(t="",e){return d("POST",t,e)}function w(t="",e){return d("PUT",t,e)}function F(t="",e){return d("DELETE",t,e)}function C(t="",e){return d("PATCH",t,e)}function I(t="",e){return d("OPTIONS",t,e)}function R(t="",e){return d("HEAD",t,e)}function d(t,e,n){return function(r,s,i){if(!r.constructor[p])r.constructor[p]=[];let g={method:t,path:e,middleware:n?.middleware||[],tags:n?.tags||[]};return r.constructor[p].push({...g,propertyKey:s,handler:i.value}),i}}function O(...t){return function(e,n,r){if(n&&r){if(!e.constructor[u])e.constructor[u]=new Map;e.constructor[u].set(n,t)}else e[u]=t;return r||e}}function j(t){return m("param",t)}function Y(t){return m("query",t)}function K(){return m("body")}function q(t){return m("header",t)}function v(t){return m("cookie",t)}function H(t){return m("param",void 0,t)}function m(t,e,n){return function(r,s,i){if(!r.constructor[c])r.constructor[c]=new Map;if(!r.constructor[c].has(s))r.constructor[c].set(s,[]);let g={type:t,key:e,token:n};r.constructor[c].get(s)[i]=g}}class f{static getInjectableMetadata(t){return t[L]}static getInjectMetadata(t){return t[o]||[]}static getOptionalMetadata(t){return t[M]||[]}static getTaggedMetadata(t){return t[k]||[]}static getControllerMetadata(t){return t[y]}static getAllRoutes(t){return t[p]||[]}static getMiddlewareMetadata(t,e){if(e)return t[u]?.get(e)||[];return t[u]||[]}static getParamMetadata(t,e){return t[c]?.get(e)||[]}}class A extends a{registerController(t){if(!f.getControllerMetadata(t))throw Error(`Class ${t.name} is not decorated with @Controller`);this.singleton(t,t);let n=f.getAllRoutes(t);for(let r of n);}resolve(t,e){if(typeof t==="function"){let n=f.getInjectableMetadata(t);if(n)try{return super.resolve(t,e)}catch{switch(n.scope||"transient"){case"singleton":this.singleton(t,t);break;case"transient":this.transient(t,t);break;default:this.transient(t,t)}}}return super.resolve(t,e)}}var N=new A;export{Fe as AuthGuard,Oe as AuthService,gt as AuthServiceProvider,xe as BaseDeferredServiceProvider,l as BaseServiceProvider,_ as BindingBuilder,ut as BindingConditions,K as Body,y as CONTROLLER_METADATA_KEY,ke as CacheManager,mt as CacheServiceProvider,Te as ConfigService,dt as ConfigServiceProvider,Ce as ConsoleLogger,a as Container,ue as ContextualContainer,E as Controller,v as Cookie,a as DIContainer,Ee as DatabaseConnection,ht as DatabaseServiceProvider,A as DecoratorContainer,ve as DefaultContextualBindingBuilder,de as DefaultServiceProviderManager,F as Delete,z as EnvironmentManager,lt as EnvironmentPresets,pe as EventBus,he as EventDispatcher,yt as EventServiceProvider,Se as FileLogger,P as Get,R as Head,q as Header,L as INJECTABLE_METADATA_KEY,o as INJECT_METADATA_KEY,b as Inject,H as InjectParam,D as Injectable,Ie as JwtService,V as Logger,pt as LoggingServiceProvider,u as MIDDLEWARE_METADATA_KEY,$e as MemoryCache,f as MetadataReader,M as OPTIONAL_METADATA_KEY,x as Optional,I as Options,c as PARAM_METADATA_KEY,j as Param,C as Patch,h as Post,Me as PostRepository,w as Put,Y as Query,p as ROUTE_METADATA_KEY,Ae as RedisCache,k as TAGGED_METADATA_KEY,T as Tagged,O as UseMiddleware,Pe as UserRepository,Ne as ValidationPipe,ft as ValidationServiceProvider,De as Validator,Re as createContainer,N as decoratorContainer,we as getContainer,be as setContainer};
2
+ import{fe,p,K,J,h,ye,nt,st,it,we,ot,_e,nr,sr,y,at,ze,ir,or,ar,cr,lr,ur,dr,ct,be,lt,ut,dt,pt,ht,mt,gt,ft,yt,wt,bt,Rt,vt,Ve,We}from"../chunk-q4ktdehf.js";var g=Symbol("controller"),l=Symbol("route"),s=Symbol("middleware"),i=Symbol("param");function M(t={}){return(e)=>(e[fe]=t,e)}function A(t,e){return function(n,r,a){let o=n.constructor===Function?n:n.constructor;if(!o[p])o[p]=[];let d={token:t,optional:e?.optional,tags:e?.tags,when:e?.when};o[p][a]=d}}function D(){return(t,e,n)=>{if(!t[K])t[K]=[];t[K][n]=!0}}function b(t){return function(e,n,r){if(!e[J])e[J]=[];e[J][r]=t}}function x(t,e){return function(n){let r={prefix:t||"",middleware:e?.middleware||[],tags:e?.tags||[]};return n[g]=r,n}}function T(t="",e){return c("GET",t,e)}function E(t="",e){return c("POST",t,e)}function P(t="",e){return c("PUT",t,e)}function w(t="",e){return c("DELETE",t,e)}function F(t="",e){return c("PATCH",t,e)}function _(t="",e){return c("OPTIONS",t,e)}function C(t="",e){return c("HEAD",t,e)}function c(t,e,n){return function(r,a,o){if(!r.constructor[l])r.constructor[l]=[];let d={method:t,path:e,middleware:n?.middleware||[],tags:n?.tags||[]};return r.constructor[l].push({...d,propertyKey:a,handler:o.value}),o}}function I(...t){return function(e,n,r){if(n&&r){if(!e.constructor[s])e.constructor[s]=new Map;e.constructor[s].set(n,t)}else e[s]=t;return r||e}}function R(t){return u("param",t)}function O(t){return u("query",t)}function j(){return u("body")}function Y(t){return u("header",t)}function L(t){return u("cookie",t)}function q(t){return u("param",void 0,t)}function u(t,e,n){return function(r,a,o){if(!r.constructor[i])r.constructor[i]=new Map;if(!r.constructor[i].has(a))r.constructor[i].set(a,[]);let d={type:t,key:e,token:n};r.constructor[i].get(a)[o]=d}}class m{static getInjectableMetadata(t){return t[fe]}static getInjectMetadata(t){return t[p]||[]}static getOptionalMetadata(t){return t[K]||[]}static getTaggedMetadata(t){return t[J]||[]}static getControllerMetadata(t){return t[g]}static getAllRoutes(t){return t[l]||[]}static getMiddlewareMetadata(t,e){if(e)return t[s]?.get(e)||[];return t[s]||[]}static getParamMetadata(t,e){return t[i]?.get(e)||[]}}class f extends h{registerController(t){if(!m.getControllerMetadata(t))throw Error(`Class ${t.name} is not decorated with @Controller`);this.singleton(t,t);let n=m.getAllRoutes(t);for(let r of n);}resolve(t,e){if(typeof t==="function"){let n=m.getInjectableMetadata(t);if(n)try{return super.resolve(t,e)}catch{switch(n.scope||"transient"){case"singleton":this.singleton(t,t);break;case"transient":this.transient(t,t);break;default:this.transient(t,t)}}}return super.resolve(t,e)}}var v=new f;export{bt as AuthGuard,yt as AuthService,lr as AuthServiceProvider,at as BaseDeferredServiceProvider,y as BaseServiceProvider,ye as BindingBuilder,sr as BindingConditions,j as Body,g as CONTROLLER_METADATA_KEY,mt as CacheManager,cr as CacheServiceProvider,ct as ConfigService,ir as ConfigServiceProvider,lt as ConsoleLogger,h as Container,_e as ContextualContainer,x as Controller,L as Cookie,h as DIContainer,dt as DatabaseConnection,ar as DatabaseServiceProvider,f as DecoratorContainer,ot as DefaultContextualBindingBuilder,ze as DefaultServiceProviderManager,w as Delete,we as EnvironmentManager,nr as EnvironmentPresets,Ve as EventBus,We as EventDispatcher,dr as EventServiceProvider,ut as FileLogger,T as Get,C as Head,Y as Header,fe as INJECTABLE_METADATA_KEY,p as INJECT_METADATA_KEY,A as Inject,q as InjectParam,M as Injectable,wt as JwtService,be as Logger,or as LoggingServiceProvider,s as MIDDLEWARE_METADATA_KEY,gt as MemoryCache,m as MetadataReader,K as OPTIONAL_METADATA_KEY,D as Optional,_ as Options,i as PARAM_METADATA_KEY,R as Param,F as Patch,E as Post,ht as PostRepository,P as Put,O as Query,l as ROUTE_METADATA_KEY,ft as RedisCache,J as TAGGED_METADATA_KEY,b as Tagged,I as UseMiddleware,pt as UserRepository,vt as ValidationPipe,ur as ValidationServiceProvider,Rt as Validator,it as createContainer,v as decoratorContainer,nt as getContainer,st as setContainer};
package/dist/index.d.ts CHANGED
@@ -25,6 +25,7 @@ export { enableRequestContext, getCurrentRequest, request, runWithRequest, runWi
25
25
  export * from './session';
26
26
  export * from './response/compression';
27
27
  export * from './response/response-factory';
28
+ export { ENRICHED_NOT_FOUND_RESPONSE } from './response/markers';
28
29
  export * from './router';
29
30
  export { MiddlewareGroupRegistry, middlewareGroups } from './router/middleware-groups';
30
31
  export * from './testing';