@stacksjs/bun-router 0.1.18 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ // @bun
2
+ class t extends Error{code;statusCode;context;retryable;severity;category;timestamp;cause;constructor(e){super(e.message);if(this.name=this.constructor.name,this.code=e.code,this.statusCode=e.statusCode||500,this.context=e.context||{},this.retryable=e.retryable||!1,this.severity=e.severity||"medium",this.category=e.category||"system",this.timestamp=new Date,this.cause=e.cause,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,statusCode:this.statusCode,context:this.context,retryable:this.retryable,severity:this.severity,category:this.category,timestamp:this.timestamp.toISOString(),stack:this.stack,cause:this.cause?{name:this.cause.name,message:this.cause.message,stack:this.cause.stack}:void 0}}toResponse(){let e={error:{code:this.code,message:this.message,statusCode:this.statusCode,timestamp:this.timestamp.toISOString(),requestId:this.context.requestId}};return new Response(JSON.stringify(e),{status:this.statusCode,headers:{"Content-Type":"application/json","X-Error-Code":this.code,"X-Request-ID":this.context.requestId||""}})}}class b extends t{fields;constructor(e,n={},r){super({code:"VALIDATION_ERROR",message:e,statusCode:400,context:r,retryable:!1,severity:"low",category:"validation"});this.fields=n}toResponse(){let e={error:{code:this.code,message:this.message,statusCode:this.statusCode,timestamp:this.timestamp.toISOString(),requestId:this.context.requestId,fields:this.fields}};return new Response(JSON.stringify(e),{status:this.statusCode,headers:{"Content-Type":"application/json","X-Error-Code":this.code,"X-Request-ID":this.context.requestId||""}})}}class ke extends t{constructor(e="Authentication required",n){super({code:"AUTHENTICATION_ERROR",message:e,statusCode:401,context:n,retryable:!1,severity:"medium",category:"authentication"})}}class $e extends t{requiredPermissions;constructor(e="Access denied",n,r){super({code:"AUTHORIZATION_ERROR",message:e,statusCode:403,context:r,retryable:!1,severity:"medium",category:"authorization"});this.requiredPermissions=n}}class Ae extends t{resource;resourceId;constructor(e="Resource not found",n,r,i){super({code:"NOT_FOUND",message:e,statusCode:404,context:i,retryable:!1,severity:"low",category:"business"});this.resource=n,this.resourceId=r}}class Oe extends t{allowedMethods;constructor(e,n,r){super({code:"METHOD_NOT_ALLOWED",message:`Method ${e} not allowed. Allowed methods: ${n.join(", ")}`,statusCode:405,context:r,retryable:!1,severity:"low",category:"business"});this.allowedMethods=n}toResponse(){let e=super.toResponse();return e.headers.set("Allow",this.allowedMethods.join(", ")),e}}class D extends t{timeoutMs;constructor(e="Request timeout",n,r){super({code:"REQUEST_TIMEOUT",message:e,statusCode:408,context:r,retryable:!0,severity:"medium",category:"network"});this.timeoutMs=n}}class Ie extends t{retryAfter;limit;remaining;constructor(e="Rate limit exceeded",n,r,i=0,s){super({code:"RATE_LIMIT_EXCEEDED",message:e,statusCode:429,context:s,retryable:!0,severity:"medium",category:"network"});this.retryAfter=n,this.limit=r,this.remaining=i}toResponse(){let e=super.toResponse();return e.headers.set("Retry-After",this.retryAfter.toString()),e.headers.set("X-RateLimit-Limit",this.limit.toString()),e.headers.set("X-RateLimit-Remaining",this.remaining.toString()),e}}class Fe extends t{constructor(e="Internal server error",n,r){super({code:"INTERNAL_SERVER_ERROR",message:e,statusCode:500,context:r,cause:n,retryable:!0,severity:"high",category:"system"})}}class Ne extends t{retryAfter;constructor(e="Service unavailable",n,r){super({code:"SERVICE_UNAVAILABLE",message:e,statusCode:503,context:r,retryable:!0,severity:"high",category:"system"});this.retryAfter=n}toResponse(){let e=super.toResponse();if(this.retryAfter)e.headers.set("Retry-After",this.retryAfter.toString());return e}}class De extends t{query;operation;constructor(e,n,r,i,s){super({code:"DATABASE_ERROR",message:e,statusCode:500,context:s,cause:i,retryable:!0,severity:"high",category:"database"});this.operation=n,this.query=r}}class q extends t{service;endpoint;constructor(e,n,r,i=502,s,a){super({code:"EXTERNAL_SERVICE_ERROR",message:e,statusCode:i,context:a,cause:s,retryable:!0,severity:"medium",category:"external"});this.service=n,this.endpoint=r}}class H extends t{service;nextAttemptAt;constructor(e,n,r){super({code:"CIRCUIT_BREAKER_OPEN",message:`Circuit breaker is open for service: ${e}. Next attempt at: ${n.toISOString()}`,statusCode:503,context:r,retryable:!0,severity:"medium",category:"external"});this.service=e,this.nextAttemptAt=n}}class qe extends t{businessRule;constructor(e,n,r){super({code:"BUSINESS_LOGIC_ERROR",message:e,statusCode:422,context:r,retryable:!1,severity:"low",category:"business"});this.businessRule=n}}class He extends t{configKey;constructor(e,n,r){super({code:"CONFIGURATION_ERROR",message:e,statusCode:500,context:r,retryable:!1,severity:"critical",category:"system"});this.configKey=n}}class Be extends t{path;operation;constructor(e,n,r,i,s){super({code:"FILESYSTEM_ERROR",message:e,statusCode:500,context:s,cause:i,retryable:!1,severity:"medium",category:"system"});this.path=n,this.operation=r}}var d={validation:(e,n,r)=>new b(e,n,r),authentication:(e,n)=>new ke(e,n),authorization:(e,n,r)=>new $e(e,n,r),notFound:(e,n,r)=>new Ae(void 0,e,n,r),methodNotAllowed:(e,n,r)=>new Oe(e,n,r),timeout:(e,n,r)=>new D(n,e,r),rateLimit:(e,n,r,i)=>new Ie(void 0,e,n,r,i),internalServer:(e,n,r)=>new Fe(e,n,r),serviceUnavailable:(e,n,r)=>new Ne(e,n,r),database:(e,n,r,i,s)=>new De(e,n,r,i,s),externalService:(e,n,r,i,s,a)=>new q(e,n,r,i,s,a),circuitBreakerOpen:(e,n,r)=>new H(e,n,r),businessLogic:(e,n,r)=>new qe(e,n,r),configuration:(e,n,r)=>new He(e,n,r),fileSystem:(e,n,r,i,s)=>new Be(e,n,r,i,s)};class G extends t{conflictingRoutes;suggestion;constructor(e,n){let r=G.buildMessage(e),i=G.buildSuggestion(e);super({code:"ROUTE_CONFLICT",message:r,statusCode:500,context:n,retryable:!1,severity:"critical",category:"system"});this.conflictingRoutes=e,this.suggestion=i}static buildMessage(e){let n=["Route conflict detected! Multiple routes match the same path pattern.","","Conflicting routes:"];for(let r of e){if(n.push(` \u2022 ${r.method} ${r.path}`),r.name)n.push(` Name: "${r.name}"`);if(r.definedAt)n.push(` Defined at: ${r.definedAt}`)}return n.join(`
3
+ `)}static buildSuggestion(e){let n=[],r=e.some((c)=>!c.path.includes("{")),i=e.some((c)=>c.path.includes("{"));if(r&&i)n.push("\u2022 Static routes should be defined before dynamic routes","\u2022 Consider using route constraints (whereNumber, whereUuid) to differentiate");if(e.filter((c)=>c.path.includes("{")).length>1)n.push("\u2022 Use different parameter names or add constraints:",' router.get("/users/{id}").whereNumber("id")',' router.get("/users/{slug}").whereAlpha("slug")');if(e.some((c)=>c.path.includes("*")))n.push("\u2022 Wildcard routes should be defined last","\u2022 Consider using more specific path prefixes");if(n.length===0)n.push("\u2022 Rename one of the conflicting routes","\u2022 Use route groups with different prefixes","\u2022 Add parameter constraints to differentiate routes");return`How to fix:
4
+ ${n.join(`
5
+ `)}`}toJSON(){return{...super.toJSON(),conflictingRoutes:this.conflictingRoutes,suggestion:this.suggestion}}}class R extends t{dependencyChain;suggestion;constructor(e,n){let r=R.buildMessage(e),i=R.buildSuggestion(e);super({code:"CIRCULAR_DEPENDENCY",message:r,statusCode:500,context:n,retryable:!1,severity:"critical",category:"system"});this.dependencyChain=e,this.suggestion=i}static buildMessage(e){let n=["Circular dependency detected in the dependency injection container!","","Dependency chain:",""];for(let r=0;r<e.length;r++){let i=r===e.length-1,s=r===0?"\u250C\u2500\u25BA":i?"\u2514\u2500\u25BA":"\u251C\u2500\u25BA";if(n.push(` ${s} ${e[r]}`),!i)n.push(" \u2502")}return n.push(" \u2502"),n.push(` \u2514\u2500\u2500 cycles back to: ${e[0]}`),n.join(`
6
+ `)}static buildSuggestion(e){return`How to fix:
7
+
8
+ 1. Break the cycle by introducing an interface:
9
+ \u2022 Create an interface for one of the dependencies
10
+ \u2022 Use lazy injection: container.bind('${e[0]}').lazy()
11
+
12
+ 2. Restructure your dependencies:
13
+ \u2022 Extract shared logic into a separate service
14
+ \u2022 Use events/callbacks instead of direct dependencies
15
+
16
+ 3. Use setter injection instead of constructor injection:
17
+ \u2022 Remove the dependency from the constructor
18
+ \u2022 Set it after instantiation using a setter method
19
+
20
+ 4. Check if the dependency is actually needed:
21
+ \u2022 Sometimes circular dependencies indicate a design issue
22
+ \u2022 Consider if the classes have too many responsibilities
23
+
24
+ Dependency chain involved:
25
+ ${e.map((n,r)=>` ${r+1}. ${n}`).join(`
26
+ `)}`}toJSON(){return{...super.toJSON(),dependencyChain:this.dependencyChain,suggestion:this.suggestion}}}class je extends t{middlewareName;configErrors;suggestion;constructor(e,n,r){let i=`Middleware "${e}" configuration error:
27
+ ${n.map((s)=>` \u2022 ${s}`).join(`
28
+ `)}`;super({code:"MIDDLEWARE_CONFIGURATION_ERROR",message:i,statusCode:500,context:r,retryable:!1,severity:"high",category:"system"});this.middlewareName=e,this.configErrors=n,this.suggestion=this.buildSuggestion()}buildSuggestion(){return`How to fix:
29
+ \u2022 Check the middleware documentation for required options
30
+ \u2022 Ensure all required configuration values are provided
31
+ \u2022 Verify configuration value types match expected types
32
+
33
+ Example configuration:
34
+ router.use(new ${this.middlewareName}({
35
+ // Add required options here
36
+ }))`}}class ge extends t{requestedPath;requestedMethod;similarRoutes;suggestion;constructor(e,n,r=[],i){let s=ge.buildMessage(e,n,r);super({code:"ROUTE_NOT_FOUND",message:s,statusCode:404,context:i,retryable:!1,severity:"low",category:"business"});this.requestedPath=n,this.requestedMethod=e,this.similarRoutes=r,this.suggestion=this.buildSuggestion()}static buildMessage(e,n,r){let i=[`Route not found: ${e} ${n}`];if(r.length>0){i.push(""),i.push("Did you mean one of these routes?");for(let s of r.slice(0,5))if(i.push(` \u2022 ${s.method} ${s.path}`),s.similarity)i.push(` (${Math.round(s.similarity*100)}% match)`)}return i.join(`
37
+ `)}buildSuggestion(){let e=[`\u2022 Verify the HTTP method is correct (you used ${this.requestedMethod})`,"\u2022 Check for typos in the URL path","\u2022 Ensure the route is registered before the server starts","\u2022 Check if the route requires specific middleware (e.g., auth)"];if(this.requestedPath.includes("//"))e.push("\u2022 Remove duplicate slashes from the URL");if(!this.requestedPath.startsWith("/"))e.push("\u2022 Ensure the path starts with a forward slash (/)");return`How to fix:
38
+ ${e.join(`
39
+ `)}`}}class Ue extends t{handlerRef;suggestion;constructor(e,n,r){let i=`Failed to resolve handler "${e}": ${n}`;super({code:"HANDLER_RESOLUTION_ERROR",message:i,statusCode:500,context:r,retryable:!1,severity:"high",category:"system"});this.handlerRef=e,this.suggestion=this.buildSuggestion(e)}buildSuggestion(e){let n=e.includes("@"),r=e.includes("/");if(n){let[i,s]=e.split("@");return`How to fix:
40
+ \u2022 Ensure the controller "${i}" is registered in the container
41
+ \u2022 Verify the method "${s}" exists and is public
42
+ \u2022 Check the controller file is imported
43
+
44
+ Example:
45
+ // Register the controller
46
+ container.singleton('${i}', ${i})
47
+
48
+ // Define the route
49
+ router.get('/path', '${e}')`}if(r)return`How to fix:
50
+ \u2022 Ensure the action class exists at the specified path
51
+ \u2022 Verify the action has a "handle" method
52
+ \u2022 Check the action file is properly exported
53
+
54
+ Example:
55
+ // Action class at ${e}.ts
56
+ export default class ${e.split("/").pop()} {
57
+ handle(req: Request): Response {
58
+ return new Response('OK')
59
+ }
60
+ }`;return`How to fix:
61
+ \u2022 Verify the handler reference is correct
62
+ \u2022 Ensure the handler function/class is exported
63
+ \u2022 Check for circular dependencies in the handler module`}}class Le extends t{modelName;paramName;paramValue;suggestion;constructor(e,n,r,i,s){let a=`Failed to bind model "${e}" for parameter "${n}" with value "${r}": ${i}`;super({code:"MODEL_BINDING_ERROR",message:a,statusCode:404,context:s,retryable:!1,severity:"low",category:"business"});this.modelName=e,this.paramName=n,this.paramValue=r,this.suggestion=this.buildSuggestion()}buildSuggestion(){return`How to fix:
64
+ \u2022 Verify the ${this.paramName} "${this.paramValue}" exists in your data source
65
+ \u2022 Check if the model resolver is correctly configured
66
+ \u2022 Ensure the route parameter matches the model's identifier field
67
+
68
+ Example model binding:
69
+ router.model('${this.paramName}', async (value) => {
70
+ const ${this.modelName.toLowerCase()} = await db.${this.modelName.toLowerCase()}s.findUnique({
71
+ where: { id: value }
72
+ })
73
+ if (!${this.modelName.toLowerCase()}) {
74
+ throw new Error('${this.modelName} not found')
75
+ }
76
+ return ${this.modelName.toLowerCase()}
77
+ })`}}function er(e,n,r=5){let i=[];for(let s of n){let a=m(e,s.path);if(a>0.3)i.push({method:s.method,path:s.path,similarity:a})}return i.sort((s,a)=>(a.similarity||0)-(s.similarity||0)).slice(0,r)}function m(e,n){let r=e.length,i=n.length;if(r===0)return i===0?1:0;if(i===0)return 0;let s=[];for(let o=0;o<=r;o++)s[o]=[o];for(let o=0;o<=i;o++)s[0][o]=o;for(let o=1;o<=r;o++)for(let u=1;u<=i;u++){let g=e[o-1]===n[u-1]?0:1;s[o][u]=Math.min(s[o-1][u]+1,s[o][u-1]+1,s[o-1][u-1]+g)}let a=s[r][i],c=Math.max(r,i);return 1-a/c}function tr(e){let n=[],r=new Set;for(let i=0;i<e.length;i++){let s=e[i],a=`${s.method}:${s.path}`;if(r.has(a))continue;let c=[];for(let o=i+1;o<e.length;o++){let u=e[o];if(s.method===u.method&&f(s.path,u.path)){if(c.length===0)c.push({method:s.method,path:s.path,name:s.name});c.push({method:u.method,path:u.path,name:u.name}),r.add(`${u.method}:${u.path}`)}}if(c.length>0)n.push(c);r.add(a)}return n}function f(e,n){if(e===n)return!0;let r=e.split("/").filter(Boolean),i=n.split("/").filter(Boolean);if(r.length!==i.length){let a=e.includes("*"),c=n.includes("*");if(!a&&!c)return!1}let s=Math.max(r.length,i.length);for(let a=0;a<s;a++){let c=r[a]||"",o=i[a]||"";if(c==="*"||o==="*")return!0;let u=c.startsWith("{")&&c.endsWith("}"),g=o.startsWith("{")&&o.endsWith("}");if(!u&&!g){if(c!==o)return!1}}return!0}var rr={routeConflict:(e,n)=>new G(e,n),circularDependency:(e,n)=>new R(e,n),middlewareConfig:(e,n,r)=>new je(e,n,r),routeNotFound:(e,n,r,i)=>new ge(e,n,r,i),handlerResolution:(e,n,r)=>new Ue(e,n,r),modelBinding:(e,n,r,i,s)=>new Le(e,n,r,i,s)};var fe=Symbol("injectable"),p=Symbol("inject"),K=Symbol("optional"),J=Symbol("tagged");class h{bindings=new Map;tagIndex=new Map;instances=new Map;scopedInstances=new Map;interceptors=new Map;parent;children=new Set;options;constructor(e={}){this.options={autoRegister:e.autoRegister??!0,strictMode:e.strictMode??!1,maxDepth:e.maxDepth??50,enableDecorators:e.enableDecorators??!0,enableInterception:e.enableInterception??!1,defaultScope:e.defaultScope??"transient"}}bind(e){return new ye(this,e)}register(e){let n=this.bindings.get(e.token);if(n?.metadata?.tags)for(let r of n.metadata.tags)this.tagIndex.get(r)?.delete(e.token);if(this.bindings.set(e.token,e),e.metadata?.tags)for(let r of e.metadata.tags){let i=this.tagIndex.get(r);if(!i)i=new Set,this.tagIndex.set(r,i);i.add(e.token)}return this}singleton(e,n){return this.bind(e).to(n).inSingletonScope().build()}transient(e,n){return this.bind(e).to(n).inTransientScope().build()}value(e,n){return this.bind(e).toValue(n).build()}factory(e,n){return this.bind(e).toFactory(n).build()}resolve(e,n){let r={container:this,token:e,environment:n?.environment||"development",requestId:n?.requestId||this.generateRequestId(),depth:n?.depth||0,resolving:n?.resolving||new Set,parent:n?.parent};return this.resolveInternal(e,r)}resolveAll(e){let n=new Set;if(this.bindings.has(e))n.add(e);if(typeof e==="string")for(let r of this.tagIndex.get(e)??[])n.add(r);return Array.from(n,(r)=>this.resolve(r))}resolveTagged(e){let n=this.tagIndex.get(e);if(!n||n.size===0)return[];return Array.from(n,(r)=>this.resolve(r))}getTaggedBindings(e){let n=this.tagIndex.get(e);if(!n||n.size===0)return[];let r=[];for(let i of n){let s=this.bindings.get(i);if(s)r.push(s)}return r}addInterceptor(e,n){let r=this.tokenToString(e);if(!this.interceptors.has(r))this.interceptors.set(r,[]);this.interceptors.get(r).push(n)}registerController(e){this.singleton(e,e)}getController(e){return this.resolve(e)}isBound(e){return this.bindings.has(e)||(this.parent?.isBound(e)??!1)}unbind(e){let n=this.bindings.get(e);if(n?.metadata?.tags)for(let r of n.metadata.tags)this.tagIndex.get(r)?.delete(e);return this.bindings.delete(e),this.instances.delete(e),this}createChild(e){let n=new h({...this.options,...e});return n.parent=this,this.children.add(n),n}createScope(e){let n=this.createChild();return n.scopedInstances.set(e,new Map),n}getBindings(){return new Map(this.bindings)}clear(){return this.bindings.clear(),this.tagIndex.clear(),this.instances.clear(),this.scopedInstances.clear(),this}intercept(e,n){if(!this.interceptors.has(e))this.interceptors.set(e,[]);return this.interceptors.get(e).push(n),this}resolveInternal(e,n){if(n.resolving.has(e)){let r=Array.from(n.resolving).map((i)=>this.tokenToString(i));throw r.push(this.tokenToString(e)),new R(r)}if(n.depth>this.options.maxDepth){let r=Array.from(n.resolving).map((i)=>this.tokenToString(i));throw Error(`Maximum resolution depth exceeded (${this.options.maxDepth}).
78
+ This usually indicates a circular or very deep dependency chain.
79
+ Current resolution chain:
80
+ ${r.map((i,s)=>` ${s+1}. ${i}`).join(`
81
+ `)}`)}n.resolving.add(e),n.depth++;try{let r=this.bindings.get(e);if(r){if(r.metadata.when&&!r.metadata.when(n))throw Error(`Contextual binding condition not met for: ${this.tokenToString(e)}`);return this.createInstance(r,n)}if(this.parent){let i={resolving:new Set,depth:0,container:this.parent,token:e};return this.parent.resolveInternal(e,i)}if(this.options.autoRegister&&typeof e==="function")return this.autoRegisterAndResolve(e,n);if(this.options.strictMode)throw Error(`No binding found for: ${this.tokenToString(e)}`);if(typeof e==="function")return this.createInstanceFromConstructor(e,n);throw Error(`Cannot resolve: ${this.tokenToString(e)}`)}finally{n.resolving.delete(e),n.depth--}}createInstance(e,n){let r;if(e.metadata.scope==="singleton"&&this.instances.has(e.token))r=this.instances.get(e.token);else if(e.metadata.scope==="scoped"&&n.requestId){let s=this.scopedInstances.get(n.requestId);if(s?.has(e.token))r=s.get(e.token);else{if(r=this.createNewInstance(e,n),!s)this.scopedInstances.set(n.requestId,new Map);this.scopedInstances.get(n.requestId).set(e.token,r)}}else if(r=this.createNewInstance(e,n),e.metadata.scope==="singleton")this.instances.set(e.token,r);let i=this.tokenToString(e.token);if(this.interceptors.has(i)){let s=this.interceptors.get(i);for(let a of s)r=a(r)}return r}createNewInstance(e,n){if(e.value!==void 0)return e.value;if(e.factory){let r=this.resolveDependencies(e.metadata.dependencies||[],n);return e.factory(...r)}if(e.instance)return e.instance;if(e.implementation)return this.createInstanceFromConstructor(e.implementation,n);throw Error(`Invalid binding configuration for: ${this.tokenToString(e.token)}`)}createInstanceFromConstructor(e,n){let r=this.getConstructorDependencies(e),i=this.resolveDependencies(r,n),s=new e(...i);if(this.options.enableDecorators)this.applyDecorators(s,e);return s}getConstructorDependencies(e){let n=Reflect.getMetadata?.(p,e)||e[p];if(!n&&e.constructor)n=e.constructor[p];if(!n&&typeof e==="function"&&e.prototype){let i=e[p];if(i)n=i}if(!n&&typeof e==="function"){let i=e[p];if(i)n=i}if(n)return n.map((i)=>i.token);let r=Reflect.getMetadata?.("design:paramtypes",e);if(r)return r;return this.parseConstructorDependencies(e)}parseConstructorDependencies(e){let r=e.toString().match(/constructor\s*\(([^)]*)\)/);if(!r||!r[1])return[];return r[1].split(",").map((i)=>i.trim().split(":")[0].trim()).filter((i)=>i.length>0)}resolveDependencies(e,n){return e.map((r)=>this.resolveInternal(r,n))}autoRegisterAndResolve(e,n){let r=Reflect.getMetadata?.(fe,e),i={token:e,implementation:e,metadata:{scope:r?.scope||this.options.defaultScope,tags:r?.tags}};return this.register(i),this.resolveInternal(e,n)}applyDecorators(e,n){let r=Reflect.getMetadata?.("decorators",n);if(r)for(let i of r)i(e)}hasTag(e,n){return e.metadata.tags?.includes(n)??!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 ye{container;binding;constructor(e,n){this.container=e;this.binding={token:n,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 l=null;function nt(){if(!l)l=new h;return l}function st(e){l=e}function it(e){return new h(e)}class we{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,n){return this.variables.get(e)??n}set(e,n){return this.variables.set(e,n),this}hasFeature(e){return this.getEnvironment()?.features.includes(e)??!1}loadEnvironmentVariables(){let e=this.getEnvironment();if(e)for(let[n,r]of Object.entries(e.variables))this.variables.set(n,r)}}class ot{container;binding;constructor(e,n){this.container=e;this.binding={token:n,conditions:[],priority:0,metadata:{scope:"transient"}}}when(e){return this.binding.conditions.push(e),this}whenEnvironment(...e){let n={type:"environment",predicate:(r)=>e.includes(r.environment||"development"),description:`Environment is one of: ${e.join(", ")}`};return this.when(n)}whenTag(e){let n={type:"tag",predicate:(r)=>r.parent?.token?.toString().includes(e)??!1,description:`Parent has tag: ${e}`};return this.when(n)}whenParent(e){let n={type:"parent",predicate:(r)=>r.parent?.token===e,description:`Parent token is: ${e.toString()}`};return this.when(n)}whenRequest(e){let n={type:"request",predicate:e,description:"Custom request condition"};return this.when(n)}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 _e extends h{contextualBindings=new Map;environmentManager;constructor(e){super(e);this.environmentManager=new we}bindContextual(e){return new ot(this,e)}registerContextualBinding(e){if(!this.contextualBindings.has(e.token))this.contextualBindings.set(e.token,[]);let n=this.contextualBindings.get(e.token);return n.push(e),n.sort((r,i)=>i.priority-r.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,n){let r={container:this,token:e,environment:n?.environment||this.environmentManager.getCurrentEnvironment(),requestId:n?.requestId||this.generateContextualRequestId(),depth:n?.depth||0,resolving:n?.resolving||new Set,parent:n?.parent},i=this.findContextualBinding(e,r);if(i)return this.createInstanceFromContextualBinding(i,r);return super.resolve(e,r)}findContextualBinding(e,n){let r=this.contextualBindings.get(e);if(!r)return;for(let i of r)if(this.evaluateConditions(i.conditions,n))return i;return}evaluateConditions(e,n){return e.every((r)=>{try{return r.predicate(n)}catch(i){return console.warn(`Error evaluating binding condition: ${r.description}`,i),!1}})}createInstanceFromContextualBinding(e,n){try{return this.createInstance(e,n)}catch(r){if(e.fallback)return console.warn(`Contextual binding failed, using fallback for ${e.token.toString()}`),this.createInstance(e.fallback,n);throw r}}generateContextualRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}class nr{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 sr{static environment(...e){return{type:"environment",predicate:(n)=>e.includes(n.environment||"development"),description:`Environment is one of: ${e.join(", ")}`}}static feature(e){return{type:"custom",predicate:(n)=>n.container.getEnvironmentManager().hasFeature(e),description:`Feature ${e} is enabled`}}static envVar(e,n){return{type:"custom",predicate:(r)=>r.container.getEnvironmentManager().get(e)===n,description:`Environment variable ${e} equals ${n}`}}static requestPattern(e){return{type:"request",predicate:(n)=>e.test(n.requestId||""),description:`Request ID matches pattern: ${e.toString()}`}}static timeRange(e,n){return{type:"custom",predicate:()=>{let r=new Date().getHours();return r>=e&&r<=n},description:`Time is between ${e}:00 and ${n}:00`}}static custom(e,n){return{type:"custom",predicate:e,description:n||"Custom condition"}}}class y{version;dependencies;environment;priority=0;boot(e){}shutdown(e){}singleton(e,n,r){e.singleton(n,r)}transient(e,n,r){e.transient(n,r)}value(e,n,r){e.value(n,r)}factory(e,n,r){e.factory(n,r)}when(e,n){return{bind:(r)=>e.bind(r).when(n)}}forEnvironment(e,...n){return this.when(e,(r)=>n.includes(r.environment||"development"))}}class at extends y{isDeferred(){return!0}}class ze{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 n=e.shouldLoad(this.container);if(n instanceof Promise)n.then((r)=>{if(r)this.doRegister(e)});else if(!n)return this}return this.doRegister(e),this}async boot(){let e=Array.from(this.providers.values()).sort((n,r)=>(r.priority||0)-(n.priority||0));this.validateDependencies(e);for(let n of e)if(!this.loadedProviders.has(n.name))await this.loadProvider(n);for(let n of e)if(!this.bootedProviders.has(n.name))await this.bootProvider(n)}async shutdown(){let e=Array.from(this.providers.values()).reverse();for(let n of e)if(n.shutdown)try{await n.shutdown(this.container)}catch(r){console.error(`Error shutting down provider ${n.name}:`,r)}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[n,r]of this.deferredProviders)if(r.provides().includes(e)&&!this.loadedProviders.has(n))await this.loadProvider(r),await this.bootProvider(r),this.deferredProviders.delete(n)}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(n){throw Error(`Failed to load provider ${e.name}: ${n}`)}}async bootProvider(e){if(e.boot)try{await e.boot(this.container),this.bootedProviders.add(e.name)}catch(n){throw Error(`Failed to boot provider ${e.name}: ${n}`)}else this.bootedProviders.add(e.name)}validateDependencies(e){let n=new Set(e.map((r)=>r.name));for(let r of e)if(r.dependencies){for(let i of r.dependencies)if(!n.has(i))throw Error(`Provider ${r.name} depends on ${i}, but it's not registered`)}}isDeferredProvider(e){return"provides"in e&&"isDeferred"in e}isConditionalProvider(e){return"shouldLoad"in e}}class ir extends y{name="config";priority=100;register(e){e.singleton("config",ct),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 or extends y{name="logging";priority=90;register(e){e.factory("logger",(n)=>new be(n.get("logging",{}))),this.forEnvironment(e,"development").bind("logger").toFactory(()=>new lt),this.forEnvironment(e,"production").bind("logger").toFactory((n)=>new ut(n.get("logging.file","./app.log")))}}class ar extends y{name="database";dependencies=["config","logging"];register(e){e.singleton("database",dt),e.transient("userRepository",pt),e.transient("postRepository",ht)}async boot(e){await e.resolve("database").connect()}async shutdown(e){await e.resolve("database").disconnect()}}class cr extends y{name="cache";dependencies=["config"];register(e){e.singleton("cache",mt),this.forEnvironment(e,"development").bind("cache.store").toFactory(()=>new gt),this.forEnvironment(e,"production").bind("cache.store").toFactory((n)=>new ft(n.get("cache.redis")))}}class lr extends y{name="auth";dependencies=["config","database"];register(e){e.singleton("authService",yt),e.singleton("jwtService",wt),e.transient("authGuard",bt)}}class ur extends y{name="validation";register(e){e.singleton("validator",Rt),e.factory("validationPipe",(n)=>new vt(n))}}class dr extends at{name="events";provides(){return["eventBus","eventDispatcher",Ve,We]}register(e){e.singleton("eventBus",Ve),e.singleton("eventDispatcher",We)}}class ct{get(e,n){return n}}class be{config;constructor(e){this.config=e}log(e){console.log(e)}}class lt extends be{constructor(){super({})}}class ut extends be{filePath;constructor(e){super({});this.filePath=e}}class dt{async connect(){}async disconnect(){}}class pt{db;constructor(e){this.db=e}}class ht{db;constructor(e){this.db=e}}class mt{store;constructor(e){this.store=e}}class gt{cache=new Map}class ft{config;constructor(e){this.config=e}}class yt{jwt;userRepo;constructor(e,n){this.jwt=e;this.userRepo=n}}class wt{config;constructor(e){this.config=e}}class bt{auth;constructor(e){this.auth=e}}class Rt{validate(e,n){return!0}}class vt{validator;constructor(e){this.validator=e}}class Ve{emit(e,n){}}class We{bus;constructor(e){this.bus=e}}
82
+ export{t,b,ke,$e,Ae,Oe,D,Ie,Fe,Ne,De,q,H,qe,He,Be,d,G,R,je,ge,Ue,Le,er,tr,rr,fe,p,K,J,h,ye,nt,st,it,we,ot,_e,nr,sr,y,at,ze,ir,or,ar,cr,lr,ur,dr,ct,be,lt,ut,dt,pt,ht,mt,gt,ft,yt,wt,bt,Rt,vt,Ve,We};
@@ -0,0 +1,102 @@
1
+ // @bun
2
+ function v(e){if(!e.includes("%"))return e;try{return decodeURIComponent(e)}catch{return e}}function X(e){let{read:t,write:o,remove:a}=e,c=()=>({...t()});for(let[d,p]of Object.entries(t()))Object.defineProperty(c,d,{value:p,writable:!0,enumerable:!0,configurable:!0});return c.get=(d)=>t()[d],c.set=(d,p,h={})=>o?.(d,p,h),c.delete=(d,p={})=>a?.(d,p),c.getAll=()=>({...t()}),c}function x(e={}){let t={...e};return X({read:()=>t,write:(o,a)=>{t[o]=a},remove:(o)=>{delete t[o]}})}import{AsyncLocalStorage as Lt}from"async_hooks";var pe=new Lt,J=!1,q=null;function Re(){J=!0}function B(e,t){if(!J){q=e;let o;try{o=t()}catch(a){throw q=null,a}if(o instanceof Promise)return o.finally(()=>{q=null});return q=null,o}return pe.run({current:e},t)}function j(e,t,o,a){if(!J){q=e;let c;try{c=t(o,a)}catch(d){throw q=null,d}if(c instanceof Promise)return c.finally(()=>{q=null});return q=null,c}return pe.run({current:e},t,o,a)}function T(e){let t=pe.getStore();if(t){t.current=e;return}if(q!==null)q=e}function Y(){if(!J)return J=!0,q??void 0;return pe.getStore()?.current??q??void 0}function ve(){let e=Y();if(!e)throw Error("request() called outside a request scope. It can only be invoked from within a route handler or middleware.");return e}var Q={enabled:!0,level:6,threshold:1024};function Ge(e){if(!e)return!1;if(e==="application/json")return!0;if(e.startsWith("text/")){if(!e.startsWith("text/event-stream"))return!0;if(e.length===17)return!1;let o=e.charCodeAt(17);return o>32&&o!==59}let t=e.split(";")[0]?.trim().toLowerCase()??"";if(t==="text/event-stream")return!1;if(t.startsWith("text/"))return!0;return["application/json","application/ld+json","application/manifest+json","application/javascript","application/x-javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/graphql","application/x-ndjson","image/svg+xml"].includes(t)}function pr(e){return $e(e).encoding}function $e(e){if(!e)return{encoding:null,identityAllowed:!0};let t,o,a,c;for(let p of e.split(",")){let h=p.indexOf(";"),f=(h<0?p:p.slice(0,h)).trim().toLowerCase();if(f!=="gzip"&&f!=="deflate"&&f!=="identity"&&f!=="*")continue;let R=1;if(h>=0){let y=/^;[\t ]*q=(0(?:\.\d{0,3})?|1(?:\.0{0,3})?)[\t ]*$/i.exec(p.slice(h));R=y?Number(y[1]):0}if(f==="gzip")t=R;else if(f==="deflate")o=R;else if(f==="identity")a=R;else c=R}t??=c??0,o??=c??0;let d=a!==void 0?a>0:c!==0;if(a!==void 0&&a>Math.max(t,o))return{encoding:null,identityAllowed:d};if(t>0&&t>=o)return{encoding:"gzip",identityAllowed:d};if(o>0)return{encoding:"deflate",identityAllowed:d};return{encoding:null,identityAllowed:d}}function hr(e,t,o){if(!t)return!1;if(e.status===204||e.status===304||e.status===206)return!1;if(e.headers.has("content-encoding"))return!1;if(!Ge(e.headers.get("content-type")))return!1;let a=Number(e.headers.get("content-length")??Number.NaN);if(Number.isFinite(a)&&!(a>=o))return!1;return Boolean(e.body)}function m(e,t,o={}){if(!(o.enabled??Q.enabled))return e;let c=e.headers;if(c.has("content-encoding"))return e;if(e.status===204)return e;let d=o.threshold??Q.threshold,p=t.headers.get("accept-encoding"),h=p?Number(c.get("content-length")??Number.NaN):Number.NaN,f=Number.isFinite(h)&&!(h>=d);if(!p||f&&(!p.includes(";")||!/identity|\*/i.test(p)))return U(c,"Accept-Encoding"),e;let{encoding:R,identityAllowed:y}=$e(p),b=Ge(c.get("content-type"))&&e.status!==206;if(!y&&e.status!==304&&e.body){if(!R||!b)return jt(e);return Me(e,e.body,R)}if(!R||f||!b||e.status===304||!e.body)return U(c,"Accept-Encoding"),e;if(!Number.isFinite(h))return Ft(e,R,d);return Me(e,e.body,R)}function jt(e){e.body?.cancel().catch(()=>{});let t=new Headers(e.headers);for(let o of["content-type","content-length","content-encoding","content-range","content-disposition","etag","last-modified","content-md5","digest","content-digest","repr-digest","expires"])t.delete(o);return t.set("Cache-Control","no-store"),U(t,"Accept-Encoding"),new Response(null,{status:406,headers:t})}async function mr(e,t,o={}){return m(e,t,o)}async function Ft(e,t,o){let a=await Tt(e.body,o);if(a.ended&&a.size<o){let c=new Headers(e.headers);return U(c,"Accept-Encoding"),c.set("Content-Length",String(a.size)),new Response(a.body,{status:e.status,statusText:e.statusText,headers:c})}return Me(e,xt(a),t)}function Me(e,t,o){let a=new Headers(e.headers);a.set("Content-Encoding",o),U(a,"Accept-Encoding"),a.delete("Content-Length");let c=t.pipeThrough(new CompressionStream(o==="gzip"?"gzip":"deflate"));return new Response(c,{status:e.status,statusText:e.statusText,headers:a})}function Bt(e,t){if(e.length===1)return e[0];let o=new Uint8Array(t),a=0;for(let c of e)o.set(c,a),a+=c.byteLength;return o}function xt(e){return e.body instanceof Uint8Array?new Response(e.body).body:e.body}async function Tt(e,t){let o=e.getReader(),a=[],c=0,d=!1;while(c<t){let{value:h,done:f}=await o.read();if(f){d=!0;break}if(h)a.push(h),c+=h.byteLength}if(d)return o.releaseLock(),{body:Bt(a,c),size:c,ended:d};return{body:new ReadableStream({start(h){for(let f of a)h.enqueue(f)},async pull(h){let{value:f,done:R}=await o.read();if(R){h.close();return}if(f)h.enqueue(f)},cancel(h){return o.cancel(h)}}),size:c,ended:d}}function U(e,t){let o=e.get("vary");if(!o){e.set("Vary",t);return}let a=o.split(",").map((c)=>c.trim().toLowerCase());if(a.includes("*")||a.includes(t.toLowerCase()))return;e.set("Vary",`${o}, ${t}`)}import{Buffer as zt}from"buffer";function ie(e,t,o,a){return new Response(e,{status:o,headers:{"Content-Type":t,"Content-Length":String(zt.byteLength(e)),...a}})}var r={json:(e,t={})=>{let o=typeof t==="number"?{status:t}:t,{status:a=200,headers:c={},pretty:d=!1}=o,p=d?JSON.stringify(e,null,2):JSON.stringify(e);return ie(p,"application/json",a,c)},noContent:(e={})=>new Response(null,{status:204,headers:e}),download:async(e,t,o={})=>{let a=Bun.file(e);if(!await a.exists())return new Response("File not found",{status:404});let d=t||e.split("/").pop()||"download",p=a.type||"application/octet-stream";return new Response(a,{status:200,headers:{"Content-Type":p,"Content-Disposition":`attachment; filename="${d}"`,"Content-Length":String(a.size),...o}})},file:async(e,t={})=>{let o=Bun.file(e);if(!await o.exists())return new Response("File not found",{status:404});let c=o.type||"application/octet-stream";return new Response(o,{status:200,headers:{"Content-Type":c,"Content-Length":String(o.size),...t}})},streamDownload:(e,t,o={})=>{let{contentType:a="application/octet-stream",headers:c={}}=o,d=new ReadableStream({async start(p){try{for await(let h of e())if(typeof h==="string")p.enqueue(new TextEncoder().encode(h));else p.enqueue(h);p.close()}catch(h){p.error(h)}}});return new Response(d,{status:200,headers:{"Content-Type":a,"Content-Disposition":`attachment; filename="${t}"`,"Transfer-Encoding":"chunked",...c}})},redirect:(e,t=302)=>new Response(null,{status:t,headers:{Location:e}}),redirectPermanent:(e)=>r.redirect(e,301),redirectTemporary:(e)=>r.redirect(e,302),back:(e,t="/")=>{let o=e.headers.get("referer")||t;return r.redirect(o)},view:(e,t=200,o={})=>ie(e,"text/html; charset=utf-8",t,o),text:(e,t=200,o={})=>ie(e,"text/plain; charset=utf-8",t,o),xml:(e,t=200,o={})=>ie(e,"application/xml; charset=utf-8",t,o),success:(e,t,o=200)=>{let a={success:!0};if(e!==void 0)a.data=e;if(t!==void 0)a.message=t;return r.json(a,{status:o})},error:(e,t=400,o)=>{let a={success:!1,message:e};if(o!==void 0)a.errors=o;return r.json(a,{status:t})},paginate:(e,t)=>{let{page:o,perPage:a,total:c,path:d}=t,p=Math.ceil(c/a),h=(o-1)*a+1,f=Math.min(o*a,c);return r.json({data:e,meta:{current_page:o,per_page:a,total:c,last_page:p,from:h,to:f,path:d,first_page_url:`${d}?page=1`,last_page_url:`${d}?page=${p}`,next_page_url:o<p?`${d}?page=${o+1}`:null,prev_page_url:o>1?`${d}?page=${o-1}`:null}})},created:(e,t)=>{let o={};if(t)o.Location=t;let a={success:!0};if(e!==void 0)a.data=e;return r.json(a,{status:201,headers:o})},accepted:(e)=>{let t={success:!0};if(e!==void 0)t.data=e;return r.json(t,{status:202})},notFound:(e="Resource not found")=>r.error(e,404),unauthorized:(e="Unauthorized")=>r.error(e,401),forbidden:(e="Forbidden")=>r.error(e,403),badRequest:(e="Bad request",t)=>r.error(e,400,t),validationError:(e,t="Validation failed")=>r.error(t,422,e),unprocessableEntity:(e="Unprocessable entity",t)=>r.error(e,422,t),serverError:(e="Internal server error")=>r.error(e,500),tooManyRequests:(e="Too many requests",t)=>{let o={};if(t)o["Retry-After"]=String(t);return ie(JSON.stringify({message:e}),"application/json",429,o)}};class Z{_status=200;_headers={};_cookies=[];_deleteCookies=[];status(e){return this._status=e,this}header(e,t){return this._headers[e]=t,this}withHeaders(e){return this._headers={...this._headers,...e},this}cookie(e,t,o={}){return this._cookies.push({name:e,value:t,options:o}),this}withoutCookie(e,t={}){return this._deleteCookies.push({name:e,options:t}),this}json(e){let t=r.json(e,{status:this._status,headers:this._headers});return this.applyCookies(t)}text(e){let t=r.text(e,this._status,this._headers);return this.applyCookies(t)}html(e){let t=r.view(e,this._status,this._headers);return this.applyCookies(t)}noContent(){let e=r.noContent(this._headers);return this.applyCookies(e)}applyCookies(e){let t=new Headers(e.headers);for(let{name:o,value:a,options:c}of this._cookies){let d=this.serializeCookie(o,a,c);t.append("Set-Cookie",d)}for(let{name:o,options:a}of this._deleteCookies){let c=this.serializeCookie(o,"",{...a,maxAge:0,expires:new Date(0)});t.append("Set-Cookie",c)}return new Response(e.body,{status:e.status,headers:t})}serializeCookie(e,t,o){let a=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(o.maxAge!==void 0)a+=`; Max-Age=${o.maxAge}`;if(o.expires)a+=`; Expires=${o.expires.toUTCString()}`;if(o.httpOnly)a+="; HttpOnly";if(o.secure)a+="; Secure";if(o.path)a+=`; Path=${o.path}`;if(o.domain)a+=`; Domain=${o.domain}`;if(o.sameSite)a+=`; SameSite=${o.sameSite.charAt(0).toUpperCase()+o.sameSite.slice(1)}`;return a}}function Ke(){return new Z}var ee=Symbol.for("@stacksjs/bun-router:enriched-not-found-response");function oe(e){let t=e;return t[ee]=!0,e}import{Buffer as Gt}from"buffer";function ge(e,t){return new Response(e,{headers:{"Content-Type":t,"Content-Length":String(Gt.byteLength(e))}})}function s(e){if(e instanceof Response)return e;if(e===null||e===void 0)return new Response(null,{status:204});if(typeof e==="string")return ge(e,"text/plain; charset=utf-8");if(typeof e==="number"||typeof e==="boolean")return ge(String(e),"text/plain; charset=utf-8");if(e instanceof ArrayBuffer||e instanceof Uint8Array)return new Response(e,{headers:{"Content-Type":"application/octet-stream","Content-Length":String(e.byteLength)}});if(e instanceof ReadableStream)return new Response(e);if(typeof e==="object")return ge(JSON.stringify(e),"application/json; charset=utf-8");return ge(String(e),"text/plain; charset=utf-8")}async function Wt(e,t){let o=t.actionsPath||"actions",a=t.controllersPath||"controllers",c=e.replace(/\.(ts|js)$/,""),d=[];if(c.includes("@")){let[h,f]=c.split("@");d.push(`${a}/${h}`,`${a}/${h}.ts`,`${a}/${h}.js`,`./${a}/${h}`,`../${a}/${h}`)}else if(c.startsWith("Actions/")||c.startsWith("actions/"))d.push(c,`./${c}`,`../${c}`);else if(c.startsWith("./")||c.startsWith("../"))d.push(c);else d.push(`${o}/${c}`,`./${o}/${c}`,`../${o}/${c}`,c,`./${c}`,`../${c}`);let p=null;for(let h of d)try{return await import(h)}catch(f){p=f}throw Error(`Failed to import handler "${e}".
3
+ Tried paths: ${d.join(", ")}
4
+ Last error: ${p?.message||"Unknown error"}`)}function Ne(e){return typeof e==="function"&&!e.prototype?.handle}async function L(e,t,o){if(e instanceof Response)return e.clone();if(Ne(e)){let a=await e(t);return s(a)}if(typeof e==="string")return Vt(e,t,o);if(typeof e==="function"&&e.prototype&&typeof e.prototype.handle==="function"){let d=await new e().handle(t);return s(d)}if(e&&typeof e==="object"&&"handle"in e){let a=e;if(typeof a.handle==="function"){let c=await a.handle(t);return s(c)}}throw Error(`Invalid handler type: ${typeof e}`)}async function Vt(e,t,o){let a=o.controllersPath||"controllers";if(e.includes("@")){let[p,h]=e.split("@"),f=[`${a}/${p}`,`./${a}/${p}`,`../${a}/${p}`,p,`./${p}`,`../${p}`],R=null,y=null;for(let w of f)try{R=await import(w);break}catch(P){y=P}if(!R)throw Error(`Failed to import controller "${p}".
5
+ Tried paths: ${f.join(", ")}
6
+ Last error: ${y?.message||"Unknown error"}`);let b=R.default||R;if(typeof b==="function"){let w=new b,P=w[h];if(typeof P!=="function")throw TypeError(`Method "${h}" not found on controller "${p}"`);let M=await P.call(w,t);return s(M)}throw Error(`Controller "${p}" is not a valid class`)}let c=await Wt(e,o),d=c.default||c;if(typeof d==="function"){if(d.prototype&&typeof d.prototype.handle==="function"){let f=await new d().handle(t);return s(f)}let p=await d(t);return s(p)}if(d&&typeof d==="object"&&"handle"in d){let p=d;if(typeof p.handle==="function"){let h=await p.handle(t);return s(h)}}throw Error(`Handler "${e}" does not export a valid handler function or class`)}function Ct(e){return(t,o)=>L(t,o,e)}function _e(e,t){if(e instanceof Response)return()=>e.clone();if(Ne(e))return(o)=>{let a=e(o);if(a instanceof Response)return a;return a instanceof Promise?a.then(s):s(a)};if(typeof e==="function"&&e.prototype&&typeof e.prototype.handle==="function"){let o=e;return(a)=>{let c=new o().handle(a);if(c instanceof Response)return c;return c instanceof Promise?c.then(s):s(c)}}return(o)=>L(e,o,t)}class De{key;entry;prev;next;constructor(e,t,o=null,a=null){this.key=e;this.entry=t;this.prev=o;this.next=a}}class _{options;cache=new Map;head=null;tail=null;stats={hits:0,misses:0,evictions:0};constructor(e){this.options=e;if(e.maxSize<=0)throw Error("maxSize must be greater than 0")}get(e){let t=this.cache.get(e);if(!t){this.stats.misses++;return}let o=Date.now(),a=t.entry;if(this.isExpired(a,o)){if(!this.options.allowStale){this.delete(e),this.stats.misses++;return}}if(a.lastAccessed=o,a.accessCount++,this.stats.hits++,this.options.updateAgeOnGet!==!1)this.moveToFront(t);return a.value}set(e,t,o){let a=Date.now(),c=this.cache.get(e);if(c){c.entry.value=t,c.entry.timestamp=a,c.entry.lastAccessed=a,c.entry.ttl=o??this.options.ttl,this.moveToFront(c);return}let d={value:t,timestamp:a,accessCount:0,lastAccessed:a,ttl:o??this.options.ttl},p=new De(e,d);if(this.cache.set(e,p),this.addToFront(p),this.cache.size>this.options.maxSize)this.evictLRU()}delete(e){let t=this.cache.get(e);if(!t)return!1;if(this.cache.delete(e),this.removeNode(t),this.options.onEvict)this.options.onEvict(e,t.entry.value);return!0}has(e){let t=this.cache.get(e);if(!t)return!1;let o=Date.now();if(this.isExpired(t.entry,o)){if(!this.options.allowStale)return this.delete(e),!1}return!0}clear(){if(this.options.onEvict)for(let[e,t]of this.cache)this.options.onEvict(e,t.entry.value);this.cache.clear(),this.head=null,this.tail=null,this.stats.evictions+=this.cache.size}keys(){let e=[],t=this.head;while(t)e.push(t.key),t=t.next;return e}values(){let e=[],t=this.head;while(t)e.push(t.entry.value),t=t.next;return e}getStats(){let e=this.estimateMemoryUsage(),t=this.stats.hits+this.stats.misses;return{size:this.cache.size,maxSize:this.options.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,hitRate:t>0?this.stats.hits/t:0,memoryUsage:e}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}prune(){let e=Date.now(),t=[];for(let[o,a]of this.cache)if(this.isExpired(a.entry,e))t.push(o);for(let o of t)this.delete(o);return t.length}getFrequentlyUsed(e=10){let t=[];for(let[o,a]of this.cache)t.push({key:o,value:a.entry.value,accessCount:a.entry.accessCount});return t.sort((o,a)=>a.accessCount-o.accessCount).slice(0,e)}resize(e){if(e<=0)throw Error("maxSize must be greater than 0");this.options.maxSize=e;while(this.cache.size>e)this.evictLRU()}isExpired(e,t){if(!e.ttl)return!1;return t-e.timestamp>e.ttl}moveToFront(e){if(e===this.head)return;this.removeNode(e),this.addToFront(e)}addToFront(e){if(e.prev=null,e.next=this.head,this.head)this.head.prev=e;if(this.head=e,!this.tail)this.tail=e}removeNode(e){if(e.prev)e.prev.next=e.next;else this.head=e.next;if(e.next)e.next.prev=e.prev;else this.tail=e.prev}evictLRU(){if(!this.tail)return;let e=this.tail.key,t=this.tail.entry.value;if(this.cache.delete(e),this.removeNode(this.tail),this.stats.evictions++,this.options.onEvict)this.options.onEvict(e,t)}estimateMemoryUsage(){let e=0;for(let[t,o]of this.cache)e+=t.length*2,e+=this.estimateValueSize(o.entry.value),e+=64;return e+=this.cache.size*48,e}estimateValueSize(e){if(e===null||e===void 0)return 0;if(typeof e==="string")return e.length*2;if(typeof e==="number")return 8;if(typeof e==="boolean")return 1;if(e instanceof ArrayBuffer)return e.byteLength;if(e instanceof Uint8Array)return e.length;try{return JSON.stringify(e).length*2}catch{return 100}}}class te{cache;config;constructor(e,t=1e4){this.config=e,this.cache=new _({maxSize:t,ttl:e.windowMs*2})}async checkLimit(e){if(this.config.skipIf&&this.config.skipIf(e))return{allowed:!0,info:{totalHits:0,resetTime:new Date(Date.now()+this.config.windowMs),remaining:this.config.maxAttempts,limit:this.config.maxAttempts,windowMs:this.config.windowMs}};let t=this.generateKey(e),o=Date.now(),a=this.cache.get(t);if(!a||o>=a.resetTime)a={count:1,resetTime:o+this.config.windowMs,firstHit:o};else a.count++;this.cache.set(t,a);let c={totalHits:a.count,resetTime:new Date(a.resetTime),remaining:Math.max(0,this.config.maxAttempts-a.count),limit:this.config.maxAttempts,windowMs:this.config.windowMs};return{allowed:a.count<=this.config.maxAttempts,info:c}}generateKey(e){if(this.config.keyGenerator)return this.config.keyGenerator(e);let t=this.getClientIP(e),o=e.user?.id;if(o)return`user:${o}`;return`ip:${t}`}getClientIP(e){let t=e.headers.get("x-forwarded-for");if(t)return t.split(",")[0].trim();let o=e.headers.get("x-real-ip");if(o)return o;let a=e.headers.get("cf-connecting-ip");if(a)return a;return"unknown"}getStats(){return{...this.cache.getStats(),config:{maxAttempts:this.config.maxAttempts,windowMs:this.config.windowMs}}}}class Je{limiters=new Map;register(e,t){let o=new te(t);return this.limiters.set(e,o),o}get(e){return this.limiters.get(e)}getOrCreate(e,t){let o=this.limiters.get(e);if(o)return o;return this.register(e,t)}}var Xe=new Je;function C(e,t){let o=t?Xe.getOrCreate(t,e):new te(e);return async(a,c)=>{let{allowed:d,info:p}=await o.checkLimit(a);if(!d){if(e.onLimitReached)return e.onLimitReached(a,p);let f=new Headers({"Content-Type":"application/json","Retry-After":Math.ceil((p.resetTime.getTime()-Date.now())/1000).toString()});if(e.headers!==!1)f.set("X-RateLimit-Limit",p.limit.toString()),f.set("X-RateLimit-Remaining",p.remaining.toString()),f.set("X-RateLimit-Reset",Math.ceil(p.resetTime.getTime()/1000).toString());return new Response(JSON.stringify({error:"Too Many Requests",message:`Rate limit exceeded. Try again in ${Math.ceil((p.resetTime.getTime()-Date.now())/1000)} seconds.`,retryAfter:Math.ceil((p.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:f})}let h=await c();if(h&&e.headers!==!1&&h.status<400){let f=new Headers(h.headers);return f.set("X-RateLimit-Limit",p.limit.toString()),f.set("X-RateLimit-Remaining",p.remaining.toString()),f.set("X-RateLimit-Reset",Math.ceil(p.resetTime.getTime()/1000).toString()),new Response(h.body,{status:h.status,statusText:h.statusText,headers:f})}return h}}function S(e){let t=e.split(","),o=Number.parseInt(t[0],10);if(Number.isNaN(o)||o<=0)throw Error(`Invalid throttle max attempts: ${t[0]}`);let a;if(t.length===1)a=60000;else{let c=t[1];a=Kt(c)}return{maxAttempts:o,windowMs:a}}function Kt(e){let t=/^(\d+)([smh]|sec|min|hour)?$/,o=e.match(t);if(!o)throw Error(`Invalid time format: ${e}`);let a=Number.parseInt(o[1],10),c=o[2]||"m";if(Number.isNaN(a)||a<=0)throw Error(`Invalid time value: ${o[1]}`);switch(c){case"s":case"sec":return a*1000;case"m":case"min":return a*60*1000;case"h":case"hour":return a*60*60*1000;default:return a*60*1000}}var St={api:(e=60,t=1)=>({maxAttempts:e,windowMs:t*60*1000,headers:!0}),auth:()=>({maxAttempts:5,windowMs:900000,keyGenerator:(e)=>{let t=e.headers.get("x-forwarded-for")?.split(",")[0]||"unknown",o=e.jsonBody?.email||e.formBody?.email||e.query?.email||"unknown";return`auth:${t}:${o}`},onLimitReached:(e,t)=>new Response(JSON.stringify({error:"Too many authentication attempts",message:"Please try again later",retryAfter:Math.ceil((t.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:{"Content-Type":"application/json","Retry-After":Math.ceil((t.resetTime.getTime()-Date.now())/1000).toString()}})}),upload:()=>({maxAttempts:10,windowMs:3600000,keyGenerator:(e)=>{let t=e.user?.id;if(t)return`upload:user:${t}`;return`upload:ip:${e.headers.get("x-forwarded-for")?.split(",")[0]||"unknown"}`}}),search:()=>({maxAttempts:100,windowMs:600000,skipIf:(e)=>e.user?.plan==="premium"}),perUser:(e,t)=>({maxAttempts:e,windowMs:t*60*1000,keyGenerator:(o)=>{let a=o.user?.id;if(!a)throw Error("User authentication required for per-user rate limiting");return`user:${a}`},skipIf:(o)=>!o.user?.id}),perIP:(e,t)=>({maxAttempts:e,windowMs:t*60*1000,keyGenerator:(o)=>`ip:${o.headers.get("x-forwarded-for")?.split(",")[0]||o.headers.get("x-real-ip")||o.headers.get("cf-connecting-ip")||"unknown"}`}),global:(e,t)=>({maxAttempts:e,windowMs:t*60*1000,keyGenerator:()=>"global"})},gr={fromString:(e,t)=>{let o=S(e);return C(o,t)},getInfo:async(e,t)=>{let o=new te(t),{info:a}=await o.checkLimit(e);return a},reset:(e,t)=>{let o=Xe.get(e);if(o)return o.cache.delete(t);return!1}};import Jt from"process";var G=new Map;function g(e,t){G.set(e,t)}function xe(e){return G.get(e)}function Et(){return new Map(G)}function Pt(){G.clear()}function Mt(e,t={},o={}){let a=G.get(e);if(!a){let f=[...G.keys()].sort().join(", ")||"(none registered)";throw Error(`Named route '${e}' is not defined. Known routes: ${f}`)}let c=new Set,d=a;for(let[f,R]of Object.entries(t)){let y=`{${f}}`,b=`{${f}?}`,w=encodeURIComponent(String(R));if(d.includes(y))d=d.replaceAll(y,w),c.add(f);else if(d.includes(b))d=d.replaceAll(b,w),c.add(f)}if(d.includes("?}")){if(d=d.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),d.length>1&&d.endsWith("/"))d=d.slice(0,-1)}let p=d.match(/\{([^}?]+)\}/g);if(p&&p.length>0)throw Error(`Missing required params for route '${e}': ${p.join(", ")}`);let h=Object.entries(t).filter(([f])=>!c.has(f));if(h.length>0){let f=new URLSearchParams;for(let[R,y]of h)f.set(R,String(y));d+=`?${f.toString()}`}if(o.absolute){let f=(o.base??Jt.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${f.startsWith("http")?f:`https://${f}`}${d.startsWith("/")?d:`/${d}`}`}return d}var fr={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function kt(e){let{preserve:t=[],exclude:o=[],routes:a=[]}=e;if(!t.length)return"";return`<script data-query-preservation>
7
+ (function(){
8
+ var preserve = ${JSON.stringify(t)};
9
+ var exclude = ${JSON.stringify(o)};
10
+ var routes = ${JSON.stringify(a)};
11
+
12
+ function shouldPreserve(href) {
13
+ // Only preserve for same-origin links
14
+ try {
15
+ var url = new URL(href, window.location.origin);
16
+ if (url.origin !== window.location.origin) return false;
17
+ // Check route patterns if specified
18
+ if (routes.length) {
19
+ var path = url.pathname;
20
+ return routes.some(function(pattern) {
21
+ if (pattern.endsWith('*')) {
22
+ return path.startsWith(pattern.slice(0, -1));
23
+ }
24
+ // eslint-disable-next-line prefer-template
25
+ return path === pattern || path.startsWith(pattern + '/');
26
+ });
27
+ }
28
+ return true;
29
+ }
30
+ catch (e) { return false; }
31
+ }
32
+
33
+ function getPreservedParams() {
34
+ var current = new URLSearchParams(window.location.search);
35
+ var preserved = {};
36
+ preserve.forEach(function(key) {
37
+ if (current.has(key) && exclude.indexOf(key) === -1) {
38
+ preserved[key] = current.get(key);
39
+ }
40
+ });
41
+ return preserved;
42
+ }
43
+
44
+ function enhanceUrl(href) {
45
+ var url = new URL(href, window.location.origin);
46
+ var preserved = getPreservedParams();
47
+ Object.keys(preserved).forEach(function(key) {
48
+ if (!url.searchParams.has(key)) {
49
+ url.searchParams.set(key, preserved[key]);
50
+ }
51
+ });
52
+ return url.toString();
53
+ }
54
+
55
+ // Intercept all link clicks
56
+ document.addEventListener('click', function(e) {
57
+ var link = e.target.closest('a[href]');
58
+ if (!link) return;
59
+
60
+ var href = link.getAttribute('href');
61
+ if (!href || href.startsWith('#') || href.startsWith('javascript:') ||
62
+ href.startsWith('mailto:') || href.startsWith('tel:')) return;
63
+
64
+ if (!shouldPreserve(href)) return;
65
+
66
+ // Check if link already has all preserved params
67
+ var enhanced = enhanceUrl(href);
68
+ if (enhanced !== new URL(href, window.location.origin).toString()) {
69
+ e.preventDefault();
70
+ window.location.href = enhanced;
71
+ }
72
+ });
73
+
74
+ // Expose API for programmatic navigation
75
+ window.__preserveQuery = {
76
+ enhance: enhanceUrl,
77
+ getPreserved: getPreservedParams,
78
+ navigate: function(href) {
79
+ window.location.href = enhanceUrl(href);
80
+ }
81
+ };
82
+ })();
83
+ </script>`}function re(e,t){if(!t.enabled||!t.preserve?.length)return e;let o=kt(t);if(!o)return e;if(e.includes("</head>"))return e.replace("</head>",`${o}
84
+ </head>`);if(e.includes("</body>"))return e.replace("</body>",`${o}
85
+ </body>`);return e+o}function yr(e,t,o,a){let c=typeof t==="string"?new URL(t):t,d=new URL(e,c.origin);if(o.preserve){for(let p of o.preserve)if(c.searchParams.has(p)&&!o.exclude?.includes(p)){if(!d.searchParams.has(p))d.searchParams.set(p,c.searchParams.get(p))}}if(a)for(let[p,h]of Object.entries(a))d.searchParams.set(p,h);return d.pathname+d.search}import{join as Ie}from"path";function z(e){let t=e.replace(/\/+/g,"/");if(!t.startsWith("/"))t=`/${t}`;if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);return t}function wr(e){return e.replace(/\//g,"_").toLowerCase()}function $t(e){if(typeof e!=="function"&&typeof e!=="object")return!1;if(typeof e==="function"&&e.prototype){if(typeof e.prototype.handle==="function")return!0}if(typeof e==="object"&&e!==null&&"handle"in e&&typeof e.handle==="function")return!0;return!1}function br(e){return typeof e==="function"&&!$t(e)}function ne(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map((o)=>o.slice(1,-1).replace("?","")):[]}function Rr(e){let t=e.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${t}$`)}var Qt=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,Xt=/\{[^}]+\?\}/,Ue=new Map,Le=new Map;function Zt(e){let t=Ue.get(e);if(t)return t;let o=e.endsWith("/*"),a=z(e),c=0,d=a.split("/").filter(Boolean).map((h)=>{let f=Xt.test(h);if(f)c++;let R=h.match(Qt);return{isParam:!!R,paramName:R?R[1].replace("?",""):"",isOptional:f,literal:h}}),p={isWildcard:o,wildcardBase:o?e.slice(0,-2):"",segments:d,optionalCount:c};return Ue.set(e,p),p}function Yt(e){let t=Le.get(e);if(t!==void 0)return t;let o;try{o=new RegExp(`^${e}$`)}catch{o=null}return Le.set(e,o),o}function l(e,t,o,a){let c=Zt(e);if(c.isWildcard&&t.startsWith(c.wildcardBase))return!0;let d=c.segments,p=z(t).split("/").filter(Boolean);if(p.length<d.length-c.optionalCount||p.length>d.length)return!1;for(let h=0;h<d.length;h++){let f=d[h],R=p[h];if(R===void 0){if(f.isOptional)continue;return!1}if(f.isParam){let y=v(R);if(o[f.paramName]=y,a&&a[f.paramName]){let b=Yt(a[f.paramName]);if(b){if(!b.test(y))return!1}else console.warn(`Invalid constraint regex for parameter ${f.paramName}: ${a[f.paramName]}`)}}else if(f.literal!==R)return!1}return!0}function u(...e){return z(e.join("/"))}function vr(e){if(!e.startsWith("/"))return!1;let t=[];for(let o of e)if(o==="{")t.push(o);else if(o==="}"){if(t.length===0||t.pop()!=="{")return!1}return t.length===0}async function Ye(e){try{return await Bun.file(e).exists()}catch{return!1}}async function Te(e,t,o){if(o.some((a)=>e.endsWith(a))){let a=z(Ie(t,e));if(await Ye(a))return a;return null}for(let a of o){let c=z(Ie(t,`${e}${a}`));if(await Ye(c))return c}return null}function Qe(e,t){let o=e.replace(/\{\{([^}]+)\}\}/g,(a,c)=>{let d=c.trim(),p=Ee(t,d);return p!==void 0?String(p):a});return o=er(o,t),o=tr(o,t),o}function er(e,t){return e.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(o,a,c,d="")=>{let p=a.trim();return Ee(t,p)?c:d})}function tr(e,t){return e.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(o,a,c)=>{let d=Ee(t,a.trim());if(!Array.isArray(d))return"";return d.map((p)=>c.replace(/\{\{@index\}\}/g,String(d.indexOf(p))).replace(/\{\{this\}\}/g,String(p)).replace(/\{\{this\.([^}]+)\}\}/g,(h,f)=>{let R=p[f.trim()];return R!==void 0?String(R):""})).join("")})}function Ee(e,t){return t.split(".").reduce((o,a)=>{if(o&&typeof o==="object"&&a in o)return o[a];return},e)}var rr=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,nr=/bot|crawler|spider|crawling/i,me=new Map;function W(e){let t=e;if(!t._parsedURL)t._parsedURL=new URL(e.url);return t._parsedURL}function F(e){let t=e;if(!t._parsedCookies){let o={},a=e.headers.get("cookie");if(a)for(let c of a.split(";")){let d=c.indexOf("=");if(d===-1)continue;let p=c.slice(0,d).trim();if(!p)continue;let h=c.slice(d+1).trim();try{o[p]=decodeURIComponent(h)}catch{o[p]=h}}t._parsedCookies=o}return t._parsedCookies}class Be{macros=new Map;epoch=0;register(e,t,o=!1){this.macros.set(e,{name:e,handler:t,accessor:o}),this.epoch++}get(e){return this.macros.get(e)}has(e){return this.macros.has(e)}all(){return Array.from(this.macros.values())}remove(e){let t=this.macros.delete(e);if(t)this.epoch++;return t}clear(){this.macros.clear(),this.epoch++}getEpoch(){return this.epoch}}var ae=new Be,je=Symbol("bunRouterMacroProto"),ke=Symbol("bunRouterMacroBase"),fe=new WeakMap,Fe=-1;class i{static macro(e,t){ae.register(e,t)}static macroAccessor(e,t){ae.register(e,t,!0)}static applyMacros(e){let t=ae.getEpoch();if(t!==Fe)fe=new WeakMap,Fe=t;let o=Object.getPrototypeOf(e)??Object.prototype;if(o[je]){if(fe.get(o[ke])===o)return e;o=o[ke]}let a=fe.get(o);if(!a){a=Object.create(o);for(let c of ae.all())if(c.accessor)Object.defineProperty(a,c.name,{get:c.handler,set(d){Object.defineProperty(this,c.name,{value:d,writable:!0,configurable:!0,enumerable:!0})},configurable:!0});else a[c.name]=c.handler;Object.defineProperty(a,je,{value:!0}),Object.defineProperty(a,ke,{value:o}),fe.set(o,a)}return Object.setPrototypeOf(e,a),e}static hasMacro(e){return ae.has(e)}}var ue={wantsJson(){let e=this.headers.get("accept")||"";return e.includes("application/json")||e.includes("json")},wantsHtml(){let e=this.headers.get("accept")||"";return e.includes("text/html")||e.includes("html")},wantsXml(){let e=this.headers.get("accept")||"";return e.includes("application/xml")||e.includes("xml")},expectsJson(){return this.wantsJson()||this.isAjax()||this.isPjax()},isAjax(){return this.headers.get("x-requested-with")==="XMLHttpRequest"},isPjax(){return this.headers.get("x-pjax")==="true"},isMobile(){return rr.test(this.headers.get("user-agent")||"")},isBot(){return nr.test(this.headers.get("user-agent")||"")},isSecure(){return this.url.startsWith("https://")||this.headers.get("x-forwarded-proto")==="https"||this.headers.get("x-forwarded-ssl")==="on"},ip(){return this.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||this.headers.get("x-real-ip")||this.headers.get("cf-connecting-ip")||this.headers.get("x-client-ip")||"unknown"},ips(){let e=this.headers.get("x-forwarded-for");if(e)return e.split(",").map((t)=>t.trim());return[ue.ip.call(this)]},userAgent(){return this.headers.get("user-agent")||""},referer(){return this.headers.get("referer")||this.headers.get("referrer")||null},bearerToken(){let e=this.headers.get("authorization");if(e&&e.startsWith("Bearer "))return e.substring(7);return null},async rawBody(){if(typeof this._rawBody==="string")return this._rawBody;try{let e=await this.clone().text();return this._rawBody=e,e}catch{return""}},basicAuth(){let e=this.headers.get("authorization");if(e&&e.startsWith("Basic "))try{let t=atob(e.substring(6)),[o,a]=t.split(":");return{username:o,password:a}}catch{return null}return null},hasHeader(e){return this.headers.has(e.toLowerCase())},header(e,t){return this.headers.get(e.toLowerCase())||t||null},allHeaders(){let e={};return this.headers.forEach((t,o)=>{e[o]=t}),e},input(e,t){if(this.validated&&e in this.validated)return this.validated[e];if(this.query&&e in this.query)return this.query[e];if(this.params&&e in this.params)return this.params[e];if(this.jsonBody&&typeof this.jsonBody==="object"&&e in this.jsonBody)return this.jsonBody[e];if(this.formBody&&typeof this.formBody==="object"&&e in this.formBody)return this.formBody[e];return t},all(){return{...this.params,...this.query,...typeof this.jsonBody==="object"&&this.jsonBody!==null?this.jsonBody:{},...typeof this.formBody==="object"&&this.formBody!==null?this.formBody:{},...typeof this.validated==="object"&&this.validated!==null?this.validated:{}}},only(e){let t=this.all(),o={};return e.forEach((a)=>{if(a in t)o[a]=t[a]}),o},except(e){let t=this.all(),o={};return Object.keys(t).forEach((a)=>{if(!e.includes(a))o[a]=t[a]}),o},has(e){let t=this.all();return e in t&&t[e]!==void 0&&t[e]!==null&&t[e]!==""},hasAny(e){return e.some((t)=>this.has(t))},missing(e){return!this.has(e)},filled(e){let t=this.input(e);if(t===null||t===void 0)return!1;if(typeof t==="string")return t.trim().length>0;if(Array.isArray(t))return t.length>0;if(typeof t==="object")return Object.keys(t).length>0;return!0},getQuery(e,t){if(!e)return this.query||{};return this.query?.[e]||t},param(e,t){return this.params?.[e]||t},cookie(e,t){let o=F(this)[e];return o!==void 0?o:t||null},cookies(){return{...F(this)}},file(e){return this.files?.find((t)=>t.fieldName===e)},hasFile(e){return!!this.files?.find((t)=>t.fieldName===e)},path(){return W(this).pathname},fullUrl(){return this.url},root(){let e=W(this);return`${e.protocol}//${e.host}`},is(e){let t=this.path(),o=me.get(e);if(!o){let a=e.replace(/\*/g,".*").replace(/\?/g,".");if(o=new RegExp(`^${a}$`),me.size>=1000)me.clear();me.set(e,o)}return o.test(t)},route(){return this.routeName||null},fingerprint(){let e=W(this),t={method:this.method,path:e.pathname,query:e.search,ip:ue.ip.call(this)};return btoa(JSON.stringify(t))},signature(e){let t=`${this.method}${this.url}${ue.ip.call(this)}${e}`,o=0;for(let a=0;a<t.length;a++){let c=t.charCodeAt(a);o=(o<<5)-o+c,o=o&o}return Math.abs(o).toString(36)},merge(e){if(!this.validated)this.validated={};Object.assign(this.validated,e)},replace(e){this.validated={...e}},age(){let e=this.startTime||Date.now();return Date.now()-e},isFromTrustedProxy(e=[]){let t=ue.ip.call(this);return e.includes(t)},contentLength(){let e=this.headers.get("content-length");return e?Number.parseInt(e,10):0},contentType(){return this.headers.get("content-type")},isContentType(e){let t=this.contentType();return t?t.includes(e):!1}};function sr(){Object.entries(ue).forEach(([e,t])=>{i.macro(e,t)})}sr();function ye(e){let t=e;if(!t._parsedQuery){let o={};if(t._parsedURL||e.url.includes("?"))for(let[a,c]of W(e).searchParams){let d=o[a];if(d===void 0)o[a]=c;else if(Array.isArray(d))d.push(c);else o[a]=[d,c]}t._parsedQuery=o}return t._parsedQuery}function Ae(e){if(e===null||e instanceof Response)return e;return Promise.resolve(e)}function ir(e){let t=Ae(e);if(t instanceof Promise)return t.then((o)=>o||new Response(null,{status:200}));return t||new Response(null,{status:200})}function ze(e){if(e.length===0)return()=>null;let t=()=>null;for(let o=e.length-1;o>=0;o--){let a=e[o],c=t;t=(d)=>{try{return Ae(a(d,()=>{try{return ir(c(d))}catch(p){return Promise.reject(p)}}))}catch(p){return Promise.reject(p)}}}return t}function le(e){let t=ze(e);return(o)=>Promise.resolve(t(o))}function V(e,t){if(e.buildMiddlewareChain===le)return ze(t);let o=e.buildMiddlewareChain(t);return(a)=>Ae(o(a))}class n{routes=[];currentGroup=null;globalMiddleware=[];namedRoutes=new Map;fallbackHandler=null;patterns=new Map;currentDomain=null;domains={};serverInstance=null;wsConfig=null;errorHandler=null;templateCache=new Map;routeCache=new Map;staticRoutes=new Map;staticResponses=new Map;precompiledPatterns=new Map;domainPatternCache=new Map;routeCompiler=null;_hasDomainRoutes=!1;middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];_middlewarePipeline;_mwEpoch=0;_allowedMethodsCache=new Map;config={verbose:!1,routesPath:"routes",apiRoutesPath:"routes/api.ts",webRoutesPath:"routes/web.ts",apiPrefix:"/api",webPrefix:"",actionsPath:"actions",controllersPath:"controllers",defaultMiddleware:{api:[],web:[]}};constructor(e={}){this.routes=[],this.config={...this.config,...e},this.initializeDefaultMiddleware()}initializeDefaultMiddleware(){this.namedMiddleware.set("auth",()=>async(e,t)=>{if(!e.headers.get("authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return await t()}),this.namedMiddleware.set("throttle",(e)=>{let t=e?S(e):{maxAttempts:60,windowMs:60000};return C({maxAttempts:t.maxAttempts||60,windowMs:t.windowMs,keyGenerator:(o)=>o.headers.get("x-forwarded-for")||"anonymous"})}),this.namedMiddleware.set("cors",()=>async(e,t)=>{let o=await t();if(o)o.headers.set("Access-Control-Allow-Origin","*"),o.headers.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),o.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization");return o})}middlewareGroup(e,t){let o=[];for(let a of t){let[c,d]=a.split(":"),p=this.namedMiddleware.get(c);if(p)o.push(p(d))}return this.middlewareGroups.set(e,o),this}middlewareGroupRoutes(e){let t=this.middlewareGroups.get(e)||[];return new Ze(this,t)}when(e){return new We(this,e)}middleware(e){let[t,o]=e.split(":"),a=this.namedMiddleware.get(t);if(!a)throw Error(`Unknown middleware: ${t}`);let c=a(o);return new Ve(this,[c])}getServer(){return this.serverInstance}extend(e){for(let[t,o]of Object.entries(e))if(typeof o==="function")this[t]=o.bind(this);return this}async register(e,t){let o=async()=>{await import(e)};if(t?.prefix||t?.middleware&&t.middleware.length>0)await this.group({prefix:t.prefix,middleware:t.middleware},o);else await o();return this}invalidateCache(){this.routeCache.clear(),this._allowedMethodsCache.clear()}registerRoute(e,t,o,a,c,d){let p=t,h=[],f=a||"web";if(this.currentGroup){if(this.currentGroup.prefix)p=u(this.currentGroup.prefix,t);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)h=[...this.currentGroup.middleware]}if(d&&d.length>0)for(let P of d){let M=this.resolveMiddleware(P);if(M)h.push(M)}if(f==="api"&&this.config.apiPrefix)p=u(this.config.apiPrefix,p);else if(f==="web"&&this.config.webPrefix)p=u(this.config.webPrefix,p);let R;if(this.currentDomain)R=this.currentDomain;let y={method:e.toUpperCase(),path:p,handler:o,domain:R,params:{},middleware:h},b=ne(p),w={};if(b.forEach((P)=>{let M=P.replace("?","");if(this.patterns.has(M))w[M]=this.patterns.get(M)}),Object.keys(w).length>0)y.constraints=w;if(y.pattern={exec:(P)=>{let M={},E=y.constraints&&!Array.isArray(y.constraints)?y.constraints:void 0;if(!l(p,P.pathname,M,E))return null;return{pathname:{groups:M}}}},R){if(!this.domains[R])this.domains[R]=[];this.domains[R].push(y)}else this.routes.push(y);if(!p.includes("{")&&!p.includes("*")){if(!this.staticRoutes.has(e.toUpperCase()))this.staticRoutes.set(e.toUpperCase(),new Map);this.staticRoutes.get(e.toUpperCase()).set(p,y)}if(c)y.name=c,this.namedRoutes.set(c,y),g(c,y.path);return this.routeCache.clear(),this}resolveMiddleware(e){if(typeof e==="function")return e;let[t,o]=e.split(":"),a=this.namedMiddleware.get(t);if(a)return a(o);return null}get(e,t,o,a,c){return this.registerRoute("GET",e,t,o,a,c)}post(e,t,o,a,c){return this.registerRoute("POST",e,t,o,a,c)}put(e,t,o,a,c){return this.registerRoute("PUT",e,t,o,a,c)}patch(e,t,o,a,c){return this.registerRoute("PATCH",e,t,o,a,c)}delete(e,t,o,a,c){return this.registerRoute("DELETE",e,t,o,a,c)}options(e,t,o,a,c){return this.registerRoute("OPTIONS",e,t,o,a,c)}match(e,t,o,a,c,d){for(let p of e)this.registerRoute(p,t,o,a,c,d);return this}any(e,t,o,a,c){for(let d of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this.registerRoute(d,e,t,o,a,c);return this}fallback(e){return this.fallbackHandler=e,this}route(e,t={}){let o=this.namedRoutes.get(e);if(!o)throw Error(`Route with name "${e}" not found`);let a=o.path;for(let[c,d]of Object.entries(t))a=a.replace(`{${c}}`,encodeURIComponent(d)),a=a.replace(`{${c}?}`,encodeURIComponent(d));return a}onError(e){return this.errorHandler=e,this}redirect(e,t=302){let o=new Headers;return o.set("Location",e),new Response(null,{status:t,headers:o})}permanentRedirect(e){return this.redirect(e,301)}redirectRoute(e,t,o=302){return this.get(e,(a)=>this.redirect(t,o)),this}async serve(e){this.invalidateCache();let t={...e,fetch:this.handleRequest.bind(this),websocket:this.wsConfig};if(this.serverInstance=Bun.serve(t),this.config.verbose){let o=this.serverInstance.port,a=this.serverInstance.hostname;console.log(`
86
+ \uD83D\uDE80 Server running at http://${a}:${o}
87
+ `)}return this.serverInstance}async handleRequest(e){try{let t=new URL(e.url);if(this.config.verbose)console.log(`${e.method} ${t.pathname}`);if(e.method==="OPTIONS"){let p=t.hostname||e.headers.get("host")?.split(":")[0]||"localhost";if(!this.matchRoute(t.pathname,"OPTIONS",p))return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}})}let o=t.hostname||e.headers.get("host")?.split(":")[0]||"localhost",a=this.matchRoute(t.pathname,e.method,o),c=this.enhanceRequest(e,a?.params||{});if(a){c.route=a.route;let p=[...this.globalMiddleware];if(a.route.middleware&&a.route.middleware.length>0)p.push(...a.route.middleware);let h=async(R,y)=>await this.resolveHandler(a.route.handler,R);p.push(h);let f=await this.runMiddleware(c,p);if(f)return this.applyModifiedCookies(f,c);return new Response("No response from middleware chain",{status:500})}let d=this.getAllowedMethods(t.pathname,o);if(d.length>0){let p=async(h,f)=>new Response(JSON.stringify({error:"Method Not Allowed",path:t.pathname,method:e.method,allowed:d}),{status:405,headers:{"Content-Type":"application/json",Allow:d.join(", ")}});if(this.globalMiddleware.length>0){let h=[...this.globalMiddleware,p],f=await this.runMiddleware(c,h);if(f)return this.applyModifiedCookies(f,c)}return p(c,async()=>new Response(null))}if(this.globalMiddleware.length>0){let p=async(R,y)=>{if(this.fallbackHandler)return await this.resolveHandler(this.fallbackHandler,c);return oe(new Response(JSON.stringify({error:"Not Found",path:t.pathname,method:e.method}),{status:404,headers:{"Content-Type":"application/json"}}))},h=[...this.globalMiddleware,p],f=await this.runMiddleware(c,h);if(f)return this.applyModifiedCookies(f,c)}if(this.fallbackHandler){let p=await this.resolveHandler(this.fallbackHandler,c);return this.applyModifiedCookies(p,c)}return oe(new Response(JSON.stringify({error:"Not Found",path:t.pathname,method:e.method}),{status:404,headers:{"Content-Type":"application/json"}}))}catch(t){if(console.error("Error handling request:",t),this.globalMiddleware.length>0){let o=this.enhanceRequest(e,{}),a=async(d,p)=>{if(this.errorHandler)return this.errorHandler(t);return new Response(JSON.stringify({error:"Internal Server Error",message:t instanceof Error?t.message:String(t)}),{status:500,headers:{"Content-Type":"application/json"}})},c=[...this.globalMiddleware,a];try{let d=await this.runMiddleware(o,c);if(d)return d}catch{}}if(this.errorHandler)return this.errorHandler(t);return new Response(JSON.stringify({error:"Internal Server Error",message:t instanceof Error?t.message:String(t)}),{status:500,headers:{"Content-Type":"application/json"}})}}getAllowedMethods(e,t,o=!1){let a,c=e;if(!o)a=new URL(e,"http://localhost"),c=a.pathname;let d=`${t||""}:${c}`,p=this._allowedMethodsCache.get(d);if(p)return p;let h=new Set;for(let[y,b]of this.staticRoutes){let w=b.get(c);if(w&&(!t||!w.domain||w.domain===t))h.add(y)}let f=t&&this.domains[t]?this.domains[t]:this.routes;for(let y of f){if(h.has(y.method))continue;if(y.path===c){h.add(y.method);continue}if(y.pattern&&y.pattern.exec(a??=new URL(c,"http://localhost"))){h.add(y.method);continue}if(y.path.endsWith("*")&&c.startsWith(y.path.slice(0,-1)))h.add(y.method)}if(h.has("GET"))h.add("HEAD");let R=Array.from(h);if(this._allowedMethodsCache.size>=1e4)this._allowedMethodsCache.clear();return this._allowedMethodsCache.set(d,R),R}matchRoute(e,t,o){let a=new URL(e,"http://localhost"),c=`${o||""}:${t}:${a.pathname}`;if(this.routeCache.has(c))return this.routeCache.get(c);if(this.staticRoutes.has(t)){let f=this.staticRoutes.get(t).get(a.pathname);if(f&&(!o||!f.domain||f.domain===o)){let R={route:f,params:{}};return this.routeCache.set(c,R),R}}let p=(o&&this.domains[o]?this.domains[o]:this.routes).filter((f)=>f.method===t);for(let f of p)if(f.path===a.pathname){let R={route:f,params:{}};return this.routeCache.set(c,R),R}for(let f of p)if(f.pattern){let R=f.pattern.exec(a);if(R){let y={route:f,params:R.pathname.groups};return this.routeCache.set(c,y),y}}if(o&&this.domains[o]){let f=this.domains[o].filter((R)=>R.method===t&&R.path.endsWith("*"));for(let R of f){let y=R.path.slice(0,-1);if(a.pathname.startsWith(y)){let b={route:R,params:{wildcard:a.pathname.slice(y.length)}};return this.routeCache.set(c,b),b}}}let h=this.routes.filter((f)=>f.method===t&&f.path.endsWith("*")&&(!o||!f.domain));for(let f of h){let R=f.path.slice(0,-1);if(a.pathname.startsWith(R)){let y={route:f,params:{wildcard:a.pathname.slice(R.length)}};return this.routeCache.set(c,y),y}}if(t==="HEAD")return this.matchRoute(e,"GET",o);return}enhanceRequest(e,t={}){let o=null,a=()=>{if(o===null)o={},(e.headers.get("cookie")||"").split(";").forEach((f)=>{let R=f.trim().split("=");if(R.length>=2){let y=R[0].trim(),b=R.slice(1).join("=").trim();o[y]=decodeURIComponent(b)}});return o},c=ye(e),d={get url(){return e.url},get method(){return e.method},get headers(){return e.headers},get body(){return e.body},get bodyUsed(){return e.bodyUsed},get cache(){return e.cache},get credentials(){return e.credentials},get destination(){return e.destination},get integrity(){return e.integrity},get keepalive(){return e.keepalive},get mode(){return e.mode},get redirect(){return e.redirect},get referrer(){return e.referrer},get referrerPolicy(){return e.referrerPolicy},get signal(){return e.signal},arrayBuffer:()=>e.arrayBuffer(),blob:()=>e.blob(),clone:()=>e.clone(),formData:()=>e.formData(),json:()=>e.json(),text:()=>e.text(),params:t,query:c,jsonBody:null,formBody:null,_cookiesToSet:[],_cookiesToDelete:[]},p=()=>{let h={};for(let[f,R]of Object.entries(c))h[f]=R;if(d.jsonBody&&typeof d.jsonBody==="object")for(let[f,R]of Object.entries(d.jsonBody))h[f]=R;if(d.formBody&&typeof d.formBody==="object")for(let[f,R]of Object.entries(d.formBody))h[f]=R;for(let[f,R]of Object.entries(t))h[f]=R;return h};return d.cookies=X({read:a,write:(h,f,R)=>{d._cookiesToSet.push({name:h,value:f,options:R})},remove:(h,f)=>{d._cookiesToDelete.push({name:h,options:f})}}),d.get=(h,f)=>{let y=p()[h];return y!==void 0?y:f},d.input=(h,f)=>{let y=p()[h];return y!==void 0?y:f},d.all=()=>p(),d.only=(h)=>{let f=p(),R={};for(let y of h)if(y in f)R[y]=f[y];return R},d.except=(h)=>{let R={...p()};for(let y of h)delete R[y];return R},d.has=(h)=>{let f=p();if(Array.isArray(h))return h.every((R)=>(R in f)&&f[R]!==void 0);return h in f&&f[h]!==void 0},d.hasAny=(h)=>{let f=p();return h.some((R)=>(R in f)&&f[R]!==void 0)},d.filled=(h)=>{let f=p(),R=(y)=>{let b=f[y];return b!==void 0&&b!==null&&b!==""&&!(Array.isArray(b)&&b.length===0)};if(Array.isArray(h))return h.every(R);return R(h)},d.missing=(h)=>{let f=p();if(Array.isArray(h))return h.every((R)=>!(R in f)||f[R]===void 0);return!(h in f)||f[h]===void 0},d.string=(h,f="")=>{let y=p()[h];return y!==void 0&&y!==null?String(y):f},d.integer=(h,f=0)=>{let y=p()[h],b=Number.parseInt(String(y),10);return Number.isNaN(b)?f:b},d.float=(h,f=0)=>{let y=p()[h],b=Number.parseFloat(String(y));return Number.isNaN(b)?f:b},d.boolean=(h,f=!1)=>{let y=p()[h];if(y===void 0||y===null)return f;if(typeof y==="boolean")return y;if(y==="true"||y==="1"||y===1)return!0;if(y==="false"||y==="0"||y===0)return!1;return f},d.array=(h)=>{let R=p()[h];if(Array.isArray(R))return R;return R!==void 0&&R!==null?[R]:[]},d.bearerToken=()=>{let h=e.headers.get("authorization")||e.headers.get("Authorization")||"";if(h.startsWith("Bearer "))return h.substring(7);return null},d.header=(h)=>e.headers.get(h)||e.headers.get(h.toLowerCase())||null,d.cookie=(h,f)=>{let R=a()[h];return R!==void 0?R:f??null},d.getParam=(h,f)=>{let R=t?.[h];return R!==void 0?R:f},d.getParamAsInt=(h)=>{let f=t?.[h];if(f===void 0||f.trim()==="")return null;let R=Number(f);return Number.isSafeInteger(R)?R:null},d.params=t||{},d}applyModifiedCookies(e,t){let o=new Response(e.body,{status:e.status,statusText:e.statusText,headers:e.headers});if(t._cookiesToSet&&t._cookiesToSet.length>0)for(let{name:a,value:c,options:d}of t._cookiesToSet){let p=this.serializeCookie(a,c,d);o.headers.append("Set-Cookie",p)}if(t._cookiesToDelete&&t._cookiesToDelete.length>0)for(let{name:a,options:c}of t._cookiesToDelete){let d={...c,expires:new Date(0),maxAge:0},p=this.serializeCookie(a,"",d);o.headers.append("Set-Cookie",p)}return o}serializeCookie(e,t,o={}){let a=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(o.maxAge!==void 0)a+=`; Max-Age=${o.maxAge}`;if(o.expires&&o.expires instanceof Date)a+=`; Expires=${o.expires.toUTCString()}`;if(o.path)a+=`; Path=${o.path}`;else a+="; Path=/";if(o.domain)a+=`; Domain=${o.domain}`;if(o.secure)a+="; Secure";if(o.httpOnly)a+="; HttpOnly";if(o.sameSite){let c=o.sameSite.toLowerCase();a+=`; SameSite=${c.charAt(0).toUpperCase()+c.slice(1)}`}return a}buildMiddlewareChain(e){return le(e)}async runMiddleware(e,t){if(t.length===0)return null;try{return await V(this,t)(e)}catch(o){if(this.errorHandler)return this.errorHandler(o);throw o}}async resolveHandler(e,t){if(typeof e==="function"&&!e.prototype?.handle)return await e(t);if(typeof e==="function"&&e.prototype?.handle)return await new e().handle(t);if(e&&typeof e.handle==="function")return await e.handle(t);throw Error(`Invalid action handler: ${typeof e}`)}use(...e){for(let t of e){let o=this.resolveMiddleware(t);if(o)this.globalMiddleware.push(o)}return this}group(e,t){let o=this.currentGroup;if(this.currentGroup={prefix:e.prefix||"",middleware:[]},e.middleware){for(let c of e.middleware)if(typeof c==="function")this.currentGroup.middleware.push(c)}let a=t();if(a instanceof Promise)return a.then(()=>(this.currentGroup=o,this),(c)=>{throw this.currentGroup=o,c});return this.currentGroup=o,this}addRoute(e){if(this.routes.push(e),e.name)this.namedRoutes.set(e.name,e),g(e.name,e.path);return this}registerMiddlewareDependency(e){if(this._middlewarePipeline)this._middlewarePipeline.registerDependency(e);return this}registerMiddlewareSkipConditions(e,t){return this}getMiddlewareStats(){if(this._middlewarePipeline)return this._middlewarePipeline.getStats();return{}}getMiddlewareCacheInfo(){return{size:0,routes:[],hitRate:0}}clearMiddlewareCache(){if(this._middlewarePipeline)this._middlewarePipeline.clear();return this}async executeMiddleware(e,t,o){if(e.length===0)return o();let a=0,c=async()=>{if(a>=e.length)return o();let d=e[a++];return await d(t,c)||new Response("No response from middleware",{status:500})};return c()}}class We{router;condition;constructor(e,t){this.router=e;this.condition=t}middleware(e){let[t,o]=e.split(":"),a=this.router.namedMiddleware.get(t);if(!a)throw Error(`Unknown middleware: ${t}`);let c=a(o);return this.router.conditionalMiddleware.push({condition:this.condition,middleware:[c]}),this}}class Ve{router;middleware;constructor(e,t){this.router=e;this.middleware=t}get(e,t){return this}post(e,t){return this}put(e,t){return this}delete(e,t){return this}}class Ze{router;middleware;constructor(e,t){this.router=e;this.middleware=t}get(e,t){return this}post(e,t){return this}put(e,t){return this}delete(e,t){return this}}var He=null;function or(){if(He===null)He=new n;return He}function se(e,t={}){if(typeof e.bearerToken==="function")return e;return or().enhanceRequest(e,t)}import{existsSync as tt,readdirSync as ar,statSync as ur}from"fs";import{basename as rt,extname as et,join as lr,resolve as nt}from"path";var cr=[".ts",".js"],dr=["routes","src/routes"],Tr=["web","index"];function xr(){let e=process.cwd();for(let t of dr){let o=nt(e,t);if(tt(o)&&ur(o).isDirectory())return o}return null}function st(e,t){let o=[];if(!tt(e))return o;let a=ar(e,{withFileTypes:!0});for(let c of a){if(c.name.startsWith(".")||c.name.startsWith("_"))continue;let d=lr(e,c.name);if(c.isDirectory())o.push(...st(d,t));else if(cr.includes(et(c.name))){let p=e===t?"":e.slice(t.length),h=rt(c.name,et(c.name)),f=Tr.includes(h)?p||"":`${p}/${h}`;o.push({filePath:d,prefix:f})}}return o}async function Pr(e,t,o,a){try{let c=await import(t),d=0,p=e.routes?.length||0;if(typeof c.default==="function"){let h=Cr(e,o);await c.default(h),d=(e.routes?.length||0)-p}else if(Array.isArray(c.routes))for(let h of c.routes){let f=(h.method||"GET").toLowerCase(),R=`${o}${h.path}`;if(typeof e[f]==="function")await e[f](R,h.handler),d++}if(a&&d>0)console.log(` ${o||"/"} \u2192 ${rt(t)} (${d} routes)`);return d}catch(c){return console.error(`[bun-router] Failed to load route file ${t}:`,c),0}}function Cr(e,t){if(!t)return e;let o=["get","post","put","patch","delete","options","any"];return new Proxy(e,{get(a,c){if(o.includes(c))return async(d,...p)=>a[c](`${t}${d}`,...p);if(c==="group")return async(d,p)=>{let h=d.prefix?`${t}${d.prefix}`:t;return a.group({...d,prefix:h},p)};return a[c]}})}function it(e){Object.defineProperties(e.prototype,{_routesDir:{value:null,writable:!0,configurable:!0},_apiRoutesInitialized:{value:!1,writable:!0,configurable:!0},_initApiRoutes:{async value(){if(this._apiRoutesInitialized)return;let t=this._routesDir||xr();if(!t){this._apiRoutesInitialized=!0;return}let o=this.config?.verbose||!1,a=st(t,t);if(a.length===0){this._apiRoutesInitialized=!0;return}if(o)console.log(`[bun-router] Auto-discovering API routes from ${t}:`);let c=0;for(let{filePath:d,prefix:p}of a)c+=await Pr(this,d,p,o);if(c>0&&o)console.log(`[bun-router] Registered ${c} API routes`);this._apiRoutesInitialized=!0},writable:!0,configurable:!0},routesFrom:{value(t){return this._routesDir=nt(t),this},writable:!0,configurable:!0}})}import{join as ce,relative as qe,resolve as N,dirname as Sr}from"path";import{readdirSync as ot,statSync as Mr,existsSync as be}from"fs";var Er=["src/views","views","resources/views","app/views"],kr=["_","components","layouts","partials","scripts","styles"],Ar=[".stx",".html"];function Hr(e=process.cwd()){for(let t of Er){let o=N(e,t);if(be(o)&&Mr(o).isDirectory())return o}return null}function at(e,t,o){if(!be(e))return!1;try{let a=ot(e,{withFileTypes:!0});for(let c of a){if(o.some((d)=>c.name.startsWith(d)||c.name===d))continue;if(c.isFile()&&t.some((d)=>c.name.endsWith(d)))return!0;if(c.isDirectory()){let d=ce(e,c.name);if(at(d,t,o))return!0}}}catch{}return!1}function qr(e,t,o){let a=qe(t,e);for(let d of o)if(a.endsWith(d)){a=a.slice(0,-d.length);break}if(a=a.replace(/\\/g,"/"),a==="index"||a.endsWith("/index"))a=a.replace(/\/?index$/,"");let c=[];if(a=a.replace(/\[\.\.\.([^\]]+)\]/g,(d,p)=>(c.push(p),`{${p}}*`)),a=a.replace(/\[([^\]]+)\]/g,(d,p)=>(c.push(p),`{${p}}`)),!a.startsWith("/"))a=`/${a}`;if(a==="/")return{routePath:"/",params:c};return{routePath:a,params:c}}function ut(e,t,o,a){let c=[];if(!be(e))return c;let d=ot(e,{withFileTypes:!0});for(let h of d){let f=ce(e,h.name);if(a.some((R)=>h.name.startsWith(R)||h.name===R))continue;if(h.isDirectory())c.push(...ut(f,t,o,a));else if(h.isFile()){if(o.some((y)=>h.name.endsWith(y))){let{routePath:y,params:b}=qr(f,t,o);c.push({filePath:f,routePath:y,params:b,isIndex:h.name.startsWith("index."),isDynamic:b.length>0})}}}c.sort((h,f)=>{if(h.isDynamic!==f.isDynamic)return h.isDynamic?1:-1;let R=h.routePath.split("/").length,y=f.routePath.split("/").length;if(R!==y)return y-R;return h.routePath.localeCompare(f.routePath)});let p=new Map;for(let h of c){let f=p.get(h.routePath);if(f)console.warn(`[bun-router] Warning: Duplicate route "${h.routePath}" found:
88
+ - ${f.filePath}
89
+ - ${h.filePath}
90
+ Using: ${f.filePath}`);else p.set(h.routePath,h)}return Array.from(p.values())}function Or(e,t){let o=qe(t,e),a=[N(process.cwd(),"dist/views",o.replace(/\.stx$/,".html")),N(process.cwd(),"views",o.replace(/\.stx$/,".html")),N("/var/task/views",o.replace(/\.stx$/,".html"))];for(let c of a)if(be(c))return c;return null}function $r(e){let t={};for(let o of String(e??"").split(";")){let a=o.indexOf("=");if(a<0)continue;try{t[o.slice(0,a).trim()]=decodeURIComponent(o.slice(a+1).trim())}catch{}}return t}async function Nr(e,t,o,a,c){let p=await import("@stacksjs/stx");if(!p.processDirectives||!p.extractVariables)throw Error("STX library not properly loaded. Install with: bun add @stacksjs/stx");let h=await Bun.file(e).text(),f=h.match(/<script\s+server\s*>([\s\S]*?)<\/script>/i),R=f?f[1]:"",y=f?h.replace(/<script\s+server\s*>[\s\S]*?<\/script>/i,""):h;y=y.replace(/<script\s+client\s*>/gi,"<script>");let b={status:200,headers:{}},w=o.headers??{},P=String(w.cookie??w.Cookie??""),M=String(o.url??""),E=M.includes("?")?M.slice(M.indexOf("?")):"",k={url:M,path:String(o.path??""),search:E,host:String(w.host??""),cookieHeader:P,cookies:$r(P),ip:"",locale:null,params:o.params??{},method:String(o.method??"GET"),request:c},A={__filename:e,__dirname:Sr(e),props:o,...o,__stxServeContext:k,setResponseStatus:(H)=>{if(Number.isInteger(H)&&H>=100&&H<=599)b.status=H},notFound:(H=404)=>{b.status=Number.isInteger(H)&&H>=400&&H<=599?H:404},setResponseHeader:(H,Ut)=>{if(H)b.headers[String(H)]=String(Ut)},definePageMeta:()=>{}};if(R)await p.extractVariables(R,A,e);let I=a?.componentsDir?N(a.componentsDir):ce(t,"components"),de=a?.layoutsDir?N(a.layoutsDir):ce(t,"layouts"),Nt=a?.partialsDir?N(a.partialsDir):ce(t,"partials"),_t={...p.defaultConfig,componentsDir:I,layoutsDir:de,partialsDir:Nt},Dt=await p.processDirectives(y,A,e,_t,new Set),he=Number(A.__stxResponseStatus),It=A.__stxResponseHeaders;return{html:Dt,status:Number.isInteger(he)&&he>=100&&he<=599?he:b.status,headers:{...b.headers,...It??{}}}}function _r(e,t,o,a){return async(c)=>{let d=new URL(c.url),p={params:c.params||{},query:Object.fromEntries(d.searchParams),url:c.url,path:d.pathname,method:c.method,headers:Object.fromEntries(c.headers.entries())};function h(f){if(a?.enabled!==!1&&a?.preserve?.length)return re(f,a);return f}try{let f=Or(e,t);if(f){let y=await Bun.file(f).text();return y=h(y),new Response(y,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}if(e.endsWith(".stx")){let y=await Nr(e,t,p,o,c),b=h(y.html);return new Response(b,{status:y.status,headers:{"Content-Type":"text/html; charset=utf-8",...y.headers}})}let R=await Bun.file(e).text();return R=h(R),new Response(R,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}catch(f){return console.error(`[bun-router] Error rendering ${e}:`,f),new Response("Internal Server Error",{status:500})}}}function lt(e){Object.defineProperties(e.prototype,{_viewsDir:{value:null,writable:!0,configurable:!0},_fileRoutingConfig:{value:null,writable:!0,configurable:!0},_fileBasedRoutes:{value:[],writable:!0,configurable:!0},_fileRoutesInitialized:{value:!1,writable:!0,configurable:!0},_initFileRoutes:{async value(){if(this._fileRoutesInitialized)return;if(!Object.prototype.hasOwnProperty.call(this,"_fileBasedRoutes"))this._fileBasedRoutes=[];let t=this._viewsDir||Hr();if(!t){this._fileRoutesInitialized=!0;return}let o=this._fileRoutingConfig||{};if(o.enabled===!1){this._fileRoutesInitialized=!0;return}let a=o.extensions||Ar,c=o.exclude||kr;if(!at(t,a,c)){this._fileRoutesInitialized=!0;return}let d=ut(t,t,a,c);if(this.config.verbose){console.log(`[bun-router] Auto-discovered ${d.length} file-based routes from ${t}:`);for(let h of d)console.log(` ${h.routePath} -> ${qe(t,h.filePath)}`)}this._viewsDir=t;let p=new Set;for(let h of this.routes)if(h.method==="GET")p.add(h.path);for(let h of d){if(p.has(h.routePath))continue;let f=_r(h.filePath,t,o,this.config.queryPreservation);this.get(h.routePath,f,"web"),this._fileBasedRoutes.push(h),p.add(h.routePath)}this._fileRoutesInitialized=!0},writable:!0,configurable:!0},views:{value(t){if(typeof t==="string")this._viewsDir=N(t),this._fileRoutingConfig={};else{if(t.viewsPath)this._viewsDir=N(t.viewsPath);this._fileRoutingConfig=t}return this},writable:!0,configurable:!0},disableFileRouting:{value(){return this._fileRoutingConfig={enabled:!1},this},writable:!0,configurable:!0},getFileRoutes:{value(){return this._fileBasedRoutes||[]},writable:!0,configurable:!0},fileRoutes:{async value(t,o){if(t)this._viewsDir=N(t);if(o)this._fileRoutingConfig={...this._fileRoutingConfig,...o};return this._fileRoutesInitialized=!1,await this._initFileRoutes(),this},writable:!0,configurable:!0},loadFileRoutes:{async value(t={}){return this.fileRoutes(t.viewsPath,t)},writable:!0,configurable:!0}})}class we{stream;headers;status;constructor(e,t={}){if(this.stream=e,this.status=t.status||200,this.headers=new Headers(t.headers),t.contentType)this.headers.set("Content-Type",t.contentType)}toResponse(){return new Response(this.stream,{status:this.status,headers:this.headers})}addHeader(e,t){return this.headers.set(e,t),this}setContentType(e){return this.headers.set("Content-Type",e),this}setStatus(e){return this.status=e,this}}class O{static direct(e,t={}){let{format:o="json",delimiter:a=`
91
+ `,contentType:c,headers:d={},status:p=200,enableCompression:h=!1}=t,f=new ReadableStream({async start(y){try{let b=new TextEncoder,w=!0;for await(let P of Array.isArray(e)?e:e){if(!w&&a)y.enqueue(b.encode(a));let M=O.formatData(P,o);y.enqueue(b.encode(M)),w=!1}y.close()}catch(b){y.error(b)}}}),R=new Headers(d);if(c)R.set("Content-Type",c);else R.set("Content-Type",O.getContentTypeForFormat(o));return new we(f,{headers:R,status:p})}static buffered(e,t={}){let{format:o="json",bufferSize:a=1024,flushInterval:c=100,contentType:d,headers:p={},status:h=200}=t,f=new ReadableStream({async start(y){try{let b=new TextEncoder,w=[],P=0,M=()=>{if(w.length>0){let k=w.join("");y.enqueue(b.encode(k)),w=[],P=0}},E=setInterval(M,c);try{for await(let k of Array.isArray(e)?e:e){let A=O.formatData(k,o);if(w.push(A),P+=A.length,P>=a)M()}M()}finally{clearInterval(E)}y.close()}catch(b){y.error(b)}}}),R=new Headers(p);if(d)R.set("Content-Type",d);else R.set("Content-Type",O.getContentTypeForFormat(o));return new we(f,{headers:R,status:h})}static json(e,t={}){return O.direct(e,{...t,format:"json",contentType:t.contentType||"application/json"})}static text(e,t={}){return O.direct(e,{...t,format:"text",contentType:t.contentType||"text/plain"})}static csv(e,t={}){let{csvHeaders:o,...a}=t,c=new ReadableStream({async start(d){try{let p=new TextEncoder,h=!0;if(o&&o.length>0)d.enqueue(p.encode(`${o.join(",")}
92
+ `));for await(let f of Array.isArray(e)?e:e){let R=O.objectToCsvRow(f,o);d.enqueue(p.encode(`${R}
93
+ `))}d.close()}catch(p){d.error(p)}}});return new we(c,{headers:a.headers,status:a.status,contentType:a.contentType||"text/csv"})}static formatData(e,t){switch(t){case"json":return JSON.stringify(e);case"text":return String(e);case"csv":return typeof e==="object"?O.objectToCsvRow(e):String(e);case"ndjson":return JSON.stringify(e);default:return JSON.stringify(e)}}static objectToCsvRow(e,t){return(t||Object.keys(e)).map((a)=>{let c=e[a],d=c===null||c===void 0?"":String(c);if(d.includes(",")||d.includes('"')||d.includes(`
94
+ `))return`"${d.replace(/"/g,'""')}"`;return d}).join(",")}static getContentTypeForFormat(e){switch(e){case"json":case"ndjson":return"application/json";case"text":return"text/plain";case"csv":return"text/csv";default:return"application/json"}}}class K{static async streamFile(e,t,o={}){let{contentType:a,enableRanges:c=!0,chunkSize:d=65536}=o;try{let p=Bun.file(e),h=p.size,f=c?t.headers.get("range"):null;if(f&&c)return K.handleRangeRequest(p,f,a);let R=new Headers({"Content-Length":h.toString(),"Accept-Ranges":c?"bytes":"none"});if(a)R.set("Content-Type",a);return new Response(p.stream(),{status:200,headers:R})}catch(p){return console.error("Error streaming file:",p),new Response("File not found",{status:404})}}static async handleRangeRequest(e,t,o){let a=K.parseRangeHeader(t,e.size);if(!a||a.length===0)return new Response("Invalid range",{status:416});let[c,d]=a[0],p=d-c+1,h=new Headers({"Content-Range":`bytes ${c}-${d}/${e.size}`,"Content-Length":p.toString(),"Accept-Ranges":"bytes"});if(o)h.set("Content-Type",o);let f=e.slice(c,d+1);return new Response(f.stream(),{status:206,headers:h})}static parseRangeHeader(e,t){let o=e.match(/^bytes=(.+)$/);if(!o)return null;let a=[],c=o[1].split(",");for(let d of c){let[p,h]=d.trim().split("-"),f,R;if(p==="")f=Math.max(0,t-Number.parseInt(h,10)),R=t-1;else if(h==="")f=Number.parseInt(p,10),R=t-1;else f=Number.parseInt(p,10),R=Number.parseInt(h,10);if(f<0||R>=t||f>R)return null;a.push([f,R])}return a}}function Pe(e,t){try{e.close()}catch{}}function ct(e){Object.defineProperties(e.prototype,{streamFile:{value(t,o,a){return K.streamFile(t,o,a)},writable:!0,configurable:!0},streamFileWithRanges:{async value(t,o){return K.streamFile(t,o,{enableRanges:!0})},writable:!0,configurable:!0},health:{value(){let o=this.config.apiPrefix?`${this.config.apiPrefix}/health`:"/health";return this.get(o,()=>new Response("OK",{headers:{"Content-Type":"text/plain"}})),this},writable:!0,configurable:!0},streamResponse:{value(t,o){let a=new Headers;if(o?.headers)for(let[c,d]of Object.entries(o.headers))a.set(c,d);return new Response(t(),{status:o?.status||200,headers:a})},writable:!0,configurable:!0},transformStream:{value(t,o){return(a)=>{if(!a.body)throw Error("Request body is required for stream transformation");let c=new TransformStream({async transform(p,h){try{let f=await t(p);if(typeof f==="string")h.enqueue(new TextEncoder().encode(f));else h.enqueue(f)}catch(f){h.error(f)}}}),d=new Headers;if(o?.headers)for(let[p,h]of Object.entries(o.headers))d.set(p,h);return new Response(a.body.pipeThrough(c),{status:o?.status||200,headers:d})}},writable:!0,configurable:!0},stream:{value(t,o=200,a={}){let c=new Headers(a),d=new ReadableStream({async start(p){let h=new TextEncoder;try{for await(let f of t())if(typeof f==="string")p.enqueue(h.encode(f));else p.enqueue(f);p.close()}catch(f){Pe(p,f)}}});return new Response(d,{status:o,headers:c})},writable:!0,configurable:!0},streamJson:{value(t,o=200,a={}){let c=new Headers({"Content-Type":"application/json",...a}),d=new ReadableStream({async start(p){let h=new TextEncoder;try{p.enqueue(h.encode("{"));let f=Object.keys(t);for(let R=0;R<f.length;R++){let y=f[R],b=t[y];p.enqueue(h.encode(`"${y}":[`));let w=!0;for await(let P of b){if(!w)p.enqueue(h.encode(","));p.enqueue(h.encode(JSON.stringify(P))),w=!1}if(p.enqueue(h.encode("]")),R<f.length-1)p.enqueue(h.encode(","))}p.enqueue(h.encode("}")),p.close()}catch(f){Pe(p,f)}}});return new Response(d,{status:o,headers:c})},writable:!0,configurable:!0},eventStream:{value(t,o={}){let a=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Cache-Control",...o}),c=new ReadableStream({async start(d){let p=new TextEncoder;try{for await(let h of t()){let f="";if(h.id)f+=`id: ${h.id}
95
+ `;if(h.event)f+=`event: ${h.event}
96
+ `;if(h.retry)f+=`retry: ${h.retry}
97
+ `;let R=typeof h.data==="string"?h.data:JSON.stringify(h.data);f+=`data: ${R}
98
+
99
+ `,d.enqueue(p.encode(f))}d.close()}catch(h){Pe(d,h)}}});return new Response(c,{status:200,headers:a})},writable:!0,configurable:!0},streamDownload:{value(t,o,a={}){let c=new Headers({"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="${o}"`,...a}),d=new ReadableStream({async start(p){let h=new TextEncoder;try{for await(let f of t())if(typeof f==="string")p.enqueue(h.encode(f));else p.enqueue(f);p.close()}catch(f){Pe(p,f)}}});return new Response(d,{status:200,headers:c})},writable:!0,configurable:!0},streamAsyncIterator:{value(t,o={}){return O.direct(t,o).toResponse()},writable:!0,configurable:!0}})}function dt(e){Object.defineProperties(e.prototype,{group:{value(t,o){let a=this.currentGroup,c={...a};if(t.prefix&&a?.prefix)c.prefix=u(a.prefix,t.prefix);else if(t.prefix)c.prefix=t.prefix;if(t.middleware)c.middleware=[...a?.middleware||[],...t.middleware];this.currentGroup=c;let d=o();if(d instanceof Promise)return d.then(()=>(this.currentGroup=a,this),(p)=>{throw this.currentGroup=a,p});return this.currentGroup=a,this},writable:!0,configurable:!0},name:{value(t,o){let a=this.currentGroup||{},c={...a};this.currentGroup=c;let d=this.routes.length;o();for(let p=d;p<this.routes.length;p++){let h=this.routes[p];if(h.name)h.name=`${t}.${h.name}`}return this.currentGroup=a,this},writable:!0,configurable:!0},controller:{value(t,o){let a=this.currentGroup||{},c={...a,controller:t};return this.currentGroup=c,o(),this.currentGroup=a,this},writable:!0,configurable:!0},domain:{value(t,o){let a=this.currentDomain;return this.currentDomain=t,o(),this.currentDomain=a,this},writable:!0,configurable:!0},prefix:{value(t,o){return this.group({prefix:t},o)},writable:!0,configurable:!0},resource:{value(t,o,a="api"){let c=t.endsWith("s")?t:`${t}s`,d=t.endsWith("s")?t.slice(0,-1):t,p=[{name:"index",method:"GET",path:`/${c}`,action:"index"},{name:"create",method:"GET",path:`/${c}/create`,action:"create"},{name:"store",method:"POST",path:`/${c}`,action:"store"},{name:"show",method:"GET",path:`/${c}/{id}`,action:"show"},{name:"edit",method:"GET",path:`/${c}/{id}/edit`,action:"edit"},{name:"update",method:"PUT",path:`/${c}/{id}`,action:"update"},{name:"destroy",method:"DELETE",path:`/${c}/{id}`,action:"destroy"}];return this.name(d,()=>{for(let h of p){let f;if(typeof o==="string")f=`${o}${h.action.charAt(0).toUpperCase()+h.action.slice(1)}Action`;else if(o[h.action])f=o[h.action];else continue;switch(h.method){case"GET":this.get(h.path,f,a,h.name);break;case"POST":this.post(h.path,f,a,h.name);break;case"PUT":this.put(h.path,f,a,h.name);break;case"DELETE":this.delete(h.path,f,a,h.name);break}}}),this},writable:!0,configurable:!0}})}function ht(e){Object.defineProperties(e.prototype,{addRoute:{value(t,o,a,c,d,p){let h=o,f=[],R=c||"web";if(this.currentGroup){if(this.currentGroup.prefix)h=u(this.currentGroup.prefix,o);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)f=[...this.currentGroup.middleware]}if(p&&p.length>0)for(let E of p){let k=this.resolveMiddleware(E);if(k)f.push(k)}if(R==="api"&&this.config.apiPrefix)h=u(this.config.apiPrefix,h);else if(R==="web"&&this.config.webPrefix)h=u(this.config.webPrefix,h);let y;if(this.currentDomain)y=this.currentDomain;let b={method:t.toUpperCase(),path:h,handler:a,domain:y,params:{},middleware:f},w=ne(h),P={};if(w.forEach((E)=>{let k=E.replace("?","");if(this.patterns.has(k))P[k]=this.patterns.get(k)}),Object.keys(P).length>0)b.constraints=P;b.pattern={exec:(E)=>{let k={},A=b.constraints&&!Array.isArray(b.constraints)?b.constraints:void 0;if(!l(h,E.pathname,k,A))return null;return{pathname:{groups:k}}}};let M=y?this.domains[y]?.some((E)=>E.method===b.method&&E.path===h)===!0:this.routes.some((E)=>E.method===b.method&&E.path===h);if(a instanceof Response&&!y&&!M){let E=this.staticResponses.get(h)??new Map;if(!E.has(b.method))E.set(b.method,a),this.staticResponses.set(h,E)}if(y){if(this._hasDomainRoutes=!0,!this.domains[y])this.domains[y]=[];this.domains[y].push(b)}else this.routes.push(b);if(!h.includes("{")&&!h.includes("*")){if(!this.staticRoutes.has(t.toUpperCase()))this.staticRoutes.set(t.toUpperCase(),new Map);let E=this.staticRoutes.get(t.toUpperCase());if(!E.has(h))E.set(h,b)}if(d)b.name=d,this.namedRoutes.set(d,b),g(d,b.path);if(this.addRouteToCompiler&&!y)this.addRouteToCompiler(b);return this.routeCache.clear(),this._allowedMethodsCache?.clear(),this},writable:!0,configurable:!0},get:{value(t,o,a,c,d){return this.addRoute("GET",t,o,a,c,d)},writable:!0,configurable:!0},post:{value(t,o,a,c,d){return this.addRoute("POST",t,o,a,c,d)},writable:!0,configurable:!0},put:{value(t,o,a,c,d){return this.addRoute("PUT",t,o,a,c,d)},writable:!0,configurable:!0},patch:{value(t,o,a,c,d){return this.addRoute("PATCH",t,o,a,c,d)},writable:!0,configurable:!0},delete:{value(t,o,a,c,d){return this.addRoute("DELETE",t,o,a,c,d)},writable:!0,configurable:!0},options:{value(t,o,a,c,d){return this.addRoute("OPTIONS",t,o,a,c,d)},writable:!0,configurable:!0},head:{value(t,o,a,c,d){return this.addRoute("HEAD",t,o,a,c,d)},writable:!0,configurable:!0},match:{value(t,o,a,c,d,p){for(let h of t)this.addRoute(h,o,a,c,d,p);return this},writable:!0,configurable:!0},any:{value(t,o,a,c,d){let p=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];return this.match(p,t,o,a,c,d)},writable:!0,configurable:!0},fallback:{value(t){return this.fallbackHandler=t,this},writable:!0,configurable:!0},route:{value(t,o={}){let a=this.namedRoutes.get(t);if(!a)throw Error(`Route with name "${t}" not found`);let c=a.path;for(let[d,p]of Object.entries(o))c=c.replace(`{${d}}`,encodeURIComponent(p)),c=c.replace(`{${d}?}`,encodeURIComponent(p));if(c.includes("{")){if(c=c.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),c.length>1&&c.endsWith("/"))c=c.slice(0,-1)}return c},writable:!0,configurable:!0},onError:{value(t){return this.errorHandler=t,this},writable:!0,configurable:!0}})}function pt(e){Object.defineProperties(e.prototype,{redirect:{value(t,o=302){let a=new Headers;return a.set("Location",t),new Response(null,{status:o,headers:a})},writable:!0,configurable:!0},permanentRedirect:{value(t){return this.redirect(t,301)},writable:!0,configurable:!0},redirectRoute:{value(t,o,a=302){return this.get(t,(c)=>this.redirect(o,a)),this},writable:!0,configurable:!0},permanentRedirectRoute:{value(t,o){return this.redirectRoute(t,o,301)},writable:!0,configurable:!0}})}function gt(e){Object.defineProperties(e.prototype,{use:{value(...t){for(let o of t){let a=this.resolveMiddleware(o);if(a)this.globalMiddleware.push(a)}return this._mwEpoch=(this._mwEpoch||0)+1,this},writable:!0,configurable:!0},resolveMiddleware:{value(t){if(typeof t==="function")return t;if(typeof t==="object"&&t!==null&&"handle"in t&&typeof t.handle==="function")return(o,a)=>t.handle(o,a);if(typeof t==="string"){let[o,a]=t.split(":"),c=this.namedMiddleware?.get(o);if(c)return c(a);let d=null,p=t;return async(h,f)=>{if(!d)try{let R=await import(`../middleware/${p}.ts`);if(R.default&&typeof R.default==="function")d=R.default;else if(R.default&&typeof R.default.handle==="function")d=(y,b)=>R.default.handle(y,b)}catch(R){console.error(`Failed to load middleware "${p}":`,R)}if(d)return d(h,f);return f()}}return null},writable:!0,configurable:!0},buildMiddlewareChain:{value:le,writable:!0,configurable:!0},runMiddleware:{async value(t,o){if(o.length===0)return null;try{return await V(this,o)(t)}catch(a){if(this.errorHandler)return this.errorHandler(a);throw a}},writable:!0,configurable:!0},middleware:{value(...t){for(let o of t)if(typeof o==="string"){let[a]=o.split(":");if(!this.namedMiddleware.has(a))throw Error(`Unknown middleware: ${a}`)}if(this.currentGroup){if(!this.currentGroup.middleware)this.currentGroup.middleware=[];this.currentGroup.middleware.push(...t)}else{let o=this.routes[this.routes.length-1];if(o)this.applyMiddlewareToRoute(o,t)}return this},writable:!0,configurable:!0},applyMiddlewareToRoute:{value(t,o){for(let a of o){let c=this.resolveMiddleware(a);if(c)t.middleware.push(c)}},writable:!0,configurable:!0},resolveHandler:{async value(t,o){return L(t,o,this.config)},writable:!0,configurable:!0},wrapResponse:{value:s,writable:!0,configurable:!0},onError:{value(t){return this.errorHandler=t,this},writable:!0,configurable:!0}})}class mt{models=new Map;cache=new Map;register(e,t){this.models.set(e,t)}get(e){return this.models.get(e)}has(e){return this.models.has(e)}async resolve(e,t,o){let a=this.models.get(e);if(!a)return{model:null,error:`Model binding '${e}' not found`,status:500};try{if(a.cache?.enabled){let p=this.getCachedModel(e,t,a);if(p)return{model:p}}let c=await a.resolver(t,o);if(c===null||c===void 0)return{model:null,error:`${e} not found`,status:404};if(a.validator){let p=await a.validator(c,t,o);if(!p.valid)return{model:null,error:p.error||"Model validation failed",status:p.status||422}}let d=c;if(a.transformer)d=await a.transformer(c,t,o);if(a.cache?.enabled)this.cacheModel(e,t,d,a);return{model:d}}catch(c){return{model:null,error:c instanceof Error?c.message:"Model resolution failed",status:500}}}createErrorResponse(e,t,o){let a=this.models.get(e),c=t.status||404,d=t.error||"Model not found";if(a?.errorHandling){if(c===404&&a.errorHandling.notFound)return a.errorHandling.notFound(o);if(c===422&&a.errorHandling.validation)return a.errorHandling.validation(null,d);if(a.errorHandling.transform)return a.errorHandling.transform(d)}return new Response(JSON.stringify({error:d,status:c,message:`Failed to resolve ${e}`}),{status:c,headers:{"Content-Type":"application/json"}})}clearCache(e,t){if(t){let o=this.models.get(e);if(o?.cache){let a=this.generateCacheKey(e,t,o);this.cache.delete(a)}}else{let o=[];for(let a of this.cache.keys())if(a.startsWith(`${e}:`))o.push(a);for(let a of o)this.cache.delete(a)}}clearAllCache(){this.cache.clear()}getCacheStats(){let e=Date.now(),t=0,o=0;for(let a of this.cache.values())if(e-a.timestamp>a.ttl)o++;else t++;return{totalEntries:this.cache.size,validEntries:t,expiredEntries:o,models:this.models.size}}cleanupCache(){let e=Date.now(),t=[];for(let[o,a]of this.cache.entries())if(e-a.timestamp>a.ttl)t.push(o);for(let o of t)this.cache.delete(o);return t.length}getCachedModel(e,t,o){if(!o.cache?.enabled)return null;let a=this.generateCacheKey(e,t,o),c=this.cache.get(a);if(!c)return null;if(Date.now()-c.timestamp>c.ttl)return this.cache.delete(a),null;return c.model}cacheModel(e,t,o,a){if(!a.cache?.enabled)return;let c=this.generateCacheKey(e,t,a);this.cache.set(c,{model:o,timestamp:Date.now(),ttl:a.cache.ttl})}generateCacheKey(e,t,o){if(o.cache?.key)return`${e}:${o.cache.key(t)}`;let a=Object.entries(t).sort(([c],[d])=>c.localeCompare(d)).map(([c,d])=>`${c}=${d}`).join("&");return`${e}:${a}`}}var ft=new mt;function Rt(e){Object.defineProperties(e.prototype,{modelRegistry:{value:ft,writable:!0,configurable:!0},model:{value(t,o,a){if(typeof o==="string")this.modelRegistry.register(t,{resolver:async(c)=>(console.warn(`Model class ${o} not implemented`),{id:c[t],modelClass:o}),errorHandling:a?{notFound:(c)=>a(null)||new Response("Not Found",{status:404})}:void 0});else this.modelRegistry.register(t,{resolver:async(c)=>{let d=c[t];if(!d)return null;return o(d)},errorHandling:a?{notFound:(c)=>a(null)||new Response("Not Found",{status:404})}:void 0});return this},writable:!0,configurable:!0},implicitBinding:{value(){return async(t,o)=>{if(!t.params)return await o()||new Response("Not Found",{status:404});for(let[c,d]of Object.entries(t.params))if(this.modelRegistry.has(c))try{let p=await this.modelRegistry.resolve(c,t.params,t);if(p.model===null){if(p.status===500)return new Response(JSON.stringify({error:"Internal Server Error",message:p.error||"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}});else if(p.status===404)return this.modelRegistry.createErrorResponse(c,p,t.params)}else t[c]=p.model}catch(p){return new Response(JSON.stringify({error:"Internal Server Error",message:p instanceof Error?p.message:"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}})}return await o()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},missing:{value(t){return async(o,a)=>{try{return await a()||t(o)}catch(c){return console.error(c),t(o)}}},writable:!0,configurable:!0},scopedBindings:{value(t){return async(o,a)=>{if(!o.params)return await a()||new Response("Not Found",{status:404});for(let[d,p]of Object.entries(t))if(o.params[d]&&o.params[p]);return await a()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},clearModelCache:{value(t){if(t)this.modelRegistry.clearCache(t);else this.modelRegistry.clearAllCache();return this},writable:!0,configurable:!0},getModelStats:{value(){return this.modelRegistry.getCacheStats()},writable:!0,configurable:!0}})}class D{children=new Map;paramChild=null;wildcardChild=null;routes=new Map;paramName=null;pattern=null;isEndpoint=!1;addRoute(e,t){this.routes.set(e,t),this.isEndpoint=!0}getRoute(e){return this.routes.get(e)}getAllRoutes(){return Array.from(this.routes.values())}}class Oe{root=new D;compiledRoutes=new Map;methodTries=new Map;constructor(){let e=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","TRACE","CONNECT"];for(let t of e)this.methodTries.set(t,new D)}compileRoute(e){let t=`${e.method}:${e.path}`;if(e.constraints&&!Array.isArray(e.constraints)){let f=e.constraints,y=Object.keys(f).sort().map((b)=>`${b}:${f[b]}`).join("|");t=`${e.method}:${e.path}#${y}`}if(this.compiledRoutes.has(t))return this.compiledRoutes.get(t);let o=this.parsePathSegments(e.path),a=o.filter((f)=>f.type==="parameter").map((f)=>f.paramName);if(e.constraints&&!Array.isArray(e.constraints)){let f=e.constraints;for(let R of o)if(R.type==="parameter"&&R.paramName&&f[R.paramName])R.pattern=new RegExp(`^${f[R.paramName]}$`)}let c=this.calculateRoutePriority(o),d=o.filter((f)=>f.type==="static").length,p=o.filter((f)=>f.type!=="static").length,h={route:e,segments:o,paramNames:a,priority:c,staticScore:d,dynamicScore:p};return this.compiledRoutes.set(t,h),h}parsePathSegments(e){let t=[],o=e.split("/").filter((a)=>a.length>0);for(let a of o)if(a==="*")t.push({type:"wildcard",value:"*"});else if(/^\{[^{}/]+\}\*$/.test(a))t.push({type:"wildcard",value:a,paramName:a.slice(1,a.indexOf("}"))});else if(a.startsWith("{")&&a.endsWith("}")){let c=a.slice(1,-1),[d,p]=c.split(":");t.push({type:"parameter",value:a,paramName:d.replace("?",""),pattern:p?new RegExp(`^${p}$`):void 0,optional:c.endsWith("?")})}else if(a.includes("{")){let c=a.replace(/\{([^}:]+)(?::([^}]+))?\}/g,(p,h,f)=>f?`(${f})`:"([^/]+)"),d=Array.from(a.matchAll(/\{([^}:]+)(?::([^}]+))?\}/g)).map((p)=>p[1].replace("?",""));t.push({type:"parameter",value:a,paramName:d[0],pattern:new RegExp(`^${c}$`)})}else t.push({type:"static",value:a});return t}calculateRoutePriority(e){let t=0;for(let o=0;o<e.length;o++){let a=e[o],c=e.length-o;switch(a.type){case"static":t+=c*1000;break;case"parameter":if(a.pattern)t+=c*100;else t+=c*10;break;case"wildcard":t+=c*1;break}}return t}addRoute(e){let t=this.compileRoute(e);this.insertRoute(this.root,t,0);let o=this.methodTries.get(e.method);if(o)this.insertRoute(o,t,0)}insertRoute(e,t,o){if(o>=t.segments.length){e.addRoute(t.route.method,t);return}let a=t.segments[o];switch(a.type){case"static":if(!e.children.has(a.value))e.children.set(a.value,new D);this.insertRoute(e.children.get(a.value),t,o+1);break;case"parameter":if(!e.paramChild)e.paramChild=new D,e.paramChild.paramName=a.paramName,e.paramChild.pattern=a.pattern||null;this.insertRoute(e.paramChild,t,o+1);break;case"wildcard":if(!e.wildcardChild)e.wildcardChild=new D,e.wildcardChild.paramName=a.paramName??null;this.insertRoute(e.wildcardChild,t,o+1);break}}match(e,t){let o=e.split("/").filter((c)=>c.length>0),a=this.methodTries.get(t);if(a){let c=this.matchSegments(a,o,0,{},t);if(c)return c}return this.matchSegments(this.root,o,0,{},t)}matchSegments(e,t,o,a,c){if(o>=t.length){let R=e.getRoute(c);if(R)return{route:R.route,params:a,score:R.priority};return null}let d=t[o],p=e.children.get(d);if(p){let R=this.matchSegments(p,t,o+1,a,c);if(R)return R}let h=e.paramChild,f=h?.paramName?v(d):d;if(h&&h.paramName&&(!h.pattern||h.pattern.test(f))){let R=a[h.paramName];a[h.paramName]=f;let y=this.matchSegments(h,t,o+1,a,c);if(y)return y;if(R===void 0)delete a[h.paramName];else a[h.paramName]=R}if(e.wildcardChild){let R=e.wildcardChild.getRoute(c);if(R)return a[e.wildcardChild.paramName??"wildcard"]=t.slice(o).map(v).join("/"),{route:R.route,params:a,score:R.priority}}return null}getAllRoutes(){return Array.from(this.compiledRoutes.values())}removeRoute(e){let t=`${e.method}:${e.path}`;if(e.constraints&&!Array.isArray(e.constraints)){let o=e.constraints,c=Object.keys(o).sort().map((d)=>`${d}:${o[d]}`).join("|");t=`${e.method}:${e.path}#${c}`}this.compiledRoutes.delete(t)}clear(){this.root=new D,this.compiledRoutes.clear();for(let[e]of this.methodTries)this.methodTries.set(e,new D)}getStats(){let e={totalRoutes:this.compiledRoutes.size,totalNodes:this.countNodes(this.root),averageDepth:0,methodDistribution:{}};for(let t of this.compiledRoutes.values()){let o=t.route.method;e.methodDistribution[o]=(e.methodDistribution[o]||0)+1}return e}countNodes(e){let t=1;for(let o of e.children.values())t+=this.countNodes(o);if(e.paramChild)t+=this.countNodes(e.paramChild);if(e.wildcardChild)t+=this.countNodes(e.wildcardChild);return t}}class Se{trie;matchCache=new Map;routeKeys=new Set;stats={totalMatches:0,cacheHits:0,cacheMisses:0,averageMatchTime:0,trieDepth:0,methodDistribution:{}};options;constructor(e={}){this.options={enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0,enableProfiling:!1,...e},this.trie=new Oe}addRoute(e){if(this.options.precompilePatterns)this.precompileRoutePattern(e);let t=`${e.method}:${e.path}`;if(this.routeKeys.has(t))return!1;if(this.routeKeys.add(t),this.trie.addRoute(e),this.options.enableCaching)this.matchCache.clear();let o=e.method;return this.stats.methodDistribution[o]=(this.stats.methodDistribution[o]||0)+1,!0}patternCache=new Map;extractParamNames(e){let t=[],o=/\{([^}:]+)(?::[^}]+)?\}/g,a;while(a=o.exec(e))t.push(a[1].replace("?",""));return t}precompileRoutePattern(e){if(!e.pattern&&e.path.includes("{")){let t=e.path;if(e.constraints&&!Array.isArray(e.constraints)){let c=e.constraints,p=Object.keys(c).sort().map((h)=>`${h}:${c[h]}`).join("|");t=`${e.path}#${p}`}if(this.patternCache.has(t)){e.pattern=this.patternCache.get(t);return}let o=this.convertToURLPattern(e.path,e.constraints&&!Array.isArray(e.constraints)?e.constraints:void 0),a={exec:(c)=>{let d=c.pathname,p=o.exec(d);if(!p)return null;return{pathname:{groups:p.groups||{}}}}};this.patternCache.set(t,a),e.pattern=a}}convertToURLPattern(e,t){let o=e,a=null,c=o.match(/\{([^{}/]+)\}\*$/);if(c)a=c[1],o=o.slice(0,c.index);else if(o.endsWith("*"))a="wildcard",o=o.slice(0,-1);let d=[],h=o.replace(/\{([^}]+)\}/g,(R,y)=>(d.push(y),`\x00${d.length-1}\x00`)).replace(/[.+*?^${}()|[\]\\]/g,"\\$&");if(h=h.replace(/\/?\u0000(\d+)\u0000/g,(R,y)=>{let b=d[Number(y)],w=b.endsWith("?"),P=w?b.slice(0,-1):b,M=P.indexOf(":"),E=M===-1?P:P.slice(0,M),k=M===-1?void 0:P.slice(M+1),A=t?.[E]??k??"[^/]+",I=`(?<${E}>${A})`,de=R.startsWith("/")?"/":"";return w?`(?:${de}${I})?`:`${de}${I}`}),a!==null)h+=`(?<${a}>${t?.[a]??".+"})`;let f=new RegExp(`^${h}$`);return{exec:(R)=>{let y=R.match(f);if(!y)return null;return{groups:y.groups||{}}}}}match(e,t){let o=this.options.enableProfiling?performance.now():0;this.stats.totalMatches++;let a;if(this.options.enableCaching){a=`${t}:${e}`;let p=this.matchCache.get(a);if(p!==void 0){if(this.stats.cacheHits++,o)this.updateMatchTime(o);return p?{route:p.route,params:{...p.params}}:null}this.stats.cacheMisses++}let c=this.trie.match(e,t),d=null;if(c)d={route:c.route,params:c.params};if(a!==void 0)this.addToCache(a,d);if(o)this.updateMatchTime(o);return d?{route:d.route,params:{...d.params}}:null}addToCache(e,t){if(this.matchCache.size>=this.options.cacheSize){let o=this.matchCache.keys().next().value;if(o!==void 0)this.matchCache.delete(o)}this.matchCache.set(e,t)}updateMatchTime(e){let t=performance.now()-e;this.stats.averageMatchTime=(this.stats.averageMatchTime*(this.stats.totalMatches-1)+t)/this.stats.totalMatches}getCompiledRoutes(){let e=this.trie.getAllRoutes();if(this.options.enablePriorityOptimization)return e.sort((t,o)=>o.priority-t.priority);return e}getRoutesByMethod(){let e=new Map;for(let t of this.trie.getAllRoutes()){let o=t.route.method;if(!e.has(o))e.set(o,[]);e.get(o).push(t)}if(this.options.enablePriorityOptimization)for(let[t,o]of e)o.sort((a,c)=>c.priority-a.priority),e.set(t,o);return e}warmCache(e,t={}){if(!this.options.enableCaching&&!t.force)return{warmedPaths:0,cacheSize:0,hitRate:0};let o=this.options.enableCaching;if(t.force&&!this.options.enableCaching)this.options.enableCaching=!0;if(t.precompile)for(let{path:y,method:b}of e){let w=`${b}:${y}`;this.matchCache.delete(w)}let a=this.matchCache.size,c=this.stats.cacheHits,d=this.stats.totalMatches;for(let{path:y,method:b}of e)if(this.match(y,b),t.precompile)this.match(y,b);let p=this.matchCache.size-a,h=this.stats.cacheHits-c,f=this.stats.totalMatches-d,R=f>0?h/f:0;if(t.force&&!o)this.options.enableCaching=o;return{warmedPaths:p,cacheSize:this.matchCache.size,hitRate:R}}clear(){this.trie.clear(),this.matchCache.clear(),this.routeKeys.clear(),this.stats={totalMatches:0,cacheHits:0,cacheMisses:0,averageMatchTime:0,trieDepth:0,methodDistribution:{}}}getStats(){let e=this.trie.getStats();return{...this.stats,trieDepth:e.averageDepth,methodDistribution:e.methodDistribution}}getCacheStats(){let e=this.stats.totalMatches>0?this.stats.cacheHits/this.stats.totalMatches:0;return{size:this.matchCache.size,maxSize:this.options.cacheSize,hitRate:e,enabled:this.options.enableCaching}}optimizeRouteOrder(e){if(!this.options.enablePriorityOptimization)return;this.matchCache.clear()}getRouteConflicts(){let e=[],t=this.trie.getAllRoutes(),o=new Map;for(let a of t){let c=a.route.method;if(!o.has(c))o.set(c,[]);o.get(c).push(a)}for(let[a,c]of o)for(let d=0;d<c.length;d++)for(let p=d+1;p<c.length;p++){let h=c[d],f=c[p];if(this.routesConflict(h,f)){let R=this.getConflictSeverity(h,f),y=this.getConflictType(h,f);e.push({routes:[h,f],conflictType:y,severity:R})}}return e}routesConflict(e,t){if(e.route.path===t.route.path)return!0;if(e.route.method!==t.route.method)return!1;return this.patternsOverlap(e.segments,t.segments)}patternsOverlap(e,t){let o=e.some((p)=>p.optional||p.type==="wildcard"),a=t.some((p)=>p.optional||p.type==="wildcard");if(e.length!==t.length&&!o&&!a)return!1;let c=Math.max(e.length,t.length),d=!0;for(let p=0;p<c;p++){let h=p<e.length?e[p]:null,f=p<t.length?t[p]:null;if(!h&&f&&!f.optional)return!1;if(!f&&h&&!h.optional)return!1;if(!h||!f)continue;if(h.type==="static"&&f.type==="static"){if(h.value!==f.value)return!1}else if(h.type==="parameter"&&f.type==="parameter"){if(h.pattern&&f.pattern){if(h.pattern.toString()===f.pattern.toString())d=!0}if(h.paramName===f.paramName)d=!0}else if(h.type==="static"&&f.type==="parameter"||h.type==="parameter"&&f.type==="static"){let R=h.type==="static"?h:f,y=h.type==="parameter"?h:f;if(y.pattern){if(!y.pattern.test(R.value))return!1}}else if(h.type==="wildcard"||f.type==="wildcard")return!0}return d}getConflictSeverity(e,t){if(e.route.path===t.route.path)return"high";if(e.staticScore===t.staticScore)return"medium";return"low"}getConflictType(e,t){if(e.route.path===t.route.path)return"duplicate";if(this.hasAmbiguousParameters(e,t))return"ambiguous";if(Math.abs(e.priority-t.priority)<10)return"ambiguous";return"overlap"}hasAmbiguousParameters(e,t){if(Math.abs(e.segments.length-t.segments.length)>1)return!1;let o=e.segments.filter((c)=>c.type==="parameter").length,a=t.segments.filter((c)=>c.type==="parameter").length;if(o>0&&a>0){let c=Math.min(e.segments.length,t.segments.length),d=0;for(let p=0;p<c;p++)if(e.segments[p].type==="parameter"&&t.segments[p].type==="parameter"){d++;let h=!!e.segments[p].pattern,f=!!t.segments[p].pattern;if(h!==f)return!0}return d>0&&d>=Math.min(o,a)/2}return!1}}function yt(e){Object.defineProperties(e.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new Se({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0})},writable:!0,configurable:!0},addRouteToCompiler:{value(t){this.initializeRouteCompiler(),this.routeCompiler.addRoute(t)},writable:!0,configurable:!0},matchRoute:{value(t,o,a,c=!1){if(this.initializeRouteCompiler(),a&&this.domains[a]){let d=this.fallbackMatchRoute(t,o,a,c);if(d)return d}else{let d=this.routeCompiler.match(t,o);if(d&&(!a||!d.route.domain||d.route.domain===a))return d;let p=this.fallbackMatchRoute(t,o,a,c);if(p)return p}if(o==="HEAD")return this.matchRoute(t,"GET",a,c);return},writable:!0,configurable:!0},fallbackMatchRoute:{value(t,o,a,c=!1){let d,p=t;if(!c)d=new URL(t,"http://localhost"),p=d.pathname;let h=`${a||""}:${o}:${p}`;if(this.routeCache.has(h))return this.routeCache.get(h);if(this.routeCache.size>=1e4)this.routeCache.clear();if(this.staticRoutes.has(o)){let b=this.staticRoutes.get(o).get(p);if(b&&(!a||!b.domain||b.domain===a)){let w={route:b,params:{}};return this.routeCache.set(h,w),w}}let R=(a&&this.domains[a]?this.domains[a]:this.routes).filter((b)=>b.method===o);for(let b of R)if(b.path===p){let w={route:b,params:{}};return this.routeCache.set(h,w),w}for(let b of R)if(b.pattern){let w=b.pattern.exec(d??=new URL(p,"http://localhost"));if(w){let P={route:b,params:w.pathname.groups};return this.routeCache.set(h,P),P}}let y=a&&this.domains[a]?[this.domains[a],this.routes]:[this.routes];for(let b of y)for(let w of b){if(w.method!==o||!w.path.endsWith("*"))continue;let P=w.path.slice(0,-1);if(p.startsWith(P)){let M={route:w,params:{wildcard:p.slice(P.length)}};return this.routeCache.set(h,M),M}}this.routeCache.set(h,void 0);return},writable:!0,configurable:!0},getRouteStats:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getStats()},writable:!0,configurable:!0},getCacheStats:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getCacheStats()},writable:!0,configurable:!0},warmRouteCache:{value(t){this.initializeRouteCompiler(),this.routeCompiler.warmCache(t)},writable:!0,configurable:!0},getRoutesByMethod:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getRoutesByMethod()},writable:!0,configurable:!0},getRouteConflicts:{value(){return this.initializeRouteCompiler(),this.routeCompiler.getRouteConflicts()},writable:!0,configurable:!0},clearRouteCache:{value(){if(this.routeCompiler)this.routeCompiler.clear();this.routeCache.clear()},writable:!0,configurable:!0},rebuildRouteCompiler:{value(){this.routeCompiler=new Se({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0});for(let t of this.routes)this.routeCompiler.addRoute(t);for(let t of Object.values(this.domains))for(let o of t)this.routeCompiler.addRoute(o)},writable:!0,configurable:!0},optimizeRoutes:{value(t={}){this.initializeRouteCompiler(),this.routeCompiler.optimizeRouteOrder(t)},writable:!0,configurable:!0}})}function bt(e){Object.defineProperties(e.prototype,{buildBunServeRoutes:{value(){let t={},o=new Map;for(let a of this.routes){if(!o.has(a.path))o.set(a.path,[]);o.get(a.path).push(a)}for(let[a,c]of o.entries())if(c.length===1){let d=c[0];if(typeof d.handler==="function"&&d.handler.toString().includes("new Response")&&!d.handler.toString().includes("await")&&d.middleware.length===0)try{let p=this.enhanceRequest(new Request("https://example.com"),{}),h=d.handler(p);if(h instanceof Response){t[a]=h;continue}}catch{}t[a]=async(p)=>{let h=new URL(p.url),f={},R=d.constraints&&!Array.isArray(d.constraints)?d.constraints:void 0;l(a,h.pathname,f,R);let y=this.enhanceRequest(p,f),b=async(M,E)=>await this.resolveHandler(d.handler,M),w=[...this.globalMiddleware,...d.middleware,b],P=await this.runMiddleware(y,w);return this.applyModifiedCookies(P??new Response("No response from middleware chain",{status:500}),y)}}else{let d={};for(let p of c){let h=p.method;d[h]=async(f)=>{let R=new URL(f.url),y={},b=p.constraints&&!Array.isArray(p.constraints)?p.constraints:void 0;l(a,R.pathname,y,b);let w=this.enhanceRequest(f,y),P=async(k,A)=>await this.resolveHandler(p.handler,k),M=[...this.globalMiddleware,...p.middleware,P],E=await this.runMiddleware(w,M);return this.applyModifiedCookies(E??new Response("No response from middleware chain",{status:500}),w)}}t[a]=d}return t},writable:!0,configurable:!0},loadRoutes:{async value(){if(!this.config.routesPath)return;try{if(this.config.apiRoutesPath)try{let t=await import(this.config.apiRoutesPath);if(t.default&&Array.isArray(t.default))for(let o of t.default)this.registerRoute(o,"api")}catch(t){if(this.config.verbose)console.warn(`Failed to load API routes: ${t}`)}if(this.config.webRoutesPath)try{let t=await import(this.config.webRoutesPath);if(t.default&&Array.isArray(t.default))for(let o of t.default)this.registerRoute(o,"web")}catch(t){if(this.config.verbose)console.warn(`Failed to load Web routes: ${t}`)}}catch(t){console.error("Error loading routes:",t)}},writable:!0,configurable:!0},registerRoute:{value(t,o){let{path:a,method:c,handler:d,middleware:p=[],name:h}=t;switch(c){case"GET":this.get(a,d,o,h,p);break;case"POST":this.post(a,d,o,h,p);break;case"PUT":this.put(a,d,o,h,p);break;case"DELETE":this.delete(a,d,o,h,p);break;case"PATCH":this.patch(a,d,o,h,p);break;case"OPTIONS":this.options(a,d,o,h,p);break;default:console.warn(`Unsupported HTTP method: ${c}`)}},writable:!0,configurable:!0}})}function wt(e){Object.defineProperties(e.prototype,{matchRoute:{value(t,o,a){let c=new URL(t,"http://localhost"),d=`${a||""}:${o}:${c.pathname}`;if(this.routeCache.has(d))return this.routeCache.get(d);if(this.staticRoutes.has(o)){let R=this.staticRoutes.get(o).get(c.pathname);if(R&&(!a||!R.domain||R.domain===a)){let y={route:R,params:{}};return this.routeCache.set(d,y),y}}let p=a&&this.domains[a]?this.domains[a]:this.routes,h=p.filter((R)=>R.method===o);for(let R of h)if(R.path===c.pathname){let y={route:R,params:{}};return this.routeCache.set(d,y),y}for(let R of h)if(R.pattern){let y=R.pattern.exec(c);if(y){let b={route:R,params:y.pathname.groups};return this.routeCache.set(d,b),b}}if(a&&this.domains[a]){let R=this.domains[a].filter((y)=>y.method===o&&y.path.endsWith("*"));for(let y of R){let b=y.path.slice(0,-1);if(c.pathname.startsWith(b)){let w={route:y,params:{wildcard:c.pathname.slice(b.length)}};return this.routeCache.set(d,w),w}}}let f=this.routes.filter((R)=>R.method===o&&R.path.endsWith("*")&&(!a||!R.domain));for(let R of f){let y=R.path.slice(0,-1);if(c.pathname.startsWith(y)){let b={route:R,params:{wildcard:c.pathname.slice(y.length)}};return this.routeCache.set(d,b),b}}if(o==="HEAD")return this.matchRoute(t,"GET",a);if(o==="OPTIONS"){let R=p.find((y)=>y.method==="OPTIONS"&&y.path==="*");if(R){let y={route:R,params:{}};return this.routeCache.set(d,y),y}for(let y of["GET","POST","PUT","PATCH","DELETE"]){let b=this.matchRoute(t,y,a);if(b){let w={route:{...b.route,method:"OPTIONS",handler:(P)=>new Response(null,{status:204})},params:b.params};return this.routeCache.set(d,w),w}}}return},writable:!0,configurable:!0},matchDomain:{value(t,o){if(t===o)return!0;if(t.startsWith("*.")){let a=t.substring(2);return o===a||o.endsWith(`.${a}`)}if(t.includes("{")){let a;if(!this.domainPatternCache.has(t)){let c=t.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)");a=new RegExp(`^${c}$`),this.domainPatternCache.set(t,a)}else a=this.domainPatternCache.get(t);return a.test(o)}return!1},writable:!0,configurable:!0},extractDomainParams:{value(t,o){let a={};if(!t.includes("{"))return a;let c=t.match(/\{([^}]+)\}/g)?.map((h)=>h.substring(1,h.length-1))||[],d=t.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)"),p=o.match(new RegExp(`^${d}$`));if(p&&p.length>1)for(let h=0;h<c.length;h++)a[c[h]]=p[h+1];return a},writable:!0,configurable:!0},pattern:{value(t,o){return this.patterns.set(t,o),this},writable:!0,configurable:!0},where:{value(t){let o=this.routes[this.routes.length-1];if(o){o.constraints={...o.constraints||{},...t};let a=o.path,c=o.constraints&&!Array.isArray(o.constraints)?o.constraints:void 0;if(o.pattern={exec:(d)=>{let p={};if(!l(a,d.pathname,p,c))return null;return{pathname:{groups:p}}}},this.routeCache.clear(),this.routeCompiler){let d=[...this.routes];this.routeCompiler.clear();for(let p of d)this.routeCompiler.addRoute(p)}}return this},writable:!0,configurable:!0},withoutNativeDispatch:{value(){let t=this.routes[this.routes.length-1];if(t)t.nativeDispatch=!1;return this},writable:!0,configurable:!0},whereNumber:{value(t){return this.where({[t]:"\\d+"})},writable:!0,configurable:!0},whereAlpha:{value(t){return this.where({[t]:"[A-Za-z]+"})},writable:!0,configurable:!0},whereAlphaNumeric:{value(t){return this.where({[t]:"[A-Za-z0-9]+"})},writable:!0,configurable:!0},whereUuid:{value(t){return this.where({[t]:"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"})},writable:!0,configurable:!0},whereIn:{value(t,o){return this.where({[t]:o.join("|")})},writable:!0,configurable:!0}})}function Dr(e){let t;if(e.startsWith("http://"))t=7;else if(e.startsWith("https://"))t=8;else{let d=e.indexOf("://");t=d===-1?0:d+3}let o=e.indexOf("/",t);if(o===-1)return"/";let a=e.indexOf("?",o);if(a!==-1)return e.slice(o,a);let c=e.indexOf("#",o);return c===-1?e.slice(o):e.slice(o,c)}async function Ir(e,t,o){let a;try{a=await t}catch(c){if(!e.errorHandler)throw c;a=await e.errorHandler(c)}return a?e.applyModifiedCookies(a,o):new Response("No response from middleware chain",{status:500})}function vt(e,t,o){console.error("Error handling request:",o);let a=e.errorHandler?e.errorHandler(o):new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:o instanceof Error?o.message:String(o)}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin"}});return a instanceof Promise?a.then((c)=>m(c,t,e.config.compression)):m(a,t,e.config.compression)}function At(e,t,o){let a=t?e._buildNativeRoutes()??{}:{};for(let[c,d]of e.staticResponses){if(o?.[c])continue;let p=a[c]??={};for(let[h,f]of d)p[h]=f}return Object.keys(a).length>0?a:null}function Ur(e,t){let{router:o,route:a,isWildcard:c}=e,d=t.params??{};if(c){let h=new URL(t.url).pathname,f=a.path==="*"?"/":a.path.slice(0,-1);d={...d,wildcard:h.slice(f.length)}}let p;try{p=o._dispatchMatchedRoute(a,t,d)}catch(h){return vt(o,t,h)}return p instanceof Promise?p.then((h)=>m(h,t,o.config.compression),(h)=>vt(o,t,h)):m(p,t,o.config.compression)}if(!i.hasMacro("getParam"))i.macro("getParam",function(e,t){let o=this.params?.[e];return o!==void 0?o:t});if(!i.hasMacro("getParamAsInt"))i.macro("getParamAsInt",function(e){let t=this.params?.[e];if(t===void 0||t.trim()==="")return null;let o=Number(t);return Number.isSafeInteger(o)?o:null});if(!i.hasMacro("get"))i.macro("get",function(e,t){let o=W(this).searchParams.get(e);return o!==null&&o!==void 0?o:t});i.macroAccessor("query",function(){return ye(this)});i.macroAccessor("cookies",function(){let e=this,t=()=>({...F(e)});for(let[o,a]of Object.entries(F(e)))Object.defineProperty(t,o,{value:a,writable:!0,enumerable:!0,configurable:!0});return t.get=(o)=>F(e)[o],t.set=(o,a,c={})=>{if(!e._cookiesToSet)e._cookiesToSet=[];e._cookiesToSet.push({name:o,value:a,options:c})},t.delete=(o,a={})=>{if(!e._cookiesToDelete)e._cookiesToDelete=[];e._cookiesToDelete.push({name:o,options:a})},t.getAll=()=>({...F(e)}),Object.defineProperty(e,"cookies",{value:t,writable:!0,configurable:!0,enumerable:!0}),t});function Ht(e){Object.defineProperties(e.prototype,{serve:{async value(t={}){if(this._initFileRoutes)await this._initFileRoutes();if(this._initApiRoutes)await this._initApiRoutes();this.invalidateCache();let o={idleTimeout:255,...t,fetch:this.handleRequest.bind(this)};if(t.development!==void 0)o.development=t.development;this._nativeRoutesEnabled=t.nativeRoutes===!0;let a=At(this,this._nativeRoutesEnabled,t.static);if(a)o.routes=a;if(this.wsConfig)o.websocket=this.wsConfig;if(this.serverInstance=Bun.serve(o),this.config.verbose){let c=this.serverInstance.port,d=this.serverInstance.hostname;console.log(`
100
+ \uD83D\uDE80 Server running at http://${d}:${c}
101
+ `)}return this.serverInstance},writable:!0,configurable:!0},reload:{async value(){if(!this.serverInstance)throw Error("Server not started, cannot reload");this.invalidateCache();let t=this.serverInstance.port,o=this.serverInstance.hostname;this.serverInstance.stop();let a={port:t,hostname:o,fetch:this.handleRequest.bind(this),websocket:this.wsConfig||void 0},c=At(this,this._nativeRoutesEnabled);if(c)a.routes=c;if(this.serverInstance=Bun.serve(a),this.config.verbose)console.log(`\uD83D\uDD04 Server reloaded at http://${o}:${t}`)},writable:!0,configurable:!0},handleRequest:{async value(t){let o=this,a=await B(t,()=>o.handleRequestImpl(t));return m(a,t,o.config?.compression)},writable:!0,configurable:!0},_dispatchMatchedRoute:{value(t,o,a){let c=this.enhanceRequest(o,a);T(c),c.route=t;let d=t,p=this._mwEpoch||0,h=d.middleware?d.middleware.length:0,f=this.globalMiddleware.length,R=d._compiledChain;if(!R||d._chainEpoch!==p||d._chainMwLen!==h){let b=_e(d.handler,this.config);if(h===0&&f===0)R=b;else{let w=h>0?[...this.globalMiddleware,...d.middleware]:[...this.globalMiddleware];w.push((P,M)=>b(P)),R=V(this,w)}d._compiledChain=R,d._chainEpoch=p,d._chainMwLen=h}let y;try{if(y=R(c),y instanceof Promise)return Ir(this,y,c)}catch(b){if(!this.errorHandler)throw b;let w=this.errorHandler(b);return w instanceof Promise?w.then((P)=>this.applyModifiedCookies(P,c)):this.applyModifiedCookies(w,c)}return y?this.applyModifiedCookies(y,c):new Response("No response from middleware chain",{status:500})},writable:!0,configurable:!0},_buildNativeRoutes:{value(){let t=new Set(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),o=(h)=>{if(h==="*")return"/*";let f=h.split("/"),R=[];for(let y=0;y<f.length;y++){let b=f[y];if(b===""){R.push(b);continue}if(b==="*")return y===f.length-1?[...R,"*"].join("/"):null;let w=b.match(/^\{([A-Z_$][\w$]*)\}$/i);if(w){R.push(`:${w[1]}`);continue}if(b.includes("{")||b.includes(":")||b.includes("*"))return null;R.push(b)}return R.join("/")},a=this,c=(h,f)=>{let R={router:a,route:h,isWildcard:f};return(y)=>j(y,Ur,R,y)},d={},p=new Map;for(let h of this.routes){if(!t.has(h.method))continue;if(h.nativeDispatch===!1)continue;if(h.constraints&&Object.keys(h.constraints).length>0)continue;if(h.handler instanceof Response)continue;let f=o(h.path);if(!f)continue;let R=f.replace(/:[^/]+/g,":p"),y=p.get(R);if(y&&y!==f)continue;p.set(R,f);let b=d[f]??={};if(b[h.method])continue;b[h.method]=c(h,h.path.endsWith("*"))}for(let h of Object.values(d))if(h.GET&&!h.HEAD)h.HEAD=h.GET;return Object.keys(d).length>0?d:null},writable:!0,configurable:!0},handleRequestImpl:{async value(t){try{let o,a="localhost";if(this._hasDomainRoutes){let R=new URL(t.url);t._parsedURL=R,o=R.pathname,a=R.hostname||t.headers.get("host")?.split(":")[0]||"localhost"}else o=Dr(t.url);let c=this.matchRoute(o,t.method,a,!0);if(t.method==="OPTIONS"&&!c){let R=t.headers.get("origin"),y={"Access-Control-Allow-Origin":R||"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin","Access-Control-Max-Age":"86400"};if(R)y["Access-Control-Allow-Credentials"]="true",y.Vary="Origin";return new Response(null,{status:204,headers:y})}if(c){let R=this._dispatchMatchedRoute(c.route,t,c.params);return R instanceof Promise?await R:R}let d=this.enhanceRequest(t,{});T(d);let p=this.getAllowedMethods(o,a,!0),h={"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin"};if(p.length>0){let R=(y,b)=>new Response(JSON.stringify({success:!1,message:"Method Not Allowed",path:o,method:t.method,allowed:p}),{status:405,headers:{...h,Allow:p.join(", ")}});if(this.globalMiddleware.length>0){let y=[...this.globalMiddleware,R],b=await this.runMiddleware(d,y);if(b)return this.applyModifiedCookies(b,d)}return R(d,async()=>null)}if(this.fallbackHandler){let R=await this.resolveHandler(this.fallbackHandler,d);return this.applyModifiedCookies(R,d)}let f=(R,y)=>oe(new Response(JSON.stringify({success:!1,message:"Not Found",path:o,method:t.method}),{status:404,headers:h}));if(this.globalMiddleware.length>0){let R=[...this.globalMiddleware,f],y=await this.runMiddleware(d,R);if(y)return this.applyModifiedCookies(y,d)}return f(d,async()=>null)}catch(o){if(console.error("Error handling request:",o),this.errorHandler)return this.errorHandler(o);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:o instanceof Error?o.message:String(o)}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin"}})}},writable:!0,configurable:!0},enhanceRequest:{value(t,o={}){let a=t;if("params"in t)Object.defineProperty(a,"params",{value:o,writable:!0,configurable:!0,enumerable:!0});else a.params=o;return i.applyMacros(a),a},writable:!0,configurable:!0},applyModifiedCookies:{value(t,o){let a=o._cookiesToSet&&o._cookiesToSet.length>0,c=o._cookiesToDelete&&o._cookiesToDelete.length>0;if(!a&&!c)return t;let d=new Response(t.body,{status:t.status,statusText:t.statusText,headers:t.headers});if(o._cookiesToSet&&o._cookiesToSet.length>0)for(let{name:p,value:h,options:f}of o._cookiesToSet){let R=this.serializeCookie(p,h,f);d.headers.append("Set-Cookie",R)}if(o._cookiesToDelete&&o._cookiesToDelete.length>0)for(let{name:p,options:h}of o._cookiesToDelete){let f={...h,expires:new Date(0),maxAge:0},R=this.serializeCookie(p,"",f);d.headers.append("Set-Cookie",R)}return d},writable:!0,configurable:!0},serializeCookie:{value(t,o,a={}){let c=`${encodeURIComponent(t)}=${encodeURIComponent(o)}`;if(a.maxAge!==void 0)c+=`; Max-Age=${a.maxAge}`;if(a.expires&&a.expires instanceof Date)c+=`; Expires=${a.expires.toUTCString()}`;if(a.path)c+=`; Path=${a.path}`;else c+="; Path=/";if(a.domain)c+=`; Domain=${a.domain}`;if(a.secure)c+="; Secure";if(a.httpOnly)c+="; HttpOnly";if(a.sameSite){let d=a.sameSite.toLowerCase();c+=`; SameSite=${d.charAt(0).toUpperCase()+d.slice(1)}`}return c},writable:!0,configurable:!0}})}import{join as Lr}from"path";function qt(e){Object.defineProperties(e.prototype,{renderView:{async value(t,o={},a={}){let c=this.config.views||{viewsPath:"resources/views",extensions:[".html",".stx"],cache:Bun.env.NODE_ENV==="production",engine:"auto"},d=`${t}:${a.layout||""}`;if(c.cache&&this.templateCache.has(d))return this.processTemplate(this.templateCache.get(d),o,c);let p=await Te(t,c.viewsPath,c.extensions);if(!p)throw Error(`View '${t}' not found`);let h=await Bun.file(p).text(),f=a.layout||c.defaultLayout;if(f){let R=await Te(Lr("layouts",f),c.viewsPath,c.extensions);if(!R)throw Error(`Layout '${f}' not found`);h=(await Bun.file(R).text()).replace(/\{\{\s*content\s*\}\}/g,h)}if(c.cache)this.templateCache.set(d,h);return this.processTemplate(h,o,c)},writable:!0,configurable:!0},processTemplate:{async value(t,o,a){if((a?.engine||"auto")==="custom"&&a?.customRenderer)return a.customRenderer(t,o,{});let d=Qe(t,o);if(a?.minify?.enabled)try{let p=a.minify.options||{removeComments:!0,collapseWhitespace:!0,minifyJS:!0,minifyCSS:!0};d=d.replace(/\s+/g," ").replace(/<!--[\s\S]*?-->/g,"")}catch(p){console.error("Error minifying HTML:",p)}return d},writable:!0,configurable:!0},view:{value(t,o,a={},c={},d="web",p){let h,f={},R={},y="web",b;if(typeof o==="string"){if(h=o,typeof a==="object"&&!Array.isArray(a))if("layout"in a||"status"in a||"headers"in a)R=a;else f=a;if(typeof c==="object")R={...R,...c};else if(typeof c==="string")y=c;if(typeof d==="string")if(d==="web"||d==="api")y=d;else b=d;if(p)b=p}else{if(f=o,typeof a==="string")h=a;else throw TypeError("View name must be a string");if(typeof c==="object")R=c;else if(typeof c==="string")if(c==="web"||c==="api")y=c;else h=c,y="web"}let w=async(P)=>{let M=await this.renderView(h,f,{layout:R.layout}),E=this.config?.queryPreservation;if(E?.enabled!==!1&&E?.preserve?.length)M=re(M,E);let k=new Headers;if(k.set("Content-Type","text/html; charset=utf-8"),R.headers)for(let[A,I]of Object.entries(R.headers))k.set(A,I);return new Response(M,{status:R.status||200,headers:k})};return this.get(t,w,y,b),this},writable:!0,configurable:!0}})}function Ot(e){Object.defineProperties(e.prototype,{websocket:{value(t){return this.wsConfig=t,this},writable:!0,configurable:!0},publish:{value(t,o,a=!1){if(!this.serverInstance)throw Error("Server not started, cannot publish to WebSocket topics");return this.serverInstance.publish(t,o,a)},writable:!0,configurable:!0},subscriberCount:{value(t){if(!this.serverInstance)throw Error("Server not started, cannot get subscriber count");return this.serverInstance.subscriberCount(t)},writable:!0,configurable:!0},upgrade:{value(t,o){if(!this.serverInstance)throw Error("Server not started, cannot upgrade to WebSocket");if(!this.wsConfig)throw Error("WebSocket configuration not set, use router.websocket() to configure");return this.serverInstance.upgrade(t,o)},writable:!0,configurable:!0},timeout:{value(t,o){if(!this.serverInstance)throw Error("Server not started, cannot set timeout");this.serverInstance.timeout(t,o)},writable:!0,configurable:!0},requestIP:{value(t){if(!this.serverInstance)throw Error("Server not started, cannot get request IP");return this.serverInstance.requestIP(t)},writable:!0,configurable:!0}})}ht(n);pt(n);wt(n);yt(n);gt(n);qt(n);Ot(n);ct(n);dt(n);Ht(n);bt(n);Rt(n);lt(n);it(n);var jr=["get","post","put","patch","delete"];function Fr(e,t,o,a){if(!a)return;let c=e,d=(p)=>{let h=c?.[p];if(typeof h!=="function")throw TypeError(`[typed-router] ${t.toUpperCase()} ${o}: this router's route does not support .${String(p)}(), so the \`${String(p)}\` option cannot be applied. Register the route directly instead of dropping it.`);return h};if(a.middleware)d("middleware").call(c,a.middleware);if(a.name)d("name").call(c,a.name);if(a.skipCsrf)d("skipCsrf").call(c);if(a.requireCsrf)d("requireCsrf").call(c);if(a.rateLimit)d("rateLimit").call(c,a.rateLimit.max,a.rateLimit.window??"minute")}function Ce(e){let t={};for(let o of jr)t[o]=(a,c,d)=>(Fr(e[o](a,c),o,a,d),t);return t}
102
+ export{v,X,x,Re,B,j,T,Y,ve,Q,Ge,pr,hr,m,mr,xt,Tt,U,r,Z,Ke,ee,s,L,Ct,_,te,Je,Xe,C,S,St,gr,g,xe,Et,Pt,Mt,fr,kt,re,yr,z,wr,$t,br,ne,Rr,l,u,vr,Ye,Te,Qe,i,n,se,Ce};