@stacksjs/bun-router 0.1.7 → 0.1.8

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.
Files changed (100) hide show
  1. package/dist/chunk-4wd1d6ay.js +416 -0
  2. package/dist/{chunk-nf3kv7kv.js → chunk-8rrs7556.js} +1 -1
  3. package/dist/{chunk-3y4gaz7v.js → chunk-m4aaj9ay.js} +1 -1
  4. package/dist/cli.js +30 -59
  5. package/dist/container/index.js +1 -1
  6. package/dist/index.js +2 -2
  7. package/package.json +9 -1
  8. package/dist/chunk-03m2j6h7.js +0 -2
  9. package/dist/chunk-08cw7ejr.js +0 -3
  10. package/dist/chunk-0e4g0fyv.js +0 -62
  11. package/dist/chunk-0mmn02yw.js +0 -2
  12. package/dist/chunk-126c9qm3.js +0 -2
  13. package/dist/chunk-12p13817.js +0 -2
  14. package/dist/chunk-14v65c37.js +0 -4
  15. package/dist/chunk-1b6a7t3v.js +0 -231
  16. package/dist/chunk-1wenkmk0.js +0 -2
  17. package/dist/chunk-2152npfd.js +0 -2
  18. package/dist/chunk-26w23krx.js +0 -2
  19. package/dist/chunk-2g8m379z.js +0 -10
  20. package/dist/chunk-2rr178et.js +0 -1654
  21. package/dist/chunk-2w8f3swz.js +0 -29
  22. package/dist/chunk-4r1x4afz.js +0 -12
  23. package/dist/chunk-4wyw66zk.js +0 -2
  24. package/dist/chunk-4z5sf8ag.js +0 -2
  25. package/dist/chunk-58tfvayh.js +0 -4
  26. package/dist/chunk-5be9x5cq.js +0 -3
  27. package/dist/chunk-5dp83qcx.js +0 -397
  28. package/dist/chunk-5f0d9j9a.js +0 -2
  29. package/dist/chunk-5z52b0fc.js +0 -28
  30. package/dist/chunk-5zrnk2kq.js +0 -4
  31. package/dist/chunk-6bbmkwng.js +0 -3
  32. package/dist/chunk-6dmqtdnq.js +0 -2
  33. package/dist/chunk-6e91956t.js +0 -3
  34. package/dist/chunk-6rv8w5jk.js +0 -2
  35. package/dist/chunk-6x1feysm.js +0 -3
  36. package/dist/chunk-7qnxdedn.js +0 -321
  37. package/dist/chunk-7y72hm1x.js +0 -2
  38. package/dist/chunk-8hbhfh6b.js +0 -194
  39. package/dist/chunk-8kfzygg5.js +0 -3
  40. package/dist/chunk-8wpj3fqe.js +0 -351
  41. package/dist/chunk-8wydx2we.js +0 -2
  42. package/dist/chunk-8zjnjvv7.js +0 -2
  43. package/dist/chunk-9805tt8n.js +0 -341
  44. package/dist/chunk-988h4bzr.js +0 -2
  45. package/dist/chunk-9b6a58ac.js +0 -2
  46. package/dist/chunk-a8fcaywb.js +0 -2
  47. package/dist/chunk-bfjwn7yg.js +0 -2
  48. package/dist/chunk-bp2522mm.js +0 -2
  49. package/dist/chunk-brpgjyqg.js +0 -3
  50. package/dist/chunk-bswe62q4.js +0 -48
  51. package/dist/chunk-c3v796c8.js +0 -943
  52. package/dist/chunk-ccqmwdry.js +0 -2
  53. package/dist/chunk-ck0crwnx.js +0 -2
  54. package/dist/chunk-cqgkxcb4.js +0 -2
  55. package/dist/chunk-dntnakjy.js +0 -2
  56. package/dist/chunk-dxg045wj.js +0 -5
  57. package/dist/chunk-e3qej0jr.js +0 -4
  58. package/dist/chunk-ettdpnrw.js +0 -60
  59. package/dist/chunk-ezqwq17j.js +0 -185
  60. package/dist/chunk-ezx3qsez.js +0 -2
  61. package/dist/chunk-f72nnjy4.js +0 -15413
  62. package/dist/chunk-fna5n0ey.js +0 -246
  63. package/dist/chunk-fqhckdt8.js +0 -2
  64. package/dist/chunk-fr6hbx25.js +0 -2
  65. package/dist/chunk-g9cwng6w.js +0 -3
  66. package/dist/chunk-gd3za5x0.js +0 -2
  67. package/dist/chunk-gf28608k.js +0 -2
  68. package/dist/chunk-h1dj6v8q.js +0 -3
  69. package/dist/chunk-hjxe7k2g.js +0 -2
  70. package/dist/chunk-hrkgznbn.js +0 -2
  71. package/dist/chunk-j6h5v0br.js +0 -2
  72. package/dist/chunk-kjtjbcq4.js +0 -71
  73. package/dist/chunk-mgb01qdv.js +0 -14
  74. package/dist/chunk-n24c9whp.js +0 -2
  75. package/dist/chunk-n2j24b0h.js +0 -4540
  76. package/dist/chunk-nhmtg01n.js +0 -84
  77. package/dist/chunk-p0qhpnqh.js +0 -70
  78. package/dist/chunk-p0w1x8y2.js +0 -3
  79. package/dist/chunk-p3dk1w2w.js +0 -216
  80. package/dist/chunk-q4e9pxs7.js +0 -3
  81. package/dist/chunk-q5dv1kyy.js +0 -2
  82. package/dist/chunk-qnqgf9tq.js +0 -2
  83. package/dist/chunk-qvwy1808.js +0 -898
  84. package/dist/chunk-r18f77vc.js +0 -12
  85. package/dist/chunk-r63za1mr.js +0 -2
  86. package/dist/chunk-rft8gw92.js +0 -7851
  87. package/dist/chunk-ryvmyskt.js +0 -4211
  88. package/dist/chunk-sa6mx308.js +0 -2
  89. package/dist/chunk-sw0chtw4.js +0 -4
  90. package/dist/chunk-va0pc7hx.js +0 -2
  91. package/dist/chunk-vcp8dnjq.js +0 -412
  92. package/dist/chunk-vg1erq1q.js +0 -2
  93. package/dist/chunk-vsh4390q.js +0 -358
  94. package/dist/chunk-w0jv49ch.js +0 -11
  95. package/dist/chunk-wm805tte.js +0 -35
  96. package/dist/chunk-xg9xscqz.js +0 -1
  97. package/dist/chunk-xj9h6mc9.js +0 -2
  98. package/dist/chunk-ytvzwrq3.js +0 -51
  99. package/dist/chunk-zde7ebc4.js +0 -288
  100. package/dist/chunk-zmqsv2xy.js +0 -2
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var d=Object.defineProperty;var e=(a)=>a;function f(a,b){this[a]=e.bind(null,b)}var g=(a,b)=>{for(var c in b)d(a,c,{get:b[c],enumerable:!0,configurable:!0,set:f.bind(b,c)})};var h=import.meta.require;
3
- export{g as Yu,h as Zu};
3
+ export{g as xb,h as yb};
@@ -79,4 +79,4 @@ This usually indicates a circular or very deep dependency chain.
79
79
  Current resolution chain:
80
80
  ${n.map((r,i)=>` ${i+1}. ${r}`).join(`
81
81
  `)}`)}t.resolving.add(e),t.depth++;try{let n=this.bindings.get(e);if(n){if(n.metadata.when&&!n.metadata.when(t))throw Error(`Contextual binding condition not met for: ${this.tokenToString(e)}`);return this.createInstance(n,t)}if(this.parent){let r={resolving:new Set,depth:0,container:this.parent,token:e};return this.parent.resolveInternal(e,r)}if(this.options.autoRegister&&typeof e==="function")return this.autoRegisterAndResolve(e,t);if(this.options.strictMode)throw Error(`No binding found for: ${this.tokenToString(e)}`);if(typeof e==="function")return this.createInstanceFromConstructor(e,t);throw Error(`Cannot resolve: ${this.tokenToString(e)}`)}finally{t.resolving.delete(e),t.depth--}}createInstance(e,t){let n;if(e.metadata.scope==="singleton"&&this.instances.has(e.token))n=this.instances.get(e.token);else if(e.metadata.scope==="scoped"&&t.requestId){let i=this.scopedInstances.get(t.requestId);if(i?.has(e.token))n=i.get(e.token);else{if(n=this.createNewInstance(e,t),!i)this.scopedInstances.set(t.requestId,new Map);this.scopedInstances.get(t.requestId).set(e.token,n)}}else if(n=this.createNewInstance(e,t),e.metadata.scope==="singleton")this.instances.set(e.token,n);let r=this.tokenToString(e.token);if(this.interceptors.has(r)){let i=this.interceptors.get(r);for(let o of i)n=o(n)}return n}createNewInstance(e,t){if(e.value!==void 0)return e.value;if(e.factory){let n=this.resolveDependencies(e.metadata.dependencies||[],t);return e.factory(...n)}if(e.instance)return e.instance;if(e.implementation)return this.createInstanceFromConstructor(e.implementation,t);throw Error(`Invalid binding configuration for: ${this.tokenToString(e.token)}`)}createInstanceFromConstructor(e,t){let n=this.getConstructorDependencies(e),r=this.resolveDependencies(n,t),i=new e(...r);if(this.options.enableDecorators)this.applyDecorators(i,e);return i}getConstructorDependencies(e){let t=Reflect.getMetadata?.(h,e)||e[h];if(!t&&e.constructor)t=e.constructor[h];if(!t&&typeof e==="function"&&e.prototype){let r=e[h];if(r)t=r}if(!t&&typeof e==="function"){let r=e[h];if(r)t=r}if(t)return t.map((r)=>r.token);let n=Reflect.getMetadata?.("design:paramtypes",e);if(n)return n;return this.parseConstructorDependencies(e)}parseConstructorDependencies(e){let n=e.toString().match(/constructor\s*\(([^)]*)\)/);if(!n||!n[1])return[];return n[1].split(",").map((r)=>r.trim().split(":")[0].trim()).filter((r)=>r.length>0)}resolveDependencies(e,t){return e.map((n)=>this.resolveInternal(n,t))}autoRegisterAndResolve(e,t){let n=Reflect.getMetadata?.(oe,e),r={token:e,implementation:e,metadata:{scope:n?.scope||this.options.defaultScope,tags:n?.tags}};return this.register(r),this.resolveInternal(e,t)}applyDecorators(e,t){let n=Reflect.getMetadata?.("decorators",t);if(n)for(let r of n)r(e)}hasTag(e,t){return e.metadata.tags?.includes(t)??!1}tokenToString(e){if(typeof e==="string")return e;if(typeof e==="symbol")return e.toString();if(typeof e==="function")return e.name||"anonymous";return"unknown"}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}class F{container;binding;constructor(e,t){this.container=e;this.binding={token:t,metadata:{scope:"transient"}}}to(e){return this.binding.implementation=e,this}toValue(e){return this.binding.value=e,this.binding.metadata.scope="singleton",this}toFactory(e){return this.binding.factory=e,this}toInstance(e){return this.binding.instance=e,this.binding.metadata.scope="singleton",this}inSingletonScope(){return this.binding.metadata.scope="singleton",this}inTransientScope(){return this.binding.metadata.scope="transient",this}inScopedScope(){return this.binding.metadata.scope="scoped",this}inRequestScope(){return this.binding.metadata.scope="request",this}withTags(...e){return this.binding.metadata.tags=[...this.binding.metadata.tags||[],...e],this}when(e){return this.binding.metadata.when=e,this}lazy(){return this.binding.metadata.lazy=!0,this}build(){return this.container.register(this.binding),this.container}}var m=null;function Ie(){if(!m)m=new g;return m}function Pe(e){m=e}function De(e){return new g(e)}class j{environments=new Map;currentEnvironment;variables=new Map;constructor(e="development"){this.currentEnvironment=e,this.loadEnvironmentVariables()}register(e){return this.environments.set(e.name,e),this}setEnvironment(e){if(!this.environments.has(e))throw Error(`Environment ${e} is not registered`);return this.currentEnvironment=e,this.loadEnvironmentVariables(),this}getCurrentEnvironment(){return this.currentEnvironment}getEnvironment(e){return this.environments.get(e||this.currentEnvironment)}is(...e){return e.includes(this.currentEnvironment)}get(e,t){return this.variables.get(e)??t}set(e,t){return this.variables.set(e,t),this}hasFeature(e){return this.getEnvironment()?.features.includes(e)??!1}loadEnvironmentVariables(){let e=this.getEnvironment();if(e)for(let[t,n]of Object.entries(e.variables))this.variables.set(t,n)}}class V{container;binding;constructor(e,t){this.container=e;this.binding={token:t,conditions:[],priority:0,metadata:{scope:"transient"}}}when(e){return this.binding.conditions.push(e),this}whenEnvironment(...e){let t={type:"environment",predicate:(n)=>e.includes(n.environment||"development"),description:`Environment is one of: ${e.join(", ")}`};return this.when(t)}whenTag(e){let t={type:"tag",predicate:(n)=>n.parent?.token?.toString().includes(e)??!1,description:`Parent has tag: ${e}`};return this.when(t)}whenParent(e){let t={type:"parent",predicate:(n)=>n.parent?.token===e,description:`Parent token is: ${e.toString()}`};return this.when(t)}whenRequest(e){let t={type:"request",predicate:e,description:"Custom request condition"};return this.when(t)}withPriority(e){return this.binding.priority=e,this}withFallback(e){return this.binding.fallback=e,this}to(e){return this.binding.implementation=e,this}toValue(e){return this.binding.value=e,this.binding.metadata.scope="singleton",this}toFactory(e){return this.binding.factory=e,this}inSingletonScope(){return this.binding.metadata.scope="singleton",this}inTransientScope(){return this.binding.metadata.scope="transient",this}build(){return this.container.registerContextualBinding(this.binding),this.container}}class ae extends g{contextualBindings=new Map;environmentManager;constructor(e){super(e);this.environmentManager=new j}bindContextual(e){return new V(this,e)}registerContextualBinding(e){if(!this.contextualBindings.has(e.token))this.contextualBindings.set(e.token,[]);let t=this.contextualBindings.get(e.token);return t.push(e),t.sort((n,r)=>r.priority-n.priority),this}getEnvironmentManager(){return this.environmentManager}forDevelopment(e){return this.bindContextual(e).whenEnvironment("development")}forProduction(e){return this.bindContextual(e).whenEnvironment("production")}forTesting(e){return this.bindContextual(e).whenEnvironment("test","testing")}forStaging(e){return this.bindContextual(e).whenEnvironment("staging")}resolve(e,t){let n={container:this,token:e,environment:t?.environment||this.environmentManager.getCurrentEnvironment(),requestId:t?.requestId||this.generateContextualRequestId(),depth:t?.depth||0,resolving:t?.resolving||new Set,parent:t?.parent},r=this.findContextualBinding(e,n);if(r)return this.createInstanceFromContextualBinding(r,n);return super.resolve(e,n)}findContextualBinding(e,t){let n=this.contextualBindings.get(e);if(!n)return;for(let r of n)if(this.evaluateConditions(r.conditions,t))return r;return}evaluateConditions(e,t){return e.every((n)=>{try{return n.predicate(t)}catch(r){return console.warn(`Error evaluating binding condition: ${n.description}`,r),!1}})}createInstanceFromContextualBinding(e,t){try{return this.createInstance(e,t)}catch(n){if(e.fallback)return console.warn(`Contextual binding failed, using fallback for ${e.token.toString()}`),this.createInstance(e.fallback,t);throw n}}generateContextualRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}class de{static development(){return{name:"development",variables:{DEBUG:!0,LOG_LEVEL:"debug",CACHE_TTL:60,DB_POOL_SIZE:5},services:{logger:"ConsoleLogger",cache:"MemoryCache",database:"SQLiteDatabase"},features:["hot-reload","debug-toolbar","detailed-errors"]}}static production(){return{name:"production",variables:{DEBUG:!1,LOG_LEVEL:"error",CACHE_TTL:3600,DB_POOL_SIZE:20},services:{logger:"FileLogger",cache:"RedisCache",database:"PostgreSQLDatabase"},features:["performance-monitoring","error-tracking"]}}static testing(){return{name:"test",variables:{DEBUG:!1,LOG_LEVEL:"warn",CACHE_TTL:1,DB_POOL_SIZE:1},services:{logger:"NullLogger",cache:"MemoryCache",database:"InMemoryDatabase"},features:["test-doubles","fast-teardown"]}}static staging(){return{name:"staging",variables:{DEBUG:!0,LOG_LEVEL:"info",CACHE_TTL:1800,DB_POOL_SIZE:10},services:{logger:"FileLogger",cache:"RedisCache",database:"PostgreSQLDatabase"},features:["performance-monitoring","debug-toolbar"]}}}class ce{static environment(...e){return{type:"environment",predicate:(t)=>e.includes(t.environment||"development"),description:`Environment is one of: ${e.join(", ")}`}}static feature(e){return{type:"custom",predicate:(t)=>t.container.getEnvironmentManager().hasFeature(e),description:`Feature ${e} is enabled`}}static envVar(e,t){return{type:"custom",predicate:(n)=>n.container.getEnvironmentManager().get(e)===t,description:`Environment variable ${e} equals ${t}`}}static requestPattern(e){return{type:"request",predicate:(t)=>e.test(t.requestId||""),description:`Request ID matches pattern: ${e.toString()}`}}static timeRange(e,t){return{type:"custom",predicate:()=>{let n=new Date().getHours();return n>=e&&n<=t},description:`Time is between ${e}:00 and ${t}:00`}}static custom(e,t){return{type:"custom",predicate:e,description:t||"Custom condition"}}}class u{version;dependencies;environment;priority=0;boot(e){}shutdown(e){}singleton(e,t,n){e.singleton(t,n)}transient(e,t,n){e.transient(t,n)}value(e,t,n){e.value(t,n)}factory(e,t,n){e.factory(t,n)}when(e,t){return{bind:(n)=>e.bind(n).when(t)}}forEnvironment(e,...t){return this.when(e,(n)=>t.includes(n.environment||"development"))}}class U extends u{isDeferred(){return!0}}class ue{providers=new Map;deferredProviders=new Map;loadedProviders=new Set;bootedProviders=new Set;container;constructor(e){this.container=e}register(e){if(this.isConditionalProvider(e)){let t=e.shouldLoad(this.container);if(t instanceof Promise)t.then((n)=>{if(n)this.doRegister(e)});else if(!t)return this}return this.doRegister(e),this}async boot(){let e=Array.from(this.providers.values()).sort((t,n)=>(n.priority||0)-(t.priority||0));this.validateDependencies(e);for(let t of e)if(!this.loadedProviders.has(t.name))await this.loadProvider(t);for(let t of e)if(!this.bootedProviders.has(t.name))await this.bootProvider(t)}async shutdown(){let e=Array.from(this.providers.values()).reverse();for(let t of e)if(t.shutdown)try{await t.shutdown(this.container)}catch(n){console.error(`Error shutting down provider ${t.name}:`,n)}this.providers.clear(),this.deferredProviders.clear(),this.loadedProviders.clear(),this.bootedProviders.clear()}getProvider(e){return this.providers.get(e)}getProviders(){return Array.from(this.providers.values())}async loadDeferredProvider(e){for(let[t,n]of this.deferredProviders)if(n.provides().includes(e)&&!this.loadedProviders.has(t))await this.loadProvider(n),await this.bootProvider(n),this.deferredProviders.delete(t)}doRegister(e){if(this.providers.has(e.name))throw Error(`Provider ${e.name} is already registered`);if(this.providers.set(e.name,e),this.isDeferredProvider(e))this.deferredProviders.set(e.name,e)}async loadProvider(e){try{await e.register(this.container),this.loadedProviders.add(e.name)}catch(t){throw Error(`Failed to load provider ${e.name}: ${t}`)}}async bootProvider(e){if(e.boot)try{await e.boot(this.container),this.bootedProviders.add(e.name)}catch(t){throw Error(`Failed to boot provider ${e.name}: ${t}`)}else this.bootedProviders.add(e.name)}validateDependencies(e){let t=new Set(e.map((n)=>n.name));for(let n of e)if(n.dependencies){for(let r of n.dependencies)if(!t.has(r))throw Error(`Provider ${n.name} depends on ${r}, but it's not registered`)}}isDeferredProvider(e){return"provides"in e&&"isDeferred"in e}isConditionalProvider(e){return"shouldLoad"in e}}class le extends u{name="config";priority=100;register(e){e.singleton("config",H),this.forEnvironment(e,"development").bind("config.debug").toValue(!0),this.forEnvironment(e,"production").bind("config.debug").toValue(!1),this.forEnvironment(e,"test").bind("config.debug").toValue(!1)}}class ge extends u{name="logging";priority=90;register(e){e.factory("logger",(t)=>new f(t.get("logging",{}))),this.forEnvironment(e,"development").bind("logger").toFactory(()=>new G),this.forEnvironment(e,"production").bind("logger").toFactory((t)=>new K(t.get("logging.file","./app.log")))}}class he extends u{name="database";dependencies=["config","logging"];register(e){e.singleton("database",W),e.transient("userRepository",z),e.transient("postRepository",J)}async boot(e){await e.resolve("database").connect()}async shutdown(e){await e.resolve("database").disconnect()}}class pe extends u{name="cache";dependencies=["config"];register(e){e.singleton("cache",X),this.forEnvironment(e,"development").bind("cache.store").toFactory(()=>new Y),this.forEnvironment(e,"production").bind("cache.store").toFactory((t)=>new Z(t.get("cache.redis")))}}class me extends u{name="auth";dependencies=["config","database"];register(e){e.singleton("authService",Q),e.singleton("jwtService",ee),e.transient("authGuard",te)}}class fe extends u{name="validation";register(e){e.singleton("validator",ne),e.factory("validationPipe",(t)=>new re(t))}}class ye extends U{name="events";provides(){return["eventBus","eventDispatcher",b,C]}register(e){e.singleton("eventBus",b),e.singleton("eventDispatcher",C)}}class H{get(e,t){return t}}class f{config;constructor(e){this.config=e}log(e){console.log(e)}}class G extends f{constructor(){super({})}}class K extends f{filePath;constructor(e){super({});this.filePath=e}}class W{async connect(){}async disconnect(){}}class z{db;constructor(e){this.db=e}}class J{db;constructor(e){this.db=e}}class X{store;constructor(e){this.store=e}}class Y{cache=new Map}class Z{config;constructor(e){this.config=e}}class Q{jwt;userRepo;constructor(e,t){this.jwt=e;this.userRepo=t}}class ee{config;constructor(e){this.config=e}}class te{auth;constructor(e){this.auth=e}}class ne{validate(e,t){return!0}}class re{validator;constructor(e){this.validator=e}}class b{emit(e,t){}}class C{bus;constructor(e){this.bus=e}}
82
- export{a as Sq,x as Tq,T as Uq,E as Vq,w as Wq,R as Xq,S as Yq,B as Zq,I as _q,P as $q,D as ar,k as br,M as cr,_ as dr,A as er,O as fr,ve as gr,p as hr,l as ir,L as jr,v as kr,q as lr,N as mr,xe as nr,Te as or,Ee as pr,oe as qr,h as rr,Se as sr,Be as tr,g as ur,F as vr,Ie as wr,Pe as xr,De as yr,j as zr,V as Ar,ae as Br,de as Cr,ce as Dr,u as Er,U as Fr,ue as Gr,le as Hr,ge as Ir,he as Jr,pe as Kr,me as Lr,fe as Mr,ye as Nr,H as Or,f as Pr,G as Qr,K as Rr,W as Sr,z as Tr,J as Ur,X as Vr,Y as Wr,Z as Xr,Q as Yr,ee as Zr,te as _r,ne as $r,re as as,b as bs,C as cs};
82
+ export{a as ka,x as la,T as ma,E as na,w as oa,R as pa,S as qa,B as ra,I as sa,P as ta,D as ua,k as va,M as wa,_ as xa,A as ya,O as za,ve as Aa,p as Ba,l as Ca,L as Da,v as Ea,q as Fa,N as Ga,xe as Ha,Te as Ia,Ee as Ja,oe as Ka,h as La,Se as Ma,Be as Na,g as Oa,F as Pa,Ie as Qa,Pe as Ra,De as Sa,j as Ta,V as Ua,ae as Va,de as Wa,ce as Xa,u as Ya,U as Za,ue as _a,le as $a,ge as ab,he as bb,pe as cb,me as db,fe as eb,ye as fb,H as gb,f as hb,G as ib,K as jb,W as kb,z as lb,J as mb,X as nb,Y as ob,Z as pb,Q as qb,ee as rb,te as sb,ne as tb,re as ub,b as vb,C as wb};
package/dist/cli.js CHANGED
@@ -1,86 +1,57 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{Zp as fe}from"./chunk-vcp8dnjq.js";import"./chunk-p0qhpnqh.js";import"./chunk-nf3kv7kv.js";import v from"process";import{existsSync as _e}from"fs";import U from"fs/promises";import se from"os";import H from"path";import S from"process";import{EventEmitter as je}from"events";import x from"process";import re from"process";import q from"process";import A from"process";import M from"process";import ae from"tty";import bt,{stdin as cs,stdout as us}from"process";class le{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=se.homedir(),t=H.join(e,".config","clapp");this.configPath=H.join(t,"telemetry.json")}async isEnabled(){if(S.env.DO_NOT_TRACK==="1"||S.env.DO_NOT_TRACK==="true")return!1;if(S.env.NO_TELEMETRY==="1"||S.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let r={event:e,...t,timestamp:Date.now(),platform:se.platform(),nodeVersion:S.version};if(this.events.push(r),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:S.env.DO_NOT_TRACK==="1"||S.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(_e(this.configPath)){let e=await U.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=H.dirname(this.configPath);await U.mkdir(t,{recursive:!0}),await U.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var Jt=new le;function ke(e,t={}){let s={_:[]},r=t.alias||{},n=new Set(t.boolean||[]),o={};for(let a of Object.keys(r))for(let i of r[a])o[i]=a;for(let a of n)if(r[a])for(let i of r[a])n.add(i);function l(a,i){let u=o[a]||a;if(s[u]=i,r[u])for(let d of r[u])s[d]=i;if(o[a]&&r[o[a]])for(let d of r[o[a]])s[d]=i;s[a]=i}for(let a=0;a<e.length;a++){let i=e[a];if(i==="--"){s._.push(...e.slice(a+1));break}if(i.startsWith("--")){let u=i.indexOf("=");if(u!==-1){let d=i.slice(2,u),h=i.slice(u+1);l(d,h)}else{let d=i.slice(2);if(d.startsWith("no-")){let m=d.slice(3);l(m,!1);continue}let h=o[d]||d;if(n.has(h)||n.has(d))l(d,!0);else{let m=e[a+1];if(m!==void 0&&!m.startsWith("-"))l(d,m),a++;else l(d,!0)}}}else if(i.startsWith("-")&&i.length>1){let u=i.slice(1);for(let d=0;d<u.length;d++){let h=u[d],m=o[h]||h;if(d===u.length-1&&!n.has(m)&&!n.has(h)){let f=e[a+1];if(f!==void 0&&!f.startsWith("-"))l(h,f),a++;else l(h,!0)}else l(h,!0)}}else s._.push(i)}return s}function z(e){return e.replace(/[<[].+/,"").trim()}function Be(e){let t=/<([^>]+)>/g,s=/\[([^\]]+)\]/g,r=[],n=(a)=>{let i=!1,u=a[1];if(u.startsWith("..."))u=u.slice(3),i=!0;return{required:a[0].startsWith("<"),value:u,variadic:i}},o;while(o=t.exec(e))r.push(n(o));let l;while(l=s.exec(e))r.push(n(l));return r}function Ae(e){let t={alias:{},boolean:[]};for(let[s,r]of e.entries()){if(r.names.length>1)t.alias[r.names[0]]=r.names.slice(1);if(r.isBoolean)if(r.negated){if(!e.some((o,l)=>l!==s&&o.names.some((a)=>r.names.includes(a))&&typeof o.required==="boolean"))t.boolean.push(r.names[0])}else t.boolean.push(r.names[0])}return t}function ie(e){return e.reduce((t,s)=>t.length>=s.length?t:s,"")}function G(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function Ne(e){return e.replace(/([a-z])-([a-z])/g,(t,s,r)=>s+r.toUpperCase())}function Le(e,t,s){let r=0,n=t.length,o=e,l;for(;r<n;++r)l=o[t[r]],o=o[t[r]]=r===n-1?s:l!=null?l:!!~t[r+1].indexOf(".")||!(+t[r+1]>-1)?{}:[]}function Pe(e,t){for(let s of Object.keys(t)){let r=t[s];if(r.shouldTransform){if(e[s]=Array.prototype.concat.call([],e[s]),typeof r.transformFunction==="function")e[s]=e[s].map(r.transformFunction)}}}function Ve(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function ce(e){return e.split(".").map((t,s)=>s===0?Ne(t):t).join(".")}class B extends Error{exitCode=2;isUsageError=!0;constructor(e){super(e);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
4
-
5
- Stack trace:
6
- ${this.stack}`;return this.message}}function De(){let{env:e}=re,{TERM:t,TERM_PROGRAM:s}=e;if(re.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||s==="Terminus-Sublime"||s==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var N="\x1B",w=`${N}[`;var ne={to(e,t){if(!t)return`${w}${e+1}G`;return`${w}${t+1};${e+1}H`},move(e,t){let s="";if(e<0)s+=`${w}${-e}D`;else if(e>0)s+=`${w}${e}C`;if(t<0)s+=`${w}${-t}A`;else if(t>0)s+=`${w}${t}B`;return s},up:(e=1)=>`${w}${e}A`,down:(e=1)=>`${w}${e}B`,forward:(e=1)=>`${w}${e}C`,backward:(e=1)=>`${w}${e}D`,nextLine:(e=1)=>`${w}E`.repeat(e),prevLine:(e=1)=>`${w}F`.repeat(e),left:`${w}G`,hide:`${w}?25l`,show:`${w}?25h`,save:`${N}7`,restore:`${N}8`};var es={screen:`${w}2J`,up:(e=1)=>`${w}1J`.repeat(e),down:(e=1)=>`${w}J`.repeat(e),line:`${w}2K`,lineEnd:`${w}K`,lineStart:`${w}1K`,lines(e){let t="";for(let s=0;s<e;s++)t+=this.line+(s<e-1?ne.up():"");if(e)t+=ne.left;return t}},ts={screen:`${N}c`};function Fe(e,t){let s=[];for(let r=0;r<=t.length;r++)s[r]=[r];for(let r=0;r<=e.length;r++)s[0][r]=r;for(let r=1;r<=t.length;r++)for(let n=1;n<=e.length;n++)if(t.charAt(r-1)===e.charAt(n-1))s[r][n]=s[r-1][n-1];else s[r][n]=Math.min(s[r-1][n-1]+1,s[r][n-1]+1,s[r-1][n]+1);return s[t.length][e.length]}function ue(e,t,s=2,r=3){return t.map((n)=>({cmd:n,distance:Fe(e,n)})).filter(({distance:n})=>n<=s).sort((n,o)=>n.distance-o.distance).slice(0,r).map(({cmd:n})=>n)}class de{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,s){if(this.rawName=e,this.description=t,this.config=Object.assign({},s),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=z(e).split(",").map((r)=>{let n=r.trim().replace(/^-{1,2}/,"");if(n.startsWith("no-"))this.negated=!0,n=n.replace(/^no-/,"");return ce(n)}).sort((r,n)=>r.length>n.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var rs=q.argv,We=`${q.platform}-${q.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,oe=A.argv,Ue=`${A.platform}-${A.arch} node-${A.version}`;class K{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,s,r){this.rawName=e,this.description=t,this.config=s,this.cli=r,this.options=[],this.aliasNames=[],this.name=z(e);let n=z(e),o=n.indexOf(":");if(o>0)this.namespace=n.substring(0,o),this.name=n.substring(o+1);if(this.args=Be(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!s)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,s){let r=new de(e,t,s);return this.options.push(r),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof Y}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){return e=e.split(".")[0],!!this.options.find((t)=>t.names.includes(e))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:s,options:r,helpCallback:n}=this.cli.globalCommand,o=[{body:`${e}${s?`/${s}`:""}`}];if(o.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let i=ie(t.map((f)=>f.rawName)),u=new Map,d=[];for(let f of t)if(f.namespace){if(!u.has(f.namespace))u.set(f.namespace,[]);u.get(f.namespace).push(f)}else d.push(f);let h="";if(d.length>0)h+=d.map((f)=>` ${G(f.rawName,i.length)} ${f.description}`).join(`
7
- `);let m=Array.from(u.keys()).sort();for(let f of m){let Me=u.get(f);if(h.length>0)h+=`
8
-
9
- `;h+=` ${f}:
10
- `,h+=Me.map((te)=>` ${G(te.rawName,i.length-2)} ${te.description}`).join(`
11
- `)}o.push({title:"Commands",body:h}),o.push({title:"For more info, run any command with the `--help` flag",body:t.map((f)=>` $ ${e}${f.displayName===""?"":` ${f.displayName}`} --help`).join(`
12
- `)})}let a=this.isGlobalCommand?r:[...this.options,...r||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)a=a.filter((i)=>i.name!=="version");if(a.length>0){let i=ie(a.map((u)=>u.rawName));o.push({title:"Options",body:a.map((u)=>` ${G(u.rawName,i.length)} ${u.description} ${u.config.default===void 0?"":`(default: ${u.config.default})`}`).join(`
13
- `)})}if(this.examples.length>0)o.push({title:"Examples",body:this.examples.map((i)=>{if(typeof i==="function")return i(e);return i}).join(`
14
- `)});if(n)o=n(o)||o;console.log(o.map((i)=>i.title?`${i.title}:
15
- ${i.body}`:i.body).join(`
16
-
17
- `))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;if(t)console.log(`${e}/${t} ${typeof Bun<"u"?We:Ue}`)}checkRequiredArgs(){let e=this.args.filter((t)=>t.required).length;if(this.cli.args.length<e){let s=this.args.filter((n)=>n.required).slice(this.cli.args.length),r=s.map((n)=>`<${n.value}>`).join(" ");throw new B(`Missing required argument${s.length>1?"s":""}: ${r}
18
-
19
- Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let s of Object.keys(e))if(s!=="--"&&!this.hasOption(s)&&!t.hasOption(s)){let n=[...t.options,...this.options].flatMap((i)=>i.names),o=s.length>1?`--${s}`:`-${s}`,l=ue(s,n),a=`Unknown option \`${o}\``;if(l.length>0)a+=`
20
-
21
- Did you mean one of these?`,l.forEach((i)=>{let u=i.length>1?`--${i}`:`-${i}`;a+=`
22
- \u2022 ${u}`});throw a+=`
23
-
24
- Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new B(a)}}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,s=[...t.options,...this.options];for(let r of s){let n=e[r.name.split(".")[0]];if(r.required){let o=s.some((l)=>l.negated&&l.names.includes(r.name));if(n===!0||n===!1&&!o)throw new B(`Option \`${r.rawName}\` requires a value.
25
-
26
- Example: ${this.cli.name} ${this.rawName} ${r.rawName} <value>`)}}}}class Y extends K{constructor(e){super("@@global@@","",{},e)}}var He=K,C={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var I={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function Ge(){return!0}function ze(){let e={};e.supportsColor=Ge();function t(r,n=[]){let o=r===""?[]:[...n,r],l=function(i){if(!e.supportsColor)return i;let u="",d="";for(let h of o)if(h in I&&I[h]in C){let m=I[h];u+=C[m][0],d=C[m][1]+d}else if(h in C)u+=C[h][0],d=C[h][1]+d;return u+i+d},a=[...Object.keys(C),...Object.keys(I)];for(let i of a)if(!(i in l))Object.defineProperty(l,i,{get(){return t(i,o)}});return l}let s=[...Object.keys(C),...Object.keys(I)];for(let r of s)if(!(r in e))Object.defineProperty(e,r,{get(){return t(r)}});return e}var E=ze();class J extends je{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(e=""){super();this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new Y(this),this.globalCommand.usage("<command> [options]")}handleSignals(e){if(this.signalHandlersSet)return this;let t=async(s)=>{if(console.log(`
27
-
28
- Received ${s}, cleaning up...`),e)try{await e()}catch(r){console.error("Error during cleanup:",r)}x.exit(0)};return x.on("SIGINT",()=>t("SIGINT")),x.on("SIGTERM",()=>t("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(e=!0){return this.enableDidYouMean=e,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(e){return this.globalCommand.usage(e),this}command(e,t,s){if(!s)s={};let r=new He(e,t||"",s,this);return r.globalCommand=this.globalCommand,this.commands.push(r),r}option(e,t,s){return this.globalCommand.option(e,t,s),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t="-v, --version"){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},s,r){if(this.args=e,this.options=t,s)this.matchedCommand=s;if(r)this.matchedCommandName=r;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(e){if(console.log(E.red(`
29
- \u2717 Command "${e}" not found.
30
- `)),this.enableDidYouMean){let t=[];for(let r of this.commands){if(r.displayName)t.push(r.displayName);if(r.aliasNames)t.push(...r.aliasNames)}let s=ue(e,t);if(s.length>0)console.log(E.yellow("Did you mean one of these?")),s.forEach((r)=>console.log(` ${E.dim("\u2022")} ${this.name} ${r}`)),console.log("")}console.log(E.dim("Run"),`${this.name} --help`,E.dim("to see all available commands")),x.exit(1)}async parse(e=oe,t={}){let{run:s=!0,exitOnError:r=!1}=t;if(r)try{return await this.parse(e,{run:s})}catch(i){throw this.handleUsageError(i),i}if(this.rawArgs=e,!this.name)this.name=e[1]?Ve(e[1]):"cli";let n=!0,o=e.slice(2),l=o[0];if(l&&!l.startsWith("-")){for(let i of this.commands)if(i.isMatched(l)){let u=this.mri(o,i);n=!1;let d={...u,args:u.args.slice(1)};this.setParsedInfo(d,i,l),this.emit(`command:${l}`,i);break}}if(n){for(let i of this.commands)if(i.name===""){n=!1;let u=this.mri(o,i);this.setParsedInfo(u,i),this.emit("command:!",i);break}}if(n){let i=this.mri(e.slice(2));this.setParsedInfo(i)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),s=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),s=!1,this.unsetMatchedCommand();let a={args:this.args,options:this.options};if(s)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return a}mri(e,t){let s=[...this.globalCommand.options,...t?t.options:[]],r=Ae(s),n=[],o=e.indexOf("--");if(o>-1)n=e.slice(o+1),e=e.slice(0,o);let l=ke(e,r),a={_:l._};for(let m of Object.keys(l))if(m!=="_")a[ce(m)]=l[m];let i=a._,u={"--":n},d=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,h=Object.create(null);for(let m of s){if(!d&&m.config.default!==void 0)for(let f of m.names)u[f]=m.config.default;if(Array.isArray(m.config.type)){if(h[m.name]===void 0)h[m.name]={shouldTransform:!0,transformFunction:m.config.type[0]}}}for(let m of Object.keys(a))if(m!=="_"){let f=m.split(".");Le(u,f,a[m]),Pe(u,h)}return{args:i,options:u}}async run(e=oe){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!(!!e&&typeof e==="object"&&e.name==="ClappError"&&e.isUsageError!==!1))return;let r=e,n=r.message??"command-line error",o=this.name?`${this.name}: `:"",l=/--help/.test(n)?"":`
31
- Run \`${this.name??"cli"} --help\` for usage.`;x.stderr.write(`${o}${n}${l}
32
- `),x.exit(r.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:s}=this;if(!s||!s.commandAction)return;s.checkUnknownOptions(),s.checkOptionValue(),s.checkRequiredArgs();let r=[];s.args.forEach((a,i)=>{if(a.variadic)r.push(e.slice(i));else r.push(e[i])}),r.push(t);let n={command:s,args:r,options:t};for(let a of s.beforeHooks)await a(n);let o,l=async()=>{let a=s.commandAction.apply(this,r);if(a instanceof Promise)o=await a;else o=a;return o};if(s.middleware.length>0){let a=0,i=async()=>{if(a<s.middleware.length){let u=s.middleware[a++];await u({...n,next:i})}else await l()};await i()}else await l();for(let a of s.afterHooks)await a(n);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return x.removeAllListeners("SIGINT"),x.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class he{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,s=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:s})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,s]of this.cache.entries())if(e-s.timestamp>s.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var ns=new he;function qe(){if("FORCE_COLOR"in M.env)return M.env.FORCE_COLOR!=="0";if("NO_COLOR"in M.env||M.env.TERM==="dumb")return!1;if(M.platform==="win32")return!0;return ae.isatty(1)&&ae.isatty(2)}var me=qe();function y(e,t){if(!me)return(s)=>s;return(s)=>e+s+t}var Ke=y("\x1B[0m","\x1B[0m"),Ye=y("\x1B[31m","\x1B[39m"),Je=y("\x1B[32m","\x1B[39m"),Qe=y("\x1B[33m","\x1B[39m"),Xe=y("\x1B[34m","\x1B[39m"),Ze=y("\x1B[35m","\x1B[39m"),et=y("\x1B[36m","\x1B[39m"),tt=y("\x1B[37m","\x1B[39m"),st=y("\x1B[90m","\x1B[39m"),rt=y("\x1B[1m","\x1B[22m"),it=y("\x1B[3m","\x1B[23m"),nt=y("\x1B[4m","\x1B[24m"),ot=y("\x1B[2m","\x1B[22m"),at=y("\x1B[7m","\x1B[27m"),lt=y("\x1B[8m","\x1B[28m"),ct=y("\x1B[9m","\x1B[29m"),ut=y("\x1B[41m","\x1B[49m"),dt=y("\x1B[42m","\x1B[49m"),ht=y("\x1B[43m","\x1B[49m"),mt=y("\x1B[44m","\x1B[49m"),pt=y("\x1B[45m","\x1B[49m"),ft=y("\x1B[46m","\x1B[49m"),gt=y("\x1B[47m","\x1B[49m"),yt=me,$t={reset:Ke,red:Ye,green:Je,yellow:Qe,blue:Xe,magenta:Ze,cyan:et,white:tt,gray:st,bold:rt,italic:it,underline:nt,dim:ot,inverse:at,hidden:lt,strikethrough:ct,bgRed:ut,bgGreen:dt,bgYellow:ht,bgBlue:mt,bgMagenta:pt,bgCyan:ft,bgWhite:gt,isColorSupported:yt},wt=$t,vt=["up","down","left","right","space","enter","cancel"],ds={actions:new Set(vt),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var hs=bt.platform.startsWith("win"),ms=Symbol("clapp:cancel");var xt=De();var g=(e,t)=>xt?e:t,ps=g("\u25C6","*"),fs=g("\u25A0","x"),gs=g("\u25B2","x"),ys=g("\u25C7","o"),$s=g("\u250C","T"),Ct=g("\u2502","|"),ws=g("\u2514","\u2014"),bs=g("\u25CF",">"),vs=g("\u25CB"," "),xs=g("\u25FB","[\u2022]"),Cs=g("\u25FC","[+]"),Rs=g("\u25FB","[ ]"),Os=g("\u25AA","\u2022"),Ss=g("\u2500","-"),Ts=g("\u256E","+"),Is=g("\u251C","+"),Es=g("\u256F","+"),Ms=g("\u25CF","\u2022"),_s=g("\u25C6","*"),js=g("\u25B2","!"),ks=g("\u25A0","x");var Bs={light:g("\u2500","-"),heavy:g("\u2501","="),block:g("\u2588","#")};function Rt(){return`${wt.gray(Ct)} `}var As=Rt();var pe="0.1.7";import R from"fs/promises";import Q from"path";import L from"process";var b={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"},c={red:(e)=>`${b.red}${e}${b.reset}`,green:(e)=>`${b.green}${e}${b.reset}`,yellow:(e)=>`${b.yellow}${e}${b.reset}`,blue:(e)=>`${b.blue}${e}${b.reset}`,cyan:(e)=>`${b.cyan}${e}${b.reset}`,white:(e)=>`${b.white}${e}${b.reset}`,gray:(e)=>`${b.gray}${e}${b.reset}`,bold:(e)=>`${b.bold}${e}${b.reset}`,dim:(e)=>`${b.dim}${e}${b.reset}`,hex:(e)=>(t)=>t};async function P(e){let t=Object.entries(fe).map(([r,n])=>({name:r,className:n.constructor.name})),s=`/**
3
+ import{ja as k}from"./chunk-4wd1d6ay.js";import"./chunk-8rrs7556.js";import g from"process";import{CLI as ue}from"@stacksjs/clapp";var F="0.1.8";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(k).map(([n,c])=>({name:n,className:c.constructor.name})),r=`/**
33
4
  * This file is auto-generated.
34
5
  * DO NOT EDIT THIS FILE DIRECTLY.
35
6
  * To update, run 'bun router middleware:types'
36
7
  */
37
- import type { ${t.map((r)=>r.className).join(", ")} } from './middleware'
8
+ import type { ${t.map((n)=>n.className).join(", ")} } from './middleware'
38
9
 
39
10
  /**
40
11
  * Available middleware map with middleware names as keys
41
12
  */
42
13
  export interface MiddlewareMap {
43
- ${t.map((r)=>` '${r.name}': ${r.className}`).join(`
14
+ ${t.map((n)=>` '${n.name}': ${n.className}`).join(`
44
15
  `)}
45
16
  }
46
17
 
47
18
  /**
48
19
  * String literal type of available middleware names
49
20
  */
50
- export type MiddlewareName = ${t.map((r)=>`'${r.name}'`).join(" | ")}
21
+ export type MiddlewareName = ${t.map((n)=>`'${n.name}'`).join(" | ")}
51
22
 
52
23
  /**
53
24
  * Middleware configuration type for router setup
54
25
  */
55
- export type MiddlewareConfig = MiddlewareName | ${t.map((r)=>r.className).join(" | ")}
26
+ export type MiddlewareConfig = MiddlewareName | ${t.map((n)=>n.className).join(" | ")}
56
27
 
57
28
  /**
58
29
  * Function to check if a middleware name is valid
59
30
  */
60
31
  export function isValidMiddleware(name: string): name is MiddlewareName {
61
- return [${t.map((r)=>`'${r.name}'`).join(", ")}].includes(name)
32
+ return [${t.map((n)=>`'${n.name}'`).join(", ")}].includes(name)
62
33
  }
63
- `;await R.writeFile(e,s)}async function ge(e){let t=[],s=await R.readdir(e,{withFileTypes:!0});for(let r of s){let n=Q.join(e,r.name);if(r.isDirectory())t.push(...await ge(n));else if(r.isFile()&&r.name.endsWith(".ts"))t.push(n)}return t}async function St(e){let t=[];try{let s=await R.readFile(e,"utf-8"),r=/export\s+(?:default\s+)?class\s+(\w+)\s+(?:implements\s+Middleware|\{[\s\S]*?handle\s*\([\s\S]*?\))/g,n=null;while(n=r.exec(s)){let o=n[1];if(o.includes("Middleware")||n[0].includes("implements Middleware")){let a=Q.relative(L.cwd(),e).replace(/\.ts$/,"");t.push({name:o,path:a})}}}catch(s){console.warn(c.yellow(`Error scanning file ${e}: ${s}`))}return t}async function V(e,t){console.log(c.blue(`Scanning directory: ${e} for middleware classes...`));try{let s=await ge(e),r=[];for(let i of s){let u=await St(i);r.push(...u)}if(r.length===0){console.warn(c.yellow("No middleware classes found in the specified directory."));return}let n=r.map((i)=>`import { ${i.name} } from '${i.path}'`).join(`
64
- `),o=r.map((i)=>` ${i.name}: typeof ${i.name}`).join(`
65
- `),l=r.map((i)=>i.name).join(" | "),a=`/**
34
+ `;await f.writeFile(e,r)}async function A(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 A(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 A(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(`
35
+ `),a=n.map((i)=>` ${i.name}: typeof ${i.name}`).join(`
36
+ `),s=n.map((i)=>i.name).join(" | "),l=`/**
66
37
  * This file is auto-generated.
67
38
  * DO NOT EDIT THIS FILE DIRECTLY.
68
39
  * To update, run 'bun router middleware:map'
69
40
  */
70
41
 
71
- ${n}
42
+ ${c}
72
43
 
73
44
  /**
74
45
  * Map of all available middleware in the project
75
46
  */
76
47
  export interface MiddlewareMap {
77
- ${o}
48
+ ${a}
78
49
  }
79
50
 
80
51
  /**
81
52
  * Type representing all available middleware classes in the project
82
53
  */
83
- export type MiddlewareType = ${l}
54
+ export type MiddlewareType = ${s}
84
55
 
85
56
  /**
86
57
  * Type for a middleware handler function
@@ -91,10 +62,10 @@ export type MiddlewareHandler = (req: any, next: () => Promise<Response>) => Pro
91
62
  * Ensure the middleware module exports all the middleware classes used in the project
92
63
  */
93
64
  export const middlewareMap: MiddlewareMap = {
94
- ${r.map((i)=>` ${i.name}: ${i.name}`).join(`,
65
+ ${n.map((i)=>` ${i.name}: ${i.name}`).join(`,
95
66
  `)}
96
67
  }
97
- `;await R.writeFile(t,a),console.log(c.green(`\u2728 Middleware map generated at ${t} with ${r.length} middleware classes`)),console.log(c.blue("Found middleware classes:"));for(let i of r)console.log(c.cyan(` - ${i.name} (${i.path})`))}catch(s){throw console.error(c.red(`Error generating middleware map: ${s}`)),s}}async function ye(e,t){try{await R.access(e)}catch{console.error(c.red(`Directory not found at ${e}`)),L.exit(1)}await V(e,t),console.log(c.blue(`Watching for changes in ${e}...`));let s=null,r=R.watch(e,{recursive:!0});for await(let n of r){if(s)clearTimeout(s);s=setTimeout(async()=>{console.log(c.yellow("Changes detected. Regenerating middleware map..."));try{await V(e,t)}catch(o){console.error(c.red(`Error regenerating middleware map: ${o.message}`))}s=null},500)}}async function $e(e){let t=Q.join(L.cwd(),"src","middleware");try{await R.access(t)}catch{console.error(c.red(`Middleware directory not found at ${t}`)),L.exit(1)}await P(e),console.log(c.green(`\u2728 Middleware types generated at ${e}`)),console.log(c.blue(`Watching for changes in ${t}...`));let s=null,r=R.watch(t,{recursive:!0});for await(let n of r){if(s)clearTimeout(s);s=setTimeout(async()=>{console.log(c.yellow("Changes detected in middleware directory. Regenerating types..."));try{await P(e),console.log(c.green(`\u2728 Middleware types regenerated at ${e}`))}catch(o){console.error(c.red(`Error regenerating types: ${o.message}`))}s=null},500)}}import Tt from"fs/promises";import X from"process";async function we(e){try{let t=`${X.cwd()}/routes/index.ts`,{router:s}=await import(t);if(!s)console.error(c.red(`Could not find router instance in ${t}.`)),X.exit(1);let r=s.routes||[];if(r.length===0)console.log(c.yellow("No routes defined. Creating empty OpenAPI specification."));let n=r.filter((i)=>i.type==="api"||i.path.startsWith("/api")),o={openapi:"3.0.3",info:{title:e.title||"API Documentation",version:e.version||"1.0.0",description:e.description||"Generated API documentation"},servers:It(e),paths:{},components:{schemas:{},securitySchemes:{}},tags:[]},l=new Set;for(let i of n){let u=o.paths[i.path]||{},d="";if(e.tags!==!1)d=i.tag||Et(i.path),l.add(d);let h={summary:i.summary||`${i.method.toUpperCase()} ${i.path}`,description:i.description||"",operationId:i.name||Mt(i.method,i.path),parameters:_t(i),responses:kt(i)};if(d)h.tags=[d];if(["post","put","patch"].includes(i.method.toLowerCase()))h.requestBody=Bt(i);if(e.security!==!1&&i.middleware){let m=At(i.middleware);if(m.length>0)h.security=m}u[i.method.toLowerCase()]=h,o.paths[i.path]=u}if(e.tags!==!1)o.tags=Array.from(l).map((i)=>({name:i,description:`Operations related to ${i}`}));let a=e.output||"openapi.json";await Tt.writeFile(a,JSON.stringify(o,null,2)),console.log(c.green(`\u2728 OpenAPI specification generated at ${a}`)),console.log(c.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(c.red(`Routes file not found at ${X.cwd()}/routes/index.ts`)),console.error(c.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(c.red(`Error generating OpenAPI specification: ${t.message}`));throw t}}function It(e){let t=[];if(e.servers){let s=e.servers.split(",").map((r)=>r.trim());for(let r of s)t.push({url:r,description:`Server ${t.length+1}`})}if(t.length===0)t.push({url:e.basePath||"/",description:"Default server"});return t}function Et(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 Mt(e,t){let r=t.replace(/\{([^}]+)\}/g,"_$1").split("/").filter(Boolean);if(r.length===0)return e.toLowerCase();let n=e.toLowerCase();for(let o of r)n+=o.charAt(0).toUpperCase()+o.slice(1);return n}function _t(e){let t=[],s=e.path.match(/\{([^}]+)\}/g);if(s)for(let r of s){let n=r.slice(1,-1);t.push({name:n,in:"path",required:!0,schema:{type:"string"},description:`Path parameter: ${n}`})}if(e.params&&e.params.query)for(let[r,n]of Object.entries(e.params.query))t.push({name:r,in:"query",schema:jt(n),required:n.required===!0,description:n.description||`Query parameter: ${r}`});return t}function jt(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 kt(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[s,r]of Object.entries(e.responses))t[s]={description:r.description||`Response with status ${s}`,content:{"application/json":{schema:r.schema||{}}}};return t}function Bt(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 At(e){let t=[];for(let s of e){let r=typeof s==="string"?s:s.name;if(r&&r.toLowerCase().includes("auth"))if(r.toLowerCase().includes("jwt"))t.push({BearerAuth:[]});else if(r.toLowerCase().includes("apikey"))t.push({ApiKeyAuth:[]});else if(r.toLowerCase().includes("basic"))t.push({BasicAuth:[]});else t.push({[r]:[]})}return t}import Z from"fs/promises";import be from"path";import T from"process";async function D(e){try{let t=`${T.cwd()}/routes/index.ts`,{router:s}=await import(t);if(!s)console.error(c.red(`Could not find router instance in ${t}.`)),T.exit(1);let r=Object.getOwnPropertyNames(Object.getPrototypeOf(s)).filter((l)=>!l.startsWith("_")&&l!=="constructor"&&typeof s[l]==="function"),n=Object.keys(s).filter((l)=>!["routes","middleware","hooks","config"].includes(l)&&typeof l==="string"&&!l.startsWith("_")),o=`/**
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 D(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 L(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 z(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 U 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=`/**
98
69
  * This file is auto-generated.
99
70
  * DO NOT EDIT THIS FILE DIRECTLY.
100
71
  * To update, run 'bun router router:types'
@@ -105,10 +76,10 @@ import type { Router, RouteHandler, MiddlewareHandler, RouteDefinition } from '.
105
76
  * Extended Router interface with all available methods and properties
106
77
  */
107
78
  export interface ExtendedRouter extends Router {
108
- ${r.map((l)=>{if(["get","post","put","delete","patch","options","head"].includes(l))return`${l}(path: string, handler: RouteHandler, options?: any): Router`;else if(l==="use")return`${l}(middleware: MiddlewareHandler | MiddlewareHandler[]): Router`;else if(l==="group")return`${l}(prefix: string, callback: (router: Router) => void): Router`;else return`${l}: Function`}).join(`
79
+ ${n.map((s)=>{if(["get","post","put","delete","patch","options","head"].includes(s))return`${s}(path: string, handler: RouteHandler, options?: any): Router`;else if(s==="use")return`${s}(middleware: MiddlewareHandler | MiddlewareHandler[]): Router`;else if(s==="group")return`${s}(prefix: string, callback: (router: Router) => void): Router`;else return`${s}: Function`}).join(`
109
80
  `)}
110
81
 
111
- ${n.map((l)=>{let a=typeof s[l];return`${l}: ${a}`}).join(`
82
+ ${c.map((s)=>{let l=typeof r[s];return`${s}: ${l}`}).join(`
112
83
  `)}
113
84
  }
114
85
 
@@ -139,9 +110,9 @@ export type RouterExtension = {
139
110
  * \`\`\`
140
111
  */
141
112
  export type ExtendRouter<T extends RouterExtension> = Router & T
142
- `;await Z.writeFile(e,o),console.log(c.green(`\u2728 Router types generated at ${e}`))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(c.red(`Routes file not found at ${T.cwd()}/routes/index.ts`)),console.error(c.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(c.red(`Error generating router types: ${t.message}`));throw t}}async function ve(e){let t=[be.join(T.cwd(),"routes"),be.join(T.cwd(),"src")],s=!1;for(let n of t)try{await Z.access(n),s=!0;break}catch{}if(!s)console.error(c.red("No valid source directories found to watch.")),T.exit(1);await D(e),console.log(c.green(`\u2728 Router types generated at ${e}`)),console.log(c.blue("Watching for changes in router files..."));let r=null;for(let n of t)try{let o=Z.watch(n,{recursive:!0});(async()=>{for await(let l of o){if(r)clearTimeout(r);r=setTimeout(async()=>{console.log(c.yellow("Changes detected in router files. Regenerating types..."));try{await D(e),console.log(c.green(`\u2728 Router types regenerated at ${e}`))}catch(a){console.error(c.red(`Error regenerating types: ${a.message}`))}r=null},500)}})()}catch{}}import ee from"fs/promises";import Nt from"path";import O from"process";async function xe(e){try{let t=`${O.cwd()}/routes/index.ts`,{router:s}=await import(t);if(!s)console.error(c.red(`Could not find router instance in ${t}.`)),O.exit(1);let r=s.routes||[];if(r.length===0){console.log(c.yellow("No routes defined."));return}let n=r;if(e.path)n=n.filter((o)=>o.path.startsWith(e.path));console.log(c.bold(`
143
- Routes:`)),console.log(c.dim("+-----------------+-------------------------+------------------+----------------+")),console.log(c.dim("| ")+c.bold("Method")+c.dim(" | ")+c.bold("URI")+c.dim(" | ")+c.bold("Name")+c.dim(" | ")+c.bold("Handler")+c.dim(" |")),console.log(c.dim("+-----------------+-------------------------+------------------+----------------+")),n.forEach((o)=>{let l=F(o.method,15),a=F(o.path,23),i=F(o.name||"",16),u;if(typeof o.handler==="string")u=o.handler;else if(typeof o.handler==="function")u=o.handler.name?`${o.handler.name}()`:"Anonymous Function";else u="Class Handler";if(u=F(u,14),console.log(c.dim("| ")+Lt(o.method)(l)+c.dim(" | ")+c.green(a)+c.dim(" | ")+c.yellow(i)+c.dim(" | ")+c.blue(u)+c.dim(" |")),e.verbose&&o.middleware&&o.middleware.length>0)console.log(c.dim("| | ")+c.dim("Middleware: ")+o.middleware.map((d)=>typeof d==="string"?d:d.name||"Anonymous").join(", ")+c.dim(" |"))}),console.log(c.dim("+-----------------+-------------------------+------------------+----------------+")),console.log(`
144
- Showing ${n.length} routes`)}catch(t){throw console.error(c.red(`Error: ${t.message}`)),console.error(c.yellow(`Make sure your routes are defined in ${O.cwd()}/routes/index.ts and export a 'router' instance.`)),t}}async function W(e){try{let t=`${O.cwd()}/routes/index.ts`,{router:s}=await import(t);if(!s)console.error(c.red(`Could not find router instance in ${t}.`)),O.exit(1);let r=s.routes||[];if(r.length===0)console.log(c.yellow("No routes defined. Creating empty types file."));let n=r.map((a)=>{if(a.name)return a.name;let i=a.method.toLowerCase(),u=a.path.replace(/^\//,"").replace(/\//g,".").replace(/\{([^}]+)\}/g,":$1");return u?`${i}.${u}`:i}),o=[...new Set(n)],l=`/**
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 B(e){let t=[U.join(y.cwd(),"routes"),U.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 H(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(`
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=`/**
145
116
  * This file is auto-generated.
146
117
  * DO NOT EDIT THIS FILE DIRECTLY.
147
118
  * To update, run 'bun router route:types'
@@ -150,13 +121,13 @@ Showing ${n.length} routes`)}catch(t){throw console.error(c.red(`Error: ${t.mess
150
121
  /**
151
122
  * String literal type for all available route names
152
123
  */
153
- export type RouteName = ${o.length>0?o.map((a)=>`'${a}'`).join(" | "):"string"}
124
+ export type RouteName = ${a.length>0?a.map((l)=>`'${l}'`).join(" | "):"string"}
154
125
 
155
126
  /**
156
127
  * Object type with route names as keys and string (for path generation) as values
157
128
  */
158
129
  export interface RouteNameMap {
159
- ${o.map((a)=>` '${a}': string`).join(`
130
+ ${a.map((l)=>` '${l}': string`).join(`
160
131
  `)}
161
132
  }
162
133
 
@@ -169,13 +140,13 @@ export type RouteFunction = <T extends RouteName>(name: T, params?: Record<strin
169
140
  * Validate that a string is a valid route name
170
141
  */
171
142
  export function isValidRouteName(name: string): name is RouteName {
172
- return [${o.map((a)=>`'${a}'`).join(", ")}].includes(name)
143
+ return [${a.map((l)=>`'${l}'`).join(", ")}].includes(name)
173
144
  }
174
- `;await ee.writeFile(e,l),console.log(c.green(`\u2728 Route types generated at ${e}`))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(c.red(`Routes file not found at ${O.cwd()}/routes/index.ts`)),console.error(c.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(c.red(`Error generating route types: ${t.message}`));throw t}}async function Ce(e){let t=Nt.join(O.cwd(),"routes");try{await ee.access(t)}catch{console.error(c.red(`Routes directory not found at ${t}`)),O.exit(1)}await W(e),console.log(c.green(`\u2728 Route types generated at ${e}`)),console.log(c.blue(`Watching for changes in ${t}...`));let s=null,r=ee.watch(t,{recursive:!0});for await(let n of r){if(s)clearTimeout(s);s=setTimeout(async()=>{console.log(c.yellow("Changes detected in routes directory. Regenerating types..."));try{await W(e),console.log(c.green(`\u2728 Route types regenerated at ${e}`))}catch(o){console.error(c.red(`Error regenerating types: ${o.message}`))}s=null},500)}}function F(e,t){return(e+" ".repeat(t)).substring(0,t)}function Lt(e){switch(e.toUpperCase()){case"GET":return c.cyan;case"POST":return c.green;case"PUT":return c.yellow;case"PATCH":return c.yellow;case"DELETE":return c.red;case"OPTIONS":return c.gray;default:return c.white}}import j from"process";var _={success:(e)=>c.green(`\u2728 ${e}`),info:(e)=>c.blue(e),warning:(e)=>c.yellow(e),error:(e)=>c.red(e),dim:(e)=>c.dim(e),bold:(e)=>c.bold(e)},p={success:(e)=>console.log(_.success(e)),info:(e)=>console.log(_.info(e)),warning:(e)=>console.log(_.warning(e)),error:(e)=>console.error(_.error(e)),debug:(e)=>console.debug(_.dim(e))};async function k(){try{let e=`${j.cwd()}/routes/index.ts`,{router:t}=await import(e);if(!t)p.error(`Could not find router instance in ${e}.`),j.exit(1);return t}catch(e){if(e.code==="ERR_MODULE_NOT_FOUND")p.error(`Routes file not found at ${j.cwd()}/routes/index.ts`),p.warning('Make sure your routes are defined and exported as "router" in routes/index.ts');else p.error(`Error loading router: ${e.message}`);throw e}}function Pt(e){switch(e.toUpperCase()){case"GET":return c.cyan.toString();case"POST":return c.green.toString();case"PUT":return c.yellow.toString();case"PATCH":return c.yellow.toString();case"DELETE":return c.red.toString();case"OPTIONS":return c.gray.toString();default:return c.white.toString()}}async function Re(e){p.info("\uD83D\uDD0D Checking router health...");try{let t=await k(),s=t.routes||[],r=t.globalMiddleware||[],n=t.namedRoutes||new Map,o={totalRoutes:s.length,namedRoutes:n.size,globalMiddleware:r.length,routesByMethod:{},duplicateRoutes:[],routesWithMiddleware:0,staticRoutes:0,dynamicRoutes:0},l=new Map;for(let a of s){let i=`${a.method}:${a.path}`;if(o.routesByMethod[a.method]=(o.routesByMethod[a.method]||0)+1,!l.has(i))l.set(i,[]);if(l.get(i).push(a.path),l.get(i).length>1)o.duplicateRoutes.push({path:a.path,method:a.method});if(a.middleware&&a.middleware.length>0)o.routesWithMiddleware++;if(a.path.includes("{")||a.path.includes("*"))o.dynamicRoutes++;else o.staticRoutes++}if(p.success("Router health check completed"),console.log(`\uD83D\uDCCA Routes: ${o.totalRoutes} total (${o.staticRoutes} static, ${o.dynamicRoutes} dynamic)`),console.log(`\uD83D\uDCDB Named routes: ${o.namedRoutes}`),console.log(`\uD83D\uDEE1\uFE0F Global middleware: ${o.globalMiddleware}`),console.log(`\uD83D\uDD27 Routes with middleware: ${o.routesWithMiddleware}`),e.verbose){console.log(`
175
- \uD83D\uDCC8 Routes by method:`);for(let[i,u]of Object.entries(o.routesByMethod)){let d=Pt(i);console.log(` ${c.hex(d)(i.padEnd(8))}: ${u}`)}if(o.duplicateRoutes.length>0){p.warning(`
176
- \u26A0\uFE0F Found ${o.duplicateRoutes.length} duplicate route(s):`);for(let i of o.duplicateRoutes)console.log(` ${i.method} ${i.path}`)}let a=[];if(o.totalRoutes===0)a.push("No routes defined");if(o.duplicateRoutes.length>0)a.push(`${o.duplicateRoutes.length} duplicate routes`);if(o.routesWithMiddleware===0&&o.globalMiddleware===0)a.push("No middleware configured");if(a.length>0){p.warning(`
177
- \u26A0\uFE0F Potential issues:`);for(let i of a)console.log(` \u2022 ${i}`)}else p.success(`
178
- \u2705 No issues detected`)}}catch(t){throw p.error(`Health check failed: ${t.message}`),t}}async function Oe(e){let t=e.baseUrl||"http://localhost:3000",s=e.timeout||5000,r=e.method?e.method.split(",").map((n)=>n.trim().toUpperCase()):null;p.info(`\uD83E\uDDEA Testing routes at ${t}...`);try{let o=(await k()).routes||[],l=o;if(e.filter){let i=new RegExp(e.filter.replace(/\*/g,".*"));l=o.filter((u)=>i.test(u.path))}if(r)l=l.filter((i)=>r.includes(i.method));if(l.length===0){p.warning("No routes match the specified filters");return}p.info(`Testing ${l.length} routes...`);let a={total:0,passed:0,failed:0,errors:[]};for(let i of l){if(a.total++,i.path.includes("{")){p.debug(`Skipping parameterized route: ${i.method} ${i.path}`);continue}try{let u=`${t}${i.path}`,d=await fetch(u,{method:i.method,signal:AbortSignal.timeout(s)});if(d.status<500)a.passed++,p.debug(`\u2705 ${i.method} ${i.path} \u2192 ${d.status}`);else a.failed++,a.errors.push({route:`${i.method} ${i.path}`,error:`HTTP ${d.status}`})}catch(u){a.failed++,a.errors.push({route:`${i.method} ${i.path}`,error:u.message})}}if(console.log(`
179
- \uD83D\uDCCA Test Results:`),console.log(` Total: ${a.total}`),console.log(` Passed: ${c.green(String(a.passed))}`),console.log(` Failed: ${c.red(String(a.failed))}`),a.errors.length>0){console.log(`
180
- \u274C Failures:`);for(let i of a.errors)console.log(` ${i.route}: ${i.error}`)}if(a.failed>0)j.exit(1);else p.success("All tests passed!")}catch(n){throw p.error(`Route testing failed: ${n.message}`),n}}async function Se(e,t){let s=t.method?.toUpperCase()||"GET";p.info(`\uD83D\uDD0D Debugging route matching for: ${s} ${e}`);try{let r=await k(),n=r.matchRoute?r.matchRoute(e,s):null;if(n){if(p.success("\u2705 Route matched!"),console.log(` Route: ${n.route.method} ${n.route.path}`),console.log(` Handler: ${typeof n.route.handler}`),Object.keys(n.params||{}).length>0){console.log(" Parameters:");for(let[o,l]of Object.entries(n.params))console.log(` ${o}: ${l}`)}if(n.route.middleware&&n.route.middleware.length>0)console.log(` Middleware: ${n.route.middleware.length} handler(s)`);if(n.route.name)console.log(` Named route: ${n.route.name}`)}else if(p.error(`\u274C No route matched for ${s} ${e}`),t.verbose){console.log(`
181
- \uD83D\uDCCB Available routes:`);let l=(r.routes||[]).filter((a)=>a.method===s);if(l.length===0)console.log(` No routes defined for ${s} method`);else for(let a of l)console.log(` ${a.method} ${a.path}`)}}catch(r){throw p.error(`Route debugging failed: ${r.message}`),r}}async function Te(e){p.info("\uD83D\uDDD1\uFE0F Clearing route caches...");try{let t=await k();if(e.stats){if(t.getCacheStats){let s=t.getCacheStats();console.log("\uD83D\uDCCA Cache statistics before clearing:"),console.log(` Hit rate: ${s.hitRate}%`),console.log(` Total hits: ${s.hits}`),console.log(` Total misses: ${s.misses}`),console.log(` Cache size: ${s.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();p.success("\u2705 Caches cleared successfully")}catch(t){throw p.error(`Cache clearing failed: ${t.message}`),t}}async function Ie(e){p.info("\uD83D\uDD0D Validating route definitions...");try{let s=(await k()).routes||[],r=[],n=[];for(let l of s){if(!l.method)r.push(`Route missing method: ${l.path}`);if(!l.path)r.push(`Route missing path: ${l.method||"UNKNOWN"}`);if(!l.handler)r.push(`Route missing handler: ${l.method} ${l.path}`);if(l.path&&!l.path.startsWith("/"))r.push(`Route path should start with '/': ${l.method} ${l.path}`);if(l.path&&l.path.includes("{")){let a=l.path.match(/\{[^}]+\}/g)||[];for(let i of a)if(!i.match(/^\{[a-z_]\w*(\?|:[^}]+)?\}$/i))r.push(`Invalid parameter syntax in ${l.method} ${l.path}: ${i}`)}if(e.strict){if(!l.name&&!l.path.includes("{")&&l.path!=="/")n.push(`Consider adding a name to route: ${l.method} ${l.path}`);if(l.path.includes("/admin")&&(!l.middleware||l.middleware.length===0))n.push(`Admin route missing middleware: ${l.method} ${l.path}`)}}let o=new Map;for(let l of s){let a=`${l.method}:${l.path}`;o.set(a,(o.get(a)||0)+1)}for(let[l,a]of o.entries())if(a>1)r.push(`Duplicate route detected: ${l} (${a} times)`);if(r.length===0&&n.length===0){p.success("\u2705 All route definitions are valid");return}if(r.length>0){p.error(`\u274C Found ${r.length} validation error(s):`);for(let l of r)console.log(` \u2022 ${l}`)}if(n.length>0){p.warning(`\u26A0\uFE0F Found ${n.length} warning(s):`);for(let l of n)console.log(` \u2022 ${l}`)}if(e.fix)p.info("\uD83D\uDD27 Auto-fixing is not yet implemented");if(r.length>0)j.exit(1)}catch(t){throw p.error(`Route validation failed: ${t.message}`),t}}function Ee(){let e=new J("router");return e.version(pe),Vt(e),Dt(e),Ft(e),Wt(e),Ut(e),e.help(),e}function Vt(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 xe(t)}catch(s){console.error(`Failed to list routes: ${s.message}`),v.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 s=t.output||"route-types.ts";if(t.watch)await Ce(s);else await W(s)}catch(s){console.error(`Failed to generate route types: ${s.message}`),v.exit(1)}})}function Dt(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 s=t.output||"middleware-types.ts";if(t.watch)await $e(s);else await P(s)}catch(s){console.error(`Failed to generate middleware types: ${s.message}`),v.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 s=t.output||"middleware-map.ts",r=t.dir||"src";if(t.watch)await ye(r,s);else await V(r,s)}catch(s){console.error(`Failed to generate middleware map: ${s.message}`),v.exit(1)}})}function Ft(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 s=t.output||"router-types.ts";if(t.watch)await ve(s);else await D(s)}catch(s){console.error(`Failed to generate router types: ${s.message}`),v.exit(1)}})}function Wt(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 we(t)}catch(s){console.error(`Failed to generate OpenAPI specification: ${s.message}`),v.exit(1)}})}function Ut(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 Re(t)}catch(s){console.error(`Health check failed: ${s.message}`),v.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 Oe(t)}catch(s){console.error(`Route testing failed: ${s.message}`),v.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,s)=>{try{await Se(t,s)}catch(r){console.error(`Route debugging failed: ${r.message}`),v.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 Te(t)}catch(s){console.error(`Cache clearing failed: ${s.message}`),v.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 Ie(t)}catch(s){console.error(`Route validation failed: ${s.message}`),v.exit(1)}})}var Ht=Ee();Ht.parse();
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 G(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 _(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(`
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
+ \u26A0\uFE0F Potential issues:`);for(let i of l)console.log(` \u2022 ${i}`)}else u.success(`
149
+ \u2705 No issues detected`)}}catch(t){throw u.error(`Health check failed: ${t.message}`),t}}async function W(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
+ \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
+ \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 q(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 V(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 Y(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 J(){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 H(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 G(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 L(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 D(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 B(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 z(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 _(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 W(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 q(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 V(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 Y(t)}catch(r){console.error(`Route validation failed: ${r.message}`),g.exit(1)}})}var he=J();he.parse();
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{$r as wt,Ar as Z,Br as tt,Cr as et,Dr as nt,Er as rt,Fr as ot,Gr as at,Hr as it,Ir as st,Jr as ct,Kr as ut,Lr as dt,Mr as lt,Nr as mt,Or as gt,Pr as pt,Qr as ft,Rr as yt,Sr as Mt,Tr as At,Ur as Dt,Vr as bt,Wr as xt,Xr as Tt,Yr as Et,Zr as Pt,_r as ht,as as Ft,bs as _t,cs as Ct,qr as y,rr as l,sr as m,tr as g,ur as D,vr as Q,wr as W,xr as z,yr as V,zr as X}from"../chunk-3y4gaz7v.js";import"../chunk-nf3kv7kv.js";var M=Symbol("controller"),p=Symbol("route"),s=Symbol("middleware"),i=Symbol("param");function b(t={}){return(e)=>(e[y]=t,e)}function x(t,e){return function(n,r,a){let o=n.constructor===Function?n:n.constructor;if(!o[l])o[l]=[];let d={token:t,optional:e?.optional,tags:e?.tags,when:e?.when};o[l][a]=d}}function T(){return(t,e,n)=>{if(!t[m])t[m]=[];t[m][n]=!0}}function E(t){return function(e,n,r){if(!e[g])e[g]=[];e[g][r]=t}}function P(t,e){return function(n){let r={prefix:t||"",middleware:e?.middleware||[],tags:e?.tags||[]};return n[M]=r,n}}function h(t="",e){return c("GET",t,e)}function w(t="",e){return c("POST",t,e)}function F(t="",e){return c("PUT",t,e)}function _(t="",e){return c("DELETE",t,e)}function C(t="",e){return c("PATCH",t,e)}function I(t="",e){return c("OPTIONS",t,e)}function R(t="",e){return c("HEAD",t,e)}function c(t,e,n){return function(r,a,o){if(!r.constructor[p])r.constructor[p]=[];let d={method:t,path:e,middleware:n?.middleware||[],tags:n?.tags||[]};return r.constructor[p].push({...d,propertyKey:a,handler:o.value}),o}}function O(...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 j(t){return u("param",t)}function Y(t){return u("query",t)}function K(){return u("body")}function L(t){return u("header",t)}function q(t){return u("cookie",t)}function v(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 f{static getInjectableMetadata(t){return t[y]}static getInjectMetadata(t){return t[l]||[]}static getOptionalMetadata(t){return t[m]||[]}static getTaggedMetadata(t){return t[g]||[]}static getControllerMetadata(t){return t[M]}static getAllRoutes(t){return t[p]||[]}static getMiddlewareMetadata(t,e){if(e)return t[s]?.get(e)||[];return t[s]||[]}static getParamMetadata(t,e){return t[i]?.get(e)||[]}}class A extends D{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 H=new A;export{ht as AuthGuard,Et as AuthService,dt as AuthServiceProvider,ot as BaseDeferredServiceProvider,rt as BaseServiceProvider,Q as BindingBuilder,nt as BindingConditions,K as Body,M as CONTROLLER_METADATA_KEY,bt as CacheManager,ut as CacheServiceProvider,gt as ConfigService,it as ConfigServiceProvider,ft as ConsoleLogger,D as Container,tt as ContextualContainer,P as Controller,q as Cookie,D as DIContainer,Mt as DatabaseConnection,ct as DatabaseServiceProvider,A as DecoratorContainer,Z as DefaultContextualBindingBuilder,at as DefaultServiceProviderManager,_ as Delete,X as EnvironmentManager,et as EnvironmentPresets,_t as EventBus,Ct as EventDispatcher,mt as EventServiceProvider,yt as FileLogger,h as Get,R as Head,L as Header,y as INJECTABLE_METADATA_KEY,l as INJECT_METADATA_KEY,x as Inject,v as InjectParam,b as Injectable,Pt as JwtService,pt as Logger,st as LoggingServiceProvider,s as MIDDLEWARE_METADATA_KEY,xt as MemoryCache,f as MetadataReader,m as OPTIONAL_METADATA_KEY,T as Optional,I as Options,i as PARAM_METADATA_KEY,j as Param,C as Patch,w as Post,Dt as PostRepository,F as Put,Y as Query,p as ROUTE_METADATA_KEY,Tt as RedisCache,g as TAGGED_METADATA_KEY,E as Tagged,O as UseMiddleware,At as UserRepository,Ft as ValidationPipe,lt as ValidationServiceProvider,wt as Validator,V as createContainer,H as decoratorContainer,W as getContainer,z as setContainer};
2
+ import{$a as it,Ka as y,La as l,Ma as m,Na as g,Oa as D,Pa as Q,Qa as W,Ra as z,Sa as V,Ta as X,Ua as Z,Va as tt,Wa as et,Xa as nt,Ya as rt,Za as ot,_a as at,ab as st,bb as ct,cb as ut,db as dt,eb as lt,fb as mt,gb as gt,hb as pt,ib as ft,jb as yt,kb as Mt,lb as At,mb as Dt,nb as bt,ob as xt,pb as Tt,qb as Et,rb as Pt,sb as ht,tb as wt,ub as Ft,vb as _t,wb as Ct}from"../chunk-m4aaj9ay.js";import"../chunk-8rrs7556.js";var M=Symbol("controller"),p=Symbol("route"),s=Symbol("middleware"),i=Symbol("param");function b(t={}){return(e)=>(e[y]=t,e)}function x(t,e){return function(n,r,a){let o=n.constructor===Function?n:n.constructor;if(!o[l])o[l]=[];let d={token:t,optional:e?.optional,tags:e?.tags,when:e?.when};o[l][a]=d}}function T(){return(t,e,n)=>{if(!t[m])t[m]=[];t[m][n]=!0}}function E(t){return function(e,n,r){if(!e[g])e[g]=[];e[g][r]=t}}function P(t,e){return function(n){let r={prefix:t||"",middleware:e?.middleware||[],tags:e?.tags||[]};return n[M]=r,n}}function h(t="",e){return c("GET",t,e)}function w(t="",e){return c("POST",t,e)}function F(t="",e){return c("PUT",t,e)}function _(t="",e){return c("DELETE",t,e)}function C(t="",e){return c("PATCH",t,e)}function I(t="",e){return c("OPTIONS",t,e)}function R(t="",e){return c("HEAD",t,e)}function c(t,e,n){return function(r,a,o){if(!r.constructor[p])r.constructor[p]=[];let d={method:t,path:e,middleware:n?.middleware||[],tags:n?.tags||[]};return r.constructor[p].push({...d,propertyKey:a,handler:o.value}),o}}function O(...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 j(t){return u("param",t)}function Y(t){return u("query",t)}function K(){return u("body")}function L(t){return u("header",t)}function q(t){return u("cookie",t)}function v(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 f{static getInjectableMetadata(t){return t[y]}static getInjectMetadata(t){return t[l]||[]}static getOptionalMetadata(t){return t[m]||[]}static getTaggedMetadata(t){return t[g]||[]}static getControllerMetadata(t){return t[M]}static getAllRoutes(t){return t[p]||[]}static getMiddlewareMetadata(t,e){if(e)return t[s]?.get(e)||[];return t[s]||[]}static getParamMetadata(t,e){return t[i]?.get(e)||[]}}class A extends D{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 H=new A;export{ht as AuthGuard,Et as AuthService,dt as AuthServiceProvider,ot as BaseDeferredServiceProvider,rt as BaseServiceProvider,Q as BindingBuilder,nt as BindingConditions,K as Body,M as CONTROLLER_METADATA_KEY,bt as CacheManager,ut as CacheServiceProvider,gt as ConfigService,it as ConfigServiceProvider,ft as ConsoleLogger,D as Container,tt as ContextualContainer,P as Controller,q as Cookie,D as DIContainer,Mt as DatabaseConnection,ct as DatabaseServiceProvider,A as DecoratorContainer,Z as DefaultContextualBindingBuilder,at as DefaultServiceProviderManager,_ as Delete,X as EnvironmentManager,et as EnvironmentPresets,_t as EventBus,Ct as EventDispatcher,mt as EventServiceProvider,yt as FileLogger,h as Get,R as Head,L as Header,y as INJECTABLE_METADATA_KEY,l as INJECT_METADATA_KEY,x as Inject,v as InjectParam,b as Injectable,Pt as JwtService,pt as Logger,st as LoggingServiceProvider,s as MIDDLEWARE_METADATA_KEY,xt as MemoryCache,f as MetadataReader,m as OPTIONAL_METADATA_KEY,T as Optional,I as Options,i as PARAM_METADATA_KEY,j as Param,C as Patch,w as Post,Dt as PostRepository,F as Put,Y as Query,p as ROUTE_METADATA_KEY,Tt as RedisCache,g as TAGGED_METADATA_KEY,E as Tagged,O as UseMiddleware,At as UserRepository,Ft as ValidationPipe,lt as ValidationServiceProvider,wt as Validator,V as createContainer,H as decoratorContainer,W as getContainer,z as setContainer};