@stacksjs/bun-router 0.1.14 → 0.1.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{J}from"./chunk-7s1kcj7w.js";import g from"process";import{CLI as ue}from"@stacksjs/clapp";var F="0.1.
|
|
3
|
+
import{J}from"./chunk-7s1kcj7w.js";import g from"process";import{CLI as ue}from"@stacksjs/clapp";var F="0.1.15";import f from"fs/promises";import I from"path";import T from"process";var p={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"},o={red:(e)=>`${p.red}${e}${p.reset}`,green:(e)=>`${p.green}${e}${p.reset}`,yellow:(e)=>`${p.yellow}${e}${p.reset}`,blue:(e)=>`${p.blue}${e}${p.reset}`,cyan:(e)=>`${p.cyan}${e}${p.reset}`,white:(e)=>`${p.white}${e}${p.reset}`,gray:(e)=>`${p.gray}${e}${p.reset}`,bold:(e)=>`${p.bold}${e}${p.reset}`,dim:(e)=>`${p.dim}${e}${p.reset}`,hex:(e)=>(t)=>t};async function v(e){let t=Object.entries(J).map(([n,c])=>({name:n,className:c.constructor.name})),r=`/**
|
|
4
4
|
* This file is auto-generated.
|
|
5
5
|
* DO NOT EDIT THIS FILE DIRECTLY.
|
|
6
6
|
* To update, run 'bun router middleware:types'
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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 Or(o){return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function pr(o){o=o.replace(/-/g,"+").replace(/_/g,"/");while(o.length%4)o+="=";return atob(o)}class an{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=Or(JSON.stringify(M)),pe=Or(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(pr(k)),he=JSON.parse(pr(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(pr(M)),payload:JSON.parse(pr(k))}}catch{return null}}createSignature(o,l,M){return Or(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 un{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 cn{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 Us={JWT:an,ApiKeyManager:un,OAuth2Helper:cn},Is=Us;var gn={};qe(gn,{AuthenticationException:()=>X,AuthorizationException:()=>Y,BugsnagReporter:()=>Dr,BusinessLogicException:()=>se,CircuitBreaker:()=>hr,CircuitBreakerHttpClient:()=>ln,CircuitBreakerOpenException:()=>C,CircuitBreakerPresets:()=>Ls,CircuitBreakerRegistry:()=>It,CircularDependencyException:()=>p,ConfigurationException:()=>ie,CustomReporter:()=>dn,DatabaseException:()=>ne,DegradationStrategies:()=>Ks,ErrorFactory:()=>i,ErrorReportingManager:()=>Xt,ErrorReportingPresets:()=>Vs,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:()=>Br,ServiceHealthMonitor:()=>Nr,ServiceUnavailableException:()=>re,TimeoutException:()=>x,ValidationException:()=>d,circuitBreaker:()=>_s,createAdvancedErrorHandler:()=>hn,createCircuitBreaker:()=>zs,createCircuitBreakerMiddleware:()=>js,createErrorReporting:()=>Ws,createGracefulDegradationMiddleware:()=>Js,detectRouteConflicts:()=>at,findSimilarRoutes:()=>ot,globalCircuitBreakerRegistry:()=>$r,withCircuitBreaker:()=>Gs});class hr{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 hr(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 _s(o){let l=new hr(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 ln{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 js(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 Ls={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}})},$r=new It;function zs(o){return $r.register(o)}async function Gs(o,l){return $r.execute(o,l)}class Br{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 Dr{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 dn{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 Br(l));break;case"bugsnag":this.reporters.push(new Dr(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 Ws(o){return new Xt(o)}var Vs={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 Nr{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 Nr(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 Js(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 Ks={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 pn{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 hn(o={}){let l=new pn(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 gr(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 gr({read:()=>l,write:(M,k)=>{l[M]=k},remove:(M)=>{delete l[M]}})}import{AsyncLocalStorage as Xs}from"async_hooks";var mr=new Xs,Zt=!1,ht=null;function Qs(){Zt=!0}function Fr(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 mr.run({current:o},l)}function Ur(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 mr.run({current:o},l,M,k)}function fr(o){let l=mr.getStore();if(l){l.current=o;return}if(ht!==null)ht=o}function mn(){if(!Zt)return Zt=!0,ht??void 0;return mr.getStore()?.current??ht??void 0}function Zs(){let o=mn();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 fn={enabled:!0,level:6,threshold:1024};function Rn(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 _o(o){return yn(o).encoding}function yn(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(!Rn(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??fn.enabled))return o;let L=o.headers;if(L.has("content-encoding"))return o;let V=M.threshold??fn.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}=yn(pe),Pe=Rn(L.get("content-type"))&&o.status!==206;if(!ve&&o.status!==204&&o.status!==304&&o.body){if(!xe||!Pe)return Ys(o);return Ir(o,o.body,xe)}if(!xe||Te||!Pe||o.status===204||o.status===304||!o.body){if(o.status!==204)Yt(L,"Accept-Encoding");return o}if(!Number.isFinite(he))return ei(o,xe,V);return Ir(o,o.body,xe)}function Ys(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 Lo(o,l,M={}){return $t(o,l,M)}async function ei(o,l,M){let k=await ti(o.body,M);if(k.ended&&k.size<M){let L=new Headers(o.headers);return Yt(L,"Accept-Encoding"),new Response(k.stream,{status:o.status,statusText:o.statusText,headers:L})}return Ir(o,k.stream,l)}function Ir(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})}async function ti(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}return{stream:new ReadableStream({start(he){for(let Te of k)he.enqueue(Te);if(V)he.close()},async pull(he){if(V)return;let{value:Te,done:xe}=await M.read();if(xe){V=!0,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}`)}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 new Response(pe,{status:k,headers:{"Content-Type":"application/json",...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={})=>new Response(o,{status:l,headers:{"Content-Type":"text/html; charset=utf-8",...M}}),text:(o,l=200,M={})=>new Response(o,{status:l,headers:{"Content-Type":"text/plain; charset=utf-8",...M}}),xml:(o,l=200,M={})=>new Response(o,{status:l,headers:{"Content-Type":"application/xml; charset=utf-8",...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 new Response(JSON.stringify({message:o}),{status:429,headers:{"Content-Type":"application/json",...M}})}};class wn{_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 Go(){return new wn}import ri from"process";class _r{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 ni={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=ri.env.NODE_ENV||"development";return o.includes(l)}})},si={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})},ii={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}},oi=new _r;import{existsSync as Tn,readdirSync as ai,statSync as ui}from"fs";import{basename as xn,extname as bn,join as ci,resolve as vn}from"path";var li=[".ts",".js"],di=["routes","src/routes"],pi=["web","index"];function hi(){let o=process.cwd();for(let l of di){let M=vn(o,l);if(Tn(M)&&ui(M).isDirectory())return M}return null}function Pn(o,l){let M=[];if(!Tn(o))return M;let k=ai(o,{withFileTypes:!0});for(let L of k){if(L.name.startsWith(".")||L.name.startsWith("_"))continue;let V=ci(o,L.name);if(L.isDirectory())M.push(...Pn(V,l));else if(li.includes(bn(L.name))){let pe=o===l?"":o.slice(l.length),he=xn(L.name,bn(L.name)),Te=pi.includes(he)?pe||"":`${pe}/${he}`;M.push({filePath:V,prefix:Te})}}return M}async function gi(o,l,M,k){try{let L=await import(l),V=0,pe=o.routes?.length||0;if(typeof L.default==="function"){let he=mi(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 ${xn(l)} (${V} routes)`);return V}catch(L){return console.error(`[bun-router] Failed to load route file ${l}:`,L),0}}function mi(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 Cn(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||hi();if(!l){this._apiRoutesInitialized=!0;return}let M=this.config?.verbose||!1,k=Pn(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 gi(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=vn(l),this},writable:!0,configurable:!0}})}import{join as er,relative as jr,resolve as Et,dirname as Ri}from"path";import{readdirSync as Mn,statSync as yi,existsSync as yr}from"fs";var Zo={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function fi(o){let{preserve:l=[],exclude:M=[],routes:k=[]}=o;if(!l.length)return"";return`<script data-query-preservation>
|
|
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 Or(o){return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function pr(o){o=o.replace(/-/g,"+").replace(/_/g,"/");while(o.length%4)o+="=";return atob(o)}class an{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=Or(JSON.stringify(M)),pe=Or(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(pr(k)),he=JSON.parse(pr(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(pr(M)),payload:JSON.parse(pr(k))}}catch{return null}}createSignature(o,l,M){return Or(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 un{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 cn{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 Us={JWT:an,ApiKeyManager:un,OAuth2Helper:cn},Is=Us;var gn={};qe(gn,{AuthenticationException:()=>X,AuthorizationException:()=>Y,BugsnagReporter:()=>Dr,BusinessLogicException:()=>se,CircuitBreaker:()=>hr,CircuitBreakerHttpClient:()=>ln,CircuitBreakerOpenException:()=>C,CircuitBreakerPresets:()=>Ls,CircuitBreakerRegistry:()=>It,CircularDependencyException:()=>p,ConfigurationException:()=>ie,CustomReporter:()=>dn,DatabaseException:()=>ne,DegradationStrategies:()=>Ks,ErrorFactory:()=>i,ErrorReportingManager:()=>Xt,ErrorReportingPresets:()=>Vs,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:()=>Br,ServiceHealthMonitor:()=>Nr,ServiceUnavailableException:()=>re,TimeoutException:()=>x,ValidationException:()=>d,circuitBreaker:()=>_s,createAdvancedErrorHandler:()=>hn,createCircuitBreaker:()=>zs,createCircuitBreakerMiddleware:()=>js,createErrorReporting:()=>Ws,createGracefulDegradationMiddleware:()=>Js,detectRouteConflicts:()=>at,findSimilarRoutes:()=>ot,globalCircuitBreakerRegistry:()=>$r,withCircuitBreaker:()=>Gs});class hr{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 hr(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 _s(o){let l=new hr(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 ln{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 js(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 Ls={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}})},$r=new It;function zs(o){return $r.register(o)}async function Gs(o,l){return $r.execute(o,l)}class Br{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 Dr{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 dn{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 Br(l));break;case"bugsnag":this.reporters.push(new Dr(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 Ws(o){return new Xt(o)}var Vs={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 Nr{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 Nr(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 Js(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 Ks={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 pn{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 hn(o={}){let l=new pn(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 gr(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 gr({read:()=>l,write:(M,k)=>{l[M]=k},remove:(M)=>{delete l[M]}})}import{AsyncLocalStorage as Xs}from"async_hooks";var mr=new Xs,Zt=!1,ht=null;function Qs(){Zt=!0}function Fr(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 mr.run({current:o},l)}function Ur(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 mr.run({current:o},l,M,k)}function fr(o){let l=mr.getStore();if(l){l.current=o;return}if(ht!==null)ht=o}function mn(){if(!Zt)return Zt=!0,ht??void 0;return mr.getStore()?.current??ht??void 0}function Zs(){let o=mn();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 fn={enabled:!0,level:6,threshold:1024};function Rn(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 _o(o){return yn(o).encoding}function yn(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(!Rn(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??fn.enabled))return o;let L=o.headers;if(L.has("content-encoding"))return o;if(o.status===204)return o;let V=M.threshold??fn.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}=yn(pe),Pe=Rn(L.get("content-type"))&&o.status!==206;if(!ve&&o.status!==304&&o.body){if(!xe||!Pe)return Ys(o);return Ir(o,o.body,xe)}if(!xe||Te||!Pe||o.status===304||!o.body)return Yt(L,"Accept-Encoding"),o;if(!Number.isFinite(he))return ei(o,xe,V);return Ir(o,o.body,xe)}function Ys(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 Lo(o,l,M={}){return $t(o,l,M)}async function ei(o,l,M){let k=await ti(o.body,M);if(k.ended&&k.size<M){let L=new Headers(o.headers);return Yt(L,"Accept-Encoding"),new Response(k.stream,{status:o.status,statusText:o.statusText,headers:L})}return Ir(o,k.stream,l)}function Ir(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})}async function ti(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}return{stream:new ReadableStream({start(he){for(let Te of k)he.enqueue(Te);if(V)he.close()},async pull(he){if(V)return;let{value:Te,done:xe}=await M.read();if(xe){V=!0,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}`)}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 new Response(pe,{status:k,headers:{"Content-Type":"application/json",...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={})=>new Response(o,{status:l,headers:{"Content-Type":"text/html; charset=utf-8",...M}}),text:(o,l=200,M={})=>new Response(o,{status:l,headers:{"Content-Type":"text/plain; charset=utf-8",...M}}),xml:(o,l=200,M={})=>new Response(o,{status:l,headers:{"Content-Type":"application/xml; charset=utf-8",...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 new Response(JSON.stringify({message:o}),{status:429,headers:{"Content-Type":"application/json",...M}})}};class wn{_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 Go(){return new wn}import ri from"process";class _r{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 ni={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=ri.env.NODE_ENV||"development";return o.includes(l)}})},si={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})},ii={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}},oi=new _r;import{existsSync as Tn,readdirSync as ai,statSync as ui}from"fs";import{basename as xn,extname as bn,join as ci,resolve as vn}from"path";var li=[".ts",".js"],di=["routes","src/routes"],pi=["web","index"];function hi(){let o=process.cwd();for(let l of di){let M=vn(o,l);if(Tn(M)&&ui(M).isDirectory())return M}return null}function Pn(o,l){let M=[];if(!Tn(o))return M;let k=ai(o,{withFileTypes:!0});for(let L of k){if(L.name.startsWith(".")||L.name.startsWith("_"))continue;let V=ci(o,L.name);if(L.isDirectory())M.push(...Pn(V,l));else if(li.includes(bn(L.name))){let pe=o===l?"":o.slice(l.length),he=xn(L.name,bn(L.name)),Te=pi.includes(he)?pe||"":`${pe}/${he}`;M.push({filePath:V,prefix:Te})}}return M}async function gi(o,l,M,k){try{let L=await import(l),V=0,pe=o.routes?.length||0;if(typeof L.default==="function"){let he=mi(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 ${xn(l)} (${V} routes)`);return V}catch(L){return console.error(`[bun-router] Failed to load route file ${l}:`,L),0}}function mi(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 Cn(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||hi();if(!l){this._apiRoutesInitialized=!0;return}let M=this.config?.verbose||!1,k=Pn(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 gi(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=vn(l),this},writable:!0,configurable:!0}})}import{join as er,relative as jr,resolve as Et,dirname as Ri}from"path";import{readdirSync as Mn,statSync as yi,existsSync as yr}from"fs";var Zo={enabled:!0,preserve:[],exclude:["_t","_cache","callback"],routes:[]};function fi(o){let{preserve:l=[],exclude:M=[],routes:k=[]}=o;if(!l.length)return"";return`<script data-query-preservation>
|
|
3
3
|
(function(){
|
|
4
4
|
var preserve = ${JSON.stringify(l)};
|
|
5
5
|
var exclude = ${JSON.stringify(M)};
|