@stacksjs/bun-router 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{$ as Fl,A as ll,B as dl,C as pl,D as hl,E as gl,F as ml,G as fl,H as Rl,I as yl,J as wl,K as bl,L as Tl,M as xl,N as vl,O as Cl,P as Pl,Q as Ml,R as El,S as Sl,T as kl,U as Hl,V as Al,W as ql,X as Ol,Y as $l,Z as Bl,_ as Dl,a as Nc,aa as Nl,b as Uc,ba as Ul,c as Ic,ca as Il,d as _c,da as _l,e as jc,ea as jl,f as Lc,fa as Ll,g as zc,ga as zl,h as Gc,ha as Gl,i as Wc,ia as Wl,j as Vc,ja as Vl,k as Jc,l as Kc,m as Xc,n as Qc,o as Zc,p as Yc,q as el,r as tl,s as rl,t as nl,u as sl,v as il,w as ol,x as al,y as ul,z as cl}from"./chunk-4wd1d6ay.js";import{Aa as B,Ba as yn,Ca as wn,Da as bn,Ea as Tn,Fa as xn,Ga as vn,Ha as Cn,Ia as Pn,Ja as Mn,Oa as Ks,Pa as Xs,Qa as Qs,Ra as Zs,Sa as Ys,Ta as ei,Va as ti,_a as ri,ka as Xe,la as oe,ma as an,na as un,oa as cn,pa as ln,qa as be,ra as dn,sa as pn,ta as hn,ua as gn,va as xe,wa as Te,xa as mn,ya as fn,za as Rn}from"./chunk-m4aaj9ay.js";import{xb as on,yb as We}from"./chunk-8rrs7556.js";import{timingSafeEqual as Vr}from"crypto";function ze(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function we(e){e=e.replace(/-/g,"+").replace(/_/g,"/");while(e.length%4)e+="=";return atob(e)}class yt{secret;constructor(e){this.secret=e}sign(e,t={}){let r={alg:t.algorithm||"HS256",typ:"JWT",...t.header},n=Math.floor(Date.now()/1000),s={...e,iat:n};if(t.expiresIn){let c=typeof t.expiresIn==="string"?this.parseTimespan(t.expiresIn):t.expiresIn;s.exp=n+c}if(t.notBefore){let c=typeof t.notBefore==="string"?this.parseTimespan(t.notBefore):t.notBefore;s.nbf=n+c}if(t.issuer)s.iss=t.issuer;if(t.subject)s.sub=t.subject;if(t.audience)s.aud=t.audience;if(t.jwtid)s.jti=t.jwtid;let i=ze(JSON.stringify(r)),o=ze(JSON.stringify(s)),a=`${i}.${o}`,u=this.createSignature(a,this.secret,r.alg);return`${a}.${u}`}verify(e,t={}){try{let r=e.split(".");if(r.length!==3)throw Error("Token structure invalid");let[n,s,i]=r,o=JSON.parse(we(n)),a=JSON.parse(we(s));if(t.algorithms&&!t.algorithms.includes(o.alg))throw Error(`Algorithm ${o.alg} not allowed`);let u=`${n}.${s}`,c=this.createSignature(u,this.secret,o.alg),l=Buffer.from(i),d=Buffer.from(c);if(l.length!==d.length||!Vr(l,d))throw Error("Invalid signature");let p=Math.floor(Date.now()/1000);if(a.exp&&!t.ignoreExpiration&&p>=a.exp)throw Error("Token expired");if(a.nbf&&p<a.nbf)throw Error("Token not active yet");if(a.iat&&a.iat>p)throw Error("Token used before issued");if(t.issuer&&a.iss!==t.issuer)throw Error("Invalid issuer");if(t.audience&&a.aud!==t.audience)throw Error("Invalid audience");if(t.subject&&a.sub!==t.subject)throw Error("Invalid subject");return a}catch{return null}}decode(e){try{let t=e.split(".");if(t.length!==3)return null;let[r,n]=t;return{header:JSON.parse(we(r)),payload:JSON.parse(we(n))}}catch{return null}}createSignature(e,t,r){return ze(JSON.stringify({data:e,secret:t.slice(0,5),alg:r}))}parseTimespan(e){let t=e.match(/^(\d+)\s*([smhd])$/i);if(!t)return Number.parseInt(e,10)||0;let r=Number.parseInt(t[1],10);switch(t[2].toLowerCase()){case"s":return r;case"m":return r*60;case"h":return r*60*60;case"d":return r*24*60*60;default:return r}}}class wt{keys;options;constructor(e={}){this.keys=new Map,this.options={source:"header",keyName:"X-API-Key",keyPrefix:"bun_",...e}}generateKey(e,t=[],r){let n=`${this.options.keyPrefix}${this.randomString(32)}`;return this.keys.set(n,{owner:e,scopes:t,expiresAt:r?new Date(Date.now()+r*1000):void 0}),n}validateKey(e,t=[]){let r=this.keys.get(e);if(!r)return!1;if(r.expiresAt&&r.expiresAt<new Date)return!1;if(t.length>0)return t.every((n)=>r.scopes.includes(n));return!0}getKeyInfo(e){return this.keys.get(e)||null}revokeKey(e){return this.keys.delete(e)}extractFromRequest(e){let{source:t,keyName:r}=this.options;switch(t){case"header":return e.headers.get(r||"X-API-Key")||null;case"query":return new URL(e.url).searchParams.get(r||"api_key")||null;case"cookie":if(e.cookies){let n=r||"api_key";if(typeof e.cookies.get==="function")return e.cookies.get(n)||null;return e.cookies[n]||null}return null;default:return null}}randomString(e){let r="";for(let n=0;n<e;n++)r+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62));return r}}class bt{config;constructor(e){this.config=e}getAuthorizationUrl(e={}){let t=new URLSearchParams({client_id:this.config.clientId,redirect_uri:this.config.redirectUri,response_type:"code",...e});if(this.config.scope)t.set("scope",this.config.scope);if(this.config.state)t.set("state",this.config.state);return`${this.config.authorizeUrl}?${t.toString()}`}async exchangeCodeForToken(e){let t=new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret}),r=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!r.ok)throw Error(`OAuth token exchange failed: ${r.status} ${r.statusText}`);return await r.json()}async refreshToken(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:this.config.clientId,client_secret:this.config.clientSecret}),r=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!r.ok)throw Error(`OAuth token refresh failed: ${r.status} ${r.statusText}`);return await r.json()}}var Jr={JWT:yt,ApiKeyManager:wt,OAuth2Helper:bt},Kr=Jr;var Pt={};on(Pt,{AuthenticationException:()=>an,AuthorizationException:()=>un,BugsnagReporter:()=>Je,BusinessLogicException:()=>mn,CircuitBreaker:()=>ve,CircuitBreakerHttpClient:()=>Tt,CircuitBreakerOpenException:()=>Te,CircuitBreakerPresets:()=>Zr,CircuitBreakerRegistry:()=>J,CircularDependencyException:()=>wn,ConfigurationException:()=>fn,CustomReporter:()=>xt,DatabaseException:()=>gn,DegradationStrategies:()=>sn,ErrorFactory:()=>B,ErrorReportingManager:()=>se,ErrorReportingPresets:()=>rn,ExternalServiceException:()=>xe,FileSystemException:()=>Rn,GracefulDegradationManager:()=>ie,HandlerResolutionException:()=>xn,InternalServerException:()=>pn,MethodNotAllowedException:()=>ln,MiddlewareConfigurationException:()=>bn,ModelBindingException:()=>vn,NotFoundException:()=>cn,RateLimitException:()=>dn,RouteConflictException:()=>yn,RouteNotFoundException:()=>Tn,RouterErrorFactory:()=>Mn,RouterException:()=>Xe,SentryReporter:()=>Ve,ServiceHealthMonitor:()=>Ke,ServiceUnavailableException:()=>hn,TimeoutException:()=>be,ValidationException:()=>oe,circuitBreaker:()=>Xr,createAdvancedErrorHandler:()=>Ct,createCircuitBreaker:()=>Yr,createCircuitBreakerMiddleware:()=>Qr,createErrorReporting:()=>tn,createGracefulDegradationMiddleware:()=>nn,detectRouteConflicts:()=>Pn,findSimilarRoutes:()=>Cn,globalCircuitBreakerRegistry:()=>Ge,withCircuitBreaker:()=>en});class ve{config;state="CLOSED";metrics;nextAttemptTime;halfOpenCallCount=0;recentRequests=[];constructor(e){let t={failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000};this.config={...t,...e},this.metrics={totalRequests:0,successfulRequests:0,failedRequests:0,timeouts:0,averageResponseTime:0,state:this.state,consecutiveFailures:0,consecutiveSuccesses:0},setInterval(()=>this.cleanupOldRequests(),this.config.monitoringPeriod/4).unref?.()}async execute(e){if(this.state==="OPEN")if(this.nextAttemptTime&&new Date<this.nextAttemptTime){let s=new Te(this.config.name,this.nextAttemptTime,e.context);if(e.fallback)try{return await e.fallback()}catch(i){console.error(i)}throw s}else this.transitionToHalfOpen();if(this.state==="HALF_OPEN"&&this.halfOpenCallCount>=this.config.halfOpenMaxCalls){let s=new Te(this.config.name,this.nextAttemptTime||new Date(Date.now()+this.config.recoveryTimeout),e.context);if(e.fallback)try{return await e.fallback()}catch(i){throw console.error(i),s}throw s}let t=Date.now(),r,n=null;try{if(this.state==="HALF_OPEN")this.halfOpenCallCount++;let s=e.timeout||this.config.timeout,i=new Promise((o,a)=>{setTimeout(()=>{a(new be(`Circuit breaker timeout for ${this.config.name}`,s,e.context))},s)});return r=await Promise.race([e.execute(),i]),this.onSuccess(Date.now()-t),r}catch(s){if(n=s,this.onFailure(n,Date.now()-t),e.fallback)try{return await e.fallback()}catch(i){throw console.error(i),n}else throw n}}getState(){return this.state}getMetrics(){return{...this.metrics,state:this.state,nextAttemptTime:this.nextAttemptTime}}forceOpen(){this.transitionToOpen()}forceClosed(){this.transitionToClosed()}reset(){this.metrics={totalRequests:0,successfulRequests:0,failedRequests:0,timeouts:0,averageResponseTime:0,state:this.state,consecutiveFailures:0,consecutiveSuccesses:0},this.recentRequests=[]}onSuccess(e){if(this.metrics.totalRequests++,this.metrics.successfulRequests++,this.metrics.consecutiveSuccesses++,this.metrics.consecutiveFailures=0,this.metrics.lastSuccessTime=new Date,this.updateAverageResponseTime(e),this.recentRequests.push({timestamp:new Date,success:!0,responseTime:e}),this.state==="HALF_OPEN"){if(this.metrics.consecutiveSuccesses>=this.config.halfOpenMaxCalls)this.transitionToClosed()}if(this.config.onSuccess)this.config.onSuccess(this.config.name)}onFailure(e,t){if(this.metrics.totalRequests++,this.metrics.failedRequests++,this.metrics.consecutiveFailures++,this.metrics.consecutiveSuccesses=0,this.metrics.lastFailureTime=new Date,e instanceof be)this.metrics.timeouts++;if(this.updateAverageResponseTime(t),this.recentRequests.push({timestamp:new Date,success:!1,responseTime:t}),this.shouldTrip(e)){if(this.state==="CLOSED")this.transitionToOpen();else if(this.state==="HALF_OPEN")this.transitionToOpen()}if(this.config.onFailure)this.config.onFailure(e,this.config.name)}shouldTrip(e){if(this.config.shouldTripOnError&&!this.config.shouldTripOnError(e))return!1;if(this.metrics.consecutiveFailures>=this.config.failureThreshold)return!0;let t=this.getRecentRequests();if(t.length>=this.config.minimumRequests){if(t.filter((s)=>!s.success).length/t.length*100>=this.config.errorThresholdPercentage)return!0}return!1}transitionToClosed(){if(this.state="CLOSED",this.nextAttemptTime=void 0,this.halfOpenCallCount=0,this.metrics.state=this.state,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}transitionToOpen(){if(this.state="OPEN",this.nextAttemptTime=new Date(Date.now()+this.config.recoveryTimeout),this.halfOpenCallCount=0,this.metrics.state=this.state,this.metrics.nextAttemptTime=this.nextAttemptTime,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}transitionToHalfOpen(){if(this.state="HALF_OPEN",this.halfOpenCallCount=0,this.metrics.state=this.state,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}updateAverageResponseTime(e){if(this.metrics.totalRequests===1)this.metrics.averageResponseTime=e;else this.metrics.averageResponseTime=0.1*e+0.9*this.metrics.averageResponseTime}getRecentRequests(){let e=new Date(Date.now()-this.config.monitoringPeriod);return this.recentRequests.filter((t)=>t.timestamp>e)}cleanupOldRequests(){let e=new Date(Date.now()-this.config.monitoringPeriod);this.recentRequests=this.recentRequests.filter((t)=>t.timestamp>e)}}class J{breakers=new Map;configs=new Map;register(e){let t=new ve(e);return this.breakers.set(e.name,t),this.configs.set(e.name,e),t}get(e){return this.breakers.get(e)}async execute(e,t){let r=this.breakers.get(e);if(!r)throw Error(`Circuit breaker '${e}' not found`);return r.execute(t)}getAllMetrics(){let e={};for(let[t,r]of this.breakers)e[t]=r.getMetrics();return e}getBreakersByState(e){let t=[];for(let[r,n]of this.breakers)if(n.getState()===e)t.push(r);return t}forceAllClosed(){for(let e of this.breakers.values())e.forceClosed()}resetAll(){for(let e of this.breakers.values())e.reset()}remove(e){return this.configs.delete(e),this.breakers.delete(e)}getNames(){return Array.from(this.breakers.keys())}}function Xr(e){let t=new ve(e);return function(r,n,s){let i=s.value;return s.value=async function(...o){return t.execute({execute:()=>i.apply(this,o),context:{method:n,timestamp:new Date}})},s}}class Tt{registry;constructor(e){this.registry=e||new J}async fetch(e,t={}){let{circuitBreaker:r,fallback:n,context:s,...i}=t,o;if(typeof r==="string")o=r;else if(r){if(o=r.name,!this.registry.get(o))this.registry.register(r)}else if(o=`http-${new URL(e).hostname}`,!this.registry.get(o))this.registry.register({name:o,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000});return this.registry.execute(o,{execute:async()=>{let a=await fetch(e,i);if(a.status>=500)throw new xe(`HTTP ${a.status}: ${a.statusText}`,o,e,a.status,void 0,s);return a},fallback:n,context:s})}getRegistry(){return this.registry}}function Qr(e){return async(t,r)=>{let n=t.context?.serviceName;if(!n)return r();let s=e.get(n);if(!s)return r();return s.execute({execute:r,context:{requestId:t.requestId,route:t.route,method:t.method,url:t.url}})}}var Zr={critical:(e)=>({name:e,failureThreshold:3,recoveryTimeout:30000,timeout:5000,monitoringPeriod:30000,minimumRequests:5,errorThresholdPercentage:30,halfOpenMaxCalls:2,resetTimeout:30000}),standard:(e)=>({name:e,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000}),tolerant:(e)=>({name:e,failureThreshold:10,recoveryTimeout:120000,timeout:60000,monitoringPeriod:120000,minimumRequests:20,errorThresholdPercentage:70,halfOpenMaxCalls:5,resetTimeout:120000}),database:(e)=>({name:e,failureThreshold:3,recoveryTimeout:60000,timeout:1e4,monitoringPeriod:60000,minimumRequests:5,errorThresholdPercentage:40,halfOpenMaxCalls:2,resetTimeout:60000,shouldTripOnError:(t)=>!(t.message.includes("validation")||t.message.includes("constraint"))}),externalApi:(e)=>({name:e,failureThreshold:5,recoveryTimeout:90000,timeout:15000,monitoringPeriod:90000,minimumRequests:8,errorThresholdPercentage:60,halfOpenMaxCalls:3,resetTimeout:90000,shouldTripOnError:(t)=>{if(t instanceof xe)return t.statusCode>=500;return!0}})},Ge=new J;function Yr(e){return Ge.register(e)}async function en(e,t){return Ge.execute(e,t)}class Ve{config;sentry;constructor(e){this.config=e,this.initializeSentry()}async initializeSentry(){try{let e=await import("@sentry/node");e.init({dsn:this.config.dsn,environment:this.config.environment||"production",release:this.config.release,sampleRate:this.config.sampleRate||1,beforeSend:(t,r)=>{let n=r.originalException;if(n&&this.config.beforeSend)return this.config.beforeSend(n,n.context)?t:null;return t},ignoreErrors:this.config.filters?.ignoreErrors,denyUrls:this.config.filters?.ignoreUrls,allowUrls:this.config.filters?.allowUrls,initialScope:{tags:this.config.tags,extra:this.config.extra,user:this.config.user},maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||100,tracesSampleRate:this.config.performance?.tracesSampleRate||0.1}),this.sentry=e}catch(e){console.warn("Failed to initialize Sentry:",e)}}async report(e,t){if(!this.sentry||!this.config.enabled)return null;try{if(this.shouldIgnoreError(e))return null;let r={...e.context,...t};return this.sentry.withScope((n)=>{if(r.requestId)n.setTag("requestId",r.requestId);if(r.userId)n.setUser({id:r.userId});if(r.traceId)n.setTag("traceId",r.traceId);if(r.route)n.setTag("route",r.route);if(r.method)n.setTag("method",r.method);n.setTag("errorCode",e.code),n.setTag("severity",e.severity),n.setTag("category",e.category),n.setLevel(this.mapSeverityToLevel(e.severity)),n.setExtra("statusCode",e.statusCode),n.setExtra("retryable",e.retryable),n.setExtra("timestamp",e.timestamp),n.setExtra("context",r);let s=this.generateFingerprint(e);if(s.length>0)n.setFingerprint(s);return this.sentry.captureException(e)})}catch(r){return console.error("Failed to report error to Sentry:",r),null}}addBreadcrumb(e,t="default",r="info",n){if(!this.sentry||!this.config.breadcrumbs?.enabled)return;this.sentry.addBreadcrumb({message:e,category:t,level:r,data:n,timestamp:Date.now()/1000})}setUser(e){if(!this.sentry)return;this.sentry.setUser(e)}setTag(e,t){if(!this.sentry)return;this.sentry.setTag(e,t)}setExtra(e,t){if(!this.sentry)return;this.sentry.setExtra(e,t)}setContext(e,t){if(!this.sentry)return;this.sentry.setContext(e,t)}async close(e=2000){if(!this.sentry)return!0;return this.sentry.close(e)}shouldIgnoreError(e){let t=this.config.filters;if(!t)return!1;if(t.ignoreCodes?.includes(e.code))return!0;if(t.ignoreErrors?.some((r)=>{if(typeof r==="string")return e.message.includes(r);return r.test(e.message)}))return!0;return!1}mapSeverityToLevel(e){switch(e){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}generateFingerprint(e){let t=[];if(t.push(e.code),t.push(e.category),e.context.route)t.push(e.context.route);return t}}class Je{config;bugsnag;constructor(e){this.config=e,this.initializeBugsnag()}async initializeBugsnag(){try{let e=await import("@bugsnag/js");e.start({apiKey:this.config.apiKey,appVersion:this.config.release,releaseStage:this.config.environment||"production",enabledReleaseStages:["production","staging"],maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||25,onError:(t)=>{let r=t.originalError;if(r&&this.config.beforeSend)return this.config.beforeSend(r,r.context)!==null;return!this.shouldIgnoreError(r)}}),this.bugsnag=e}catch(e){console.warn("Failed to initialize Bugsnag:",e)}}async report(e,t){if(!this.bugsnag||!this.config.enabled)return null;try{if(this.shouldIgnoreError(e))return null;let r={...e.context,...t};return this.bugsnag.notify(e,(n)=>{if(n.severity=this.mapSeverityToBugsnag(e.severity),n.context=r.route||r.url,r.userId)n.setUser(r.userId,void 0,void 0);n.addMetadata("error",{code:e.code,category:e.category,statusCode:e.statusCode,retryable:e.retryable,timestamp:e.timestamp}),n.addMetadata("request",{requestId:r.requestId,method:r.method,url:r.url,userAgent:r.userAgent,ip:r.ip}),n.groupingHash=this.generateGroupingHash(e)}),"reported"}catch(r){return console.error("Failed to report error to Bugsnag:",r),null}}addBreadcrumb(e,t="manual",r="info",n){if(!this.bugsnag||!this.config.breadcrumbs?.enabled)return;this.bugsnag.leaveBreadcrumb(e,n,t)}setUser(e){if(!this.bugsnag)return;this.bugsnag.setUser(e.id,e.email,e.username)}setTag(e,t){if(!this.bugsnag)return;this.bugsnag.addMetadata("tags",{[e]:t})}setExtra(e,t){if(!this.bugsnag)return;this.bugsnag.addMetadata("extra",{[e]:t})}setContext(e,t){if(!this.bugsnag)return;this.bugsnag.addMetadata(e,t)}async close(){return!0}shouldIgnoreError(e){let t=this.config.filters;if(!t)return!1;if(t.ignoreCodes?.includes(e.code))return!0;if(t.ignoreErrors?.some((r)=>{if(typeof r==="string")return e.message.includes(r);return r.test(e.message)}))return!0;return!1}mapSeverityToBugsnag(e){switch(e){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"error";default:return"warning"}}generateGroupingHash(e){return`${e.code}-${e.category}-${e.context.route||"unknown"}`}}class xt{config;reportHandler;constructor(e,t){this.config=e,this.reportHandler=t}async report(e,t){if(!this.config.enabled)return null;try{let r={...e.context,...t};if(this.config.beforeSend){if(!this.config.beforeSend(e,r))return null}let n={error:e,context:r,level:this.mapSeverityToLevel(e.severity),tags:this.config.tags,extra:this.config.extra,user:this.config.user};return await this.reportHandler(n)}catch(r){return console.error("Failed to report error with custom handler:",r),null}}addBreadcrumb(){}setUser(){}setTag(){}setExtra(){}setContext(){}async close(){return!0}mapSeverityToLevel(e){switch(e){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}}class se{reporters=[];breadcrumbs=[];maxBreadcrumbs=50;constructor(e){this.initializeReporters(e)}initializeReporters(e){for(let t of e){if(!t.enabled)continue;switch(t.service){case"sentry":this.reporters.push(new Ve(t));break;case"bugsnag":this.reporters.push(new Je(t));break;case"custom":break}}}addReporter(e){this.reporters.push(e)}async report(e,t){let r=[];this.addBreadcrumb(`Error occurred: ${e.message}`,"error",{code:e.code,severity:e.severity});let n=this.reporters.map(async(s)=>{try{let i=await s.report(e,t);if(i)r.push(i)}catch(i){console.error("Reporter failed:",i)}});return await Promise.allSettled(n),r}addBreadcrumb(e,t="default",r){if(this.breadcrumbs.push({message:e,timestamp:new Date,data:{category:t,...r}}),this.breadcrumbs.length>this.maxBreadcrumbs)this.breadcrumbs=this.breadcrumbs.slice(-this.maxBreadcrumbs);this.reporters.forEach((n)=>{n.addBreadcrumb(e,t,"info",r)})}setUser(e){this.reporters.forEach((t)=>t.setUser(e))}setTag(e,t){this.reporters.forEach((r)=>r.setTag(e,t))}setExtra(e,t){this.reporters.forEach((r)=>r.setExtra(e,t))}setContext(e,t){this.reporters.forEach((r)=>r.setContext(e,t))}async close(e=5000){let t=this.reporters.map((n)=>n.close(e));return(await Promise.allSettled(t)).every((n)=>n.status==="fulfilled"&&n.value)}getBreadcrumbs(){return[...this.breadcrumbs]}}function tn(e){return new se(e)}var rn={sentry:(e,t="production")=>({enabled:!0,service:"sentry",dsn:e,environment:t,sampleRate:1,breadcrumbs:{enabled:!0,maxBreadcrumbs:100},performance:{enabled:!0,tracesSampleRate:0.1},filters:{ignoreErrors:["Non-Error promise rejection captured","ResizeObserver loop limit exceeded"],ignoreCodes:["VALIDATION_ERROR"]}}),bugsnag:(e,t="production")=>({enabled:!0,service:"bugsnag",apiKey:e,environment:t,breadcrumbs:{enabled:!0,maxBreadcrumbs:25},filters:{ignoreCodes:["VALIDATION_ERROR"]}}),development:()=>({enabled:!1,service:"custom",environment:"development"})};class Ke{healthStatus=new Map;healthCheckIntervals=new Map;config;constructor(e){this.config=e,this.initializeHealthChecks()}initializeHealthChecks(){for(let[e,t]of Object.entries(this.config.healthChecks)){if(!t.enabled)continue;this.healthStatus.set(e,{name:e,status:"healthy",lastCheck:new Date,responseTime:0,errorRate:0,availability:100,consecutiveFailures:0});let r=setInterval(()=>this.performHealthCheck(e,t),t.interval);r.unref?.(),this.healthCheckIntervals.set(e,r)}}async performHealthCheck(e,t){let r=Date.now(),n=!1;try{let i=new AbortController,o=setTimeout(()=>i.abort(),t.timeout),a=await fetch(t.endpoint,{signal:i.signal,headers:t.headers,method:"GET"});if(clearTimeout(o),n=t.expectedStatus.includes(a.status),n&&t.expectedBody){let u=await a.text();if(typeof t.expectedBody==="string")n=u.includes(t.expectedBody);else n=t.expectedBody.test(u)}}catch(i){console.error(i),n=!1}let s=Date.now()-r;if(this.updateHealthStatus(e,n,s),n&&t.onHealthy)t.onHealthy();else if(!n&&t.onUnhealthy)t.onUnhealthy(Error(`Health check failed for ${e}`))}updateHealthStatus(e,t,r){let n=this.healthStatus.get(e);if(!n)return;let s={...n,lastCheck:new Date,responseTime:r,consecutiveFailures:t?0:n.consecutiveFailures+1};if(s.consecutiveFailures===0)s.status="healthy";else if(s.consecutiveFailures<3)s.status="degraded";else s.status="unhealthy";let i=t?1:0;s.availability=n.availability*0.9+i*10,this.healthStatus.set(e,s)}getServiceHealth(e){return this.healthStatus.get(e)}getAllServiceHealth(){return Array.from(this.healthStatus.values())}isServiceHealthy(e){return this.healthStatus.get(e)?.status==="healthy"}isServiceDegraded(e){return this.healthStatus.get(e)?.status==="degraded"}stop(){for(let e of this.healthCheckIntervals.values())clearInterval(e);this.healthCheckIntervals.clear()}}class ie{config;healthMonitor;cache=new Map;metrics=new Map;constructor(e){this.config=e,this.healthMonitor=new Ke(e)}async handleFailure(e,t,r,n){if(!this.config.enabled)throw t;let s=this.config.fallbackStrategies[e];if(!s)throw t;let i={request:r,serviceName:e,error:t,attemptCount:1,startTime:new Date};return this.executeFallbackStrategy(s,i,n)}async executeFallbackStrategy(e,t,r){if(t.attemptCount<=e.retries)try{if(t.attemptCount>1){let i=this.calculateBackoffDelay(e.backoff,t.attemptCount);await this.sleep(i)}let n=new Promise((i,o)=>{setTimeout(()=>o(Error("Timeout")),e.timeout)}),s=await Promise.race([r(),n]);return this.updateMetrics(t.serviceName,!0,Date.now()-t.startTime.getTime()),s}catch(n){if(console.error(n),t.attemptCount++,t.attemptCount<=e.retries)return this.executeFallbackStrategy(e,t,r)}switch(this.updateMetrics(t.serviceName,!1,Date.now()-t.startTime.getTime()),e.type){case"cache":return this.handleCacheFallback(e,t);case"static":return this.handleStaticFallback(e,t);case"simplified":return this.handleSimplifiedFallback(e,t);case"redirect":return this.handleRedirectFallback(e,t);case"custom":return this.handleCustomFallback(e,t);default:throw t.error}}async handleCacheFallback(e,t){if(!e.cacheConfig)throw t.error;let r=this.generateCacheKey(e.cacheConfig.key,t),n=this.cache.get(r);if(n&&(n.expires>new Date||e.cacheConfig.staleWhileRevalidate)){let s=new Headers({"Content-Type":"application/json","X-Cache":"HIT","X-Degraded":"true","X-Service-Status":this.healthMonitor.getServiceHealth(t.serviceName)?.status||"unknown"});if(e.cacheConfig.staleWhileRevalidate&&n.expires<=new Date)s.set("X-Cache","STALE");return new Response(JSON.stringify(n.data),{status:200,headers:s})}throw t.error}async handleStaticFallback(e,t){if(!e.staticResponse)throw t.error;let r=new Headers(e.staticResponse.headers||{});return r.set("X-Degraded","true"),r.set("X-Fallback-Type","static"),r.set("X-Service-Status",this.healthMonitor.getServiceHealth(t.serviceName)?.status||"unknown"),new Response(typeof e.staticResponse.body==="string"?e.staticResponse.body:JSON.stringify(e.staticResponse.body),{status:e.staticResponse.status,headers:r})}async handleSimplifiedFallback(e,t){let r={message:"Service temporarily unavailable. Showing simplified view.",status:"degraded",timestamp:new Date().toISOString(),requestId:t.request.requestId};return new Response(JSON.stringify(r),{status:200,headers:{"Content-Type":"application/json","X-Degraded":"true","X-Fallback-Type":"simplified","X-Service-Status":this.healthMonitor.getServiceHealth(t.serviceName)?.status||"unknown"}})}async handleRedirectFallback(e,t){if(!e.redirectConfig)throw t.error;return new Response(null,{status:e.redirectConfig.permanent?301:302,headers:{Location:e.redirectConfig.url,"X-Degraded":"true","X-Fallback-Type":"redirect"}})}async handleCustomFallback(e,t){if(!e.fallbackHandler)throw t.error;try{let r=await e.fallbackHandler(t.error,t.error.context);return r.headers.set("X-Degraded","true"),r.headers.set("X-Fallback-Type","custom"),r.headers.set("X-Service-Status",this.healthMonitor.getServiceHealth(t.serviceName)?.status||"unknown"),r}catch(r){throw console.error(r),t.error}}cacheResponse(e,t,r,n){let s=this.config.fallbackStrategies[e];if(s?.type==="cache"&&s.cacheConfig){let i=this.generateCacheKey(t,{serviceName:e});this.cache.set(i,{data:r,expires:new Date(Date.now()+n*1000)})}}getServiceMetrics(e){let t=this.metrics.get(e);if(!t||t.requests===0)return{errorRate:0,avgResponseTime:0,totalRequests:0};return{errorRate:t.errors/t.requests*100,avgResponseTime:t.totalTime/t.requests,totalRequests:t.requests}}getSystemHealth(){let e=this.healthMonitor.getAllServiceHealth(),t=e.filter((s)=>s.status==="unhealthy").length,r=e.filter((s)=>s.status==="degraded").length,n="healthy";if(t>0)n=t>e.length/2?"unhealthy":"degraded";else if(r>0)n="degraded";return{status:n,services:e}}calculateBackoffDelay(e,t){if(e.type==="fixed")return e.delay;let r=e.delay*2**(t-1);return Math.min(r,e.maxDelay||30000)}generateCacheKey(e,t){return e.replace("{service}",t.serviceName).replace("{url}",t.request.url).replace("{method}",t.request.method).replace("{userId}",String(t.request.user?.id||"anonymous"))}updateMetrics(e,t,r){let n=this.metrics.get(e)||{requests:0,errors:0,totalTime:0};if(n.requests++,n.totalTime+=r,!t)n.errors++;this.metrics.set(e,n)}sleep(e){return new Promise((t)=>setTimeout(t,e))}stop(){this.healthMonitor.stop()}}function nn(e){let t=new ie(e);return async(r,n)=>{try{let s=await n(),i=r.context?.serviceName;if(i&&s.ok){let o=e.fallbackStrategies[i];if(o?.type==="cache"&&o.cacheConfig)try{let a=await s.clone().json();t.cacheResponse(i,o.cacheConfig.key,a,o.cacheConfig.ttl)}catch{}}return s}catch(s){let i=r.context?.serviceName;if(i&&s instanceof Error){let o=s;try{return await t.handleFailure(i,o,r,n)}catch(a){throw console.error(a),s}}throw s}}}var sn={cacheFirst:(e=3600,t=!0)=>({type:"cache",priority:1,timeout:5000,retries:2,backoff:{type:"exponential",delay:1000,maxDelay:5000},cacheConfig:{key:"{service}:{url}:{method}",ttl:e,staleWhileRevalidate:t}}),staticFallback:(e,t=200)=>({type:"static",priority:2,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},staticResponse:{status:t,body:e,headers:{"Content-Type":"application/json"}}}),simplifiedView:()=>({type:"simplified",priority:3,timeout:1000,retries:0,backoff:{type:"fixed",delay:0}}),redirectToMaintenance:(e)=>({type:"redirect",priority:4,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},redirectConfig:{url:e,permanent:!1}})};class vt{errorReporting;gracefulDegradation;circuitBreakerRegistry;config;constructor(e={}){this.config={development:!1,includeStackTrace:!1,sanitizeErrors:!0,logErrors:!0,...e},this.initializeComponents()}initializeComponents(){if(this.config.errorReporting?.length)this.errorReporting=new se(this.config.errorReporting);if(this.config.gracefulDegradation?.enabled)this.gracefulDegradation=new ie(this.config.gracefulDegradation);if(this.config.circuitBreakers?.length){this.circuitBreakerRegistry=new J;for(let e of this.config.circuitBreakers)this.circuitBreakerRegistry.register(e)}}middleware(){return async(e,t)=>{try{let r={requestId:e.requestId,userId:e.user?.id,traceId:e.traceId,spanId:e.spanId,route:e.params?.route||e.url,method:e.method,url:e.url,userAgent:e.userAgent?.()||void 0,ip:e.ip?.()||void 0,timestamp:new Date};if(e.context={...e.context,errorContext:r},this.circuitBreakerRegistry&&e.context?.serviceName){let n=this.circuitBreakerRegistry.get(e.context.serviceName);if(n)return await n.execute({execute:t,context:r})}return await t()}catch(r){return this.handleError(r,e)}}}async handleError(e,t){let r=this.normalizeError(e,t);if(this.errorReporting)this.errorReporting.addBreadcrumb(`Error in ${t.method} ${t.url}`,"error",{code:r.code,severity:r.severity,statusCode:r.statusCode});if(this.config.logErrors)this.logError(r,t);if(this.gracefulDegradation&&t.context?.serviceName)try{return await this.gracefulDegradation.handleFailure(t.context.serviceName,r,t,async()=>{throw r})}catch{}if(this.errorReporting)try{await this.errorReporting.report(r,r.context)}catch(s){console.error("Failed to report error:",s)}if(this.config.globalErrorHandler)try{return await this.config.globalErrorHandler(r,t)}catch(s){console.error("Global error handler failed:",s)}let n=this.config.customErrorPages?.[r.statusCode];if(n)try{if(typeof n==="string")return new Response(n,{status:r.statusCode,headers:{"Content-Type":"text/html"}});else return await n(r,t)}catch(s){console.error("Custom error page failed:",s)}return this.createErrorResponse(r,t)}normalizeError(e,t){let r={requestId:t.requestId,userId:t.user?.id,traceId:t.traceId,spanId:t.spanId,route:t.params?.route||t.url,method:t.method,url:t.url,userAgent:t.userAgent?.()||void 0,ip:t.ip?.()||void 0,timestamp:new Date,metadata:t.context};if(e instanceof Xe)return e;if(e instanceof Error){if(e.name==="ValidationError")return B.validation(e.message,{},r);if(e.name==="UnauthorizedError"||e.message.includes("unauthorized"))return B.authentication(e.message,r);if(e.name==="ForbiddenError"||e.message.includes("forbidden"))return B.authorization(e.message,[],r);if(e.name==="NotFoundError"||e.message.includes("not found"))return B.notFound(void 0,void 0,r);if(e.name==="TimeoutError"||e.message.includes("timeout"))return B.timeout(30000,e.message,r);return B.internalServer(e.message,e,r)}if(typeof e==="string")return B.internalServer(e,void 0,r);return B.internalServer("An unknown error occurred",void 0,r)}createErrorResponse(e,t){let r=this.config.development,n=this.config.includeStackTrace||r,s=this.config.sanitizeErrors&&!r,i=e.message;if(s&&e.statusCode>=500)i="An internal server error occurred";let o={error:{code:e.code,message:i,statusCode:e.statusCode,timestamp:e.timestamp.toISOString(),requestId:e.context.requestId,traceId:e.context.traceId}};if(r)o.error.category=e.category,o.error.severity=e.severity,o.error.retryable=e.retryable,o.error.context=e.context;if(n){if(o.error.stack=e.stack,e.cause)o.error.cause={name:e.cause.name,message:e.cause.message,stack:e.cause.stack}}if("fields"in e)o.error.fields=e.fields;if("allowedMethods"in e)o.error.allowedMethods=e.allowedMethods;if("retryAfter"in e)o.error.retryAfter=e.retryAfter;let a=new Headers({"Content-Type":"application/json","X-Error-Code":e.code,"X-Request-ID":e.context.requestId||"","X-Trace-ID":e.context.traceId||""});if("allowedMethods"in e)a.set("Allow",e.allowedMethods.join(", "));if("retryAfter"in e)a.set("Retry-After",e.retryAfter.toString());if("limit"in e)a.set("X-RateLimit-Limit",e.limit.toString()),a.set("X-RateLimit-Remaining",e.remaining.toString());return new Response(JSON.stringify(o),{status:e.statusCode,headers:a})}logError(e,t){let r={error:e.toJSON(),request:{method:t.method,url:t.url,headers:Object.fromEntries(t.headers.entries()),userAgent:t.userAgent?.()||void 0,ip:t.ip?.()||void 0,requestId:t.requestId,traceId:t.traceId}};switch(e.severity){case"critical":console.error("[CRITICAL ERROR]",r);break;case"high":console.error("[ERROR]",r);break;case"medium":console.warn("[WARNING]",r);break;case"low":console.warn("[INFO]",r);break;default:console.error("[ERROR]",r)}}getStats(){return{errorReporting:this.errorReporting?{breadcrumbs:this.errorReporting.getBreadcrumbs().length}:void 0,gracefulDegradation:this.gracefulDegradation?this.gracefulDegradation.getSystemHealth():void 0,circuitBreakers:this.circuitBreakerRegistry?this.circuitBreakerRegistry.getAllMetrics():void 0}}async cleanup(){if(this.errorReporting)await this.errorReporting.close();if(this.gracefulDegradation)this.gracefulDegradation.stop()}}function Ct(e={}){let t=new vt(e);return{middleware:t.middleware(),getStats:()=>t.getStats(),cleanup:()=>t.cleanup()}}function K(e){if(!e.includes("%"))return e;try{return decodeURIComponent(e)}catch{return e}}function Ce(e){let{read:t,write:r,remove:n}=e,s=()=>({...t()});for(let[i,o]of Object.entries(t()))Object.defineProperty(s,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return s.get=(i)=>t()[i],s.set=(i,o,a={})=>r?.(i,o,a),s.delete=(i,o={})=>n?.(i,o),s.getAll=()=>({...t()}),s}function X(e={}){let t={...e};return Ce({read:()=>t,write:(r,n)=>{t[r]=n},remove:(r)=>{delete t[r]}})}import{AsyncLocalStorage as En}from"async_hooks";var Qe=new En,Pe=!1,j=null;function Sn(){Pe=!0}function Me(e,t){if(!Pe){j=e;let r=t();if(r instanceof Promise)return r.finally(()=>{j=null});return j=null,r}return Qe.run({current:e},t)}function Ee(e){let t=Qe.getStore();if(t){t.current=e;return}if(j!==null)j=e}function Mt(){if(!Pe)return Pe=!0,j??void 0;return Qe.getStore()?.current??j??void 0}function kn(){let e=Mt();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 Hn={enabled:!0,level:6,threshold:1024};function Et(e){if(!e)return!1;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 An(e){if(!e)return null;let t=new Map;for(let n of e.split(",")){let[s="",...i]=n.trim().split(";"),o=i.map((a)=>/^\s*q=([\d.]+)\s*$/i.exec(a)).find(Boolean);t.set(s.trim().toLowerCase(),o?Number(o[1]):1)}let r=(n)=>(t.get(n)??t.get("*")??0)>0;if(r("gzip"))return"gzip";if(r("deflate"))return"deflate";return null}function qn(e,t,r){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(!Et(e.headers.get("content-type")))return!1;if(!e.body)return!1;let n=Number(e.headers.get("content-length")??Number.NaN);return Number.isFinite(n)?n>=r:!0}async function St(e,t,r={}){let n={...Hn,...r};if(!n.enabled)return e;let s=An(t.headers.get("accept-encoding"));if(!qn(e,s,n.threshold)){if(Et(e.headers.get("content-type"))&&!e.headers.has("content-encoding"))Ze(e.headers,"Accept-Encoding");return e}let i=Number(e.headers.get("content-length")??Number.NaN),o=Number.isFinite(i)?{stream:e.body,size:i,ended:!1}:await On(e.body,n.threshold);if(o.ended&&o.size<n.threshold){let c=new Headers(e.headers);return Ze(c,"Accept-Encoding"),new Response(o.stream,{status:e.status,statusText:e.statusText,headers:c})}let a=new Headers(e.headers);a.set("Content-Encoding",s),Ze(a,"Accept-Encoding"),a.delete("Content-Length");let u=o.stream.pipeThrough(new CompressionStream(s==="gzip"?"gzip":"deflate"));return new Response(u,{status:e.status,statusText:e.statusText,headers:a})}async function On(e,t){let r=e.getReader(),n=[],s=0,i=!1;while(s<t){let{value:a,done:u}=await r.read();if(u){i=!0;break}if(a)n.push(a),s+=a.byteLength}return{stream:new ReadableStream({start(a){for(let u of n)a.enqueue(u);if(i)a.close()},async pull(a){if(i)return;let{value:u,done:c}=await r.read();if(c){i=!0,a.close();return}if(u)a.enqueue(u)},cancel(a){return r.cancel(a)}}),size:s,ended:i}}function Ze(e,t){let r=e.get("vary");if(!r){e.set("Vary",t);return}let n=r.split(",").map((s)=>s.trim().toLowerCase());if(n.includes("*")||n.includes(t.toLowerCase()))return;e.set("Vary",`${r}, ${t}`)}var R={json:(e,t={})=>{let r=typeof t==="number"?{status:t}:t,{status:n=200,headers:s={},pretty:i=!1}=r,o=i?JSON.stringify(e,null,2):JSON.stringify(e);return new Response(o,{status:n,headers:{"Content-Type":"application/json",...s}})},noContent:(e={})=>new Response(null,{status:204,headers:e}),download:async(e,t,r={})=>{let n=Bun.file(e);if(!await n.exists())return new Response("File not found",{status:404});let i=t||e.split("/").pop()||"download",o=n.type||"application/octet-stream";return new Response(n,{status:200,headers:{"Content-Type":o,"Content-Disposition":`attachment; filename="${i}"`,"Content-Length":String(n.size),...r}})},file:async(e,t={})=>{let r=Bun.file(e);if(!await r.exists())return new Response("File not found",{status:404});let s=r.type||"application/octet-stream";return new Response(r,{status:200,headers:{"Content-Type":s,"Content-Length":String(r.size),...t}})},streamDownload:(e,t,r={})=>{let{contentType:n="application/octet-stream",headers:s={}}=r,i=new ReadableStream({async start(o){try{for await(let a of e())if(typeof a==="string")o.enqueue(new TextEncoder().encode(a));else o.enqueue(a);o.close()}catch(a){o.error(a)}}});return new Response(i,{status:200,headers:{"Content-Type":n,"Content-Disposition":`attachment; filename="${t}"`,"Transfer-Encoding":"chunked",...s}})},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 r=e.headers.get("referer")||t;return R.redirect(r)},view:(e,t=200,r={})=>new Response(e,{status:t,headers:{"Content-Type":"text/html; charset=utf-8",...r}}),text:(e,t=200,r={})=>new Response(e,{status:t,headers:{"Content-Type":"text/plain; charset=utf-8",...r}}),xml:(e,t=200,r={})=>new Response(e,{status:t,headers:{"Content-Type":"application/xml; charset=utf-8",...r}}),success:(e,t,r=200)=>{let n={success:!0};if(e!==void 0)n.data=e;if(t!==void 0)n.message=t;return R.json(n,{status:r})},error:(e,t=400,r)=>{let n={success:!1,message:e};if(r!==void 0)n.errors=r;return R.json(n,{status:t})},paginate:(e,t)=>{let{page:r,perPage:n,total:s,path:i}=t,o=Math.ceil(s/n),a=(r-1)*n+1,u=Math.min(r*n,s);return R.json({data:e,meta:{current_page:r,per_page:n,total:s,last_page:o,from:a,to:u,path:i,first_page_url:`${i}?page=1`,last_page_url:`${i}?page=${o}`,next_page_url:r<o?`${i}?page=${r+1}`:null,prev_page_url:r>1?`${i}?page=${r-1}`:null}})},created:(e,t)=>{let r={};if(t)r.Location=t;let n={success:!0};if(e!==void 0)n.data=e;return R.json(n,{status:201,headers:r})},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 r={};if(t)r["Retry-After"]=String(t);return new Response(JSON.stringify({message:e}),{status:429,headers:{"Content-Type":"application/json",...r}})}};class kt{_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,r={}){return this._cookies.push({name:e,value:t,options:r}),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:r,value:n,options:s}of this._cookies){let i=this.serializeCookie(r,n,s);t.append("Set-Cookie",i)}for(let{name:r,options:n}of this._deleteCookies){let s=this.serializeCookie(r,"",{...n,maxAge:0,expires:new Date(0)});t.append("Set-Cookie",s)}return new Response(e.body,{status:e.status,headers:t})}serializeCookie(e,t,r){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(r.maxAge!==void 0)n+=`; Max-Age=${r.maxAge}`;if(r.expires)n+=`; Expires=${r.expires.toUTCString()}`;if(r.httpOnly)n+="; HttpOnly";if(r.secure)n+="; Secure";if(r.path)n+=`; Path=${r.path}`;if(r.domain)n+=`; Domain=${r.domain}`;if(r.sameSite)n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`;return n}}function Pi(){return new kt}import $n from"process";class Ye{compiledPipelines=new Map;dependencyRegistry=new Map;singletonInstances=new Map;stats={totalExecutions:0,cacheHits:0,cacheMisses:0,shortCircuits:0,skippedMiddleware:0,averageExecutionTime:0,dependencyResolutions:0};registerDependency(e){this.dependencyRegistry.set(e.name,e)}compileMiddleware(e,t,r=[]){let n=[];for(let s=0;s<t.length;s++){let i=t[s],o=i.name||`middleware_${s}`;n.push({handler:i,name:o,skipConditions:r.filter((a)=>a.name.includes(o)||a.name==="global"),dependencies:this.extractDependencies(i),canShortCircuit:this.canShortCircuit(i),priority:s})}this.compiledPipelines.set(e,n)}async execute(e,t,r){let n=performance.now();this.stats.totalExecutions++;let s=this.compiledPipelines.get(e);if(!s)return this.stats.cacheMisses++,await r();this.stats.cacheHits++;let i={request:t,dependencies:new Map,metadata:{}};await this.resolveDependencies(i,s);let o=0,a=async()=>{if(o>=s.length)return await r();let l=s[o++];if(await this.shouldSkip(l,i))return this.stats.skippedMiddleware++,await a();let d=await l.handler(t,a);if(d instanceof Response&&l.canShortCircuit)return this.stats.shortCircuits++,d;return d},u=await a(),c=performance.now()-n;return this.updateAverageExecutionTime(c),u||new Response("Internal Server Error",{status:500})}async shouldSkip(e,t){for(let r of e.skipConditions)if(await r.condition(t))return!0;return!1}async resolveDependencies(e,t){let r=new Set;for(let n of t)for(let s of n.dependencies)r.add(s);for(let n of r){let s=this.dependencyRegistry.get(n);if(!s)continue;if(this.stats.dependencyResolutions++,s.singleton&&this.singletonInstances.has(n))e.dependencies.set(n,this.singletonInstances.get(n));else{let i=await s.factory(e);if(e.dependencies.set(n,i),s.singleton)this.singletonInstances.set(n,i)}}}extractDependencies(e){let t=e.toString(),r=[];if(t.includes("database")||t.includes("db"))r.push("database");if(t.includes("logger")||t.includes("log"))r.push("logger");if(t.includes("cache"))r.push("cache");if(t.includes("httpClient")||t.includes("http"))r.push("httpClient");return r}canShortCircuit(e){let t=e.toString();return t.includes("return")&&t.includes("Response")}updateAverageExecutionTime(e){let t=this.stats.averageExecutionTime*(this.stats.totalExecutions-1);this.stats.averageExecutionTime=(t+e)/this.stats.totalExecutions}getStats(){return{...this.stats}}clear(){this.compiledPipelines.clear(),this.singletonInstances.clear(),this.stats={totalExecutions:0,cacheHits:0,cacheMisses:0,shortCircuits:0,skippedMiddleware:0,averageExecutionTime:0,dependencyResolutions:0}}}var Bn={skipForMethods:(e)=>({name:`skip_for_methods_${e.join("_")}`,condition:(t)=>e.includes(t.request.method)}),skipForPaths:(e)=>({name:`skip_for_paths_${e.join("_").replace(/\//g,"_")}`,condition:(t)=>{let r=new URL(t.request.url);return e.some((n)=>r.pathname.startsWith(n))}}),skipForHeaders:(e)=>({name:`skip_for_headers_${Object.keys(e).join("_")}`,condition:(t)=>Object.entries(e).some(([r,n])=>t.request.headers.get(r)===n)}),skipForRoles:(e)=>({name:`skip_for_roles_${e.join("_")}`,condition:(t)=>{let r=t.request.user?.roles||[];return!e.some((n)=>r.includes(n))}}),skipForEnvironment:(e)=>({name:`skip_for_env_${e.join("_")}`,condition:()=>{let t=$n.env.NODE_ENV||"development";return e.includes(t)}})},Dn={database:(e)=>({name:"database",factory:async()=>({query:async(t)=>({rows:[]}),close:async()=>{},connectionString:e||"mock://database"}),singleton:!0}),logger:(e="info")=>({name:"logger",factory:()=>({info:(t)=>console.log(`[INFO] ${t}`),error:(t)=>console.error(`[ERROR] ${t}`),warn:(t)=>console.warn(`[WARN] ${t}`),debug:(t)=>console.debug(`[DEBUG] ${t}`),level:e}),singleton:!0}),cache:(e=1000)=>({name:"cache",factory:()=>{let t=new Map;return{get:(r)=>t.get(r),set:(r,n)=>{if(t.size>=e){let s=t.keys().next().value;t.delete(s)}t.set(r,n)},delete:(r)=>t.delete(r),clear:()=>t.clear(),size:()=>t.size}},singleton:!0}),httpClient:(e)=>({name:"httpClient",factory:()=>({get:async(t)=>fetch(e?`${e}${t}`:t),post:async(t,r)=>fetch(e?`${e}${t}`:t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),put:async(t,r)=>fetch(e?`${e}${t}`:t,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),delete:async(t)=>fetch(e?`${e}${t}`:t,{method:"DELETE"})}),singleton:!0})},Fn={auth:(e={})=>async(t,r)=>{let n=new URL(t.url);if(e.skipPaths?.some((i)=>n.pathname.startsWith(i)))return await r();if(!t.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});try{return t.user={id:"123",roles:["user"]},await r()}catch{return new Response("Invalid token",{status:401})}},rateLimit:(e)=>{let t=new Map;return async(r,n)=>{let s=r.headers.get("x-forwarded-for")||"unknown",i=Date.now(),o=i-e.windowMs;if(!t.has(s))t.set(s,[]);let u=t.get(s).filter((c)=>c>o);if(u.length>=e.maxRequests)return new Response("Too Many Requests",{status:429});return u.push(i),t.set(s,u),await n()}},cors:(e={})=>async(t,r)=>{let n=await r();if(n){let s=new Headers(n.headers);return s.set("Access-Control-Allow-Origin",e.origin||"*"),s.set("Access-Control-Allow-Methods",e.methods?.join(", ")||"GET, POST, PUT, DELETE"),s.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(n.body,{status:n.status,statusText:n.statusText,headers:s})}return n},logging:(e={})=>async(t,r)=>{let n=performance.now(),s=new URL(t.url);console.log(`[${new Date().toISOString()}] ${t.method} ${s.pathname}`);let i=await r(),o=performance.now()-n;if(i)console.log(`[${new Date().toISOString()}] ${t.method} ${s.pathname} - ${i.status} (${o.toFixed(2)}ms)`);return i}},Nn=new Ye;import{existsSync as At,readdirSync as Un,statSync as In}from"fs";import{basename as qt,extname as Ht,join as _n,resolve as Ot}from"path";var jn=[".ts",".js"],Ln=["routes","src/routes"],zn=["web","index"];function Gn(){let e=process.cwd();for(let t of Ln){let r=Ot(e,t);if(At(r)&&In(r).isDirectory())return r}return null}function $t(e,t){let r=[];if(!At(e))return r;let n=Un(e,{withFileTypes:!0});for(let s of n){if(s.name.startsWith(".")||s.name.startsWith("_"))continue;let i=_n(e,s.name);if(s.isDirectory())r.push(...$t(i,t));else if(jn.includes(Ht(s.name))){let o=e===t?"":e.slice(t.length),a=qt(s.name,Ht(s.name)),u=zn.includes(a)?o||"":`${o}/${a}`;r.push({filePath:i,prefix:u})}}return r}async function Wn(e,t,r,n){try{let s=await import(t),i=0,o=e.routes?.length||0;if(typeof s.default==="function"){let a=Vn(e,r);await s.default(a),i=(e.routes?.length||0)-o}else if(Array.isArray(s.routes))for(let a of s.routes){let u=(a.method||"GET").toLowerCase(),c=`${r}${a.path}`;if(typeof e[u]==="function")await e[u](c,a.handler),i++}if(n&&i>0)console.log(` ${r||"/"} \u2192 ${qt(t)} (${i} routes)`);return i}catch(s){return console.error(`[bun-router] Failed to load route file ${t}:`,s),0}}function Vn(e,t){if(!t)return e;let r=["get","post","put","patch","delete","options","any"];return new Proxy(e,{get(n,s){if(r.includes(s))return async(i,...o)=>n[s](`${t}${i}`,...o);if(s==="group")return async(i,o)=>{let a=i.prefix?`${t}${i.prefix}`:t;return n.group({...i,prefix:a},o)};return n[s]}})}function Bt(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||Gn();if(!t){this._apiRoutesInitialized=!0;return}let r=this.config?.verbose||!1,n=$t(t,t);if(n.length===0){this._apiRoutesInitialized=!0;return}if(r)console.log(`[bun-router] Auto-discovering API routes from ${t}:`);let s=0;for(let{filePath:i,prefix:o}of n)s+=await Wn(this,i,o,r);if(s>0&&r)console.log(`[bun-router] Registered ${s} API routes`);this._apiRoutesInitialized=!0},writable:!0,configurable:!0},routesFrom:{value(t){return this._routesDir=Ot(t),this},writable:!0,configurable:!0}})}import{join as ae,relative as et,resolve as D,dirname as Kn}from"path";import{readdirSync as Dt,statSync as Xn,existsSync as ke}from"fs";var qi={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function Jn(e){let{preserve:t=[],exclude:r=[],routes:n=[]}=e;if(!t.length)return"";return`<script data-query-preservation>
2
+ import{he,ft,e,me,V,ge,Ne,qe,He,Be,je,p,r,h,k,W,m,n,fe,g,Ue,Le,_e,l,A,O,I,yt,G,F,f,y,ze,w,Ve,C,a,We,Ge,Ke,Je,Xe,S,b,Ye,D,Qe,N,Ze,q,et,H,tt,R,rt,B,nt,wt,bt,Rt,vt,xt,Tt,K}from"./chunk-trm3jyqk.js";import{t,u,J,X,Y,Q,v,Z,ee,te,re,x,T,ne,se,ie,s,E,d,oe,j,ae,ce,st,it,ot,o,L,ye,we,be,_,le,ue}from"./chunk-7g1et0fb.js";var Os=Object.defineProperty;var $s=(i)=>i;function Bs(i,c){this[i]=$s.bind(null,c)}var Ds=(i,c)=>{for(var P in c)Os(i,P,{get:c[P],enumerable:!0,configurable:!0,set:Bs.bind(c,P)})};import{timingSafeEqual as Fs}from"crypto";function kr(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ar(i){i=i.replace(/-/g,"+").replace(/_/g,"/");while(i.length%4)i+="=";return atob(i)}class rn{secret;constructor(i){this.secret=i}sign(i,c={}){let P={alg:c.algorithm||"HS256",typ:"JWT",...c.header},M=Math.floor(Date.now()/1000),U={...i,iat:M};if(c.expiresIn){let Te=typeof c.expiresIn==="string"?this.parseTimespan(c.expiresIn):c.expiresIn;U.exp=M+Te}if(c.notBefore){let Te=typeof c.notBefore==="string"?this.parseTimespan(c.notBefore):c.notBefore;U.nbf=M+Te}if(c.issuer)U.iss=c.issuer;if(c.subject)U.sub=c.subject;if(c.audience)U.aud=c.audience;if(c.jwtid)U.jti=c.jwtid;let z=kr(JSON.stringify(P)),de=kr(JSON.stringify(U)),pe=`${z}.${de}`,Re=this.createSignature(pe,this.secret,P.alg);return`${pe}.${Re}`}verify(i,c={}){try{let P=i.split(".");if(P.length!==3)throw Error("Token structure invalid");let[M,U,z]=P,de=JSON.parse(ar(M)),pe=JSON.parse(ar(U));if(c.algorithms&&!c.algorithms.includes(de.alg))throw Error(`Algorithm ${de.alg} not allowed`);let Re=`${M}.${U}`,Te=this.createSignature(Re,this.secret,de.alg),xe=Buffer.from(z),ve=Buffer.from(Te);if(xe.length!==ve.length||!Fs(xe,ve))throw Error("Invalid signature");let Ce=Math.floor(Date.now()/1000);if(pe.exp&&!c.ignoreExpiration&&Ce>=pe.exp)throw Error("Token expired");if(pe.nbf&&Ce<pe.nbf)throw Error("Token not active yet");if(pe.iat&&pe.iat>Ce)throw Error("Token used before issued");if(c.issuer&&pe.iss!==c.issuer)throw Error("Invalid issuer");if(c.audience&&pe.aud!==c.audience)throw Error("Invalid audience");if(c.subject&&pe.sub!==c.subject)throw Error("Invalid subject");return pe}catch{return null}}decode(i){try{let c=i.split(".");if(c.length!==3)return null;let[P,M]=c;return{header:JSON.parse(ar(P)),payload:JSON.parse(ar(M))}}catch{return null}}createSignature(i,c,P){return kr(JSON.stringify({data:i,secret:c.slice(0,5),alg:P}))}parseTimespan(i){let c=i.match(/^(\d+)\s*([smhd])$/i);if(!c)return Number.parseInt(i,10)||0;let P=Number.parseInt(c[1],10);switch(c[2].toLowerCase()){case"s":return P;case"m":return P*60;case"h":return P*60*60;case"d":return P*24*60*60;default:return P}}}class nn{keys;options;constructor(i={}){this.keys=new Map,this.options={source:"header",keyName:"X-API-Key",keyPrefix:"bun_",...i}}generateKey(i,c=[],P){let M=`${this.options.keyPrefix}${this.randomString(32)}`;return this.keys.set(M,{owner:i,scopes:c,expiresAt:P?new Date(Date.now()+P*1000):void 0}),M}validateKey(i,c=[]){let P=this.keys.get(i);if(!P)return!1;if(P.expiresAt&&P.expiresAt<new Date)return!1;if(c.length>0)return c.every((M)=>P.scopes.includes(M));return!0}getKeyInfo(i){return this.keys.get(i)||null}revokeKey(i){return this.keys.delete(i)}extractFromRequest(i){let{source:c,keyName:P}=this.options;switch(c){case"header":return i.headers.get(P||"X-API-Key")||null;case"query":return new URL(i.url).searchParams.get(P||"api_key")||null;case"cookie":if(i.cookies){let M=P||"api_key";if(typeof i.cookies.get==="function")return i.cookies.get(M)||null;return i.cookies[M]||null}return null;default:return null}}randomString(i){let P="";for(let M=0;M<i;M++)P+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62));return P}}class sn{config;constructor(i){this.config=i}getAuthorizationUrl(i={}){let c=new URLSearchParams({client_id:this.config.clientId,redirect_uri:this.config.redirectUri,response_type:"code",...i});if(this.config.scope)c.set("scope",this.config.scope);if(this.config.state)c.set("state",this.config.state);return`${this.config.authorizeUrl}?${c.toString()}`}async exchangeCodeForToken(i){let c=new URLSearchParams({grant_type:"authorization_code",code:i,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret}),P=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c.toString()});if(!P.ok)throw Error(`OAuth token exchange failed: ${P.status} ${P.statusText}`);return await P.json()}async refreshToken(i){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:i,client_id:this.config.clientId,client_secret:this.config.clientSecret}),P=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c.toString()});if(!P.ok)throw Error(`OAuth token refresh failed: ${P.status} ${P.statusText}`);return await P.json()}}var Ns={JWT:rn,ApiKeyManager:nn,OAuth2Helper:sn},Us=Ns;var ln={};Ds(ln,{AuthenticationException:()=>J,AuthorizationException:()=>X,BugsnagReporter:()=>qr,BusinessLogicException:()=>ne,CircuitBreaker:()=>ur,CircuitBreakerHttpClient:()=>on,CircuitBreakerOpenException:()=>T,CircuitBreakerPresets:()=>js,CircuitBreakerRegistry:()=>Ft,CircularDependencyException:()=>d,ConfigurationException:()=>se,CustomReporter:()=>an,DatabaseException:()=>re,DegradationStrategies:()=>Js,ErrorFactory:()=>s,ErrorReportingManager:()=>Vt,ErrorReportingPresets:()=>Ws,ExternalServiceException:()=>x,FileSystemException:()=>ie,GracefulDegradationManager:()=>Jt,HandlerResolutionException:()=>ae,InternalServerException:()=>ee,MethodNotAllowedException:()=>Q,MiddlewareConfigurationException:()=>oe,ModelBindingException:()=>ce,NotFoundException:()=>Y,RateLimitException:()=>Z,RouteConflictException:()=>E,RouteNotFoundException:()=>j,RouterErrorFactory:()=>ot,RouterException:()=>t,SentryReporter:()=>Ar,ServiceHealthMonitor:()=>Or,ServiceUnavailableException:()=>te,TimeoutException:()=>v,ValidationException:()=>u,circuitBreaker:()=>Is,createAdvancedErrorHandler:()=>cn,createCircuitBreaker:()=>Ls,createCircuitBreakerMiddleware:()=>_s,createErrorReporting:()=>Gs,createGracefulDegradationMiddleware:()=>Vs,detectRouteConflicts:()=>it,findSimilarRoutes:()=>st,globalCircuitBreakerRegistry:()=>Hr,withCircuitBreaker:()=>zs});class ur{config;state="CLOSED";metrics;nextAttemptTime;halfOpenCallCount=0;recentRequests=[];constructor(i){let c={failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000};this.config={...c,...i},this.metrics={totalRequests:0,successfulRequests:0,failedRequests:0,timeouts:0,averageResponseTime:0,state:this.state,consecutiveFailures:0,consecutiveSuccesses:0},setInterval(()=>this.cleanupOldRequests(),this.config.monitoringPeriod/4).unref?.()}async execute(i){if(this.state==="OPEN")if(this.nextAttemptTime&&new Date<this.nextAttemptTime){let U=new T(this.config.name,this.nextAttemptTime,i.context);if(i.fallback)try{return await i.fallback()}catch(z){console.error(z)}throw U}else this.transitionToHalfOpen();if(this.state==="HALF_OPEN"&&this.halfOpenCallCount>=this.config.halfOpenMaxCalls){let U=new T(this.config.name,this.nextAttemptTime||new Date(Date.now()+this.config.recoveryTimeout),i.context);if(i.fallback)try{return await i.fallback()}catch(z){throw console.error(z),U}throw U}let c=Date.now(),P,M=null;try{if(this.state==="HALF_OPEN")this.halfOpenCallCount++;let U=i.timeout||this.config.timeout,z=new Promise((de,pe)=>{setTimeout(()=>{pe(new v(`Circuit breaker timeout for ${this.config.name}`,U,i.context))},U)});return P=await Promise.race([i.execute(),z]),this.onSuccess(Date.now()-c),P}catch(U){if(M=U,this.onFailure(M,Date.now()-c),i.fallback)try{return await i.fallback()}catch(z){throw console.error(z),M}else throw M}}getState(){return this.state}getMetrics(){return{...this.metrics,state:this.state,nextAttemptTime:this.nextAttemptTime}}forceOpen(){this.transitionToOpen()}forceClosed(){this.transitionToClosed()}reset(){this.metrics={totalRequests:0,successfulRequests:0,failedRequests:0,timeouts:0,averageResponseTime:0,state:this.state,consecutiveFailures:0,consecutiveSuccesses:0},this.recentRequests=[]}onSuccess(i){if(this.metrics.totalRequests++,this.metrics.successfulRequests++,this.metrics.consecutiveSuccesses++,this.metrics.consecutiveFailures=0,this.metrics.lastSuccessTime=new Date,this.updateAverageResponseTime(i),this.recentRequests.push({timestamp:new Date,success:!0,responseTime:i}),this.state==="HALF_OPEN"){if(this.metrics.consecutiveSuccesses>=this.config.halfOpenMaxCalls)this.transitionToClosed()}if(this.config.onSuccess)this.config.onSuccess(this.config.name)}onFailure(i,c){if(this.metrics.totalRequests++,this.metrics.failedRequests++,this.metrics.consecutiveFailures++,this.metrics.consecutiveSuccesses=0,this.metrics.lastFailureTime=new Date,i instanceof v)this.metrics.timeouts++;if(this.updateAverageResponseTime(c),this.recentRequests.push({timestamp:new Date,success:!1,responseTime:c}),this.shouldTrip(i)){if(this.state==="CLOSED")this.transitionToOpen();else if(this.state==="HALF_OPEN")this.transitionToOpen()}if(this.config.onFailure)this.config.onFailure(i,this.config.name)}shouldTrip(i){if(this.config.shouldTripOnError&&!this.config.shouldTripOnError(i))return!1;if(this.metrics.consecutiveFailures>=this.config.failureThreshold)return!0;let c=this.getRecentRequests();if(c.length>=this.config.minimumRequests){if(c.filter((U)=>!U.success).length/c.length*100>=this.config.errorThresholdPercentage)return!0}return!1}transitionToClosed(){if(this.state="CLOSED",this.nextAttemptTime=void 0,this.halfOpenCallCount=0,this.metrics.state=this.state,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}transitionToOpen(){if(this.state="OPEN",this.nextAttemptTime=new Date(Date.now()+this.config.recoveryTimeout),this.halfOpenCallCount=0,this.metrics.state=this.state,this.metrics.nextAttemptTime=this.nextAttemptTime,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}transitionToHalfOpen(){if(this.state="HALF_OPEN",this.halfOpenCallCount=0,this.metrics.state=this.state,this.config.onStateChange)this.config.onStateChange(this.state,this.config.name)}updateAverageResponseTime(i){if(this.metrics.totalRequests===1)this.metrics.averageResponseTime=i;else this.metrics.averageResponseTime=0.1*i+0.9*this.metrics.averageResponseTime}getRecentRequests(){let i=new Date(Date.now()-this.config.monitoringPeriod);return this.recentRequests.filter((c)=>c.timestamp>i)}cleanupOldRequests(){let i=new Date(Date.now()-this.config.monitoringPeriod);this.recentRequests=this.recentRequests.filter((c)=>c.timestamp>i)}}class Ft{breakers=new Map;configs=new Map;register(i){let c=new ur(i);return this.breakers.set(i.name,c),this.configs.set(i.name,i),c}get(i){return this.breakers.get(i)}async execute(i,c){let P=this.breakers.get(i);if(!P)throw Error(`Circuit breaker '${i}' not found`);return P.execute(c)}getAllMetrics(){let i={};for(let[c,P]of this.breakers)i[c]=P.getMetrics();return i}getBreakersByState(i){let c=[];for(let[P,M]of this.breakers)if(M.getState()===i)c.push(P);return c}forceAllClosed(){for(let i of this.breakers.values())i.forceClosed()}resetAll(){for(let i of this.breakers.values())i.reset()}remove(i){return this.configs.delete(i),this.breakers.delete(i)}getNames(){return Array.from(this.breakers.keys())}}function Is(i){let c=new ur(i);return function(P,M,U){let z=U.value;return U.value=async function(...de){return c.execute({execute:()=>z.apply(this,de),context:{method:M,timestamp:new Date}})},U}}class on{registry;constructor(i){this.registry=i||new Ft}async fetch(i,c={}){let{circuitBreaker:P,fallback:M,context:U,...z}=c,de;if(typeof P==="string")de=P;else if(P){if(de=P.name,!this.registry.get(de))this.registry.register(P)}else if(de=`http-${new URL(i).hostname}`,!this.registry.get(de))this.registry.register({name:de,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000});return this.registry.execute(de,{execute:async()=>{let pe=await fetch(i,z);if(pe.status>=500)throw new x(`HTTP ${pe.status}: ${pe.statusText}`,de,i,pe.status,void 0,U);return pe},fallback:M,context:U})}getRegistry(){return this.registry}}function _s(i){return async(c,P)=>{let M=c.context?.serviceName;if(!M)return P();let U=i.get(M);if(!U)return P();return U.execute({execute:P,context:{requestId:c.requestId,route:c.route,method:c.method,url:c.url}})}}var js={critical:(i)=>({name:i,failureThreshold:3,recoveryTimeout:30000,timeout:5000,monitoringPeriod:30000,minimumRequests:5,errorThresholdPercentage:30,halfOpenMaxCalls:2,resetTimeout:30000}),standard:(i)=>({name:i,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000}),tolerant:(i)=>({name:i,failureThreshold:10,recoveryTimeout:120000,timeout:60000,monitoringPeriod:120000,minimumRequests:20,errorThresholdPercentage:70,halfOpenMaxCalls:5,resetTimeout:120000}),database:(i)=>({name:i,failureThreshold:3,recoveryTimeout:60000,timeout:1e4,monitoringPeriod:60000,minimumRequests:5,errorThresholdPercentage:40,halfOpenMaxCalls:2,resetTimeout:60000,shouldTripOnError:(c)=>!(c.message.includes("validation")||c.message.includes("constraint"))}),externalApi:(i)=>({name:i,failureThreshold:5,recoveryTimeout:90000,timeout:15000,monitoringPeriod:90000,minimumRequests:8,errorThresholdPercentage:60,halfOpenMaxCalls:3,resetTimeout:90000,shouldTripOnError:(c)=>{if(c instanceof x)return c.statusCode>=500;return!0}})},Hr=new Ft;function Ls(i){return Hr.register(i)}async function zs(i,c){return Hr.execute(i,c)}class Ar{config;sentry;constructor(i){this.config=i,this.initializeSentry()}async initializeSentry(){try{let i=await import("@sentry/node");i.init({dsn:this.config.dsn,environment:this.config.environment||"production",release:this.config.release,sampleRate:this.config.sampleRate||1,beforeSend:(c,P)=>{let M=P.originalException;if(M&&this.config.beforeSend)return this.config.beforeSend(M,M.context)?c:null;return c},ignoreErrors:this.config.filters?.ignoreErrors,denyUrls:this.config.filters?.ignoreUrls,allowUrls:this.config.filters?.allowUrls,initialScope:{tags:this.config.tags,extra:this.config.extra,user:this.config.user},maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||100,tracesSampleRate:this.config.performance?.tracesSampleRate||0.1}),this.sentry=i}catch(i){console.warn("Failed to initialize Sentry:",i)}}async report(i,c){if(!this.sentry||!this.config.enabled)return null;try{if(this.shouldIgnoreError(i))return null;let P={...i.context,...c};return this.sentry.withScope((M)=>{if(P.requestId)M.setTag("requestId",P.requestId);if(P.userId)M.setUser({id:P.userId});if(P.traceId)M.setTag("traceId",P.traceId);if(P.route)M.setTag("route",P.route);if(P.method)M.setTag("method",P.method);M.setTag("errorCode",i.code),M.setTag("severity",i.severity),M.setTag("category",i.category),M.setLevel(this.mapSeverityToLevel(i.severity)),M.setExtra("statusCode",i.statusCode),M.setExtra("retryable",i.retryable),M.setExtra("timestamp",i.timestamp),M.setExtra("context",P);let U=this.generateFingerprint(i);if(U.length>0)M.setFingerprint(U);return this.sentry.captureException(i)})}catch(P){return console.error("Failed to report error to Sentry:",P),null}}addBreadcrumb(i,c="default",P="info",M){if(!this.sentry||!this.config.breadcrumbs?.enabled)return;this.sentry.addBreadcrumb({message:i,category:c,level:P,data:M,timestamp:Date.now()/1000})}setUser(i){if(!this.sentry)return;this.sentry.setUser(i)}setTag(i,c){if(!this.sentry)return;this.sentry.setTag(i,c)}setExtra(i,c){if(!this.sentry)return;this.sentry.setExtra(i,c)}setContext(i,c){if(!this.sentry)return;this.sentry.setContext(i,c)}async close(i=2000){if(!this.sentry)return!0;return this.sentry.close(i)}shouldIgnoreError(i){let c=this.config.filters;if(!c)return!1;if(c.ignoreCodes?.includes(i.code))return!0;if(c.ignoreErrors?.some((P)=>{if(typeof P==="string")return i.message.includes(P);return P.test(i.message)}))return!0;return!1}mapSeverityToLevel(i){switch(i){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}generateFingerprint(i){let c=[];if(c.push(i.code),c.push(i.category),i.context.route)c.push(i.context.route);return c}}class qr{config;bugsnag;constructor(i){this.config=i,this.initializeBugsnag()}async initializeBugsnag(){try{let i=await import("@bugsnag/js");i.start({apiKey:this.config.apiKey,appVersion:this.config.release,releaseStage:this.config.environment||"production",enabledReleaseStages:["production","staging"],maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||25,onError:(c)=>{let P=c.originalError;if(P&&this.config.beforeSend)return this.config.beforeSend(P,P.context)!==null;return!this.shouldIgnoreError(P)}}),this.bugsnag=i}catch(i){console.warn("Failed to initialize Bugsnag:",i)}}async report(i,c){if(!this.bugsnag||!this.config.enabled)return null;try{if(this.shouldIgnoreError(i))return null;let P={...i.context,...c};return this.bugsnag.notify(i,(M)=>{if(M.severity=this.mapSeverityToBugsnag(i.severity),M.context=P.route||P.url,P.userId)M.setUser(P.userId,void 0,void 0);M.addMetadata("error",{code:i.code,category:i.category,statusCode:i.statusCode,retryable:i.retryable,timestamp:i.timestamp}),M.addMetadata("request",{requestId:P.requestId,method:P.method,url:P.url,userAgent:P.userAgent,ip:P.ip}),M.groupingHash=this.generateGroupingHash(i)}),"reported"}catch(P){return console.error("Failed to report error to Bugsnag:",P),null}}addBreadcrumb(i,c="manual",P="info",M){if(!this.bugsnag||!this.config.breadcrumbs?.enabled)return;this.bugsnag.leaveBreadcrumb(i,M,c)}setUser(i){if(!this.bugsnag)return;this.bugsnag.setUser(i.id,i.email,i.username)}setTag(i,c){if(!this.bugsnag)return;this.bugsnag.addMetadata("tags",{[i]:c})}setExtra(i,c){if(!this.bugsnag)return;this.bugsnag.addMetadata("extra",{[i]:c})}setContext(i,c){if(!this.bugsnag)return;this.bugsnag.addMetadata(i,c)}async close(){return!0}shouldIgnoreError(i){let c=this.config.filters;if(!c)return!1;if(c.ignoreCodes?.includes(i.code))return!0;if(c.ignoreErrors?.some((P)=>{if(typeof P==="string")return i.message.includes(P);return P.test(i.message)}))return!0;return!1}mapSeverityToBugsnag(i){switch(i){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"error";default:return"warning"}}generateGroupingHash(i){return`${i.code}-${i.category}-${i.context.route||"unknown"}`}}class an{config;reportHandler;constructor(i,c){this.config=i,this.reportHandler=c}async report(i,c){if(!this.config.enabled)return null;try{let P={...i.context,...c};if(this.config.beforeSend){if(!this.config.beforeSend(i,P))return null}let M={error:i,context:P,level:this.mapSeverityToLevel(i.severity),tags:this.config.tags,extra:this.config.extra,user:this.config.user};return await this.reportHandler(M)}catch(P){return console.error("Failed to report error with custom handler:",P),null}}addBreadcrumb(){}setUser(){}setTag(){}setExtra(){}setContext(){}async close(){return!0}mapSeverityToLevel(i){switch(i){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}}class Vt{reporters=[];breadcrumbs=[];maxBreadcrumbs=50;constructor(i){this.initializeReporters(i)}initializeReporters(i){for(let c of i){if(!c.enabled)continue;switch(c.service){case"sentry":this.reporters.push(new Ar(c));break;case"bugsnag":this.reporters.push(new qr(c));break;case"custom":break}}}addReporter(i){this.reporters.push(i)}async report(i,c){let P=[];this.addBreadcrumb(`Error occurred: ${i.message}`,"error",{code:i.code,severity:i.severity});let M=this.reporters.map(async(U)=>{try{let z=await U.report(i,c);if(z)P.push(z)}catch(z){console.error("Reporter failed:",z)}});return await Promise.allSettled(M),P}addBreadcrumb(i,c="default",P){if(this.breadcrumbs.push({message:i,timestamp:new Date,data:{category:c,...P}}),this.breadcrumbs.length>this.maxBreadcrumbs)this.breadcrumbs=this.breadcrumbs.slice(-this.maxBreadcrumbs);this.reporters.forEach((M)=>{M.addBreadcrumb(i,c,"info",P)})}setUser(i){this.reporters.forEach((c)=>c.setUser(i))}setTag(i,c){this.reporters.forEach((P)=>P.setTag(i,c))}setExtra(i,c){this.reporters.forEach((P)=>P.setExtra(i,c))}setContext(i,c){this.reporters.forEach((P)=>P.setContext(i,c))}async close(i=5000){let c=this.reporters.map((M)=>M.close(i));return(await Promise.allSettled(c)).every((M)=>M.status==="fulfilled"&&M.value)}getBreadcrumbs(){return[...this.breadcrumbs]}}function Gs(i){return new Vt(i)}var Ws={sentry:(i,c="production")=>({enabled:!0,service:"sentry",dsn:i,environment:c,sampleRate:1,breadcrumbs:{enabled:!0,maxBreadcrumbs:100},performance:{enabled:!0,tracesSampleRate:0.1},filters:{ignoreErrors:["Non-Error promise rejection captured","ResizeObserver loop limit exceeded"],ignoreCodes:["VALIDATION_ERROR"]}}),bugsnag:(i,c="production")=>({enabled:!0,service:"bugsnag",apiKey:i,environment:c,breadcrumbs:{enabled:!0,maxBreadcrumbs:25},filters:{ignoreCodes:["VALIDATION_ERROR"]}}),development:()=>({enabled:!1,service:"custom",environment:"development"})};class Or{healthStatus=new Map;healthCheckIntervals=new Map;config;constructor(i){this.config=i,this.initializeHealthChecks()}initializeHealthChecks(){for(let[i,c]of Object.entries(this.config.healthChecks)){if(!c.enabled)continue;this.healthStatus.set(i,{name:i,status:"healthy",lastCheck:new Date,responseTime:0,errorRate:0,availability:100,consecutiveFailures:0});let P=setInterval(()=>this.performHealthCheck(i,c),c.interval);P.unref?.(),this.healthCheckIntervals.set(i,P)}}async performHealthCheck(i,c){let P=Date.now(),M=!1;try{let z=new AbortController,de=setTimeout(()=>z.abort(),c.timeout),pe=await fetch(c.endpoint,{signal:z.signal,headers:c.headers,method:"GET"});if(clearTimeout(de),M=c.expectedStatus.includes(pe.status),M&&c.expectedBody){let Re=await pe.text();if(typeof c.expectedBody==="string")M=Re.includes(c.expectedBody);else M=c.expectedBody.test(Re)}}catch(z){console.error(z),M=!1}let U=Date.now()-P;if(this.updateHealthStatus(i,M,U),M&&c.onHealthy)c.onHealthy();else if(!M&&c.onUnhealthy)c.onUnhealthy(Error(`Health check failed for ${i}`))}updateHealthStatus(i,c,P){let M=this.healthStatus.get(i);if(!M)return;let U={...M,lastCheck:new Date,responseTime:P,consecutiveFailures:c?0:M.consecutiveFailures+1};if(U.consecutiveFailures===0)U.status="healthy";else if(U.consecutiveFailures<3)U.status="degraded";else U.status="unhealthy";let z=c?1:0;U.availability=M.availability*0.9+z*10,this.healthStatus.set(i,U)}getServiceHealth(i){return this.healthStatus.get(i)}getAllServiceHealth(){return Array.from(this.healthStatus.values())}isServiceHealthy(i){return this.healthStatus.get(i)?.status==="healthy"}isServiceDegraded(i){return this.healthStatus.get(i)?.status==="degraded"}stop(){for(let i of this.healthCheckIntervals.values())clearInterval(i);this.healthCheckIntervals.clear()}}class Jt{config;healthMonitor;cache=new Map;metrics=new Map;constructor(i){this.config=i,this.healthMonitor=new Or(i)}async handleFailure(i,c,P,M){if(!this.config.enabled)throw c;let U=this.config.fallbackStrategies[i];if(!U)throw c;let z={request:P,serviceName:i,error:c,attemptCount:1,startTime:new Date};return this.executeFallbackStrategy(U,z,M)}async executeFallbackStrategy(i,c,P){if(c.attemptCount<=i.retries)try{if(c.attemptCount>1){let z=this.calculateBackoffDelay(i.backoff,c.attemptCount);await this.sleep(z)}let M=new Promise((z,de)=>{setTimeout(()=>de(Error("Timeout")),i.timeout)}),U=await Promise.race([P(),M]);return this.updateMetrics(c.serviceName,!0,Date.now()-c.startTime.getTime()),U}catch(M){if(console.error(M),c.attemptCount++,c.attemptCount<=i.retries)return this.executeFallbackStrategy(i,c,P)}switch(this.updateMetrics(c.serviceName,!1,Date.now()-c.startTime.getTime()),i.type){case"cache":return this.handleCacheFallback(i,c);case"static":return this.handleStaticFallback(i,c);case"simplified":return this.handleSimplifiedFallback(i,c);case"redirect":return this.handleRedirectFallback(i,c);case"custom":return this.handleCustomFallback(i,c);default:throw c.error}}async handleCacheFallback(i,c){if(!i.cacheConfig)throw c.error;let P=this.generateCacheKey(i.cacheConfig.key,c),M=this.cache.get(P);if(M&&(M.expires>new Date||i.cacheConfig.staleWhileRevalidate)){let U=new Headers({"Content-Type":"application/json","X-Cache":"HIT","X-Degraded":"true","X-Service-Status":this.healthMonitor.getServiceHealth(c.serviceName)?.status||"unknown"});if(i.cacheConfig.staleWhileRevalidate&&M.expires<=new Date)U.set("X-Cache","STALE");return new Response(JSON.stringify(M.data),{status:200,headers:U})}throw c.error}async handleStaticFallback(i,c){if(!i.staticResponse)throw c.error;let P=new Headers(i.staticResponse.headers||{});return P.set("X-Degraded","true"),P.set("X-Fallback-Type","static"),P.set("X-Service-Status",this.healthMonitor.getServiceHealth(c.serviceName)?.status||"unknown"),new Response(typeof i.staticResponse.body==="string"?i.staticResponse.body:JSON.stringify(i.staticResponse.body),{status:i.staticResponse.status,headers:P})}async handleSimplifiedFallback(i,c){let P={message:"Service temporarily unavailable. Showing simplified view.",status:"degraded",timestamp:new Date().toISOString(),requestId:c.request.requestId};return new Response(JSON.stringify(P),{status:200,headers:{"Content-Type":"application/json","X-Degraded":"true","X-Fallback-Type":"simplified","X-Service-Status":this.healthMonitor.getServiceHealth(c.serviceName)?.status||"unknown"}})}async handleRedirectFallback(i,c){if(!i.redirectConfig)throw c.error;return new Response(null,{status:i.redirectConfig.permanent?301:302,headers:{Location:i.redirectConfig.url,"X-Degraded":"true","X-Fallback-Type":"redirect"}})}async handleCustomFallback(i,c){if(!i.fallbackHandler)throw c.error;try{let P=await i.fallbackHandler(c.error,c.error.context);return P.headers.set("X-Degraded","true"),P.headers.set("X-Fallback-Type","custom"),P.headers.set("X-Service-Status",this.healthMonitor.getServiceHealth(c.serviceName)?.status||"unknown"),P}catch(P){throw console.error(P),c.error}}cacheResponse(i,c,P,M){let U=this.config.fallbackStrategies[i];if(U?.type==="cache"&&U.cacheConfig){let z=this.generateCacheKey(c,{serviceName:i});this.cache.set(z,{data:P,expires:new Date(Date.now()+M*1000)})}}getServiceMetrics(i){let c=this.metrics.get(i);if(!c||c.requests===0)return{errorRate:0,avgResponseTime:0,totalRequests:0};return{errorRate:c.errors/c.requests*100,avgResponseTime:c.totalTime/c.requests,totalRequests:c.requests}}getSystemHealth(){let i=this.healthMonitor.getAllServiceHealth(),c=i.filter((U)=>U.status==="unhealthy").length,P=i.filter((U)=>U.status==="degraded").length,M="healthy";if(c>0)M=c>i.length/2?"unhealthy":"degraded";else if(P>0)M="degraded";return{status:M,services:i}}calculateBackoffDelay(i,c){if(i.type==="fixed")return i.delay;let P=i.delay*2**(c-1);return Math.min(P,i.maxDelay||30000)}generateCacheKey(i,c){return i.replace("{service}",c.serviceName).replace("{url}",c.request.url).replace("{method}",c.request.method).replace("{userId}",String(c.request.user?.id||"anonymous"))}updateMetrics(i,c,P){let M=this.metrics.get(i)||{requests:0,errors:0,totalTime:0};if(M.requests++,M.totalTime+=P,!c)M.errors++;this.metrics.set(i,M)}sleep(i){return new Promise((c)=>setTimeout(c,i))}stop(){this.healthMonitor.stop()}}function Vs(i){let c=new Jt(i);return async(P,M)=>{try{let U=await M(),z=P.context?.serviceName;if(z&&U.ok){let de=i.fallbackStrategies[z];if(de?.type==="cache"&&de.cacheConfig)try{let pe=await U.clone().json();c.cacheResponse(z,de.cacheConfig.key,pe,de.cacheConfig.ttl)}catch{}}return U}catch(U){let z=P.context?.serviceName;if(z&&U instanceof Error){let de=U;try{return await c.handleFailure(z,de,P,M)}catch(pe){throw console.error(pe),U}}throw U}}}var Js={cacheFirst:(i=3600,c=!0)=>({type:"cache",priority:1,timeout:5000,retries:2,backoff:{type:"exponential",delay:1000,maxDelay:5000},cacheConfig:{key:"{service}:{url}:{method}",ttl:i,staleWhileRevalidate:c}}),staticFallback:(i,c=200)=>({type:"static",priority:2,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},staticResponse:{status:c,body:i,headers:{"Content-Type":"application/json"}}}),simplifiedView:()=>({type:"simplified",priority:3,timeout:1000,retries:0,backoff:{type:"fixed",delay:0}}),redirectToMaintenance:(i)=>({type:"redirect",priority:4,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},redirectConfig:{url:i,permanent:!1}})};class un{errorReporting;gracefulDegradation;circuitBreakerRegistry;config;constructor(i={}){this.config={development:!1,includeStackTrace:!1,sanitizeErrors:!0,logErrors:!0,...i},this.initializeComponents()}initializeComponents(){if(this.config.errorReporting?.length)this.errorReporting=new Vt(this.config.errorReporting);if(this.config.gracefulDegradation?.enabled)this.gracefulDegradation=new Jt(this.config.gracefulDegradation);if(this.config.circuitBreakers?.length){this.circuitBreakerRegistry=new Ft;for(let i of this.config.circuitBreakers)this.circuitBreakerRegistry.register(i)}}middleware(){return async(i,c)=>{try{let P={requestId:i.requestId,userId:i.user?.id,traceId:i.traceId,spanId:i.spanId,route:i.params?.route||i.url,method:i.method,url:i.url,userAgent:i.userAgent?.()||void 0,ip:i.ip?.()||void 0,timestamp:new Date};if(i.context={...i.context,errorContext:P},this.circuitBreakerRegistry&&i.context?.serviceName){let M=this.circuitBreakerRegistry.get(i.context.serviceName);if(M)return await M.execute({execute:c,context:P})}return await c()}catch(P){return this.handleError(P,i)}}}async handleError(i,c){let P=this.normalizeError(i,c);if(this.errorReporting)this.errorReporting.addBreadcrumb(`Error in ${c.method} ${c.url}`,"error",{code:P.code,severity:P.severity,statusCode:P.statusCode});if(this.config.logErrors)this.logError(P,c);if(this.gracefulDegradation&&c.context?.serviceName)try{return await this.gracefulDegradation.handleFailure(c.context.serviceName,P,c,async()=>{throw P})}catch{}if(this.errorReporting)try{await this.errorReporting.report(P,P.context)}catch(U){console.error("Failed to report error:",U)}if(this.config.globalErrorHandler)try{return await this.config.globalErrorHandler(P,c)}catch(U){console.error("Global error handler failed:",U)}let M=this.config.customErrorPages?.[P.statusCode];if(M)try{if(typeof M==="string")return new Response(M,{status:P.statusCode,headers:{"Content-Type":"text/html"}});else return await M(P,c)}catch(U){console.error("Custom error page failed:",U)}return this.createErrorResponse(P,c)}normalizeError(i,c){let P={requestId:c.requestId,userId:c.user?.id,traceId:c.traceId,spanId:c.spanId,route:c.params?.route||c.url,method:c.method,url:c.url,userAgent:c.userAgent?.()||void 0,ip:c.ip?.()||void 0,timestamp:new Date,metadata:c.context};if(i instanceof t)return i;if(i instanceof Error){if(i.name==="ValidationError")return s.validation(i.message,{},P);if(i.name==="UnauthorizedError"||i.message.includes("unauthorized"))return s.authentication(i.message,P);if(i.name==="ForbiddenError"||i.message.includes("forbidden"))return s.authorization(i.message,[],P);if(i.name==="NotFoundError"||i.message.includes("not found"))return s.notFound(void 0,void 0,P);if(i.name==="TimeoutError"||i.message.includes("timeout"))return s.timeout(30000,i.message,P);return s.internalServer(i.message,i,P)}if(typeof i==="string")return s.internalServer(i,void 0,P);return s.internalServer("An unknown error occurred",void 0,P)}createErrorResponse(i,c){let P=this.config.development,M=this.config.includeStackTrace||P,U=this.config.sanitizeErrors&&!P,z=i.message;if(U&&i.statusCode>=500)z="An internal server error occurred";let de={error:{code:i.code,message:z,statusCode:i.statusCode,timestamp:i.timestamp.toISOString(),requestId:i.context.requestId,traceId:i.context.traceId}};if(P)de.error.category=i.category,de.error.severity=i.severity,de.error.retryable=i.retryable,de.error.context=i.context;if(M){if(de.error.stack=i.stack,i.cause)de.error.cause={name:i.cause.name,message:i.cause.message,stack:i.cause.stack}}if("fields"in i)de.error.fields=i.fields;if("allowedMethods"in i)de.error.allowedMethods=i.allowedMethods;if("retryAfter"in i)de.error.retryAfter=i.retryAfter;let pe=new Headers({"Content-Type":"application/json","X-Error-Code":i.code,"X-Request-ID":i.context.requestId||"","X-Trace-ID":i.context.traceId||""});if("allowedMethods"in i)pe.set("Allow",i.allowedMethods.join(", "));if("retryAfter"in i)pe.set("Retry-After",i.retryAfter.toString());if("limit"in i)pe.set("X-RateLimit-Limit",i.limit.toString()),pe.set("X-RateLimit-Remaining",i.remaining.toString());return new Response(JSON.stringify(de),{status:i.statusCode,headers:pe})}logError(i,c){let P={error:i.toJSON(),request:{method:c.method,url:c.url,headers:Object.fromEntries(c.headers.entries()),userAgent:c.userAgent?.()||void 0,ip:c.ip?.()||void 0,requestId:c.requestId,traceId:c.traceId}};switch(i.severity){case"critical":console.error("[CRITICAL ERROR]",P);break;case"high":console.error("[ERROR]",P);break;case"medium":console.warn("[WARNING]",P);break;case"low":console.warn("[INFO]",P);break;default:console.error("[ERROR]",P)}}getStats(){return{errorReporting:this.errorReporting?{breadcrumbs:this.errorReporting.getBreadcrumbs().length}:void 0,gracefulDegradation:this.gracefulDegradation?this.gracefulDegradation.getSystemHealth():void 0,circuitBreakers:this.circuitBreakerRegistry?this.circuitBreakerRegistry.getAllMetrics():void 0}}async cleanup(){if(this.errorReporting)await this.errorReporting.close();if(this.gracefulDegradation)this.gracefulDegradation.stop()}}function cn(i={}){let c=new un(i);return{middleware:c.middleware(),getStats:()=>c.getStats(),cleanup:()=>c.cleanup()}}function Nt(i){if(!i.includes("%"))return i;try{return decodeURIComponent(i)}catch{return i}}function cr(i){let{read:c,write:P,remove:M}=i,U=()=>({...c()});for(let[z,de]of Object.entries(c()))Object.defineProperty(U,z,{value:de,writable:!0,enumerable:!0,configurable:!0});return U.get=(z)=>c()[z],U.set=(z,de,pe={})=>P?.(z,de,pe),U.delete=(z,de={})=>M?.(z,de),U.getAll=()=>({...c()}),U}function Ut(i={}){let c={...i};return cr({read:()=>c,write:(P,M)=>{c[P]=M},remove:(P)=>{delete c[P]}})}import{AsyncLocalStorage as Ks}from"async_hooks";var $r=new Ks,lr=!1,At=null;function Xs(){lr=!0}function dr(i,c){if(!lr){At=i;let P=c();if(P instanceof Promise)return P.finally(()=>{At=null});return At=null,P}return $r.run({current:i},c)}function pr(i){let c=$r.getStore();if(c){c.current=i;return}if(At!==null)At=i}function dn(){if(!lr)return lr=!0,At??void 0;return $r.getStore()?.current??At??void 0}function Qs(){let i=dn();if(!i)throw Error("request() called outside a request scope. It can only be invoked from within a route handler or middleware.");return i}var pn={enabled:!0,level:6,threshold:1024};function hn(i){if(!i)return!1;let c=i.split(";")[0]?.trim().toLowerCase()??"";if(c==="text/event-stream")return!1;if(c.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(c)}function Zs(i){if(!i)return null;let c=new Map;for(let M of i.split(",")){let[U="",...z]=M.trim().split(";"),de=z.map((pe)=>/^\s*q=([\d.]+)\s*$/i.exec(pe)).find(Boolean);c.set(U.trim().toLowerCase(),de?Number(de[1]):1)}let P=(M)=>(c.get(M)??c.get("*")??0)>0;if(P("gzip"))return"gzip";if(P("deflate"))return"deflate";return null}function Ys(i,c,P){if(!c)return!1;if(i.status===204||i.status===304||i.status===206)return!1;if(i.headers.has("content-encoding"))return!1;if(!hn(i.headers.get("content-type")))return!1;if(!i.body)return!1;let M=Number(i.headers.get("content-length")??Number.NaN);return Number.isFinite(M)?M>=P:!0}function Br(i,c,P={}){if(!(P.enabled??pn.enabled))return i;let U=P.threshold??pn.threshold,z=Zs(c.headers.get("accept-encoding"));if(!Ys(i,z,U)){if(hn(i.headers.get("content-type"))&&!i.headers.has("content-encoding"))Dr(i.headers,"Accept-Encoding");return i}let de=Number(i.headers.get("content-length")??Number.NaN);if(!Number.isFinite(de))return ei(i,z,U);return gn(i,i.body,z)}async function Io(i,c,P={}){return Br(i,c,P)}async function ei(i,c,P){let M=await ti(i.body,P);if(M.ended&&M.size<P){let U=new Headers(i.headers);return Dr(U,"Accept-Encoding"),new Response(M.stream,{status:i.status,statusText:i.statusText,headers:U})}return gn(i,M.stream,c)}function gn(i,c,P){let M=new Headers(i.headers);M.set("Content-Encoding",P),Dr(M,"Accept-Encoding"),M.delete("Content-Length");let U=c.pipeThrough(new CompressionStream(P==="gzip"?"gzip":"deflate"));return new Response(U,{status:i.status,statusText:i.statusText,headers:M})}async function ti(i,c){let P=i.getReader(),M=[],U=0,z=!1;while(U<c){let{value:pe,done:Re}=await P.read();if(Re){z=!0;break}if(pe)M.push(pe),U+=pe.byteLength}return{stream:new ReadableStream({start(pe){for(let Re of M)pe.enqueue(Re);if(z)pe.close()},async pull(pe){if(z)return;let{value:Re,done:Te}=await P.read();if(Te){z=!0,pe.close();return}if(Re)pe.enqueue(Re)},cancel(pe){return P.cancel(pe)}}),size:U,ended:z}}function Dr(i,c){let P=i.get("vary");if(!P){i.set("Vary",c);return}let M=P.split(",").map((U)=>U.trim().toLowerCase());if(M.includes("*")||M.includes(c.toLowerCase()))return;i.set("Vary",`${P}, ${c}`)}var ke={json:(i,c={})=>{let P=typeof c==="number"?{status:c}:c,{status:M=200,headers:U={},pretty:z=!1}=P,de=z?JSON.stringify(i,null,2):JSON.stringify(i);return new Response(de,{status:M,headers:{"Content-Type":"application/json",...U}})},noContent:(i={})=>new Response(null,{status:204,headers:i}),download:async(i,c,P={})=>{let M=Bun.file(i);if(!await M.exists())return new Response("File not found",{status:404});let z=c||i.split("/").pop()||"download",de=M.type||"application/octet-stream";return new Response(M,{status:200,headers:{"Content-Type":de,"Content-Disposition":`attachment; filename="${z}"`,"Content-Length":String(M.size),...P}})},file:async(i,c={})=>{let P=Bun.file(i);if(!await P.exists())return new Response("File not found",{status:404});let U=P.type||"application/octet-stream";return new Response(P,{status:200,headers:{"Content-Type":U,"Content-Length":String(P.size),...c}})},streamDownload:(i,c,P={})=>{let{contentType:M="application/octet-stream",headers:U={}}=P,z=new ReadableStream({async start(de){try{for await(let pe of i())if(typeof pe==="string")de.enqueue(new TextEncoder().encode(pe));else de.enqueue(pe);de.close()}catch(pe){de.error(pe)}}});return new Response(z,{status:200,headers:{"Content-Type":M,"Content-Disposition":`attachment; filename="${c}"`,"Transfer-Encoding":"chunked",...U}})},redirect:(i,c=302)=>new Response(null,{status:c,headers:{Location:i}}),redirectPermanent:(i)=>ke.redirect(i,301),redirectTemporary:(i)=>ke.redirect(i,302),back:(i,c="/")=>{let P=i.headers.get("referer")||c;return ke.redirect(P)},view:(i,c=200,P={})=>new Response(i,{status:c,headers:{"Content-Type":"text/html; charset=utf-8",...P}}),text:(i,c=200,P={})=>new Response(i,{status:c,headers:{"Content-Type":"text/plain; charset=utf-8",...P}}),xml:(i,c=200,P={})=>new Response(i,{status:c,headers:{"Content-Type":"application/xml; charset=utf-8",...P}}),success:(i,c,P=200)=>{let M={success:!0};if(i!==void 0)M.data=i;if(c!==void 0)M.message=c;return ke.json(M,{status:P})},error:(i,c=400,P)=>{let M={success:!1,message:i};if(P!==void 0)M.errors=P;return ke.json(M,{status:c})},paginate:(i,c)=>{let{page:P,perPage:M,total:U,path:z}=c,de=Math.ceil(U/M),pe=(P-1)*M+1,Re=Math.min(P*M,U);return ke.json({data:i,meta:{current_page:P,per_page:M,total:U,last_page:de,from:pe,to:Re,path:z,first_page_url:`${z}?page=1`,last_page_url:`${z}?page=${de}`,next_page_url:P<de?`${z}?page=${P+1}`:null,prev_page_url:P>1?`${z}?page=${P-1}`:null}})},created:(i,c)=>{let P={};if(c)P.Location=c;let M={success:!0};if(i!==void 0)M.data=i;return ke.json(M,{status:201,headers:P})},accepted:(i)=>{let c={success:!0};if(i!==void 0)c.data=i;return ke.json(c,{status:202})},notFound:(i="Resource not found")=>ke.error(i,404),unauthorized:(i="Unauthorized")=>ke.error(i,401),forbidden:(i="Forbidden")=>ke.error(i,403),badRequest:(i="Bad request",c)=>ke.error(i,400,c),validationError:(i,c="Validation failed")=>ke.error(c,422,i),unprocessableEntity:(i="Unprocessable entity",c)=>ke.error(i,422,c),serverError:(i="Internal server error")=>ke.error(i,500),tooManyRequests:(i="Too many requests",c)=>{let P={};if(c)P["Retry-After"]=String(c);return new Response(JSON.stringify({message:i}),{status:429,headers:{"Content-Type":"application/json",...P}})}};class mn{_status=200;_headers={};_cookies=[];_deleteCookies=[];status(i){return this._status=i,this}header(i,c){return this._headers[i]=c,this}withHeaders(i){return this._headers={...this._headers,...i},this}cookie(i,c,P={}){return this._cookies.push({name:i,value:c,options:P}),this}withoutCookie(i,c={}){return this._deleteCookies.push({name:i,options:c}),this}json(i){let c=ke.json(i,{status:this._status,headers:this._headers});return this.applyCookies(c)}text(i){let c=ke.text(i,this._status,this._headers);return this.applyCookies(c)}html(i){let c=ke.view(i,this._status,this._headers);return this.applyCookies(c)}noContent(){let i=ke.noContent(this._headers);return this.applyCookies(i)}applyCookies(i){let c=new Headers(i.headers);for(let{name:P,value:M,options:U}of this._cookies){let z=this.serializeCookie(P,M,U);c.append("Set-Cookie",z)}for(let{name:P,options:M}of this._deleteCookies){let U=this.serializeCookie(P,"",{...M,maxAge:0,expires:new Date(0)});c.append("Set-Cookie",U)}return new Response(i.body,{status:i.status,headers:c})}serializeCookie(i,c,P){let M=`${encodeURIComponent(i)}=${encodeURIComponent(c)}`;if(P.maxAge!==void 0)M+=`; Max-Age=${P.maxAge}`;if(P.expires)M+=`; Expires=${P.expires.toUTCString()}`;if(P.httpOnly)M+="; HttpOnly";if(P.secure)M+="; Secure";if(P.path)M+=`; Path=${P.path}`;if(P.domain)M+=`; Domain=${P.domain}`;if(P.sameSite)M+=`; SameSite=${P.sameSite.charAt(0).toUpperCase()+P.sameSite.slice(1)}`;return M}}function jo(){return new mn}import ri from"process";class Fr{compiledPipelines=new Map;dependencyRegistry=new Map;singletonInstances=new Map;stats={totalExecutions:0,cacheHits:0,cacheMisses:0,shortCircuits:0,skippedMiddleware:0,averageExecutionTime:0,dependencyResolutions:0};registerDependency(i){this.dependencyRegistry.set(i.name,i)}compileMiddleware(i,c,P=[]){let M=[];for(let U=0;U<c.length;U++){let z=c[U],de=z.name||`middleware_${U}`;M.push({handler:z,name:de,skipConditions:P.filter((pe)=>pe.name.includes(de)||pe.name==="global"),dependencies:this.extractDependencies(z),canShortCircuit:this.canShortCircuit(z),priority:U})}this.compiledPipelines.set(i,M)}async execute(i,c,P){let M=performance.now();this.stats.totalExecutions++;let U=this.compiledPipelines.get(i);if(!U)return this.stats.cacheMisses++,await P();this.stats.cacheHits++;let z={request:c,dependencies:new Map,metadata:{}};await this.resolveDependencies(z,U);let de=0,pe=async()=>{if(de>=U.length)return await P();let xe=U[de++];if(await this.shouldSkip(xe,z))return this.stats.skippedMiddleware++,await pe();let ve=await xe.handler(c,pe);if(ve instanceof Response&&xe.canShortCircuit)return this.stats.shortCircuits++,ve;return ve},Re=await pe(),Te=performance.now()-M;return this.updateAverageExecutionTime(Te),Re||new Response("Internal Server Error",{status:500})}async shouldSkip(i,c){for(let P of i.skipConditions)if(await P.condition(c))return!0;return!1}async resolveDependencies(i,c){let P=new Set;for(let M of c)for(let U of M.dependencies)P.add(U);for(let M of P){let U=this.dependencyRegistry.get(M);if(!U)continue;if(this.stats.dependencyResolutions++,U.singleton&&this.singletonInstances.has(M))i.dependencies.set(M,this.singletonInstances.get(M));else{let z=await U.factory(i);if(i.dependencies.set(M,z),U.singleton)this.singletonInstances.set(M,z)}}}extractDependencies(i){let c=i.toString(),P=[];if(c.includes("database")||c.includes("db"))P.push("database");if(c.includes("logger")||c.includes("log"))P.push("logger");if(c.includes("cache"))P.push("cache");if(c.includes("httpClient")||c.includes("http"))P.push("httpClient");return P}canShortCircuit(i){let c=i.toString();return c.includes("return")&&c.includes("Response")}updateAverageExecutionTime(i){let c=this.stats.averageExecutionTime*(this.stats.totalExecutions-1);this.stats.averageExecutionTime=(c+i)/this.stats.totalExecutions}getStats(){return{...this.stats}}clear(){this.compiledPipelines.clear(),this.singletonInstances.clear(),this.stats={totalExecutions:0,cacheHits:0,cacheMisses:0,shortCircuits:0,skippedMiddleware:0,averageExecutionTime:0,dependencyResolutions:0}}}var ni={skipForMethods:(i)=>({name:`skip_for_methods_${i.join("_")}`,condition:(c)=>i.includes(c.request.method)}),skipForPaths:(i)=>({name:`skip_for_paths_${i.join("_").replace(/\//g,"_")}`,condition:(c)=>{let P=new URL(c.request.url);return i.some((M)=>P.pathname.startsWith(M))}}),skipForHeaders:(i)=>({name:`skip_for_headers_${Object.keys(i).join("_")}`,condition:(c)=>Object.entries(i).some(([P,M])=>c.request.headers.get(P)===M)}),skipForRoles:(i)=>({name:`skip_for_roles_${i.join("_")}`,condition:(c)=>{let P=c.request.user?.roles||[];return!i.some((M)=>P.includes(M))}}),skipForEnvironment:(i)=>({name:`skip_for_env_${i.join("_")}`,condition:()=>{let c=ri.env.NODE_ENV||"development";return i.includes(c)}})},si={database:(i)=>({name:"database",factory:async()=>({query:async(c)=>({rows:[]}),close:async()=>{},connectionString:i||"mock://database"}),singleton:!0}),logger:(i="info")=>({name:"logger",factory:()=>({info:(c)=>console.log(`[INFO] ${c}`),error:(c)=>console.error(`[ERROR] ${c}`),warn:(c)=>console.warn(`[WARN] ${c}`),debug:(c)=>console.debug(`[DEBUG] ${c}`),level:i}),singleton:!0}),cache:(i=1000)=>({name:"cache",factory:()=>{let c=new Map;return{get:(P)=>c.get(P),set:(P,M)=>{if(c.size>=i){let U=c.keys().next().value;c.delete(U)}c.set(P,M)},delete:(P)=>c.delete(P),clear:()=>c.clear(),size:()=>c.size}},singleton:!0}),httpClient:(i)=>({name:"httpClient",factory:()=>({get:async(c)=>fetch(i?`${i}${c}`:c),post:async(c,P)=>fetch(i?`${i}${c}`:c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)}),put:async(c,P)=>fetch(i?`${i}${c}`:c,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)}),delete:async(c)=>fetch(i?`${i}${c}`:c,{method:"DELETE"})}),singleton:!0})},ii={auth:(i={})=>async(c,P)=>{let M=new URL(c.url);if(i.skipPaths?.some((z)=>M.pathname.startsWith(z)))return await P();if(!c.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});try{return c.user={id:"123",roles:["user"]},await P()}catch{return new Response("Invalid token",{status:401})}},rateLimit:(i)=>{let c=new Map;return async(P,M)=>{let U=P.headers.get("x-forwarded-for")||"unknown",z=Date.now(),de=z-i.windowMs;if(!c.has(U))c.set(U,[]);let Re=c.get(U).filter((Te)=>Te>de);if(Re.length>=i.maxRequests)return new Response("Too Many Requests",{status:429});return Re.push(z),c.set(U,Re),await M()}},cors:(i={})=>async(c,P)=>{let M=await P();if(M){let U=new Headers(M.headers);return U.set("Access-Control-Allow-Origin",i.origin||"*"),U.set("Access-Control-Allow-Methods",i.methods?.join(", ")||"GET, POST, PUT, DELETE"),U.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(M.body,{status:M.status,statusText:M.statusText,headers:U})}return M},logging:(i={})=>async(c,P)=>{let M=performance.now(),U=new URL(c.url);console.log(`[${new Date().toISOString()}] ${c.method} ${U.pathname}`);let z=await P(),de=performance.now()-M;if(z)console.log(`[${new Date().toISOString()}] ${c.method} ${U.pathname} - ${z.status} (${de.toFixed(2)}ms)`);return z}},oi=new Fr;import{existsSync as Rn,readdirSync as ai,statSync as ui}from"fs";import{basename as yn,extname as fn,join as ci,resolve as wn}from"path";var li=[".ts",".js"],di=["routes","src/routes"],pi=["web","index"];function hi(){let i=process.cwd();for(let c of di){let P=wn(i,c);if(Rn(P)&&ui(P).isDirectory())return P}return null}function bn(i,c){let P=[];if(!Rn(i))return P;let M=ai(i,{withFileTypes:!0});for(let U of M){if(U.name.startsWith(".")||U.name.startsWith("_"))continue;let z=ci(i,U.name);if(U.isDirectory())P.push(...bn(z,c));else if(li.includes(fn(U.name))){let de=i===c?"":i.slice(c.length),pe=yn(U.name,fn(U.name)),Re=pi.includes(pe)?de||"":`${de}/${pe}`;P.push({filePath:z,prefix:Re})}}return P}async function gi(i,c,P,M){try{let U=await import(c),z=0,de=i.routes?.length||0;if(typeof U.default==="function"){let pe=mi(i,P);await U.default(pe),z=(i.routes?.length||0)-de}else if(Array.isArray(U.routes))for(let pe of U.routes){let Re=(pe.method||"GET").toLowerCase(),Te=`${P}${pe.path}`;if(typeof i[Re]==="function")await i[Re](Te,pe.handler),z++}if(M&&z>0)console.log(` ${P||"/"} \u2192 ${yn(c)} (${z} routes)`);return z}catch(U){return console.error(`[bun-router] Failed to load route file ${c}:`,U),0}}function mi(i,c){if(!c)return i;let P=["get","post","put","patch","delete","options","any"];return new Proxy(i,{get(M,U){if(P.includes(U))return async(z,...de)=>M[U](`${c}${z}`,...de);if(U==="group")return async(z,de)=>{let pe=z.prefix?`${c}${z.prefix}`:c;return M.group({...z,prefix:pe},de)};return M[U]}})}function Tn(i){Object.defineProperties(i.prototype,{_routesDir:{value:null,writable:!0,configurable:!0},_apiRoutesInitialized:{value:!1,writable:!0,configurable:!0},_initApiRoutes:{async value(){if(this._apiRoutesInitialized)return;let c=this._routesDir||hi();if(!c){this._apiRoutesInitialized=!0;return}let P=this.config?.verbose||!1,M=bn(c,c);if(M.length===0){this._apiRoutesInitialized=!0;return}if(P)console.log(`[bun-router] Auto-discovering API routes from ${c}:`);let U=0;for(let{filePath:z,prefix:de}of M)U+=await gi(this,z,de,P);if(U>0&&P)console.log(`[bun-router] Registered ${U} API routes`);this._apiRoutesInitialized=!0},writable:!0,configurable:!0},routesFrom:{value(c){return this._routesDir=wn(c),this},writable:!0,configurable:!0}})}import{join as Kt,relative as Nr,resolve as Pt,dirname as Ri}from"path";import{readdirSync as xn,statSync as yi,existsSync as gr}from"fs";var Ko={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function fi(i){let{preserve:c=[],exclude:P=[],routes:M=[]}=i;if(!c.length)return"";return`<script data-query-preservation>
3
3
  (function(){
4
- var preserve = ${JSON.stringify(t)};
5
- var exclude = ${JSON.stringify(r)};
6
- var routes = ${JSON.stringify(n)};
4
+ var preserve = ${JSON.stringify(c)};
5
+ var exclude = ${JSON.stringify(P)};
6
+ var routes = ${JSON.stringify(M)};
7
7
 
8
8
  function shouldPreserve(href) {
9
9
  // Only preserve for same-origin links
@@ -76,30 +76,30 @@ catch (e) { return false; }
76
76
  }
77
77
  };
78
78
  })();
79
- </script>`}function Se(e,t){if(!t.enabled||!t.preserve?.length)return e;let r=Jn(t);if(!r)return e;if(e.includes("</head>"))return e.replace("</head>",`${r}
80
- </head>`);if(e.includes("</body>"))return e.replace("</body>",`${r}
81
- </body>`);return e+r}function Oi(e,t,r,n){let s=typeof t==="string"?new URL(t):t,i=new URL(e,s.origin);if(r.preserve){for(let o of r.preserve)if(s.searchParams.has(o)&&!r.exclude?.includes(o)){if(!i.searchParams.has(o))i.searchParams.set(o,s.searchParams.get(o))}}if(n)for(let[o,a]of Object.entries(n))i.searchParams.set(o,a);return i.pathname+i.search}var Qn=["src/views","views","resources/views","app/views"],Zn=["_","components","layouts","partials","scripts","styles"],Yn=[".stx",".html"];function es(e=process.cwd()){for(let t of Qn){let r=D(e,t);if(ke(r)&&Xn(r).isDirectory())return r}return null}function Ft(e,t,r){if(!ke(e))return!1;try{let n=Dt(e,{withFileTypes:!0});for(let s of n){if(r.some((i)=>s.name.startsWith(i)||s.name===i))continue;if(s.isFile()&&t.some((i)=>s.name.endsWith(i)))return!0;if(s.isDirectory()){let i=ae(e,s.name);if(Ft(i,t,r))return!0}}}catch{}return!1}function ts(e,t,r){let n=et(t,e);for(let i of r)if(n.endsWith(i)){n=n.slice(0,-i.length);break}if(n=n.replace(/\\/g,"/"),n==="index"||n.endsWith("/index"))n=n.replace(/\/?index$/,"");let s=[];if(n=n.replace(/\[\.\.\.([^\]]+)\]/g,(i,o)=>(s.push(o),`{${o}}*`)),n=n.replace(/\[([^\]]+)\]/g,(i,o)=>(s.push(o),`{${o}}`)),!n.startsWith("/"))n=`/${n}`;if(n==="/")return{routePath:"/",params:s};return{routePath:n,params:s}}function Nt(e,t,r,n){let s=[];if(!ke(e))return s;let i=Dt(e,{withFileTypes:!0});for(let a of i){let u=ae(e,a.name);if(n.some((c)=>a.name.startsWith(c)||a.name===c))continue;if(a.isDirectory())s.push(...Nt(u,t,r,n));else if(a.isFile()){if(r.some((l)=>a.name.endsWith(l))){let{routePath:l,params:d}=ts(u,t,r);s.push({filePath:u,routePath:l,params:d,isIndex:a.name.startsWith("index."),isDynamic:d.length>0})}}}s.sort((a,u)=>{if(a.isDynamic!==u.isDynamic)return a.isDynamic?1:-1;let c=a.routePath.split("/").length,l=u.routePath.split("/").length;if(c!==l)return l-c;return a.routePath.localeCompare(u.routePath)});let o=new Map;for(let a of s){let u=o.get(a.routePath);if(u)console.warn(`[bun-router] Warning: Duplicate route "${a.routePath}" found:
82
- - ${u.filePath}
83
- - ${a.filePath}
84
- Using: ${u.filePath}`);else o.set(a.routePath,a)}return Array.from(o.values())}function rs(e,t){let r=et(t,e),n=[D(process.cwd(),"dist/views",r.replace(/\.stx$/,".html")),D(process.cwd(),"views",r.replace(/\.stx$/,".html")),D("/var/task/views",r.replace(/\.stx$/,".html"))];for(let s of n)if(ke(s))return s;return null}function ns(e){let t={};for(let r of String(e??"").split(";")){let n=r.indexOf("=");if(n<0)continue;try{t[r.slice(0,n).trim()]=decodeURIComponent(r.slice(n+1).trim())}catch{}}return t}async function ss(e,t,r,n,s){let o=await import("@stacksjs/stx");if(!o.processDirectives||!o.extractVariables)throw Error("STX library not properly loaded. Install with: bun add @stacksjs/stx");let a=await Bun.file(e).text(),u=a.match(/<script\s+server\s*>([\s\S]*?)<\/script>/i),c=u?u[1]:"",l=u?a.replace(/<script\s+server\s*>[\s\S]*?<\/script>/i,""):a;l=l.replace(/<script\s+client\s*>/gi,"<script>");let d={status:200,headers:{}},p=r.headers??{},g=String(p.cookie??p.Cookie??""),h=String(r.url??""),m=h.includes("?")?h.slice(h.indexOf("?")):"",y={url:h,path:String(r.path??""),search:m,host:String(p.host??""),cookieHeader:g,cookies:ns(g),ip:"",locale:null,params:r.params??{},method:String(r.method??"GET"),request:s},x={__filename:e,__dirname:Kn(e),props:r,...r,__stxServeContext:y,setResponseStatus:(M)=>{if(Number.isInteger(M)&&M>=100&&M<=599)d.status=M},notFound:(M=404)=>{d.status=Number.isInteger(M)&&M>=400&&M<=599?M:404},setResponseHeader:(M,Wr)=>{if(M)d.headers[String(M)]=String(Wr)},definePageMeta:()=>{}};if(c)await o.extractVariables(c,x,e);let V=n?.componentsDir?D(n.componentsDir):ae(t,"components"),Re=n?.layoutsDir?D(n.layoutsDir):ae(t,"layouts"),jr=n?.partialsDir?D(n.partialsDir):ae(t,"partials"),Lr={...o.defaultConfig,componentsDir:V,layoutsDir:Re,partialsDir:jr},zr=await o.processDirectives(l,x,e,Lr,new Set),ye=Number(x.__stxResponseStatus),Gr=x.__stxResponseHeaders;return{html:zr,status:Number.isInteger(ye)&&ye>=100&&ye<=599?ye:d.status,headers:{...d.headers,...Gr??{}}}}function is(e,t,r,n){return async(s)=>{let i=new URL(s.url),o={params:s.params||{},query:Object.fromEntries(i.searchParams),url:s.url,path:i.pathname,method:s.method,headers:Object.fromEntries(s.headers.entries())};function a(u){if(n?.enabled!==!1&&n?.preserve?.length)return Se(u,n);return u}try{let u=rs(e,t);if(u){let l=await Bun.file(u).text();return l=a(l),new Response(l,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}if(e.endsWith(".stx")){let l=await ss(e,t,o,r,s),d=a(l.html);return new Response(d,{status:l.status,headers:{"Content-Type":"text/html; charset=utf-8",...l.headers}})}let c=await Bun.file(e).text();return c=a(c),new Response(c,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}catch(u){return console.error(`[bun-router] Error rendering ${e}:`,u),new Response("Internal Server Error",{status:500})}}}function Ut(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||es();if(!t){this._fileRoutesInitialized=!0;return}let r=this._fileRoutingConfig||{};if(r.enabled===!1){this._fileRoutesInitialized=!0;return}let n=r.extensions||Yn,s=r.exclude||Zn;if(!Ft(t,n,s)){this._fileRoutesInitialized=!0;return}let i=Nt(t,t,n,s);if(this.config.verbose){console.log(`[bun-router] Auto-discovered ${i.length} file-based routes from ${t}:`);for(let a of i)console.log(` ${a.routePath} -> ${et(t,a.filePath)}`)}this._viewsDir=t;let o=new Set;for(let a of this.routes)if(a.method==="GET")o.add(a.path);for(let a of i){if(o.has(a.routePath))continue;let u=is(a.filePath,t,r,this.config.queryPreservation);this.get(a.routePath,u,"web"),this._fileBasedRoutes.push(a),o.add(a.routePath)}this._fileRoutesInitialized=!0},writable:!0,configurable:!0},views:{value(t){if(typeof t==="string")this._viewsDir=D(t),this._fileRoutingConfig={};else{if(t.viewsPath)this._viewsDir=D(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,r){if(t)this._viewsDir=D(t);if(r)this._fileRoutingConfig={...this._fileRoutingConfig,...r};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 He{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 S{static direct(e,t={}){let{format:r="json",delimiter:n=`
85
- `,contentType:s,headers:i={},status:o=200,enableCompression:a=!1}=t,u=new ReadableStream({async start(l){try{let d=new TextEncoder,p=!0;for await(let g of Array.isArray(e)?e:e){if(!p&&n)l.enqueue(d.encode(n));let h=S.formatData(g,r);l.enqueue(d.encode(h)),p=!1}l.close()}catch(d){l.error(d)}}}),c=new Headers(i);if(s)c.set("Content-Type",s);else c.set("Content-Type",S.getContentTypeForFormat(r));return new He(u,{headers:c,status:o})}static buffered(e,t={}){let{format:r="json",bufferSize:n=1024,flushInterval:s=100,contentType:i,headers:o={},status:a=200}=t,u=new ReadableStream({async start(l){try{let d=new TextEncoder,p=[],g=0,h=()=>{if(p.length>0){let y=p.join("");l.enqueue(d.encode(y)),p=[],g=0}},m=setInterval(h,s);try{for await(let y of Array.isArray(e)?e:e){let x=S.formatData(y,r);if(p.push(x),g+=x.length,g>=n)h()}h()}finally{clearInterval(m)}l.close()}catch(d){l.error(d)}}}),c=new Headers(o);if(i)c.set("Content-Type",i);else c.set("Content-Type",S.getContentTypeForFormat(r));return new He(u,{headers:c,status:a})}static json(e,t={}){return S.direct(e,{...t,format:"json",contentType:t.contentType||"application/json"})}static text(e,t={}){return S.direct(e,{...t,format:"text",contentType:t.contentType||"text/plain"})}static csv(e,t={}){let{csvHeaders:r,...n}=t,s=new ReadableStream({async start(i){try{let o=new TextEncoder,a=!0;if(r&&r.length>0)i.enqueue(o.encode(`${r.join(",")}
86
- `));for await(let u of Array.isArray(e)?e:e){let c=S.objectToCsvRow(u,r);i.enqueue(o.encode(`${c}
87
- `))}i.close()}catch(o){i.error(o)}}});return new He(s,{headers:n.headers,status:n.status,contentType:n.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"?S.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((n)=>{let s=e[n],i=s===null||s===void 0?"":String(s);if(i.includes(",")||i.includes('"')||i.includes(`
88
- `))return`"${i.replace(/"/g,'""')}"`;return i}).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 Q{static async streamFile(e,t,r={}){let{contentType:n,enableRanges:s=!0,chunkSize:i=65536}=r;try{let o=Bun.file(e),a=o.size,u=s?t.headers.get("range"):null;if(u&&s)return Q.handleRangeRequest(o,u,n);let c=new Headers({"Content-Length":a.toString(),"Accept-Ranges":s?"bytes":"none"});if(n)c.set("Content-Type",n);return new Response(o.stream(),{status:200,headers:c})}catch(o){return console.error("Error streaming file:",o),new Response("File not found",{status:404})}}static async handleRangeRequest(e,t,r){let n=Q.parseRangeHeader(t,e.size);if(!n||n.length===0)return new Response("Invalid range",{status:416});let[s,i]=n[0],o=i-s+1,a=new Headers({"Content-Range":`bytes ${s}-${i}/${e.size}`,"Content-Length":o.toString(),"Accept-Ranges":"bytes"});if(r)a.set("Content-Type",r);let u=e.slice(s,i+1);return new Response(u.stream(),{status:206,headers:a})}static parseRangeHeader(e,t){let r=e.match(/^bytes=(.+)$/);if(!r)return null;let n=[],s=r[1].split(",");for(let i of s){let[o,a]=i.trim().split("-"),u,c;if(o==="")u=Math.max(0,t-Number.parseInt(a,10)),c=t-1;else if(a==="")u=Number.parseInt(o,10),c=t-1;else u=Number.parseInt(o,10),c=Number.parseInt(a,10);if(u<0||c>=t||u>c)return null;n.push([u,c])}return n}}function Ae(e,t){try{e.close()}catch{}}function It(e){Object.defineProperties(e.prototype,{streamFile:{value(t,r,n){return Q.streamFile(t,r,n)},writable:!0,configurable:!0},streamFileWithRanges:{async value(t,r){return Q.streamFile(t,r,{enableRanges:!0})},writable:!0,configurable:!0},health:{value(){let r=this.config.apiPrefix?`${this.config.apiPrefix}/health`:"/health";return this.get(r,()=>new Response("OK",{headers:{"Content-Type":"text/plain"}})),this},writable:!0,configurable:!0},streamResponse:{value(t,r){let n=new Headers;if(r?.headers)for(let[s,i]of Object.entries(r.headers))n.set(s,i);return new Response(t(),{status:r?.status||200,headers:n})},writable:!0,configurable:!0},transformStream:{value(t,r){return(n)=>{if(!n.body)throw Error("Request body is required for stream transformation");let s=new TransformStream({async transform(o,a){try{let u=await t(o);if(typeof u==="string")a.enqueue(new TextEncoder().encode(u));else a.enqueue(u)}catch(u){a.error(u)}}}),i=new Headers;if(r?.headers)for(let[o,a]of Object.entries(r.headers))i.set(o,a);return new Response(n.body.pipeThrough(s),{status:r?.status||200,headers:i})}},writable:!0,configurable:!0},stream:{value(t,r=200,n={}){let s=new Headers(n),i=new ReadableStream({async start(o){let a=new TextEncoder;try{for await(let u of t())if(typeof u==="string")o.enqueue(a.encode(u));else o.enqueue(u);o.close()}catch(u){Ae(o,u)}}});return new Response(i,{status:r,headers:s})},writable:!0,configurable:!0},streamJson:{value(t,r=200,n={}){let s=new Headers({"Content-Type":"application/json",...n}),i=new ReadableStream({async start(o){let a=new TextEncoder;try{o.enqueue(a.encode("{"));let u=Object.keys(t);for(let c=0;c<u.length;c++){let l=u[c],d=t[l];o.enqueue(a.encode(`"${l}":[`));let p=!0;for await(let g of d){if(!p)o.enqueue(a.encode(","));o.enqueue(a.encode(JSON.stringify(g))),p=!1}if(o.enqueue(a.encode("]")),c<u.length-1)o.enqueue(a.encode(","))}o.enqueue(a.encode("}")),o.close()}catch(u){Ae(o,u)}}});return new Response(i,{status:r,headers:s})},writable:!0,configurable:!0},eventStream:{value(t,r={}){let n=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Cache-Control",...r}),s=new ReadableStream({async start(i){let o=new TextEncoder;try{for await(let a of t()){let u="";if(a.id)u+=`id: ${a.id}
89
- `;if(a.event)u+=`event: ${a.event}
90
- `;if(a.retry)u+=`retry: ${a.retry}
91
- `;let c=typeof a.data==="string"?a.data:JSON.stringify(a.data);u+=`data: ${c}
79
+ </script>`}function hr(i,c){if(!c.enabled||!c.preserve?.length)return i;let P=fi(c);if(!P)return i;if(i.includes("</head>"))return i.replace("</head>",`${P}
80
+ </head>`);if(i.includes("</body>"))return i.replace("</body>",`${P}
81
+ </body>`);return i+P}function Xo(i,c,P,M){let U=typeof c==="string"?new URL(c):c,z=new URL(i,U.origin);if(P.preserve){for(let de of P.preserve)if(U.searchParams.has(de)&&!P.exclude?.includes(de)){if(!z.searchParams.has(de))z.searchParams.set(de,U.searchParams.get(de))}}if(M)for(let[de,pe]of Object.entries(M))z.searchParams.set(de,pe);return z.pathname+z.search}var wi=["src/views","views","resources/views","app/views"],bi=["_","components","layouts","partials","scripts","styles"],Ti=[".stx",".html"];function xi(i=process.cwd()){for(let c of wi){let P=Pt(i,c);if(gr(P)&&yi(P).isDirectory())return P}return null}function vn(i,c,P){if(!gr(i))return!1;try{let M=xn(i,{withFileTypes:!0});for(let U of M){if(P.some((z)=>U.name.startsWith(z)||U.name===z))continue;if(U.isFile()&&c.some((z)=>U.name.endsWith(z)))return!0;if(U.isDirectory()){let z=Kt(i,U.name);if(vn(z,c,P))return!0}}}catch{}return!1}function vi(i,c,P){let M=Nr(c,i);for(let z of P)if(M.endsWith(z)){M=M.slice(0,-z.length);break}if(M=M.replace(/\\/g,"/"),M==="index"||M.endsWith("/index"))M=M.replace(/\/?index$/,"");let U=[];if(M=M.replace(/\[\.\.\.([^\]]+)\]/g,(z,de)=>(U.push(de),`{${de}}*`)),M=M.replace(/\[([^\]]+)\]/g,(z,de)=>(U.push(de),`{${de}}`)),!M.startsWith("/"))M=`/${M}`;if(M==="/")return{routePath:"/",params:U};return{routePath:M,params:U}}function Cn(i,c,P,M){let U=[];if(!gr(i))return U;let z=xn(i,{withFileTypes:!0});for(let pe of z){let Re=Kt(i,pe.name);if(M.some((Te)=>pe.name.startsWith(Te)||pe.name===Te))continue;if(pe.isDirectory())U.push(...Cn(Re,c,P,M));else if(pe.isFile()){if(P.some((xe)=>pe.name.endsWith(xe))){let{routePath:xe,params:ve}=vi(Re,c,P);U.push({filePath:Re,routePath:xe,params:ve,isIndex:pe.name.startsWith("index."),isDynamic:ve.length>0})}}}U.sort((pe,Re)=>{if(pe.isDynamic!==Re.isDynamic)return pe.isDynamic?1:-1;let Te=pe.routePath.split("/").length,xe=Re.routePath.split("/").length;if(Te!==xe)return xe-Te;return pe.routePath.localeCompare(Re.routePath)});let de=new Map;for(let pe of U){let Re=de.get(pe.routePath);if(Re)console.warn(`[bun-router] Warning: Duplicate route "${pe.routePath}" found:
82
+ - ${Re.filePath}
83
+ - ${pe.filePath}
84
+ Using: ${Re.filePath}`);else de.set(pe.routePath,pe)}return Array.from(de.values())}function Ci(i,c){let P=Nr(c,i),M=[Pt(process.cwd(),"dist/views",P.replace(/\.stx$/,".html")),Pt(process.cwd(),"views",P.replace(/\.stx$/,".html")),Pt("/var/task/views",P.replace(/\.stx$/,".html"))];for(let U of M)if(gr(U))return U;return null}function Pi(i){let c={};for(let P of String(i??"").split(";")){let M=P.indexOf("=");if(M<0)continue;try{c[P.slice(0,M).trim()]=decodeURIComponent(P.slice(M+1).trim())}catch{}}return c}async function Mi(i,c,P,M,U){let de=await import("@stacksjs/stx");if(!de.processDirectives||!de.extractVariables)throw Error("STX library not properly loaded. Install with: bun add @stacksjs/stx");let pe=await Bun.file(i).text(),Re=pe.match(/<script\s+server\s*>([\s\S]*?)<\/script>/i),Te=Re?Re[1]:"",xe=Re?pe.replace(/<script\s+server\s*>[\s\S]*?<\/script>/i,""):pe;xe=xe.replace(/<script\s+client\s*>/gi,"<script>");let ve={status:200,headers:{}},Ce=P.headers??{},Me=String(Ce.cookie??Ce.Cookie??""),Pe=String(P.url??""),Ee=Pe.includes("?")?Pe.slice(Pe.indexOf("?")):"",Ae={url:Pe,path:String(P.path??""),search:Ee,host:String(Ce.host??""),cookieHeader:Me,cookies:Pi(Me),ip:"",locale:null,params:P.params??{},method:String(P.method??"GET"),request:U},Fe={__filename:i,__dirname:Ri(i),props:P,...P,__stxServeContext:Ae,setResponseStatus:(ct)=>{if(Number.isInteger(ct)&&ct>=100&&ct<=599)ve.status=ct},notFound:(ct=404)=>{ve.status=Number.isInteger(ct)&&ct>=400&&ct<=599?ct:404},setResponseHeader:(ct,qs)=>{if(ct)ve.headers[String(ct)]=String(qs)},definePageMeta:()=>{}};if(Te)await de.extractVariables(Te,Fe,i);let Dt=M?.componentsDir?Pt(M.componentsDir):Kt(c,"components"),ir=M?.layoutsDir?Pt(M.layoutsDir):Kt(c,"layouts"),Ss=M?.partialsDir?Pt(M.partialsDir):Kt(c,"partials"),ks={...de.defaultConfig,componentsDir:Dt,layoutsDir:ir,partialsDir:Ss},Hs=await de.processDirectives(xe,Fe,i,ks,new Set),or=Number(Fe.__stxResponseStatus),As=Fe.__stxResponseHeaders;return{html:Hs,status:Number.isInteger(or)&&or>=100&&or<=599?or:ve.status,headers:{...ve.headers,...As??{}}}}function Ei(i,c,P,M){return async(U)=>{let z=new URL(U.url),de={params:U.params||{},query:Object.fromEntries(z.searchParams),url:U.url,path:z.pathname,method:U.method,headers:Object.fromEntries(U.headers.entries())};function pe(Re){if(M?.enabled!==!1&&M?.preserve?.length)return hr(Re,M);return Re}try{let Re=Ci(i,c);if(Re){let xe=await Bun.file(Re).text();return xe=pe(xe),new Response(xe,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}if(i.endsWith(".stx")){let xe=await Mi(i,c,de,P,U),ve=pe(xe.html);return new Response(ve,{status:xe.status,headers:{"Content-Type":"text/html; charset=utf-8",...xe.headers}})}let Te=await Bun.file(i).text();return Te=pe(Te),new Response(Te,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}catch(Re){return console.error(`[bun-router] Error rendering ${i}:`,Re),new Response("Internal Server Error",{status:500})}}}function Pn(i){Object.defineProperties(i.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 c=this._viewsDir||xi();if(!c){this._fileRoutesInitialized=!0;return}let P=this._fileRoutingConfig||{};if(P.enabled===!1){this._fileRoutesInitialized=!0;return}let M=P.extensions||Ti,U=P.exclude||bi;if(!vn(c,M,U)){this._fileRoutesInitialized=!0;return}let z=Cn(c,c,M,U);if(this.config.verbose){console.log(`[bun-router] Auto-discovered ${z.length} file-based routes from ${c}:`);for(let pe of z)console.log(` ${pe.routePath} -> ${Nr(c,pe.filePath)}`)}this._viewsDir=c;let de=new Set;for(let pe of this.routes)if(pe.method==="GET")de.add(pe.path);for(let pe of z){if(de.has(pe.routePath))continue;let Re=Ei(pe.filePath,c,P,this.config.queryPreservation);this.get(pe.routePath,Re,"web"),this._fileBasedRoutes.push(pe),de.add(pe.routePath)}this._fileRoutesInitialized=!0},writable:!0,configurable:!0},views:{value(c){if(typeof c==="string")this._viewsDir=Pt(c),this._fileRoutingConfig={};else{if(c.viewsPath)this._viewsDir=Pt(c.viewsPath);this._fileRoutingConfig=c}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(c,P){if(c)this._viewsDir=Pt(c);if(P)this._fileRoutingConfig={...this._fileRoutingConfig,...P};return this._fileRoutesInitialized=!1,await this._initFileRoutes(),this},writable:!0,configurable:!0},loadFileRoutes:{async value(c={}){return this.fileRoutes(c.viewsPath,c)},writable:!0,configurable:!0}})}class mr{stream;headers;status;constructor(i,c={}){if(this.stream=i,this.status=c.status||200,this.headers=new Headers(c.headers),c.contentType)this.headers.set("Content-Type",c.contentType)}toResponse(){return new Response(this.stream,{status:this.status,headers:this.headers})}addHeader(i,c){return this.headers.set(i,c),this}setContentType(i){return this.headers.set("Content-Type",i),this}setStatus(i){return this.status=i,this}}class dt{static direct(i,c={}){let{format:P="json",delimiter:M=`
85
+ `,contentType:U,headers:z={},status:de=200,enableCompression:pe=!1}=c,Re=new ReadableStream({async start(xe){try{let ve=new TextEncoder,Ce=!0;for await(let Me of Array.isArray(i)?i:i){if(!Ce&&M)xe.enqueue(ve.encode(M));let Pe=dt.formatData(Me,P);xe.enqueue(ve.encode(Pe)),Ce=!1}xe.close()}catch(ve){xe.error(ve)}}}),Te=new Headers(z);if(U)Te.set("Content-Type",U);else Te.set("Content-Type",dt.getContentTypeForFormat(P));return new mr(Re,{headers:Te,status:de})}static buffered(i,c={}){let{format:P="json",bufferSize:M=1024,flushInterval:U=100,contentType:z,headers:de={},status:pe=200}=c,Re=new ReadableStream({async start(xe){try{let ve=new TextEncoder,Ce=[],Me=0,Pe=()=>{if(Ce.length>0){let Ae=Ce.join("");xe.enqueue(ve.encode(Ae)),Ce=[],Me=0}},Ee=setInterval(Pe,U);try{for await(let Ae of Array.isArray(i)?i:i){let Fe=dt.formatData(Ae,P);if(Ce.push(Fe),Me+=Fe.length,Me>=M)Pe()}Pe()}finally{clearInterval(Ee)}xe.close()}catch(ve){xe.error(ve)}}}),Te=new Headers(de);if(z)Te.set("Content-Type",z);else Te.set("Content-Type",dt.getContentTypeForFormat(P));return new mr(Re,{headers:Te,status:pe})}static json(i,c={}){return dt.direct(i,{...c,format:"json",contentType:c.contentType||"application/json"})}static text(i,c={}){return dt.direct(i,{...c,format:"text",contentType:c.contentType||"text/plain"})}static csv(i,c={}){let{csvHeaders:P,...M}=c,U=new ReadableStream({async start(z){try{let de=new TextEncoder,pe=!0;if(P&&P.length>0)z.enqueue(de.encode(`${P.join(",")}
86
+ `));for await(let Re of Array.isArray(i)?i:i){let Te=dt.objectToCsvRow(Re,P);z.enqueue(de.encode(`${Te}
87
+ `))}z.close()}catch(de){z.error(de)}}});return new mr(U,{headers:M.headers,status:M.status,contentType:M.contentType||"text/csv"})}static formatData(i,c){switch(c){case"json":return JSON.stringify(i);case"text":return String(i);case"csv":return typeof i==="object"?dt.objectToCsvRow(i):String(i);case"ndjson":return JSON.stringify(i);default:return JSON.stringify(i)}}static objectToCsvRow(i,c){return(c||Object.keys(i)).map((M)=>{let U=i[M],z=U===null||U===void 0?"":String(U);if(z.includes(",")||z.includes('"')||z.includes(`
88
+ `))return`"${z.replace(/"/g,'""')}"`;return z}).join(",")}static getContentTypeForFormat(i){switch(i){case"json":case"ndjson":return"application/json";case"text":return"text/plain";case"csv":return"text/csv";default:return"application/json"}}}class It{static async streamFile(i,c,P={}){let{contentType:M,enableRanges:U=!0,chunkSize:z=65536}=P;try{let de=Bun.file(i),pe=de.size,Re=U?c.headers.get("range"):null;if(Re&&U)return It.handleRangeRequest(de,Re,M);let Te=new Headers({"Content-Length":pe.toString(),"Accept-Ranges":U?"bytes":"none"});if(M)Te.set("Content-Type",M);return new Response(de.stream(),{status:200,headers:Te})}catch(de){return console.error("Error streaming file:",de),new Response("File not found",{status:404})}}static async handleRangeRequest(i,c,P){let M=It.parseRangeHeader(c,i.size);if(!M||M.length===0)return new Response("Invalid range",{status:416});let[U,z]=M[0],de=z-U+1,pe=new Headers({"Content-Range":`bytes ${U}-${z}/${i.size}`,"Content-Length":de.toString(),"Accept-Ranges":"bytes"});if(P)pe.set("Content-Type",P);let Re=i.slice(U,z+1);return new Response(Re.stream(),{status:206,headers:pe})}static parseRangeHeader(i,c){let P=i.match(/^bytes=(.+)$/);if(!P)return null;let M=[],U=P[1].split(",");for(let z of U){let[de,pe]=z.trim().split("-"),Re,Te;if(de==="")Re=Math.max(0,c-Number.parseInt(pe,10)),Te=c-1;else if(pe==="")Re=Number.parseInt(de,10),Te=c-1;else Re=Number.parseInt(de,10),Te=Number.parseInt(pe,10);if(Re<0||Te>=c||Re>Te)return null;M.push([Re,Te])}return M}}function fr(i,c){try{i.close()}catch{}}function Mn(i){Object.defineProperties(i.prototype,{streamFile:{value(c,P,M){return It.streamFile(c,P,M)},writable:!0,configurable:!0},streamFileWithRanges:{async value(c,P){return It.streamFile(c,P,{enableRanges:!0})},writable:!0,configurable:!0},health:{value(){let P=this.config.apiPrefix?`${this.config.apiPrefix}/health`:"/health";return this.get(P,()=>new Response("OK",{headers:{"Content-Type":"text/plain"}})),this},writable:!0,configurable:!0},streamResponse:{value(c,P){let M=new Headers;if(P?.headers)for(let[U,z]of Object.entries(P.headers))M.set(U,z);return new Response(c(),{status:P?.status||200,headers:M})},writable:!0,configurable:!0},transformStream:{value(c,P){return(M)=>{if(!M.body)throw Error("Request body is required for stream transformation");let U=new TransformStream({async transform(de,pe){try{let Re=await c(de);if(typeof Re==="string")pe.enqueue(new TextEncoder().encode(Re));else pe.enqueue(Re)}catch(Re){pe.error(Re)}}}),z=new Headers;if(P?.headers)for(let[de,pe]of Object.entries(P.headers))z.set(de,pe);return new Response(M.body.pipeThrough(U),{status:P?.status||200,headers:z})}},writable:!0,configurable:!0},stream:{value(c,P=200,M={}){let U=new Headers(M),z=new ReadableStream({async start(de){let pe=new TextEncoder;try{for await(let Re of c())if(typeof Re==="string")de.enqueue(pe.encode(Re));else de.enqueue(Re);de.close()}catch(Re){fr(de,Re)}}});return new Response(z,{status:P,headers:U})},writable:!0,configurable:!0},streamJson:{value(c,P=200,M={}){let U=new Headers({"Content-Type":"application/json",...M}),z=new ReadableStream({async start(de){let pe=new TextEncoder;try{de.enqueue(pe.encode("{"));let Re=Object.keys(c);for(let Te=0;Te<Re.length;Te++){let xe=Re[Te],ve=c[xe];de.enqueue(pe.encode(`"${xe}":[`));let Ce=!0;for await(let Me of ve){if(!Ce)de.enqueue(pe.encode(","));de.enqueue(pe.encode(JSON.stringify(Me))),Ce=!1}if(de.enqueue(pe.encode("]")),Te<Re.length-1)de.enqueue(pe.encode(","))}de.enqueue(pe.encode("}")),de.close()}catch(Re){fr(de,Re)}}});return new Response(z,{status:P,headers:U})},writable:!0,configurable:!0},eventStream:{value(c,P={}){let M=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Cache-Control",...P}),U=new ReadableStream({async start(z){let de=new TextEncoder;try{for await(let pe of c()){let Re="";if(pe.id)Re+=`id: ${pe.id}
89
+ `;if(pe.event)Re+=`event: ${pe.event}
90
+ `;if(pe.retry)Re+=`retry: ${pe.retry}
91
+ `;let Te=typeof pe.data==="string"?pe.data:JSON.stringify(pe.data);Re+=`data: ${Te}
92
92
 
93
- `,i.enqueue(o.encode(u))}i.close()}catch(a){Ae(i,a)}}});return new Response(s,{status:200,headers:n})},writable:!0,configurable:!0},streamDownload:{value(t,r,n={}){let s=new Headers({"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="${r}"`,...n}),i=new ReadableStream({async start(o){let a=new TextEncoder;try{for await(let u of t())if(typeof u==="string")o.enqueue(a.encode(u));else o.enqueue(u);o.close()}catch(u){Ae(o,u)}}});return new Response(i,{status:200,headers:s})},writable:!0,configurable:!0},streamAsyncIterator:{value(t,r={}){return S.direct(t,r).toResponse()},writable:!0,configurable:!0}})}class qe extends Error{modelName;value;field;constructor(e,t,r="id"){super(`${e} not found with ${r}: ${t}`);this.modelName=e;this.value=t;this.field=r;this.name="ModelNotFoundError"}}class jt{bindings=new Map;model(e,t){this.bindings.set(e,t)}bind(e,t){this.bindings.set(e,t)}getBinding(e){return this.bindings.get(e)}hasBinding(e){return this.bindings.has(e)}}var os=new jt;async function _t(e,t,r,n,s={}){if(n)return await r.resolveRouteBinding(t,n);let i=r.getRouteKeyName();if(i!=="id")return await r.resolveRouteBinding(t,i);return await r.find(t)}function Lt(e,t){return async(r,n)=>{let s={};try{for(let i of e){let o=r.params?.[i.name];if(!o)continue;let a=os.getBinding(i.name);if(a){let l=null;if(typeof a==="function")l=await a(o);else l=await _t(i.name,o,a,i.key,s);if(!l)throw new qe(i.name,o,i.key||"id");s[i.name]=l;continue}let u=t[i.name];if(!u)continue;let c=await _t(i.name,o,u,i.key,s);if(!c)throw new qe(i.name,o,i.key||"id");s[i.name]=c}return r.models=s,await n()}catch(i){if(i instanceof qe)return new Response(`${i.modelName} not found`,{status:404});throw i}}}class zt{key;entry;prev;next;constructor(e,t,r=null,n=null){this.key=e;this.entry=t;this.prev=r;this.next=n}}class ue{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 r=Date.now(),n=t.entry;if(this.isExpired(n,r)){if(!this.options.allowStale){this.delete(e),this.stats.misses++;return}}if(n.lastAccessed=r,n.accessCount++,this.stats.hits++,this.options.updateAgeOnGet!==!1)this.moveToFront(t);return n.value}set(e,t,r){let n=Date.now(),s=this.cache.get(e);if(s){s.entry.value=t,s.entry.timestamp=n,s.entry.lastAccessed=n,s.entry.ttl=r??this.options.ttl,this.moveToFront(s);return}let i={value:t,timestamp:n,accessCount:0,lastAccessed:n,ttl:r??this.options.ttl},o=new zt(e,i);if(this.cache.set(e,o),this.addToFront(o),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 r=Date.now();if(this.isExpired(t.entry,r)){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[r,n]of this.cache)if(this.isExpired(n.entry,e))t.push(r);for(let r of t)this.delete(r);return t.length}getFrequentlyUsed(e=10){let t=[];for(let[r,n]of this.cache)t.push({key:r,value:n.entry.value,accessCount:n.entry.accessCount});return t.sort((r,n)=>n.accessCount-r.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,r]of this.cache)e+=t.length*2,e+=this.estimateValueSize(r.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 Gt{static generateKey(e,t){let r=new URL(e.url),n=e.method,s=r.pathname,i=[n,s],o=new URLSearchParams(r.search),a=t.excludeQuery||[],u=[];for(let[c,l]of o.entries())if(!a.includes(c))u.push(`${c}=${l}`);if(u.length>0)i.push(u.sort().join("&"));if(t.varyBy){let c=[];for(let l of t.varyBy){let d=e.headers.get(l);if(d)c.push(`${l}:${d}`)}if(c.length>0)i.push(c.join("|"))}return i.join("::")}}class Wt{cache;tagIndex=new Map;keyTags=new Map;constructor(e=1000){this.cache=new ue({maxSize:e})}async get(e){let t=this.cache.get(e);if(!t)return null;if(t.ttl&&Date.now()-t.timestamp>t.ttl)return this.delete(e),null;return t}async set(e,t){this.cache.set(e,t),this.keyTags.set(e,new Set(t.tags));for(let r of t.tags){if(!this.tagIndex.has(r))this.tagIndex.set(r,new Set);this.tagIndex.get(r).add(e)}}delete(e){let t=this.keyTags.get(e);if(t){for(let r of t){let n=this.tagIndex.get(r);if(n){if(n.delete(e),n.size===0)this.tagIndex.delete(r)}}this.keyTags.delete(e)}return this.cache.delete(e)}invalidateByTags(e){let t=new Set;for(let r of e){let n=this.tagIndex.get(r);if(n)for(let s of n)t.add(s)}for(let r of t)this.delete(r);return t.size}clear(){this.cache.clear(),this.tagIndex.clear(),this.keyTags.clear()}getStats(){return{...this.cache.getStats(),totalTags:this.tagIndex.size,totalKeyTagMappings:this.keyTags.size}}}var Z=new Wt;function Vt(e){return async(t,r)=>{if(e.condition&&!e.condition(t))return await r();if(t.method!=="GET"&&t.method!=="HEAD")return await r();let n=Gt.generateKey(t,e),s=await Z.get(n);if(s){let o=new Headers(s.headers);if(o.set("X-Cache","HIT"),o.set("X-Cache-Key",n),s.etag){if(o.set("ETag",s.etag),t.headers.get("If-None-Match")===s.etag)return new Response(null,{status:304,headers:o})}return new Response(s.body,{status:s.status,headers:o})}let i=await r();if(i.status>=200&&i.status<300)try{let o=i.clone(),a=await o.arrayBuffer(),u=await as(a),c={};o.headers.forEach((p,g)=>{c[g]=p});let l={response:o,headers:c,status:i.status,body:new Uint8Array(a),timestamp:Date.now(),ttl:e.ttl,tags:e.tags||[],etag:u};await Z.set(n,l);let d=new Headers(i.headers);return d.set("X-Cache","MISS"),d.set("X-Cache-Key",n),d.set("ETag",u),new Response(i.body,{status:i.status,headers:d})}catch(o){return console.error("Error caching response:",o),i}return i}}async function as(e){let t=await crypto.subtle.digest("SHA-256",e);return`"${Array.from(new Uint8Array(t)).map((s)=>s.toString(16).padStart(2,"0")).join("").substring(0,16)}"`}var Jt={short:(e=[])=>({ttl:300000,maxSize:500,tags:e}),medium:(e=[])=>({ttl:3600000,maxSize:1000,tags:e}),long:(e=[])=>({ttl:86400000,maxSize:2000,tags:e}),api:(e=[])=>({ttl:900000,maxSize:1000,tags:e,varyBy:["Authorization","Accept","Accept-Language"],excludeQuery:["_t","timestamp","cache_bust"]}),static:(e=[])=>({ttl:604800000,maxSize:5000,tags:e,varyBy:["Accept-Encoding"]}),user:(e=[])=>({ttl:1800000,maxSize:2000,tags:e,varyBy:["Authorization"],condition:(t)=>!!t.headers.get("Authorization")})},Wi={byTags:(e)=>Z.invalidateByTags(e),forUser:(e)=>Z.invalidateByTags([`user:${e}`]),forModel:(e,t)=>{let r=t?[`${e}:${t}`,e]:[e];return Z.invalidateByTags(r)},all:()=>{Z.clear()}};class Oe{cache;config;constructor(e,t=1e4){this.config=e,this.cache=new ue({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),r=Date.now(),n=this.cache.get(t);if(!n||r>=n.resetTime)n={count:1,resetTime:r+this.config.windowMs,firstHit:r};else n.count++;this.cache.set(t,n);let s={totalHits:n.count,resetTime:new Date(n.resetTime),remaining:Math.max(0,this.config.maxAttempts-n.count),limit:this.config.maxAttempts,windowMs:this.config.windowMs};return{allowed:n.count<=this.config.maxAttempts,info:s}}generateKey(e){if(this.config.keyGenerator)return this.config.keyGenerator(e);let t=this.getClientIP(e),r=e.user?.id;if(r)return`user:${r}`;return`ip:${t}`}getClientIP(e){let t=e.headers.get("x-forwarded-for");if(t)return t.split(",")[0].trim();let r=e.headers.get("x-real-ip");if(r)return r;let n=e.headers.get("cf-connecting-ip");if(n)return n;return"unknown"}getStats(){return{...this.cache.getStats(),config:{maxAttempts:this.config.maxAttempts,windowMs:this.config.windowMs}}}}class Kt{limiters=new Map;register(e,t){let r=new Oe(t);return this.limiters.set(e,r),r}get(e){return this.limiters.get(e)}getOrCreate(e,t){let r=this.limiters.get(e);if(r)return r;return this.register(e,t)}}var Xt=new Kt;function Y(e,t){let r=t?Xt.getOrCreate(t,e):new Oe(e);return async(n,s)=>{let{allowed:i,info:o}=await r.checkLimit(n);if(!i){if(e.onLimitReached)return e.onLimitReached(n,o);let u=new Headers({"Content-Type":"application/json","Retry-After":Math.ceil((o.resetTime.getTime()-Date.now())/1000).toString()});if(e.headers!==!1)u.set("X-RateLimit-Limit",o.limit.toString()),u.set("X-RateLimit-Remaining",o.remaining.toString()),u.set("X-RateLimit-Reset",Math.ceil(o.resetTime.getTime()/1000).toString());return new Response(JSON.stringify({error:"Too Many Requests",message:`Rate limit exceeded. Try again in ${Math.ceil((o.resetTime.getTime()-Date.now())/1000)} seconds.`,retryAfter:Math.ceil((o.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:u})}let a=await s();if(a&&e.headers!==!1&&a.status<400){let u=new Headers(a.headers);return u.set("X-RateLimit-Limit",o.limit.toString()),u.set("X-RateLimit-Remaining",o.remaining.toString()),u.set("X-RateLimit-Reset",Math.ceil(o.resetTime.getTime()/1000).toString()),new Response(a.body,{status:a.status,statusText:a.statusText,headers:u})}return a}}function ee(e){let t=e.split(","),r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<=0)throw Error(`Invalid throttle max attempts: ${t[0]}`);let n;if(t.length===1)n=60000;else{let s=t[1];n=us(s)}return{maxAttempts:r,windowMs:n}}function us(e){let t=/^(\d+)([smh]|sec|min|hour)?$/,r=e.match(t);if(!r)throw Error(`Invalid time format: ${e}`);let n=Number.parseInt(r[1],10),s=r[2]||"m";if(Number.isNaN(n)||n<=0)throw Error(`Invalid time value: ${r[1]}`);switch(s){case"s":case"sec":return n*1000;case"m":case"min":return n*60*1000;case"h":case"hour":return n*60*60*1000;default:return n*60*1000}}var cs={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",r=e.jsonBody?.email||e.formBody?.email||e.query?.email||"unknown";return`auth:${t}:${r}`},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:(r)=>{let n=r.user?.id;if(!n)throw Error("User authentication required for per-user rate limiting");return`user:${n}`},skipIf:(r)=>!r.user?.id}),perIP:(e,t)=>({maxAttempts:e,windowMs:t*60*1000,keyGenerator:(r)=>`ip:${r.headers.get("x-forwarded-for")?.split(",")[0]||r.headers.get("x-real-ip")||r.headers.get("cf-connecting-ip")||"unknown"}`}),global:(e,t)=>({maxAttempts:e,windowMs:t*60*1000,keyGenerator:()=>"global"})},Ki={fromString:(e,t)=>{let r=ee(e);return Y(r,t)},getInfo:async(e,t)=>{let r=new Oe(t),{info:n}=await r.checkLimit(e);return n},reset:(e,t)=>{let r=Xt.get(e);if(r)return r.cache.delete(t);return!1}};class k{static parseDomainPattern(e){let t=[],r=e.match(/\{([^}]+)\}/g)||[];for(let i of r){let o=i.slice(1,-1);t.push(o)}let n=e.replace(/\./g,"\\.").replace(/\{([^}]+)\}/g,"([^.]+)");n=`^${n}$`;let s=new RegExp(n,"i");return{pattern:e,parameters:t,regex:s}}static matchDomain(e,t){let r=e.match(t.regex);if(!r)return null;let n={};for(let s=0;s<t.parameters.length;s++){let i=t.parameters[s],o=r[s+1];n[i]=o}return n}static extractSubdomainInfo(e){let t=e.split(".");if(t.length<=2)return{domain:e,parameters:{},rootDomain:e};let r=t[0],n=t.slice(1).join(".");return{domain:e,parameters:{subdomain:r},subdomain:r,rootDomain:n}}}class ce{pattern;config;routes=[];constructor(e,t){this.pattern=e;this.config=t}addRoute(e,t,r,n=[],s){let i=[...this.config.middleware||[],...n],o=this.config.prefix?`${this.config.prefix}${t}`:t;this.routes.push({method:e.toUpperCase(),path:o,handler:r,middleware:i,name:s||(this.config.name?`${this.config.name}.${e.toLowerCase()}${t}`:void 0)})}getRoutes(){return[...this.routes]}matchesDomain(e){return k.matchDomain(e,this.pattern)}}class tt{domainGroups=[];wildcardGroup;domain(e){let t=k.parseDomainPattern(e);return new Qt(this,t)}addDomainGroup(e){if(e.pattern.pattern.includes("*")&&e.pattern.parameters.length===0)this.wildcardGroup=e;else this.domainGroups.push(e)}findDomainGroup(e){for(let t of this.domainGroups){let r=t.matchesDomain(e);if(r!==null)return{group:t,parameters:r}}if(this.wildcardGroup)return{group:this.wildcardGroup,parameters:k.extractSubdomainInfo(e).parameters};return null}getAllRoutes(){let e=[];for(let t of this.domainGroups){let r=t.getRoutes();for(let n of r)e.push({domainPattern:t.pattern.pattern,domainParameters:{},...n})}if(this.wildcardGroup){let t=this.wildcardGroup.getRoutes();for(let r of t)e.push({domainPattern:this.wildcardGroup.pattern.pattern,domainParameters:{},...r})}return e}}class Qt{router;pattern;group;constructor(e,t){this.router=e;this.pattern=t;this.group=new ce(t,{domain:t.pattern})}middleware(e){return this.group.config.middleware=e,this}prefix(e){return this.group.config.prefix=e,this}name(e){return this.group.config.name=e,this}routes(e){let t=new Zt(this.group);e(t),this.router.addDomainGroup(this.group)}get(e,t,r){this.group.addRoute("GET",e,t,r),this.router.addDomainGroup(this.group)}post(e,t,r){this.group.addRoute("POST",e,t,r),this.router.addDomainGroup(this.group)}put(e,t,r){this.group.addRoute("PUT",e,t,r),this.router.addDomainGroup(this.group)}delete(e,t,r){this.group.addRoute("DELETE",e,t,r),this.router.addDomainGroup(this.group)}patch(e,t,r){this.group.addRoute("PATCH",e,t,r),this.router.addDomainGroup(this.group)}}class Zt{group;constructor(e){this.group=e}get(e,t,r,n){this.group.addRoute("GET",e,t,r,n)}post(e,t,r,n){this.group.addRoute("POST",e,t,r,n)}put(e,t,r,n){this.group.addRoute("PUT",e,t,r,n)}delete(e,t,r,n){this.group.addRoute("DELETE",e,t,r,n)}patch(e,t,r,n){this.group.addRoute("PATCH",e,t,r,n)}options(e,t,r,n){this.group.addRoute("OPTIONS",e,t,r,n)}head(e,t,r,n){this.group.addRoute("HEAD",e,t,r,n)}any(e,t,r,n){let s=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];for(let i of s)this.group.addRoute(i,e,t,r,n)}}function Qi(e){return async(t,r)=>{let s=new URL(t.url).hostname,i=e.findDomainGroup(s);if(i){let o=t;o.domainParams=i.parameters,Object.assign(t.params||{},i.parameters);let a=k.extractSubdomainInfo(s);o.subdomainInfo=a}return await r()}}var Zi={getSubdomain:(e)=>{let t=new URL(e.url);return k.extractSubdomainInfo(t.hostname).subdomain||null},getDomainParams:(e)=>e.domainParams||{},matchesDomain:(e,t)=>{let r=new URL(e.url),n=k.parseDomainPattern(t);return k.matchDomain(r.hostname,n)!==null},getSubdomainInfo:(e)=>e.subdomainInfo||null},Yi={single:(e,t)=>`${e}.${t}`,wildcard:(e,t="subdomain")=>`{${t}}.${e}`,multiLevel:(e,...t)=>`${t.map((n)=>`{${n}}`).join(".")}.${e}`,apiVersion:(e)=>`{version}.api.${e}`,tenant:(e)=>`{tenant}.app.${e}`,environment:(e)=>`{env}.${e}`};import ls from"process";var te=new Map;function U(e,t){te.set(e,t)}function rt(e){return te.get(e)}function ds(){return new Map(te)}function ps(){te.clear()}function hs(e,t={},r={}){let n=te.get(e);if(!n){let u=[...te.keys()].sort().join(", ")||"(none registered)";throw Error(`Named route '${e}' is not defined. Known routes: ${u}`)}let s=new Set,i=n;for(let[u,c]of Object.entries(t)){let l=`{${u}}`,d=`{${u}?}`,p=encodeURIComponent(String(c));if(i.includes(l))i=i.replaceAll(l,p),s.add(u);else if(i.includes(d))i=i.replaceAll(d,p),s.add(u)}if(i.includes("?}")){if(i=i.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),i.length>1&&i.endsWith("/"))i=i.slice(0,-1)}let o=i.match(/\{([^}?]+)\}/g);if(o&&o.length>0)throw Error(`Missing required params for route '${e}': ${o.join(", ")}`);let a=Object.entries(t).filter(([u])=>!s.has(u));if(a.length>0){let u=new URLSearchParams;for(let[c,l]of a)u.set(c,String(l));i+=`?${u.toString()}`}if(r.absolute){let u=(r.base??ls.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${u.startsWith("http")?u:`https://${u}`}${i.startsWith("/")?i:`/${i}`}`}return i}import{join as Yt}from"path";function le(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 io(e){return e.replace(/\//g,"_").toLowerCase()}function gs(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 oo(e){return typeof e==="function"&&!gs(e)}function $e(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map((r)=>r.slice(1,-1).replace("?","")):[]}function ao(e){let t=e.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${t}$`)}var ms=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,fs=/\{[^}]+\?\}/,er=new Map,tr=new Map;function Rs(e){let t=er.get(e);if(t)return t;let r=e.endsWith("/*"),n=le(e),s=0,i=n.split("/").filter(Boolean).map((a)=>{let u=fs.test(a);if(u)s++;let c=a.match(ms);return{isParam:!!c,paramName:c?c[1].replace("?",""):"",isOptional:u,literal:a}}),o={isWildcard:r,wildcardBase:r?e.slice(0,-2):"",segments:i,optionalCount:s};return er.set(e,o),o}function ys(e){let t=tr.get(e);if(t!==void 0)return t;let r;try{r=new RegExp(`^${e}$`)}catch{r=null}return tr.set(e,r),r}function H(e,t,r,n){let s=Rs(e);if(s.isWildcard&&t.startsWith(s.wildcardBase))return!0;let i=s.segments,o=le(t).split("/").filter(Boolean);if(o.length<i.length-s.optionalCount||o.length>i.length)return!1;for(let a=0;a<i.length;a++){let u=i[a],c=o[a];if(c===void 0){if(u.isOptional)continue;return!1}if(u.isParam){let l=K(c);if(r[u.paramName]=l,n&&n[u.paramName]){let d=ys(n[u.paramName]);if(d){if(!d.test(l))return!1}else console.warn(`Invalid constraint regex for parameter ${u.paramName}: ${n[u.paramName]}`)}}else if(u.literal!==c)return!1}return!0}function F(...e){return le(e.join("/"))}function uo(e){if(!e.startsWith("/"))return!1;let t=[];for(let r of e)if(r==="{")t.push(r);else if(r==="}"){if(t.length===0||t.pop()!=="{")return!1}return t.length===0}async function rr(e){try{return await Bun.file(e).exists()}catch{return!1}}async function nt(e,t,r){if(r.some((n)=>e.endsWith(n))){let n=le(Yt(t,e));if(await rr(n))return n;return null}for(let n of r){let s=le(Yt(t,`${e}${n}`));if(await rr(s))return s}return null}function nr(e,t){let r=e.replace(/\{\{([^}]+)\}\}/g,(n,s)=>{let i=s.trim(),o=st(t,i);return o!==void 0?String(o):n});return r=ws(r,t),r=bs(r,t),r}function ws(e,t){return e.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(r,n,s,i="")=>{let o=n.trim();return st(t,o)?s:i})}function bs(e,t){return e.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(r,n,s)=>{let i=st(t,n.trim());if(!Array.isArray(i))return"";return i.map((o)=>s.replace(/\{\{@index\}\}/g,String(i.indexOf(o))).replace(/\{\{this\}\}/g,String(o)).replace(/\{\{this\.([^}]+)\}\}/g,(a,u)=>{let c=o[u.trim()];return c!==void 0?String(c):""})).join("")})}function st(e,t){return t.split(".").reduce((r,n)=>{if(r&&typeof r==="object"&&n in r)return r[n];return},e)}class f{method;path;handler;middleware=[];cacheConfig;throttleConfig;routeName;modelBindings={};constructor(e,t,r){this.method=e;this.path=t;this.handler=r}addMiddleware(e){if(Array.isArray(e))this.middleware.push(...e);else this.middleware.push(e);return this}cached(e=[],t){return this.cacheConfig={...Jt.api(e),...t},this}throttle(e,t){if(typeof e==="string"){let r=ee(e);this.throttleConfig={maxAttempts:r.maxAttempts??60,windowMs:r.windowMs,keyGenerator:(n)=>n.headers.get("x-forwarded-for")||"anonymous"}}else this.throttleConfig=e;return this}name(e){return this.routeName=e,this}model(e,t){return this.modelBindings[e]=t,this}build(){let e=[];if(Object.keys(this.modelBindings).length>0){let t=Object.keys(this.modelBindings).map((n)=>({name:n})),r=Lt(t,this.modelBindings);e.push(r)}if(this.throttleConfig){let t=Y(this.throttleConfig);e.push(t)}if(this.cacheConfig){let t=Vt(this.cacheConfig);e.push(t)}return e.push(...this.middleware),{method:this.method,path:this.path,handler:this.handler,middleware:e,name:this.routeName}}}class sr{router;condition;constructor(e,t){this.router=e;this.condition=t}middleware(e){let[t,r]=e.split(":"),n=this.router.resolveNamedMiddleware(t);if(!n)throw Error(`Unknown middleware: ${t}`);return this.router.addConditionalMiddleware({condition:this.condition,middleware:[n(r)]}),this}}class ir{router;middleware;constructor(e,t){this.router=e;this.middleware=t}get(e,t){return new f("GET",e,t).addMiddleware(this.middleware)}post(e,t){return new f("POST",e,t).addMiddleware(this.middleware)}put(e,t){return new f("PUT",e,t).addMiddleware(this.middleware)}delete(e,t){return new f("DELETE",e,t).addMiddleware(this.middleware)}patch(e,t){return new f("PATCH",e,t).addMiddleware(this.middleware)}}class or{router;groupMiddleware;constructor(e,t){this.router=e;this.groupMiddleware=t}get(e,t){return new f("GET",e,t).addMiddleware(this.groupMiddleware)}post(e,t){return new f("POST",e,t).addMiddleware(this.groupMiddleware)}put(e,t){return new f("PUT",e,t).addMiddleware(this.groupMiddleware)}delete(e,t){return new f("DELETE",e,t).addMiddleware(this.groupMiddleware)}patch(e,t){return new f("PATCH",e,t).addMiddleware(this.groupMiddleware)}}class de{routes=[];globalMiddleware=[];subdomainRouter=new tt;routeGroups=[];middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];constructor(){this.setupDefaultMiddleware()}setupDefaultMiddleware(){this.namedMiddleware.set("throttle",(e)=>{let t=e?ee(e):{maxAttempts:60,windowMs:60000},r=Y({maxAttempts:t.maxAttempts,windowMs:t.windowMs,keyGenerator:(s)=>s.headers.get("x-forwarded-for")||"anonymous"});return async(s,i)=>await r(s,async()=>await i()??new Response(null))}),this.namedMiddleware.set("auth",()=>async(e,t)=>{if(!e.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return e.user={id:"123",roles:["user"]},await t()}),this.namedMiddleware.set("cors",()=>async(e,t)=>{let r=await t();if(r){let n=new Headers(r.headers);return n.set("Access-Control-Allow-Origin","*"),n.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"),n.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(r.body,{status:r.status,statusText:r.statusText,headers:n})}return r})}middlewareGroup(e,t){let r=[];for(let n of t){let[s,i]=n.split(":"),o=this.namedMiddleware.get(s);if(o)r.push(o(i))}return this.middlewareGroups.set(e,r),this}middlewareGroupRoutes(e){let t=this.middlewareGroups.get(e)||[];return new or(this,t)}when(e){return new sr(this,e)}resolveNamedMiddleware(e){return this.namedMiddleware.get(e)}addConditionalMiddleware(e){this.conditionalMiddleware.push(e)}middleware(e){let[t,r]=e.split(":"),n=this.namedMiddleware.get(t);if(!n)throw Error(`Unknown middleware: ${t}`);let s=n(r);return new ir(this,[s])}use(e){return this.globalMiddleware.push(e),this}get(e,t){return new f("GET",e,t)}post(e,t){return new f("POST",e,t)}put(e,t){return new f("PUT",e,t)}delete(e,t){return new f("DELETE",e,t)}patch(e,t){return new f("PATCH",e,t)}register(e){let t=e.build();if(this.routes.push(t),t.name)U(t.name,t.path);return this}cached(e=[],t){return{get:(r,n)=>this.get(r,n).cached(e,t),post:(r,n)=>this.post(r,n).cached(e,t),put:(r,n)=>this.put(r,n).cached(e,t),delete:(r,n)=>this.delete(r,n).cached(e,t),patch:(r,n)=>this.patch(r,n).cached(e,t)}}throttled(e){return{get:(t,r)=>this.get(t,r).throttle(e),post:(t,r)=>this.post(t,r).throttle(e),put:(t,r)=>this.put(t,r).throttle(e),delete:(t,r)=>this.delete(t,r).throttle(e),patch:(t,r)=>this.patch(t,r).throttle(e)}}group(e,t){let r=new de;t(r);for(let n of r.routes){let s={...n,path:e.prefix?`${e.prefix}${n.path}`:n.path,middleware:[...e.middleware||[],...n.middleware],name:e.name&&n.name?`${e.name}.${n.name}`:n.name};if(e.domain){let i=k.parseDomainPattern(e.domain),o=new ce(i,{domain:e.domain});o.addRoute(s.method,s.path,s.handler,s.middleware,s.name),this.subdomainRouter.addDomainGroup(o)}else if(this.routes.push(s),s.name)U(s.name,s.path)}return this}domain(e){return{routes:(t)=>{let r=new de;t(r);let n=k.parseDomainPattern(e),s=new ce(n,{domain:e});for(let i of r.routes)s.addRoute(i.method,i.path,i.handler,i.middleware,i.name);return this.subdomainRouter.addDomainGroup(s),this}}}resource(e,t,r={}){let n=["index","create","store","show","edit","update","destroy"],s=r.only||n.filter((o)=>!r.except?.includes(o)),i=[{action:"index",method:"GET",path:`/${e}`,handler:t.index},{action:"create",method:"GET",path:`/${e}/create`,handler:t.create},{action:"store",method:"POST",path:`/${e}`,handler:t.store},{action:"show",method:"GET",path:`/${e}/{${e.slice(0,-1)}}`,handler:t.show},{action:"edit",method:"GET",path:`/${e}/{${e.slice(0,-1)}}/edit`,handler:t.edit},{action:"update",method:"PUT",path:`/${e}/{${e.slice(0,-1)}}`,handler:t.update},{action:"destroy",method:"DELETE",path:`/${e}/{${e.slice(0,-1)}}`,handler:t.destroy}];for(let o of i)if(s.includes(o.action)&&o.handler){let a=new f(o.method,o.path,o.handler).name(`${e}.${o.action}`);if(r.model&&["show","edit","update","destroy"].includes(o.action))a.model(e.slice(0,-1),r.model);this.register(a)}return this}getRoutes(){return[...this.routes,...this.subdomainRouter.getAllRoutes()]}async handle(e){let t=new URL(e.url),r=t.hostname,n=this.subdomainRouter.findDomainGroup(r);if(n){let s=e;s.domainParams=n.parameters;for(let i of n.group.getRoutes()){let o=this.matchRouteParams(i,e.method,t.pathname);if(o)return await this.executeRoute(i,s,o)}}for(let s of this.routes){let i=this.matchRouteParams(s,e.method,t.pathname);if(i)return await this.executeRoute(s,e,i)}return null}matchRouteParams(e,t,r){if(e.method!==t)return null;let n={};return H(e.path,r,n)?n:null}async executeRoute(e,t,r){t.params=r;let n=[...this.globalMiddleware];for(let o of this.conditionalMiddleware)if(await o.condition(t))n.push(...o.middleware);n.push(...e.middleware);let s=0,i=async()=>{if(s<n.length){let o=n[s++];return await o(t,i)??new Response(null)}return await e.handler(t)};return await i()}}var Ts={api:(e,t,r={})=>{let n=r.method||"GET",s=new f(n,e,t);if(r.cache)s.cached(r.cache);if(r.throttle)s.throttle(r.throttle);return s},protected:(e,t,r={})=>{let n=r.method||"GET",s=new f(n,e,t);return s.addMiddleware(async(i,o)=>{if(!i.headers.get("Authorization"))return new Response("Unauthorized",{status:401});return await o()}),s},upload:(e,t,r={})=>{let n=new f("POST",e,t);return n.addMiddleware(async(s,i)=>await i()),n}},xs={route:(e,t={},r={})=>{let n=rt(e)??`/${e}`;for(let[i,o]of Object.entries(t)){let a=encodeURIComponent(o);n=n.replace(`{${i}}`,a),n=n.replace(`{${i}?}`,a)}if(n.includes("?}")){if(n=n.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),n.length>1&&n.endsWith("/"))n=n.slice(0,-1)}let s=new URLSearchParams(r).toString();if(s)n+=`?${s}`;return n},redirect:(e,t=302)=>new Response(null,{status:t,headers:{Location:e}}),json:(e,t=200)=>new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}})},vs=new de;function ar(e){Object.defineProperties(e.prototype,{group:{value(t,r){let n=this.currentGroup,s={...n};if(t.prefix&&n?.prefix)s.prefix=F(n.prefix,t.prefix);else if(t.prefix)s.prefix=t.prefix;if(t.middleware)s.middleware=[...n?.middleware||[],...t.middleware];this.currentGroup=s;let i=r();if(i instanceof Promise)return i.then(()=>(this.currentGroup=n,this),(o)=>{throw this.currentGroup=n,o});return this.currentGroup=n,this},writable:!0,configurable:!0},name:{value(t,r){let n=this.currentGroup||{},s={...n};this.currentGroup=s;let i=this.routes.length;r();for(let o=i;o<this.routes.length;o++){let a=this.routes[o];if(a.name)a.name=`${t}.${a.name}`}return this.currentGroup=n,this},writable:!0,configurable:!0},controller:{value(t,r){let n=this.currentGroup||{},s={...n,controller:t};return this.currentGroup=s,r(),this.currentGroup=n,this},writable:!0,configurable:!0},domain:{value(t,r){let n=this.currentDomain;return this.currentDomain=t,r(),this.currentDomain=n,this},writable:!0,configurable:!0},prefix:{value(t,r){return this.group({prefix:t},r)},writable:!0,configurable:!0},resource:{value(t,r,n="api"){let s=t.endsWith("s")?t:`${t}s`,i=t.endsWith("s")?t.slice(0,-1):t,o=[{name:"index",method:"GET",path:`/${s}`,action:"index"},{name:"create",method:"GET",path:`/${s}/create`,action:"create"},{name:"store",method:"POST",path:`/${s}`,action:"store"},{name:"show",method:"GET",path:`/${s}/{id}`,action:"show"},{name:"edit",method:"GET",path:`/${s}/{id}/edit`,action:"edit"},{name:"update",method:"PUT",path:`/${s}/{id}`,action:"update"},{name:"destroy",method:"DELETE",path:`/${s}/{id}`,action:"destroy"}];return this.name(i,()=>{for(let a of o){let u;if(typeof r==="string")u=`${r}${a.action.charAt(0).toUpperCase()+a.action.slice(1)}Action`;else if(r[a.action])u=r[a.action];else continue;switch(a.method){case"GET":this.get(a.path,u,n,a.name);break;case"POST":this.post(a.path,u,n,a.name);break;case"PUT":this.put(a.path,u,n,a.name);break;case"DELETE":this.delete(a.path,u,n,a.name);break}}}),this},writable:!0,configurable:!0}})}function ur(e){Object.defineProperties(e.prototype,{addRoute:{value(t,r,n,s,i,o){let a=r,u=[],c=s||"web";if(this.currentGroup){if(this.currentGroup.prefix)a=F(this.currentGroup.prefix,r);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)u=[...this.currentGroup.middleware]}if(o&&o.length>0)for(let h of o){let m=this.resolveMiddleware(h);if(m)u.push(m)}if(c==="api"&&this.config.apiPrefix)a=F(this.config.apiPrefix,a);else if(c==="web"&&this.config.webPrefix)a=F(this.config.webPrefix,a);let l;if(this.currentDomain)l=this.currentDomain;let d={method:t.toUpperCase(),path:a,handler:n,domain:l,params:{},middleware:u},p=$e(a),g={};if(p.forEach((h)=>{let m=h.replace("?","");if(this.patterns.has(m))g[m]=this.patterns.get(m)}),Object.keys(g).length>0)d.constraints=g;if(d.pattern={exec:(h)=>{let m={},y=d.constraints&&!Array.isArray(d.constraints)?d.constraints:void 0;if(!H(a,h.pathname,m,y))return null;return{pathname:{groups:m}}}},n instanceof Response)this.staticResponses.set(a,n);if(l){if(!this.domains[l])this.domains[l]=[];this.domains[l].push(d)}else this.routes.push(d);if(!a.includes("{")&&!a.includes("*")){if(!this.staticRoutes.has(t.toUpperCase()))this.staticRoutes.set(t.toUpperCase(),new Map);let h=this.staticRoutes.get(t.toUpperCase());if(!h.has(a))h.set(a,d)}if(i)d.name=i,this.namedRoutes.set(i,d),U(i,d.path);if(this.addRouteToCompiler&&!l)this.addRouteToCompiler(d);return this.routeCache.clear(),this._allowedMethodsCache?.clear(),this},writable:!0,configurable:!0},get:{value(t,r,n,s,i){return this.addRoute("GET",t,r,n,s,i)},writable:!0,configurable:!0},post:{value(t,r,n,s,i){return this.addRoute("POST",t,r,n,s,i)},writable:!0,configurable:!0},put:{value(t,r,n,s,i){return this.addRoute("PUT",t,r,n,s,i)},writable:!0,configurable:!0},patch:{value(t,r,n,s,i){return this.addRoute("PATCH",t,r,n,s,i)},writable:!0,configurable:!0},delete:{value(t,r,n,s,i){return this.addRoute("DELETE",t,r,n,s,i)},writable:!0,configurable:!0},options:{value(t,r,n,s,i){return this.addRoute("OPTIONS",t,r,n,s,i)},writable:!0,configurable:!0},head:{value(t,r,n,s,i){return this.addRoute("HEAD",t,r,n,s,i)},writable:!0,configurable:!0},match:{value(t,r,n,s,i,o){for(let a of t)this.addRoute(a,r,n,s,i,o);return this},writable:!0,configurable:!0},any:{value(t,r,n,s,i){let o=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];return this.match(o,t,r,n,s,i)},writable:!0,configurable:!0},fallback:{value(t){return this.fallbackHandler=t,this},writable:!0,configurable:!0},route:{value(t,r={}){let n=this.namedRoutes.get(t);if(!n)throw Error(`Route with name "${t}" not found`);let s=n.path;for(let[i,o]of Object.entries(r))s=s.replace(`{${i}}`,encodeURIComponent(o)),s=s.replace(`{${i}?}`,encodeURIComponent(o));if(s.includes("{")){if(s=s.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),s.length>1&&s.endsWith("/"))s=s.slice(0,-1)}return s},writable:!0,configurable:!0},onError:{value(t){return this.errorHandler=t,this},writable:!0,configurable:!0}})}function cr(e){Object.defineProperties(e.prototype,{redirect:{value(t,r=302){let n=new Headers;return n.set("Location",t),new Response(null,{status:r,headers:n})},writable:!0,configurable:!0},permanentRedirect:{value(t){return this.redirect(t,301)},writable:!0,configurable:!0},redirectRoute:{value(t,r,n=302){return this.get(t,(s)=>this.redirect(r,n)),this},writable:!0,configurable:!0},permanentRedirectRoute:{value(t,r){return this.redirectRoute(t,r,301)},writable:!0,configurable:!0}})}function E(e){if(e instanceof Response)return e;if(e===null||e===void 0)return new Response(null,{status:204});if(typeof e==="string")return new Response(e,{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(typeof e==="number"||typeof e==="boolean")return new Response(String(e),{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(e instanceof ArrayBuffer||e instanceof Uint8Array)return new Response(e,{headers:{"Content-Type":"application/octet-stream"}});if(e instanceof ReadableStream)return new Response(e);if(typeof e==="object")return new Response(JSON.stringify(e),{headers:{"Content-Type":"application/json; charset=utf-8"}});return new Response(String(e),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}async function Cs(e,t){let r=t.actionsPath||"actions",n=t.controllersPath||"controllers",s=e.replace(/\.(ts|js)$/,""),i=[];if(s.includes("@")){let[a,u]=s.split("@");i.push(`${n}/${a}`,`${n}/${a}.ts`,`${n}/${a}.js`,`./${n}/${a}`,`../${n}/${a}`)}else if(s.startsWith("Actions/")||s.startsWith("actions/"))i.push(s,`./${s}`,`../${s}`);else if(s.startsWith("./")||s.startsWith("../"))i.push(s);else i.push(`${r}/${s}`,`./${r}/${s}`,`../${r}/${s}`,s,`./${s}`,`../${s}`);let o=null;for(let a of i)try{return await import(a)}catch(u){o=u}throw Error(`Failed to import handler "${e}".
94
- Tried paths: ${i.join(", ")}
95
- Last error: ${o?.message||"Unknown error"}`)}function lr(e){return typeof e==="function"&&!e.prototype?.handle}async function pe(e,t,r){if(e instanceof Response)return e.clone();if(lr(e)){let n=await e(t);return E(n)}if(typeof e==="string")return Ps(e,t,r);if(typeof e==="function"&&e.prototype&&typeof e.prototype.handle==="function"){let i=await new e().handle(t);return E(i)}if(e&&typeof e==="object"&&"handle"in e){let n=e;if(typeof n.handle==="function"){let s=await n.handle(t);return E(s)}}throw Error(`Invalid handler type: ${typeof e}`)}async function Ps(e,t,r){let n=r.controllersPath||"controllers";if(e.includes("@")){let[o,a]=e.split("@"),u=[`${n}/${o}`,`./${n}/${o}`,`../${n}/${o}`,o,`./${o}`,`../${o}`],c=null,l=null;for(let p of u)try{c=await import(p);break}catch(g){l=g}if(!c)throw Error(`Failed to import controller "${o}".
96
- Tried paths: ${u.join(", ")}
97
- Last error: ${l?.message||"Unknown error"}`);let d=c.default||c;if(typeof d==="function"){let p=new d,g=p[a];if(typeof g!=="function")throw TypeError(`Method "${a}" not found on controller "${o}"`);let h=await g.call(p,t);return E(h)}throw Error(`Controller "${o}" is not a valid class`)}let s=await Cs(e,r),i=s.default||s;if(typeof i==="function"){if(i.prototype&&typeof i.prototype.handle==="function"){let u=await new i().handle(t);return E(u)}let o=await i(t);return E(o)}if(i&&typeof i==="object"&&"handle"in i){let o=i;if(typeof o.handle==="function"){let a=await o.handle(t);return E(a)}}throw Error(`Handler "${e}" does not export a valid handler function or class`)}function Ms(e){return(t,r)=>pe(t,r,e)}function dr(e,t){if(e instanceof Response)return async()=>e.clone();if(lr(e))return async(r)=>E(await e(r));if(typeof e==="function"&&e.prototype&&typeof e.prototype.handle==="function"){let r=e;return async(n)=>E(await new r().handle(n))}return(r)=>pe(e,r,t)}function pr(e){Object.defineProperties(e.prototype,{use:{value(...t){for(let r of t){let n=this.resolveMiddleware(r);if(n)this.globalMiddleware.push(n)}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(r,n)=>t.handle(r,n);if(typeof t==="string"){let[r,n]=t.split(":"),s=this.namedMiddleware?.get(r);if(s)return s(n);let i=null,o=t;return async(a,u)=>{if(!i)try{let c=await import(`../middleware/${o}.ts`);if(c.default&&typeof c.default==="function")i=c.default;else if(c.default&&typeof c.default.handle==="function")i=(l,d)=>c.default.handle(l,d)}catch(c){console.error(`Failed to load middleware "${o}":`,c)}if(i)return i(a,u);return u()}}return null},writable:!0,configurable:!0},buildMiddlewareChain:{value(t){if(t.length===0)return async(n)=>null;let r=async(n)=>null;for(let n=t.length-1;n>=0;n--){let s=t[n],i=r;r=async(o)=>s(o,async()=>await i(o)||new Response(null,{status:200}))}return r},writable:!0,configurable:!0},runMiddleware:{async value(t,r){if(r.length===0)return null;try{return await this.buildMiddlewareChain(r)(t)}catch(n){if(this.errorHandler)return this.errorHandler(n);throw n}},writable:!0,configurable:!0},middleware:{value(...t){for(let r of t)if(typeof r==="string"){let[n]=r.split(":");if(!this.namedMiddleware.has(n))throw Error(`Unknown middleware: ${n}`)}if(this.currentGroup){if(!this.currentGroup.middleware)this.currentGroup.middleware=[];this.currentGroup.middleware.push(...t)}else{let r=this.routes[this.routes.length-1];if(r)this.applyMiddlewareToRoute(r,t)}return this},writable:!0,configurable:!0},applyMiddlewareToRoute:{value(t,r){for(let n of r){let s=this.resolveMiddleware(n);if(s)t.middleware.push(s)}},writable:!0,configurable:!0},resolveHandler:{async value(t,r){return pe(t,r,this.config)},writable:!0,configurable:!0},wrapResponse:{value:E,writable:!0,configurable:!0},onError:{value(t){return this.errorHandler=t,this},writable:!0,configurable:!0}})}class hr{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,r){let n=this.models.get(e);if(!n)return{model:null,error:`Model binding '${e}' not found`,status:500};try{if(n.cache?.enabled){let o=this.getCachedModel(e,t,n);if(o)return{model:o}}let s=await n.resolver(t,r);if(s===null||s===void 0)return{model:null,error:`${e} not found`,status:404};if(n.validator){let o=await n.validator(s,t,r);if(!o.valid)return{model:null,error:o.error||"Model validation failed",status:o.status||422}}let i=s;if(n.transformer)i=await n.transformer(s,t,r);if(n.cache?.enabled)this.cacheModel(e,t,i,n);return{model:i}}catch(s){return{model:null,error:s instanceof Error?s.message:"Model resolution failed",status:500}}}createErrorResponse(e,t,r){let n=this.models.get(e),s=t.status||404,i=t.error||"Model not found";if(n?.errorHandling){if(s===404&&n.errorHandling.notFound)return n.errorHandling.notFound(r);if(s===422&&n.errorHandling.validation)return n.errorHandling.validation(null,i);if(n.errorHandling.transform)return n.errorHandling.transform(i)}return new Response(JSON.stringify({error:i,status:s,message:`Failed to resolve ${e}`}),{status:s,headers:{"Content-Type":"application/json"}})}clearCache(e,t){if(t){let r=this.models.get(e);if(r?.cache){let n=this.generateCacheKey(e,t,r);this.cache.delete(n)}}else{let r=[];for(let n of this.cache.keys())if(n.startsWith(`${e}:`))r.push(n);for(let n of r)this.cache.delete(n)}}clearAllCache(){this.cache.clear()}getCacheStats(){let e=Date.now(),t=0,r=0;for(let n of this.cache.values())if(e-n.timestamp>n.ttl)r++;else t++;return{totalEntries:this.cache.size,validEntries:t,expiredEntries:r,models:this.models.size}}cleanupCache(){let e=Date.now(),t=[];for(let[r,n]of this.cache.entries())if(e-n.timestamp>n.ttl)t.push(r);for(let r of t)this.cache.delete(r);return t.length}getCachedModel(e,t,r){if(!r.cache?.enabled)return null;let n=this.generateCacheKey(e,t,r),s=this.cache.get(n);if(!s)return null;if(Date.now()-s.timestamp>s.ttl)return this.cache.delete(n),null;return s.model}cacheModel(e,t,r,n){if(!n.cache?.enabled)return;let s=this.generateCacheKey(e,t,n);this.cache.set(s,{model:r,timestamp:Date.now(),ttl:n.cache.ttl})}generateCacheKey(e,t,r){if(r.cache?.key)return`${e}:${r.cache.key(t)}`;let n=Object.entries(t).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${s}=${i}`).join("&");return`${e}:${n}`}}var gr=new hr;function mr(e){Object.defineProperties(e.prototype,{modelRegistry:{value:gr,writable:!0,configurable:!0},model:{value(t,r,n){if(typeof r==="string")this.modelRegistry.register(t,{resolver:async(s)=>(console.warn(`Model class ${r} not implemented`),{id:s[t],modelClass:r}),errorHandling:n?{notFound:(s)=>n(null)||new Response("Not Found",{status:404})}:void 0});else this.modelRegistry.register(t,{resolver:async(s)=>{let i=s[t];if(!i)return null;return r(i)},errorHandling:n?{notFound:(s)=>n(null)||new Response("Not Found",{status:404})}:void 0});return this},writable:!0,configurable:!0},implicitBinding:{value(){return async(t,r)=>{if(!t.params)return await r()||new Response("Not Found",{status:404});for(let[s,i]of Object.entries(t.params))if(this.modelRegistry.has(s))try{let o=await this.modelRegistry.resolve(s,t.params,t);if(o.model===null){if(o.status===500)return new Response(JSON.stringify({error:"Internal Server Error",message:o.error||"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}});else if(o.status===404)return this.modelRegistry.createErrorResponse(s,o,t.params)}else t[s]=o.model}catch(o){return new Response(JSON.stringify({error:"Internal Server Error",message:o instanceof Error?o.message:"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}})}return await r()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},missing:{value(t){return async(r,n)=>{try{return await n()||t(r)}catch(s){return console.error(s),t(r)}}},writable:!0,configurable:!0},scopedBindings:{value(t){return async(r,n)=>{if(!r.params)return await n()||new Response("Not Found",{status:404});for(let[i,o]of Object.entries(t))if(r.params[i]&&r.params[o]);return await n()||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 I{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 it{root=new I;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 I)}compileRoute(e){let t=`${e.method}:${e.path}`;if(e.constraints&&!Array.isArray(e.constraints)){let u=e.constraints,l=Object.keys(u).sort().map((d)=>`${d}:${u[d]}`).join("|");t=`${e.method}:${e.path}#${l}`}if(this.compiledRoutes.has(t))return this.compiledRoutes.get(t);let r=this.parsePathSegments(e.path),n=r.filter((u)=>u.type==="parameter").map((u)=>u.paramName);if(e.constraints&&!Array.isArray(e.constraints)){let u=e.constraints;for(let c of r)if(c.type==="parameter"&&c.paramName&&u[c.paramName])c.pattern=new RegExp(`^${u[c.paramName]}$`)}let s=this.calculateRoutePriority(r),i=r.filter((u)=>u.type==="static").length,o=r.filter((u)=>u.type!=="static").length,a={route:e,segments:r,paramNames:n,priority:s,staticScore:i,dynamicScore:o};return this.compiledRoutes.set(t,a),a}parsePathSegments(e){let t=[],r=e.split("/").filter((n)=>n.length>0);for(let n of r)if(n==="*")t.push({type:"wildcard",value:"*"});else if(/^\{[^{}/]+\}\*$/.test(n))t.push({type:"wildcard",value:n,paramName:n.slice(1,n.indexOf("}"))});else if(n.startsWith("{")&&n.endsWith("}")){let s=n.slice(1,-1),[i,o]=s.split(":");t.push({type:"parameter",value:n,paramName:i.replace("?",""),pattern:o?new RegExp(`^${o}$`):void 0,optional:s.endsWith("?")})}else if(n.includes("{")){let s=n.replace(/\{([^}:]+)(?::([^}]+))?\}/g,(o,a,u)=>u?`(${u})`:"([^/]+)"),i=Array.from(n.matchAll(/\{([^}:]+)(?::([^}]+))?\}/g)).map((o)=>o[1].replace("?",""));t.push({type:"parameter",value:n,paramName:i[0],pattern:new RegExp(`^${s}$`)})}else t.push({type:"static",value:n});return t}calculateRoutePriority(e){let t=0;for(let r=0;r<e.length;r++){let n=e[r],s=e.length-r;switch(n.type){case"static":t+=s*1000;break;case"parameter":if(n.pattern)t+=s*100;else t+=s*10;break;case"wildcard":t+=s*1;break}}return t}addRoute(e){let t=this.compileRoute(e);this.insertRoute(this.root,t,0);let r=this.methodTries.get(e.method);if(r)this.insertRoute(r,t,0)}insertRoute(e,t,r){if(r>=t.segments.length){e.addRoute(t.route.method,t);return}let n=t.segments[r];switch(n.type){case"static":if(!e.children.has(n.value))e.children.set(n.value,new I);this.insertRoute(e.children.get(n.value),t,r+1);break;case"parameter":if(!e.paramChild)e.paramChild=new I,e.paramChild.paramName=n.paramName,e.paramChild.pattern=n.pattern||null;this.insertRoute(e.paramChild,t,r+1);break;case"wildcard":if(!e.wildcardChild)e.wildcardChild=new I,e.wildcardChild.paramName=n.paramName??null;this.insertRoute(e.wildcardChild,t,r+1);break}}match(e,t){let r=e.split("/").filter((s)=>s.length>0),n=this.methodTries.get(t);if(n){let s=this.matchSegments(n,r,0,{},t);if(s)return s}return this.matchSegments(this.root,r,0,{},t)}matchSegments(e,t,r,n,s){if(r>=t.length){let c=e.getRoute(s);if(c)return{route:c.route,params:n,score:c.priority};return null}let i=t[r],o=e.children.get(i);if(o){let c=this.matchSegments(o,t,r+1,n,s);if(c)return c}let a=e.paramChild,u=a?.paramName?K(i):i;if(a&&a.paramName&&(!a.pattern||a.pattern.test(u))){let c=n[a.paramName];n[a.paramName]=u;let l=this.matchSegments(a,t,r+1,n,s);if(l)return l;if(c===void 0)delete n[a.paramName];else n[a.paramName]=c}if(e.wildcardChild){let c=e.wildcardChild.getRoute(s);if(c)return n[e.wildcardChild.paramName??"wildcard"]=t.slice(r).map(K).join("/"),{route:c.route,params:n,score:c.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 r=e.constraints,s=Object.keys(r).sort().map((i)=>`${i}:${r[i]}`).join("|");t=`${e.method}:${e.path}#${s}`}this.compiledRoutes.delete(t)}clear(){this.root=new I,this.compiledRoutes.clear();for(let[e]of this.methodTries)this.methodTries.set(e,new I)}getStats(){let e={totalRoutes:this.compiledRoutes.size,totalNodes:this.countNodes(this.root),averageDepth:0,methodDistribution:{}};for(let t of this.compiledRoutes.values()){let r=t.route.method;e.methodDistribution[r]=(e.methodDistribution[r]||0)+1}return e}countNodes(e){let t=1;for(let r of e.children.values())t+=this.countNodes(r);if(e.paramChild)t+=this.countNodes(e.paramChild);if(e.wildcardChild)t+=this.countNodes(e.wildcardChild);return t}}class Be{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 it}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 r=e.method;return this.stats.methodDistribution[r]=(this.stats.methodDistribution[r]||0)+1,!0}patternCache=new Map;extractParamNames(e){let t=[],r=/\{([^}:]+)(?::[^}]+)?\}/g,n;while(n=r.exec(e))t.push(n[1].replace("?",""));return t}precompileRoutePattern(e){if(!e.pattern&&e.path.includes("{")){let t=e.path;if(e.constraints&&!Array.isArray(e.constraints)){let s=e.constraints,o=Object.keys(s).sort().map((a)=>`${a}:${s[a]}`).join("|");t=`${e.path}#${o}`}if(this.patternCache.has(t)){e.pattern=this.patternCache.get(t);return}let r=this.convertToURLPattern(e.path,e.constraints&&!Array.isArray(e.constraints)?e.constraints:void 0),n={exec:(s)=>{let i=s.pathname,o=r.exec(i);if(!o)return null;return{pathname:{groups:o.groups||{}}}}};this.patternCache.set(t,n),e.pattern=n}}convertToURLPattern(e,t){let r=e,n=null,s=r.match(/\{([^{}/]+)\}\*$/);if(s)n=s[1],r=r.slice(0,s.index);else if(r.endsWith("*"))n="wildcard",r=r.slice(0,-1);let i=[],a=r.replace(/\{([^}]+)\}/g,(c,l)=>(i.push(l),`\x00${i.length-1}\x00`)).replace(/[.+*?^${}()|[\]\\]/g,"\\$&");if(a=a.replace(/\/?\u0000(\d+)\u0000/g,(c,l)=>{let d=i[Number(l)],p=d.endsWith("?"),g=p?d.slice(0,-1):d,h=g.indexOf(":"),m=h===-1?g:g.slice(0,h),y=h===-1?void 0:g.slice(h+1),x=t?.[m]??y??"[^/]+",V=`(?<${m}>${x})`,Re=c.startsWith("/")?"/":"";return p?`(?:${Re}${V})?`:`${Re}${V}`}),n!==null)a+=`(?<${n}>${t?.[n]??".+"})`;let u=new RegExp(`^${a}$`);return{exec:(c)=>{let l=c.match(u);if(!l)return null;return{groups:l.groups||{}}}}}match(e,t){let r=this.options.enableProfiling?performance.now():0;if(this.stats.totalMatches++,this.options.enableCaching){let i=`${t}:${e}`,o=this.matchCache.get(i);if(o!==void 0||this.matchCache.has(i)){if(this.stats.cacheHits++,r)this.updateMatchTime(r);return o?{route:o.route,params:{...o.params}}:null}this.stats.cacheMisses++}let n=this.trie.match(e,t),s=null;if(n)s={route:n.route,params:n.params};if(this.options.enableCaching){let i=`${t}:${e}`;this.addToCache(i,s)}if(r)this.updateMatchTime(r);return s?{route:s.route,params:{...s.params}}:null}addToCache(e,t){if(this.matchCache.size>=this.options.cacheSize&&!this.matchCache.has(e)){let r=this.matchCache.keys().next().value;if(r!==void 0)this.matchCache.delete(r)}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,r)=>r.priority-t.priority);return e}getRoutesByMethod(){let e=new Map;for(let t of this.trie.getAllRoutes()){let r=t.route.method;if(!e.has(r))e.set(r,[]);e.get(r).push(t)}if(this.options.enablePriorityOptimization)for(let[t,r]of e)r.sort((n,s)=>s.priority-n.priority),e.set(t,r);return e}warmCache(e,t={}){if(!this.options.enableCaching&&!t.force)return{warmedPaths:0,cacheSize:0,hitRate:0};let r=this.options.enableCaching;if(t.force&&!this.options.enableCaching)this.options.enableCaching=!0;if(t.precompile)for(let{path:l,method:d}of e){let p=`${d}:${l}`;this.matchCache.delete(p)}let n=this.matchCache.size,s=this.stats.cacheHits,i=this.stats.totalMatches;for(let{path:l,method:d}of e)if(this.match(l,d),t.precompile)this.match(l,d);let o=this.matchCache.size-n,a=this.stats.cacheHits-s,u=this.stats.totalMatches-i,c=u>0?a/u:0;if(t.force&&!r)this.options.enableCaching=r;return{warmedPaths:o,cacheSize:this.matchCache.size,hitRate:c}}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(),r=new Map;for(let n of t){let s=n.route.method;if(!r.has(s))r.set(s,[]);r.get(s).push(n)}for(let[n,s]of r)for(let i=0;i<s.length;i++)for(let o=i+1;o<s.length;o++){let a=s[i],u=s[o];if(this.routesConflict(a,u)){let c=this.getConflictSeverity(a,u),l=this.getConflictType(a,u);e.push({routes:[a,u],conflictType:l,severity:c})}}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 r=e.some((o)=>o.optional||o.type==="wildcard"),n=t.some((o)=>o.optional||o.type==="wildcard");if(e.length!==t.length&&!r&&!n)return!1;let s=Math.max(e.length,t.length),i=!0;for(let o=0;o<s;o++){let a=o<e.length?e[o]:null,u=o<t.length?t[o]:null;if(!a&&u&&!u.optional)return!1;if(!u&&a&&!a.optional)return!1;if(!a||!u)continue;if(a.type==="static"&&u.type==="static"){if(a.value!==u.value)return!1}else if(a.type==="parameter"&&u.type==="parameter"){if(a.pattern&&u.pattern){if(a.pattern.toString()===u.pattern.toString())i=!0}if(a.paramName===u.paramName)i=!0}else if(a.type==="static"&&u.type==="parameter"||a.type==="parameter"&&u.type==="static"){let c=a.type==="static"?a:u,l=a.type==="parameter"?a:u;if(l.pattern){if(!l.pattern.test(c.value))return!1}}else if(a.type==="wildcard"||u.type==="wildcard")return!0}return i}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 r=e.segments.filter((s)=>s.type==="parameter").length,n=t.segments.filter((s)=>s.type==="parameter").length;if(r>0&&n>0){let s=Math.min(e.segments.length,t.segments.length),i=0;for(let o=0;o<s;o++)if(e.segments[o].type==="parameter"&&t.segments[o].type==="parameter"){i++;let a=!!e.segments[o].pattern,u=!!t.segments[o].pattern;if(a!==u)return!0}return i>0&&i>=Math.min(r,n)/2}return!1}}function fr(e){Object.defineProperties(e.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new Be({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,r,n){if(this.initializeRouteCompiler(),n&&this.domains[n]){let s=this.fallbackMatchRoute(t,r,n);if(s)return s}else{let s=this.routeCompiler.match(t,r);if(s&&(!n||!s.route.domain||s.route.domain===n))return s;let i=this.fallbackMatchRoute(t,r,n);if(i)return i}if(r==="HEAD")return this.matchRoute(t,"GET",n);return},writable:!0,configurable:!0},fallbackMatchRoute:{value(t,r,n){let s=new URL(t,"http://localhost"),i=`${n||""}:${r}:${s.pathname}`;if(this.routeCache.has(i))return this.routeCache.get(i);if(this.routeCache.size>=1e4)this.routeCache.clear();if(this.staticRoutes.has(r)){let c=this.staticRoutes.get(r).get(s.pathname);if(c&&(!n||!c.domain||c.domain===n)){let l={route:c,params:{}};return this.routeCache.set(i,l),l}}let a=(n&&this.domains[n]?this.domains[n]:this.routes).filter((c)=>c.method===r);for(let c of a)if(c.path===s.pathname){let l={route:c,params:{}};return this.routeCache.set(i,l),l}for(let c of a)if(c.pattern){let l=c.pattern.exec(s);if(l){let d={route:c,params:l.pathname.groups};return this.routeCache.set(i,d),d}}let u=n&&this.domains[n]?[this.domains[n],this.routes]:[this.routes];for(let c of u)for(let l of c){if(l.method!==r||!l.path.endsWith("*"))continue;let d=l.path.slice(0,-1);if(s.pathname.startsWith(d)){let p={route:l,params:{wildcard:s.pathname.slice(d.length)}};return this.routeCache.set(i,p),p}}this.routeCache.set(i,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 Be({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 r of t)this.routeCompiler.addRoute(r)},writable:!0,configurable:!0},optimizeRoutes:{value(t={}){this.initializeRouteCompiler(),this.routeCompiler.optimizeRouteOrder(t)},writable:!0,configurable:!0}})}function Rr(e){Object.defineProperties(e.prototype,{buildBunServeRoutes:{value(){let t={},r=new Map;for(let n of this.routes){if(!r.has(n.path))r.set(n.path,[]);r.get(n.path).push(n)}for(let[n,s]of r.entries())if(s.length===1){let i=s[0];if(typeof i.handler==="function"&&i.handler.toString().includes("new Response")&&!i.handler.toString().includes("await")&&i.middleware.length===0)try{let o=this.enhanceRequest(new Request("https://example.com"),{}),a=i.handler(o);if(a instanceof Response){t[n]=a;continue}}catch{}t[n]=async(o)=>{let a=new URL(o.url),u={},c=i.constraints&&!Array.isArray(i.constraints)?i.constraints:void 0;H(n,a.pathname,u,c);let l=this.enhanceRequest(o,u),d=async(h,m)=>await this.resolveHandler(i.handler,h),p=[...this.globalMiddleware,...i.middleware,d],g=await this.runMiddleware(l,p);return this.applyModifiedCookies(g??new Response("No response from middleware chain",{status:500}),l)}}else{let i={};for(let o of s){let a=o.method;i[a]=async(u)=>{let c=new URL(u.url),l={},d=o.constraints&&!Array.isArray(o.constraints)?o.constraints:void 0;H(n,c.pathname,l,d);let p=this.enhanceRequest(u,l),g=async(y,x)=>await this.resolveHandler(o.handler,y),h=[...this.globalMiddleware,...o.middleware,g],m=await this.runMiddleware(p,h);return this.applyModifiedCookies(m??new Response("No response from middleware chain",{status:500}),p)}}t[n]=i}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 r of t.default)this.registerRoute(r,"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 r of t.default)this.registerRoute(r,"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,r){let{path:n,method:s,handler:i,middleware:o=[],name:a}=t;switch(s){case"GET":this.get(n,i,r,a,o);break;case"POST":this.post(n,i,r,a,o);break;case"PUT":this.put(n,i,r,a,o);break;case"DELETE":this.delete(n,i,r,a,o);break;case"PATCH":this.patch(n,i,r,a,o);break;case"OPTIONS":this.options(n,i,r,a,o);break;default:console.warn(`Unsupported HTTP method: ${s}`)}},writable:!0,configurable:!0}})}function yr(e){Object.defineProperties(e.prototype,{matchRoute:{value(t,r,n){let s=new URL(t,"http://localhost"),i=`${n||""}:${r}:${s.pathname}`;if(this.routeCache.has(i))return this.routeCache.get(i);if(this.staticRoutes.has(r)){let c=this.staticRoutes.get(r).get(s.pathname);if(c&&(!n||!c.domain||c.domain===n)){let l={route:c,params:{}};return this.routeCache.set(i,l),l}}let o=n&&this.domains[n]?this.domains[n]:this.routes,a=o.filter((c)=>c.method===r);for(let c of a)if(c.path===s.pathname){let l={route:c,params:{}};return this.routeCache.set(i,l),l}for(let c of a)if(c.pattern){let l=c.pattern.exec(s);if(l){let d={route:c,params:l.pathname.groups};return this.routeCache.set(i,d),d}}if(n&&this.domains[n]){let c=this.domains[n].filter((l)=>l.method===r&&l.path.endsWith("*"));for(let l of c){let d=l.path.slice(0,-1);if(s.pathname.startsWith(d)){let p={route:l,params:{wildcard:s.pathname.slice(d.length)}};return this.routeCache.set(i,p),p}}}let u=this.routes.filter((c)=>c.method===r&&c.path.endsWith("*")&&(!n||!c.domain));for(let c of u){let l=c.path.slice(0,-1);if(s.pathname.startsWith(l)){let d={route:c,params:{wildcard:s.pathname.slice(l.length)}};return this.routeCache.set(i,d),d}}if(r==="HEAD")return this.matchRoute(t,"GET",n);if(r==="OPTIONS"){let c=o.find((l)=>l.method==="OPTIONS"&&l.path==="*");if(c){let l={route:c,params:{}};return this.routeCache.set(i,l),l}for(let l of["GET","POST","PUT","PATCH","DELETE"]){let d=this.matchRoute(t,l,n);if(d){let p={route:{...d.route,method:"OPTIONS",handler:(g)=>new Response(null,{status:204})},params:d.params};return this.routeCache.set(i,p),p}}}return},writable:!0,configurable:!0},matchDomain:{value(t,r){if(t===r)return!0;if(t.startsWith("*.")){let n=t.substring(2);return r===n||r.endsWith(`.${n}`)}if(t.includes("{")){let n;if(!this.domainPatternCache.has(t)){let s=t.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)");n=new RegExp(`^${s}$`),this.domainPatternCache.set(t,n)}else n=this.domainPatternCache.get(t);return n.test(r)}return!1},writable:!0,configurable:!0},extractDomainParams:{value(t,r){let n={};if(!t.includes("{"))return n;let s=t.match(/\{([^}]+)\}/g)?.map((a)=>a.substring(1,a.length-1))||[],i=t.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)"),o=r.match(new RegExp(`^${i}$`));if(o&&o.length>1)for(let a=0;a<s.length;a++)n[s[a]]=o[a+1];return n},writable:!0,configurable:!0},pattern:{value(t,r){return this.patterns.set(t,r),this},writable:!0,configurable:!0},where:{value(t){let r=this.routes[this.routes.length-1];if(r){r.constraints={...r.constraints||{},...t};let n=r.path,s=r.constraints&&!Array.isArray(r.constraints)?r.constraints:void 0;if(r.pattern={exec:(i)=>{let o={};if(!H(n,i.pathname,o,s))return null;return{pathname:{groups:o}}}},this.routeCache.clear(),this.routeCompiler){let i=[...this.routes];this.routeCompiler.clear();for(let o of i)this.routeCompiler.addRoute(o)}}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,r){return this.where({[t]:r.join("|")})},writable:!0,configurable:!0}})}var Es=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,Ss=/bot|crawler|spider|crawling/i,De=new Map;function re(e){let t=e;if(!t._parsedURL)t._parsedURL=new URL(e.url);return t._parsedURL}function L(e){let t=e;if(!t._parsedCookies){let r={},n=e.headers.get("cookie");if(n)for(let s of n.split(";")){let i=s.indexOf("=");if(i===-1)continue;let o=s.slice(0,i).trim();if(!o)continue;let a=s.slice(i+1).trim();try{r[o]=decodeURIComponent(a)}catch{r[o]=a}}t._parsedCookies=r}return t._parsedCookies}class Tr{macros=new Map;epoch=0;register(e,t,r=!1){this.macros.set(e,{name:e,handler:t,accessor:r}),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 he=new Tr,wr=Symbol("bunRouterMacroProto"),ot=Symbol("bunRouterMacroBase"),Fe=new WeakMap,br=-1;class b{static macro(e,t){he.register(e,t)}static macroAccessor(e,t){he.register(e,t,!0)}static applyMacros(e){let t=he.getEpoch();if(t!==br)Fe=new WeakMap,br=t;let r=Object.getPrototypeOf(e)??Object.prototype;if(r[wr]){if(Fe.get(r[ot])===r)return e;r=r[ot]}let n=Fe.get(r);if(!n){n=Object.create(r);for(let s of he.all())if(s.accessor)Object.defineProperty(n,s.name,{get:s.handler,set(i){Object.defineProperty(this,s.name,{value:i,writable:!0,configurable:!0,enumerable:!0})},configurable:!0});else n[s.name]=s.handler;Object.defineProperty(n,wr,{value:!0}),Object.defineProperty(n,ot,{value:r}),Fe.set(r,n)}return Object.setPrototypeOf(e,n),e}static hasMacro(e){return he.has(e)}}var ge={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 Es.test(this.headers.get("user-agent")||"")},isBot(){return Ss.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[ge.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)),[r,n]=t.split(":");return{username:r,password:n}}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,r)=>{e[r]=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(),r={};return e.forEach((n)=>{if(n in t)r[n]=t[n]}),r},except(e){let t=this.all(),r={};return Object.keys(t).forEach((n)=>{if(!e.includes(n))r[n]=t[n]}),r},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 r=L(this)[e];return r!==void 0?r:t||null},cookies(){return{...L(this)}},file(e){return this.files?.find((t)=>t.fieldName===e)},hasFile(e){return!!this.files?.find((t)=>t.fieldName===e)},path(){return re(this).pathname},fullUrl(){return this.url},root(){let e=re(this);return`${e.protocol}//${e.host}`},is(e){let t=this.path(),r=De.get(e);if(!r){let n=e.replace(/\*/g,".*").replace(/\?/g,".");if(r=new RegExp(`^${n}$`),De.size>=1000)De.clear();De.set(e,r)}return r.test(t)},route(){return this.routeName||null},fingerprint(){let e=re(this),t={method:this.method,path:e.pathname,query:e.search,ip:ge.ip.call(this)};return btoa(JSON.stringify(t))},signature(e){let t=`${this.method}${this.url}${ge.ip.call(this)}${e}`,r=0;for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);r=(r<<5)-r+s,r=r&r}return Math.abs(r).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=ge.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 ks(){Object.entries(ge).forEach(([e,t])=>{b.macro(e,t)})}ks();function Ne(e){let t=e;if(!t._parsedQuery){let r={};for(let[n,s]of re(e).searchParams){let i=r[n];if(i===void 0)r[n]=s;else if(Array.isArray(i))i.push(s);else r[n]=[i,s]}t._parsedQuery=r}return t._parsedQuery}class w{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;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?ee(e):{maxAttempts:60,windowMs:60000};return Y({maxAttempts:t.maxAttempts||60,windowMs:t.windowMs,keyGenerator:(r)=>r.headers.get("x-forwarded-for")||"anonymous"})}),this.namedMiddleware.set("cors",()=>async(e,t)=>{let r=await t();if(r)r.headers.set("Access-Control-Allow-Origin","*"),r.headers.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),r.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization");return r})}middlewareGroup(e,t){let r=[];for(let n of t){let[s,i]=n.split(":"),o=this.namedMiddleware.get(s);if(o)r.push(o(i))}return this.middlewareGroups.set(e,r),this}middlewareGroupRoutes(e){let t=this.middlewareGroups.get(e)||[];return new Cr(this,t)}when(e){return new xr(this,e)}middleware(e){let[t,r]=e.split(":"),n=this.namedMiddleware.get(t);if(!n)throw Error(`Unknown middleware: ${t}`);let s=n(r);return new vr(this,[s])}getServer(){return this.serverInstance}extend(e){for(let[t,r]of Object.entries(e))if(typeof r==="function")this[t]=r.bind(this);return this}async register(e,t){let r=async()=>{await import(e)};if(t?.prefix||t?.middleware&&t.middleware.length>0)await this.group({prefix:t.prefix,middleware:t.middleware},r);else await r();return this}invalidateCache(){this.routeCache.clear(),this._allowedMethodsCache.clear()}registerRoute(e,t,r,n,s,i){let o=t,a=[],u=n||"web";if(this.currentGroup){if(this.currentGroup.prefix)o=F(this.currentGroup.prefix,t);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)a=[...this.currentGroup.middleware]}if(i&&i.length>0)for(let g of i){let h=this.resolveMiddleware(g);if(h)a.push(h)}if(u==="api"&&this.config.apiPrefix)o=F(this.config.apiPrefix,o);else if(u==="web"&&this.config.webPrefix)o=F(this.config.webPrefix,o);let c;if(this.currentDomain)c=this.currentDomain;let l={method:e.toUpperCase(),path:o,handler:r,domain:c,params:{},middleware:a},d=$e(o),p={};if(d.forEach((g)=>{let h=g.replace("?","");if(this.patterns.has(h))p[h]=this.patterns.get(h)}),Object.keys(p).length>0)l.constraints=p;if(l.pattern={exec:(g)=>{let h={},m=l.constraints&&!Array.isArray(l.constraints)?l.constraints:void 0;if(!H(o,g.pathname,h,m))return null;return{pathname:{groups:h}}}},c){if(!this.domains[c])this.domains[c]=[];this.domains[c].push(l)}else this.routes.push(l);if(!o.includes("{")&&!o.includes("*")){if(!this.staticRoutes.has(e.toUpperCase()))this.staticRoutes.set(e.toUpperCase(),new Map);this.staticRoutes.get(e.toUpperCase()).set(o,l)}if(s)l.name=s,this.namedRoutes.set(s,l),U(s,l.path);return this.routeCache.clear(),this}resolveMiddleware(e){if(typeof e==="function")return e;let[t,r]=e.split(":"),n=this.namedMiddleware.get(t);if(n)return n(r);return null}get(e,t,r,n,s){return this.registerRoute("GET",e,t,r,n,s)}post(e,t,r,n,s){return this.registerRoute("POST",e,t,r,n,s)}put(e,t,r,n,s){return this.registerRoute("PUT",e,t,r,n,s)}patch(e,t,r,n,s){return this.registerRoute("PATCH",e,t,r,n,s)}delete(e,t,r,n,s){return this.registerRoute("DELETE",e,t,r,n,s)}options(e,t,r,n,s){return this.registerRoute("OPTIONS",e,t,r,n,s)}match(e,t,r,n,s,i){for(let o of e)this.registerRoute(o,t,r,n,s,i);return this}any(e,t,r,n,s){for(let i of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this.registerRoute(i,e,t,r,n,s);return this}fallback(e){return this.fallbackHandler=e,this}route(e,t={}){let r=this.namedRoutes.get(e);if(!r)throw Error(`Route with name "${e}" not found`);let n=r.path;for(let[s,i]of Object.entries(t))n=n.replace(`{${s}}`,encodeURIComponent(i)),n=n.replace(`{${s}?}`,encodeURIComponent(i));return n}onError(e){return this.errorHandler=e,this}redirect(e,t=302){let r=new Headers;return r.set("Location",e),new Response(null,{status:t,headers:r})}permanentRedirect(e){return this.redirect(e,301)}redirectRoute(e,t,r=302){return this.get(e,(n)=>this.redirect(t,r)),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 r=this.serverInstance.port,n=this.serverInstance.hostname;console.log(`
98
- \uD83D\uDE80 Server running at http://${n}:${r}
99
- `)}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 o=t.hostname||e.headers.get("host")?.split(":")[0]||"localhost";if(!this.matchRoute(t.pathname,"OPTIONS",o))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 r=t.hostname||e.headers.get("host")?.split(":")[0]||"localhost",n=this.matchRoute(t.pathname,e.method,r),s=this.enhanceRequest(e,n?.params||{});if(n){s.route=n.route;let o=[...this.globalMiddleware];if(n.route.middleware&&n.route.middleware.length>0)o.push(...n.route.middleware);let a=async(c,l)=>await this.resolveHandler(n.route.handler,c);o.push(a);let u=await this.runMiddleware(s,o);if(u)return this.applyModifiedCookies(u,s);return new Response("No response from middleware chain",{status:500})}let i=this.getAllowedMethods(t.pathname,r);if(i.length>0){let o=async(a,u)=>new Response(JSON.stringify({error:"Method Not Allowed",path:t.pathname,method:e.method,allowed:i}),{status:405,headers:{"Content-Type":"application/json",Allow:i.join(", ")}});if(this.globalMiddleware.length>0){let a=[...this.globalMiddleware,o],u=await this.runMiddleware(s,a);if(u)return this.applyModifiedCookies(u,s)}return o(s,async()=>new Response(null))}if(this.globalMiddleware.length>0){let o=async(c,l)=>{if(this.fallbackHandler)return await this.resolveHandler(this.fallbackHandler,s);return new Response(JSON.stringify({error:"Not Found",path:t.pathname,method:e.method}),{status:404,headers:{"Content-Type":"application/json"}})},a=[...this.globalMiddleware,o],u=await this.runMiddleware(s,a);if(u)return this.applyModifiedCookies(u,s)}if(this.fallbackHandler){let o=await this.resolveHandler(this.fallbackHandler,s);return this.applyModifiedCookies(o,s)}return 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 r=this.enhanceRequest(e,{}),n=async(i,o)=>{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"}})},s=[...this.globalMiddleware,n];try{let i=await this.runMiddleware(r,s);if(i)return i}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){let r=new URL(e,"http://localhost"),n=`${t||""}:${r.pathname}`,s=this._allowedMethodsCache.get(n);if(s)return s;let i=new Set;for(let[u,c]of this.staticRoutes){let l=c.get(r.pathname);if(l&&(!t||!l.domain||l.domain===t))i.add(u)}let o=t&&this.domains[t]?this.domains[t]:this.routes;for(let u of o){if(i.has(u.method))continue;if(u.path===r.pathname){i.add(u.method);continue}if(u.pattern&&u.pattern.exec(r)){i.add(u.method);continue}if(u.path.endsWith("*")&&r.pathname.startsWith(u.path.slice(0,-1)))i.add(u.method)}if(i.has("GET"))i.add("HEAD");let a=Array.from(i);if(this._allowedMethodsCache.size>=1e4)this._allowedMethodsCache.clear();return this._allowedMethodsCache.set(n,a),a}matchRoute(e,t,r){let n=new URL(e,"http://localhost"),s=`${r||""}:${t}:${n.pathname}`;if(this.routeCache.has(s))return this.routeCache.get(s);if(this.staticRoutes.has(t)){let u=this.staticRoutes.get(t).get(n.pathname);if(u&&(!r||!u.domain||u.domain===r)){let c={route:u,params:{}};return this.routeCache.set(s,c),c}}let o=(r&&this.domains[r]?this.domains[r]:this.routes).filter((u)=>u.method===t);for(let u of o)if(u.path===n.pathname){let c={route:u,params:{}};return this.routeCache.set(s,c),c}for(let u of o)if(u.pattern){let c=u.pattern.exec(n);if(c){let l={route:u,params:c.pathname.groups};return this.routeCache.set(s,l),l}}if(r&&this.domains[r]){let u=this.domains[r].filter((c)=>c.method===t&&c.path.endsWith("*"));for(let c of u){let l=c.path.slice(0,-1);if(n.pathname.startsWith(l)){let d={route:c,params:{wildcard:n.pathname.slice(l.length)}};return this.routeCache.set(s,d),d}}}let a=this.routes.filter((u)=>u.method===t&&u.path.endsWith("*")&&(!r||!u.domain));for(let u of a){let c=u.path.slice(0,-1);if(n.pathname.startsWith(c)){let l={route:u,params:{wildcard:n.pathname.slice(c.length)}};return this.routeCache.set(s,l),l}}if(t==="HEAD")return this.matchRoute(e,"GET",r);return}enhanceRequest(e,t={}){let r=null,n=()=>{if(r===null)r={},(e.headers.get("cookie")||"").split(";").forEach((u)=>{let c=u.trim().split("=");if(c.length>=2){let l=c[0].trim(),d=c.slice(1).join("=").trim();r[l]=decodeURIComponent(d)}});return r},s=Ne(e),i={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:s,jsonBody:null,formBody:null,_cookiesToSet:[],_cookiesToDelete:[]},o=()=>{let a={};for(let[u,c]of Object.entries(s))a[u]=c;if(i.jsonBody&&typeof i.jsonBody==="object")for(let[u,c]of Object.entries(i.jsonBody))a[u]=c;if(i.formBody&&typeof i.formBody==="object")for(let[u,c]of Object.entries(i.formBody))a[u]=c;for(let[u,c]of Object.entries(t))a[u]=c;return a};return i.cookies=Ce({read:n,write:(a,u,c)=>{i._cookiesToSet.push({name:a,value:u,options:c})},remove:(a,u)=>{i._cookiesToDelete.push({name:a,options:u})}}),i.get=(a,u)=>{let l=o()[a];return l!==void 0?l:u},i.input=(a,u)=>{let l=o()[a];return l!==void 0?l:u},i.all=()=>o(),i.only=(a)=>{let u=o(),c={};for(let l of a)if(l in u)c[l]=u[l];return c},i.except=(a)=>{let c={...o()};for(let l of a)delete c[l];return c},i.has=(a)=>{let u=o();if(Array.isArray(a))return a.every((c)=>(c in u)&&u[c]!==void 0);return a in u&&u[a]!==void 0},i.hasAny=(a)=>{let u=o();return a.some((c)=>(c in u)&&u[c]!==void 0)},i.filled=(a)=>{let u=o(),c=(l)=>{let d=u[l];return d!==void 0&&d!==null&&d!==""&&!(Array.isArray(d)&&d.length===0)};if(Array.isArray(a))return a.every(c);return c(a)},i.missing=(a)=>{let u=o();if(Array.isArray(a))return a.every((c)=>!(c in u)||u[c]===void 0);return!(a in u)||u[a]===void 0},i.string=(a,u="")=>{let l=o()[a];return l!==void 0&&l!==null?String(l):u},i.integer=(a,u=0)=>{let l=o()[a],d=Number.parseInt(String(l),10);return Number.isNaN(d)?u:d},i.float=(a,u=0)=>{let l=o()[a],d=Number.parseFloat(String(l));return Number.isNaN(d)?u:d},i.boolean=(a,u=!1)=>{let l=o()[a];if(l===void 0||l===null)return u;if(typeof l==="boolean")return l;if(l==="true"||l==="1"||l===1)return!0;if(l==="false"||l==="0"||l===0)return!1;return u},i.array=(a)=>{let c=o()[a];if(Array.isArray(c))return c;return c!==void 0&&c!==null?[c]:[]},i.bearerToken=()=>{let a=e.headers.get("authorization")||e.headers.get("Authorization")||"";if(a.startsWith("Bearer "))return a.substring(7);return null},i.header=(a)=>e.headers.get(a)||e.headers.get(a.toLowerCase())||null,i.cookie=(a,u)=>{let c=n()[a];return c!==void 0?c:u??null},i.getParam=(a,u)=>{let c=t?.[a];return c!==void 0?c:u},i.getParamAsInt=(a)=>{let u=t?.[a];if(u===void 0||u.trim()==="")return null;let c=Number(u);return Number.isSafeInteger(c)?c:null},i.params=t||{},i}applyModifiedCookies(e,t){let r=new Response(e.body,{status:e.status,statusText:e.statusText,headers:e.headers});if(t._cookiesToSet&&t._cookiesToSet.length>0)for(let{name:n,value:s,options:i}of t._cookiesToSet){let o=this.serializeCookie(n,s,i);r.headers.append("Set-Cookie",o)}if(t._cookiesToDelete&&t._cookiesToDelete.length>0)for(let{name:n,options:s}of t._cookiesToDelete){let i={...s,expires:new Date(0),maxAge:0},o=this.serializeCookie(n,"",i);r.headers.append("Set-Cookie",o)}return r}serializeCookie(e,t,r={}){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(r.maxAge!==void 0)n+=`; Max-Age=${r.maxAge}`;if(r.expires&&r.expires instanceof Date)n+=`; Expires=${r.expires.toUTCString()}`;if(r.path)n+=`; Path=${r.path}`;else n+="; Path=/";if(r.domain)n+=`; Domain=${r.domain}`;if(r.secure)n+="; Secure";if(r.httpOnly)n+="; HttpOnly";if(r.sameSite){let s=r.sameSite.toLowerCase();n+=`; SameSite=${s.charAt(0).toUpperCase()+s.slice(1)}`}return n}buildMiddlewareChain(e){if(e.length===0)return async(r)=>null;let t=async(r)=>null;for(let r=e.length-1;r>=0;r--){let n=e[r],s=t;t=async(i)=>n(i,async()=>await s(i)||new Response(null,{status:200}))}return t}async runMiddleware(e,t){if(t.length===0)return null;try{return await this.buildMiddlewareChain(t)(e)}catch(r){if(this.errorHandler)return this.errorHandler(r);throw r}}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 r=this.resolveMiddleware(t);if(r)this.globalMiddleware.push(r)}return this}group(e,t){let r=this.currentGroup;if(this.currentGroup={prefix:e.prefix||"",middleware:[]},e.middleware){for(let s of e.middleware)if(typeof s==="function")this.currentGroup.middleware.push(s)}let n=t();if(n instanceof Promise)return n.then(()=>(this.currentGroup=r,this),(s)=>{throw this.currentGroup=r,s});return this.currentGroup=r,this}addRoute(e){if(this.routes.push(e),e.name)this.namedRoutes.set(e.name,e),U(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,r){if(e.length===0)return r();let n=0,s=async()=>{if(n>=e.length)return r();let i=e[n++];return await i(t,s)||new Response("No response from middleware",{status:500})};return s()}}class xr{router;condition;constructor(e,t){this.router=e;this.condition=t}middleware(e){let[t,r]=e.split(":"),n=this.router.namedMiddleware.get(t);if(!n)throw Error(`Unknown middleware: ${t}`);let s=n(r);return this.router.conditionalMiddleware.push({condition:this.condition,middleware:[s]}),this}}class vr{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 Cr{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 at=null;function Hs(){if(at===null)at=new w;return at}function As(e,t={}){if(typeof e.bearerToken==="function")return e;return Hs().enhanceRequest(e,t)}if(!b.hasMacro("getParam"))b.macro("getParam",function(e,t){let r=this.params?.[e];return r!==void 0?r:t});if(!b.hasMacro("getParamAsInt"))b.macro("getParamAsInt",function(e){let t=this.params?.[e];if(t===void 0||t.trim()==="")return null;let r=Number(t);return Number.isSafeInteger(r)?r:null});if(!b.hasMacro("get"))b.macro("get",function(e,t){let r=re(this).searchParams.get(e);return r!==null&&r!==void 0?r:t});b.macroAccessor("query",function(){return Ne(this)});b.macroAccessor("cookies",function(){let e=this,t=()=>({...L(e)});for(let[r,n]of Object.entries(L(e)))Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0});return t.get=(r)=>L(e)[r],t.set=(r,n,s={})=>{if(!e._cookiesToSet)e._cookiesToSet=[];e._cookiesToSet.push({name:r,value:n,options:s})},t.delete=(r,n={})=>{if(!e._cookiesToDelete)e._cookiesToDelete=[];e._cookiesToDelete.push({name:r,options:n})},t.getAll=()=>({...L(e)}),Object.defineProperty(e,"cookies",{value:t,writable:!0,configurable:!0,enumerable:!0}),t});function Pr(e){Object.defineProperties(e.prototype,{serve:{async value(t={}){if(this._initFileRoutes)await this._initFileRoutes();if(this._initApiRoutes)await this._initApiRoutes();this.invalidateCache();let r={idleTimeout:255,...t,fetch:this.handleRequest.bind(this)},n={};if(this.staticResponses&&this.staticResponses.size>0)for(let[s,i]of this.staticResponses)n[s]=i;if(t.static)Object.assign(n,t.static);if(Object.keys(n).length>0)r.static=n;if(t.development!==void 0)r.development=t.development;if(this._nativeRoutesEnabled=t.nativeRoutes===!0,this._nativeRoutesEnabled){let s=this._buildNativeRoutes();if(s)r.routes=s}if(this.wsConfig)r.websocket=this.wsConfig;if(this.serverInstance=Bun.serve(r),this.config.verbose){let s=this.serverInstance.port,i=this.serverInstance.hostname;console.log(`
100
- \uD83D\uDE80 Server running at http://${i}:${s}
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,r=this.serverInstance.hostname;this.serverInstance.stop();let n={port:t,hostname:r,fetch:this.handleRequest.bind(this),websocket:this.wsConfig||void 0};if(this._nativeRoutesEnabled){let s=this._buildNativeRoutes();if(s)n.routes=s}if(this.serverInstance=Bun.serve(n),this.config.verbose)console.log(`\uD83D\uDD04 Server reloaded at http://${r}:${t}`)},writable:!0,configurable:!0},handleRequest:{async value(t){let r=this,n=await Me(t,()=>r.handleRequestImpl(t));return await St(n,t,r.config?.compression??{})},writable:!0,configurable:!0},_dispatchMatchedRoute:{async value(t,r,n){let s=this.enhanceRequest(r,n);Ee(s),s.route=t;let i=t,o=this._mwEpoch||0,a=i.middleware?i.middleware.length:0,u=i._compiledChain;if(!u||i._chainEpoch!==o||i._chainMwLen!==a){let l=dr(i.handler,this.config);if(a===0&&this.globalMiddleware.length===0)u=l;else{let d=a>0?[...this.globalMiddleware,...i.middleware]:[...this.globalMiddleware];d.push((p,g)=>l(p)),u=this.buildMiddlewareChain(d)}i._compiledChain=u,i._chainEpoch=o,i._chainMwLen=a}let c;try{c=await u(s)}catch(l){if(this.errorHandler)c=await this.errorHandler(l);else throw l}if(c)return this.applyModifiedCookies(c,s);return 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"]),r=(a)=>{if(a==="*")return"/*";let u=a.split("/"),c=[];for(let l=0;l<u.length;l++){let d=u[l];if(d===""){c.push(d);continue}if(d==="*")return l===u.length-1?[...c,"*"].join("/"):null;let p=d.match(/^\{([A-Z_$][\w$]*)\}$/i);if(p){c.push(`:${p[1]}`);continue}if(d.includes("{")||d.includes(":")||d.includes("*"))return null;c.push(d)}return c.join("/")},n=this,s=(a,u)=>(c)=>Me(c,async()=>{try{let l=c.params??{};if(u){let d=new URL(c.url).pathname,p=a.path==="*"?"/":a.path.slice(0,-1);l={...l,wildcard:d.slice(p.length)}}return await n._dispatchMatchedRoute(a,c,l)}catch(l){if(console.error("Error handling request:",l),n.errorHandler)return n.errorHandler(l);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:l instanceof Error?l.message:String(l)}),{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"}})}}),i={},o=new Map;for(let a of this.routes){if(!t.has(a.method))continue;if(a.nativeDispatch===!1)continue;if(a.constraints&&Object.keys(a.constraints).length>0)continue;if(a.handler instanceof Response)continue;let u=r(a.path);if(!u)continue;let c=u.replace(/:[^/]+/g,":p"),l=o.get(c);if(l&&l!==u)continue;o.set(c,u);let d=i[u]??={};if(d[a.method])continue;d[a.method]=s(a,a.path.endsWith("*"))}for(let a of Object.values(i))if(a.GET&&!a.HEAD)a.HEAD=a.GET;return Object.keys(i).length>0?i:null},writable:!0,configurable:!0},handleRequestImpl:{async value(t){try{let r=new URL(t.url);t._parsedURL=r;let n=r.hostname||t.headers.get("host")?.split(":")[0]||"localhost",s=this.matchRoute(r.pathname,t.method,n);if(t.method==="OPTIONS"&&!s){let c=t.headers.get("origin"),l={"Access-Control-Allow-Origin":c||"*","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(c)l["Access-Control-Allow-Credentials"]="true",l.Vary="Origin";return new Response(null,{status:204,headers:l})}if(s)return await this._dispatchMatchedRoute(s.route,t,s.params);let i=this.enhanceRequest(t,{});Ee(i);let o=this.getAllowedMethods(r.pathname,n),a={"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(o.length>0){let c=async(l,d)=>new Response(JSON.stringify({success:!1,message:"Method Not Allowed",path:r.pathname,method:t.method,allowed:o}),{status:405,headers:{...a,Allow:o.join(", ")}});if(this.globalMiddleware.length>0){let l=[...this.globalMiddleware,c],d=await this.runMiddleware(i,l);if(d)return this.applyModifiedCookies(d,i)}return await c(i,async()=>null)}if(this.fallbackHandler){let c=await this.resolveHandler(this.fallbackHandler,i);return this.applyModifiedCookies(c,i)}let u=async(c,l)=>new Response(JSON.stringify({success:!1,message:"Not Found",path:r.pathname,method:t.method}),{status:404,headers:a});if(this.globalMiddleware.length>0){let c=[...this.globalMiddleware,u],l=await this.runMiddleware(i,c);if(l)return this.applyModifiedCookies(l,i)}return await u(i,async()=>null)}catch(r){if(console.error("Error handling request:",r),this.errorHandler)return this.errorHandler(r);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:r instanceof Error?r.message:String(r)}),{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,r={}){let n=t;if("params"in t)Object.defineProperty(n,"params",{value:r,writable:!0,configurable:!0,enumerable:!0});else n.params=r;return b.applyMacros(n),n},writable:!0,configurable:!0},applyModifiedCookies:{value(t,r){let n=r._cookiesToSet&&r._cookiesToSet.length>0,s=r._cookiesToDelete&&r._cookiesToDelete.length>0;if(!n&&!s)return t;let i=new Response(t.body,{status:t.status,statusText:t.statusText,headers:t.headers});if(r._cookiesToSet&&r._cookiesToSet.length>0)for(let{name:o,value:a,options:u}of r._cookiesToSet){let c=this.serializeCookie(o,a,u);i.headers.append("Set-Cookie",c)}if(r._cookiesToDelete&&r._cookiesToDelete.length>0)for(let{name:o,options:a}of r._cookiesToDelete){let u={...a,expires:new Date(0),maxAge:0},c=this.serializeCookie(o,"",u);i.headers.append("Set-Cookie",c)}return i},writable:!0,configurable:!0},serializeCookie:{value(t,r,n={}){let s=`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(n.maxAge!==void 0)s+=`; Max-Age=${n.maxAge}`;if(n.expires&&n.expires instanceof Date)s+=`; Expires=${n.expires.toUTCString()}`;if(n.path)s+=`; Path=${n.path}`;else s+="; Path=/";if(n.domain)s+=`; Domain=${n.domain}`;if(n.secure)s+="; Secure";if(n.httpOnly)s+="; HttpOnly";if(n.sameSite){let i=n.sameSite.toLowerCase();s+=`; SameSite=${i.charAt(0).toUpperCase()+i.slice(1)}`}return s},writable:!0,configurable:!0}})}import{join as qs}from"path";function Mr(e){Object.defineProperties(e.prototype,{renderView:{async value(t,r={},n={}){let s=this.config.views||{viewsPath:"resources/views",extensions:[".html",".stx"],cache:Bun.env.NODE_ENV==="production",engine:"auto"},i=`${t}:${n.layout||""}`;if(s.cache&&this.templateCache.has(i))return this.processTemplate(this.templateCache.get(i),r,s);let o=await nt(t,s.viewsPath,s.extensions);if(!o)throw Error(`View '${t}' not found`);let a=await Bun.file(o).text(),u=n.layout||s.defaultLayout;if(u){let c=await nt(qs("layouts",u),s.viewsPath,s.extensions);if(!c)throw Error(`Layout '${u}' not found`);a=(await Bun.file(c).text()).replace(/\{\{\s*content\s*\}\}/g,a)}if(s.cache)this.templateCache.set(i,a);return this.processTemplate(a,r,s)},writable:!0,configurable:!0},processTemplate:{async value(t,r,n){if((n?.engine||"auto")==="custom"&&n?.customRenderer)return n.customRenderer(t,r,{});let i=nr(t,r);if(n?.minify?.enabled)try{let o=n.minify.options||{removeComments:!0,collapseWhitespace:!0,minifyJS:!0,minifyCSS:!0};i=i.replace(/\s+/g," ").replace(/<!--[\s\S]*?-->/g,"")}catch(o){console.error("Error minifying HTML:",o)}return i},writable:!0,configurable:!0},view:{value(t,r,n={},s={},i="web",o){let a,u={},c={},l="web",d;if(typeof r==="string"){if(a=r,typeof n==="object"&&!Array.isArray(n))if("layout"in n||"status"in n||"headers"in n)c=n;else u=n;if(typeof s==="object")c={...c,...s};else if(typeof s==="string")l=s;if(typeof i==="string")if(i==="web"||i==="api")l=i;else d=i;if(o)d=o}else{if(u=r,typeof n==="string")a=n;else throw TypeError("View name must be a string");if(typeof s==="object")c=s;else if(typeof s==="string")if(s==="web"||s==="api")l=s;else a=s,l="web"}let p=async(g)=>{let h=await this.renderView(a,u,{layout:c.layout}),m=this.config?.queryPreservation;if(m?.enabled!==!1&&m?.preserve?.length)h=Se(h,m);let y=new Headers;if(y.set("Content-Type","text/html; charset=utf-8"),c.headers)for(let[x,V]of Object.entries(c.headers))y.set(x,V);return new Response(h,{status:c.status||200,headers:y})};return this.get(t,p,l,d),this},writable:!0,configurable:!0}})}function Er(e){Object.defineProperties(e.prototype,{websocket:{value(t){return this.wsConfig=t,this},writable:!0,configurable:!0},publish:{value(t,r,n=!1){if(!this.serverInstance)throw Error("Server not started, cannot publish to WebSocket topics");return this.serverInstance.publish(t,r,n)},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,r){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,r)},writable:!0,configurable:!0},timeout:{value(t,r){if(!this.serverInstance)throw Error("Server not started, cannot set timeout");this.serverInstance.timeout(t,r)},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}})}import Os from"process";class Sr{macros=new Map;register(e,t){this.macros.set(e,{name:e,handler:t})}get(e){return this.macros.get(e)}has(e){return this.macros.has(e)}all(){return Array.from(this.macros.values())}remove(e){return this.macros.delete(e)}clear(){this.macros.clear()}}var ut=new Sr;class me extends Response{static macro(e,t){ut.register(e,t),Response[e]=t}static callMacro(e,...t){let r=ut.get(e);if(!r)throw Error(`Response macro "${e}" not found`);return r.handler(...t)}static hasMacro(e){return ut.has(e)}}function Ue(e,t){if(typeof e==="number")return{status:e,mergedHeaders:t};if(e&&typeof e==="object"){let r=typeof e.status==="number"?e.status:200,n=t;if(e.headers)if(n={},e.headers instanceof Headers)e.headers.forEach((s,i)=>{n[i]=s});else if(Array.isArray(e.headers))for(let[s,i]of e.headers)n[s]=i;else Object.assign(n,e.headers);return{status:r,mergedHeaders:n}}return{status:200,mergedHeaders:t}}var A={success:(e,t,r=200)=>{let n={};if(e!==void 0)n.data=e;if(t!==void 0)n.message=t;return new Response(JSON.stringify(n),{status:r,headers:{"Content-Type":"application/json"}})},error:(e,t,r=400)=>{let n={error:e};if(t!==void 0)n.errors=t;return new Response(JSON.stringify(n),{status:r,headers:{"Content-Type":"application/json"}})},validationError:(e,t="Validation failed")=>A.error(t,e,422),notFound:(e="Resource not found")=>A.error(e,void 0,404),unauthorized:(e="Unauthorized")=>A.error(e,void 0,401),forbidden:(e="Forbidden")=>A.error(e,void 0,403),serverError:(e="Internal server error")=>A.error(e,void 0,500),created:(e,t="Resource created successfully")=>A.success(e,t,201),updated:(e,t="Resource updated successfully")=>A.success(e,t,200),deleted:(e="Resource deleted successfully")=>A.success(null,e,200),noContent:()=>new Response(null,{status:204}),accepted:(e,t="Request accepted")=>A.success(e,t,202),paginated:(e,t,r)=>{let n=Math.ceil(t.total/t.per_page),s=(t.current_page-1)*t.per_page+1,i=Math.min(s+t.per_page-1,t.total),o={data:e,message:r,meta:{current_page:t.current_page,per_page:t.per_page,total:t.total,last_page:n,from:s,to:i,path:t.path,first_page_url:`${t.path}?page=1`,last_page_url:`${t.path}?page=${n}`,next_page_url:t.current_page<n?`${t.path}?page=${t.current_page+1}`:void 0,prev_page_url:t.current_page>1?`${t.path}?page=${t.current_page-1}`:void 0}};return new Response(JSON.stringify(o),{status:200,headers:{"Content-Type":"application/json"}})},json:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Ue(t,r);return new Response(JSON.stringify(e),{status:n,headers:{"Content-Type":"application/json",...s}})},html:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Ue(t,r);return new Response(e,{status:n,headers:{"Content-Type":"text/html",...s}})},text:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Ue(t,r);return new Response(e,{status:n,headers:{"Content-Type":"text/plain",...s}})},xml:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Ue(t,r);return new Response(e,{status:n,headers:{"Content-Type":"application/xml",...s}})},redirect:(e,t=302)=>new Response(null,{status:t,headers:{Location:e}}),permanentRedirect:(e)=>A.redirect(e,301),download:(e,t,r="application/octet-stream")=>new Response(e,{status:200,headers:{"Content-Type":r,"Content-Disposition":`attachment; filename="${t}"`}}),stream:(e,t="application/octet-stream",r={})=>new Response(e,{status:200,headers:{"Content-Type":t,...r}}),cache:(e,t=3600,r=!0,n)=>{let i={"Content-Type":"application/json","Cache-Control":r?`public, max-age=${t}`:`private, max-age=${t}`};if(n)i.ETag=n;return new Response(JSON.stringify(e),{status:200,headers:i})},cors:(e,t="*",r="GET,POST,PUT,DELETE,OPTIONS",n="Content-Type,Authorization")=>new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":t,"Access-Control-Allow-Methods":r,"Access-Control-Allow-Headers":n}}),sse:(e,t,r)=>{let n="";if(r)n+=`id: ${r}
102
- `;if(t)n+=`event: ${t}
103
- `;return n+=`data: ${e}
93
+ `,z.enqueue(de.encode(Re))}z.close()}catch(pe){fr(z,pe)}}});return new Response(U,{status:200,headers:M})},writable:!0,configurable:!0},streamDownload:{value(c,P,M={}){let U=new Headers({"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="${P}"`,...M}),z=new ReadableStream({async start(de){let pe=new TextEncoder;try{for await(let Re of c())if(typeof Re==="string")de.enqueue(pe.encode(Re));else de.enqueue(Re);de.close()}catch(Re){fr(de,Re)}}});return new Response(z,{status:200,headers:U})},writable:!0,configurable:!0},streamAsyncIterator:{value(c,P={}){return dt.direct(c,P).toResponse()},writable:!0,configurable:!0}})}class Rr extends Error{modelName;value;field;constructor(i,c,P="id"){super(`${i} not found with ${P}: ${c}`);this.modelName=i;this.value=c;this.field=P;this.name="ModelNotFoundError"}}class Sn{bindings=new Map;model(i,c){this.bindings.set(i,c)}bind(i,c){this.bindings.set(i,c)}getBinding(i){return this.bindings.get(i)}hasBinding(i){return this.bindings.has(i)}}var Si=new Sn;async function En(i,c,P,M,U={}){if(M)return await P.resolveRouteBinding(c,M);let z=P.getRouteKeyName();if(z!=="id")return await P.resolveRouteBinding(c,z);return await P.find(c)}function kn(i,c){return async(P,M)=>{let U={};try{for(let z of i){let de=P.params?.[z.name];if(!de)continue;let pe=Si.getBinding(z.name);if(pe){let xe=null;if(typeof pe==="function")xe=await pe(de);else xe=await En(z.name,de,pe,z.key,U);if(!xe)throw new Rr(z.name,de,z.key||"id");U[z.name]=xe;continue}let Re=c[z.name];if(!Re)continue;let Te=await En(z.name,de,Re,z.key,U);if(!Te)throw new Rr(z.name,de,z.key||"id");U[z.name]=Te}return P.models=U,await M()}catch(z){if(z instanceof Rr)return new Response(`${z.modelName} not found`,{status:404});throw z}}}class Hn{key;entry;prev;next;constructor(i,c,P=null,M=null){this.key=i;this.entry=c;this.prev=P;this.next=M}}class Xt{options;cache=new Map;head=null;tail=null;stats={hits:0,misses:0,evictions:0};constructor(i){this.options=i;if(i.maxSize<=0)throw Error("maxSize must be greater than 0")}get(i){let c=this.cache.get(i);if(!c){this.stats.misses++;return}let P=Date.now(),M=c.entry;if(this.isExpired(M,P)){if(!this.options.allowStale){this.delete(i),this.stats.misses++;return}}if(M.lastAccessed=P,M.accessCount++,this.stats.hits++,this.options.updateAgeOnGet!==!1)this.moveToFront(c);return M.value}set(i,c,P){let M=Date.now(),U=this.cache.get(i);if(U){U.entry.value=c,U.entry.timestamp=M,U.entry.lastAccessed=M,U.entry.ttl=P??this.options.ttl,this.moveToFront(U);return}let z={value:c,timestamp:M,accessCount:0,lastAccessed:M,ttl:P??this.options.ttl},de=new Hn(i,z);if(this.cache.set(i,de),this.addToFront(de),this.cache.size>this.options.maxSize)this.evictLRU()}delete(i){let c=this.cache.get(i);if(!c)return!1;if(this.cache.delete(i),this.removeNode(c),this.options.onEvict)this.options.onEvict(i,c.entry.value);return!0}has(i){let c=this.cache.get(i);if(!c)return!1;let P=Date.now();if(this.isExpired(c.entry,P)){if(!this.options.allowStale)return this.delete(i),!1}return!0}clear(){if(this.options.onEvict)for(let[i,c]of this.cache)this.options.onEvict(i,c.entry.value);this.cache.clear(),this.head=null,this.tail=null,this.stats.evictions+=this.cache.size}keys(){let i=[],c=this.head;while(c)i.push(c.key),c=c.next;return i}values(){let i=[],c=this.head;while(c)i.push(c.entry.value),c=c.next;return i}getStats(){let i=this.estimateMemoryUsage(),c=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:c>0?this.stats.hits/c:0,memoryUsage:i}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}prune(){let i=Date.now(),c=[];for(let[P,M]of this.cache)if(this.isExpired(M.entry,i))c.push(P);for(let P of c)this.delete(P);return c.length}getFrequentlyUsed(i=10){let c=[];for(let[P,M]of this.cache)c.push({key:P,value:M.entry.value,accessCount:M.entry.accessCount});return c.sort((P,M)=>M.accessCount-P.accessCount).slice(0,i)}resize(i){if(i<=0)throw Error("maxSize must be greater than 0");this.options.maxSize=i;while(this.cache.size>i)this.evictLRU()}isExpired(i,c){if(!i.ttl)return!1;return c-i.timestamp>i.ttl}moveToFront(i){if(i===this.head)return;this.removeNode(i),this.addToFront(i)}addToFront(i){if(i.prev=null,i.next=this.head,this.head)this.head.prev=i;if(this.head=i,!this.tail)this.tail=i}removeNode(i){if(i.prev)i.prev.next=i.next;else this.head=i.next;if(i.next)i.next.prev=i.prev;else this.tail=i.prev}evictLRU(){if(!this.tail)return;let i=this.tail.key,c=this.tail.entry.value;if(this.cache.delete(i),this.removeNode(this.tail),this.stats.evictions++,this.options.onEvict)this.options.onEvict(i,c)}estimateMemoryUsage(){let i=0;for(let[c,P]of this.cache)i+=c.length*2,i+=this.estimateValueSize(P.entry.value),i+=64;return i+=this.cache.size*48,i}estimateValueSize(i){if(i===null||i===void 0)return 0;if(typeof i==="string")return i.length*2;if(typeof i==="number")return 8;if(typeof i==="boolean")return 1;if(i instanceof ArrayBuffer)return i.byteLength;if(i instanceof Uint8Array)return i.length;try{return JSON.stringify(i).length*2}catch{return 100}}}class An{static generateKey(i,c){let P=new URL(i.url),M=i.method,U=P.pathname,z=[M,U],de=new URLSearchParams(P.search),pe=c.excludeQuery||[],Re=[];for(let[Te,xe]of de.entries())if(!pe.includes(Te))Re.push(`${Te}=${xe}`);if(Re.length>0)z.push(Re.sort().join("&"));if(c.varyBy){let Te=[];for(let xe of c.varyBy){let ve=i.headers.get(xe);if(ve)Te.push(`${xe}:${ve}`)}if(Te.length>0)z.push(Te.join("|"))}return z.join("::")}}class qn{cache;tagIndex=new Map;keyTags=new Map;constructor(i=1000){this.cache=new Xt({maxSize:i})}async get(i){let c=this.cache.get(i);if(!c)return null;if(c.ttl&&Date.now()-c.timestamp>c.ttl)return this.delete(i),null;return c}async set(i,c){this.cache.set(i,c),this.keyTags.set(i,new Set(c.tags));for(let P of c.tags){if(!this.tagIndex.has(P))this.tagIndex.set(P,new Set);this.tagIndex.get(P).add(i)}}delete(i){let c=this.keyTags.get(i);if(c){for(let P of c){let M=this.tagIndex.get(P);if(M){if(M.delete(i),M.size===0)this.tagIndex.delete(P)}}this.keyTags.delete(i)}return this.cache.delete(i)}invalidateByTags(i){let c=new Set;for(let P of i){let M=this.tagIndex.get(P);if(M)for(let U of M)c.add(U)}for(let P of c)this.delete(P);return c.size}clear(){this.cache.clear(),this.tagIndex.clear(),this.keyTags.clear()}getStats(){return{...this.cache.getStats(),totalTags:this.tagIndex.size,totalKeyTagMappings:this.keyTags.size}}}var _t=new qn;function On(i){return async(c,P)=>{if(i.condition&&!i.condition(c))return await P();if(c.method!=="GET"&&c.method!=="HEAD")return await P();let M=An.generateKey(c,i),U=await _t.get(M);if(U){let de=new Headers(U.headers);if(de.set("X-Cache","HIT"),de.set("X-Cache-Key",M),U.etag){if(de.set("ETag",U.etag),c.headers.get("If-None-Match")===U.etag)return new Response(null,{status:304,headers:de})}return new Response(U.body,{status:U.status,headers:de})}let z=await P();if(z.status>=200&&z.status<300)try{let de=z.clone(),pe=await de.arrayBuffer(),Re=await ki(pe),Te={};de.headers.forEach((Ce,Me)=>{Te[Me]=Ce});let xe={response:de,headers:Te,status:z.status,body:new Uint8Array(pe),timestamp:Date.now(),ttl:i.ttl,tags:i.tags||[],etag:Re};await _t.set(M,xe);let ve=new Headers(z.headers);return ve.set("X-Cache","MISS"),ve.set("X-Cache-Key",M),ve.set("ETag",Re),new Response(z.body,{status:z.status,headers:ve})}catch(de){return console.error("Error caching response:",de),z}return z}}async function ki(i){let c=await crypto.subtle.digest("SHA-256",i);return`"${Array.from(new Uint8Array(c)).map((U)=>U.toString(16).padStart(2,"0")).join("").substring(0,16)}"`}var $n={short:(i=[])=>({ttl:300000,maxSize:500,tags:i}),medium:(i=[])=>({ttl:3600000,maxSize:1000,tags:i}),long:(i=[])=>({ttl:86400000,maxSize:2000,tags:i}),api:(i=[])=>({ttl:900000,maxSize:1000,tags:i,varyBy:["Authorization","Accept","Accept-Language"],excludeQuery:["_t","timestamp","cache_bust"]}),static:(i=[])=>({ttl:604800000,maxSize:5000,tags:i,varyBy:["Accept-Encoding"]}),user:(i=[])=>({ttl:1800000,maxSize:2000,tags:i,varyBy:["Authorization"],condition:(c)=>!!c.headers.get("Authorization")})},ca={byTags:(i)=>_t.invalidateByTags(i),forUser:(i)=>_t.invalidateByTags([`user:${i}`]),forModel:(i,c)=>{let P=c?[`${i}:${c}`,i]:[i];return _t.invalidateByTags(P)},all:()=>{_t.clear()}};class yr{cache;config;constructor(i,c=1e4){this.config=i,this.cache=new Xt({maxSize:c,ttl:i.windowMs*2})}async checkLimit(i){if(this.config.skipIf&&this.config.skipIf(i))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 c=this.generateKey(i),P=Date.now(),M=this.cache.get(c);if(!M||P>=M.resetTime)M={count:1,resetTime:P+this.config.windowMs,firstHit:P};else M.count++;this.cache.set(c,M);let U={totalHits:M.count,resetTime:new Date(M.resetTime),remaining:Math.max(0,this.config.maxAttempts-M.count),limit:this.config.maxAttempts,windowMs:this.config.windowMs};return{allowed:M.count<=this.config.maxAttempts,info:U}}generateKey(i){if(this.config.keyGenerator)return this.config.keyGenerator(i);let c=this.getClientIP(i),P=i.user?.id;if(P)return`user:${P}`;return`ip:${c}`}getClientIP(i){let c=i.headers.get("x-forwarded-for");if(c)return c.split(",")[0].trim();let P=i.headers.get("x-real-ip");if(P)return P;let M=i.headers.get("cf-connecting-ip");if(M)return M;return"unknown"}getStats(){return{...this.cache.getStats(),config:{maxAttempts:this.config.maxAttempts,windowMs:this.config.windowMs}}}}class Bn{limiters=new Map;register(i,c){let P=new yr(c);return this.limiters.set(i,P),P}get(i){return this.limiters.get(i)}getOrCreate(i,c){let P=this.limiters.get(i);if(P)return P;return this.register(i,c)}}var Dn=new Bn;function jt(i,c){let P=c?Dn.getOrCreate(c,i):new yr(i);return async(M,U)=>{let{allowed:z,info:de}=await P.checkLimit(M);if(!z){if(i.onLimitReached)return i.onLimitReached(M,de);let Re=new Headers({"Content-Type":"application/json","Retry-After":Math.ceil((de.resetTime.getTime()-Date.now())/1000).toString()});if(i.headers!==!1)Re.set("X-RateLimit-Limit",de.limit.toString()),Re.set("X-RateLimit-Remaining",de.remaining.toString()),Re.set("X-RateLimit-Reset",Math.ceil(de.resetTime.getTime()/1000).toString());return new Response(JSON.stringify({error:"Too Many Requests",message:`Rate limit exceeded. Try again in ${Math.ceil((de.resetTime.getTime()-Date.now())/1000)} seconds.`,retryAfter:Math.ceil((de.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:Re})}let pe=await U();if(pe&&i.headers!==!1&&pe.status<400){let Re=new Headers(pe.headers);return Re.set("X-RateLimit-Limit",de.limit.toString()),Re.set("X-RateLimit-Remaining",de.remaining.toString()),Re.set("X-RateLimit-Reset",Math.ceil(de.resetTime.getTime()/1000).toString()),new Response(pe.body,{status:pe.status,statusText:pe.statusText,headers:Re})}return pe}}function Lt(i){let c=i.split(","),P=Number.parseInt(c[0],10);if(Number.isNaN(P)||P<=0)throw Error(`Invalid throttle max attempts: ${c[0]}`);let M;if(c.length===1)M=60000;else{let U=c[1];M=Hi(U)}return{maxAttempts:P,windowMs:M}}function Hi(i){let c=/^(\d+)([smh]|sec|min|hour)?$/,P=i.match(c);if(!P)throw Error(`Invalid time format: ${i}`);let M=Number.parseInt(P[1],10),U=P[2]||"m";if(Number.isNaN(M)||M<=0)throw Error(`Invalid time value: ${P[1]}`);switch(U){case"s":case"sec":return M*1000;case"m":case"min":return M*60*1000;case"h":case"hour":return M*60*60*1000;default:return M*60*1000}}var Ai={api:(i=60,c=1)=>({maxAttempts:i,windowMs:c*60*1000,headers:!0}),auth:()=>({maxAttempts:5,windowMs:900000,keyGenerator:(i)=>{let c=i.headers.get("x-forwarded-for")?.split(",")[0]||"unknown",P=i.jsonBody?.email||i.formBody?.email||i.query?.email||"unknown";return`auth:${c}:${P}`},onLimitReached:(i,c)=>new Response(JSON.stringify({error:"Too many authentication attempts",message:"Please try again later",retryAfter:Math.ceil((c.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:{"Content-Type":"application/json","Retry-After":Math.ceil((c.resetTime.getTime()-Date.now())/1000).toString()}})}),upload:()=>({maxAttempts:10,windowMs:3600000,keyGenerator:(i)=>{let c=i.user?.id;if(c)return`upload:user:${c}`;return`upload:ip:${i.headers.get("x-forwarded-for")?.split(",")[0]||"unknown"}`}}),search:()=>({maxAttempts:100,windowMs:600000,skipIf:(i)=>i.user?.plan==="premium"}),perUser:(i,c)=>({maxAttempts:i,windowMs:c*60*1000,keyGenerator:(P)=>{let M=P.user?.id;if(!M)throw Error("User authentication required for per-user rate limiting");return`user:${M}`},skipIf:(P)=>!P.user?.id}),perIP:(i,c)=>({maxAttempts:i,windowMs:c*60*1000,keyGenerator:(P)=>`ip:${P.headers.get("x-forwarded-for")?.split(",")[0]||P.headers.get("x-real-ip")||P.headers.get("cf-connecting-ip")||"unknown"}`}),global:(i,c)=>({maxAttempts:i,windowMs:c*60*1000,keyGenerator:()=>"global"})},pa={fromString:(i,c)=>{let P=Lt(i);return jt(P,c)},getInfo:async(i,c)=>{let P=new yr(c),{info:M}=await P.checkLimit(i);return M},reset:(i,c)=>{let P=Dn.get(i);if(P)return P.cache.delete(c);return!1}};class pt{static parseDomainPattern(i){let c=[],P=i.match(/\{([^}]+)\}/g)||[];for(let z of P){let de=z.slice(1,-1);c.push(de)}let M=i.replace(/\./g,"\\.").replace(/\{([^}]+)\}/g,"([^.]+)");M=`^${M}$`;let U=new RegExp(M,"i");return{pattern:i,parameters:c,regex:U}}static matchDomain(i,c){let P=i.match(c.regex);if(!P)return null;let M={};for(let U=0;U<c.parameters.length;U++){let z=c.parameters[U],de=P[U+1];M[z]=de}return M}static extractSubdomainInfo(i){let c=i.split(".");if(c.length<=2)return{domain:i,parameters:{},rootDomain:i};let P=c[0],M=c.slice(1).join(".");return{domain:i,parameters:{subdomain:P},subdomain:P,rootDomain:M}}}class Qt{pattern;config;routes=[];constructor(i,c){this.pattern=i;this.config=c}addRoute(i,c,P,M=[],U){let z=[...this.config.middleware||[],...M],de=this.config.prefix?`${this.config.prefix}${c}`:c;this.routes.push({method:i.toUpperCase(),path:de,handler:P,middleware:z,name:U||(this.config.name?`${this.config.name}.${i.toLowerCase()}${c}`:void 0)})}getRoutes(){return[...this.routes]}matchesDomain(i){return pt.matchDomain(i,this.pattern)}}class Ur{domainGroups=[];wildcardGroup;domain(i){let c=pt.parseDomainPattern(i);return new Fn(this,c)}addDomainGroup(i){if(i.pattern.pattern.includes("*")&&i.pattern.parameters.length===0)this.wildcardGroup=i;else this.domainGroups.push(i)}findDomainGroup(i){for(let c of this.domainGroups){let P=c.matchesDomain(i);if(P!==null)return{group:c,parameters:P}}if(this.wildcardGroup)return{group:this.wildcardGroup,parameters:pt.extractSubdomainInfo(i).parameters};return null}getAllRoutes(){let i=[];for(let c of this.domainGroups){let P=c.getRoutes();for(let M of P)i.push({domainPattern:c.pattern.pattern,domainParameters:{},...M})}if(this.wildcardGroup){let c=this.wildcardGroup.getRoutes();for(let P of c)i.push({domainPattern:this.wildcardGroup.pattern.pattern,domainParameters:{},...P})}return i}}class Fn{router;pattern;group;constructor(i,c){this.router=i;this.pattern=c;this.group=new Qt(c,{domain:c.pattern})}middleware(i){return this.group.config.middleware=i,this}prefix(i){return this.group.config.prefix=i,this}name(i){return this.group.config.name=i,this}routes(i){let c=new Nn(this.group);i(c),this.router.addDomainGroup(this.group)}get(i,c,P){this.group.addRoute("GET",i,c,P),this.router.addDomainGroup(this.group)}post(i,c,P){this.group.addRoute("POST",i,c,P),this.router.addDomainGroup(this.group)}put(i,c,P){this.group.addRoute("PUT",i,c,P),this.router.addDomainGroup(this.group)}delete(i,c,P){this.group.addRoute("DELETE",i,c,P),this.router.addDomainGroup(this.group)}patch(i,c,P){this.group.addRoute("PATCH",i,c,P),this.router.addDomainGroup(this.group)}}class Nn{group;constructor(i){this.group=i}get(i,c,P,M){this.group.addRoute("GET",i,c,P,M)}post(i,c,P,M){this.group.addRoute("POST",i,c,P,M)}put(i,c,P,M){this.group.addRoute("PUT",i,c,P,M)}delete(i,c,P,M){this.group.addRoute("DELETE",i,c,P,M)}patch(i,c,P,M){this.group.addRoute("PATCH",i,c,P,M)}options(i,c,P,M){this.group.addRoute("OPTIONS",i,c,P,M)}head(i,c,P,M){this.group.addRoute("HEAD",i,c,P,M)}any(i,c,P,M){let U=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];for(let z of U)this.group.addRoute(z,i,c,P,M)}}function ga(i){return async(c,P)=>{let U=new URL(c.url).hostname,z=i.findDomainGroup(U);if(z){let de=c;de.domainParams=z.parameters,Object.assign(c.params||{},z.parameters);let pe=pt.extractSubdomainInfo(U);de.subdomainInfo=pe}return await P()}}var ma={getSubdomain:(i)=>{let c=new URL(i.url);return pt.extractSubdomainInfo(c.hostname).subdomain||null},getDomainParams:(i)=>i.domainParams||{},matchesDomain:(i,c)=>{let P=new URL(i.url),M=pt.parseDomainPattern(c);return pt.matchDomain(P.hostname,M)!==null},getSubdomainInfo:(i)=>i.subdomainInfo||null},fa={single:(i,c)=>`${i}.${c}`,wildcard:(i,c="subdomain")=>`{${c}}.${i}`,multiLevel:(i,...c)=>`${c.map((M)=>`{${M}}`).join(".")}.${i}`,apiVersion:(i)=>`{version}.api.${i}`,tenant:(i)=>`{tenant}.app.${i}`,environment:(i)=>`{env}.${i}`};import qi from"process";var zt=new Map;function St(i,c){zt.set(i,c)}function Ir(i){return zt.get(i)}function Oi(){return new Map(zt)}function $i(){zt.clear()}function Bi(i,c={},P={}){let M=zt.get(i);if(!M){let Re=[...zt.keys()].sort().join(", ")||"(none registered)";throw Error(`Named route '${i}' is not defined. Known routes: ${Re}`)}let U=new Set,z=M;for(let[Re,Te]of Object.entries(c)){let xe=`{${Re}}`,ve=`{${Re}?}`,Ce=encodeURIComponent(String(Te));if(z.includes(xe))z=z.replaceAll(xe,Ce),U.add(Re);else if(z.includes(ve))z=z.replaceAll(ve,Ce),U.add(Re)}if(z.includes("?}")){if(z=z.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),z.length>1&&z.endsWith("/"))z=z.slice(0,-1)}let de=z.match(/\{([^}?]+)\}/g);if(de&&de.length>0)throw Error(`Missing required params for route '${i}': ${de.join(", ")}`);let pe=Object.entries(c).filter(([Re])=>!U.has(Re));if(pe.length>0){let Re=new URLSearchParams;for(let[Te,xe]of pe)Re.set(Te,String(xe));z+=`?${Re.toString()}`}if(P.absolute){let Re=(P.base??qi.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${Re.startsWith("http")?Re:`https://${Re}`}${z.startsWith("/")?z:`/${z}`}`}return z}import{join as Un}from"path";function Zt(i){let c=i.replace(/\/+/g,"/");if(!c.startsWith("/"))c=`/${c}`;if(c.length>1&&c.endsWith("/"))c=c.slice(0,-1);return c}function xa(i){return i.replace(/\//g,"_").toLowerCase()}function Di(i){if(typeof i!=="function"&&typeof i!=="object")return!1;if(typeof i==="function"&&i.prototype){if(typeof i.prototype.handle==="function")return!0}if(typeof i==="object"&&i!==null&&"handle"in i&&typeof i.handle==="function")return!0;return!1}function va(i){return typeof i==="function"&&!Di(i)}function wr(i){let c=i.match(/\{([^}]+)\}/g);return c?c.map((P)=>P.slice(1,-1).replace("?","")):[]}function Ca(i){let c=i.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${c}$`)}var Fi=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,Ni=/\{[^}]+\?\}/,In=new Map,_n=new Map;function Ui(i){let c=In.get(i);if(c)return c;let P=i.endsWith("/*"),M=Zt(i),U=0,z=M.split("/").filter(Boolean).map((pe)=>{let Re=Ni.test(pe);if(Re)U++;let Te=pe.match(Fi);return{isParam:!!Te,paramName:Te?Te[1].replace("?",""):"",isOptional:Re,literal:pe}}),de={isWildcard:P,wildcardBase:P?i.slice(0,-2):"",segments:z,optionalCount:U};return In.set(i,de),de}function Ii(i){let c=_n.get(i);if(c!==void 0)return c;let P;try{P=new RegExp(`^${i}$`)}catch{P=null}return _n.set(i,P),P}function ht(i,c,P,M){let U=Ui(i);if(U.isWildcard&&c.startsWith(U.wildcardBase))return!0;let z=U.segments,de=Zt(c).split("/").filter(Boolean);if(de.length<z.length-U.optionalCount||de.length>z.length)return!1;for(let pe=0;pe<z.length;pe++){let Re=z[pe],Te=de[pe];if(Te===void 0){if(Re.isOptional)continue;return!1}if(Re.isParam){let xe=Nt(Te);if(P[Re.paramName]=xe,M&&M[Re.paramName]){let ve=Ii(M[Re.paramName]);if(ve){if(!ve.test(xe))return!1}else console.warn(`Invalid constraint regex for parameter ${Re.paramName}: ${M[Re.paramName]}`)}}else if(Re.literal!==Te)return!1}return!0}function Mt(...i){return Zt(i.join("/"))}function Pa(i){if(!i.startsWith("/"))return!1;let c=[];for(let P of i)if(P==="{")c.push(P);else if(P==="}"){if(c.length===0||c.pop()!=="{")return!1}return c.length===0}async function jn(i){try{return await Bun.file(i).exists()}catch{return!1}}async function _r(i,c,P){if(P.some((M)=>i.endsWith(M))){let M=Zt(Un(c,i));if(await jn(M))return M;return null}for(let M of P){let U=Zt(Un(c,`${i}${M}`));if(await jn(U))return U}return null}function Ln(i,c){let P=i.replace(/\{\{([^}]+)\}\}/g,(M,U)=>{let z=U.trim(),de=jr(c,z);return de!==void 0?String(de):M});return P=_i(P,c),P=ji(P,c),P}function _i(i,c){return i.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(P,M,U,z="")=>{let de=M.trim();return jr(c,de)?U:z})}function ji(i,c){return i.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(P,M,U)=>{let z=jr(c,M.trim());if(!Array.isArray(z))return"";return z.map((de)=>U.replace(/\{\{@index\}\}/g,String(z.indexOf(de))).replace(/\{\{this\}\}/g,String(de)).replace(/\{\{this\.([^}]+)\}\}/g,(pe,Re)=>{let Te=de[Re.trim()];return Te!==void 0?String(Te):""})).join("")})}function jr(i,c){return c.split(".").reduce((P,M)=>{if(P&&typeof P==="object"&&M in P)return P[M];return},i)}class Se{method;path;handler;middleware=[];cacheConfig;throttleConfig;routeName;modelBindings={};constructor(i,c,P){this.method=i;this.path=c;this.handler=P}addMiddleware(i){if(Array.isArray(i))this.middleware.push(...i);else this.middleware.push(i);return this}cached(i=[],c){return this.cacheConfig={...$n.api(i),...c},this}throttle(i,c){if(typeof i==="string"){let P=Lt(i);this.throttleConfig={maxAttempts:P.maxAttempts??60,windowMs:P.windowMs,keyGenerator:(M)=>M.headers.get("x-forwarded-for")||"anonymous"}}else this.throttleConfig=i;return this}name(i){return this.routeName=i,this}model(i,c){return this.modelBindings[i]=c,this}build(){let i=[];if(Object.keys(this.modelBindings).length>0){let c=Object.keys(this.modelBindings).map((M)=>({name:M})),P=kn(c,this.modelBindings);i.push(P)}if(this.throttleConfig){let c=jt(this.throttleConfig);i.push(c)}if(this.cacheConfig){let c=On(this.cacheConfig);i.push(c)}return i.push(...this.middleware),{method:this.method,path:this.path,handler:this.handler,middleware:i,name:this.routeName}}}class zn{router;condition;constructor(i,c){this.router=i;this.condition=c}middleware(i){let[c,P]=i.split(":"),M=this.router.resolveNamedMiddleware(c);if(!M)throw Error(`Unknown middleware: ${c}`);return this.router.addConditionalMiddleware({condition:this.condition,middleware:[M(P)]}),this}}class Gn{router;middleware;constructor(i,c){this.router=i;this.middleware=c}get(i,c){return new Se("GET",i,c).addMiddleware(this.middleware)}post(i,c){return new Se("POST",i,c).addMiddleware(this.middleware)}put(i,c){return new Se("PUT",i,c).addMiddleware(this.middleware)}delete(i,c){return new Se("DELETE",i,c).addMiddleware(this.middleware)}patch(i,c){return new Se("PATCH",i,c).addMiddleware(this.middleware)}}class Wn{router;groupMiddleware;constructor(i,c){this.router=i;this.groupMiddleware=c}get(i,c){return new Se("GET",i,c).addMiddleware(this.groupMiddleware)}post(i,c){return new Se("POST",i,c).addMiddleware(this.groupMiddleware)}put(i,c){return new Se("PUT",i,c).addMiddleware(this.groupMiddleware)}delete(i,c){return new Se("DELETE",i,c).addMiddleware(this.groupMiddleware)}patch(i,c){return new Se("PATCH",i,c).addMiddleware(this.groupMiddleware)}}class Yt{routes=[];globalMiddleware=[];subdomainRouter=new Ur;routeGroups=[];middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];constructor(){this.setupDefaultMiddleware()}setupDefaultMiddleware(){this.namedMiddleware.set("throttle",(i)=>{let c=i?Lt(i):{maxAttempts:60,windowMs:60000},P=jt({maxAttempts:c.maxAttempts,windowMs:c.windowMs,keyGenerator:(U)=>U.headers.get("x-forwarded-for")||"anonymous"});return async(U,z)=>await P(U,async()=>await z()??new Response(null))}),this.namedMiddleware.set("auth",()=>async(i,c)=>{if(!i.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return i.user={id:"123",roles:["user"]},await c()}),this.namedMiddleware.set("cors",()=>async(i,c)=>{let P=await c();if(P){let M=new Headers(P.headers);return M.set("Access-Control-Allow-Origin","*"),M.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"),M.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(P.body,{status:P.status,statusText:P.statusText,headers:M})}return P})}middlewareGroup(i,c){let P=[];for(let M of c){let[U,z]=M.split(":"),de=this.namedMiddleware.get(U);if(de)P.push(de(z))}return this.middlewareGroups.set(i,P),this}middlewareGroupRoutes(i){let c=this.middlewareGroups.get(i)||[];return new Wn(this,c)}when(i){return new zn(this,i)}resolveNamedMiddleware(i){return this.namedMiddleware.get(i)}addConditionalMiddleware(i){this.conditionalMiddleware.push(i)}middleware(i){let[c,P]=i.split(":"),M=this.namedMiddleware.get(c);if(!M)throw Error(`Unknown middleware: ${c}`);let U=M(P);return new Gn(this,[U])}use(i){return this.globalMiddleware.push(i),this}get(i,c){return new Se("GET",i,c)}post(i,c){return new Se("POST",i,c)}put(i,c){return new Se("PUT",i,c)}delete(i,c){return new Se("DELETE",i,c)}patch(i,c){return new Se("PATCH",i,c)}register(i){let c=i.build();if(this.routes.push(c),c.name)St(c.name,c.path);return this}cached(i=[],c){return{get:(P,M)=>this.get(P,M).cached(i,c),post:(P,M)=>this.post(P,M).cached(i,c),put:(P,M)=>this.put(P,M).cached(i,c),delete:(P,M)=>this.delete(P,M).cached(i,c),patch:(P,M)=>this.patch(P,M).cached(i,c)}}throttled(i){return{get:(c,P)=>this.get(c,P).throttle(i),post:(c,P)=>this.post(c,P).throttle(i),put:(c,P)=>this.put(c,P).throttle(i),delete:(c,P)=>this.delete(c,P).throttle(i),patch:(c,P)=>this.patch(c,P).throttle(i)}}group(i,c){let P=new Yt;c(P);for(let M of P.routes){let U={...M,path:i.prefix?`${i.prefix}${M.path}`:M.path,middleware:[...i.middleware||[],...M.middleware],name:i.name&&M.name?`${i.name}.${M.name}`:M.name};if(i.domain){let z=pt.parseDomainPattern(i.domain),de=new Qt(z,{domain:i.domain});de.addRoute(U.method,U.path,U.handler,U.middleware,U.name),this.subdomainRouter.addDomainGroup(de)}else if(this.routes.push(U),U.name)St(U.name,U.path)}return this}domain(i){return{routes:(c)=>{let P=new Yt;c(P);let M=pt.parseDomainPattern(i),U=new Qt(M,{domain:i});for(let z of P.routes)U.addRoute(z.method,z.path,z.handler,z.middleware,z.name);return this.subdomainRouter.addDomainGroup(U),this}}}resource(i,c,P={}){let M=["index","create","store","show","edit","update","destroy"],U=P.only||M.filter((de)=>!P.except?.includes(de)),z=[{action:"index",method:"GET",path:`/${i}`,handler:c.index},{action:"create",method:"GET",path:`/${i}/create`,handler:c.create},{action:"store",method:"POST",path:`/${i}`,handler:c.store},{action:"show",method:"GET",path:`/${i}/{${i.slice(0,-1)}}`,handler:c.show},{action:"edit",method:"GET",path:`/${i}/{${i.slice(0,-1)}}/edit`,handler:c.edit},{action:"update",method:"PUT",path:`/${i}/{${i.slice(0,-1)}}`,handler:c.update},{action:"destroy",method:"DELETE",path:`/${i}/{${i.slice(0,-1)}}`,handler:c.destroy}];for(let de of z)if(U.includes(de.action)&&de.handler){let pe=new Se(de.method,de.path,de.handler).name(`${i}.${de.action}`);if(P.model&&["show","edit","update","destroy"].includes(de.action))pe.model(i.slice(0,-1),P.model);this.register(pe)}return this}getRoutes(){return[...this.routes,...this.subdomainRouter.getAllRoutes()]}async handle(i){let c=new URL(i.url),P=c.hostname,M=this.subdomainRouter.findDomainGroup(P);if(M){let U=i;U.domainParams=M.parameters;for(let z of M.group.getRoutes()){let de=this.matchRouteParams(z,i.method,c.pathname);if(de)return await this.executeRoute(z,U,de)}}for(let U of this.routes){let z=this.matchRouteParams(U,i.method,c.pathname);if(z)return await this.executeRoute(U,i,z)}return null}matchRouteParams(i,c,P){if(i.method!==c)return null;let M={};return ht(i.path,P,M)?M:null}async executeRoute(i,c,P){c.params=P;let M=[...this.globalMiddleware];for(let de of this.conditionalMiddleware)if(await de.condition(c))M.push(...de.middleware);M.push(...i.middleware);let U=0,z=async()=>{if(U<M.length){let de=M[U++];return await de(c,z)??new Response(null)}return await i.handler(c)};return await z()}}var Li={api:(i,c,P={})=>{let M=P.method||"GET",U=new Se(M,i,c);if(P.cache)U.cached(P.cache);if(P.throttle)U.throttle(P.throttle);return U},protected:(i,c,P={})=>{let M=P.method||"GET",U=new Se(M,i,c);return U.addMiddleware(async(z,de)=>{if(!z.headers.get("Authorization"))return new Response("Unauthorized",{status:401});return await de()}),U},upload:(i,c,P={})=>{let M=new Se("POST",i,c);return M.addMiddleware(async(U,z)=>await z()),M}},zi={route:(i,c={},P={})=>{let M=Ir(i)??`/${i}`;for(let[z,de]of Object.entries(c)){let pe=encodeURIComponent(de);M=M.replace(`{${z}}`,pe),M=M.replace(`{${z}?}`,pe)}if(M.includes("?}")){if(M=M.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),M.length>1&&M.endsWith("/"))M=M.slice(0,-1)}let U=new URLSearchParams(P).toString();if(U)M+=`?${U}`;return M},redirect:(i,c=302)=>new Response(null,{status:c,headers:{Location:i}}),json:(i,c=200)=>new Response(JSON.stringify(i),{status:c,headers:{"Content-Type":"application/json"}})},Gi=new Yt;function Vn(i){Object.defineProperties(i.prototype,{group:{value(c,P){let M=this.currentGroup,U={...M};if(c.prefix&&M?.prefix)U.prefix=Mt(M.prefix,c.prefix);else if(c.prefix)U.prefix=c.prefix;if(c.middleware)U.middleware=[...M?.middleware||[],...c.middleware];this.currentGroup=U;let z=P();if(z instanceof Promise)return z.then(()=>(this.currentGroup=M,this),(de)=>{throw this.currentGroup=M,de});return this.currentGroup=M,this},writable:!0,configurable:!0},name:{value(c,P){let M=this.currentGroup||{},U={...M};this.currentGroup=U;let z=this.routes.length;P();for(let de=z;de<this.routes.length;de++){let pe=this.routes[de];if(pe.name)pe.name=`${c}.${pe.name}`}return this.currentGroup=M,this},writable:!0,configurable:!0},controller:{value(c,P){let M=this.currentGroup||{},U={...M,controller:c};return this.currentGroup=U,P(),this.currentGroup=M,this},writable:!0,configurable:!0},domain:{value(c,P){let M=this.currentDomain;return this.currentDomain=c,P(),this.currentDomain=M,this},writable:!0,configurable:!0},prefix:{value(c,P){return this.group({prefix:c},P)},writable:!0,configurable:!0},resource:{value(c,P,M="api"){let U=c.endsWith("s")?c:`${c}s`,z=c.endsWith("s")?c.slice(0,-1):c,de=[{name:"index",method:"GET",path:`/${U}`,action:"index"},{name:"create",method:"GET",path:`/${U}/create`,action:"create"},{name:"store",method:"POST",path:`/${U}`,action:"store"},{name:"show",method:"GET",path:`/${U}/{id}`,action:"show"},{name:"edit",method:"GET",path:`/${U}/{id}/edit`,action:"edit"},{name:"update",method:"PUT",path:`/${U}/{id}`,action:"update"},{name:"destroy",method:"DELETE",path:`/${U}/{id}`,action:"destroy"}];return this.name(z,()=>{for(let pe of de){let Re;if(typeof P==="string")Re=`${P}${pe.action.charAt(0).toUpperCase()+pe.action.slice(1)}Action`;else if(P[pe.action])Re=P[pe.action];else continue;switch(pe.method){case"GET":this.get(pe.path,Re,M,pe.name);break;case"POST":this.post(pe.path,Re,M,pe.name);break;case"PUT":this.put(pe.path,Re,M,pe.name);break;case"DELETE":this.delete(pe.path,Re,M,pe.name);break}}}),this},writable:!0,configurable:!0}})}function Jn(i){Object.defineProperties(i.prototype,{addRoute:{value(c,P,M,U,z,de){let pe=P,Re=[],Te=U||"web";if(this.currentGroup){if(this.currentGroup.prefix)pe=Mt(this.currentGroup.prefix,P);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)Re=[...this.currentGroup.middleware]}if(de&&de.length>0)for(let Pe of de){let Ee=this.resolveMiddleware(Pe);if(Ee)Re.push(Ee)}if(Te==="api"&&this.config.apiPrefix)pe=Mt(this.config.apiPrefix,pe);else if(Te==="web"&&this.config.webPrefix)pe=Mt(this.config.webPrefix,pe);let xe;if(this.currentDomain)xe=this.currentDomain;let ve={method:c.toUpperCase(),path:pe,handler:M,domain:xe,params:{},middleware:Re},Ce=wr(pe),Me={};if(Ce.forEach((Pe)=>{let Ee=Pe.replace("?","");if(this.patterns.has(Ee))Me[Ee]=this.patterns.get(Ee)}),Object.keys(Me).length>0)ve.constraints=Me;if(ve.pattern={exec:(Pe)=>{let Ee={},Ae=ve.constraints&&!Array.isArray(ve.constraints)?ve.constraints:void 0;if(!ht(pe,Pe.pathname,Ee,Ae))return null;return{pathname:{groups:Ee}}}},M instanceof Response)this.staticResponses.set(pe,M);if(xe){if(!this.domains[xe])this.domains[xe]=[];this.domains[xe].push(ve)}else this.routes.push(ve);if(!pe.includes("{")&&!pe.includes("*")){if(!this.staticRoutes.has(c.toUpperCase()))this.staticRoutes.set(c.toUpperCase(),new Map);let Pe=this.staticRoutes.get(c.toUpperCase());if(!Pe.has(pe))Pe.set(pe,ve)}if(z)ve.name=z,this.namedRoutes.set(z,ve),St(z,ve.path);if(this.addRouteToCompiler&&!xe)this.addRouteToCompiler(ve);return this.routeCache.clear(),this._allowedMethodsCache?.clear(),this},writable:!0,configurable:!0},get:{value(c,P,M,U,z){return this.addRoute("GET",c,P,M,U,z)},writable:!0,configurable:!0},post:{value(c,P,M,U,z){return this.addRoute("POST",c,P,M,U,z)},writable:!0,configurable:!0},put:{value(c,P,M,U,z){return this.addRoute("PUT",c,P,M,U,z)},writable:!0,configurable:!0},patch:{value(c,P,M,U,z){return this.addRoute("PATCH",c,P,M,U,z)},writable:!0,configurable:!0},delete:{value(c,P,M,U,z){return this.addRoute("DELETE",c,P,M,U,z)},writable:!0,configurable:!0},options:{value(c,P,M,U,z){return this.addRoute("OPTIONS",c,P,M,U,z)},writable:!0,configurable:!0},head:{value(c,P,M,U,z){return this.addRoute("HEAD",c,P,M,U,z)},writable:!0,configurable:!0},match:{value(c,P,M,U,z,de){for(let pe of c)this.addRoute(pe,P,M,U,z,de);return this},writable:!0,configurable:!0},any:{value(c,P,M,U,z){let de=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];return this.match(de,c,P,M,U,z)},writable:!0,configurable:!0},fallback:{value(c){return this.fallbackHandler=c,this},writable:!0,configurable:!0},route:{value(c,P={}){let M=this.namedRoutes.get(c);if(!M)throw Error(`Route with name "${c}" not found`);let U=M.path;for(let[z,de]of Object.entries(P))U=U.replace(`{${z}}`,encodeURIComponent(de)),U=U.replace(`{${z}?}`,encodeURIComponent(de));if(U.includes("{")){if(U=U.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),U.length>1&&U.endsWith("/"))U=U.slice(0,-1)}return U},writable:!0,configurable:!0},onError:{value(c){return this.errorHandler=c,this},writable:!0,configurable:!0}})}function Kn(i){Object.defineProperties(i.prototype,{redirect:{value(c,P=302){let M=new Headers;return M.set("Location",c),new Response(null,{status:P,headers:M})},writable:!0,configurable:!0},permanentRedirect:{value(c){return this.redirect(c,301)},writable:!0,configurable:!0},redirectRoute:{value(c,P,M=302){return this.get(c,(U)=>this.redirect(P,M)),this},writable:!0,configurable:!0},permanentRedirectRoute:{value(c,P){return this.redirectRoute(c,P,301)},writable:!0,configurable:!0}})}function lt(i){if(i instanceof Response)return i;if(i===null||i===void 0)return new Response(null,{status:204});if(typeof i==="string")return new Response(i,{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(typeof i==="number"||typeof i==="boolean")return new Response(String(i),{headers:{"Content-Type":"text/plain; charset=utf-8"}});if(i instanceof ArrayBuffer||i instanceof Uint8Array)return new Response(i,{headers:{"Content-Type":"application/octet-stream"}});if(i instanceof ReadableStream)return new Response(i);if(typeof i==="object")return new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json; charset=utf-8"}});return new Response(String(i),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}async function Wi(i,c){let P=c.actionsPath||"actions",M=c.controllersPath||"controllers",U=i.replace(/\.(ts|js)$/,""),z=[];if(U.includes("@")){let[pe,Re]=U.split("@");z.push(`${M}/${pe}`,`${M}/${pe}.ts`,`${M}/${pe}.js`,`./${M}/${pe}`,`../${M}/${pe}`)}else if(U.startsWith("Actions/")||U.startsWith("actions/"))z.push(U,`./${U}`,`../${U}`);else if(U.startsWith("./")||U.startsWith("../"))z.push(U);else z.push(`${P}/${U}`,`./${P}/${U}`,`../${P}/${U}`,U,`./${U}`,`../${U}`);let de=null;for(let pe of z)try{return await import(pe)}catch(Re){de=Re}throw Error(`Failed to import handler "${i}".
94
+ Tried paths: ${z.join(", ")}
95
+ Last error: ${de?.message||"Unknown error"}`)}function Xn(i){return typeof i==="function"&&!i.prototype?.handle}async function er(i,c,P){if(i instanceof Response)return i.clone();if(Xn(i)){let M=await i(c);return lt(M)}if(typeof i==="string")return Vi(i,c,P);if(typeof i==="function"&&i.prototype&&typeof i.prototype.handle==="function"){let z=await new i().handle(c);return lt(z)}if(i&&typeof i==="object"&&"handle"in i){let M=i;if(typeof M.handle==="function"){let U=await M.handle(c);return lt(U)}}throw Error(`Invalid handler type: ${typeof i}`)}async function Vi(i,c,P){let M=P.controllersPath||"controllers";if(i.includes("@")){let[de,pe]=i.split("@"),Re=[`${M}/${de}`,`./${M}/${de}`,`../${M}/${de}`,de,`./${de}`,`../${de}`],Te=null,xe=null;for(let Ce of Re)try{Te=await import(Ce);break}catch(Me){xe=Me}if(!Te)throw Error(`Failed to import controller "${de}".
96
+ Tried paths: ${Re.join(", ")}
97
+ Last error: ${xe?.message||"Unknown error"}`);let ve=Te.default||Te;if(typeof ve==="function"){let Ce=new ve,Me=Ce[pe];if(typeof Me!=="function")throw TypeError(`Method "${pe}" not found on controller "${de}"`);let Pe=await Me.call(Ce,c);return lt(Pe)}throw Error(`Controller "${de}" is not a valid class`)}let U=await Wi(i,P),z=U.default||U;if(typeof z==="function"){if(z.prototype&&typeof z.prototype.handle==="function"){let Re=await new z().handle(c);return lt(Re)}let de=await z(c);return lt(de)}if(z&&typeof z==="object"&&"handle"in z){let de=z;if(typeof de.handle==="function"){let pe=await de.handle(c);return lt(pe)}}throw Error(`Handler "${i}" does not export a valid handler function or class`)}function Ji(i){return(c,P)=>er(c,P,i)}function Qn(i,c){if(i instanceof Response)return async()=>i.clone();if(Xn(i))return async(P)=>lt(await i(P));if(typeof i==="function"&&i.prototype&&typeof i.prototype.handle==="function"){let P=i;return async(M)=>lt(await new P().handle(M))}return(P)=>er(i,P,c)}function Zn(i){Object.defineProperties(i.prototype,{use:{value(...c){for(let P of c){let M=this.resolveMiddleware(P);if(M)this.globalMiddleware.push(M)}return this._mwEpoch=(this._mwEpoch||0)+1,this},writable:!0,configurable:!0},resolveMiddleware:{value(c){if(typeof c==="function")return c;if(typeof c==="object"&&c!==null&&"handle"in c&&typeof c.handle==="function")return(P,M)=>c.handle(P,M);if(typeof c==="string"){let[P,M]=c.split(":"),U=this.namedMiddleware?.get(P);if(U)return U(M);let z=null,de=c;return async(pe,Re)=>{if(!z)try{let Te=await import(`../middleware/${de}.ts`);if(Te.default&&typeof Te.default==="function")z=Te.default;else if(Te.default&&typeof Te.default.handle==="function")z=(xe,ve)=>Te.default.handle(xe,ve)}catch(Te){console.error(`Failed to load middleware "${de}":`,Te)}if(z)return z(pe,Re);return Re()}}return null},writable:!0,configurable:!0},buildMiddlewareChain:{value(c){if(c.length===0)return async(M)=>null;let P=async(M)=>null;for(let M=c.length-1;M>=0;M--){let U=c[M],z=P;P=async(de)=>U(de,async()=>await z(de)||new Response(null,{status:200}))}return P},writable:!0,configurable:!0},runMiddleware:{async value(c,P){if(P.length===0)return null;try{return await this.buildMiddlewareChain(P)(c)}catch(M){if(this.errorHandler)return this.errorHandler(M);throw M}},writable:!0,configurable:!0},middleware:{value(...c){for(let P of c)if(typeof P==="string"){let[M]=P.split(":");if(!this.namedMiddleware.has(M))throw Error(`Unknown middleware: ${M}`)}if(this.currentGroup){if(!this.currentGroup.middleware)this.currentGroup.middleware=[];this.currentGroup.middleware.push(...c)}else{let P=this.routes[this.routes.length-1];if(P)this.applyMiddlewareToRoute(P,c)}return this},writable:!0,configurable:!0},applyMiddlewareToRoute:{value(c,P){for(let M of P){let U=this.resolveMiddleware(M);if(U)c.middleware.push(U)}},writable:!0,configurable:!0},resolveHandler:{async value(c,P){return er(c,P,this.config)},writable:!0,configurable:!0},wrapResponse:{value:lt,writable:!0,configurable:!0},onError:{value(c){return this.errorHandler=c,this},writable:!0,configurable:!0}})}class Yn{models=new Map;cache=new Map;register(i,c){this.models.set(i,c)}get(i){return this.models.get(i)}has(i){return this.models.has(i)}async resolve(i,c,P){let M=this.models.get(i);if(!M)return{model:null,error:`Model binding '${i}' not found`,status:500};try{if(M.cache?.enabled){let de=this.getCachedModel(i,c,M);if(de)return{model:de}}let U=await M.resolver(c,P);if(U===null||U===void 0)return{model:null,error:`${i} not found`,status:404};if(M.validator){let de=await M.validator(U,c,P);if(!de.valid)return{model:null,error:de.error||"Model validation failed",status:de.status||422}}let z=U;if(M.transformer)z=await M.transformer(U,c,P);if(M.cache?.enabled)this.cacheModel(i,c,z,M);return{model:z}}catch(U){return{model:null,error:U instanceof Error?U.message:"Model resolution failed",status:500}}}createErrorResponse(i,c,P){let M=this.models.get(i),U=c.status||404,z=c.error||"Model not found";if(M?.errorHandling){if(U===404&&M.errorHandling.notFound)return M.errorHandling.notFound(P);if(U===422&&M.errorHandling.validation)return M.errorHandling.validation(null,z);if(M.errorHandling.transform)return M.errorHandling.transform(z)}return new Response(JSON.stringify({error:z,status:U,message:`Failed to resolve ${i}`}),{status:U,headers:{"Content-Type":"application/json"}})}clearCache(i,c){if(c){let P=this.models.get(i);if(P?.cache){let M=this.generateCacheKey(i,c,P);this.cache.delete(M)}}else{let P=[];for(let M of this.cache.keys())if(M.startsWith(`${i}:`))P.push(M);for(let M of P)this.cache.delete(M)}}clearAllCache(){this.cache.clear()}getCacheStats(){let i=Date.now(),c=0,P=0;for(let M of this.cache.values())if(i-M.timestamp>M.ttl)P++;else c++;return{totalEntries:this.cache.size,validEntries:c,expiredEntries:P,models:this.models.size}}cleanupCache(){let i=Date.now(),c=[];for(let[P,M]of this.cache.entries())if(i-M.timestamp>M.ttl)c.push(P);for(let P of c)this.cache.delete(P);return c.length}getCachedModel(i,c,P){if(!P.cache?.enabled)return null;let M=this.generateCacheKey(i,c,P),U=this.cache.get(M);if(!U)return null;if(Date.now()-U.timestamp>U.ttl)return this.cache.delete(M),null;return U.model}cacheModel(i,c,P,M){if(!M.cache?.enabled)return;let U=this.generateCacheKey(i,c,M);this.cache.set(U,{model:P,timestamp:Date.now(),ttl:M.cache.ttl})}generateCacheKey(i,c,P){if(P.cache?.key)return`${i}:${P.cache.key(c)}`;let M=Object.entries(c).sort(([U],[z])=>U.localeCompare(z)).map(([U,z])=>`${U}=${z}`).join("&");return`${i}:${M}`}}var es=new Yn;function ts(i){Object.defineProperties(i.prototype,{modelRegistry:{value:es,writable:!0,configurable:!0},model:{value(c,P,M){if(typeof P==="string")this.modelRegistry.register(c,{resolver:async(U)=>(console.warn(`Model class ${P} not implemented`),{id:U[c],modelClass:P}),errorHandling:M?{notFound:(U)=>M(null)||new Response("Not Found",{status:404})}:void 0});else this.modelRegistry.register(c,{resolver:async(U)=>{let z=U[c];if(!z)return null;return P(z)},errorHandling:M?{notFound:(U)=>M(null)||new Response("Not Found",{status:404})}:void 0});return this},writable:!0,configurable:!0},implicitBinding:{value(){return async(c,P)=>{if(!c.params)return await P()||new Response("Not Found",{status:404});for(let[U,z]of Object.entries(c.params))if(this.modelRegistry.has(U))try{let de=await this.modelRegistry.resolve(U,c.params,c);if(de.model===null){if(de.status===500)return new Response(JSON.stringify({error:"Internal Server Error",message:de.error||"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}});else if(de.status===404)return this.modelRegistry.createErrorResponse(U,de,c.params)}else c[U]=de.model}catch(de){return new Response(JSON.stringify({error:"Internal Server Error",message:de instanceof Error?de.message:"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}})}return await P()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},missing:{value(c){return async(P,M)=>{try{return await M()||c(P)}catch(U){return console.error(U),c(P)}}},writable:!0,configurable:!0},scopedBindings:{value(c){return async(P,M)=>{if(!P.params)return await M()||new Response("Not Found",{status:404});for(let[z,de]of Object.entries(c))if(P.params[z]&&P.params[de]);return await M()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},clearModelCache:{value(c){if(c)this.modelRegistry.clearCache(c);else this.modelRegistry.clearAllCache();return this},writable:!0,configurable:!0},getModelStats:{value(){return this.modelRegistry.getCacheStats()},writable:!0,configurable:!0}})}class kt{children=new Map;paramChild=null;wildcardChild=null;routes=new Map;paramName=null;pattern=null;isEndpoint=!1;addRoute(i,c){this.routes.set(i,c),this.isEndpoint=!0}getRoute(i){return this.routes.get(i)}getAllRoutes(){return Array.from(this.routes.values())}}class Lr{root=new kt;compiledRoutes=new Map;methodTries=new Map;constructor(){let i=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","TRACE","CONNECT"];for(let c of i)this.methodTries.set(c,new kt)}compileRoute(i){let c=`${i.method}:${i.path}`;if(i.constraints&&!Array.isArray(i.constraints)){let Re=i.constraints,xe=Object.keys(Re).sort().map((ve)=>`${ve}:${Re[ve]}`).join("|");c=`${i.method}:${i.path}#${xe}`}if(this.compiledRoutes.has(c))return this.compiledRoutes.get(c);let P=this.parsePathSegments(i.path),M=P.filter((Re)=>Re.type==="parameter").map((Re)=>Re.paramName);if(i.constraints&&!Array.isArray(i.constraints)){let Re=i.constraints;for(let Te of P)if(Te.type==="parameter"&&Te.paramName&&Re[Te.paramName])Te.pattern=new RegExp(`^${Re[Te.paramName]}$`)}let U=this.calculateRoutePriority(P),z=P.filter((Re)=>Re.type==="static").length,de=P.filter((Re)=>Re.type!=="static").length,pe={route:i,segments:P,paramNames:M,priority:U,staticScore:z,dynamicScore:de};return this.compiledRoutes.set(c,pe),pe}parsePathSegments(i){let c=[],P=i.split("/").filter((M)=>M.length>0);for(let M of P)if(M==="*")c.push({type:"wildcard",value:"*"});else if(/^\{[^{}/]+\}\*$/.test(M))c.push({type:"wildcard",value:M,paramName:M.slice(1,M.indexOf("}"))});else if(M.startsWith("{")&&M.endsWith("}")){let U=M.slice(1,-1),[z,de]=U.split(":");c.push({type:"parameter",value:M,paramName:z.replace("?",""),pattern:de?new RegExp(`^${de}$`):void 0,optional:U.endsWith("?")})}else if(M.includes("{")){let U=M.replace(/\{([^}:]+)(?::([^}]+))?\}/g,(de,pe,Re)=>Re?`(${Re})`:"([^/]+)"),z=Array.from(M.matchAll(/\{([^}:]+)(?::([^}]+))?\}/g)).map((de)=>de[1].replace("?",""));c.push({type:"parameter",value:M,paramName:z[0],pattern:new RegExp(`^${U}$`)})}else c.push({type:"static",value:M});return c}calculateRoutePriority(i){let c=0;for(let P=0;P<i.length;P++){let M=i[P],U=i.length-P;switch(M.type){case"static":c+=U*1000;break;case"parameter":if(M.pattern)c+=U*100;else c+=U*10;break;case"wildcard":c+=U*1;break}}return c}addRoute(i){let c=this.compileRoute(i);this.insertRoute(this.root,c,0);let P=this.methodTries.get(i.method);if(P)this.insertRoute(P,c,0)}insertRoute(i,c,P){if(P>=c.segments.length){i.addRoute(c.route.method,c);return}let M=c.segments[P];switch(M.type){case"static":if(!i.children.has(M.value))i.children.set(M.value,new kt);this.insertRoute(i.children.get(M.value),c,P+1);break;case"parameter":if(!i.paramChild)i.paramChild=new kt,i.paramChild.paramName=M.paramName,i.paramChild.pattern=M.pattern||null;this.insertRoute(i.paramChild,c,P+1);break;case"wildcard":if(!i.wildcardChild)i.wildcardChild=new kt,i.wildcardChild.paramName=M.paramName??null;this.insertRoute(i.wildcardChild,c,P+1);break}}match(i,c){let P=i.split("/").filter((U)=>U.length>0),M=this.methodTries.get(c);if(M){let U=this.matchSegments(M,P,0,{},c);if(U)return U}return this.matchSegments(this.root,P,0,{},c)}matchSegments(i,c,P,M,U){if(P>=c.length){let Te=i.getRoute(U);if(Te)return{route:Te.route,params:M,score:Te.priority};return null}let z=c[P],de=i.children.get(z);if(de){let Te=this.matchSegments(de,c,P+1,M,U);if(Te)return Te}let pe=i.paramChild,Re=pe?.paramName?Nt(z):z;if(pe&&pe.paramName&&(!pe.pattern||pe.pattern.test(Re))){let Te=M[pe.paramName];M[pe.paramName]=Re;let xe=this.matchSegments(pe,c,P+1,M,U);if(xe)return xe;if(Te===void 0)delete M[pe.paramName];else M[pe.paramName]=Te}if(i.wildcardChild){let Te=i.wildcardChild.getRoute(U);if(Te)return M[i.wildcardChild.paramName??"wildcard"]=c.slice(P).map(Nt).join("/"),{route:Te.route,params:M,score:Te.priority}}return null}getAllRoutes(){return Array.from(this.compiledRoutes.values())}removeRoute(i){let c=`${i.method}:${i.path}`;if(i.constraints&&!Array.isArray(i.constraints)){let P=i.constraints,U=Object.keys(P).sort().map((z)=>`${z}:${P[z]}`).join("|");c=`${i.method}:${i.path}#${U}`}this.compiledRoutes.delete(c)}clear(){this.root=new kt,this.compiledRoutes.clear();for(let[i]of this.methodTries)this.methodTries.set(i,new kt)}getStats(){let i={totalRoutes:this.compiledRoutes.size,totalNodes:this.countNodes(this.root),averageDepth:0,methodDistribution:{}};for(let c of this.compiledRoutes.values()){let P=c.route.method;i.methodDistribution[P]=(i.methodDistribution[P]||0)+1}return i}countNodes(i){let c=1;for(let P of i.children.values())c+=this.countNodes(P);if(i.paramChild)c+=this.countNodes(i.paramChild);if(i.wildcardChild)c+=this.countNodes(i.wildcardChild);return c}}class br{trie;matchCache=new Map;routeKeys=new Set;stats={totalMatches:0,cacheHits:0,cacheMisses:0,averageMatchTime:0,trieDepth:0,methodDistribution:{}};options;constructor(i={}){this.options={enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0,enableProfiling:!1,...i},this.trie=new Lr}addRoute(i){if(this.options.precompilePatterns)this.precompileRoutePattern(i);let c=`${i.method}:${i.path}`;if(this.routeKeys.has(c))return!1;if(this.routeKeys.add(c),this.trie.addRoute(i),this.options.enableCaching)this.matchCache.clear();let P=i.method;return this.stats.methodDistribution[P]=(this.stats.methodDistribution[P]||0)+1,!0}patternCache=new Map;extractParamNames(i){let c=[],P=/\{([^}:]+)(?::[^}]+)?\}/g,M;while(M=P.exec(i))c.push(M[1].replace("?",""));return c}precompileRoutePattern(i){if(!i.pattern&&i.path.includes("{")){let c=i.path;if(i.constraints&&!Array.isArray(i.constraints)){let U=i.constraints,de=Object.keys(U).sort().map((pe)=>`${pe}:${U[pe]}`).join("|");c=`${i.path}#${de}`}if(this.patternCache.has(c)){i.pattern=this.patternCache.get(c);return}let P=this.convertToURLPattern(i.path,i.constraints&&!Array.isArray(i.constraints)?i.constraints:void 0),M={exec:(U)=>{let z=U.pathname,de=P.exec(z);if(!de)return null;return{pathname:{groups:de.groups||{}}}}};this.patternCache.set(c,M),i.pattern=M}}convertToURLPattern(i,c){let P=i,M=null,U=P.match(/\{([^{}/]+)\}\*$/);if(U)M=U[1],P=P.slice(0,U.index);else if(P.endsWith("*"))M="wildcard",P=P.slice(0,-1);let z=[],pe=P.replace(/\{([^}]+)\}/g,(Te,xe)=>(z.push(xe),`\x00${z.length-1}\x00`)).replace(/[.+*?^${}()|[\]\\]/g,"\\$&");if(pe=pe.replace(/\/?\u0000(\d+)\u0000/g,(Te,xe)=>{let ve=z[Number(xe)],Ce=ve.endsWith("?"),Me=Ce?ve.slice(0,-1):ve,Pe=Me.indexOf(":"),Ee=Pe===-1?Me:Me.slice(0,Pe),Ae=Pe===-1?void 0:Me.slice(Pe+1),Fe=c?.[Ee]??Ae??"[^/]+",Dt=`(?<${Ee}>${Fe})`,ir=Te.startsWith("/")?"/":"";return Ce?`(?:${ir}${Dt})?`:`${ir}${Dt}`}),M!==null)pe+=`(?<${M}>${c?.[M]??".+"})`;let Re=new RegExp(`^${pe}$`);return{exec:(Te)=>{let xe=Te.match(Re);if(!xe)return null;return{groups:xe.groups||{}}}}}match(i,c){let P=this.options.enableProfiling?performance.now():0;if(this.stats.totalMatches++,this.options.enableCaching){let z=`${c}:${i}`,de=this.matchCache.get(z);if(de!==void 0||this.matchCache.has(z)){if(this.stats.cacheHits++,P)this.updateMatchTime(P);return de?{route:de.route,params:{...de.params}}:null}this.stats.cacheMisses++}let M=this.trie.match(i,c),U=null;if(M)U={route:M.route,params:M.params};if(this.options.enableCaching){let z=`${c}:${i}`;this.addToCache(z,U)}if(P)this.updateMatchTime(P);return U?{route:U.route,params:{...U.params}}:null}addToCache(i,c){if(this.matchCache.size>=this.options.cacheSize&&!this.matchCache.has(i)){let P=this.matchCache.keys().next().value;if(P!==void 0)this.matchCache.delete(P)}this.matchCache.set(i,c)}updateMatchTime(i){let c=performance.now()-i;this.stats.averageMatchTime=(this.stats.averageMatchTime*(this.stats.totalMatches-1)+c)/this.stats.totalMatches}getCompiledRoutes(){let i=this.trie.getAllRoutes();if(this.options.enablePriorityOptimization)return i.sort((c,P)=>P.priority-c.priority);return i}getRoutesByMethod(){let i=new Map;for(let c of this.trie.getAllRoutes()){let P=c.route.method;if(!i.has(P))i.set(P,[]);i.get(P).push(c)}if(this.options.enablePriorityOptimization)for(let[c,P]of i)P.sort((M,U)=>U.priority-M.priority),i.set(c,P);return i}warmCache(i,c={}){if(!this.options.enableCaching&&!c.force)return{warmedPaths:0,cacheSize:0,hitRate:0};let P=this.options.enableCaching;if(c.force&&!this.options.enableCaching)this.options.enableCaching=!0;if(c.precompile)for(let{path:xe,method:ve}of i){let Ce=`${ve}:${xe}`;this.matchCache.delete(Ce)}let M=this.matchCache.size,U=this.stats.cacheHits,z=this.stats.totalMatches;for(let{path:xe,method:ve}of i)if(this.match(xe,ve),c.precompile)this.match(xe,ve);let de=this.matchCache.size-M,pe=this.stats.cacheHits-U,Re=this.stats.totalMatches-z,Te=Re>0?pe/Re:0;if(c.force&&!P)this.options.enableCaching=P;return{warmedPaths:de,cacheSize:this.matchCache.size,hitRate:Te}}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 i=this.trie.getStats();return{...this.stats,trieDepth:i.averageDepth,methodDistribution:i.methodDistribution}}getCacheStats(){let i=this.stats.totalMatches>0?this.stats.cacheHits/this.stats.totalMatches:0;return{size:this.matchCache.size,maxSize:this.options.cacheSize,hitRate:i,enabled:this.options.enableCaching}}optimizeRouteOrder(i){if(!this.options.enablePriorityOptimization)return;this.matchCache.clear()}getRouteConflicts(){let i=[],c=this.trie.getAllRoutes(),P=new Map;for(let M of c){let U=M.route.method;if(!P.has(U))P.set(U,[]);P.get(U).push(M)}for(let[M,U]of P)for(let z=0;z<U.length;z++)for(let de=z+1;de<U.length;de++){let pe=U[z],Re=U[de];if(this.routesConflict(pe,Re)){let Te=this.getConflictSeverity(pe,Re),xe=this.getConflictType(pe,Re);i.push({routes:[pe,Re],conflictType:xe,severity:Te})}}return i}routesConflict(i,c){if(i.route.path===c.route.path)return!0;if(i.route.method!==c.route.method)return!1;return this.patternsOverlap(i.segments,c.segments)}patternsOverlap(i,c){let P=i.some((de)=>de.optional||de.type==="wildcard"),M=c.some((de)=>de.optional||de.type==="wildcard");if(i.length!==c.length&&!P&&!M)return!1;let U=Math.max(i.length,c.length),z=!0;for(let de=0;de<U;de++){let pe=de<i.length?i[de]:null,Re=de<c.length?c[de]:null;if(!pe&&Re&&!Re.optional)return!1;if(!Re&&pe&&!pe.optional)return!1;if(!pe||!Re)continue;if(pe.type==="static"&&Re.type==="static"){if(pe.value!==Re.value)return!1}else if(pe.type==="parameter"&&Re.type==="parameter"){if(pe.pattern&&Re.pattern){if(pe.pattern.toString()===Re.pattern.toString())z=!0}if(pe.paramName===Re.paramName)z=!0}else if(pe.type==="static"&&Re.type==="parameter"||pe.type==="parameter"&&Re.type==="static"){let Te=pe.type==="static"?pe:Re,xe=pe.type==="parameter"?pe:Re;if(xe.pattern){if(!xe.pattern.test(Te.value))return!1}}else if(pe.type==="wildcard"||Re.type==="wildcard")return!0}return z}getConflictSeverity(i,c){if(i.route.path===c.route.path)return"high";if(i.staticScore===c.staticScore)return"medium";return"low"}getConflictType(i,c){if(i.route.path===c.route.path)return"duplicate";if(this.hasAmbiguousParameters(i,c))return"ambiguous";if(Math.abs(i.priority-c.priority)<10)return"ambiguous";return"overlap"}hasAmbiguousParameters(i,c){if(Math.abs(i.segments.length-c.segments.length)>1)return!1;let P=i.segments.filter((U)=>U.type==="parameter").length,M=c.segments.filter((U)=>U.type==="parameter").length;if(P>0&&M>0){let U=Math.min(i.segments.length,c.segments.length),z=0;for(let de=0;de<U;de++)if(i.segments[de].type==="parameter"&&c.segments[de].type==="parameter"){z++;let pe=!!i.segments[de].pattern,Re=!!c.segments[de].pattern;if(pe!==Re)return!0}return z>0&&z>=Math.min(P,M)/2}return!1}}function rs(i){Object.defineProperties(i.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new br({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0})},writable:!0,configurable:!0},addRouteToCompiler:{value(c){this.initializeRouteCompiler(),this.routeCompiler.addRoute(c)},writable:!0,configurable:!0},matchRoute:{value(c,P,M){if(this.initializeRouteCompiler(),M&&this.domains[M]){let U=this.fallbackMatchRoute(c,P,M);if(U)return U}else{let U=this.routeCompiler.match(c,P);if(U&&(!M||!U.route.domain||U.route.domain===M))return U;let z=this.fallbackMatchRoute(c,P,M);if(z)return z}if(P==="HEAD")return this.matchRoute(c,"GET",M);return},writable:!0,configurable:!0},fallbackMatchRoute:{value(c,P,M){let U=new URL(c,"http://localhost"),z=`${M||""}:${P}:${U.pathname}`;if(this.routeCache.has(z))return this.routeCache.get(z);if(this.routeCache.size>=1e4)this.routeCache.clear();if(this.staticRoutes.has(P)){let Te=this.staticRoutes.get(P).get(U.pathname);if(Te&&(!M||!Te.domain||Te.domain===M)){let xe={route:Te,params:{}};return this.routeCache.set(z,xe),xe}}let pe=(M&&this.domains[M]?this.domains[M]:this.routes).filter((Te)=>Te.method===P);for(let Te of pe)if(Te.path===U.pathname){let xe={route:Te,params:{}};return this.routeCache.set(z,xe),xe}for(let Te of pe)if(Te.pattern){let xe=Te.pattern.exec(U);if(xe){let ve={route:Te,params:xe.pathname.groups};return this.routeCache.set(z,ve),ve}}let Re=M&&this.domains[M]?[this.domains[M],this.routes]:[this.routes];for(let Te of Re)for(let xe of Te){if(xe.method!==P||!xe.path.endsWith("*"))continue;let ve=xe.path.slice(0,-1);if(U.pathname.startsWith(ve)){let Ce={route:xe,params:{wildcard:U.pathname.slice(ve.length)}};return this.routeCache.set(z,Ce),Ce}}this.routeCache.set(z,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(c){this.initializeRouteCompiler(),this.routeCompiler.warmCache(c)},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 br({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0});for(let c of this.routes)this.routeCompiler.addRoute(c);for(let c of Object.values(this.domains))for(let P of c)this.routeCompiler.addRoute(P)},writable:!0,configurable:!0},optimizeRoutes:{value(c={}){this.initializeRouteCompiler(),this.routeCompiler.optimizeRouteOrder(c)},writable:!0,configurable:!0}})}function ns(i){Object.defineProperties(i.prototype,{buildBunServeRoutes:{value(){let c={},P=new Map;for(let M of this.routes){if(!P.has(M.path))P.set(M.path,[]);P.get(M.path).push(M)}for(let[M,U]of P.entries())if(U.length===1){let z=U[0];if(typeof z.handler==="function"&&z.handler.toString().includes("new Response")&&!z.handler.toString().includes("await")&&z.middleware.length===0)try{let de=this.enhanceRequest(new Request("https://example.com"),{}),pe=z.handler(de);if(pe instanceof Response){c[M]=pe;continue}}catch{}c[M]=async(de)=>{let pe=new URL(de.url),Re={},Te=z.constraints&&!Array.isArray(z.constraints)?z.constraints:void 0;ht(M,pe.pathname,Re,Te);let xe=this.enhanceRequest(de,Re),ve=async(Pe,Ee)=>await this.resolveHandler(z.handler,Pe),Ce=[...this.globalMiddleware,...z.middleware,ve],Me=await this.runMiddleware(xe,Ce);return this.applyModifiedCookies(Me??new Response("No response from middleware chain",{status:500}),xe)}}else{let z={};for(let de of U){let pe=de.method;z[pe]=async(Re)=>{let Te=new URL(Re.url),xe={},ve=de.constraints&&!Array.isArray(de.constraints)?de.constraints:void 0;ht(M,Te.pathname,xe,ve);let Ce=this.enhanceRequest(Re,xe),Me=async(Ae,Fe)=>await this.resolveHandler(de.handler,Ae),Pe=[...this.globalMiddleware,...de.middleware,Me],Ee=await this.runMiddleware(Ce,Pe);return this.applyModifiedCookies(Ee??new Response("No response from middleware chain",{status:500}),Ce)}}c[M]=z}return c},writable:!0,configurable:!0},loadRoutes:{async value(){if(!this.config.routesPath)return;try{if(this.config.apiRoutesPath)try{let c=await import(this.config.apiRoutesPath);if(c.default&&Array.isArray(c.default))for(let P of c.default)this.registerRoute(P,"api")}catch(c){if(this.config.verbose)console.warn(`Failed to load API routes: ${c}`)}if(this.config.webRoutesPath)try{let c=await import(this.config.webRoutesPath);if(c.default&&Array.isArray(c.default))for(let P of c.default)this.registerRoute(P,"web")}catch(c){if(this.config.verbose)console.warn(`Failed to load Web routes: ${c}`)}}catch(c){console.error("Error loading routes:",c)}},writable:!0,configurable:!0},registerRoute:{value(c,P){let{path:M,method:U,handler:z,middleware:de=[],name:pe}=c;switch(U){case"GET":this.get(M,z,P,pe,de);break;case"POST":this.post(M,z,P,pe,de);break;case"PUT":this.put(M,z,P,pe,de);break;case"DELETE":this.delete(M,z,P,pe,de);break;case"PATCH":this.patch(M,z,P,pe,de);break;case"OPTIONS":this.options(M,z,P,pe,de);break;default:console.warn(`Unsupported HTTP method: ${U}`)}},writable:!0,configurable:!0}})}function ss(i){Object.defineProperties(i.prototype,{matchRoute:{value(c,P,M){let U=new URL(c,"http://localhost"),z=`${M||""}:${P}:${U.pathname}`;if(this.routeCache.has(z))return this.routeCache.get(z);if(this.staticRoutes.has(P)){let Te=this.staticRoutes.get(P).get(U.pathname);if(Te&&(!M||!Te.domain||Te.domain===M)){let xe={route:Te,params:{}};return this.routeCache.set(z,xe),xe}}let de=M&&this.domains[M]?this.domains[M]:this.routes,pe=de.filter((Te)=>Te.method===P);for(let Te of pe)if(Te.path===U.pathname){let xe={route:Te,params:{}};return this.routeCache.set(z,xe),xe}for(let Te of pe)if(Te.pattern){let xe=Te.pattern.exec(U);if(xe){let ve={route:Te,params:xe.pathname.groups};return this.routeCache.set(z,ve),ve}}if(M&&this.domains[M]){let Te=this.domains[M].filter((xe)=>xe.method===P&&xe.path.endsWith("*"));for(let xe of Te){let ve=xe.path.slice(0,-1);if(U.pathname.startsWith(ve)){let Ce={route:xe,params:{wildcard:U.pathname.slice(ve.length)}};return this.routeCache.set(z,Ce),Ce}}}let Re=this.routes.filter((Te)=>Te.method===P&&Te.path.endsWith("*")&&(!M||!Te.domain));for(let Te of Re){let xe=Te.path.slice(0,-1);if(U.pathname.startsWith(xe)){let ve={route:Te,params:{wildcard:U.pathname.slice(xe.length)}};return this.routeCache.set(z,ve),ve}}if(P==="HEAD")return this.matchRoute(c,"GET",M);if(P==="OPTIONS"){let Te=de.find((xe)=>xe.method==="OPTIONS"&&xe.path==="*");if(Te){let xe={route:Te,params:{}};return this.routeCache.set(z,xe),xe}for(let xe of["GET","POST","PUT","PATCH","DELETE"]){let ve=this.matchRoute(c,xe,M);if(ve){let Ce={route:{...ve.route,method:"OPTIONS",handler:(Me)=>new Response(null,{status:204})},params:ve.params};return this.routeCache.set(z,Ce),Ce}}}return},writable:!0,configurable:!0},matchDomain:{value(c,P){if(c===P)return!0;if(c.startsWith("*.")){let M=c.substring(2);return P===M||P.endsWith(`.${M}`)}if(c.includes("{")){let M;if(!this.domainPatternCache.has(c)){let U=c.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)");M=new RegExp(`^${U}$`),this.domainPatternCache.set(c,M)}else M=this.domainPatternCache.get(c);return M.test(P)}return!1},writable:!0,configurable:!0},extractDomainParams:{value(c,P){let M={};if(!c.includes("{"))return M;let U=c.match(/\{([^}]+)\}/g)?.map((pe)=>pe.substring(1,pe.length-1))||[],z=c.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)"),de=P.match(new RegExp(`^${z}$`));if(de&&de.length>1)for(let pe=0;pe<U.length;pe++)M[U[pe]]=de[pe+1];return M},writable:!0,configurable:!0},pattern:{value(c,P){return this.patterns.set(c,P),this},writable:!0,configurable:!0},where:{value(c){let P=this.routes[this.routes.length-1];if(P){P.constraints={...P.constraints||{},...c};let M=P.path,U=P.constraints&&!Array.isArray(P.constraints)?P.constraints:void 0;if(P.pattern={exec:(z)=>{let de={};if(!ht(M,z.pathname,de,U))return null;return{pathname:{groups:de}}}},this.routeCache.clear(),this.routeCompiler){let z=[...this.routes];this.routeCompiler.clear();for(let de of z)this.routeCompiler.addRoute(de)}}return this},writable:!0,configurable:!0},withoutNativeDispatch:{value(){let c=this.routes[this.routes.length-1];if(c)c.nativeDispatch=!1;return this},writable:!0,configurable:!0},whereNumber:{value(c){return this.where({[c]:"\\d+"})},writable:!0,configurable:!0},whereAlpha:{value(c){return this.where({[c]:"[A-Za-z]+"})},writable:!0,configurable:!0},whereAlphaNumeric:{value(c){return this.where({[c]:"[A-Za-z0-9]+"})},writable:!0,configurable:!0},whereUuid:{value(c){return this.where({[c]:"[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(c,P){return this.where({[c]:P.join("|")})},writable:!0,configurable:!0}})}var Ki=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,Xi=/bot|crawler|spider|crawling/i,Tr=new Map;function Gt(i){let c=i;if(!c._parsedURL)c._parsedURL=new URL(i.url);return c._parsedURL}function qt(i){let c=i;if(!c._parsedCookies){let P={},M=i.headers.get("cookie");if(M)for(let U of M.split(";")){let z=U.indexOf("=");if(z===-1)continue;let de=U.slice(0,z).trim();if(!de)continue;let pe=U.slice(z+1).trim();try{P[de]=decodeURIComponent(pe)}catch{P[de]=pe}}c._parsedCookies=P}return c._parsedCookies}class as{macros=new Map;epoch=0;register(i,c,P=!1){this.macros.set(i,{name:i,handler:c,accessor:P}),this.epoch++}get(i){return this.macros.get(i)}has(i){return this.macros.has(i)}all(){return Array.from(this.macros.values())}remove(i){let c=this.macros.delete(i);if(c)this.epoch++;return c}clear(){this.macros.clear(),this.epoch++}getEpoch(){return this.epoch}}var tr=new as,is=Symbol("bunRouterMacroProto"),zr=Symbol("bunRouterMacroBase"),xr=new WeakMap,os=-1;class $e{static macro(i,c){tr.register(i,c)}static macroAccessor(i,c){tr.register(i,c,!0)}static applyMacros(i){let c=tr.getEpoch();if(c!==os)xr=new WeakMap,os=c;let P=Object.getPrototypeOf(i)??Object.prototype;if(P[is]){if(xr.get(P[zr])===P)return i;P=P[zr]}let M=xr.get(P);if(!M){M=Object.create(P);for(let U of tr.all())if(U.accessor)Object.defineProperty(M,U.name,{get:U.handler,set(z){Object.defineProperty(this,U.name,{value:z,writable:!0,configurable:!0,enumerable:!0})},configurable:!0});else M[U.name]=U.handler;Object.defineProperty(M,is,{value:!0}),Object.defineProperty(M,zr,{value:P}),xr.set(P,M)}return Object.setPrototypeOf(i,M),i}static hasMacro(i){return tr.has(i)}}var rr={wantsJson(){let i=this.headers.get("accept")||"";return i.includes("application/json")||i.includes("json")},wantsHtml(){let i=this.headers.get("accept")||"";return i.includes("text/html")||i.includes("html")},wantsXml(){let i=this.headers.get("accept")||"";return i.includes("application/xml")||i.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 Ki.test(this.headers.get("user-agent")||"")},isBot(){return Xi.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 i=this.headers.get("x-forwarded-for");if(i)return i.split(",").map((c)=>c.trim());return[rr.ip.call(this)]},userAgent(){return this.headers.get("user-agent")||""},referer(){return this.headers.get("referer")||this.headers.get("referrer")||null},bearerToken(){let i=this.headers.get("authorization");if(i&&i.startsWith("Bearer "))return i.substring(7);return null},async rawBody(){if(typeof this._rawBody==="string")return this._rawBody;try{let i=await this.clone().text();return this._rawBody=i,i}catch{return""}},basicAuth(){let i=this.headers.get("authorization");if(i&&i.startsWith("Basic "))try{let c=atob(i.substring(6)),[P,M]=c.split(":");return{username:P,password:M}}catch{return null}return null},hasHeader(i){return this.headers.has(i.toLowerCase())},header(i,c){return this.headers.get(i.toLowerCase())||c||null},allHeaders(){let i={};return this.headers.forEach((c,P)=>{i[P]=c}),i},input(i,c){if(this.validated&&i in this.validated)return this.validated[i];if(this.query&&i in this.query)return this.query[i];if(this.params&&i in this.params)return this.params[i];if(this.jsonBody&&typeof this.jsonBody==="object"&&i in this.jsonBody)return this.jsonBody[i];if(this.formBody&&typeof this.formBody==="object"&&i in this.formBody)return this.formBody[i];return c},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(i){let c=this.all(),P={};return i.forEach((M)=>{if(M in c)P[M]=c[M]}),P},except(i){let c=this.all(),P={};return Object.keys(c).forEach((M)=>{if(!i.includes(M))P[M]=c[M]}),P},has(i){let c=this.all();return i in c&&c[i]!==void 0&&c[i]!==null&&c[i]!==""},hasAny(i){return i.some((c)=>this.has(c))},missing(i){return!this.has(i)},filled(i){let c=this.input(i);if(c===null||c===void 0)return!1;if(typeof c==="string")return c.trim().length>0;if(Array.isArray(c))return c.length>0;if(typeof c==="object")return Object.keys(c).length>0;return!0},getQuery(i,c){if(!i)return this.query||{};return this.query?.[i]||c},param(i,c){return this.params?.[i]||c},cookie(i,c){let P=qt(this)[i];return P!==void 0?P:c||null},cookies(){return{...qt(this)}},file(i){return this.files?.find((c)=>c.fieldName===i)},hasFile(i){return!!this.files?.find((c)=>c.fieldName===i)},path(){return Gt(this).pathname},fullUrl(){return this.url},root(){let i=Gt(this);return`${i.protocol}//${i.host}`},is(i){let c=this.path(),P=Tr.get(i);if(!P){let M=i.replace(/\*/g,".*").replace(/\?/g,".");if(P=new RegExp(`^${M}$`),Tr.size>=1000)Tr.clear();Tr.set(i,P)}return P.test(c)},route(){return this.routeName||null},fingerprint(){let i=Gt(this),c={method:this.method,path:i.pathname,query:i.search,ip:rr.ip.call(this)};return btoa(JSON.stringify(c))},signature(i){let c=`${this.method}${this.url}${rr.ip.call(this)}${i}`,P=0;for(let M=0;M<c.length;M++){let U=c.charCodeAt(M);P=(P<<5)-P+U,P=P&P}return Math.abs(P).toString(36)},merge(i){if(!this.validated)this.validated={};Object.assign(this.validated,i)},replace(i){this.validated={...i}},age(){let i=this.startTime||Date.now();return Date.now()-i},isFromTrustedProxy(i=[]){let c=rr.ip.call(this);return i.includes(c)},contentLength(){let i=this.headers.get("content-length");return i?Number.parseInt(i,10):0},contentType(){return this.headers.get("content-type")},isContentType(i){let c=this.contentType();return c?c.includes(i):!1}};function Qi(){Object.entries(rr).forEach(([i,c])=>{$e.macro(i,c)})}Qi();function vr(i){let c=i;if(!c._parsedQuery){let P={};for(let[M,U]of Gt(i).searchParams){let z=P[M];if(z===void 0)P[M]=U;else if(Array.isArray(z))z.push(U);else P[M]=[z,U]}c._parsedQuery=P}return c._parsedQuery}class Oe{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;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(i={}){this.routes=[],this.config={...this.config,...i},this.initializeDefaultMiddleware()}initializeDefaultMiddleware(){this.namedMiddleware.set("auth",()=>async(i,c)=>{if(!i.headers.get("authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return await c()}),this.namedMiddleware.set("throttle",(i)=>{let c=i?Lt(i):{maxAttempts:60,windowMs:60000};return jt({maxAttempts:c.maxAttempts||60,windowMs:c.windowMs,keyGenerator:(P)=>P.headers.get("x-forwarded-for")||"anonymous"})}),this.namedMiddleware.set("cors",()=>async(i,c)=>{let P=await c();if(P)P.headers.set("Access-Control-Allow-Origin","*"),P.headers.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),P.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization");return P})}middlewareGroup(i,c){let P=[];for(let M of c){let[U,z]=M.split(":"),de=this.namedMiddleware.get(U);if(de)P.push(de(z))}return this.middlewareGroups.set(i,P),this}middlewareGroupRoutes(i){let c=this.middlewareGroups.get(i)||[];return new ls(this,c)}when(i){return new us(this,i)}middleware(i){let[c,P]=i.split(":"),M=this.namedMiddleware.get(c);if(!M)throw Error(`Unknown middleware: ${c}`);let U=M(P);return new cs(this,[U])}getServer(){return this.serverInstance}extend(i){for(let[c,P]of Object.entries(i))if(typeof P==="function")this[c]=P.bind(this);return this}async register(i,c){let P=async()=>{await import(i)};if(c?.prefix||c?.middleware&&c.middleware.length>0)await this.group({prefix:c.prefix,middleware:c.middleware},P);else await P();return this}invalidateCache(){this.routeCache.clear(),this._allowedMethodsCache.clear()}registerRoute(i,c,P,M,U,z){let de=c,pe=[],Re=M||"web";if(this.currentGroup){if(this.currentGroup.prefix)de=Mt(this.currentGroup.prefix,c);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)pe=[...this.currentGroup.middleware]}if(z&&z.length>0)for(let Me of z){let Pe=this.resolveMiddleware(Me);if(Pe)pe.push(Pe)}if(Re==="api"&&this.config.apiPrefix)de=Mt(this.config.apiPrefix,de);else if(Re==="web"&&this.config.webPrefix)de=Mt(this.config.webPrefix,de);let Te;if(this.currentDomain)Te=this.currentDomain;let xe={method:i.toUpperCase(),path:de,handler:P,domain:Te,params:{},middleware:pe},ve=wr(de),Ce={};if(ve.forEach((Me)=>{let Pe=Me.replace("?","");if(this.patterns.has(Pe))Ce[Pe]=this.patterns.get(Pe)}),Object.keys(Ce).length>0)xe.constraints=Ce;if(xe.pattern={exec:(Me)=>{let Pe={},Ee=xe.constraints&&!Array.isArray(xe.constraints)?xe.constraints:void 0;if(!ht(de,Me.pathname,Pe,Ee))return null;return{pathname:{groups:Pe}}}},Te){if(!this.domains[Te])this.domains[Te]=[];this.domains[Te].push(xe)}else this.routes.push(xe);if(!de.includes("{")&&!de.includes("*")){if(!this.staticRoutes.has(i.toUpperCase()))this.staticRoutes.set(i.toUpperCase(),new Map);this.staticRoutes.get(i.toUpperCase()).set(de,xe)}if(U)xe.name=U,this.namedRoutes.set(U,xe),St(U,xe.path);return this.routeCache.clear(),this}resolveMiddleware(i){if(typeof i==="function")return i;let[c,P]=i.split(":"),M=this.namedMiddleware.get(c);if(M)return M(P);return null}get(i,c,P,M,U){return this.registerRoute("GET",i,c,P,M,U)}post(i,c,P,M,U){return this.registerRoute("POST",i,c,P,M,U)}put(i,c,P,M,U){return this.registerRoute("PUT",i,c,P,M,U)}patch(i,c,P,M,U){return this.registerRoute("PATCH",i,c,P,M,U)}delete(i,c,P,M,U){return this.registerRoute("DELETE",i,c,P,M,U)}options(i,c,P,M,U){return this.registerRoute("OPTIONS",i,c,P,M,U)}match(i,c,P,M,U,z){for(let de of i)this.registerRoute(de,c,P,M,U,z);return this}any(i,c,P,M,U){for(let z of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this.registerRoute(z,i,c,P,M,U);return this}fallback(i){return this.fallbackHandler=i,this}route(i,c={}){let P=this.namedRoutes.get(i);if(!P)throw Error(`Route with name "${i}" not found`);let M=P.path;for(let[U,z]of Object.entries(c))M=M.replace(`{${U}}`,encodeURIComponent(z)),M=M.replace(`{${U}?}`,encodeURIComponent(z));return M}onError(i){return this.errorHandler=i,this}redirect(i,c=302){let P=new Headers;return P.set("Location",i),new Response(null,{status:c,headers:P})}permanentRedirect(i){return this.redirect(i,301)}redirectRoute(i,c,P=302){return this.get(i,(M)=>this.redirect(c,P)),this}async serve(i){this.invalidateCache();let c={...i,fetch:this.handleRequest.bind(this),websocket:this.wsConfig};if(this.serverInstance=Bun.serve(c),this.config.verbose){let P=this.serverInstance.port,M=this.serverInstance.hostname;console.log(`
98
+ \uD83D\uDE80 Server running at http://${M}:${P}
99
+ `)}return this.serverInstance}async handleRequest(i){try{let c=new URL(i.url);if(this.config.verbose)console.log(`${i.method} ${c.pathname}`);if(i.method==="OPTIONS"){let de=c.hostname||i.headers.get("host")?.split(":")[0]||"localhost";if(!this.matchRoute(c.pathname,"OPTIONS",de))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 P=c.hostname||i.headers.get("host")?.split(":")[0]||"localhost",M=this.matchRoute(c.pathname,i.method,P),U=this.enhanceRequest(i,M?.params||{});if(M){U.route=M.route;let de=[...this.globalMiddleware];if(M.route.middleware&&M.route.middleware.length>0)de.push(...M.route.middleware);let pe=async(Te,xe)=>await this.resolveHandler(M.route.handler,Te);de.push(pe);let Re=await this.runMiddleware(U,de);if(Re)return this.applyModifiedCookies(Re,U);return new Response("No response from middleware chain",{status:500})}let z=this.getAllowedMethods(c.pathname,P);if(z.length>0){let de=async(pe,Re)=>new Response(JSON.stringify({error:"Method Not Allowed",path:c.pathname,method:i.method,allowed:z}),{status:405,headers:{"Content-Type":"application/json",Allow:z.join(", ")}});if(this.globalMiddleware.length>0){let pe=[...this.globalMiddleware,de],Re=await this.runMiddleware(U,pe);if(Re)return this.applyModifiedCookies(Re,U)}return de(U,async()=>new Response(null))}if(this.globalMiddleware.length>0){let de=async(Te,xe)=>{if(this.fallbackHandler)return await this.resolveHandler(this.fallbackHandler,U);return new Response(JSON.stringify({error:"Not Found",path:c.pathname,method:i.method}),{status:404,headers:{"Content-Type":"application/json"}})},pe=[...this.globalMiddleware,de],Re=await this.runMiddleware(U,pe);if(Re)return this.applyModifiedCookies(Re,U)}if(this.fallbackHandler){let de=await this.resolveHandler(this.fallbackHandler,U);return this.applyModifiedCookies(de,U)}return new Response(JSON.stringify({error:"Not Found",path:c.pathname,method:i.method}),{status:404,headers:{"Content-Type":"application/json"}})}catch(c){if(console.error("Error handling request:",c),this.globalMiddleware.length>0){let P=this.enhanceRequest(i,{}),M=async(z,de)=>{if(this.errorHandler)return this.errorHandler(c);return new Response(JSON.stringify({error:"Internal Server Error",message:c instanceof Error?c.message:String(c)}),{status:500,headers:{"Content-Type":"application/json"}})},U=[...this.globalMiddleware,M];try{let z=await this.runMiddleware(P,U);if(z)return z}catch{}}if(this.errorHandler)return this.errorHandler(c);return new Response(JSON.stringify({error:"Internal Server Error",message:c instanceof Error?c.message:String(c)}),{status:500,headers:{"Content-Type":"application/json"}})}}getAllowedMethods(i,c){let P=new URL(i,"http://localhost"),M=`${c||""}:${P.pathname}`,U=this._allowedMethodsCache.get(M);if(U)return U;let z=new Set;for(let[Re,Te]of this.staticRoutes){let xe=Te.get(P.pathname);if(xe&&(!c||!xe.domain||xe.domain===c))z.add(Re)}let de=c&&this.domains[c]?this.domains[c]:this.routes;for(let Re of de){if(z.has(Re.method))continue;if(Re.path===P.pathname){z.add(Re.method);continue}if(Re.pattern&&Re.pattern.exec(P)){z.add(Re.method);continue}if(Re.path.endsWith("*")&&P.pathname.startsWith(Re.path.slice(0,-1)))z.add(Re.method)}if(z.has("GET"))z.add("HEAD");let pe=Array.from(z);if(this._allowedMethodsCache.size>=1e4)this._allowedMethodsCache.clear();return this._allowedMethodsCache.set(M,pe),pe}matchRoute(i,c,P){let M=new URL(i,"http://localhost"),U=`${P||""}:${c}:${M.pathname}`;if(this.routeCache.has(U))return this.routeCache.get(U);if(this.staticRoutes.has(c)){let Re=this.staticRoutes.get(c).get(M.pathname);if(Re&&(!P||!Re.domain||Re.domain===P)){let Te={route:Re,params:{}};return this.routeCache.set(U,Te),Te}}let de=(P&&this.domains[P]?this.domains[P]:this.routes).filter((Re)=>Re.method===c);for(let Re of de)if(Re.path===M.pathname){let Te={route:Re,params:{}};return this.routeCache.set(U,Te),Te}for(let Re of de)if(Re.pattern){let Te=Re.pattern.exec(M);if(Te){let xe={route:Re,params:Te.pathname.groups};return this.routeCache.set(U,xe),xe}}if(P&&this.domains[P]){let Re=this.domains[P].filter((Te)=>Te.method===c&&Te.path.endsWith("*"));for(let Te of Re){let xe=Te.path.slice(0,-1);if(M.pathname.startsWith(xe)){let ve={route:Te,params:{wildcard:M.pathname.slice(xe.length)}};return this.routeCache.set(U,ve),ve}}}let pe=this.routes.filter((Re)=>Re.method===c&&Re.path.endsWith("*")&&(!P||!Re.domain));for(let Re of pe){let Te=Re.path.slice(0,-1);if(M.pathname.startsWith(Te)){let xe={route:Re,params:{wildcard:M.pathname.slice(Te.length)}};return this.routeCache.set(U,xe),xe}}if(c==="HEAD")return this.matchRoute(i,"GET",P);return}enhanceRequest(i,c={}){let P=null,M=()=>{if(P===null)P={},(i.headers.get("cookie")||"").split(";").forEach((Re)=>{let Te=Re.trim().split("=");if(Te.length>=2){let xe=Te[0].trim(),ve=Te.slice(1).join("=").trim();P[xe]=decodeURIComponent(ve)}});return P},U=vr(i),z={get url(){return i.url},get method(){return i.method},get headers(){return i.headers},get body(){return i.body},get bodyUsed(){return i.bodyUsed},get cache(){return i.cache},get credentials(){return i.credentials},get destination(){return i.destination},get integrity(){return i.integrity},get keepalive(){return i.keepalive},get mode(){return i.mode},get redirect(){return i.redirect},get referrer(){return i.referrer},get referrerPolicy(){return i.referrerPolicy},get signal(){return i.signal},arrayBuffer:()=>i.arrayBuffer(),blob:()=>i.blob(),clone:()=>i.clone(),formData:()=>i.formData(),json:()=>i.json(),text:()=>i.text(),params:c,query:U,jsonBody:null,formBody:null,_cookiesToSet:[],_cookiesToDelete:[]},de=()=>{let pe={};for(let[Re,Te]of Object.entries(U))pe[Re]=Te;if(z.jsonBody&&typeof z.jsonBody==="object")for(let[Re,Te]of Object.entries(z.jsonBody))pe[Re]=Te;if(z.formBody&&typeof z.formBody==="object")for(let[Re,Te]of Object.entries(z.formBody))pe[Re]=Te;for(let[Re,Te]of Object.entries(c))pe[Re]=Te;return pe};return z.cookies=cr({read:M,write:(pe,Re,Te)=>{z._cookiesToSet.push({name:pe,value:Re,options:Te})},remove:(pe,Re)=>{z._cookiesToDelete.push({name:pe,options:Re})}}),z.get=(pe,Re)=>{let xe=de()[pe];return xe!==void 0?xe:Re},z.input=(pe,Re)=>{let xe=de()[pe];return xe!==void 0?xe:Re},z.all=()=>de(),z.only=(pe)=>{let Re=de(),Te={};for(let xe of pe)if(xe in Re)Te[xe]=Re[xe];return Te},z.except=(pe)=>{let Te={...de()};for(let xe of pe)delete Te[xe];return Te},z.has=(pe)=>{let Re=de();if(Array.isArray(pe))return pe.every((Te)=>(Te in Re)&&Re[Te]!==void 0);return pe in Re&&Re[pe]!==void 0},z.hasAny=(pe)=>{let Re=de();return pe.some((Te)=>(Te in Re)&&Re[Te]!==void 0)},z.filled=(pe)=>{let Re=de(),Te=(xe)=>{let ve=Re[xe];return ve!==void 0&&ve!==null&&ve!==""&&!(Array.isArray(ve)&&ve.length===0)};if(Array.isArray(pe))return pe.every(Te);return Te(pe)},z.missing=(pe)=>{let Re=de();if(Array.isArray(pe))return pe.every((Te)=>!(Te in Re)||Re[Te]===void 0);return!(pe in Re)||Re[pe]===void 0},z.string=(pe,Re="")=>{let xe=de()[pe];return xe!==void 0&&xe!==null?String(xe):Re},z.integer=(pe,Re=0)=>{let xe=de()[pe],ve=Number.parseInt(String(xe),10);return Number.isNaN(ve)?Re:ve},z.float=(pe,Re=0)=>{let xe=de()[pe],ve=Number.parseFloat(String(xe));return Number.isNaN(ve)?Re:ve},z.boolean=(pe,Re=!1)=>{let xe=de()[pe];if(xe===void 0||xe===null)return Re;if(typeof xe==="boolean")return xe;if(xe==="true"||xe==="1"||xe===1)return!0;if(xe==="false"||xe==="0"||xe===0)return!1;return Re},z.array=(pe)=>{let Te=de()[pe];if(Array.isArray(Te))return Te;return Te!==void 0&&Te!==null?[Te]:[]},z.bearerToken=()=>{let pe=i.headers.get("authorization")||i.headers.get("Authorization")||"";if(pe.startsWith("Bearer "))return pe.substring(7);return null},z.header=(pe)=>i.headers.get(pe)||i.headers.get(pe.toLowerCase())||null,z.cookie=(pe,Re)=>{let Te=M()[pe];return Te!==void 0?Te:Re??null},z.getParam=(pe,Re)=>{let Te=c?.[pe];return Te!==void 0?Te:Re},z.getParamAsInt=(pe)=>{let Re=c?.[pe];if(Re===void 0||Re.trim()==="")return null;let Te=Number(Re);return Number.isSafeInteger(Te)?Te:null},z.params=c||{},z}applyModifiedCookies(i,c){let P=new Response(i.body,{status:i.status,statusText:i.statusText,headers:i.headers});if(c._cookiesToSet&&c._cookiesToSet.length>0)for(let{name:M,value:U,options:z}of c._cookiesToSet){let de=this.serializeCookie(M,U,z);P.headers.append("Set-Cookie",de)}if(c._cookiesToDelete&&c._cookiesToDelete.length>0)for(let{name:M,options:U}of c._cookiesToDelete){let z={...U,expires:new Date(0),maxAge:0},de=this.serializeCookie(M,"",z);P.headers.append("Set-Cookie",de)}return P}serializeCookie(i,c,P={}){let M=`${encodeURIComponent(i)}=${encodeURIComponent(c)}`;if(P.maxAge!==void 0)M+=`; Max-Age=${P.maxAge}`;if(P.expires&&P.expires instanceof Date)M+=`; Expires=${P.expires.toUTCString()}`;if(P.path)M+=`; Path=${P.path}`;else M+="; Path=/";if(P.domain)M+=`; Domain=${P.domain}`;if(P.secure)M+="; Secure";if(P.httpOnly)M+="; HttpOnly";if(P.sameSite){let U=P.sameSite.toLowerCase();M+=`; SameSite=${U.charAt(0).toUpperCase()+U.slice(1)}`}return M}buildMiddlewareChain(i){if(i.length===0)return async(P)=>null;let c=async(P)=>null;for(let P=i.length-1;P>=0;P--){let M=i[P],U=c;c=async(z)=>M(z,async()=>await U(z)||new Response(null,{status:200}))}return c}async runMiddleware(i,c){if(c.length===0)return null;try{return await this.buildMiddlewareChain(c)(i)}catch(P){if(this.errorHandler)return this.errorHandler(P);throw P}}async resolveHandler(i,c){if(typeof i==="function"&&!i.prototype?.handle)return await i(c);if(typeof i==="function"&&i.prototype?.handle)return await new i().handle(c);if(i&&typeof i.handle==="function")return await i.handle(c);throw Error(`Invalid action handler: ${typeof i}`)}use(...i){for(let c of i){let P=this.resolveMiddleware(c);if(P)this.globalMiddleware.push(P)}return this}group(i,c){let P=this.currentGroup;if(this.currentGroup={prefix:i.prefix||"",middleware:[]},i.middleware){for(let U of i.middleware)if(typeof U==="function")this.currentGroup.middleware.push(U)}let M=c();if(M instanceof Promise)return M.then(()=>(this.currentGroup=P,this),(U)=>{throw this.currentGroup=P,U});return this.currentGroup=P,this}addRoute(i){if(this.routes.push(i),i.name)this.namedRoutes.set(i.name,i),St(i.name,i.path);return this}registerMiddlewareDependency(i){if(this._middlewarePipeline)this._middlewarePipeline.registerDependency(i);return this}registerMiddlewareSkipConditions(i,c){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(i,c,P){if(i.length===0)return P();let M=0,U=async()=>{if(M>=i.length)return P();let z=i[M++];return await z(c,U)||new Response("No response from middleware",{status:500})};return U()}}class us{router;condition;constructor(i,c){this.router=i;this.condition=c}middleware(i){let[c,P]=i.split(":"),M=this.router.namedMiddleware.get(c);if(!M)throw Error(`Unknown middleware: ${c}`);let U=M(P);return this.router.conditionalMiddleware.push({condition:this.condition,middleware:[U]}),this}}class cs{router;middleware;constructor(i,c){this.router=i;this.middleware=c}get(i,c){return this}post(i,c){return this}put(i,c){return this}delete(i,c){return this}}class ls{router;middleware;constructor(i,c){this.router=i;this.middleware=c}get(i,c){return this}post(i,c){return this}put(i,c){return this}delete(i,c){return this}}var Gr=null;function Zi(){if(Gr===null)Gr=new Oe;return Gr}function Yi(i,c={}){if(typeof i.bearerToken==="function")return i;return Zi().enhanceRequest(i,c)}if(!$e.hasMacro("getParam"))$e.macro("getParam",function(i,c){let P=this.params?.[i];return P!==void 0?P:c});if(!$e.hasMacro("getParamAsInt"))$e.macro("getParamAsInt",function(i){let c=this.params?.[i];if(c===void 0||c.trim()==="")return null;let P=Number(c);return Number.isSafeInteger(P)?P:null});if(!$e.hasMacro("get"))$e.macro("get",function(i,c){let P=Gt(this).searchParams.get(i);return P!==null&&P!==void 0?P:c});$e.macroAccessor("query",function(){return vr(this)});$e.macroAccessor("cookies",function(){let i=this,c=()=>({...qt(i)});for(let[P,M]of Object.entries(qt(i)))Object.defineProperty(c,P,{value:M,writable:!0,enumerable:!0,configurable:!0});return c.get=(P)=>qt(i)[P],c.set=(P,M,U={})=>{if(!i._cookiesToSet)i._cookiesToSet=[];i._cookiesToSet.push({name:P,value:M,options:U})},c.delete=(P,M={})=>{if(!i._cookiesToDelete)i._cookiesToDelete=[];i._cookiesToDelete.push({name:P,options:M})},c.getAll=()=>({...qt(i)}),Object.defineProperty(i,"cookies",{value:c,writable:!0,configurable:!0,enumerable:!0}),c});function ds(i){Object.defineProperties(i.prototype,{serve:{async value(c={}){if(this._initFileRoutes)await this._initFileRoutes();if(this._initApiRoutes)await this._initApiRoutes();this.invalidateCache();let P={idleTimeout:255,...c,fetch:this.handleRequest.bind(this)},M={};if(this.staticResponses&&this.staticResponses.size>0)for(let[U,z]of this.staticResponses)M[U]=z;if(c.static)Object.assign(M,c.static);if(Object.keys(M).length>0)P.static=M;if(c.development!==void 0)P.development=c.development;if(this._nativeRoutesEnabled=c.nativeRoutes===!0,this._nativeRoutesEnabled){let U=this._buildNativeRoutes();if(U)P.routes=U}if(this.wsConfig)P.websocket=this.wsConfig;if(this.serverInstance=Bun.serve(P),this.config.verbose){let U=this.serverInstance.port,z=this.serverInstance.hostname;console.log(`
100
+ \uD83D\uDE80 Server running at http://${z}:${U}
101
+ `)}return this.serverInstance},writable:!0,configurable:!0},reload:{async value(){if(!this.serverInstance)throw Error("Server not started, cannot reload");this.invalidateCache();let c=this.serverInstance.port,P=this.serverInstance.hostname;this.serverInstance.stop();let M={port:c,hostname:P,fetch:this.handleRequest.bind(this),websocket:this.wsConfig||void 0};if(this._nativeRoutesEnabled){let U=this._buildNativeRoutes();if(U)M.routes=U}if(this.serverInstance=Bun.serve(M),this.config.verbose)console.log(`\uD83D\uDD04 Server reloaded at http://${P}:${c}`)},writable:!0,configurable:!0},handleRequest:{async value(c){let P=this,M=await dr(c,()=>P.handleRequestImpl(c));return Br(M,c,P.config?.compression)},writable:!0,configurable:!0},_dispatchMatchedRoute:{async value(c,P,M){let U=this.enhanceRequest(P,M);pr(U),U.route=c;let z=c,de=this._mwEpoch||0,pe=z.middleware?z.middleware.length:0,Re=z._compiledChain;if(!Re||z._chainEpoch!==de||z._chainMwLen!==pe){let xe=Qn(z.handler,this.config);if(pe===0&&this.globalMiddleware.length===0)Re=xe;else{let ve=pe>0?[...this.globalMiddleware,...z.middleware]:[...this.globalMiddleware];ve.push((Ce,Me)=>xe(Ce)),Re=this.buildMiddlewareChain(ve)}z._compiledChain=Re,z._chainEpoch=de,z._chainMwLen=pe}let Te;try{Te=await Re(U)}catch(xe){if(this.errorHandler)Te=await this.errorHandler(xe);else throw xe}if(Te)return this.applyModifiedCookies(Te,U);return new Response("No response from middleware chain",{status:500})},writable:!0,configurable:!0},_buildNativeRoutes:{value(){let c=new Set(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),P=(pe)=>{if(pe==="*")return"/*";let Re=pe.split("/"),Te=[];for(let xe=0;xe<Re.length;xe++){let ve=Re[xe];if(ve===""){Te.push(ve);continue}if(ve==="*")return xe===Re.length-1?[...Te,"*"].join("/"):null;let Ce=ve.match(/^\{([A-Z_$][\w$]*)\}$/i);if(Ce){Te.push(`:${Ce[1]}`);continue}if(ve.includes("{")||ve.includes(":")||ve.includes("*"))return null;Te.push(ve)}return Te.join("/")},M=this,U=(pe,Re)=>(Te)=>dr(Te,async()=>{try{let xe=Te.params??{};if(Re){let ve=new URL(Te.url).pathname,Ce=pe.path==="*"?"/":pe.path.slice(0,-1);xe={...xe,wildcard:ve.slice(Ce.length)}}return await M._dispatchMatchedRoute(pe,Te,xe)}catch(xe){if(console.error("Error handling request:",xe),M.errorHandler)return M.errorHandler(xe);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:xe instanceof Error?xe.message:String(xe)}),{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"}})}}),z={},de=new Map;for(let pe of this.routes){if(!c.has(pe.method))continue;if(pe.nativeDispatch===!1)continue;if(pe.constraints&&Object.keys(pe.constraints).length>0)continue;if(pe.handler instanceof Response)continue;let Re=P(pe.path);if(!Re)continue;let Te=Re.replace(/:[^/]+/g,":p"),xe=de.get(Te);if(xe&&xe!==Re)continue;de.set(Te,Re);let ve=z[Re]??={};if(ve[pe.method])continue;ve[pe.method]=U(pe,pe.path.endsWith("*"))}for(let pe of Object.values(z))if(pe.GET&&!pe.HEAD)pe.HEAD=pe.GET;return Object.keys(z).length>0?z:null},writable:!0,configurable:!0},handleRequestImpl:{async value(c){try{let P=new URL(c.url);c._parsedURL=P;let M=P.hostname||c.headers.get("host")?.split(":")[0]||"localhost",U=this.matchRoute(P.pathname,c.method,M);if(c.method==="OPTIONS"&&!U){let Te=c.headers.get("origin"),xe={"Access-Control-Allow-Origin":Te||"*","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(Te)xe["Access-Control-Allow-Credentials"]="true",xe.Vary="Origin";return new Response(null,{status:204,headers:xe})}if(U)return await this._dispatchMatchedRoute(U.route,c,U.params);let z=this.enhanceRequest(c,{});pr(z);let de=this.getAllowedMethods(P.pathname,M),pe={"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(de.length>0){let Te=async(xe,ve)=>new Response(JSON.stringify({success:!1,message:"Method Not Allowed",path:P.pathname,method:c.method,allowed:de}),{status:405,headers:{...pe,Allow:de.join(", ")}});if(this.globalMiddleware.length>0){let xe=[...this.globalMiddleware,Te],ve=await this.runMiddleware(z,xe);if(ve)return this.applyModifiedCookies(ve,z)}return await Te(z,async()=>null)}if(this.fallbackHandler){let Te=await this.resolveHandler(this.fallbackHandler,z);return this.applyModifiedCookies(Te,z)}let Re=async(Te,xe)=>new Response(JSON.stringify({success:!1,message:"Not Found",path:P.pathname,method:c.method}),{status:404,headers:pe});if(this.globalMiddleware.length>0){let Te=[...this.globalMiddleware,Re],xe=await this.runMiddleware(z,Te);if(xe)return this.applyModifiedCookies(xe,z)}return await Re(z,async()=>null)}catch(P){if(console.error("Error handling request:",P),this.errorHandler)return this.errorHandler(P);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:P instanceof Error?P.message:String(P)}),{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(c,P={}){let M=c;if("params"in c)Object.defineProperty(M,"params",{value:P,writable:!0,configurable:!0,enumerable:!0});else M.params=P;return $e.applyMacros(M),M},writable:!0,configurable:!0},applyModifiedCookies:{value(c,P){let M=P._cookiesToSet&&P._cookiesToSet.length>0,U=P._cookiesToDelete&&P._cookiesToDelete.length>0;if(!M&&!U)return c;let z=new Response(c.body,{status:c.status,statusText:c.statusText,headers:c.headers});if(P._cookiesToSet&&P._cookiesToSet.length>0)for(let{name:de,value:pe,options:Re}of P._cookiesToSet){let Te=this.serializeCookie(de,pe,Re);z.headers.append("Set-Cookie",Te)}if(P._cookiesToDelete&&P._cookiesToDelete.length>0)for(let{name:de,options:pe}of P._cookiesToDelete){let Re={...pe,expires:new Date(0),maxAge:0},Te=this.serializeCookie(de,"",Re);z.headers.append("Set-Cookie",Te)}return z},writable:!0,configurable:!0},serializeCookie:{value(c,P,M={}){let U=`${encodeURIComponent(c)}=${encodeURIComponent(P)}`;if(M.maxAge!==void 0)U+=`; Max-Age=${M.maxAge}`;if(M.expires&&M.expires instanceof Date)U+=`; Expires=${M.expires.toUTCString()}`;if(M.path)U+=`; Path=${M.path}`;else U+="; Path=/";if(M.domain)U+=`; Domain=${M.domain}`;if(M.secure)U+="; Secure";if(M.httpOnly)U+="; HttpOnly";if(M.sameSite){let z=M.sameSite.toLowerCase();U+=`; SameSite=${z.charAt(0).toUpperCase()+z.slice(1)}`}return U},writable:!0,configurable:!0}})}import{join as eo}from"path";function ps(i){Object.defineProperties(i.prototype,{renderView:{async value(c,P={},M={}){let U=this.config.views||{viewsPath:"resources/views",extensions:[".html",".stx"],cache:Bun.env.NODE_ENV==="production",engine:"auto"},z=`${c}:${M.layout||""}`;if(U.cache&&this.templateCache.has(z))return this.processTemplate(this.templateCache.get(z),P,U);let de=await _r(c,U.viewsPath,U.extensions);if(!de)throw Error(`View '${c}' not found`);let pe=await Bun.file(de).text(),Re=M.layout||U.defaultLayout;if(Re){let Te=await _r(eo("layouts",Re),U.viewsPath,U.extensions);if(!Te)throw Error(`Layout '${Re}' not found`);pe=(await Bun.file(Te).text()).replace(/\{\{\s*content\s*\}\}/g,pe)}if(U.cache)this.templateCache.set(z,pe);return this.processTemplate(pe,P,U)},writable:!0,configurable:!0},processTemplate:{async value(c,P,M){if((M?.engine||"auto")==="custom"&&M?.customRenderer)return M.customRenderer(c,P,{});let z=Ln(c,P);if(M?.minify?.enabled)try{let de=M.minify.options||{removeComments:!0,collapseWhitespace:!0,minifyJS:!0,minifyCSS:!0};z=z.replace(/\s+/g," ").replace(/<!--[\s\S]*?-->/g,"")}catch(de){console.error("Error minifying HTML:",de)}return z},writable:!0,configurable:!0},view:{value(c,P,M={},U={},z="web",de){let pe,Re={},Te={},xe="web",ve;if(typeof P==="string"){if(pe=P,typeof M==="object"&&!Array.isArray(M))if("layout"in M||"status"in M||"headers"in M)Te=M;else Re=M;if(typeof U==="object")Te={...Te,...U};else if(typeof U==="string")xe=U;if(typeof z==="string")if(z==="web"||z==="api")xe=z;else ve=z;if(de)ve=de}else{if(Re=P,typeof M==="string")pe=M;else throw TypeError("View name must be a string");if(typeof U==="object")Te=U;else if(typeof U==="string")if(U==="web"||U==="api")xe=U;else pe=U,xe="web"}let Ce=async(Me)=>{let Pe=await this.renderView(pe,Re,{layout:Te.layout}),Ee=this.config?.queryPreservation;if(Ee?.enabled!==!1&&Ee?.preserve?.length)Pe=hr(Pe,Ee);let Ae=new Headers;if(Ae.set("Content-Type","text/html; charset=utf-8"),Te.headers)for(let[Fe,Dt]of Object.entries(Te.headers))Ae.set(Fe,Dt);return new Response(Pe,{status:Te.status||200,headers:Ae})};return this.get(c,Ce,xe,ve),this},writable:!0,configurable:!0}})}function hs(i){Object.defineProperties(i.prototype,{websocket:{value(c){return this.wsConfig=c,this},writable:!0,configurable:!0},publish:{value(c,P,M=!1){if(!this.serverInstance)throw Error("Server not started, cannot publish to WebSocket topics");return this.serverInstance.publish(c,P,M)},writable:!0,configurable:!0},subscriberCount:{value(c){if(!this.serverInstance)throw Error("Server not started, cannot get subscriber count");return this.serverInstance.subscriberCount(c)},writable:!0,configurable:!0},upgrade:{value(c,P){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(c,P)},writable:!0,configurable:!0},timeout:{value(c,P){if(!this.serverInstance)throw Error("Server not started, cannot set timeout");this.serverInstance.timeout(c,P)},writable:!0,configurable:!0},requestIP:{value(c){if(!this.serverInstance)throw Error("Server not started, cannot get request IP");return this.serverInstance.requestIP(c)},writable:!0,configurable:!0}})}import to from"process";class gs{macros=new Map;register(i,c){this.macros.set(i,{name:i,handler:c})}get(i){return this.macros.get(i)}has(i){return this.macros.has(i)}all(){return Array.from(this.macros.values())}remove(i){return this.macros.delete(i)}clear(){this.macros.clear()}}var Wr=new gs;class nr extends Response{static macro(i,c){Wr.register(i,c),Response[i]=c}static callMacro(i,...c){let P=Wr.get(i);if(!P)throw Error(`Response macro "${i}" not found`);return P.handler(...c)}static hasMacro(i){return Wr.has(i)}}function Cr(i,c){if(typeof i==="number")return{status:i,mergedHeaders:c};if(i&&typeof i==="object"){let P=typeof i.status==="number"?i.status:200,M=c;if(i.headers)if(M={},i.headers instanceof Headers)i.headers.forEach((U,z)=>{M[z]=U});else if(Array.isArray(i.headers))for(let[U,z]of i.headers)M[U]=z;else Object.assign(M,i.headers);return{status:P,mergedHeaders:M}}return{status:200,mergedHeaders:c}}var gt={success:(i,c,P=200)=>{let M={};if(i!==void 0)M.data=i;if(c!==void 0)M.message=c;return new Response(JSON.stringify(M),{status:P,headers:{"Content-Type":"application/json"}})},error:(i,c,P=400)=>{let M={error:i};if(c!==void 0)M.errors=c;return new Response(JSON.stringify(M),{status:P,headers:{"Content-Type":"application/json"}})},validationError:(i,c="Validation failed")=>gt.error(c,i,422),notFound:(i="Resource not found")=>gt.error(i,void 0,404),unauthorized:(i="Unauthorized")=>gt.error(i,void 0,401),forbidden:(i="Forbidden")=>gt.error(i,void 0,403),serverError:(i="Internal server error")=>gt.error(i,void 0,500),created:(i,c="Resource created successfully")=>gt.success(i,c,201),updated:(i,c="Resource updated successfully")=>gt.success(i,c,200),deleted:(i="Resource deleted successfully")=>gt.success(null,i,200),noContent:()=>new Response(null,{status:204}),accepted:(i,c="Request accepted")=>gt.success(i,c,202),paginated:(i,c,P)=>{let M=Math.ceil(c.total/c.per_page),U=(c.current_page-1)*c.per_page+1,z=Math.min(U+c.per_page-1,c.total),de={data:i,message:P,meta:{current_page:c.current_page,per_page:c.per_page,total:c.total,last_page:M,from:U,to:z,path:c.path,first_page_url:`${c.path}?page=1`,last_page_url:`${c.path}?page=${M}`,next_page_url:c.current_page<M?`${c.path}?page=${c.current_page+1}`:void 0,prev_page_url:c.current_page>1?`${c.path}?page=${c.current_page-1}`:void 0}};return new Response(JSON.stringify(de),{status:200,headers:{"Content-Type":"application/json"}})},json:(i,c=200,P={})=>{let{status:M,mergedHeaders:U}=Cr(c,P);return new Response(JSON.stringify(i),{status:M,headers:{"Content-Type":"application/json",...U}})},html:(i,c=200,P={})=>{let{status:M,mergedHeaders:U}=Cr(c,P);return new Response(i,{status:M,headers:{"Content-Type":"text/html",...U}})},text:(i,c=200,P={})=>{let{status:M,mergedHeaders:U}=Cr(c,P);return new Response(i,{status:M,headers:{"Content-Type":"text/plain",...U}})},xml:(i,c=200,P={})=>{let{status:M,mergedHeaders:U}=Cr(c,P);return new Response(i,{status:M,headers:{"Content-Type":"application/xml",...U}})},redirect:(i,c=302)=>new Response(null,{status:c,headers:{Location:i}}),permanentRedirect:(i)=>gt.redirect(i,301),download:(i,c,P="application/octet-stream")=>new Response(i,{status:200,headers:{"Content-Type":P,"Content-Disposition":`attachment; filename="${c}"`}}),stream:(i,c="application/octet-stream",P={})=>new Response(i,{status:200,headers:{"Content-Type":c,...P}}),cache:(i,c=3600,P=!0,M)=>{let z={"Content-Type":"application/json","Cache-Control":P?`public, max-age=${c}`:`private, max-age=${c}`};if(M)z.ETag=M;return new Response(JSON.stringify(i),{status:200,headers:z})},cors:(i,c="*",P="GET,POST,PUT,DELETE,OPTIONS",M="Content-Type,Authorization")=>new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":c,"Access-Control-Allow-Methods":P,"Access-Control-Allow-Headers":M}}),sse:(i,c,P)=>{let M="";if(P)M+=`id: ${P}
102
+ `;if(c)M+=`event: ${c}
103
+ `;return M+=`data: ${i}
104
104
 
105
- `,new Response(n,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})},health:(e="healthy",t={})=>{let r=e==="healthy"?200:e==="degraded"?200:503,n={status:e,timestamp:new Date().toISOString(),checks:t,uptime:Os.uptime?.()||0};return new Response(JSON.stringify(n),{status:r,headers:{"Content-Type":"application/json"}})}};function $s(){Object.entries(A).forEach(([e,t])=>{me.macro(e,t)})}$s();var Bs=/^[A-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[A-Z0-9](?:[A-Z0-9-]*[A-Z0-9])?(?:\.[A-Z0-9](?:[A-Z0-9-]*[A-Z0-9])?)*\.[A-Z]{2,}$/i,Ds={required:{name:"required",validate:(e)=>{if(e===null||e===void 0)return!1;if(typeof e==="string")return e.trim().length>0;if(Array.isArray(e))return e.length>0;if(typeof e==="object")return Object.keys(e).length>0;return!0},message:"The :field field is required."},string:{name:"string",validate:(e)=>typeof e==="string",message:"The :field field must be a string."},number:{name:"number",validate:(e)=>typeof e==="number"&&!Number.isNaN(e),message:"The :field field must be a number."},integer:{name:"integer",validate:(e)=>Number.isInteger(Number(e)),message:"The :field field must be an integer."},boolean:{name:"boolean",validate:(e)=>typeof e==="boolean"||e==="true"||e==="false"||e==="1"||e==="0",message:"The :field field must be true or false."},email:{name:"email",validate:(e)=>typeof e==="string"&&Bs.test(e),message:"The :field field must be a valid email address."},url:{name:"url",validate:(e)=>{try{let t=new URL(e);return Boolean(t)}catch{return!1}},message:"The :field field must be a valid URL."},min:{name:"min",validate:(e,t)=>{let r=Number(t[0]);if(typeof e==="string")return e.length>=r;if(typeof e==="number")return e>=r;if(Array.isArray(e))return e.length>=r;return!1},message:(e,t)=>`The ${e} field must be at least ${t[0]} characters.`},max:{name:"max",validate:(e,t)=>{let r=Number(t[0]);if(typeof e==="string")return e.length<=r;if(typeof e==="number")return e<=r;if(Array.isArray(e))return e.length<=r;return!1},message:(e,t)=>`The ${e} field must not exceed ${t[0]} characters.`},between:{name:"between",validate:(e,t)=>{let r=Number(t[0]),n=Number(t[1]);if(typeof e==="string")return e.length>=r&&e.length<=n;if(typeof e==="number")return e>=r&&e<=n;if(Array.isArray(e))return e.length>=r&&e.length<=n;return!1},message:(e,t)=>`The ${e} field must be between ${t[0]} and ${t[1]}.`},in:{name:"in",validate:(e,t)=>t.includes(String(e)),message:(e,t)=>`The ${e} field must be one of: ${t.join(", ")}.`},notIn:{name:"not_in",validate:(e,t)=>!t.includes(String(e)),message:(e,t)=>`The ${e} field must not be one of: ${t.join(", ")}.`},regex:{name:"regex",validate:(e,t)=>{let r=new RegExp(t[0]);return typeof e==="string"&&r.test(e)},message:"The :field field format is invalid."},alpha:{name:"alpha",validate:(e)=>typeof e==="string"&&/^[a-z]+$/i.test(e),message:"The :field field must contain only letters."},alphaNum:{name:"alpha_num",validate:(e)=>typeof e==="string"&&/^[a-z0-9]+$/i.test(e),message:"The :field field must contain only letters and numbers."},alphaDash:{name:"alpha_dash",validate:(e)=>typeof e==="string"&&/^[\w-]+$/.test(e),message:"The :field field must contain only letters, numbers, dashes, and underscores."},date:{name:"date",validate:(e)=>{let t=new Date(e);return!Number.isNaN(t.getTime())},message:"The :field field must be a valid date."},dateAfter:{name:"after",validate:(e,t)=>{let r=new Date(e),n=new Date(t[0]);return!Number.isNaN(r.getTime())&&!Number.isNaN(n.getTime())&&r>n},message:(e,t)=>`The ${e} field must be after ${t[0]}.`},dateBefore:{name:"before",validate:(e,t)=>{let r=new Date(e),n=new Date(t[0]);return!Number.isNaN(r.getTime())&&!Number.isNaN(n.getTime())&&r<n},message:(e,t)=>`The ${e} field must be before ${t[0]}.`},confirmed:{name:"confirmed",validate:(e,t,r,n)=>{let s=t[0]||`${r}_confirmation`;return e===n[s]},message:"The :field confirmation does not match."},same:{name:"same",validate:(e,t,r,n)=>e===n[t[0]],message:(e,t)=>`The ${e} field must match ${t[0]}.`},different:{name:"different",validate:(e,t,r,n)=>e!==n[t[0]],message:(e,t)=>`The ${e} field must be different from ${t[0]}.`},json:{name:"json",validate:(e)=>{try{return JSON.parse(e),!0}catch{return!1}},message:"The :field field must be valid JSON."},uuid:{name:"uuid",validate:(e)=>typeof e==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e),message:"The :field field must be a valid UUID."},array:{name:"array",validate:(e)=>Array.isArray(e),message:"The :field field must be an array."},object:{name:"object",validate:(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),message:"The :field field must be an object."}},ia={unique:{name:"unique",validate:async(e,t)=>(console.warn('Database validation rule "unique" requires external implementation'),!0),message:"The :field field must be unique."},exists:{name:"exists",validate:async(e,t)=>(console.warn('Database validation rule "exists" requires external implementation'),!0),message:"The selected :field is invalid."}};class Ie{rules={};config;constructor(e={}){this.config={stopOnFirstFailure:!1,bail:!1,...e},this.registerRules(Ds)}registerRule(e){this.rules[e.name]=e}registerRules(e){Object.values(e).forEach((t)=>this.registerRule(t))}parseRuleString(e){return e.split("|").map((t)=>{let[r,...n]=t.split(":"),s=n.length>0?n.join(":").split(","):[];return{name:r.trim(),parameters:s}})}async validate(e,t){let r={};for(let[n,s]of Object.entries(t)){let i=[],o=this.getNestedValue(e,n),a=typeof s==="string"?this.parseRuleString(s):s.map((u)=>({name:u.name,parameters:[]}));for(let{name:u,parameters:c}of a){let l=this.rules[u];if(!l){console.warn(`Validation rule "${u}" not found`);continue}try{if(!await l.validate(o,c,n,e)){let p=this.formatErrorMessage(l,n,c);if(i.push(p),this.config.stopOnFirstFailure||this.config.bail)break}}catch(d){console.error(`Error validating rule "${u}" for field "${n}":`,d),i.push(`Validation error for ${n}`)}}if(i.length>0)r[n]=i}return r}async validateOrFail(e,t){let r=await this.validate(e,t);if(Object.keys(r).length>0)throw new oe("Validation failed",r)}getNestedValue(e,t){return t.split(".").reduce((r,n)=>r&&r[n]!==void 0?r[n]:void 0,e)}formatErrorMessage(e,t,r){let n=this.config.customMessages?.[`${t}.${e.name}`]||this.config.customMessages?.[e.name];if(n)return this.replacePlaceholders(n,t,r);let s=typeof e.message==="function"?e.message(t,r):e.message;return this.replacePlaceholders(s,t,r)}replacePlaceholders(e,t,r){let n=this.config.customAttributes?.[t]||t.replace(/_/g," ");return e.replace(/:field/g,n).replace(/:attribute/g,n).replace(/:value/g,r[0]||"").replace(/:other/g,r[1]||"")}}var oa=new Ie;function _e(e,t){let r=new Ie(t);return async(n,s)=>{try{let i={...n.query,...n.params,...n.jsonBody||{},...n.formBody||{}};return await r.validateOrFail(i,e),n.validated=i,await s()}catch(i){if(i instanceof oe)throw i;throw new oe("Validation error occurred")}}}class ct{rules=[];required(){return this.rules.push("required"),this}string(){return this.rules.push("string"),this}number(){return this.rules.push("number"),this}integer(){return this.rules.push("integer"),this}boolean(){return this.rules.push("boolean"),this}email(){return this.rules.push("email"),this}url(){return this.rules.push("url"),this}min(e){return this.rules.push(`min:${e}`),this}max(e){return this.rules.push(`max:${e}`),this}between(e,t){return this.rules.push(`between:${e},${t}`),this}in(...e){return this.rules.push(`in:${e.join(",")}`),this}notIn(...e){return this.rules.push(`not_in:${e.join(",")}`),this}regex(e){return this.rules.push(`regex:${e}`),this}alpha(){return this.rules.push("alpha"),this}alphaNum(){return this.rules.push("alpha_num"),this}alphaDash(){return this.rules.push("alpha_dash"),this}date(){return this.rules.push("date"),this}after(e){return this.rules.push(`after:${e}`),this}before(e){return this.rules.push(`before:${e}`),this}confirmed(e){return this.rules.push(e?`confirmed:${e}`:"confirmed"),this}same(e){return this.rules.push(`same:${e}`),this}different(e){return this.rules.push(`different:${e}`),this}json(){return this.rules.push("json"),this}uuid(){return this.rules.push("uuid"),this}array(){return this.rules.push("array"),this}object(){return this.rules.push("object"),this}unique(e,t){return this.rules.push(t?`unique:${e},${t}`:`unique:${e}`),this}exists(e,t){return this.rules.push(t?`exists:${e},${t}`:`exists:${e}`),this}custom(e,...t){return this.rules.push(t.length>0?`${e}:${t.join(",")}`:e),this}build(){return this.rules.join("|")}}function aa(){return new ct}var ua={rules(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n instanceof ct?n.build():n;return t},async validateValue(e,t,r="value"){return(await new Ie().validate({[r]:e},{[r]:t}))[r]||[]},async passes(e,t){return(await this.validateValue(e,t)).length===0},async fails(e,t){return!await this.passes(e,t)}};class C{method;path;handler;validationRules;validatorConfig;constructor(e,t,r){this.method=e;this.path=t;this.handler=r}validate(e,t){return this.validationRules=e,this.validatorConfig=t,this}build(){let e=[];if(this.validationRules)e.push(_e(this.validationRules,this.validatorConfig));return e.push(async(t,r)=>(b.applyMacros(t),await r()||new Response("Not Found",{status:404}))),{method:this.method,path:this.path,handler:this.handler,middleware:e.length>0?e:void 0}}}class Hr{routes=[];get(e,t){return new C("GET",e,t)}post(e,t){return new C("POST",e,t)}put(e,t){return new C("PUT",e,t)}patch(e,t){return new C("PATCH",e,t)}delete(e,t){return new C("DELETE",e,t)}register(e){let t=e.build();this.routes.push(t)}getRoutes(){return this.routes}}function lt(){return async(e,t)=>(b.applyMacros(e),e.startTime=Date.now(),await t())}class Ar{rules={};config={};field(e,t){return this.rules[e]=t,this}fields(e){return Object.assign(this.rules,e),this}configure(e){return Object.assign(this.config,e),this}stopOnFirstFailure(){return this.config.stopOnFirstFailure=!0,this}messages(e){return this.config.customMessages=e,this}attributes(e){return this.config.customAttributes=e,this}build(){return _e(this.rules,this.config)}}function ha(){return new Ar}var ga={validated:(e,t,r,n,s)=>new C(e,t,r).validate(n,s),apiRoute:(e,t,r,n)=>{let s=new C(e,t,async(i)=>{if(!i.expectsJson())return me.callMacro("error","API endpoint requires JSON Accept header",void 0,406);return await r(i)});if(n)s.validate(n);return s},resourceRoute:(e,t,r)=>{let n=[];if(t.index)n.push(new C("GET",e,t.index));if(t.show)n.push(new C("GET",`${e}/{id}`,t.show));if(t.store){let s=new C("POST",e,t.store);if(r?.store)s.validate(r.store);n.push(s)}if(t.update){let s=new C("PUT",`${e}/{id}`,t.update);if(r?.update)s.validate(r.update);n.push(s)}if(t.destroy)n.push(new C("DELETE",`${e}/{id}`,t.destroy));return n}};function ma(){return new Hr}var kr={compose:(...e)=>async(t,r)=>{let n=0,s=async()=>{if(n>=e.length)return await r();let i=e[n++];return await i(t,s)};return await s()},when:(e,t)=>async(r,n)=>{if(e(r))return await t(r,n);return await n()},unless:(e,t)=>kr.when((r)=>!e(r),t),group:(e)=>kr.compose(...e)},fa={api:()=>[lt(),async(e,t)=>{try{let r=await t(),n=new Headers(r.headers);return n.set("X-API-Version","1.0"),n.set("X-Response-Time",new Date().toISOString()),new Response(r.body,{status:r.status,statusText:r.statusText,headers:n})}catch(r){return console.error(r),me.callMacro("error","Internal server error",void 0,500)}}],web:()=>[lt(),async(e,t)=>(e.session={},await t())],validation:(e,t)=>[lt(),_e(e,t)]};ur(w);cr(w);yr(w);fr(w);pr(w);Mr(w);Er(w);It(w);ar(w);Pr(w);Rr(w);mr(w);Ut(w);Bt(w);class dt{groups=new Map;globalMiddleware=[];middlewarePriority=new Map;define(e,t){return this.groups.set(e,[...t]),this}extend(e,t){let r=this.groups.get(e)||[];return this.groups.set(e,[...r,...t]),this}prepend(e,t){let r=this.groups.get(e)||[];return this.groups.set(e,[...t,...r]),this}get(e){return this.groups.get(e)||[]}has(e){return this.groups.has(e)}remove(e){return this.groups.delete(e),this}resolve(e){if(typeof e==="function")return[e];if(this.groups.has(e))return this.get(e);return[e]}resolveAll(e){let t=[];for(let r of e)t.push(...this.resolve(r));return t}pushGlobal(...e){return this.globalMiddleware.push(...e),this}prependGlobal(...e){return this.globalMiddleware.unshift(...e),this}removeGlobal(e){return this.globalMiddleware=this.globalMiddleware.filter((t)=>typeof t==="string"?t!==e:!0),this}getGlobal(){return[...this.globalMiddleware]}setPriority(e,t){return this.middlewarePriority.set(e,t),this}sortByPriority(e){return[...e].sort((t,r)=>{let n=typeof t==="string"?t.split(":")[0]:"",s=typeof r==="string"?r.split(":")[0]:"",i=this.middlewarePriority.get(n)??100,o=this.middlewarePriority.get(s)??100;return i-o})}filter(e,t){if(t.only&&t.only.length>0)return e.filter((r)=>{if(typeof r==="string"){let n=r.split(":")[0];return t.only.includes(n)}return!1});if(t.except&&t.except.length>0)return e.filter((r)=>{if(typeof r==="string"){let n=r.split(":")[0];return!t.except.includes(n)}return!0});return e}flush(){this.groups.clear(),this.globalMiddleware=[],this.middlewarePriority.clear()}}var P=new dt;P.define("web",["session","csrf","cors"]);P.define("api",["throttle:60,1","cors"]);P.setPriority("session",10);P.setPriority("cors",20);P.setPriority("csrf",30);P.setPriority("auth",40);P.setPriority("throttle",50);P.setPriority("role",60);P.setPriority("permission",60);P.setPriority("can",70);P.setPriority("abilities",70);P.setPriority("verified",80);import{mock as pt}from"bun:test";class q{request;url;constructor(e,t,r={}){if(this.url=new URL(t,"http://localhost:3000"),r.query)Object.entries(r.query).forEach(([n,s])=>{if(Array.isArray(s))s.forEach((i)=>this.url.searchParams.append(n,i));else this.url.searchParams.set(n,s)});this.request={method:e,url:this.url.toString(),headers:new Headers(r.headers||{}),params:{},query:this.parseQuery(this.url.searchParams),jsonBody:void 0,formBody:r.body&&typeof r.body==="object"?r.body:void 0,files:r.files?this.convertTestFiles(r.files):void 0,session:r.session,user:r.user,context:r.context||{},requestId:`test-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ip:()=>"127.0.0.1",userAgent:()=>"BunRouter-TestClient/1.0",cookies:X(r.cookies||{}),startTime:Date.now(),traceId:`trace-${Date.now()}`,spanId:`span-${Date.now()}`},this.handleBody(r.body)}parseQuery(e){let t={};for(let[r,n]of e.entries())if(t[r])if(Array.isArray(t[r]))t[r].push(n);else t[r]=[t[r],n];else t[r]=n;return t}convertTestFiles(e){return e.map((t)=>({fieldName:t.fieldName,originalName:t.filename,filename:`test-${Date.now()}-${t.filename}`,path:`/tmp/test-uploads/${t.filename}`,size:t.content instanceof ArrayBuffer?t.content.byteLength:new TextEncoder().encode(t.content.toString()).length,mimetype:t.mimetype||"application/octet-stream",buffer:t.content instanceof ArrayBuffer?t.content:new TextEncoder().encode(t.content.toString()).buffer}))}handleBody(e){if(!e)return;let t=this.request.headers?.get("content-type")||"";if(t.includes("application/json")||typeof e==="object"){if(this.request.jsonBody=e,!this.request.headers?.has("content-type"))this.request.headers?.set("content-type","application/json")}else if(t.includes("application/x-www-form-urlencoded"))this.request.formBody=e}params(e){return this.request.params={...this.request.params,...e},this}headers(e){return Object.entries(e).forEach(([t,r])=>{this.request.headers?.set(t,r)}),this}auth(e,t="Bearer"){return this.request.headers?.set("Authorization",`${t} ${e}`),this}user(e){return this.request.user=e,this}session(e){return this.request.session=e,this}cookies(e){let t=this.request.cookies?.getAll()||{};return this.request.cookies=X({...t,...e}),this}context(e){return this.request.context={...this.request.context,...e},this}json(e){return this.request.jsonBody=e,this.request.headers?.set("content-type","application/json"),this}form(e){return this.request.formBody=e,this.request.headers?.set("content-type","application/x-www-form-urlencoded"),this}files(e){return this.request.files=this.convertTestFiles(e),this.request.headers?.set("content-type","multipart/form-data"),this}ip(e){return this.request.ip=()=>e,this}userAgent(e){return this.request.userAgent=()=>e,this.request.headers?.set("User-Agent",e),this}csrf(e){return this.request.csrfToken=e,this.request.headers?.set("X-CSRF-Token",e),this}build(){let e={method:this.request.method,headers:this.request.headers};if(this.request.jsonBody)e.body=JSON.stringify(this.request.jsonBody);else if(this.request.formBody){let n=new FormData;Object.entries(this.request.formBody).forEach(([s,i])=>{n.append(s,i)}),e.body=n}let t=new Request(this.url.toString(),e);return Object.assign(t,{params:this.request.params||{},query:this.request.query||{},jsonBody:this.request.jsonBody,formBody:this.request.formBody,files:this.request.files,session:this.request.session,user:this.request.user,context:this.request.context||{},requestId:this.request.requestId,ip:this.request.ip,userAgent:this.request.userAgent,cookies:this.request.cookies||{},startTime:this.request.startTime,traceId:this.request.traceId,spanId:this.request.spanId})}}var za={get:(e,t)=>new q("GET",e,t),post:(e,t)=>new q("POST",e,t),put:(e,t)=>new q("PUT",e,t),patch:(e,t)=>new q("PATCH",e,t),delete:(e,t)=>new q("DELETE",e,t),options:(e,t)=>new q("OPTIONS",e,t),head:(e,t)=>new q("HEAD",e,t)};function T(e="GET",t="/",r={}){return new q(e,t,r).build()}class fe{request;constructor(e){this.request=e||T()}as(e){return this.request.user=e,this}withJWT(e,t="Bearer"){let r=new Headers(this.request.headers);return r.set("Authorization",`${t} ${e}`),this.request={...this.request,headers:r},this}withSession(e){return this.request.session=e,this}withApiKey(e,t="X-API-Key"){let r=new Headers(this.request.headers);return r.set(t,e),this.request={...this.request,headers:r},this}withBasicAuth(e,t){let r=btoa(`${e}:${t}`),n=new Headers(this.request.headers);return n.set("Authorization",`Basic ${r}`),this.request={...this.request,headers:n},this}withAuthCookies(e){let t=this.request.cookies?.getAll()||{};return this.request.cookies=X({...t,...e}),this}unauthenticated(){if(this.request.user=void 0,this.request.session=void 0,this.request.headers)this.request.headers.delete("Authorization");return this}getRequest(){return this.request}}class ht{options;constructor(e={}){this.options={secret:"test-secret",expiresIn:"1h",algorithm:"HS256",...e}}generateToken(e={}){let t={alg:this.options.algorithm,typ:"JWT",...this.options.headers},r=Math.floor(Date.now()/1000),n=r+this.parseExpiresIn(this.options.expiresIn||"1h"),s={iat:r,exp:n,...this.options.payload,...e},i=btoa(JSON.stringify(t)).replace(/=/g,""),o=btoa(JSON.stringify(s)).replace(/=/g,""),a=btoa(`${i}.${o}.${this.options.secret}`).replace(/=/g,"");return`${i}.${o}.${a}`}generateExpiredToken(e={}){let t={alg:this.options.algorithm,typ:"JWT"},r=Math.floor(Date.now()/1000),n={iat:r-7200,exp:r-3600,...e},s=btoa(JSON.stringify(t)).replace(/=/g,""),i=btoa(JSON.stringify(n)).replace(/=/g,""),o=btoa(`${s}.${i}.${this.options.secret}`).replace(/=/g,"");return`${s}.${i}.${o}`}generateInvalidToken(){return"invalid.jwt.token"}decodeToken(e){let[t,r,n]=e.split(".");return{header:JSON.parse(atob(t)),payload:JSON.parse(atob(r)),signature:n}}parseExpiresIn(e){let t=e.match(/^(\d+)([smhd])$/);if(!t)return 3600;let r=Number.parseInt(t[1]);switch(t[2]){case"s":return r;case"m":return r*60;case"h":return r*3600;case"d":return r*86400;default:return 3600}}}class gt{options;constructor(e={}){this.options={sessionId:`test-session-${Date.now()}`,maxAge:3600000,secure:!1,httpOnly:!0,...e}}createSession(e={}){let t={...this.options.data,...e},r=this.generateSessionCookie();return{sessionId:this.options.sessionId,data:t,cookie:r}}generateSessionCookie(e="session"){let t=[];if(this.options.maxAge)t.push(`Max-Age=${Math.floor(this.options.maxAge/1000)}`);if(this.options.secure)t.push("Secure");if(this.options.httpOnly)t.push("HttpOnly");let r=t.length>0?`; ${t.join("; ")}`:"";return`${e}=${this.options.sessionId}${r}`}createExpiredSession(){let e={...this.options,maxAge:-1};return new gt(e).createSession()}}var Ka={user:(e={})=>({id:1,email:"test@example.com",username:"testuser",roles:["user"],permissions:["read"],...e}),adminUser:(e={})=>({id:1,email:"admin@example.com",username:"admin",roles:["admin"],permissions:["read","write","delete"],...e}),guestUser:()=>({id:0,email:"guest@example.com",username:"guest",roles:["guest"],permissions:[]}),authMiddleware:(e)=>pt(async(t,r)=>{if(e)return t.user=e,await r();return new Response("Unauthorized",{status:401})}),roleMiddleware:(e)=>pt(async(t,r)=>{if(!t.user)return new Response("Unauthorized",{status:401});let n=t.user.roles||[];if(!e.some((i)=>n.includes(i)))return new Response("Forbidden",{status:403});return await r()}),permissionMiddleware:(e)=>pt(async(t,r)=>{if(!t.user)return new Response("Unauthorized",{status:401});let n=t.user.permissions||[];if(!e.every((i)=>n.includes(i)))return new Response("Forbidden",{status:403});return await r()})},Xa={authenticatedRequest:(e,t)=>new fe(t).as(e).getRequest(),jwtRequest:(e={},t)=>{let n=new ht().generateToken(e);return new fe(t).withJWT(n).getRequest()},sessionRequest:(e={},t)=>new fe(t).withSession(e).getRequest(),verifyJWTStructure:(e)=>{let t=e.split(".");return t.length===3&&t.every((r)=>r.length>0)},extractJWTPayload:(e)=>{try{let[,t]=e.split(".");return JSON.parse(atob(t))}catch{return null}}};function Qa(e){return new fe(e)}function Za(e){return new ht(e)}function Ya(e){return new gt(e)}import{mock as z}from"bun:test";class _{request;files;constructor(e){this.request=e||T(),this.files=[]}addFile(e){let t={fieldName:e.fieldName,originalName:e.filename,filename:`test-${Date.now()}-${e.filename}`,path:`/tmp/test-uploads/${e.filename}`,size:e.content instanceof ArrayBuffer?e.content.byteLength:new TextEncoder().encode(e.content.toString()).length,mimetype:e.mimetype||this.detectMimeType(e.filename),buffer:e.content instanceof ArrayBuffer?e.content:new TextEncoder().encode(e.content.toString()).buffer};return this.files.push(t),this.request.files=[...this.request.files||[],t],this}addFiles(e){return e.forEach((t)=>this.addFile(t)),this}addImage(e,t="test.jpg",r=1024){let n=new ArrayBuffer(r);return this.addFile({fieldName:e,filename:t,content:n,mimetype:"image/jpeg"})}addDocument(e,t="test.pdf",r="Test PDF content"){return this.addFile({fieldName:e,filename:t,content:r,mimetype:"application/pdf"})}addTextFile(e,t="test.txt",r="Test content"){return this.addFile({fieldName:e,filename:t,content:r,mimetype:"text/plain"})}addLargeFile(e,t=10){let r=t*1024*1024,n=new ArrayBuffer(r);return this.addFile({fieldName:e,filename:`large-file-${t}mb.bin`,content:n,mimetype:"application/octet-stream"})}addInvalidFile(e,t="malicious.exe"){return this.addFile({fieldName:e,filename:t,content:"Potentially malicious content",mimetype:"application/x-executable"})}withFormData(e){return this.request.formBody={...this.request.formBody,...e},this}getRequest(){return this.request}getFiles(){return this.files}clearFiles(){return this.files=[],this.request.files=[],this}detectMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json",xml:"application/xml",zip:"application/zip",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}[t||""]||"application/octet-stream"}}class mt{static testFileSize(e,t){return e.size<=t}static testFileType(e,t){return t.includes(e.mimetype)}static testFileExtension(e,t){let r=e.originalName.split(".").pop()?.toLowerCase();return r?t.includes(r):!1}static testFilename(e){let t=e.originalName;if(t.includes("..")||t.includes("/")||t.includes("\\"))return!1;if(t.includes("\x00"))return!1;let r=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],n=t.split(".")[0].toUpperCase();if(r.includes(n))return!1;return!0}static testImageFile(e){return["image/jpeg","image/png","image/gif","image/webp","image/svg+xml"].includes(e.mimetype)}static testDocumentFile(e){return["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/csv"].includes(e.mimetype)}}var nu={validationMiddleware:(e={})=>z(async(r,n)=>{let s=r.files||[],{maxSize:i=5242880,allowedTypes:o=[],maxFiles:a=10}=e;if(s.length>a)return new Response(`Too many files. Maximum ${a} allowed.`,{status:400});for(let u of s){if(u.size>i)return new Response(`File ${u.originalName} is too large. Maximum size: ${i} bytes.`,{status:400});if(o.length>0&&!o.includes(u.mimetype))return new Response(`File type ${u.mimetype} not allowed.`,{status:400});if(!mt.testFilename(u))return new Response(`Invalid filename: ${u.originalName}`,{status:400})}return await n()}),imageUploadMiddleware:(e={})=>z(async(r,n)=>{let s=r.files||[],{maxSize:i=2097152}=e;for(let o of s){if(!mt.testImageFile(o))return new Response(`File ${o.originalName} is not a valid image.`,{status:400});if(o.size>i)return new Response(`Image ${o.originalName} is too large.`,{status:400})}return await n()}),storageService:{store:z(async(e,t)=>t||`/uploads/${Date.now()}-${e.filename}`),delete:z(async(e)=>{}),exists:z(async(e)=>!e.includes("not-found")),getUrl:z((e)=>`https://example.com/storage${e}`)},virusScanner:{scan:z(async(e)=>{if(e.originalName.endsWith(".exe")||e.mimetype==="application/x-executable")return{clean:!1,threat:"Potentially malicious executable"};return{clean:!0}})}},su={singleFileUpload:()=>new _().addImage("avatar","profile.jpg").withFormData({description:"Profile picture"}),multipleFileUpload:()=>new _().addImage("images","photo1.jpg").addImage("images","photo2.png").addDocument("documents","report.pdf").withFormData({album:"vacation"}),fileSizeExceeded:()=>new _().addLargeFile("file",50),invalidFileType:()=>new _().addInvalidFile("file","virus.exe"),emptyFileUpload:()=>new _().addFile({fieldName:"file",filename:"empty.txt",content:"",mimetype:"text/plain"}),maliciousFilename:()=>new _().addFile({fieldName:"file",filename:"../../../etc/passwd",content:"malicious content",mimetype:"text/plain"})},iu={hasFiles:(e,t)=>{let r=e.files||[];if(t!==void 0&&r.length!==t)throw Error(`Expected ${t} files, but got ${r.length}`);if(r.length===0)throw Error("Expected request to have files")},hasFileWithField:(e,t)=>{if(!(e.files||[]).some((s)=>s.fieldName===t))throw Error(`Expected file with field name '${t}'`)},fileMatches:(e,t)=>{Object.entries(t).forEach(([r,n])=>{if(e[r]!==n)throw Error(`Expected file.${r} to be '${n}', got '${e[r]}'`)})},fileSizeWithinLimit:(e,t)=>{if(e.size>t)throw Error(`File size ${e.size} exceeds limit of ${t}`)},fileTypeAllowed:(e,t)=>{if(!t.includes(e.mimetype))throw Error(`File type '${e.mimetype}' is not allowed. Allowed types: ${t.join(", ")}`)}};function ou(e){return new _(e)}var au={image:(e="image",t="test.jpg")=>({fieldName:e,filename:t,content:new ArrayBuffer(1024),mimetype:"image/jpeg"}),document:(e="document",t="test.pdf")=>({fieldName:e,filename:t,content:"PDF content",mimetype:"application/pdf"}),text:(e="file",t="test.txt",r="Test content")=>({fieldName:e,filename:t,content:r,mimetype:"text/plain"}),large:(e="file",t=10)=>({fieldName:e,filename:`large-${t}mb.bin`,content:new ArrayBuffer(t*1024*1024),mimetype:"application/octet-stream"}),malicious:(e="file")=>({fieldName:e,filename:"../../../malicious.exe",content:"malicious content",mimetype:"application/x-executable"})};import{mock as v,spyOn as Fs}from"bun:test";class qr{middleware;context;constructor(e){this.middleware=e,this.context=this.createContext()}createContext(){let e=T(),t=v(()=>Promise.resolve(new Response("Next called",{status:200})));return{request:e,next:t}}withRequest(e){return this.context.request=e,this}withNext(e){return this.context.next=v(e),this}withError(e){return this.context.error=e,this}async execute(){try{return await this.middleware(this.context.request,this.context.next)}catch(e){throw this.context.error=e,e}}expectNextCalled(e=1){if(this.context.next.mock.calls.length!==e)throw Error(`Expected next to be called ${e} times, but was called ${this.context.next.mock.calls.length} times`);return this}expectNextNotCalled(){if(this.context.next.mock.calls.length>0)throw Error(`Expected next not to be called, but was called ${this.context.next.mock.calls.length} times`);return this}expectError(e){if(!this.context.error)throw Error("Expected middleware to throw an error, but no error was thrown");if(e&&this.context.error.message!==e)throw Error(`Expected error message "${e}", but got "${this.context.error.message}"`);return this}getContext(){return this.context}reset(){return this.context=this.createContext(),this}}function du(e){return new qr(e)}var pu={passthrough:()=>v(async(e,t)=>await t()),response:(e=200,t)=>v(async()=>new Response(t?JSON.stringify(t):null,{status:e})),error:(e="Middleware error")=>v(async()=>{throw Error(e)}),modifyRequest:(e)=>v(async(t,r)=>(e(t),await r())),addContext:(e,t)=>v(async(r,n)=>(r.context=r.context||{},r.context[e]=t,await n())),auth:(e)=>v(async(t,r)=>{if(e)return t.user=e,await r();else return new Response("Unauthorized",{status:401})}),rateLimit:(e=!1)=>v(async(t,r)=>{if(e)return new Response("Too Many Requests",{status:429});return await r()}),cors:(e="*")=>v(async(t,r)=>{let n=await r();if(n)n.headers.set("Access-Control-Allow-Origin",e);return n})};class Or{middlewares;request;finalHandler;constructor(e){this.middlewares=e,this.request=T(),this.finalHandler=v(async()=>new Response("Final handler",{status:200}))}withRequest(e){return this.request=e,this}withFinalHandler(e){return this.finalHandler=v(e),this}async execute(){let e=0,t=async()=>{if(e<this.middlewares.length){let r=this.middlewares[e++];return await r(this.request,t)}else return await this.finalHandler()};return await t()}getExecutionOrder(){return this.middlewares.map((e,t)=>t)}}function hu(e){return new Or(e)}function gu(e){return Fs(e,"call")}function mu(){let e=v(async(t,r)=>await r());return{middleware:e,spy:e}}async function fu(e,t=1000){let r=[],n=T(),s=v(async()=>new Response("OK"));for(let c=0;c<t;c++){let l=performance.now();await e(n,s);let d=performance.now();r.push(d-l)}let i=r.reduce((c,l)=>c+l,0),o=i/t,a=Math.min(...r),u=Math.max(...r);return{averageTime:o,minTime:a,maxTime:u,totalTime:i}}import{mock as N}from"bun:test";class Ns{id;attributes;constructor(e={}){this.id=e.id,this.attributes=e}static modelName="GenericMockModel";static async find(e){return null}static async findOrFail(e){throw Error("Not implemented")}static async where(e){return[]}static async create(e){throw Error("Not implemented")}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}}class Us{id;email;name;constructor(e={id:1}){this.id=e.id,this.email=e.email||"test@example.com",this.name=e.name||"Test User"}static async find(e){return null}static async findOrFail(e){throw Error("Not implemented")}toJSON(){return{id:this.id,email:this.email,name:this.name}}}class Is{id;title;content;userId;constructor(e={id:1}){this.id=e.id,this.title=e.title||"Test Post",this.content=e.content||"Test content",this.userId=e.userId||1}static async find(e){return null}static async findOrFail(e){throw Error("Not implemented")}async belongsTo(e){return!1}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}class $r{request;options;constructor(e={}){this.options=e,this.request=T()}withRequest(e){return this.request=e,this}withParams(e){return this.request.params={...this.request.params,...e},this}withModel(e){return this.options.modelClass=e,this}withRouteKey(e){return this.options.routeKey=e,this}withConstraints(e){return this.options.constraints=e,this}withResolver(e){return this.options.customResolver=e,this}async testResolution(e){if(this.options.customResolver)return await this.options.customResolver(e);if(this.options.modelClass)return new this.options.modelClass({id:e});return{id:e}}async testNotFound(e){try{throw await this.testResolution(e),Error("Expected model not found error")}catch(t){if(t instanceof Error&&t.message!=="Model not found")throw t}}getRequest(){return this.request}}var bu={createModel:(e,t={})=>class r{id;attributes;constructor(n={}){this.id=n.id,this.attributes={...t,...n}}static modelName=e;static async find(n){if(n==="not-found")return null;return new r({id:n,...t})}static async findOrFail(n){let s=await this.find(n);if(!s)throw Error("Model not found");return s}static async where(n){return[new r({id:1,...t,...n})]}static async create(n){return new r({id:Date.now(),...n})}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}},User:class e{id;email;name;constructor(t={id:1}){this.id=t.id,this.email=t.email||"test@example.com",this.name=t.name||"Test User"}static async find(t){if(t==="not-found")return null;return new e({id:Number.parseInt(t)})}static async findOrFail(t){let r=await this.find(t);if(!r)throw Error("User not found");return r}toJSON(){return{id:this.id,email:this.email,name:this.name}}},Post:class e{id;title;content;userId;constructor(t={id:1}){this.id=t.id,this.title=t.title||"Test Post",this.content=t.content||"Test content",this.userId=t.userId||1}static async find(t){if(t==="not-found")return null;return new e({id:Number.parseInt(t)})}static async findOrFail(t){let r=await this.find(t);if(!r)throw Error("Post not found");return r}async belongsTo(t){return this.userId===t}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}},Tu={belongsTo:(e="userId")=>N(async(r,n)=>{if(!n.user)return!1;return r[e]===n.user.id}),belongsToUser:()=>N(async(t,r)=>{if(!r.user)return!1;return t.userId===r.user.id}),published:()=>N(async(t)=>t.published===!0||t.status==="published"),visible:()=>N(async(t)=>t.visible!==!1&&t.hidden!==!0),custom:(e)=>N(e),combine:(...e)=>N(async(r,n)=>{for(let s of e)if(!await s(r,n))return!1;return!0})};class Br{resolvers=new Map;register(e,t){return this.resolvers.set(e,N(t)),this}registerModel(e,t){let r=N(async(n)=>{if(t.find){let s=await t.find(n);if(!s)throw Error(`${t.name||"Model"} not found`);return s}return new t({id:n})});return this.resolvers.set(e,r),this}async resolve(e,t){let r=this.resolvers.get(e);if(!r)throw Error(`No resolver registered for key: ${e}`);return await r(t)}async testAll(e="1"){let t={};for(let[r,n]of this.resolvers)try{t[r]=await n(e)}catch(s){t[r]={error:s instanceof Error?s.message:"Unknown error"}}return t}getKeys(){return Array.from(this.resolvers.keys())}clear(){return this.resolvers.clear(),this}}var xu={testRoute:async(e,t,r)=>{let n=T("GET",e);n.params=t;for(let[s,i]of Object.entries(r))n.context=n.context||{},n.context[s]=i;return n},createHandler:(e)=>N(async(r)=>{let n=r.context||{};for(let s of e)if(!n[s])return new Response(`Model ${s} not found`,{status:404});return new Response(JSON.stringify({params:r.params,models:Object.fromEntries(e.map((s)=>[s,n[s]]))}),{headers:{"Content-Type":"application/json"}})}),testBindingMiddleware:(e)=>N(async(r,n)=>{r.context=r.context||{};for(let[s,i]of Object.entries(e)){let o=r.params[s];if(o)try{if(typeof i==="function")r.context[s]=await i(o);else r.context[s]=i}catch(a){return console.error(`Error resolving model ${s}:`,a),new Response(`${s} not found`,{status:404})}}return await n()})};function vu(e){return new $r(e)}function Cu(){return new Br}var _s=async(e,t)=>e.userId===t.id,Pu={testUserScoped:async(e,t,r=_s)=>await r(e,t),testRoleAccess:async(e,t,r)=>{if(!t.roles)return!1;return r.some((n)=>t.roles.includes(n))},testPermissionAccess:async(e,t,r)=>{if(!t.permissions)return!1;return r.every((n)=>t.permissions.includes(n))}};import{mock as js}from"bun:test";import G from"process";class Fr{metrics=[];startTime=0;endTime=0;start(){return this.startTime=performance.now(),this}end(){return this.endTime=performance.now(),this}recordMetric(e){return this.metrics.push(e),this}getElapsedTime(){return this.endTime-this.startTime}getMetrics(){return[...this.metrics]}getAverageResponseTime(){if(this.metrics.length===0)return 0;return this.metrics.reduce((t,r)=>t+r.responseTime,0)/this.metrics.length}getMemoryStats(){if(this.metrics.length===0)return{averageHeapUsed:0,maxHeapUsed:0,averageRSS:0,maxRSS:0};let e=this.metrics.map((r)=>r.memoryUsage.heapUsed),t=this.metrics.map((r)=>r.memoryUsage.rss);return{averageHeapUsed:e.reduce((r,n)=>r+n,0)/e.length,maxHeapUsed:Math.max(...e),averageRSS:t.reduce((r,n)=>r+n,0)/t.length,maxRSS:Math.max(...t)}}clear(){return this.metrics=[],this.startTime=0,this.endTime=0,this}}class ne{client;config;constructor(e,t){this.client=e,this.config=t}async run(e,t="GET",r={}){let n={totalRequests:0,successfulRequests:0,failedRequests:0,averageResponseTime:0,requestsPerSecond:0,errors:[]},s=[],i=new Map,o=Date.now(),a=this.config.maxRequests||Math.floor(this.config.duration/1000*(this.config.requestsPerSecond||this.config.concurrency)),u=[];for(let d=0;d<a;d++){let p=this.makeRequest(e,t,r).then((g)=>{s.push(g),n.successfulRequests++}).catch((g)=>{let h=g instanceof Error?g.message:"Unknown error";i.set(h,(i.get(h)||0)+1),n.failedRequests++});if(u.push(p),this.config.requestsPerSecond){let g=1000/this.config.requestsPerSecond;await new Promise((h)=>setTimeout(h,g))}if(u.length>=this.config.concurrency)await Promise.race(u),u.filter((h)=>h.then(()=>!0).catch(()=>!0)).forEach((h)=>{let m=u.indexOf(h);if(m>-1)u.splice(m,1)})}await Promise.allSettled(u);let l=(Date.now()-o)/1000;return n.totalRequests=a,n.averageResponseTime=s.length>0?s.reduce((d,p)=>d+p,0)/s.length:0,n.requestsPerSecond=a/l,n.errors=Array.from(i.entries()).map(([d,p])=>({error:d,count:p})),n}async makeRequest(e,t,r){let n=performance.now();try{return await this.client.request(t,e,r),performance.now()-n}catch(s){let i=performance.now();throw s}}}var Hu={routeHandler:async(e,t=1000)=>{let r=[],n=T();for(let c=0;c<t;c++){let l=performance.now();await e(n);let d=performance.now();r.push(d-l)}let s=r.reduce((c,l)=>c+l,0),i=s/t,o=Math.min(...r),a=Math.max(...r),u=t/s*1000;return{averageTime:i,minTime:o,maxTime:a,totalTime:s,throughput:u}},middleware:async(e,t=1000)=>{let r=[],n=T(),s=js(async()=>new Response("OK"));for(let c=0;c<t;c++){let l=performance.now();await e(n,s);let d=performance.now();r.push(d-l)}let i=r.reduce((c,l)=>c+l,0),o=i/t,a=Math.min(...r),u=Math.max(...r);return{averageTime:o,minTime:a,maxTime:u,totalTime:i}},jsonSerialization:async(e,t=1e4)=>{let r=[];for(let u=0;u<t;u++){let c=performance.now(),l=JSON.stringify(e),d=performance.now();r.push(d-c)}let n=r.reduce((u,c)=>u+c,0),s=n/t,i=Math.min(...r),o=Math.max(...r),a=JSON.stringify(e).length;return{averageTime:s,minTime:i,maxTime:o,totalTime:n,dataSize:a}},routeMatching:async(e,t,r=1000)=>{let n=[],s=0;for(let l=0;l<r;l++){let d=t[l%t.length],p=performance.now();if(e.find((m)=>{let y=m.path.replace(/:\w+/g,"[^/]+");return new RegExp(`^${y}$`).test(d)}))s++;let h=performance.now();n.push(h-p)}let i=n.reduce((l,d)=>l+d,0),o=i/r,a=Math.min(...n),u=Math.max(...n),c=s/r;return{averageTime:o,minTime:a,maxTime:u,totalTime:i,matchRate:c}}},Au={measureMemoryUsage:async(e,t=100)=>{let r=[],n=[];if(globalThis.gc)globalThis.gc();let s=G.memoryUsage().heapUsed;for(let c=0;c<t;c++){let l=await e();r.push(l);let d=G.memoryUsage();if(n.push(d.heapUsed),c%10===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let i=G.memoryUsage().heapUsed,o=n.reduce((c,l)=>c+l,0)/n.length,a=Math.max(...n),u=i-s>1048576;return{averageHeapUsed:o,maxHeapUsed:a,memoryLeakDetected:u,results:r}},testRouteHandlerMemoryLeaks:async(e,t=1000)=>{if(globalThis.gc)globalThis.gc();let r=G.memoryUsage().heapUsed;for(let o=0;o<t;o++){let a=T();if(await e(a),o%100===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let n=G.memoryUsage().heapUsed,s=n-r;return{memoryLeakDetected:s>5242880,initialMemory:r,finalMemory:n,memoryGrowth:s}}},qu={rampUpTest:async(e,t,r)=>{let n=[],s=10,i=r.testDuration/10,o=(r.endConcurrency-r.startConcurrency)/10;for(let a=0;a<10;a++){let u=Math.round(r.startConcurrency+o*a),l=await new ne(e,{duration:i,concurrency:u,requestsPerSecond:u*2}).run(t);n.push({concurrency:u,requestsPerSecond:l.requestsPerSecond,averageResponseTime:l.averageResponseTime,errorRate:l.failedRequests/l.totalRequests})}return n},spikeTest:async(e,t,r)=>{let s=await new ne(e,{duration:30000,concurrency:r.normalLoad}).run(t),o=await new ne(e,{duration:r.spikeDuration,concurrency:r.spikeLoad}).run(t),u=await new ne(e,{duration:30000,concurrency:r.normalLoad}).run(t);return{normalPhase:s,spikePhase:o,recoveryPhase:u}}},Ou={responseTimeWithin:(e,t)=>{if(e>t)throw Error(`Response time ${e}ms exceeds maximum ${t}ms`)},throughputAtLeast:(e,t)=>{if(e<t)throw Error(`Throughput ${e} RPS is below minimum ${t} RPS`)},errorRateBelow:(e,t)=>{if(e>t)throw Error(`Error rate ${(e*100).toFixed(2)}% exceeds maximum ${(t*100).toFixed(2)}%`)},memoryUsageWithin:(e,t)=>{if(e>t)throw Error(`Memory usage ${(e/1024/1024).toFixed(2)}MB exceeds maximum ${(t/1024/1024).toFixed(2)}MB`)},noMemoryLeaks:(e,t=5242880)=>{if(e>t)throw Error(`Potential memory leak detected: ${(e/1024/1024).toFixed(2)}MB growth`)}};function $u(){return new Fr}function Bu(e,t){return new ne(e,t)}var Dr={getCurrentMemoryUsage:()=>{let e=G.memoryUsage();return{heapUsed:e.heapUsed,heapTotal:e.heapTotal,external:e.external,rss:e.rss}},getCPUUsage:()=>{let e=G.cpuUsage();return{user:e.user,system:e.system}},createMetricSnapshot:(e)=>({responseTime:e,memoryUsage:Dr.getCurrentMemoryUsage(),cpuUsage:Dr.getCPUUsage()}),formatResults:(e)=>JSON.stringify(e,null,2)};class ft{status;statusText;headers;body;text;json;cookies;redirected;url;ok;type;originalResponse;constructor(e,t){this.originalResponse=e,this.status=e.status,this.statusText=e.statusText,this.headers=this.parseHeaders(e.headers),this.cookies=this.parseCookies(e.headers.get("set-cookie")),this.redirected=e.redirected,this.url=e.url,this.ok=e.ok,this.type=e.type,this.body=t,this.text=typeof t==="string"?t:JSON.stringify(t);try{this.json=typeof t==="string"?JSON.parse(t):t}catch{this.json=null}}parseHeaders(e){let t={};return e.forEach((r,n)=>{t[n.toLowerCase()]=r}),t}parseCookies(e){if(!e)return{};let t={};return e.split(",").forEach((r)=>{let[n]=r.trim().split(";"),[s,i]=n.split("=");if(s&&i)t[s.trim()]=i.trim()}),t}expectStatus(e){if(this.status!==e)throw Error(`Expected status ${e}, got ${this.status}`);return this}expectSuccess(){if(!this.ok)throw Error(`Expected successful response, got ${this.status}`);return this}expectHeader(e,t){let r=this.headers[e.toLowerCase()];if(r===void 0)throw Error(`Expected header '${e}' to be present`);if(t!==void 0&&r!==t)throw Error(`Expected header '${e}' to be '${t}', got '${r}'`);return this}expectBody(e){if(typeof e==="string"){if(this.text!==e)throw Error(`Expected body '${e}', got '${this.text}'`)}else if(JSON.stringify(this.json)!==JSON.stringify(e))throw Error(`Expected body ${JSON.stringify(e)}, got ${JSON.stringify(this.json)}`);return this}expectJson(e){if(JSON.stringify(this.json)!==JSON.stringify(e))throw Error(`Expected JSON ${JSON.stringify(e)}, got ${JSON.stringify(this.json)}`);return this}expectJsonContains(e){if(typeof this.json!=="object"||this.json===null)throw Error("Response is not a JSON object");return Object.entries(e).forEach(([t,r])=>{let n=this.json[t];if(typeof r==="object"&&r!==null&&typeof n==="object"&&n!==null){let s=JSON.stringify(r),i=JSON.stringify(n);if(s!==i)throw Error(`Expected JSON property '${t}' to be ${s}, got ${i}`)}else if(n!==r)throw Error(`Expected JSON property '${t}' to be '${r}', got '${n}'`)}),this}expectCookie(e,t){let r=this.cookies[e];if(r===void 0)throw Error(`Expected cookie '${e}' to be present`);if(t!==void 0&&r!==t)throw Error(`Expected cookie '${e}' to be '${t}', got '${r}'`);return this}expectRedirect(e){if(this.status<300||this.status>=400)throw Error(`Expected redirect status (3xx), got ${this.status}`);if(e){let t=this.headers.location;if(t!==e)throw Error(`Expected redirect to '${e}', got '${t}'`)}return this}expectValidationError(e,t){if(this.status!==422)throw Error(`Expected validation error status (422), got ${this.status}`);if(e){let r=this.json?.errors||this.json?.message;if(!r||!r[e])throw Error(`Expected validation error for field '${e}'`);if(t){if(!(Array.isArray(r[e])?r[e]:[r[e]]).includes(t))throw Error(`Expected validation error message '${t}' for field '${e}'`)}}return this}expectContentType(e){let t=this.headers["content-type"];if(!t||!t.includes(e))throw Error(`Expected content type '${e}', got '${t}'`);return this}expectBodyContains(e){if(!this.text.includes(e))throw Error(`Expected body to contain '${e}'`);return this}expectBodyMatches(e){if(!e.test(this.text))throw Error(`Expected body to match pattern ${e}`);return this}expectJsonStructure(e){return this.validateStructure(this.json,e,"root"),this}validateStructure(e,t,r){if(t&&typeof t==="object"&&t.$$typeof)return;if(Array.isArray(t)){if(!Array.isArray(e))throw TypeError(`Expected ${r} to be an array`);if(t.length>0&&e.length>0)this.validateStructure(e[0],t[0],`${r}[0]`)}else if(typeof t==="object"&&t!==null){if(typeof e!=="object"||e===null)throw Error(`Expected ${r} to be an object`);Object.keys(t).forEach((n)=>{if(!(n in e))throw Error(`Expected ${r} to have property '${n}'`);this.validateStructure(e[n],t[n],`${r}.${n}`)})}}getOriginalResponse(){return this.originalResponse}toJSON(){return{status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,json:this.json,cookies:this.cookies,redirected:this.redirected,url:this.url,ok:this.ok,type:this.type}}}async function Nr(e){let t=await e.text();return new ft(e,t)}function Fu(e=200,t,r){let n=new Headers(r);if(t&&typeof t==="object"&&!n.has("content-type"))n.set("content-type","application/json");let s=new Response(t?typeof t==="string"?t:JSON.stringify(t):null,{status:e,headers:n});return new ft(s,t)}class Le{router;config;defaultHeaders;constructor(e,t={}){this.router=e,this.config={baseUrl:"http://localhost:3000",timeout:5000,followRedirects:!0,validateStatus:(r)=>r>=200&&r<300,...t},this.defaultHeaders=t.defaultHeaders||{}}async get(e,t={}){return this.request("GET",e,t)}async post(e,t={}){return this.request("POST",e,t)}async put(e,t={}){return this.request("PUT",e,t)}async patch(e,t={}){return this.request("PATCH",e,t)}async delete(e,t={}){return this.request("DELETE",e,t)}async options(e,t={}){return this.request("OPTIONS",e,t)}async head(e,t={}){return this.request("HEAD",e,t)}async request(e,t,r={}){let n={...this.defaultHeaders,...r.headers},s={...r,headers:n},i=new q(e,t,s).build();try{let o=await this.handleRequest(i);return await Nr(o)}catch(o){throw Error(`Test request failed: ${o instanceof Error?o.message:"Unknown error"}`)}}async handleRequest(e){let t=new URL(e.url),r=this.findMatchingRoute(e.method,t.pathname);if(!r)return new Response("Not Found",{status:404});let{route:n,params:s}=r;e.params={...e.params,...s};try{return await this.executeMiddlewareChain(e,n)||new Response("No response",{status:500})}catch(i){return new Response(JSON.stringify({error:i instanceof Error?i.message:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}findMatchingRoute(e,t){for(let r of this.router.routes){if(r.method.toLowerCase()!==e.toLowerCase())continue;let n=this.matchPath(r.path,t);if(n!==null)return{route:r,params:n}}return null}matchPath(e,t){let r=e.split("/"),n=t.split("/");if(r.length!==n.length)return null;let s={};for(let i=0;i<r.length;i++){let o=r[i],a=n[i];if(o.startsWith(":")){let u=o.slice(1);s[u]=a}else if(o!==a)return null}return s}async executeMiddlewareChain(e,t){let r=[...this.router.globalMiddleware,...t.middleware],n=0,s=async()=>{if(n<r.length){let o=r[n++];return await o(e,s)}else return await this.executeHandler(t.handler,e)};return await s()||new Response("No response",{status:500})}async executeHandler(e,t){if(typeof e==="function")return await e(t);else if(typeof e==="string")throw TypeError(`String handlers not supported in test environment: ${e}`);else if(typeof e==="object"&&e.handle)return await new e().handle(t);throw Error("Invalid handler type")}setDefaultHeaders(e){return this.defaultHeaders={...this.defaultHeaders,...e},this}auth(e,t="Bearer"){return this.defaultHeaders.Authorization=`${t} ${e}`,this}userAgent(e){return this.defaultHeaders["User-Agent"]=e,this}withConfig(e){return new Le(this.router,{...this.config,...e})}withHeaders(e){return new Le(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...e}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function je(e,t){return new Le(e,t)}var _u={for:(e,t)=>je(e,t),withConfig:(e)=>(t)=>je(t,e),withAuth:(e,t="Bearer")=>(r)=>je(r).auth(e,t),withHeaders:(e)=>(t)=>je(t).withHeaders(e)};import{mock as W}from"bun:test";class O{messages=[];isConnected=!1;readyState=0;eventHandlers=new Map;constructor(){this.setupEventHandlers()}setupEventHandlers(){this.eventHandlers.set("open",[]),this.eventHandlers.set("message",[]),this.eventHandlers.set("close",[]),this.eventHandlers.set("error",[])}connect(){return this.isConnected=!0,this.readyState=1,this.emit("open",{type:"open"}),this}disconnect(e=1000,t="Normal closure"){return this.isConnected=!1,this.readyState=3,this.emit("close",{type:"close",code:e,reason:t}),this}send(e){if(!this.isConnected)throw Error("WebSocket is not connected");let t={type:typeof e==="string"?"text":"binary",data:e,timestamp:Date.now()};return this.messages.push(t),this}receive(e){if(!this.isConnected)throw Error("WebSocket is not connected");let t={type:typeof e==="string"?"text":"binary",data:e,timestamp:Date.now()};return this.emit("message",{type:"message",data:e}),this}ping(e){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("ping",{type:"ping",data:e}),this}pong(e){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("pong",{type:"pong",data:e}),this}on(e,t){if(!this.eventHandlers.has(e))this.eventHandlers.set(e,[]);return this.eventHandlers.get(e).push(t),this}off(e,t){let r=this.eventHandlers.get(e);if(r){let n=r.indexOf(t);if(n>-1)r.splice(n,1)}return this}emit(e,t){(this.eventHandlers.get(e)||[]).forEach((n)=>n(t))}getSentMessages(){return[...this.messages]}getMessagesByType(e){return this.messages.filter((t)=>t.type===e)}clearMessages(){return this.messages=[],this}getState(){return{isConnected:this.isConnected,readyState:this.readyState}}getTestClient(){return{send:(e)=>this.send(e),close:(e,t)=>this.disconnect(e,t),ping:(e)=>this.ping(e),pong:(e)=>this.pong(e),messages:this.getSentMessages(),isConnected:this.isConnected,readyState:this.readyState}}}class Ur{tester;_data;constructor(e={}){this.tester=new O,this._data=e}send(e){this.tester.send(e)}close(e,t){this.tester.disconnect(e,t)}ping(e){this.tester.ping(e)}pong(e){this.tester.pong(e)}publish(e,t){this.tester.send(t)}subscribe(e){}unsubscribe(e){}isSubscribed(e){return!0}cork(e){e()}get readyState(){return this.tester.getState().readyState}get data(){return this._data}set data(e){this._data=e}getTester(){return this.tester}}var zu={onOpen:()=>W(async(e)=>{}),onMessage:(e)=>W(async(t,r)=>{if(e)t.send(e)}),onClose:()=>W(async(e,t,r)=>{}),onError:()=>W(async(e,t)=>{}),echo:()=>W(async(e,t)=>{e.send(t)}),broadcast:(e)=>W(async(t,r)=>{e.forEach((n)=>{if(n!==t&&n.readyState===1)n.send(r)})}),chatRoom:(e)=>W(async(t,r)=>{t.publish(e,r)})},Gu={basicConnection:()=>new O().connect().send("Hello WebSocket").receive("Hello Client"),connectionFailure:()=>{let e=new O;return e.on("error",()=>{}),e},messageBroadcast:(e=3)=>{let t=Array.from({length:e},()=>new O().connect());return t[0].send("Broadcast message"),t.slice(1).forEach((r)=>r.receive("Broadcast message")),t},pingPong:()=>new O().connect().ping().pong(),connectionTimeout:()=>{let e=new O;return setTimeout(()=>{e.disconnect(1006,"Connection timeout")},100),e}},Wu={isConnected:(e)=>{if(!e.getState().isConnected)throw Error("Expected WebSocket to be connected")},isDisconnected:(e)=>{if(e.getState().isConnected)throw Error("Expected WebSocket to be disconnected")},messageSent:(e,t)=>{if(!e.getSentMessages().some((s)=>{if(typeof t==="string"&&typeof s.data==="string")return s.data===t;return s.data===t}))throw Error("Expected message not found in sent messages")},messageCount:(e,t)=>{let r=e.getSentMessages();if(r.length!==t)throw Error(`Expected ${t} messages, but got ${r.length}`)},messageType:(e,t,r)=>{let n=e.getSentMessages();if(t>=n.length)throw Error(`Message at index ${t} does not exist`);if(n[t].type!==r)throw Error(`Expected message type '${r}', got '${n[t].type}'`)},readyState:(e,t)=>{let r=e.getState();if(r.readyState!==t)throw Error(`Expected ready state ${t}, got ${r.readyState}`)}},Vu={testThroughput:async(e=1000,t=1024)=>{let r=new O().connect(),n="x".repeat(t),s=performance.now();for(let c=0;c<e;c++)r.send(n);let o=performance.now()-s,a=e/o*1000,u=o/e;return{messagesPerSecond:a,totalTime:o,averageLatency:u}},testConcurrentConnections:async(e=100)=>{let t={successfulConnections:0,failedConnections:0,averageConnectionTime:0},r=[],n=Array.from({length:e},async()=>{let s=performance.now();try{new O().connect();let o=performance.now();r.push(o-s),t.successfulConnections++}catch(i){console.error("WebSocket connection failed:",i),t.failedConnections++}});return await Promise.all(n),t.averageConnectionTime=r.length>0?r.reduce((s,i)=>s+i,0)/r.length:0,t}};function Ju(){return new O}function Ku(e){return new Ur(e)}var Xu={createClients:(e)=>Array.from({length:e},()=>new O().connect()),withLatency:(e,t)=>{let r=e.send.bind(e);return e.send=(n)=>(setTimeout(()=>r(n),t),e),e},withPacketLoss:(e,t)=>{let r=e.send.bind(e);return e.send=(n)=>{if(Math.random()>t)r(n);return e},e},*messageGenerator(e,t="Message"){for(let r=1;r<=e;r++)yield`${t} ${r}`}};class Rt extends Error{status;response;body;constructor(e,t){let r=typeof t?.message==="string"?t.message:e.statusText||"Request failed";super(`${e.status} ${r}`);this.name="TypedClientError",this.status=e.status,this.response=e,this.body=t}}function Ir(e,t){if(!t)return e;let r=e;for(let[n,s]of Object.entries(t)){let i=encodeURIComponent(s);r=r.split(`{${n}}`).join(i),r=r.replace(new RegExp(`:${n}(?![A-Z0-9_])`,"gi"),i)}return r}function _r(e,t){if(!t)return e;let r=new URLSearchParams;for(let[s,i]of Object.entries(t))if(i!==void 0&&i!==null)r.append(s,String(i));let n=r.toString();if(!n)return e;return e.includes("?")?`${e}&${n}`:`${e}?${n}`}async function Ls(e){if(e.status===204||e.headers.get("content-length")==="0")return;if((e.headers.get("content-type")??"").includes("json"))try{return await e.json()}catch{return}return await e.text()}function zs(e){let t=e.baseUrl.replace(/\/+$/,""),r=e.fetch??globalThis.fetch;async function n(){if(typeof e.headers==="function")return await e.headers();return e.headers??{}}async function s(i,o,a,u,c){let l=_r(`${t}${Ir(o,c?.params)}`,c?.query),d={accept:"application/json",...await n(),...c?.headers};if(u&&d["content-type"]===void 0&&d["Content-Type"]===void 0)d["content-type"]="application/json";let p=await r(l,{method:i,headers:d,...u?{body:JSON.stringify(a)}:{},...e.credentials?{credentials:e.credentials}:{},...c?.signal?{signal:c.signal}:{}}),g=await Ls(p);if(!p.ok){let h=new Rt(p,g);if(e.onError)return e.onError(h);throw h}return g}return{get:(i,o)=>s("GET",i,void 0,!1,o),post:(i,o,a)=>s("POST",i,o,!0,a),put:(i,o,a)=>s("PUT",i,o,!0,a),patch:(i,o,a)=>s("PATCH",i,o,!0,a),delete:(i,o)=>s("DELETE",i,void 0,!1,o),async raw(i,o,a){let{params:u,query:c,...l}=a??{},d=_r(`${t}${Ir(o,u)}`,c);return await r(d,{method:i,...l,headers:{...await n(),...l.headers},...e.credentials?{credentials:e.credentials}:{}})}}}function Gs(e){return e}var Ws=["get","post","put","patch","delete"];function Vs(e,t,r,n){if(!n)return;let s=e,i=(o)=>{let a=s?.[o];if(typeof a!=="function")throw TypeError(`[typed-router] ${t.toUpperCase()} ${r}: this router's route does not support .${String(o)}(), so the \`${String(o)}\` option cannot be applied. Register the route directly instead of dropping it.`);return a};if(n.middleware)i("middleware").call(s,n.middleware);if(n.name)i("name").call(s,n.name);if(n.skipCsrf)i("skipCsrf").call(s);if(n.requireCsrf)i("requireCsrf").call(s);if(n.rateLimit)i("rateLimit").call(s,n.rateLimit.max,n.rateLimit.window??"minute")}function Js(e){let t={};for(let r of Ws)t[r]=(n,s,i)=>(Vs(e[r](n,s),r,n,i),t);return t}export{wt as ApiKeyManager,Kr as Auth,fe as AuthTester,Xs as BindingBuilder,Ds as BuiltInRules,Wi as CacheInvalidation,Ks as Container,ml as ContentSecurityPolicy,ti as ContextualContainer,Kc as Cors,Xc as Csrf,Rl as DDoSProtection,Hn as DEFAULT_COMPRESSION,ia as DatabaseRules,ll as DatabaseSessionStore,ri as DefaultServiceProviderManager,Dn as Dependencies,ce as DomainGroup,Qt as DomainGroupBuilder,k as DomainMatcher,fa as EnhancementPresets,ei as EnvironmentManager,Pt as Errors,wl as FileSecurity,ul as FileSessionStore,bl as FileUpload,_ as FileUploadTester,mt as FileValidationTester,f as FluentRouteBuilder,de as FluentRouter,Ns as GenericMockModel,Ml as Helmet,rl as InMemoryNonceStore,El as InputValidation,yt as JWT,ht as JWTTester,Qc as JsonBody,ne as LoadTester,al as MemorySessionStore,Or as MiddlewareChainTester,Fn as MiddlewareFactory,dt as MiddlewareGroupRegistry,kr as MiddlewareHelpers,Ye as MiddlewarePipeline,qr as MiddlewareTester,Is as MockPostClass,Ur as MockServerWebSocket,Us as MockUserClass,$r as ModelBindingTester,Br as ModelResolverTester,bt as OAuth2Helper,kl as PerformanceAlerting,Al as PerformanceDashboard,Ol as PerformanceMonitor,Fr as PerformanceTester,Zc as RateLimit,Kt as RateLimitRegistry,Ki as RateLimitUtils,Oe as RateLimiter,cl as RedisSessionStore,el as RequestId,nl as RequestSigning,Bl as RequestTracer,kt as ResponseBuilder,C as RouteBuilder,Jt as RouteCacheFactory,Gt as RouteCacheKeyGenerator,Wt as RouteCacheManager,Ts as RouteFactory,Zt as RouteGroupBuilder,ga as RouteHelpers,w as Router,xs as RouterUtils,Fl as Security,Ul as SecuritySuite,gl as Session,pl as SessionManager,gt as SessionTester,tl as SignatureError,Bn as SkipConditions,Yi as SubdomainPatterns,tt as SubdomainRouter,Zi as SubdomainUtils,Le as TestClient,q as TestRequestBuilder,ft as TestResponseWrapper,cs as ThrottleFactory,Rt as TypedClientError,Hr as ValidationFluentRouter,ua as ValidationHelpers,Ar as ValidationMiddlewareBuilder,ct as ValidationRuleBuilder,Ie as Validator,O as WebSocketTester,Vc as apiKeyAuth,Ze as appendVary,As as applyRequestEnhancements,Wl as auth,Xa as authHelpers,Ka as authMocks,zc as basicAuth,Gc as bearerAuth,fu as benchmarkMiddleware,Hu as benchmarkTests,Oi as buildUrlWithPreservedParams,ps as clearNamedRoutes,St as compressResponse,Ic as config,Tu as constraintHelpers,fl as contentSecurityPolicy,_l as cors,Qa as createAuthTester,Ys as createContainer,Ce as createCookieAccessor,lt as createEnhancementMiddleware,ou as createFileUploadTester,ma as createFluentRouter,Ms as createHandlerResolver,X as createInMemoryCookieAccessor,Za as createJWTTester,Bu as createLoadTester,mu as createMiddlewareSpy,T as createMockRequest,Fu as createMockResponse,Ku as createMockServerWebSocket,vu as createModelBindingTester,Cu as createModelResolverTester,ao as createPathRegex,$u as createPerformanceTester,Y as createRateLimitMiddleware,Vt as createRouteCacheMiddleware,dl as createSessionStore,Ya as createSessionTester,Qi as createSubdomainMiddleware,je as createTestClient,Nr as createTestResponse,zs as createTypedClient,Js as createTypedRouter,_e as createValidationMiddleware,Ju as createWebSocketTester,Gl as csrf,yl as ddosProtection,K as decodeParam,Nc as defaultConfig,qi as defaultQueryPreservationConfig,Gs as defineEndpoint,Pl as documentUpload,Sn as enableRequestContext,Lc as extractApiKey,_c as extractBasicAuth,jc as extractBearerToken,$e as extractParamNames,rr as fileExists,Tl as fileUpload,iu as fileUploadAssertions,nu as fileUploadMocks,su as fileUploadScenarios,Jn as generateQueryPreservationScript,hl as generateSessionId,Uc as getConfig,Qs as getContainer,Mt as getCurrentRequest,rt as getNamedRoutePath,ds as getNamedRoutes,Nn as globalMiddlewarePipeline,oa as globalValidator,Cl as imageUpload,Se as injectQueryPreservationScript,Sl as inputValidation,gs as isActionClass,Et as isCompressible,oo as isRouteHandler,F as joinPaths,jl as jsonBody,Wc as jwtAuth,H as matchPath,Au as memoryTests,Vl as middleware,P as middlewareGroups,pu as mockMiddleware,bu as modelMocks,vl as multipleFileUpload,An as negotiateEncoding,le as normalizePath,Jc as oauth2Auth,ee as parseThrottleString,On as peekBody,Hl as performanceAlerting,Ou as performanceAssertions,ql as performanceDashboard,$l as performanceMonitor,Dr as performanceUtils,nr as processHtmlTemplate,Yc as rateLimit,Xt as rateLimitRegistry,U as registerNamedRoute,kn as request,Ll as requestId,sl as requestSigning,Dl as requestTracer,pe as resolveHandler,nt as resolveViewPath,R as response,Pi as responseBuilder,Z as routeCacheManager,xu as routeModelHelpers,vs as router,aa as rule,Me as runWithRequest,Pu as scopedBindingHelpers,Nl as security,Il as securitySuite,zl as session,Zs as setContainer,Ee as setCurrentRequest,qn as shouldCompress,il as signRequest,xl as singleFileUpload,gu as spyOnMiddleware,qu as stressTests,_u as testClient,au as testFiles,du as testMiddleware,hu as testMiddlewareChain,za as testRequest,io as toActionPath,hs as url,ha as validate,uo as validatePath,ol as verifySignature,E as wrapResponse,Wu as wsAssertions,zu as wsHandlerMocks,Vu as wsPerformance,Gu as wsTestScenarios,Xu as wsTestUtils};
105
+ `,new Response(M,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})},health:(i="healthy",c={})=>{let P=i==="healthy"?200:i==="degraded"?200:503,M={status:i,timestamp:new Date().toISOString(),checks:c,uptime:to.uptime?.()||0};return new Response(JSON.stringify(M),{status:P,headers:{"Content-Type":"application/json"}})}};function ro(){Object.entries(gt).forEach(([i,c])=>{nr.macro(i,c)})}ro();var no=/^[A-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[A-Z0-9](?:[A-Z0-9-]*[A-Z0-9])?(?:\.[A-Z0-9](?:[A-Z0-9-]*[A-Z0-9])?)*\.[A-Z]{2,}$/i,so={required:{name:"required",validate:(i)=>{if(i===null||i===void 0)return!1;if(typeof i==="string")return i.trim().length>0;if(Array.isArray(i))return i.length>0;if(typeof i==="object")return Object.keys(i).length>0;return!0},message:"The :field field is required."},string:{name:"string",validate:(i)=>typeof i==="string",message:"The :field field must be a string."},number:{name:"number",validate:(i)=>typeof i==="number"&&!Number.isNaN(i),message:"The :field field must be a number."},integer:{name:"integer",validate:(i)=>Number.isInteger(Number(i)),message:"The :field field must be an integer."},boolean:{name:"boolean",validate:(i)=>typeof i==="boolean"||i==="true"||i==="false"||i==="1"||i==="0",message:"The :field field must be true or false."},email:{name:"email",validate:(i)=>typeof i==="string"&&no.test(i),message:"The :field field must be a valid email address."},url:{name:"url",validate:(i)=>{try{let c=new URL(i);return Boolean(c)}catch{return!1}},message:"The :field field must be a valid URL."},min:{name:"min",validate:(i,c)=>{let P=Number(c[0]);if(typeof i==="string")return i.length>=P;if(typeof i==="number")return i>=P;if(Array.isArray(i))return i.length>=P;return!1},message:(i,c)=>`The ${i} field must be at least ${c[0]} characters.`},max:{name:"max",validate:(i,c)=>{let P=Number(c[0]);if(typeof i==="string")return i.length<=P;if(typeof i==="number")return i<=P;if(Array.isArray(i))return i.length<=P;return!1},message:(i,c)=>`The ${i} field must not exceed ${c[0]} characters.`},between:{name:"between",validate:(i,c)=>{let P=Number(c[0]),M=Number(c[1]);if(typeof i==="string")return i.length>=P&&i.length<=M;if(typeof i==="number")return i>=P&&i<=M;if(Array.isArray(i))return i.length>=P&&i.length<=M;return!1},message:(i,c)=>`The ${i} field must be between ${c[0]} and ${c[1]}.`},in:{name:"in",validate:(i,c)=>c.includes(String(i)),message:(i,c)=>`The ${i} field must be one of: ${c.join(", ")}.`},notIn:{name:"not_in",validate:(i,c)=>!c.includes(String(i)),message:(i,c)=>`The ${i} field must not be one of: ${c.join(", ")}.`},regex:{name:"regex",validate:(i,c)=>{let P=new RegExp(c[0]);return typeof i==="string"&&P.test(i)},message:"The :field field format is invalid."},alpha:{name:"alpha",validate:(i)=>typeof i==="string"&&/^[a-z]+$/i.test(i),message:"The :field field must contain only letters."},alphaNum:{name:"alpha_num",validate:(i)=>typeof i==="string"&&/^[a-z0-9]+$/i.test(i),message:"The :field field must contain only letters and numbers."},alphaDash:{name:"alpha_dash",validate:(i)=>typeof i==="string"&&/^[\w-]+$/.test(i),message:"The :field field must contain only letters, numbers, dashes, and underscores."},date:{name:"date",validate:(i)=>{let c=new Date(i);return!Number.isNaN(c.getTime())},message:"The :field field must be a valid date."},dateAfter:{name:"after",validate:(i,c)=>{let P=new Date(i),M=new Date(c[0]);return!Number.isNaN(P.getTime())&&!Number.isNaN(M.getTime())&&P>M},message:(i,c)=>`The ${i} field must be after ${c[0]}.`},dateBefore:{name:"before",validate:(i,c)=>{let P=new Date(i),M=new Date(c[0]);return!Number.isNaN(P.getTime())&&!Number.isNaN(M.getTime())&&P<M},message:(i,c)=>`The ${i} field must be before ${c[0]}.`},confirmed:{name:"confirmed",validate:(i,c,P,M)=>{let U=c[0]||`${P}_confirmation`;return i===M[U]},message:"The :field confirmation does not match."},same:{name:"same",validate:(i,c,P,M)=>i===M[c[0]],message:(i,c)=>`The ${i} field must match ${c[0]}.`},different:{name:"different",validate:(i,c,P,M)=>i!==M[c[0]],message:(i,c)=>`The ${i} field must be different from ${c[0]}.`},json:{name:"json",validate:(i)=>{try{return JSON.parse(i),!0}catch{return!1}},message:"The :field field must be valid JSON."},uuid:{name:"uuid",validate:(i)=>typeof i==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(i),message:"The :field field must be a valid UUID."},array:{name:"array",validate:(i)=>Array.isArray(i),message:"The :field field must be an array."},object:{name:"object",validate:(i)=>typeof i==="object"&&i!==null&&!Array.isArray(i),message:"The :field field must be an object."}},Tu={unique:{name:"unique",validate:async(i,c)=>(console.warn('Database validation rule "unique" requires external implementation'),!0),message:"The :field field must be unique."},exists:{name:"exists",validate:async(i,c)=>(console.warn('Database validation rule "exists" requires external implementation'),!0),message:"The selected :field is invalid."}};class Pr{rules={};config;constructor(i={}){this.config={stopOnFirstFailure:!1,bail:!1,...i},this.registerRules(so)}registerRule(i){this.rules[i.name]=i}registerRules(i){Object.values(i).forEach((c)=>this.registerRule(c))}parseRuleString(i){return i.split("|").map((c)=>{let[P,...M]=c.split(":"),U=M.length>0?M.join(":").split(","):[];return{name:P.trim(),parameters:U}})}async validate(i,c){let P={};for(let[M,U]of Object.entries(c)){let z=[],de=this.getNestedValue(i,M),pe=typeof U==="string"?this.parseRuleString(U):U.map((Re)=>({name:Re.name,parameters:[]}));for(let{name:Re,parameters:Te}of pe){let xe=this.rules[Re];if(!xe){console.warn(`Validation rule "${Re}" not found`);continue}try{if(!await xe.validate(de,Te,M,i)){let Ce=this.formatErrorMessage(xe,M,Te);if(z.push(Ce),this.config.stopOnFirstFailure||this.config.bail)break}}catch(ve){console.error(`Error validating rule "${Re}" for field "${M}":`,ve),z.push(`Validation error for ${M}`)}}if(z.length>0)P[M]=z}return P}async validateOrFail(i,c){let P=await this.validate(i,c);if(Object.keys(P).length>0)throw new u("Validation failed",P)}getNestedValue(i,c){return c.split(".").reduce((P,M)=>P&&P[M]!==void 0?P[M]:void 0,i)}formatErrorMessage(i,c,P){let M=this.config.customMessages?.[`${c}.${i.name}`]||this.config.customMessages?.[i.name];if(M)return this.replacePlaceholders(M,c,P);let U=typeof i.message==="function"?i.message(c,P):i.message;return this.replacePlaceholders(U,c,P)}replacePlaceholders(i,c,P){let M=this.config.customAttributes?.[c]||c.replace(/_/g," ");return i.replace(/:field/g,M).replace(/:attribute/g,M).replace(/:value/g,P[0]||"").replace(/:other/g,P[1]||"")}}var xu=new Pr;function Mr(i,c){let P=new Pr(c);return async(M,U)=>{try{let z={...M.query,...M.params,...M.jsonBody||{},...M.formBody||{}};return await P.validateOrFail(z,i),M.validated=z,await U()}catch(z){if(z instanceof u)throw z;throw new u("Validation error occurred")}}}class Vr{rules=[];required(){return this.rules.push("required"),this}string(){return this.rules.push("string"),this}number(){return this.rules.push("number"),this}integer(){return this.rules.push("integer"),this}boolean(){return this.rules.push("boolean"),this}email(){return this.rules.push("email"),this}url(){return this.rules.push("url"),this}min(i){return this.rules.push(`min:${i}`),this}max(i){return this.rules.push(`max:${i}`),this}between(i,c){return this.rules.push(`between:${i},${c}`),this}in(...i){return this.rules.push(`in:${i.join(",")}`),this}notIn(...i){return this.rules.push(`not_in:${i.join(",")}`),this}regex(i){return this.rules.push(`regex:${i}`),this}alpha(){return this.rules.push("alpha"),this}alphaNum(){return this.rules.push("alpha_num"),this}alphaDash(){return this.rules.push("alpha_dash"),this}date(){return this.rules.push("date"),this}after(i){return this.rules.push(`after:${i}`),this}before(i){return this.rules.push(`before:${i}`),this}confirmed(i){return this.rules.push(i?`confirmed:${i}`:"confirmed"),this}same(i){return this.rules.push(`same:${i}`),this}different(i){return this.rules.push(`different:${i}`),this}json(){return this.rules.push("json"),this}uuid(){return this.rules.push("uuid"),this}array(){return this.rules.push("array"),this}object(){return this.rules.push("object"),this}unique(i,c){return this.rules.push(c?`unique:${i},${c}`:`unique:${i}`),this}exists(i,c){return this.rules.push(c?`exists:${i},${c}`:`exists:${i}`),this}custom(i,...c){return this.rules.push(c.length>0?`${i}:${c.join(",")}`:i),this}build(){return this.rules.join("|")}}function vu(){return new Vr}var Cu={rules(i){let c={};for(let[P,M]of Object.entries(i))c[P]=M instanceof Vr?M.build():M;return c},async validateValue(i,c,P="value"){return(await new Pr().validate({[P]:i},{[P]:c}))[P]||[]},async passes(i,c){return(await this.validateValue(i,c)).length===0},async fails(i,c){return!await this.passes(i,c)}};class at{method;path;handler;validationRules;validatorConfig;constructor(i,c,P){this.method=i;this.path=c;this.handler=P}validate(i,c){return this.validationRules=i,this.validatorConfig=c,this}build(){let i=[];if(this.validationRules)i.push(Mr(this.validationRules,this.validatorConfig));return i.push(async(c,P)=>($e.applyMacros(c),await P()||new Response("Not Found",{status:404}))),{method:this.method,path:this.path,handler:this.handler,middleware:i.length>0?i:void 0}}}class fs{routes=[];get(i,c){return new at("GET",i,c)}post(i,c){return new at("POST",i,c)}put(i,c){return new at("PUT",i,c)}patch(i,c){return new at("PATCH",i,c)}delete(i,c){return new at("DELETE",i,c)}register(i){let c=i.build();this.routes.push(c)}getRoutes(){return this.routes}}function Jr(){return async(i,c)=>($e.applyMacros(i),i.startTime=Date.now(),await c())}class Rs{rules={};config={};field(i,c){return this.rules[i]=c,this}fields(i){return Object.assign(this.rules,i),this}configure(i){return Object.assign(this.config,i),this}stopOnFirstFailure(){return this.config.stopOnFirstFailure=!0,this}messages(i){return this.config.customMessages=i,this}attributes(i){return this.config.customAttributes=i,this}build(){return Mr(this.rules,this.config)}}function ku(){return new Rs}var Hu={validated:(i,c,P,M,U)=>new at(i,c,P).validate(M,U),apiRoute:(i,c,P,M)=>{let U=new at(i,c,async(z)=>{if(!z.expectsJson())return nr.callMacro("error","API endpoint requires JSON Accept header",void 0,406);return await P(z)});if(M)U.validate(M);return U},resourceRoute:(i,c,P)=>{let M=[];if(c.index)M.push(new at("GET",i,c.index));if(c.show)M.push(new at("GET",`${i}/{id}`,c.show));if(c.store){let U=new at("POST",i,c.store);if(P?.store)U.validate(P.store);M.push(U)}if(c.update){let U=new at("PUT",`${i}/{id}`,c.update);if(P?.update)U.validate(P.update);M.push(U)}if(c.destroy)M.push(new at("DELETE",`${i}/{id}`,c.destroy));return M}};function Au(){return new fs}var ms={compose:(...i)=>async(c,P)=>{let M=0,U=async()=>{if(M>=i.length)return await P();let z=i[M++];return await z(c,U)};return await U()},when:(i,c)=>async(P,M)=>{if(i(P))return await c(P,M);return await M()},unless:(i,c)=>ms.when((P)=>!i(P),c),group:(i)=>ms.compose(...i)},qu={api:()=>[Jr(),async(i,c)=>{try{let P=await c(),M=new Headers(P.headers);return M.set("X-API-Version","1.0"),M.set("X-Response-Time",new Date().toISOString()),new Response(P.body,{status:P.status,statusText:P.statusText,headers:M})}catch(P){return console.error(P),nr.callMacro("error","Internal server error",void 0,500)}}],web:()=>[Jr(),async(i,c)=>(i.session={},await c())],validation:(i,c)=>[Jr(),Mr(i,c)]};Jn(Oe);Kn(Oe);ss(Oe);rs(Oe);Zn(Oe);ps(Oe);hs(Oe);Mn(Oe);Vn(Oe);ds(Oe);ns(Oe);ts(Oe);Pn(Oe);Tn(Oe);class Kr{groups=new Map;globalMiddleware=[];middlewarePriority=new Map;define(i,c){return this.groups.set(i,[...c]),this}extend(i,c){let P=this.groups.get(i)||[];return this.groups.set(i,[...P,...c]),this}prepend(i,c){let P=this.groups.get(i)||[];return this.groups.set(i,[...c,...P]),this}get(i){return this.groups.get(i)||[]}has(i){return this.groups.has(i)}remove(i){return this.groups.delete(i),this}resolve(i){if(typeof i==="function")return[i];if(this.groups.has(i))return this.get(i);return[i]}resolveAll(i){let c=[];for(let P of i)c.push(...this.resolve(P));return c}pushGlobal(...i){return this.globalMiddleware.push(...i),this}prependGlobal(...i){return this.globalMiddleware.unshift(...i),this}removeGlobal(i){return this.globalMiddleware=this.globalMiddleware.filter((c)=>typeof c==="string"?c!==i:!0),this}getGlobal(){return[...this.globalMiddleware]}setPriority(i,c){return this.middlewarePriority.set(i,c),this}sortByPriority(i){return[...i].sort((c,P)=>{let M=typeof c==="string"?c.split(":")[0]:"",U=typeof P==="string"?P.split(":")[0]:"",z=this.middlewarePriority.get(M)??100,de=this.middlewarePriority.get(U)??100;return z-de})}filter(i,c){if(c.only&&c.only.length>0)return i.filter((P)=>{if(typeof P==="string"){let M=P.split(":")[0];return c.only.includes(M)}return!1});if(c.except&&c.except.length>0)return i.filter((P)=>{if(typeof P==="string"){let M=P.split(":")[0];return!c.except.includes(M)}return!0});return i}flush(){this.groups.clear(),this.globalMiddleware=[],this.middlewarePriority.clear()}}var ut=new Kr;ut.define("web",["session","csrf","cors"]);ut.define("api",["throttle:60,1","cors"]);ut.setPriority("session",10);ut.setPriority("cors",20);ut.setPriority("csrf",30);ut.setPriority("auth",40);ut.setPriority("throttle",50);ut.setPriority("role",60);ut.setPriority("permission",60);ut.setPriority("can",70);ut.setPriority("abilities",70);ut.setPriority("verified",80);import{mock as Xr}from"bun:test";class mt{request;url;constructor(i,c,P={}){if(this.url=new URL(c,"http://localhost:3000"),P.query)Object.entries(P.query).forEach(([M,U])=>{if(Array.isArray(U))U.forEach((z)=>this.url.searchParams.append(M,z));else this.url.searchParams.set(M,U)});this.request={method:i,url:this.url.toString(),headers:new Headers(P.headers||{}),params:{},query:this.parseQuery(this.url.searchParams),jsonBody:void 0,formBody:P.body&&typeof P.body==="object"?P.body:void 0,files:P.files?this.convertTestFiles(P.files):void 0,session:P.session,user:P.user,context:P.context||{},requestId:`test-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ip:()=>"127.0.0.1",userAgent:()=>"BunRouter-TestClient/1.0",cookies:Ut(P.cookies||{}),startTime:Date.now(),traceId:`trace-${Date.now()}`,spanId:`span-${Date.now()}`},this.handleBody(P.body)}parseQuery(i){let c={};for(let[P,M]of i.entries())if(c[P])if(Array.isArray(c[P]))c[P].push(M);else c[P]=[c[P],M];else c[P]=M;return c}convertTestFiles(i){return i.map((c)=>({fieldName:c.fieldName,originalName:c.filename,filename:`test-${Date.now()}-${c.filename}`,path:`/tmp/test-uploads/${c.filename}`,size:c.content instanceof ArrayBuffer?c.content.byteLength:new TextEncoder().encode(c.content.toString()).length,mimetype:c.mimetype||"application/octet-stream",buffer:c.content instanceof ArrayBuffer?c.content:new TextEncoder().encode(c.content.toString()).buffer}))}handleBody(i){if(!i)return;let c=this.request.headers?.get("content-type")||"";if(c.includes("application/json")||typeof i==="object"){if(this.request.jsonBody=i,!this.request.headers?.has("content-type"))this.request.headers?.set("content-type","application/json")}else if(c.includes("application/x-www-form-urlencoded"))this.request.formBody=i}params(i){return this.request.params={...this.request.params,...i},this}headers(i){return Object.entries(i).forEach(([c,P])=>{this.request.headers?.set(c,P)}),this}auth(i,c="Bearer"){return this.request.headers?.set("Authorization",`${c} ${i}`),this}user(i){return this.request.user=i,this}session(i){return this.request.session=i,this}cookies(i){let c=this.request.cookies?.getAll()||{};return this.request.cookies=Ut({...c,...i}),this}context(i){return this.request.context={...this.request.context,...i},this}json(i){return this.request.jsonBody=i,this.request.headers?.set("content-type","application/json"),this}form(i){return this.request.formBody=i,this.request.headers?.set("content-type","application/x-www-form-urlencoded"),this}files(i){return this.request.files=this.convertTestFiles(i),this.request.headers?.set("content-type","multipart/form-data"),this}ip(i){return this.request.ip=()=>i,this}userAgent(i){return this.request.userAgent=()=>i,this.request.headers?.set("User-Agent",i),this}csrf(i){return this.request.csrfToken=i,this.request.headers?.set("X-CSRF-Token",i),this}build(){let i={method:this.request.method,headers:this.request.headers};if(this.request.jsonBody)i.body=JSON.stringify(this.request.jsonBody);else if(this.request.formBody){let M=new FormData;Object.entries(this.request.formBody).forEach(([U,z])=>{M.append(U,z)}),i.body=M}let c=new Request(this.url.toString(),i);return Object.assign(c,{params:this.request.params||{},query:this.request.query||{},jsonBody:this.request.jsonBody,formBody:this.request.formBody,files:this.request.files,session:this.request.session,user:this.request.user,context:this.request.context||{},requestId:this.request.requestId,ip:this.request.ip,userAgent:this.request.userAgent,cookies:this.request.cookies||{},startTime:this.request.startTime,traceId:this.request.traceId,spanId:this.request.spanId})}}var oc={get:(i,c)=>new mt("GET",i,c),post:(i,c)=>new mt("POST",i,c),put:(i,c)=>new mt("PUT",i,c),patch:(i,c)=>new mt("PATCH",i,c),delete:(i,c)=>new mt("DELETE",i,c),options:(i,c)=>new mt("OPTIONS",i,c),head:(i,c)=>new mt("HEAD",i,c)};function De(i="GET",c="/",P={}){return new mt(i,c,P).build()}class sr{request;constructor(i){this.request=i||De()}as(i){return this.request.user=i,this}withJWT(i,c="Bearer"){let P=new Headers(this.request.headers);return P.set("Authorization",`${c} ${i}`),this.request={...this.request,headers:P},this}withSession(i){return this.request.session=i,this}withApiKey(i,c="X-API-Key"){let P=new Headers(this.request.headers);return P.set(c,i),this.request={...this.request,headers:P},this}withBasicAuth(i,c){let P=btoa(`${i}:${c}`),M=new Headers(this.request.headers);return M.set("Authorization",`Basic ${P}`),this.request={...this.request,headers:M},this}withAuthCookies(i){let c=this.request.cookies?.getAll()||{};return this.request.cookies=Ut({...c,...i}),this}unauthenticated(){if(this.request.user=void 0,this.request.session=void 0,this.request.headers)this.request.headers.delete("Authorization");return this}getRequest(){return this.request}}class Qr{options;constructor(i={}){this.options={secret:"test-secret",expiresIn:"1h",algorithm:"HS256",...i}}generateToken(i={}){let c={alg:this.options.algorithm,typ:"JWT",...this.options.headers},P=Math.floor(Date.now()/1000),M=P+this.parseExpiresIn(this.options.expiresIn||"1h"),U={iat:P,exp:M,...this.options.payload,...i},z=btoa(JSON.stringify(c)).replace(/=/g,""),de=btoa(JSON.stringify(U)).replace(/=/g,""),pe=btoa(`${z}.${de}.${this.options.secret}`).replace(/=/g,"");return`${z}.${de}.${pe}`}generateExpiredToken(i={}){let c={alg:this.options.algorithm,typ:"JWT"},P=Math.floor(Date.now()/1000),M={iat:P-7200,exp:P-3600,...i},U=btoa(JSON.stringify(c)).replace(/=/g,""),z=btoa(JSON.stringify(M)).replace(/=/g,""),de=btoa(`${U}.${z}.${this.options.secret}`).replace(/=/g,"");return`${U}.${z}.${de}`}generateInvalidToken(){return"invalid.jwt.token"}decodeToken(i){let[c,P,M]=i.split(".");return{header:JSON.parse(atob(c)),payload:JSON.parse(atob(P)),signature:M}}parseExpiresIn(i){let c=i.match(/^(\d+)([smhd])$/);if(!c)return 3600;let P=Number.parseInt(c[1]);switch(c[2]){case"s":return P;case"m":return P*60;case"h":return P*3600;case"d":return P*86400;default:return 3600}}}class Zr{options;constructor(i={}){this.options={sessionId:`test-session-${Date.now()}`,maxAge:3600000,secure:!1,httpOnly:!0,...i}}createSession(i={}){let c={...this.options.data,...i},P=this.generateSessionCookie();return{sessionId:this.options.sessionId,data:c,cookie:P}}generateSessionCookie(i="session"){let c=[];if(this.options.maxAge)c.push(`Max-Age=${Math.floor(this.options.maxAge/1000)}`);if(this.options.secure)c.push("Secure");if(this.options.httpOnly)c.push("HttpOnly");let P=c.length>0?`; ${c.join("; ")}`:"";return`${i}=${this.options.sessionId}${P}`}createExpiredSession(){let i={...this.options,maxAge:-1};return new Zr(i).createSession()}}var dc={user:(i={})=>({id:1,email:"test@example.com",username:"testuser",roles:["user"],permissions:["read"],...i}),adminUser:(i={})=>({id:1,email:"admin@example.com",username:"admin",roles:["admin"],permissions:["read","write","delete"],...i}),guestUser:()=>({id:0,email:"guest@example.com",username:"guest",roles:["guest"],permissions:[]}),authMiddleware:(i)=>Xr(async(c,P)=>{if(i)return c.user=i,await P();return new Response("Unauthorized",{status:401})}),roleMiddleware:(i)=>Xr(async(c,P)=>{if(!c.user)return new Response("Unauthorized",{status:401});let M=c.user.roles||[];if(!i.some((z)=>M.includes(z)))return new Response("Forbidden",{status:403});return await P()}),permissionMiddleware:(i)=>Xr(async(c,P)=>{if(!c.user)return new Response("Unauthorized",{status:401});let M=c.user.permissions||[];if(!i.every((z)=>M.includes(z)))return new Response("Forbidden",{status:403});return await P()})},pc={authenticatedRequest:(i,c)=>new sr(c).as(i).getRequest(),jwtRequest:(i={},c)=>{let M=new Qr().generateToken(i);return new sr(c).withJWT(M).getRequest()},sessionRequest:(i={},c)=>new sr(c).withSession(i).getRequest(),verifyJWTStructure:(i)=>{let c=i.split(".");return c.length===3&&c.every((P)=>P.length>0)},extractJWTPayload:(i)=>{try{let[,c]=i.split(".");return JSON.parse(atob(c))}catch{return null}}};function hc(i){return new sr(i)}function gc(i){return new Qr(i)}function mc(i){return new Zr(i)}import{mock as Ot}from"bun:test";class Ht{request;files;constructor(i){this.request=i||De(),this.files=[]}addFile(i){let c={fieldName:i.fieldName,originalName:i.filename,filename:`test-${Date.now()}-${i.filename}`,path:`/tmp/test-uploads/${i.filename}`,size:i.content instanceof ArrayBuffer?i.content.byteLength:new TextEncoder().encode(i.content.toString()).length,mimetype:i.mimetype||this.detectMimeType(i.filename),buffer:i.content instanceof ArrayBuffer?i.content:new TextEncoder().encode(i.content.toString()).buffer};return this.files.push(c),this.request.files=[...this.request.files||[],c],this}addFiles(i){return i.forEach((c)=>this.addFile(c)),this}addImage(i,c="test.jpg",P=1024){let M=new ArrayBuffer(P);return this.addFile({fieldName:i,filename:c,content:M,mimetype:"image/jpeg"})}addDocument(i,c="test.pdf",P="Test PDF content"){return this.addFile({fieldName:i,filename:c,content:P,mimetype:"application/pdf"})}addTextFile(i,c="test.txt",P="Test content"){return this.addFile({fieldName:i,filename:c,content:P,mimetype:"text/plain"})}addLargeFile(i,c=10){let P=c*1024*1024,M=new ArrayBuffer(P);return this.addFile({fieldName:i,filename:`large-file-${c}mb.bin`,content:M,mimetype:"application/octet-stream"})}addInvalidFile(i,c="malicious.exe"){return this.addFile({fieldName:i,filename:c,content:"Potentially malicious content",mimetype:"application/x-executable"})}withFormData(i){return this.request.formBody={...this.request.formBody,...i},this}getRequest(){return this.request}getFiles(){return this.files}clearFiles(){return this.files=[],this.request.files=[],this}detectMimeType(i){let c=i.split(".").pop()?.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json",xml:"application/xml",zip:"application/zip",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}[c||""]||"application/octet-stream"}}class Yr{static testFileSize(i,c){return i.size<=c}static testFileType(i,c){return c.includes(i.mimetype)}static testFileExtension(i,c){let P=i.originalName.split(".").pop()?.toLowerCase();return P?c.includes(P):!1}static testFilename(i){let c=i.originalName;if(c.includes("..")||c.includes("/")||c.includes("\\"))return!1;if(c.includes("\x00"))return!1;let P=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],M=c.split(".")[0].toUpperCase();if(P.includes(M))return!1;return!0}static testImageFile(i){return["image/jpeg","image/png","image/gif","image/webp","image/svg+xml"].includes(i.mimetype)}static testDocumentFile(i){return["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/csv"].includes(i.mimetype)}}var wc={validationMiddleware:(i={})=>Ot(async(P,M)=>{let U=P.files||[],{maxSize:z=5242880,allowedTypes:de=[],maxFiles:pe=10}=i;if(U.length>pe)return new Response(`Too many files. Maximum ${pe} allowed.`,{status:400});for(let Re of U){if(Re.size>z)return new Response(`File ${Re.originalName} is too large. Maximum size: ${z} bytes.`,{status:400});if(de.length>0&&!de.includes(Re.mimetype))return new Response(`File type ${Re.mimetype} not allowed.`,{status:400});if(!Yr.testFilename(Re))return new Response(`Invalid filename: ${Re.originalName}`,{status:400})}return await M()}),imageUploadMiddleware:(i={})=>Ot(async(P,M)=>{let U=P.files||[],{maxSize:z=2097152}=i;for(let de of U){if(!Yr.testImageFile(de))return new Response(`File ${de.originalName} is not a valid image.`,{status:400});if(de.size>z)return new Response(`Image ${de.originalName} is too large.`,{status:400})}return await M()}),storageService:{store:Ot(async(i,c)=>c||`/uploads/${Date.now()}-${i.filename}`),delete:Ot(async(i)=>{}),exists:Ot(async(i)=>!i.includes("not-found")),getUrl:Ot((i)=>`https://example.com/storage${i}`)},virusScanner:{scan:Ot(async(i)=>{if(i.originalName.endsWith(".exe")||i.mimetype==="application/x-executable")return{clean:!1,threat:"Potentially malicious executable"};return{clean:!0}})}},bc={singleFileUpload:()=>new Ht().addImage("avatar","profile.jpg").withFormData({description:"Profile picture"}),multipleFileUpload:()=>new Ht().addImage("images","photo1.jpg").addImage("images","photo2.png").addDocument("documents","report.pdf").withFormData({album:"vacation"}),fileSizeExceeded:()=>new Ht().addLargeFile("file",50),invalidFileType:()=>new Ht().addInvalidFile("file","virus.exe"),emptyFileUpload:()=>new Ht().addFile({fieldName:"file",filename:"empty.txt",content:"",mimetype:"text/plain"}),maliciousFilename:()=>new Ht().addFile({fieldName:"file",filename:"../../../etc/passwd",content:"malicious content",mimetype:"text/plain"})},Tc={hasFiles:(i,c)=>{let P=i.files||[];if(c!==void 0&&P.length!==c)throw Error(`Expected ${c} files, but got ${P.length}`);if(P.length===0)throw Error("Expected request to have files")},hasFileWithField:(i,c)=>{if(!(i.files||[]).some((U)=>U.fieldName===c))throw Error(`Expected file with field name '${c}'`)},fileMatches:(i,c)=>{Object.entries(c).forEach(([P,M])=>{if(i[P]!==M)throw Error(`Expected file.${P} to be '${M}', got '${i[P]}'`)})},fileSizeWithinLimit:(i,c)=>{if(i.size>c)throw Error(`File size ${i.size} exceeds limit of ${c}`)},fileTypeAllowed:(i,c)=>{if(!c.includes(i.mimetype))throw Error(`File type '${i.mimetype}' is not allowed. Allowed types: ${c.join(", ")}`)}};function xc(i){return new Ht(i)}var vc={image:(i="image",c="test.jpg")=>({fieldName:i,filename:c,content:new ArrayBuffer(1024),mimetype:"image/jpeg"}),document:(i="document",c="test.pdf")=>({fieldName:i,filename:c,content:"PDF content",mimetype:"application/pdf"}),text:(i="file",c="test.txt",P="Test content")=>({fieldName:i,filename:c,content:P,mimetype:"text/plain"}),large:(i="file",c=10)=>({fieldName:i,filename:`large-${c}mb.bin`,content:new ArrayBuffer(c*1024*1024),mimetype:"application/octet-stream"}),malicious:(i="file")=>({fieldName:i,filename:"../../../malicious.exe",content:"malicious content",mimetype:"application/x-executable"})};import{mock as Ie,spyOn as io}from"bun:test";class ys{middleware;context;constructor(i){this.middleware=i,this.context=this.createContext()}createContext(){let i=De(),c=Ie(()=>Promise.resolve(new Response("Next called",{status:200})));return{request:i,next:c}}withRequest(i){return this.context.request=i,this}withNext(i){return this.context.next=Ie(i),this}withError(i){return this.context.error=i,this}async execute(){try{return await this.middleware(this.context.request,this.context.next)}catch(i){throw this.context.error=i,i}}expectNextCalled(i=1){if(this.context.next.mock.calls.length!==i)throw Error(`Expected next to be called ${i} times, but was called ${this.context.next.mock.calls.length} times`);return this}expectNextNotCalled(){if(this.context.next.mock.calls.length>0)throw Error(`Expected next not to be called, but was called ${this.context.next.mock.calls.length} times`);return this}expectError(i){if(!this.context.error)throw Error("Expected middleware to throw an error, but no error was thrown");if(i&&this.context.error.message!==i)throw Error(`Expected error message "${i}", but got "${this.context.error.message}"`);return this}getContext(){return this.context}reset(){return this.context=this.createContext(),this}}function Ec(i){return new ys(i)}var Sc={passthrough:()=>Ie(async(i,c)=>await c()),response:(i=200,c)=>Ie(async()=>new Response(c?JSON.stringify(c):null,{status:i})),error:(i="Middleware error")=>Ie(async()=>{throw Error(i)}),modifyRequest:(i)=>Ie(async(c,P)=>(i(c),await P())),addContext:(i,c)=>Ie(async(P,M)=>(P.context=P.context||{},P.context[i]=c,await M())),auth:(i)=>Ie(async(c,P)=>{if(i)return c.user=i,await P();else return new Response("Unauthorized",{status:401})}),rateLimit:(i=!1)=>Ie(async(c,P)=>{if(i)return new Response("Too Many Requests",{status:429});return await P()}),cors:(i="*")=>Ie(async(c,P)=>{let M=await P();if(M)M.headers.set("Access-Control-Allow-Origin",i);return M})};class ws{middlewares;request;finalHandler;constructor(i){this.middlewares=i,this.request=De(),this.finalHandler=Ie(async()=>new Response("Final handler",{status:200}))}withRequest(i){return this.request=i,this}withFinalHandler(i){return this.finalHandler=Ie(i),this}async execute(){let i=0,c=async()=>{if(i<this.middlewares.length){let P=this.middlewares[i++];return await P(this.request,c)}else return await this.finalHandler()};return await c()}getExecutionOrder(){return this.middlewares.map((i,c)=>c)}}function kc(i){return new ws(i)}function Hc(i){return io(i,"call")}function Ac(){let i=Ie(async(c,P)=>await P());return{middleware:i,spy:i}}async function qc(i,c=1000){let P=[],M=De(),U=Ie(async()=>new Response("OK"));for(let Te=0;Te<c;Te++){let xe=performance.now();await i(M,U);let ve=performance.now();P.push(ve-xe)}let z=P.reduce((Te,xe)=>Te+xe,0),de=z/c,pe=Math.min(...P),Re=Math.max(...P);return{averageTime:de,minTime:pe,maxTime:Re,totalTime:z}}import{mock as Et}from"bun:test";class oo{id;attributes;constructor(i={}){this.id=i.id,this.attributes=i}static modelName="GenericMockModel";static async find(i){return null}static async findOrFail(i){throw Error("Not implemented")}static async where(i){return[]}static async create(i){throw Error("Not implemented")}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}}class ao{id;email;name;constructor(i={id:1}){this.id=i.id,this.email=i.email||"test@example.com",this.name=i.name||"Test User"}static async find(i){return null}static async findOrFail(i){throw Error("Not implemented")}toJSON(){return{id:this.id,email:this.email,name:this.name}}}class uo{id;title;content;userId;constructor(i={id:1}){this.id=i.id,this.title=i.title||"Test Post",this.content=i.content||"Test content",this.userId=i.userId||1}static async find(i){return null}static async findOrFail(i){throw Error("Not implemented")}async belongsTo(i){return!1}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}class bs{request;options;constructor(i={}){this.options=i,this.request=De()}withRequest(i){return this.request=i,this}withParams(i){return this.request.params={...this.request.params,...i},this}withModel(i){return this.options.modelClass=i,this}withRouteKey(i){return this.options.routeKey=i,this}withConstraints(i){return this.options.constraints=i,this}withResolver(i){return this.options.customResolver=i,this}async testResolution(i){if(this.options.customResolver)return await this.options.customResolver(i);if(this.options.modelClass)return new this.options.modelClass({id:i});return{id:i}}async testNotFound(i){try{throw await this.testResolution(i),Error("Expected model not found error")}catch(c){if(c instanceof Error&&c.message!=="Model not found")throw c}}getRequest(){return this.request}}var Dc={createModel:(i,c={})=>class P{id;attributes;constructor(M={}){this.id=M.id,this.attributes={...c,...M}}static modelName=i;static async find(M){if(M==="not-found")return null;return new P({id:M,...c})}static async findOrFail(M){let U=await this.find(M);if(!U)throw Error("Model not found");return U}static async where(M){return[new P({id:1,...c,...M})]}static async create(M){return new P({id:Date.now(),...M})}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}},User:class i{id;email;name;constructor(c={id:1}){this.id=c.id,this.email=c.email||"test@example.com",this.name=c.name||"Test User"}static async find(c){if(c==="not-found")return null;return new i({id:Number.parseInt(c)})}static async findOrFail(c){let P=await this.find(c);if(!P)throw Error("User not found");return P}toJSON(){return{id:this.id,email:this.email,name:this.name}}},Post:class i{id;title;content;userId;constructor(c={id:1}){this.id=c.id,this.title=c.title||"Test Post",this.content=c.content||"Test content",this.userId=c.userId||1}static async find(c){if(c==="not-found")return null;return new i({id:Number.parseInt(c)})}static async findOrFail(c){let P=await this.find(c);if(!P)throw Error("Post not found");return P}async belongsTo(c){return this.userId===c}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}},Fc={belongsTo:(i="userId")=>Et(async(P,M)=>{if(!M.user)return!1;return P[i]===M.user.id}),belongsToUser:()=>Et(async(c,P)=>{if(!P.user)return!1;return c.userId===P.user.id}),published:()=>Et(async(c)=>c.published===!0||c.status==="published"),visible:()=>Et(async(c)=>c.visible!==!1&&c.hidden!==!0),custom:(i)=>Et(i),combine:(...i)=>Et(async(P,M)=>{for(let U of i)if(!await U(P,M))return!1;return!0})};class Ts{resolvers=new Map;register(i,c){return this.resolvers.set(i,Et(c)),this}registerModel(i,c){let P=Et(async(M)=>{if(c.find){let U=await c.find(M);if(!U)throw Error(`${c.name||"Model"} not found`);return U}return new c({id:M})});return this.resolvers.set(i,P),this}async resolve(i,c){let P=this.resolvers.get(i);if(!P)throw Error(`No resolver registered for key: ${i}`);return await P(c)}async testAll(i="1"){let c={};for(let[P,M]of this.resolvers)try{c[P]=await M(i)}catch(U){c[P]={error:U instanceof Error?U.message:"Unknown error"}}return c}getKeys(){return Array.from(this.resolvers.keys())}clear(){return this.resolvers.clear(),this}}var Nc={testRoute:async(i,c,P)=>{let M=De("GET",i);M.params=c;for(let[U,z]of Object.entries(P))M.context=M.context||{},M.context[U]=z;return M},createHandler:(i)=>Et(async(P)=>{let M=P.context||{};for(let U of i)if(!M[U])return new Response(`Model ${U} not found`,{status:404});return new Response(JSON.stringify({params:P.params,models:Object.fromEntries(i.map((U)=>[U,M[U]]))}),{headers:{"Content-Type":"application/json"}})}),testBindingMiddleware:(i)=>Et(async(P,M)=>{P.context=P.context||{};for(let[U,z]of Object.entries(i)){let de=P.params[U];if(de)try{if(typeof z==="function")P.context[U]=await z(de);else P.context[U]=z}catch(pe){return console.error(`Error resolving model ${U}:`,pe),new Response(`${U} not found`,{status:404})}}return await M()})};function Uc(i){return new bs(i)}function Ic(){return new Ts}var co=async(i,c)=>i.userId===c.id,_c={testUserScoped:async(i,c,P=co)=>await P(i,c),testRoleAccess:async(i,c,P)=>{if(!c.roles)return!1;return P.some((M)=>c.roles.includes(M))},testPermissionAccess:async(i,c,P)=>{if(!c.permissions)return!1;return P.every((M)=>c.permissions.includes(M))}};import{mock as lo}from"bun:test";import $t from"process";class vs{metrics=[];startTime=0;endTime=0;start(){return this.startTime=performance.now(),this}end(){return this.endTime=performance.now(),this}recordMetric(i){return this.metrics.push(i),this}getElapsedTime(){return this.endTime-this.startTime}getMetrics(){return[...this.metrics]}getAverageResponseTime(){if(this.metrics.length===0)return 0;return this.metrics.reduce((c,P)=>c+P.responseTime,0)/this.metrics.length}getMemoryStats(){if(this.metrics.length===0)return{averageHeapUsed:0,maxHeapUsed:0,averageRSS:0,maxRSS:0};let i=this.metrics.map((P)=>P.memoryUsage.heapUsed),c=this.metrics.map((P)=>P.memoryUsage.rss);return{averageHeapUsed:i.reduce((P,M)=>P+M,0)/i.length,maxHeapUsed:Math.max(...i),averageRSS:c.reduce((P,M)=>P+M,0)/c.length,maxRSS:Math.max(...c)}}clear(){return this.metrics=[],this.startTime=0,this.endTime=0,this}}class Wt{client;config;constructor(i,c){this.client=i,this.config=c}async run(i,c="GET",P={}){let M={totalRequests:0,successfulRequests:0,failedRequests:0,averageResponseTime:0,requestsPerSecond:0,errors:[]},U=[],z=new Map,de=Date.now(),pe=this.config.maxRequests||Math.floor(this.config.duration/1000*(this.config.requestsPerSecond||this.config.concurrency)),Re=[];for(let ve=0;ve<pe;ve++){let Ce=this.makeRequest(i,c,P).then((Me)=>{U.push(Me),M.successfulRequests++}).catch((Me)=>{let Pe=Me instanceof Error?Me.message:"Unknown error";z.set(Pe,(z.get(Pe)||0)+1),M.failedRequests++});if(Re.push(Ce),this.config.requestsPerSecond){let Me=1000/this.config.requestsPerSecond;await new Promise((Pe)=>setTimeout(Pe,Me))}if(Re.length>=this.config.concurrency)await Promise.race(Re),Re.filter((Pe)=>Pe.then(()=>!0).catch(()=>!0)).forEach((Pe)=>{let Ee=Re.indexOf(Pe);if(Ee>-1)Re.splice(Ee,1)})}await Promise.allSettled(Re);let xe=(Date.now()-de)/1000;return M.totalRequests=pe,M.averageResponseTime=U.length>0?U.reduce((ve,Ce)=>ve+Ce,0)/U.length:0,M.requestsPerSecond=pe/xe,M.errors=Array.from(z.entries()).map(([ve,Ce])=>({error:ve,count:Ce})),M}async makeRequest(i,c,P){let M=performance.now();try{return await this.client.request(c,i,P),performance.now()-M}catch(U){let z=performance.now();throw U}}}var Wc={routeHandler:async(i,c=1000)=>{let P=[],M=De();for(let Te=0;Te<c;Te++){let xe=performance.now();await i(M);let ve=performance.now();P.push(ve-xe)}let U=P.reduce((Te,xe)=>Te+xe,0),z=U/c,de=Math.min(...P),pe=Math.max(...P),Re=c/U*1000;return{averageTime:z,minTime:de,maxTime:pe,totalTime:U,throughput:Re}},middleware:async(i,c=1000)=>{let P=[],M=De(),U=lo(async()=>new Response("OK"));for(let Te=0;Te<c;Te++){let xe=performance.now();await i(M,U);let ve=performance.now();P.push(ve-xe)}let z=P.reduce((Te,xe)=>Te+xe,0),de=z/c,pe=Math.min(...P),Re=Math.max(...P);return{averageTime:de,minTime:pe,maxTime:Re,totalTime:z}},jsonSerialization:async(i,c=1e4)=>{let P=[];for(let Re=0;Re<c;Re++){let Te=performance.now(),xe=JSON.stringify(i),ve=performance.now();P.push(ve-Te)}let M=P.reduce((Re,Te)=>Re+Te,0),U=M/c,z=Math.min(...P),de=Math.max(...P),pe=JSON.stringify(i).length;return{averageTime:U,minTime:z,maxTime:de,totalTime:M,dataSize:pe}},routeMatching:async(i,c,P=1000)=>{let M=[],U=0;for(let xe=0;xe<P;xe++){let ve=c[xe%c.length],Ce=performance.now();if(i.find((Ee)=>{let Ae=Ee.path.replace(/:\w+/g,"[^/]+");return new RegExp(`^${Ae}$`).test(ve)}))U++;let Pe=performance.now();M.push(Pe-Ce)}let z=M.reduce((xe,ve)=>xe+ve,0),de=z/P,pe=Math.min(...M),Re=Math.max(...M),Te=U/P;return{averageTime:de,minTime:pe,maxTime:Re,totalTime:z,matchRate:Te}}},Vc={measureMemoryUsage:async(i,c=100)=>{let P=[],M=[];if(globalThis.gc)globalThis.gc();let U=$t.memoryUsage().heapUsed;for(let Te=0;Te<c;Te++){let xe=await i();P.push(xe);let ve=$t.memoryUsage();if(M.push(ve.heapUsed),Te%10===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let z=$t.memoryUsage().heapUsed,de=M.reduce((Te,xe)=>Te+xe,0)/M.length,pe=Math.max(...M),Re=z-U>1048576;return{averageHeapUsed:de,maxHeapUsed:pe,memoryLeakDetected:Re,results:P}},testRouteHandlerMemoryLeaks:async(i,c=1000)=>{if(globalThis.gc)globalThis.gc();let P=$t.memoryUsage().heapUsed;for(let de=0;de<c;de++){let pe=De();if(await i(pe),de%100===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let M=$t.memoryUsage().heapUsed,U=M-P;return{memoryLeakDetected:U>5242880,initialMemory:P,finalMemory:M,memoryGrowth:U}}},Jc={rampUpTest:async(i,c,P)=>{let M=[],U=10,z=P.testDuration/10,de=(P.endConcurrency-P.startConcurrency)/10;for(let pe=0;pe<10;pe++){let Re=Math.round(P.startConcurrency+de*pe),xe=await new Wt(i,{duration:z,concurrency:Re,requestsPerSecond:Re*2}).run(c);M.push({concurrency:Re,requestsPerSecond:xe.requestsPerSecond,averageResponseTime:xe.averageResponseTime,errorRate:xe.failedRequests/xe.totalRequests})}return M},spikeTest:async(i,c,P)=>{let U=await new Wt(i,{duration:30000,concurrency:P.normalLoad}).run(c),de=await new Wt(i,{duration:P.spikeDuration,concurrency:P.spikeLoad}).run(c),Re=await new Wt(i,{duration:30000,concurrency:P.normalLoad}).run(c);return{normalPhase:U,spikePhase:de,recoveryPhase:Re}}},Kc={responseTimeWithin:(i,c)=>{if(i>c)throw Error(`Response time ${i}ms exceeds maximum ${c}ms`)},throughputAtLeast:(i,c)=>{if(i<c)throw Error(`Throughput ${i} RPS is below minimum ${c} RPS`)},errorRateBelow:(i,c)=>{if(i>c)throw Error(`Error rate ${(i*100).toFixed(2)}% exceeds maximum ${(c*100).toFixed(2)}%`)},memoryUsageWithin:(i,c)=>{if(i>c)throw Error(`Memory usage ${(i/1024/1024).toFixed(2)}MB exceeds maximum ${(c/1024/1024).toFixed(2)}MB`)},noMemoryLeaks:(i,c=5242880)=>{if(i>c)throw Error(`Potential memory leak detected: ${(i/1024/1024).toFixed(2)}MB growth`)}};function Xc(){return new vs}function Qc(i,c){return new Wt(i,c)}var xs={getCurrentMemoryUsage:()=>{let i=$t.memoryUsage();return{heapUsed:i.heapUsed,heapTotal:i.heapTotal,external:i.external,rss:i.rss}},getCPUUsage:()=>{let i=$t.cpuUsage();return{user:i.user,system:i.system}},createMetricSnapshot:(i)=>({responseTime:i,memoryUsage:xs.getCurrentMemoryUsage(),cpuUsage:xs.getCPUUsage()}),formatResults:(i)=>JSON.stringify(i,null,2)};class en{status;statusText;headers;body;text;json;cookies;redirected;url;ok;type;originalResponse;constructor(i,c){this.originalResponse=i,this.status=i.status,this.statusText=i.statusText,this.headers=this.parseHeaders(i.headers),this.cookies=this.parseCookies(i.headers.get("set-cookie")),this.redirected=i.redirected,this.url=i.url,this.ok=i.ok,this.type=i.type,this.body=c,this.text=typeof c==="string"?c:JSON.stringify(c);try{this.json=typeof c==="string"?JSON.parse(c):c}catch{this.json=null}}parseHeaders(i){let c={};return i.forEach((P,M)=>{c[M.toLowerCase()]=P}),c}parseCookies(i){if(!i)return{};let c={};return i.split(",").forEach((P)=>{let[M]=P.trim().split(";"),[U,z]=M.split("=");if(U&&z)c[U.trim()]=z.trim()}),c}expectStatus(i){if(this.status!==i)throw Error(`Expected status ${i}, got ${this.status}`);return this}expectSuccess(){if(!this.ok)throw Error(`Expected successful response, got ${this.status}`);return this}expectHeader(i,c){let P=this.headers[i.toLowerCase()];if(P===void 0)throw Error(`Expected header '${i}' to be present`);if(c!==void 0&&P!==c)throw Error(`Expected header '${i}' to be '${c}', got '${P}'`);return this}expectBody(i){if(typeof i==="string"){if(this.text!==i)throw Error(`Expected body '${i}', got '${this.text}'`)}else if(JSON.stringify(this.json)!==JSON.stringify(i))throw Error(`Expected body ${JSON.stringify(i)}, got ${JSON.stringify(this.json)}`);return this}expectJson(i){if(JSON.stringify(this.json)!==JSON.stringify(i))throw Error(`Expected JSON ${JSON.stringify(i)}, got ${JSON.stringify(this.json)}`);return this}expectJsonContains(i){if(typeof this.json!=="object"||this.json===null)throw Error("Response is not a JSON object");return Object.entries(i).forEach(([c,P])=>{let M=this.json[c];if(typeof P==="object"&&P!==null&&typeof M==="object"&&M!==null){let U=JSON.stringify(P),z=JSON.stringify(M);if(U!==z)throw Error(`Expected JSON property '${c}' to be ${U}, got ${z}`)}else if(M!==P)throw Error(`Expected JSON property '${c}' to be '${P}', got '${M}'`)}),this}expectCookie(i,c){let P=this.cookies[i];if(P===void 0)throw Error(`Expected cookie '${i}' to be present`);if(c!==void 0&&P!==c)throw Error(`Expected cookie '${i}' to be '${c}', got '${P}'`);return this}expectRedirect(i){if(this.status<300||this.status>=400)throw Error(`Expected redirect status (3xx), got ${this.status}`);if(i){let c=this.headers.location;if(c!==i)throw Error(`Expected redirect to '${i}', got '${c}'`)}return this}expectValidationError(i,c){if(this.status!==422)throw Error(`Expected validation error status (422), got ${this.status}`);if(i){let P=this.json?.errors||this.json?.message;if(!P||!P[i])throw Error(`Expected validation error for field '${i}'`);if(c){if(!(Array.isArray(P[i])?P[i]:[P[i]]).includes(c))throw Error(`Expected validation error message '${c}' for field '${i}'`)}}return this}expectContentType(i){let c=this.headers["content-type"];if(!c||!c.includes(i))throw Error(`Expected content type '${i}', got '${c}'`);return this}expectBodyContains(i){if(!this.text.includes(i))throw Error(`Expected body to contain '${i}'`);return this}expectBodyMatches(i){if(!i.test(this.text))throw Error(`Expected body to match pattern ${i}`);return this}expectJsonStructure(i){return this.validateStructure(this.json,i,"root"),this}validateStructure(i,c,P){if(c&&typeof c==="object"&&c.$$typeof)return;if(Array.isArray(c)){if(!Array.isArray(i))throw TypeError(`Expected ${P} to be an array`);if(c.length>0&&i.length>0)this.validateStructure(i[0],c[0],`${P}[0]`)}else if(typeof c==="object"&&c!==null){if(typeof i!=="object"||i===null)throw Error(`Expected ${P} to be an object`);Object.keys(c).forEach((M)=>{if(!(M in i))throw Error(`Expected ${P} to have property '${M}'`);this.validateStructure(i[M],c[M],`${P}.${M}`)})}}getOriginalResponse(){return this.originalResponse}toJSON(){return{status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,json:this.json,cookies:this.cookies,redirected:this.redirected,url:this.url,ok:this.ok,type:this.type}}}async function Cs(i){let c=await i.text();return new en(i,c)}function Yc(i=200,c,P){let M=new Headers(P);if(c&&typeof c==="object"&&!M.has("content-type"))M.set("content-type","application/json");let U=new Response(c?typeof c==="string"?c:JSON.stringify(c):null,{status:i,headers:M});return new en(U,c)}class Sr{router;config;defaultHeaders;constructor(i,c={}){this.router=i,this.config={baseUrl:"http://localhost:3000",timeout:5000,followRedirects:!0,validateStatus:(P)=>P>=200&&P<300,...c},this.defaultHeaders=c.defaultHeaders||{}}async get(i,c={}){return this.request("GET",i,c)}async post(i,c={}){return this.request("POST",i,c)}async put(i,c={}){return this.request("PUT",i,c)}async patch(i,c={}){return this.request("PATCH",i,c)}async delete(i,c={}){return this.request("DELETE",i,c)}async options(i,c={}){return this.request("OPTIONS",i,c)}async head(i,c={}){return this.request("HEAD",i,c)}async request(i,c,P={}){let M={...this.defaultHeaders,...P.headers},U={...P,headers:M},z=new mt(i,c,U).build();try{let de=await this.handleRequest(z);return await Cs(de)}catch(de){throw Error(`Test request failed: ${de instanceof Error?de.message:"Unknown error"}`)}}async handleRequest(i){let c=new URL(i.url),P=this.findMatchingRoute(i.method,c.pathname);if(!P)return new Response("Not Found",{status:404});let{route:M,params:U}=P;i.params={...i.params,...U};try{return await this.executeMiddlewareChain(i,M)||new Response("No response",{status:500})}catch(z){return new Response(JSON.stringify({error:z instanceof Error?z.message:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}findMatchingRoute(i,c){for(let P of this.router.routes){if(P.method.toLowerCase()!==i.toLowerCase())continue;let M=this.matchPath(P.path,c);if(M!==null)return{route:P,params:M}}return null}matchPath(i,c){let P=i.split("/"),M=c.split("/");if(P.length!==M.length)return null;let U={};for(let z=0;z<P.length;z++){let de=P[z],pe=M[z];if(de.startsWith(":")){let Re=de.slice(1);U[Re]=pe}else if(de!==pe)return null}return U}async executeMiddlewareChain(i,c){let P=[...this.router.globalMiddleware,...c.middleware],M=0,U=async()=>{if(M<P.length){let de=P[M++];return await de(i,U)}else return await this.executeHandler(c.handler,i)};return await U()||new Response("No response",{status:500})}async executeHandler(i,c){if(typeof i==="function")return await i(c);else if(typeof i==="string")throw TypeError(`String handlers not supported in test environment: ${i}`);else if(typeof i==="object"&&i.handle)return await new i().handle(c);throw Error("Invalid handler type")}setDefaultHeaders(i){return this.defaultHeaders={...this.defaultHeaders,...i},this}auth(i,c="Bearer"){return this.defaultHeaders.Authorization=`${c} ${i}`,this}userAgent(i){return this.defaultHeaders["User-Agent"]=i,this}withConfig(i){return new Sr(this.router,{...this.config,...i})}withHeaders(i){return new Sr(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...i}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function Er(i,c){return new Sr(i,c)}var nl={for:(i,c)=>Er(i,c),withConfig:(i)=>(c)=>Er(c,i),withAuth:(i,c="Bearer")=>(P)=>Er(P).auth(i,c),withHeaders:(i)=>(c)=>Er(c).withHeaders(i)};import{mock as Bt}from"bun:test";class Ct{messages=[];isConnected=!1;readyState=0;eventHandlers=new Map;constructor(){this.setupEventHandlers()}setupEventHandlers(){this.eventHandlers.set("open",[]),this.eventHandlers.set("message",[]),this.eventHandlers.set("close",[]),this.eventHandlers.set("error",[])}connect(){return this.isConnected=!0,this.readyState=1,this.emit("open",{type:"open"}),this}disconnect(i=1000,c="Normal closure"){return this.isConnected=!1,this.readyState=3,this.emit("close",{type:"close",code:i,reason:c}),this}send(i){if(!this.isConnected)throw Error("WebSocket is not connected");let c={type:typeof i==="string"?"text":"binary",data:i,timestamp:Date.now()};return this.messages.push(c),this}receive(i){if(!this.isConnected)throw Error("WebSocket is not connected");let c={type:typeof i==="string"?"text":"binary",data:i,timestamp:Date.now()};return this.emit("message",{type:"message",data:i}),this}ping(i){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("ping",{type:"ping",data:i}),this}pong(i){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("pong",{type:"pong",data:i}),this}on(i,c){if(!this.eventHandlers.has(i))this.eventHandlers.set(i,[]);return this.eventHandlers.get(i).push(c),this}off(i,c){let P=this.eventHandlers.get(i);if(P){let M=P.indexOf(c);if(M>-1)P.splice(M,1)}return this}emit(i,c){(this.eventHandlers.get(i)||[]).forEach((M)=>M(c))}getSentMessages(){return[...this.messages]}getMessagesByType(i){return this.messages.filter((c)=>c.type===i)}clearMessages(){return this.messages=[],this}getState(){return{isConnected:this.isConnected,readyState:this.readyState}}getTestClient(){return{send:(i)=>this.send(i),close:(i,c)=>this.disconnect(i,c),ping:(i)=>this.ping(i),pong:(i)=>this.pong(i),messages:this.getSentMessages(),isConnected:this.isConnected,readyState:this.readyState}}}class Ps{tester;_data;constructor(i={}){this.tester=new Ct,this._data=i}send(i){this.tester.send(i)}close(i,c){this.tester.disconnect(i,c)}ping(i){this.tester.ping(i)}pong(i){this.tester.pong(i)}publish(i,c){this.tester.send(c)}subscribe(i){}unsubscribe(i){}isSubscribed(i){return!0}cork(i){i()}get readyState(){return this.tester.getState().readyState}get data(){return this._data}set data(i){this._data=i}getTester(){return this.tester}}var ol={onOpen:()=>Bt(async(i)=>{}),onMessage:(i)=>Bt(async(c,P)=>{if(i)c.send(i)}),onClose:()=>Bt(async(i,c,P)=>{}),onError:()=>Bt(async(i,c)=>{}),echo:()=>Bt(async(i,c)=>{i.send(c)}),broadcast:(i)=>Bt(async(c,P)=>{i.forEach((M)=>{if(M!==c&&M.readyState===1)M.send(P)})}),chatRoom:(i)=>Bt(async(c,P)=>{c.publish(i,P)})},al={basicConnection:()=>new Ct().connect().send("Hello WebSocket").receive("Hello Client"),connectionFailure:()=>{let i=new Ct;return i.on("error",()=>{}),i},messageBroadcast:(i=3)=>{let c=Array.from({length:i},()=>new Ct().connect());return c[0].send("Broadcast message"),c.slice(1).forEach((P)=>P.receive("Broadcast message")),c},pingPong:()=>new Ct().connect().ping().pong(),connectionTimeout:()=>{let i=new Ct;return setTimeout(()=>{i.disconnect(1006,"Connection timeout")},100),i}},ul={isConnected:(i)=>{if(!i.getState().isConnected)throw Error("Expected WebSocket to be connected")},isDisconnected:(i)=>{if(i.getState().isConnected)throw Error("Expected WebSocket to be disconnected")},messageSent:(i,c)=>{if(!i.getSentMessages().some((U)=>{if(typeof c==="string"&&typeof U.data==="string")return U.data===c;return U.data===c}))throw Error("Expected message not found in sent messages")},messageCount:(i,c)=>{let P=i.getSentMessages();if(P.length!==c)throw Error(`Expected ${c} messages, but got ${P.length}`)},messageType:(i,c,P)=>{let M=i.getSentMessages();if(c>=M.length)throw Error(`Message at index ${c} does not exist`);if(M[c].type!==P)throw Error(`Expected message type '${P}', got '${M[c].type}'`)},readyState:(i,c)=>{let P=i.getState();if(P.readyState!==c)throw Error(`Expected ready state ${c}, got ${P.readyState}`)}},cl={testThroughput:async(i=1000,c=1024)=>{let P=new Ct().connect(),M="x".repeat(c),U=performance.now();for(let Te=0;Te<i;Te++)P.send(M);let de=performance.now()-U,pe=i/de*1000,Re=de/i;return{messagesPerSecond:pe,totalTime:de,averageLatency:Re}},testConcurrentConnections:async(i=100)=>{let c={successfulConnections:0,failedConnections:0,averageConnectionTime:0},P=[],M=Array.from({length:i},async()=>{let U=performance.now();try{new Ct().connect();let de=performance.now();P.push(de-U),c.successfulConnections++}catch(z){console.error("WebSocket connection failed:",z),c.failedConnections++}});return await Promise.all(M),c.averageConnectionTime=P.length>0?P.reduce((U,z)=>U+z,0)/P.length:0,c}};function ll(){return new Ct}function dl(i){return new Ps(i)}var pl={createClients:(i)=>Array.from({length:i},()=>new Ct().connect()),withLatency:(i,c)=>{let P=i.send.bind(i);return i.send=(M)=>(setTimeout(()=>P(M),c),i),i},withPacketLoss:(i,c)=>{let P=i.send.bind(i);return i.send=(M)=>{if(Math.random()>c)P(M);return i},i},*messageGenerator(i,c="Message"){for(let P=1;P<=i;P++)yield`${c} ${P}`}};class tn extends Error{status;response;body;constructor(i,c){let P=typeof c?.message==="string"?c.message:i.statusText||"Request failed";super(`${i.status} ${P}`);this.name="TypedClientError",this.status=i.status,this.response=i,this.body=c}}function Ms(i,c){if(!c)return i;let P=i;for(let[M,U]of Object.entries(c)){let z=encodeURIComponent(U);P=P.split(`{${M}}`).join(z),P=P.replace(new RegExp(`:${M}(?![A-Z0-9_])`,"gi"),z)}return P}function Es(i,c){if(!c)return i;let P=new URLSearchParams;for(let[U,z]of Object.entries(c))if(z!==void 0&&z!==null)P.append(U,String(z));let M=P.toString();if(!M)return i;return i.includes("?")?`${i}&${M}`:`${i}?${M}`}async function po(i){if(i.status===204||i.headers.get("content-length")==="0")return;if((i.headers.get("content-type")??"").includes("json"))try{return await i.json()}catch{return}return await i.text()}function ho(i){let c=i.baseUrl.replace(/\/+$/,""),P=i.fetch??globalThis.fetch;async function M(){if(typeof i.headers==="function")return await i.headers();return i.headers??{}}async function U(z,de,pe,Re,Te){let xe=Es(`${c}${Ms(de,Te?.params)}`,Te?.query),ve={accept:"application/json",...await M(),...Te?.headers};if(Re&&ve["content-type"]===void 0&&ve["Content-Type"]===void 0)ve["content-type"]="application/json";let Ce=await P(xe,{method:z,headers:ve,...Re?{body:JSON.stringify(pe)}:{},...i.credentials?{credentials:i.credentials}:{},...Te?.signal?{signal:Te.signal}:{}}),Me=await po(Ce);if(!Ce.ok){let Pe=new tn(Ce,Me);if(i.onError)return i.onError(Pe);throw Pe}return Me}return{get:(z,de)=>U("GET",z,void 0,!1,de),post:(z,de,pe)=>U("POST",z,de,!0,pe),put:(z,de,pe)=>U("PUT",z,de,!0,pe),patch:(z,de,pe)=>U("PATCH",z,de,!0,pe),delete:(z,de)=>U("DELETE",z,void 0,!1,de),async raw(z,de,pe){let{params:Re,query:Te,...xe}=pe??{},ve=Es(`${c}${Ms(de,Re)}`,Te);return await P(ve,{method:z,...xe,headers:{...await M(),...xe.headers},...i.credentials?{credentials:i.credentials}:{}})}}}function go(i){return i}var mo=["get","post","put","patch","delete"];function fo(i,c,P,M){if(!M)return;let U=i,z=(de)=>{let pe=U?.[de];if(typeof pe!=="function")throw TypeError(`[typed-router] ${c.toUpperCase()} ${P}: this router's route does not support .${String(de)}(), so the \`${String(de)}\` option cannot be applied. Register the route directly instead of dropping it.`);return pe};if(M.middleware)z("middleware").call(U,M.middleware);if(M.name)z("name").call(U,M.name);if(M.skipCsrf)z("skipCsrf").call(U);if(M.requireCsrf)z("requireCsrf").call(U);if(M.rateLimit)z("rateLimit").call(U,M.rateLimit.max,M.rateLimit.window??"minute")}function Ro(i){let c={};for(let P of mo)c[P]=(M,U,z)=>(fo(i[P](M,U),P,M,z),c);return c}export{nn as ApiKeyManager,Us as Auth,sr as AuthTester,L as BindingBuilder,so as BuiltInRules,ca as CacheInvalidation,o as Container,y as ContentSecurityPolicy,le as ContextualContainer,p as Cors,r as Csrf,w as DDoSProtection,pn as DEFAULT_COMPRESSION,Tu as DatabaseRules,I as DatabaseSessionStore,ue as DefaultServiceProviderManager,si as Dependencies,Qt as DomainGroup,Fn as DomainGroupBuilder,pt as DomainMatcher,qu as EnhancementPresets,_ as EnvironmentManager,ln as Errors,C as FileSecurity,A as FileSessionStore,a as FileUpload,Ht as FileUploadTester,Yr as FileValidationTester,Se as FluentRouteBuilder,Yt as FluentRouter,oo as GenericMockModel,S as Helmet,fe as InMemoryNonceStore,b as InputValidation,rn as JWT,Qr as JWTTester,h as JsonBody,Wt as LoadTester,l as MemorySessionStore,ws as MiddlewareChainTester,ii as MiddlewareFactory,Kr as MiddlewareGroupRegistry,ms as MiddlewareHelpers,Fr as MiddlewarePipeline,ys as MiddlewareTester,uo as MockPostClass,Ps as MockServerWebSocket,ao as MockUserClass,bs as ModelBindingTester,Ts as ModelResolverTester,sn as OAuth2Helper,D as PerformanceAlerting,N as PerformanceDashboard,q as PerformanceMonitor,vs as PerformanceTester,k as RateLimit,Bn as RateLimitRegistry,pa as RateLimitUtils,yr as RateLimiter,O as RedisSessionStore,m as RequestId,g as RequestSigning,H as RequestTracer,mn as ResponseBuilder,at as RouteBuilder,$n as RouteCacheFactory,An as RouteCacheKeyGenerator,qn as RouteCacheManager,Li as RouteFactory,Nn as RouteGroupBuilder,Hu as RouteHelpers,Oe as Router,zi as RouterUtils,R as Security,B as SecuritySuite,f as Session,G as SessionManager,Zr as SessionTester,n as SignatureError,ni as SkipConditions,fa as SubdomainPatterns,Ur as SubdomainRouter,ma as SubdomainUtils,Sr as TestClient,mt as TestRequestBuilder,en as TestResponseWrapper,Ai as ThrottleFactory,tn as TypedClientError,fs as ValidationFluentRouter,Cu as ValidationHelpers,Rs as ValidationMiddlewareBuilder,Vr as ValidationRuleBuilder,Pr as Validator,Ct as WebSocketTester,Be as apiKeyAuth,Dr as appendVary,Yi as applyRequestEnhancements,Br as applyResponseCompression,Tt as auth,pc as authHelpers,dc as authMocks,Ne as basicAuth,qe as bearerAuth,qc as benchmarkMiddleware,Wc as benchmarkTests,Xo as buildUrlWithPreservedParams,$i as clearNamedRoutes,Io as compressResponse,e as config,Fc as constraintHelpers,ze as contentSecurityPolicy,wt as cors,hc as createAuthTester,be as createContainer,cr as createCookieAccessor,Jr as createEnhancementMiddleware,xc as createFileUploadTester,Au as createFluentRouter,Ji as createHandlerResolver,Ut as createInMemoryCookieAccessor,gc as createJWTTester,Qc as createLoadTester,Ac as createMiddlewareSpy,De as createMockRequest,Yc as createMockResponse,dl as createMockServerWebSocket,Uc as createModelBindingTester,Ic as createModelResolverTester,Ca as createPathRegex,Xc as createPerformanceTester,jt as createRateLimitMiddleware,On as createRouteCacheMiddleware,yt as createSessionStore,mc as createSessionTester,ga as createSubdomainMiddleware,Er as createTestClient,Cs as createTestResponse,ho as createTypedClient,Ro as createTypedRouter,Mr as createValidationMiddleware,ll as createWebSocketTester,xt as csrf,Ve as ddosProtection,Nt as decodeParam,he as defaultConfig,Ko as defaultQueryPreservationConfig,go as defineEndpoint,Xe as documentUpload,Xs as enableRequestContext,ge as extractApiKey,me as extractBasicAuth,V as extractBearerToken,wr as extractParamNames,jn as fileExists,We as fileUpload,Tc as fileUploadAssertions,wc as fileUploadMocks,bc as fileUploadScenarios,fi as generateQueryPreservationScript,F as generateSessionId,ft as getConfig,ye as getContainer,dn as getCurrentRequest,Ir as getNamedRoutePath,Oi as getNamedRoutes,oi as globalMiddlewarePipeline,xu as globalValidator,Je as imageUpload,hr as injectQueryPreservationScript,Ye as inputValidation,Di as isActionClass,hn as isCompressible,va as isRouteHandler,Mt as joinPaths,bt as jsonBody,He as jwtAuth,ht as matchPath,Vc as memoryTests,K as middleware,ut as middlewareGroups,Sc as mockMiddleware,Dc as modelMocks,Ke as multipleFileUpload,Zs as negotiateEncoding,Zt as normalizePath,je as oauth2Auth,Lt as parseThrottleString,ti as peekBody,Qe as performanceAlerting,Kc as performanceAssertions,Ze as performanceDashboard,et as performanceMonitor,xs as performanceUtils,Ln as processHtmlTemplate,W as rateLimit,Dn as rateLimitRegistry,St as registerNamedRoute,Qs as request,Rt as requestId,Ue as requestSigning,tt as requestTracer,er as resolveHandler,_r as resolveViewPath,ke as response,jo as responseBuilder,_t as routeCacheManager,Nc as routeModelHelpers,Gi as router,vu as rule,dr as runWithRequest,_c as scopedBindingHelpers,rt as security,nt as securitySuite,vt as session,we as setContainer,pr as setCurrentRequest,Ys as shouldCompress,Le as signRequest,Ge as singleFileUpload,Hc as spyOnMiddleware,Jc as stressTests,nl as testClient,vc as testFiles,Ec as testMiddleware,kc as testMiddlewareChain,oc as testRequest,xa as toActionPath,Bi as url,ku as validate,Pa as validatePath,_e as verifySignature,lt as wrapResponse,ul as wsAssertions,ol as wsHandlerMocks,cl as wsPerformance,al as wsTestScenarios,pl as wsTestUtils};