yinzerflow 0.6.12 → 0.6.14

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/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.6.14] - 2026-02-20
4
+
5
+ ### Bug Fixes
6
+
7
+ - **Use correct API key environment variable** — Fixed publish script to reference the proper API key environment variable for changelog generation (c4f420c)
8
+
9
+ ### Internal
10
+
11
+ - **Enhance preflight checks in publish script** — Refactored preflight validation logic to improve robustness of the publish process (09ad711)
12
+ - **Require API key for changelog generation** — Updated publish configuration to enforce API key presence when generating changelogs (04bfd70)
13
+
14
+ ## [0.6.13] - 2026-02-20
15
+
16
+ - ``` 🔧 chore: update progress to Phase 2 (7a55239)
17
+ - ♻️ refactor(hook-registry): fix typo in error log (057a458)
18
+ - ♻️ refactor(request-response-handling): optimize headers (a133d7c)
19
+
3
20
  All notable changes to YinzerFlow will be documented in this file.
4
21
 
5
22
  ## [0.6.12] - 2026-02-20
package/index.js CHANGED
@@ -1,23 +1,19 @@
1
- var b1=Object.create;var{getPrototypeOf:k1,defineProperty:s$,getOwnPropertyNames:C1}=Object;var x1=Object.prototype.hasOwnProperty;var q$=($,W,Z)=>{Z=$!=null?b1(k1($)):{};let Y=W||!$||!$.__esModule?s$(Z,"default",{value:$,enumerable:!0}):Z;for(let Q of C1($))if(!x1.call(Y,Q))s$(Y,Q,{get:()=>$[Q],enumerable:!0});return Y};var y1=($,W)=>()=>(W||$((W={exports:{}}).exports,W),W.exports);var Y$=y1((w$,N$)=>{(function($,W){typeof w$=="object"&&typeof N$<"u"?N$.exports=W():typeof define=="function"&&define.amd?define(W):($=typeof globalThis<"u"?globalThis:$||self).dayjs=W()})(w$,function(){var $=1000,W=60000,Z=3600000,Y="millisecond",Q="second",X="minute",J="hour",M="day",F="week",w="month",_="quarter",V="year",H="date",e="Invalid Date",L1=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,R1=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,v1={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(q){var j=["th","st","nd","rd"],D=q%100;return"["+q+(j[(D-20)%10]||j[D]||j[0])+"]"}},G$=function(q,j,D){var G=String(q);return!G||G.length>=j?q:""+Array(j+1-G.length).join(D)+q},P1={s:G$,z:function(q){var j=-q.utcOffset(),D=Math.abs(j),G=Math.floor(D/60),K=D%60;return(j<=0?"+":"-")+G$(G,2,"0")+":"+G$(K,2,"0")},m:function q(j,D){if(j.date()<D.date())return-q(D,j);var G=12*(D.year()-j.year())+(D.month()-j.month()),K=j.clone().add(G,w),N=D-K<0,B=j.clone().add(G+(N?-1:1),w);return+(-(G+(D-K)/(N?K-B:B-K))||0)},a:function(q){return q<0?Math.ceil(q)||0:Math.floor(q)},p:function(q){return{M:w,y:V,w:F,d:M,D:H,h:J,m:X,s:Q,ms:Y,Q:_}[q]||String(q||"").toLowerCase().replace(/s$/,"")},u:function(q){return q===void 0}},d="en",h={};h[d]=v1;var g$="$isDayjsObject",F$=function(q){return q instanceof W$||!(!q||!q[g$])},$$=function q(j,D,G){var K;if(!j)return d;if(typeof j=="string"){var N=j.toLowerCase();h[N]&&(K=N),D&&(h[N]=D,K=N);var B=j.split("-");if(!K&&B.length>1)return q(B[0])}else{var A=j.name;h[A]=j,K=A}return!G&&K&&(d=K),K||!G&&d},T=function(q,j){if(F$(q))return q.clone();var D=typeof j=="object"?j:{};return D.date=q,D.args=arguments,new W$(D)},O=P1;O.l=$$,O.i=F$,O.w=function(q,j){return T(q,{locale:j.$L,utc:j.$u,x:j.$x,$offset:j.$offset})};var W$=function(){function q(D){this.$L=$$(D.locale,null,!0),this.parse(D),this.$x=this.$x||D.x||{},this[g$]=!0}var j=q.prototype;return j.parse=function(D){this.$d=function(G){var{date:K,utc:N}=G;if(K===null)return new Date(NaN);if(O.u(K))return new Date;if(K instanceof Date)return new Date(K);if(typeof K=="string"&&!/Z$/i.test(K)){var B=K.match(L1);if(B){var A=B[2]-1||0,z=(B[7]||"0").substring(0,3);return N?new Date(Date.UTC(B[1],A,B[3]||1,B[4]||0,B[5]||0,B[6]||0,z)):new Date(B[1],A,B[3]||1,B[4]||0,B[5]||0,B[6]||0,z)}}return new Date(K)}(D),this.init()},j.init=function(){var D=this.$d;this.$y=D.getFullYear(),this.$M=D.getMonth(),this.$D=D.getDate(),this.$W=D.getDay(),this.$H=D.getHours(),this.$m=D.getMinutes(),this.$s=D.getSeconds(),this.$ms=D.getMilliseconds()},j.$utils=function(){return O},j.isValid=function(){return this.$d.toString()!==e},j.isSame=function(D,G){var K=T(D);return this.startOf(G)<=K&&K<=this.endOf(G)},j.isAfter=function(D,G){return T(D)<this.startOf(G)},j.isBefore=function(D,G){return this.endOf(G)<T(D)},j.$g=function(D,G,K){return O.u(D)?this[G]:this.set(K,D)},j.unix=function(){return Math.floor(this.valueOf()/1000)},j.valueOf=function(){return this.$d.getTime()},j.startOf=function(D,G){var K=this,N=!!O.u(G)||G,B=O.p(D),A=function(m,v){var y=O.w(K.$u?Date.UTC(K.$y,v,m):new Date(K.$y,v,m),K);return N?y:y.endOf(M)},z=function(m,v){return O.w(K.toDate()[m].apply(K.toDate("s"),(N?[0,0,0,0]:[23,59,59,999]).slice(v)),K)},S=this.$W,R=this.$M,P=this.$D,l="set"+(this.$u?"UTC":"");switch(B){case V:return N?A(1,0):A(31,11);case w:return N?A(1,R):A(0,R+1);case F:var u=this.$locale().weekStart||0,s=(S<u?S+7:S)-u;return A(N?P-s:P+(6-s),R);case M:case H:return z(l+"Hours",0);case J:return z(l+"Minutes",1);case X:return z(l+"Seconds",2);case Q:return z(l+"Milliseconds",3);default:return this.clone()}},j.endOf=function(D){return this.startOf(D,!1)},j.$set=function(D,G){var K,N=O.p(D),B="set"+(this.$u?"UTC":""),A=(K={},K[M]=B+"Date",K[H]=B+"Date",K[w]=B+"Month",K[V]=B+"FullYear",K[J]=B+"Hours",K[X]=B+"Minutes",K[Q]=B+"Seconds",K[Y]=B+"Milliseconds",K)[N],z=N===M?this.$D+(G-this.$W):G;if(N===w||N===V){var S=this.clone().set(H,1);S.$d[A](z),S.init(),this.$d=S.set(H,Math.min(this.$D,S.daysInMonth())).$d}else A&&this.$d[A](z);return this.init(),this},j.set=function(D,G){return this.clone().$set(D,G)},j.get=function(D){return this[O.p(D)]()},j.add=function(D,G){var K,N=this;D=Number(D);var B=O.p(G),A=function(R){var P=T(N);return O.w(P.date(P.date()+Math.round(R*D)),N)};if(B===w)return this.set(w,this.$M+D);if(B===V)return this.set(V,this.$y+D);if(B===M)return A(1);if(B===F)return A(7);var z=(K={},K[X]=W,K[J]=Z,K[Q]=$,K)[B]||1,S=this.$d.getTime()+D*z;return O.w(S,this)},j.subtract=function(D,G){return this.add(-1*D,G)},j.format=function(D){var G=this,K=this.$locale();if(!this.isValid())return K.invalidDate||e;var N=D||"YYYY-MM-DDTHH:mm:ssZ",B=O.z(this),A=this.$H,z=this.$m,S=this.$M,R=K.weekdays,P=K.months,l=K.meridiem,u=function(v,y,c,Z$){return v&&(v[y]||v(G,N))||c[y].slice(0,Z$)},s=function(v){return O.s(A%12||12,v,"0")},m=l||function(v,y,c){var Z$=v<12?"AM":"PM";return c?Z$.toLowerCase():Z$};return N.replace(R1,function(v,y){return y||function(c){switch(c){case"YY":return String(G.$y).slice(-2);case"YYYY":return O.s(G.$y,4,"0");case"M":return S+1;case"MM":return O.s(S+1,2,"0");case"MMM":return u(K.monthsShort,S,P,3);case"MMMM":return u(P,S);case"D":return G.$D;case"DD":return O.s(G.$D,2,"0");case"d":return String(G.$W);case"dd":return u(K.weekdaysMin,G.$W,R,2);case"ddd":return u(K.weekdaysShort,G.$W,R,3);case"dddd":return R[G.$W];case"H":return String(A);case"HH":return O.s(A,2,"0");case"h":return s(1);case"hh":return s(2);case"a":return m(A,z,!0);case"A":return m(A,z,!1);case"m":return String(z);case"mm":return O.s(z,2,"0");case"s":return String(G.$s);case"ss":return O.s(G.$s,2,"0");case"SSS":return O.s(G.$ms,3,"0");case"Z":return B}return null}(v)||B.replace(":","")})},j.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},j.diff=function(D,G,K){var N,B=this,A=O.p(G),z=T(D),S=(z.utcOffset()-this.utcOffset())*W,R=this-z,P=function(){return O.m(B,z)};switch(A){case V:N=P()/12;break;case w:N=P();break;case _:N=P()/3;break;case F:N=(R-S)/604800000;break;case M:N=(R-S)/86400000;break;case J:N=R/Z;break;case X:N=R/W;break;case Q:N=R/$;break;default:N=R}return K?N:O.a(N)},j.daysInMonth=function(){return this.endOf(w).$D},j.$locale=function(){return h[this.$L]},j.locale=function(D,G){if(!D)return this.$L;var K=this.clone(),N=$$(D,G,!0);return N&&(K.$L=N),K},j.clone=function(){return O.w(this.$d,this)},j.toDate=function(){return new Date(this.valueOf())},j.toJSON=function(){return this.isValid()?this.toISOString():null},j.toISOString=function(){return this.$d.toISOString()},j.toString=function(){return this.$d.toUTCString()},q}(),d$=W$.prototype;return T.prototype=d$,[["$ms",Y],["$s",Q],["$m",X],["$H",J],["$W",M],["$M",w],["$y",V],["$D",H]].forEach(function(q){d$[q[1]]=function(j){return this.$g(j,q[0],q[1])}}),T.extend=function(q,j){return q.$i||(q(j,W$,T),q.$i=!0),T},T.locale=$$,T.isDayjs=F$,T.unix=function(q){return T(1000*q)},T.en=h[d],T.Ls=h,T.p={},T})});import{createServer as V2}from"net";var V$=q$(Y$(),1);var c$=q$(Y$(),1);var E={reset:"\x1B[0m",cyan:"\x1B[96m",yellow:"\x1B[93m",red:"\x1B[91m",green:"\x1B[92m",magenta:"\x1B[95m",gray:"\x1B[90m"};var r={off:"off",error:"error",warn:"warn",info:"info"};var p={off:0,error:1,warn:2,info:3},h1={positive:["n'at!","yinz are good!","that's the way!","right on!","lookin' good!","way to go!","keep it up!"],neutral:["n'at","yinz know","just sayin'","that's how it is","what can ya do","it happens"],negative:["aw jeez","that ain't right","what a jagoff move","that's terrible n'at","somebody messed up","this is bad news","yinz better fix this"]},Q$=($)=>{let W=h1[$];return W[Math.floor(Math.random()*W.length)]??""},r$=()=>c$.default().format("YYYY-MM-DD HH:mm:ss.SSS"),B$=($,W,...Z)=>{let Y=r$(),Q=E.reset;if(W==="NETWORK")Q=E.gray;if($==="error"){let J=`${E.red}[${W}] ❌ [${Y}] [ERROR]${E.reset}`;console.error(`${J}`,`${Q}`,...Z,`${E.reset} - ${Q$("negative")}`);return}if($==="warn"){let J=`${E.yellow}[${W}] ⚠️ [${Y}] [WARN]${E.reset}`;console.warn(`${J}`,`${Q}`,...Z,`${E.reset} - ${Q$("neutral")}`);return}if($==="off")return;let X=`${E.cyan}[${W}] ✅ [${Y}] [INFO]${E.reset}`;console.info(`${X}`,`${Q}`,...Z,`${E.reset} - ${Q$("positive")}`)},u1=($,W,...Z)=>{let Y=r$(),Q=`${E.magenta}[${$}] \uD83D\uDCCA [${Y}] [TABLE]${E.reset}`;if(console.log(`${Q} - ${Q$("positive")}`),console.table(W),Z.length>0)console.log(`${E.gray}Additional context:${E.reset}`,...Z)},a=($)=>{let W={logLevel:$?.logLevel??r.info,prefix:$?.prefix??"YINZER",logger:$?.logger??null},Z=(M)=>p[M]??p.info;return{info:(...M)=>{if(Z(W.logLevel)<p.info)return;if(W.logger){W.logger.info(...M);return}B$("info",W.prefix,...M)},warn:(...M)=>{if(Z(W.logLevel)<p.warn)return;if(W.logger){W.logger.warn(...M);return}B$("warn",W.prefix,...M)},error:(...M)=>{if(Z(W.logLevel)<p.error)return;if(W.logger){W.logger.error(...M);return}B$("error",W.prefix,...M)},table:(M,...F)=>{if(Z(W.logLevel)<p.info)return;if(W.logger){W.logger.info("TABLE:",M,...F);return}u1(W.prefix,M,...F)},levels:p}},U=a();class E${setup;constructor($){this.setup=$}async handle($){try{if(await this._handleBeforeRoutingHooks($))return;let W=await this._matchRoute($);if(!W)return;Object.assign($.request.params,W.params);let{handler:Z,options:Y}=W,{beforeHooks:Q=[],afterHooks:X=[]}=Y;if(await this._handleBeforeAllHooks($))return;if(await this._handleBeforeHooks($,Q))return;let J=null;try{J=await Z($)}catch(F){throw F}for(let F of X)await F($);let M=this.setup._hooks._afterAll;for(let F of M){if(!this._shouldRunHook(F.options,$.request.path))continue;await F.handler($)}if($._response._setBody(J),$.request.method==="HEAD")$._response._setBody(null);$._response._parseResponseIntoString();return}catch(W){await this.handleError($,W)}}async handleError($,W){try{let Z=this.setup._hooks._onError,Y=await Z($,W);$._response._setBody(Y),$._response._parseResponseIntoString(),$._response._setHeadersIfNotSet({Date:V$.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":$._response._stringBody.split(`
2
-
3
- `)[1]?.length.toString()??"0"})}catch(Z){U.error("Error handler failed, this might be an internal error in the YinzerFlow framework: ",Z),$.response.setStatusCode(500),$._response._setBody({success:!1,message:"Internal Server Error"}),$._response._parseResponseIntoString(),$._response._setHeadersIfNotSet({Date:V$.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":$._response._stringBody.split(`
4
-
5
- `)[1]?.length.toString()??"0"})}}async _handleBeforeRoutingHooks($){let W=this.setup._hooks._beforeRouting;for(let Z of W){if(!this._shouldRunHook(Z.options,$.request.path))continue;let Y=await Z.handler($);if(Y!==void 0)return $._response._setBody(Y),$._response._parseResponseIntoString(),!0}return!1}async _matchRoute($){let W=this.setup._routeRegistry._findRoute($.request.method,$.request.path);if(!W){let Z=await this.setup._hooks._onNotFound($);return $._response._setBody(Z),$._response._parseResponseIntoString(),null}return W}async _handleBeforeAllHooks($){let W=this.setup._hooks._beforeAll;for(let Z of W){if(!this._shouldRunHook(Z.options,$.request.path))continue;let Y=await Z.handler($);if(Y!==void 0)return $._response._setBody(Y),$._response._parseResponseIntoString(),!0}return!1}async _handleBeforeHooks($,W){for(let Z of W){let Y=await Z($);if(Y!==void 0)return $._response._setBody(Y),$._response._parseResponseIntoString(),!0}return!1}_shouldRunHook($,W){if(!$)return!0;let{routesToInclude:Z,routesToExclude:Y}=$;if(Y.some((Q)=>this._matchesPattern(W,Q)))return!1;if(Z.length===0)return!0;return Z.some((Q)=>this._matchesPattern(W,Q))}_matchesPattern($,W){if(W===$)return!0;if(W.endsWith("/*")){let Z=W.slice(0,-2);return $.startsWith(Z)}return!1}}var a$=["__proto__","constructor","prototype"],n$=($,W)=>{if(!$||!$.trim()||$.trim()==="\x00")return;let Z=Buffer.byteLength($,"utf8");if(Z>W.maxSize)throw U.warn("[SECURITY] JSON request body too large",{size:Z,limit:W.maxSize,sizeMB:Math.round(Z/1024/1024)}),Error(`Request body too large: ${Z} bytes exceeds limit of ${W.maxSize} bytes`);let Y=null;try{Y=JSON.parse($)}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw Error(`Invalid JSON syntax: ${X}`)}try{O$(Y,W,1)}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw Error(`JSON security validation failed: ${X}`)}return Y},m1=($,W)=>{if(typeof $==="string"&&$.length>W.maxStringLength)throw Error(`String too long: ${$.length} characters exceeds limit of ${W.maxStringLength}`)},p1=($,W,Z)=>{if($.length>W.maxArrayLength)throw Error(`Array too large: ${$.length} elements exceeds limit of ${W.maxArrayLength}`);for(let Y of $)O$(Y,W,Z+1)},f1=($,W)=>{if($.length>W.maxKeys)throw Error(`Object has too many keys: ${$.length} exceeds limit of ${W.maxKeys}`);if(!W.allowPrototypeProperties){for(let Z of $)if(a$.includes(Z))throw U.warn("[SECURITY] Prototype pollution attempt detected",{property:Z,dangerousProperties:a$}),Error(`Prototype pollution attempt detected: property '${Z}' is not allowed`)}},l1=($,W,Z)=>{let Y=Object.keys($);for(let Q of Y){if(Q.length>W.maxStringLength)throw Error(`Object key too long: '${Q.substring(0,50)}...' exceeds limit of ${W.maxStringLength}`);let X=$[Q];if(typeof X==="string"&&X.length>W.maxStringLength)throw Error(`String value too long: property '${Q}' has ${X.length} characters, exceeds limit of ${W.maxStringLength}`);O$(X,W,Z+1)}},O$=($,W,Z)=>{if(Z>W.maxDepth)throw U.warn("[SECURITY] JSON nesting too deep - potential stack overflow attack",{currentDepth:Z,maxDepth:W.maxDepth}),Error(`JSON nesting too deep: current depth ${Z} exceeds maximum depth of ${W.maxDepth}`);if($===null||typeof $!=="object"){m1($,W);return}if(Array.isArray($)){p1($,W,Z);return}let Y=Object.keys($);f1(Y,W),l1($,W,Z)};var g1=($)=>{let W=$.startsWith(`\r
1
+ var P1=Object.create;var{getPrototypeOf:b1,defineProperty:p$,getOwnPropertyNames:k1}=Object;var x1=Object.prototype.hasOwnProperty;var C1=($,W,Z)=>{Z=$!=null?P1(b1($)):{};let Y=W||!$||!$.__esModule?p$(Z,"default",{value:$,enumerable:!0}):Z;for(let Q of k1($))if(!x1.call(Y,Q))p$(Y,Q,{get:()=>$[Q],enumerable:!0});return Y};var y1=($,W)=>()=>(W||$((W={exports:{}}).exports,W),W.exports);var l$=y1((G$,F$)=>{(function($,W){typeof G$=="object"&&typeof F$<"u"?F$.exports=W():typeof define=="function"&&define.amd?define(W):($=typeof globalThis<"u"?globalThis:$||self).dayjs=W()})(G$,function(){var $=1000,W=60000,Z=3600000,Y="millisecond",Q="second",X="minute",J="hour",M="day",q="week",B="month",H="quarter",V="year",z="date",e="Invalid Date",S1=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,L1=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,R1={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(F){var K=["th","st","nd","rd"],j=F%100;return"["+F+(K[(j-20)%10]||K[j]||K[0])+"]"}},K$=function(F,K,j){var G=String(F);return!G||G.length>=K?F:""+Array(K+1-G.length).join(j)+F},v1={s:K$,z:function(F){var K=-F.utcOffset(),j=Math.abs(K),G=Math.floor(j/60),D=j%60;return(K<=0?"+":"-")+K$(G,2,"0")+":"+K$(D,2,"0")},m:function F(K,j){if(K.date()<j.date())return-F(j,K);var G=12*(j.year()-K.year())+(j.month()-K.month()),D=K.clone().add(G,B),w=j-D<0,N=K.clone().add(G+(w?-1:1),B);return+(-(G+(j-D)/(w?D-N:N-D))||0)},a:function(F){return F<0?Math.ceil(F)||0:Math.floor(F)},p:function(F){return{M:B,y:V,w:q,d:M,D:z,h:J,m:X,s:Q,ms:Y,Q:H}[F]||String(F||"").toLowerCase().replace(/s$/,"")},u:function(F){return F===void 0}},d="en",h={};h[d]=R1;var m$="$isDayjsObject",U$=function(F){return F instanceof W$||!(!F||!F[m$])},$$=function F(K,j,G){var D;if(!K)return d;if(typeof K=="string"){var w=K.toLowerCase();h[w]&&(D=w),j&&(h[w]=j,D=w);var N=K.split("-");if(!D&&N.length>1)return F(N[0])}else{var A=K.name;h[A]=K,D=A}return!G&&D&&(d=D),D||!G&&d},T=function(F,K){if(U$(F))return F.clone();var j=typeof K=="object"?K:{};return j.date=F,j.args=arguments,new W$(j)},O=v1;O.l=$$,O.i=U$,O.w=function(F,K){return T(F,{locale:K.$L,utc:K.$u,x:K.$x,$offset:K.$offset})};var W$=function(){function F(j){this.$L=$$(j.locale,null,!0),this.parse(j),this.$x=this.$x||j.x||{},this[m$]=!0}var K=F.prototype;return K.parse=function(j){this.$d=function(G){var{date:D,utc:w}=G;if(D===null)return new Date(NaN);if(O.u(D))return new Date;if(D instanceof Date)return new Date(D);if(typeof D=="string"&&!/Z$/i.test(D)){var N=D.match(S1);if(N){var A=N[2]-1||0,_=(N[7]||"0").substring(0,3);return w?new Date(Date.UTC(N[1],A,N[3]||1,N[4]||0,N[5]||0,N[6]||0,_)):new Date(N[1],A,N[3]||1,N[4]||0,N[5]||0,N[6]||0,_)}}return new Date(D)}(j),this.init()},K.init=function(){var j=this.$d;this.$y=j.getFullYear(),this.$M=j.getMonth(),this.$D=j.getDate(),this.$W=j.getDay(),this.$H=j.getHours(),this.$m=j.getMinutes(),this.$s=j.getSeconds(),this.$ms=j.getMilliseconds()},K.$utils=function(){return O},K.isValid=function(){return this.$d.toString()!==e},K.isSame=function(j,G){var D=T(j);return this.startOf(G)<=D&&D<=this.endOf(G)},K.isAfter=function(j,G){return T(j)<this.startOf(G)},K.isBefore=function(j,G){return this.endOf(G)<T(j)},K.$g=function(j,G,D){return O.u(j)?this[G]:this.set(D,j)},K.unix=function(){return Math.floor(this.valueOf()/1000)},K.valueOf=function(){return this.$d.getTime()},K.startOf=function(j,G){var D=this,w=!!O.u(G)||G,N=O.p(j),A=function(m,v){var y=O.w(D.$u?Date.UTC(D.$y,v,m):new Date(D.$y,v,m),D);return w?y:y.endOf(M)},_=function(m,v){return O.w(D.toDate()[m].apply(D.toDate("s"),(w?[0,0,0,0]:[23,59,59,999]).slice(v)),D)},S=this.$W,R=this.$M,P=this.$D,l="set"+(this.$u?"UTC":"");switch(N){case V:return w?A(1,0):A(31,11);case B:return w?A(1,R):A(0,R+1);case q:var u=this.$locale().weekStart||0,s=(S<u?S+7:S)-u;return A(w?P-s:P+(6-s),R);case M:case z:return _(l+"Hours",0);case J:return _(l+"Minutes",1);case X:return _(l+"Seconds",2);case Q:return _(l+"Milliseconds",3);default:return this.clone()}},K.endOf=function(j){return this.startOf(j,!1)},K.$set=function(j,G){var D,w=O.p(j),N="set"+(this.$u?"UTC":""),A=(D={},D[M]=N+"Date",D[z]=N+"Date",D[B]=N+"Month",D[V]=N+"FullYear",D[J]=N+"Hours",D[X]=N+"Minutes",D[Q]=N+"Seconds",D[Y]=N+"Milliseconds",D)[w],_=w===M?this.$D+(G-this.$W):G;if(w===B||w===V){var S=this.clone().set(z,1);S.$d[A](_),S.init(),this.$d=S.set(z,Math.min(this.$D,S.daysInMonth())).$d}else A&&this.$d[A](_);return this.init(),this},K.set=function(j,G){return this.clone().$set(j,G)},K.get=function(j){return this[O.p(j)]()},K.add=function(j,G){var D,w=this;j=Number(j);var N=O.p(G),A=function(R){var P=T(w);return O.w(P.date(P.date()+Math.round(R*j)),w)};if(N===B)return this.set(B,this.$M+j);if(N===V)return this.set(V,this.$y+j);if(N===M)return A(1);if(N===q)return A(7);var _=(D={},D[X]=W,D[J]=Z,D[Q]=$,D)[N]||1,S=this.$d.getTime()+j*_;return O.w(S,this)},K.subtract=function(j,G){return this.add(-1*j,G)},K.format=function(j){var G=this,D=this.$locale();if(!this.isValid())return D.invalidDate||e;var w=j||"YYYY-MM-DDTHH:mm:ssZ",N=O.z(this),A=this.$H,_=this.$m,S=this.$M,R=D.weekdays,P=D.months,l=D.meridiem,u=function(v,y,c,Z$){return v&&(v[y]||v(G,w))||c[y].slice(0,Z$)},s=function(v){return O.s(A%12||12,v,"0")},m=l||function(v,y,c){var Z$=v<12?"AM":"PM";return c?Z$.toLowerCase():Z$};return w.replace(L1,function(v,y){return y||function(c){switch(c){case"YY":return String(G.$y).slice(-2);case"YYYY":return O.s(G.$y,4,"0");case"M":return S+1;case"MM":return O.s(S+1,2,"0");case"MMM":return u(D.monthsShort,S,P,3);case"MMMM":return u(P,S);case"D":return G.$D;case"DD":return O.s(G.$D,2,"0");case"d":return String(G.$W);case"dd":return u(D.weekdaysMin,G.$W,R,2);case"ddd":return u(D.weekdaysShort,G.$W,R,3);case"dddd":return R[G.$W];case"H":return String(A);case"HH":return O.s(A,2,"0");case"h":return s(1);case"hh":return s(2);case"a":return m(A,_,!0);case"A":return m(A,_,!1);case"m":return String(_);case"mm":return O.s(_,2,"0");case"s":return String(G.$s);case"ss":return O.s(G.$s,2,"0");case"SSS":return O.s(G.$ms,3,"0");case"Z":return N}return null}(v)||N.replace(":","")})},K.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},K.diff=function(j,G,D){var w,N=this,A=O.p(G),_=T(j),S=(_.utcOffset()-this.utcOffset())*W,R=this-_,P=function(){return O.m(N,_)};switch(A){case V:w=P()/12;break;case B:w=P();break;case H:w=P()/3;break;case q:w=(R-S)/604800000;break;case M:w=(R-S)/86400000;break;case J:w=R/Z;break;case X:w=R/W;break;case Q:w=R/$;break;default:w=R}return D?w:O.a(w)},K.daysInMonth=function(){return this.endOf(B).$D},K.$locale=function(){return h[this.$L]},K.locale=function(j,G){if(!j)return this.$L;var D=this.clone(),w=$$(j,G,!0);return w&&(D.$L=w),D},K.clone=function(){return O.w(this.$d,this)},K.toDate=function(){return new Date(this.valueOf())},K.toJSON=function(){return this.isValid()?this.toISOString():null},K.toISOString=function(){return this.$d.toISOString()},K.toString=function(){return this.$d.toUTCString()},F}(),f$=W$.prototype;return T.prototype=f$,[["$ms",Y],["$s",Q],["$m",X],["$H",J],["$W",M],["$M",B],["$y",V],["$D",z]].forEach(function(F){f$[F[1]]=function(K){return this.$g(K,F[0],F[1])}}),T.extend=function(F,K){return F.$i||(F(K,W$,T),F.$i=!0),T},T.locale=$$,T.isDayjs=U$,T.unix=function(F){return T(1000*F)},T.en=h[d],T.Ls=h,T.p={},T})});import{createServer as E2}from"net";var g$=C1(l$(),1);var E={reset:"\x1B[0m",cyan:"\x1B[96m",yellow:"\x1B[93m",red:"\x1B[91m",green:"\x1B[92m",magenta:"\x1B[95m",gray:"\x1B[90m"};var r={off:"off",error:"error",warn:"warn",info:"info"};var f={off:0,error:1,warn:2,info:3},h1={positive:["n'at!","yinz are good!","that's the way!","right on!","lookin' good!","way to go!","keep it up!"],neutral:["n'at","yinz know","just sayin'","that's how it is","what can ya do","it happens"],negative:["aw jeez","that ain't right","what a jagoff move","that's terrible n'at","somebody messed up","this is bad news","yinz better fix this"]},Y$=($)=>{let W=h1[$];return W[Math.floor(Math.random()*W.length)]??""},d$=()=>g$.default().format("YYYY-MM-DD HH:mm:ss.SSS"),q$=($,W,...Z)=>{let Y=d$(),Q=E.reset;if(W==="NETWORK")Q=E.gray;if($==="error"){let J=`${E.red}[${W}] ❌ [${Y}] [ERROR]${E.reset}`;console.error(`${J}`,`${Q}`,...Z,`${E.reset} - ${Y$("negative")}`);return}if($==="warn"){let J=`${E.yellow}[${W}] ⚠️ [${Y}] [WARN]${E.reset}`;console.warn(`${J}`,`${Q}`,...Z,`${E.reset} - ${Y$("neutral")}`);return}if($==="off")return;let X=`${E.cyan}[${W}] ✅ [${Y}] [INFO]${E.reset}`;console.info(`${X}`,`${Q}`,...Z,`${E.reset} - ${Y$("positive")}`)},u1=($,W,...Z)=>{let Y=d$(),Q=`${E.magenta}[${$}] \uD83D\uDCCA [${Y}] [TABLE]${E.reset}`;if(console.log(`${Q} - ${Y$("positive")}`),console.table(W),Z.length>0)console.log(`${E.gray}Additional context:${E.reset}`,...Z)},a=($)=>{let W={logLevel:$?.logLevel??r.info,prefix:$?.prefix??"YINZER",logger:$?.logger??null},Z=(M)=>f[M]??f.info;return{info:(...M)=>{if(Z(W.logLevel)<f.info)return;if(W.logger){W.logger.info(...M);return}q$("info",W.prefix,...M)},warn:(...M)=>{if(Z(W.logLevel)<f.warn)return;if(W.logger){W.logger.warn(...M);return}q$("warn",W.prefix,...M)},error:(...M)=>{if(Z(W.logLevel)<f.error)return;if(W.logger){W.logger.error(...M);return}q$("error",W.prefix,...M)},table:(M,...q)=>{if(Z(W.logLevel)<f.info)return;if(W.logger){W.logger.info("TABLE:",M,...q);return}u1(W.prefix,M,...q)},levels:f}},U=a();class w${setup;constructor($){this.setup=$}async handle($){try{if(await this._handleBeforeRoutingHooks($))return;let W=await this._matchRoute($);if(!W)return;Object.assign($.request.params,W.params);let{handler:Z,options:Y}=W,{beforeHooks:Q=[],afterHooks:X=[]}=Y;if(await this._handleBeforeAllHooks($))return;if(await this._handleBeforeHooks($,Q))return;let J=await Z($);$._response._setBody(J);for(let q of X)await q($);let M=this.setup._hooks._afterAll;for(let q of M){if(!this._shouldRunHook(q.options,$.request.path))continue;await q.handler($)}if($.request.method==="HEAD")$._response._setBody(null);$._response._parseResponseIntoString();return}catch(W){await this.handleError($,W)}}async handleError($,W){try{let Z=this.setup._hooks._onError,Y=await Z($,W);$._response._setBody(Y),$._response._parseResponseIntoString()}catch(Z){U.error("Your custom error handler threw an error. Check your onError() handler for bugs: ",Z),$.response.setStatusCode(500),$._response._setBody({success:!1,message:"Internal Server Error"}),$._response._parseResponseIntoString()}}async _handleBeforeRoutingHooks($){let W=this.setup._hooks._beforeRouting;for(let Z of W){if(!this._shouldRunHook(Z.options,$.request.path))continue;let Y=await Z.handler($);if(this._applyHookResponse(Y,$))return!0}return!1}async _matchRoute($){let W=this.setup._routeRegistry._findRoute($.request.method,$.request.path);if(!W){let Z=await this.setup._hooks._onNotFound($);return $._response._setBody(Z),$._response._parseResponseIntoString(),null}return W}async _handleBeforeAllHooks($){let W=this.setup._hooks._beforeAll;for(let Z of W){if(!this._shouldRunHook(Z.options,$.request.path))continue;let Y=await Z.handler($);if(this._applyHookResponse(Y,$))return!0}return!1}async _handleBeforeHooks($,W){for(let Z of W){let Y=await Z($);if(this._applyHookResponse(Y,$))return!0}return!1}_applyHookResponse($,W){if($===void 0)return!1;return W._response._setBody($),W._response._parseResponseIntoString(),!0}_shouldRunHook($,W){if(!$)return!0;let{routesToInclude:Z=[],routesToExclude:Y=[]}=$;if(Y.some((Q)=>this._matchesPattern(W,Q)))return!1;if(Z.length===0)return!0;return Z.some((Q)=>this._matchesPattern(W,Q))}_matchesPattern($,W){if(W===$)return!0;if(W.endsWith("/*")){let Z=W.slice(0,-1);return $.startsWith(Z)||$===W.slice(0,-2)}return!1}}var s$=["__proto__","constructor","prototype"],c$=($,W)=>{if(!$||!$.trim()||$.trim()==="\x00")return;let Z=Buffer.byteLength($,"utf8");if(Z>W.maxSize)throw U.warn("[SECURITY] JSON request body too large",{size:Z,limit:W.maxSize,sizeMB:Math.round(Z/1024/1024)}),Error(`Request body too large: ${Z} bytes exceeds limit of ${W.maxSize} bytes`);let Y=null;try{Y=JSON.parse($)}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw Error(`Invalid JSON syntax: ${X}`)}try{N$(Y,W,1)}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw Error(`JSON security validation failed: ${X}`)}return Y},m1=($,W)=>{if(typeof $==="string"&&$.length>W.maxStringLength)throw Error(`String too long: ${$.length} characters exceeds limit of ${W.maxStringLength}`)},f1=($,W,Z)=>{if($.length>W.maxArrayLength)throw Error(`Array too large: ${$.length} elements exceeds limit of ${W.maxArrayLength}`);for(let Y of $)N$(Y,W,Z+1)},p1=($,W)=>{if($.length>W.maxKeys)throw Error(`Object has too many keys: ${$.length} exceeds limit of ${W.maxKeys}`);if(!W.allowPrototypeProperties){for(let Z of $)if(s$.includes(Z))throw U.warn("[SECURITY] Prototype pollution attempt detected",{property:Z,dangerousProperties:s$}),Error(`Prototype pollution attempt detected: property '${Z}' is not allowed`)}},l1=($,W,Z)=>{let Y=Object.keys($);for(let Q of Y){if(Q.length>W.maxStringLength)throw Error(`Object key too long: '${Q.substring(0,50)}...' exceeds limit of ${W.maxStringLength}`);let X=$[Q];if(typeof X==="string"&&X.length>W.maxStringLength)throw Error(`String value too long: property '${Q}' has ${X.length} characters, exceeds limit of ${W.maxStringLength}`);N$(X,W,Z+1)}},N$=($,W,Z)=>{if(Z>W.maxDepth)throw U.warn("[SECURITY] JSON nesting too deep - potential stack overflow attack",{currentDepth:Z,maxDepth:W.maxDepth}),Error(`JSON nesting too deep: current depth ${Z} exceeds maximum depth of ${W.maxDepth}`);if($===null||typeof $!=="object"){m1($,W);return}if(Array.isArray($)){f1($,W,Z);return}let Y=Object.keys($);p1(Y,W),l1($,W,Z)};var g1=($)=>{let W=$.startsWith(`\r
6
2
  `)?$.slice(2):$,Z=W.indexOf(`\r
7
3
  \r
8
4
  `);if(Z===-1)return["",""];let Y=W.slice(0,Z),Q=W.slice(Z+4);return[Y,Q]},d1=($)=>{let W={name:""},Z=/name=(?:"(?<temp2>[^"]*)"|(?<temp1>[^;,\s]+))/i.exec($),Y=/filename=(?:"(?<temp2>[^"]*)"|(?<temp1>[^;,\s]+))/i.exec($);if(Z)W.name=Z[1]??Z[2]??"";if(Y){let Q=Y[1]??Y[2];if(Q)W.filename=Q}return W},s1=($)=>{let Z=$.split(/\r?\n/).find((Y)=>Y.toLowerCase().startsWith("content-type:"));if(!Z)return"application/octet-stream";return Z.slice(Z.indexOf(":")+1).trim().split(";")[0]?.trim()??"application/octet-stream"},c1=($)=>{return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/x-"].some((Z)=>$.toLowerCase().startsWith(Z))},r1=($)=>Buffer.isBuffer($)?$.length:Buffer.byteLength($,"utf8"),a1=($,W)=>{if(!W)return;if($.size>W.maxFileSize)throw U.warn("[SECURITY] File upload too large",{filename:$.filename,size:$.size,limit:W.maxFileSize,sizeMB:Math.round($.size/1024/1024)}),Error(`File too large: ${$.filename} is ${$.size} bytes, exceeds limit of ${W.maxFileSize} bytes`);if($.filename&&$.filename.length>W.maxFilenameLength)throw Error(`Filename too long: ${$.filename.length} characters exceeds limit of ${W.maxFilenameLength}`);if($.filename){let Z=$.filename.toLowerCase().substring($.filename.lastIndexOf("."));if(W.blockedExtensions.includes(Z))throw U.warn("[SECURITY] Blocked file type upload attempt",{filename:$.filename,extension:Z,blockedExtensions:W.blockedExtensions}),Error(`File type not allowed: ${Z} files are blocked for security reasons`);if(W.allowedExtensions.length>0&&!W.allowedExtensions.includes(Z))throw Error(`File type not allowed: ${Z} is not in the allowed extensions list`)}},n1=({contentDisposition:$,contentSection:W,headersSection:Z,config:Y})=>{let Q=s1(Z),X=W.endsWith(`\r
9
- `)?W.slice(0,-2):W,J=c1(Q)?Buffer.from(X,"binary"):X,M={filename:$.filename??"",contentType:Q,size:r1(J),content:J};return a1(M,Y),M},i$=($,W,Z)=>{let Y={fields:{},files:[]},Q=$.split(`--${W}`).slice(1),X=0;for(let J of Q){if(!J||J.trim()===""||J.trim()==="--")continue;let[M,F]=g1(J);if(!M)continue;let _=M.split(/\r?\n/).find((H)=>H.toLowerCase().startsWith("content-disposition:"));if(!_)continue;let V=d1(_);if(!V.name)continue;if(V.filename!==void 0){if(Z&&Y.files.length>=Z.maxFiles)throw U.warn("[SECURITY] Too many files in upload request",{fileCount:Y.files.length,maxFiles:Z.maxFiles}),Error(`Too many files: maximum of ${Z.maxFiles} files allowed per request`);let H=n1({contentDisposition:V,contentSection:F,headersSection:M,config:Z});if(X+=H.size,Z&&X>Z.maxTotalSize)throw U.warn("[SECURITY] Total upload size too large",{totalSize:X,limit:Z.maxTotalSize,totalSizeMB:Math.round(X/1024/1024)}),Error(`Total file size too large: ${X} bytes exceeds limit of ${Z.maxTotalSize} bytes`);Y.files.push(H)}if(V.filename===void 0){let H=F.endsWith(`\r
10
- `)?F.slice(0,-2):F;Y.fields[V.name]=H}}return Y};var n={ok:"OK",created:"Created",accepted:"Accepted",noContent:"No Content",movedPermanently:"Moved Permanently",found:"Found",notModified:"Not Modified",badRequest:"Bad Request",unauthorized:"Unauthorized",forbidden:"Forbidden",notFound:"Not Found",methodNotAllowed:"Method Not Allowed",conflict:"Conflict",unsupportedMediaType:"Unsupported Media Type",tooManyRequests:"Too Many Requests",internalServerError:"Internal Server Error"},b={ok:200,created:201,accepted:202,noContent:204,movedPermanently:301,found:302,notModified:304,badRequest:400,unauthorized:401,forbidden:403,notFound:404,methodNotAllowed:405,conflict:409,unsupportedMediaType:415,tooManyRequests:429,internalServerError:500},I={delete:"DELETE",get:"GET",head:"HEAD",post:"POST",put:"PUT",patch:"PATCH",options:"OPTIONS"},k={json:"application/json",html:"text/html",form:"application/x-www-form-urlencoded",multipart:"multipart/form-data",xml:"application/xml",text:"text/plain",csv:"text/csv",yamlApplication:"application/yaml",yamlText:"text/yaml",urlEncodedJson:"application/x-www-form-urlencoded+json"},f={authorization:"Authorization",proxyAuthorization:"Proxy-Authorization",wwwAuthenticate:"WWW-Authenticate",cacheControl:"Cache-Control",etag:"ETag",expires:"Expires",lastModified:"Last-Modified",ifMatch:"If-Match",ifNoneMatch:"If-None-Match",ifModifiedSince:"If-Modified-Since",ifUnmodifiedSince:"If-Unmodified-Since",ifRange:"If-Range",age:"Age",vary:"Vary",contentType:"Content-Type",contentLength:"Content-Length",contentEncoding:"Content-Encoding",contentLanguage:"Content-Language",contentDisposition:"Content-Disposition",contentLocation:"Content-Location",contentRange:"Content-Range",accessControlAllowCredentials:"Access-Control-Allow-Credentials",accessControlAllowHeaders:"Access-Control-Allow-Headers",accessControlAllowMethods:"Access-Control-Allow-Methods",accessControlAllowOrigin:"Access-Control-Allow-Origin",accessControlExposeHeaders:"Access-Control-Expose-Headers",accessControlMaxAge:"Access-Control-Max-Age",accessControlRequestHeaders:"Access-Control-Request-Headers",accessControlRequestMethod:"Access-Control-Request-Method",accept:"Accept",acceptEncoding:"Accept-Encoding",acceptLanguage:"Accept-Language",acceptRanges:"Accept-Ranges",host:"Host",userAgent:"User-Agent",referer:"Referer",origin:"Origin",from:"From",expect:"Expect",location:"Location",server:"Server",date:"Date",allow:"Allow",retryAfter:"Retry-After",range:"Range",contentSecurityPolicy:"Content-Security-Policy",contentSecurityPolicyReportOnly:"Content-Security-Policy-Report-Only",strictTransportSecurity:"Strict-Transport-Security",xContentTypeOptions:"X-Content-Type-Options",xFrameOptions:"X-Frame-Options",xXSSProtection:"X-XSS-Protection",referrerPolicy:"Referrer-Policy",permissionsPolicy:"Permissions-Policy",crossOriginEmbedderPolicy:"Cross-Origin-Embedder-Policy",crossOriginOpenerPolicy:"Cross-Origin-Opener-Policy",crossOriginResourcePolicy:"Cross-Origin-Resource-Policy",cookie:"Cookie",setCookie:"Set-Cookie",connection:"Connection",keepAlive:"Keep-Alive",upgrade:"Upgrade",upgradeInsecureRequests:"Upgrade-Insecure-Requests",transferEncoding:"Transfer-Encoding",te:"TE",trailer:"Trailer",forwarded:"Forwarded",xForwardedFor:"X-Forwarded-For",via:"Via",maxForwards:"Max-Forwards",altSvc:"Alt-Svc",altUsed:"Alt-Used",timingAllowOrigin:"Timing-Allow-Origin",serverTiming:"Server-Timing",refresh:"Refresh",link:"Link",xPoweredBy:"X-Powered-By",xPermittedCrossDomainPolicies:"X-Permitted-Cross-Domain-Policies",reportTo:"Report-To",serviceWorkerAllowed:"Service-Worker-Allowed",sourceMap:"SourceMap",priority:"Priority",secGPC:"Sec-GPC",clearSiteData:"Clear-Site-Data",noVarySearch:"No-Vary-Search"},t$={base64:"base64",binary:"binary",utf8:"utf8"};var i1=($,W)=>{if($.length>W.maxFields)throw Error(`Too many form fields: ${$.length} exceeds limit of ${W.maxFields}`)},t1=($,W,Z)=>{if($.length>Z.maxFieldNameLength)throw Error(`Form field name too long: ${$.length} characters exceeds limit of ${Z.maxFieldNameLength}`);if(W&&W.length>Z.maxFieldLength)throw Error(`Form field value too long: field '${$}' has ${W.length} characters, exceeds limit of ${Z.maxFieldLength}`)},o1=($,W,Z)=>{if($.length>Z.maxFieldNameLength)throw Error(`Decoded form field name too long: ${$.length} characters exceeds limit of ${Z.maxFieldNameLength}`);if(W.length>Z.maxFieldLength)throw Error(`Decoded form field value too long: field '${$}' has ${W.length} characters, exceeds limit of ${Z.maxFieldLength}`)},e1=($,W,Z)=>{let[Y,Q]=$.split("=");if(!Y)return;if(Z)t1(Y,Q,Z);try{let X=decodeURIComponent(Y),J=Q?decodeURIComponent(Q):"";if(Z)o1(X,J,Z);W[X]=J}catch(X){if(X instanceof Error&&X.message.includes("exceeds limit"))throw X;W[Y]=Q??""}},o$=($,W)=>{let Z={},Y=$.split("&");if(W)i1(Y,W);for(let Q of Y)e1(Q,Z,W);return Z};var X$={JPEG:[255,216,255],PNG:[137,80,78,71],GIF87A:[71,73,70,56,55,97],GIF89A:[71,73,70,56,57,97],BMP:[66,77],TIFF_LE:[73,73,42,0],TIFF_BE:[77,77,0,42],WEBP:[82,73,70,70],ICO:[0,0,1,0],MP3_ID3:[73,68,51],MP3_FRAME:[255,251],WAV:[82,73,70,70],FLAC:[102,76,97,67],OGG:[79,103,103,83],MP4_FTYP:[0,0,0,24,102,116,121,112],MP4_FTYP_ALT:[0,0,0,28,102,116,121,112],AVI:[82,73,70,70],WEBM:[26,69,223,163],PDF:[37,80,68,70],ZIP:[80,75,3,4],ZIP_EMPTY:[80,75,5,6],ZIP_SPANNED:[80,75,7,8],RAR:[82,97,114,33,26,7,0],RAR5:[82,97,114,33,26,7,1,0],SEVENZ:[55,122,188,175,39,28],GZIP:[31,139],EXE:[77,90],ELF:[127,69,76,70],OFFICE_OLD:[208,207,17,224,161,177,26,225]},J$=($,W)=>{if($.length<W.length)return!1;return W.every((Z,Y)=>$[Y]===Z)},$0=($)=>{if(J$($,X$.WEBP)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WEBP";if(J$($,X$.WAV)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WAVE";if(J$($,X$.AVI)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="AVI ";return!1},M$=($,W)=>{if(!$)return W0(W);let Z=$.toLowerCase();if(Z.startsWith("image/")||Z.startsWith("video/")||Z.startsWith("audio/")||Z==="application/pdf"||Z==="application/octet-stream"||Z.startsWith("application/zip")||Z.startsWith("application/x-"))return"base64";if(Z.startsWith("text/")||Z.startsWith("application/json")||Z.startsWith("application/xml")||Z.startsWith("application/javascript"))return"utf8";return"binary"},W0=($)=>{if(Buffer.isBuffer($))return Z0($)?"base64":"utf8";if(typeof $==="object"&&$!==null)return"utf8";if(typeof $==="string")return"utf8";return"utf8"},Z0=($)=>{if($.length===0)return!1;let W=Object.values(X$);for(let Q of W)if(J$($,Q))return!0;if($0($))return!0;let Z=$.filter((Q)=>Q===0).length,Y=$.filter((Q)=>Q<32&&Q!==9&&Q!==10&&Q!==13).length;return Z/$.length>0.1||Y/$.length>0.3};var Y0=($)=>{if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return!1;try{return JSON.parse($),!0}catch{return!1}},Q0=($)=>$.includes("=")&&$.includes("&"),X0=($)=>$.includes("boundary="),J0=($)=>typeof $==="object"&&$!==null&&!Buffer.isBuffer($)&&!($ instanceof Uint8Array)&&!($ instanceof ArrayBuffer)&&!($ instanceof Date),M0=($)=>$ instanceof Date,D0=($)=>{if(Buffer.isBuffer($))return $;return Buffer.from($)},K0=($)=>{return M$(void 0,$)==="base64"?"application/octet-stream":"text/plain"},A$=($)=>{let W=$.trim();if(Y0(W))return k.json;if(Q0(W))return k.form;if(X0(W))return k.multipart;return"text/plain"},e$=($)=>{if($===null||$===void 0)return"text/plain";if(M0($))return"text/plain";if(J0($))return k.json;if(typeof $==="string")return A$($);if(Buffer.isBuffer($)||$ instanceof Uint8Array||$ instanceof ArrayBuffer){let W=D0($);return K0(W)}return"text/plain"};var j0=($,W,Z)=>{let Y=Buffer.byteLength($,"utf8");if(W===k.json){if(Y>Z.json.maxSize)throw Error(`JSON body too large: ${Y} bytes exceeds limit of ${Z.json.maxSize} bytes`)}else if(W===k.form){if(Y>Z.urlEncoded.maxSize)throw Error(`URL-encoded body too large: ${Y} bytes exceeds limit of ${Z.urlEncoded.maxSize} bytes`)}else if(W===k.multipart){if(Y>Z.fileUploads.maxTotalSize)throw Error(`Multipart body too large: ${Y} bytes exceeds limit of ${Z.fileUploads.maxTotalSize} bytes`)}},$1=($,W={})=>{let{headerContentType:Z,boundary:Y,config:Q}=W;if(!$||!$.trim())return;let X=Z??A$($);if(Q)j0($,X,Q);if(X===k.json){if(!Q)throw Error("Body parser configuration is required for JSON parsing");return n$($,Q.json)}if(X===k.multipart){if(!Y)throw Error("Invalid multipart form data: missing boundary");return i$($,Y,Q?.fileUploads)}if(X===k.form)return o$($,Q?.urlEncoded);return $};var H$=($,W)=>{let Z=$.indexOf(W);if(Z===-1)return[$,""];let Y=$.slice(0,Z),Q=$.slice(Z+W.length);return[Y,Q]};var W1=($)=>{if(!$||!$.trim())return{method:"GET",path:"/",protocol:"HTTP/1.1",headersRaw:"",rawBody:""};let[W,Z]=H$($,`\r
11
- `),[Y,Q,X]=W.split(" ",3),[J,M]=H$(Z,`\r
5
+ `)?W.slice(0,-2):W,J=c1(Q)?Buffer.from(X,"binary"):X,M={filename:$.filename??"",contentType:Q,size:r1(J),content:J};return a1(M,Y),M},r$=($,W,Z)=>{let Y={fields:{},files:[]},Q=$.split(`--${W}`).slice(1),X=0;for(let J of Q){if(!J||J.trim()===""||J.trim()==="--")continue;let[M,q]=g1(J);if(!M)continue;let H=M.split(/\r?\n/).find((z)=>z.toLowerCase().startsWith("content-disposition:"));if(!H)continue;let V=d1(H);if(!V.name)continue;if(V.filename!==void 0){if(Z&&Y.files.length>=Z.maxFiles)throw U.warn("[SECURITY] Too many files in upload request",{fileCount:Y.files.length,maxFiles:Z.maxFiles}),Error(`Too many files: maximum of ${Z.maxFiles} files allowed per request`);let z=n1({contentDisposition:V,contentSection:q,headersSection:M,config:Z});if(X+=z.size,Z&&X>Z.maxTotalSize)throw U.warn("[SECURITY] Total upload size too large",{totalSize:X,limit:Z.maxTotalSize,totalSizeMB:Math.round(X/1024/1024)}),Error(`Total file size too large: ${X} bytes exceeds limit of ${Z.maxTotalSize} bytes`);Y.files.push(z)}if(V.filename===void 0){let z=q.endsWith(`\r
6
+ `)?q.slice(0,-2):q;Y.fields[V.name]=z}}return Y};var n={ok:"OK",created:"Created",accepted:"Accepted",noContent:"No Content",movedPermanently:"Moved Permanently",found:"Found",notModified:"Not Modified",badRequest:"Bad Request",unauthorized:"Unauthorized",forbidden:"Forbidden",notFound:"Not Found",methodNotAllowed:"Method Not Allowed",conflict:"Conflict",unsupportedMediaType:"Unsupported Media Type",tooManyRequests:"Too Many Requests",internalServerError:"Internal Server Error"},b={ok:200,created:201,accepted:202,noContent:204,movedPermanently:301,found:302,notModified:304,badRequest:400,unauthorized:401,forbidden:403,notFound:404,methodNotAllowed:405,conflict:409,unsupportedMediaType:415,tooManyRequests:429,internalServerError:500},I={delete:"DELETE",get:"GET",head:"HEAD",post:"POST",put:"PUT",patch:"PATCH",options:"OPTIONS"},k={json:"application/json",html:"text/html",form:"application/x-www-form-urlencoded",multipart:"multipart/form-data",xml:"application/xml",text:"text/plain",csv:"text/csv",yamlApplication:"application/yaml",yamlText:"text/yaml",urlEncodedJson:"application/x-www-form-urlencoded+json"},p={authorization:"Authorization",proxyAuthorization:"Proxy-Authorization",wwwAuthenticate:"WWW-Authenticate",cacheControl:"Cache-Control",etag:"ETag",expires:"Expires",lastModified:"Last-Modified",ifMatch:"If-Match",ifNoneMatch:"If-None-Match",ifModifiedSince:"If-Modified-Since",ifUnmodifiedSince:"If-Unmodified-Since",ifRange:"If-Range",age:"Age",vary:"Vary",contentType:"Content-Type",contentLength:"Content-Length",contentEncoding:"Content-Encoding",contentLanguage:"Content-Language",contentDisposition:"Content-Disposition",contentLocation:"Content-Location",contentRange:"Content-Range",accessControlAllowCredentials:"Access-Control-Allow-Credentials",accessControlAllowHeaders:"Access-Control-Allow-Headers",accessControlAllowMethods:"Access-Control-Allow-Methods",accessControlAllowOrigin:"Access-Control-Allow-Origin",accessControlExposeHeaders:"Access-Control-Expose-Headers",accessControlMaxAge:"Access-Control-Max-Age",accessControlRequestHeaders:"Access-Control-Request-Headers",accessControlRequestMethod:"Access-Control-Request-Method",accept:"Accept",acceptEncoding:"Accept-Encoding",acceptLanguage:"Accept-Language",acceptRanges:"Accept-Ranges",host:"Host",userAgent:"User-Agent",referer:"Referer",origin:"Origin",from:"From",expect:"Expect",location:"Location",server:"Server",date:"Date",allow:"Allow",retryAfter:"Retry-After",range:"Range",contentSecurityPolicy:"Content-Security-Policy",contentSecurityPolicyReportOnly:"Content-Security-Policy-Report-Only",strictTransportSecurity:"Strict-Transport-Security",xContentTypeOptions:"X-Content-Type-Options",xFrameOptions:"X-Frame-Options",xXSSProtection:"X-XSS-Protection",referrerPolicy:"Referrer-Policy",permissionsPolicy:"Permissions-Policy",crossOriginEmbedderPolicy:"Cross-Origin-Embedder-Policy",crossOriginOpenerPolicy:"Cross-Origin-Opener-Policy",crossOriginResourcePolicy:"Cross-Origin-Resource-Policy",cookie:"Cookie",setCookie:"Set-Cookie",connection:"Connection",keepAlive:"Keep-Alive",upgrade:"Upgrade",upgradeInsecureRequests:"Upgrade-Insecure-Requests",transferEncoding:"Transfer-Encoding",te:"TE",trailer:"Trailer",forwarded:"Forwarded",xForwardedFor:"X-Forwarded-For",via:"Via",maxForwards:"Max-Forwards",altSvc:"Alt-Svc",altUsed:"Alt-Used",timingAllowOrigin:"Timing-Allow-Origin",serverTiming:"Server-Timing",refresh:"Refresh",link:"Link",xPoweredBy:"X-Powered-By",xPermittedCrossDomainPolicies:"X-Permitted-Cross-Domain-Policies",reportTo:"Report-To",serviceWorkerAllowed:"Service-Worker-Allowed",sourceMap:"SourceMap",priority:"Priority",secGPC:"Sec-GPC",clearSiteData:"Clear-Site-Data",noVarySearch:"No-Vary-Search"},a$={base64:"base64",binary:"binary",utf8:"utf8"};var i1=($,W)=>{if($.length>W.maxFields)throw Error(`Too many form fields: ${$.length} exceeds limit of ${W.maxFields}`)},t1=($,W,Z)=>{if($.length>Z.maxFieldNameLength)throw Error(`Form field name too long: ${$.length} characters exceeds limit of ${Z.maxFieldNameLength}`);if(W&&W.length>Z.maxFieldLength)throw Error(`Form field value too long: field '${$}' has ${W.length} characters, exceeds limit of ${Z.maxFieldLength}`)},o1=($,W,Z)=>{if($.length>Z.maxFieldNameLength)throw Error(`Decoded form field name too long: ${$.length} characters exceeds limit of ${Z.maxFieldNameLength}`);if(W.length>Z.maxFieldLength)throw Error(`Decoded form field value too long: field '${$}' has ${W.length} characters, exceeds limit of ${Z.maxFieldLength}`)},e1=($,W,Z)=>{let[Y,Q]=$.split("=");if(!Y)return;if(Z)t1(Y,Q,Z);try{let X=decodeURIComponent(Y),J=Q?decodeURIComponent(Q):"";if(Z)o1(X,J,Z);W[X]=J}catch(X){if(X instanceof Error&&X.message.includes("exceeds limit"))throw X;W[Y]=Q??""}},n$=($,W)=>{let Z={},Y=$.split("&");if(W)i1(Y,W);for(let Q of Y)e1(Q,Z,W);return Z};var Q$={JPEG:[255,216,255],PNG:[137,80,78,71],GIF87A:[71,73,70,56,55,97],GIF89A:[71,73,70,56,57,97],BMP:[66,77],TIFF_LE:[73,73,42,0],TIFF_BE:[77,77,0,42],WEBP:[82,73,70,70],ICO:[0,0,1,0],MP3_ID3:[73,68,51],MP3_FRAME:[255,251],WAV:[82,73,70,70],FLAC:[102,76,97,67],OGG:[79,103,103,83],MP4_FTYP:[0,0,0,24,102,116,121,112],MP4_FTYP_ALT:[0,0,0,28,102,116,121,112],AVI:[82,73,70,70],WEBM:[26,69,223,163],PDF:[37,80,68,70],ZIP:[80,75,3,4],ZIP_EMPTY:[80,75,5,6],ZIP_SPANNED:[80,75,7,8],RAR:[82,97,114,33,26,7,0],RAR5:[82,97,114,33,26,7,1,0],SEVENZ:[55,122,188,175,39,28],GZIP:[31,139],EXE:[77,90],ELF:[127,69,76,70],OFFICE_OLD:[208,207,17,224,161,177,26,225]},X$=($,W)=>{if($.length<W.length)return!1;return W.every((Z,Y)=>$[Y]===Z)},$0=($)=>{if(X$($,Q$.WEBP)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WEBP";if(X$($,Q$.WAV)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WAVE";if(X$($,Q$.AVI)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="AVI ";return!1},J$=($,W)=>{if(!$)return W0(W);let Z=$.toLowerCase();if(Z.startsWith("image/")||Z.startsWith("video/")||Z.startsWith("audio/")||Z==="application/pdf"||Z==="application/octet-stream"||Z.startsWith("application/zip")||Z.startsWith("application/x-"))return"base64";if(Z.startsWith("text/")||Z.startsWith("application/json")||Z.startsWith("application/xml")||Z.startsWith("application/javascript"))return"utf8";return"binary"},W0=($)=>{if(Buffer.isBuffer($))return Z0($)?"base64":"utf8";if(typeof $==="object"&&$!==null)return"utf8";if(typeof $==="string")return"utf8";return"utf8"},Z0=($)=>{if($.length===0)return!1;let W=Object.values(Q$);for(let Q of W)if(X$($,Q))return!0;if($0($))return!0;let Z=$.filter((Q)=>Q===0).length,Y=$.filter((Q)=>Q<32&&Q!==9&&Q!==10&&Q!==13).length;return Z/$.length>0.1||Y/$.length>0.3};var Y0=($)=>{if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return!1;try{return JSON.parse($),!0}catch{return!1}},Q0=($)=>$.includes("=")&&$.includes("&"),X0=($)=>$.includes("boundary="),J0=($)=>typeof $==="object"&&$!==null&&!Buffer.isBuffer($)&&!($ instanceof Uint8Array)&&!($ instanceof ArrayBuffer)&&!($ instanceof Date),M0=($)=>$ instanceof Date,j0=($)=>{if(Buffer.isBuffer($))return $;return Buffer.from($)},D0=($)=>{return J$(void 0,$)==="base64"?"application/octet-stream":"text/plain"},B$=($)=>{let W=$.trim();if(Y0(W))return k.json;if(Q0(W))return k.form;if(X0(W))return k.multipart;return"text/plain"},i$=($)=>{if($===null||$===void 0)return"text/plain";if(M0($))return"text/plain";if(J0($))return k.json;if(typeof $==="string")return B$($);if(Buffer.isBuffer($)||$ instanceof Uint8Array||$ instanceof ArrayBuffer){let W=j0($);return D0(W)}return"text/plain"};var K0=($,W,Z)=>{let Y=Buffer.byteLength($,"utf8");if(W===k.json){if(Y>Z.json.maxSize)throw Error(`JSON body too large: ${Y} bytes exceeds limit of ${Z.json.maxSize} bytes`)}else if(W===k.form){if(Y>Z.urlEncoded.maxSize)throw Error(`URL-encoded body too large: ${Y} bytes exceeds limit of ${Z.urlEncoded.maxSize} bytes`)}else if(W===k.multipart){if(Y>Z.fileUploads.maxTotalSize)throw Error(`Multipart body too large: ${Y} bytes exceeds limit of ${Z.fileUploads.maxTotalSize} bytes`)}},t$=($,W={})=>{let{headerContentType:Z,boundary:Y,config:Q}=W;if(!$||!$.trim())return;let X=Z??B$($);if(Q)K0($,X,Q);if(X===k.json){if(!Q)throw Error("Body parser configuration is required for JSON parsing");return c$($,Q.json)}if(X===k.multipart){if(!Y)throw Error("Invalid multipart form data: missing boundary");return r$($,Y,Q?.fileUploads)}if(X===k.form)return n$($,Q?.urlEncoded);return $};var V$=($,W)=>{let Z=$.indexOf(W);if(Z===-1)return[$,""];let Y=$.slice(0,Z),Q=$.slice(Z+W.length);return[Y,Q]};var o$=($)=>{if(!$||!$.trim())return{method:"GET",path:"/",protocol:"HTTP/1.1",headersRaw:"",rawBody:""};let[W,Z]=V$($,`\r
7
+ `),[Y,Q,X]=W.split(" ",3),[J,M]=V$(Z,`\r
12
8
  \r
13
- `);if(!Y||!Object.values(I).includes(Y))return{method:"GET",path:Q??"/",protocol:X??"HTTP/1.1",headersRaw:J,rawBody:M};return{method:Y,path:Q??"/",protocol:X??"HTTP/1.1",headersRaw:J,rawBody:M}};var Z1=($)=>{if(!$)return{};if(!$.includes("?"))return{};let[,W]=$.split("?");if(!W)return{};let Z={},Y=W.split("&");for(let Q of Y){let[X,J]=Q.split("=");if(X)try{let M=decodeURIComponent(X),F=J?decodeURIComponent(J):"";Z[M]=F}catch{Z[X]=J??""}}return Z};var U0=[/^(?<classA>10)\./,/^(?<classB>172)\.(?<classBRange>1[6-9]|2[0-9]|3[0-1])\./,/^(?<classC>192)\.(?<classCRange>168)\./,/^(?<linkLocal>169)\.(?<linkLocalRange>254)\./,/^(?<loopback>127)\./,/^(?<ipv6Loopback>::1)$/,/^(?<ipv6LinkLocal>fe80):/i,/^(?<ipv6UniqueLocalFC>fc00):/i,/^(?<ipv6UniqueLocalFD>fd00):/i],Y1=($)=>{if(!$||typeof $!=="string")return!1;let W=$.replace(/^\[|\]$/g,"");if(/^(?<octet>(?<highByte>25[0-5]|(?<midByte>2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/.test(W)){let Q=W.split(".");return Q.length===4&&Q.every((X)=>{let J=parseInt(X,10);return J>=0&&J<=255})}if(W.includes("::")&&(W.match(/::/g)??[]).length>1)return!1;return/^(?<ipv6Address>(?<fullAddress>(?<hexQuad>[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4})|(?<compressedAddress>(?<leadingPart>[0-9a-fA-F]{1,4}:){1,7}:)|(?<mixedCompression>(?<frontPart>[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4})|(?<doubleColonOnly>::)|(?<linkLocal>fe80:(?<linkSuffix>:[0-9a-fA-F]{0,4}){0,4}(?<zoneId>%[0-9a-zA-Z]+)?)|(?<ipv4MappedFull>::ffff:(?<mappedIpv4>(?<mappedOctet>[0-9]{1,3}\.){3}[0-9]{1,3}))|(?<generalPattern>(?<segmentGroup>[0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}))$/.test(W)},Q1=($)=>{if(!$)return!1;let W=$.replace(/^\[|\]$/g,"");return U0.some((Z)=>Z.test(W))},X1=($,W)=>{if(!$||!W.length)return!1;if(W.includes("*"))return!0;return W.includes($)},G0=($,W)=>{if(!W.detectSpoofing||$.length<=1)return!1;if($.length>W.maxChainLength)return!0;if(new Set($).size!==$.length)return!0;let Y=$.filter(Y1).length;if(Y>0&&Y<$.length)return!0;return!1},F0=($,W)=>{if($.length<=1)return!0;let Z=$[$.length-1];return Boolean(Z&&X1(Z,W.trustedProxies))},q0=($,W)=>{if(W==="x-forwarded-for")return $[0];return $[$.length-1]},w0=($)=>{let{clientIp:W,headerName:Z,ipChain:Y,config:Q}=$,X=Q1(W),J=Z==="x-forwarded-for"?X1(Y[Y.length-1]??"",Q.trustedProxies):!0;return{ip:W,isValid:!0,isPrivate:X,source:Z,trusted:J}},N0=()=>({ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}),B0=($,W)=>{for(let Z of W.headerPreference){let Y=$[Z];if(!Y)continue;let Q=Y.split(",").map((M)=>M.trim()).filter(Boolean);if(Q.length===0)continue;if(G0(Q,W))continue;if(Z==="x-forwarded-for"&&!F0(Q,W))continue;let X=q0(Q,Z);if(!X||!Y1(X))continue;if(Q1(X)&&!W.allowPrivateIps)continue;return w0({clientIp:X,headerName:Z,ipChain:Q,config:W})}return N0()},V0=($,W,Z={})=>{let Q={...$._configuration.ipSecurity,...Z},X=B0(W,Q);if(X.isValid)return X;return{ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}},J1=($,W)=>{return V0($,W).ip};var M1=($)=>{if(!$)return;return/boundary\s*=\s*(?<temp1>[^;,\s]*)/i.exec($)?.[1]};var D1=($)=>{if(!$)return{};E0($);let W=O0($),Z=A0(W);return H0(Z)},E0=($)=>{if($.split(/\r\n|\r|\n/).length>100)throw Error("Too many headers: maximum 100 allowed")},O0=($)=>{let W={},Y=$.replace(/\r\n|\r|\n/g,`
9
+ `);if(!Y||!Object.values(I).includes(Y))return{method:"GET",path:Q??"/",protocol:X??"HTTP/1.1",headersRaw:J,rawBody:M};return{method:Y,path:Q??"/",protocol:X??"HTTP/1.1",headersRaw:J,rawBody:M}};var e$=($)=>{if(!$)return{};if(!$.includes("?"))return{};let[,W]=$.split("?");if(!W)return{};let Z={},Y=W.split("&");for(let Q of Y){let[X,J]=Q.split("=");if(X)try{let M=decodeURIComponent(X),q=J?decodeURIComponent(J):"";Z[M]=q}catch{Z[X]=J??""}}return Z};var U0=[/^(?<classA>10)\./,/^(?<classB>172)\.(?<classBRange>1[6-9]|2[0-9]|3[0-1])\./,/^(?<classC>192)\.(?<classCRange>168)\./,/^(?<linkLocal>169)\.(?<linkLocalRange>254)\./,/^(?<loopback>127)\./,/^(?<ipv6Loopback>::1)$/,/^(?<ipv6LinkLocal>fe80):/i,/^(?<ipv6UniqueLocalFC>fc00):/i,/^(?<ipv6UniqueLocalFD>fd00):/i],$1=($)=>{if(!$||typeof $!=="string")return!1;let W=$.replace(/^\[|\]$/g,"");if(/^(?<octet>(?<highByte>25[0-5]|(?<midByte>2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/.test(W)){let Q=W.split(".");return Q.length===4&&Q.every((X)=>{let J=parseInt(X,10);return J>=0&&J<=255})}if(W.includes("::")&&(W.match(/::/g)??[]).length>1)return!1;return/^(?<ipv6Address>(?<fullAddress>(?<hexQuad>[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4})|(?<compressedAddress>(?<leadingPart>[0-9a-fA-F]{1,4}:){1,7}:)|(?<mixedCompression>(?<frontPart>[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4})|(?<doubleColonOnly>::)|(?<linkLocal>fe80:(?<linkSuffix>:[0-9a-fA-F]{0,4}){0,4}(?<zoneId>%[0-9a-zA-Z]+)?)|(?<ipv4MappedFull>::ffff:(?<mappedIpv4>(?<mappedOctet>[0-9]{1,3}\.){3}[0-9]{1,3}))|(?<generalPattern>(?<segmentGroup>[0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}))$/.test(W)},W1=($)=>{if(!$)return!1;let W=$.replace(/^\[|\]$/g,"");return U0.some((Z)=>Z.test(W))},Z1=($,W)=>{if(!$||!W.length)return!1;if(W.includes("*"))return!0;return W.includes($)},G0=($,W)=>{if(!W.detectSpoofing||$.length<=1)return!1;if($.length>W.maxChainLength)return!0;if(new Set($).size!==$.length)return!0;let Y=$.filter($1).length;if(Y>0&&Y<$.length)return!0;return!1},F0=($,W)=>{if($.length<=1)return!0;let Z=$[$.length-1];return Boolean(Z&&Z1(Z,W.trustedProxies))},q0=($,W)=>{if(W==="x-forwarded-for")return $[0];return $[$.length-1]},w0=($)=>{let{clientIp:W,headerName:Z,ipChain:Y,config:Q}=$,X=W1(W),J=Z==="x-forwarded-for"?Z1(Y[Y.length-1]??"",Q.trustedProxies):!0;return{ip:W,isValid:!0,isPrivate:X,source:Z,trusted:J}},N0=()=>({ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}),B0=($,W)=>{for(let Z of W.headerPreference){let Y=$[Z];if(!Y)continue;let Q=Y.split(",").map((M)=>M.trim()).filter(Boolean);if(Q.length===0)continue;if(G0(Q,W))continue;if(Z==="x-forwarded-for"&&!F0(Q,W))continue;let X=q0(Q,Z);if(!X||!$1(X))continue;if(W1(X)&&!W.allowPrivateIps)continue;return w0({clientIp:X,headerName:Z,ipChain:Q,config:W})}return N0()},V0=($,W,Z={})=>{let Q={...$._configuration.ipSecurity,...Z},X=B0(W,Q);if(X.isValid)return X;return{ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}},Y1=($,W)=>{return V0($,W).ip};var Q1=($)=>{if(!$)return;return/boundary\s*=\s*(?<temp1>[^;,\s]*)/i.exec($)?.[1]};var X1=($)=>{if(!$)return{};E0($);let W=O0($),Z=A0(W);return z0(Z)},E0=($)=>{if($.split(/\r\n|\r|\n/).length>100)throw Error("Too many headers: maximum 100 allowed")},O0=($)=>{let W={},Y=$.replace(/\r\n|\r|\n/g,`
14
10
  `).split(`
15
- `);for(let Q of Y){if(!Q.trim())continue;let X=Q.indexOf(":");if(X===-1)continue;let J=Q.slice(0,X).trim(),M=Q.slice(X+1).trim();if(!J)continue;if(!_0(J))throw Error(`Invalid header name: ${J}`);if(J.length>200)throw Error("Header name too long: maximum 200 characters allowed");if(M.length>8192)throw Error("Header value too long: maximum 8192 characters allowed");W[J.toLowerCase()]=M}return W},A0=($)=>{let W={};for(let[Z,Y]of Object.entries($))W[Z]=z0(Y);return W},H0=($)=>$,_0=($)=>{return/^[a-zA-Z0-9!#$%&'*+\-.^_`|~]+$/.test($)},z0=($)=>{return $.replace(/[\x00-\x08\x0A-\x1F\x7F]/g,"")};class _${_rawRequest;_setup;method;path;protocol;headers;body;query;params;ipAddress;rawBody;cookies=new Map;signedCookies=new Map;constructor($,W,Z){this._rawRequest=$,this._setup=W,this.ipAddress=Z??"";let{method:Y,path:Q,protocol:X,headers:J,body:M,query:F,params:w,rawBody:_}=this._parseRequestIntoObject();this.method=Y,this.path=Q,this.protocol=X,this.headers=J,this.body=M,this.query=F??{},this.params=w??{},this.rawBody=_;let V=J1(this._setup,J);if(V)this.ipAddress=V}_parseRequestIntoObject(){let $=this._rawRequest.toString(),{method:W,path:Z,protocol:Y,headersRaw:Q,rawBody:X}=W1($),J=D1(Q),M=J["content-type"],F=M?.split(";")[0]?.trim().toLowerCase(),w=M1(M);return{method:W,path:Z,protocol:Y,headers:J,body:$1(X,{headerContentType:F,boundary:w,config:this._setup._configuration.bodyParser}),query:Z1(Z),params:{},rawBody:X}}}var G1=q$(Y$(),1);var K1=($,W)=>{let Z=W?.encoding??"utf8";if($===null||$===void 0)return"";if(Buffer.isBuffer($))return z$($,Z);if($ instanceof Uint8Array)return I0($,Z);if($ instanceof ArrayBuffer)return T0($,Z);if(typeof $==="string")return $;if(typeof $==="object")return S0($);return String($)},z$=($,W)=>{if(W==="base64")return $.toString("base64");if(W==="binary")return $.toString("binary");return $.toString("utf8")},I0=($,W)=>{let Z=Buffer.from($);return z$(Z,W)},T0=($,W)=>{let Z=Buffer.from($);return z$(Z,W)},S0=($)=>{try{return JSON.stringify($)}catch(W){return String($)}};var j1=new Map;for(let[$,W]of Object.entries(b)){let Y=n[$];j1.set(W,Y)}var U1=($)=>{let W=j1.get($);if(!W)throw Error(`Unknown status code: ${$}`);return W};var L0=($,W)=>{if(typeof W!=="string")throw Error(`Header value must be a string, got ${typeof W}`);if(W.includes("\r")||W.includes(`
16
- `))throw Error(`Header value contains invalid line break characters: ${$}`);let Z=[/[\r\n](?:set-cookie|location|authorization|www-authenticate):/i,/\r\n\r\n|\n\n/,/[\r\n]http\/\d\.\d\s+\d+/i];for(let Y of Z)if(Y.test(W))throw Error(`Header value contains suspicious injection pattern: ${$}`)},R0=($)=>{for(let[W,Z]of Object.entries($))L0(W,Z)},I$=($)=>{let W={};for(let[Z,Y]of Object.entries($))if(Y!==void 0)W[Z]=Y;return R0(W),W};var D$=($)=>{if(v0($))return $.length;if(typeof $==="string")return Buffer.byteLength($,"utf8");if(P0($))try{let W=JSON.stringify($);return Buffer.byteLength(W,"utf8")}catch{return 0}return 0},v0=($)=>typeof Buffer<"u"&&Buffer.isBuffer($),P0=($)=>typeof $==="object"&&$!==null;class T${_request;_statusCode=b.ok;_status=n.ok;_headers={};_setCookies=[];_body="";_stringBody="";_encoding=t$.utf8;constructor($){this._request=$,this._setSecurityHeaders()}_parseResponseIntoString(){let $=`${this._request.protocol} ${this._statusCode} ${this._status}`,W=Object.entries(this._headers).map(([F,w])=>`${F}: ${w}`),Z=this._setCookies.map((F)=>`Set-Cookie: ${F}`),Y=[...W,...Z],Q=M$(this._headers["content-type"],this._body),X=K1(this._body,{encoding:Q});this._encoding=Q;let J=Y.length>0?`${Y.join(`
17
- `)}
18
- `:"";this._stringBody=`${$}
19
- ${J}
20
- ${X}`;let M=D$(this._stringBody);this._setHeadersIfNotSet({Date:G1.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":String(M)})}_setHeadersIfNotSet($){let W={};for(let[Y,Q]of Object.entries($))if(Q!==void 0&&!(Y in this._headers))W[Y]=Q;let Z=I$(W);Object.assign(this._headers,Z)}_setBody($){if(this._body=$,!this._headers["content-type"]){let W=e$($);this._setHeadersIfNotSet({"Content-Type":W})}}setStatusCode($){this._statusCode=$,this._status=U1($)}addHeaders($){let W=I$($);for(let[Z,Y]of Object.entries(W))if(Z==="Set-Cookie"){if(Y)this._setCookies.push(Y)}else this._headers[Z]=Y}removeHeaders($){for(let W of $)delete this._headers[W]}_setSecurityHeaders(){this._setHeadersIfNotSet({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"1; mode=block","Referrer-Policy":"strict-origin-when-cross-origin"})}}class S${_request;_response;request;response;state={};cookies={set:($,W,Z)=>{},sign:($,W)=>"",unsign:($,W)=>!1};constructor($,W,Z){this._request=new _$($,W,Z),this._response=new T$(this._request),this.request=this._request,this.response=this._response}}var K$={json:{maxSize:262144,maxDepth:10,allowPrototypeProperties:!1,maxKeys:1000,maxStringLength:1048576,maxArrayLength:1e4},fileUploads:{maxFileSize:10485760,maxTotalSize:52428800,maxFiles:10,allowedExtensions:[],blockedExtensions:[".exe",".bat",".cmd",".scr",".pif",".com"],maxFilenameLength:255},urlEncoded:{maxSize:1048576,maxFields:1000,maxFieldNameLength:100,maxFieldLength:1048576}},F1={trustedProxies:["127.0.0.1","::1"],allowPrivateIps:!0,headerPreference:["x-forwarded-for","x-real-ip","cf-connecting-ip","x-client-ip","true-client-ip"],maxChainLength:10,detectSpoofing:!0},b0={port:5000,host:"0.0.0.0",networkLogs:!1,gracefulShutdownTimeout:"15m",cors:{enabled:!1},bodyParser:K$,ipSecurity:F1},k0=($)=>{if($.maxSize<1)throw Error("bodyParser.json.maxSize must be at least 1 byte");if($.maxDepth<1)throw Error("bodyParser.json.maxDepth must be at least 1");if($.maxKeys<1)throw Error("bodyParser.json.maxKeys must be at least 1");if($.maxStringLength<1)throw Error("bodyParser.json.maxStringLength must be at least 1 byte");if($.maxArrayLength<1)throw Error("bodyParser.json.maxArrayLength must be at least 1")},C0=($)=>{if($.maxFileSize<1)throw Error("bodyParser.fileUploads.maxFileSize must be at least 1 byte");if($.maxTotalSize<1)throw Error("bodyParser.fileUploads.maxTotalSize must be at least 1 byte");if($.maxFiles<1)throw Error("bodyParser.fileUploads.maxFiles must be at least 1");if($.maxFilenameLength<1)throw Error("bodyParser.fileUploads.maxFilenameLength must be at least 1 character")},x0=($)=>{if($.maxSize<1)throw Error("bodyParser.urlEncoded.maxSize must be at least 1 byte");if($.maxFields<1)throw Error("bodyParser.urlEncoded.maxFields must be at least 1");if($.maxFieldNameLength<1)throw Error("bodyParser.urlEncoded.maxFieldNameLength must be at least 1 character");if($.maxFieldLength<1)throw Error("bodyParser.urlEncoded.maxFieldLength must be at least 1 byte")},y0=($)=>{if(!Array.isArray($.trustedProxies))throw Error("ipSecurity.trustedProxies must be an array");if(!Array.isArray($.headerPreference))throw Error("ipSecurity.headerPreference must be an array");if($.headerPreference.length===0)throw Error("ipSecurity.headerPreference must contain at least one header");if($.maxChainLength<1)throw Error("ipSecurity.maxChainLength must be at least 1");if($.maxChainLength>50)throw Error("ipSecurity.maxChainLength must not exceed 50 to prevent DoS attacks")},h0=($)=>{if($.allowPrototypeProperties)U.warn("[SECURITY WARNING] bodyParser.json.allowPrototypeProperties is enabled. This allows prototype pollution attacks. Only enable this if you absolutely need it and have other protections in place.");if($.maxSize>10485760)U.warn(`[SECURITY WARNING] bodyParser.json.maxSize is set to ${$.maxSize} bytes (${Math.round($.maxSize/1024/1024)}MB). Large JSON payloads can cause memory exhaustion and DoS attacks. Consider if this size is necessary.`);if($.maxDepth>50)U.warn(`[SECURITY WARNING] bodyParser.json.maxDepth is set to ${$.maxDepth}. Very deep JSON nesting can cause stack overflow attacks. Consider if this depth is necessary.`)},u0=($)=>{if($.maxFileSize>104857600)U.warn(`[SECURITY WARNING] bodyParser.fileUploads.maxFileSize is set to ${$.maxFileSize} bytes (${Math.round($.maxFileSize/1024/1024)}MB). Large file uploads can consume significant server resources.`);if($.maxTotalSize>1073741824)U.warn(`[SECURITY WARNING] bodyParser.fileUploads.maxTotalSize is set to ${$.maxTotalSize} bytes (${Math.round($.maxTotalSize/1024/1024/1024)}GB). Very large total upload sizes can cause memory and disk space exhaustion.`);let W=[".exe",".bat",".cmd",".scr",".pif",".com",".vbs",".jar",".app"],Z=$.allowedExtensions.filter((Y)=>W.includes(Y.toLowerCase()));if(Z.length>0)U.warn(`[SECURITY WARNING] bodyParser.fileUploads.allowedExtensions includes dangerous file types: ${Z.join(", ")}. This could allow execution of malicious files. Only allow these if absolutely necessary.`);if($.blockedExtensions.length===0&&$.allowedExtensions.length===0)U.warn("[SECURITY WARNING] File uploads have no extension restrictions (no blockedExtensions and no allowedExtensions). Consider adding blockedExtensions or allowedExtensions to improve security.")},m0=($)=>{if($.trustedProxies.length===0)U.warn("[SECURITY WARNING] ipSecurity.trustedProxies is empty. No proxy headers will be trusted, which may prevent proper client IP detection.");if($.maxChainLength>20)U.warn(`[SECURITY WARNING] ipSecurity.maxChainLength is set to ${$.maxChainLength}. Very long proxy chains can consume significant resources and may indicate amplification attacks.`);if(!$.detectSpoofing)U.warn("[SECURITY WARNING] ipSecurity.detectSpoofing is disabled. This reduces protection against IP spoofing attacks. Only disable if you have other protective measures.")},p0=($,W)=>{if(W?.bodyParser)$.bodyParser={json:{...K$.json,...W.bodyParser.json},fileUploads:{...K$.fileUploads,...W.bodyParser.fileUploads},urlEncoded:{...K$.urlEncoded,...W.bodyParser.urlEncoded}},g0($.bodyParser)},f0=($,W)=>{if(W?.ipSecurity)$.ipSecurity={...F1,...W.ipSecurity},y0($.ipSecurity),m0($.ipSecurity)},l0=($,W)=>{if(W?.port!==void 0){let Z=Number(W.port);if(isNaN(Z)||Z<1||Z>65535)throw Error("Invalid port number");$.port=Z}},g0=($)=>{k0($.json),C0($.fileUploads),x0($.urlEncoded),h0($.json),u0($.fileUploads)},q1=($)=>{let W={...b0};return Object.assign(W,$),p0(W,$),f0(W,$),l0(W,$),W};class L${_beforeRouting;_beforeAll;_afterAll;_onError;_onNotFound;constructor(){this._beforeRouting=new Set,this._beforeAll=new Set,this._afterAll=new Set,this._onError=($,W)=>{return U.error("Error while handeling your request: ",W),$.response.setStatusCode(b.internalServerError),{success:!1,message:"Internal Server Error"}},this._onNotFound=($)=>{return $.response.setStatusCode(b.notFound),{success:!1,message:"404 Not Found"}}}_addBeforeRoutingHooks($,W){this._validateHandlersArray($,"beforeRouting");for(let Z of $)this._beforeRouting.add({handler:Z,options:W??{routesToExclude:[],routesToInclude:[]}})}_addBeforeHooks($,W){this._validateHandlersArray($,"beforeAll");for(let Z of $)this._beforeAll.add({handler:Z,options:W??{routesToExclude:[],routesToInclude:[]}})}_addAfterHooks($,W){this._validateHandlersArray($,"afterAll");for(let Z of $)this._afterAll.add({handler:Z,options:W??{routesToExclude:[],routesToInclude:[]}})}_validateHandlersArray($,W){if(!Array.isArray($)){let Z=typeof $;throw Error(`YinzerFlow: ${W}() expects an array of handler functions, but received ${Z}.${Z==="function"?`
11
+ `);for(let Q of Y){if(!Q.trim())continue;let X=Q.indexOf(":");if(X===-1)continue;let J=Q.slice(0,X).trim(),M=Q.slice(X+1).trim();if(!J)continue;if(!H0(J))throw Error(`Invalid header name: ${J}`);if(J.length>200)throw Error("Header name too long: maximum 200 characters allowed");if(M.length>8192)throw Error("Header value too long: maximum 8192 characters allowed");W[J.toLowerCase()]=M}return W},A0=($)=>{let W={};for(let[Z,Y]of Object.entries($))W[Z]=_0(Y);return W},z0=($)=>$,H0=($)=>{return/^[a-zA-Z0-9!#$%&'*+\-.^_`|~]+$/.test($)},_0=($)=>{return $.replace(/[\x00-\x08\x0A-\x1F\x7F]/g,"")};class E${_rawRequest;_setup;method;path;protocol;headers;body;query;params;ipAddress;rawBody;cookies=new Map;signedCookies=new Map;constructor($,W,Z){this._rawRequest=$,this._setup=W,this.ipAddress=Z??"";let{method:Y,path:Q,protocol:X,headers:J,body:M,query:q,params:B,rawBody:H}=this._parseRequestIntoObject();this.method=Y,this.path=Q,this.protocol=X,this.headers=J,this.body=M,this.query=q??{},this.params=B??{},this.rawBody=H;let V=Y1(this._setup,J);if(V)this.ipAddress=V}_parseRequestIntoObject(){let $=this._rawRequest.toString(),{method:W,path:Z,protocol:Y,headersRaw:Q,rawBody:X}=o$($),J=X1(Q),M=J["content-type"],q=M?.split(";")[0]?.trim().toLowerCase(),B=Q1(M);return{method:W,path:Z,protocol:Y,headers:J,body:t$(X,{headerContentType:q,boundary:B,config:this._setup._configuration.bodyParser}),query:e$(Z),params:{},rawBody:X}}}var J1=($,W)=>{let Z=W?.encoding??"utf8";if($===null||$===void 0)return"";if(Buffer.isBuffer($))return O$($,Z);if($ instanceof Uint8Array)return I0($,Z);if($ instanceof ArrayBuffer)return T0($,Z);if(typeof $==="string")return $;if(typeof $==="object")return S0($);return String($)},O$=($,W)=>{if(W==="base64")return $.toString("base64");if(W==="binary")return $.toString("binary");return $.toString("utf8")},I0=($,W)=>{let Z=Buffer.from($);return O$(Z,W)},T0=($,W)=>{let Z=Buffer.from($);return O$(Z,W)},S0=($)=>{try{return JSON.stringify($)}catch(W){return String($)}};var M1=new Map;for(let[$,W]of Object.entries(b)){let Y=n[$];M1.set(W,Y)}var j1=($)=>{let W=M1.get($);if(!W)throw Error(`Unknown status code: ${$}`);return W};var L0=($,W)=>{if(typeof W!=="string")throw Error(`Header value must be a string, got ${typeof W}`);if(W.includes("\r")||W.includes(`
12
+ `))throw Error(`Header value contains invalid line break characters: ${$}`);let Z=[/[\r\n](?:set-cookie|location|authorization|www-authenticate):/i,/\r\n\r\n|\n\n/,/[\r\n]http\/\d\.\d\s+\d+/i];for(let Y of Z)if(Y.test(W))throw Error(`Header value contains suspicious injection pattern: ${$}`)},R0=($)=>{for(let[W,Z]of Object.entries($))L0(W,Z)},A$=($)=>{let W={};for(let[Z,Y]of Object.entries($))if(Y!==void 0)W[Z]=Y;return R0(W),W};var D1=()=>{let $=new Date,W=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Z=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Y=(Q)=>Q<10?`0${Q}`:String(Q);return`${W[$.getUTCDay()]}, ${Y($.getUTCDate())} ${Z[$.getUTCMonth()]} ${$.getUTCFullYear()} ${Y($.getUTCHours())}:${Y($.getUTCMinutes())}:${Y($.getUTCSeconds())} GMT`},K1=D1(),v0=setInterval(()=>{K1=D1()},1000);v0.unref();class z${_request;_statusCode=b.ok;_status=n.ok;_headers={};_setCookies=[];_body="";_stringBody="";_encoding=a$.utf8;constructor($){this._request=$,this._setSecurityHeaders()}_parseResponseIntoString(){let $=`${this._request.protocol} ${this._statusCode} ${this._status}`,W=J$(this._headers["content-type"],this._body),Z=J1(this._body,{encoding:W});this._setHeadersIfNotSet({Date:K1,"Content-Length":String(Buffer.byteLength(Z,"utf8"))}),this._encoding=W;let Y=Object.entries(this._headers).map(([M,q])=>`${M}: ${q}`),Q=this._setCookies.map((M)=>`Set-Cookie: ${M}`),X=[...Y,...Q],J=X.length>0?`${X.join(`\r
13
+ `)}\r
14
+ `:"";this._stringBody=`${$}\r
15
+ ${J}\r
16
+ ${Z}`}_setHeadersIfNotSet($){let W={};for(let[Y,Q]of Object.entries($))if(Q!==void 0&&!(Y in this._headers))W[Y]=Q;let Z=A$(W);Object.assign(this._headers,Z)}_setBody($){if(this._body=$,!this._headers["content-type"]){let W=i$($);this._setHeadersIfNotSet({"Content-Type":W})}}setStatusCode($){this._statusCode=$,this._status=j1($)}addHeaders($){let W=A$($);for(let[Z,Y]of Object.entries(W))if(Z==="Set-Cookie"){if(Y)this._setCookies.push(Y)}else this._headers[Z]=Y}removeHeaders($){for(let W of $)delete this._headers[W]}_setSecurityHeaders(){this._setHeadersIfNotSet({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"1; mode=block","Referrer-Policy":"strict-origin-when-cross-origin"})}}class H${_request;_response;request;response;state={};cookies={set:($,W,Z)=>{},sign:($,W)=>"",unsign:($,W)=>!1};constructor($,W,Z){this._request=new E$($,W,Z),this._response=new z$(this._request),this.request=this._request,this.response=this._response}}var M$={json:{maxSize:262144,maxDepth:10,allowPrototypeProperties:!1,maxKeys:1000,maxStringLength:1048576,maxArrayLength:1e4},fileUploads:{maxFileSize:10485760,maxTotalSize:52428800,maxFiles:10,allowedExtensions:[],blockedExtensions:[".exe",".bat",".cmd",".scr",".pif",".com"],maxFilenameLength:255},urlEncoded:{maxSize:1048576,maxFields:1000,maxFieldNameLength:100,maxFieldLength:1048576}},U1={trustedProxies:["127.0.0.1","::1"],allowPrivateIps:!0,headerPreference:["x-forwarded-for","x-real-ip","cf-connecting-ip","x-client-ip","true-client-ip"],maxChainLength:10,detectSpoofing:!0},P0={port:5000,host:"0.0.0.0",networkLogs:!1,gracefulShutdownTimeout:"15m",cors:{enabled:!1},bodyParser:M$,ipSecurity:U1},b0=($)=>{if($.maxSize<1)throw Error("bodyParser.json.maxSize must be at least 1 byte");if($.maxDepth<1)throw Error("bodyParser.json.maxDepth must be at least 1");if($.maxKeys<1)throw Error("bodyParser.json.maxKeys must be at least 1");if($.maxStringLength<1)throw Error("bodyParser.json.maxStringLength must be at least 1 byte");if($.maxArrayLength<1)throw Error("bodyParser.json.maxArrayLength must be at least 1")},k0=($)=>{if($.maxFileSize<1)throw Error("bodyParser.fileUploads.maxFileSize must be at least 1 byte");if($.maxTotalSize<1)throw Error("bodyParser.fileUploads.maxTotalSize must be at least 1 byte");if($.maxFiles<1)throw Error("bodyParser.fileUploads.maxFiles must be at least 1");if($.maxFilenameLength<1)throw Error("bodyParser.fileUploads.maxFilenameLength must be at least 1 character")},x0=($)=>{if($.maxSize<1)throw Error("bodyParser.urlEncoded.maxSize must be at least 1 byte");if($.maxFields<1)throw Error("bodyParser.urlEncoded.maxFields must be at least 1");if($.maxFieldNameLength<1)throw Error("bodyParser.urlEncoded.maxFieldNameLength must be at least 1 character");if($.maxFieldLength<1)throw Error("bodyParser.urlEncoded.maxFieldLength must be at least 1 byte")},C0=($)=>{if(!Array.isArray($.trustedProxies))throw Error("ipSecurity.trustedProxies must be an array");if(!Array.isArray($.headerPreference))throw Error("ipSecurity.headerPreference must be an array");if($.headerPreference.length===0)throw Error("ipSecurity.headerPreference must contain at least one header");if($.maxChainLength<1)throw Error("ipSecurity.maxChainLength must be at least 1");if($.maxChainLength>50)throw Error("ipSecurity.maxChainLength must not exceed 50 to prevent DoS attacks")},y0=($)=>{if($.allowPrototypeProperties)U.warn("[SECURITY WARNING] bodyParser.json.allowPrototypeProperties is enabled. This allows prototype pollution attacks. Only enable this if you absolutely need it and have other protections in place.");if($.maxSize>10485760)U.warn(`[SECURITY WARNING] bodyParser.json.maxSize is set to ${$.maxSize} bytes (${Math.round($.maxSize/1024/1024)}MB). Large JSON payloads can cause memory exhaustion and DoS attacks. Consider if this size is necessary.`);if($.maxDepth>50)U.warn(`[SECURITY WARNING] bodyParser.json.maxDepth is set to ${$.maxDepth}. Very deep JSON nesting can cause stack overflow attacks. Consider if this depth is necessary.`)},h0=($)=>{if($.maxFileSize>104857600)U.warn(`[SECURITY WARNING] bodyParser.fileUploads.maxFileSize is set to ${$.maxFileSize} bytes (${Math.round($.maxFileSize/1024/1024)}MB). Large file uploads can consume significant server resources.`);if($.maxTotalSize>1073741824)U.warn(`[SECURITY WARNING] bodyParser.fileUploads.maxTotalSize is set to ${$.maxTotalSize} bytes (${Math.round($.maxTotalSize/1024/1024/1024)}GB). Very large total upload sizes can cause memory and disk space exhaustion.`);let W=[".exe",".bat",".cmd",".scr",".pif",".com",".vbs",".jar",".app"],Z=$.allowedExtensions.filter((Y)=>W.includes(Y.toLowerCase()));if(Z.length>0)U.warn(`[SECURITY WARNING] bodyParser.fileUploads.allowedExtensions includes dangerous file types: ${Z.join(", ")}. This could allow execution of malicious files. Only allow these if absolutely necessary.`);if($.blockedExtensions.length===0&&$.allowedExtensions.length===0)U.warn("[SECURITY WARNING] File uploads have no extension restrictions (no blockedExtensions and no allowedExtensions). Consider adding blockedExtensions or allowedExtensions to improve security.")},u0=($)=>{if($.trustedProxies.length===0)U.warn("[SECURITY WARNING] ipSecurity.trustedProxies is empty. No proxy headers will be trusted, which may prevent proper client IP detection.");if($.maxChainLength>20)U.warn(`[SECURITY WARNING] ipSecurity.maxChainLength is set to ${$.maxChainLength}. Very long proxy chains can consume significant resources and may indicate amplification attacks.`);if(!$.detectSpoofing)U.warn("[SECURITY WARNING] ipSecurity.detectSpoofing is disabled. This reduces protection against IP spoofing attacks. Only disable if you have other protective measures.")},m0=($,W)=>{if(W?.bodyParser)$.bodyParser={json:{...M$.json,...W.bodyParser.json},fileUploads:{...M$.fileUploads,...W.bodyParser.fileUploads},urlEncoded:{...M$.urlEncoded,...W.bodyParser.urlEncoded}},l0($.bodyParser)},f0=($,W)=>{if(W?.ipSecurity)$.ipSecurity={...U1,...W.ipSecurity},C0($.ipSecurity),u0($.ipSecurity)},p0=($,W)=>{if(W?.port!==void 0){let Z=Number(W.port);if(isNaN(Z)||Z<1||Z>65535)throw Error("Invalid port number");$.port=Z}},l0=($)=>{b0($.json),k0($.fileUploads),x0($.urlEncoded),y0($.json),h0($.fileUploads)},G1=($)=>{let W={...P0};return Object.assign(W,$),m0(W,$),f0(W,$),p0(W,$),W};class _${_beforeRouting;_beforeAll;_afterAll;_onError;_onNotFound;constructor(){this._beforeRouting=new Set,this._beforeAll=new Set,this._afterAll=new Set,this._onError=($,W)=>{return U.error("Error while handling your request: ",W),$.response.setStatusCode(b.internalServerError),{success:!1,message:"Internal Server Error"}},this._onNotFound=($)=>{return $.response.setStatusCode(b.notFound),{success:!1,message:"404 Not Found"}}}_addBeforeRoutingHooks($,W){this._validateHandlersArray($,"beforeRouting");for(let Z of $)this._beforeRouting.add({handler:Z,options:W??{routesToExclude:[],routesToInclude:[]}})}_addBeforeHooks($,W){this._validateHandlersArray($,"beforeAll");for(let Z of $)this._beforeAll.add({handler:Z,options:W??{routesToExclude:[],routesToInclude:[]}})}_addAfterHooks($,W){this._validateHandlersArray($,"afterAll");for(let Z of $)this._afterAll.add({handler:Z,options:W??{routesToExclude:[],routesToInclude:[]}})}_validateHandlersArray($,W){if(!Array.isArray($)){let Z=typeof $;throw Error(`YinzerFlow: ${W}() expects an array of handler functions, but received ${Z}.${Z==="function"?`
21
17
 
22
18
  ❌ Incorrect: app.${W}${E.red}(${E.reset}(ctx) => { ... }${E.red})${E.reset}
23
19
  ✅ Correct: app.${W}${E.green}([${E.reset}(ctx) => { ... }${E.green}])${E.reset}
@@ -27,16 +23,16 @@ Note: Wrap your handler function in ${E.magenta}square brackets${E.reset} to mak
27
23
  `:`
28
24
 
29
25
  Expected: Array<HandlerCallback>
30
- Received: ${Z}`}`)}if($.length===0){U.warn(`${W}() called with empty array. No hooks will be registered.`);return}for(let Z=0;Z<$.length;Z++){let Y=$[Z];if(typeof Y!=="function")throw Error(`YinzerFlow: ${W}() array contains non-function at index ${Z}. Expected: function, received: ${typeof Y}`)}}_addOnError($){this._onError=$}_addOnNotFound($){this._onNotFound=$}}var w1=($)=>{let W=[],Z=$.path.replace(/:\w+/g,(Y)=>{let Q=Y.slice(1);return W.push(Q),"([^/]+)"}).replace(/\//g,"\\/");return{...$,pattern:new RegExp(`^${Z}$`),paramNames:W,isParameterized:!0}};var R$=($)=>{let[W]=$.split("?");if(!W)return"";if([W]=W.split("#"),!W)return"";try{W=decodeURIComponent(W)}catch(Z){U.warn("Failed to decode URL path",{path:W})}if(W=W.startsWith("/")?W:`/${W}`,W=W.replace(/\/\/+/g,"/"),W=d0(W),W.length>1&&W.endsWith("/"))W=W.slice(0,-1);return W},d0=($)=>{let W=$.split("/"),Z=[];for(let Q of W){if(Q==="."||Q===""){if(Q===""&&Z.length===0)Z.push(Q);continue}if(Q===".."){if(Z.length>1)Z.pop()}else Z.push(Q)}return Z.join("/")||"/"},v$=($)=>$.replace(/:\w+/g,":param");var N1=($)=>{let W=$.match(/:\w+/g);if(!W)return;let Z=W.map((Q)=>Q.slice(1)),Y=new Set(Z);if(Z.length!==Y.size){let Q=Z.filter((X,J)=>Z.indexOf(X)!==J);throw Error(`Route ${$} has duplicate parameter names: ${Q.join(", ")}. Parameter names must be unique within a route for clarity and to prevent conflicts.`)}};class P${_exactRoutes=new Map;_parameterizedRoutes=new Map;_register({method:$,path:W,handler:Z,options:Y}){let Q=R$(W),X=Q.includes(":");if(X)N1(Q);if(this._hasExactRoutePattern($,Q))throw Error(`Route ${Q} already exists for method ${$}`);let J={method:$,path:Q,handler:Z,options:Y,params:{}};if(X)this._storeParameterizedRoute($,J);else this._storeExactRoute($,Q,J)}_findRoute($,W){let Z=R$(W),Y=this._exactRoutes.get($)?.get(Z);if(Y)return Y;let Q=this._findParameterizedRoute($,Z);if(Q)return Q;return}_hasExactRoutePattern($,W){if(this._exactRoutes.get($)?.has(W))return!0;if(W.includes(":")){let Z=v$(W),Y=this._parameterizedRoutes.get($);if(Y)return Y.some((Q)=>v$(Q.path)===Z)}else{let Z=this._parameterizedRoutes.get($);if(Z)return Z.some((Y)=>Y.path===W)}return!1}_storeExactRoute($,W,Z){if(!this._exactRoutes.has($))this._exactRoutes.set($,new Map);this._exactRoutes.get($)?.set(W,Z)}_storeParameterizedRoute($,W){if(!this._parameterizedRoutes.has($))this._parameterizedRoutes.set($,[]);let Z=w1(W);this._parameterizedRoutes.get($)?.push(Z)}_findParameterizedRoute($,W){let Z=this._parameterizedRoutes.get($);if(!Z)return;for(let Y of Z){let Q=W.match(Y.pattern);if(Q){let X={};for(let J=0;J<Y.paramNames.length;J++){let M=Q[J+1],F=Y.paramNames[J];if(M!==void 0&&F!==void 0)X[F]=M}return{...Y,params:X}}}return}}var x=($)=>({beforeHooks:$?.beforeHooks??[],afterHooks:$?.afterHooks??[]}),b$=($,W)=>({beforeHooks:[...$.beforeHooks??[],...W?.beforeHooks??[]],afterHooks:[...W?.afterHooks??[],...$.afterHooks??[]]}),k$=($,W)=>{let Z=$.endsWith("/")?$.slice(0,-1):$,Y=W.startsWith("/")?W:`/${W}`;return`${Z}${Y}`};class j${_setup;_prefix;_options;constructor($,W,Z){this._setup=$,this._prefix=W,this._options=x(Z)}_createRouteHandler($){return(W,Z,Y)=>{let Q=k$(this._prefix,W),X=b$(this._options,Y);if(this._setup._routeRegistry._register({method:$,handler:Z,path:Q,options:X,params:{}}),$===I.get)this._setup._routeRegistry._register({method:I.head,handler:Z,path:Q,options:X,params:{}})}}get=this._createRouteHandler(I.get);head=this._createRouteHandler(I.head);post=this._createRouteHandler(I.post);put=this._createRouteHandler(I.put);delete=this._createRouteHandler(I.delete);patch=this._createRouteHandler(I.patch);options=this._createRouteHandler(I.options);group($,W,Z){let Y=k$(this._prefix,$),Q=b$(this._options,Z),X=new j$(this._setup,Y,Q);return W(X),X}}class C${_configuration;_routeRegistry=new P$;_hooks=new L$;constructor($){this._configuration=q1($)}get($,W,Z){let Y=x(Z);this._routeRegistry._register({method:I.get,handler:W,path:$,options:Y,params:{}}),this._routeRegistry._register({method:I.head,handler:W,path:$,options:Y,params:{}})}head($,W,Z){this._routeRegistry._register({method:I.head,handler:W,path:$,options:x(Z),params:{}})}post($,W,Z){this._routeRegistry._register({method:I.post,handler:W,path:$,options:x(Z),params:{}})}put($,W,Z){this._routeRegistry._register({method:I.put,handler:W,path:$,options:x(Z),params:{}})}patch($,W,Z){this._routeRegistry._register({method:I.patch,handler:W,path:$,options:x(Z),params:{}})}delete($,W,Z){this._routeRegistry._register({method:I.delete,handler:W,path:$,options:x(Z),params:{}})}options($,W,Z){this._routeRegistry._register({method:I.options,handler:W,path:$,options:x(Z),params:{}})}group($,W,Z){let Y=new j$(this,$,Z);return W(Y),Y}beforeRouting($,W){this._hooks._addBeforeRoutingHooks($,W)}beforeAll($,W){this._hooks._addBeforeHooks($,W)}afterAll($,W){this._hooks._addAfterHooks($,W)}onError($){this._hooks._addOnError($)}onNotFound($){this._hooks._addOnNotFound($)}}var B1={prefix:"NETWORK",logLevel:"off",logger:void 0},L={log:a(B1),enable:($)=>{L.log=a({...B1,logLevel:r.info,logger:$})}},V1=($)=>{if($>=200&&$<300)return"✅";if($>=300&&$<400)return"\uD83D\uDD04";if($>=400&&$<500)return"❌";if($>=500)return"\uD83D\uDCA5";return"❓"},x$=[{maxTime:50,emoji:"⚡",phrase:"faster than a Stillers touchdown!"},{maxTime:100,emoji:"\uD83D\uDD25",phrase:"smooth as butter n'at!"},{maxTime:200,emoji:"✅",phrase:"not bad yinz!"},{maxTime:500,emoji:"⚠️",phrase:"slowin' down a bit there"},{maxTime:1000,emoji:"\uD83D\uDC0C",phrase:"that's draggin' n'at"},{maxTime:1/0,emoji:"\uD83D\uDCA5",phrase:"what a jagoff response time!"}],E1=($)=>{let W=x$.find((Z)=>$<Z.maxTime)??x$[x$.length-1];if(!W)throw Error("No threshold found for performance details");L.log.warn(`${E.magenta} ${W.emoji} Response time: ${$}ms - ${W.phrase}${E.reset}`)};var O1=()=>{let $=new Map;return{get:async(W)=>Promise.resolve($.get(W)),set:async(W,Z)=>{return $.set(W,Z),Promise.resolve()},delete:async(W)=>{return $.delete(W),Promise.resolve()},destroy:async()=>{return $.clear(),Promise.resolve()}}};import{Redis as A1}from"ioredis";var C=($)=>{if(typeof $==="number")return $;if(typeof $!=="string")throw Error("Invalid time format. Expected format: 1ms, 1s, 1m, 1h, 1d");if($.length<2)throw Error("Invalid time format. Expected format: 1ms, 1s, 1m, 1h, 1d");if($.length>3)throw Error("Invalid time format. Expected format: 1ms, 1s, 1m, 1h, 1d");let W=$.includes("ms")?$.slice(-2):$.slice(-1),Z=$.includes("ms")?$.slice(0,-2):$.slice(0,-1);if(!["ms","s","m","h","d"].includes(W))throw Error(`Invalid time unit: "${W}". Expected: s (seconds), m (minutes), h (hours), or d (days)`);let Y=Number(Z);if(isNaN(Y)||Y<=0)throw Error(`Invalid time value: "${Z}". Must be a positive number`);switch(W){case"ms":return Y;case"s":return Y*1000;case"m":return Y*60*1000;case"h":return Y*60*60*1000;case"d":return Y*24*60*60*1000;default:throw Error(`Unsupported time unit: "${W}"`)}};var H1=async($)=>{let{store:W}=$;if(W.type!=="redis")throw Error(`Expected Redis store configuration but got: ${JSON.stringify(W)}`);let{client:Z,keyPrefix:Y="rate_limit:",maxRetries:Q=3,retryDelay:X=1000}=W,J=C(X),M=!1;return await(async()=>{for(let w=1;w<=Q;w++)try{await Z.ping(),M=!0,U.info(`[RedisStore] Successfully connected to Redis (attempt ${w})`);return}catch(_){if(U.warn(`[RedisStore] Redis connection attempt ${w}/${Q} failed:`,_),w<Q)U.info(`[RedisStore] Retrying connection in ${X}...`),await new Promise((V)=>{setTimeout(V,J)});else U.error("[RedisStore] All Redis connection attempts failed. Store will operate in degraded mode."),M=!1}})(),{get:async(w)=>n0({client:Z,key:w,keyPrefix:Y,connectionHealthy:M}),set:async(w,_)=>i0({client:Z,config:$,key:w,value:_,keyPrefix:Y,connectionHealthy:M}),delete:async(w)=>t0({client:Z,key:w,keyPrefix:Y,connectionHealthy:M}),destroy:async()=>o0({client:Z,keyPrefix:Y,connectionHealthy:M})}},y$=($,W)=>`${W}${$}`,s0=($)=>{try{return JSON.stringify($)}catch(W){throw U.error("[RedisStore] Failed to serialize value:",W),Error("Failed to serialize rate limit data")}},c0=($)=>{try{return JSON.parse($)}catch(W){throw U.error("[RedisStore] Failed to deserialize value:",W),Error("Failed to deserialize rate limit data")}},U$=($,W,Z)=>{if(Z)U.warn(`[RedisStore] Redis ${$} failed (connection was healthy):`,W);else U.error(`[RedisStore] Redis ${$} failed (connection unhealthy):`,W)},r0=async({client:$,key:W,value:Z,ttlSeconds:Y})=>{try{if($ instanceof A1)await $.set(W,Z,"EX",Y);else await $.set(W,Z,{EX:Y})}catch(Q){if(Q instanceof Error)throw Error(`Unsupported Redis client or Redis operation failed: ${Q.message}`);throw Q}},a0=async({client:$,key:W,value:Z})=>{try{if($ instanceof A1)await $.set(W,Z,"KEEPTTL");else await $.set(W,Z,{KEEPTTL:!0})}catch(Y){if(Y instanceof Error)throw Error(`Unsupported Redis client or Redis operation failed: ${Y.message}`);throw Y}},n0=async({client:$,key:W,keyPrefix:Z,connectionHealthy:Y})=>{try{let Q=y$(W,Z),X=await $.get(Q);if(X===null)return;return c0(X)}catch(Q){U$("GET",Q,Y);return}},i0=async({client:$,config:W,key:Z,value:Y,keyPrefix:Q,connectionHealthy:X})=>{try{let J=y$(Z,Q),M=s0(Y);if(await $.exists(J))await a0({client:$,key:J,value:M});else await r0({client:$,key:J,value:M,ttlSeconds:Math.floor(W.window/1000)})}catch(J){U$("SET",J,X)}},t0=async({client:$,key:W,keyPrefix:Z,connectionHealthy:Y})=>{try{let Q=y$(W,Z);await $.del(Q)}catch(Q){U$("DELETE",Q,Y)}},o0=async({client:$,keyPrefix:W,connectionHealthy:Z})=>{try{let Y=`${W}*`,Q=await $.keys(Y);if(Q.length>0)await Promise.all(Q.map(async(X)=>$.del(X))),U.info(`[RedisStore] Destroyed ${Q.length} rate limit keys`)}catch(Y){U$("DESTROY",Y,Z)}};var e0=()=>({memory:()=>O1(),redis:async($)=>H1($)}),_1=async($)=>{let Z=e0()[$.store.type];if(!Z)throw Error(`Unsupported store type: ${$.store.type}`);return Z($)};class h${_config;_store=null;constructor($){this._config=$}async _getStore(){return this._store??=await _1(this._config),this._store}async check($){let W=await this._getStore(),Z=this._config.keyGenerator($),Y=Date.now(),Q=await W.get(Z)??{currentWindowCount:0,previousWindowCount:0,windowStart:Y};if(Y-Q.windowStart>=this._config.window)Q.previousWindowCount=0,Q.currentWindowCount=0,Q.windowStart=Y;let M=(Y-Q.windowStart)/this._config.window,F=Q.previousWindowCount*(1-M),w=Q.currentWindowCount+F,_=w<this._config.max;if(_)Q.currentWindowCount++;await W.set(Z,Q);let V=Math.max(0,Math.floor(this._config.max-w-(_?1:0))),H=Q.windowStart+this._config.window;return{allowed:_,remaining:V,resetTime:H,totalHits:Math.ceil(w+(_?1:0)),limit:this._config.max}}async destroy(){await(await this._getStore()).destroy()}}var $2=($)=>Math.ceil(($-Date.now())/1000),W2=($)=>new h$($);class i{_config;_strategy;constructor($){this._config=$,this._strategy=W2($)}async check($){return this._strategy.check($)}async destroy(){await this._strategy.destroy()}get config(){return this._config}}var u$=($,W)=>{if($.response.addHeaders({"RateLimit-Limit":String(W.limit),"RateLimit-Remaining":String(W.remaining),"RateLimit-Reset":String(Math.ceil(W.resetTime/1000))}),!W.allowed){let Z=$2(W.resetTime);$.response.addHeaders({"Retry-After":String(Z)})}};var m$={slidingWindowCounter:"sliding-window-counter"},Z2={memory:"memory",redis:"redis"};class t{algorithm;store;window;max;standardHeaders;skipSuccessfulRequests;skipFailedRequests;keyGenerator;handler;constructor($){this._validateConfig($),this.algorithm=$?.algorithm??m$.slidingWindowCounter,this.store=$?.store??{type:"memory"},this.window=C($?.window??"15m"),this.max=$?.max??100,this.standardHeaders=$?.standardHeaders??!0,this.skipSuccessfulRequests=$?.skipSuccessfulRequests??!1,this.skipFailedRequests=$?.skipFailedRequests??!1,this.keyGenerator=$?.keyGenerator??J2,this.handler=$?.handler??X2}_validateConfig($){if(!$)return;Y2($),Q2($)}get config(){return{algorithm:this.algorithm,window:this.window,max:this.max,standardHeaders:this.standardHeaders,skipSuccessfulRequests:this.skipSuccessfulRequests,skipFailedRequests:this.skipFailedRequests,keyGenerator:this.keyGenerator,handler:this.handler}}}var Y2=($)=>{if($.max!==void 0){if(typeof $.max!=="number"||isNaN($.max))throw Error("rateLimit.max must be a number");if($.max<1)throw Error("rateLimit.max must be at least 1 request per window");if(!Number.isInteger($.max))throw Error("rateLimit.max must be an integer (no decimals)")}if($.window!==void 0)if(typeof $.window==="string"){if(!/^(?<value>\d+)(?<unit>s|m|h|d)$/.test($.window))throw Error(`rateLimit.window must be a valid time string (e.g., '30s', '15m', '2h', '1d') or milliseconds as a number. Received: "${$.window}"`);let Z=C($.window);if(Z<1000)throw Error(`rateLimit.window must be at least 1000ms (1 second). Received: ${$.window} (${Z}ms). Very short time windows can cause performance issues and inaccurate rate limiting.`)}else if(typeof $.window==="number"){if(isNaN($.window))throw Error("rateLimit.window must be a valid number when using milliseconds");if($.window<1000)throw Error(`rateLimit.window must be at least 1000ms (1 second). Received: ${$.window}ms. Very short time windows can cause performance issues and inaccurate rate limiting.`);if(!Number.isInteger($.window))throw Error("rateLimit.window must be an integer when using milliseconds (no decimals)")}else throw Error('rateLimit.window must be a time string (e.g., "15m") or milliseconds as a number')},Q2=($)=>{if($.enabled===!1)U.warn("[SECURITY WARNING] Rate limiting is disabled. This removes DoS protection from your API. Only disable for development or if you have external rate limiting (e.g., API gateway, CDN).");if($.max!==void 0&&$.max>1e4)U.warn(`[SECURITY WARNING] rateLimit.max is set to ${$.max} requests. Very high rate limits may not provide adequate DoS protection. Consider if this limit is necessary for your use case.`);if($.window!==void 0){let W=typeof $.window==="string"?C($.window):$.window,Z=3600000;if(W>3600000){let Y=Math.round(W/3600000);U.warn(`[SECURITY WARNING] rateLimit.window is set to ${typeof $.window==="string"?$.window:`${W}ms`} (${Y}h). Very long time windows may allow burst attacks before limits are enforced. Consider shorter windows for better protection.`)}}if($.window!==void 0){let W=typeof $.window==="string"?C($.window):$.window;if(W<1e4&&$.max!==void 0&&$.max>100)U.warn(`[PERFORMANCE WARNING] rateLimit.window is set to ${typeof $.window==="string"?$.window:`${W}ms`} with max ${$.max} requests. Very short time windows with high request counts can cause performance overhead. Consider increasing the window or decreasing max.`)}},X2=($)=>{return $.response.setStatusCode(b.tooManyRequests),{success:!1,message:"Yinz are sending too many requests. Slow down, jagoff!"}},J2=($)=>$.request.ipAddress;var M2=($)=>async(W)=>{let Z=new t($),Y=new i(Z),Q=await Y.check(W);if(Y.config.standardHeaders)u$(W,Q);if(!Q.allowed)return Y.config.handler(W);return},z1=($)=>async(W)=>{let Z=await $.check(W);if($.config.standardHeaders)u$(W,Z);if(!Z.allowed)return $.config.handler(W);return};import{createHmac as I1}from"node:crypto";class o{enabled;secret;signed;defaults;constructor($){this._validateConfig($),this.enabled=$?.enabled??!1,this.secret=$?.secret,this.signed=$?.signed,this.defaults=$?.defaults}_validateConfig($){if(!$)return;D2($),B2($)}get config(){let $={enabled:this.enabled};if(this.secret!==void 0)$.secret=this.secret;if(this.signed!==void 0)$.signed=this.signed;if(this.defaults!==void 0)$.defaults=this.defaults;return $}}var D2=($)=>{if($.secret!==void 0){if(typeof $.secret!=="string")throw Error("cookieParser.secret must be a string");if($.secret.length<32)throw Error("cookieParser.secret must be at least 32 characters for security. Use a strong, random secret stored in environment variables.")}if($.signed!==void 0){if(!Array.isArray($.signed))throw Error("cookieParser.signed must be an array of cookie names");for(let W of $.signed){if(typeof W!=="string")throw Error("cookieParser.signed must be an array of strings (cookie names)");if(W.length===0)throw Error("cookieParser.signed cannot contain empty cookie names")}}if($.defaults)K2($.defaults)},K2=($)=>{if(!$)return;j2($),U2($),G2($),F2($),q2($),w2($),N2($)},j2=($)=>{if(!$||$.maxAge===void 0)return;if(typeof $.maxAge==="string"){if(!/^(?<value>\d+)(?<unit>ms|s|m|h|d)$/.test($.maxAge))throw Error(`cookieParser.defaults.maxAge must be a valid time string (e.g., '30s', '15m', '2h', '1d') or seconds as a number. Received: "${$.maxAge}"`);return}if(typeof $.maxAge!=="number"||isNaN($.maxAge))throw Error(`cookieParser.defaults.maxAge must be a valid time string (e.g., '30s', '15m', '2h', '1d') or seconds as a number. Received: "${$.maxAge}"`);if($.maxAge<0)throw Error("cookieParser.defaults.maxAge must be 0 or greater");if(!Number.isInteger($.maxAge))throw Error("cookieParser.defaults.maxAge must be an integer (no decimals)")},U2=($)=>{if(!$||$.secure===void 0)return;if(typeof $.secure!=="boolean")throw Error("cookieParser.defaults.secure must be a boolean")},G2=($)=>{if(!$||$.httpOnly===void 0)return;if(typeof $.httpOnly!=="boolean")throw Error("cookieParser.defaults.httpOnly must be a boolean")},F2=($)=>{if(!$||$.sameSite===void 0)return;if(!["strict","lax","none"].includes($.sameSite))throw Error('cookieParser.defaults.sameSite must be one of: "strict", "lax", "none"')},q2=($)=>{if(!$)return;if($.domain===void 0)return;if(typeof $.domain!=="string")throw Error("cookieParser.defaults.domain must be a string");if($.domain.length===0)throw Error("cookieParser.defaults.domain cannot be empty")},w2=($)=>{if(!$||$.path===void 0)return;if(typeof $.path!=="string")throw Error("cookieParser.defaults.path must be a string");if(!$.path.startsWith("/"))throw Error('cookieParser.defaults.path must start with "/"')},N2=($)=>{if(!$||$.expires===void 0)return;if(!($.expires instanceof Date))throw Error("cookieParser.defaults.expires must be a Date object")},B2=($)=>{if($.enabled===!1)U.warn("[SECURITY WARNING] Cookie parser is disabled. Cookies will not be parsed or validated. Only disable for special use cases.");let W=!1;if(W&&!$.secret)U.warn("[SECURITY WARNING] No secret provided for cookie signing in production. Cookies will not be signed and cannot be validated for tampering. Consider using a secret.");if(W&&$.defaults?.secure===!1)U.warn("[SECURITY WARNING] cookieParser.defaults.secure is false in production. Cookies will be sent over HTTP, which is insecure. Always use secure cookies in production.");if(W&&$.defaults?.httpOnly===!1)U.warn("[SECURITY WARNING] cookieParser.defaults.httpOnly is false in production. Cookies will be accessible to JavaScript, which increases XSS risk. Only disable httpOnly for cookies that need JavaScript access.");if($.defaults?.sameSite==="none"&&$.defaults.secure!==!0)U.warn("[SECURITY WARNING] SameSite=none requires secure=true. Browsers will reject cookies with SameSite=none without secure flag.")};class p${_config;constructor($){this._config=new o($)}parse($){let W=new Map;if(!$||typeof $!=="string")return W;let Z=$.split(";");for(let Y of Z){let Q=Y.trim();if(!Q)continue;let X=Q.indexOf("=");if(X===-1)continue;let J=Q.slice(0,X).trim(),M=Q.slice(X+1).trim();if(J&&M)try{W.set(J,decodeURIComponent(M))}catch(F){continue}}return W}set($,W,Z){let Y=encodeURIComponent($),Q=encodeURIComponent(W),X=this._mergeOptions(Z),J=[`${Y}=${Q}`];if(X.expires)J.push(`Expires=${X.expires.toUTCString()}`);if(X.maxAge!==void 0)J.push(`Max-Age=${X.maxAge}`);if(X.domain)J.push(`Domain=${X.domain}`);if(X.path)J.push(`Path=${X.path}`);if(X.secure)J.push("Secure");if(X.httpOnly)J.push("HttpOnly");if(X.sameSite)J.push(`SameSite=${X.sameSite.charAt(0).toUpperCase()+X.sameSite.slice(1)}`);return J.join("; ")}sign($,W){if(!this._config.secret)throw Error("Cannot sign cookie: no secret configured");let Z=I1("sha256",this._config.secret).update(`${$}=${W}`).digest("base64url").replace(/=/g,"");return`${W}.${Z}`}unsign($,W){if(!this._config.secret)throw Error("Cannot unsign cookie: no secret configured");let Z=W.lastIndexOf(".");if(Z===-1)return!1;let Y=W.slice(0,Z),Q=W.slice(Z+1);return I1("sha256",this._config.secret).update(`${$}=${Y}`).digest("base64url").replace(/=/g,"")===Q?Y:!1}_mergeOptions($){let W={...this._config.defaults,...$};if(W.maxAge!==void 0&&typeof W.maxAge==="string")W.maxAge=C(W.maxAge)/1000;return W}get config(){return this._config}shouldSign($){if(!this._config.secret)return!1;if(this._config.signed===void 0||this._config.signed.length===0)return!0;return this._config.signed.includes($)}}var T1=($)=>(W)=>{let Z=new p$($),Y=W.request.headers.cookie,Q=Z.parse(Y??"");if(W.request.cookies=Q,W.request.signedCookies=new Map,Z.config.secret){for(let[X,J]of Q.entries())if(Z.shouldSign(X)){let M=Z.unsign(X,J);if(M!==!1)W.request.signedCookies.set(X,M)}}W.cookies={set:(X,J,M)=>{let F=J;if(Z.shouldSign(X))F=Z.sign(X,J);let w=Z.set(X,F,M);W.response.addHeaders({"Set-Cookie":w})},sign:(X,J)=>{if(!Z.config.secret)throw Error("Cannot sign cookie: no secret configured");return Z.sign(X,J)},unsign:(X,J)=>{if(!Z.config.secret)throw Error("Cannot unsign cookie: no secret configured");return Z.unsign(X,J)}};return};class f${config;_normalizedOrigins;constructor($){this.config=$;if($.origin==="*"&&$.credentials)throw Error(`CORS Configuration Error: Cannot use origin: "*" with credentials: true. The CORS specification forbids this combination as it creates security vulnerabilities. Choose one of these solutions:
26
+ Received: ${Z}`}`)}if($.length===0){U.warn(`${W}() called with empty array. No hooks will be registered.`);return}for(let Z=0;Z<$.length;Z++){let Y=$[Z];if(typeof Y!=="function")throw Error(`YinzerFlow: ${W}() array contains non-function at index ${Z}. Expected: function, received: ${typeof Y}`)}}_addOnError($){this._onError=$}_addOnNotFound($){this._onNotFound=$}}var F1=($)=>{let W=[],Z=$.path.replace(/:\w+/g,(Y)=>{let Q=Y.slice(1);return W.push(Q),"([^/]+)"}).replace(/\//g,"\\/");return{...$,pattern:new RegExp(`^${Z}$`),paramNames:W,isParameterized:!0}};var I$=($)=>{let[W]=$.split("?");if(!W)return"";if([W]=W.split("#"),!W)return"";try{W=decodeURIComponent(W)}catch(Z){U.warn("Failed to decode URL path",{path:W})}if(W=W.startsWith("/")?W:`/${W}`,W=W.replace(/\/\/+/g,"/"),W=g0(W),W.length>1&&W.endsWith("/"))W=W.slice(0,-1);return W},g0=($)=>{let W=$.split("/"),Z=[];for(let Q of W){if(Q==="."||Q===""){if(Q===""&&Z.length===0)Z.push(Q);continue}if(Q===".."){if(Z.length>1)Z.pop()}else Z.push(Q)}return Z.join("/")||"/"},T$=($)=>$.replace(/:\w+/g,":param");var q1=($)=>{let W=$.match(/:\w+/g);if(!W)return;let Z=W.map((Q)=>Q.slice(1)),Y=new Set(Z);if(Z.length!==Y.size){let Q=Z.filter((X,J)=>Z.indexOf(X)!==J);throw Error(`Route ${$} has duplicate parameter names: ${Q.join(", ")}. Parameter names must be unique within a route for clarity and to prevent conflicts.`)}};class S${_exactRoutes=new Map;_parameterizedRoutes=new Map;_register({method:$,path:W,handler:Z,options:Y}){let Q=I$(W),X=Q.includes(":");if(X)q1(Q);if(this._hasExactRoutePattern($,Q))throw Error(`Route ${Q} already exists for method ${$}`);let J={method:$,path:Q,handler:Z,options:Y,params:{}};if(X)this._storeParameterizedRoute($,J);else this._storeExactRoute($,Q,J)}_findRoute($,W){let Z=I$(W),Y=this._exactRoutes.get($)?.get(Z);if(Y)return Y;let Q=this._findParameterizedRoute($,Z);if(Q)return Q;return}_hasExactRoutePattern($,W){if(this._exactRoutes.get($)?.has(W))return!0;if(W.includes(":")){let Z=T$(W),Y=this._parameterizedRoutes.get($);if(Y)return Y.some((Q)=>T$(Q.path)===Z)}else{let Z=this._parameterizedRoutes.get($);if(Z)return Z.some((Y)=>Y.path===W)}return!1}_storeExactRoute($,W,Z){if(!this._exactRoutes.has($))this._exactRoutes.set($,new Map);this._exactRoutes.get($)?.set(W,Z)}_storeParameterizedRoute($,W){if(!this._parameterizedRoutes.has($))this._parameterizedRoutes.set($,[]);let Z=F1(W);this._parameterizedRoutes.get($)?.push(Z)}_findParameterizedRoute($,W){let Z=this._parameterizedRoutes.get($);if(!Z)return;for(let Y of Z){let Q=W.match(Y.pattern);if(Q){let X={};for(let J=0;J<Y.paramNames.length;J++){let M=Q[J+1],q=Y.paramNames[J];if(M!==void 0&&q!==void 0)X[q]=M}return{...Y,params:X}}}return}}var C=($)=>({beforeHooks:$?.beforeHooks??[],afterHooks:$?.afterHooks??[]}),L$=($,W)=>({beforeHooks:[...$.beforeHooks??[],...W?.beforeHooks??[]],afterHooks:[...W?.afterHooks??[],...$.afterHooks??[]]}),R$=($,W)=>{let Z=$.endsWith("/")?$.slice(0,-1):$,Y=W.startsWith("/")?W:`/${W}`;return`${Z}${Y}`};class j${_setup;_prefix;_options;constructor($,W,Z){this._setup=$,this._prefix=W,this._options=C(Z)}_createRouteHandler($){return(W,Z,Y)=>{let Q=R$(this._prefix,W),X=L$(this._options,Y);if(this._setup._routeRegistry._register({method:$,handler:Z,path:Q,options:X,params:{}}),$===I.get)this._setup._routeRegistry._register({method:I.head,handler:Z,path:Q,options:X,params:{}})}}get=this._createRouteHandler(I.get);head=this._createRouteHandler(I.head);post=this._createRouteHandler(I.post);put=this._createRouteHandler(I.put);delete=this._createRouteHandler(I.delete);patch=this._createRouteHandler(I.patch);options=this._createRouteHandler(I.options);group($,W,Z){let Y=R$(this._prefix,$),Q=L$(this._options,Z),X=new j$(this._setup,Y,Q);return W(X),X}}class v${_configuration;_routeRegistry=new S$;_hooks=new _$;constructor($){this._configuration=G1($)}get($,W,Z){let Y=C(Z);this._routeRegistry._register({method:I.get,handler:W,path:$,options:Y,params:{}}),this._routeRegistry._register({method:I.head,handler:W,path:$,options:Y,params:{}})}head($,W,Z){this._routeRegistry._register({method:I.head,handler:W,path:$,options:C(Z),params:{}})}post($,W,Z){this._routeRegistry._register({method:I.post,handler:W,path:$,options:C(Z),params:{}})}put($,W,Z){this._routeRegistry._register({method:I.put,handler:W,path:$,options:C(Z),params:{}})}patch($,W,Z){this._routeRegistry._register({method:I.patch,handler:W,path:$,options:C(Z),params:{}})}delete($,W,Z){this._routeRegistry._register({method:I.delete,handler:W,path:$,options:C(Z),params:{}})}options($,W,Z){this._routeRegistry._register({method:I.options,handler:W,path:$,options:C(Z),params:{}})}group($,W,Z){let Y=new j$(this,$,Z);return W(Y),Y}beforeRouting($,W){this._hooks._addBeforeRoutingHooks($,W)}beforeAll($,W){this._hooks._addBeforeHooks($,W)}afterAll($,W){this._hooks._addAfterHooks($,W)}onError($){this._hooks._addOnError($)}onNotFound($){this._hooks._addOnNotFound($)}}var w1={prefix:"NETWORK",logLevel:"off",logger:void 0},L={log:a(w1),enable:($)=>{L.log=a({...w1,logLevel:r.info,logger:$})}},N1=($)=>{if($>=200&&$<300)return"✅";if($>=300&&$<400)return"\uD83D\uDD04";if($>=400&&$<500)return"❌";if($>=500)return"\uD83D\uDCA5";return"❓"},P$=[{maxTime:50,emoji:"⚡",phrase:"faster than a Stillers touchdown!"},{maxTime:100,emoji:"\uD83D\uDD25",phrase:"smooth as butter n'at!"},{maxTime:200,emoji:"✅",phrase:"not bad yinz!"},{maxTime:500,emoji:"⚠️",phrase:"slowin' down a bit there"},{maxTime:1000,emoji:"\uD83D\uDC0C",phrase:"that's draggin' n'at"},{maxTime:1/0,emoji:"\uD83D\uDCA5",phrase:"what a jagoff response time!"}],B1=($)=>{let W=P$.find((Z)=>$<Z.maxTime)??P$[P$.length-1];if(!W)throw Error("No threshold found for performance details");L.log.warn(`${E.magenta} ${W.emoji} Response time: ${$}ms - ${W.phrase}${E.reset}`)};var V1=($)=>{if(d0($))return $.length;if(typeof $==="string")return Buffer.byteLength($,"utf8");if(s0($))try{let W=JSON.stringify($);return Buffer.byteLength(W,"utf8")}catch{return 0}return 0},d0=($)=>typeof Buffer<"u"&&Buffer.isBuffer($),s0=($)=>typeof $==="object"&&$!==null;var E1=()=>{let $=new Map;return{get:async(W)=>Promise.resolve($.get(W)),set:async(W,Z)=>{return $.set(W,Z),Promise.resolve()},delete:async(W)=>{return $.delete(W),Promise.resolve()},destroy:async()=>{return $.clear(),Promise.resolve()}}};import{Redis as O1}from"ioredis";var x=($)=>{if(typeof $==="number")return $;if(typeof $!=="string")throw Error("Invalid time format. Expected format: 1ms, 1s, 1m, 1h, 1d");if($.length<2)throw Error("Invalid time format. Expected format: 1ms, 1s, 1m, 1h, 1d");if($.length>3)throw Error("Invalid time format. Expected format: 1ms, 1s, 1m, 1h, 1d");let W=$.includes("ms")?$.slice(-2):$.slice(-1),Z=$.includes("ms")?$.slice(0,-2):$.slice(0,-1);if(!["ms","s","m","h","d"].includes(W))throw Error(`Invalid time unit: "${W}". Expected: s (seconds), m (minutes), h (hours), or d (days)`);let Y=Number(Z);if(isNaN(Y)||Y<=0)throw Error(`Invalid time value: "${Z}". Must be a positive number`);switch(W){case"ms":return Y;case"s":return Y*1000;case"m":return Y*60*1000;case"h":return Y*60*60*1000;case"d":return Y*24*60*60*1000;default:throw Error(`Unsupported time unit: "${W}"`)}};var A1=async($)=>{let{store:W}=$;if(W.type!=="redis")throw Error(`Expected Redis store configuration but got: ${JSON.stringify(W)}`);let{client:Z,keyPrefix:Y="rate_limit:",maxRetries:Q=3,retryDelay:X=1000}=W,J=x(X),M=!1;return await(async()=>{for(let B=1;B<=Q;B++)try{await Z.ping(),M=!0,U.info(`[RedisStore] Successfully connected to Redis (attempt ${B})`);return}catch(H){if(U.warn(`[RedisStore] Redis connection attempt ${B}/${Q} failed:`,H),B<Q)U.info(`[RedisStore] Retrying connection in ${X}...`),await new Promise((V)=>{setTimeout(V,J)});else U.error("[RedisStore] All Redis connection attempts failed. Store will operate in degraded mode."),M=!1}})(),{get:async(B)=>i0({client:Z,key:B,keyPrefix:Y,connectionHealthy:M}),set:async(B,H)=>t0({client:Z,config:$,key:B,value:H,keyPrefix:Y,connectionHealthy:M}),delete:async(B)=>o0({client:Z,key:B,keyPrefix:Y,connectionHealthy:M}),destroy:async()=>e0({client:Z,keyPrefix:Y,connectionHealthy:M})}},b$=($,W)=>`${W}${$}`,c0=($)=>{try{return JSON.stringify($)}catch(W){throw U.error("[RedisStore] Failed to serialize value:",W),Error("Failed to serialize rate limit data")}},r0=($)=>{try{return JSON.parse($)}catch(W){throw U.error("[RedisStore] Failed to deserialize value:",W),Error("Failed to deserialize rate limit data")}},D$=($,W,Z)=>{if(Z)U.warn(`[RedisStore] Redis ${$} failed (connection was healthy):`,W);else U.error(`[RedisStore] Redis ${$} failed (connection unhealthy):`,W)},a0=async({client:$,key:W,value:Z,ttlSeconds:Y})=>{try{if($ instanceof O1)await $.set(W,Z,"EX",Y);else await $.set(W,Z,{EX:Y})}catch(Q){if(Q instanceof Error)throw Error(`Unsupported Redis client or Redis operation failed: ${Q.message}`);throw Q}},n0=async({client:$,key:W,value:Z})=>{try{if($ instanceof O1)await $.set(W,Z,"KEEPTTL");else await $.set(W,Z,{KEEPTTL:!0})}catch(Y){if(Y instanceof Error)throw Error(`Unsupported Redis client or Redis operation failed: ${Y.message}`);throw Y}},i0=async({client:$,key:W,keyPrefix:Z,connectionHealthy:Y})=>{try{let Q=b$(W,Z),X=await $.get(Q);if(X===null)return;return r0(X)}catch(Q){D$("GET",Q,Y);return}},t0=async({client:$,config:W,key:Z,value:Y,keyPrefix:Q,connectionHealthy:X})=>{try{let J=b$(Z,Q),M=c0(Y);if(await $.exists(J))await n0({client:$,key:J,value:M});else await a0({client:$,key:J,value:M,ttlSeconds:Math.floor(W.window/1000)})}catch(J){D$("SET",J,X)}},o0=async({client:$,key:W,keyPrefix:Z,connectionHealthy:Y})=>{try{let Q=b$(W,Z);await $.del(Q)}catch(Q){D$("DELETE",Q,Y)}},e0=async({client:$,keyPrefix:W,connectionHealthy:Z})=>{try{let Y=`${W}*`,Q=await $.keys(Y);if(Q.length>0)await Promise.all(Q.map(async(X)=>$.del(X))),U.info(`[RedisStore] Destroyed ${Q.length} rate limit keys`)}catch(Y){D$("DESTROY",Y,Z)}};var $2=()=>({memory:()=>E1(),redis:async($)=>A1($)}),z1=async($)=>{let Z=$2()[$.store.type];if(!Z)throw Error(`Unsupported store type: ${$.store.type}`);return Z($)};class k${_config;_store=null;constructor($){this._config=$}async _getStore(){return this._store??=await z1(this._config),this._store}async check($){let W=await this._getStore(),Z=this._config.keyGenerator($),Y=Date.now(),Q=await W.get(Z)??{currentWindowCount:0,previousWindowCount:0,windowStart:Y};if(Y-Q.windowStart>=this._config.window)Q.previousWindowCount=0,Q.currentWindowCount=0,Q.windowStart=Y;let M=(Y-Q.windowStart)/this._config.window,q=Q.previousWindowCount*(1-M),B=Q.currentWindowCount+q,H=B<this._config.max;if(H)Q.currentWindowCount++;await W.set(Z,Q);let V=Math.max(0,Math.floor(this._config.max-B-(H?1:0))),z=Q.windowStart+this._config.window;return{allowed:H,remaining:V,resetTime:z,totalHits:Math.ceil(B+(H?1:0)),limit:this._config.max}}async destroy(){await(await this._getStore()).destroy()}}var W2=($)=>Math.ceil(($-Date.now())/1000),Z2=($)=>new k$($);class i{_config;_strategy;constructor($){this._config=$,this._strategy=Z2($)}async check($){return this._strategy.check($)}async destroy(){await this._strategy.destroy()}get config(){return this._config}}var x$=($,W)=>{if($.response.addHeaders({"RateLimit-Limit":String(W.limit),"RateLimit-Remaining":String(W.remaining),"RateLimit-Reset":String(Math.ceil(W.resetTime/1000))}),!W.allowed){let Z=W2(W.resetTime);$.response.addHeaders({"Retry-After":String(Z)})}};var C$={slidingWindowCounter:"sliding-window-counter"},Y2={memory:"memory",redis:"redis"};class t{algorithm;store;window;max;standardHeaders;skipSuccessfulRequests;skipFailedRequests;keyGenerator;handler;constructor($){this._validateConfig($),this.algorithm=$?.algorithm??C$.slidingWindowCounter,this.store=$?.store??{type:"memory"},this.window=x($?.window??"15m"),this.max=$?.max??100,this.standardHeaders=$?.standardHeaders??!0,this.skipSuccessfulRequests=$?.skipSuccessfulRequests??!1,this.skipFailedRequests=$?.skipFailedRequests??!1,this.keyGenerator=$?.keyGenerator??M2,this.handler=$?.handler??J2}_validateConfig($){if(!$)return;Q2($),X2($)}get config(){return{algorithm:this.algorithm,window:this.window,max:this.max,standardHeaders:this.standardHeaders,skipSuccessfulRequests:this.skipSuccessfulRequests,skipFailedRequests:this.skipFailedRequests,keyGenerator:this.keyGenerator,handler:this.handler}}}var Q2=($)=>{if($.max!==void 0){if(typeof $.max!=="number"||isNaN($.max))throw Error("rateLimit.max must be a number");if($.max<1)throw Error("rateLimit.max must be at least 1 request per window");if(!Number.isInteger($.max))throw Error("rateLimit.max must be an integer (no decimals)")}if($.window!==void 0)if(typeof $.window==="string"){if(!/^(?<value>\d+)(?<unit>s|m|h|d)$/.test($.window))throw Error(`rateLimit.window must be a valid time string (e.g., '30s', '15m', '2h', '1d') or milliseconds as a number. Received: "${$.window}"`);let Z=x($.window);if(Z<1000)throw Error(`rateLimit.window must be at least 1000ms (1 second). Received: ${$.window} (${Z}ms). Very short time windows can cause performance issues and inaccurate rate limiting.`)}else if(typeof $.window==="number"){if(isNaN($.window))throw Error("rateLimit.window must be a valid number when using milliseconds");if($.window<1000)throw Error(`rateLimit.window must be at least 1000ms (1 second). Received: ${$.window}ms. Very short time windows can cause performance issues and inaccurate rate limiting.`);if(!Number.isInteger($.window))throw Error("rateLimit.window must be an integer when using milliseconds (no decimals)")}else throw Error('rateLimit.window must be a time string (e.g., "15m") or milliseconds as a number')},X2=($)=>{if($.enabled===!1)U.warn("[SECURITY WARNING] Rate limiting is disabled. This removes DoS protection from your API. Only disable for development or if you have external rate limiting (e.g., API gateway, CDN).");if($.max!==void 0&&$.max>1e4)U.warn(`[SECURITY WARNING] rateLimit.max is set to ${$.max} requests. Very high rate limits may not provide adequate DoS protection. Consider if this limit is necessary for your use case.`);if($.window!==void 0){let W=typeof $.window==="string"?x($.window):$.window,Z=3600000;if(W>3600000){let Y=Math.round(W/3600000);U.warn(`[SECURITY WARNING] rateLimit.window is set to ${typeof $.window==="string"?$.window:`${W}ms`} (${Y}h). Very long time windows may allow burst attacks before limits are enforced. Consider shorter windows for better protection.`)}}if($.window!==void 0){let W=typeof $.window==="string"?x($.window):$.window;if(W<1e4&&$.max!==void 0&&$.max>100)U.warn(`[PERFORMANCE WARNING] rateLimit.window is set to ${typeof $.window==="string"?$.window:`${W}ms`} with max ${$.max} requests. Very short time windows with high request counts can cause performance overhead. Consider increasing the window or decreasing max.`)}},J2=($)=>{return $.response.setStatusCode(b.tooManyRequests),{success:!1,message:"Yinz are sending too many requests. Slow down, jagoff!"}},M2=($)=>$.request.ipAddress;var j2=($)=>async(W)=>{let Z=new t($),Y=new i(Z),Q=await Y.check(W);if(Y.config.standardHeaders)x$(W,Q);if(!Q.allowed)return Y.config.handler(W);return},H1=($)=>async(W)=>{let Z=await $.check(W);if($.config.standardHeaders)x$(W,Z);if(!Z.allowed)return $.config.handler(W);return};import{createHmac as _1}from"node:crypto";class o{enabled;secret;signed;defaults;constructor($){this._validateConfig($),this.enabled=$?.enabled??!1,this.secret=$?.secret,this.signed=$?.signed,this.defaults=$?.defaults}_validateConfig($){if(!$)return;D2($),V2($)}get config(){let $={enabled:this.enabled};if(this.secret!==void 0)$.secret=this.secret;if(this.signed!==void 0)$.signed=this.signed;if(this.defaults!==void 0)$.defaults=this.defaults;return $}}var D2=($)=>{if($.secret!==void 0){if(typeof $.secret!=="string")throw Error("cookieParser.secret must be a string");if($.secret.length<32)throw Error("cookieParser.secret must be at least 32 characters for security. Use a strong, random secret stored in environment variables.")}if($.signed!==void 0){if(!Array.isArray($.signed))throw Error("cookieParser.signed must be an array of cookie names");for(let W of $.signed){if(typeof W!=="string")throw Error("cookieParser.signed must be an array of strings (cookie names)");if(W.length===0)throw Error("cookieParser.signed cannot contain empty cookie names")}}if($.defaults)K2($.defaults)},K2=($)=>{if(!$)return;U2($),G2($),F2($),q2($),w2($),N2($),B2($)},U2=($)=>{if(!$||$.maxAge===void 0)return;if(typeof $.maxAge==="string"){if(!/^(?<value>\d+)(?<unit>ms|s|m|h|d)$/.test($.maxAge))throw Error(`cookieParser.defaults.maxAge must be a valid time string (e.g., '30s', '15m', '2h', '1d') or seconds as a number. Received: "${$.maxAge}"`);return}if(typeof $.maxAge!=="number"||isNaN($.maxAge))throw Error(`cookieParser.defaults.maxAge must be a valid time string (e.g., '30s', '15m', '2h', '1d') or seconds as a number. Received: "${$.maxAge}"`);if($.maxAge<0)throw Error("cookieParser.defaults.maxAge must be 0 or greater");if(!Number.isInteger($.maxAge))throw Error("cookieParser.defaults.maxAge must be an integer (no decimals)")},G2=($)=>{if(!$||$.secure===void 0)return;if(typeof $.secure!=="boolean")throw Error("cookieParser.defaults.secure must be a boolean")},F2=($)=>{if(!$||$.httpOnly===void 0)return;if(typeof $.httpOnly!=="boolean")throw Error("cookieParser.defaults.httpOnly must be a boolean")},q2=($)=>{if(!$||$.sameSite===void 0)return;if(!["strict","lax","none"].includes($.sameSite))throw Error('cookieParser.defaults.sameSite must be one of: "strict", "lax", "none"')},w2=($)=>{if(!$)return;if($.domain===void 0)return;if(typeof $.domain!=="string")throw Error("cookieParser.defaults.domain must be a string");if($.domain.length===0)throw Error("cookieParser.defaults.domain cannot be empty")},N2=($)=>{if(!$||$.path===void 0)return;if(typeof $.path!=="string")throw Error("cookieParser.defaults.path must be a string");if(!$.path.startsWith("/"))throw Error('cookieParser.defaults.path must start with "/"')},B2=($)=>{if(!$||$.expires===void 0)return;if(!($.expires instanceof Date))throw Error("cookieParser.defaults.expires must be a Date object")},V2=($)=>{if($.enabled===!1)U.warn("[SECURITY WARNING] Cookie parser is disabled. Cookies will not be parsed or validated. Only disable for special use cases.");let W=!1;if(W&&!$.secret)U.warn("[SECURITY WARNING] No secret provided for cookie signing in production. Cookies will not be signed and cannot be validated for tampering. Consider using a secret.");if(W&&$.defaults?.secure===!1)U.warn("[SECURITY WARNING] cookieParser.defaults.secure is false in production. Cookies will be sent over HTTP, which is insecure. Always use secure cookies in production.");if(W&&$.defaults?.httpOnly===!1)U.warn("[SECURITY WARNING] cookieParser.defaults.httpOnly is false in production. Cookies will be accessible to JavaScript, which increases XSS risk. Only disable httpOnly for cookies that need JavaScript access.");if($.defaults?.sameSite==="none"&&$.defaults.secure!==!0)U.warn("[SECURITY WARNING] SameSite=none requires secure=true. Browsers will reject cookies with SameSite=none without secure flag.")};class y${_config;constructor($){this._config=new o($)}parse($){let W=new Map;if(!$||typeof $!=="string")return W;let Z=$.split(";");for(let Y of Z){let Q=Y.trim();if(!Q)continue;let X=Q.indexOf("=");if(X===-1)continue;let J=Q.slice(0,X).trim(),M=Q.slice(X+1).trim();if(J&&M)try{W.set(J,decodeURIComponent(M))}catch(q){continue}}return W}set($,W,Z){let Y=encodeURIComponent($),Q=encodeURIComponent(W),X=this._mergeOptions(Z),J=[`${Y}=${Q}`];if(X.expires)J.push(`Expires=${X.expires.toUTCString()}`);if(X.maxAge!==void 0)J.push(`Max-Age=${X.maxAge}`);if(X.domain)J.push(`Domain=${X.domain}`);if(X.path)J.push(`Path=${X.path}`);if(X.secure)J.push("Secure");if(X.httpOnly)J.push("HttpOnly");if(X.sameSite)J.push(`SameSite=${X.sameSite.charAt(0).toUpperCase()+X.sameSite.slice(1)}`);return J.join("; ")}sign($,W){if(!this._config.secret)throw Error("Cannot sign cookie: no secret configured");let Z=_1("sha256",this._config.secret).update(`${$}=${W}`).digest("base64url").replace(/=/g,"");return`${W}.${Z}`}unsign($,W){if(!this._config.secret)throw Error("Cannot unsign cookie: no secret configured");let Z=W.lastIndexOf(".");if(Z===-1)return!1;let Y=W.slice(0,Z),Q=W.slice(Z+1);return _1("sha256",this._config.secret).update(`${$}=${Y}`).digest("base64url").replace(/=/g,"")===Q?Y:!1}_mergeOptions($){let W={...this._config.defaults,...$};if(W.maxAge!==void 0&&typeof W.maxAge==="string")W.maxAge=x(W.maxAge)/1000;return W}get config(){return this._config}shouldSign($){if(!this._config.secret)return!1;if(this._config.signed===void 0||this._config.signed.length===0)return!0;return this._config.signed.includes($)}}var I1=($)=>(W)=>{let Z=new y$($),Y=W.request.headers.cookie,Q=Z.parse(Y??"");if(W.request.cookies=Q,W.request.signedCookies=new Map,Z.config.secret){for(let[X,J]of Q.entries())if(Z.shouldSign(X)){let M=Z.unsign(X,J);if(M!==!1)W.request.signedCookies.set(X,M)}}W.cookies={set:(X,J,M)=>{let q=J;if(Z.shouldSign(X))q=Z.sign(X,J);let B=Z.set(X,q,M);W.response.addHeaders({"Set-Cookie":B})},sign:(X,J)=>{if(!Z.config.secret)throw Error("Cannot sign cookie: no secret configured");return Z.sign(X,J)},unsign:(X,J)=>{if(!Z.config.secret)throw Error("Cannot unsign cookie: no secret configured");return Z.unsign(X,J)}};return};class h${config;_normalizedOrigins;constructor($){this.config=$;if($.origin==="*"&&$.credentials)throw Error(`CORS Configuration Error: Cannot use origin: "*" with credentials: true. The CORS specification forbids this combination as it creates security vulnerabilities. Choose one of these solutions:
31
27
  1) Set credentials: false (recommended for public APIs)
32
28
  2) Use specific origins instead of "*" (e.g., origin: ["https://example.com"])
33
- 3) Disable CORS entirely (enabled: false)`);if(Array.isArray($.origin))this._normalizedOrigins=new Set($.origin.map((W)=>W.toLowerCase()));else this._normalizedOrigins=null}handle($){if($.request.method==="OPTIONS")return this._handlePreflightRequest($);return void this._handleActualRequest($)}_handlePreflightRequest($){let W=$.request.headers.origin?.toLowerCase()??"";if(!this._isOriginAllowed(W,$))return $.response.setStatusCode(403),{error:"CORS: Origin not allowed",origin:$.request.headers.origin};$.response.setStatusCode(this.config.optionsSuccessStatus);let Y=this._resolveAllowedOrigin($);if(this._setCommonCorsHeaders($,Y),$._response._setHeadersIfNotSet({[f.accessControlAllowMethods]:this.config.methods.join(", "),[f.accessControlAllowHeaders]:typeof this.config.allowedHeaders==="string"?this.config.allowedHeaders:this.config.allowedHeaders.join(", "),[f.accessControlExposeHeaders]:this.config.exposedHeaders.join(", "),[f.accessControlMaxAge]:this.config.maxAge.toString()}),this.config.preflightContinue)return;return""}_handleActualRequest($){let W=$.request.headers.origin?.toLowerCase()??"";if(this._isOriginAllowed(W,$)){let Y=this._resolveAllowedOrigin($);this._setCommonCorsHeaders($,Y)}return}_setCommonCorsHeaders($,W){$._response._setHeadersIfNotSet({[f.accessControlAllowOrigin]:W,[f.accessControlAllowCredentials]:this.config.credentials?"true":"false"})}_resolveAllowedOrigin($){if(this.config.origin==="*")return"*";let W=$.request.headers.origin;if(W)return W;if(typeof this.config.origin==="string")return this.config.origin;if(Array.isArray(this.config.origin)&&this.config.origin.length>0){let[Z]=this.config.origin;return Z??"null"}return"null"}_isOriginAllowed($,W){if(this.config.origin==="*")return!0;if(typeof this.config.origin==="function")return Boolean(this.config.origin($,W?.request));if(typeof this.config.origin==="string")return $===this.config.origin.toLowerCase();if(this._normalizedOrigins)return this._normalizedOrigins.has($);if(this.config.origin instanceof RegExp)return this.config.origin.test($);return!1}}var l$=($)=>{let W=new f$($);return(Z)=>W.handle(Z)};class g{static getDefaults(){return{enabled:!1}}static getEnabledDefaults(){return{enabled:!0,origin:"*",methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:"*",exposedHeaders:[],credentials:!1,maxAge:86400,preflightContinue:!1,optionsSuccessStatus:b.noContent}}static merge($){if(!$||!$.enabled)return g.getDefaults();let W=g.getEnabledDefaults();return{enabled:!0,origin:$.origin??W.origin,methods:$.methods??W.methods,allowedHeaders:$.allowedHeaders??W.allowedHeaders,exposedHeaders:$.exposedHeaders??W.exposedHeaders,credentials:$.credentials??W.credentials,maxAge:$.maxAge??W.maxAge,preflightContinue:$.preflightContinue??W.preflightContinue,optionsSuccessStatus:$.optionsSuccessStatus??W.optionsSuccessStatus}}static validate($){if(!$.enabled)return;if($.origin==="*"&&$.credentials)throw Error('CORS Security Error: origin: "*" with credentials: true is forbidden by CORS spec and creates security vulnerabilities. Use specific origins instead.');if(!$.origin)throw Error("CORS Configuration Error: origin is required when CORS is enabled.");if(!Array.isArray($.methods)||$.methods.length===0)throw Error("CORS Configuration Error: methods must be a non-empty array.");if(!Array.isArray($.exposedHeaders))throw Error("CORS Configuration Error: exposedHeaders must be an array.");if(typeof $.maxAge!=="number"||$.maxAge<0)throw Error("CORS Configuration Error: maxAge must be a non-negative number.")}}var E2=65536;class S1 extends C${_isListening=!1;_server;_globalRateLimiter;_maxBufferSize;constructor($){super($);if(this._maxBufferSize=Math.max(this._configuration.bodyParser.json.maxSize,this._configuration.bodyParser.urlEncoded.maxSize,this._configuration.bodyParser.fileUploads.maxTotalSize)+E2,this._configuration.logger)Object.assign(U,this._configuration.logger);if(this._configuration.networkLogs)L.enable(this._configuration.networkLogger);let W=new t($?.rateLimit);if($?.rateLimit?.enabled){this._globalRateLimiter=new i(W);let Z=z1(this._globalRateLimiter);this.beforeAll([Z])}if($?.cookieParser?.enabled){let Z=new o($.cookieParser),Y=T1(Z.config);this.beforeAll([Y])}if($?.cors?.enabled){let Z=g.merge($.cors);g.validate(Z);let Y=l$(Z);this.beforeRouting([Y])}if(this._configuration.gracefulShutdownTimeout){let Z=C(this._configuration.gracefulShutdownTimeout);if(Z>0)this._setupGracefulShutdown(Z)}}_setupServer($,W,Z){if(!this._server)return;this._server.on("error",(Y)=>{L.log.error(`YinzerFlow server error at ${this._configuration.host}:${this._configuration.port} - ${Y.message}`),this._server?.close(),delete this._server,W(Y)}),this._server.on("listening",()=>{this._isListening=!0,L.log.info(`YinzerFlow server at ${this._configuration.host}:${this._configuration.port} is up and running`),$()}),this._server.on("connection",(Y)=>{this._handleConnection(Y,Z)})}async _processRequest({data:$,socket:W,requestHandler:Z,clientAddress:Y}){let Q=Date.now();L.log.info("Incoming request",`${Y} ${D$($)}bytes`);let X=new S$($,this,Y);if(await Z.handle(X),!W.destroyed)W.write(X._response._stringBody),W.end();let M=Date.now()-Q,F=Buffer.byteLength(X._response._stringBody,"utf8");L.log.info(`${V1(X._response._statusCode)} ${Y} "${X.request.method} ${X.request.path} ${X.request.protocol}" ${X._response._statusCode} ${F}bytes "${X.request.headers.referer??"-"}" "${X.request.headers["user-agent"]??"-"}" ${M}ms`),E1(M)}_handleRequestError($,W,Z){let Y=$ instanceof Error?$.message:"Unknown error";if(L.log.error(`Visitor from ${W} experienced an error during request processing: ${Y}`,$),!Z.destroyed)Z.destroy()}_dispatchRequest({data:$,socket:W,requestHandler:Z,clientAddress:Y}){this._processRequest({data:$,socket:W,requestHandler:Z,clientAddress:Y}).catch((Q)=>this._handleRequestError(Q,Y,W))}_rejectOversizedRequest({socket:$,clientAddress:W,totalLength:Z,headersParsed:Y}){if(Y){let Q=JSON.stringify({error:"Payload too large",maxSize:this._maxBufferSize,received:Z});$.write(`HTTP/1.1 413 Payload Too Large\r
29
+ 3) Disable CORS entirely (enabled: false)`);if(Array.isArray($.origin))this._normalizedOrigins=new Set($.origin.map((W)=>W.toLowerCase()));else this._normalizedOrigins=null}handle($){if($.request.method==="OPTIONS")return this._handlePreflightRequest($);return void this._handleActualRequest($)}_handlePreflightRequest($){let W=$.request.headers.origin?.toLowerCase()??"";if(!this._isOriginAllowed(W,$))return $.response.setStatusCode(403),{error:"CORS: Origin not allowed",origin:$.request.headers.origin};$.response.setStatusCode(this.config.optionsSuccessStatus);let Y=this._resolveAllowedOrigin($);if(this._setCommonCorsHeaders($,Y),$._response._setHeadersIfNotSet({[p.accessControlAllowMethods]:this.config.methods.join(", "),[p.accessControlAllowHeaders]:typeof this.config.allowedHeaders==="string"?this.config.allowedHeaders:this.config.allowedHeaders.join(", "),[p.accessControlExposeHeaders]:this.config.exposedHeaders.join(", "),[p.accessControlMaxAge]:this.config.maxAge.toString()}),this.config.preflightContinue)return;return""}_handleActualRequest($){let W=$.request.headers.origin?.toLowerCase()??"";if(this._isOriginAllowed(W,$)){let Y=this._resolveAllowedOrigin($);this._setCommonCorsHeaders($,Y)}return}_setCommonCorsHeaders($,W){$._response._setHeadersIfNotSet({[p.accessControlAllowOrigin]:W,[p.accessControlAllowCredentials]:this.config.credentials?"true":"false"})}_resolveAllowedOrigin($){if(this.config.origin==="*")return"*";let W=$.request.headers.origin;if(W)return W;if(typeof this.config.origin==="string")return this.config.origin;if(Array.isArray(this.config.origin)&&this.config.origin.length>0){let[Z]=this.config.origin;return Z??"null"}return"null"}_isOriginAllowed($,W){if(this.config.origin==="*")return!0;if(typeof this.config.origin==="function")return Boolean(this.config.origin($,W?.request));if(typeof this.config.origin==="string")return $===this.config.origin.toLowerCase();if(this._normalizedOrigins)return this._normalizedOrigins.has($);if(this.config.origin instanceof RegExp)return this.config.origin.test($);return!1}}var u$=($)=>{let W=new h$($);return(Z)=>W.handle(Z)};class g{static getDefaults(){return{enabled:!1}}static getEnabledDefaults(){return{enabled:!0,origin:"*",methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:"*",exposedHeaders:[],credentials:!1,maxAge:86400,preflightContinue:!1,optionsSuccessStatus:b.noContent}}static merge($){if(!$||!$.enabled)return g.getDefaults();let W=g.getEnabledDefaults();return{enabled:!0,origin:$.origin??W.origin,methods:$.methods??W.methods,allowedHeaders:$.allowedHeaders??W.allowedHeaders,exposedHeaders:$.exposedHeaders??W.exposedHeaders,credentials:$.credentials??W.credentials,maxAge:$.maxAge??W.maxAge,preflightContinue:$.preflightContinue??W.preflightContinue,optionsSuccessStatus:$.optionsSuccessStatus??W.optionsSuccessStatus}}static validate($){if(!$.enabled)return;if($.origin==="*"&&$.credentials)throw Error('CORS Security Error: origin: "*" with credentials: true is forbidden by CORS spec and creates security vulnerabilities. Use specific origins instead.');if(!$.origin)throw Error("CORS Configuration Error: origin is required when CORS is enabled.");if(!Array.isArray($.methods)||$.methods.length===0)throw Error("CORS Configuration Error: methods must be a non-empty array.");if(!Array.isArray($.exposedHeaders))throw Error("CORS Configuration Error: exposedHeaders must be an array.");if(typeof $.maxAge!=="number"||$.maxAge<0)throw Error("CORS Configuration Error: maxAge must be a non-negative number.")}}var O2=65536;class T1 extends v${_isListening=!1;_server;_globalRateLimiter;_maxBufferSize;constructor($){super($);if(this._maxBufferSize=Math.max(this._configuration.bodyParser.json.maxSize,this._configuration.bodyParser.urlEncoded.maxSize,this._configuration.bodyParser.fileUploads.maxTotalSize)+O2,this._configuration.logger)Object.assign(U,this._configuration.logger);if(this._configuration.networkLogs)L.enable(this._configuration.networkLogger);let W=new t($?.rateLimit);if($?.rateLimit?.enabled){this._globalRateLimiter=new i(W);let Z=H1(this._globalRateLimiter);this.beforeAll([Z])}if($?.cookieParser?.enabled){let Z=new o($.cookieParser),Y=I1(Z.config);this.beforeAll([Y])}if($?.cors?.enabled){let Z=g.merge($.cors);g.validate(Z);let Y=u$(Z);this.beforeRouting([Y])}if(this._configuration.gracefulShutdownTimeout){let Z=x(this._configuration.gracefulShutdownTimeout);if(Z>0)this._setupGracefulShutdown(Z)}}_setupServer($,W,Z){if(!this._server)return;this._server.on("error",(Y)=>{L.log.error(`YinzerFlow server error at ${this._configuration.host}:${this._configuration.port} - ${Y.message}`),this._server?.close(),delete this._server,W(Y)}),this._server.on("listening",()=>{this._isListening=!0,L.log.info(`YinzerFlow server at ${this._configuration.host}:${this._configuration.port} is up and running`),$()}),this._server.on("connection",(Y)=>{this._handleConnection(Y,Z)})}async _processRequest({data:$,socket:W,requestHandler:Z,clientAddress:Y}){let Q=Date.now();L.log.info("Incoming request",`${Y} ${V1($)}bytes`);let X=new H$($,this,Y);if(await Z.handle(X),!W.destroyed)W.write(X._response._stringBody),W.end();let M=Date.now()-Q,q=Buffer.byteLength(X._response._stringBody,"utf8");L.log.info(`${N1(X._response._statusCode)} ${Y} "${X.request.method} ${X.request.path} ${X.request.protocol}" ${X._response._statusCode} ${q}bytes "${X.request.headers.referer??"-"}" "${X.request.headers["user-agent"]??"-"}" ${M}ms`),B1(M)}_handleRequestError($,W,Z){let Y=$ instanceof Error?$.message:"Unknown error";if(L.log.error(`Visitor from ${W} experienced an error during request processing: ${Y}`,$),!Z.destroyed)Z.destroy()}_dispatchRequest({data:$,socket:W,requestHandler:Z,clientAddress:Y}){this._processRequest({data:$,socket:W,requestHandler:Z,clientAddress:Y}).catch((Q)=>this._handleRequestError(Q,Y,W))}_rejectOversizedRequest({socket:$,clientAddress:W,totalLength:Z,headersParsed:Y}){if(Y){let Q=JSON.stringify({error:"Payload too large",maxSize:this._maxBufferSize,received:Z});$.write(`HTTP/1.1 413 Payload Too Large\r
34
30
  Content-Type: application/json\r
35
31
  Content-Length: ${Buffer.byteLength(Q,"utf8")}\r
36
32
  Connection: close\r
37
33
  \r
38
- ${Q}`)}L.log.warn(`Request from ${W} exceeded maximum buffer size (${Z} > ${this._maxBufferSize} bytes). Current limits: json=${this._configuration.bodyParser.json.maxSize}, urlEncoded=${this._configuration.bodyParser.urlEncoded.maxSize}, fileUploads=${this._configuration.bodyParser.fileUploads.maxTotalSize}`),$.destroy()}_looksLikeHttp($,W,Z){if(W>=1){let Y=$[0]?.[0]??0;if(Y!==71&&Y!==80&&Y!==68&&Y!==72&&Y!==79)return!1}if(W>=8){let Y=Z.subarray(0,8).toString();if(!/^(?:GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\s/.test(Y))return!1}return!0}_parseContentLength($,W){let Z=$.subarray(0,W).toString(),Y=/content-length:\s*(?<digits>\d+)/i.exec(Z);return Y?.groups?.digits?parseInt(Y.groups.digits,10):0}_handleConnection($,W){let Z=$.remoteAddress??"unknown",Y=Date.now(),Q=!1;L.log.info(`New visitor from ${Z}`);let X=[],J=0,M=!1,F=0,w=-1,_=!1;$.on("data",(V)=>{if(!Q){Q=!0;let H=Date.now()-Y;if(H>100)L.log.warn(`Delayed data from ${Z} (${H}ms connection delay)`)}if(_)return;if(X.push(V),J+=V.length,J>this._maxBufferSize){this._rejectOversizedRequest({socket:$,clientAddress:Z,totalLength:J,headersParsed:M});return}if(!M){let H=Buffer.concat(X,J);if(w=H.indexOf(`\r
34
+ ${Q}`)}L.log.warn(`Request from ${W} exceeded maximum buffer size (${Z} > ${this._maxBufferSize} bytes). Current limits: json=${this._configuration.bodyParser.json.maxSize}, urlEncoded=${this._configuration.bodyParser.urlEncoded.maxSize}, fileUploads=${this._configuration.bodyParser.fileUploads.maxTotalSize}`),$.destroy()}_looksLikeHttp($,W,Z){if(W>=1){let Y=$[0]?.[0]??0;if(Y!==71&&Y!==80&&Y!==68&&Y!==72&&Y!==79)return!1}if(W>=8){let Y=Z.subarray(0,8).toString();if(!/^(?:GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\s/.test(Y))return!1}return!0}_parseContentLength($,W){let Z=$.subarray(0,W).toString(),Y=/content-length:\s*(?<digits>\d+)/i.exec(Z);return Y?.groups?.digits?parseInt(Y.groups.digits,10):0}_handleConnection($,W){let Z=$.remoteAddress??"unknown",Y=Date.now(),Q=!1;L.log.info(`New visitor from ${Z}`);let X=[],J=0,M=!1,q=0,B=-1,H=!1;$.on("data",(V)=>{if(!Q){Q=!0;let z=Date.now()-Y;if(z>100)L.log.warn(`Delayed data from ${Z} (${z}ms connection delay)`)}if(H)return;if(X.push(V),J+=V.length,J>this._maxBufferSize){this._rejectOversizedRequest({socket:$,clientAddress:Z,totalLength:J,headersParsed:M});return}if(!M){let z=Buffer.concat(X,J);if(B=z.indexOf(`\r
39
35
  \r
40
- `),w===-1){if(!this._looksLikeHttp(X,J,H))_=!0,this._dispatchRequest({data:H,socket:$,requestHandler:W,clientAddress:Z});return}M=!0,F=this._parseContentLength(H,w);let e=w+4;if(H.length-e>=F)_=!0,this._dispatchRequest({data:H,socket:$,requestHandler:W,clientAddress:Z});return}if(J-(w+4)>=F)_=!0,this._dispatchRequest({data:Buffer.concat(X,J),socket:$,requestHandler:W,clientAddress:Z})}),$.on("error",(V)=>{L.log.error(`Visitor from ${Z} experienced an error during socket connection: ${V.message}`,V)}),$.on("close",()=>{let V=Date.now()-Y;if(Q){L.log.info(`Visitor from ${Z} headed out (${V}ms total)`);return}if(V<10)L.log.info(`${Z} quick connectivity check (${V}ms) - health probe`);else L.log.warn(`${Z} disconnected without sending data (${V}ms) - potential probe`)})}async listen(){if(this._isListening)throw Error("Server is already listening");return new Promise(($,W)=>{let Z=new E$(this);this._server=V2(),this._setupServer($,W,Z),this._server.listen(this._configuration.port,this._configuration.host)})}async close(){if(!this._isListening||!this._server)return;if(this._globalRateLimiter)await this._globalRateLimiter.destroy(),this._globalRateLimiter=void 0;return new Promise(($)=>{if(!this._server){this._isListening=!1,$();return}this._server.close(()=>{this._isListening=!1,L.log.warn(`YinzerFlow server at ${this._configuration.host}:${this._configuration.port} is shutting down - See yinz later`),$()})})}status(){return{isListening:this._isListening,port:this._configuration.port,host:this._configuration.host}}_setupGracefulShutdown($){if($<=0)return;if(process.listenerCount("SIGTERM")===0&&process.listenerCount("SIGINT")===0){let W=(Z)=>{U.info(`\uD83D\uDED1 Received ${Z}, shutting down gracefully in ${this._configuration.gracefulShutdownTimeout}...`),setTimeout(()=>{this.close().then(()=>{U.info("✅ Server shut down gracefully"),process.exit(0)}).catch((Y)=>{U.error("❌ Error during graceful shutdown:",Y),process.exit(1)})},$)};process.on("SIGTERM",()=>W("SIGTERM")),process.on("SIGINT",()=>W("SIGINT"))}}}export{Z2 as rateLimitStoreType,M2 as rateLimitHook,m$ as rateLimitAlgorithm,r as logLevels,U as log,b as httpStatusCode,n as httpStatus,a as createLogger,l$ as corsHook,E as colors,S1 as YinzerFlow};
36
+ `),B===-1){if(!this._looksLikeHttp(X,J,z))H=!0,this._dispatchRequest({data:z,socket:$,requestHandler:W,clientAddress:Z});return}M=!0,q=this._parseContentLength(z,B);let e=B+4;if(z.length-e>=q)H=!0,this._dispatchRequest({data:z,socket:$,requestHandler:W,clientAddress:Z});return}if(J-(B+4)>=q)H=!0,this._dispatchRequest({data:Buffer.concat(X,J),socket:$,requestHandler:W,clientAddress:Z})}),$.on("error",(V)=>{L.log.error(`Visitor from ${Z} experienced an error during socket connection: ${V.message}`,V)}),$.on("close",()=>{let V=Date.now()-Y;if(Q){L.log.info(`Visitor from ${Z} headed out (${V}ms total)`);return}if(V<10)L.log.info(`${Z} quick connectivity check (${V}ms) - health probe`);else L.log.warn(`${Z} disconnected without sending data (${V}ms) - potential probe`)})}async listen(){if(this._isListening)throw Error("Server is already listening");return new Promise(($,W)=>{let Z=new w$(this);this._server=E2(),this._setupServer($,W,Z),this._server.listen(this._configuration.port,this._configuration.host)})}async close(){if(!this._isListening||!this._server)return;if(this._globalRateLimiter)await this._globalRateLimiter.destroy(),this._globalRateLimiter=void 0;return new Promise(($)=>{if(!this._server){this._isListening=!1,$();return}this._server.close(()=>{this._isListening=!1,L.log.warn(`YinzerFlow server at ${this._configuration.host}:${this._configuration.port} is shutting down - See yinz later`),$()})})}status(){return{isListening:this._isListening,port:this._configuration.port,host:this._configuration.host}}_setupGracefulShutdown($){if($<=0)return;if(process.listenerCount("SIGTERM")===0&&process.listenerCount("SIGINT")===0){let W=(Z)=>{U.info(`\uD83D\uDED1 Received ${Z}, shutting down gracefully in ${this._configuration.gracefulShutdownTimeout}...`),setTimeout(()=>{this.close().then(()=>{U.info("✅ Server shut down gracefully"),process.exit(0)}).catch((Y)=>{U.error("❌ Error during graceful shutdown:",Y),process.exit(1)})},$)};process.on("SIGTERM",()=>W("SIGTERM")),process.on("SIGINT",()=>W("SIGINT"))}}}export{Y2 as rateLimitStoreType,j2 as rateLimitHook,C$ as rateLimitAlgorithm,r as logLevels,U as log,b as httpStatusCode,n as httpStatus,a as createLogger,u$ as corsHook,E as colors,T1 as YinzerFlow};
41
37
 
42
- //# debugId=F35721FED347557264756E2164756E21
38
+ //# debugId=BFF7409AFAB81C3764756E2164756E21