@stacksjs/bun-router 0.1.4 → 0.1.6

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,5 +1,5 @@
1
1
  // @bun
2
- import{$o as jc,Ap as ml,Bp as fl,Cp as Rl,Dp as yl,Ep as wl,Fp as bl,Gp as Tl,Hp as xl,Ip as vl,Jp as Cl,Kp as Pl,Lp as Ml,Mp as El,Np as Sl,Op as kl,Pp as Hl,Qo as Ac,Qp as Al,Ro as qc,Rp as ql,So as Oc,Sp as Ol,To as $c,Tp as $l,Uo as Bc,Up as Bl,Vo as Dc,Vp as Dl,Wo as Fc,Wp as Fl,Xo as Nc,Xp as Nl,Yo as Uc,Yp as Ul,Zo as Ic,Zp as Il,_o as _c,ap as Lc,bp as zc,cp as Gc,dp as Wc,ep as Vc,fp as Jc,gp as Kc,hp as Xc,ip as Qc,jp as Zc,kp as Yc,lp as el,mp as tl,np as rl,op as nl,pp as sl,qp as il,rp as ol,sp as al,tp as ul,up as cl,vp as ll,wp as dl,xp as pl,yp as hl,zp as gl}from"./chunk-vcp8dnjq.js";import"./chunk-p0qhpnqh.js";import{$q as dn,Br as Ys,Gr as ei,Sq as Je,Tq as se,Uq as sn,Vq as on,Wq as an,Xq as un,Yq as we,Zq as cn,_q as ln,ar as pn,br as Te,cr as be,dr as hn,er as gn,fr as mn,gr as B,hr as fn,ir as Rn,jr as yn,kr as wn,lr as bn,mr as Tn,nr as xn,or as vn,pr as Cn,ur as Vs,vr as Js,wr as Ks,xr as Xs,yr as Qs,zr as Zs}from"./chunk-3y4gaz7v.js";import{Yu as nn,Zu as ze}from"./chunk-nf3kv7kv.js";import{timingSafeEqual as Gr}from"crypto";function je(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ye(e){e=e.replace(/-/g,"+").replace(/_/g,"/");while(e.length%4)e+="=";return atob(e)}class ft{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=je(JSON.stringify(r)),o=je(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(ye(n)),a=JSON.parse(ye(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||!Gr(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(ye(r)),payload:JSON.parse(ye(n))}}catch{return null}}createSignature(e,t,r){return je(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 Rt{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 yt{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 Wr={JWT:ft,ApiKeyManager:Rt,OAuth2Helper:yt},Vr=Wr;var vt={};nn(vt,{AuthenticationException:()=>sn,AuthorizationException:()=>on,BugsnagReporter:()=>We,BusinessLogicException:()=>hn,CircuitBreaker:()=>xe,CircuitBreakerHttpClient:()=>wt,CircuitBreakerOpenException:()=>be,CircuitBreakerPresets:()=>Xr,CircuitBreakerRegistry:()=>J,CircularDependencyException:()=>Rn,ConfigurationException:()=>gn,CustomReporter:()=>bt,DatabaseException:()=>pn,DegradationStrategies:()=>rn,ErrorFactory:()=>B,ErrorReportingManager:()=>re,ErrorReportingPresets:()=>en,ExternalServiceException:()=>Te,FileSystemException:()=>mn,GracefulDegradationManager:()=>ne,HandlerResolutionException:()=>bn,InternalServerException:()=>ln,MethodNotAllowedException:()=>un,MiddlewareConfigurationException:()=>yn,ModelBindingException:()=>Tn,NotFoundException:()=>an,RateLimitException:()=>cn,RouteConflictException:()=>fn,RouteNotFoundException:()=>wn,RouterErrorFactory:()=>Cn,RouterException:()=>Je,SentryReporter:()=>Ge,ServiceHealthMonitor:()=>Ve,ServiceUnavailableException:()=>dn,TimeoutException:()=>we,ValidationException:()=>se,circuitBreaker:()=>Jr,createAdvancedErrorHandler:()=>xt,createCircuitBreaker:()=>Qr,createCircuitBreakerMiddleware:()=>Kr,createErrorReporting:()=>Yr,createGracefulDegradationMiddleware:()=>tn,detectRouteConflicts:()=>vn,findSimilarRoutes:()=>xn,globalCircuitBreakerRegistry:()=>Le,withCircuitBreaker:()=>Zr});class xe{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 be(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 be(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 we(`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 we)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 xe(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 Jr(e){let t=new xe(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 wt{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 Te(`HTTP ${a.status}: ${a.statusText}`,o,e,a.status,void 0,s);return a},fallback:n,context:s})}getRegistry(){return this.registry}}function Kr(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 Xr={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 Te)return t.statusCode>=500;return!0}})},Le=new J;function Qr(e){return Le.register(e)}async function Zr(e,t){return Le.execute(e,t)}class Ge{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 We{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 bt{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 re{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 Ge(t));break;case"bugsnag":this.reporters.push(new We(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 Yr(e){return new re(e)}var en={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 Ve{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 ne{config;healthMonitor;cache=new Map;metrics=new Map;constructor(e){this.config=e,this.healthMonitor=new Ve(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 tn(e){let t=new ne(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 rn={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 Tt{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 re(this.config.errorReporting);if(this.config.gracefulDegradation?.enabled)this.gracefulDegradation=new ne(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 Je)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 xt(e={}){let t=new Tt(e);return{middleware:t.middleware(),getStats:()=>t.getStats(),cleanup:()=>t.cleanup()}}function ve(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 K(e={}){let t={...e};return ve({read:()=>t,write:(r,n)=>{t[r]=n},remove:(r)=>{delete t[r]}})}import{AsyncLocalStorage as Pn}from"async_hooks";var Ke=new Pn,Ce=!1,j=null;function Mn(){Ce=!0}function Pe(e,t){if(!Ce){j=e;let r=t();if(r instanceof Promise)return r.finally(()=>{j=null});return j=null,r}return Ke.run({current:e},t)}function Me(e){let t=Ke.getStore();if(t){t.current=e;return}if(j!==null)j=e}function Ct(){if(!Ce)return Ce=!0,j??void 0;return Ke.getStore()?.current??j??void 0}function En(){let e=Ct();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 Sn={enabled:!0,level:6,threshold:1024};function Pt(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 kn(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 Hn(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(!Pt(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 Mt(e,t,r={}){let n={...Sn,...r};if(!n.enabled)return e;let s=kn(t.headers.get("accept-encoding"));if(!Hn(e,s,n.threshold)){if(Pt(e.headers.get("content-type"))&&!e.headers.has("content-encoding"))Xe(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 An(e.body,n.threshold);if(o.ended&&o.size<n.threshold){let c=new Headers(e.headers);return Xe(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),Xe(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 An(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 Xe(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 Et{_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 xi(){return new Et}import qn from"process";class Qe{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 On={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=qn.env.NODE_ENV||"development";return e.includes(t)}})},$n={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})},Bn={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}},Dn=new Qe;import{existsSync as kt,readdirSync as Fn,statSync as Nn}from"fs";import{basename as Ht,extname as St,join as Un,resolve as At}from"path";var In=[".ts",".js"],_n=["routes","src/routes"],jn=["web","index"];function Ln(){let e=process.cwd();for(let t of _n){let r=At(e,t);if(kt(r)&&Nn(r).isDirectory())return r}return null}function qt(e,t){let r=[];if(!kt(e))return r;let n=Fn(e,{withFileTypes:!0});for(let s of n){if(s.name.startsWith(".")||s.name.startsWith("_"))continue;let i=Un(e,s.name);if(s.isDirectory())r.push(...qt(i,t));else if(In.includes(St(s.name))){let o=e===t?"":e.slice(t.length),a=Ht(s.name,St(s.name)),u=jn.includes(a)?o||"":`${o}/${a}`;r.push({filePath:i,prefix:u})}}return r}async function zn(e,t,r,n){try{let s=await import(t),i=0,o=e.routes?.length||0;if(typeof s.default==="function"){let a=Gn(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 ${Ht(t)} (${i} routes)`);return i}catch(s){return console.error(`[bun-router] Failed to load route file ${t}:`,s),0}}function Gn(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 Ot(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||Ln();if(!t){this._apiRoutesInitialized=!0;return}let r=this.config?.verbose||!1,n=qt(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 zn(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=At(t),this},writable:!0,configurable:!0}})}import{join as ie,relative as Ze,resolve as D,dirname as Vn}from"path";import{readdirSync as $t,statSync as Jn,existsSync as Se}from"fs";var ki={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function Wn(e){let{preserve:t=[],exclude:r=[],routes:n=[]}=e;if(!t.length)return"";return`<script data-query-preservation>
2
+ import{$o as Vc,Ap as bl,Bp as Tl,Cp as xl,Dp as vl,Ep as Cl,Fp as Pl,Gp as Ml,Hp as El,Ip as Sl,Jp as kl,Kp as Hl,Lp as Al,Mp as ql,Np as Ol,Op as $l,Pp as Bl,Qo as Dc,Qp as Dl,Ro as Fc,Rp as Fl,So as Nc,Sp as Nl,To as Uc,Tp as Ul,Uo as Ic,Up as Il,Vo as _c,Vp as _l,Wo as jc,Wp as jl,Xo as Lc,Xp as Ll,Yo as zc,Yp as zl,Zo as Gc,Zp as Gl,_o as Wc,ap as Jc,bp as Kc,cp as Xc,dp as Qc,ep as Zc,fp as Yc,gp as el,hp as tl,ip as rl,jp as nl,kp as sl,lp as il,mp as ol,np as al,op as ul,pp as cl,qp as ll,rp as dl,sp as pl,tp as hl,up as gl,vp as ml,wp as fl,xp as Rl,yp as yl,zp as wl}from"./chunk-vcp8dnjq.js";import"./chunk-p0qhpnqh.js";import{$q as pn,Br as ei,Gr as ti,Sq as Ke,Tq as ie,Uq as on,Vq as an,Wq as un,Xq as cn,Yq as be,Zq as ln,_q as dn,ar as hn,br as xe,cr as Te,dr as gn,er as mn,fr as fn,gr as B,hr as Rn,ir as yn,jr as wn,kr as bn,lr as Tn,mr as xn,nr as vn,or as Cn,pr as Pn,ur as Js,vr as Ks,wr as Xs,xr as Qs,yr as Zs,zr as Ys}from"./chunk-3y4gaz7v.js";import{Yu as sn,Zu as Ge}from"./chunk-nf3kv7kv.js";import{timingSafeEqual as Wr}from"crypto";function Le(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 Rt{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=Le(JSON.stringify(r)),o=Le(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||!Wr(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 Le(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 yt{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 wt{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 Vr={JWT:Rt,ApiKeyManager:yt,OAuth2Helper:wt},Jr=Vr;var Ct={};sn(Ct,{AuthenticationException:()=>on,AuthorizationException:()=>an,BugsnagReporter:()=>Ve,BusinessLogicException:()=>gn,CircuitBreaker:()=>ve,CircuitBreakerHttpClient:()=>bt,CircuitBreakerOpenException:()=>Te,CircuitBreakerPresets:()=>Qr,CircuitBreakerRegistry:()=>J,CircularDependencyException:()=>yn,ConfigurationException:()=>mn,CustomReporter:()=>Tt,DatabaseException:()=>hn,DegradationStrategies:()=>nn,ErrorFactory:()=>B,ErrorReportingManager:()=>ne,ErrorReportingPresets:()=>tn,ExternalServiceException:()=>xe,FileSystemException:()=>fn,GracefulDegradationManager:()=>se,HandlerResolutionException:()=>Tn,InternalServerException:()=>dn,MethodNotAllowedException:()=>cn,MiddlewareConfigurationException:()=>wn,ModelBindingException:()=>xn,NotFoundException:()=>un,RateLimitException:()=>ln,RouteConflictException:()=>Rn,RouteNotFoundException:()=>bn,RouterErrorFactory:()=>Pn,RouterException:()=>Ke,SentryReporter:()=>We,ServiceHealthMonitor:()=>Je,ServiceUnavailableException:()=>pn,TimeoutException:()=>be,ValidationException:()=>ie,circuitBreaker:()=>Kr,createAdvancedErrorHandler:()=>vt,createCircuitBreaker:()=>Zr,createCircuitBreakerMiddleware:()=>Xr,createErrorReporting:()=>en,createGracefulDegradationMiddleware:()=>rn,detectRouteConflicts:()=>Cn,findSimilarRoutes:()=>vn,globalCircuitBreakerRegistry:()=>ze,withCircuitBreaker:()=>Yr});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 Kr(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 bt{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 Xr(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 Qr={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}})},ze=new J;function Zr(e){return ze.register(e)}async function Yr(e,t){return ze.execute(e,t)}class We{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 Ve{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 Tt{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 ne{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 We(t));break;case"bugsnag":this.reporters.push(new Ve(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 en(e){return new ne(e)}var tn={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 Je{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 se{config;healthMonitor;cache=new Map;metrics=new Map;constructor(e){this.config=e,this.healthMonitor=new Je(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 rn(e){let t=new se(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 nn={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 xt{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 ne(this.config.errorReporting);if(this.config.gracefulDegradation?.enabled)this.gracefulDegradation=new se(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 Ke)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 vt(e={}){let t=new xt(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 Mn}from"async_hooks";var Xe=new Mn,Pe=!1,j=null;function En(){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 Xe.run({current:e},t)}function Ee(e){let t=Xe.getStore();if(t){t.current=e;return}if(j!==null)j=e}function Pt(){if(!Pe)return Pe=!0,j??void 0;return Xe.getStore()?.current??j??void 0}function Sn(){let e=Pt();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 kn={enabled:!0,level:6,threshold:1024};function Mt(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 Hn(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 An(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(!Mt(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 Et(e,t,r={}){let n={...kn,...r};if(!n.enabled)return e;let s=Hn(t.headers.get("accept-encoding"));if(!An(e,s,n.threshold)){if(Mt(e.headers.get("content-type"))&&!e.headers.has("content-encoding"))Qe(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 qn(e.body,n.threshold);if(o.ended&&o.size<n.threshold){let c=new Headers(e.headers);return Qe(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),Qe(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 qn(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 Qe(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 St{_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 Ci(){return new St}import On from"process";class Ze{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 $n={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=On.env.NODE_ENV||"development";return e.includes(t)}})},Bn={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})},Dn={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}},Fn=new Ze;import{existsSync as Ht,readdirSync as Nn,statSync as Un}from"fs";import{basename as At,extname as kt,join as In,resolve as qt}from"path";var _n=[".ts",".js"],jn=["routes","src/routes"],Ln=["web","index"];function zn(){let e=process.cwd();for(let t of jn){let r=qt(e,t);if(Ht(r)&&Un(r).isDirectory())return r}return null}function Ot(e,t){let r=[];if(!Ht(e))return r;let n=Nn(e,{withFileTypes:!0});for(let s of n){if(s.name.startsWith(".")||s.name.startsWith("_"))continue;let i=In(e,s.name);if(s.isDirectory())r.push(...Ot(i,t));else if(_n.includes(kt(s.name))){let o=e===t?"":e.slice(t.length),a=At(s.name,kt(s.name)),u=Ln.includes(a)?o||"":`${o}/${a}`;r.push({filePath:i,prefix:u})}}return r}async function Gn(e,t,r,n){try{let s=await import(t),i=0,o=e.routes?.length||0;if(typeof s.default==="function"){let a=Wn(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 ${At(t)} (${i} routes)`);return i}catch(s){return console.error(`[bun-router] Failed to load route file ${t}:`,s),0}}function Wn(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 $t(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||zn();if(!t){this._apiRoutesInitialized=!0;return}let r=this.config?.verbose||!1,n=Ot(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 Gn(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=qt(t),this},writable:!0,configurable:!0}})}import{join as oe,relative as Ye,resolve as D,dirname as Jn}from"path";import{readdirSync as Bt,statSync as Kn,existsSync as ke}from"fs";var Ai={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function Vn(e){let{preserve:t=[],exclude:r=[],routes:n=[]}=e;if(!t.length)return"";return`<script data-query-preservation>
3
3
  (function(){
4
4
  var preserve = ${JSON.stringify(t)};
5
5
  var exclude = ${JSON.stringify(r)};
@@ -76,30 +76,30 @@ catch (e) { return false; }
76
76
  }
77
77
  };
78
78
  })();
79
- </script>`}function Ee(e,t){if(!t.enabled||!t.preserve?.length)return e;let r=Wn(t);if(!r)return e;if(e.includes("</head>"))return e.replace("</head>",`${r}
79
+ </script>`}function Se(e,t){if(!t.enabled||!t.preserve?.length)return e;let r=Vn(t);if(!r)return e;if(e.includes("</head>"))return e.replace("</head>",`${r}
80
80
  </head>`);if(e.includes("</body>"))return e.replace("</body>",`${r}
81
- </body>`);return e+r}function Hi(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 Kn=["src/views","views","resources/views","app/views"],Xn=["_","components","layouts","partials","scripts","styles"],Qn=[".stx",".html"];function Zn(e=process.cwd()){for(let t of Kn){let r=D(e,t);if(Se(r)&&Jn(r).isDirectory())return r}return null}function Bt(e,t,r){if(!Se(e))return!1;try{let n=$t(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=ie(e,s.name);if(Bt(i,t,r))return!0}}}catch{}return!1}function Yn(e,t,r){let n=Ze(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 Dt(e,t,r,n){let s=[];if(!Se(e))return s;let i=$t(e,{withFileTypes:!0});for(let a of i){let u=ie(e,a.name);if(n.some((c)=>a.name.startsWith(c)||a.name===c))continue;if(a.isDirectory())s.push(...Dt(u,t,r,n));else if(a.isFile()){if(r.some((l)=>a.name.endsWith(l))){let{routePath:l,params:d}=Yn(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:
81
+ </body>`);return e+r}function qi(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 Xn=["src/views","views","resources/views","app/views"],Qn=["_","components","layouts","partials","scripts","styles"],Zn=[".stx",".html"];function Yn(e=process.cwd()){for(let t of Xn){let r=D(e,t);if(ke(r)&&Kn(r).isDirectory())return r}return null}function Dt(e,t,r){if(!ke(e))return!1;try{let n=Bt(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=oe(e,s.name);if(Dt(i,t,r))return!0}}}catch{}return!1}function es(e,t,r){let n=Ye(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 Ft(e,t,r,n){let s=[];if(!ke(e))return s;let i=Bt(e,{withFileTypes:!0});for(let a of i){let u=oe(e,a.name);if(n.some((c)=>a.name.startsWith(c)||a.name===c))continue;if(a.isDirectory())s.push(...Ft(u,t,r,n));else if(a.isFile()){if(r.some((l)=>a.name.endsWith(l))){let{routePath:l,params:d}=es(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
82
  - ${u.filePath}
83
83
  - ${a.filePath}
84
- Using: ${u.filePath}`);else o.set(a.routePath,a)}return Array.from(o.values())}function es(e,t){let r=Ze(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(Se(s))return s;return null}function ts(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 rs(e,t,r,n,s){let o=await import("./chunk-n2j24b0h.js");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:ts(g),ip:"",locale:null,params:r.params??{},method:String(r.method??"GET"),request:s},T={__filename:e,__dirname:Vn(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,zr)=>{if(M)d.headers[String(M)]=String(zr)},definePageMeta:()=>{}};if(c)await o.extractVariables(c,T,e);let V=n?.componentsDir?D(n.componentsDir):ie(t,"components"),fe=n?.layoutsDir?D(n.layoutsDir):ie(t,"layouts"),Ir=n?.partialsDir?D(n.partialsDir):ie(t,"partials"),_r={...o.defaultConfig,componentsDir:V,layoutsDir:fe,partialsDir:Ir},jr=await o.processDirectives(l,T,e,_r,new Set),Re=Number(T.__stxResponseStatus),Lr=T.__stxResponseHeaders;return{html:jr,status:Number.isInteger(Re)&&Re>=100&&Re<=599?Re:d.status,headers:{...d.headers,...Lr??{}}}}function ns(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 Ee(u,n);return u}try{let u=es(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 rs(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 Ft(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||Zn();if(!t){this._fileRoutesInitialized=!0;return}let r=this._fileRoutingConfig||{};if(r.enabled===!1){this._fileRoutesInitialized=!0;return}let n=r.extensions||Qn,s=r.exclude||Xn;if(!Bt(t,n,s)){this._fileRoutesInitialized=!0;return}let i=Dt(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} -> ${Ze(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=ns(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 ke{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 ke(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 T=S.formatData(y,r);if(p.push(T),g+=T.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 ke(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(",")}
84
+ Using: ${u.filePath}`);else o.set(a.routePath,a)}return Array.from(o.values())}function ts(e,t){let r=Ye(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 rs(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 ns(e,t,r,n,s){let o=await import("./chunk-n2j24b0h.js");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:rs(g),ip:"",locale:null,params:r.params??{},method:String(r.method??"GET"),request:s},T={__filename:e,__dirname:Jn(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,Gr)=>{if(M)d.headers[String(M)]=String(Gr)},definePageMeta:()=>{}};if(c)await o.extractVariables(c,T,e);let V=n?.componentsDir?D(n.componentsDir):oe(t,"components"),Re=n?.layoutsDir?D(n.layoutsDir):oe(t,"layouts"),_r=n?.partialsDir?D(n.partialsDir):oe(t,"partials"),jr={...o.defaultConfig,componentsDir:V,layoutsDir:Re,partialsDir:_r},Lr=await o.processDirectives(l,T,e,jr,new Set),ye=Number(T.__stxResponseStatus),zr=T.__stxResponseHeaders;return{html:Lr,status:Number.isInteger(ye)&&ye>=100&&ye<=599?ye:d.status,headers:{...d.headers,...zr??{}}}}function ss(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=ts(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 ns(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 Nt(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||Yn();if(!t){this._fileRoutesInitialized=!0;return}let r=this._fileRoutingConfig||{};if(r.enabled===!1){this._fileRoutesInitialized=!0;return}let n=r.extensions||Zn,s=r.exclude||Qn;if(!Dt(t,n,s)){this._fileRoutesInitialized=!0;return}let i=Ft(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} -> ${Ye(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=ss(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 T=S.formatData(y,r);if(p.push(T),g+=T.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
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 ke(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 X{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 X.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=X.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 He(e,t){try{e.close()}catch{}}function Nt(e){Object.defineProperties(e.prototype,{streamFile:{value(t,r,n){return X.streamFile(t,r,n)},writable:!0,configurable:!0},streamFileWithRanges:{async value(t,r){return X.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){He(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){He(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}
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 Ut(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
89
  `;if(a.event)u+=`event: ${a.event}
90
90
  `;if(a.retry)u+=`retry: ${a.retry}
91
91
  `;let c=typeof a.data==="string"?a.data:JSON.stringify(a.data);u+=`data: ${c}
92
92
 
93
- `,i.enqueue(o.encode(u))}i.close()}catch(a){He(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){He(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 Ae 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 It{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 ss=new It;async function Ut(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 _t(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=ss.getBinding(i.name);if(a){let l=null;if(typeof a==="function")l=await a(o);else l=await Ut(i.name,o,a,i.key,s);if(!l)throw new Ae(i.name,o,i.key||"id");s[i.name]=l;continue}let u=t[i.name];if(!u)continue;let c=await Ut(i.name,o,u,i.key,s);if(!c)throw new Ae(i.name,o,i.key||"id");s[i.name]=c}return r.models=s,await n()}catch(i){if(i instanceof Ae)return new Response(`${i.modelName} not found`,{status:404});throw i}}}class jt{key;entry;prev;next;constructor(e,t,r=null,n=null){this.key=e;this.entry=t;this.prev=r;this.next=n}}class oe{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 jt(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 Lt{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 zt{cache;tagIndex=new Map;keyTags=new Map;constructor(e=1000){this.cache=new oe({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 Q=new zt;function Gt(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=Lt.generateKey(t,e),s=await Q.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 is(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 Q.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 is(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 Wt={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")})},Li={byTags:(e)=>Q.invalidateByTags(e),forUser:(e)=>Q.invalidateByTags([`user:${e}`]),forModel:(e,t)=>{let r=t?[`${e}:${t}`,e]:[e];return Q.invalidateByTags(r)},all:()=>{Q.clear()}};class qe{cache;config;constructor(e,t=1e4){this.config=e,this.cache=new oe({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 Vt{limiters=new Map;register(e,t){let r=new qe(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 Jt=new Vt;function Z(e,t){let r=t?Jt.getOrCreate(t,e):new qe(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 Y(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=os(s)}return{maxAttempts:r,windowMs:n}}function os(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 as={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"})},Wi={fromString:(e,t)=>{let r=Y(e);return Z(r,t)},getInfo:async(e,t)=>{let r=new qe(t),{info:n}=await r.checkLimit(e);return n},reset:(e,t)=>{let r=Jt.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 ae{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 Ye{domainGroups=[];wildcardGroup;domain(e){let t=k.parseDomainPattern(e);return new Kt(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 Kt{router;pattern;group;constructor(e,t){this.router=e;this.pattern=t;this.group=new ae(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 Xt(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 Xt{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 Ji(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 Ki={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},Xi={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 us from"process";var ee=new Map;function U(e,t){ee.set(e,t)}function et(e){return ee.get(e)}function cs(){return new Map(ee)}function ls(){ee.clear()}function ds(e,t={},r={}){let n=ee.get(e);if(!n){let u=[...ee.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??us.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${u.startsWith("http")?u:`https://${u}`}${i.startsWith("/")?i:`/${i}`}`}return i}import{join as Qt}from"path";function ue(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 to(e){return e.replace(/\//g,"_").toLowerCase()}function ps(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 ro(e){return typeof e==="function"&&!ps(e)}function Oe(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map((r)=>r.slice(1,-1).replace("?","")):[]}function no(e){let t=e.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${t}$`)}var hs=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,gs=/\{[^}]+\?\}/,Zt=new Map,Yt=new Map;function ms(e){let t=Zt.get(e);if(t)return t;let r=e.endsWith("/*"),n=ue(e),s=0,i=n.split("/").filter(Boolean).map((a)=>{let u=gs.test(a);if(u)s++;let c=a.match(hs);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 Zt.set(e,o),o}function fs(e){let t=Yt.get(e);if(t!==void 0)return t;let r;try{r=new RegExp(`^${e}$`)}catch{r=null}return Yt.set(e,r),r}function H(e,t,r,n){let s=ms(e);if(s.isWildcard&&t.startsWith(s.wildcardBase))return!0;let i=s.segments,o=ue(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){if(r[u.paramName]=c,n&&n[u.paramName]){let l=fs(n[u.paramName]);if(l){if(!l.test(c))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 ue(e.join("/"))}function so(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 er(e){try{return await Bun.file(e).exists()}catch{return!1}}async function tt(e,t,r){if(r.some((n)=>e.endsWith(n))){let n=ue(Qt(t,e));if(await er(n))return n;return null}for(let n of r){let s=ue(Qt(t,`${e}${n}`));if(await er(s))return s}return null}function tr(e,t){let r=e.replace(/\{\{([^}]+)\}\}/g,(n,s)=>{let i=s.trim(),o=rt(t,i);return o!==void 0?String(o):n});return r=Rs(r,t),r=ys(r,t),r}function Rs(e,t){return e.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(r,n,s,i="")=>{let o=n.trim();return rt(t,o)?s:i})}function ys(e,t){return e.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(r,n,s)=>{let i=rt(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 rt(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={...Wt.api(e),...t},this}throttle(e,t){if(typeof e==="string"){let r=Y(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=_t(t,this.modelBindings);e.push(r)}if(this.throttleConfig){let t=Z(this.throttleConfig);e.push(t)}if(this.cacheConfig){let t=Gt(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 rr{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 nr{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 sr{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 ce{routes=[];globalMiddleware=[];subdomainRouter=new Ye;routeGroups=[];middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];constructor(){this.setupDefaultMiddleware()}setupDefaultMiddleware(){this.namedMiddleware.set("throttle",(e)=>{let t=e?Y(e):{maxAttempts:60,windowMs:60000},r=Z({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 sr(this,t)}when(e){return new rr(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 nr(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 ce;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 ae(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 ce;t(r);let n=k.parseDomainPattern(e),s=new ae(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 ws={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}},bs={route:(e,t={},r={})=>{let n=et(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"}})},Ts=new ce;function ir(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 or(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=Oe(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 ar(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 xs(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}".
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 _t{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 is=new _t;async function It(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 jt(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=is.getBinding(i.name);if(a){let l=null;if(typeof a==="function")l=await a(o);else l=await It(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 It(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 Lt{key;entry;prev;next;constructor(e,t,r=null,n=null){this.key=e;this.entry=t;this.prev=r;this.next=n}}class ae{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 Lt(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 zt{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 Gt{cache;tagIndex=new Map;keyTags=new Map;constructor(e=1000){this.cache=new ae({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 Gt;function Wt(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=zt.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 os(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 os(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 Vt={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")})},Gi={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 ae({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 Jt{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 Kt=new Jt;function Y(e,t){let r=t?Kt.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=as(s)}return{maxAttempts:r,windowMs:n}}function as(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 us={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"})},Ji={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=Kt.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 ue{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 et{domainGroups=[];wildcardGroup;domain(e){let t=k.parseDomainPattern(e);return new Xt(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 Xt{router;pattern;group;constructor(e,t){this.router=e;this.pattern=t;this.group=new ue(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 Qt(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 Qt{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 Xi(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 Qi={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},Zi={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 cs from"process";var te=new Map;function U(e,t){te.set(e,t)}function tt(e){return te.get(e)}function ls(){return new Map(te)}function ds(){te.clear()}function ps(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??cs.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${u.startsWith("http")?u:`https://${u}`}${i.startsWith("/")?i:`/${i}`}`}return i}import{join as Zt}from"path";function ce(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 so(e){return e.replace(/\//g,"_").toLowerCase()}function hs(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 io(e){return typeof e==="function"&&!hs(e)}function $e(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map((r)=>r.slice(1,-1).replace("?","")):[]}function oo(e){let t=e.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${t}$`)}var gs=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,ms=/\{[^}]+\?\}/,Yt=new Map,er=new Map;function fs(e){let t=Yt.get(e);if(t)return t;let r=e.endsWith("/*"),n=ce(e),s=0,i=n.split("/").filter(Boolean).map((a)=>{let u=ms.test(a);if(u)s++;let c=a.match(gs);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 Yt.set(e,o),o}function Rs(e){let t=er.get(e);if(t!==void 0)return t;let r;try{r=new RegExp(`^${e}$`)}catch{r=null}return er.set(e,r),r}function H(e,t,r,n){let s=fs(e);if(s.isWildcard&&t.startsWith(s.wildcardBase))return!0;let i=s.segments,o=ce(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=Rs(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 ce(e.join("/"))}function ao(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 tr(e){try{return await Bun.file(e).exists()}catch{return!1}}async function rt(e,t,r){if(r.some((n)=>e.endsWith(n))){let n=ce(Zt(t,e));if(await tr(n))return n;return null}for(let n of r){let s=ce(Zt(t,`${e}${n}`));if(await tr(s))return s}return null}function rr(e,t){let r=e.replace(/\{\{([^}]+)\}\}/g,(n,s)=>{let i=s.trim(),o=nt(t,i);return o!==void 0?String(o):n});return r=ys(r,t),r=ws(r,t),r}function ys(e,t){return e.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(r,n,s,i="")=>{let o=n.trim();return nt(t,o)?s:i})}function ws(e,t){return e.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(r,n,s)=>{let i=nt(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 nt(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={...Vt.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=jt(t,this.modelBindings);e.push(r)}if(this.throttleConfig){let t=Y(this.throttleConfig);e.push(t)}if(this.cacheConfig){let t=Wt(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 nr{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 sr{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 ir{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 le{routes=[];globalMiddleware=[];subdomainRouter=new et;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 ir(this,t)}when(e){return new nr(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 sr(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 le;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 ue(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 le;t(r);let n=k.parseDomainPattern(e),s=new ue(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 bs={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}},Ts={route:(e,t={},r={})=>{let n=tt(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"}})},xs=new le;function or(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 ar(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 ur(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 vs(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
94
  Tried paths: ${i.join(", ")}
95
- Last error: ${o?.message||"Unknown error"}`)}function ur(e){return typeof e==="function"&&!e.prototype?.handle}async function le(e,t,r){if(e instanceof Response)return e.clone();if(ur(e)){let n=await e(t);return E(n)}if(typeof e==="string")return vs(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 vs(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}".
95
+ Last error: ${o?.message||"Unknown error"}`)}function cr(e){return typeof e==="function"&&!e.prototype?.handle}async function de(e,t,r){if(e instanceof Response)return e.clone();if(cr(e)){let n=await e(t);return E(n)}if(typeof e==="string")return Cs(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 Cs(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
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 xs(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 Cs(e){return(t,r)=>le(t,r,e)}function cr(e,t){if(e instanceof Response)return async()=>e.clone();if(ur(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)=>le(e,r,t)}function lr(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 le(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 dr{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 pr=new dr;function hr(e){Object.defineProperties(e.prototype,{modelRegistry:{value:pr,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 nt{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 u=e.getRoute(s);if(u)return{route:u.route,params:n,score:u.priority};return null}let i=t[r],o=e.children.get(i);if(o){let u=this.matchSegments(o,t,r+1,n,s);if(u)return u}let a=e.paramChild;if(a&&a.paramName&&(!a.pattern||a.pattern.test(i))){let u=n[a.paramName];n[a.paramName]=i;let c=this.matchSegments(a,t,r+1,n,s);if(c)return c;if(u===void 0)delete n[a.paramName];else n[a.paramName]=u}if(e.wildcardChild){let u=e.wildcardChild.getRoute(s);if(u)return n[e.wildcardChild.paramName??"wildcard"]=t.slice(r).join("/"),{route:u.route,params:n,score:u.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 $e{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 nt}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),T=t?.[m]??y??"[^/]+",V=`(?<${m}>${T})`,fe=c.startsWith("/")?"/":"";return p?`(?:${fe}${V})?`:`${fe}${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 gr(e){Object.defineProperties(e.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new $e({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 $e({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 mr(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,T)=>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 fr(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}})}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?Y(e):{maxAttempts:60,windowMs:60000};return Z({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 wr(this,t)}when(e){return new Rr(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 yr(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=Oe(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(`
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 vs(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 Ps(e){return(t,r)=>de(t,r,e)}function lr(e,t){if(e instanceof Response)return async()=>e.clone();if(cr(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)=>de(e,r,t)}function dr(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 de(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 pr{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 hr=new pr;function gr(e){Object.defineProperties(e.prototype,{modelRegistry:{value:hr,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 st{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 st}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),T=t?.[m]??y??"[^/]+",V=`(?<${m}>${T})`,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 mr(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 fr(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,T)=>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 Rr(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}})}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 br(this,t)}when(e){return new yr(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 wr(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
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((c)=>{let l=c.trim().split("=");if(l.length>=2){let d=l[0].trim(),p=l.slice(1).join("=").trim();r[d]=decodeURIComponent(p)}});return r},s=new URL(e.url),i={};s.searchParams.forEach((u,c)=>{i[c]=u});let o={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:i,jsonBody:null,formBody:null,_cookiesToSet:[],_cookiesToDelete:[]},a=()=>{let u={};for(let[c,l]of Object.entries(i))u[c]=l;if(o.jsonBody&&typeof o.jsonBody==="object")for(let[c,l]of Object.entries(o.jsonBody))u[c]=l;if(o.formBody&&typeof o.formBody==="object")for(let[c,l]of Object.entries(o.formBody))u[c]=l;for(let[c,l]of Object.entries(t))u[c]=l;return u};return o.cookies=ve({read:n,write:(u,c,l)=>{o._cookiesToSet.push({name:u,value:c,options:l})},remove:(u,c)=>{o._cookiesToDelete.push({name:u,options:c})}}),o.get=(u,c)=>{let d=a()[u];return d!==void 0?d:c},o.input=(u,c)=>{let d=a()[u];return d!==void 0?d:c},o.all=()=>a(),o.only=(u)=>{let c=a(),l={};for(let d of u)if(d in c)l[d]=c[d];return l},o.except=(u)=>{let l={...a()};for(let d of u)delete l[d];return l},o.has=(u)=>{let c=a();if(Array.isArray(u))return u.every((l)=>(l in c)&&c[l]!==void 0);return u in c&&c[u]!==void 0},o.hasAny=(u)=>{let c=a();return u.some((l)=>(l in c)&&c[l]!==void 0)},o.filled=(u)=>{let c=a(),l=(d)=>{let p=c[d];return p!==void 0&&p!==null&&p!==""&&!(Array.isArray(p)&&p.length===0)};if(Array.isArray(u))return u.every(l);return l(u)},o.missing=(u)=>{let c=a();if(Array.isArray(u))return u.every((l)=>!(l in c)||c[l]===void 0);return!(u in c)||c[u]===void 0},o.string=(u,c="")=>{let d=a()[u];return d!==void 0&&d!==null?String(d):c},o.integer=(u,c=0)=>{let d=a()[u],p=Number.parseInt(String(d),10);return Number.isNaN(p)?c:p},o.float=(u,c=0)=>{let d=a()[u],p=Number.parseFloat(String(d));return Number.isNaN(p)?c:p},o.boolean=(u,c=!1)=>{let d=a()[u];if(d===void 0||d===null)return c;if(typeof d==="boolean")return d;if(d==="true"||d==="1"||d===1)return!0;if(d==="false"||d==="0"||d===0)return!1;return c},o.array=(u)=>{let l=a()[u];if(Array.isArray(l))return l;return l!==void 0&&l!==null?[l]:[]},o.bearerToken=()=>{let u=e.headers.get("authorization")||e.headers.get("Authorization")||"";if(u.startsWith("Bearer "))return u.substring(7);return null},o.header=(u)=>e.headers.get(u)||e.headers.get(u.toLowerCase())||null,o.cookie=(u,c)=>{let l=n()[u];return l!==void 0?l:c??null},o.getParam=(u,c)=>{let l=t?.[u];return l!==void 0?l:c},o.getParamAsInt=(u)=>{let c=t?.[u];if(c===void 0||c.trim()==="")return null;let l=Number(c);return Number.isSafeInteger(l)?l:null},o.params=t||{},o}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 Rr{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 yr{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 wr{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 st=null;function Ps(){if(st===null)st=new w;return st}function Ms(e,t={}){if(typeof e.bearerToken==="function")return e;return Ps().enhanceRequest(e,t)}var Es=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,Ss=/bot|crawler|spider|crawling/i,Be=new Map;function he(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 xr{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 de=new xr,br=Symbol("bunRouterMacroProto"),it=Symbol("bunRouterMacroBase"),De=new WeakMap,Tr=-1;class x{static macro(e,t){de.register(e,t)}static macroAccessor(e,t){de.register(e,t,!0)}static applyMacros(e){let t=de.getEpoch();if(t!==Tr)De=new WeakMap,Tr=t;let r=Object.getPrototypeOf(e)??Object.prototype;if(r[br]){if(De.get(r[it])===r)return e;r=r[it]}let n=De.get(r);if(!n){n=Object.create(r);for(let s of de.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,br,{value:!0}),Object.defineProperty(n,it,{value:r}),De.set(r,n)}return Object.setPrototypeOf(e,n),e}static hasMacro(e){return de.has(e)}}var pe={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[pe.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 he(this).pathname},fullUrl(){return this.url},root(){let e=he(this);return`${e.protocol}//${e.host}`},is(e){let t=this.path(),r=Be.get(e);if(!r){let n=e.replace(/\*/g,".*").replace(/\?/g,".");if(r=new RegExp(`^${n}$`),Be.size>=1000)Be.clear();Be.set(e,r)}return r.test(t)},route(){return this.routeName||null},fingerprint(){let e=he(this),t={method:this.method,path:e.pathname,query:e.search,ip:pe.ip.call(this)};return btoa(JSON.stringify(t))},signature(e){let t=`${this.method}${this.url}${pe.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=pe.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(pe).forEach(([e,t])=>{x.macro(e,t)})}ks();if(!x.hasMacro("getParam"))x.macro("getParam",function(e,t){let r=this.params?.[e];return r!==void 0?r:t});if(!x.hasMacro("getParamAsInt"))x.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(!x.hasMacro("get"))x.macro("get",function(e,t){let r=he(this).searchParams.get(e);return r!==null&&r!==void 0?r:t});x.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 vr(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(`
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((c)=>{let l=c.trim().split("=");if(l.length>=2){let d=l[0].trim(),p=l.slice(1).join("=").trim();r[d]=decodeURIComponent(p)}});return r},s=new URL(e.url),i={};s.searchParams.forEach((u,c)=>{i[c]=u});let o={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:i,jsonBody:null,formBody:null,_cookiesToSet:[],_cookiesToDelete:[]},a=()=>{let u={};for(let[c,l]of Object.entries(i))u[c]=l;if(o.jsonBody&&typeof o.jsonBody==="object")for(let[c,l]of Object.entries(o.jsonBody))u[c]=l;if(o.formBody&&typeof o.formBody==="object")for(let[c,l]of Object.entries(o.formBody))u[c]=l;for(let[c,l]of Object.entries(t))u[c]=l;return u};return o.cookies=Ce({read:n,write:(u,c,l)=>{o._cookiesToSet.push({name:u,value:c,options:l})},remove:(u,c)=>{o._cookiesToDelete.push({name:u,options:c})}}),o.get=(u,c)=>{let d=a()[u];return d!==void 0?d:c},o.input=(u,c)=>{let d=a()[u];return d!==void 0?d:c},o.all=()=>a(),o.only=(u)=>{let c=a(),l={};for(let d of u)if(d in c)l[d]=c[d];return l},o.except=(u)=>{let l={...a()};for(let d of u)delete l[d];return l},o.has=(u)=>{let c=a();if(Array.isArray(u))return u.every((l)=>(l in c)&&c[l]!==void 0);return u in c&&c[u]!==void 0},o.hasAny=(u)=>{let c=a();return u.some((l)=>(l in c)&&c[l]!==void 0)},o.filled=(u)=>{let c=a(),l=(d)=>{let p=c[d];return p!==void 0&&p!==null&&p!==""&&!(Array.isArray(p)&&p.length===0)};if(Array.isArray(u))return u.every(l);return l(u)},o.missing=(u)=>{let c=a();if(Array.isArray(u))return u.every((l)=>!(l in c)||c[l]===void 0);return!(u in c)||c[u]===void 0},o.string=(u,c="")=>{let d=a()[u];return d!==void 0&&d!==null?String(d):c},o.integer=(u,c=0)=>{let d=a()[u],p=Number.parseInt(String(d),10);return Number.isNaN(p)?c:p},o.float=(u,c=0)=>{let d=a()[u],p=Number.parseFloat(String(d));return Number.isNaN(p)?c:p},o.boolean=(u,c=!1)=>{let d=a()[u];if(d===void 0||d===null)return c;if(typeof d==="boolean")return d;if(d==="true"||d==="1"||d===1)return!0;if(d==="false"||d==="0"||d===0)return!1;return c},o.array=(u)=>{let l=a()[u];if(Array.isArray(l))return l;return l!==void 0&&l!==null?[l]:[]},o.bearerToken=()=>{let u=e.headers.get("authorization")||e.headers.get("Authorization")||"";if(u.startsWith("Bearer "))return u.substring(7);return null},o.header=(u)=>e.headers.get(u)||e.headers.get(u.toLowerCase())||null,o.cookie=(u,c)=>{let l=n()[u];return l!==void 0?l:c??null},o.getParam=(u,c)=>{let l=t?.[u];return l!==void 0?l:c},o.getParamAsInt=(u)=>{let c=t?.[u];if(c===void 0||c.trim()==="")return null;let l=Number(c);return Number.isSafeInteger(l)?l:null},o.params=t||{},o}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 yr{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 wr{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 br{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 it=null;function Ms(){if(it===null)it=new w;return it}function Es(e,t={}){if(typeof e.bearerToken==="function")return e;return Ms().enhanceRequest(e,t)}var Ss=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,ks=/bot|crawler|spider|crawling/i,De=new Map;function ge(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 vr{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 pe=new vr,Tr=Symbol("bunRouterMacroProto"),ot=Symbol("bunRouterMacroBase"),Fe=new WeakMap,xr=-1;class x{static macro(e,t){pe.register(e,t)}static macroAccessor(e,t){pe.register(e,t,!0)}static applyMacros(e){let t=pe.getEpoch();if(t!==xr)Fe=new WeakMap,xr=t;let r=Object.getPrototypeOf(e)??Object.prototype;if(r[Tr]){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 pe.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,Tr,{value:!0}),Object.defineProperty(n,ot,{value:r}),Fe.set(r,n)}return Object.setPrototypeOf(e,n),e}static hasMacro(e){return pe.has(e)}}var he={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 Ss.test(this.headers.get("user-agent")||"")},isBot(){return ks.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[he.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 ge(this).pathname},fullUrl(){return this.url},root(){let e=ge(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=ge(this),t={method:this.method,path:e.pathname,query:e.search,ip:he.ip.call(this)};return btoa(JSON.stringify(t))},signature(e){let t=`${this.method}${this.url}${he.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=he.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 Hs(){Object.entries(he).forEach(([e,t])=>{x.macro(e,t)})}Hs();if(!x.hasMacro("getParam"))x.macro("getParam",function(e,t){let r=this.params?.[e];return r!==void 0?r:t});if(!x.hasMacro("getParamAsInt"))x.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(!x.hasMacro("get"))x.macro("get",function(e,t){let r=ge(this).searchParams.get(e);return r!==null&&r!==void 0?r:t});x.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 Cr(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
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 Pe(t,()=>r.handleRequestImpl(t));return await Mt(n,t,r.config?.compression??{})},writable:!0,configurable:!0},_dispatchMatchedRoute:{async value(t,r,n){let s=this.enhanceRequest(r,n);Me(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=cr(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)=>Pe(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,{});Me(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 x.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 Hs}from"path";function Cr(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 tt(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 tt(Hs("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=tr(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=Ee(h,m);let y=new Headers;if(y.set("Content-Type","text/html; charset=utf-8"),c.headers)for(let[T,V]of Object.entries(c.headers))y.set(T,V);return new Response(h,{status:c.status||200,headers:y})};return this.get(t,p,l,d),this},writable:!0,configurable:!0}})}function Pr(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 As from"process";class Mr{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 ot=new Mr;class ge extends Response{static macro(e,t){ot.register(e,t),Response[e]=t}static callMacro(e,...t){let r=ot.get(e);if(!r)throw Error(`Response macro "${e}" not found`);return r.handler(...t)}static hasMacro(e){return ot.has(e)}}function Fe(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}=Fe(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}=Fe(t,r);return new Response(e,{status:n,headers:{"Content-Type":"text/html",...s}})},text:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Fe(t,r);return new Response(e,{status:n,headers:{"Content-Type":"text/plain",...s}})},xml:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Fe(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}
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 Et(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=lr(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 x.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 As}from"path";function Pr(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 rt(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 rt(As("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=rr(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[T,V]of Object.entries(c.headers))y.set(T,V);return new Response(h,{status:c.status||200,headers:y})};return this.get(t,p,l,d),this},writable:!0,configurable:!0}})}function Mr(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 qs from"process";class Er{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 at=new Er;class me extends Response{static macro(e,t){at.register(e,t),Response[e]=t}static callMacro(e,...t){let r=at.get(e);if(!r)throw Error(`Response macro "${e}" not found`);return r.handler(...t)}static hasMacro(e){return at.has(e)}}function Ne(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}=Ne(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}=Ne(t,r);return new Response(e,{status:n,headers:{"Content-Type":"text/html",...s}})},text:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Ne(t,r);return new Response(e,{status:n,headers:{"Content-Type":"text/plain",...s}})},xml:(e,t=200,r={})=>{let{status:n,mergedHeaders:s}=Ne(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
102
  `;if(t)n+=`event: ${t}
103
103
  `;return n+=`data: ${e}
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:As.uptime?.()||0};return new Response(JSON.stringify(n),{status:r,headers:{"Content-Type":"application/json"}})}};function qs(){Object.entries(A).forEach(([e,t])=>{ge.macro(e,t)})}qs();var Os=/^[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,$s={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"&&Os.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."}},Yo={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 Ne{rules={};config;constructor(e={}){this.config={stopOnFirstFailure:!1,bail:!1,...e},this.registerRules($s)}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 se("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 ea=new Ne;function Ue(e,t){let r=new Ne(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 se)throw i;throw new se("Validation error occurred")}}}class at{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 ta(){return new at}var ra={rules(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n instanceof at?n.build():n;return t},async validateValue(e,t,r="value"){return(await new Ne().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(Ue(this.validationRules,this.validatorConfig));return e.push(async(t,r)=>(x.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 Sr{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 ut(){return async(e,t)=>(x.applyMacros(e),e.startTime=Date.now(),await t())}class kr{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 Ue(this.rules,this.config)}}function aa(){return new kr}var ua={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 ge.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 ca(){return new Sr}var Er={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)=>Er.when((r)=>!e(r),t),group:(e)=>Er.compose(...e)},la={api:()=>[ut(),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),ge.callMacro("error","Internal server error",void 0,500)}}],web:()=>[ut(),async(e,t)=>(e.session={},await t())],validation:(e,t)=>[ut(),Ue(e,t)]};or(w);ar(w);fr(w);gr(w);lr(w);Cr(w);Pr(w);Nt(w);ir(w);vr(w);mr(w);hr(w);Ft(w);Ot(w);class ct{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 ct;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 lt}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:K(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=K({...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 Na={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 b(e="GET",t="/",r={}){return new q(e,t,r).build()}class me{request;constructor(e){this.request=e||b()}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=K({...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 dt{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 pt{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 pt(e).createSession()}}var La={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)=>lt(async(t,r)=>{if(e)return t.user=e,await r();return new Response("Unauthorized",{status:401})}),roleMiddleware:(e)=>lt(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)=>lt(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()})},za={authenticatedRequest:(e,t)=>new me(t).as(e).getRequest(),jwtRequest:(e={},t)=>{let n=new dt().generateToken(e);return new me(t).withJWT(n).getRequest()},sessionRequest:(e={},t)=>new me(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 Ga(e){return new me(e)}function Wa(e){return new dt(e)}function Va(e){return new pt(e)}import{mock as z}from"bun:test";class _{request;files;constructor(e){this.request=e||b(),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 ht{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 Qa={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(!ht.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(!ht.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}})}},Za={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"})},Ya={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 eu(e){return new _(e)}var tu={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 Bs}from"bun:test";class Hr{middleware;context;constructor(e){this.middleware=e,this.context=this.createContext()}createContext(){let e=b(),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 iu(e){return new Hr(e)}var ou={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 Ar{middlewares;request;finalHandler;constructor(e){this.middlewares=e,this.request=b(),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 au(e){return new Ar(e)}function uu(e){return Bs(e,"call")}function cu(){let e=v(async(t,r)=>await r());return{middleware:e,spy:e}}async function lu(e,t=1000){let r=[],n=b(),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 Ds{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 Fs{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 Ns{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 qr{request;options;constructor(e={}){this.options=e,this.request=b()}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 gu={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}}}},mu={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 Or{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 fu={testRoute:async(e,t,r)=>{let n=b("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 Ru(e){return new qr(e)}function yu(){return new Or}var Us=async(e,t)=>e.userId===t.id,wu={testUserScoped:async(e,t,r=Us)=>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 Is}from"bun:test";import G from"process";class Br{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 te{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 Cu={routeHandler:async(e,t=1000)=>{let r=[],n=b();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=b(),s=Is(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}}},Pu={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=b();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}}},Mu={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 te(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 te(e,{duration:30000,concurrency:r.normalLoad}).run(t),o=await new te(e,{duration:r.spikeDuration,concurrency:r.spikeLoad}).run(t),u=await new te(e,{duration:30000,concurrency:r.normalLoad}).run(t);return{normalPhase:s,spikePhase:o,recoveryPhase:u}}},Eu={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 Su(){return new Br}function ku(e,t){return new te(e,t)}var $r={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:$r.getCurrentMemoryUsage(),cpuUsage:$r.getCPUUsage()}),formatResults:(e)=>JSON.stringify(e,null,2)};class gt{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 Dr(e){let t=await e.text();return new gt(e,t)}function Au(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 gt(s,t)}class _e{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 Dr(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 _e(this.router,{...this.config,...e})}withHeaders(e){return new _e(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...e}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function Ie(e,t){return new _e(e,t)}var Bu={for:(e,t)=>Ie(e,t),withConfig:(e)=>(t)=>Ie(t,e),withAuth:(e,t="Bearer")=>(r)=>Ie(r).auth(e,t),withHeaders:(e)=>(t)=>Ie(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 Fr{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 Nu={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)})},Uu={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}},Iu={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}`)}},_u={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 Lu(e){return new Fr(e)}var zu={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 mt 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 Nr(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 Ur(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 _s(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 js(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=Ur(`${t}${Nr(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 _s(p);if(!p.ok){let h=new mt(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=Ur(`${t}${Nr(o,u)}`,c);return await r(d,{method:i,...l,headers:{...await n(),...l.headers},...e.credentials?{credentials:e.credentials}:{}})}}}function Ls(e){return e}var zs=["get","post","put","patch","delete"];function Gs(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 Ws(e){let t={};for(let r of zs)t[r]=(n,s,i)=>(Gs(e[r](n,s),r,n,i),t);return t}export{Rt as ApiKeyManager,Vr as Auth,me as AuthTester,Js as BindingBuilder,$s as BuiltInRules,Li as CacheInvalidation,Vs as Container,ul as ContentSecurityPolicy,Ys as ContextualContainer,jc as Cors,Lc as Csrf,ll as DDoSProtection,Sn as DEFAULT_COMPRESSION,Yo as DatabaseRules,nl as DatabaseSessionStore,ei as DefaultServiceProviderManager,$n as Dependencies,ae as DomainGroup,Kt as DomainGroupBuilder,k as DomainMatcher,la as EnhancementPresets,Zs as EnvironmentManager,vt as Errors,pl as FileSecurity,tl as FileSessionStore,hl as FileUpload,_ as FileUploadTester,ht as FileValidationTester,f as FluentRouteBuilder,ce as FluentRouter,Ds as GenericMockModel,wl as Helmet,Kc as InMemoryNonceStore,bl as InputValidation,ft as JWT,dt as JWTTester,zc as JsonBody,te as LoadTester,el as MemorySessionStore,Ar as MiddlewareChainTester,Bn as MiddlewareFactory,ct as MiddlewareGroupRegistry,Er as MiddlewareHelpers,Qe as MiddlewarePipeline,Hr as MiddlewareTester,Ns as MockPostClass,Fr as MockServerWebSocket,Fs as MockUserClass,qr as ModelBindingTester,Or as ModelResolverTester,yt as OAuth2Helper,xl as PerformanceAlerting,Cl as PerformanceDashboard,Ml as PerformanceMonitor,Br as PerformanceTester,Gc as RateLimit,Vt as RateLimitRegistry,Wi as RateLimitUtils,qe as RateLimiter,rl as RedisSessionStore,Vc as RequestId,Xc as RequestSigning,Sl as RequestTracer,Et as ResponseBuilder,C as RouteBuilder,Wt as RouteCacheFactory,Lt as RouteCacheKeyGenerator,zt as RouteCacheManager,ws as RouteFactory,Xt as RouteGroupBuilder,ua as RouteHelpers,w as Router,bs as RouterUtils,Hl as Security,ql as SecuritySuite,al as Session,il as SessionManager,pt as SessionTester,Jc as SignatureError,On as SkipConditions,Xi as SubdomainPatterns,Ye as SubdomainRouter,Ki as SubdomainUtils,_e as TestClient,q as TestRequestBuilder,gt as TestResponseWrapper,as as ThrottleFactory,mt as TypedClientError,Sr as ValidationFluentRouter,ra as ValidationHelpers,kr as ValidationMiddlewareBuilder,at as ValidationRuleBuilder,Ne as Validator,O as WebSocketTester,Ic as apiKeyAuth,Xe as appendVary,Ms as applyRequestEnhancements,Ul as auth,za as authHelpers,La as authMocks,Fc as basicAuth,Nc as bearerAuth,lu as benchmarkMiddleware,Cu as benchmarkTests,Hi as buildUrlWithPreservedParams,ls as clearNamedRoutes,Mt as compressResponse,Oc as config,mu as constraintHelpers,cl as contentSecurityPolicy,$l as cors,Ga as createAuthTester,Qs as createContainer,ve as createCookieAccessor,ut as createEnhancementMiddleware,eu as createFileUploadTester,ca as createFluentRouter,Cs as createHandlerResolver,K as createInMemoryCookieAccessor,Wa as createJWTTester,ku as createLoadTester,cu as createMiddlewareSpy,b as createMockRequest,Au as createMockResponse,Lu as createMockServerWebSocket,Ru as createModelBindingTester,yu as createModelResolverTester,no as createPathRegex,Su as createPerformanceTester,Z as createRateLimitMiddleware,Gt as createRouteCacheMiddleware,sl as createSessionStore,Va as createSessionTester,Ji as createSubdomainMiddleware,Ie as createTestClient,Dr as createTestResponse,js as createTypedClient,Ws as createTypedRouter,Ue as createValidationMiddleware,ju as createWebSocketTester,Nl as csrf,dl as ddosProtection,Ac as defaultConfig,ki as defaultQueryPreservationConfig,Ls as defineEndpoint,yl as documentUpload,Mn as enableRequestContext,Dc as extractApiKey,$c as extractBasicAuth,Bc as extractBearerToken,Oe as extractParamNames,er as fileExists,gl as fileUpload,Ya as fileUploadAssertions,Qa as fileUploadMocks,Za as fileUploadScenarios,Wn as generateQueryPreservationScript,ol as generateSessionId,qc as getConfig,Ks as getContainer,Ct as getCurrentRequest,et as getNamedRoutePath,cs as getNamedRoutes,Dn as globalMiddlewarePipeline,ea as globalValidator,Rl as imageUpload,Ee as injectQueryPreservationScript,Tl as inputValidation,ps as isActionClass,Pt as isCompressible,ro as isRouteHandler,F as joinPaths,Bl as jsonBody,Uc as jwtAuth,H as matchPath,Pu as memoryTests,Il as middleware,P as middlewareGroups,ou as mockMiddleware,gu as modelMocks,fl as multipleFileUpload,kn as negotiateEncoding,ue as normalizePath,_c as oauth2Auth,Y as parseThrottleString,An as peekBody,vl as performanceAlerting,Eu as performanceAssertions,Pl as performanceDashboard,El as performanceMonitor,$r as performanceUtils,tr as processHtmlTemplate,Wc as rateLimit,Jt as rateLimitRegistry,U as registerNamedRoute,En as request,Dl as requestId,Qc as requestSigning,kl as requestTracer,le as resolveHandler,tt as resolveViewPath,R as response,xi as responseBuilder,Q as routeCacheManager,fu as routeModelHelpers,Ts as router,ta as rule,Pe as runWithRequest,wu as scopedBindingHelpers,Al as security,Ol as securitySuite,Fl as session,Xs as setContainer,Me as setCurrentRequest,Hn as shouldCompress,Zc as signRequest,ml as singleFileUpload,uu as spyOnMiddleware,Mu as stressTests,Bu as testClient,tu as testFiles,iu as testMiddleware,au as testMiddlewareChain,Na as testRequest,to as toActionPath,ds as url,aa as validate,so as validatePath,Yc as verifySignature,E as wrapResponse,Iu as wsAssertions,Nu as wsHandlerMocks,_u as wsPerformance,Uu as wsTestScenarios,zu as wsTestUtils};
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:qs.uptime?.()||0};return new Response(JSON.stringify(n),{status:r,headers:{"Content-Type":"application/json"}})}};function Os(){Object.entries(A).forEach(([e,t])=>{me.macro(e,t)})}Os();var $s=/^[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,Bs={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"&&$s.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."}},na={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 Ue{rules={};config;constructor(e={}){this.config={stopOnFirstFailure:!1,bail:!1,...e},this.registerRules(Bs)}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 ie("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 sa=new Ue;function Ie(e,t){let r=new Ue(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 ie)throw i;throw new ie("Validation error occurred")}}}class ut{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 ia(){return new ut}var oa={rules(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n instanceof ut?n.build():n;return t},async validateValue(e,t,r="value"){return(await new Ue().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(Ie(this.validationRules,this.validatorConfig));return e.push(async(t,r)=>(x.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 kr{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 ct(){return async(e,t)=>(x.applyMacros(e),e.startTime=Date.now(),await t())}class Hr{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 Ie(this.rules,this.config)}}function da(){return new Hr}var pa={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 ha(){return new kr}var Sr={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)=>Sr.when((r)=>!e(r),t),group:(e)=>Sr.compose(...e)},ga={api:()=>[ct(),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:()=>[ct(),async(e,t)=>(e.session={},await t())],validation:(e,t)=>[ct(),Ie(e,t)]};ar(w);ur(w);Rr(w);mr(w);dr(w);Pr(w);Mr(w);Ut(w);or(w);Cr(w);fr(w);gr(w);Nt(w);$t(w);class lt{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 lt;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 dt}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 ja={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 b(e="GET",t="/",r={}){return new q(e,t,r).build()}class fe{request;constructor(e){this.request=e||b()}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 pt{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 ht{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 ht(e).createSession()}}var Va={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)=>dt(async(t,r)=>{if(e)return t.user=e,await r();return new Response("Unauthorized",{status:401})}),roleMiddleware:(e)=>dt(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)=>dt(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()})},Ja={authenticatedRequest:(e,t)=>new fe(t).as(e).getRequest(),jwtRequest:(e={},t)=>{let n=new pt().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 Ka(e){return new fe(e)}function Xa(e){return new pt(e)}function Qa(e){return new ht(e)}import{mock as z}from"bun:test";class _{request;files;constructor(e){this.request=e||b(),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 gt{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 tu={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(!gt.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(!gt.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}})}},ru={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"})},nu={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 su(e){return new _(e)}var iu={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 Ds}from"bun:test";class Ar{middleware;context;constructor(e){this.middleware=e,this.context=this.createContext()}createContext(){let e=b(),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 cu(e){return new Ar(e)}var lu={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 qr{middlewares;request;finalHandler;constructor(e){this.middlewares=e,this.request=b(),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 du(e){return new qr(e)}function pu(e){return Ds(e,"call")}function hu(){let e=v(async(t,r)=>await r());return{middleware:e,spy:e}}async function gu(e,t=1000){let r=[],n=b(),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 Fs{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 Ns{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 Us{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 Or{request;options;constructor(e={}){this.options=e,this.request=b()}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 yu={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}}}},wu={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 $r{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 bu={testRoute:async(e,t,r)=>{let n=b("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 Tu(e){return new Or(e)}function xu(){return new $r}var Is=async(e,t)=>e.userId===t.id,vu={testUserScoped:async(e,t,r=Is)=>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 _s}from"bun:test";import G from"process";class Dr{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 re{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 Su={routeHandler:async(e,t=1000)=>{let r=[],n=b();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=b(),s=_s(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}}},ku={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=b();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}}},Hu={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 re(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 re(e,{duration:30000,concurrency:r.normalLoad}).run(t),o=await new re(e,{duration:r.spikeDuration,concurrency:r.spikeLoad}).run(t),u=await new re(e,{duration:30000,concurrency:r.normalLoad}).run(t);return{normalPhase:s,spikePhase:o,recoveryPhase:u}}},Au={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 qu(){return new Dr}function Ou(e,t){return new re(e,t)}var Br={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:Br.getCurrentMemoryUsage(),cpuUsage:Br.getCPUUsage()}),formatResults:(e)=>JSON.stringify(e,null,2)};class mt{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 Fr(e){let t=await e.text();return new mt(e,t)}function Bu(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 mt(s,t)}class je{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 Fr(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 je(this.router,{...this.config,...e})}withHeaders(e){return new je(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...e}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function _e(e,t){return new je(e,t)}var Uu={for:(e,t)=>_e(e,t),withConfig:(e)=>(t)=>_e(t,e),withAuth:(e,t="Bearer")=>(r)=>_e(r).auth(e,t),withHeaders:(e)=>(t)=>_e(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 Nr{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 ju={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)})},Lu={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}},zu={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}`)}},Gu={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 Wu(){return new O}function Vu(e){return new Nr(e)}var Ju={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 ft 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 Ur(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 Ir(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 js(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 Ls(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=Ir(`${t}${Ur(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 js(p);if(!p.ok){let h=new ft(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=Ir(`${t}${Ur(o,u)}`,c);return await r(d,{method:i,...l,headers:{...await n(),...l.headers},...e.credentials?{credentials:e.credentials}:{}})}}}function zs(e){return e}var Gs=["get","post","put","patch","delete"];function Ws(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 Vs(e){let t={};for(let r of Gs)t[r]=(n,s,i)=>(Ws(e[r](n,s),r,n,i),t);return t}export{yt as ApiKeyManager,Jr as Auth,fe as AuthTester,Ks as BindingBuilder,Bs as BuiltInRules,Gi as CacheInvalidation,Js as Container,hl as ContentSecurityPolicy,ei as ContextualContainer,Vc as Cors,Jc as Csrf,ml as DDoSProtection,kn as DEFAULT_COMPRESSION,na as DatabaseRules,ul as DatabaseSessionStore,ti as DefaultServiceProviderManager,Bn as Dependencies,ue as DomainGroup,Xt as DomainGroupBuilder,k as DomainMatcher,ga as EnhancementPresets,Ys as EnvironmentManager,Ct as Errors,Rl as FileSecurity,ol as FileSessionStore,yl as FileUpload,_ as FileUploadTester,gt as FileValidationTester,f as FluentRouteBuilder,le as FluentRouter,Fs as GenericMockModel,Cl as Helmet,el as InMemoryNonceStore,Pl as InputValidation,Rt as JWT,pt as JWTTester,Kc as JsonBody,re as LoadTester,il as MemorySessionStore,qr as MiddlewareChainTester,Dn as MiddlewareFactory,lt as MiddlewareGroupRegistry,Sr as MiddlewareHelpers,Ze as MiddlewarePipeline,Ar as MiddlewareTester,Us as MockPostClass,Nr as MockServerWebSocket,Ns as MockUserClass,Or as ModelBindingTester,$r as ModelResolverTester,wt as OAuth2Helper,El as PerformanceAlerting,kl as PerformanceDashboard,Al as PerformanceMonitor,Dr as PerformanceTester,Xc as RateLimit,Jt as RateLimitRegistry,Ji as RateLimitUtils,Oe as RateLimiter,al as RedisSessionStore,Zc as RequestId,tl as RequestSigning,Ol as RequestTracer,St as ResponseBuilder,C as RouteBuilder,Vt as RouteCacheFactory,zt as RouteCacheKeyGenerator,Gt as RouteCacheManager,bs as RouteFactory,Qt as RouteGroupBuilder,pa as RouteHelpers,w as Router,Ts as RouterUtils,Bl as Security,Fl as SecuritySuite,pl as Session,ll as SessionManager,ht as SessionTester,Yc as SignatureError,$n as SkipConditions,Zi as SubdomainPatterns,et as SubdomainRouter,Qi as SubdomainUtils,je as TestClient,q as TestRequestBuilder,mt as TestResponseWrapper,us as ThrottleFactory,ft as TypedClientError,kr as ValidationFluentRouter,oa as ValidationHelpers,Hr as ValidationMiddlewareBuilder,ut as ValidationRuleBuilder,Ue as Validator,O as WebSocketTester,Gc as apiKeyAuth,Qe as appendVary,Es as applyRequestEnhancements,zl as auth,Ja as authHelpers,Va as authMocks,jc as basicAuth,Lc as bearerAuth,gu as benchmarkMiddleware,Su as benchmarkTests,qi as buildUrlWithPreservedParams,ds as clearNamedRoutes,Et as compressResponse,Nc as config,wu as constraintHelpers,gl as contentSecurityPolicy,Ul as cors,Ka as createAuthTester,Zs as createContainer,Ce as createCookieAccessor,ct as createEnhancementMiddleware,su as createFileUploadTester,ha as createFluentRouter,Ps as createHandlerResolver,X as createInMemoryCookieAccessor,Xa as createJWTTester,Ou as createLoadTester,hu as createMiddlewareSpy,b as createMockRequest,Bu as createMockResponse,Vu as createMockServerWebSocket,Tu as createModelBindingTester,xu as createModelResolverTester,oo as createPathRegex,qu as createPerformanceTester,Y as createRateLimitMiddleware,Wt as createRouteCacheMiddleware,cl as createSessionStore,Qa as createSessionTester,Xi as createSubdomainMiddleware,_e as createTestClient,Fr as createTestResponse,Ls as createTypedClient,Vs as createTypedRouter,Ie as createValidationMiddleware,Wu as createWebSocketTester,Ll as csrf,fl as ddosProtection,K as decodeParam,Dc as defaultConfig,Ai as defaultQueryPreservationConfig,zs as defineEndpoint,vl as documentUpload,En as enableRequestContext,_c as extractApiKey,Uc as extractBasicAuth,Ic as extractBearerToken,$e as extractParamNames,tr as fileExists,wl as fileUpload,nu as fileUploadAssertions,tu as fileUploadMocks,ru as fileUploadScenarios,Vn as generateQueryPreservationScript,dl as generateSessionId,Fc as getConfig,Xs as getContainer,Pt as getCurrentRequest,tt as getNamedRoutePath,ls as getNamedRoutes,Fn as globalMiddlewarePipeline,sa as globalValidator,xl as imageUpload,Se as injectQueryPreservationScript,Ml as inputValidation,hs as isActionClass,Mt as isCompressible,io as isRouteHandler,F as joinPaths,Il as jsonBody,zc as jwtAuth,H as matchPath,ku as memoryTests,Gl as middleware,P as middlewareGroups,lu as mockMiddleware,yu as modelMocks,Tl as multipleFileUpload,Hn as negotiateEncoding,ce as normalizePath,Wc as oauth2Auth,ee as parseThrottleString,qn as peekBody,Sl as performanceAlerting,Au as performanceAssertions,Hl as performanceDashboard,ql as performanceMonitor,Br as performanceUtils,rr as processHtmlTemplate,Qc as rateLimit,Kt as rateLimitRegistry,U as registerNamedRoute,Sn as request,_l as requestId,rl as requestSigning,$l as requestTracer,de as resolveHandler,rt as resolveViewPath,R as response,Ci as responseBuilder,Z as routeCacheManager,bu as routeModelHelpers,xs as router,ia as rule,Me as runWithRequest,vu as scopedBindingHelpers,Dl as security,Nl as securitySuite,jl as session,Qs as setContainer,Ee as setCurrentRequest,An as shouldCompress,nl as signRequest,bl as singleFileUpload,pu as spyOnMiddleware,Hu as stressTests,Uu as testClient,iu as testFiles,cu as testMiddleware,du as testMiddlewareChain,ja as testRequest,so as toActionPath,ps as url,da as validate,ao as validatePath,sl as verifySignature,E as wrapResponse,zu as wsAssertions,ju as wsHandlerMocks,Gu as wsPerformance,Lu as wsTestScenarios,Ju as wsTestUtils};