@stacksjs/bun-router 0.1.18 → 0.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/chunk-mpyfk9k4.js +357 -0
- package/dist/chunk-q4ktdehf.js +82 -0
- package/dist/chunk-sr7yt36v.js +102 -0
- package/dist/cli.js +8 -8
- package/dist/container/index.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +4 -103
- package/dist/response/markers.d.ts +2 -0
- package/dist/router/index.d.ts +1 -105
- package/dist/router/middleware-chain.d.ts +10 -0
- package/dist/router/router.d.ts +1 -1
- package/dist/router/runtime.d.ts +107 -0
- package/dist/runtime.d.ts +16 -0
- package/dist/runtime.js +2 -0
- package/package.json +11 -1
- package/dist/chunk-7s1kcj7w.js +0 -357
- package/dist/chunk-sccx6r6k.js +0 -82
package/dist/index.js
CHANGED
|
@@ -1,105 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{qe,s,me,wt,e,ge,W,fe,He,Be,je,Ue,Le,h,r,m,A,G,g,n,ye,f,_e,ze,Ve,u,O,I,F,bt,K,D,y,w,We,b,Ge,S,c,Ke,Je,Xe,Ye,Qe,E,R,Ze,N,et,q,tt,H,rt,B,nt,v,st,j,it,Rt,vt,xt,Tt,Ct,St,J}from"./chunk-7s1kcj7w.js";import{t,d,X,Y,Q,Z,x,ee,te,re,ne,T,C,se,ie,oe,i,P,p,ae,U,ce,le,ot,at,ct,a,_,we,be,Re,z,ue,de}from"./chunk-sccx6r6k.js";function Br(o){return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function hr(o){o=o.replace(/-/g,"+").replace(/_/g,"/");while(o.length%4)o+="=";return atob(o)}class cn{secret;constructor(o){this.secret=o}sign(o,l={}){let M={alg:l.algorithm||"HS256",typ:"JWT",...l.header},k=Math.floor(Date.now()/1000),L={...o,iat:k};if(l.expiresIn){let xe=typeof l.expiresIn==="string"?this.parseTimespan(l.expiresIn):l.expiresIn;L.exp=k+xe}if(l.notBefore){let xe=typeof l.notBefore==="string"?this.parseTimespan(l.notBefore):l.notBefore;L.nbf=k+xe}if(l.issuer)L.iss=l.issuer;if(l.subject)L.sub=l.subject;if(l.audience)L.aud=l.audience;if(l.jwtid)L.jti=l.jwtid;let V=Br(JSON.stringify(M)),pe=Br(JSON.stringify(L)),he=`${V}.${pe}`,Te=this.createSignature(he,this.secret,M.alg);return`${he}.${Te}`}verify(o,l={}){try{let M=o.split(".");if(M.length!==3)throw Error("Token structure invalid");let[k,L,V]=M,pe=JSON.parse(hr(k)),he=JSON.parse(hr(L));if(l.algorithms&&!l.algorithms.includes(pe.alg))throw Error(`Algorithm ${pe.alg} not allowed`);let Te=`${k}.${L}`,xe=this.createSignature(Te,this.secret,pe.alg),ve=Buffer.from(V),Pe=Buffer.from(xe);if(ve.length!==Pe.length||!s().timingSafeEqual(ve,Pe))throw Error("Invalid signature");let Ce=Math.floor(Date.now()/1000);if(he.exp&&!l.ignoreExpiration&&Ce>=he.exp)throw Error("Token expired");if(he.nbf&&Ce<he.nbf)throw Error("Token not active yet");if(he.iat&&he.iat>Ce)throw Error("Token used before issued");if(l.issuer&&he.iss!==l.issuer)throw Error("Invalid issuer");if(l.audience&&he.aud!==l.audience)throw Error("Invalid audience");if(l.subject&&he.sub!==l.subject)throw Error("Invalid subject");return he}catch{return null}}decode(o){try{let l=o.split(".");if(l.length!==3)return null;let[M,k]=l;return{header:JSON.parse(hr(M)),payload:JSON.parse(hr(k))}}catch{return null}}createSignature(o,l,M){return Br(JSON.stringify({data:o,secret:l.slice(0,5),alg:M}))}parseTimespan(o){let l=o.match(/^(\d+)\s*([smhd])$/i);if(!l)return Number.parseInt(o,10)||0;let M=Number.parseInt(l[1],10);switch(l[2].toLowerCase()){case"s":return M;case"m":return M*60;case"h":return M*60*60;case"d":return M*24*60*60;default:return M}}}class ln{keys;options;constructor(o={}){this.keys=new Map,this.options={source:"header",keyName:"X-API-Key",keyPrefix:"bun_",...o}}generateKey(o,l=[],M){let k=`${this.options.keyPrefix}${this.randomString(32)}`;return this.keys.set(k,{owner:o,scopes:l,expiresAt:M?new Date(Date.now()+M*1000):void 0}),k}validateKey(o,l=[]){let M=this.keys.get(o);if(!M)return!1;if(M.expiresAt&&M.expiresAt<new Date)return!1;if(l.length>0)return l.every((k)=>M.scopes.includes(k));return!0}getKeyInfo(o){return this.keys.get(o)||null}revokeKey(o){return this.keys.delete(o)}extractFromRequest(o){let{source:l,keyName:M}=this.options;switch(l){case"header":return o.headers.get(M||"X-API-Key")||null;case"query":return new URL(o.url).searchParams.get(M||"api_key")||null;case"cookie":if(o.cookies){let k=M||"api_key";if(typeof o.cookies.get==="function")return o.cookies.get(k)||null;return o.cookies[k]||null}return null;default:return null}}randomString(o){let M="";for(let k=0;k<o;k++)M+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62));return M}}class dn{config;constructor(o){this.config=o}getAuthorizationUrl(o={}){let l=new URLSearchParams({client_id:this.config.clientId,redirect_uri:this.config.redirectUri,response_type:"code",...o});if(this.config.scope)l.set("scope",this.config.scope);if(this.config.state)l.set("state",this.config.state);return`${this.config.authorizeUrl}?${l.toString()}`}async exchangeCodeForToken(o){let l=new URLSearchParams({grant_type:"authorization_code",code:o,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret}),M=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!M.ok)throw Error(`OAuth token exchange failed: ${M.status} ${M.statusText}`);return await M.json()}async refreshToken(o){let l=new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:this.config.clientId,client_secret:this.config.clientSecret}),M=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!M.ok)throw Error(`OAuth token refresh failed: ${M.status} ${M.statusText}`);return await M.json()}}var _s={JWT:cn,ApiKeyManager:ln,OAuth2Helper:dn},js=_s;var fn={};qe(fn,{AuthenticationException:()=>X,AuthorizationException:()=>Y,BugsnagReporter:()=>Ur,BusinessLogicException:()=>se,CircuitBreaker:()=>gr,CircuitBreakerHttpClient:()=>pn,CircuitBreakerOpenException:()=>C,CircuitBreakerPresets:()=>Gs,CircuitBreakerRegistry:()=>It,CircularDependencyException:()=>p,ConfigurationException:()=>ie,CustomReporter:()=>hn,DatabaseException:()=>ne,DegradationStrategies:()=>Qs,ErrorFactory:()=>i,ErrorReportingManager:()=>Xt,ErrorReportingPresets:()=>Ks,ExternalServiceException:()=>T,FileSystemException:()=>oe,GracefulDegradationManager:()=>Qt,HandlerResolutionException:()=>ce,InternalServerException:()=>te,MethodNotAllowedException:()=>Z,MiddlewareConfigurationException:()=>ae,ModelBindingException:()=>le,NotFoundException:()=>Q,RateLimitException:()=>ee,RouteConflictException:()=>P,RouteNotFoundException:()=>U,RouterErrorFactory:()=>ct,RouterException:()=>t,SentryReporter:()=>Nr,ServiceHealthMonitor:()=>Fr,ServiceUnavailableException:()=>re,TimeoutException:()=>x,ValidationException:()=>d,circuitBreaker:()=>Ls,createAdvancedErrorHandler:()=>mn,createCircuitBreaker:()=>Ws,createCircuitBreakerMiddleware:()=>zs,createErrorReporting:()=>Js,createGracefulDegradationMiddleware:()=>Xs,detectRouteConflicts:()=>at,findSimilarRoutes:()=>ot,globalCircuitBreakerRegistry:()=>Dr,withCircuitBreaker:()=>Vs});class gr{config;state="CLOSED";metrics;nextAttemptTime;halfOpenCallCount=0;recentRequests=[];constructor(o){let l={failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000};this.config={...l,...o},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(o){if(this.state==="OPEN")if(this.nextAttemptTime&&new Date<this.nextAttemptTime){let L=new C(this.config.name,this.nextAttemptTime,o.context);if(o.fallback)try{return await o.fallback()}catch(V){console.error(V)}throw L}else this.transitionToHalfOpen();if(this.state==="HALF_OPEN"&&this.halfOpenCallCount>=this.config.halfOpenMaxCalls){let L=new C(this.config.name,this.nextAttemptTime||new Date(Date.now()+this.config.recoveryTimeout),o.context);if(o.fallback)try{return await o.fallback()}catch(V){throw console.error(V),L}throw L}let l=Date.now(),M,k=null;try{if(this.state==="HALF_OPEN")this.halfOpenCallCount++;let L=o.timeout||this.config.timeout,V=new Promise((pe,he)=>{setTimeout(()=>{he(new x(`Circuit breaker timeout for ${this.config.name}`,L,o.context))},L)});return M=await Promise.race([o.execute(),V]),this.onSuccess(Date.now()-l),M}catch(L){if(k=L,this.onFailure(k,Date.now()-l),o.fallback)try{return await o.fallback()}catch(V){throw console.error(V),k}else throw k}}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(o){if(this.metrics.totalRequests++,this.metrics.successfulRequests++,this.metrics.consecutiveSuccesses++,this.metrics.consecutiveFailures=0,this.metrics.lastSuccessTime=new Date,this.updateAverageResponseTime(o),this.recentRequests.push({timestamp:new Date,success:!0,responseTime:o}),this.state==="HALF_OPEN"){if(this.metrics.consecutiveSuccesses>=this.config.halfOpenMaxCalls)this.transitionToClosed()}if(this.config.onSuccess)this.config.onSuccess(this.config.name)}onFailure(o,l){if(this.metrics.totalRequests++,this.metrics.failedRequests++,this.metrics.consecutiveFailures++,this.metrics.consecutiveSuccesses=0,this.metrics.lastFailureTime=new Date,o instanceof x)this.metrics.timeouts++;if(this.updateAverageResponseTime(l),this.recentRequests.push({timestamp:new Date,success:!1,responseTime:l}),this.shouldTrip(o)){if(this.state==="CLOSED")this.transitionToOpen();else if(this.state==="HALF_OPEN")this.transitionToOpen()}if(this.config.onFailure)this.config.onFailure(o,this.config.name)}shouldTrip(o){if(this.config.shouldTripOnError&&!this.config.shouldTripOnError(o))return!1;if(this.metrics.consecutiveFailures>=this.config.failureThreshold)return!0;let l=this.getRecentRequests();if(l.length>=this.config.minimumRequests){if(l.filter((L)=>!L.success).length/l.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(o){if(this.metrics.totalRequests===1)this.metrics.averageResponseTime=o;else this.metrics.averageResponseTime=0.1*o+0.9*this.metrics.averageResponseTime}getRecentRequests(){let o=new Date(Date.now()-this.config.monitoringPeriod);return this.recentRequests.filter((l)=>l.timestamp>o)}cleanupOldRequests(){let o=new Date(Date.now()-this.config.monitoringPeriod);this.recentRequests=this.recentRequests.filter((l)=>l.timestamp>o)}}class It{breakers=new Map;configs=new Map;register(o){let l=new gr(o);return this.breakers.set(o.name,l),this.configs.set(o.name,o),l}get(o){return this.breakers.get(o)}async execute(o,l){let M=this.breakers.get(o);if(!M)throw Error(`Circuit breaker '${o}' not found`);return M.execute(l)}getAllMetrics(){let o={};for(let[l,M]of this.breakers)o[l]=M.getMetrics();return o}getBreakersByState(o){let l=[];for(let[M,k]of this.breakers)if(k.getState()===o)l.push(M);return l}forceAllClosed(){for(let o of this.breakers.values())o.forceClosed()}resetAll(){for(let o of this.breakers.values())o.reset()}remove(o){return this.configs.delete(o),this.breakers.delete(o)}getNames(){return Array.from(this.breakers.keys())}}function Ls(o){let l=new gr(o);return function(M,k,L){let V=L.value;return L.value=async function(...pe){return l.execute({execute:()=>V.apply(this,pe),context:{method:k,timestamp:new Date}})},L}}class pn{registry;constructor(o){this.registry=o||new It}async fetch(o,l={}){let{circuitBreaker:M,fallback:k,context:L,...V}=l,pe;if(typeof M==="string")pe=M;else if(M){if(pe=M.name,!this.registry.get(pe))this.registry.register(M)}else if(pe=`http-${new URL(o).hostname}`,!this.registry.get(pe))this.registry.register({name:pe,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000});return this.registry.execute(pe,{execute:async()=>{let he=await fetch(o,V);if(he.status>=500)throw new T(`HTTP ${he.status}: ${he.statusText}`,pe,o,he.status,void 0,L);return he},fallback:k,context:L})}getRegistry(){return this.registry}}function zs(o){return async(l,M)=>{let k=l.context?.serviceName;if(!k)return M();let L=o.get(k);if(!L)return M();return L.execute({execute:M,context:{requestId:l.requestId,route:l.route,method:l.method,url:l.url}})}}var Gs={critical:(o)=>({name:o,failureThreshold:3,recoveryTimeout:30000,timeout:5000,monitoringPeriod:30000,minimumRequests:5,errorThresholdPercentage:30,halfOpenMaxCalls:2,resetTimeout:30000}),standard:(o)=>({name:o,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000}),tolerant:(o)=>({name:o,failureThreshold:10,recoveryTimeout:120000,timeout:60000,monitoringPeriod:120000,minimumRequests:20,errorThresholdPercentage:70,halfOpenMaxCalls:5,resetTimeout:120000}),database:(o)=>({name:o,failureThreshold:3,recoveryTimeout:60000,timeout:1e4,monitoringPeriod:60000,minimumRequests:5,errorThresholdPercentage:40,halfOpenMaxCalls:2,resetTimeout:60000,shouldTripOnError:(l)=>!(l.message.includes("validation")||l.message.includes("constraint"))}),externalApi:(o)=>({name:o,failureThreshold:5,recoveryTimeout:90000,timeout:15000,monitoringPeriod:90000,minimumRequests:8,errorThresholdPercentage:60,halfOpenMaxCalls:3,resetTimeout:90000,shouldTripOnError:(l)=>{if(l instanceof T)return l.statusCode>=500;return!0}})},Dr=new It;function Ws(o){return Dr.register(o)}async function Vs(o,l){return Dr.execute(o,l)}class Nr{config;sentry;constructor(o){this.config=o,this.initializeSentry()}async initializeSentry(){try{let o=await import("@sentry/node");o.init({dsn:this.config.dsn,environment:this.config.environment||"production",release:this.config.release,sampleRate:this.config.sampleRate||1,beforeSend:(l,M)=>{let k=M.originalException;if(k&&this.config.beforeSend)return this.config.beforeSend(k,k.context)?l:null;return l},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=o}catch(o){console.warn("Failed to initialize Sentry:",o)}}async report(o,l){if(!this.sentry||!this.config.enabled)return null;try{if(this.shouldIgnoreError(o))return null;let M={...o.context,...l};return this.sentry.withScope((k)=>{if(M.requestId)k.setTag("requestId",M.requestId);if(M.userId)k.setUser({id:M.userId});if(M.traceId)k.setTag("traceId",M.traceId);if(M.route)k.setTag("route",M.route);if(M.method)k.setTag("method",M.method);k.setTag("errorCode",o.code),k.setTag("severity",o.severity),k.setTag("category",o.category),k.setLevel(this.mapSeverityToLevel(o.severity)),k.setExtra("statusCode",o.statusCode),k.setExtra("retryable",o.retryable),k.setExtra("timestamp",o.timestamp),k.setExtra("context",M);let L=this.generateFingerprint(o);if(L.length>0)k.setFingerprint(L);return this.sentry.captureException(o)})}catch(M){return console.error("Failed to report error to Sentry:",M),null}}addBreadcrumb(o,l="default",M="info",k){if(!this.sentry||!this.config.breadcrumbs?.enabled)return;this.sentry.addBreadcrumb({message:o,category:l,level:M,data:k,timestamp:Date.now()/1000})}setUser(o){if(!this.sentry)return;this.sentry.setUser(o)}setTag(o,l){if(!this.sentry)return;this.sentry.setTag(o,l)}setExtra(o,l){if(!this.sentry)return;this.sentry.setExtra(o,l)}setContext(o,l){if(!this.sentry)return;this.sentry.setContext(o,l)}async close(o=2000){if(!this.sentry)return!0;return this.sentry.close(o)}shouldIgnoreError(o){let l=this.config.filters;if(!l)return!1;if(l.ignoreCodes?.includes(o.code))return!0;if(l.ignoreErrors?.some((M)=>{if(typeof M==="string")return o.message.includes(M);return M.test(o.message)}))return!0;return!1}mapSeverityToLevel(o){switch(o){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}generateFingerprint(o){let l=[];if(l.push(o.code),l.push(o.category),o.context.route)l.push(o.context.route);return l}}class Ur{config;bugsnag;constructor(o){this.config=o,this.initializeBugsnag()}async initializeBugsnag(){try{let o=await import("@bugsnag/js");o.start({apiKey:this.config.apiKey,appVersion:this.config.release,releaseStage:this.config.environment||"production",enabledReleaseStages:["production","staging"],maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||25,onError:(l)=>{let M=l.originalError;if(M&&this.config.beforeSend)return this.config.beforeSend(M,M.context)!==null;return!this.shouldIgnoreError(M)}}),this.bugsnag=o}catch(o){console.warn("Failed to initialize Bugsnag:",o)}}async report(o,l){if(!this.bugsnag||!this.config.enabled)return null;try{if(this.shouldIgnoreError(o))return null;let M={...o.context,...l};return this.bugsnag.notify(o,(k)=>{if(k.severity=this.mapSeverityToBugsnag(o.severity),k.context=M.route||M.url,M.userId)k.setUser(M.userId,void 0,void 0);k.addMetadata("error",{code:o.code,category:o.category,statusCode:o.statusCode,retryable:o.retryable,timestamp:o.timestamp}),k.addMetadata("request",{requestId:M.requestId,method:M.method,url:M.url,userAgent:M.userAgent,ip:M.ip}),k.groupingHash=this.generateGroupingHash(o)}),"reported"}catch(M){return console.error("Failed to report error to Bugsnag:",M),null}}addBreadcrumb(o,l="manual",M="info",k){if(!this.bugsnag||!this.config.breadcrumbs?.enabled)return;this.bugsnag.leaveBreadcrumb(o,k,l)}setUser(o){if(!this.bugsnag)return;this.bugsnag.setUser(o.id,o.email,o.username)}setTag(o,l){if(!this.bugsnag)return;this.bugsnag.addMetadata("tags",{[o]:l})}setExtra(o,l){if(!this.bugsnag)return;this.bugsnag.addMetadata("extra",{[o]:l})}setContext(o,l){if(!this.bugsnag)return;this.bugsnag.addMetadata(o,l)}async close(){return!0}shouldIgnoreError(o){let l=this.config.filters;if(!l)return!1;if(l.ignoreCodes?.includes(o.code))return!0;if(l.ignoreErrors?.some((M)=>{if(typeof M==="string")return o.message.includes(M);return M.test(o.message)}))return!0;return!1}mapSeverityToBugsnag(o){switch(o){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"error";default:return"warning"}}generateGroupingHash(o){return`${o.code}-${o.category}-${o.context.route||"unknown"}`}}class hn{config;reportHandler;constructor(o,l){this.config=o,this.reportHandler=l}async report(o,l){if(!this.config.enabled)return null;try{let M={...o.context,...l};if(this.config.beforeSend){if(!this.config.beforeSend(o,M))return null}let k={error:o,context:M,level:this.mapSeverityToLevel(o.severity),tags:this.config.tags,extra:this.config.extra,user:this.config.user};return await this.reportHandler(k)}catch(M){return console.error("Failed to report error with custom handler:",M),null}}addBreadcrumb(){}setUser(){}setTag(){}setExtra(){}setContext(){}async close(){return!0}mapSeverityToLevel(o){switch(o){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}}class Xt{reporters=[];breadcrumbs=[];maxBreadcrumbs=50;constructor(o){this.initializeReporters(o)}initializeReporters(o){for(let l of o){if(!l.enabled)continue;switch(l.service){case"sentry":this.reporters.push(new Nr(l));break;case"bugsnag":this.reporters.push(new Ur(l));break;case"custom":break}}}addReporter(o){this.reporters.push(o)}async report(o,l){let M=[];this.addBreadcrumb(`Error occurred: ${o.message}`,"error",{code:o.code,severity:o.severity});let k=this.reporters.map(async(L)=>{try{let V=await L.report(o,l);if(V)M.push(V)}catch(V){console.error("Reporter failed:",V)}});return await Promise.allSettled(k),M}addBreadcrumb(o,l="default",M){if(this.breadcrumbs.push({message:o,timestamp:new Date,data:{category:l,...M}}),this.breadcrumbs.length>this.maxBreadcrumbs)this.breadcrumbs=this.breadcrumbs.slice(-this.maxBreadcrumbs);this.reporters.forEach((k)=>{k.addBreadcrumb(o,l,"info",M)})}setUser(o){this.reporters.forEach((l)=>l.setUser(o))}setTag(o,l){this.reporters.forEach((M)=>M.setTag(o,l))}setExtra(o,l){this.reporters.forEach((M)=>M.setExtra(o,l))}setContext(o,l){this.reporters.forEach((M)=>M.setContext(o,l))}async close(o=5000){let l=this.reporters.map((k)=>k.close(o));return(await Promise.allSettled(l)).every((k)=>k.status==="fulfilled"&&k.value)}getBreadcrumbs(){return[...this.breadcrumbs]}}function Js(o){return new Xt(o)}var Ks={sentry:(o,l="production")=>({enabled:!0,service:"sentry",dsn:o,environment:l,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:(o,l="production")=>({enabled:!0,service:"bugsnag",apiKey:o,environment:l,breadcrumbs:{enabled:!0,maxBreadcrumbs:25},filters:{ignoreCodes:["VALIDATION_ERROR"]}}),development:()=>({enabled:!1,service:"custom",environment:"development"})};class Fr{healthStatus=new Map;healthCheckIntervals=new Map;config;constructor(o){this.config=o,this.initializeHealthChecks()}initializeHealthChecks(){for(let[o,l]of Object.entries(this.config.healthChecks)){if(!l.enabled)continue;this.healthStatus.set(o,{name:o,status:"healthy",lastCheck:new Date,responseTime:0,errorRate:0,availability:100,consecutiveFailures:0});let M=setInterval(()=>this.performHealthCheck(o,l),l.interval);M.unref?.(),this.healthCheckIntervals.set(o,M)}}async performHealthCheck(o,l){let M=Date.now(),k=!1;try{let V=new AbortController,pe=setTimeout(()=>V.abort(),l.timeout),he=await fetch(l.endpoint,{signal:V.signal,headers:l.headers,method:"GET"});if(clearTimeout(pe),k=l.expectedStatus.includes(he.status),k&&l.expectedBody){let Te=await he.text();if(typeof l.expectedBody==="string")k=Te.includes(l.expectedBody);else k=l.expectedBody.test(Te)}}catch(V){console.error(V),k=!1}let L=Date.now()-M;if(this.updateHealthStatus(o,k,L),k&&l.onHealthy)l.onHealthy();else if(!k&&l.onUnhealthy)l.onUnhealthy(Error(`Health check failed for ${o}`))}updateHealthStatus(o,l,M){let k=this.healthStatus.get(o);if(!k)return;let L={...k,lastCheck:new Date,responseTime:M,consecutiveFailures:l?0:k.consecutiveFailures+1};if(L.consecutiveFailures===0)L.status="healthy";else if(L.consecutiveFailures<3)L.status="degraded";else L.status="unhealthy";let V=l?1:0;L.availability=k.availability*0.9+V*10,this.healthStatus.set(o,L)}getServiceHealth(o){return this.healthStatus.get(o)}getAllServiceHealth(){return Array.from(this.healthStatus.values())}isServiceHealthy(o){return this.healthStatus.get(o)?.status==="healthy"}isServiceDegraded(o){return this.healthStatus.get(o)?.status==="degraded"}stop(){for(let o of this.healthCheckIntervals.values())clearInterval(o);this.healthCheckIntervals.clear()}}class Qt{config;healthMonitor;cache=new Map;metrics=new Map;constructor(o){this.config=o,this.healthMonitor=new Fr(o)}async handleFailure(o,l,M,k){if(!this.config.enabled)throw l;let L=this.config.fallbackStrategies[o];if(!L)throw l;let V={request:M,serviceName:o,error:l,attemptCount:1,startTime:new Date};return this.executeFallbackStrategy(L,V,k)}async executeFallbackStrategy(o,l,M){if(l.attemptCount<=o.retries)try{if(l.attemptCount>1){let V=this.calculateBackoffDelay(o.backoff,l.attemptCount);await this.sleep(V)}let k=new Promise((V,pe)=>{setTimeout(()=>pe(Error("Timeout")),o.timeout)}),L=await Promise.race([M(),k]);return this.updateMetrics(l.serviceName,!0,Date.now()-l.startTime.getTime()),L}catch(k){if(console.error(k),l.attemptCount++,l.attemptCount<=o.retries)return this.executeFallbackStrategy(o,l,M)}switch(this.updateMetrics(l.serviceName,!1,Date.now()-l.startTime.getTime()),o.type){case"cache":return this.handleCacheFallback(o,l);case"static":return this.handleStaticFallback(o,l);case"simplified":return this.handleSimplifiedFallback(o,l);case"redirect":return this.handleRedirectFallback(o,l);case"custom":return this.handleCustomFallback(o,l);default:throw l.error}}async handleCacheFallback(o,l){if(!o.cacheConfig)throw l.error;let M=this.generateCacheKey(o.cacheConfig.key,l),k=this.cache.get(M);if(k&&(k.expires>new Date||o.cacheConfig.staleWhileRevalidate)){let L=new Headers({"Content-Type":"application/json","X-Cache":"HIT","X-Degraded":"true","X-Service-Status":this.healthMonitor.getServiceHealth(l.serviceName)?.status||"unknown"});if(o.cacheConfig.staleWhileRevalidate&&k.expires<=new Date)L.set("X-Cache","STALE");return new Response(JSON.stringify(k.data),{status:200,headers:L})}throw l.error}async handleStaticFallback(o,l){if(!o.staticResponse)throw l.error;let M=new Headers(o.staticResponse.headers||{});return M.set("X-Degraded","true"),M.set("X-Fallback-Type","static"),M.set("X-Service-Status",this.healthMonitor.getServiceHealth(l.serviceName)?.status||"unknown"),new Response(typeof o.staticResponse.body==="string"?o.staticResponse.body:JSON.stringify(o.staticResponse.body),{status:o.staticResponse.status,headers:M})}async handleSimplifiedFallback(o,l){let M={message:"Service temporarily unavailable. Showing simplified view.",status:"degraded",timestamp:new Date().toISOString(),requestId:l.request.requestId};return new Response(JSON.stringify(M),{status:200,headers:{"Content-Type":"application/json","X-Degraded":"true","X-Fallback-Type":"simplified","X-Service-Status":this.healthMonitor.getServiceHealth(l.serviceName)?.status||"unknown"}})}async handleRedirectFallback(o,l){if(!o.redirectConfig)throw l.error;return new Response(null,{status:o.redirectConfig.permanent?301:302,headers:{Location:o.redirectConfig.url,"X-Degraded":"true","X-Fallback-Type":"redirect"}})}async handleCustomFallback(o,l){if(!o.fallbackHandler)throw l.error;try{let M=await o.fallbackHandler(l.error,l.error.context);return M.headers.set("X-Degraded","true"),M.headers.set("X-Fallback-Type","custom"),M.headers.set("X-Service-Status",this.healthMonitor.getServiceHealth(l.serviceName)?.status||"unknown"),M}catch(M){throw console.error(M),l.error}}cacheResponse(o,l,M,k){let L=this.config.fallbackStrategies[o];if(L?.type==="cache"&&L.cacheConfig){let V=this.generateCacheKey(l,{serviceName:o});this.cache.set(V,{data:M,expires:new Date(Date.now()+k*1000)})}}getServiceMetrics(o){let l=this.metrics.get(o);if(!l||l.requests===0)return{errorRate:0,avgResponseTime:0,totalRequests:0};return{errorRate:l.errors/l.requests*100,avgResponseTime:l.totalTime/l.requests,totalRequests:l.requests}}getSystemHealth(){let o=this.healthMonitor.getAllServiceHealth(),l=o.filter((L)=>L.status==="unhealthy").length,M=o.filter((L)=>L.status==="degraded").length,k="healthy";if(l>0)k=l>o.length/2?"unhealthy":"degraded";else if(M>0)k="degraded";return{status:k,services:o}}calculateBackoffDelay(o,l){if(o.type==="fixed")return o.delay;let M=o.delay*2**(l-1);return Math.min(M,o.maxDelay||30000)}generateCacheKey(o,l){return o.replace("{service}",l.serviceName).replace("{url}",l.request.url).replace("{method}",l.request.method).replace("{userId}",String(l.request.user?.id||"anonymous"))}updateMetrics(o,l,M){let k=this.metrics.get(o)||{requests:0,errors:0,totalTime:0};if(k.requests++,k.totalTime+=M,!l)k.errors++;this.metrics.set(o,k)}sleep(o){return new Promise((l)=>setTimeout(l,o))}stop(){this.healthMonitor.stop()}}function Xs(o){let l=new Qt(o);return async(M,k)=>{try{let L=await k(),V=M.context?.serviceName;if(V&&L.ok){let pe=o.fallbackStrategies[V];if(pe?.type==="cache"&&pe.cacheConfig)try{let he=await L.clone().json();l.cacheResponse(V,pe.cacheConfig.key,he,pe.cacheConfig.ttl)}catch{}}return L}catch(L){let V=M.context?.serviceName;if(V&&L instanceof Error){let pe=L;try{return await l.handleFailure(V,pe,M,k)}catch(he){throw console.error(he),L}}throw L}}}var Qs={cacheFirst:(o=3600,l=!0)=>({type:"cache",priority:1,timeout:5000,retries:2,backoff:{type:"exponential",delay:1000,maxDelay:5000},cacheConfig:{key:"{service}:{url}:{method}",ttl:o,staleWhileRevalidate:l}}),staticFallback:(o,l=200)=>({type:"static",priority:2,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},staticResponse:{status:l,body:o,headers:{"Content-Type":"application/json"}}}),simplifiedView:()=>({type:"simplified",priority:3,timeout:1000,retries:0,backoff:{type:"fixed",delay:0}}),redirectToMaintenance:(o)=>({type:"redirect",priority:4,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},redirectConfig:{url:o,permanent:!1}})};class gn{errorReporting;gracefulDegradation;circuitBreakerRegistry;config;constructor(o={}){this.config={development:!1,includeStackTrace:!1,sanitizeErrors:!0,logErrors:!0,...o},this.initializeComponents()}initializeComponents(){if(this.config.errorReporting?.length)this.errorReporting=new Xt(this.config.errorReporting);if(this.config.gracefulDegradation?.enabled)this.gracefulDegradation=new Qt(this.config.gracefulDegradation);if(this.config.circuitBreakers?.length){this.circuitBreakerRegistry=new It;for(let o of this.config.circuitBreakers)this.circuitBreakerRegistry.register(o)}}middleware(){return async(o,l)=>{try{let M={requestId:o.requestId,userId:o.user?.id,traceId:o.traceId,spanId:o.spanId,route:o.params?.route||o.url,method:o.method,url:o.url,userAgent:o.userAgent?.()||void 0,ip:o.ip?.()||void 0,timestamp:new Date};if(o.context={...o.context,errorContext:M},this.circuitBreakerRegistry&&o.context?.serviceName){let k=this.circuitBreakerRegistry.get(o.context.serviceName);if(k)return await k.execute({execute:l,context:M})}return await l()}catch(M){return this.handleError(M,o)}}}async handleError(o,l){let M=this.normalizeError(o,l);if(this.errorReporting)this.errorReporting.addBreadcrumb(`Error in ${l.method} ${l.url}`,"error",{code:M.code,severity:M.severity,statusCode:M.statusCode});if(this.config.logErrors)this.logError(M,l);if(this.gracefulDegradation&&l.context?.serviceName)try{return await this.gracefulDegradation.handleFailure(l.context.serviceName,M,l,async()=>{throw M})}catch{}if(this.errorReporting)try{await this.errorReporting.report(M,M.context)}catch(L){console.error("Failed to report error:",L)}if(this.config.globalErrorHandler)try{return await this.config.globalErrorHandler(M,l)}catch(L){console.error("Global error handler failed:",L)}let k=this.config.customErrorPages?.[M.statusCode];if(k)try{if(typeof k==="string")return new Response(k,{status:M.statusCode,headers:{"Content-Type":"text/html"}});else return await k(M,l)}catch(L){console.error("Custom error page failed:",L)}return this.createErrorResponse(M,l)}normalizeError(o,l){let M={requestId:l.requestId,userId:l.user?.id,traceId:l.traceId,spanId:l.spanId,route:l.params?.route||l.url,method:l.method,url:l.url,userAgent:l.userAgent?.()||void 0,ip:l.ip?.()||void 0,timestamp:new Date,metadata:l.context};if(o instanceof t)return o;if(o instanceof Error){if(o.name==="ValidationError")return i.validation(o.message,{},M);if(o.name==="UnauthorizedError"||o.message.includes("unauthorized"))return i.authentication(o.message,M);if(o.name==="ForbiddenError"||o.message.includes("forbidden"))return i.authorization(o.message,[],M);if(o.name==="NotFoundError"||o.message.includes("not found"))return i.notFound(void 0,void 0,M);if(o.name==="TimeoutError"||o.message.includes("timeout"))return i.timeout(30000,o.message,M);return i.internalServer(o.message,o,M)}if(typeof o==="string")return i.internalServer(o,void 0,M);return i.internalServer("An unknown error occurred",void 0,M)}createErrorResponse(o,l){let M=this.config.development,k=this.config.includeStackTrace||M,L=this.config.sanitizeErrors&&!M,V=o.message;if(L&&o.statusCode>=500)V="An internal server error occurred";let pe={error:{code:o.code,message:V,statusCode:o.statusCode,timestamp:o.timestamp.toISOString(),requestId:o.context.requestId,traceId:o.context.traceId}};if(M)pe.error.category=o.category,pe.error.severity=o.severity,pe.error.retryable=o.retryable,pe.error.context=o.context;if(k){if(pe.error.stack=o.stack,o.cause)pe.error.cause={name:o.cause.name,message:o.cause.message,stack:o.cause.stack}}if("fields"in o)pe.error.fields=o.fields;if("allowedMethods"in o)pe.error.allowedMethods=o.allowedMethods;if("retryAfter"in o)pe.error.retryAfter=o.retryAfter;let he=new Headers({"Content-Type":"application/json","X-Error-Code":o.code,"X-Request-ID":o.context.requestId||"","X-Trace-ID":o.context.traceId||""});if("allowedMethods"in o)he.set("Allow",o.allowedMethods.join(", "));if("retryAfter"in o)he.set("Retry-After",o.retryAfter.toString());if("limit"in o)he.set("X-RateLimit-Limit",o.limit.toString()),he.set("X-RateLimit-Remaining",o.remaining.toString());return new Response(JSON.stringify(pe),{status:o.statusCode,headers:he})}logError(o,l){let M={error:o.toJSON(),request:{method:l.method,url:l.url,headers:Object.fromEntries(l.headers.entries()),userAgent:l.userAgent?.()||void 0,ip:l.ip?.()||void 0,requestId:l.requestId,traceId:l.traceId}};switch(o.severity){case"critical":console.error("[CRITICAL ERROR]",M);break;case"high":console.error("[ERROR]",M);break;case"medium":console.warn("[WARNING]",M);break;case"low":console.warn("[INFO]",M);break;default:console.error("[ERROR]",M)}}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 mn(o={}){let l=new gn(o);return{middleware:l.middleware(),getStats:()=>l.getStats(),cleanup:()=>l.cleanup()}}function _t(o){if(!o.includes("%"))return o;try{return decodeURIComponent(o)}catch{return o}}function mr(o){let{read:l,write:M,remove:k}=o,L=()=>({...l()});for(let[V,pe]of Object.entries(l()))Object.defineProperty(L,V,{value:pe,writable:!0,enumerable:!0,configurable:!0});return L.get=(V)=>l()[V],L.set=(V,pe,he={})=>M?.(V,pe,he),L.delete=(V,pe={})=>k?.(V,pe),L.getAll=()=>({...l()}),L}function jt(o={}){let l={...o};return mr({read:()=>l,write:(M,k)=>{l[M]=k},remove:(M)=>{delete l[M]}})}import{AsyncLocalStorage as Zs}from"async_hooks";var fr=new Zs,Zt=!1,ht=null;function Ys(){Zt=!0}function Ir(o,l){if(!Zt){ht=o;let M;try{M=l()}catch(k){throw ht=null,k}if(M instanceof Promise)return M.finally(()=>{ht=null});return ht=null,M}return fr.run({current:o},l)}function _r(o,l,M,k){if(!Zt){ht=o;let L;try{L=l(M,k)}catch(V){throw ht=null,V}if(L instanceof Promise)return L.finally(()=>{ht=null});return ht=null,L}return fr.run({current:o},l,M,k)}function Rr(o){let l=fr.getStore();if(l){l.current=o;return}if(ht!==null)ht=o}function Rn(){if(!Zt)return Zt=!0,ht??void 0;return fr.getStore()?.current??ht??void 0}function ei(){let o=Rn();if(!o)throw Error("request() called outside a request scope. It can only be invoked from within a route handler or middleware.");return o}var yn={enabled:!0,level:6,threshold:1024};function wn(o){if(!o)return!1;if(o==="application/json")return!0;if(o.startsWith("text/")){if(!o.startsWith("text/event-stream"))return!0;if(o.length===17)return!1;let M=o.charCodeAt(17);return M>32&&M!==59}let l=o.split(";")[0]?.trim().toLowerCase()??"";if(l==="text/event-stream")return!1;if(l.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(l)}function Vo(o){return bn(o).encoding}function bn(o){if(!o)return{encoding:null,identityAllowed:!0};let l,M,k,L;for(let pe of o.split(",")){let he=pe.indexOf(";"),Te=(he<0?pe:pe.slice(0,he)).trim().toLowerCase();if(Te!=="gzip"&&Te!=="deflate"&&Te!=="identity"&&Te!=="*")continue;let xe=1;if(he>=0){let ve=/^;[\t ]*q=(0(?:\.\d{0,3})?|1(?:\.0{0,3})?)[\t ]*$/i.exec(pe.slice(he));xe=ve?Number(ve[1]):0}if(Te==="gzip")l=xe;else if(Te==="deflate")M=xe;else if(Te==="identity")k=xe;else L=xe}l??=L??0,M??=L??0;let V=k!==void 0?k>0:L!==0;if(k!==void 0&&k>Math.max(l,M))return{encoding:null,identityAllowed:V};if(l>0&&l>=M)return{encoding:"gzip",identityAllowed:V};if(M>0)return{encoding:"deflate",identityAllowed:V};return{encoding:null,identityAllowed:V}}function Jo(o,l,M){if(!l)return!1;if(o.status===204||o.status===304||o.status===206)return!1;if(o.headers.has("content-encoding"))return!1;if(!wn(o.headers.get("content-type")))return!1;let k=Number(o.headers.get("content-length")??Number.NaN);if(Number.isFinite(k)&&!(k>=M))return!1;return Boolean(o.body)}function $t(o,l,M={}){if(!(M.enabled??yn.enabled))return o;let L=o.headers;if(L.has("content-encoding"))return o;if(o.status===204)return o;let V=M.threshold??yn.threshold,pe=l.headers.get("accept-encoding"),he=pe?Number(L.get("content-length")??Number.NaN):Number.NaN,Te=Number.isFinite(he)&&!(he>=V);if(!pe||Te&&(!pe.includes(";")||!/identity|\*/i.test(pe)))return Yt(L,"Accept-Encoding"),o;let{encoding:xe,identityAllowed:ve}=bn(pe),Pe=wn(L.get("content-type"))&&o.status!==206;if(!ve&&o.status!==304&&o.body){if(!xe||!Pe)return ti(o);return jr(o,o.body,xe)}if(!xe||Te||!Pe||o.status===304||!o.body)return Yt(L,"Accept-Encoding"),o;if(!Number.isFinite(he))return ri(o,xe,V);return jr(o,o.body,xe)}function ti(o){o.body?.cancel().catch(()=>{});let l=new Headers(o.headers);for(let M of["content-type","content-length","content-encoding","content-range","content-disposition","etag","last-modified","content-md5","digest","content-digest","repr-digest","expires"])l.delete(M);return l.set("Cache-Control","no-store"),Yt(l,"Accept-Encoding"),new Response(null,{status:406,headers:l})}async function Ko(o,l,M={}){return $t(o,l,M)}async function ri(o,l,M){let k=await ii(o.body,M);if(k.ended&&k.size<M){let L=new Headers(o.headers);return Yt(L,"Accept-Encoding"),L.set("Content-Length",String(k.size)),new Response(k.body,{status:o.status,statusText:o.statusText,headers:L})}return jr(o,si(k),l)}function jr(o,l,M){let k=new Headers(o.headers);k.set("Content-Encoding",M),Yt(k,"Accept-Encoding"),k.delete("Content-Length");let L=l.pipeThrough(new CompressionStream(M==="gzip"?"gzip":"deflate"));return new Response(L,{status:o.status,statusText:o.statusText,headers:k})}function ni(o,l){if(o.length===1)return o[0];let M=new Uint8Array(l),k=0;for(let L of o)M.set(L,k),k+=L.byteLength;return M}function si(o){return o.body instanceof Uint8Array?new Response(o.body).body:o.body}async function ii(o,l){let M=o.getReader(),k=[],L=0,V=!1;while(L<l){let{value:he,done:Te}=await M.read();if(Te){V=!0;break}if(he)k.push(he),L+=he.byteLength}if(V)return M.releaseLock(),{body:ni(k,L),size:L,ended:V};return{body:new ReadableStream({start(he){for(let Te of k)he.enqueue(Te)},async pull(he){let{value:Te,done:xe}=await M.read();if(xe){he.close();return}if(Te)he.enqueue(Te)},cancel(he){return M.cancel(he)}}),size:L,ended:V}}function Yt(o,l){let M=o.get("vary");if(!M){o.set("Vary",l);return}let k=M.split(",").map((L)=>L.trim().toLowerCase());if(k.includes("*")||k.includes(l.toLowerCase()))return;o.set("Vary",`${M}, ${l}`)}import{Buffer as oi}from"buffer";function er(o,l,M,k){return new Response(o,{status:M,headers:{"Content-Type":l,"Content-Length":String(oi.byteLength(o)),...k}})}var Ae={json:(o,l={})=>{let M=typeof l==="number"?{status:l}:l,{status:k=200,headers:L={},pretty:V=!1}=M,pe=V?JSON.stringify(o,null,2):JSON.stringify(o);return er(pe,"application/json",k,L)},noContent:(o={})=>new Response(null,{status:204,headers:o}),download:async(o,l,M={})=>{let k=Bun.file(o);if(!await k.exists())return new Response("File not found",{status:404});let V=l||o.split("/").pop()||"download",pe=k.type||"application/octet-stream";return new Response(k,{status:200,headers:{"Content-Type":pe,"Content-Disposition":`attachment; filename="${V}"`,"Content-Length":String(k.size),...M}})},file:async(o,l={})=>{let M=Bun.file(o);if(!await M.exists())return new Response("File not found",{status:404});let L=M.type||"application/octet-stream";return new Response(M,{status:200,headers:{"Content-Type":L,"Content-Length":String(M.size),...l}})},streamDownload:(o,l,M={})=>{let{contentType:k="application/octet-stream",headers:L={}}=M,V=new ReadableStream({async start(pe){try{for await(let he of o())if(typeof he==="string")pe.enqueue(new TextEncoder().encode(he));else pe.enqueue(he);pe.close()}catch(he){pe.error(he)}}});return new Response(V,{status:200,headers:{"Content-Type":k,"Content-Disposition":`attachment; filename="${l}"`,"Transfer-Encoding":"chunked",...L}})},redirect:(o,l=302)=>new Response(null,{status:l,headers:{Location:o}}),redirectPermanent:(o)=>Ae.redirect(o,301),redirectTemporary:(o)=>Ae.redirect(o,302),back:(o,l="/")=>{let M=o.headers.get("referer")||l;return Ae.redirect(M)},view:(o,l=200,M={})=>er(o,"text/html; charset=utf-8",l,M),text:(o,l=200,M={})=>er(o,"text/plain; charset=utf-8",l,M),xml:(o,l=200,M={})=>er(o,"application/xml; charset=utf-8",l,M),success:(o,l,M=200)=>{let k={success:!0};if(o!==void 0)k.data=o;if(l!==void 0)k.message=l;return Ae.json(k,{status:M})},error:(o,l=400,M)=>{let k={success:!1,message:o};if(M!==void 0)k.errors=M;return Ae.json(k,{status:l})},paginate:(o,l)=>{let{page:M,perPage:k,total:L,path:V}=l,pe=Math.ceil(L/k),he=(M-1)*k+1,Te=Math.min(M*k,L);return Ae.json({data:o,meta:{current_page:M,per_page:k,total:L,last_page:pe,from:he,to:Te,path:V,first_page_url:`${V}?page=1`,last_page_url:`${V}?page=${pe}`,next_page_url:M<pe?`${V}?page=${M+1}`:null,prev_page_url:M>1?`${V}?page=${M-1}`:null}})},created:(o,l)=>{let M={};if(l)M.Location=l;let k={success:!0};if(o!==void 0)k.data=o;return Ae.json(k,{status:201,headers:M})},accepted:(o)=>{let l={success:!0};if(o!==void 0)l.data=o;return Ae.json(l,{status:202})},notFound:(o="Resource not found")=>Ae.error(o,404),unauthorized:(o="Unauthorized")=>Ae.error(o,401),forbidden:(o="Forbidden")=>Ae.error(o,403),badRequest:(o="Bad request",l)=>Ae.error(o,400,l),validationError:(o,l="Validation failed")=>Ae.error(l,422,o),unprocessableEntity:(o="Unprocessable entity",l)=>Ae.error(o,422,l),serverError:(o="Internal server error")=>Ae.error(o,500),tooManyRequests:(o="Too many requests",l)=>{let M={};if(l)M["Retry-After"]=String(l);return er(JSON.stringify({message:o}),"application/json",429,M)}};class Tn{_status=200;_headers={};_cookies=[];_deleteCookies=[];status(o){return this._status=o,this}header(o,l){return this._headers[o]=l,this}withHeaders(o){return this._headers={...this._headers,...o},this}cookie(o,l,M={}){return this._cookies.push({name:o,value:l,options:M}),this}withoutCookie(o,l={}){return this._deleteCookies.push({name:o,options:l}),this}json(o){let l=Ae.json(o,{status:this._status,headers:this._headers});return this.applyCookies(l)}text(o){let l=Ae.text(o,this._status,this._headers);return this.applyCookies(l)}html(o){let l=Ae.view(o,this._status,this._headers);return this.applyCookies(l)}noContent(){let o=Ae.noContent(this._headers);return this.applyCookies(o)}applyCookies(o){let l=new Headers(o.headers);for(let{name:M,value:k,options:L}of this._cookies){let V=this.serializeCookie(M,k,L);l.append("Set-Cookie",V)}for(let{name:M,options:k}of this._deleteCookies){let L=this.serializeCookie(M,"",{...k,maxAge:0,expires:new Date(0)});l.append("Set-Cookie",L)}return new Response(o.body,{status:o.status,headers:l})}serializeCookie(o,l,M){let k=`${encodeURIComponent(o)}=${encodeURIComponent(l)}`;if(M.maxAge!==void 0)k+=`; Max-Age=${M.maxAge}`;if(M.expires)k+=`; Expires=${M.expires.toUTCString()}`;if(M.httpOnly)k+="; HttpOnly";if(M.secure)k+="; Secure";if(M.path)k+=`; Path=${M.path}`;if(M.domain)k+=`; Domain=${M.domain}`;if(M.sameSite)k+=`; SameSite=${M.sameSite.charAt(0).toUpperCase()+M.sameSite.slice(1)}`;return k}}function Zo(){return new Tn}import ai from"process";class Lr{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(o){this.dependencyRegistry.set(o.name,o)}compileMiddleware(o,l,M=[]){let k=[];for(let L=0;L<l.length;L++){let V=l[L],pe=V.name||`middleware_${L}`;k.push({handler:V,name:pe,skipConditions:M.filter((he)=>he.name.includes(pe)||he.name==="global"),dependencies:this.extractDependencies(V),canShortCircuit:this.canShortCircuit(V),priority:L})}this.compiledPipelines.set(o,k)}async execute(o,l,M){let k=performance.now();this.stats.totalExecutions++;let L=this.compiledPipelines.get(o);if(!L)return this.stats.cacheMisses++,await M();this.stats.cacheHits++;let V={request:l,dependencies:new Map,metadata:{}};await this.resolveDependencies(V,L);let pe=0,he=async()=>{if(pe>=L.length)return await M();let ve=L[pe++];if(await this.shouldSkip(ve,V))return this.stats.skippedMiddleware++,await he();let Pe=await ve.handler(l,he);if(Pe instanceof Response&&ve.canShortCircuit)return this.stats.shortCircuits++,Pe;return Pe},Te=await he(),xe=performance.now()-k;return this.updateAverageExecutionTime(xe),Te||new Response("Internal Server Error",{status:500})}async shouldSkip(o,l){for(let M of o.skipConditions)if(await M.condition(l))return!0;return!1}async resolveDependencies(o,l){let M=new Set;for(let k of l)for(let L of k.dependencies)M.add(L);for(let k of M){let L=this.dependencyRegistry.get(k);if(!L)continue;if(this.stats.dependencyResolutions++,L.singleton&&this.singletonInstances.has(k))o.dependencies.set(k,this.singletonInstances.get(k));else{let V=await L.factory(o);if(o.dependencies.set(k,V),L.singleton)this.singletonInstances.set(k,V)}}}extractDependencies(o){let l=o.toString(),M=[];if(l.includes("database")||l.includes("db"))M.push("database");if(l.includes("logger")||l.includes("log"))M.push("logger");if(l.includes("cache"))M.push("cache");if(l.includes("httpClient")||l.includes("http"))M.push("httpClient");return M}canShortCircuit(o){let l=o.toString();return l.includes("return")&&l.includes("Response")}updateAverageExecutionTime(o){let l=this.stats.averageExecutionTime*(this.stats.totalExecutions-1);this.stats.averageExecutionTime=(l+o)/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 ui={skipForMethods:(o)=>({name:`skip_for_methods_${o.join("_")}`,condition:(l)=>o.includes(l.request.method)}),skipForPaths:(o)=>({name:`skip_for_paths_${o.join("_").replace(/\//g,"_")}`,condition:(l)=>{let M=new URL(l.request.url);return o.some((k)=>M.pathname.startsWith(k))}}),skipForHeaders:(o)=>({name:`skip_for_headers_${Object.keys(o).join("_")}`,condition:(l)=>Object.entries(o).some(([M,k])=>l.request.headers.get(M)===k)}),skipForRoles:(o)=>({name:`skip_for_roles_${o.join("_")}`,condition:(l)=>{let M=l.request.user?.roles||[];return!o.some((k)=>M.includes(k))}}),skipForEnvironment:(o)=>({name:`skip_for_env_${o.join("_")}`,condition:()=>{let l=ai.env.NODE_ENV||"development";return o.includes(l)}})},ci={database:(o)=>({name:"database",factory:async()=>({query:async(l)=>({rows:[]}),close:async()=>{},connectionString:o||"mock://database"}),singleton:!0}),logger:(o="info")=>({name:"logger",factory:()=>({info:(l)=>console.log(`[INFO] ${l}`),error:(l)=>console.error(`[ERROR] ${l}`),warn:(l)=>console.warn(`[WARN] ${l}`),debug:(l)=>console.debug(`[DEBUG] ${l}`),level:o}),singleton:!0}),cache:(o=1000)=>({name:"cache",factory:()=>{let l=new Map;return{get:(M)=>l.get(M),set:(M,k)=>{if(l.size>=o){let L=l.keys().next().value;l.delete(L)}l.set(M,k)},delete:(M)=>l.delete(M),clear:()=>l.clear(),size:()=>l.size}},singleton:!0}),httpClient:(o)=>({name:"httpClient",factory:()=>({get:async(l)=>fetch(o?`${o}${l}`:l),post:async(l,M)=>fetch(o?`${o}${l}`:l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)}),put:async(l,M)=>fetch(o?`${o}${l}`:l,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)}),delete:async(l)=>fetch(o?`${o}${l}`:l,{method:"DELETE"})}),singleton:!0})},li={auth:(o={})=>async(l,M)=>{let k=new URL(l.url);if(o.skipPaths?.some((V)=>k.pathname.startsWith(V)))return await M();if(!l.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});try{return l.user={id:"123",roles:["user"]},await M()}catch{return new Response("Invalid token",{status:401})}},rateLimit:(o)=>{let l=new Map;return async(M,k)=>{let L=M.headers.get("x-forwarded-for")||"unknown",V=Date.now(),pe=V-o.windowMs;if(!l.has(L))l.set(L,[]);let Te=l.get(L).filter((xe)=>xe>pe);if(Te.length>=o.maxRequests)return new Response("Too Many Requests",{status:429});return Te.push(V),l.set(L,Te),await k()}},cors:(o={})=>async(l,M)=>{let k=await M();if(k){let L=new Headers(k.headers);return L.set("Access-Control-Allow-Origin",o.origin||"*"),L.set("Access-Control-Allow-Methods",o.methods?.join(", ")||"GET, POST, PUT, DELETE"),L.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(k.body,{status:k.status,statusText:k.statusText,headers:L})}return k},logging:(o={})=>async(l,M)=>{let k=performance.now(),L=new URL(l.url);console.log(`[${new Date().toISOString()}] ${l.method} ${L.pathname}`);let V=await M(),pe=performance.now()-k;if(V)console.log(`[${new Date().toISOString()}] ${l.method} ${L.pathname} - ${V.status} (${pe.toFixed(2)}ms)`);return V}},di=new Lr;import{existsSync as vn,readdirSync as pi,statSync as hi}from"fs";import{basename as Pn,extname as xn,join as gi,resolve as Cn}from"path";var mi=[".ts",".js"],fi=["routes","src/routes"],Ri=["web","index"];function yi(){let o=process.cwd();for(let l of fi){let M=Cn(o,l);if(vn(M)&&hi(M).isDirectory())return M}return null}function Mn(o,l){let M=[];if(!vn(o))return M;let k=pi(o,{withFileTypes:!0});for(let L of k){if(L.name.startsWith(".")||L.name.startsWith("_"))continue;let V=gi(o,L.name);if(L.isDirectory())M.push(...Mn(V,l));else if(mi.includes(xn(L.name))){let pe=o===l?"":o.slice(l.length),he=Pn(L.name,xn(L.name)),Te=Ri.includes(he)?pe||"":`${pe}/${he}`;M.push({filePath:V,prefix:Te})}}return M}async function wi(o,l,M,k){try{let L=await import(l),V=0,pe=o.routes?.length||0;if(typeof L.default==="function"){let he=bi(o,M);await L.default(he),V=(o.routes?.length||0)-pe}else if(Array.isArray(L.routes))for(let he of L.routes){let Te=(he.method||"GET").toLowerCase(),xe=`${M}${he.path}`;if(typeof o[Te]==="function")await o[Te](xe,he.handler),V++}if(k&&V>0)console.log(` ${M||"/"} \u2192 ${Pn(l)} (${V} routes)`);return V}catch(L){return console.error(`[bun-router] Failed to load route file ${l}:`,L),0}}function bi(o,l){if(!l)return o;let M=["get","post","put","patch","delete","options","any"];return new Proxy(o,{get(k,L){if(M.includes(L))return async(V,...pe)=>k[L](`${l}${V}`,...pe);if(L==="group")return async(V,pe)=>{let he=V.prefix?`${l}${V.prefix}`:l;return k.group({...V,prefix:he},pe)};return k[L]}})}function En(o){Object.defineProperties(o.prototype,{_routesDir:{value:null,writable:!0,configurable:!0},_apiRoutesInitialized:{value:!1,writable:!0,configurable:!0},_initApiRoutes:{async value(){if(this._apiRoutesInitialized)return;let l=this._routesDir||yi();if(!l){this._apiRoutesInitialized=!0;return}let M=this.config?.verbose||!1,k=Mn(l,l);if(k.length===0){this._apiRoutesInitialized=!0;return}if(M)console.log(`[bun-router] Auto-discovering API routes from ${l}:`);let L=0;for(let{filePath:V,prefix:pe}of k)L+=await wi(this,V,pe,M);if(L>0&&M)console.log(`[bun-router] Registered ${L} API routes`);this._apiRoutesInitialized=!0},writable:!0,configurable:!0},routesFrom:{value(l){return this._routesDir=Cn(l),this},writable:!0,configurable:!0}})}import{join as tr,relative as zr,resolve as Et,dirname as xi}from"path";import{readdirSync as Sn,statSync as vi,existsSync as wr}from"fs";var ia={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function Ti(o){let{preserve:l=[],exclude:M=[],routes:k=[]}=o;if(!l.length)return"";return`<script data-query-preservation>
|
|
3
|
-
(
|
|
4
|
-
|
|
5
|
-
var exclude = ${JSON.stringify(M)};
|
|
6
|
-
var routes = ${JSON.stringify(k)};
|
|
2
|
+
import{At,c,Ze,xr,e,et,Se,tt,Ot,It,Ft,Nt,Dt,E,o,P,ie,Ee,M,a,rt,k,qt,Ht,Bt,w,oe,ae,ce,Tr,Pe,le,A,O,jt,I,Ut,V,f,Lt,_t,zt,Vt,Wt,W,F,Gt,ue,Kt,de,Jt,pe,Xt,he,Yt,N,Qt,me,Zt,Cr,Sr,Er,Pr,Mr,kr,Me}from"./chunk-mpyfk9k4.js";import{t,b,ke,$e,Ae,Oe,D,Ie,Fe,Ne,De,q,H,qe,He,Be,d,G,R,je,ge,Ue,Le,er,tr,rr,h,ye,nt,st,it,we,_e,ze}from"./chunk-q4ktdehf.js";import{v,X,x,Re,B,j,T,Y,ve,Q,Ge,pr,hr,m,mr,xt,Tt,U,r,Z,Ke,ee,s,L,Ct,_,te,Je,Xe,C,S,St,gr,g,xe,Et,Pt,Mt,fr,kt,re,yr,z,wr,$t,br,ne,Rr,l,u,vr,Ye,Te,Qe,i,n,se,Ce}from"./chunk-sr7yt36v.js";function Wr(p){return btoa(p).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Fr(p){p=p.replace(/-/g,"+").replace(/_/g,"/");while(p.length%4)p+="=";return atob(p)}class dn{secret;constructor(p){this.secret=p}sign(p,y={}){let J={alg:y.algorithm||"HS256",typ:"JWT",...y.header},K=Math.floor(Date.now()/1000),fe={...p,iat:K};if(y.expiresIn){let at=typeof y.expiresIn==="string"?this.parseTimespan(y.expiresIn):y.expiresIn;fe.exp=K+at}if(y.notBefore){let at=typeof y.notBefore==="string"?this.parseTimespan(y.notBefore):y.notBefore;fe.nbf=K+at}if(y.issuer)fe.iss=y.issuer;if(y.subject)fe.sub=y.subject;if(y.audience)fe.aud=y.audience;if(y.jwtid)fe.jti=y.jwtid;let be=Wr(JSON.stringify(J)),We=Wr(JSON.stringify(fe)),Ve=`${be}.${We}`,ot=this.createSignature(Ve,this.secret,J.alg);return`${Ve}.${ot}`}verify(p,y={}){try{let J=p.split(".");if(J.length!==3)throw Error("Token structure invalid");let[K,fe,be]=J,We=JSON.parse(Fr(K)),Ve=JSON.parse(Fr(fe));if(y.algorithms&&!y.algorithms.includes(We.alg))throw Error(`Algorithm ${We.alg} not allowed`);let ot=`${K}.${fe}`,at=this.createSignature(ot,this.secret,We.alg),dt=Buffer.from(be),ut=Buffer.from(at);if(dt.length!==ut.length||!c().timingSafeEqual(dt,ut))throw Error("Invalid signature");let lt=Math.floor(Date.now()/1000);if(Ve.exp&&!y.ignoreExpiration&<>=Ve.exp)throw Error("Token expired");if(Ve.nbf&<<Ve.nbf)throw Error("Token not active yet");if(Ve.iat&&Ve.iat>lt)throw Error("Token used before issued");if(y.issuer&&Ve.iss!==y.issuer)throw Error("Invalid issuer");if(y.audience&&Ve.aud!==y.audience)throw Error("Invalid audience");if(y.subject&&Ve.sub!==y.subject)throw Error("Invalid subject");return Ve}catch{return null}}decode(p){try{let y=p.split(".");if(y.length!==3)return null;let[J,K]=y;return{header:JSON.parse(Fr(J)),payload:JSON.parse(Fr(K))}}catch{return null}}createSignature(p,y,J){return Wr(JSON.stringify({data:p,secret:y.slice(0,5),alg:J}))}parseTimespan(p){let y=p.match(/^(\d+)\s*([smhd])$/i);if(!y)return Number.parseInt(p,10)||0;let J=Number.parseInt(y[1],10);switch(y[2].toLowerCase()){case"s":return J;case"m":return J*60;case"h":return J*60*60;case"d":return J*24*60*60;default:return J}}}class un{keys;options;constructor(p={}){this.keys=new Map,this.options={source:"header",keyName:"X-API-Key",keyPrefix:"bun_",...p}}generateKey(p,y=[],J){let K=`${this.options.keyPrefix}${this.randomString(32)}`;return this.keys.set(K,{owner:p,scopes:y,expiresAt:J?new Date(Date.now()+J*1000):void 0}),K}validateKey(p,y=[]){let J=this.keys.get(p);if(!J)return!1;if(J.expiresAt&&J.expiresAt<new Date)return!1;if(y.length>0)return y.every((K)=>J.scopes.includes(K));return!0}getKeyInfo(p){return this.keys.get(p)||null}revokeKey(p){return this.keys.delete(p)}extractFromRequest(p){let{source:y,keyName:J}=this.options;switch(y){case"header":return p.headers.get(J||"X-API-Key")||null;case"query":return new URL(p.url).searchParams.get(J||"api_key")||null;case"cookie":if(p.cookies){let K=J||"api_key";if(typeof p.cookies.get==="function")return p.cookies.get(K)||null;return p.cookies[K]||null}return null;default:return null}}randomString(p){let J="";for(let K=0;K<p;K++)J+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62));return J}}class cn{config;constructor(p){this.config=p}getAuthorizationUrl(p={}){let y=new URLSearchParams({client_id:this.config.clientId,redirect_uri:this.config.redirectUri,response_type:"code",...p});if(this.config.scope)y.set("scope",this.config.scope);if(this.config.state)y.set("state",this.config.state);return`${this.config.authorizeUrl}?${y.toString()}`}async exchangeCodeForToken(p){let y=new URLSearchParams({grant_type:"authorization_code",code:p,redirect_uri:this.config.redirectUri,client_id:this.config.clientId,client_secret:this.config.clientSecret}),J=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:y.toString()});if(!J.ok)throw Error(`OAuth token exchange failed: ${J.status} ${J.statusText}`);return await J.json()}async refreshToken(p){let y=new URLSearchParams({grant_type:"refresh_token",refresh_token:p,client_id:this.config.clientId,client_secret:this.config.clientSecret}),J=await fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:y.toString()});if(!J.ok)throw Error(`OAuth token refresh failed: ${J.status} ${J.statusText}`);return await J.json()}}var Ln={JWT:dn,ApiKeyManager:un,OAuth2Helper:cn},Wn=Ln;var gn={};At(gn,{AuthenticationException:()=>ke,AuthorizationException:()=>$e,BugsnagReporter:()=>Vr,BusinessLogicException:()=>qe,CircuitBreaker:()=>Ur,CircuitBreakerHttpClient:()=>ln,CircuitBreakerOpenException:()=>H,CircuitBreakerPresets:()=>Vn,CircuitBreakerRegistry:()=>dr,CircularDependencyException:()=>R,ConfigurationException:()=>He,CustomReporter:()=>pn,DatabaseException:()=>De,DegradationStrategies:()=>Yn,ErrorFactory:()=>d,ErrorReportingManager:()=>lr,ErrorReportingPresets:()=>Qn,ExternalServiceException:()=>q,FileSystemException:()=>Be,GracefulDegradationManager:()=>Hr,HandlerResolutionException:()=>Ue,InternalServerException:()=>Fe,MethodNotAllowedException:()=>Oe,MiddlewareConfigurationException:()=>je,ModelBindingException:()=>Le,NotFoundException:()=>Ae,RateLimitException:()=>Ie,RouteConflictException:()=>G,RouteNotFoundException:()=>ge,RouterErrorFactory:()=>rr,RouterException:()=>t,SentryReporter:()=>Jr,ServiceHealthMonitor:()=>zr,ServiceUnavailableException:()=>Ne,TimeoutException:()=>D,ValidationException:()=>b,circuitBreaker:()=>Gn,createAdvancedErrorHandler:()=>mn,createCircuitBreaker:()=>zn,createCircuitBreakerMiddleware:()=>Jn,createErrorReporting:()=>Xn,createGracefulDegradationMiddleware:()=>Zn,detectRouteConflicts:()=>tr,findSimilarRoutes:()=>er,globalCircuitBreakerRegistry:()=>Gr,withCircuitBreaker:()=>Kn});class Ur{config;state="CLOSED";metrics;nextAttemptTime;halfOpenCallCount=0;recentRequests=[];constructor(p){let y={failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000};this.config={...y,...p},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(p){if(this.state==="OPEN")if(this.nextAttemptTime&&new Date<this.nextAttemptTime){let fe=new H(this.config.name,this.nextAttemptTime,p.context);if(p.fallback)try{return await p.fallback()}catch(be){console.error(be)}throw fe}else this.transitionToHalfOpen();if(this.state==="HALF_OPEN"&&this.halfOpenCallCount>=this.config.halfOpenMaxCalls){let fe=new H(this.config.name,this.nextAttemptTime||new Date(Date.now()+this.config.recoveryTimeout),p.context);if(p.fallback)try{return await p.fallback()}catch(be){throw console.error(be),fe}throw fe}let y=Date.now(),J,K=null;try{if(this.state==="HALF_OPEN")this.halfOpenCallCount++;let fe=p.timeout||this.config.timeout,be=new Promise((We,Ve)=>{setTimeout(()=>{Ve(new D(`Circuit breaker timeout for ${this.config.name}`,fe,p.context))},fe)});return J=await Promise.race([p.execute(),be]),this.onSuccess(Date.now()-y),J}catch(fe){if(K=fe,this.onFailure(K,Date.now()-y),p.fallback)try{return await p.fallback()}catch(be){throw console.error(be),K}else throw K}}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(p){if(this.metrics.totalRequests++,this.metrics.successfulRequests++,this.metrics.consecutiveSuccesses++,this.metrics.consecutiveFailures=0,this.metrics.lastSuccessTime=new Date,this.updateAverageResponseTime(p),this.recentRequests.push({timestamp:new Date,success:!0,responseTime:p}),this.state==="HALF_OPEN"){if(this.metrics.consecutiveSuccesses>=this.config.halfOpenMaxCalls)this.transitionToClosed()}if(this.config.onSuccess)this.config.onSuccess(this.config.name)}onFailure(p,y){if(this.metrics.totalRequests++,this.metrics.failedRequests++,this.metrics.consecutiveFailures++,this.metrics.consecutiveSuccesses=0,this.metrics.lastFailureTime=new Date,p instanceof D)this.metrics.timeouts++;if(this.updateAverageResponseTime(y),this.recentRequests.push({timestamp:new Date,success:!1,responseTime:y}),this.shouldTrip(p)){if(this.state==="CLOSED")this.transitionToOpen();else if(this.state==="HALF_OPEN")this.transitionToOpen()}if(this.config.onFailure)this.config.onFailure(p,this.config.name)}shouldTrip(p){if(this.config.shouldTripOnError&&!this.config.shouldTripOnError(p))return!1;if(this.metrics.consecutiveFailures>=this.config.failureThreshold)return!0;let y=this.getRecentRequests();if(y.length>=this.config.minimumRequests){if(y.filter((fe)=>!fe.success).length/y.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(p){if(this.metrics.totalRequests===1)this.metrics.averageResponseTime=p;else this.metrics.averageResponseTime=0.1*p+0.9*this.metrics.averageResponseTime}getRecentRequests(){let p=new Date(Date.now()-this.config.monitoringPeriod);return this.recentRequests.filter((y)=>y.timestamp>p)}cleanupOldRequests(){let p=new Date(Date.now()-this.config.monitoringPeriod);this.recentRequests=this.recentRequests.filter((y)=>y.timestamp>p)}}class dr{breakers=new Map;configs=new Map;register(p){let y=new Ur(p);return this.breakers.set(p.name,y),this.configs.set(p.name,p),y}get(p){return this.breakers.get(p)}async execute(p,y){let J=this.breakers.get(p);if(!J)throw Error(`Circuit breaker '${p}' not found`);return J.execute(y)}getAllMetrics(){let p={};for(let[y,J]of this.breakers)p[y]=J.getMetrics();return p}getBreakersByState(p){let y=[];for(let[J,K]of this.breakers)if(K.getState()===p)y.push(J);return y}forceAllClosed(){for(let p of this.breakers.values())p.forceClosed()}resetAll(){for(let p of this.breakers.values())p.reset()}remove(p){return this.configs.delete(p),this.breakers.delete(p)}getNames(){return Array.from(this.breakers.keys())}}function Gn(p){let y=new Ur(p);return function(J,K,fe){let be=fe.value;return fe.value=async function(...We){return y.execute({execute:()=>be.apply(this,We),context:{method:K,timestamp:new Date}})},fe}}class ln{registry;constructor(p){this.registry=p||new dr}async fetch(p,y={}){let{circuitBreaker:J,fallback:K,context:fe,...be}=y,We;if(typeof J==="string")We=J;else if(J){if(We=J.name,!this.registry.get(We))this.registry.register(J)}else if(We=`http-${new URL(p).hostname}`,!this.registry.get(We))this.registry.register({name:We,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000});return this.registry.execute(We,{execute:async()=>{let Ve=await fetch(p,be);if(Ve.status>=500)throw new q(`HTTP ${Ve.status}: ${Ve.statusText}`,We,p,Ve.status,void 0,fe);return Ve},fallback:K,context:fe})}getRegistry(){return this.registry}}function Jn(p){return async(y,J)=>{let K=y.context?.serviceName;if(!K)return J();let fe=p.get(K);if(!fe)return J();return fe.execute({execute:J,context:{requestId:y.requestId,route:y.route,method:y.method,url:y.url}})}}var Vn={critical:(p)=>({name:p,failureThreshold:3,recoveryTimeout:30000,timeout:5000,monitoringPeriod:30000,minimumRequests:5,errorThresholdPercentage:30,halfOpenMaxCalls:2,resetTimeout:30000}),standard:(p)=>({name:p,failureThreshold:5,recoveryTimeout:60000,timeout:30000,monitoringPeriod:60000,minimumRequests:10,errorThresholdPercentage:50,halfOpenMaxCalls:3,resetTimeout:60000}),tolerant:(p)=>({name:p,failureThreshold:10,recoveryTimeout:120000,timeout:60000,monitoringPeriod:120000,minimumRequests:20,errorThresholdPercentage:70,halfOpenMaxCalls:5,resetTimeout:120000}),database:(p)=>({name:p,failureThreshold:3,recoveryTimeout:60000,timeout:1e4,monitoringPeriod:60000,minimumRequests:5,errorThresholdPercentage:40,halfOpenMaxCalls:2,resetTimeout:60000,shouldTripOnError:(y)=>!(y.message.includes("validation")||y.message.includes("constraint"))}),externalApi:(p)=>({name:p,failureThreshold:5,recoveryTimeout:90000,timeout:15000,monitoringPeriod:90000,minimumRequests:8,errorThresholdPercentage:60,halfOpenMaxCalls:3,resetTimeout:90000,shouldTripOnError:(y)=>{if(y instanceof q)return y.statusCode>=500;return!0}})},Gr=new dr;function zn(p){return Gr.register(p)}async function Kn(p,y){return Gr.execute(p,y)}class Jr{config;sentry;constructor(p){this.config=p,this.initializeSentry()}async initializeSentry(){try{let p=await import("@sentry/node");p.init({dsn:this.config.dsn,environment:this.config.environment||"production",release:this.config.release,sampleRate:this.config.sampleRate||1,beforeSend:(y,J)=>{let K=J.originalException;if(K&&this.config.beforeSend)return this.config.beforeSend(K,K.context)?y:null;return y},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=p}catch(p){console.warn("Failed to initialize Sentry:",p)}}async report(p,y){if(!this.sentry||!this.config.enabled)return null;try{if(this.shouldIgnoreError(p))return null;let J={...p.context,...y};return this.sentry.withScope((K)=>{if(J.requestId)K.setTag("requestId",J.requestId);if(J.userId)K.setUser({id:J.userId});if(J.traceId)K.setTag("traceId",J.traceId);if(J.route)K.setTag("route",J.route);if(J.method)K.setTag("method",J.method);K.setTag("errorCode",p.code),K.setTag("severity",p.severity),K.setTag("category",p.category),K.setLevel(this.mapSeverityToLevel(p.severity)),K.setExtra("statusCode",p.statusCode),K.setExtra("retryable",p.retryable),K.setExtra("timestamp",p.timestamp),K.setExtra("context",J);let fe=this.generateFingerprint(p);if(fe.length>0)K.setFingerprint(fe);return this.sentry.captureException(p)})}catch(J){return console.error("Failed to report error to Sentry:",J),null}}addBreadcrumb(p,y="default",J="info",K){if(!this.sentry||!this.config.breadcrumbs?.enabled)return;this.sentry.addBreadcrumb({message:p,category:y,level:J,data:K,timestamp:Date.now()/1000})}setUser(p){if(!this.sentry)return;this.sentry.setUser(p)}setTag(p,y){if(!this.sentry)return;this.sentry.setTag(p,y)}setExtra(p,y){if(!this.sentry)return;this.sentry.setExtra(p,y)}setContext(p,y){if(!this.sentry)return;this.sentry.setContext(p,y)}async close(p=2000){if(!this.sentry)return!0;return this.sentry.close(p)}shouldIgnoreError(p){let y=this.config.filters;if(!y)return!1;if(y.ignoreCodes?.includes(p.code))return!0;if(y.ignoreErrors?.some((J)=>{if(typeof J==="string")return p.message.includes(J);return J.test(p.message)}))return!0;return!1}mapSeverityToLevel(p){switch(p){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}generateFingerprint(p){let y=[];if(y.push(p.code),y.push(p.category),p.context.route)y.push(p.context.route);return y}}class Vr{config;bugsnag;constructor(p){this.config=p,this.initializeBugsnag()}async initializeBugsnag(){try{let p=await import("@bugsnag/js");p.start({apiKey:this.config.apiKey,appVersion:this.config.release,releaseStage:this.config.environment||"production",enabledReleaseStages:["production","staging"],maxBreadcrumbs:this.config.breadcrumbs?.maxBreadcrumbs||25,onError:(y)=>{let J=y.originalError;if(J&&this.config.beforeSend)return this.config.beforeSend(J,J.context)!==null;return!this.shouldIgnoreError(J)}}),this.bugsnag=p}catch(p){console.warn("Failed to initialize Bugsnag:",p)}}async report(p,y){if(!this.bugsnag||!this.config.enabled)return null;try{if(this.shouldIgnoreError(p))return null;let J={...p.context,...y};return this.bugsnag.notify(p,(K)=>{if(K.severity=this.mapSeverityToBugsnag(p.severity),K.context=J.route||J.url,J.userId)K.setUser(J.userId,void 0,void 0);K.addMetadata("error",{code:p.code,category:p.category,statusCode:p.statusCode,retryable:p.retryable,timestamp:p.timestamp}),K.addMetadata("request",{requestId:J.requestId,method:J.method,url:J.url,userAgent:J.userAgent,ip:J.ip}),K.groupingHash=this.generateGroupingHash(p)}),"reported"}catch(J){return console.error("Failed to report error to Bugsnag:",J),null}}addBreadcrumb(p,y="manual",J="info",K){if(!this.bugsnag||!this.config.breadcrumbs?.enabled)return;this.bugsnag.leaveBreadcrumb(p,K,y)}setUser(p){if(!this.bugsnag)return;this.bugsnag.setUser(p.id,p.email,p.username)}setTag(p,y){if(!this.bugsnag)return;this.bugsnag.addMetadata("tags",{[p]:y})}setExtra(p,y){if(!this.bugsnag)return;this.bugsnag.addMetadata("extra",{[p]:y})}setContext(p,y){if(!this.bugsnag)return;this.bugsnag.addMetadata(p,y)}async close(){return!0}shouldIgnoreError(p){let y=this.config.filters;if(!y)return!1;if(y.ignoreCodes?.includes(p.code))return!0;if(y.ignoreErrors?.some((J)=>{if(typeof J==="string")return p.message.includes(J);return J.test(p.message)}))return!0;return!1}mapSeverityToBugsnag(p){switch(p){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"error";default:return"warning"}}generateGroupingHash(p){return`${p.code}-${p.category}-${p.context.route||"unknown"}`}}class pn{config;reportHandler;constructor(p,y){this.config=p,this.reportHandler=y}async report(p,y){if(!this.config.enabled)return null;try{let J={...p.context,...y};if(this.config.beforeSend){if(!this.config.beforeSend(p,J))return null}let K={error:p,context:J,level:this.mapSeverityToLevel(p.severity),tags:this.config.tags,extra:this.config.extra,user:this.config.user};return await this.reportHandler(K)}catch(J){return console.error("Failed to report error with custom handler:",J),null}}addBreadcrumb(){}setUser(){}setTag(){}setExtra(){}setContext(){}async close(){return!0}mapSeverityToLevel(p){switch(p){case"low":return"info";case"medium":return"warning";case"high":return"error";case"critical":return"fatal";default:return"error"}}}class lr{reporters=[];breadcrumbs=[];maxBreadcrumbs=50;constructor(p){this.initializeReporters(p)}initializeReporters(p){for(let y of p){if(!y.enabled)continue;switch(y.service){case"sentry":this.reporters.push(new Jr(y));break;case"bugsnag":this.reporters.push(new Vr(y));break;case"custom":break}}}addReporter(p){this.reporters.push(p)}async report(p,y){let J=[];this.addBreadcrumb(`Error occurred: ${p.message}`,"error",{code:p.code,severity:p.severity});let K=this.reporters.map(async(fe)=>{try{let be=await fe.report(p,y);if(be)J.push(be)}catch(be){console.error("Reporter failed:",be)}});return await Promise.allSettled(K),J}addBreadcrumb(p,y="default",J){if(this.breadcrumbs.push({message:p,timestamp:new Date,data:{category:y,...J}}),this.breadcrumbs.length>this.maxBreadcrumbs)this.breadcrumbs=this.breadcrumbs.slice(-this.maxBreadcrumbs);this.reporters.forEach((K)=>{K.addBreadcrumb(p,y,"info",J)})}setUser(p){this.reporters.forEach((y)=>y.setUser(p))}setTag(p,y){this.reporters.forEach((J)=>J.setTag(p,y))}setExtra(p,y){this.reporters.forEach((J)=>J.setExtra(p,y))}setContext(p,y){this.reporters.forEach((J)=>J.setContext(p,y))}async close(p=5000){let y=this.reporters.map((K)=>K.close(p));return(await Promise.allSettled(y)).every((K)=>K.status==="fulfilled"&&K.value)}getBreadcrumbs(){return[...this.breadcrumbs]}}function Xn(p){return new lr(p)}var Qn={sentry:(p,y="production")=>({enabled:!0,service:"sentry",dsn:p,environment:y,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:(p,y="production")=>({enabled:!0,service:"bugsnag",apiKey:p,environment:y,breadcrumbs:{enabled:!0,maxBreadcrumbs:25},filters:{ignoreCodes:["VALIDATION_ERROR"]}}),development:()=>({enabled:!1,service:"custom",environment:"development"})};class zr{healthStatus=new Map;healthCheckIntervals=new Map;config;constructor(p){this.config=p,this.initializeHealthChecks()}initializeHealthChecks(){for(let[p,y]of Object.entries(this.config.healthChecks)){if(!y.enabled)continue;this.healthStatus.set(p,{name:p,status:"healthy",lastCheck:new Date,responseTime:0,errorRate:0,availability:100,consecutiveFailures:0});let J=setInterval(()=>this.performHealthCheck(p,y),y.interval);J.unref?.(),this.healthCheckIntervals.set(p,J)}}async performHealthCheck(p,y){let J=Date.now(),K=!1;try{let be=new AbortController,We=setTimeout(()=>be.abort(),y.timeout),Ve=await fetch(y.endpoint,{signal:be.signal,headers:y.headers,method:"GET"});if(clearTimeout(We),K=y.expectedStatus.includes(Ve.status),K&&y.expectedBody){let ot=await Ve.text();if(typeof y.expectedBody==="string")K=ot.includes(y.expectedBody);else K=y.expectedBody.test(ot)}}catch(be){console.error(be),K=!1}let fe=Date.now()-J;if(this.updateHealthStatus(p,K,fe),K&&y.onHealthy)y.onHealthy();else if(!K&&y.onUnhealthy)y.onUnhealthy(Error(`Health check failed for ${p}`))}updateHealthStatus(p,y,J){let K=this.healthStatus.get(p);if(!K)return;let fe={...K,lastCheck:new Date,responseTime:J,consecutiveFailures:y?0:K.consecutiveFailures+1};if(fe.consecutiveFailures===0)fe.status="healthy";else if(fe.consecutiveFailures<3)fe.status="degraded";else fe.status="unhealthy";let be=y?1:0;fe.availability=K.availability*0.9+be*10,this.healthStatus.set(p,fe)}getServiceHealth(p){return this.healthStatus.get(p)}getAllServiceHealth(){return Array.from(this.healthStatus.values())}isServiceHealthy(p){return this.healthStatus.get(p)?.status==="healthy"}isServiceDegraded(p){return this.healthStatus.get(p)?.status==="degraded"}stop(){for(let p of this.healthCheckIntervals.values())clearInterval(p);this.healthCheckIntervals.clear()}}class Hr{config;healthMonitor;cache=new Map;metrics=new Map;constructor(p){this.config=p,this.healthMonitor=new zr(p)}async handleFailure(p,y,J,K){if(!this.config.enabled)throw y;let fe=this.config.fallbackStrategies[p];if(!fe)throw y;let be={request:J,serviceName:p,error:y,attemptCount:1,startTime:new Date};return this.executeFallbackStrategy(fe,be,K)}async executeFallbackStrategy(p,y,J){if(y.attemptCount<=p.retries)try{if(y.attemptCount>1){let be=this.calculateBackoffDelay(p.backoff,y.attemptCount);await this.sleep(be)}let K=new Promise((be,We)=>{setTimeout(()=>We(Error("Timeout")),p.timeout)}),fe=await Promise.race([J(),K]);return this.updateMetrics(y.serviceName,!0,Date.now()-y.startTime.getTime()),fe}catch(K){if(console.error(K),y.attemptCount++,y.attemptCount<=p.retries)return this.executeFallbackStrategy(p,y,J)}switch(this.updateMetrics(y.serviceName,!1,Date.now()-y.startTime.getTime()),p.type){case"cache":return this.handleCacheFallback(p,y);case"static":return this.handleStaticFallback(p,y);case"simplified":return this.handleSimplifiedFallback(p,y);case"redirect":return this.handleRedirectFallback(p,y);case"custom":return this.handleCustomFallback(p,y);default:throw y.error}}async handleCacheFallback(p,y){if(!p.cacheConfig)throw y.error;let J=this.generateCacheKey(p.cacheConfig.key,y),K=this.cache.get(J);if(K&&(K.expires>new Date||p.cacheConfig.staleWhileRevalidate)){let fe=new Headers({"Content-Type":"application/json","X-Cache":"HIT","X-Degraded":"true","X-Service-Status":this.healthMonitor.getServiceHealth(y.serviceName)?.status||"unknown"});if(p.cacheConfig.staleWhileRevalidate&&K.expires<=new Date)fe.set("X-Cache","STALE");return new Response(JSON.stringify(K.data),{status:200,headers:fe})}throw y.error}async handleStaticFallback(p,y){if(!p.staticResponse)throw y.error;let J=new Headers(p.staticResponse.headers||{});return J.set("X-Degraded","true"),J.set("X-Fallback-Type","static"),J.set("X-Service-Status",this.healthMonitor.getServiceHealth(y.serviceName)?.status||"unknown"),new Response(typeof p.staticResponse.body==="string"?p.staticResponse.body:JSON.stringify(p.staticResponse.body),{status:p.staticResponse.status,headers:J})}async handleSimplifiedFallback(p,y){let J={message:"Service temporarily unavailable. Showing simplified view.",status:"degraded",timestamp:new Date().toISOString(),requestId:y.request.requestId};return new Response(JSON.stringify(J),{status:200,headers:{"Content-Type":"application/json","X-Degraded":"true","X-Fallback-Type":"simplified","X-Service-Status":this.healthMonitor.getServiceHealth(y.serviceName)?.status||"unknown"}})}async handleRedirectFallback(p,y){if(!p.redirectConfig)throw y.error;return new Response(null,{status:p.redirectConfig.permanent?301:302,headers:{Location:p.redirectConfig.url,"X-Degraded":"true","X-Fallback-Type":"redirect"}})}async handleCustomFallback(p,y){if(!p.fallbackHandler)throw y.error;try{let J=await p.fallbackHandler(y.error,y.error.context);return J.headers.set("X-Degraded","true"),J.headers.set("X-Fallback-Type","custom"),J.headers.set("X-Service-Status",this.healthMonitor.getServiceHealth(y.serviceName)?.status||"unknown"),J}catch(J){throw console.error(J),y.error}}cacheResponse(p,y,J,K){let fe=this.config.fallbackStrategies[p];if(fe?.type==="cache"&&fe.cacheConfig){let be=this.generateCacheKey(y,{serviceName:p});this.cache.set(be,{data:J,expires:new Date(Date.now()+K*1000)})}}getServiceMetrics(p){let y=this.metrics.get(p);if(!y||y.requests===0)return{errorRate:0,avgResponseTime:0,totalRequests:0};return{errorRate:y.errors/y.requests*100,avgResponseTime:y.totalTime/y.requests,totalRequests:y.requests}}getSystemHealth(){let p=this.healthMonitor.getAllServiceHealth(),y=p.filter((fe)=>fe.status==="unhealthy").length,J=p.filter((fe)=>fe.status==="degraded").length,K="healthy";if(y>0)K=y>p.length/2?"unhealthy":"degraded";else if(J>0)K="degraded";return{status:K,services:p}}calculateBackoffDelay(p,y){if(p.type==="fixed")return p.delay;let J=p.delay*2**(y-1);return Math.min(J,p.maxDelay||30000)}generateCacheKey(p,y){return p.replace("{service}",y.serviceName).replace("{url}",y.request.url).replace("{method}",y.request.method).replace("{userId}",String(y.request.user?.id||"anonymous"))}updateMetrics(p,y,J){let K=this.metrics.get(p)||{requests:0,errors:0,totalTime:0};if(K.requests++,K.totalTime+=J,!y)K.errors++;this.metrics.set(p,K)}sleep(p){return new Promise((y)=>setTimeout(y,p))}stop(){this.healthMonitor.stop()}}function Zn(p){let y=new Hr(p);return async(J,K)=>{try{let fe=await K(),be=J.context?.serviceName;if(be&&fe.ok){let We=p.fallbackStrategies[be];if(We?.type==="cache"&&We.cacheConfig)try{let Ve=await fe.clone().json();y.cacheResponse(be,We.cacheConfig.key,Ve,We.cacheConfig.ttl)}catch{}}return fe}catch(fe){let be=J.context?.serviceName;if(be&&fe instanceof Error){let We=fe;try{return await y.handleFailure(be,We,J,K)}catch(Ve){throw console.error(Ve),fe}}throw fe}}}var Yn={cacheFirst:(p=3600,y=!0)=>({type:"cache",priority:1,timeout:5000,retries:2,backoff:{type:"exponential",delay:1000,maxDelay:5000},cacheConfig:{key:"{service}:{url}:{method}",ttl:p,staleWhileRevalidate:y}}),staticFallback:(p,y=200)=>({type:"static",priority:2,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},staticResponse:{status:y,body:p,headers:{"Content-Type":"application/json"}}}),simplifiedView:()=>({type:"simplified",priority:3,timeout:1000,retries:0,backoff:{type:"fixed",delay:0}}),redirectToMaintenance:(p)=>({type:"redirect",priority:4,timeout:1000,retries:0,backoff:{type:"fixed",delay:0},redirectConfig:{url:p,permanent:!1}})};class hn{errorReporting;gracefulDegradation;circuitBreakerRegistry;config;constructor(p={}){this.config={development:!1,includeStackTrace:!1,sanitizeErrors:!0,logErrors:!0,...p},this.initializeComponents()}initializeComponents(){if(this.config.errorReporting?.length)this.errorReporting=new lr(this.config.errorReporting);if(this.config.gracefulDegradation?.enabled)this.gracefulDegradation=new Hr(this.config.gracefulDegradation);if(this.config.circuitBreakers?.length){this.circuitBreakerRegistry=new dr;for(let p of this.config.circuitBreakers)this.circuitBreakerRegistry.register(p)}}middleware(){return async(p,y)=>{try{let J={requestId:p.requestId,userId:p.user?.id,traceId:p.traceId,spanId:p.spanId,route:p.params?.route||p.url,method:p.method,url:p.url,userAgent:p.userAgent?.()||void 0,ip:p.ip?.()||void 0,timestamp:new Date};if(p.context={...p.context,errorContext:J},this.circuitBreakerRegistry&&p.context?.serviceName){let K=this.circuitBreakerRegistry.get(p.context.serviceName);if(K)return await K.execute({execute:y,context:J})}return await y()}catch(J){return this.handleError(J,p)}}}async handleError(p,y){let J=this.normalizeError(p,y);if(this.errorReporting)this.errorReporting.addBreadcrumb(`Error in ${y.method} ${y.url}`,"error",{code:J.code,severity:J.severity,statusCode:J.statusCode});if(this.config.logErrors)this.logError(J,y);if(this.gracefulDegradation&&y.context?.serviceName)try{return await this.gracefulDegradation.handleFailure(y.context.serviceName,J,y,async()=>{throw J})}catch{}if(this.errorReporting)try{await this.errorReporting.report(J,J.context)}catch(fe){console.error("Failed to report error:",fe)}if(this.config.globalErrorHandler)try{return await this.config.globalErrorHandler(J,y)}catch(fe){console.error("Global error handler failed:",fe)}let K=this.config.customErrorPages?.[J.statusCode];if(K)try{if(typeof K==="string")return new Response(K,{status:J.statusCode,headers:{"Content-Type":"text/html"}});else return await K(J,y)}catch(fe){console.error("Custom error page failed:",fe)}return this.createErrorResponse(J,y)}normalizeError(p,y){let J={requestId:y.requestId,userId:y.user?.id,traceId:y.traceId,spanId:y.spanId,route:y.params?.route||y.url,method:y.method,url:y.url,userAgent:y.userAgent?.()||void 0,ip:y.ip?.()||void 0,timestamp:new Date,metadata:y.context};if(p instanceof t)return p;if(p instanceof Error){if(p.name==="ValidationError")return d.validation(p.message,{},J);if(p.name==="UnauthorizedError"||p.message.includes("unauthorized"))return d.authentication(p.message,J);if(p.name==="ForbiddenError"||p.message.includes("forbidden"))return d.authorization(p.message,[],J);if(p.name==="NotFoundError"||p.message.includes("not found"))return d.notFound(void 0,void 0,J);if(p.name==="TimeoutError"||p.message.includes("timeout"))return d.timeout(30000,p.message,J);return d.internalServer(p.message,p,J)}if(typeof p==="string")return d.internalServer(p,void 0,J);return d.internalServer("An unknown error occurred",void 0,J)}createErrorResponse(p,y){let J=this.config.development,K=this.config.includeStackTrace||J,fe=this.config.sanitizeErrors&&!J,be=p.message;if(fe&&p.statusCode>=500)be="An internal server error occurred";let We={error:{code:p.code,message:be,statusCode:p.statusCode,timestamp:p.timestamp.toISOString(),requestId:p.context.requestId,traceId:p.context.traceId}};if(J)We.error.category=p.category,We.error.severity=p.severity,We.error.retryable=p.retryable,We.error.context=p.context;if(K){if(We.error.stack=p.stack,p.cause)We.error.cause={name:p.cause.name,message:p.cause.message,stack:p.cause.stack}}if("fields"in p)We.error.fields=p.fields;if("allowedMethods"in p)We.error.allowedMethods=p.allowedMethods;if("retryAfter"in p)We.error.retryAfter=p.retryAfter;let Ve=new Headers({"Content-Type":"application/json","X-Error-Code":p.code,"X-Request-ID":p.context.requestId||"","X-Trace-ID":p.context.traceId||""});if("allowedMethods"in p)Ve.set("Allow",p.allowedMethods.join(", "));if("retryAfter"in p)Ve.set("Retry-After",p.retryAfter.toString());if("limit"in p)Ve.set("X-RateLimit-Limit",p.limit.toString()),Ve.set("X-RateLimit-Remaining",p.remaining.toString());return new Response(JSON.stringify(We),{status:p.statusCode,headers:Ve})}logError(p,y){let J={error:p.toJSON(),request:{method:y.method,url:y.url,headers:Object.fromEntries(y.headers.entries()),userAgent:y.userAgent?.()||void 0,ip:y.ip?.()||void 0,requestId:y.requestId,traceId:y.traceId}};switch(p.severity){case"critical":console.error("[CRITICAL ERROR]",J);break;case"high":console.error("[ERROR]",J);break;case"medium":console.warn("[WARNING]",J);break;case"low":console.warn("[INFO]",J);break;default:console.error("[ERROR]",J)}}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 mn(p={}){let y=new hn(p);return{middleware:y.middleware(),getStats:()=>y.getStats(),cleanup:()=>y.cleanup()}}import es from"process";class Kr{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(p){this.dependencyRegistry.set(p.name,p)}compileMiddleware(p,y,J=[]){let K=[];for(let fe=0;fe<y.length;fe++){let be=y[fe],We=be.name||`middleware_${fe}`;K.push({handler:be,name:We,skipConditions:J.filter((Ve)=>Ve.name.includes(We)||Ve.name==="global"),dependencies:this.extractDependencies(be),canShortCircuit:this.canShortCircuit(be),priority:fe})}this.compiledPipelines.set(p,K)}async execute(p,y,J){let K=performance.now();this.stats.totalExecutions++;let fe=this.compiledPipelines.get(p);if(!fe)return this.stats.cacheMisses++,await J();this.stats.cacheHits++;let be={request:y,dependencies:new Map,metadata:{}};await this.resolveDependencies(be,fe);let We=0,Ve=async()=>{if(We>=fe.length)return await J();let dt=fe[We++];if(await this.shouldSkip(dt,be))return this.stats.skippedMiddleware++,await Ve();let ut=await dt.handler(y,Ve);if(ut instanceof Response&&dt.canShortCircuit)return this.stats.shortCircuits++,ut;return ut},ot=await Ve(),at=performance.now()-K;return this.updateAverageExecutionTime(at),ot||new Response("Internal Server Error",{status:500})}async shouldSkip(p,y){for(let J of p.skipConditions)if(await J.condition(y))return!0;return!1}async resolveDependencies(p,y){let J=new Set;for(let K of y)for(let fe of K.dependencies)J.add(fe);for(let K of J){let fe=this.dependencyRegistry.get(K);if(!fe)continue;if(this.stats.dependencyResolutions++,fe.singleton&&this.singletonInstances.has(K))p.dependencies.set(K,this.singletonInstances.get(K));else{let be=await fe.factory(p);if(p.dependencies.set(K,be),fe.singleton)this.singletonInstances.set(K,be)}}}extractDependencies(p){let y=p.toString(),J=[];if(y.includes("database")||y.includes("db"))J.push("database");if(y.includes("logger")||y.includes("log"))J.push("logger");if(y.includes("cache"))J.push("cache");if(y.includes("httpClient")||y.includes("http"))J.push("httpClient");return J}canShortCircuit(p){let y=p.toString();return y.includes("return")&&y.includes("Response")}updateAverageExecutionTime(p){let y=this.stats.averageExecutionTime*(this.stats.totalExecutions-1);this.stats.averageExecutionTime=(y+p)/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 ts={skipForMethods:(p)=>({name:`skip_for_methods_${p.join("_")}`,condition:(y)=>p.includes(y.request.method)}),skipForPaths:(p)=>({name:`skip_for_paths_${p.join("_").replace(/\//g,"_")}`,condition:(y)=>{let J=new URL(y.request.url);return p.some((K)=>J.pathname.startsWith(K))}}),skipForHeaders:(p)=>({name:`skip_for_headers_${Object.keys(p).join("_")}`,condition:(y)=>Object.entries(p).some(([J,K])=>y.request.headers.get(J)===K)}),skipForRoles:(p)=>({name:`skip_for_roles_${p.join("_")}`,condition:(y)=>{let J=y.request.user?.roles||[];return!p.some((K)=>J.includes(K))}}),skipForEnvironment:(p)=>({name:`skip_for_env_${p.join("_")}`,condition:()=>{let y=es.env.NODE_ENV||"development";return p.includes(y)}})},rs={database:(p)=>({name:"database",factory:async()=>({query:async(y)=>({rows:[]}),close:async()=>{},connectionString:p||"mock://database"}),singleton:!0}),logger:(p="info")=>({name:"logger",factory:()=>({info:(y)=>console.log(`[INFO] ${y}`),error:(y)=>console.error(`[ERROR] ${y}`),warn:(y)=>console.warn(`[WARN] ${y}`),debug:(y)=>console.debug(`[DEBUG] ${y}`),level:p}),singleton:!0}),cache:(p=1000)=>({name:"cache",factory:()=>{let y=new Map;return{get:(J)=>y.get(J),set:(J,K)=>{if(y.size>=p){let fe=y.keys().next().value;y.delete(fe)}y.set(J,K)},delete:(J)=>y.delete(J),clear:()=>y.clear(),size:()=>y.size}},singleton:!0}),httpClient:(p)=>({name:"httpClient",factory:()=>({get:async(y)=>fetch(p?`${p}${y}`:y),post:async(y,J)=>fetch(p?`${p}${y}`:y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}),put:async(y,J)=>fetch(p?`${p}${y}`:y,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}),delete:async(y)=>fetch(p?`${p}${y}`:y,{method:"DELETE"})}),singleton:!0})},ns={auth:(p={})=>async(y,J)=>{let K=new URL(y.url);if(p.skipPaths?.some((be)=>K.pathname.startsWith(be)))return await J();if(!y.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});try{return y.user={id:"123",roles:["user"]},await J()}catch{return new Response("Invalid token",{status:401})}},rateLimit:(p)=>{let y=new Map;return async(J,K)=>{let fe=J.headers.get("x-forwarded-for")||"unknown",be=Date.now(),We=be-p.windowMs;if(!y.has(fe))y.set(fe,[]);let ot=y.get(fe).filter((at)=>at>We);if(ot.length>=p.maxRequests)return new Response("Too Many Requests",{status:429});return ot.push(be),y.set(fe,ot),await K()}},cors:(p={})=>async(y,J)=>{let K=await J();if(K){let fe=new Headers(K.headers);return fe.set("Access-Control-Allow-Origin",p.origin||"*"),fe.set("Access-Control-Allow-Methods",p.methods?.join(", ")||"GET, POST, PUT, DELETE"),fe.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(K.body,{status:K.status,statusText:K.statusText,headers:fe})}return K},logging:(p={})=>async(y,J)=>{let K=performance.now(),fe=new URL(y.url);console.log(`[${new Date().toISOString()}] ${y.method} ${fe.pathname}`);let be=await J(),We=performance.now()-K;if(be)console.log(`[${new Date().toISOString()}] ${y.method} ${fe.pathname} - ${be.status} (${We.toFixed(2)}ms)`);return be}},ss=new Kr;class Dr extends Error{modelName;value;field;constructor(p,y,J="id"){super(`${p} not found with ${J}: ${y}`);this.modelName=p;this.value=y;this.field=J;this.name="ModelNotFoundError"}}class yn{bindings=new Map;model(p,y){this.bindings.set(p,y)}bind(p,y){this.bindings.set(p,y)}getBinding(p){return this.bindings.get(p)}hasBinding(p){return this.bindings.has(p)}}var is=new yn;async function fn(p,y,J,K,fe={}){if(K)return await J.resolveRouteBinding(y,K);let be=J.getRouteKeyName();if(be!=="id")return await J.resolveRouteBinding(y,be);return await J.find(y)}function Rn(p,y){return async(J,K)=>{let fe={};try{for(let be of p){let We=J.params?.[be.name];if(!We)continue;let Ve=is.getBinding(be.name);if(Ve){let dt=null;if(typeof Ve==="function")dt=await Ve(We);else dt=await fn(be.name,We,Ve,be.key,fe);if(!dt)throw new Dr(be.name,We,be.key||"id");fe[be.name]=dt;continue}let ot=y[be.name];if(!ot)continue;let at=await fn(be.name,We,ot,be.key,fe);if(!at)throw new Dr(be.name,We,be.key||"id");fe[be.name]=at}return J.models=fe,await K()}catch(be){if(be instanceof Dr)return new Response(`${be.modelName} not found`,{status:404});throw be}}}class wn{static generateKey(p,y){let J=new URL(p.url),K=p.method,fe=J.pathname,be=[K,fe],We=new URLSearchParams(J.search),Ve=y.excludeQuery||[],ot=[];for(let[at,dt]of We.entries())if(!Ve.includes(at))ot.push(`${at}=${dt}`);if(ot.length>0)be.push(ot.sort().join("&"));if(y.varyBy){let at=[];for(let dt of y.varyBy){let ut=p.headers.get(dt);if(ut)at.push(`${dt}:${ut}`)}if(at.length>0)be.push(at.join("|"))}return be.join("::")}}class bn{cache;tagIndex=new Map;keyTags=new Map;constructor(p=1000){this.cache=new _({maxSize:p})}async get(p){let y=this.cache.get(p);if(!y)return null;if(y.ttl&&Date.now()-y.timestamp>y.ttl)return this.delete(p),null;return y}async set(p,y){this.cache.set(p,y),this.keyTags.set(p,new Set(y.tags));for(let J of y.tags){if(!this.tagIndex.has(J))this.tagIndex.set(J,new Set);this.tagIndex.get(J).add(p)}}delete(p){let y=this.keyTags.get(p);if(y){for(let J of y){let K=this.tagIndex.get(J);if(K){if(K.delete(p),K.size===0)this.tagIndex.delete(J)}}this.keyTags.delete(p)}return this.cache.delete(p)}invalidateByTags(p){let y=new Set;for(let J of p){let K=this.tagIndex.get(J);if(K)for(let fe of K)y.add(fe)}for(let J of y)this.delete(J);return y.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 ur=new bn;function Tn(p){return async(y,J)=>{if(p.condition&&!p.condition(y))return await J();if(y.method!=="GET"&&y.method!=="HEAD")return await J();let K=wn.generateKey(y,p),fe=await ur.get(K);if(fe){let We=new Headers(fe.headers);if(We.set("X-Cache","HIT"),We.set("X-Cache-Key",K),fe.etag){if(We.set("ETag",fe.etag),y.headers.get("If-None-Match")===fe.etag)return new Response(null,{status:304,headers:We})}return new Response(fe.body,{status:fe.status,headers:We})}let be=await J();if(be.status>=200&&be.status<300)try{let We=be.clone(),Ve=await We.arrayBuffer(),ot=await os(Ve),at={};We.headers.forEach((lt,mt)=>{at[mt]=lt});let dt={response:We,headers:at,status:be.status,body:new Uint8Array(Ve),timestamp:Date.now(),ttl:p.ttl,tags:p.tags||[],etag:ot};await ur.set(K,dt);let ut=new Headers(be.headers);return ut.set("X-Cache","MISS"),ut.set("X-Cache-Key",K),ut.set("ETag",ot),new Response(be.body,{status:be.status,headers:ut})}catch(We){return console.error("Error caching response:",We),be}return be}}async function os(p){let y=await crypto.subtle.digest("SHA-256",p);return`"${Array.from(new Uint8Array(y)).map((fe)=>fe.toString(16).padStart(2,"0")).join("").substring(0,16)}"`}var xn={short:(p=[])=>({ttl:300000,maxSize:500,tags:p}),medium:(p=[])=>({ttl:3600000,maxSize:1000,tags:p}),long:(p=[])=>({ttl:86400000,maxSize:2000,tags:p}),api:(p=[])=>({ttl:900000,maxSize:1000,tags:p,varyBy:["Authorization","Accept","Accept-Language"],excludeQuery:["_t","timestamp","cache_bust"]}),static:(p=[])=>({ttl:604800000,maxSize:5000,tags:p,varyBy:["Accept-Encoding"]}),user:(p=[])=>({ttl:1800000,maxSize:2000,tags:p,varyBy:["Authorization"],condition:(y)=>!!y.headers.get("Authorization")})},Gs={byTags:(p)=>ur.invalidateByTags(p),forUser:(p)=>ur.invalidateByTags([`user:${p}`]),forModel:(p,y)=>{let J=y?[`${p}:${y}`,p]:[p];return ur.invalidateByTags(J)},all:()=>{ur.clear()}};class Rt{static parseDomainPattern(p){let y=[],J=p.match(/\{([^}]+)\}/g)||[];for(let be of J){let We=be.slice(1,-1);y.push(We)}let K=p.replace(/\./g,"\\.").replace(/\{([^}]+)\}/g,"([^.]+)");K=`^${K}$`;let fe=new RegExp(K,"i");return{pattern:p,parameters:y,regex:fe}}static matchDomain(p,y){let J=p.match(y.regex);if(!J)return null;let K={};for(let fe=0;fe<y.parameters.length;fe++){let be=y.parameters[fe],We=J[fe+1];K[be]=We}return K}static extractSubdomainInfo(p){let y=p.split(".");if(y.length<=2)return{domain:p,parameters:{},rootDomain:p};let J=y[0],K=y.slice(1).join(".");return{domain:p,parameters:{subdomain:J},subdomain:J,rootDomain:K}}}class qr{pattern;config;routes=[];constructor(p,y){this.pattern=p;this.config=y}addRoute(p,y,J,K=[],fe){let be=[...this.config.middleware||[],...K],We=this.config.prefix?`${this.config.prefix}${y}`:y;this.routes.push({method:p.toUpperCase(),path:We,handler:J,middleware:be,name:fe||(this.config.name?`${this.config.name}.${p.toLowerCase()}${y}`:void 0)})}getRoutes(){return[...this.routes]}matchesDomain(p){return Rt.matchDomain(p,this.pattern)}}class Xr{domainGroups=[];wildcardGroup;domain(p){let y=Rt.parseDomainPattern(p);return new vn(this,y)}addDomainGroup(p){if(p.pattern.pattern.includes("*")&&p.pattern.parameters.length===0)this.wildcardGroup=p;else this.domainGroups.push(p)}findDomainGroup(p){for(let y of this.domainGroups){let J=y.matchesDomain(p);if(J!==null)return{group:y,parameters:J}}if(this.wildcardGroup)return{group:this.wildcardGroup,parameters:Rt.extractSubdomainInfo(p).parameters};return null}getAllRoutes(){let p=[];for(let y of this.domainGroups){let J=y.getRoutes();for(let K of J)p.push({domainPattern:y.pattern.pattern,domainParameters:{},...K})}if(this.wildcardGroup){let y=this.wildcardGroup.getRoutes();for(let J of y)p.push({domainPattern:this.wildcardGroup.pattern.pattern,domainParameters:{},...J})}return p}}class vn{router;pattern;group;constructor(p,y){this.router=p;this.pattern=y;this.group=new qr(y,{domain:y.pattern})}middleware(p){return this.group.config.middleware=p,this}prefix(p){return this.group.config.prefix=p,this}name(p){return this.group.config.name=p,this}routes(p){let y=new Mn(this.group);p(y),this.router.addDomainGroup(this.group)}get(p,y,J){this.group.addRoute("GET",p,y,J),this.router.addDomainGroup(this.group)}post(p,y,J){this.group.addRoute("POST",p,y,J),this.router.addDomainGroup(this.group)}put(p,y,J){this.group.addRoute("PUT",p,y,J),this.router.addDomainGroup(this.group)}delete(p,y,J){this.group.addRoute("DELETE",p,y,J),this.router.addDomainGroup(this.group)}patch(p,y,J){this.group.addRoute("PATCH",p,y,J),this.router.addDomainGroup(this.group)}}class Mn{group;constructor(p){this.group=p}get(p,y,J,K){this.group.addRoute("GET",p,y,J,K)}post(p,y,J,K){this.group.addRoute("POST",p,y,J,K)}put(p,y,J,K){this.group.addRoute("PUT",p,y,J,K)}delete(p,y,J,K){this.group.addRoute("DELETE",p,y,J,K)}patch(p,y,J,K){this.group.addRoute("PATCH",p,y,J,K)}options(p,y,J,K){this.group.addRoute("OPTIONS",p,y,J,K)}head(p,y,J,K){this.group.addRoute("HEAD",p,y,J,K)}any(p,y,J,K){let fe=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];for(let be of fe)this.group.addRoute(be,p,y,J,K)}}function Vs(p){return async(y,J)=>{let fe=new URL(y.url).hostname,be=p.findDomainGroup(fe);if(be){let We=y;We.domainParams=be.parameters,Object.assign(y.params||{},be.parameters);let Ve=Rt.extractSubdomainInfo(fe);We.subdomainInfo=Ve}return await J()}}var zs={getSubdomain:(p)=>{let y=new URL(p.url);return Rt.extractSubdomainInfo(y.hostname).subdomain||null},getDomainParams:(p)=>p.domainParams||{},matchesDomain:(p,y)=>{let J=new URL(p.url),K=Rt.parseDomainPattern(y);return Rt.matchDomain(J.hostname,K)!==null},getSubdomainInfo:(p)=>p.subdomainInfo||null},Ks={single:(p,y)=>`${p}.${y}`,wildcard:(p,y="subdomain")=>`{${y}}.${p}`,multiLevel:(p,...y)=>`${y.map((K)=>`{${K}}`).join(".")}.${p}`,apiVersion:(p)=>`{version}.api.${p}`,tenant:(p)=>`{tenant}.app.${p}`,environment:(p)=>`{env}.${p}`};class ct{method;path;handler;middleware=[];cacheConfig;throttleConfig;routeName;modelBindings={};constructor(p,y,J){this.method=p;this.path=y;this.handler=J}addMiddleware(p){if(Array.isArray(p))this.middleware.push(...p);else this.middleware.push(p);return this}cached(p=[],y){return this.cacheConfig={...xn.api(p),...y},this}throttle(p,y){if(typeof p==="string"){let J=S(p);this.throttleConfig={maxAttempts:J.maxAttempts??60,windowMs:J.windowMs,keyGenerator:(K)=>K.headers.get("x-forwarded-for")||"anonymous"}}else this.throttleConfig=p;return this}name(p){return this.routeName=p,this}model(p,y){return this.modelBindings[p]=y,this}build(){let p=[];if(Object.keys(this.modelBindings).length>0){let y=Object.keys(this.modelBindings).map((K)=>({name:K})),J=Rn(y,this.modelBindings);p.push(J)}if(this.throttleConfig){let y=C(this.throttleConfig);p.push(y)}if(this.cacheConfig){let y=Tn(this.cacheConfig);p.push(y)}return p.push(...this.middleware),{method:this.method,path:this.path,handler:this.handler,middleware:p,name:this.routeName}}}class En{router;condition;constructor(p,y){this.router=p;this.condition=y}middleware(p){let[y,J]=p.split(":"),K=this.router.resolveNamedMiddleware(y);if(!K)throw Error(`Unknown middleware: ${y}`);return this.router.addConditionalMiddleware({condition:this.condition,middleware:[K(J)]}),this}}class Cn{router;middleware;constructor(p,y){this.router=p;this.middleware=y}get(p,y){return new ct("GET",p,y).addMiddleware(this.middleware)}post(p,y){return new ct("POST",p,y).addMiddleware(this.middleware)}put(p,y){return new ct("PUT",p,y).addMiddleware(this.middleware)}delete(p,y){return new ct("DELETE",p,y).addMiddleware(this.middleware)}patch(p,y){return new ct("PATCH",p,y).addMiddleware(this.middleware)}}class Pn{router;groupMiddleware;constructor(p,y){this.router=p;this.groupMiddleware=y}get(p,y){return new ct("GET",p,y).addMiddleware(this.groupMiddleware)}post(p,y){return new ct("POST",p,y).addMiddleware(this.groupMiddleware)}put(p,y){return new ct("PUT",p,y).addMiddleware(this.groupMiddleware)}delete(p,y){return new ct("DELETE",p,y).addMiddleware(this.groupMiddleware)}patch(p,y){return new ct("PATCH",p,y).addMiddleware(this.groupMiddleware)}}class Or{routes=[];globalMiddleware=[];subdomainRouter=new Xr;routeGroups=[];middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];constructor(){this.setupDefaultMiddleware()}setupDefaultMiddleware(){this.namedMiddleware.set("throttle",(p)=>{let y=p?S(p):{maxAttempts:60,windowMs:60000},J=C({maxAttempts:y.maxAttempts,windowMs:y.windowMs,keyGenerator:(fe)=>fe.headers.get("x-forwarded-for")||"anonymous"});return async(fe,be)=>await J(fe,async()=>await be()??new Response(null))}),this.namedMiddleware.set("auth",()=>async(p,y)=>{if(!p.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return p.user={id:"123",roles:["user"]},await y()}),this.namedMiddleware.set("cors",()=>async(p,y)=>{let J=await y();if(J){let K=new Headers(J.headers);return K.set("Access-Control-Allow-Origin","*"),K.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"),K.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(J.body,{status:J.status,statusText:J.statusText,headers:K})}return J})}middlewareGroup(p,y){let J=[];for(let K of y){let[fe,be]=K.split(":"),We=this.namedMiddleware.get(fe);if(We)J.push(We(be))}return this.middlewareGroups.set(p,J),this}middlewareGroupRoutes(p){let y=this.middlewareGroups.get(p)||[];return new Pn(this,y)}when(p){return new En(this,p)}resolveNamedMiddleware(p){return this.namedMiddleware.get(p)}addConditionalMiddleware(p){this.conditionalMiddleware.push(p)}middleware(p){let[y,J]=p.split(":"),K=this.namedMiddleware.get(y);if(!K)throw Error(`Unknown middleware: ${y}`);let fe=K(J);return new Cn(this,[fe])}use(p){return this.globalMiddleware.push(p),this}get(p,y){return new ct("GET",p,y)}post(p,y){return new ct("POST",p,y)}put(p,y){return new ct("PUT",p,y)}delete(p,y){return new ct("DELETE",p,y)}patch(p,y){return new ct("PATCH",p,y)}register(p){let y=p.build();if(this.routes.push(y),y.name)g(y.name,y.path);return this}cached(p=[],y){return{get:(J,K)=>this.get(J,K).cached(p,y),post:(J,K)=>this.post(J,K).cached(p,y),put:(J,K)=>this.put(J,K).cached(p,y),delete:(J,K)=>this.delete(J,K).cached(p,y),patch:(J,K)=>this.patch(J,K).cached(p,y)}}throttled(p){return{get:(y,J)=>this.get(y,J).throttle(p),post:(y,J)=>this.post(y,J).throttle(p),put:(y,J)=>this.put(y,J).throttle(p),delete:(y,J)=>this.delete(y,J).throttle(p),patch:(y,J)=>this.patch(y,J).throttle(p)}}group(p,y){let J=new Or;y(J);for(let K of J.routes){let fe={...K,path:p.prefix?`${p.prefix}${K.path}`:K.path,middleware:[...p.middleware||[],...K.middleware],name:p.name&&K.name?`${p.name}.${K.name}`:K.name};if(p.domain){let be=Rt.parseDomainPattern(p.domain),We=new qr(be,{domain:p.domain});We.addRoute(fe.method,fe.path,fe.handler,fe.middleware,fe.name),this.subdomainRouter.addDomainGroup(We)}else if(this.routes.push(fe),fe.name)g(fe.name,fe.path)}return this}domain(p){return{routes:(y)=>{let J=new Or;y(J);let K=Rt.parseDomainPattern(p),fe=new qr(K,{domain:p});for(let be of J.routes)fe.addRoute(be.method,be.path,be.handler,be.middleware,be.name);return this.subdomainRouter.addDomainGroup(fe),this}}}resource(p,y,J={}){let K=["index","create","store","show","edit","update","destroy"],fe=J.only||K.filter((We)=>!J.except?.includes(We)),be=[{action:"index",method:"GET",path:`/${p}`,handler:y.index},{action:"create",method:"GET",path:`/${p}/create`,handler:y.create},{action:"store",method:"POST",path:`/${p}`,handler:y.store},{action:"show",method:"GET",path:`/${p}/{${p.slice(0,-1)}}`,handler:y.show},{action:"edit",method:"GET",path:`/${p}/{${p.slice(0,-1)}}/edit`,handler:y.edit},{action:"update",method:"PUT",path:`/${p}/{${p.slice(0,-1)}}`,handler:y.update},{action:"destroy",method:"DELETE",path:`/${p}/{${p.slice(0,-1)}}`,handler:y.destroy}];for(let We of be)if(fe.includes(We.action)&&We.handler){let Ve=new ct(We.method,We.path,We.handler).name(`${p}.${We.action}`);if(J.model&&["show","edit","update","destroy"].includes(We.action))Ve.model(p.slice(0,-1),J.model);this.register(Ve)}return this}getRoutes(){return[...this.routes,...this.subdomainRouter.getAllRoutes()]}async handle(p){let y=new URL(p.url),J=y.hostname,K=this.subdomainRouter.findDomainGroup(J);if(K){let fe=p;fe.domainParams=K.parameters;for(let be of K.group.getRoutes()){let We=this.matchRouteParams(be,p.method,y.pathname);if(We)return await this.executeRoute(be,fe,We)}}for(let fe of this.routes){let be=this.matchRouteParams(fe,p.method,y.pathname);if(be)return await this.executeRoute(fe,p,be)}return null}matchRouteParams(p,y,J){if(p.method!==y)return null;let K={};return l(p.path,J,K)?K:null}async executeRoute(p,y,J){y.params=J;let K=[...this.globalMiddleware];for(let We of this.conditionalMiddleware)if(await We.condition(y))K.push(...We.middleware);K.push(...p.middleware);let fe=0,be=async()=>{if(fe<K.length){let We=K[fe++];return await We(y,be)??new Response(null)}return s(await p.handler(y))};return await be()}}var as={api:(p,y,J={})=>{let K=J.method||"GET",fe=new ct(K,p,y);if(J.cache)fe.cached(J.cache);if(J.throttle)fe.throttle(J.throttle);return fe},protected:(p,y,J={})=>{let K=J.method||"GET",fe=new ct(K,p,y);return fe.addMiddleware(async(be,We)=>{if(!be.headers.get("Authorization"))return new Response("Unauthorized",{status:401});return await We()}),fe},upload:(p,y,J={})=>{let K=new ct("POST",p,y);return K.addMiddleware(async(fe,be)=>await be()),K}},ds={route:(p,y={},J={})=>{let K=xe(p)??`/${p}`;for(let[be,We]of Object.entries(y)){let Ve=encodeURIComponent(We);K=K.replace(`{${be}}`,Ve),K=K.replace(`{${be}?}`,Ve)}if(K.includes("?}")){if(K=K.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),K.length>1&&K.endsWith("/"))K=K.slice(0,-1)}let fe=new URLSearchParams(J).toString();if(fe)K+=`?${fe}`;return K},redirect:(p,y=302)=>new Response(null,{status:y,headers:{Location:p}}),json:(p,y=200)=>new Response(JSON.stringify(p),{status:y,headers:{"Content-Type":"application/json"}})},us=new Or;import cs from"process";class Sn{macros=new Map;register(p,y){this.macros.set(p,{name:p,handler:y})}get(p){return this.macros.get(p)}has(p){return this.macros.has(p)}all(){return Array.from(this.macros.values())}remove(p){return this.macros.delete(p)}clear(){this.macros.clear()}}var Qr=new Sn;class Ar extends Response{static macro(p,y){Qr.register(p,y),Response[p]=y}static callMacro(p,...y){let J=Qr.get(p);if(!J)throw Error(`Response macro "${p}" not found`);return J.handler(...y)}static hasMacro(p){return Qr.has(p)}}function Nr(p,y){if(typeof p==="number")return{status:p,mergedHeaders:y};if(p&&typeof p==="object"){let J=typeof p.status==="number"?p.status:200,K=y;if(p.headers)if(K={},p.headers instanceof Headers)p.headers.forEach((fe,be)=>{K[be]=fe});else if(Array.isArray(p.headers))for(let[fe,be]of p.headers)K[fe]=be;else Object.assign(K,p.headers);return{status:J,mergedHeaders:K}}return{status:200,mergedHeaders:y}}var wt={success:(p,y,J=200)=>{let K={};if(p!==void 0)K.data=p;if(y!==void 0)K.message=y;return new Response(JSON.stringify(K),{status:J,headers:{"Content-Type":"application/json"}})},error:(p,y,J=400)=>{let K={error:p};if(y!==void 0)K.errors=y;return new Response(JSON.stringify(K),{status:J,headers:{"Content-Type":"application/json"}})},validationError:(p,y="Validation failed")=>wt.error(y,p,422),notFound:(p="Resource not found")=>wt.error(p,void 0,404),unauthorized:(p="Unauthorized")=>wt.error(p,void 0,401),forbidden:(p="Forbidden")=>wt.error(p,void 0,403),serverError:(p="Internal server error")=>wt.error(p,void 0,500),created:(p,y="Resource created successfully")=>wt.success(p,y,201),updated:(p,y="Resource updated successfully")=>wt.success(p,y,200),deleted:(p="Resource deleted successfully")=>wt.success(null,p,200),noContent:()=>new Response(null,{status:204}),accepted:(p,y="Request accepted")=>wt.success(p,y,202),paginated:(p,y,J)=>{let K=Math.ceil(y.total/y.per_page),fe=(y.current_page-1)*y.per_page+1,be=Math.min(fe+y.per_page-1,y.total),We={data:p,message:J,meta:{current_page:y.current_page,per_page:y.per_page,total:y.total,last_page:K,from:fe,to:be,path:y.path,first_page_url:`${y.path}?page=1`,last_page_url:`${y.path}?page=${K}`,next_page_url:y.current_page<K?`${y.path}?page=${y.current_page+1}`:void 0,prev_page_url:y.current_page>1?`${y.path}?page=${y.current_page-1}`:void 0}};return new Response(JSON.stringify(We),{status:200,headers:{"Content-Type":"application/json"}})},json:(p,y=200,J={})=>{let{status:K,mergedHeaders:fe}=Nr(y,J);return new Response(JSON.stringify(p),{status:K,headers:{"Content-Type":"application/json",...fe}})},html:(p,y=200,J={})=>{let{status:K,mergedHeaders:fe}=Nr(y,J);return new Response(p,{status:K,headers:{"Content-Type":"text/html",...fe}})},text:(p,y=200,J={})=>{let{status:K,mergedHeaders:fe}=Nr(y,J);return new Response(p,{status:K,headers:{"Content-Type":"text/plain",...fe}})},xml:(p,y=200,J={})=>{let{status:K,mergedHeaders:fe}=Nr(y,J);return new Response(p,{status:K,headers:{"Content-Type":"application/xml",...fe}})},redirect:(p,y=302)=>new Response(null,{status:y,headers:{Location:p}}),permanentRedirect:(p)=>wt.redirect(p,301),download:(p,y,J="application/octet-stream")=>new Response(p,{status:200,headers:{"Content-Type":J,"Content-Disposition":`attachment; filename="${y}"`}}),stream:(p,y="application/octet-stream",J={})=>new Response(p,{status:200,headers:{"Content-Type":y,...J}}),cache:(p,y=3600,J=!0,K)=>{let be={"Content-Type":"application/json","Cache-Control":J?`public, max-age=${y}`:`private, max-age=${y}`};if(K)be.ETag=K;return new Response(JSON.stringify(p),{status:200,headers:be})},cors:(p,y="*",J="GET,POST,PUT,DELETE,OPTIONS",K="Content-Type,Authorization")=>new Response(JSON.stringify(p),{status:200,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":y,"Access-Control-Allow-Methods":J,"Access-Control-Allow-Headers":K}}),sse:(p,y,J)=>{let K="";if(J)K+=`id: ${J}
|
|
3
|
+
`;if(y)K+=`event: ${y}
|
|
4
|
+
`;return K+=`data: ${p}
|
|
7
5
|
|
|
8
|
-
function shouldPreserve(href) {
|
|
9
|
-
// Only preserve for same-origin links
|
|
10
|
-
try {
|
|
11
|
-
var url = new URL(href, window.location.origin);
|
|
12
|
-
if (url.origin !== window.location.origin) return false;
|
|
13
|
-
// Check route patterns if specified
|
|
14
|
-
if (routes.length) {
|
|
15
|
-
var path = url.pathname;
|
|
16
|
-
return routes.some(function(pattern) {
|
|
17
|
-
if (pattern.endsWith('*')) {
|
|
18
|
-
return path.startsWith(pattern.slice(0, -1));
|
|
19
|
-
}
|
|
20
|
-
// eslint-disable-next-line prefer-template
|
|
21
|
-
return path === pattern || path.startsWith(pattern + '/');
|
|
22
|
-
});
|
|
23
|
-
}
|
|
24
|
-
return true;
|
|
25
|
-
}
|
|
26
|
-
catch (e) { return false; }
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function getPreservedParams() {
|
|
30
|
-
var current = new URLSearchParams(window.location.search);
|
|
31
|
-
var preserved = {};
|
|
32
|
-
preserve.forEach(function(key) {
|
|
33
|
-
if (current.has(key) && exclude.indexOf(key) === -1) {
|
|
34
|
-
preserved[key] = current.get(key);
|
|
35
|
-
}
|
|
36
|
-
});
|
|
37
|
-
return preserved;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function enhanceUrl(href) {
|
|
41
|
-
var url = new URL(href, window.location.origin);
|
|
42
|
-
var preserved = getPreservedParams();
|
|
43
|
-
Object.keys(preserved).forEach(function(key) {
|
|
44
|
-
if (!url.searchParams.has(key)) {
|
|
45
|
-
url.searchParams.set(key, preserved[key]);
|
|
46
|
-
}
|
|
47
|
-
});
|
|
48
|
-
return url.toString();
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// Intercept all link clicks
|
|
52
|
-
document.addEventListener('click', function(e) {
|
|
53
|
-
var link = e.target.closest('a[href]');
|
|
54
|
-
if (!link) return;
|
|
55
|
-
|
|
56
|
-
var href = link.getAttribute('href');
|
|
57
|
-
if (!href || href.startsWith('#') || href.startsWith('javascript:') ||
|
|
58
|
-
href.startsWith('mailto:') || href.startsWith('tel:')) return;
|
|
59
|
-
|
|
60
|
-
if (!shouldPreserve(href)) return;
|
|
61
|
-
|
|
62
|
-
// Check if link already has all preserved params
|
|
63
|
-
var enhanced = enhanceUrl(href);
|
|
64
|
-
if (enhanced !== new URL(href, window.location.origin).toString()) {
|
|
65
|
-
e.preventDefault();
|
|
66
|
-
window.location.href = enhanced;
|
|
67
|
-
}
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
// Expose API for programmatic navigation
|
|
71
|
-
window.__preserveQuery = {
|
|
72
|
-
enhance: enhanceUrl,
|
|
73
|
-
getPreserved: getPreservedParams,
|
|
74
|
-
navigate: function(href) {
|
|
75
|
-
window.location.href = enhanceUrl(href);
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
})();
|
|
79
|
-
</script>`}function yr(o,l){if(!l.enabled||!l.preserve?.length)return o;let M=Ti(l);if(!M)return o;if(o.includes("</head>"))return o.replace("</head>",`${M}
|
|
80
|
-
</head>`);if(o.includes("</body>"))return o.replace("</body>",`${M}
|
|
81
|
-
</body>`);return o+M}function oa(o,l,M,k){let L=typeof l==="string"?new URL(l):l,V=new URL(o,L.origin);if(M.preserve){for(let pe of M.preserve)if(L.searchParams.has(pe)&&!M.exclude?.includes(pe)){if(!V.searchParams.has(pe))V.searchParams.set(pe,L.searchParams.get(pe))}}if(k)for(let[pe,he]of Object.entries(k))V.searchParams.set(pe,he);return V.pathname+V.search}var Pi=["src/views","views","resources/views","app/views"],Ci=["_","components","layouts","partials","scripts","styles"],Mi=[".stx",".html"];function Ei(o=process.cwd()){for(let l of Pi){let M=Et(o,l);if(wr(M)&&vi(M).isDirectory())return M}return null}function kn(o,l,M){if(!wr(o))return!1;try{let k=Sn(o,{withFileTypes:!0});for(let L of k){if(M.some((V)=>L.name.startsWith(V)||L.name===V))continue;if(L.isFile()&&l.some((V)=>L.name.endsWith(V)))return!0;if(L.isDirectory()){let V=tr(o,L.name);if(kn(V,l,M))return!0}}}catch{}return!1}function Si(o,l,M){let k=zr(l,o);for(let V of M)if(k.endsWith(V)){k=k.slice(0,-V.length);break}if(k=k.replace(/\\/g,"/"),k==="index"||k.endsWith("/index"))k=k.replace(/\/?index$/,"");let L=[];if(k=k.replace(/\[\.\.\.([^\]]+)\]/g,(V,pe)=>(L.push(pe),`{${pe}}*`)),k=k.replace(/\[([^\]]+)\]/g,(V,pe)=>(L.push(pe),`{${pe}}`)),!k.startsWith("/"))k=`/${k}`;if(k==="/")return{routePath:"/",params:L};return{routePath:k,params:L}}function Hn(o,l,M,k){let L=[];if(!wr(o))return L;let V=Sn(o,{withFileTypes:!0});for(let he of V){let Te=tr(o,he.name);if(k.some((xe)=>he.name.startsWith(xe)||he.name===xe))continue;if(he.isDirectory())L.push(...Hn(Te,l,M,k));else if(he.isFile()){if(M.some((ve)=>he.name.endsWith(ve))){let{routePath:ve,params:Pe}=Si(Te,l,M);L.push({filePath:Te,routePath:ve,params:Pe,isIndex:he.name.startsWith("index."),isDynamic:Pe.length>0})}}}L.sort((he,Te)=>{if(he.isDynamic!==Te.isDynamic)return he.isDynamic?1:-1;let xe=he.routePath.split("/").length,ve=Te.routePath.split("/").length;if(xe!==ve)return ve-xe;return he.routePath.localeCompare(Te.routePath)});let pe=new Map;for(let he of L){let Te=pe.get(he.routePath);if(Te)console.warn(`[bun-router] Warning: Duplicate route "${he.routePath}" found:
|
|
82
|
-
- ${Te.filePath}
|
|
83
|
-
- ${he.filePath}
|
|
84
|
-
Using: ${Te.filePath}`);else pe.set(he.routePath,he)}return Array.from(pe.values())}function ki(o,l){let M=zr(l,o),k=[Et(process.cwd(),"dist/views",M.replace(/\.stx$/,".html")),Et(process.cwd(),"views",M.replace(/\.stx$/,".html")),Et("/var/task/views",M.replace(/\.stx$/,".html"))];for(let L of k)if(wr(L))return L;return null}function Hi(o){let l={};for(let M of String(o??"").split(";")){let k=M.indexOf("=");if(k<0)continue;try{l[M.slice(0,k).trim()]=decodeURIComponent(M.slice(k+1).trim())}catch{}}return l}async function Ai(o,l,M,k,L){let pe=await import("@stacksjs/stx");if(!pe.processDirectives||!pe.extractVariables)throw Error("STX library not properly loaded. Install with: bun add @stacksjs/stx");let he=await Bun.file(o).text(),Te=he.match(/<script\s+server\s*>([\s\S]*?)<\/script>/i),xe=Te?Te[1]:"",ve=Te?he.replace(/<script\s+server\s*>[\s\S]*?<\/script>/i,""):he;ve=ve.replace(/<script\s+client\s*>/gi,"<script>");let Pe={status:200,headers:{}},Ce=M.headers??{},Ee=String(Ce.cookie??Ce.Cookie??""),Me=String(M.url??""),Se=Me.includes("?")?Me.slice(Me.indexOf("?")):"",Oe={url:Me,path:String(M.path??""),search:Se,host:String(Ce.host??""),cookieHeader:Ee,cookies:Hi(Ee),ip:"",locale:null,params:M.params??{},method:String(M.method??"GET"),request:L},Ie={__filename:o,__dirname:xi(o),props:M,...M,__stxServeContext:Oe,setResponseStatus:(pt)=>{if(Number.isInteger(pt)&&pt>=100&&pt<=599)Pe.status=pt},notFound:(pt=404)=>{Pe.status=Number.isInteger(pt)&&pt>=400&&pt<=599?pt:404},setResponseHeader:(pt,Is)=>{if(pt)Pe.headers[String(pt)]=String(Is)},definePageMeta:()=>{}};if(xe)await pe.extractVariables(xe,Ie,o);let Ft=k?.componentsDir?Et(k.componentsDir):tr(l,"components"),dr=k?.layoutsDir?Et(k.layoutsDir):tr(l,"layouts"),Ds=k?.partialsDir?Et(k.partialsDir):tr(l,"partials"),Ns={...pe.defaultConfig,componentsDir:Ft,layoutsDir:dr,partialsDir:Ds},Us=await pe.processDirectives(ve,Ie,o,Ns,new Set),pr=Number(Ie.__stxResponseStatus),Fs=Ie.__stxResponseHeaders;return{html:Us,status:Number.isInteger(pr)&&pr>=100&&pr<=599?pr:Pe.status,headers:{...Pe.headers,...Fs??{}}}}function qi(o,l,M,k){return async(L)=>{let V=new URL(L.url),pe={params:L.params||{},query:Object.fromEntries(V.searchParams),url:L.url,path:V.pathname,method:L.method,headers:Object.fromEntries(L.headers.entries())};function he(Te){if(k?.enabled!==!1&&k?.preserve?.length)return yr(Te,k);return Te}try{let Te=ki(o,l);if(Te){let ve=await Bun.file(Te).text();return ve=he(ve),new Response(ve,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}if(o.endsWith(".stx")){let ve=await Ai(o,l,pe,M,L),Pe=he(ve.html);return new Response(Pe,{status:ve.status,headers:{"Content-Type":"text/html; charset=utf-8",...ve.headers}})}let xe=await Bun.file(o).text();return xe=he(xe),new Response(xe,{status:200,headers:{"Content-Type":"text/html; charset=utf-8"}})}catch(Te){return console.error(`[bun-router] Error rendering ${o}:`,Te),new Response("Internal Server Error",{status:500})}}}function An(o){Object.defineProperties(o.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 l=this._viewsDir||Ei();if(!l){this._fileRoutesInitialized=!0;return}let M=this._fileRoutingConfig||{};if(M.enabled===!1){this._fileRoutesInitialized=!0;return}let k=M.extensions||Mi,L=M.exclude||Ci;if(!kn(l,k,L)){this._fileRoutesInitialized=!0;return}let V=Hn(l,l,k,L);if(this.config.verbose){console.log(`[bun-router] Auto-discovered ${V.length} file-based routes from ${l}:`);for(let he of V)console.log(` ${he.routePath} -> ${zr(l,he.filePath)}`)}this._viewsDir=l;let pe=new Set;for(let he of this.routes)if(he.method==="GET")pe.add(he.path);for(let he of V){if(pe.has(he.routePath))continue;let Te=qi(he.filePath,l,M,this.config.queryPreservation);this.get(he.routePath,Te,"web"),this._fileBasedRoutes.push(he),pe.add(he.routePath)}this._fileRoutesInitialized=!0},writable:!0,configurable:!0},views:{value(l){if(typeof l==="string")this._viewsDir=Et(l),this._fileRoutingConfig={};else{if(l.viewsPath)this._viewsDir=Et(l.viewsPath);this._fileRoutingConfig=l}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(l,M){if(l)this._viewsDir=Et(l);if(M)this._fileRoutingConfig={...this._fileRoutingConfig,...M};return this._fileRoutesInitialized=!1,await this._initFileRoutes(),this},writable:!0,configurable:!0},loadFileRoutes:{async value(l={}){return this.fileRoutes(l.viewsPath,l)},writable:!0,configurable:!0}})}class br{stream;headers;status;constructor(o,l={}){if(this.stream=o,this.status=l.status||200,this.headers=new Headers(l.headers),l.contentType)this.headers.set("Content-Type",l.contentType)}toResponse(){return new Response(this.stream,{status:this.status,headers:this.headers})}addHeader(o,l){return this.headers.set(o,l),this}setContentType(o){return this.headers.set("Content-Type",o),this}setStatus(o){return this.status=o,this}}class gt{static direct(o,l={}){let{format:M="json",delimiter:k=`
|
|
85
|
-
`,contentType:L,headers:V={},status:pe=200,enableCompression:he=!1}=l,Te=new ReadableStream({async start(ve){try{let Pe=new TextEncoder,Ce=!0;for await(let Ee of Array.isArray(o)?o:o){if(!Ce&&k)ve.enqueue(Pe.encode(k));let Me=gt.formatData(Ee,M);ve.enqueue(Pe.encode(Me)),Ce=!1}ve.close()}catch(Pe){ve.error(Pe)}}}),xe=new Headers(V);if(L)xe.set("Content-Type",L);else xe.set("Content-Type",gt.getContentTypeForFormat(M));return new br(Te,{headers:xe,status:pe})}static buffered(o,l={}){let{format:M="json",bufferSize:k=1024,flushInterval:L=100,contentType:V,headers:pe={},status:he=200}=l,Te=new ReadableStream({async start(ve){try{let Pe=new TextEncoder,Ce=[],Ee=0,Me=()=>{if(Ce.length>0){let Oe=Ce.join("");ve.enqueue(Pe.encode(Oe)),Ce=[],Ee=0}},Se=setInterval(Me,L);try{for await(let Oe of Array.isArray(o)?o:o){let Ie=gt.formatData(Oe,M);if(Ce.push(Ie),Ee+=Ie.length,Ee>=k)Me()}Me()}finally{clearInterval(Se)}ve.close()}catch(Pe){ve.error(Pe)}}}),xe=new Headers(pe);if(V)xe.set("Content-Type",V);else xe.set("Content-Type",gt.getContentTypeForFormat(M));return new br(Te,{headers:xe,status:he})}static json(o,l={}){return gt.direct(o,{...l,format:"json",contentType:l.contentType||"application/json"})}static text(o,l={}){return gt.direct(o,{...l,format:"text",contentType:l.contentType||"text/plain"})}static csv(o,l={}){let{csvHeaders:M,...k}=l,L=new ReadableStream({async start(V){try{let pe=new TextEncoder,he=!0;if(M&&M.length>0)V.enqueue(pe.encode(`${M.join(",")}
|
|
86
|
-
`));for await(let Te of Array.isArray(o)?o:o){let xe=gt.objectToCsvRow(Te,M);V.enqueue(pe.encode(`${xe}
|
|
87
|
-
`))}V.close()}catch(pe){V.error(pe)}}});return new br(L,{headers:k.headers,status:k.status,contentType:k.contentType||"text/csv"})}static formatData(o,l){switch(l){case"json":return JSON.stringify(o);case"text":return String(o);case"csv":return typeof o==="object"?gt.objectToCsvRow(o):String(o);case"ndjson":return JSON.stringify(o);default:return JSON.stringify(o)}}static objectToCsvRow(o,l){return(l||Object.keys(o)).map((k)=>{let L=o[k],V=L===null||L===void 0?"":String(L);if(V.includes(",")||V.includes('"')||V.includes(`
|
|
88
|
-
`))return`"${V.replace(/"/g,'""')}"`;return V}).join(",")}static getContentTypeForFormat(o){switch(o){case"json":case"ndjson":return"application/json";case"text":return"text/plain";case"csv":return"text/csv";default:return"application/json"}}}class Lt{static async streamFile(o,l,M={}){let{contentType:k,enableRanges:L=!0,chunkSize:V=65536}=M;try{let pe=Bun.file(o),he=pe.size,Te=L?l.headers.get("range"):null;if(Te&&L)return Lt.handleRangeRequest(pe,Te,k);let xe=new Headers({"Content-Length":he.toString(),"Accept-Ranges":L?"bytes":"none"});if(k)xe.set("Content-Type",k);return new Response(pe.stream(),{status:200,headers:xe})}catch(pe){return console.error("Error streaming file:",pe),new Response("File not found",{status:404})}}static async handleRangeRequest(o,l,M){let k=Lt.parseRangeHeader(l,o.size);if(!k||k.length===0)return new Response("Invalid range",{status:416});let[L,V]=k[0],pe=V-L+1,he=new Headers({"Content-Range":`bytes ${L}-${V}/${o.size}`,"Content-Length":pe.toString(),"Accept-Ranges":"bytes"});if(M)he.set("Content-Type",M);let Te=o.slice(L,V+1);return new Response(Te.stream(),{status:206,headers:he})}static parseRangeHeader(o,l){let M=o.match(/^bytes=(.+)$/);if(!M)return null;let k=[],L=M[1].split(",");for(let V of L){let[pe,he]=V.trim().split("-"),Te,xe;if(pe==="")Te=Math.max(0,l-Number.parseInt(he,10)),xe=l-1;else if(he==="")Te=Number.parseInt(pe,10),xe=l-1;else Te=Number.parseInt(pe,10),xe=Number.parseInt(he,10);if(Te<0||xe>=l||Te>xe)return null;k.push([Te,xe])}return k}}function Tr(o,l){try{o.close()}catch{}}function qn(o){Object.defineProperties(o.prototype,{streamFile:{value(l,M,k){return Lt.streamFile(l,M,k)},writable:!0,configurable:!0},streamFileWithRanges:{async value(l,M){return Lt.streamFile(l,M,{enableRanges:!0})},writable:!0,configurable:!0},health:{value(){let M=this.config.apiPrefix?`${this.config.apiPrefix}/health`:"/health";return this.get(M,()=>new Response("OK",{headers:{"Content-Type":"text/plain"}})),this},writable:!0,configurable:!0},streamResponse:{value(l,M){let k=new Headers;if(M?.headers)for(let[L,V]of Object.entries(M.headers))k.set(L,V);return new Response(l(),{status:M?.status||200,headers:k})},writable:!0,configurable:!0},transformStream:{value(l,M){return(k)=>{if(!k.body)throw Error("Request body is required for stream transformation");let L=new TransformStream({async transform(pe,he){try{let Te=await l(pe);if(typeof Te==="string")he.enqueue(new TextEncoder().encode(Te));else he.enqueue(Te)}catch(Te){he.error(Te)}}}),V=new Headers;if(M?.headers)for(let[pe,he]of Object.entries(M.headers))V.set(pe,he);return new Response(k.body.pipeThrough(L),{status:M?.status||200,headers:V})}},writable:!0,configurable:!0},stream:{value(l,M=200,k={}){let L=new Headers(k),V=new ReadableStream({async start(pe){let he=new TextEncoder;try{for await(let Te of l())if(typeof Te==="string")pe.enqueue(he.encode(Te));else pe.enqueue(Te);pe.close()}catch(Te){Tr(pe,Te)}}});return new Response(V,{status:M,headers:L})},writable:!0,configurable:!0},streamJson:{value(l,M=200,k={}){let L=new Headers({"Content-Type":"application/json",...k}),V=new ReadableStream({async start(pe){let he=new TextEncoder;try{pe.enqueue(he.encode("{"));let Te=Object.keys(l);for(let xe=0;xe<Te.length;xe++){let ve=Te[xe],Pe=l[ve];pe.enqueue(he.encode(`"${ve}":[`));let Ce=!0;for await(let Ee of Pe){if(!Ce)pe.enqueue(he.encode(","));pe.enqueue(he.encode(JSON.stringify(Ee))),Ce=!1}if(pe.enqueue(he.encode("]")),xe<Te.length-1)pe.enqueue(he.encode(","))}pe.enqueue(he.encode("}")),pe.close()}catch(Te){Tr(pe,Te)}}});return new Response(V,{status:M,headers:L})},writable:!0,configurable:!0},eventStream:{value(l,M={}){let k=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Cache-Control",...M}),L=new ReadableStream({async start(V){let pe=new TextEncoder;try{for await(let he of l()){let Te="";if(he.id)Te+=`id: ${he.id}
|
|
89
|
-
`;if(he.event)Te+=`event: ${he.event}
|
|
90
|
-
`;if(he.retry)Te+=`retry: ${he.retry}
|
|
91
|
-
`;let xe=typeof he.data==="string"?he.data:JSON.stringify(he.data);Te+=`data: ${xe}
|
|
92
|
-
|
|
93
|
-
`,V.enqueue(pe.encode(Te))}V.close()}catch(he){Tr(V,he)}}});return new Response(L,{status:200,headers:k})},writable:!0,configurable:!0},streamDownload:{value(l,M,k={}){let L=new Headers({"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="${M}"`,...k}),V=new ReadableStream({async start(pe){let he=new TextEncoder;try{for await(let Te of l())if(typeof Te==="string")pe.enqueue(he.encode(Te));else pe.enqueue(Te);pe.close()}catch(Te){Tr(pe,Te)}}});return new Response(V,{status:200,headers:L})},writable:!0,configurable:!0},streamAsyncIterator:{value(l,M={}){return gt.direct(l,M).toResponse()},writable:!0,configurable:!0}})}import{Buffer as Oi}from"buffer";function xr(o,l){return new Response(o,{headers:{"Content-Type":l,"Content-Length":String(Oi.byteLength(o))}})}function $e(o){if(o instanceof Response)return o;if(o===null||o===void 0)return new Response(null,{status:204});if(typeof o==="string")return xr(o,"text/plain; charset=utf-8");if(typeof o==="number"||typeof o==="boolean")return xr(String(o),"text/plain; charset=utf-8");if(o instanceof ArrayBuffer||o instanceof Uint8Array)return new Response(o,{headers:{"Content-Type":"application/octet-stream","Content-Length":String(o.byteLength)}});if(o instanceof ReadableStream)return new Response(o);if(typeof o==="object")return xr(JSON.stringify(o),"application/json; charset=utf-8");return xr(String(o),"text/plain; charset=utf-8")}async function $i(o,l){let M=l.actionsPath||"actions",k=l.controllersPath||"controllers",L=o.replace(/\.(ts|js)$/,""),V=[];if(L.includes("@")){let[he,Te]=L.split("@");V.push(`${k}/${he}`,`${k}/${he}.ts`,`${k}/${he}.js`,`./${k}/${he}`,`../${k}/${he}`)}else if(L.startsWith("Actions/")||L.startsWith("actions/"))V.push(L,`./${L}`,`../${L}`);else if(L.startsWith("./")||L.startsWith("../"))V.push(L);else V.push(`${M}/${L}`,`./${M}/${L}`,`../${M}/${L}`,L,`./${L}`,`../${L}`);let pe=null;for(let he of V)try{return await import(he)}catch(Te){pe=Te}throw Error(`Failed to import handler "${o}".
|
|
94
|
-
Tried paths: ${V.join(", ")}
|
|
95
|
-
Last error: ${pe?.message||"Unknown error"}`)}function On(o){return typeof o==="function"&&!o.prototype?.handle}async function rr(o,l,M){if(o instanceof Response)return o.clone();if(On(o)){let k=await o(l);return $e(k)}if(typeof o==="string")return Bi(o,l,M);if(typeof o==="function"&&o.prototype&&typeof o.prototype.handle==="function"){let V=await new o().handle(l);return $e(V)}if(o&&typeof o==="object"&&"handle"in o){let k=o;if(typeof k.handle==="function"){let L=await k.handle(l);return $e(L)}}throw Error(`Invalid handler type: ${typeof o}`)}async function Bi(o,l,M){let k=M.controllersPath||"controllers";if(o.includes("@")){let[pe,he]=o.split("@"),Te=[`${k}/${pe}`,`./${k}/${pe}`,`../${k}/${pe}`,pe,`./${pe}`,`../${pe}`],xe=null,ve=null;for(let Ce of Te)try{xe=await import(Ce);break}catch(Ee){ve=Ee}if(!xe)throw Error(`Failed to import controller "${pe}".
|
|
96
|
-
Tried paths: ${Te.join(", ")}
|
|
97
|
-
Last error: ${ve?.message||"Unknown error"}`);let Pe=xe.default||xe;if(typeof Pe==="function"){let Ce=new Pe,Ee=Ce[he];if(typeof Ee!=="function")throw TypeError(`Method "${he}" not found on controller "${pe}"`);let Me=await Ee.call(Ce,l);return $e(Me)}throw Error(`Controller "${pe}" is not a valid class`)}let L=await $i(o,M),V=L.default||L;if(typeof V==="function"){if(V.prototype&&typeof V.prototype.handle==="function"){let Te=await new V().handle(l);return $e(Te)}let pe=await V(l);return $e(pe)}if(V&&typeof V==="object"&&"handle"in V){let pe=V;if(typeof pe.handle==="function"){let he=await pe.handle(l);return $e(he)}}throw Error(`Handler "${o}" does not export a valid handler function or class`)}function Di(o){return(l,M)=>rr(l,M,o)}function $n(o,l){if(o instanceof Response)return()=>o.clone();if(On(o))return(M)=>{let k=o(M);if(k instanceof Response)return k;return k instanceof Promise?k.then($e):$e(k)};if(typeof o==="function"&&o.prototype&&typeof o.prototype.handle==="function"){let M=o;return(k)=>{let L=new M().handle(k);if(L instanceof Response)return L;return L instanceof Promise?L.then($e):$e(L)}}return(M)=>rr(o,M,l)}class vr extends Error{modelName;value;field;constructor(o,l,M="id"){super(`${o} not found with ${M}: ${l}`);this.modelName=o;this.value=l;this.field=M;this.name="ModelNotFoundError"}}class Dn{bindings=new Map;model(o,l){this.bindings.set(o,l)}bind(o,l){this.bindings.set(o,l)}getBinding(o){return this.bindings.get(o)}hasBinding(o){return this.bindings.has(o)}}var Ni=new Dn;async function Bn(o,l,M,k,L={}){if(k)return await M.resolveRouteBinding(l,k);let V=M.getRouteKeyName();if(V!=="id")return await M.resolveRouteBinding(l,V);return await M.find(l)}function Nn(o,l){return async(M,k)=>{let L={};try{for(let V of o){let pe=M.params?.[V.name];if(!pe)continue;let he=Ni.getBinding(V.name);if(he){let ve=null;if(typeof he==="function")ve=await he(pe);else ve=await Bn(V.name,pe,he,V.key,L);if(!ve)throw new vr(V.name,pe,V.key||"id");L[V.name]=ve;continue}let Te=l[V.name];if(!Te)continue;let xe=await Bn(V.name,pe,Te,V.key,L);if(!xe)throw new vr(V.name,pe,V.key||"id");L[V.name]=xe}return M.models=L,await k()}catch(V){if(V instanceof vr)return new Response(`${V.modelName} not found`,{status:404});throw V}}}class Un{key;entry;prev;next;constructor(o,l,M=null,k=null){this.key=o;this.entry=l;this.prev=M;this.next=k}}class nr{options;cache=new Map;head=null;tail=null;stats={hits:0,misses:0,evictions:0};constructor(o){this.options=o;if(o.maxSize<=0)throw Error("maxSize must be greater than 0")}get(o){let l=this.cache.get(o);if(!l){this.stats.misses++;return}let M=Date.now(),k=l.entry;if(this.isExpired(k,M)){if(!this.options.allowStale){this.delete(o),this.stats.misses++;return}}if(k.lastAccessed=M,k.accessCount++,this.stats.hits++,this.options.updateAgeOnGet!==!1)this.moveToFront(l);return k.value}set(o,l,M){let k=Date.now(),L=this.cache.get(o);if(L){L.entry.value=l,L.entry.timestamp=k,L.entry.lastAccessed=k,L.entry.ttl=M??this.options.ttl,this.moveToFront(L);return}let V={value:l,timestamp:k,accessCount:0,lastAccessed:k,ttl:M??this.options.ttl},pe=new Un(o,V);if(this.cache.set(o,pe),this.addToFront(pe),this.cache.size>this.options.maxSize)this.evictLRU()}delete(o){let l=this.cache.get(o);if(!l)return!1;if(this.cache.delete(o),this.removeNode(l),this.options.onEvict)this.options.onEvict(o,l.entry.value);return!0}has(o){let l=this.cache.get(o);if(!l)return!1;let M=Date.now();if(this.isExpired(l.entry,M)){if(!this.options.allowStale)return this.delete(o),!1}return!0}clear(){if(this.options.onEvict)for(let[o,l]of this.cache)this.options.onEvict(o,l.entry.value);this.cache.clear(),this.head=null,this.tail=null,this.stats.evictions+=this.cache.size}keys(){let o=[],l=this.head;while(l)o.push(l.key),l=l.next;return o}values(){let o=[],l=this.head;while(l)o.push(l.entry.value),l=l.next;return o}getStats(){let o=this.estimateMemoryUsage(),l=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:l>0?this.stats.hits/l:0,memoryUsage:o}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}prune(){let o=Date.now(),l=[];for(let[M,k]of this.cache)if(this.isExpired(k.entry,o))l.push(M);for(let M of l)this.delete(M);return l.length}getFrequentlyUsed(o=10){let l=[];for(let[M,k]of this.cache)l.push({key:M,value:k.entry.value,accessCount:k.entry.accessCount});return l.sort((M,k)=>k.accessCount-M.accessCount).slice(0,o)}resize(o){if(o<=0)throw Error("maxSize must be greater than 0");this.options.maxSize=o;while(this.cache.size>o)this.evictLRU()}isExpired(o,l){if(!o.ttl)return!1;return l-o.timestamp>o.ttl}moveToFront(o){if(o===this.head)return;this.removeNode(o),this.addToFront(o)}addToFront(o){if(o.prev=null,o.next=this.head,this.head)this.head.prev=o;if(this.head=o,!this.tail)this.tail=o}removeNode(o){if(o.prev)o.prev.next=o.next;else this.head=o.next;if(o.next)o.next.prev=o.prev;else this.tail=o.prev}evictLRU(){if(!this.tail)return;let o=this.tail.key,l=this.tail.entry.value;if(this.cache.delete(o),this.removeNode(this.tail),this.stats.evictions++,this.options.onEvict)this.options.onEvict(o,l)}estimateMemoryUsage(){let o=0;for(let[l,M]of this.cache)o+=l.length*2,o+=this.estimateValueSize(M.entry.value),o+=64;return o+=this.cache.size*48,o}estimateValueSize(o){if(o===null||o===void 0)return 0;if(typeof o==="string")return o.length*2;if(typeof o==="number")return 8;if(typeof o==="boolean")return 1;if(o instanceof ArrayBuffer)return o.byteLength;if(o instanceof Uint8Array)return o.length;try{return JSON.stringify(o).length*2}catch{return 100}}}class Fn{static generateKey(o,l){let M=new URL(o.url),k=o.method,L=M.pathname,V=[k,L],pe=new URLSearchParams(M.search),he=l.excludeQuery||[],Te=[];for(let[xe,ve]of pe.entries())if(!he.includes(xe))Te.push(`${xe}=${ve}`);if(Te.length>0)V.push(Te.sort().join("&"));if(l.varyBy){let xe=[];for(let ve of l.varyBy){let Pe=o.headers.get(ve);if(Pe)xe.push(`${ve}:${Pe}`)}if(xe.length>0)V.push(xe.join("|"))}return V.join("::")}}class In{cache;tagIndex=new Map;keyTags=new Map;constructor(o=1000){this.cache=new nr({maxSize:o})}async get(o){let l=this.cache.get(o);if(!l)return null;if(l.ttl&&Date.now()-l.timestamp>l.ttl)return this.delete(o),null;return l}async set(o,l){this.cache.set(o,l),this.keyTags.set(o,new Set(l.tags));for(let M of l.tags){if(!this.tagIndex.has(M))this.tagIndex.set(M,new Set);this.tagIndex.get(M).add(o)}}delete(o){let l=this.keyTags.get(o);if(l){for(let M of l){let k=this.tagIndex.get(M);if(k){if(k.delete(o),k.size===0)this.tagIndex.delete(M)}}this.keyTags.delete(o)}return this.cache.delete(o)}invalidateByTags(o){let l=new Set;for(let M of o){let k=this.tagIndex.get(M);if(k)for(let L of k)l.add(L)}for(let M of l)this.delete(M);return l.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 zt=new In;function _n(o){return async(l,M)=>{if(o.condition&&!o.condition(l))return await M();if(l.method!=="GET"&&l.method!=="HEAD")return await M();let k=Fn.generateKey(l,o),L=await zt.get(k);if(L){let pe=new Headers(L.headers);if(pe.set("X-Cache","HIT"),pe.set("X-Cache-Key",k),L.etag){if(pe.set("ETag",L.etag),l.headers.get("If-None-Match")===L.etag)return new Response(null,{status:304,headers:pe})}return new Response(L.body,{status:L.status,headers:pe})}let V=await M();if(V.status>=200&&V.status<300)try{let pe=V.clone(),he=await pe.arrayBuffer(),Te=await Ui(he),xe={};pe.headers.forEach((Ce,Ee)=>{xe[Ee]=Ce});let ve={response:pe,headers:xe,status:V.status,body:new Uint8Array(he),timestamp:Date.now(),ttl:o.ttl,tags:o.tags||[],etag:Te};await zt.set(k,ve);let Pe=new Headers(V.headers);return Pe.set("X-Cache","MISS"),Pe.set("X-Cache-Key",k),Pe.set("ETag",Te),new Response(V.body,{status:V.status,headers:Pe})}catch(pe){return console.error("Error caching response:",pe),V}return V}}async function Ui(o){let l=await crypto.subtle.digest("SHA-256",o);return`"${Array.from(new Uint8Array(l)).map((L)=>L.toString(16).padStart(2,"0")).join("").substring(0,16)}"`}var jn={short:(o=[])=>({ttl:300000,maxSize:500,tags:o}),medium:(o=[])=>({ttl:3600000,maxSize:1000,tags:o}),long:(o=[])=>({ttl:86400000,maxSize:2000,tags:o}),api:(o=[])=>({ttl:900000,maxSize:1000,tags:o,varyBy:["Authorization","Accept","Accept-Language"],excludeQuery:["_t","timestamp","cache_bust"]}),static:(o=[])=>({ttl:604800000,maxSize:5000,tags:o,varyBy:["Accept-Encoding"]}),user:(o=[])=>({ttl:1800000,maxSize:2000,tags:o,varyBy:["Authorization"],condition:(l)=>!!l.headers.get("Authorization")})},Ta={byTags:(o)=>zt.invalidateByTags(o),forUser:(o)=>zt.invalidateByTags([`user:${o}`]),forModel:(o,l)=>{let M=l?[`${o}:${l}`,o]:[o];return zt.invalidateByTags(M)},all:()=>{zt.clear()}};class Pr{cache;config;constructor(o,l=1e4){this.config=o,this.cache=new nr({maxSize:l,ttl:o.windowMs*2})}async checkLimit(o){if(this.config.skipIf&&this.config.skipIf(o))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 l=this.generateKey(o),M=Date.now(),k=this.cache.get(l);if(!k||M>=k.resetTime)k={count:1,resetTime:M+this.config.windowMs,firstHit:M};else k.count++;this.cache.set(l,k);let L={totalHits:k.count,resetTime:new Date(k.resetTime),remaining:Math.max(0,this.config.maxAttempts-k.count),limit:this.config.maxAttempts,windowMs:this.config.windowMs};return{allowed:k.count<=this.config.maxAttempts,info:L}}generateKey(o){if(this.config.keyGenerator)return this.config.keyGenerator(o);let l=this.getClientIP(o),M=o.user?.id;if(M)return`user:${M}`;return`ip:${l}`}getClientIP(o){let l=o.headers.get("x-forwarded-for");if(l)return l.split(",")[0].trim();let M=o.headers.get("x-real-ip");if(M)return M;let k=o.headers.get("cf-connecting-ip");if(k)return k;return"unknown"}getStats(){return{...this.cache.getStats(),config:{maxAttempts:this.config.maxAttempts,windowMs:this.config.windowMs}}}}class Ln{limiters=new Map;register(o,l){let M=new Pr(l);return this.limiters.set(o,M),M}get(o){return this.limiters.get(o)}getOrCreate(o,l){let M=this.limiters.get(o);if(M)return M;return this.register(o,l)}}var zn=new Ln;function Gt(o,l){let M=l?zn.getOrCreate(l,o):new Pr(o);return async(k,L)=>{let{allowed:V,info:pe}=await M.checkLimit(k);if(!V){if(o.onLimitReached)return o.onLimitReached(k,pe);let Te=new Headers({"Content-Type":"application/json","Retry-After":Math.ceil((pe.resetTime.getTime()-Date.now())/1000).toString()});if(o.headers!==!1)Te.set("X-RateLimit-Limit",pe.limit.toString()),Te.set("X-RateLimit-Remaining",pe.remaining.toString()),Te.set("X-RateLimit-Reset",Math.ceil(pe.resetTime.getTime()/1000).toString());return new Response(JSON.stringify({error:"Too Many Requests",message:`Rate limit exceeded. Try again in ${Math.ceil((pe.resetTime.getTime()-Date.now())/1000)} seconds.`,retryAfter:Math.ceil((pe.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:Te})}let he=await L();if(he&&o.headers!==!1&&he.status<400){let Te=new Headers(he.headers);return Te.set("X-RateLimit-Limit",pe.limit.toString()),Te.set("X-RateLimit-Remaining",pe.remaining.toString()),Te.set("X-RateLimit-Reset",Math.ceil(pe.resetTime.getTime()/1000).toString()),new Response(he.body,{status:he.status,statusText:he.statusText,headers:Te})}return he}}function Wt(o){let l=o.split(","),M=Number.parseInt(l[0],10);if(Number.isNaN(M)||M<=0)throw Error(`Invalid throttle max attempts: ${l[0]}`);let k;if(l.length===1)k=60000;else{let L=l[1];k=Fi(L)}return{maxAttempts:M,windowMs:k}}function Fi(o){let l=/^(\d+)([smh]|sec|min|hour)?$/,M=o.match(l);if(!M)throw Error(`Invalid time format: ${o}`);let k=Number.parseInt(M[1],10),L=M[2]||"m";if(Number.isNaN(k)||k<=0)throw Error(`Invalid time value: ${M[1]}`);switch(L){case"s":case"sec":return k*1000;case"m":case"min":return k*60*1000;case"h":case"hour":return k*60*60*1000;default:return k*60*1000}}var Ii={api:(o=60,l=1)=>({maxAttempts:o,windowMs:l*60*1000,headers:!0}),auth:()=>({maxAttempts:5,windowMs:900000,keyGenerator:(o)=>{let l=o.headers.get("x-forwarded-for")?.split(",")[0]||"unknown",M=o.jsonBody?.email||o.formBody?.email||o.query?.email||"unknown";return`auth:${l}:${M}`},onLimitReached:(o,l)=>new Response(JSON.stringify({error:"Too many authentication attempts",message:"Please try again later",retryAfter:Math.ceil((l.resetTime.getTime()-Date.now())/1000)}),{status:429,headers:{"Content-Type":"application/json","Retry-After":Math.ceil((l.resetTime.getTime()-Date.now())/1000).toString()}})}),upload:()=>({maxAttempts:10,windowMs:3600000,keyGenerator:(o)=>{let l=o.user?.id;if(l)return`upload:user:${l}`;return`upload:ip:${o.headers.get("x-forwarded-for")?.split(",")[0]||"unknown"}`}}),search:()=>({maxAttempts:100,windowMs:600000,skipIf:(o)=>o.user?.plan==="premium"}),perUser:(o,l)=>({maxAttempts:o,windowMs:l*60*1000,keyGenerator:(M)=>{let k=M.user?.id;if(!k)throw Error("User authentication required for per-user rate limiting");return`user:${k}`},skipIf:(M)=>!M.user?.id}),perIP:(o,l)=>({maxAttempts:o,windowMs:l*60*1000,keyGenerator:(M)=>`ip:${M.headers.get("x-forwarded-for")?.split(",")[0]||M.headers.get("x-real-ip")||M.headers.get("cf-connecting-ip")||"unknown"}`}),global:(o,l)=>({maxAttempts:o,windowMs:l*60*1000,keyGenerator:()=>"global"})},Pa={fromString:(o,l)=>{let M=Wt(o);return Gt(M,l)},getInfo:async(o,l)=>{let M=new Pr(l),{info:k}=await M.checkLimit(o);return k},reset:(o,l)=>{let M=zn.get(o);if(M)return M.cache.delete(l);return!1}};class mt{static parseDomainPattern(o){let l=[],M=o.match(/\{([^}]+)\}/g)||[];for(let V of M){let pe=V.slice(1,-1);l.push(pe)}let k=o.replace(/\./g,"\\.").replace(/\{([^}]+)\}/g,"([^.]+)");k=`^${k}$`;let L=new RegExp(k,"i");return{pattern:o,parameters:l,regex:L}}static matchDomain(o,l){let M=o.match(l.regex);if(!M)return null;let k={};for(let L=0;L<l.parameters.length;L++){let V=l.parameters[L],pe=M[L+1];k[V]=pe}return k}static extractSubdomainInfo(o){let l=o.split(".");if(l.length<=2)return{domain:o,parameters:{},rootDomain:o};let M=l[0],k=l.slice(1).join(".");return{domain:o,parameters:{subdomain:M},subdomain:M,rootDomain:k}}}class sr{pattern;config;routes=[];constructor(o,l){this.pattern=o;this.config=l}addRoute(o,l,M,k=[],L){let V=[...this.config.middleware||[],...k],pe=this.config.prefix?`${this.config.prefix}${l}`:l;this.routes.push({method:o.toUpperCase(),path:pe,handler:M,middleware:V,name:L||(this.config.name?`${this.config.name}.${o.toLowerCase()}${l}`:void 0)})}getRoutes(){return[...this.routes]}matchesDomain(o){return mt.matchDomain(o,this.pattern)}}class Gr{domainGroups=[];wildcardGroup;domain(o){let l=mt.parseDomainPattern(o);return new Gn(this,l)}addDomainGroup(o){if(o.pattern.pattern.includes("*")&&o.pattern.parameters.length===0)this.wildcardGroup=o;else this.domainGroups.push(o)}findDomainGroup(o){for(let l of this.domainGroups){let M=l.matchesDomain(o);if(M!==null)return{group:l,parameters:M}}if(this.wildcardGroup)return{group:this.wildcardGroup,parameters:mt.extractSubdomainInfo(o).parameters};return null}getAllRoutes(){let o=[];for(let l of this.domainGroups){let M=l.getRoutes();for(let k of M)o.push({domainPattern:l.pattern.pattern,domainParameters:{},...k})}if(this.wildcardGroup){let l=this.wildcardGroup.getRoutes();for(let M of l)o.push({domainPattern:this.wildcardGroup.pattern.pattern,domainParameters:{},...M})}return o}}class Gn{router;pattern;group;constructor(o,l){this.router=o;this.pattern=l;this.group=new sr(l,{domain:l.pattern})}middleware(o){return this.group.config.middleware=o,this}prefix(o){return this.group.config.prefix=o,this}name(o){return this.group.config.name=o,this}routes(o){let l=new Wn(this.group);o(l),this.router.addDomainGroup(this.group)}get(o,l,M){this.group.addRoute("GET",o,l,M),this.router.addDomainGroup(this.group)}post(o,l,M){this.group.addRoute("POST",o,l,M),this.router.addDomainGroup(this.group)}put(o,l,M){this.group.addRoute("PUT",o,l,M),this.router.addDomainGroup(this.group)}delete(o,l,M){this.group.addRoute("DELETE",o,l,M),this.router.addDomainGroup(this.group)}patch(o,l,M){this.group.addRoute("PATCH",o,l,M),this.router.addDomainGroup(this.group)}}class Wn{group;constructor(o){this.group=o}get(o,l,M,k){this.group.addRoute("GET",o,l,M,k)}post(o,l,M,k){this.group.addRoute("POST",o,l,M,k)}put(o,l,M,k){this.group.addRoute("PUT",o,l,M,k)}delete(o,l,M,k){this.group.addRoute("DELETE",o,l,M,k)}patch(o,l,M,k){this.group.addRoute("PATCH",o,l,M,k)}options(o,l,M,k){this.group.addRoute("OPTIONS",o,l,M,k)}head(o,l,M,k){this.group.addRoute("HEAD",o,l,M,k)}any(o,l,M,k){let L=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];for(let V of L)this.group.addRoute(V,o,l,M,k)}}function Ma(o){return async(l,M)=>{let L=new URL(l.url).hostname,V=o.findDomainGroup(L);if(V){let pe=l;pe.domainParams=V.parameters,Object.assign(l.params||{},V.parameters);let he=mt.extractSubdomainInfo(L);pe.subdomainInfo=he}return await M()}}var Ea={getSubdomain:(o)=>{let l=new URL(o.url);return mt.extractSubdomainInfo(l.hostname).subdomain||null},getDomainParams:(o)=>o.domainParams||{},matchesDomain:(o,l)=>{let M=new URL(o.url),k=mt.parseDomainPattern(l);return mt.matchDomain(M.hostname,k)!==null},getSubdomainInfo:(o)=>o.subdomainInfo||null},Sa={single:(o,l)=>`${o}.${l}`,wildcard:(o,l="subdomain")=>`{${l}}.${o}`,multiLevel:(o,...l)=>`${l.map((k)=>`{${k}}`).join(".")}.${o}`,apiVersion:(o)=>`{version}.api.${o}`,tenant:(o)=>`{tenant}.app.${o}`,environment:(o)=>`{env}.${o}`};import _i from"process";var Vt=new Map;function At(o,l){Vt.set(o,l)}function Wr(o){return Vt.get(o)}function ji(){return new Map(Vt)}function Li(){Vt.clear()}function zi(o,l={},M={}){let k=Vt.get(o);if(!k){let Te=[...Vt.keys()].sort().join(", ")||"(none registered)";throw Error(`Named route '${o}' is not defined. Known routes: ${Te}`)}let L=new Set,V=k;for(let[Te,xe]of Object.entries(l)){let ve=`{${Te}}`,Pe=`{${Te}?}`,Ce=encodeURIComponent(String(xe));if(V.includes(ve))V=V.replaceAll(ve,Ce),L.add(Te);else if(V.includes(Pe))V=V.replaceAll(Pe,Ce),L.add(Te)}if(V.includes("?}")){if(V=V.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),V.length>1&&V.endsWith("/"))V=V.slice(0,-1)}let pe=V.match(/\{([^}?]+)\}/g);if(pe&&pe.length>0)throw Error(`Missing required params for route '${o}': ${pe.join(", ")}`);let he=Object.entries(l).filter(([Te])=>!L.has(Te));if(he.length>0){let Te=new URLSearchParams;for(let[xe,ve]of he)Te.set(xe,String(ve));V+=`?${Te.toString()}`}if(M.absolute){let Te=(M.base??_i.env.APP_URL??"http://localhost").replace(/\/$/,"");return`${Te.startsWith("http")?Te:`https://${Te}`}${V.startsWith("/")?V:`/${V}`}`}return V}import{join as Vn}from"path";function ir(o){let l=o.replace(/\/+/g,"/");if(!l.startsWith("/"))l=`/${l}`;if(l.length>1&&l.endsWith("/"))l=l.slice(0,-1);return l}function $a(o){return o.replace(/\//g,"_").toLowerCase()}function Gi(o){if(typeof o!=="function"&&typeof o!=="object")return!1;if(typeof o==="function"&&o.prototype){if(typeof o.prototype.handle==="function")return!0}if(typeof o==="object"&&o!==null&&"handle"in o&&typeof o.handle==="function")return!0;return!1}function Ba(o){return typeof o==="function"&&!Gi(o)}function Cr(o){let l=o.match(/\{([^}]+)\}/g);return l?l.map((M)=>M.slice(1,-1).replace("?","")):[]}function Da(o){let l=o.replace(/\{([^}]+)\}/g,"([^/]+)");return new RegExp(`^${l}$`)}var Wi=/\{([^}:]+)(?::[^}]+)?(\?)?\}/,Vi=/\{[^}]+\?\}/,Jn=new Map,Kn=new Map;function Ji(o){let l=Jn.get(o);if(l)return l;let M=o.endsWith("/*"),k=ir(o),L=0,V=k.split("/").filter(Boolean).map((he)=>{let Te=Vi.test(he);if(Te)L++;let xe=he.match(Wi);return{isParam:!!xe,paramName:xe?xe[1].replace("?",""):"",isOptional:Te,literal:he}}),pe={isWildcard:M,wildcardBase:M?o.slice(0,-2):"",segments:V,optionalCount:L};return Jn.set(o,pe),pe}function Ki(o){let l=Kn.get(o);if(l!==void 0)return l;let M;try{M=new RegExp(`^${o}$`)}catch{M=null}return Kn.set(o,M),M}function ft(o,l,M,k){let L=Ji(o);if(L.isWildcard&&l.startsWith(L.wildcardBase))return!0;let V=L.segments,pe=ir(l).split("/").filter(Boolean);if(pe.length<V.length-L.optionalCount||pe.length>V.length)return!1;for(let he=0;he<V.length;he++){let Te=V[he],xe=pe[he];if(xe===void 0){if(Te.isOptional)continue;return!1}if(Te.isParam){let ve=_t(xe);if(M[Te.paramName]=ve,k&&k[Te.paramName]){let Pe=Ki(k[Te.paramName]);if(Pe){if(!Pe.test(ve))return!1}else console.warn(`Invalid constraint regex for parameter ${Te.paramName}: ${k[Te.paramName]}`)}}else if(Te.literal!==xe)return!1}return!0}function kt(...o){return ir(o.join("/"))}function Na(o){if(!o.startsWith("/"))return!1;let l=[];for(let M of o)if(M==="{")l.push(M);else if(M==="}"){if(l.length===0||l.pop()!=="{")return!1}return l.length===0}async function Xn(o){try{return await Bun.file(o).exists()}catch{return!1}}async function Vr(o,l,M){if(M.some((k)=>o.endsWith(k))){let k=ir(Vn(l,o));if(await Xn(k))return k;return null}for(let k of M){let L=ir(Vn(l,`${o}${k}`));if(await Xn(L))return L}return null}function Qn(o,l){let M=o.replace(/\{\{([^}]+)\}\}/g,(k,L)=>{let V=L.trim(),pe=Jr(l,V);return pe!==void 0?String(pe):k});return M=Xi(M,l),M=Qi(M,l),M}function Xi(o,l){return o.replace(/\{\{#if ([^}]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,(M,k,L,V="")=>{let pe=k.trim();return Jr(l,pe)?L:V})}function Qi(o,l){return o.replace(/\{\{#each ([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(M,k,L)=>{let V=Jr(l,k.trim());if(!Array.isArray(V))return"";return V.map((pe)=>L.replace(/\{\{@index\}\}/g,String(V.indexOf(pe))).replace(/\{\{this\}\}/g,String(pe)).replace(/\{\{this\.([^}]+)\}\}/g,(he,Te)=>{let xe=pe[Te.trim()];return xe!==void 0?String(xe):""})).join("")})}function Jr(o,l){return l.split(".").reduce((M,k)=>{if(M&&typeof M==="object"&&k in M)return M[k];return},o)}class ke{method;path;handler;middleware=[];cacheConfig;throttleConfig;routeName;modelBindings={};constructor(o,l,M){this.method=o;this.path=l;this.handler=M}addMiddleware(o){if(Array.isArray(o))this.middleware.push(...o);else this.middleware.push(o);return this}cached(o=[],l){return this.cacheConfig={...jn.api(o),...l},this}throttle(o,l){if(typeof o==="string"){let M=Wt(o);this.throttleConfig={maxAttempts:M.maxAttempts??60,windowMs:M.windowMs,keyGenerator:(k)=>k.headers.get("x-forwarded-for")||"anonymous"}}else this.throttleConfig=o;return this}name(o){return this.routeName=o,this}model(o,l){return this.modelBindings[o]=l,this}build(){let o=[];if(Object.keys(this.modelBindings).length>0){let l=Object.keys(this.modelBindings).map((k)=>({name:k})),M=Nn(l,this.modelBindings);o.push(M)}if(this.throttleConfig){let l=Gt(this.throttleConfig);o.push(l)}if(this.cacheConfig){let l=_n(this.cacheConfig);o.push(l)}return o.push(...this.middleware),{method:this.method,path:this.path,handler:this.handler,middleware:o,name:this.routeName}}}class Zn{router;condition;constructor(o,l){this.router=o;this.condition=l}middleware(o){let[l,M]=o.split(":"),k=this.router.resolveNamedMiddleware(l);if(!k)throw Error(`Unknown middleware: ${l}`);return this.router.addConditionalMiddleware({condition:this.condition,middleware:[k(M)]}),this}}class Yn{router;middleware;constructor(o,l){this.router=o;this.middleware=l}get(o,l){return new ke("GET",o,l).addMiddleware(this.middleware)}post(o,l){return new ke("POST",o,l).addMiddleware(this.middleware)}put(o,l){return new ke("PUT",o,l).addMiddleware(this.middleware)}delete(o,l){return new ke("DELETE",o,l).addMiddleware(this.middleware)}patch(o,l){return new ke("PATCH",o,l).addMiddleware(this.middleware)}}class es{router;groupMiddleware;constructor(o,l){this.router=o;this.groupMiddleware=l}get(o,l){return new ke("GET",o,l).addMiddleware(this.groupMiddleware)}post(o,l){return new ke("POST",o,l).addMiddleware(this.groupMiddleware)}put(o,l){return new ke("PUT",o,l).addMiddleware(this.groupMiddleware)}delete(o,l){return new ke("DELETE",o,l).addMiddleware(this.groupMiddleware)}patch(o,l){return new ke("PATCH",o,l).addMiddleware(this.groupMiddleware)}}class or{routes=[];globalMiddleware=[];subdomainRouter=new Gr;routeGroups=[];middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];constructor(){this.setupDefaultMiddleware()}setupDefaultMiddleware(){this.namedMiddleware.set("throttle",(o)=>{let l=o?Wt(o):{maxAttempts:60,windowMs:60000},M=Gt({maxAttempts:l.maxAttempts,windowMs:l.windowMs,keyGenerator:(L)=>L.headers.get("x-forwarded-for")||"anonymous"});return async(L,V)=>await M(L,async()=>await V()??new Response(null))}),this.namedMiddleware.set("auth",()=>async(o,l)=>{if(!o.headers.get("Authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return o.user={id:"123",roles:["user"]},await l()}),this.namedMiddleware.set("cors",()=>async(o,l)=>{let M=await l();if(M){let k=new Headers(M.headers);return k.set("Access-Control-Allow-Origin","*"),k.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"),k.set("Access-Control-Allow-Headers","Content-Type, Authorization"),new Response(M.body,{status:M.status,statusText:M.statusText,headers:k})}return M})}middlewareGroup(o,l){let M=[];for(let k of l){let[L,V]=k.split(":"),pe=this.namedMiddleware.get(L);if(pe)M.push(pe(V))}return this.middlewareGroups.set(o,M),this}middlewareGroupRoutes(o){let l=this.middlewareGroups.get(o)||[];return new es(this,l)}when(o){return new Zn(this,o)}resolveNamedMiddleware(o){return this.namedMiddleware.get(o)}addConditionalMiddleware(o){this.conditionalMiddleware.push(o)}middleware(o){let[l,M]=o.split(":"),k=this.namedMiddleware.get(l);if(!k)throw Error(`Unknown middleware: ${l}`);let L=k(M);return new Yn(this,[L])}use(o){return this.globalMiddleware.push(o),this}get(o,l){return new ke("GET",o,l)}post(o,l){return new ke("POST",o,l)}put(o,l){return new ke("PUT",o,l)}delete(o,l){return new ke("DELETE",o,l)}patch(o,l){return new ke("PATCH",o,l)}register(o){let l=o.build();if(this.routes.push(l),l.name)At(l.name,l.path);return this}cached(o=[],l){return{get:(M,k)=>this.get(M,k).cached(o,l),post:(M,k)=>this.post(M,k).cached(o,l),put:(M,k)=>this.put(M,k).cached(o,l),delete:(M,k)=>this.delete(M,k).cached(o,l),patch:(M,k)=>this.patch(M,k).cached(o,l)}}throttled(o){return{get:(l,M)=>this.get(l,M).throttle(o),post:(l,M)=>this.post(l,M).throttle(o),put:(l,M)=>this.put(l,M).throttle(o),delete:(l,M)=>this.delete(l,M).throttle(o),patch:(l,M)=>this.patch(l,M).throttle(o)}}group(o,l){let M=new or;l(M);for(let k of M.routes){let L={...k,path:o.prefix?`${o.prefix}${k.path}`:k.path,middleware:[...o.middleware||[],...k.middleware],name:o.name&&k.name?`${o.name}.${k.name}`:k.name};if(o.domain){let V=mt.parseDomainPattern(o.domain),pe=new sr(V,{domain:o.domain});pe.addRoute(L.method,L.path,L.handler,L.middleware,L.name),this.subdomainRouter.addDomainGroup(pe)}else if(this.routes.push(L),L.name)At(L.name,L.path)}return this}domain(o){return{routes:(l)=>{let M=new or;l(M);let k=mt.parseDomainPattern(o),L=new sr(k,{domain:o});for(let V of M.routes)L.addRoute(V.method,V.path,V.handler,V.middleware,V.name);return this.subdomainRouter.addDomainGroup(L),this}}}resource(o,l,M={}){let k=["index","create","store","show","edit","update","destroy"],L=M.only||k.filter((pe)=>!M.except?.includes(pe)),V=[{action:"index",method:"GET",path:`/${o}`,handler:l.index},{action:"create",method:"GET",path:`/${o}/create`,handler:l.create},{action:"store",method:"POST",path:`/${o}`,handler:l.store},{action:"show",method:"GET",path:`/${o}/{${o.slice(0,-1)}}`,handler:l.show},{action:"edit",method:"GET",path:`/${o}/{${o.slice(0,-1)}}/edit`,handler:l.edit},{action:"update",method:"PUT",path:`/${o}/{${o.slice(0,-1)}}`,handler:l.update},{action:"destroy",method:"DELETE",path:`/${o}/{${o.slice(0,-1)}}`,handler:l.destroy}];for(let pe of V)if(L.includes(pe.action)&&pe.handler){let he=new ke(pe.method,pe.path,pe.handler).name(`${o}.${pe.action}`);if(M.model&&["show","edit","update","destroy"].includes(pe.action))he.model(o.slice(0,-1),M.model);this.register(he)}return this}getRoutes(){return[...this.routes,...this.subdomainRouter.getAllRoutes()]}async handle(o){let l=new URL(o.url),M=l.hostname,k=this.subdomainRouter.findDomainGroup(M);if(k){let L=o;L.domainParams=k.parameters;for(let V of k.group.getRoutes()){let pe=this.matchRouteParams(V,o.method,l.pathname);if(pe)return await this.executeRoute(V,L,pe)}}for(let L of this.routes){let V=this.matchRouteParams(L,o.method,l.pathname);if(V)return await this.executeRoute(L,o,V)}return null}matchRouteParams(o,l,M){if(o.method!==l)return null;let k={};return ft(o.path,M,k)?k:null}async executeRoute(o,l,M){l.params=M;let k=[...this.globalMiddleware];for(let pe of this.conditionalMiddleware)if(await pe.condition(l))k.push(...pe.middleware);k.push(...o.middleware);let L=0,V=async()=>{if(L<k.length){let pe=k[L++];return await pe(l,V)??new Response(null)}return $e(await o.handler(l))};return await V()}}var Zi={api:(o,l,M={})=>{let k=M.method||"GET",L=new ke(k,o,l);if(M.cache)L.cached(M.cache);if(M.throttle)L.throttle(M.throttle);return L},protected:(o,l,M={})=>{let k=M.method||"GET",L=new ke(k,o,l);return L.addMiddleware(async(V,pe)=>{if(!V.headers.get("Authorization"))return new Response("Unauthorized",{status:401});return await pe()}),L},upload:(o,l,M={})=>{let k=new ke("POST",o,l);return k.addMiddleware(async(L,V)=>await V()),k}},Yi={route:(o,l={},M={})=>{let k=Wr(o)??`/${o}`;for(let[V,pe]of Object.entries(l)){let he=encodeURIComponent(pe);k=k.replace(`{${V}}`,he),k=k.replace(`{${V}?}`,he)}if(k.includes("?}")){if(k=k.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),k.length>1&&k.endsWith("/"))k=k.slice(0,-1)}let L=new URLSearchParams(M).toString();if(L)k+=`?${L}`;return k},redirect:(o,l=302)=>new Response(null,{status:l,headers:{Location:o}}),json:(o,l=200)=>new Response(JSON.stringify(o),{status:l,headers:{"Content-Type":"application/json"}})},eo=new or;function ts(o){Object.defineProperties(o.prototype,{group:{value(l,M){let k=this.currentGroup,L={...k};if(l.prefix&&k?.prefix)L.prefix=kt(k.prefix,l.prefix);else if(l.prefix)L.prefix=l.prefix;if(l.middleware)L.middleware=[...k?.middleware||[],...l.middleware];this.currentGroup=L;let V=M();if(V instanceof Promise)return V.then(()=>(this.currentGroup=k,this),(pe)=>{throw this.currentGroup=k,pe});return this.currentGroup=k,this},writable:!0,configurable:!0},name:{value(l,M){let k=this.currentGroup||{},L={...k};this.currentGroup=L;let V=this.routes.length;M();for(let pe=V;pe<this.routes.length;pe++){let he=this.routes[pe];if(he.name)he.name=`${l}.${he.name}`}return this.currentGroup=k,this},writable:!0,configurable:!0},controller:{value(l,M){let k=this.currentGroup||{},L={...k,controller:l};return this.currentGroup=L,M(),this.currentGroup=k,this},writable:!0,configurable:!0},domain:{value(l,M){let k=this.currentDomain;return this.currentDomain=l,M(),this.currentDomain=k,this},writable:!0,configurable:!0},prefix:{value(l,M){return this.group({prefix:l},M)},writable:!0,configurable:!0},resource:{value(l,M,k="api"){let L=l.endsWith("s")?l:`${l}s`,V=l.endsWith("s")?l.slice(0,-1):l,pe=[{name:"index",method:"GET",path:`/${L}`,action:"index"},{name:"create",method:"GET",path:`/${L}/create`,action:"create"},{name:"store",method:"POST",path:`/${L}`,action:"store"},{name:"show",method:"GET",path:`/${L}/{id}`,action:"show"},{name:"edit",method:"GET",path:`/${L}/{id}/edit`,action:"edit"},{name:"update",method:"PUT",path:`/${L}/{id}`,action:"update"},{name:"destroy",method:"DELETE",path:`/${L}/{id}`,action:"destroy"}];return this.name(V,()=>{for(let he of pe){let Te;if(typeof M==="string")Te=`${M}${he.action.charAt(0).toUpperCase()+he.action.slice(1)}Action`;else if(M[he.action])Te=M[he.action];else continue;switch(he.method){case"GET":this.get(he.path,Te,k,he.name);break;case"POST":this.post(he.path,Te,k,he.name);break;case"PUT":this.put(he.path,Te,k,he.name);break;case"DELETE":this.delete(he.path,Te,k,he.name);break}}}),this},writable:!0,configurable:!0}})}function rs(o){Object.defineProperties(o.prototype,{addRoute:{value(l,M,k,L,V,pe){let he=M,Te=[],xe=L||"web";if(this.currentGroup){if(this.currentGroup.prefix)he=kt(this.currentGroup.prefix,M);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)Te=[...this.currentGroup.middleware]}if(pe&&pe.length>0)for(let Me of pe){let Se=this.resolveMiddleware(Me);if(Se)Te.push(Se)}if(xe==="api"&&this.config.apiPrefix)he=kt(this.config.apiPrefix,he);else if(xe==="web"&&this.config.webPrefix)he=kt(this.config.webPrefix,he);let ve;if(this.currentDomain)ve=this.currentDomain;let Pe={method:l.toUpperCase(),path:he,handler:k,domain:ve,params:{},middleware:Te},Ce=Cr(he),Ee={};if(Ce.forEach((Me)=>{let Se=Me.replace("?","");if(this.patterns.has(Se))Ee[Se]=this.patterns.get(Se)}),Object.keys(Ee).length>0)Pe.constraints=Ee;if(Pe.pattern={exec:(Me)=>{let Se={},Oe=Pe.constraints&&!Array.isArray(Pe.constraints)?Pe.constraints:void 0;if(!ft(he,Me.pathname,Se,Oe))return null;return{pathname:{groups:Se}}}},k instanceof Response)this.staticResponses.set(he,k);if(ve){if(this._hasDomainRoutes=!0,!this.domains[ve])this.domains[ve]=[];this.domains[ve].push(Pe)}else this.routes.push(Pe);if(!he.includes("{")&&!he.includes("*")){if(!this.staticRoutes.has(l.toUpperCase()))this.staticRoutes.set(l.toUpperCase(),new Map);let Me=this.staticRoutes.get(l.toUpperCase());if(!Me.has(he))Me.set(he,Pe)}if(V)Pe.name=V,this.namedRoutes.set(V,Pe),At(V,Pe.path);if(this.addRouteToCompiler&&!ve)this.addRouteToCompiler(Pe);return this.routeCache.clear(),this._allowedMethodsCache?.clear(),this},writable:!0,configurable:!0},get:{value(l,M,k,L,V){return this.addRoute("GET",l,M,k,L,V)},writable:!0,configurable:!0},post:{value(l,M,k,L,V){return this.addRoute("POST",l,M,k,L,V)},writable:!0,configurable:!0},put:{value(l,M,k,L,V){return this.addRoute("PUT",l,M,k,L,V)},writable:!0,configurable:!0},patch:{value(l,M,k,L,V){return this.addRoute("PATCH",l,M,k,L,V)},writable:!0,configurable:!0},delete:{value(l,M,k,L,V){return this.addRoute("DELETE",l,M,k,L,V)},writable:!0,configurable:!0},options:{value(l,M,k,L,V){return this.addRoute("OPTIONS",l,M,k,L,V)},writable:!0,configurable:!0},head:{value(l,M,k,L,V){return this.addRoute("HEAD",l,M,k,L,V)},writable:!0,configurable:!0},match:{value(l,M,k,L,V,pe){for(let he of l)this.addRoute(he,M,k,L,V,pe);return this},writable:!0,configurable:!0},any:{value(l,M,k,L,V){let pe=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];return this.match(pe,l,M,k,L,V)},writable:!0,configurable:!0},fallback:{value(l){return this.fallbackHandler=l,this},writable:!0,configurable:!0},route:{value(l,M={}){let k=this.namedRoutes.get(l);if(!k)throw Error(`Route with name "${l}" not found`);let L=k.path;for(let[V,pe]of Object.entries(M))L=L.replace(`{${V}}`,encodeURIComponent(pe)),L=L.replace(`{${V}?}`,encodeURIComponent(pe));if(L.includes("{")){if(L=L.replace(/\{[^}]+\?\}/g,"").replace(/\/{2,}/g,"/"),L.length>1&&L.endsWith("/"))L=L.slice(0,-1)}return L},writable:!0,configurable:!0},onError:{value(l){return this.errorHandler=l,this},writable:!0,configurable:!0}})}function ns(o){Object.defineProperties(o.prototype,{redirect:{value(l,M=302){let k=new Headers;return k.set("Location",l),new Response(null,{status:M,headers:k})},writable:!0,configurable:!0},permanentRedirect:{value(l){return this.redirect(l,301)},writable:!0,configurable:!0},redirectRoute:{value(l,M,k=302){return this.get(l,(L)=>this.redirect(M,k)),this},writable:!0,configurable:!0},permanentRedirectRoute:{value(l,M){return this.redirectRoute(l,M,301)},writable:!0,configurable:!0}})}function ss(o){Object.defineProperties(o.prototype,{use:{value(...l){for(let M of l){let k=this.resolveMiddleware(M);if(k)this.globalMiddleware.push(k)}return this._mwEpoch=(this._mwEpoch||0)+1,this},writable:!0,configurable:!0},resolveMiddleware:{value(l){if(typeof l==="function")return l;if(typeof l==="object"&&l!==null&&"handle"in l&&typeof l.handle==="function")return(M,k)=>l.handle(M,k);if(typeof l==="string"){let[M,k]=l.split(":"),L=this.namedMiddleware?.get(M);if(L)return L(k);let V=null,pe=l;return async(he,Te)=>{if(!V)try{let xe=await import(`../middleware/${pe}.ts`);if(xe.default&&typeof xe.default==="function")V=xe.default;else if(xe.default&&typeof xe.default.handle==="function")V=(ve,Pe)=>xe.default.handle(ve,Pe)}catch(xe){console.error(`Failed to load middleware "${pe}":`,xe)}if(V)return V(he,Te);return Te()}}return null},writable:!0,configurable:!0},buildMiddlewareChain:{value(l){if(l.length===0)return async(k)=>null;let M=async(k)=>null;for(let k=l.length-1;k>=0;k--){let L=l[k],V=M;M=async(pe)=>L(pe,async()=>await V(pe)||new Response(null,{status:200}))}return M},writable:!0,configurable:!0},runMiddleware:{async value(l,M){if(M.length===0)return null;try{return await this.buildMiddlewareChain(M)(l)}catch(k){if(this.errorHandler)return this.errorHandler(k);throw k}},writable:!0,configurable:!0},middleware:{value(...l){for(let M of l)if(typeof M==="string"){let[k]=M.split(":");if(!this.namedMiddleware.has(k))throw Error(`Unknown middleware: ${k}`)}if(this.currentGroup){if(!this.currentGroup.middleware)this.currentGroup.middleware=[];this.currentGroup.middleware.push(...l)}else{let M=this.routes[this.routes.length-1];if(M)this.applyMiddlewareToRoute(M,l)}return this},writable:!0,configurable:!0},applyMiddlewareToRoute:{value(l,M){for(let k of M){let L=this.resolveMiddleware(k);if(L)l.middleware.push(L)}},writable:!0,configurable:!0},resolveHandler:{async value(l,M){return rr(l,M,this.config)},writable:!0,configurable:!0},wrapResponse:{value:$e,writable:!0,configurable:!0},onError:{value(l){return this.errorHandler=l,this},writable:!0,configurable:!0}})}class is{models=new Map;cache=new Map;register(o,l){this.models.set(o,l)}get(o){return this.models.get(o)}has(o){return this.models.has(o)}async resolve(o,l,M){let k=this.models.get(o);if(!k)return{model:null,error:`Model binding '${o}' not found`,status:500};try{if(k.cache?.enabled){let pe=this.getCachedModel(o,l,k);if(pe)return{model:pe}}let L=await k.resolver(l,M);if(L===null||L===void 0)return{model:null,error:`${o} not found`,status:404};if(k.validator){let pe=await k.validator(L,l,M);if(!pe.valid)return{model:null,error:pe.error||"Model validation failed",status:pe.status||422}}let V=L;if(k.transformer)V=await k.transformer(L,l,M);if(k.cache?.enabled)this.cacheModel(o,l,V,k);return{model:V}}catch(L){return{model:null,error:L instanceof Error?L.message:"Model resolution failed",status:500}}}createErrorResponse(o,l,M){let k=this.models.get(o),L=l.status||404,V=l.error||"Model not found";if(k?.errorHandling){if(L===404&&k.errorHandling.notFound)return k.errorHandling.notFound(M);if(L===422&&k.errorHandling.validation)return k.errorHandling.validation(null,V);if(k.errorHandling.transform)return k.errorHandling.transform(V)}return new Response(JSON.stringify({error:V,status:L,message:`Failed to resolve ${o}`}),{status:L,headers:{"Content-Type":"application/json"}})}clearCache(o,l){if(l){let M=this.models.get(o);if(M?.cache){let k=this.generateCacheKey(o,l,M);this.cache.delete(k)}}else{let M=[];for(let k of this.cache.keys())if(k.startsWith(`${o}:`))M.push(k);for(let k of M)this.cache.delete(k)}}clearAllCache(){this.cache.clear()}getCacheStats(){let o=Date.now(),l=0,M=0;for(let k of this.cache.values())if(o-k.timestamp>k.ttl)M++;else l++;return{totalEntries:this.cache.size,validEntries:l,expiredEntries:M,models:this.models.size}}cleanupCache(){let o=Date.now(),l=[];for(let[M,k]of this.cache.entries())if(o-k.timestamp>k.ttl)l.push(M);for(let M of l)this.cache.delete(M);return l.length}getCachedModel(o,l,M){if(!M.cache?.enabled)return null;let k=this.generateCacheKey(o,l,M),L=this.cache.get(k);if(!L)return null;if(Date.now()-L.timestamp>L.ttl)return this.cache.delete(k),null;return L.model}cacheModel(o,l,M,k){if(!k.cache?.enabled)return;let L=this.generateCacheKey(o,l,k);this.cache.set(L,{model:M,timestamp:Date.now(),ttl:k.cache.ttl})}generateCacheKey(o,l,M){if(M.cache?.key)return`${o}:${M.cache.key(l)}`;let k=Object.entries(l).sort(([L],[V])=>L.localeCompare(V)).map(([L,V])=>`${L}=${V}`).join("&");return`${o}:${k}`}}var os=new is;function as(o){Object.defineProperties(o.prototype,{modelRegistry:{value:os,writable:!0,configurable:!0},model:{value(l,M,k){if(typeof M==="string")this.modelRegistry.register(l,{resolver:async(L)=>(console.warn(`Model class ${M} not implemented`),{id:L[l],modelClass:M}),errorHandling:k?{notFound:(L)=>k(null)||new Response("Not Found",{status:404})}:void 0});else this.modelRegistry.register(l,{resolver:async(L)=>{let V=L[l];if(!V)return null;return M(V)},errorHandling:k?{notFound:(L)=>k(null)||new Response("Not Found",{status:404})}:void 0});return this},writable:!0,configurable:!0},implicitBinding:{value(){return async(l,M)=>{if(!l.params)return await M()||new Response("Not Found",{status:404});for(let[L,V]of Object.entries(l.params))if(this.modelRegistry.has(L))try{let pe=await this.modelRegistry.resolve(L,l.params,l);if(pe.model===null){if(pe.status===500)return new Response(JSON.stringify({error:"Internal Server Error",message:pe.error||"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}});else if(pe.status===404)return this.modelRegistry.createErrorResponse(L,pe,l.params)}else l[L]=pe.model}catch(pe){return new Response(JSON.stringify({error:"Internal Server Error",message:pe instanceof Error?pe.message:"Model resolution failed"}),{status:500,headers:{"Content-Type":"application/json"}})}return await M()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},missing:{value(l){return async(M,k)=>{try{return await k()||l(M)}catch(L){return console.error(L),l(M)}}},writable:!0,configurable:!0},scopedBindings:{value(l){return async(M,k)=>{if(!M.params)return await k()||new Response("Not Found",{status:404});for(let[V,pe]of Object.entries(l))if(M.params[V]&&M.params[pe]);return await k()||new Response("Not Found",{status:404})}},writable:!0,configurable:!0},clearModelCache:{value(l){if(l)this.modelRegistry.clearCache(l);else this.modelRegistry.clearAllCache();return this},writable:!0,configurable:!0},getModelStats:{value(){return this.modelRegistry.getCacheStats()},writable:!0,configurable:!0}})}class qt{children=new Map;paramChild=null;wildcardChild=null;routes=new Map;paramName=null;pattern=null;isEndpoint=!1;addRoute(o,l){this.routes.set(o,l),this.isEndpoint=!0}getRoute(o){return this.routes.get(o)}getAllRoutes(){return Array.from(this.routes.values())}}class Kr{root=new qt;compiledRoutes=new Map;methodTries=new Map;constructor(){let o=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","TRACE","CONNECT"];for(let l of o)this.methodTries.set(l,new qt)}compileRoute(o){let l=`${o.method}:${o.path}`;if(o.constraints&&!Array.isArray(o.constraints)){let Te=o.constraints,ve=Object.keys(Te).sort().map((Pe)=>`${Pe}:${Te[Pe]}`).join("|");l=`${o.method}:${o.path}#${ve}`}if(this.compiledRoutes.has(l))return this.compiledRoutes.get(l);let M=this.parsePathSegments(o.path),k=M.filter((Te)=>Te.type==="parameter").map((Te)=>Te.paramName);if(o.constraints&&!Array.isArray(o.constraints)){let Te=o.constraints;for(let xe of M)if(xe.type==="parameter"&&xe.paramName&&Te[xe.paramName])xe.pattern=new RegExp(`^${Te[xe.paramName]}$`)}let L=this.calculateRoutePriority(M),V=M.filter((Te)=>Te.type==="static").length,pe=M.filter((Te)=>Te.type!=="static").length,he={route:o,segments:M,paramNames:k,priority:L,staticScore:V,dynamicScore:pe};return this.compiledRoutes.set(l,he),he}parsePathSegments(o){let l=[],M=o.split("/").filter((k)=>k.length>0);for(let k of M)if(k==="*")l.push({type:"wildcard",value:"*"});else if(/^\{[^{}/]+\}\*$/.test(k))l.push({type:"wildcard",value:k,paramName:k.slice(1,k.indexOf("}"))});else if(k.startsWith("{")&&k.endsWith("}")){let L=k.slice(1,-1),[V,pe]=L.split(":");l.push({type:"parameter",value:k,paramName:V.replace("?",""),pattern:pe?new RegExp(`^${pe}$`):void 0,optional:L.endsWith("?")})}else if(k.includes("{")){let L=k.replace(/\{([^}:]+)(?::([^}]+))?\}/g,(pe,he,Te)=>Te?`(${Te})`:"([^/]+)"),V=Array.from(k.matchAll(/\{([^}:]+)(?::([^}]+))?\}/g)).map((pe)=>pe[1].replace("?",""));l.push({type:"parameter",value:k,paramName:V[0],pattern:new RegExp(`^${L}$`)})}else l.push({type:"static",value:k});return l}calculateRoutePriority(o){let l=0;for(let M=0;M<o.length;M++){let k=o[M],L=o.length-M;switch(k.type){case"static":l+=L*1000;break;case"parameter":if(k.pattern)l+=L*100;else l+=L*10;break;case"wildcard":l+=L*1;break}}return l}addRoute(o){let l=this.compileRoute(o);this.insertRoute(this.root,l,0);let M=this.methodTries.get(o.method);if(M)this.insertRoute(M,l,0)}insertRoute(o,l,M){if(M>=l.segments.length){o.addRoute(l.route.method,l);return}let k=l.segments[M];switch(k.type){case"static":if(!o.children.has(k.value))o.children.set(k.value,new qt);this.insertRoute(o.children.get(k.value),l,M+1);break;case"parameter":if(!o.paramChild)o.paramChild=new qt,o.paramChild.paramName=k.paramName,o.paramChild.pattern=k.pattern||null;this.insertRoute(o.paramChild,l,M+1);break;case"wildcard":if(!o.wildcardChild)o.wildcardChild=new qt,o.wildcardChild.paramName=k.paramName??null;this.insertRoute(o.wildcardChild,l,M+1);break}}match(o,l){let M=o.split("/").filter((L)=>L.length>0),k=this.methodTries.get(l);if(k){let L=this.matchSegments(k,M,0,{},l);if(L)return L}return this.matchSegments(this.root,M,0,{},l)}matchSegments(o,l,M,k,L){if(M>=l.length){let xe=o.getRoute(L);if(xe)return{route:xe.route,params:k,score:xe.priority};return null}let V=l[M],pe=o.children.get(V);if(pe){let xe=this.matchSegments(pe,l,M+1,k,L);if(xe)return xe}let he=o.paramChild,Te=he?.paramName?_t(V):V;if(he&&he.paramName&&(!he.pattern||he.pattern.test(Te))){let xe=k[he.paramName];k[he.paramName]=Te;let ve=this.matchSegments(he,l,M+1,k,L);if(ve)return ve;if(xe===void 0)delete k[he.paramName];else k[he.paramName]=xe}if(o.wildcardChild){let xe=o.wildcardChild.getRoute(L);if(xe)return k[o.wildcardChild.paramName??"wildcard"]=l.slice(M).map(_t).join("/"),{route:xe.route,params:k,score:xe.priority}}return null}getAllRoutes(){return Array.from(this.compiledRoutes.values())}removeRoute(o){let l=`${o.method}:${o.path}`;if(o.constraints&&!Array.isArray(o.constraints)){let M=o.constraints,L=Object.keys(M).sort().map((V)=>`${V}:${M[V]}`).join("|");l=`${o.method}:${o.path}#${L}`}this.compiledRoutes.delete(l)}clear(){this.root=new qt,this.compiledRoutes.clear();for(let[o]of this.methodTries)this.methodTries.set(o,new qt)}getStats(){let o={totalRoutes:this.compiledRoutes.size,totalNodes:this.countNodes(this.root),averageDepth:0,methodDistribution:{}};for(let l of this.compiledRoutes.values()){let M=l.route.method;o.methodDistribution[M]=(o.methodDistribution[M]||0)+1}return o}countNodes(o){let l=1;for(let M of o.children.values())l+=this.countNodes(M);if(o.paramChild)l+=this.countNodes(o.paramChild);if(o.wildcardChild)l+=this.countNodes(o.wildcardChild);return l}}class Mr{trie;matchCache=new Map;routeKeys=new Set;stats={totalMatches:0,cacheHits:0,cacheMisses:0,averageMatchTime:0,trieDepth:0,methodDistribution:{}};options;constructor(o={}){this.options={enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0,enableProfiling:!1,...o},this.trie=new Kr}addRoute(o){if(this.options.precompilePatterns)this.precompileRoutePattern(o);let l=`${o.method}:${o.path}`;if(this.routeKeys.has(l))return!1;if(this.routeKeys.add(l),this.trie.addRoute(o),this.options.enableCaching)this.matchCache.clear();let M=o.method;return this.stats.methodDistribution[M]=(this.stats.methodDistribution[M]||0)+1,!0}patternCache=new Map;extractParamNames(o){let l=[],M=/\{([^}:]+)(?::[^}]+)?\}/g,k;while(k=M.exec(o))l.push(k[1].replace("?",""));return l}precompileRoutePattern(o){if(!o.pattern&&o.path.includes("{")){let l=o.path;if(o.constraints&&!Array.isArray(o.constraints)){let L=o.constraints,pe=Object.keys(L).sort().map((he)=>`${he}:${L[he]}`).join("|");l=`${o.path}#${pe}`}if(this.patternCache.has(l)){o.pattern=this.patternCache.get(l);return}let M=this.convertToURLPattern(o.path,o.constraints&&!Array.isArray(o.constraints)?o.constraints:void 0),k={exec:(L)=>{let V=L.pathname,pe=M.exec(V);if(!pe)return null;return{pathname:{groups:pe.groups||{}}}}};this.patternCache.set(l,k),o.pattern=k}}convertToURLPattern(o,l){let M=o,k=null,L=M.match(/\{([^{}/]+)\}\*$/);if(L)k=L[1],M=M.slice(0,L.index);else if(M.endsWith("*"))k="wildcard",M=M.slice(0,-1);let V=[],he=M.replace(/\{([^}]+)\}/g,(xe,ve)=>(V.push(ve),`\x00${V.length-1}\x00`)).replace(/[.+*?^${}()|[\]\\]/g,"\\$&");if(he=he.replace(/\/?\u0000(\d+)\u0000/g,(xe,ve)=>{let Pe=V[Number(ve)],Ce=Pe.endsWith("?"),Ee=Ce?Pe.slice(0,-1):Pe,Me=Ee.indexOf(":"),Se=Me===-1?Ee:Ee.slice(0,Me),Oe=Me===-1?void 0:Ee.slice(Me+1),Ie=l?.[Se]??Oe??"[^/]+",Ft=`(?<${Se}>${Ie})`,dr=xe.startsWith("/")?"/":"";return Ce?`(?:${dr}${Ft})?`:`${dr}${Ft}`}),k!==null)he+=`(?<${k}>${l?.[k]??".+"})`;let Te=new RegExp(`^${he}$`);return{exec:(xe)=>{let ve=xe.match(Te);if(!ve)return null;return{groups:ve.groups||{}}}}}match(o,l){let M=this.options.enableProfiling?performance.now():0;this.stats.totalMatches++;let k;if(this.options.enableCaching){k=`${l}:${o}`;let pe=this.matchCache.get(k);if(pe!==void 0){if(this.stats.cacheHits++,M)this.updateMatchTime(M);return pe?{route:pe.route,params:{...pe.params}}:null}this.stats.cacheMisses++}let L=this.trie.match(o,l),V=null;if(L)V={route:L.route,params:L.params};if(k!==void 0)this.addToCache(k,V);if(M)this.updateMatchTime(M);return V?{route:V.route,params:{...V.params}}:null}addToCache(o,l){if(this.matchCache.size>=this.options.cacheSize){let M=this.matchCache.keys().next().value;if(M!==void 0)this.matchCache.delete(M)}this.matchCache.set(o,l)}updateMatchTime(o){let l=performance.now()-o;this.stats.averageMatchTime=(this.stats.averageMatchTime*(this.stats.totalMatches-1)+l)/this.stats.totalMatches}getCompiledRoutes(){let o=this.trie.getAllRoutes();if(this.options.enablePriorityOptimization)return o.sort((l,M)=>M.priority-l.priority);return o}getRoutesByMethod(){let o=new Map;for(let l of this.trie.getAllRoutes()){let M=l.route.method;if(!o.has(M))o.set(M,[]);o.get(M).push(l)}if(this.options.enablePriorityOptimization)for(let[l,M]of o)M.sort((k,L)=>L.priority-k.priority),o.set(l,M);return o}warmCache(o,l={}){if(!this.options.enableCaching&&!l.force)return{warmedPaths:0,cacheSize:0,hitRate:0};let M=this.options.enableCaching;if(l.force&&!this.options.enableCaching)this.options.enableCaching=!0;if(l.precompile)for(let{path:ve,method:Pe}of o){let Ce=`${Pe}:${ve}`;this.matchCache.delete(Ce)}let k=this.matchCache.size,L=this.stats.cacheHits,V=this.stats.totalMatches;for(let{path:ve,method:Pe}of o)if(this.match(ve,Pe),l.precompile)this.match(ve,Pe);let pe=this.matchCache.size-k,he=this.stats.cacheHits-L,Te=this.stats.totalMatches-V,xe=Te>0?he/Te:0;if(l.force&&!M)this.options.enableCaching=M;return{warmedPaths:pe,cacheSize:this.matchCache.size,hitRate:xe}}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 o=this.trie.getStats();return{...this.stats,trieDepth:o.averageDepth,methodDistribution:o.methodDistribution}}getCacheStats(){let o=this.stats.totalMatches>0?this.stats.cacheHits/this.stats.totalMatches:0;return{size:this.matchCache.size,maxSize:this.options.cacheSize,hitRate:o,enabled:this.options.enableCaching}}optimizeRouteOrder(o){if(!this.options.enablePriorityOptimization)return;this.matchCache.clear()}getRouteConflicts(){let o=[],l=this.trie.getAllRoutes(),M=new Map;for(let k of l){let L=k.route.method;if(!M.has(L))M.set(L,[]);M.get(L).push(k)}for(let[k,L]of M)for(let V=0;V<L.length;V++)for(let pe=V+1;pe<L.length;pe++){let he=L[V],Te=L[pe];if(this.routesConflict(he,Te)){let xe=this.getConflictSeverity(he,Te),ve=this.getConflictType(he,Te);o.push({routes:[he,Te],conflictType:ve,severity:xe})}}return o}routesConflict(o,l){if(o.route.path===l.route.path)return!0;if(o.route.method!==l.route.method)return!1;return this.patternsOverlap(o.segments,l.segments)}patternsOverlap(o,l){let M=o.some((pe)=>pe.optional||pe.type==="wildcard"),k=l.some((pe)=>pe.optional||pe.type==="wildcard");if(o.length!==l.length&&!M&&!k)return!1;let L=Math.max(o.length,l.length),V=!0;for(let pe=0;pe<L;pe++){let he=pe<o.length?o[pe]:null,Te=pe<l.length?l[pe]:null;if(!he&&Te&&!Te.optional)return!1;if(!Te&&he&&!he.optional)return!1;if(!he||!Te)continue;if(he.type==="static"&&Te.type==="static"){if(he.value!==Te.value)return!1}else if(he.type==="parameter"&&Te.type==="parameter"){if(he.pattern&&Te.pattern){if(he.pattern.toString()===Te.pattern.toString())V=!0}if(he.paramName===Te.paramName)V=!0}else if(he.type==="static"&&Te.type==="parameter"||he.type==="parameter"&&Te.type==="static"){let xe=he.type==="static"?he:Te,ve=he.type==="parameter"?he:Te;if(ve.pattern){if(!ve.pattern.test(xe.value))return!1}}else if(he.type==="wildcard"||Te.type==="wildcard")return!0}return V}getConflictSeverity(o,l){if(o.route.path===l.route.path)return"high";if(o.staticScore===l.staticScore)return"medium";return"low"}getConflictType(o,l){if(o.route.path===l.route.path)return"duplicate";if(this.hasAmbiguousParameters(o,l))return"ambiguous";if(Math.abs(o.priority-l.priority)<10)return"ambiguous";return"overlap"}hasAmbiguousParameters(o,l){if(Math.abs(o.segments.length-l.segments.length)>1)return!1;let M=o.segments.filter((L)=>L.type==="parameter").length,k=l.segments.filter((L)=>L.type==="parameter").length;if(M>0&&k>0){let L=Math.min(o.segments.length,l.segments.length),V=0;for(let pe=0;pe<L;pe++)if(o.segments[pe].type==="parameter"&&l.segments[pe].type==="parameter"){V++;let he=!!o.segments[pe].pattern,Te=!!l.segments[pe].pattern;if(he!==Te)return!0}return V>0&&V>=Math.min(M,k)/2}return!1}}function us(o){Object.defineProperties(o.prototype,{initializeRouteCompiler:{value(){if(!this.routeCompiler)this.routeCompiler=new Mr({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0})},writable:!0,configurable:!0},addRouteToCompiler:{value(l){this.initializeRouteCompiler(),this.routeCompiler.addRoute(l)},writable:!0,configurable:!0},matchRoute:{value(l,M,k,L=!1){if(this.initializeRouteCompiler(),k&&this.domains[k]){let V=this.fallbackMatchRoute(l,M,k,L);if(V)return V}else{let V=this.routeCompiler.match(l,M);if(V&&(!k||!V.route.domain||V.route.domain===k))return V;let pe=this.fallbackMatchRoute(l,M,k,L);if(pe)return pe}if(M==="HEAD")return this.matchRoute(l,"GET",k,L);return},writable:!0,configurable:!0},fallbackMatchRoute:{value(l,M,k,L=!1){let V,pe=l;if(!L)V=new URL(l,"http://localhost"),pe=V.pathname;let he=`${k||""}:${M}:${pe}`;if(this.routeCache.has(he))return this.routeCache.get(he);if(this.routeCache.size>=1e4)this.routeCache.clear();if(this.staticRoutes.has(M)){let Pe=this.staticRoutes.get(M).get(pe);if(Pe&&(!k||!Pe.domain||Pe.domain===k)){let Ce={route:Pe,params:{}};return this.routeCache.set(he,Ce),Ce}}let xe=(k&&this.domains[k]?this.domains[k]:this.routes).filter((Pe)=>Pe.method===M);for(let Pe of xe)if(Pe.path===pe){let Ce={route:Pe,params:{}};return this.routeCache.set(he,Ce),Ce}for(let Pe of xe)if(Pe.pattern){let Ce=Pe.pattern.exec(V??=new URL(pe,"http://localhost"));if(Ce){let Ee={route:Pe,params:Ce.pathname.groups};return this.routeCache.set(he,Ee),Ee}}let ve=k&&this.domains[k]?[this.domains[k],this.routes]:[this.routes];for(let Pe of ve)for(let Ce of Pe){if(Ce.method!==M||!Ce.path.endsWith("*"))continue;let Ee=Ce.path.slice(0,-1);if(pe.startsWith(Ee)){let Me={route:Ce,params:{wildcard:pe.slice(Ee.length)}};return this.routeCache.set(he,Me),Me}}this.routeCache.set(he,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(l){this.initializeRouteCompiler(),this.routeCompiler.warmCache(l)},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 Mr({enableCaching:!0,enableMethodGrouping:!0,enablePriorityOptimization:!0,cacheSize:1000,precompilePatterns:!0});for(let l of this.routes)this.routeCompiler.addRoute(l);for(let l of Object.values(this.domains))for(let M of l)this.routeCompiler.addRoute(M)},writable:!0,configurable:!0},optimizeRoutes:{value(l={}){this.initializeRouteCompiler(),this.routeCompiler.optimizeRouteOrder(l)},writable:!0,configurable:!0}})}function cs(o){Object.defineProperties(o.prototype,{buildBunServeRoutes:{value(){let l={},M=new Map;for(let k of this.routes){if(!M.has(k.path))M.set(k.path,[]);M.get(k.path).push(k)}for(let[k,L]of M.entries())if(L.length===1){let V=L[0];if(typeof V.handler==="function"&&V.handler.toString().includes("new Response")&&!V.handler.toString().includes("await")&&V.middleware.length===0)try{let pe=this.enhanceRequest(new Request("https://example.com"),{}),he=V.handler(pe);if(he instanceof Response){l[k]=he;continue}}catch{}l[k]=async(pe)=>{let he=new URL(pe.url),Te={},xe=V.constraints&&!Array.isArray(V.constraints)?V.constraints:void 0;ft(k,he.pathname,Te,xe);let ve=this.enhanceRequest(pe,Te),Pe=async(Me,Se)=>await this.resolveHandler(V.handler,Me),Ce=[...this.globalMiddleware,...V.middleware,Pe],Ee=await this.runMiddleware(ve,Ce);return this.applyModifiedCookies(Ee??new Response("No response from middleware chain",{status:500}),ve)}}else{let V={};for(let pe of L){let he=pe.method;V[he]=async(Te)=>{let xe=new URL(Te.url),ve={},Pe=pe.constraints&&!Array.isArray(pe.constraints)?pe.constraints:void 0;ft(k,xe.pathname,ve,Pe);let Ce=this.enhanceRequest(Te,ve),Ee=async(Oe,Ie)=>await this.resolveHandler(pe.handler,Oe),Me=[...this.globalMiddleware,...pe.middleware,Ee],Se=await this.runMiddleware(Ce,Me);return this.applyModifiedCookies(Se??new Response("No response from middleware chain",{status:500}),Ce)}}l[k]=V}return l},writable:!0,configurable:!0},loadRoutes:{async value(){if(!this.config.routesPath)return;try{if(this.config.apiRoutesPath)try{let l=await import(this.config.apiRoutesPath);if(l.default&&Array.isArray(l.default))for(let M of l.default)this.registerRoute(M,"api")}catch(l){if(this.config.verbose)console.warn(`Failed to load API routes: ${l}`)}if(this.config.webRoutesPath)try{let l=await import(this.config.webRoutesPath);if(l.default&&Array.isArray(l.default))for(let M of l.default)this.registerRoute(M,"web")}catch(l){if(this.config.verbose)console.warn(`Failed to load Web routes: ${l}`)}}catch(l){console.error("Error loading routes:",l)}},writable:!0,configurable:!0},registerRoute:{value(l,M){let{path:k,method:L,handler:V,middleware:pe=[],name:he}=l;switch(L){case"GET":this.get(k,V,M,he,pe);break;case"POST":this.post(k,V,M,he,pe);break;case"PUT":this.put(k,V,M,he,pe);break;case"DELETE":this.delete(k,V,M,he,pe);break;case"PATCH":this.patch(k,V,M,he,pe);break;case"OPTIONS":this.options(k,V,M,he,pe);break;default:console.warn(`Unsupported HTTP method: ${L}`)}},writable:!0,configurable:!0}})}function ls(o){Object.defineProperties(o.prototype,{matchRoute:{value(l,M,k){let L=new URL(l,"http://localhost"),V=`${k||""}:${M}:${L.pathname}`;if(this.routeCache.has(V))return this.routeCache.get(V);if(this.staticRoutes.has(M)){let xe=this.staticRoutes.get(M).get(L.pathname);if(xe&&(!k||!xe.domain||xe.domain===k)){let ve={route:xe,params:{}};return this.routeCache.set(V,ve),ve}}let pe=k&&this.domains[k]?this.domains[k]:this.routes,he=pe.filter((xe)=>xe.method===M);for(let xe of he)if(xe.path===L.pathname){let ve={route:xe,params:{}};return this.routeCache.set(V,ve),ve}for(let xe of he)if(xe.pattern){let ve=xe.pattern.exec(L);if(ve){let Pe={route:xe,params:ve.pathname.groups};return this.routeCache.set(V,Pe),Pe}}if(k&&this.domains[k]){let xe=this.domains[k].filter((ve)=>ve.method===M&&ve.path.endsWith("*"));for(let ve of xe){let Pe=ve.path.slice(0,-1);if(L.pathname.startsWith(Pe)){let Ce={route:ve,params:{wildcard:L.pathname.slice(Pe.length)}};return this.routeCache.set(V,Ce),Ce}}}let Te=this.routes.filter((xe)=>xe.method===M&&xe.path.endsWith("*")&&(!k||!xe.domain));for(let xe of Te){let ve=xe.path.slice(0,-1);if(L.pathname.startsWith(ve)){let Pe={route:xe,params:{wildcard:L.pathname.slice(ve.length)}};return this.routeCache.set(V,Pe),Pe}}if(M==="HEAD")return this.matchRoute(l,"GET",k);if(M==="OPTIONS"){let xe=pe.find((ve)=>ve.method==="OPTIONS"&&ve.path==="*");if(xe){let ve={route:xe,params:{}};return this.routeCache.set(V,ve),ve}for(let ve of["GET","POST","PUT","PATCH","DELETE"]){let Pe=this.matchRoute(l,ve,k);if(Pe){let Ce={route:{...Pe.route,method:"OPTIONS",handler:(Ee)=>new Response(null,{status:204})},params:Pe.params};return this.routeCache.set(V,Ce),Ce}}}return},writable:!0,configurable:!0},matchDomain:{value(l,M){if(l===M)return!0;if(l.startsWith("*.")){let k=l.substring(2);return M===k||M.endsWith(`.${k}`)}if(l.includes("{")){let k;if(!this.domainPatternCache.has(l)){let L=l.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)");k=new RegExp(`^${L}$`),this.domainPatternCache.set(l,k)}else k=this.domainPatternCache.get(l);return k.test(M)}return!1},writable:!0,configurable:!0},extractDomainParams:{value(l,M){let k={};if(!l.includes("{"))return k;let L=l.match(/\{([^}]+)\}/g)?.map((he)=>he.substring(1,he.length-1))||[],V=l.replace(/\./g,"\\.").replace(/\{[^}]+\}/g,"([^.]+)"),pe=M.match(new RegExp(`^${V}$`));if(pe&&pe.length>1)for(let he=0;he<L.length;he++)k[L[he]]=pe[he+1];return k},writable:!0,configurable:!0},pattern:{value(l,M){return this.patterns.set(l,M),this},writable:!0,configurable:!0},where:{value(l){let M=this.routes[this.routes.length-1];if(M){M.constraints={...M.constraints||{},...l};let k=M.path,L=M.constraints&&!Array.isArray(M.constraints)?M.constraints:void 0;if(M.pattern={exec:(V)=>{let pe={};if(!ft(k,V.pathname,pe,L))return null;return{pathname:{groups:pe}}}},this.routeCache.clear(),this.routeCompiler){let V=[...this.routes];this.routeCompiler.clear();for(let pe of V)this.routeCompiler.addRoute(pe)}}return this},writable:!0,configurable:!0},withoutNativeDispatch:{value(){let l=this.routes[this.routes.length-1];if(l)l.nativeDispatch=!1;return this},writable:!0,configurable:!0},whereNumber:{value(l){return this.where({[l]:"\\d+"})},writable:!0,configurable:!0},whereAlpha:{value(l){return this.where({[l]:"[A-Za-z]+"})},writable:!0,configurable:!0},whereAlphaNumeric:{value(l){return this.where({[l]:"[A-Za-z0-9]+"})},writable:!0,configurable:!0},whereUuid:{value(l){return this.where({[l]:"[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(l,M){return this.where({[l]:M.join("|")})},writable:!0,configurable:!0}})}var to=/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,ro=/bot|crawler|spider|crawling/i,Er=new Map;function Jt(o){let l=o;if(!l._parsedURL)l._parsedURL=new URL(o.url);return l._parsedURL}function Bt(o){let l=o;if(!l._parsedCookies){let M={},k=o.headers.get("cookie");if(k)for(let L of k.split(";")){let V=L.indexOf("=");if(V===-1)continue;let pe=L.slice(0,V).trim();if(!pe)continue;let he=L.slice(V+1).trim();try{M[pe]=decodeURIComponent(he)}catch{M[pe]=he}}l._parsedCookies=M}return l._parsedCookies}class hs{macros=new Map;epoch=0;register(o,l,M=!1){this.macros.set(o,{name:o,handler:l,accessor:M}),this.epoch++}get(o){return this.macros.get(o)}has(o){return this.macros.has(o)}all(){return Array.from(this.macros.values())}remove(o){let l=this.macros.delete(o);if(l)this.epoch++;return l}clear(){this.macros.clear(),this.epoch++}getEpoch(){return this.epoch}}var ar=new hs,ds=Symbol("bunRouterMacroProto"),Xr=Symbol("bunRouterMacroBase"),Sr=new WeakMap,ps=-1;class Ne{static macro(o,l){ar.register(o,l)}static macroAccessor(o,l){ar.register(o,l,!0)}static applyMacros(o){let l=ar.getEpoch();if(l!==ps)Sr=new WeakMap,ps=l;let M=Object.getPrototypeOf(o)??Object.prototype;if(M[ds]){if(Sr.get(M[Xr])===M)return o;M=M[Xr]}let k=Sr.get(M);if(!k){k=Object.create(M);for(let L of ar.all())if(L.accessor)Object.defineProperty(k,L.name,{get:L.handler,set(V){Object.defineProperty(this,L.name,{value:V,writable:!0,configurable:!0,enumerable:!0})},configurable:!0});else k[L.name]=L.handler;Object.defineProperty(k,ds,{value:!0}),Object.defineProperty(k,Xr,{value:M}),Sr.set(M,k)}return Object.setPrototypeOf(o,k),o}static hasMacro(o){return ar.has(o)}}var ur={wantsJson(){let o=this.headers.get("accept")||"";return o.includes("application/json")||o.includes("json")},wantsHtml(){let o=this.headers.get("accept")||"";return o.includes("text/html")||o.includes("html")},wantsXml(){let o=this.headers.get("accept")||"";return o.includes("application/xml")||o.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 to.test(this.headers.get("user-agent")||"")},isBot(){return ro.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 o=this.headers.get("x-forwarded-for");if(o)return o.split(",").map((l)=>l.trim());return[ur.ip.call(this)]},userAgent(){return this.headers.get("user-agent")||""},referer(){return this.headers.get("referer")||this.headers.get("referrer")||null},bearerToken(){let o=this.headers.get("authorization");if(o&&o.startsWith("Bearer "))return o.substring(7);return null},async rawBody(){if(typeof this._rawBody==="string")return this._rawBody;try{let o=await this.clone().text();return this._rawBody=o,o}catch{return""}},basicAuth(){let o=this.headers.get("authorization");if(o&&o.startsWith("Basic "))try{let l=atob(o.substring(6)),[M,k]=l.split(":");return{username:M,password:k}}catch{return null}return null},hasHeader(o){return this.headers.has(o.toLowerCase())},header(o,l){return this.headers.get(o.toLowerCase())||l||null},allHeaders(){let o={};return this.headers.forEach((l,M)=>{o[M]=l}),o},input(o,l){if(this.validated&&o in this.validated)return this.validated[o];if(this.query&&o in this.query)return this.query[o];if(this.params&&o in this.params)return this.params[o];if(this.jsonBody&&typeof this.jsonBody==="object"&&o in this.jsonBody)return this.jsonBody[o];if(this.formBody&&typeof this.formBody==="object"&&o in this.formBody)return this.formBody[o];return l},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(o){let l=this.all(),M={};return o.forEach((k)=>{if(k in l)M[k]=l[k]}),M},except(o){let l=this.all(),M={};return Object.keys(l).forEach((k)=>{if(!o.includes(k))M[k]=l[k]}),M},has(o){let l=this.all();return o in l&&l[o]!==void 0&&l[o]!==null&&l[o]!==""},hasAny(o){return o.some((l)=>this.has(l))},missing(o){return!this.has(o)},filled(o){let l=this.input(o);if(l===null||l===void 0)return!1;if(typeof l==="string")return l.trim().length>0;if(Array.isArray(l))return l.length>0;if(typeof l==="object")return Object.keys(l).length>0;return!0},getQuery(o,l){if(!o)return this.query||{};return this.query?.[o]||l},param(o,l){return this.params?.[o]||l},cookie(o,l){let M=Bt(this)[o];return M!==void 0?M:l||null},cookies(){return{...Bt(this)}},file(o){return this.files?.find((l)=>l.fieldName===o)},hasFile(o){return!!this.files?.find((l)=>l.fieldName===o)},path(){return Jt(this).pathname},fullUrl(){return this.url},root(){let o=Jt(this);return`${o.protocol}//${o.host}`},is(o){let l=this.path(),M=Er.get(o);if(!M){let k=o.replace(/\*/g,".*").replace(/\?/g,".");if(M=new RegExp(`^${k}$`),Er.size>=1000)Er.clear();Er.set(o,M)}return M.test(l)},route(){return this.routeName||null},fingerprint(){let o=Jt(this),l={method:this.method,path:o.pathname,query:o.search,ip:ur.ip.call(this)};return btoa(JSON.stringify(l))},signature(o){let l=`${this.method}${this.url}${ur.ip.call(this)}${o}`,M=0;for(let k=0;k<l.length;k++){let L=l.charCodeAt(k);M=(M<<5)-M+L,M=M&M}return Math.abs(M).toString(36)},merge(o){if(!this.validated)this.validated={};Object.assign(this.validated,o)},replace(o){this.validated={...o}},age(){let o=this.startTime||Date.now();return Date.now()-o},isFromTrustedProxy(o=[]){let l=ur.ip.call(this);return o.includes(l)},contentLength(){let o=this.headers.get("content-length");return o?Number.parseInt(o,10):0},contentType(){return this.headers.get("content-type")},isContentType(o){let l=this.contentType();return l?l.includes(o):!1}};function no(){Object.entries(ur).forEach(([o,l])=>{Ne.macro(o,l)})}no();function kr(o){let l=o;if(!l._parsedQuery){let M={};if(l._parsedURL||o.url.includes("?"))for(let[k,L]of Jt(o).searchParams){let V=M[k];if(V===void 0)M[k]=L;else if(Array.isArray(V))V.push(L);else M[k]=[V,L]}l._parsedQuery=M}return l._parsedQuery}class De{routes=[];currentGroup=null;globalMiddleware=[];namedRoutes=new Map;fallbackHandler=null;patterns=new Map;currentDomain=null;domains={};serverInstance=null;wsConfig=null;errorHandler=null;templateCache=new Map;routeCache=new Map;staticRoutes=new Map;staticResponses=new Map;precompiledPatterns=new Map;domainPatternCache=new Map;routeCompiler=null;_hasDomainRoutes=!1;middlewareGroups=new Map;namedMiddleware=new Map;conditionalMiddleware=[];_middlewarePipeline;_mwEpoch=0;_allowedMethodsCache=new Map;config={verbose:!1,routesPath:"routes",apiRoutesPath:"routes/api.ts",webRoutesPath:"routes/web.ts",apiPrefix:"/api",webPrefix:"",actionsPath:"actions",controllersPath:"controllers",defaultMiddleware:{api:[],web:[]}};constructor(o={}){this.routes=[],this.config={...this.config,...o},this.initializeDefaultMiddleware()}initializeDefaultMiddleware(){this.namedMiddleware.set("auth",()=>async(o,l)=>{if(!o.headers.get("authorization")?.replace("Bearer ",""))return new Response("Unauthorized",{status:401});return await l()}),this.namedMiddleware.set("throttle",(o)=>{let l=o?Wt(o):{maxAttempts:60,windowMs:60000};return Gt({maxAttempts:l.maxAttempts||60,windowMs:l.windowMs,keyGenerator:(M)=>M.headers.get("x-forwarded-for")||"anonymous"})}),this.namedMiddleware.set("cors",()=>async(o,l)=>{let M=await l();if(M)M.headers.set("Access-Control-Allow-Origin","*"),M.headers.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),M.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization");return M})}middlewareGroup(o,l){let M=[];for(let k of l){let[L,V]=k.split(":"),pe=this.namedMiddleware.get(L);if(pe)M.push(pe(V))}return this.middlewareGroups.set(o,M),this}middlewareGroupRoutes(o){let l=this.middlewareGroups.get(o)||[];return new fs(this,l)}when(o){return new gs(this,o)}middleware(o){let[l,M]=o.split(":"),k=this.namedMiddleware.get(l);if(!k)throw Error(`Unknown middleware: ${l}`);let L=k(M);return new ms(this,[L])}getServer(){return this.serverInstance}extend(o){for(let[l,M]of Object.entries(o))if(typeof M==="function")this[l]=M.bind(this);return this}async register(o,l){let M=async()=>{await import(o)};if(l?.prefix||l?.middleware&&l.middleware.length>0)await this.group({prefix:l.prefix,middleware:l.middleware},M);else await M();return this}invalidateCache(){this.routeCache.clear(),this._allowedMethodsCache.clear()}registerRoute(o,l,M,k,L,V){let pe=l,he=[],Te=k||"web";if(this.currentGroup){if(this.currentGroup.prefix)pe=kt(this.currentGroup.prefix,l);if(this.currentGroup.middleware&&this.currentGroup.middleware.length>0)he=[...this.currentGroup.middleware]}if(V&&V.length>0)for(let Ee of V){let Me=this.resolveMiddleware(Ee);if(Me)he.push(Me)}if(Te==="api"&&this.config.apiPrefix)pe=kt(this.config.apiPrefix,pe);else if(Te==="web"&&this.config.webPrefix)pe=kt(this.config.webPrefix,pe);let xe;if(this.currentDomain)xe=this.currentDomain;let ve={method:o.toUpperCase(),path:pe,handler:M,domain:xe,params:{},middleware:he},Pe=Cr(pe),Ce={};if(Pe.forEach((Ee)=>{let Me=Ee.replace("?","");if(this.patterns.has(Me))Ce[Me]=this.patterns.get(Me)}),Object.keys(Ce).length>0)ve.constraints=Ce;if(ve.pattern={exec:(Ee)=>{let Me={},Se=ve.constraints&&!Array.isArray(ve.constraints)?ve.constraints:void 0;if(!ft(pe,Ee.pathname,Me,Se))return null;return{pathname:{groups:Me}}}},xe){if(!this.domains[xe])this.domains[xe]=[];this.domains[xe].push(ve)}else this.routes.push(ve);if(!pe.includes("{")&&!pe.includes("*")){if(!this.staticRoutes.has(o.toUpperCase()))this.staticRoutes.set(o.toUpperCase(),new Map);this.staticRoutes.get(o.toUpperCase()).set(pe,ve)}if(L)ve.name=L,this.namedRoutes.set(L,ve),At(L,ve.path);return this.routeCache.clear(),this}resolveMiddleware(o){if(typeof o==="function")return o;let[l,M]=o.split(":"),k=this.namedMiddleware.get(l);if(k)return k(M);return null}get(o,l,M,k,L){return this.registerRoute("GET",o,l,M,k,L)}post(o,l,M,k,L){return this.registerRoute("POST",o,l,M,k,L)}put(o,l,M,k,L){return this.registerRoute("PUT",o,l,M,k,L)}patch(o,l,M,k,L){return this.registerRoute("PATCH",o,l,M,k,L)}delete(o,l,M,k,L){return this.registerRoute("DELETE",o,l,M,k,L)}options(o,l,M,k,L){return this.registerRoute("OPTIONS",o,l,M,k,L)}match(o,l,M,k,L,V){for(let pe of o)this.registerRoute(pe,l,M,k,L,V);return this}any(o,l,M,k,L){for(let V of["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"])this.registerRoute(V,o,l,M,k,L);return this}fallback(o){return this.fallbackHandler=o,this}route(o,l={}){let M=this.namedRoutes.get(o);if(!M)throw Error(`Route with name "${o}" not found`);let k=M.path;for(let[L,V]of Object.entries(l))k=k.replace(`{${L}}`,encodeURIComponent(V)),k=k.replace(`{${L}?}`,encodeURIComponent(V));return k}onError(o){return this.errorHandler=o,this}redirect(o,l=302){let M=new Headers;return M.set("Location",o),new Response(null,{status:l,headers:M})}permanentRedirect(o){return this.redirect(o,301)}redirectRoute(o,l,M=302){return this.get(o,(k)=>this.redirect(l,M)),this}async serve(o){this.invalidateCache();let l={...o,fetch:this.handleRequest.bind(this),websocket:this.wsConfig};if(this.serverInstance=Bun.serve(l),this.config.verbose){let M=this.serverInstance.port,k=this.serverInstance.hostname;console.log(`
|
|
98
|
-
\uD83D\uDE80 Server running at http://${k}:${M}
|
|
99
|
-
`)}return this.serverInstance}async handleRequest(o){try{let l=new URL(o.url);if(this.config.verbose)console.log(`${o.method} ${l.pathname}`);if(o.method==="OPTIONS"){let pe=l.hostname||o.headers.get("host")?.split(":")[0]||"localhost";if(!this.matchRoute(l.pathname,"OPTIONS",pe))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 M=l.hostname||o.headers.get("host")?.split(":")[0]||"localhost",k=this.matchRoute(l.pathname,o.method,M),L=this.enhanceRequest(o,k?.params||{});if(k){L.route=k.route;let pe=[...this.globalMiddleware];if(k.route.middleware&&k.route.middleware.length>0)pe.push(...k.route.middleware);let he=async(xe,ve)=>await this.resolveHandler(k.route.handler,xe);pe.push(he);let Te=await this.runMiddleware(L,pe);if(Te)return this.applyModifiedCookies(Te,L);return new Response("No response from middleware chain",{status:500})}let V=this.getAllowedMethods(l.pathname,M);if(V.length>0){let pe=async(he,Te)=>new Response(JSON.stringify({error:"Method Not Allowed",path:l.pathname,method:o.method,allowed:V}),{status:405,headers:{"Content-Type":"application/json",Allow:V.join(", ")}});if(this.globalMiddleware.length>0){let he=[...this.globalMiddleware,pe],Te=await this.runMiddleware(L,he);if(Te)return this.applyModifiedCookies(Te,L)}return pe(L,async()=>new Response(null))}if(this.globalMiddleware.length>0){let pe=async(xe,ve)=>{if(this.fallbackHandler)return await this.resolveHandler(this.fallbackHandler,L);return new Response(JSON.stringify({error:"Not Found",path:l.pathname,method:o.method}),{status:404,headers:{"Content-Type":"application/json"}})},he=[...this.globalMiddleware,pe],Te=await this.runMiddleware(L,he);if(Te)return this.applyModifiedCookies(Te,L)}if(this.fallbackHandler){let pe=await this.resolveHandler(this.fallbackHandler,L);return this.applyModifiedCookies(pe,L)}return new Response(JSON.stringify({error:"Not Found",path:l.pathname,method:o.method}),{status:404,headers:{"Content-Type":"application/json"}})}catch(l){if(console.error("Error handling request:",l),this.globalMiddleware.length>0){let M=this.enhanceRequest(o,{}),k=async(V,pe)=>{if(this.errorHandler)return this.errorHandler(l);return new Response(JSON.stringify({error:"Internal Server Error",message:l instanceof Error?l.message:String(l)}),{status:500,headers:{"Content-Type":"application/json"}})},L=[...this.globalMiddleware,k];try{let V=await this.runMiddleware(M,L);if(V)return V}catch{}}if(this.errorHandler)return this.errorHandler(l);return new Response(JSON.stringify({error:"Internal Server Error",message:l instanceof Error?l.message:String(l)}),{status:500,headers:{"Content-Type":"application/json"}})}}getAllowedMethods(o,l,M=!1){let k,L=o;if(!M)k=new URL(o,"http://localhost"),L=k.pathname;let V=`${l||""}:${L}`,pe=this._allowedMethodsCache.get(V);if(pe)return pe;let he=new Set;for(let[ve,Pe]of this.staticRoutes){let Ce=Pe.get(L);if(Ce&&(!l||!Ce.domain||Ce.domain===l))he.add(ve)}let Te=l&&this.domains[l]?this.domains[l]:this.routes;for(let ve of Te){if(he.has(ve.method))continue;if(ve.path===L){he.add(ve.method);continue}if(ve.pattern&&ve.pattern.exec(k??=new URL(L,"http://localhost"))){he.add(ve.method);continue}if(ve.path.endsWith("*")&&L.startsWith(ve.path.slice(0,-1)))he.add(ve.method)}if(he.has("GET"))he.add("HEAD");let xe=Array.from(he);if(this._allowedMethodsCache.size>=1e4)this._allowedMethodsCache.clear();return this._allowedMethodsCache.set(V,xe),xe}matchRoute(o,l,M){let k=new URL(o,"http://localhost"),L=`${M||""}:${l}:${k.pathname}`;if(this.routeCache.has(L))return this.routeCache.get(L);if(this.staticRoutes.has(l)){let Te=this.staticRoutes.get(l).get(k.pathname);if(Te&&(!M||!Te.domain||Te.domain===M)){let xe={route:Te,params:{}};return this.routeCache.set(L,xe),xe}}let pe=(M&&this.domains[M]?this.domains[M]:this.routes).filter((Te)=>Te.method===l);for(let Te of pe)if(Te.path===k.pathname){let xe={route:Te,params:{}};return this.routeCache.set(L,xe),xe}for(let Te of pe)if(Te.pattern){let xe=Te.pattern.exec(k);if(xe){let ve={route:Te,params:xe.pathname.groups};return this.routeCache.set(L,ve),ve}}if(M&&this.domains[M]){let Te=this.domains[M].filter((xe)=>xe.method===l&&xe.path.endsWith("*"));for(let xe of Te){let ve=xe.path.slice(0,-1);if(k.pathname.startsWith(ve)){let Pe={route:xe,params:{wildcard:k.pathname.slice(ve.length)}};return this.routeCache.set(L,Pe),Pe}}}let he=this.routes.filter((Te)=>Te.method===l&&Te.path.endsWith("*")&&(!M||!Te.domain));for(let Te of he){let xe=Te.path.slice(0,-1);if(k.pathname.startsWith(xe)){let ve={route:Te,params:{wildcard:k.pathname.slice(xe.length)}};return this.routeCache.set(L,ve),ve}}if(l==="HEAD")return this.matchRoute(o,"GET",M);return}enhanceRequest(o,l={}){let M=null,k=()=>{if(M===null)M={},(o.headers.get("cookie")||"").split(";").forEach((Te)=>{let xe=Te.trim().split("=");if(xe.length>=2){let ve=xe[0].trim(),Pe=xe.slice(1).join("=").trim();M[ve]=decodeURIComponent(Pe)}});return M},L=kr(o),V={get url(){return o.url},get method(){return o.method},get headers(){return o.headers},get body(){return o.body},get bodyUsed(){return o.bodyUsed},get cache(){return o.cache},get credentials(){return o.credentials},get destination(){return o.destination},get integrity(){return o.integrity},get keepalive(){return o.keepalive},get mode(){return o.mode},get redirect(){return o.redirect},get referrer(){return o.referrer},get referrerPolicy(){return o.referrerPolicy},get signal(){return o.signal},arrayBuffer:()=>o.arrayBuffer(),blob:()=>o.blob(),clone:()=>o.clone(),formData:()=>o.formData(),json:()=>o.json(),text:()=>o.text(),params:l,query:L,jsonBody:null,formBody:null,_cookiesToSet:[],_cookiesToDelete:[]},pe=()=>{let he={};for(let[Te,xe]of Object.entries(L))he[Te]=xe;if(V.jsonBody&&typeof V.jsonBody==="object")for(let[Te,xe]of Object.entries(V.jsonBody))he[Te]=xe;if(V.formBody&&typeof V.formBody==="object")for(let[Te,xe]of Object.entries(V.formBody))he[Te]=xe;for(let[Te,xe]of Object.entries(l))he[Te]=xe;return he};return V.cookies=mr({read:k,write:(he,Te,xe)=>{V._cookiesToSet.push({name:he,value:Te,options:xe})},remove:(he,Te)=>{V._cookiesToDelete.push({name:he,options:Te})}}),V.get=(he,Te)=>{let ve=pe()[he];return ve!==void 0?ve:Te},V.input=(he,Te)=>{let ve=pe()[he];return ve!==void 0?ve:Te},V.all=()=>pe(),V.only=(he)=>{let Te=pe(),xe={};for(let ve of he)if(ve in Te)xe[ve]=Te[ve];return xe},V.except=(he)=>{let xe={...pe()};for(let ve of he)delete xe[ve];return xe},V.has=(he)=>{let Te=pe();if(Array.isArray(he))return he.every((xe)=>(xe in Te)&&Te[xe]!==void 0);return he in Te&&Te[he]!==void 0},V.hasAny=(he)=>{let Te=pe();return he.some((xe)=>(xe in Te)&&Te[xe]!==void 0)},V.filled=(he)=>{let Te=pe(),xe=(ve)=>{let Pe=Te[ve];return Pe!==void 0&&Pe!==null&&Pe!==""&&!(Array.isArray(Pe)&&Pe.length===0)};if(Array.isArray(he))return he.every(xe);return xe(he)},V.missing=(he)=>{let Te=pe();if(Array.isArray(he))return he.every((xe)=>!(xe in Te)||Te[xe]===void 0);return!(he in Te)||Te[he]===void 0},V.string=(he,Te="")=>{let ve=pe()[he];return ve!==void 0&&ve!==null?String(ve):Te},V.integer=(he,Te=0)=>{let ve=pe()[he],Pe=Number.parseInt(String(ve),10);return Number.isNaN(Pe)?Te:Pe},V.float=(he,Te=0)=>{let ve=pe()[he],Pe=Number.parseFloat(String(ve));return Number.isNaN(Pe)?Te:Pe},V.boolean=(he,Te=!1)=>{let ve=pe()[he];if(ve===void 0||ve===null)return Te;if(typeof ve==="boolean")return ve;if(ve==="true"||ve==="1"||ve===1)return!0;if(ve==="false"||ve==="0"||ve===0)return!1;return Te},V.array=(he)=>{let xe=pe()[he];if(Array.isArray(xe))return xe;return xe!==void 0&&xe!==null?[xe]:[]},V.bearerToken=()=>{let he=o.headers.get("authorization")||o.headers.get("Authorization")||"";if(he.startsWith("Bearer "))return he.substring(7);return null},V.header=(he)=>o.headers.get(he)||o.headers.get(he.toLowerCase())||null,V.cookie=(he,Te)=>{let xe=k()[he];return xe!==void 0?xe:Te??null},V.getParam=(he,Te)=>{let xe=l?.[he];return xe!==void 0?xe:Te},V.getParamAsInt=(he)=>{let Te=l?.[he];if(Te===void 0||Te.trim()==="")return null;let xe=Number(Te);return Number.isSafeInteger(xe)?xe:null},V.params=l||{},V}applyModifiedCookies(o,l){let M=new Response(o.body,{status:o.status,statusText:o.statusText,headers:o.headers});if(l._cookiesToSet&&l._cookiesToSet.length>0)for(let{name:k,value:L,options:V}of l._cookiesToSet){let pe=this.serializeCookie(k,L,V);M.headers.append("Set-Cookie",pe)}if(l._cookiesToDelete&&l._cookiesToDelete.length>0)for(let{name:k,options:L}of l._cookiesToDelete){let V={...L,expires:new Date(0),maxAge:0},pe=this.serializeCookie(k,"",V);M.headers.append("Set-Cookie",pe)}return M}serializeCookie(o,l,M={}){let k=`${encodeURIComponent(o)}=${encodeURIComponent(l)}`;if(M.maxAge!==void 0)k+=`; Max-Age=${M.maxAge}`;if(M.expires&&M.expires instanceof Date)k+=`; Expires=${M.expires.toUTCString()}`;if(M.path)k+=`; Path=${M.path}`;else k+="; Path=/";if(M.domain)k+=`; Domain=${M.domain}`;if(M.secure)k+="; Secure";if(M.httpOnly)k+="; HttpOnly";if(M.sameSite){let L=M.sameSite.toLowerCase();k+=`; SameSite=${L.charAt(0).toUpperCase()+L.slice(1)}`}return k}buildMiddlewareChain(o){if(o.length===0)return async(M)=>null;let l=async(M)=>null;for(let M=o.length-1;M>=0;M--){let k=o[M],L=l;l=async(V)=>k(V,async()=>await L(V)||new Response(null,{status:200}))}return l}async runMiddleware(o,l){if(l.length===0)return null;try{return await this.buildMiddlewareChain(l)(o)}catch(M){if(this.errorHandler)return this.errorHandler(M);throw M}}async resolveHandler(o,l){if(typeof o==="function"&&!o.prototype?.handle)return await o(l);if(typeof o==="function"&&o.prototype?.handle)return await new o().handle(l);if(o&&typeof o.handle==="function")return await o.handle(l);throw Error(`Invalid action handler: ${typeof o}`)}use(...o){for(let l of o){let M=this.resolveMiddleware(l);if(M)this.globalMiddleware.push(M)}return this}group(o,l){let M=this.currentGroup;if(this.currentGroup={prefix:o.prefix||"",middleware:[]},o.middleware){for(let L of o.middleware)if(typeof L==="function")this.currentGroup.middleware.push(L)}let k=l();if(k instanceof Promise)return k.then(()=>(this.currentGroup=M,this),(L)=>{throw this.currentGroup=M,L});return this.currentGroup=M,this}addRoute(o){if(this.routes.push(o),o.name)this.namedRoutes.set(o.name,o),At(o.name,o.path);return this}registerMiddlewareDependency(o){if(this._middlewarePipeline)this._middlewarePipeline.registerDependency(o);return this}registerMiddlewareSkipConditions(o,l){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(o,l,M){if(o.length===0)return M();let k=0,L=async()=>{if(k>=o.length)return M();let V=o[k++];return await V(l,L)||new Response("No response from middleware",{status:500})};return L()}}class gs{router;condition;constructor(o,l){this.router=o;this.condition=l}middleware(o){let[l,M]=o.split(":"),k=this.router.namedMiddleware.get(l);if(!k)throw Error(`Unknown middleware: ${l}`);let L=k(M);return this.router.conditionalMiddleware.push({condition:this.condition,middleware:[L]}),this}}class ms{router;middleware;constructor(o,l){this.router=o;this.middleware=l}get(o,l){return this}post(o,l){return this}put(o,l){return this}delete(o,l){return this}}class fs{router;middleware;constructor(o,l){this.router=o;this.middleware=l}get(o,l){return this}post(o,l){return this}put(o,l){return this}delete(o,l){return this}}var Qr=null;function so(){if(Qr===null)Qr=new De;return Qr}function io(o,l={}){if(typeof o.bearerToken==="function")return o;return so().enhanceRequest(o,l)}function oo(o){let l;if(o.startsWith("http://"))l=7;else if(o.startsWith("https://"))l=8;else{let V=o.indexOf("://");l=V===-1?0:V+3}let M=o.indexOf("/",l);if(M===-1)return"/";let k=o.indexOf("?",M);if(k!==-1)return o.slice(M,k);let L=o.indexOf("#",M);return L===-1?o.slice(M):o.slice(M,L)}async function Rs(o,l,M){let k;try{k=await l}catch(L){if(!o.errorHandler)throw L;k=await o.errorHandler(L)}return k?o.applyModifiedCookies(k,M):new Response("No response from middleware chain",{status:500})}function ys(o,l,M){console.error("Error handling request:",M);let k=o.errorHandler?o.errorHandler(M):new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:M instanceof Error?M.message:String(M)}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin"}});return k instanceof Promise?k.then((L)=>$t(L,l,o.config.compression)):$t(k,l,o.config.compression)}function ao(o,l){let{router:M,route:k,isWildcard:L}=o,V=l.params??{};if(L){let he=new URL(l.url).pathname,Te=k.path==="*"?"/":k.path.slice(0,-1);V={...V,wildcard:he.slice(Te.length)}}let pe;try{pe=M._dispatchMatchedRoute(k,l,V)}catch(he){return ys(M,l,he)}return pe instanceof Promise?pe.then((he)=>$t(he,l,M.config.compression),(he)=>ys(M,l,he)):$t(pe,l,M.config.compression)}if(!Ne.hasMacro("getParam"))Ne.macro("getParam",function(o,l){let M=this.params?.[o];return M!==void 0?M:l});if(!Ne.hasMacro("getParamAsInt"))Ne.macro("getParamAsInt",function(o){let l=this.params?.[o];if(l===void 0||l.trim()==="")return null;let M=Number(l);return Number.isSafeInteger(M)?M:null});if(!Ne.hasMacro("get"))Ne.macro("get",function(o,l){let M=Jt(this).searchParams.get(o);return M!==null&&M!==void 0?M:l});Ne.macroAccessor("query",function(){return kr(this)});Ne.macroAccessor("cookies",function(){let o=this,l=()=>({...Bt(o)});for(let[M,k]of Object.entries(Bt(o)))Object.defineProperty(l,M,{value:k,writable:!0,enumerable:!0,configurable:!0});return l.get=(M)=>Bt(o)[M],l.set=(M,k,L={})=>{if(!o._cookiesToSet)o._cookiesToSet=[];o._cookiesToSet.push({name:M,value:k,options:L})},l.delete=(M,k={})=>{if(!o._cookiesToDelete)o._cookiesToDelete=[];o._cookiesToDelete.push({name:M,options:k})},l.getAll=()=>({...Bt(o)}),Object.defineProperty(o,"cookies",{value:l,writable:!0,configurable:!0,enumerable:!0}),l});function ws(o){Object.defineProperties(o.prototype,{serve:{async value(l={}){if(this._initFileRoutes)await this._initFileRoutes();if(this._initApiRoutes)await this._initApiRoutes();this.invalidateCache();let M={idleTimeout:255,...l,fetch:this.handleRequest.bind(this)},k={};if(this.staticResponses&&this.staticResponses.size>0)for(let[L,V]of this.staticResponses)k[L]=V;if(l.static)Object.assign(k,l.static);if(Object.keys(k).length>0)M.static=k;if(l.development!==void 0)M.development=l.development;if(this._nativeRoutesEnabled=l.nativeRoutes===!0,this._nativeRoutesEnabled){let L=this._buildNativeRoutes();if(L)M.routes=L}if(this.wsConfig)M.websocket=this.wsConfig;if(this.serverInstance=Bun.serve(M),this.config.verbose){let L=this.serverInstance.port,V=this.serverInstance.hostname;console.log(`
|
|
100
|
-
\uD83D\uDE80 Server running at http://${V}:${L}
|
|
101
|
-
`)}return this.serverInstance},writable:!0,configurable:!0},reload:{async value(){if(!this.serverInstance)throw Error("Server not started, cannot reload");this.invalidateCache();let l=this.serverInstance.port,M=this.serverInstance.hostname;this.serverInstance.stop();let k={port:l,hostname:M,fetch:this.handleRequest.bind(this),websocket:this.wsConfig||void 0};if(this._nativeRoutesEnabled){let L=this._buildNativeRoutes();if(L)k.routes=L}if(this.serverInstance=Bun.serve(k),this.config.verbose)console.log(`\uD83D\uDD04 Server reloaded at http://${M}:${l}`)},writable:!0,configurable:!0},handleRequest:{async value(l){let M=this,k=await Ir(l,()=>M.handleRequestImpl(l));return $t(k,l,M.config?.compression)},writable:!0,configurable:!0},_dispatchMatchedRoute:{value(l,M,k){let L=this.enhanceRequest(M,k);Rr(L),L.route=l;let V=l,pe=this._mwEpoch||0,he=V.middleware?V.middleware.length:0,Te=this.globalMiddleware.length,xe=V._compiledChain;if(!xe||V._chainEpoch!==pe||V._chainMwLen!==he){let ve=$n(V.handler,this.config);if(he===0&&Te===0)xe=ve;else{let Pe=he>0?[...this.globalMiddleware,...V.middleware]:[...this.globalMiddleware];Pe.push((Ce,Ee)=>ve(Ce)),xe=this.buildMiddlewareChain(Pe)}V._compiledChain=xe,V._chainEpoch=pe,V._chainMwLen=he}try{let ve=xe(L);if(he!==0||Te!==0)return Rs(this,ve,L);if(ve instanceof Promise)return Rs(this,ve,L);return ve?this.applyModifiedCookies(ve,L):new Response("No response from middleware chain",{status:500})}catch(ve){if(!this.errorHandler)throw ve;let Pe=this.errorHandler(ve);return Pe instanceof Promise?Pe.then((Ce)=>this.applyModifiedCookies(Ce,L)):this.applyModifiedCookies(Pe,L)}},writable:!0,configurable:!0},_buildNativeRoutes:{value(){let l=new Set(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),M=(he)=>{if(he==="*")return"/*";let Te=he.split("/"),xe=[];for(let ve=0;ve<Te.length;ve++){let Pe=Te[ve];if(Pe===""){xe.push(Pe);continue}if(Pe==="*")return ve===Te.length-1?[...xe,"*"].join("/"):null;let Ce=Pe.match(/^\{([A-Z_$][\w$]*)\}$/i);if(Ce){xe.push(`:${Ce[1]}`);continue}if(Pe.includes("{")||Pe.includes(":")||Pe.includes("*"))return null;xe.push(Pe)}return xe.join("/")},k=this,L=(he,Te)=>{let xe={router:k,route:he,isWildcard:Te};return(ve)=>_r(ve,ao,xe,ve)},V={},pe=new Map;for(let he of this.routes){if(!l.has(he.method))continue;if(he.nativeDispatch===!1)continue;if(he.constraints&&Object.keys(he.constraints).length>0)continue;if(he.handler instanceof Response)continue;let Te=M(he.path);if(!Te)continue;let xe=Te.replace(/:[^/]+/g,":p"),ve=pe.get(xe);if(ve&&ve!==Te)continue;pe.set(xe,Te);let Pe=V[Te]??={};if(Pe[he.method])continue;Pe[he.method]=L(he,he.path.endsWith("*"))}for(let he of Object.values(V))if(he.GET&&!he.HEAD)he.HEAD=he.GET;return Object.keys(V).length>0?V:null},writable:!0,configurable:!0},handleRequestImpl:{async value(l){try{let M,k="localhost";if(this._hasDomainRoutes){let xe=new URL(l.url);l._parsedURL=xe,M=xe.pathname,k=xe.hostname||l.headers.get("host")?.split(":")[0]||"localhost"}else M=oo(l.url);let L=this.matchRoute(M,l.method,k,!0);if(l.method==="OPTIONS"&&!L){let xe=l.headers.get("origin"),ve={"Access-Control-Allow-Origin":xe||"*","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(xe)ve["Access-Control-Allow-Credentials"]="true",ve.Vary="Origin";return new Response(null,{status:204,headers:ve})}if(L){let xe=this._dispatchMatchedRoute(L.route,l,L.params);return xe instanceof Promise?await xe:xe}let V=this.enhanceRequest(l,{});Rr(V);let pe=this.getAllowedMethods(M,k,!0),he={"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(pe.length>0){let xe=(ve,Pe)=>new Response(JSON.stringify({success:!1,message:"Method Not Allowed",path:M,method:l.method,allowed:pe}),{status:405,headers:{...he,Allow:pe.join(", ")}});if(this.globalMiddleware.length>0){let ve=[...this.globalMiddleware,xe],Pe=await this.runMiddleware(V,ve);if(Pe)return this.applyModifiedCookies(Pe,V)}return xe(V,async()=>null)}if(this.fallbackHandler){let xe=await this.resolveHandler(this.fallbackHandler,V);return this.applyModifiedCookies(xe,V)}let Te=(xe,ve)=>new Response(JSON.stringify({success:!1,message:"Not Found",path:M,method:l.method}),{status:404,headers:he});if(this.globalMiddleware.length>0){let xe=[...this.globalMiddleware,Te],ve=await this.runMiddleware(V,xe);if(ve)return this.applyModifiedCookies(ve,V)}return Te(V,async()=>null)}catch(M){if(console.error("Error handling request:",M),this.errorHandler)return this.errorHandler(M);return new Response(JSON.stringify({success:!1,message:"Internal Server Error",error:M instanceof Error?M.message:String(M)}),{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(l,M={}){let k=l;if("params"in l)Object.defineProperty(k,"params",{value:M,writable:!0,configurable:!0,enumerable:!0});else k.params=M;return Ne.applyMacros(k),k},writable:!0,configurable:!0},applyModifiedCookies:{value(l,M){let k=M._cookiesToSet&&M._cookiesToSet.length>0,L=M._cookiesToDelete&&M._cookiesToDelete.length>0;if(!k&&!L)return l;let V=new Response(l.body,{status:l.status,statusText:l.statusText,headers:l.headers});if(M._cookiesToSet&&M._cookiesToSet.length>0)for(let{name:pe,value:he,options:Te}of M._cookiesToSet){let xe=this.serializeCookie(pe,he,Te);V.headers.append("Set-Cookie",xe)}if(M._cookiesToDelete&&M._cookiesToDelete.length>0)for(let{name:pe,options:he}of M._cookiesToDelete){let Te={...he,expires:new Date(0),maxAge:0},xe=this.serializeCookie(pe,"",Te);V.headers.append("Set-Cookie",xe)}return V},writable:!0,configurable:!0},serializeCookie:{value(l,M,k={}){let L=`${encodeURIComponent(l)}=${encodeURIComponent(M)}`;if(k.maxAge!==void 0)L+=`; Max-Age=${k.maxAge}`;if(k.expires&&k.expires instanceof Date)L+=`; Expires=${k.expires.toUTCString()}`;if(k.path)L+=`; Path=${k.path}`;else L+="; Path=/";if(k.domain)L+=`; Domain=${k.domain}`;if(k.secure)L+="; Secure";if(k.httpOnly)L+="; HttpOnly";if(k.sameSite){let V=k.sameSite.toLowerCase();L+=`; SameSite=${V.charAt(0).toUpperCase()+V.slice(1)}`}return L},writable:!0,configurable:!0}})}import{join as uo}from"path";function bs(o){Object.defineProperties(o.prototype,{renderView:{async value(l,M={},k={}){let L=this.config.views||{viewsPath:"resources/views",extensions:[".html",".stx"],cache:Bun.env.NODE_ENV==="production",engine:"auto"},V=`${l}:${k.layout||""}`;if(L.cache&&this.templateCache.has(V))return this.processTemplate(this.templateCache.get(V),M,L);let pe=await Vr(l,L.viewsPath,L.extensions);if(!pe)throw Error(`View '${l}' not found`);let he=await Bun.file(pe).text(),Te=k.layout||L.defaultLayout;if(Te){let xe=await Vr(uo("layouts",Te),L.viewsPath,L.extensions);if(!xe)throw Error(`Layout '${Te}' not found`);he=(await Bun.file(xe).text()).replace(/\{\{\s*content\s*\}\}/g,he)}if(L.cache)this.templateCache.set(V,he);return this.processTemplate(he,M,L)},writable:!0,configurable:!0},processTemplate:{async value(l,M,k){if((k?.engine||"auto")==="custom"&&k?.customRenderer)return k.customRenderer(l,M,{});let V=Qn(l,M);if(k?.minify?.enabled)try{let pe=k.minify.options||{removeComments:!0,collapseWhitespace:!0,minifyJS:!0,minifyCSS:!0};V=V.replace(/\s+/g," ").replace(/<!--[\s\S]*?-->/g,"")}catch(pe){console.error("Error minifying HTML:",pe)}return V},writable:!0,configurable:!0},view:{value(l,M,k={},L={},V="web",pe){let he,Te={},xe={},ve="web",Pe;if(typeof M==="string"){if(he=M,typeof k==="object"&&!Array.isArray(k))if("layout"in k||"status"in k||"headers"in k)xe=k;else Te=k;if(typeof L==="object")xe={...xe,...L};else if(typeof L==="string")ve=L;if(typeof V==="string")if(V==="web"||V==="api")ve=V;else Pe=V;if(pe)Pe=pe}else{if(Te=M,typeof k==="string")he=k;else throw TypeError("View name must be a string");if(typeof L==="object")xe=L;else if(typeof L==="string")if(L==="web"||L==="api")ve=L;else he=L,ve="web"}let Ce=async(Ee)=>{let Me=await this.renderView(he,Te,{layout:xe.layout}),Se=this.config?.queryPreservation;if(Se?.enabled!==!1&&Se?.preserve?.length)Me=yr(Me,Se);let Oe=new Headers;if(Oe.set("Content-Type","text/html; charset=utf-8"),xe.headers)for(let[Ie,Ft]of Object.entries(xe.headers))Oe.set(Ie,Ft);return new Response(Me,{status:xe.status||200,headers:Oe})};return this.get(l,Ce,ve,Pe),this},writable:!0,configurable:!0}})}function Ts(o){Object.defineProperties(o.prototype,{websocket:{value(l){return this.wsConfig=l,this},writable:!0,configurable:!0},publish:{value(l,M,k=!1){if(!this.serverInstance)throw Error("Server not started, cannot publish to WebSocket topics");return this.serverInstance.publish(l,M,k)},writable:!0,configurable:!0},subscriberCount:{value(l){if(!this.serverInstance)throw Error("Server not started, cannot get subscriber count");return this.serverInstance.subscriberCount(l)},writable:!0,configurable:!0},upgrade:{value(l,M){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(l,M)},writable:!0,configurable:!0},timeout:{value(l,M){if(!this.serverInstance)throw Error("Server not started, cannot set timeout");this.serverInstance.timeout(l,M)},writable:!0,configurable:!0},requestIP:{value(l){if(!this.serverInstance)throw Error("Server not started, cannot get request IP");return this.serverInstance.requestIP(l)},writable:!0,configurable:!0}})}import co from"process";class xs{macros=new Map;register(o,l){this.macros.set(o,{name:o,handler:l})}get(o){return this.macros.get(o)}has(o){return this.macros.has(o)}all(){return Array.from(this.macros.values())}remove(o){return this.macros.delete(o)}clear(){this.macros.clear()}}var Zr=new xs;class cr extends Response{static macro(o,l){Zr.register(o,l),Response[o]=l}static callMacro(o,...l){let M=Zr.get(o);if(!M)throw Error(`Response macro "${o}" not found`);return M.handler(...l)}static hasMacro(o){return Zr.has(o)}}function Hr(o,l){if(typeof o==="number")return{status:o,mergedHeaders:l};if(o&&typeof o==="object"){let M=typeof o.status==="number"?o.status:200,k=l;if(o.headers)if(k={},o.headers instanceof Headers)o.headers.forEach((L,V)=>{k[V]=L});else if(Array.isArray(o.headers))for(let[L,V]of o.headers)k[L]=V;else Object.assign(k,o.headers);return{status:M,mergedHeaders:k}}return{status:200,mergedHeaders:l}}var yt={success:(o,l,M=200)=>{let k={};if(o!==void 0)k.data=o;if(l!==void 0)k.message=l;return new Response(JSON.stringify(k),{status:M,headers:{"Content-Type":"application/json"}})},error:(o,l,M=400)=>{let k={error:o};if(l!==void 0)k.errors=l;return new Response(JSON.stringify(k),{status:M,headers:{"Content-Type":"application/json"}})},validationError:(o,l="Validation failed")=>yt.error(l,o,422),notFound:(o="Resource not found")=>yt.error(o,void 0,404),unauthorized:(o="Unauthorized")=>yt.error(o,void 0,401),forbidden:(o="Forbidden")=>yt.error(o,void 0,403),serverError:(o="Internal server error")=>yt.error(o,void 0,500),created:(o,l="Resource created successfully")=>yt.success(o,l,201),updated:(o,l="Resource updated successfully")=>yt.success(o,l,200),deleted:(o="Resource deleted successfully")=>yt.success(null,o,200),noContent:()=>new Response(null,{status:204}),accepted:(o,l="Request accepted")=>yt.success(o,l,202),paginated:(o,l,M)=>{let k=Math.ceil(l.total/l.per_page),L=(l.current_page-1)*l.per_page+1,V=Math.min(L+l.per_page-1,l.total),pe={data:o,message:M,meta:{current_page:l.current_page,per_page:l.per_page,total:l.total,last_page:k,from:L,to:V,path:l.path,first_page_url:`${l.path}?page=1`,last_page_url:`${l.path}?page=${k}`,next_page_url:l.current_page<k?`${l.path}?page=${l.current_page+1}`:void 0,prev_page_url:l.current_page>1?`${l.path}?page=${l.current_page-1}`:void 0}};return new Response(JSON.stringify(pe),{status:200,headers:{"Content-Type":"application/json"}})},json:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=Hr(l,M);return new Response(JSON.stringify(o),{status:k,headers:{"Content-Type":"application/json",...L}})},html:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=Hr(l,M);return new Response(o,{status:k,headers:{"Content-Type":"text/html",...L}})},text:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=Hr(l,M);return new Response(o,{status:k,headers:{"Content-Type":"text/plain",...L}})},xml:(o,l=200,M={})=>{let{status:k,mergedHeaders:L}=Hr(l,M);return new Response(o,{status:k,headers:{"Content-Type":"application/xml",...L}})},redirect:(o,l=302)=>new Response(null,{status:l,headers:{Location:o}}),permanentRedirect:(o)=>yt.redirect(o,301),download:(o,l,M="application/octet-stream")=>new Response(o,{status:200,headers:{"Content-Type":M,"Content-Disposition":`attachment; filename="${l}"`}}),stream:(o,l="application/octet-stream",M={})=>new Response(o,{status:200,headers:{"Content-Type":l,...M}}),cache:(o,l=3600,M=!0,k)=>{let V={"Content-Type":"application/json","Cache-Control":M?`public, max-age=${l}`:`private, max-age=${l}`};if(k)V.ETag=k;return new Response(JSON.stringify(o),{status:200,headers:V})},cors:(o,l="*",M="GET,POST,PUT,DELETE,OPTIONS",k="Content-Type,Authorization")=>new Response(JSON.stringify(o),{status:200,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":l,"Access-Control-Allow-Methods":M,"Access-Control-Allow-Headers":k}}),sse:(o,l,M)=>{let k="";if(M)k+=`id: ${M}
|
|
102
|
-
`;if(l)k+=`event: ${l}
|
|
103
|
-
`;return k+=`data: ${o}
|
|
104
|
-
|
|
105
|
-
`,new Response(k,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})},health:(o="healthy",l={})=>{let M=o==="healthy"?200:o==="degraded"?200:503,k={status:o,timestamp:new Date().toISOString(),checks:l,uptime:co.uptime?.()||0};return new Response(JSON.stringify(k),{status:M,headers:{"Content-Type":"application/json"}})}};function lo(){Object.entries(yt).forEach(([o,l])=>{cr.macro(o,l)})}lo();var po=/^[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,ho={required:{name:"required",validate:(o)=>{if(o===null||o===void 0)return!1;if(typeof o==="string")return o.trim().length>0;if(Array.isArray(o))return o.length>0;if(typeof o==="object")return Object.keys(o).length>0;return!0},message:"The :field field is required."},string:{name:"string",validate:(o)=>typeof o==="string",message:"The :field field must be a string."},number:{name:"number",validate:(o)=>typeof o==="number"&&!Number.isNaN(o),message:"The :field field must be a number."},integer:{name:"integer",validate:(o)=>Number.isInteger(Number(o)),message:"The :field field must be an integer."},boolean:{name:"boolean",validate:(o)=>typeof o==="boolean"||o==="true"||o==="false"||o==="1"||o==="0",message:"The :field field must be true or false."},email:{name:"email",validate:(o)=>typeof o==="string"&&po.test(o),message:"The :field field must be a valid email address."},url:{name:"url",validate:(o)=>{try{let l=new URL(o);return Boolean(l)}catch{return!1}},message:"The :field field must be a valid URL."},min:{name:"min",validate:(o,l)=>{let M=Number(l[0]);if(typeof o==="string")return o.length>=M;if(typeof o==="number")return o>=M;if(Array.isArray(o))return o.length>=M;return!1},message:(o,l)=>`The ${o} field must be at least ${l[0]} characters.`},max:{name:"max",validate:(o,l)=>{let M=Number(l[0]);if(typeof o==="string")return o.length<=M;if(typeof o==="number")return o<=M;if(Array.isArray(o))return o.length<=M;return!1},message:(o,l)=>`The ${o} field must not exceed ${l[0]} characters.`},between:{name:"between",validate:(o,l)=>{let M=Number(l[0]),k=Number(l[1]);if(typeof o==="string")return o.length>=M&&o.length<=k;if(typeof o==="number")return o>=M&&o<=k;if(Array.isArray(o))return o.length>=M&&o.length<=k;return!1},message:(o,l)=>`The ${o} field must be between ${l[0]} and ${l[1]}.`},in:{name:"in",validate:(o,l)=>l.includes(String(o)),message:(o,l)=>`The ${o} field must be one of: ${l.join(", ")}.`},notIn:{name:"not_in",validate:(o,l)=>!l.includes(String(o)),message:(o,l)=>`The ${o} field must not be one of: ${l.join(", ")}.`},regex:{name:"regex",validate:(o,l)=>{let M=new RegExp(l[0]);return typeof o==="string"&&M.test(o)},message:"The :field field format is invalid."},alpha:{name:"alpha",validate:(o)=>typeof o==="string"&&/^[a-z]+$/i.test(o),message:"The :field field must contain only letters."},alphaNum:{name:"alpha_num",validate:(o)=>typeof o==="string"&&/^[a-z0-9]+$/i.test(o),message:"The :field field must contain only letters and numbers."},alphaDash:{name:"alpha_dash",validate:(o)=>typeof o==="string"&&/^[\w-]+$/.test(o),message:"The :field field must contain only letters, numbers, dashes, and underscores."},date:{name:"date",validate:(o)=>{let l=new Date(o);return!Number.isNaN(l.getTime())},message:"The :field field must be a valid date."},dateAfter:{name:"after",validate:(o,l)=>{let M=new Date(o),k=new Date(l[0]);return!Number.isNaN(M.getTime())&&!Number.isNaN(k.getTime())&&M>k},message:(o,l)=>`The ${o} field must be after ${l[0]}.`},dateBefore:{name:"before",validate:(o,l)=>{let M=new Date(o),k=new Date(l[0]);return!Number.isNaN(M.getTime())&&!Number.isNaN(k.getTime())&&M<k},message:(o,l)=>`The ${o} field must be before ${l[0]}.`},confirmed:{name:"confirmed",validate:(o,l,M,k)=>{let L=l[0]||`${M}_confirmation`;return o===k[L]},message:"The :field confirmation does not match."},same:{name:"same",validate:(o,l,M,k)=>o===k[l[0]],message:(o,l)=>`The ${o} field must match ${l[0]}.`},different:{name:"different",validate:(o,l,M,k)=>o!==k[l[0]],message:(o,l)=>`The ${o} field must be different from ${l[0]}.`},json:{name:"json",validate:(o)=>{try{return JSON.parse(o),!0}catch{return!1}},message:"The :field field must be valid JSON."},uuid:{name:"uuid",validate:(o)=>typeof o==="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(o),message:"The :field field must be a valid UUID."},array:{name:"array",validate:(o)=>Array.isArray(o),message:"The :field field must be an array."},object:{name:"object",validate:(o)=>typeof o==="object"&&o!==null&&!Array.isArray(o),message:"The :field field must be an object."}},Ou={unique:{name:"unique",validate:async(o,l)=>(console.warn('Database validation rule "unique" requires external implementation'),!0),message:"The :field field must be unique."},exists:{name:"exists",validate:async(o,l)=>(console.warn('Database validation rule "exists" requires external implementation'),!0),message:"The selected :field is invalid."}};class Ar{rules={};config;constructor(o={}){this.config={stopOnFirstFailure:!1,bail:!1,...o},this.registerRules(ho)}registerRule(o){this.rules[o.name]=o}registerRules(o){Object.values(o).forEach((l)=>this.registerRule(l))}parseRuleString(o){return o.split("|").map((l)=>{let[M,...k]=l.split(":"),L=k.length>0?k.join(":").split(","):[];return{name:M.trim(),parameters:L}})}async validate(o,l){let M={};for(let[k,L]of Object.entries(l)){let V=[],pe=this.getNestedValue(o,k),he=typeof L==="string"?this.parseRuleString(L):L.map((Te)=>({name:Te.name,parameters:[]}));for(let{name:Te,parameters:xe}of he){let ve=this.rules[Te];if(!ve){console.warn(`Validation rule "${Te}" not found`);continue}try{if(!await ve.validate(pe,xe,k,o)){let Ce=this.formatErrorMessage(ve,k,xe);if(V.push(Ce),this.config.stopOnFirstFailure||this.config.bail)break}}catch(Pe){console.error(`Error validating rule "${Te}" for field "${k}":`,Pe),V.push(`Validation error for ${k}`)}}if(V.length>0)M[k]=V}return M}async validateOrFail(o,l){let M=await this.validate(o,l);if(Object.keys(M).length>0)throw new d("Validation failed",M)}getNestedValue(o,l){return l.split(".").reduce((M,k)=>M&&M[k]!==void 0?M[k]:void 0,o)}formatErrorMessage(o,l,M){let k=this.config.customMessages?.[`${l}.${o.name}`]||this.config.customMessages?.[o.name];if(k)return this.replacePlaceholders(k,l,M);let L=typeof o.message==="function"?o.message(l,M):o.message;return this.replacePlaceholders(L,l,M)}replacePlaceholders(o,l,M){let k=this.config.customAttributes?.[l]||l.replace(/_/g," ");return o.replace(/:field/g,k).replace(/:attribute/g,k).replace(/:value/g,M[0]||"").replace(/:other/g,M[1]||"")}}var $u=new Ar;function qr(o,l){let M=new Ar(l);return async(k,L)=>{try{let V={...k.query,...k.params,...k.jsonBody||{},...k.formBody||{}};return await M.validateOrFail(V,o),k.validated=V,await L()}catch(V){if(V instanceof d)throw V;throw new d("Validation error occurred")}}}class Yr{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(o){return this.rules.push(`min:${o}`),this}max(o){return this.rules.push(`max:${o}`),this}between(o,l){return this.rules.push(`between:${o},${l}`),this}in(...o){return this.rules.push(`in:${o.join(",")}`),this}notIn(...o){return this.rules.push(`not_in:${o.join(",")}`),this}regex(o){return this.rules.push(`regex:${o}`),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(o){return this.rules.push(`after:${o}`),this}before(o){return this.rules.push(`before:${o}`),this}confirmed(o){return this.rules.push(o?`confirmed:${o}`:"confirmed"),this}same(o){return this.rules.push(`same:${o}`),this}different(o){return this.rules.push(`different:${o}`),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(o,l){return this.rules.push(l?`unique:${o},${l}`:`unique:${o}`),this}exists(o,l){return this.rules.push(l?`exists:${o},${l}`:`exists:${o}`),this}custom(o,...l){return this.rules.push(l.length>0?`${o}:${l.join(",")}`:o),this}build(){return this.rules.join("|")}}function Bu(){return new Yr}var Du={rules(o){let l={};for(let[M,k]of Object.entries(o))l[M]=k instanceof Yr?k.build():k;return l},async validateValue(o,l,M="value"){return(await new Ar().validate({[M]:o},{[M]:l}))[M]||[]},async passes(o,l){return(await this.validateValue(o,l)).length===0},async fails(o,l){return!await this.passes(o,l)}};class lt{method;path;handler;validationRules;validatorConfig;constructor(o,l,M){this.method=o;this.path=l;this.handler=M}validate(o,l){return this.validationRules=o,this.validatorConfig=l,this}build(){let o=[];if(this.validationRules)o.push(qr(this.validationRules,this.validatorConfig));return o.push(async(l,M)=>(Ne.applyMacros(l),await M()||new Response("Not Found",{status:404}))),{method:this.method,path:this.path,handler:this.handler,middleware:o.length>0?o:void 0}}}class Ps{routes=[];get(o,l){return new lt("GET",o,l)}post(o,l){return new lt("POST",o,l)}put(o,l){return new lt("PUT",o,l)}patch(o,l){return new lt("PATCH",o,l)}delete(o,l){return new lt("DELETE",o,l)}register(o){let l=o.build();this.routes.push(l)}getRoutes(){return this.routes}}function en(){return async(o,l)=>(Ne.applyMacros(o),o.startTime=Date.now(),await l())}class Cs{rules={};config={};field(o,l){return this.rules[o]=l,this}fields(o){return Object.assign(this.rules,o),this}configure(o){return Object.assign(this.config,o),this}stopOnFirstFailure(){return this.config.stopOnFirstFailure=!0,this}messages(o){return this.config.customMessages=o,this}attributes(o){return this.config.customAttributes=o,this}build(){return qr(this.rules,this.config)}}function ju(){return new Cs}var Lu={validated:(o,l,M,k,L)=>new lt(o,l,M).validate(k,L),apiRoute:(o,l,M,k)=>{let L=new lt(o,l,async(V)=>{if(!V.expectsJson())return cr.callMacro("error","API endpoint requires JSON Accept header",void 0,406);return $e(await M(V))});if(k)L.validate(k);return L},resourceRoute:(o,l,M)=>{let k=[];if(l.index)k.push(new lt("GET",o,l.index));if(l.show)k.push(new lt("GET",`${o}/{id}`,l.show));if(l.store){let L=new lt("POST",o,l.store);if(M?.store)L.validate(M.store);k.push(L)}if(l.update){let L=new lt("PUT",`${o}/{id}`,l.update);if(M?.update)L.validate(M.update);k.push(L)}if(l.destroy)k.push(new lt("DELETE",`${o}/{id}`,l.destroy));return k}};function zu(){return new Ps}var vs={compose:(...o)=>async(l,M)=>{let k=0,L=async()=>{if(k>=o.length)return await M();let V=o[k++];return await V(l,L)};return await L()},when:(o,l)=>async(M,k)=>{if(o(M))return await l(M,k);return await k()},unless:(o,l)=>vs.when((M)=>!o(M),l),group:(o)=>vs.compose(...o)},Gu={api:()=>[en(),async(o,l)=>{try{let M=await l(),k=new Headers(M.headers);return k.set("X-API-Version","1.0"),k.set("X-Response-Time",new Date().toISOString()),new Response(M.body,{status:M.status,statusText:M.statusText,headers:k})}catch(M){return console.error(M),cr.callMacro("error","Internal server error",void 0,500)}}],web:()=>[en(),async(o,l)=>(o.session={},await l())],validation:(o,l)=>[en(),qr(o,l)]};rs(De);ns(De);ls(De);us(De);ss(De);bs(De);Ts(De);qn(De);ts(De);ws(De);cs(De);as(De);An(De);En(De);class tn{groups=new Map;globalMiddleware=[];middlewarePriority=new Map;define(o,l){return this.groups.set(o,[...l]),this}extend(o,l){let M=this.groups.get(o)||[];return this.groups.set(o,[...M,...l]),this}prepend(o,l){let M=this.groups.get(o)||[];return this.groups.set(o,[...l,...M]),this}get(o){return this.groups.get(o)||[]}has(o){return this.groups.has(o)}remove(o){return this.groups.delete(o),this}resolve(o){if(typeof o==="function")return[o];if(this.groups.has(o))return this.get(o);return[o]}resolveAll(o){let l=[];for(let M of o)l.push(...this.resolve(M));return l}pushGlobal(...o){return this.globalMiddleware.push(...o),this}prependGlobal(...o){return this.globalMiddleware.unshift(...o),this}removeGlobal(o){return this.globalMiddleware=this.globalMiddleware.filter((l)=>typeof l==="string"?l!==o:!0),this}getGlobal(){return[...this.globalMiddleware]}setPriority(o,l){return this.middlewarePriority.set(o,l),this}sortByPriority(o){return[...o].sort((l,M)=>{let k=typeof l==="string"?l.split(":")[0]:"",L=typeof M==="string"?M.split(":")[0]:"",V=this.middlewarePriority.get(k)??100,pe=this.middlewarePriority.get(L)??100;return V-pe})}filter(o,l){if(l.only&&l.only.length>0)return o.filter((M)=>{if(typeof M==="string"){let k=M.split(":")[0];return l.only.includes(k)}return!1});if(l.except&&l.except.length>0)return o.filter((M)=>{if(typeof M==="string"){let k=M.split(":")[0];return!l.except.includes(k)}return!0});return o}flush(){this.groups.clear(),this.globalMiddleware=[],this.middlewarePriority.clear()}}var dt=new tn;dt.define("web",["session","csrf","cors"]);dt.define("api",["throttle:60,1","cors"]);dt.setPriority("session",10);dt.setPriority("cors",20);dt.setPriority("csrf",30);dt.setPriority("auth",40);dt.setPriority("throttle",50);dt.setPriority("role",60);dt.setPriority("permission",60);dt.setPriority("can",70);dt.setPriority("abilities",70);dt.setPriority("verified",80);import{mock as rn}from"bun:test";class Pt{request;url;constructor(o,l,M={}){if(this.url=new URL(l,"http://localhost:3000"),M.query)Object.entries(M.query).forEach(([k,L])=>{if(Array.isArray(L))L.forEach((V)=>this.url.searchParams.append(k,V));else this.url.searchParams.set(k,L)});this.request={method:o,url:this.url.toString(),headers:new Headers(M.headers||{}),params:{},query:this.parseQuery(this.url.searchParams),jsonBody:void 0,formBody:M.body&&typeof M.body==="object"?M.body:void 0,files:M.files?this.convertTestFiles(M.files):void 0,session:M.session,user:M.user,context:M.context||{},requestId:`test-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ip:()=>"127.0.0.1",userAgent:()=>"BunRouter-TestClient/1.0",cookies:jt(M.cookies||{}),startTime:Date.now(),traceId:`trace-${Date.now()}`,spanId:`span-${Date.now()}`},this.handleBody(M.body)}parseQuery(o){let l={};for(let[M,k]of o.entries())if(l[M])if(Array.isArray(l[M]))l[M].push(k);else l[M]=[l[M],k];else l[M]=k;return l}convertTestFiles(o){return o.map((l)=>({fieldName:l.fieldName,originalName:l.filename,filename:`test-${Date.now()}-${l.filename}`,path:`/tmp/test-uploads/${l.filename}`,size:l.content instanceof ArrayBuffer?l.content.byteLength:new TextEncoder().encode(l.content.toString()).length,mimetype:l.mimetype||"application/octet-stream",buffer:l.content instanceof ArrayBuffer?l.content:new TextEncoder().encode(l.content.toString()).buffer}))}handleBody(o){if(!o)return;let l=this.request.headers?.get("content-type")||"";if(l.includes("application/json")||typeof o==="object"){if(this.request.jsonBody=o,!this.request.headers?.has("content-type"))this.request.headers?.set("content-type","application/json")}else if(l.includes("application/x-www-form-urlencoded"))this.request.formBody=o}params(o){return this.request.params={...this.request.params,...o},this}headers(o){return Object.entries(o).forEach(([l,M])=>{this.request.headers?.set(l,M)}),this}auth(o,l="Bearer"){return this.request.headers?.set("Authorization",`${l} ${o}`),this}user(o){return this.request.user=o,this}session(o){return this.request.session=o,this}cookies(o){let l=this.request.cookies?.getAll()||{};return this.request.cookies=jt({...l,...o}),this}context(o){return this.request.context={...this.request.context,...o},this}json(o){return this.request.jsonBody=o,this.request.headers?.set("content-type","application/json"),this}form(o){return this.request.formBody=o,this.request.headers?.set("content-type","application/x-www-form-urlencoded"),this}files(o){return this.request.files=this.convertTestFiles(o),this.request.headers?.set("content-type","multipart/form-data"),this}ip(o){return this.request.ip=()=>o,this}userAgent(o){return this.request.userAgent=()=>o,this.request.headers?.set("User-Agent",o),this}csrf(o){return this.request.csrfToken=o,this.request.headers?.set("X-CSRF-Token",o),this}build(){let o={method:this.request.method,headers:this.request.headers};if(this.request.jsonBody)o.body=JSON.stringify(this.request.jsonBody);else if(this.request.formBody){let k=new FormData;Object.entries(this.request.formBody).forEach(([L,V])=>{k.append(L,V)}),o.body=k}let l=new Request(this.url.toString(),o);return Object.assign(l,{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 wc={get:(o,l)=>new Pt("GET",o,l),post:(o,l)=>new Pt("POST",o,l),put:(o,l)=>new Pt("PUT",o,l),patch:(o,l)=>new Pt("PATCH",o,l),delete:(o,l)=>new Pt("DELETE",o,l),options:(o,l)=>new Pt("OPTIONS",o,l),head:(o,l)=>new Pt("HEAD",o,l)};function Fe(o="GET",l="/",M={}){return new Pt(o,l,M).build()}class lr{request;constructor(o){this.request=o||Fe()}as(o){return this.request.user=o,this}withJWT(o,l="Bearer"){let M=new Headers(this.request.headers);return M.set("Authorization",`${l} ${o}`),this.request={...this.request,headers:M},this}withSession(o){return this.request.session=o,this}withApiKey(o,l="X-API-Key"){let M=new Headers(this.request.headers);return M.set(l,o),this.request={...this.request,headers:M},this}withBasicAuth(o,l){let M=btoa(`${o}:${l}`),k=new Headers(this.request.headers);return k.set("Authorization",`Basic ${M}`),this.request={...this.request,headers:k},this}withAuthCookies(o){let l=this.request.cookies?.getAll()||{};return this.request.cookies=jt({...l,...o}),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 nn{options;constructor(o={}){this.options={secret:"test-secret",expiresIn:"1h",algorithm:"HS256",...o}}generateToken(o={}){let l={alg:this.options.algorithm,typ:"JWT",...this.options.headers},M=Math.floor(Date.now()/1000),k=M+this.parseExpiresIn(this.options.expiresIn||"1h"),L={iat:M,exp:k,...this.options.payload,...o},V=btoa(JSON.stringify(l)).replace(/=/g,""),pe=btoa(JSON.stringify(L)).replace(/=/g,""),he=btoa(`${V}.${pe}.${this.options.secret}`).replace(/=/g,"");return`${V}.${pe}.${he}`}generateExpiredToken(o={}){let l={alg:this.options.algorithm,typ:"JWT"},M=Math.floor(Date.now()/1000),k={iat:M-7200,exp:M-3600,...o},L=btoa(JSON.stringify(l)).replace(/=/g,""),V=btoa(JSON.stringify(k)).replace(/=/g,""),pe=btoa(`${L}.${V}.${this.options.secret}`).replace(/=/g,"");return`${L}.${V}.${pe}`}generateInvalidToken(){return"invalid.jwt.token"}decodeToken(o){let[l,M,k]=o.split(".");return{header:JSON.parse(atob(l)),payload:JSON.parse(atob(M)),signature:k}}parseExpiresIn(o){let l=o.match(/^(\d+)([smhd])$/);if(!l)return 3600;let M=Number.parseInt(l[1]);switch(l[2]){case"s":return M;case"m":return M*60;case"h":return M*3600;case"d":return M*86400;default:return 3600}}}class sn{options;constructor(o={}){this.options={sessionId:`test-session-${Date.now()}`,maxAge:3600000,secure:!1,httpOnly:!0,...o}}createSession(o={}){let l={...this.options.data,...o},M=this.generateSessionCookie();return{sessionId:this.options.sessionId,data:l,cookie:M}}generateSessionCookie(o="session"){let l=[];if(this.options.maxAge)l.push(`Max-Age=${Math.floor(this.options.maxAge/1000)}`);if(this.options.secure)l.push("Secure");if(this.options.httpOnly)l.push("HttpOnly");let M=l.length>0?`; ${l.join("; ")}`:"";return`${o}=${this.options.sessionId}${M}`}createExpiredSession(){let o={...this.options,maxAge:-1};return new sn(o).createSession()}}var Pc={user:(o={})=>({id:1,email:"test@example.com",username:"testuser",roles:["user"],permissions:["read"],...o}),adminUser:(o={})=>({id:1,email:"admin@example.com",username:"admin",roles:["admin"],permissions:["read","write","delete"],...o}),guestUser:()=>({id:0,email:"guest@example.com",username:"guest",roles:["guest"],permissions:[]}),authMiddleware:(o)=>rn(async(l,M)=>{if(o)return l.user=o,await M();return new Response("Unauthorized",{status:401})}),roleMiddleware:(o)=>rn(async(l,M)=>{if(!l.user)return new Response("Unauthorized",{status:401});let k=l.user.roles||[];if(!o.some((V)=>k.includes(V)))return new Response("Forbidden",{status:403});return await M()}),permissionMiddleware:(o)=>rn(async(l,M)=>{if(!l.user)return new Response("Unauthorized",{status:401});let k=l.user.permissions||[];if(!o.every((V)=>k.includes(V)))return new Response("Forbidden",{status:403});return await M()})},Cc={authenticatedRequest:(o,l)=>new lr(l).as(o).getRequest(),jwtRequest:(o={},l)=>{let k=new nn().generateToken(o);return new lr(l).withJWT(k).getRequest()},sessionRequest:(o={},l)=>new lr(l).withSession(o).getRequest(),verifyJWTStructure:(o)=>{let l=o.split(".");return l.length===3&&l.every((M)=>M.length>0)},extractJWTPayload:(o)=>{try{let[,l]=o.split(".");return JSON.parse(atob(l))}catch{return null}}};function Mc(o){return new lr(o)}function Ec(o){return new nn(o)}function Sc(o){return new sn(o)}import{mock as Dt}from"bun:test";class Ot{request;files;constructor(o){this.request=o||Fe(),this.files=[]}addFile(o){let l={fieldName:o.fieldName,originalName:o.filename,filename:`test-${Date.now()}-${o.filename}`,path:`/tmp/test-uploads/${o.filename}`,size:o.content instanceof ArrayBuffer?o.content.byteLength:new TextEncoder().encode(o.content.toString()).length,mimetype:o.mimetype||this.detectMimeType(o.filename),buffer:o.content instanceof ArrayBuffer?o.content:new TextEncoder().encode(o.content.toString()).buffer};return this.files.push(l),this.request.files=[...this.request.files||[],l],this}addFiles(o){return o.forEach((l)=>this.addFile(l)),this}addImage(o,l="test.jpg",M=1024){let k=new ArrayBuffer(M);return this.addFile({fieldName:o,filename:l,content:k,mimetype:"image/jpeg"})}addDocument(o,l="test.pdf",M="Test PDF content"){return this.addFile({fieldName:o,filename:l,content:M,mimetype:"application/pdf"})}addTextFile(o,l="test.txt",M="Test content"){return this.addFile({fieldName:o,filename:l,content:M,mimetype:"text/plain"})}addLargeFile(o,l=10){let M=l*1024*1024,k=new ArrayBuffer(M);return this.addFile({fieldName:o,filename:`large-file-${l}mb.bin`,content:k,mimetype:"application/octet-stream"})}addInvalidFile(o,l="malicious.exe"){return this.addFile({fieldName:o,filename:l,content:"Potentially malicious content",mimetype:"application/x-executable"})}withFormData(o){return this.request.formBody={...this.request.formBody,...o},this}getRequest(){return this.request}getFiles(){return this.files}clearFiles(){return this.files=[],this.request.files=[],this}detectMimeType(o){let l=o.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"}[l||""]||"application/octet-stream"}}class on{static testFileSize(o,l){return o.size<=l}static testFileType(o,l){return l.includes(o.mimetype)}static testFileExtension(o,l){let M=o.originalName.split(".").pop()?.toLowerCase();return M?l.includes(M):!1}static testFilename(o){let l=o.originalName;if(l.includes("..")||l.includes("/")||l.includes("\\"))return!1;if(l.includes("\x00"))return!1;let M=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],k=l.split(".")[0].toUpperCase();if(M.includes(k))return!1;return!0}static testImageFile(o){return["image/jpeg","image/png","image/gif","image/webp","image/svg+xml"].includes(o.mimetype)}static testDocumentFile(o){return["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/csv"].includes(o.mimetype)}}var qc={validationMiddleware:(o={})=>Dt(async(M,k)=>{let L=M.files||[],{maxSize:V=5242880,allowedTypes:pe=[],maxFiles:he=10}=o;if(L.length>he)return new Response(`Too many files. Maximum ${he} allowed.`,{status:400});for(let Te of L){if(Te.size>V)return new Response(`File ${Te.originalName} is too large. Maximum size: ${V} bytes.`,{status:400});if(pe.length>0&&!pe.includes(Te.mimetype))return new Response(`File type ${Te.mimetype} not allowed.`,{status:400});if(!on.testFilename(Te))return new Response(`Invalid filename: ${Te.originalName}`,{status:400})}return await k()}),imageUploadMiddleware:(o={})=>Dt(async(M,k)=>{let L=M.files||[],{maxSize:V=2097152}=o;for(let pe of L){if(!on.testImageFile(pe))return new Response(`File ${pe.originalName} is not a valid image.`,{status:400});if(pe.size>V)return new Response(`Image ${pe.originalName} is too large.`,{status:400})}return await k()}),storageService:{store:Dt(async(o,l)=>l||`/uploads/${Date.now()}-${o.filename}`),delete:Dt(async(o)=>{}),exists:Dt(async(o)=>!o.includes("not-found")),getUrl:Dt((o)=>`https://example.com/storage${o}`)},virusScanner:{scan:Dt(async(o)=>{if(o.originalName.endsWith(".exe")||o.mimetype==="application/x-executable")return{clean:!1,threat:"Potentially malicious executable"};return{clean:!0}})}},Oc={singleFileUpload:()=>new Ot().addImage("avatar","profile.jpg").withFormData({description:"Profile picture"}),multipleFileUpload:()=>new Ot().addImage("images","photo1.jpg").addImage("images","photo2.png").addDocument("documents","report.pdf").withFormData({album:"vacation"}),fileSizeExceeded:()=>new Ot().addLargeFile("file",50),invalidFileType:()=>new Ot().addInvalidFile("file","virus.exe"),emptyFileUpload:()=>new Ot().addFile({fieldName:"file",filename:"empty.txt",content:"",mimetype:"text/plain"}),maliciousFilename:()=>new Ot().addFile({fieldName:"file",filename:"../../../etc/passwd",content:"malicious content",mimetype:"text/plain"})},$c={hasFiles:(o,l)=>{let M=o.files||[];if(l!==void 0&&M.length!==l)throw Error(`Expected ${l} files, but got ${M.length}`);if(M.length===0)throw Error("Expected request to have files")},hasFileWithField:(o,l)=>{if(!(o.files||[]).some((L)=>L.fieldName===l))throw Error(`Expected file with field name '${l}'`)},fileMatches:(o,l)=>{Object.entries(l).forEach(([M,k])=>{if(o[M]!==k)throw Error(`Expected file.${M} to be '${k}', got '${o[M]}'`)})},fileSizeWithinLimit:(o,l)=>{if(o.size>l)throw Error(`File size ${o.size} exceeds limit of ${l}`)},fileTypeAllowed:(o,l)=>{if(!l.includes(o.mimetype))throw Error(`File type '${o.mimetype}' is not allowed. Allowed types: ${l.join(", ")}`)}};function Bc(o){return new Ot(o)}var Dc={image:(o="image",l="test.jpg")=>({fieldName:o,filename:l,content:new ArrayBuffer(1024),mimetype:"image/jpeg"}),document:(o="document",l="test.pdf")=>({fieldName:o,filename:l,content:"PDF content",mimetype:"application/pdf"}),text:(o="file",l="test.txt",M="Test content")=>({fieldName:o,filename:l,content:M,mimetype:"text/plain"}),large:(o="file",l=10)=>({fieldName:o,filename:`large-${l}mb.bin`,content:new ArrayBuffer(l*1024*1024),mimetype:"application/octet-stream"}),malicious:(o="file")=>({fieldName:o,filename:"../../../malicious.exe",content:"malicious content",mimetype:"application/x-executable"})};import{mock as ut,spyOn as go}from"bun:test";class Ms{middleware;context;constructor(o){this.middleware=o,this.context=this.createContext()}createContext(){let o=Fe(),l=ut(()=>Promise.resolve(new Response("Next called",{status:200})));return{request:o,next:l}}withRequest(o){return this.context.request=o,this}withNext(o){return this.context.next=ut(o),this}withError(o){return this.context.error=o,this}async execute(){try{return await this.middleware(this.context.request,this.context.next)}catch(o){throw this.context.error=o,o}}expectNextCalled(o=1){if(this.context.next.mock.calls.length!==o)throw Error(`Expected next to be called ${o} 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(o){if(!this.context.error)throw Error("Expected middleware to throw an error, but no error was thrown");if(o&&this.context.error.message!==o)throw Error(`Expected error message "${o}", but got "${this.context.error.message}"`);return this}getContext(){return this.context}reset(){return this.context=this.createContext(),this}}function Ic(o){return new Ms(o)}var _c={passthrough:()=>ut(async(o,l)=>await l()),response:(o=200,l)=>ut(async()=>new Response(l?JSON.stringify(l):null,{status:o})),error:(o="Middleware error")=>ut(async()=>{throw Error(o)}),modifyRequest:(o)=>ut(async(l,M)=>(o(l),await M())),addContext:(o,l)=>ut(async(M,k)=>(M.context=M.context||{},M.context[o]=l,await k())),auth:(o)=>ut(async(l,M)=>{if(o)return l.user=o,await M();else return new Response("Unauthorized",{status:401})}),rateLimit:(o=!1)=>ut(async(l,M)=>{if(o)return new Response("Too Many Requests",{status:429});return await M()}),cors:(o="*")=>ut(async(l,M)=>{let k=await M();if(k)k.headers.set("Access-Control-Allow-Origin",o);return k})};class Es{middlewares;request;finalHandler;constructor(o){this.middlewares=o,this.request=Fe(),this.finalHandler=ut(async()=>new Response("Final handler",{status:200}))}withRequest(o){return this.request=o,this}withFinalHandler(o){return this.finalHandler=ut(o),this}async execute(){let o=0,l=async()=>{if(o<this.middlewares.length){let M=this.middlewares[o++];return await M(this.request,l)}else return await this.finalHandler()};return await l()}getExecutionOrder(){return this.middlewares.map((o,l)=>l)}}function jc(o){return new Es(o)}function Lc(o){return go(o,"call")}function zc(){let o=ut(async(l,M)=>await M());return{middleware:o,spy:o}}async function Gc(o,l=1000){let M=[],k=Fe(),L=ut(async()=>new Response("OK"));for(let xe=0;xe<l;xe++){let ve=performance.now();await o(k,L);let Pe=performance.now();M.push(Pe-ve)}let V=M.reduce((xe,ve)=>xe+ve,0),pe=V/l,he=Math.min(...M),Te=Math.max(...M);return{averageTime:pe,minTime:he,maxTime:Te,totalTime:V}}import{mock as Ht}from"bun:test";class mo{id;attributes;constructor(o={}){this.id=o.id,this.attributes=o}static modelName="GenericMockModel";static async find(o){return null}static async findOrFail(o){throw Error("Not implemented")}static async where(o){return[]}static async create(o){throw Error("Not implemented")}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}}class fo{id;email;name;constructor(o={id:1}){this.id=o.id,this.email=o.email||"test@example.com",this.name=o.name||"Test User"}static async find(o){return null}static async findOrFail(o){throw Error("Not implemented")}toJSON(){return{id:this.id,email:this.email,name:this.name}}}class Ro{id;title;content;userId;constructor(o={id:1}){this.id=o.id,this.title=o.title||"Test Post",this.content=o.content||"Test content",this.userId=o.userId||1}static async find(o){return null}static async findOrFail(o){throw Error("Not implemented")}async belongsTo(o){return!1}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}class Ss{request;options;constructor(o={}){this.options=o,this.request=Fe()}withRequest(o){return this.request=o,this}withParams(o){return this.request.params={...this.request.params,...o},this}withModel(o){return this.options.modelClass=o,this}withRouteKey(o){return this.options.routeKey=o,this}withConstraints(o){return this.options.constraints=o,this}withResolver(o){return this.options.customResolver=o,this}async testResolution(o){if(this.options.customResolver)return await this.options.customResolver(o);if(this.options.modelClass)return new this.options.modelClass({id:o});return{id:o}}async testNotFound(o){try{throw await this.testResolution(o),Error("Expected model not found error")}catch(l){if(l instanceof Error&&l.message!=="Model not found")throw l}}getRequest(){return this.request}}var Kc={createModel:(o,l={})=>class M{id;attributes;constructor(k={}){this.id=k.id,this.attributes={...l,...k}}static modelName=o;static async find(k){if(k==="not-found")return null;return new M({id:k,...l})}static async findOrFail(k){let L=await this.find(k);if(!L)throw Error("Model not found");return L}static async where(k){return[new M({id:1,...l,...k})]}static async create(k){return new M({id:Date.now(),...k})}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}},User:class o{id;email;name;constructor(l={id:1}){this.id=l.id,this.email=l.email||"test@example.com",this.name=l.name||"Test User"}static async find(l){if(l==="not-found")return null;return new o({id:Number.parseInt(l)})}static async findOrFail(l){let M=await this.find(l);if(!M)throw Error("User not found");return M}toJSON(){return{id:this.id,email:this.email,name:this.name}}},Post:class o{id;title;content;userId;constructor(l={id:1}){this.id=l.id,this.title=l.title||"Test Post",this.content=l.content||"Test content",this.userId=l.userId||1}static async find(l){if(l==="not-found")return null;return new o({id:Number.parseInt(l)})}static async findOrFail(l){let M=await this.find(l);if(!M)throw Error("Post not found");return M}async belongsTo(l){return this.userId===l}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}},Xc={belongsTo:(o="userId")=>Ht(async(M,k)=>{if(!k.user)return!1;return M[o]===k.user.id}),belongsToUser:()=>Ht(async(l,M)=>{if(!M.user)return!1;return l.userId===M.user.id}),published:()=>Ht(async(l)=>l.published===!0||l.status==="published"),visible:()=>Ht(async(l)=>l.visible!==!1&&l.hidden!==!0),custom:(o)=>Ht(o),combine:(...o)=>Ht(async(M,k)=>{for(let L of o)if(!await L(M,k))return!1;return!0})};class ks{resolvers=new Map;register(o,l){return this.resolvers.set(o,Ht(l)),this}registerModel(o,l){let M=Ht(async(k)=>{if(l.find){let L=await l.find(k);if(!L)throw Error(`${l.name||"Model"} not found`);return L}return new l({id:k})});return this.resolvers.set(o,M),this}async resolve(o,l){let M=this.resolvers.get(o);if(!M)throw Error(`No resolver registered for key: ${o}`);return await M(l)}async testAll(o="1"){let l={};for(let[M,k]of this.resolvers)try{l[M]=await k(o)}catch(L){l[M]={error:L instanceof Error?L.message:"Unknown error"}}return l}getKeys(){return Array.from(this.resolvers.keys())}clear(){return this.resolvers.clear(),this}}var Qc={testRoute:async(o,l,M)=>{let k=Fe("GET",o);k.params=l;for(let[L,V]of Object.entries(M))k.context=k.context||{},k.context[L]=V;return k},createHandler:(o)=>Ht(async(M)=>{let k=M.context||{};for(let L of o)if(!k[L])return new Response(`Model ${L} not found`,{status:404});return new Response(JSON.stringify({params:M.params,models:Object.fromEntries(o.map((L)=>[L,k[L]]))}),{headers:{"Content-Type":"application/json"}})}),testBindingMiddleware:(o)=>Ht(async(M,k)=>{M.context=M.context||{};for(let[L,V]of Object.entries(o)){let pe=M.params[L];if(pe)try{if(typeof V==="function")M.context[L]=await V(pe);else M.context[L]=V}catch(he){return console.error(`Error resolving model ${L}:`,he),new Response(`${L} not found`,{status:404})}}return await k()})};function Zc(o){return new Ss(o)}function Yc(){return new ks}var yo=async(o,l)=>o.userId===l.id,el={testUserScoped:async(o,l,M=yo)=>await M(o,l),testRoleAccess:async(o,l,M)=>{if(!l.roles)return!1;return M.some((k)=>l.roles.includes(k))},testPermissionAccess:async(o,l,M)=>{if(!l.permissions)return!1;return M.every((k)=>l.permissions.includes(k))}};import{mock as wo}from"bun:test";import Nt from"process";class As{metrics=[];startTime=0;endTime=0;start(){return this.startTime=performance.now(),this}end(){return this.endTime=performance.now(),this}recordMetric(o){return this.metrics.push(o),this}getElapsedTime(){return this.endTime-this.startTime}getMetrics(){return[...this.metrics]}getAverageResponseTime(){if(this.metrics.length===0)return 0;return this.metrics.reduce((l,M)=>l+M.responseTime,0)/this.metrics.length}getMemoryStats(){if(this.metrics.length===0)return{averageHeapUsed:0,maxHeapUsed:0,averageRSS:0,maxRSS:0};let o=this.metrics.map((M)=>M.memoryUsage.heapUsed),l=this.metrics.map((M)=>M.memoryUsage.rss);return{averageHeapUsed:o.reduce((M,k)=>M+k,0)/o.length,maxHeapUsed:Math.max(...o),averageRSS:l.reduce((M,k)=>M+k,0)/l.length,maxRSS:Math.max(...l)}}clear(){return this.metrics=[],this.startTime=0,this.endTime=0,this}}class Kt{client;config;constructor(o,l){this.client=o,this.config=l}async run(o,l="GET",M={}){let k={totalRequests:0,successfulRequests:0,failedRequests:0,averageResponseTime:0,requestsPerSecond:0,errors:[]},L=[],V=new Map,pe=Date.now(),he=this.config.maxRequests||Math.floor(this.config.duration/1000*(this.config.requestsPerSecond||this.config.concurrency)),Te=[];for(let Pe=0;Pe<he;Pe++){let Ce=this.makeRequest(o,l,M).then((Ee)=>{L.push(Ee),k.successfulRequests++}).catch((Ee)=>{let Me=Ee instanceof Error?Ee.message:"Unknown error";V.set(Me,(V.get(Me)||0)+1),k.failedRequests++});if(Te.push(Ce),this.config.requestsPerSecond){let Ee=1000/this.config.requestsPerSecond;await new Promise((Me)=>setTimeout(Me,Ee))}if(Te.length>=this.config.concurrency)await Promise.race(Te),Te.filter((Me)=>Me.then(()=>!0).catch(()=>!0)).forEach((Me)=>{let Se=Te.indexOf(Me);if(Se>-1)Te.splice(Se,1)})}await Promise.allSettled(Te);let ve=(Date.now()-pe)/1000;return k.totalRequests=he,k.averageResponseTime=L.length>0?L.reduce((Pe,Ce)=>Pe+Ce,0)/L.length:0,k.requestsPerSecond=he/ve,k.errors=Array.from(V.entries()).map(([Pe,Ce])=>({error:Pe,count:Ce})),k}async makeRequest(o,l,M){let k=performance.now();try{return await this.client.request(l,o,M),performance.now()-k}catch(L){let V=performance.now();throw L}}}var il={routeHandler:async(o,l=1000)=>{let M=[],k=Fe();for(let xe=0;xe<l;xe++){let ve=performance.now();await o(k);let Pe=performance.now();M.push(Pe-ve)}let L=M.reduce((xe,ve)=>xe+ve,0),V=L/l,pe=Math.min(...M),he=Math.max(...M),Te=l/L*1000;return{averageTime:V,minTime:pe,maxTime:he,totalTime:L,throughput:Te}},middleware:async(o,l=1000)=>{let M=[],k=Fe(),L=wo(async()=>new Response("OK"));for(let xe=0;xe<l;xe++){let ve=performance.now();await o(k,L);let Pe=performance.now();M.push(Pe-ve)}let V=M.reduce((xe,ve)=>xe+ve,0),pe=V/l,he=Math.min(...M),Te=Math.max(...M);return{averageTime:pe,minTime:he,maxTime:Te,totalTime:V}},jsonSerialization:async(o,l=1e4)=>{let M=[];for(let Te=0;Te<l;Te++){let xe=performance.now(),ve=JSON.stringify(o),Pe=performance.now();M.push(Pe-xe)}let k=M.reduce((Te,xe)=>Te+xe,0),L=k/l,V=Math.min(...M),pe=Math.max(...M),he=JSON.stringify(o).length;return{averageTime:L,minTime:V,maxTime:pe,totalTime:k,dataSize:he}},routeMatching:async(o,l,M=1000)=>{let k=[],L=0;for(let ve=0;ve<M;ve++){let Pe=l[ve%l.length],Ce=performance.now();if(o.find((Se)=>{let Oe=Se.path.replace(/:\w+/g,"[^/]+");return new RegExp(`^${Oe}$`).test(Pe)}))L++;let Me=performance.now();k.push(Me-Ce)}let V=k.reduce((ve,Pe)=>ve+Pe,0),pe=V/M,he=Math.min(...k),Te=Math.max(...k),xe=L/M;return{averageTime:pe,minTime:he,maxTime:Te,totalTime:V,matchRate:xe}}},ol={measureMemoryUsage:async(o,l=100)=>{let M=[],k=[];if(globalThis.gc)globalThis.gc();let L=Nt.memoryUsage().heapUsed;for(let xe=0;xe<l;xe++){let ve=await o();M.push(ve);let Pe=Nt.memoryUsage();if(k.push(Pe.heapUsed),xe%10===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let V=Nt.memoryUsage().heapUsed,pe=k.reduce((xe,ve)=>xe+ve,0)/k.length,he=Math.max(...k),Te=V-L>1048576;return{averageHeapUsed:pe,maxHeapUsed:he,memoryLeakDetected:Te,results:M}},testRouteHandlerMemoryLeaks:async(o,l=1000)=>{if(globalThis.gc)globalThis.gc();let M=Nt.memoryUsage().heapUsed;for(let pe=0;pe<l;pe++){let he=Fe();if(await o(he),pe%100===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let k=Nt.memoryUsage().heapUsed,L=k-M;return{memoryLeakDetected:L>5242880,initialMemory:M,finalMemory:k,memoryGrowth:L}}},al={rampUpTest:async(o,l,M)=>{let k=[],L=10,V=M.testDuration/10,pe=(M.endConcurrency-M.startConcurrency)/10;for(let he=0;he<10;he++){let Te=Math.round(M.startConcurrency+pe*he),ve=await new Kt(o,{duration:V,concurrency:Te,requestsPerSecond:Te*2}).run(l);k.push({concurrency:Te,requestsPerSecond:ve.requestsPerSecond,averageResponseTime:ve.averageResponseTime,errorRate:ve.failedRequests/ve.totalRequests})}return k},spikeTest:async(o,l,M)=>{let L=await new Kt(o,{duration:30000,concurrency:M.normalLoad}).run(l),pe=await new Kt(o,{duration:M.spikeDuration,concurrency:M.spikeLoad}).run(l),Te=await new Kt(o,{duration:30000,concurrency:M.normalLoad}).run(l);return{normalPhase:L,spikePhase:pe,recoveryPhase:Te}}},ul={responseTimeWithin:(o,l)=>{if(o>l)throw Error(`Response time ${o}ms exceeds maximum ${l}ms`)},throughputAtLeast:(o,l)=>{if(o<l)throw Error(`Throughput ${o} RPS is below minimum ${l} RPS`)},errorRateBelow:(o,l)=>{if(o>l)throw Error(`Error rate ${(o*100).toFixed(2)}% exceeds maximum ${(l*100).toFixed(2)}%`)},memoryUsageWithin:(o,l)=>{if(o>l)throw Error(`Memory usage ${(o/1024/1024).toFixed(2)}MB exceeds maximum ${(l/1024/1024).toFixed(2)}MB`)},noMemoryLeaks:(o,l=5242880)=>{if(o>l)throw Error(`Potential memory leak detected: ${(o/1024/1024).toFixed(2)}MB growth`)}};function cl(){return new As}function ll(o,l){return new Kt(o,l)}var Hs={getCurrentMemoryUsage:()=>{let o=Nt.memoryUsage();return{heapUsed:o.heapUsed,heapTotal:o.heapTotal,external:o.external,rss:o.rss}},getCPUUsage:()=>{let o=Nt.cpuUsage();return{user:o.user,system:o.system}},createMetricSnapshot:(o)=>({responseTime:o,memoryUsage:Hs.getCurrentMemoryUsage(),cpuUsage:Hs.getCPUUsage()}),formatResults:(o)=>JSON.stringify(o,null,2)};class an{status;statusText;headers;body;text;json;cookies;redirected;url;ok;type;originalResponse;constructor(o,l){this.originalResponse=o,this.status=o.status,this.statusText=o.statusText,this.headers=this.parseHeaders(o.headers),this.cookies=this.parseCookies(o.headers.get("set-cookie")),this.redirected=o.redirected,this.url=o.url,this.ok=o.ok,this.type=o.type,this.body=l,this.text=typeof l==="string"?l:JSON.stringify(l);try{this.json=typeof l==="string"?JSON.parse(l):l}catch{this.json=null}}parseHeaders(o){let l={};return o.forEach((M,k)=>{l[k.toLowerCase()]=M}),l}parseCookies(o){if(!o)return{};let l={};return o.split(",").forEach((M)=>{let[k]=M.trim().split(";"),[L,V]=k.split("=");if(L&&V)l[L.trim()]=V.trim()}),l}expectStatus(o){if(this.status!==o)throw Error(`Expected status ${o}, got ${this.status}`);return this}expectSuccess(){if(!this.ok)throw Error(`Expected successful response, got ${this.status}`);return this}expectHeader(o,l){let M=this.headers[o.toLowerCase()];if(M===void 0)throw Error(`Expected header '${o}' to be present`);if(l!==void 0&&M!==l)throw Error(`Expected header '${o}' to be '${l}', got '${M}'`);return this}expectBody(o){if(typeof o==="string"){if(this.text!==o)throw Error(`Expected body '${o}', got '${this.text}'`)}else if(JSON.stringify(this.json)!==JSON.stringify(o))throw Error(`Expected body ${JSON.stringify(o)}, got ${JSON.stringify(this.json)}`);return this}expectJson(o){if(JSON.stringify(this.json)!==JSON.stringify(o))throw Error(`Expected JSON ${JSON.stringify(o)}, got ${JSON.stringify(this.json)}`);return this}expectJsonContains(o){if(typeof this.json!=="object"||this.json===null)throw Error("Response is not a JSON object");return Object.entries(o).forEach(([l,M])=>{let k=this.json[l];if(typeof M==="object"&&M!==null&&typeof k==="object"&&k!==null){let L=JSON.stringify(M),V=JSON.stringify(k);if(L!==V)throw Error(`Expected JSON property '${l}' to be ${L}, got ${V}`)}else if(k!==M)throw Error(`Expected JSON property '${l}' to be '${M}', got '${k}'`)}),this}expectCookie(o,l){let M=this.cookies[o];if(M===void 0)throw Error(`Expected cookie '${o}' to be present`);if(l!==void 0&&M!==l)throw Error(`Expected cookie '${o}' to be '${l}', got '${M}'`);return this}expectRedirect(o){if(this.status<300||this.status>=400)throw Error(`Expected redirect status (3xx), got ${this.status}`);if(o){let l=this.headers.location;if(l!==o)throw Error(`Expected redirect to '${o}', got '${l}'`)}return this}expectValidationError(o,l){if(this.status!==422)throw Error(`Expected validation error status (422), got ${this.status}`);if(o){let M=this.json?.errors||this.json?.message;if(!M||!M[o])throw Error(`Expected validation error for field '${o}'`);if(l){if(!(Array.isArray(M[o])?M[o]:[M[o]]).includes(l))throw Error(`Expected validation error message '${l}' for field '${o}'`)}}return this}expectContentType(o){let l=this.headers["content-type"];if(!l||!l.includes(o))throw Error(`Expected content type '${o}', got '${l}'`);return this}expectBodyContains(o){if(!this.text.includes(o))throw Error(`Expected body to contain '${o}'`);return this}expectBodyMatches(o){if(!o.test(this.text))throw Error(`Expected body to match pattern ${o}`);return this}expectJsonStructure(o){return this.validateStructure(this.json,o,"root"),this}validateStructure(o,l,M){if(l&&typeof l==="object"&&l.$$typeof)return;if(Array.isArray(l)){if(!Array.isArray(o))throw TypeError(`Expected ${M} to be an array`);if(l.length>0&&o.length>0)this.validateStructure(o[0],l[0],`${M}[0]`)}else if(typeof l==="object"&&l!==null){if(typeof o!=="object"||o===null)throw Error(`Expected ${M} to be an object`);Object.keys(l).forEach((k)=>{if(!(k in o))throw Error(`Expected ${M} to have property '${k}'`);this.validateStructure(o[k],l[k],`${M}.${k}`)})}}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 qs(o){let l=await o.text();return new an(o,l)}function pl(o=200,l,M){let k=new Headers(M);if(l&&typeof l==="object"&&!k.has("content-type"))k.set("content-type","application/json");let L=new Response(l?typeof l==="string"?l:JSON.stringify(l):null,{status:o,headers:k});return new an(L,l)}class $r{router;config;defaultHeaders;constructor(o,l={}){this.router=o,this.config={baseUrl:"http://localhost:3000",timeout:5000,followRedirects:!0,validateStatus:(M)=>M>=200&&M<300,...l},this.defaultHeaders=l.defaultHeaders||{}}async get(o,l={}){return this.request("GET",o,l)}async post(o,l={}){return this.request("POST",o,l)}async put(o,l={}){return this.request("PUT",o,l)}async patch(o,l={}){return this.request("PATCH",o,l)}async delete(o,l={}){return this.request("DELETE",o,l)}async options(o,l={}){return this.request("OPTIONS",o,l)}async head(o,l={}){return this.request("HEAD",o,l)}async request(o,l,M={}){let k={...this.defaultHeaders,...M.headers},L={...M,headers:k},V=new Pt(o,l,L).build();try{let pe=await this.handleRequest(V);return await qs(pe)}catch(pe){throw Error(`Test request failed: ${pe instanceof Error?pe.message:"Unknown error"}`)}}async handleRequest(o){let l=new URL(o.url),M=this.findMatchingRoute(o.method,l.pathname);if(!M)return new Response("Not Found",{status:404});let{route:k,params:L}=M;o.params={...o.params,...L};try{return await this.executeMiddlewareChain(o,k)||new Response("No response",{status:500})}catch(V){return new Response(JSON.stringify({error:V instanceof Error?V.message:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}findMatchingRoute(o,l){for(let M of this.router.routes){if(M.method.toLowerCase()!==o.toLowerCase())continue;let k=this.matchPath(M.path,l);if(k!==null)return{route:M,params:k}}return null}matchPath(o,l){let M=o.split("/"),k=l.split("/");if(M.length!==k.length)return null;let L={};for(let V=0;V<M.length;V++){let pe=M[V],he=k[V];if(pe.startsWith(":")){let Te=pe.slice(1);L[Te]=he}else if(pe!==he)return null}return L}async executeMiddlewareChain(o,l){let M=[...this.router.globalMiddleware,...l.middleware],k=0,L=async()=>{if(k<M.length){let pe=M[k++];return await pe(o,L)}else return await this.executeHandler(l.handler,o)};return await L()||new Response("No response",{status:500})}async executeHandler(o,l){if(typeof o==="function")return await o(l);else if(typeof o==="string")throw TypeError(`String handlers not supported in test environment: ${o}`);else if(typeof o==="object"&&o.handle)return await new o().handle(l);throw Error("Invalid handler type")}setDefaultHeaders(o){return this.defaultHeaders={...this.defaultHeaders,...o},this}auth(o,l="Bearer"){return this.defaultHeaders.Authorization=`${l} ${o}`,this}userAgent(o){return this.defaultHeaders["User-Agent"]=o,this}withConfig(o){return new $r(this.router,{...this.config,...o})}withHeaders(o){return new $r(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...o}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function Or(o,l){return new $r(o,l)}var fl={for:(o,l)=>Or(o,l),withConfig:(o)=>(l)=>Or(l,o),withAuth:(o,l="Bearer")=>(M)=>Or(M).auth(o,l),withHeaders:(o)=>(l)=>Or(l).withHeaders(o)};import{mock as Ut}from"bun:test";class Mt{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(o=1000,l="Normal closure"){return this.isConnected=!1,this.readyState=3,this.emit("close",{type:"close",code:o,reason:l}),this}send(o){if(!this.isConnected)throw Error("WebSocket is not connected");let l={type:typeof o==="string"?"text":"binary",data:o,timestamp:Date.now()};return this.messages.push(l),this}receive(o){if(!this.isConnected)throw Error("WebSocket is not connected");let l={type:typeof o==="string"?"text":"binary",data:o,timestamp:Date.now()};return this.emit("message",{type:"message",data:o}),this}ping(o){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("ping",{type:"ping",data:o}),this}pong(o){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("pong",{type:"pong",data:o}),this}on(o,l){if(!this.eventHandlers.has(o))this.eventHandlers.set(o,[]);return this.eventHandlers.get(o).push(l),this}off(o,l){let M=this.eventHandlers.get(o);if(M){let k=M.indexOf(l);if(k>-1)M.splice(k,1)}return this}emit(o,l){(this.eventHandlers.get(o)||[]).forEach((k)=>k(l))}getSentMessages(){return[...this.messages]}getMessagesByType(o){return this.messages.filter((l)=>l.type===o)}clearMessages(){return this.messages=[],this}getState(){return{isConnected:this.isConnected,readyState:this.readyState}}getTestClient(){return{send:(o)=>this.send(o),close:(o,l)=>this.disconnect(o,l),ping:(o)=>this.ping(o),pong:(o)=>this.pong(o),messages:this.getSentMessages(),isConnected:this.isConnected,readyState:this.readyState}}}class Os{tester;_data;constructor(o={}){this.tester=new Mt,this._data=o}send(o){this.tester.send(o)}close(o,l){this.tester.disconnect(o,l)}ping(o){this.tester.ping(o)}pong(o){this.tester.pong(o)}publish(o,l){this.tester.send(l)}subscribe(o){}unsubscribe(o){}isSubscribed(o){return!0}cork(o){o()}get readyState(){return this.tester.getState().readyState}get data(){return this._data}set data(o){this._data=o}getTester(){return this.tester}}var wl={onOpen:()=>Ut(async(o)=>{}),onMessage:(o)=>Ut(async(l,M)=>{if(o)l.send(o)}),onClose:()=>Ut(async(o,l,M)=>{}),onError:()=>Ut(async(o,l)=>{}),echo:()=>Ut(async(o,l)=>{o.send(l)}),broadcast:(o)=>Ut(async(l,M)=>{o.forEach((k)=>{if(k!==l&&k.readyState===1)k.send(M)})}),chatRoom:(o)=>Ut(async(l,M)=>{l.publish(o,M)})},bl={basicConnection:()=>new Mt().connect().send("Hello WebSocket").receive("Hello Client"),connectionFailure:()=>{let o=new Mt;return o.on("error",()=>{}),o},messageBroadcast:(o=3)=>{let l=Array.from({length:o},()=>new Mt().connect());return l[0].send("Broadcast message"),l.slice(1).forEach((M)=>M.receive("Broadcast message")),l},pingPong:()=>new Mt().connect().ping().pong(),connectionTimeout:()=>{let o=new Mt;return setTimeout(()=>{o.disconnect(1006,"Connection timeout")},100),o}},Tl={isConnected:(o)=>{if(!o.getState().isConnected)throw Error("Expected WebSocket to be connected")},isDisconnected:(o)=>{if(o.getState().isConnected)throw Error("Expected WebSocket to be disconnected")},messageSent:(o,l)=>{if(!o.getSentMessages().some((L)=>{if(typeof l==="string"&&typeof L.data==="string")return L.data===l;return L.data===l}))throw Error("Expected message not found in sent messages")},messageCount:(o,l)=>{let M=o.getSentMessages();if(M.length!==l)throw Error(`Expected ${l} messages, but got ${M.length}`)},messageType:(o,l,M)=>{let k=o.getSentMessages();if(l>=k.length)throw Error(`Message at index ${l} does not exist`);if(k[l].type!==M)throw Error(`Expected message type '${M}', got '${k[l].type}'`)},readyState:(o,l)=>{let M=o.getState();if(M.readyState!==l)throw Error(`Expected ready state ${l}, got ${M.readyState}`)}},xl={testThroughput:async(o=1000,l=1024)=>{let M=new Mt().connect(),k="x".repeat(l),L=performance.now();for(let xe=0;xe<o;xe++)M.send(k);let pe=performance.now()-L,he=o/pe*1000,Te=pe/o;return{messagesPerSecond:he,totalTime:pe,averageLatency:Te}},testConcurrentConnections:async(o=100)=>{let l={successfulConnections:0,failedConnections:0,averageConnectionTime:0},M=[],k=Array.from({length:o},async()=>{let L=performance.now();try{new Mt().connect();let pe=performance.now();M.push(pe-L),l.successfulConnections++}catch(V){console.error("WebSocket connection failed:",V),l.failedConnections++}});return await Promise.all(k),l.averageConnectionTime=M.length>0?M.reduce((L,V)=>L+V,0)/M.length:0,l}};function vl(){return new Mt}function Pl(o){return new Os(o)}var Cl={createClients:(o)=>Array.from({length:o},()=>new Mt().connect()),withLatency:(o,l)=>{let M=o.send.bind(o);return o.send=(k)=>(setTimeout(()=>M(k),l),o),o},withPacketLoss:(o,l)=>{let M=o.send.bind(o);return o.send=(k)=>{if(Math.random()>l)M(k);return o},o},*messageGenerator(o,l="Message"){for(let M=1;M<=o;M++)yield`${l} ${M}`}};class un extends Error{status;response;body;constructor(o,l){let M=typeof l?.message==="string"?l.message:o.statusText||"Request failed";super(`${o.status} ${M}`);this.name="TypedClientError",this.status=o.status,this.response=o,this.body=l}}function $s(o,l){if(!l)return o;let M=o;for(let[k,L]of Object.entries(l)){let V=encodeURIComponent(L);M=M.split(`{${k}}`).join(V),M=M.replace(new RegExp(`:${k}(?![A-Z0-9_])`,"gi"),V)}return M}function Bs(o,l){if(!l)return o;let M=new URLSearchParams;for(let[L,V]of Object.entries(l))if(V!==void 0&&V!==null)M.append(L,String(V));let k=M.toString();if(!k)return o;return o.includes("?")?`${o}&${k}`:`${o}?${k}`}async function bo(o){if(o.status===204||o.headers.get("content-length")==="0")return;if((o.headers.get("content-type")??"").includes("json"))try{return await o.json()}catch{return}return await o.text()}function To(o){let l=o.baseUrl.replace(/\/+$/,""),M=o.fetch??globalThis.fetch;async function k(){if(typeof o.headers==="function")return await o.headers();return o.headers??{}}async function L(V,pe,he,Te,xe){let ve=Bs(`${l}${$s(pe,xe?.params)}`,xe?.query),Pe={accept:"application/json",...await k(),...xe?.headers};if(Te&&Pe["content-type"]===void 0&&Pe["Content-Type"]===void 0)Pe["content-type"]="application/json";let Ce=await M(ve,{method:V,headers:Pe,...Te?{body:JSON.stringify(he)}:{},...o.credentials?{credentials:o.credentials}:{},...xe?.signal?{signal:xe.signal}:{}}),Ee=await bo(Ce);if(!Ce.ok){let Me=new un(Ce,Ee);if(o.onError)return o.onError(Me);throw Me}return Ee}return{get:(V,pe)=>L("GET",V,void 0,!1,pe),post:(V,pe,he)=>L("POST",V,pe,!0,he),put:(V,pe,he)=>L("PUT",V,pe,!0,he),patch:(V,pe,he)=>L("PATCH",V,pe,!0,he),delete:(V,pe)=>L("DELETE",V,void 0,!1,pe),async raw(V,pe,he){let{params:Te,query:xe,...ve}=he??{},Pe=Bs(`${l}${$s(pe,Te)}`,xe);return await M(Pe,{method:V,...ve,headers:{...await k(),...ve.headers},...o.credentials?{credentials:o.credentials}:{}})}}}function xo(o){return o}var vo=["get","post","put","patch","delete"];function Po(o,l,M,k){if(!k)return;let L=o,V=(pe)=>{let he=L?.[pe];if(typeof he!=="function")throw TypeError(`[typed-router] ${l.toUpperCase()} ${M}: this router's route does not support .${String(pe)}(), so the \`${String(pe)}\` option cannot be applied. Register the route directly instead of dropping it.`);return he};if(k.middleware)V("middleware").call(L,k.middleware);if(k.name)V("name").call(L,k.name);if(k.skipCsrf)V("skipCsrf").call(L);if(k.requireCsrf)V("requireCsrf").call(L);if(k.rateLimit)V("rateLimit").call(L,k.rateLimit.max,k.rateLimit.window??"minute")}function Co(o){let l={};for(let M of vo)l[M]=(k,L,V)=>(Po(o[M](k,L),M,k,V),l);return l}export{ln as ApiKeyManager,js as Auth,lr as AuthTester,_ as BindingBuilder,ho as BuiltInRules,Ta as CacheInvalidation,a as Container,w as ContentSecurityPolicy,ue as ContextualContainer,h as Cors,r as Csrf,b as DDoSProtection,yn as DEFAULT_COMPRESSION,Ou as DatabaseRules,F as DatabaseSessionStore,de as DefaultServiceProviderManager,ci as Dependencies,sr as DomainGroup,Gn as DomainGroupBuilder,mt as DomainMatcher,Gu as EnhancementPresets,z as EnvironmentManager,fn as Errors,S as FileSecurity,O as FileSessionStore,c as FileUpload,Ot as FileUploadTester,on as FileValidationTester,ke as FluentRouteBuilder,or as FluentRouter,mo as GenericMockModel,E as Helmet,ye as InMemoryNonceStore,R as InputValidation,cn as JWT,nn as JWTTester,m as JsonBody,Kt as LoadTester,u as MemorySessionStore,Es as MiddlewareChainTester,li as MiddlewareFactory,tn as MiddlewareGroupRegistry,vs as MiddlewareHelpers,Lr as MiddlewarePipeline,Ms as MiddlewareTester,Ro as MockPostClass,Os as MockServerWebSocket,fo as MockUserClass,Ss as ModelBindingTester,ks as ModelResolverTester,dn as OAuth2Helper,N as PerformanceAlerting,q as PerformanceDashboard,H as PerformanceMonitor,As as PerformanceTester,A as RateLimit,Ln as RateLimitRegistry,Pa as RateLimitUtils,Pr as RateLimiter,I as RedisSessionStore,g as RequestId,f as RequestSigning,B as RequestTracer,Tn as ResponseBuilder,lt as RouteBuilder,jn as RouteCacheFactory,Fn as RouteCacheKeyGenerator,In as RouteCacheManager,Zi as RouteFactory,Wn as RouteGroupBuilder,Lu as RouteHelpers,De as Router,Yi as RouterUtils,v as Security,j as SecuritySuite,y as Session,K as SessionManager,sn as SessionTester,n as SignatureError,ui as SkipConditions,Sa as SubdomainPatterns,Gr as SubdomainRouter,Ea as SubdomainUtils,$r as TestClient,Pt as TestRequestBuilder,an as TestResponseWrapper,Ii as ThrottleFactory,un as TypedClientError,Ps as ValidationFluentRouter,Du as ValidationHelpers,Cs as ValidationMiddlewareBuilder,Yr as ValidationRuleBuilder,Ar as Validator,Mt as WebSocketTester,Ue as apiKeyAuth,Yt as appendVary,io as applyRequestEnhancements,$t as applyResponseCompression,St as auth,Cc as authHelpers,Pc as authMocks,He as basicAuth,Be as bearerAuth,Gc as benchmarkMiddleware,il as benchmarkTests,oa as buildUrlWithPreservedParams,Li as clearNamedRoutes,Ko as compressResponse,e as config,Xc as constraintHelpers,We as contentSecurityPolicy,Rt as cors,Mc as createAuthTester,Re as createContainer,mr as createCookieAccessor,en as createEnhancementMiddleware,Bc as createFileUploadTester,zu as createFluentRouter,Di as createHandlerResolver,jt as createInMemoryCookieAccessor,Ec as createJWTTester,ll as createLoadTester,zc as createMiddlewareSpy,Fe as createMockRequest,pl as createMockResponse,Pl as createMockServerWebSocket,Zc as createModelBindingTester,Yc as createModelResolverTester,Da as createPathRegex,cl as createPerformanceTester,Gt as createRateLimitMiddleware,_n as createRouteCacheMiddleware,bt as createSessionStore,Sc as createSessionTester,Ma as createSubdomainMiddleware,Or as createTestClient,qs as createTestResponse,To as createTypedClient,Co as createTypedRouter,qr as createValidationMiddleware,vl as createWebSocketTester,Ct as csrf,Ge as ddosProtection,_t as decodeParam,me as defaultConfig,ia as defaultQueryPreservationConfig,xo as defineEndpoint,Qe as documentUpload,Ys as enableRequestContext,fe as extractApiKey,ge as extractBasicAuth,W as extractBearerToken,Cr as extractParamNames,Xn as fileExists,Ke as fileUpload,$c as fileUploadAssertions,qc as fileUploadMocks,Oc as fileUploadScenarios,Ti as generateQueryPreservationScript,D as generateSessionId,wt as getConfig,we as getContainer,Rn as getCurrentRequest,Wr as getNamedRoutePath,ji as getNamedRoutes,di as globalMiddlewarePipeline,$u as globalValidator,Ye as imageUpload,yr as injectQueryPreservationScript,Ze as inputValidation,Gi as isActionClass,wn as isCompressible,Ba as isRouteHandler,kt as joinPaths,vt as jsonBody,je as jwtAuth,ft as matchPath,ol as memoryTests,J as middleware,dt as middlewareGroups,_c as mockMiddleware,Kc as modelMocks,Xe as multipleFileUpload,Vo as negotiateEncoding,ir as normalizePath,Le as oauth2Auth,Wt as parseThrottleString,ii as peekBody,si as peekedStream,et as performanceAlerting,ul as performanceAssertions,tt as performanceDashboard,rt as performanceMonitor,Hs as performanceUtils,Qn as processHtmlTemplate,G as rateLimit,zn as rateLimitRegistry,At as registerNamedRoute,ei as request,xt as requestId,_e as requestSigning,nt as requestTracer,rr as resolveHandler,Vr as resolveViewPath,Ae as response,Zo as responseBuilder,zt as routeCacheManager,Qc as routeModelHelpers,eo as router,Bu as rule,Ir as runWithRequest,_r as runWithRequestArguments,el as scopedBindingHelpers,st as security,it as securitySuite,Tt as session,be as setContainer,Rr as setCurrentRequest,Jo as shouldCompress,ze as signRequest,Je as singleFileUpload,Lc as spyOnMiddleware,al as stressTests,fl as testClient,Dc as testFiles,Ic as testMiddleware,jc as testMiddlewareChain,wc as testRequest,$a as toActionPath,zi as url,ju as validate,Na as validatePath,Ve as verifySignature,$e as wrapResponse,Tl as wsAssertions,wl as wsHandlerMocks,xl as wsPerformance,bl as wsTestScenarios,Cl as wsTestUtils};
|
|
6
|
+
`,new Response(K,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})},health:(p="healthy",y={})=>{let J=p==="healthy"?200:p==="degraded"?200:503,K={status:p,timestamp:new Date().toISOString(),checks:y,uptime:cs.uptime?.()||0};return new Response(JSON.stringify(K),{status:J,headers:{"Content-Type":"application/json"}})}};function ls(){Object.entries(wt).forEach(([p,y])=>{Ar.macro(p,y)})}ls();var ps=/^[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,hs={required:{name:"required",validate:(p)=>{if(p===null||p===void 0)return!1;if(typeof p==="string")return p.trim().length>0;if(Array.isArray(p))return p.length>0;if(typeof p==="object")return Object.keys(p).length>0;return!0},message:"The :field field is required."},string:{name:"string",validate:(p)=>typeof p==="string",message:"The :field field must be a string."},number:{name:"number",validate:(p)=>typeof p==="number"&&!Number.isNaN(p),message:"The :field field must be a number."},integer:{name:"integer",validate:(p)=>Number.isInteger(Number(p)),message:"The :field field must be an integer."},boolean:{name:"boolean",validate:(p)=>typeof p==="boolean"||p==="true"||p==="false"||p==="1"||p==="0",message:"The :field field must be true or false."},email:{name:"email",validate:(p)=>typeof p==="string"&&ps.test(p),message:"The :field field must be a valid email address."},url:{name:"url",validate:(p)=>{try{let y=new URL(p);return Boolean(y)}catch{return!1}},message:"The :field field must be a valid URL."},min:{name:"min",validate:(p,y)=>{let J=Number(y[0]);if(typeof p==="string")return p.length>=J;if(typeof p==="number")return p>=J;if(Array.isArray(p))return p.length>=J;return!1},message:(p,y)=>`The ${p} field must be at least ${y[0]} characters.`},max:{name:"max",validate:(p,y)=>{let J=Number(y[0]);if(typeof p==="string")return p.length<=J;if(typeof p==="number")return p<=J;if(Array.isArray(p))return p.length<=J;return!1},message:(p,y)=>`The ${p} field must not exceed ${y[0]} characters.`},between:{name:"between",validate:(p,y)=>{let J=Number(y[0]),K=Number(y[1]);if(typeof p==="string")return p.length>=J&&p.length<=K;if(typeof p==="number")return p>=J&&p<=K;if(Array.isArray(p))return p.length>=J&&p.length<=K;return!1},message:(p,y)=>`The ${p} field must be between ${y[0]} and ${y[1]}.`},in:{name:"in",validate:(p,y)=>y.includes(String(p)),message:(p,y)=>`The ${p} field must be one of: ${y.join(", ")}.`},notIn:{name:"not_in",validate:(p,y)=>!y.includes(String(p)),message:(p,y)=>`The ${p} field must not be one of: ${y.join(", ")}.`},regex:{name:"regex",validate:(p,y)=>{let J=new RegExp(y[0]);return typeof p==="string"&&J.test(p)},message:"The :field field format is invalid."},alpha:{name:"alpha",validate:(p)=>typeof p==="string"&&/^[a-z]+$/i.test(p),message:"The :field field must contain only letters."},alphaNum:{name:"alpha_num",validate:(p)=>typeof p==="string"&&/^[a-z0-9]+$/i.test(p),message:"The :field field must contain only letters and numbers."},alphaDash:{name:"alpha_dash",validate:(p)=>typeof p==="string"&&/^[\w-]+$/.test(p),message:"The :field field must contain only letters, numbers, dashes, and underscores."},date:{name:"date",validate:(p)=>{let y=new Date(p);return!Number.isNaN(y.getTime())},message:"The :field field must be a valid date."},dateAfter:{name:"after",validate:(p,y)=>{let J=new Date(p),K=new Date(y[0]);return!Number.isNaN(J.getTime())&&!Number.isNaN(K.getTime())&&J>K},message:(p,y)=>`The ${p} field must be after ${y[0]}.`},dateBefore:{name:"before",validate:(p,y)=>{let J=new Date(p),K=new Date(y[0]);return!Number.isNaN(J.getTime())&&!Number.isNaN(K.getTime())&&J<K},message:(p,y)=>`The ${p} field must be before ${y[0]}.`},confirmed:{name:"confirmed",validate:(p,y,J,K)=>{let fe=y[0]||`${J}_confirmation`;return p===K[fe]},message:"The :field confirmation does not match."},same:{name:"same",validate:(p,y,J,K)=>p===K[y[0]],message:(p,y)=>`The ${p} field must match ${y[0]}.`},different:{name:"different",validate:(p,y,J,K)=>p!==K[y[0]],message:(p,y)=>`The ${p} field must be different from ${y[0]}.`},json:{name:"json",validate:(p)=>{try{return JSON.parse(p),!0}catch{return!1}},message:"The :field field must be valid JSON."},uuid:{name:"uuid",validate:(p)=>typeof p==="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(p),message:"The :field field must be a valid UUID."},array:{name:"array",validate:(p)=>Array.isArray(p),message:"The :field field must be an array."},object:{name:"object",validate:(p)=>typeof p==="object"&&p!==null&&!Array.isArray(p),message:"The :field field must be an object."}},di={unique:{name:"unique",validate:async(p,y)=>(console.warn('Database validation rule "unique" requires external implementation'),!0),message:"The :field field must be unique."},exists:{name:"exists",validate:async(p,y)=>(console.warn('Database validation rule "exists" requires external implementation'),!0),message:"The selected :field is invalid."}};class Ir{rules={};config;constructor(p={}){this.config={stopOnFirstFailure:!1,bail:!1,...p},this.registerRules(hs)}registerRule(p){this.rules[p.name]=p}registerRules(p){Object.values(p).forEach((y)=>this.registerRule(y))}parseRuleString(p){return p.split("|").map((y)=>{let[J,...K]=y.split(":"),fe=K.length>0?K.join(":").split(","):[];return{name:J.trim(),parameters:fe}})}async validate(p,y){let J={};for(let[K,fe]of Object.entries(y)){let be=[],We=this.getNestedValue(p,K),Ve=typeof fe==="string"?this.parseRuleString(fe):fe.map((ot)=>({name:ot.name,parameters:[]}));for(let{name:ot,parameters:at}of Ve){let dt=this.rules[ot];if(!dt){console.warn(`Validation rule "${ot}" not found`);continue}try{if(!await dt.validate(We,at,K,p)){let lt=this.formatErrorMessage(dt,K,at);if(be.push(lt),this.config.stopOnFirstFailure||this.config.bail)break}}catch(ut){console.error(`Error validating rule "${ot}" for field "${K}":`,ut),be.push(`Validation error for ${K}`)}}if(be.length>0)J[K]=be}return J}async validateOrFail(p,y){let J=await this.validate(p,y);if(Object.keys(J).length>0)throw new b("Validation failed",J)}getNestedValue(p,y){return y.split(".").reduce((J,K)=>J&&J[K]!==void 0?J[K]:void 0,p)}formatErrorMessage(p,y,J){let K=this.config.customMessages?.[`${y}.${p.name}`]||this.config.customMessages?.[p.name];if(K)return this.replacePlaceholders(K,y,J);let fe=typeof p.message==="function"?p.message(y,J):p.message;return this.replacePlaceholders(fe,y,J)}replacePlaceholders(p,y,J){let K=this.config.customAttributes?.[y]||y.replace(/_/g," ");return p.replace(/:field/g,K).replace(/:attribute/g,K).replace(/:value/g,J[0]||"").replace(/:other/g,J[1]||"")}}var ui=new Ir;function _r(p,y){let J=new Ir(y);return async(K,fe)=>{try{let be={...K.query,...K.params,...K.jsonBody||{},...K.formBody||{}};return await J.validateOrFail(be,p),K.validated=be,await fe()}catch(be){if(be instanceof b)throw be;throw new b("Validation error occurred")}}}class Zr{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(p){return this.rules.push(`min:${p}`),this}max(p){return this.rules.push(`max:${p}`),this}between(p,y){return this.rules.push(`between:${p},${y}`),this}in(...p){return this.rules.push(`in:${p.join(",")}`),this}notIn(...p){return this.rules.push(`not_in:${p.join(",")}`),this}regex(p){return this.rules.push(`regex:${p}`),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(p){return this.rules.push(`after:${p}`),this}before(p){return this.rules.push(`before:${p}`),this}confirmed(p){return this.rules.push(p?`confirmed:${p}`:"confirmed"),this}same(p){return this.rules.push(`same:${p}`),this}different(p){return this.rules.push(`different:${p}`),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(p,y){return this.rules.push(y?`unique:${p},${y}`:`unique:${p}`),this}exists(p,y){return this.rules.push(y?`exists:${p},${y}`:`exists:${p}`),this}custom(p,...y){return this.rules.push(y.length>0?`${p}:${y.join(",")}`:p),this}build(){return this.rules.join("|")}}function ci(){return new Zr}var li={rules(p){let y={};for(let[J,K]of Object.entries(p))y[J]=K instanceof Zr?K.build():K;return y},async validateValue(p,y,J="value"){return(await new Ir().validate({[J]:p},{[J]:y}))[J]||[]},async passes(p,y){return(await this.validateValue(p,y)).length===0},async fails(p,y){return!await this.passes(p,y)}};class ft{method;path;handler;validationRules;validatorConfig;constructor(p,y,J){this.method=p;this.path=y;this.handler=J}validate(p,y){return this.validationRules=p,this.validatorConfig=y,this}build(){let p=[];if(this.validationRules)p.push(_r(this.validationRules,this.validatorConfig));return p.push(async(y,J)=>(i.applyMacros(y),await J()||new Response("Not Found",{status:404}))),{method:this.method,path:this.path,handler:this.handler,middleware:p.length>0?p:void 0}}}class Hn{routes=[];get(p,y){return new ft("GET",p,y)}post(p,y){return new ft("POST",p,y)}put(p,y){return new ft("PUT",p,y)}patch(p,y){return new ft("PATCH",p,y)}delete(p,y){return new ft("DELETE",p,y)}register(p){let y=p.build();this.routes.push(y)}getRoutes(){return this.routes}}function Yr(){return async(p,y)=>(i.applyMacros(p),p.startTime=Date.now(),await y())}class qn{rules={};config={};field(p,y){return this.rules[p]=y,this}fields(p){return Object.assign(this.rules,p),this}configure(p){return Object.assign(this.config,p),this}stopOnFirstFailure(){return this.config.stopOnFirstFailure=!0,this}messages(p){return this.config.customMessages=p,this}attributes(p){return this.config.customAttributes=p,this}build(){return _r(this.rules,this.config)}}function yi(){return new qn}var Ri={validated:(p,y,J,K,fe)=>new ft(p,y,J).validate(K,fe),apiRoute:(p,y,J,K)=>{let fe=new ft(p,y,async(be)=>{if(!be.expectsJson())return Ar.callMacro("error","API endpoint requires JSON Accept header",void 0,406);return s(await J(be))});if(K)fe.validate(K);return fe},resourceRoute:(p,y,J)=>{let K=[];if(y.index)K.push(new ft("GET",p,y.index));if(y.show)K.push(new ft("GET",`${p}/{id}`,y.show));if(y.store){let fe=new ft("POST",p,y.store);if(J?.store)fe.validate(J.store);K.push(fe)}if(y.update){let fe=new ft("PUT",`${p}/{id}`,y.update);if(J?.update)fe.validate(J.update);K.push(fe)}if(y.destroy)K.push(new ft("DELETE",`${p}/{id}`,y.destroy));return K}};function wi(){return new Hn}var kn={compose:(...p)=>async(y,J)=>{let K=0,fe=async()=>{if(K>=p.length)return await J();let be=p[K++];return await be(y,fe)};return await fe()},when:(p,y)=>async(J,K)=>{if(p(J))return await y(J,K);return await K()},unless:(p,y)=>kn.when((J)=>!p(J),y),group:(p)=>kn.compose(...p)},bi={api:()=>[Yr(),async(p,y)=>{try{let J=await y(),K=new Headers(J.headers);return K.set("X-API-Version","1.0"),K.set("X-Response-Time",new Date().toISOString()),new Response(J.body,{status:J.status,statusText:J.statusText,headers:K})}catch(J){return console.error(J),Ar.callMacro("error","Internal server error",void 0,500)}}],web:()=>[Yr(),async(p,y)=>(p.session={},await y())],validation:(p,y)=>[Yr(),_r(p,y)]};class en{groups=new Map;globalMiddleware=[];middlewarePriority=new Map;define(p,y){return this.groups.set(p,[...y]),this}extend(p,y){let J=this.groups.get(p)||[];return this.groups.set(p,[...J,...y]),this}prepend(p,y){let J=this.groups.get(p)||[];return this.groups.set(p,[...y,...J]),this}get(p){return this.groups.get(p)||[]}has(p){return this.groups.has(p)}remove(p){return this.groups.delete(p),this}resolve(p){if(typeof p==="function")return[p];if(this.groups.has(p))return this.get(p);return[p]}resolveAll(p){let y=[];for(let J of p)y.push(...this.resolve(J));return y}pushGlobal(...p){return this.globalMiddleware.push(...p),this}prependGlobal(...p){return this.globalMiddleware.unshift(...p),this}removeGlobal(p){return this.globalMiddleware=this.globalMiddleware.filter((y)=>typeof y==="string"?y!==p:!0),this}getGlobal(){return[...this.globalMiddleware]}setPriority(p,y){return this.middlewarePriority.set(p,y),this}sortByPriority(p){return[...p].sort((y,J)=>{let K=typeof y==="string"?y.split(":")[0]:"",fe=typeof J==="string"?J.split(":")[0]:"",be=this.middlewarePriority.get(K)??100,We=this.middlewarePriority.get(fe)??100;return be-We})}filter(p,y){if(y.only&&y.only.length>0)return p.filter((J)=>{if(typeof J==="string"){let K=J.split(":")[0];return y.only.includes(K)}return!1});if(y.except&&y.except.length>0)return p.filter((J)=>{if(typeof J==="string"){let K=J.split(":")[0];return!y.except.includes(K)}return!0});return p}flush(){this.groups.clear(),this.globalMiddleware=[],this.middlewarePriority.clear()}}var yt=new en;yt.define("web",["session","csrf","cors"]);yt.define("api",["throttle:60,1","cors"]);yt.setPriority("session",10);yt.setPriority("cors",20);yt.setPriority("csrf",30);yt.setPriority("auth",40);yt.setPriority("throttle",50);yt.setPriority("role",60);yt.setPriority("permission",60);yt.setPriority("can",70);yt.setPriority("abilities",70);yt.setPriority("verified",80);import{mock as tn}from"bun:test";class bt{request;url;constructor(p,y,J={}){if(this.url=new URL(y,"http://localhost:3000"),J.query)Object.entries(J.query).forEach(([K,fe])=>{if(Array.isArray(fe))fe.forEach((be)=>this.url.searchParams.append(K,be));else this.url.searchParams.set(K,fe)});this.request={method:p,url:this.url.toString(),headers:new Headers(J.headers||{}),params:{},query:this.parseQuery(this.url.searchParams),jsonBody:void 0,formBody:J.body&&typeof J.body==="object"?J.body:void 0,files:J.files?this.convertTestFiles(J.files):void 0,session:J.session,user:J.user,context:J.context||{},requestId:`test-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ip:()=>"127.0.0.1",userAgent:()=>"BunRouter-TestClient/1.0",cookies:x(J.cookies||{}),startTime:Date.now(),traceId:`trace-${Date.now()}`,spanId:`span-${Date.now()}`},this.handleBody(J.body)}parseQuery(p){let y={};for(let[J,K]of p.entries())if(y[J])if(Array.isArray(y[J]))y[J].push(K);else y[J]=[y[J],K];else y[J]=K;return y}convertTestFiles(p){return p.map((y)=>({fieldName:y.fieldName,originalName:y.filename,filename:`test-${Date.now()}-${y.filename}`,path:`/tmp/test-uploads/${y.filename}`,size:y.content instanceof ArrayBuffer?y.content.byteLength:new TextEncoder().encode(y.content.toString()).length,mimetype:y.mimetype||"application/octet-stream",buffer:y.content instanceof ArrayBuffer?y.content:new TextEncoder().encode(y.content.toString()).buffer}))}handleBody(p){if(!p)return;let y=this.request.headers?.get("content-type")||"";if(y.includes("application/json")||typeof p==="object"){if(this.request.jsonBody=p,!this.request.headers?.has("content-type"))this.request.headers?.set("content-type","application/json")}else if(y.includes("application/x-www-form-urlencoded"))this.request.formBody=p}params(p){return this.request.params={...this.request.params,...p},this}headers(p){return Object.entries(p).forEach(([y,J])=>{this.request.headers?.set(y,J)}),this}auth(p,y="Bearer"){return this.request.headers?.set("Authorization",`${y} ${p}`),this}user(p){return this.request.user=p,this}session(p){return this.request.session=p,this}cookies(p){let y=this.request.cookies?.getAll()||{};return this.request.cookies=x({...y,...p}),this}context(p){return this.request.context={...this.request.context,...p},this}json(p){return this.request.jsonBody=p,this.request.headers?.set("content-type","application/json"),this}form(p){return this.request.formBody=p,this.request.headers?.set("content-type","application/x-www-form-urlencoded"),this}files(p){return this.request.files=this.convertTestFiles(p),this.request.headers?.set("content-type","multipart/form-data"),this}ip(p){return this.request.ip=()=>p,this}userAgent(p){return this.request.userAgent=()=>p,this.request.headers?.set("User-Agent",p),this}csrf(p){return this.request.csrfToken=p,this.request.headers?.set("X-CSRF-Token",p),this}build(){let p={method:this.request.method,headers:this.request.headers};if(this.request.jsonBody)p.body=JSON.stringify(this.request.jsonBody);else if(this.request.formBody){let K=new FormData;Object.entries(this.request.formBody).forEach(([fe,be])=>{K.append(fe,be)}),p.body=K}let y=new Request(this.url.toString(),p);return Object.assign(y,{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 Bi={get:(p,y)=>new bt("GET",p,y),post:(p,y)=>new bt("POST",p,y),put:(p,y)=>new bt("PUT",p,y),patch:(p,y)=>new bt("PATCH",p,y),delete:(p,y)=>new bt("DELETE",p,y),options:(p,y)=>new bt("OPTIONS",p,y),head:(p,y)=>new bt("HEAD",p,y)};function pt(p="GET",y="/",J={}){return new bt(p,y,J).build()}class Br{request;constructor(p){this.request=p||pt()}as(p){return this.request.user=p,this}withJWT(p,y="Bearer"){let J=new Headers(this.request.headers);return J.set("Authorization",`${y} ${p}`),this.request={...this.request,headers:J},this}withSession(p){return this.request.session=p,this}withApiKey(p,y="X-API-Key"){let J=new Headers(this.request.headers);return J.set(y,p),this.request={...this.request,headers:J},this}withBasicAuth(p,y){let J=btoa(`${p}:${y}`),K=new Headers(this.request.headers);return K.set("Authorization",`Basic ${J}`),this.request={...this.request,headers:K},this}withAuthCookies(p){let y=this.request.cookies?.getAll()||{};return this.request.cookies=x({...y,...p}),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 rn{options;constructor(p={}){this.options={secret:"test-secret",expiresIn:"1h",algorithm:"HS256",...p}}generateToken(p={}){let y={alg:this.options.algorithm,typ:"JWT",...this.options.headers},J=Math.floor(Date.now()/1000),K=J+this.parseExpiresIn(this.options.expiresIn||"1h"),fe={iat:J,exp:K,...this.options.payload,...p},be=btoa(JSON.stringify(y)).replace(/=/g,""),We=btoa(JSON.stringify(fe)).replace(/=/g,""),Ve=btoa(`${be}.${We}.${this.options.secret}`).replace(/=/g,"");return`${be}.${We}.${Ve}`}generateExpiredToken(p={}){let y={alg:this.options.algorithm,typ:"JWT"},J=Math.floor(Date.now()/1000),K={iat:J-7200,exp:J-3600,...p},fe=btoa(JSON.stringify(y)).replace(/=/g,""),be=btoa(JSON.stringify(K)).replace(/=/g,""),We=btoa(`${fe}.${be}.${this.options.secret}`).replace(/=/g,"");return`${fe}.${be}.${We}`}generateInvalidToken(){return"invalid.jwt.token"}decodeToken(p){let[y,J,K]=p.split(".");return{header:JSON.parse(atob(y)),payload:JSON.parse(atob(J)),signature:K}}parseExpiresIn(p){let y=p.match(/^(\d+)([smhd])$/);if(!y)return 3600;let J=Number.parseInt(y[1]);switch(y[2]){case"s":return J;case"m":return J*60;case"h":return J*3600;case"d":return J*86400;default:return 3600}}}class nn{options;constructor(p={}){this.options={sessionId:`test-session-${Date.now()}`,maxAge:3600000,secure:!1,httpOnly:!0,...p}}createSession(p={}){let y={...this.options.data,...p},J=this.generateSessionCookie();return{sessionId:this.options.sessionId,data:y,cookie:J}}generateSessionCookie(p="session"){let y=[];if(this.options.maxAge)y.push(`Max-Age=${Math.floor(this.options.maxAge/1000)}`);if(this.options.secure)y.push("Secure");if(this.options.httpOnly)y.push("HttpOnly");let J=y.length>0?`; ${y.join("; ")}`:"";return`${p}=${this.options.sessionId}${J}`}createExpiredSession(){let p={...this.options,maxAge:-1};return new nn(p).createSession()}}var Ni={user:(p={})=>({id:1,email:"test@example.com",username:"testuser",roles:["user"],permissions:["read"],...p}),adminUser:(p={})=>({id:1,email:"admin@example.com",username:"admin",roles:["admin"],permissions:["read","write","delete"],...p}),guestUser:()=>({id:0,email:"guest@example.com",username:"guest",roles:["guest"],permissions:[]}),authMiddleware:(p)=>tn(async(y,J)=>{if(p)return y.user=p,await J();return new Response("Unauthorized",{status:401})}),roleMiddleware:(p)=>tn(async(y,J)=>{if(!y.user)return new Response("Unauthorized",{status:401});let K=y.user.roles||[];if(!p.some((be)=>K.includes(be)))return new Response("Forbidden",{status:403});return await J()}),permissionMiddleware:(p)=>tn(async(y,J)=>{if(!y.user)return new Response("Unauthorized",{status:401});let K=y.user.permissions||[];if(!p.every((be)=>K.includes(be)))return new Response("Forbidden",{status:403});return await J()})},Ii={authenticatedRequest:(p,y)=>new Br(y).as(p).getRequest(),jwtRequest:(p={},y)=>{let K=new rn().generateToken(p);return new Br(y).withJWT(K).getRequest()},sessionRequest:(p={},y)=>new Br(y).withSession(p).getRequest(),verifyJWTStructure:(p)=>{let y=p.split(".");return y.length===3&&y.every((J)=>J.length>0)},extractJWTPayload:(p)=>{try{let[,y]=p.split(".");return JSON.parse(atob(y))}catch{return null}}};function _i(p){return new Br(p)}function ji(p){return new rn(p)}function Li(p){return new nn(p)}import{mock as ir}from"bun:test";class sr{request;files;constructor(p){this.request=p||pt(),this.files=[]}addFile(p){let y={fieldName:p.fieldName,originalName:p.filename,filename:`test-${Date.now()}-${p.filename}`,path:`/tmp/test-uploads/${p.filename}`,size:p.content instanceof ArrayBuffer?p.content.byteLength:new TextEncoder().encode(p.content.toString()).length,mimetype:p.mimetype||this.detectMimeType(p.filename),buffer:p.content instanceof ArrayBuffer?p.content:new TextEncoder().encode(p.content.toString()).buffer};return this.files.push(y),this.request.files=[...this.request.files||[],y],this}addFiles(p){return p.forEach((y)=>this.addFile(y)),this}addImage(p,y="test.jpg",J=1024){let K=new ArrayBuffer(J);return this.addFile({fieldName:p,filename:y,content:K,mimetype:"image/jpeg"})}addDocument(p,y="test.pdf",J="Test PDF content"){return this.addFile({fieldName:p,filename:y,content:J,mimetype:"application/pdf"})}addTextFile(p,y="test.txt",J="Test content"){return this.addFile({fieldName:p,filename:y,content:J,mimetype:"text/plain"})}addLargeFile(p,y=10){let J=y*1024*1024,K=new ArrayBuffer(J);return this.addFile({fieldName:p,filename:`large-file-${y}mb.bin`,content:K,mimetype:"application/octet-stream"})}addInvalidFile(p,y="malicious.exe"){return this.addFile({fieldName:p,filename:y,content:"Potentially malicious content",mimetype:"application/x-executable"})}withFormData(p){return this.request.formBody={...this.request.formBody,...p},this}getRequest(){return this.request}getFiles(){return this.files}clearFiles(){return this.files=[],this.request.files=[],this}detectMimeType(p){let y=p.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"}[y||""]||"application/octet-stream"}}class sn{static testFileSize(p,y){return p.size<=y}static testFileType(p,y){return y.includes(p.mimetype)}static testFileExtension(p,y){let J=p.originalName.split(".").pop()?.toLowerCase();return J?y.includes(J):!1}static testFilename(p){let y=p.originalName;if(y.includes("..")||y.includes("/")||y.includes("\\"))return!1;if(y.includes("\x00"))return!1;let J=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],K=y.split(".")[0].toUpperCase();if(J.includes(K))return!1;return!0}static testImageFile(p){return["image/jpeg","image/png","image/gif","image/webp","image/svg+xml"].includes(p.mimetype)}static testDocumentFile(p){return["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/csv"].includes(p.mimetype)}}var Vi={validationMiddleware:(p={})=>ir(async(J,K)=>{let fe=J.files||[],{maxSize:be=5242880,allowedTypes:We=[],maxFiles:Ve=10}=p;if(fe.length>Ve)return new Response(`Too many files. Maximum ${Ve} allowed.`,{status:400});for(let ot of fe){if(ot.size>be)return new Response(`File ${ot.originalName} is too large. Maximum size: ${be} bytes.`,{status:400});if(We.length>0&&!We.includes(ot.mimetype))return new Response(`File type ${ot.mimetype} not allowed.`,{status:400});if(!sn.testFilename(ot))return new Response(`Invalid filename: ${ot.originalName}`,{status:400})}return await K()}),imageUploadMiddleware:(p={})=>ir(async(J,K)=>{let fe=J.files||[],{maxSize:be=2097152}=p;for(let We of fe){if(!sn.testImageFile(We))return new Response(`File ${We.originalName} is not a valid image.`,{status:400});if(We.size>be)return new Response(`Image ${We.originalName} is too large.`,{status:400})}return await K()}),storageService:{store:ir(async(p,y)=>y||`/uploads/${Date.now()}-${p.filename}`),delete:ir(async(p)=>{}),exists:ir(async(p)=>!p.includes("not-found")),getUrl:ir((p)=>`https://example.com/storage${p}`)},virusScanner:{scan:ir(async(p)=>{if(p.originalName.endsWith(".exe")||p.mimetype==="application/x-executable")return{clean:!1,threat:"Potentially malicious executable"};return{clean:!0}})}},zi={singleFileUpload:()=>new sr().addImage("avatar","profile.jpg").withFormData({description:"Profile picture"}),multipleFileUpload:()=>new sr().addImage("images","photo1.jpg").addImage("images","photo2.png").addDocument("documents","report.pdf").withFormData({album:"vacation"}),fileSizeExceeded:()=>new sr().addLargeFile("file",50),invalidFileType:()=>new sr().addInvalidFile("file","virus.exe"),emptyFileUpload:()=>new sr().addFile({fieldName:"file",filename:"empty.txt",content:"",mimetype:"text/plain"}),maliciousFilename:()=>new sr().addFile({fieldName:"file",filename:"../../../etc/passwd",content:"malicious content",mimetype:"text/plain"})},Ki={hasFiles:(p,y)=>{let J=p.files||[];if(y!==void 0&&J.length!==y)throw Error(`Expected ${y} files, but got ${J.length}`);if(J.length===0)throw Error("Expected request to have files")},hasFileWithField:(p,y)=>{if(!(p.files||[]).some((fe)=>fe.fieldName===y))throw Error(`Expected file with field name '${y}'`)},fileMatches:(p,y)=>{Object.entries(y).forEach(([J,K])=>{if(p[J]!==K)throw Error(`Expected file.${J} to be '${K}', got '${p[J]}'`)})},fileSizeWithinLimit:(p,y)=>{if(p.size>y)throw Error(`File size ${p.size} exceeds limit of ${y}`)},fileTypeAllowed:(p,y)=>{if(!y.includes(p.mimetype))throw Error(`File type '${p.mimetype}' is not allowed. Allowed types: ${y.join(", ")}`)}};function Xi(p){return new sr(p)}var Qi={image:(p="image",y="test.jpg")=>({fieldName:p,filename:y,content:new ArrayBuffer(1024),mimetype:"image/jpeg"}),document:(p="document",y="test.pdf")=>({fieldName:p,filename:y,content:"PDF content",mimetype:"application/pdf"}),text:(p="file",y="test.txt",J="Test content")=>({fieldName:p,filename:y,content:J,mimetype:"text/plain"}),large:(p="file",y=10)=>({fieldName:p,filename:`large-${y}mb.bin`,content:new ArrayBuffer(y*1024*1024),mimetype:"application/octet-stream"}),malicious:(p="file")=>({fieldName:p,filename:"../../../malicious.exe",content:"malicious content",mimetype:"application/x-executable"})};import{mock as ht,spyOn as ms}from"bun:test";class On{middleware;context;constructor(p){this.middleware=p,this.context=this.createContext()}createContext(){let p=pt(),y=ht(()=>Promise.resolve(new Response("Next called",{status:200})));return{request:p,next:y}}withRequest(p){return this.context.request=p,this}withNext(p){return this.context.next=ht(p),this}withError(p){return this.context.error=p,this}async execute(){try{return await this.middleware(this.context.request,this.context.next)}catch(p){throw this.context.error=p,p}}expectNextCalled(p=1){if(this.context.next.mock.calls.length!==p)throw Error(`Expected next to be called ${p} 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(p){if(!this.context.error)throw Error("Expected middleware to throw an error, but no error was thrown");if(p&&this.context.error.message!==p)throw Error(`Expected error message "${p}", but got "${this.context.error.message}"`);return this}getContext(){return this.context}reset(){return this.context=this.createContext(),this}}function to(p){return new On(p)}var ro={passthrough:()=>ht(async(p,y)=>await y()),response:(p=200,y)=>ht(async()=>new Response(y?JSON.stringify(y):null,{status:p})),error:(p="Middleware error")=>ht(async()=>{throw Error(p)}),modifyRequest:(p)=>ht(async(y,J)=>(p(y),await J())),addContext:(p,y)=>ht(async(J,K)=>(J.context=J.context||{},J.context[p]=y,await K())),auth:(p)=>ht(async(y,J)=>{if(p)return y.user=p,await J();else return new Response("Unauthorized",{status:401})}),rateLimit:(p=!1)=>ht(async(y,J)=>{if(p)return new Response("Too Many Requests",{status:429});return await J()}),cors:(p="*")=>ht(async(y,J)=>{let K=await J();if(K)K.headers.set("Access-Control-Allow-Origin",p);return K})};class An{middlewares;request;finalHandler;constructor(p){this.middlewares=p,this.request=pt(),this.finalHandler=ht(async()=>new Response("Final handler",{status:200}))}withRequest(p){return this.request=p,this}withFinalHandler(p){return this.finalHandler=ht(p),this}async execute(){let p=0,y=async()=>{if(p<this.middlewares.length){let J=this.middlewares[p++];return await J(this.request,y)}else return await this.finalHandler()};return await y()}getExecutionOrder(){return this.middlewares.map((p,y)=>y)}}function no(p){return new An(p)}function so(p){return ms(p,"call")}function io(){let p=ht(async(y,J)=>await J());return{middleware:p,spy:p}}async function oo(p,y=1000){let J=[],K=pt(),fe=ht(async()=>new Response("OK"));for(let at=0;at<y;at++){let dt=performance.now();await p(K,fe);let ut=performance.now();J.push(ut-dt)}let be=J.reduce((at,dt)=>at+dt,0),We=be/y,Ve=Math.min(...J),ot=Math.max(...J);return{averageTime:We,minTime:Ve,maxTime:ot,totalTime:be}}import{mock as nr}from"bun:test";class gs{id;attributes;constructor(p={}){this.id=p.id,this.attributes=p}static modelName="GenericMockModel";static async find(p){return null}static async findOrFail(p){throw Error("Not implemented")}static async where(p){return[]}static async create(p){throw Error("Not implemented")}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}}class fs{id;email;name;constructor(p={id:1}){this.id=p.id,this.email=p.email||"test@example.com",this.name=p.name||"Test User"}static async find(p){return null}static async findOrFail(p){throw Error("Not implemented")}toJSON(){return{id:this.id,email:this.email,name:this.name}}}class ys{id;title;content;userId;constructor(p={id:1}){this.id=p.id,this.title=p.title||"Test Post",this.content=p.content||"Test content",this.userId=p.userId||1}static async find(p){return null}static async findOrFail(p){throw Error("Not implemented")}async belongsTo(p){return!1}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}class Bn{request;options;constructor(p={}){this.options=p,this.request=pt()}withRequest(p){return this.request=p,this}withParams(p){return this.request.params={...this.request.params,...p},this}withModel(p){return this.options.modelClass=p,this}withRouteKey(p){return this.options.routeKey=p,this}withConstraints(p){return this.options.constraints=p,this}withResolver(p){return this.options.customResolver=p,this}async testResolution(p){if(this.options.customResolver)return await this.options.customResolver(p);if(this.options.modelClass)return new this.options.modelClass({id:p});return{id:p}}async testNotFound(p){try{throw await this.testResolution(p),Error("Expected model not found error")}catch(y){if(y instanceof Error&&y.message!=="Model not found")throw y}}getRequest(){return this.request}}var lo={createModel:(p,y={})=>class J{id;attributes;constructor(K={}){this.id=K.id,this.attributes={...y,...K}}static modelName=p;static async find(K){if(K==="not-found")return null;return new J({id:K,...y})}static async findOrFail(K){let fe=await this.find(K);if(!fe)throw Error("Model not found");return fe}static async where(K){return[new J({id:1,...y,...K})]}static async create(K){return new J({id:Date.now(),...K})}async save(){return this}async delete(){}toJSON(){return{id:this.id,...this.attributes}}},User:class p{id;email;name;constructor(y={id:1}){this.id=y.id,this.email=y.email||"test@example.com",this.name=y.name||"Test User"}static async find(y){if(y==="not-found")return null;return new p({id:Number.parseInt(y)})}static async findOrFail(y){let J=await this.find(y);if(!J)throw Error("User not found");return J}toJSON(){return{id:this.id,email:this.email,name:this.name}}},Post:class p{id;title;content;userId;constructor(y={id:1}){this.id=y.id,this.title=y.title||"Test Post",this.content=y.content||"Test content",this.userId=y.userId||1}static async find(y){if(y==="not-found")return null;return new p({id:Number.parseInt(y)})}static async findOrFail(y){let J=await this.find(y);if(!J)throw Error("Post not found");return J}async belongsTo(y){return this.userId===y}toJSON(){return{id:this.id,title:this.title,content:this.content,userId:this.userId}}}},po={belongsTo:(p="userId")=>nr(async(J,K)=>{if(!K.user)return!1;return J[p]===K.user.id}),belongsToUser:()=>nr(async(y,J)=>{if(!J.user)return!1;return y.userId===J.user.id}),published:()=>nr(async(y)=>y.published===!0||y.status==="published"),visible:()=>nr(async(y)=>y.visible!==!1&&y.hidden!==!0),custom:(p)=>nr(p),combine:(...p)=>nr(async(J,K)=>{for(let fe of p)if(!await fe(J,K))return!1;return!0})};class $n{resolvers=new Map;register(p,y){return this.resolvers.set(p,nr(y)),this}registerModel(p,y){let J=nr(async(K)=>{if(y.find){let fe=await y.find(K);if(!fe)throw Error(`${y.name||"Model"} not found`);return fe}return new y({id:K})});return this.resolvers.set(p,J),this}async resolve(p,y){let J=this.resolvers.get(p);if(!J)throw Error(`No resolver registered for key: ${p}`);return await J(y)}async testAll(p="1"){let y={};for(let[J,K]of this.resolvers)try{y[J]=await K(p)}catch(fe){y[J]={error:fe instanceof Error?fe.message:"Unknown error"}}return y}getKeys(){return Array.from(this.resolvers.keys())}clear(){return this.resolvers.clear(),this}}var ho={testRoute:async(p,y,J)=>{let K=pt("GET",p);K.params=y;for(let[fe,be]of Object.entries(J))K.context=K.context||{},K.context[fe]=be;return K},createHandler:(p)=>nr(async(J)=>{let K=J.context||{};for(let fe of p)if(!K[fe])return new Response(`Model ${fe} not found`,{status:404});return new Response(JSON.stringify({params:J.params,models:Object.fromEntries(p.map((fe)=>[fe,K[fe]]))}),{headers:{"Content-Type":"application/json"}})}),testBindingMiddleware:(p)=>nr(async(J,K)=>{J.context=J.context||{};for(let[fe,be]of Object.entries(p)){let We=J.params[fe];if(We)try{if(typeof be==="function")J.context[fe]=await be(We);else J.context[fe]=be}catch(Ve){return console.error(`Error resolving model ${fe}:`,Ve),new Response(`${fe} not found`,{status:404})}}return await K()})};function mo(p){return new Bn(p)}function go(){return new $n}var Rs=async(p,y)=>p.userId===y.id,fo={testUserScoped:async(p,y,J=Rs)=>await J(p,y),testRoleAccess:async(p,y,J)=>{if(!y.roles)return!1;return J.some((K)=>y.roles.includes(K))},testPermissionAccess:async(p,y,J)=>{if(!y.permissions)return!1;return J.every((K)=>y.permissions.includes(K))}};import{mock as ws}from"bun:test";import or from"process";class Un{metrics=[];startTime=0;endTime=0;start(){return this.startTime=performance.now(),this}end(){return this.endTime=performance.now(),this}recordMetric(p){return this.metrics.push(p),this}getElapsedTime(){return this.endTime-this.startTime}getMetrics(){return[...this.metrics]}getAverageResponseTime(){if(this.metrics.length===0)return 0;return this.metrics.reduce((y,J)=>y+J.responseTime,0)/this.metrics.length}getMemoryStats(){if(this.metrics.length===0)return{averageHeapUsed:0,maxHeapUsed:0,averageRSS:0,maxRSS:0};let p=this.metrics.map((J)=>J.memoryUsage.heapUsed),y=this.metrics.map((J)=>J.memoryUsage.rss);return{averageHeapUsed:p.reduce((J,K)=>J+K,0)/p.length,maxHeapUsed:Math.max(...p),averageRSS:y.reduce((J,K)=>J+K,0)/y.length,maxRSS:Math.max(...y)}}clear(){return this.metrics=[],this.startTime=0,this.endTime=0,this}}class cr{client;config;constructor(p,y){this.client=p,this.config=y}async run(p,y="GET",J={}){let K={totalRequests:0,successfulRequests:0,failedRequests:0,averageResponseTime:0,requestsPerSecond:0,errors:[]},fe=[],be=new Map,We=Date.now(),Ve=this.config.maxRequests||Math.floor(this.config.duration/1000*(this.config.requestsPerSecond||this.config.concurrency)),ot=[];for(let ut=0;ut<Ve;ut++){let lt=this.makeRequest(p,y,J).then((mt)=>{fe.push(mt),K.successfulRequests++}).catch((mt)=>{let gt=mt instanceof Error?mt.message:"Unknown error";be.set(gt,(be.get(gt)||0)+1),K.failedRequests++});if(ot.push(lt),this.config.requestsPerSecond){let mt=1000/this.config.requestsPerSecond;await new Promise((gt)=>setTimeout(gt,mt))}if(ot.length>=this.config.concurrency)await Promise.race(ot),ot.filter((gt)=>gt.then(()=>!0).catch(()=>!0)).forEach((gt)=>{let $r=ot.indexOf(gt);if($r>-1)ot.splice($r,1)})}await Promise.allSettled(ot);let dt=(Date.now()-We)/1000;return K.totalRequests=Ve,K.averageResponseTime=fe.length>0?fe.reduce((ut,lt)=>ut+lt,0)/fe.length:0,K.requestsPerSecond=Ve/dt,K.errors=Array.from(be.entries()).map(([ut,lt])=>({error:ut,count:lt})),K}async makeRequest(p,y,J){let K=performance.now();try{return await this.client.request(y,p,J),performance.now()-K}catch(fe){let be=performance.now();throw fe}}}var To={routeHandler:async(p,y=1000)=>{let J=[],K=pt();for(let at=0;at<y;at++){let dt=performance.now();await p(K);let ut=performance.now();J.push(ut-dt)}let fe=J.reduce((at,dt)=>at+dt,0),be=fe/y,We=Math.min(...J),Ve=Math.max(...J),ot=y/fe*1000;return{averageTime:be,minTime:We,maxTime:Ve,totalTime:fe,throughput:ot}},middleware:async(p,y=1000)=>{let J=[],K=pt(),fe=ws(async()=>new Response("OK"));for(let at=0;at<y;at++){let dt=performance.now();await p(K,fe);let ut=performance.now();J.push(ut-dt)}let be=J.reduce((at,dt)=>at+dt,0),We=be/y,Ve=Math.min(...J),ot=Math.max(...J);return{averageTime:We,minTime:Ve,maxTime:ot,totalTime:be}},jsonSerialization:async(p,y=1e4)=>{let J=[];for(let ot=0;ot<y;ot++){let at=performance.now(),dt=JSON.stringify(p),ut=performance.now();J.push(ut-at)}let K=J.reduce((ot,at)=>ot+at,0),fe=K/y,be=Math.min(...J),We=Math.max(...J),Ve=JSON.stringify(p).length;return{averageTime:fe,minTime:be,maxTime:We,totalTime:K,dataSize:Ve}},routeMatching:async(p,y,J=1000)=>{let K=[],fe=0;for(let dt=0;dt<J;dt++){let ut=y[dt%y.length],lt=performance.now();if(p.find(($r)=>{let jn=$r.path.replace(/:\w+/g,"[^/]+");return new RegExp(`^${jn}$`).test(ut)}))fe++;let gt=performance.now();K.push(gt-lt)}let be=K.reduce((dt,ut)=>dt+ut,0),We=be/J,Ve=Math.min(...K),ot=Math.max(...K),at=fe/J;return{averageTime:We,minTime:Ve,maxTime:ot,totalTime:be,matchRate:at}}},xo={measureMemoryUsage:async(p,y=100)=>{let J=[],K=[];if(globalThis.gc)globalThis.gc();let fe=or.memoryUsage().heapUsed;for(let at=0;at<y;at++){let dt=await p();J.push(dt);let ut=or.memoryUsage();if(K.push(ut.heapUsed),at%10===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let be=or.memoryUsage().heapUsed,We=K.reduce((at,dt)=>at+dt,0)/K.length,Ve=Math.max(...K),ot=be-fe>1048576;return{averageHeapUsed:We,maxHeapUsed:Ve,memoryLeakDetected:ot,results:J}},testRouteHandlerMemoryLeaks:async(p,y=1000)=>{if(globalThis.gc)globalThis.gc();let J=or.memoryUsage().heapUsed;for(let We=0;We<y;We++){let Ve=pt();if(await p(Ve),We%100===0&&globalThis.gc)globalThis.gc()}if(globalThis.gc)globalThis.gc();let K=or.memoryUsage().heapUsed,fe=K-J;return{memoryLeakDetected:fe>5242880,initialMemory:J,finalMemory:K,memoryGrowth:fe}}},vo={rampUpTest:async(p,y,J)=>{let K=[],fe=10,be=J.testDuration/10,We=(J.endConcurrency-J.startConcurrency)/10;for(let Ve=0;Ve<10;Ve++){let ot=Math.round(J.startConcurrency+We*Ve),dt=await new cr(p,{duration:be,concurrency:ot,requestsPerSecond:ot*2}).run(y);K.push({concurrency:ot,requestsPerSecond:dt.requestsPerSecond,averageResponseTime:dt.averageResponseTime,errorRate:dt.failedRequests/dt.totalRequests})}return K},spikeTest:async(p,y,J)=>{let fe=await new cr(p,{duration:30000,concurrency:J.normalLoad}).run(y),We=await new cr(p,{duration:J.spikeDuration,concurrency:J.spikeLoad}).run(y),ot=await new cr(p,{duration:30000,concurrency:J.normalLoad}).run(y);return{normalPhase:fe,spikePhase:We,recoveryPhase:ot}}},Mo={responseTimeWithin:(p,y)=>{if(p>y)throw Error(`Response time ${p}ms exceeds maximum ${y}ms`)},throughputAtLeast:(p,y)=>{if(p<y)throw Error(`Throughput ${p} RPS is below minimum ${y} RPS`)},errorRateBelow:(p,y)=>{if(p>y)throw Error(`Error rate ${(p*100).toFixed(2)}% exceeds maximum ${(y*100).toFixed(2)}%`)},memoryUsageWithin:(p,y)=>{if(p>y)throw Error(`Memory usage ${(p/1024/1024).toFixed(2)}MB exceeds maximum ${(y/1024/1024).toFixed(2)}MB`)},noMemoryLeaks:(p,y=5242880)=>{if(p>y)throw Error(`Potential memory leak detected: ${(p/1024/1024).toFixed(2)}MB growth`)}};function Eo(){return new Un}function Co(p,y){return new cr(p,y)}var Fn={getCurrentMemoryUsage:()=>{let p=or.memoryUsage();return{heapUsed:p.heapUsed,heapTotal:p.heapTotal,external:p.external,rss:p.rss}},getCPUUsage:()=>{let p=or.cpuUsage();return{user:p.user,system:p.system}},createMetricSnapshot:(p)=>({responseTime:p,memoryUsage:Fn.getCurrentMemoryUsage(),cpuUsage:Fn.getCPUUsage()}),formatResults:(p)=>JSON.stringify(p,null,2)};class on{status;statusText;headers;body;text;json;cookies;redirected;url;ok;type;originalResponse;constructor(p,y){this.originalResponse=p,this.status=p.status,this.statusText=p.statusText,this.headers=this.parseHeaders(p.headers),this.cookies=this.parseCookies(p.headers.get("set-cookie")),this.redirected=p.redirected,this.url=p.url,this.ok=p.ok,this.type=p.type,this.body=y,this.text=typeof y==="string"?y:JSON.stringify(y);try{this.json=typeof y==="string"?JSON.parse(y):y}catch{this.json=null}}parseHeaders(p){let y={};return p.forEach((J,K)=>{y[K.toLowerCase()]=J}),y}parseCookies(p){if(!p)return{};let y={};return p.split(",").forEach((J)=>{let[K]=J.trim().split(";"),[fe,be]=K.split("=");if(fe&&be)y[fe.trim()]=be.trim()}),y}expectStatus(p){if(this.status!==p)throw Error(`Expected status ${p}, got ${this.status}`);return this}expectSuccess(){if(!this.ok)throw Error(`Expected successful response, got ${this.status}`);return this}expectHeader(p,y){let J=this.headers[p.toLowerCase()];if(J===void 0)throw Error(`Expected header '${p}' to be present`);if(y!==void 0&&J!==y)throw Error(`Expected header '${p}' to be '${y}', got '${J}'`);return this}expectBody(p){if(typeof p==="string"){if(this.text!==p)throw Error(`Expected body '${p}', got '${this.text}'`)}else if(JSON.stringify(this.json)!==JSON.stringify(p))throw Error(`Expected body ${JSON.stringify(p)}, got ${JSON.stringify(this.json)}`);return this}expectJson(p){if(JSON.stringify(this.json)!==JSON.stringify(p))throw Error(`Expected JSON ${JSON.stringify(p)}, got ${JSON.stringify(this.json)}`);return this}expectJsonContains(p){if(typeof this.json!=="object"||this.json===null)throw Error("Response is not a JSON object");return Object.entries(p).forEach(([y,J])=>{let K=this.json[y];if(typeof J==="object"&&J!==null&&typeof K==="object"&&K!==null){let fe=JSON.stringify(J),be=JSON.stringify(K);if(fe!==be)throw Error(`Expected JSON property '${y}' to be ${fe}, got ${be}`)}else if(K!==J)throw Error(`Expected JSON property '${y}' to be '${J}', got '${K}'`)}),this}expectCookie(p,y){let J=this.cookies[p];if(J===void 0)throw Error(`Expected cookie '${p}' to be present`);if(y!==void 0&&J!==y)throw Error(`Expected cookie '${p}' to be '${y}', got '${J}'`);return this}expectRedirect(p){if(this.status<300||this.status>=400)throw Error(`Expected redirect status (3xx), got ${this.status}`);if(p){let y=this.headers.location;if(y!==p)throw Error(`Expected redirect to '${p}', got '${y}'`)}return this}expectValidationError(p,y){if(this.status!==422)throw Error(`Expected validation error status (422), got ${this.status}`);if(p){let J=this.json?.errors||this.json?.message;if(!J||!J[p])throw Error(`Expected validation error for field '${p}'`);if(y){if(!(Array.isArray(J[p])?J[p]:[J[p]]).includes(y))throw Error(`Expected validation error message '${y}' for field '${p}'`)}}return this}expectContentType(p){let y=this.headers["content-type"];if(!y||!y.includes(p))throw Error(`Expected content type '${p}', got '${y}'`);return this}expectBodyContains(p){if(!this.text.includes(p))throw Error(`Expected body to contain '${p}'`);return this}expectBodyMatches(p){if(!p.test(this.text))throw Error(`Expected body to match pattern ${p}`);return this}expectJsonStructure(p){return this.validateStructure(this.json,p,"root"),this}validateStructure(p,y,J){if(y&&typeof y==="object"&&y.$$typeof)return;if(Array.isArray(y)){if(!Array.isArray(p))throw TypeError(`Expected ${J} to be an array`);if(y.length>0&&p.length>0)this.validateStructure(p[0],y[0],`${J}[0]`)}else if(typeof y==="object"&&y!==null){if(typeof p!=="object"||p===null)throw Error(`Expected ${J} to be an object`);Object.keys(y).forEach((K)=>{if(!(K in p))throw Error(`Expected ${J} to have property '${K}'`);this.validateStructure(p[K],y[K],`${J}.${K}`)})}}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 Dn(p){let y=await p.text();return new on(p,y)}function So(p=200,y,J){let K=new Headers(J);if(y&&typeof y==="object"&&!K.has("content-type"))K.set("content-type","application/json");let fe=new Response(y?typeof y==="string"?y:JSON.stringify(y):null,{status:p,headers:K});return new on(fe,y)}class Lr{router;config;defaultHeaders;constructor(p,y={}){this.router=p,this.config={baseUrl:"http://localhost:3000",timeout:5000,followRedirects:!0,validateStatus:(J)=>J>=200&&J<300,...y},this.defaultHeaders=y.defaultHeaders||{}}async get(p,y={}){return this.request("GET",p,y)}async post(p,y={}){return this.request("POST",p,y)}async put(p,y={}){return this.request("PUT",p,y)}async patch(p,y={}){return this.request("PATCH",p,y)}async delete(p,y={}){return this.request("DELETE",p,y)}async options(p,y={}){return this.request("OPTIONS",p,y)}async head(p,y={}){return this.request("HEAD",p,y)}async request(p,y,J={}){let K={...this.defaultHeaders,...J.headers},fe={...J,headers:K},be=new bt(p,y,fe).build();try{let We=await this.handleRequest(be);return await Dn(We)}catch(We){throw Error(`Test request failed: ${We instanceof Error?We.message:"Unknown error"}`)}}async handleRequest(p){let y=new URL(p.url),J=this.findMatchingRoute(p.method,y.pathname);if(!J)return new Response("Not Found",{status:404});let{route:K,params:fe}=J;p.params={...p.params,...fe};try{return await this.executeMiddlewareChain(p,K)||new Response("No response",{status:500})}catch(be){return new Response(JSON.stringify({error:be instanceof Error?be.message:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}findMatchingRoute(p,y){for(let J of this.router.routes){if(J.method.toLowerCase()!==p.toLowerCase())continue;let K=this.matchPath(J.path,y);if(K!==null)return{route:J,params:K}}return null}matchPath(p,y){let J=p.split("/"),K=y.split("/");if(J.length!==K.length)return null;let fe={};for(let be=0;be<J.length;be++){let We=J[be],Ve=K[be];if(We.startsWith(":")){let ot=We.slice(1);fe[ot]=Ve}else if(We!==Ve)return null}return fe}async executeMiddlewareChain(p,y){let J=[...this.router.globalMiddleware,...y.middleware],K=0,fe=async()=>{if(K<J.length){let We=J[K++];return await We(p,fe)}else return await this.executeHandler(y.handler,p)};return await fe()||new Response("No response",{status:500})}async executeHandler(p,y){if(typeof p==="function")return await p(y);else if(typeof p==="string")throw TypeError(`String handlers not supported in test environment: ${p}`);else if(typeof p==="object"&&p.handle)return await new p().handle(y);throw Error("Invalid handler type")}setDefaultHeaders(p){return this.defaultHeaders={...this.defaultHeaders,...p},this}auth(p,y="Bearer"){return this.defaultHeaders.Authorization=`${y} ${p}`,this}userAgent(p){return this.defaultHeaders["User-Agent"]=p,this}withConfig(p){return new Lr(this.router,{...this.config,...p})}withHeaders(p){return new Lr(this.router,{...this.config,defaultHeaders:{...this.defaultHeaders,...p}})}getRouter(){return this.router}getConfig(){return{...this.config}}}function jr(p,y){return new Lr(p,y)}var Oo={for:(p,y)=>jr(p,y),withConfig:(p)=>(y)=>jr(y,p),withAuth:(p,y="Bearer")=>(J)=>jr(J).auth(p,y),withHeaders:(p)=>(y)=>jr(y).withHeaders(p)};import{mock as ar}from"bun:test";class vt{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(p=1000,y="Normal closure"){return this.isConnected=!1,this.readyState=3,this.emit("close",{type:"close",code:p,reason:y}),this}send(p){if(!this.isConnected)throw Error("WebSocket is not connected");let y={type:typeof p==="string"?"text":"binary",data:p,timestamp:Date.now()};return this.messages.push(y),this}receive(p){if(!this.isConnected)throw Error("WebSocket is not connected");let y={type:typeof p==="string"?"text":"binary",data:p,timestamp:Date.now()};return this.emit("message",{type:"message",data:p}),this}ping(p){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("ping",{type:"ping",data:p}),this}pong(p){if(!this.isConnected)throw Error("WebSocket is not connected");return this.emit("pong",{type:"pong",data:p}),this}on(p,y){if(!this.eventHandlers.has(p))this.eventHandlers.set(p,[]);return this.eventHandlers.get(p).push(y),this}off(p,y){let J=this.eventHandlers.get(p);if(J){let K=J.indexOf(y);if(K>-1)J.splice(K,1)}return this}emit(p,y){(this.eventHandlers.get(p)||[]).forEach((K)=>K(y))}getSentMessages(){return[...this.messages]}getMessagesByType(p){return this.messages.filter((y)=>y.type===p)}clearMessages(){return this.messages=[],this}getState(){return{isConnected:this.isConnected,readyState:this.readyState}}getTestClient(){return{send:(p)=>this.send(p),close:(p,y)=>this.disconnect(p,y),ping:(p)=>this.ping(p),pong:(p)=>this.pong(p),messages:this.getSentMessages(),isConnected:this.isConnected,readyState:this.readyState}}}class Nn{tester;_data;constructor(p={}){this.tester=new vt,this._data=p}send(p){this.tester.send(p)}close(p,y){this.tester.disconnect(p,y)}ping(p){this.tester.ping(p)}pong(p){this.tester.pong(p)}publish(p,y){this.tester.send(y)}subscribe(p){}unsubscribe(p){}isSubscribed(p){return!0}cork(p){p()}get readyState(){return this.tester.getState().readyState}get data(){return this._data}set data(p){this._data=p}getTester(){return this.tester}}var $o={onOpen:()=>ar(async(p)=>{}),onMessage:(p)=>ar(async(y,J)=>{if(p)y.send(p)}),onClose:()=>ar(async(p,y,J)=>{}),onError:()=>ar(async(p,y)=>{}),echo:()=>ar(async(p,y)=>{p.send(y)}),broadcast:(p)=>ar(async(y,J)=>{p.forEach((K)=>{if(K!==y&&K.readyState===1)K.send(J)})}),chatRoom:(p)=>ar(async(y,J)=>{y.publish(p,J)})},Fo={basicConnection:()=>new vt().connect().send("Hello WebSocket").receive("Hello Client"),connectionFailure:()=>{let p=new vt;return p.on("error",()=>{}),p},messageBroadcast:(p=3)=>{let y=Array.from({length:p},()=>new vt().connect());return y[0].send("Broadcast message"),y.slice(1).forEach((J)=>J.receive("Broadcast message")),y},pingPong:()=>new vt().connect().ping().pong(),connectionTimeout:()=>{let p=new vt;return setTimeout(()=>{p.disconnect(1006,"Connection timeout")},100),p}},Uo={isConnected:(p)=>{if(!p.getState().isConnected)throw Error("Expected WebSocket to be connected")},isDisconnected:(p)=>{if(p.getState().isConnected)throw Error("Expected WebSocket to be disconnected")},messageSent:(p,y)=>{if(!p.getSentMessages().some((fe)=>{if(typeof y==="string"&&typeof fe.data==="string")return fe.data===y;return fe.data===y}))throw Error("Expected message not found in sent messages")},messageCount:(p,y)=>{let J=p.getSentMessages();if(J.length!==y)throw Error(`Expected ${y} messages, but got ${J.length}`)},messageType:(p,y,J)=>{let K=p.getSentMessages();if(y>=K.length)throw Error(`Message at index ${y} does not exist`);if(K[y].type!==J)throw Error(`Expected message type '${J}', got '${K[y].type}'`)},readyState:(p,y)=>{let J=p.getState();if(J.readyState!==y)throw Error(`Expected ready state ${y}, got ${J.readyState}`)}},Do={testThroughput:async(p=1000,y=1024)=>{let J=new vt().connect(),K="x".repeat(y),fe=performance.now();for(let at=0;at<p;at++)J.send(K);let We=performance.now()-fe,Ve=p/We*1000,ot=We/p;return{messagesPerSecond:Ve,totalTime:We,averageLatency:ot}},testConcurrentConnections:async(p=100)=>{let y={successfulConnections:0,failedConnections:0,averageConnectionTime:0},J=[],K=Array.from({length:p},async()=>{let fe=performance.now();try{new vt().connect();let We=performance.now();J.push(We-fe),y.successfulConnections++}catch(be){console.error("WebSocket connection failed:",be),y.failedConnections++}});return await Promise.all(K),y.averageConnectionTime=J.length>0?J.reduce((fe,be)=>fe+be,0)/J.length:0,y}};function No(){return new vt}function Io(p){return new Nn(p)}var _o={createClients:(p)=>Array.from({length:p},()=>new vt().connect()),withLatency:(p,y)=>{let J=p.send.bind(p);return p.send=(K)=>(setTimeout(()=>J(K),y),p),p},withPacketLoss:(p,y)=>{let J=p.send.bind(p);return p.send=(K)=>{if(Math.random()>y)J(K);return p},p},*messageGenerator(p,y="Message"){for(let J=1;J<=p;J++)yield`${y} ${J}`}};class an extends Error{status;response;body;constructor(p,y){let J=typeof y?.message==="string"?y.message:p.statusText||"Request failed";super(`${p.status} ${J}`);this.name="TypedClientError",this.status=p.status,this.response=p,this.body=y}}function In(p,y){if(!y)return p;let J=p;for(let[K,fe]of Object.entries(y)){let be=encodeURIComponent(fe);J=J.split(`{${K}}`).join(be),J=J.replace(new RegExp(`:${K}(?![A-Z0-9_])`,"gi"),be)}return J}function _n(p,y){if(!y)return p;let J=new URLSearchParams;for(let[fe,be]of Object.entries(y))if(be!==void 0&&be!==null)J.append(fe,String(be));let K=J.toString();if(!K)return p;return p.includes("?")?`${p}&${K}`:`${p}?${K}`}async function bs(p){if(p.status===204||p.headers.get("content-length")==="0")return;if((p.headers.get("content-type")??"").includes("json"))try{return await p.json()}catch{return}return await p.text()}function Ts(p){let y=p.baseUrl.replace(/\/+$/,""),J=p.fetch??globalThis.fetch;async function K(){if(typeof p.headers==="function")return await p.headers();return p.headers??{}}async function fe(be,We,Ve,ot,at){let dt=_n(`${y}${In(We,at?.params)}`,at?.query),ut={accept:"application/json",...await K(),...at?.headers};if(ot&&ut["content-type"]===void 0&&ut["Content-Type"]===void 0)ut["content-type"]="application/json";let lt=await J(dt,{method:be,headers:ut,...ot?{body:JSON.stringify(Ve)}:{},...p.credentials?{credentials:p.credentials}:{},...at?.signal?{signal:at.signal}:{}}),mt=await bs(lt);if(!lt.ok){let gt=new an(lt,mt);if(p.onError)return p.onError(gt);throw gt}return mt}return{get:(be,We)=>fe("GET",be,void 0,!1,We),post:(be,We,Ve)=>fe("POST",be,We,!0,Ve),put:(be,We,Ve)=>fe("PUT",be,We,!0,Ve),patch:(be,We,Ve)=>fe("PATCH",be,We,!0,Ve),delete:(be,We)=>fe("DELETE",be,void 0,!1,We),async raw(be,We,Ve){let{params:ot,query:at,...dt}=Ve??{},ut=_n(`${y}${In(We,ot)}`,at);return await J(ut,{method:be,...dt,headers:{...await K(),...dt.headers},...p.credentials?{credentials:p.credentials}:{}})}}}function xs(p){return p}export{un as ApiKeyManager,Wn as Auth,Br as AuthTester,ye as BindingBuilder,hs as BuiltInRules,Gs as CacheInvalidation,h as Container,O as ContentSecurityPolicy,_e as ContextualContainer,E as Cors,o as Csrf,I as DDoSProtection,Q as DEFAULT_COMPRESSION,di as DatabaseRules,ce as DatabaseSessionStore,ze as DefaultServiceProviderManager,rs as Dependencies,qr as DomainGroup,vn as DomainGroupBuilder,Rt as DomainMatcher,ee as ENRICHED_NOT_FOUND_RESPONSE,bi as EnhancementPresets,we as EnvironmentManager,gn as Errors,V as FileSecurity,oe as FileSessionStore,f as FileUpload,sr as FileUploadTester,sn as FileValidationTester,ct as FluentRouteBuilder,Or as FluentRouter,gs as GenericMockModel,W as Helmet,rt as InMemoryNonceStore,F as InputValidation,dn as JWT,rn as JWTTester,P as JsonBody,cr as LoadTester,w as MemorySessionStore,An as MiddlewareChainTester,ns as MiddlewareFactory,en as MiddlewareGroupRegistry,kn as MiddlewareHelpers,Kr as MiddlewarePipeline,On as MiddlewareTester,ys as MockPostClass,Nn as MockServerWebSocket,fs as MockUserClass,Bn as ModelBindingTester,$n as ModelResolverTester,cn as OAuth2Helper,ue as PerformanceAlerting,de as PerformanceDashboard,pe as PerformanceMonitor,Un as PerformanceTester,ie as RateLimit,Je as RateLimitRegistry,gr as RateLimitUtils,te as RateLimiter,ae as RedisSessionStore,M as RequestId,k as RequestSigning,he as RequestTracer,Z as ResponseBuilder,ft as RouteBuilder,xn as RouteCacheFactory,wn as RouteCacheKeyGenerator,bn as RouteCacheManager,as as RouteFactory,Mn as RouteGroupBuilder,Ri as RouteHelpers,n as Router,ds as RouterUtils,N as Security,me as SecuritySuite,A as Session,Pe as SessionManager,nn as SessionTester,a as SignatureError,ts as SkipConditions,Ks as SubdomainPatterns,Xr as SubdomainRouter,zs as SubdomainUtils,Lr as TestClient,bt as TestRequestBuilder,on as TestResponseWrapper,St as ThrottleFactory,an as TypedClientError,Hn as ValidationFluentRouter,li as ValidationHelpers,qn as ValidationMiddlewareBuilder,Zr as ValidationRuleBuilder,Ir as Validator,vt as WebSocketTester,Nt as apiKeyAuth,U as appendVary,se as applyRequestEnhancements,m as applyResponseCompression,kr as auth,Ii as authHelpers,Ni as authMocks,Ot as basicAuth,It as bearerAuth,oo as benchmarkMiddleware,To as benchmarkTests,yr as buildUrlWithPreservedParams,Pt as clearNamedRoutes,mr as compressResponse,e as config,po as constraintHelpers,jt as contentSecurityPolicy,Cr as cors,_i as createAuthTester,it as createContainer,X as createCookieAccessor,Yr as createEnhancementMiddleware,Xi as createFileUploadTester,wi as createFluentRouter,Ct as createHandlerResolver,x as createInMemoryCookieAccessor,ji as createJWTTester,Co as createLoadTester,io as createMiddlewareSpy,pt as createMockRequest,So as createMockResponse,Io as createMockServerWebSocket,mo as createModelBindingTester,go as createModelResolverTester,Rr as createPathRegex,Eo as createPerformanceTester,C as createRateLimitMiddleware,Tn as createRouteCacheMiddleware,Tr as createSessionStore,Li as createSessionTester,Vs as createSubdomainMiddleware,jr as createTestClient,Dn as createTestResponse,Ts as createTypedClient,Ce as createTypedRouter,_r as createValidationMiddleware,No as createWebSocketTester,Mr as csrf,Ut as ddosProtection,v as decodeParam,Ze as defaultConfig,fr as defaultQueryPreservationConfig,xs as defineEndpoint,Wt as documentUpload,Re as enableRequestContext,tt as extractApiKey,et as extractBasicAuth,Se as extractBearerToken,ne as extractParamNames,Ye as fileExists,Lt as fileUpload,Ki as fileUploadAssertions,Vi as fileUploadMocks,zi as fileUploadScenarios,kt as generateQueryPreservationScript,le as generateSessionId,xr as getConfig,nt as getContainer,Y as getCurrentRequest,xe as getNamedRoutePath,Et as getNamedRoutes,ss as globalMiddlewarePipeline,ui as globalValidator,Vt as imageUpload,re as injectQueryPreservationScript,Gt as inputValidation,$t as isActionClass,Ge as isCompressible,br as isRouteHandler,u as joinPaths,Sr as jsonBody,Ft as jwtAuth,l as matchPath,xo as memoryTests,Me as middleware,yt as middlewareGroups,ro as mockMiddleware,lo as modelMocks,zt as multipleFileUpload,pr as negotiateEncoding,z as normalizePath,Dt as oauth2Auth,S as parseThrottleString,Tt as peekBody,xt as peekedStream,Kt as performanceAlerting,Mo as performanceAssertions,Jt as performanceDashboard,Xt as performanceMonitor,Fn as performanceUtils,Qe as processHtmlTemplate,Ee as rateLimit,Xe as rateLimitRegistry,g as registerNamedRoute,ve as request,Er as requestId,qt as requestSigning,Yt as requestTracer,L as resolveHandler,Te as resolveViewPath,r as response,Ke as responseBuilder,ur as routeCacheManager,ho as routeModelHelpers,us as router,ci as rule,B as runWithRequest,j as runWithRequestArguments,fo as scopedBindingHelpers,Qt as security,Zt as securitySuite,Pr as session,st as setContainer,T as setCurrentRequest,hr as shouldCompress,Ht as signRequest,_t as singleFileUpload,so as spyOnMiddleware,vo as stressTests,Oo as testClient,Qi as testFiles,to as testMiddleware,no as testMiddlewareChain,Bi as testRequest,wr as toActionPath,Mt as url,yi as validate,vr as validatePath,Bt as verifySignature,s as wrapResponse,Uo as wsAssertions,$o as wsHandlerMocks,Do as wsPerformance,Fo as wsTestScenarios,_o as wsTestUtils};
|