yinzerflow 0.2.1 → 0.2.2
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/YinzerFlow.d.ts +54 -18
- package/YinzerFlow.js +13 -15
- package/YinzerFlow.js.map +18 -17
- package/docs/advanced-configuration-options.md +11 -2
- package/docs/logging.md +334 -0
- package/package.json +2 -2
- package/example/index.ts +0 -119
package/YinzerFlow.d.ts
CHANGED
|
@@ -8,10 +8,10 @@ export type DeepPartial<T> = {
|
|
|
8
8
|
: DeepPartial<T[P]> : T[P];
|
|
9
9
|
};
|
|
10
10
|
export interface InternalHandlerCallbackGenerics {
|
|
11
|
-
body
|
|
12
|
-
response
|
|
13
|
-
query
|
|
14
|
-
params
|
|
11
|
+
body?: unknown;
|
|
12
|
+
response?: unknown;
|
|
13
|
+
query?: Record<string, string>;
|
|
14
|
+
params?: Record<string, string>;
|
|
15
15
|
}
|
|
16
16
|
declare const httpStatusCode: {
|
|
17
17
|
readonly ok: 200;
|
|
@@ -129,7 +129,7 @@ declare const httpHeaders: {
|
|
|
129
129
|
export type InternalHttpStatusCode = CreateEnum<typeof httpStatusCode>;
|
|
130
130
|
export type InternalHttpMethod = CreateEnum<typeof httpMethod>;
|
|
131
131
|
export type InternalHttpHeaders = Lowercase<CreateEnum<typeof httpHeaders>> | string;
|
|
132
|
-
interface Request$1<T = InternalHandlerCallbackGenerics> {
|
|
132
|
+
interface Request$1<T extends InternalHandlerCallbackGenerics = InternalHandlerCallbackGenerics> {
|
|
133
133
|
protocol: string;
|
|
134
134
|
method: InternalHttpMethod;
|
|
135
135
|
path: string;
|
|
@@ -145,8 +145,8 @@ interface Response$1 {
|
|
|
145
145
|
addHeaders: (headers: Partial<Record<InternalHttpHeaders, string>>) => void;
|
|
146
146
|
removeHeaders: (headerNames: Array<InternalHttpHeaders>) => void;
|
|
147
147
|
}
|
|
148
|
-
export interface Context {
|
|
149
|
-
request: Request$1
|
|
148
|
+
export interface Context<T extends InternalHandlerCallbackGenerics = InternalHandlerCallbackGenerics> {
|
|
149
|
+
request: Request$1<T>;
|
|
150
150
|
response: Response$1;
|
|
151
151
|
}
|
|
152
152
|
/**
|
|
@@ -159,7 +159,7 @@ export interface Context {
|
|
|
159
159
|
* @param ctx - The request context containing request and response objects
|
|
160
160
|
* @returns A response body or a promise that resolves to a response body
|
|
161
161
|
*/
|
|
162
|
-
export type HandlerCallback<T = InternalHandlerCallbackGenerics> = (ctx: Context) => Promise<T["response"] | void> | T["response"] | void;
|
|
162
|
+
export type HandlerCallback<T extends InternalHandlerCallbackGenerics = InternalHandlerCallbackGenerics> = (ctx: Context<T>) => Promise<T["response"] | void> | T["response"] | void;
|
|
163
163
|
export type InternalGlobalHookOptions = {
|
|
164
164
|
routesToExclude: Array<string>;
|
|
165
165
|
} & {
|
|
@@ -218,9 +218,17 @@ export interface InternalPreCompiledRoute extends InternalRouteRegistry {
|
|
|
218
218
|
}
|
|
219
219
|
declare const logLevels: {
|
|
220
220
|
readonly off: "off";
|
|
221
|
-
readonly
|
|
222
|
-
readonly
|
|
221
|
+
readonly error: "error";
|
|
222
|
+
readonly warn: "warn";
|
|
223
|
+
readonly info: "info";
|
|
223
224
|
};
|
|
225
|
+
export interface Logger {
|
|
226
|
+
info: (...args: Array<unknown>) => void;
|
|
227
|
+
warn: (...args: Array<unknown>) => void;
|
|
228
|
+
error: (...args: Array<unknown>) => void;
|
|
229
|
+
debug?: (...args: Array<unknown>) => void;
|
|
230
|
+
trace?: (...args: Array<unknown>) => void;
|
|
231
|
+
}
|
|
224
232
|
/**
|
|
225
233
|
* Internal CORS Configuration Options
|
|
226
234
|
* Provides fine-grained control over Cross-Origin Resource Sharing
|
|
@@ -258,15 +266,21 @@ export interface InternalCorsEnabledConfiguration {
|
|
|
258
266
|
*/
|
|
259
267
|
methods: Array<string>;
|
|
260
268
|
/**
|
|
261
|
-
* Headers allowed in CORS requests
|
|
262
|
-
* - string[]: Specific headers
|
|
263
|
-
* - '*': Allow all headers
|
|
269
|
+
* Headers allowed in CORS requests *
|
|
264
270
|
* @default ['*']
|
|
271
|
+
*
|
|
272
|
+
* These are the headers that will be allowed in each request.
|
|
273
|
+
* These headers typically include things like 'Content-Type', 'Authorization', 'X-Requested-With', etc.
|
|
274
|
+
* Other common headers would include headers needed for third party services like stripe or AWS via webhooks.
|
|
265
275
|
*/
|
|
266
276
|
allowedHeaders: Array<string> | string | "*";
|
|
267
277
|
/**
|
|
268
278
|
* Headers exposed to the client in CORS responses
|
|
269
279
|
* @default []
|
|
280
|
+
*
|
|
281
|
+
* These are headers that in simple terms give the client "Permission" to access the headers in the response.
|
|
282
|
+
* For more context, the response can send as many headers as it wants, but the client can only access the headers that are exposed
|
|
283
|
+
* in this array.
|
|
270
284
|
*/
|
|
271
285
|
exposedHeaders: Array<string>;
|
|
272
286
|
/**
|
|
@@ -519,13 +533,35 @@ export interface InternalServerConfiguration {
|
|
|
519
533
|
*/
|
|
520
534
|
host: string;
|
|
521
535
|
/**
|
|
522
|
-
*
|
|
523
|
-
* - 'off': No logging (silent mode)
|
|
524
|
-
* - '
|
|
525
|
-
* - '
|
|
526
|
-
*
|
|
536
|
+
* Application logging level for YinzerFlow server
|
|
537
|
+
* - 'off': No application logging (silent mode)
|
|
538
|
+
* - 'error': Only error messages
|
|
539
|
+
* - 'warn': Warning and error messages
|
|
540
|
+
* - 'info': All application logging with Pittsburgh personality
|
|
541
|
+
* @default 'warn'
|
|
527
542
|
*/
|
|
528
543
|
logLevel: CreateEnum<typeof logLevels>;
|
|
544
|
+
/**
|
|
545
|
+
* Custom logger implementation
|
|
546
|
+
* If provided, this logger will be used instead of the built-in YinzerFlow logger
|
|
547
|
+
* Must implement the Logger interface
|
|
548
|
+
* @default undefined (uses built-in logger)
|
|
549
|
+
*/
|
|
550
|
+
logger?: Logger;
|
|
551
|
+
/**
|
|
552
|
+
* Network request/response logging (nginx-style logs)
|
|
553
|
+
* Completely separate from application logs - simple on/off toggle
|
|
554
|
+
* @default false
|
|
555
|
+
*/
|
|
556
|
+
networkLogs: boolean;
|
|
557
|
+
/**
|
|
558
|
+
* Custom logger for network logs (optional)
|
|
559
|
+
* If provided, network logs will be routed to this logger instead of built-in formatting
|
|
560
|
+
* Can be the same as the application logger or a different one
|
|
561
|
+
* Useful for unified monitoring (e.g., Winston with Datadog transport for both app and network logs)
|
|
562
|
+
* @default undefined (uses built-in network logging)
|
|
563
|
+
*/
|
|
564
|
+
networkLogger?: Logger;
|
|
529
565
|
/**
|
|
530
566
|
* Cross-Origin Resource Sharing configuration
|
|
531
567
|
*/
|
package/YinzerFlow.js
CHANGED
|
@@ -1,24 +1,22 @@
|
|
|
1
|
-
var Y1=Object.create;var{getPrototypeOf:Q1,defineProperty:R$,getOwnPropertyNames:X1}=Object;var J1=Object.prototype.hasOwnProperty;var T$=($,W,D)=>{D=$!=null?Y1(Q1($)):{};let Z=W||!$||!$.__esModule?R$(D,"default",{value:$,enumerable:!0}):D;for(let Y of X1($))if(!J1.call(Z,Y))R$(Z,Y,{get:()=>$[Y],enumerable:!0});return Z};var w1=($,W)=>()=>(W||$((W={exports:{}}).exports,W),W.exports);var O$=w1((K$,G$)=>{(function($,W){typeof K$=="object"&&typeof G$!="undefined"?G$.exports=W():typeof define=="function"&&define.amd?define(W):($=typeof globalThis!="undefined"?globalThis:$||self).dayjs=W()})(K$,function(){var $=1000,W=60000,D=3600000,Z="millisecond",Y="second",Q="minute",J="hour",O="day",F="week",k="month",V="quarter",N="year",S="date",p="Invalid Date",X$=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,W1=/\[([^\]]+)]|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,D1={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(M){var K=["th","st","nd","rd"],X=M%100;return"["+M+(K[(X-20)%10]||K[X]||K[0])+"]"}},J$=function(M,K,X){var G=String(M);return!G||G.length>=K?M:""+Array(K+1-G.length).join(X)+M},Z1={s:J$,z:function(M){var K=-M.utcOffset(),X=Math.abs(K),G=Math.floor(X/60),w=X%60;return(K<=0?"+":"-")+J$(G,2,"0")+":"+J$(w,2,"0")},m:function M(K,X){if(K.date()<X.date())return-M(X,K);var G=12*(X.year()-K.year())+(X.month()-K.month()),w=K.clone().add(G,k),U=X-w<0,j=K.clone().add(G+(U?-1:1),k);return+(-(G+(X-w)/(U?w-j:j-w))||0)},a:function(M){return M<0?Math.ceil(M)||0:Math.floor(M)},p:function(M){return{M:k,y:N,w:F,d:O,D:S,h:J,m:Q,s:Y,ms:Z,Q:V}[M]||String(M||"").toLowerCase().replace(/s$/,"")},u:function(M){return M===void 0}},r="en",h={};h[r]=D1;var z$="$isDayjsObject",w$=function(M){return M instanceof o||!(!M||!M[z$])},t=function M(K,X,G){var w;if(!K)return r;if(typeof K=="string"){var U=K.toLowerCase();h[U]&&(w=U),X&&(h[U]=X,w=U);var j=K.split("-");if(!w&&j.length>1)return M(j[0])}else{var H=K.name;h[H]=K,w=H}return!G&&w&&(r=w),w||!G&&r},L=function(M,K){if(w$(M))return M.clone();var X=typeof K=="object"?K:{};return X.date=M,X.args=arguments,new o(X)},_=Z1;_.l=t,_.i=w$,_.w=function(M,K){return L(M,{locale:K.$L,utc:K.$u,x:K.$x,$offset:K.$offset})};var o=function(){function M(X){this.$L=t(X.locale,null,!0),this.parse(X),this.$x=this.$x||X.x||{},this[z$]=!0}var K=M.prototype;return K.parse=function(X){this.$d=function(G){var{date:w,utc:U}=G;if(w===null)return new Date(NaN);if(_.u(w))return new Date;if(w instanceof Date)return new Date(w);if(typeof w=="string"&&!/Z$/i.test(w)){var j=w.match(X$);if(j){var H=j[2]-1||0,B=(j[7]||"0").substring(0,3);return U?new Date(Date.UTC(j[1],H,j[3]||1,j[4]||0,j[5]||0,j[6]||0,B)):new Date(j[1],H,j[3]||1,j[4]||0,j[5]||0,j[6]||0,B)}}return new Date(w)}(X),this.init()},K.init=function(){var X=this.$d;this.$y=X.getFullYear(),this.$M=X.getMonth(),this.$D=X.getDate(),this.$W=X.getDay(),this.$H=X.getHours(),this.$m=X.getMinutes(),this.$s=X.getSeconds(),this.$ms=X.getMilliseconds()},K.$utils=function(){return _},K.isValid=function(){return this.$d.toString()!==p},K.isSame=function(X,G){var w=L(X);return this.startOf(G)<=w&&w<=this.endOf(G)},K.isAfter=function(X,G){return L(X)<this.startOf(G)},K.isBefore=function(X,G){return this.endOf(G)<L(X)},K.$g=function(X,G,w){return _.u(X)?this[G]:this.set(w,X)},K.unix=function(){return Math.floor(this.valueOf()/1000)},K.valueOf=function(){return this.$d.getTime()},K.startOf=function(X,G){var w=this,U=!!_.u(G)||G,j=_.p(X),H=function(f,R){var y=_.w(w.$u?Date.UTC(w.$y,R,f):new Date(w.$y,R,f),w);return U?y:y.endOf(O)},B=function(f,R){return _.w(w.toDate()[f].apply(w.toDate("s"),(U?[0,0,0,0]:[23,59,59,999]).slice(R)),w)},A=this.$W,I=this.$M,P=this.$D,g="set"+(this.$u?"UTC":"");switch(j){case N:return U?H(1,0):H(31,11);case k:return U?H(1,I):H(0,I+1);case F:var m=this.$locale().weekStart||0,d=(A<m?A+7:A)-m;return H(U?P-d:P+(6-d),I);case O:case S:return B(g+"Hours",0);case J:return B(g+"Minutes",1);case Q:return B(g+"Seconds",2);case Y:return B(g+"Milliseconds",3);default:return this.clone()}},K.endOf=function(X){return this.startOf(X,!1)},K.$set=function(X,G){var w,U=_.p(X),j="set"+(this.$u?"UTC":""),H=(w={},w[O]=j+"Date",w[S]=j+"Date",w[k]=j+"Month",w[N]=j+"FullYear",w[J]=j+"Hours",w[Q]=j+"Minutes",w[Y]=j+"Seconds",w[Z]=j+"Milliseconds",w)[U],B=U===O?this.$D+(G-this.$W):G;if(U===k||U===N){var A=this.clone().set(S,1);A.$d[H](B),A.init(),this.$d=A.set(S,Math.min(this.$D,A.daysInMonth())).$d}else H&&this.$d[H](B);return this.init(),this},K.set=function(X,G){return this.clone().$set(X,G)},K.get=function(X){return this[_.p(X)]()},K.add=function(X,G){var w,U=this;X=Number(X);var j=_.p(G),H=function(I){var P=L(U);return _.w(P.date(P.date()+Math.round(I*X)),U)};if(j===k)return this.set(k,this.$M+X);if(j===N)return this.set(N,this.$y+X);if(j===O)return H(1);if(j===F)return H(7);var B=(w={},w[Q]=W,w[J]=D,w[Y]=$,w)[j]||1,A=this.$d.getTime()+X*B;return _.w(A,this)},K.subtract=function(X,G){return this.add(-1*X,G)},K.format=function(X){var G=this,w=this.$locale();if(!this.isValid())return w.invalidDate||p;var U=X||"YYYY-MM-DDTHH:mm:ssZ",j=_.z(this),H=this.$H,B=this.$m,A=this.$M,I=w.weekdays,P=w.months,g=w.meridiem,m=function(R,y,i,e){return R&&(R[y]||R(G,U))||i[y].slice(0,e)},d=function(R){return _.s(H%12||12,R,"0")},f=g||function(R,y,i){var e=R<12?"AM":"PM";return i?e.toLowerCase():e};return U.replace(W1,function(R,y){return y||function(i){switch(i){case"YY":return String(G.$y).slice(-2);case"YYYY":return _.s(G.$y,4,"0");case"M":return A+1;case"MM":return _.s(A+1,2,"0");case"MMM":return m(w.monthsShort,A,P,3);case"MMMM":return m(P,A);case"D":return G.$D;case"DD":return _.s(G.$D,2,"0");case"d":return String(G.$W);case"dd":return m(w.weekdaysMin,G.$W,I,2);case"ddd":return m(w.weekdaysShort,G.$W,I,3);case"dddd":return I[G.$W];case"H":return String(H);case"HH":return _.s(H,2,"0");case"h":return d(1);case"hh":return d(2);case"a":return f(H,B,!0);case"A":return f(H,B,!1);case"m":return String(B);case"mm":return _.s(B,2,"0");case"s":return String(G.$s);case"ss":return _.s(G.$s,2,"0");case"SSS":return _.s(G.$ms,3,"0");case"Z":return j}return null}(R)||j.replace(":","")})},K.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},K.diff=function(X,G,w){var U,j=this,H=_.p(G),B=L(X),A=(B.utcOffset()-this.utcOffset())*W,I=this-B,P=function(){return _.m(j,B)};switch(H){case N:U=P()/12;break;case k:U=P();break;case V:U=P()/3;break;case F:U=(I-A)/604800000;break;case O:U=(I-A)/86400000;break;case J:U=I/D;break;case Q:U=I/W;break;case Y:U=I/$;break;default:U=I}return w?U:_.a(U)},K.daysInMonth=function(){return this.endOf(k).$D},K.$locale=function(){return h[this.$L]},K.locale=function(X,G){if(!X)return this.$L;var w=this.clone(),U=t(X,G,!0);return U&&(w.$L=U),w},K.clone=function(){return _.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()},M}(),I$=o.prototype;return L.prototype=I$,[["$ms",Z],["$s",Y],["$m",Q],["$H",J],["$W",O],["$M",k],["$y",N],["$D",S]].forEach(function(M){I$[M[1]]=function(K){return this.$g(K,M[0],M[1])}}),L.extend=function(M,K){return M.$i||(M(K,o,L),M.$i=!0),L},L.locale=t,L.isDayjs=w$,L.unix=function(M){return L(1000*M)},L.en=h[r],L.Ls=h,L.p={},L})});import{createServer as C0}from"net";var n=T$(O$(),1);var $$={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},E={delete:"DELETE",get:"GET",head:"HEAD",post:"POST",put:"PUT",patch:"PATCH",options:"OPTIONS"},x={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"},u={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"},c={base64:"base64",binary:"binary",utf8:"utf8"};var v$=($,W)=>{if(!$)return"0";let D=0;if(W===c.base64)D=Buffer.byteLength($,"utf8");if(W===c.binary)D=$.length;if(W===c.utf8)D=Buffer.byteLength($,"utf8");return String(D)};var W$=($,W)=>{if(!W.enabled)return!1;if($.request.method==="OPTIONS"){if(!x$($,W))return $.response.setStatusCode(403),$._response._setBody({error:"CORS: Origin not allowed",origin:$.request.headers.origin}),!0;$.response.setStatusCode(W.optionsSuccessStatus);let Y=P$($,W);if($._response._setHeadersIfNotSet({[u.accessControlAllowOrigin]:Y,[u.accessControlAllowMethods]:W.methods.join(", "),[u.accessControlAllowHeaders]:typeof W.allowedHeaders==="string"?W.allowedHeaders:W.allowedHeaders.join(", "),[u.accessControlAllowCredentials]:W.credentials?"true":"false",[u.accessControlExposeHeaders]:W.exposedHeaders.join(", "),[u.accessControlMaxAge]:W.maxAge.toString()}),W.preflightContinue)return!0;return $._response._setBody(""),!1}if(x$($,W)){let Z=P$($,W);$._response._setHeadersIfNotSet({[u.accessControlAllowOrigin]:Z,[u.accessControlAllowCredentials]:W.credentials?"true":"false"})}return!0},P$=($,W)=>{if(W.origin==="*"){if(W.credentials)throw new Error('CORS Security Error: origin: "*" with credentials: true is forbidden by CORS spec and creates security vulnerabilities. Use specific origins instead.');return"*"}let D=$.request.headers.origin;if(D)return D;if(typeof W.origin==="string")return W.origin;if(Array.isArray(W.origin)&&W.origin.length>0){let[Z]=W.origin;return Z??"null"}return"null"},x$=($,W)=>{if(W.origin==="*")return!0;let D=$.request.headers.origin?.toLowerCase()??"";if(typeof W.origin==="function")return Boolean(W.origin(D,$.request));if(typeof W.origin==="string")return D===W.origin.toLowerCase();if(Array.isArray(W.origin))return W.origin.some((Z)=>D===Z.toLowerCase());if(W.origin instanceof RegExp)return W.origin.test(D);return!1};class M${setup;constructor($){this.setup=$}async handle($){try{if(W$($,this.setup._configuration.cors))return;let W=this.setup._routeRegistry._findRoute($.request.method,$.request.path);if(!W){let V=await this.setup._hooks._onNotFound($);$._response._setBody(V),$._response._parseResponseIntoString(),$._response._setHeadersIfNotSet({Date:n.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":$._response._stringBody.split(`
|
|
1
|
+
var O1=Object.create;var{getPrototypeOf:M1,defineProperty:u$,getOwnPropertyNames:U1}=Object;var j1=Object.prototype.hasOwnProperty;var F$=($,W,Z)=>{Z=$!=null?O1(M1($)):{};let D=W||!$||!$.__esModule?u$(Z,"default",{value:$,enumerable:!0}):Z;for(let Y of U1($))if(!j1.call(D,Y))u$(D,Y,{get:()=>$[Y],enumerable:!0});return D};var F1=($,W)=>()=>(W||$((W={exports:{}}).exports,W),W.exports);var Y$=F1((_$,V$)=>{(function($,W){typeof _$=="object"&&typeof V$!="undefined"?V$.exports=W():typeof define=="function"&&define.amd?define(W):($=typeof globalThis!="undefined"?globalThis:$||self).dayjs=W()})(_$,function(){var $=1000,W=60000,Z=3600000,D="millisecond",Y="second",Q="minute",X="hour",O="day",H="week",_="month",I="quarter",A="year",L="date",o="Invalid Date",M$=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,e=/\[([^\]]+)]|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,U$={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(U){var G=["th","st","nd","rd"],J=U%100;return"["+U+(G[(J-20)%10]||G[J]||G[0])+"]"}},s=function(U,G,J){var M=String(U);return!M||M.length>=G?U:""+Array(G+1-M.length).join(J)+U},$$={s,z:function(U){var G=-U.utcOffset(),J=Math.abs(G),M=Math.floor(J/60),K=J%60;return(G<=0?"+":"-")+s(M,2,"0")+":"+s(K,2,"0")},m:function U(G,J){if(G.date()<J.date())return-U(J,G);var M=12*(J.year()-G.year())+(J.month()-G.month()),K=G.clone().add(M,_),j=J-K<0,F=G.clone().add(M+(j?-1:1),_);return+(-(M+(J-K)/(j?K-F:F-K))||0)},a:function(U){return U<0?Math.ceil(U)||0:Math.floor(U)},p:function(U){return{M:_,y:A,w:H,d:O,D:L,h:X,m:Q,s:Y,ms:D,Q:I}[U]||String(U||"").toLowerCase().replace(/s$/,"")},u:function(U){return U===void 0}},m="en",f={};f[m]=U$;var C$="$isDayjsObject",j$=function(U){return U instanceof Z$||!(!U||!U[C$])},W$=function U(G,J,M){var K;if(!G)return m;if(typeof G=="string"){var j=G.toLowerCase();f[j]&&(K=j),J&&(f[j]=J,K=j);var F=G.split("-");if(!K&&F.length>1)return U(F[0])}else{var w=G.name;f[w]=G,K=w}return!M&&K&&(m=K),K||!M&&m},z=function(U,G){if(j$(U))return U.clone();var J=typeof G=="object"?G:{};return J.date=U,J.args=arguments,new Z$(J)},q=$$;q.l=W$,q.i=j$,q.w=function(U,G){return z(U,{locale:G.$L,utc:G.$u,x:G.$x,$offset:G.$offset})};var Z$=function(){function U(J){this.$L=W$(J.locale,null,!0),this.parse(J),this.$x=this.$x||J.x||{},this[C$]=!0}var G=U.prototype;return G.parse=function(J){this.$d=function(M){var{date:K,utc:j}=M;if(K===null)return new Date(NaN);if(q.u(K))return new Date;if(K instanceof Date)return new Date(K);if(typeof K=="string"&&!/Z$/i.test(K)){var F=K.match(M$);if(F){var w=F[2]-1||0,B=(F[7]||"0").substring(0,3);return j?new Date(Date.UTC(F[1],w,F[3]||1,F[4]||0,F[5]||0,F[6]||0,B)):new Date(F[1],w,F[3]||1,F[4]||0,F[5]||0,F[6]||0,B)}}return new Date(K)}(J),this.init()},G.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()},G.$utils=function(){return q},G.isValid=function(){return this.$d.toString()!==o},G.isSame=function(J,M){var K=z(J);return this.startOf(M)<=K&&K<=this.endOf(M)},G.isAfter=function(J,M){return z(J)<this.startOf(M)},G.isBefore=function(J,M){return this.endOf(M)<z(J)},G.$g=function(J,M,K){return q.u(J)?this[M]:this.set(K,J)},G.unix=function(){return Math.floor(this.valueOf()/1000)},G.valueOf=function(){return this.$d.getTime()},G.startOf=function(J,M){var K=this,j=!!q.u(M)||M,F=q.p(J),w=function(p,R){var h=q.w(K.$u?Date.UTC(K.$y,R,p):new Date(K.$y,R,p),K);return j?h:h.endOf(O)},B=function(p,R){return q.w(K.toDate()[p].apply(K.toDate("s"),(j?[0,0,0,0]:[23,59,59,999]).slice(R)),K)},S=this.$W,k=this.$M,T=this.$D,c="set"+(this.$u?"UTC":"");switch(F){case A:return j?w(1,0):w(31,11);case _:return j?w(1,k):w(0,k+1);case H:var l=this.$locale().weekStart||0,a=(S<l?S+7:S)-l;return w(j?T-a:T+(6-a),k);case O:case L:return B(c+"Hours",0);case X:return B(c+"Minutes",1);case Q:return B(c+"Seconds",2);case Y:return B(c+"Milliseconds",3);default:return this.clone()}},G.endOf=function(J){return this.startOf(J,!1)},G.$set=function(J,M){var K,j=q.p(J),F="set"+(this.$u?"UTC":""),w=(K={},K[O]=F+"Date",K[L]=F+"Date",K[_]=F+"Month",K[A]=F+"FullYear",K[X]=F+"Hours",K[Q]=F+"Minutes",K[Y]=F+"Seconds",K[D]=F+"Milliseconds",K)[j],B=j===O?this.$D+(M-this.$W):M;if(j===_||j===A){var S=this.clone().set(L,1);S.$d[w](B),S.init(),this.$d=S.set(L,Math.min(this.$D,S.daysInMonth())).$d}else w&&this.$d[w](B);return this.init(),this},G.set=function(J,M){return this.clone().$set(J,M)},G.get=function(J){return this[q.p(J)]()},G.add=function(J,M){var K,j=this;J=Number(J);var F=q.p(M),w=function(k){var T=z(j);return q.w(T.date(T.date()+Math.round(k*J)),j)};if(F===_)return this.set(_,this.$M+J);if(F===A)return this.set(A,this.$y+J);if(F===O)return w(1);if(F===H)return w(7);var B=(K={},K[Q]=W,K[X]=Z,K[Y]=$,K)[F]||1,S=this.$d.getTime()+J*B;return q.w(S,this)},G.subtract=function(J,M){return this.add(-1*J,M)},G.format=function(J){var M=this,K=this.$locale();if(!this.isValid())return K.invalidDate||o;var j=J||"YYYY-MM-DDTHH:mm:ssZ",F=q.z(this),w=this.$H,B=this.$m,S=this.$M,k=K.weekdays,T=K.months,c=K.meridiem,l=function(R,h,n,D$){return R&&(R[h]||R(M,j))||n[h].slice(0,D$)},a=function(R){return q.s(w%12||12,R,"0")},p=c||function(R,h,n){var D$=R<12?"AM":"PM";return n?D$.toLowerCase():D$};return j.replace(e,function(R,h){return h||function(n){switch(n){case"YY":return String(M.$y).slice(-2);case"YYYY":return q.s(M.$y,4,"0");case"M":return S+1;case"MM":return q.s(S+1,2,"0");case"MMM":return l(K.monthsShort,S,T,3);case"MMMM":return l(T,S);case"D":return M.$D;case"DD":return q.s(M.$D,2,"0");case"d":return String(M.$W);case"dd":return l(K.weekdaysMin,M.$W,k,2);case"ddd":return l(K.weekdaysShort,M.$W,k,3);case"dddd":return k[M.$W];case"H":return String(w);case"HH":return q.s(w,2,"0");case"h":return a(1);case"hh":return a(2);case"a":return p(w,B,!0);case"A":return p(w,B,!1);case"m":return String(B);case"mm":return q.s(B,2,"0");case"s":return String(M.$s);case"ss":return q.s(M.$s,2,"0");case"SSS":return q.s(M.$ms,3,"0");case"Z":return F}return null}(R)||F.replace(":","")})},G.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},G.diff=function(J,M,K){var j,F=this,w=q.p(M),B=z(J),S=(B.utcOffset()-this.utcOffset())*W,k=this-B,T=function(){return q.m(F,B)};switch(w){case A:j=T()/12;break;case _:j=T();break;case I:j=T()/3;break;case H:j=(k-S)/604800000;break;case O:j=(k-S)/86400000;break;case X:j=k/Z;break;case Q:j=k/W;break;case Y:j=k/$;break;default:j=k}return K?j:q.a(j)},G.daysInMonth=function(){return this.endOf(_).$D},G.$locale=function(){return f[this.$L]},G.locale=function(J,M){if(!J)return this.$L;var K=this.clone(),j=W$(J,M,!0);return j&&(K.$L=j),K},G.clone=function(){return q.w(this.$d,this)},G.toDate=function(){return new Date(this.valueOf())},G.toJSON=function(){return this.isValid()?this.toISOString():null},G.toISOString=function(){return this.$d.toISOString()},G.toString=function(){return this.$d.toUTCString()},U}(),b$=Z$.prototype;return z.prototype=b$,[["$ms",D],["$s",Y],["$m",Q],["$H",X],["$W",O],["$M",_],["$y",A],["$D",L]].forEach(function(U){b$[U[1]]=function(G){return this.$g(G,U[0],U[1])}}),z.extend=function(U,G){return U.$i||(U(G,Z$,z),U.$i=!0),z},z.locale=W$,z.isDayjs=j$,z.unix=function(U){return z(1000*U)},z.en=f[m],z.Ls=f,z.p={},z})});import{createServer as f0}from"net";var w$=F$(Y$(),1);var Q$={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},E={delete:"DELETE",get:"GET",head:"HEAD",post:"POST",put:"PUT",patch:"PATCH",options:"OPTIONS"},v={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"},u={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"},r={base64:"base64",binary:"binary",utf8:"utf8"};var X$=($,W)=>{if(!W.enabled)return!1;if($.request.method==="OPTIONS"){if(!h$($,W))return $.response.setStatusCode(403),$._response._setBody({error:"CORS: Origin not allowed",origin:$.request.headers.origin}),!0;$.response.setStatusCode(W.optionsSuccessStatus);let Y=y$($,W);if($._response._setHeadersIfNotSet({[u.accessControlAllowOrigin]:Y,[u.accessControlAllowMethods]:W.methods.join(", "),[u.accessControlAllowHeaders]:typeof W.allowedHeaders==="string"?W.allowedHeaders:W.allowedHeaders.join(", "),[u.accessControlAllowCredentials]:W.credentials?"true":"false",[u.accessControlExposeHeaders]:W.exposedHeaders.join(", "),[u.accessControlMaxAge]:W.maxAge.toString()}),W.preflightContinue)return!1;return $._response._setBody(""),!0}if(h$($,W)){let D=y$($,W);$._response._setHeadersIfNotSet({[u.accessControlAllowOrigin]:D,[u.accessControlAllowCredentials]:W.credentials?"true":"false"})}return!0},y$=($,W)=>{if(W.origin==="*"){if(W.credentials)throw new Error('CORS Security Error: origin: "*" with credentials: true is forbidden by CORS spec and creates security vulnerabilities. Use specific origins instead.');return"*"}let Z=$.request.headers.origin;if(Z)return Z;if(typeof W.origin==="string")return W.origin;if(Array.isArray(W.origin)&&W.origin.length>0){let[D]=W.origin;return D??"null"}return"null"},h$=($,W)=>{if(W.origin==="*")return!0;let Z=$.request.headers.origin?.toLowerCase()??"";if(typeof W.origin==="function")return Boolean(W.origin(Z,$.request));if(typeof W.origin==="string")return Z===W.origin.toLowerCase();if(Array.isArray(W.origin))return W.origin.some((D)=>Z===D.toLowerCase());if(W.origin instanceof RegExp)return W.origin.test(Z);return!1};var m$=F$(Y$(),1),y="YINZER",N={reset:"\x1B[0m",cyan:"\x1B[96m",yellow:"\x1B[93m",red:"\x1B[91m",green:"\x1B[92m",magenta:"\x1B[95m",gray:"\x1B[90m"},_1={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"]},d=!1,P=null,C=()=>m$.default().format("YYYY-MM-DD HH:mm:ss.SSS"),H$=($)=>{let W=_1[$];return W[Math.floor(Math.random()*W.length)]??""},V1=($)=>{if(typeof $==="string")return Buffer.byteLength($,"utf8");if(Buffer.isBuffer($))return $.length;if(typeof $==="object"&&$!==null)try{return Buffer.byteLength(JSON.stringify($),"utf8")}catch{return 0}return 0},H1=($)=>{if($>=200&&$<300)return"✅";if($>=300&&$<400)return"\uD83D\uDD04";if($>=400&&$<500)return"❌";if($>=500)return"\uD83D\uDCA5";return"❓"},q1=($)=>{if($<50)return{emoji:"⚡",phrase:Math.random()<0.5?"lightning quick n'at!":"faster than a Stillers touchdown!"};if($<100)return{emoji:"\uD83D\uDD25",phrase:Math.random()<0.5?"that's the way!":"smooth as butter n'at!"};if($<200)return{emoji:"✅",phrase:Math.random()<0.5?"not bad yinz!":"keepin' up just fine!"};if($<500)return{emoji:"⚠️",phrase:Math.random()<0.5?"eh, could be better":"slowin' down a bit there"};if($<1000)return{emoji:"\uD83D\uDC0C",phrase:Math.random()<0.5?"that's draggin' n'at":"c'mon, pick up the pace!"};return{emoji:"\uD83D\uDCA5",phrase:Math.random()<0.5?"what a jagoff response time!":"slower than traffic on the Parkway!"}},w1=($,W,Z)=>{if(!d)return;let D=C(),Y=W??"unknown",Q=Z?` - ${Z}`:"",X="",O="info";if($==="connect")X=`\uD83E\uDD1D [NETWORK] New visitor from ${Y} - Welcome to the 'Burgh!`;else if($==="disconnect")X=`\uD83D\uDC4B [NETWORK] ${Y} headed out - Thanks for stopping by, yinz come back now!`;else X=`\uD83D\uDCA5 [NETWORK] Connection trouble with ${Y}${Q} - That's not good, n'at!`,O="error";if(P)P[O](X);else{let H=O==="error"?N.red:N.gray;console.log(`${H}[${y}] [${D}] ${X}${N.reset}`)}},N1=($,W,Z)=>{if(!d)return;let{request:D}=$,Y=$._response,Q=(Z-W).toFixed(1),X=D.ipAddress||"unknown",{method:O,path:H,protocol:_}=D,I=Y._statusCode,A=V1(Y._body),L=D.headers.referer?`"${D.headers.referer}"`:'"-"',o=D.headers["user-agent"]?`"${D.headers["user-agent"]}"`:'"-"',M$=H1(I),e=`\uD83C\uDFE0 ${X} - - [${C()}] "${O} ${H} ${_}" ${I} ${A}b ${L} ${o} ${Q}ms ${M$}`,U$=parseFloat(Q),{emoji:s,phrase:$$}=q1(U$),m=`${s} [PERF] Response time: ${Q}ms - ${$$}`;if(P)P.info(`[NETWORK] ${e}`),P.info(`[PERF] ${m}`);else console.log(`${N.gray}[${y}] [${C()}] [NETWORK] ${e}${N.reset}`),console.log(`${N.magenta}[${y}] ${s} [${C()}] [PERF] Response time: ${Q}ms - ${$$}${N.reset}`)},B1=($,W)=>{if(!d)return;let Z=C(),D=$&&W?`${W}:${$}`:"unknown",Y=H$("positive"),Q=`\uD83D\uDE80 [NETWORK] YinzerFlow server is up and running at ${D} - Ready to serve yinz all, ${Y}!`;if(P)P.info(Q);else console.log(`${N.gray}[${y}] [${Z}] ${Q}${N.reset}`)},E1=($,W)=>{if(!d)return;let Z=C(),D=$&&W?`${W}:${$}`:"unknown",Y=H$("neutral"),Q=`\uD83D\uDED1 [NETWORK] YinzerFlow server at ${D} is shutting down - See yinz later, ${Y}!`;if(P)P.info(Q);else console.log(`${N.gray}[${y}] [${Z}] ${Q}${N.reset}`)},A1=($,W,Z)=>{if(!d)return;let D=C(),Y=$&&W?`${W}:${$}`:"unknown",Q=Z?` - ${Z}`:"",X=H$("negative"),O=`\uD83D\uDCA5 [NETWORK] Server error at ${Y}${Q} - Something's not right, ${X}!`;if(P)P.error(O);else console.log(`${N.red}[${y}] [${D}] ${O}${N.reset}`)},z1=($)=>{d=$},S1=($)=>{P=$},x={setEnabled:z1,setNetworkLogger:S1,connection:w1,request:N1,serverStart:B1,serverStop:E1,serverError:A1};var i={off:0,error:1,warn:2,info:3},k1={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"]},t=i.warn,g=null,I1=($)=>{let W=k1[$];return W[Math.floor(Math.random()*W.length)]??""},L1=(...$)=>{if(t<i.info)return;if(g)g.info(...$);else q$("info",...$)},R1=(...$)=>{if(t<i.warn)return;if(g)g.warn(...$);else q$("warn",...$)},T1=(...$)=>{if(t<i.error)return;if(g)g.error(...$);else q$("error",...$)},v1=($,W,Z)=>{if(t<i.info)return;let D=C(),Y="❓ ",Q="";if(W<50)Y="⚡ ",Q=Math.random()<0.5?"lightning quick n'at!":"faster than a Stillers touchdown!";else if(W<100)Y="\uD83D\uDD25 ",Q=Math.random()<0.5?"that's the way!":"smooth as butter n'at!";else if(W<200)Y="✅ ",Q=Math.random()<0.5?"not bad yinz!":"keepin' up just fine!";else if(W<500)Y="⚠️ ",Q=Math.random()<0.5?"eh, could be better":"slowin' down a bit there";else if(W<1000)Y="\uD83D\uDC0C ",Q=Math.random()<0.5?"that's draggin' n'at":"c'mon, pick up the pace!";else Y="\uD83D\uDCA5 ",Q=Math.random()<0.5?"what a jagoff response time!":"slower than traffic on the Parkway!";let X=`${N.magenta}[${y}] ${Y} [${D}] [PERF]${N.reset}`,O=Z?{...Z,executionTime:`${W}ms`}:{executionTime:`${W}ms`};console.log(`${X} ${$} -`,O,`- ${Q}`)},P1=($)=>{t={off:0,error:1,warn:2,info:3}[$]},x1=($)=>{g=$},q$=($,...W)=>{let Z=C(),D="✅ ",Y=N.cyan,Q="positive",X="log";if($==="error")D="❌ ",Y=N.red,Q="negative",X="error";else if($==="warn")D="⚠️ ",Y=N.yellow,Q="neutral",X="warn";else D="✅ ",Y=N.cyan,Q="positive",X="log";let O=I1(Q),H=`${Y}[${y}] ${D}[${Z}] [${$.toUpperCase()}]${N.reset}`;console[X](`${H}`,...W,`- ${O}`)},V={setLogLevel:P1,setCustomLogger:x1,info:L1,warn:R1,error:T1,perf:v1,levels:i};class N${setup;constructor($){this.setup=$}async handle($){try{if(X$($,this.setup._configuration.cors)){$._response._parseResponseIntoString();return}let W=this.setup._routeRegistry._findRoute($.request.method,$.request.path);if(!W){let _=await this.setup._hooks._onNotFound($);$._response._setBody(_),$._response._parseResponseIntoString();return}let{handler:Z,options:D}=W,{beforeHooks:Y,afterHooks:Q}=D,X=this.setup._hooks._beforeAll;for(let _ of X)await _.handler($);for(let _ of Y)await _($);let O=await Z($);for(let _ of Q)await _($);let H=this.setup._hooks._afterAll;for(let _ of H)await _.handler($);if($._response._setBody(O),$.request.method==="HEAD")$._response._setBody(null);$._response._parseResponseIntoString();return}catch(W){await this.handleError($,W)}}async handleError($,W){V.error("Request handling error",W);try{let Z=this.setup._hooks._onError,D=await Z($);$._response._setBody(D),X$($,this.setup._configuration.cors),$._response._parseResponseIntoString(),$._response._setHeadersIfNotSet({Date:w$.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":$._response._stringBody.split(`
|
|
2
2
|
|
|
3
|
-
`)[1]?.length.toString()??"0"})
|
|
3
|
+
`)[1]?.length.toString()??"0"})}catch(Z){V.error("Error handler failed",Z),$.response.setStatusCode(500),$._response._setBody({success:!1,message:"Internal Server Error"}),X$($,this.setup._configuration.cors),$._response._parseResponseIntoString(),$._response._setHeadersIfNotSet({Date:w$.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":$._response._stringBody.split(`
|
|
4
4
|
|
|
5
|
-
`)[1]?.length.toString()??"0"})}
|
|
6
|
-
|
|
7
|
-
`)[1]?.length.toString()??"0"})}}}var K1=["__proto__","constructor","prototype"],C$=($,W)=>{if(!$||!$.trim()||$.trim()==="\x00")return;let D=Buffer.byteLength($,"utf8");if(D>W.maxSize)throw new Error(`Request body too large: ${D} bytes exceeds limit of ${W.maxSize} bytes`);let Z=null;try{Z=JSON.parse($)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);throw new Error(`Invalid JSON syntax: ${Q}`)}try{U$(Z,W,1)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);throw new Error(`JSON security validation failed: ${Q}`)}return Z},G1=($,W)=>{if(typeof $==="string"&&$.length>W.maxStringLength)throw new Error(`String too long: ${$.length} characters exceeds limit of ${W.maxStringLength}`)},O1=($,W,D)=>{if($.length>W.maxArrayLength)throw new Error(`Array too large: ${$.length} elements exceeds limit of ${W.maxArrayLength}`);for(let Z of $)U$(Z,W,D+1)},M1=($,W)=>{if($.length>W.maxKeys)throw new Error(`Object has too many keys: ${$.length} exceeds limit of ${W.maxKeys}`);if(!W.allowPrototypeProperties){for(let D of $)if(K1.includes(D))throw new Error(`Prototype pollution attempt detected: property '${D}' is not allowed`)}},U1=($,W,D)=>{let Z=Object.keys($);for(let Y of Z){if(Y.length>W.maxStringLength)throw new Error(`Object key too long: '${Y.substring(0,50)}...' exceeds limit of ${W.maxStringLength}`);let Q=$[Y];if(typeof Q==="string"&&Q.length>W.maxStringLength)throw new Error(`String value too long: property '${Y}' has ${Q.length} characters, exceeds limit of ${W.maxStringLength}`);U$(Q,W,D+1)}},U$=($,W,D)=>{if(D>W.maxDepth)throw new Error(`JSON nesting too deep: current depth ${D} exceeds maximum depth of ${W.maxDepth}`);if($===null||typeof $!=="object"){G1($,W);return}if(Array.isArray($)){O1($,W,D);return}let Z=Object.keys($);M1(Z,W),U1($,W,D)};var j1=($)=>{let W=$.startsWith(`\r
|
|
8
|
-
`)?$.slice(2):$,D=W.indexOf(`\r
|
|
5
|
+
`)[1]?.length.toString()??"0"})}}}var f$=["__proto__","constructor","prototype"],l$=($,W)=>{if(!$||!$.trim()||$.trim()==="\x00")return;let Z=Buffer.byteLength($,"utf8");if(Z>W.maxSize)throw V.warn("[SECURITY] JSON request body too large",{size:Z,limit:W.maxSize,sizeMB:Math.round(Z/1024/1024)}),new Error(`Request body too large: ${Z} bytes exceeds limit of ${W.maxSize} bytes`);let D=null;try{D=JSON.parse($)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);throw new Error(`Invalid JSON syntax: ${Q}`)}try{B$(D,W,1)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);throw new Error(`JSON security validation failed: ${Q}`)}return D},C1=($,W)=>{if(typeof $==="string"&&$.length>W.maxStringLength)throw new Error(`String too long: ${$.length} characters exceeds limit of ${W.maxStringLength}`)},b1=($,W,Z)=>{if($.length>W.maxArrayLength)throw new Error(`Array too large: ${$.length} elements exceeds limit of ${W.maxArrayLength}`);for(let D of $)B$(D,W,Z+1)},u1=($,W)=>{if($.length>W.maxKeys)throw new Error(`Object has too many keys: ${$.length} exceeds limit of ${W.maxKeys}`);if(!W.allowPrototypeProperties){for(let Z of $)if(f$.includes(Z))throw V.warn("[SECURITY] Prototype pollution attempt detected",{property:Z,dangerousProperties:f$}),new Error(`Prototype pollution attempt detected: property '${Z}' is not allowed`)}},y1=($,W,Z)=>{let D=Object.keys($);for(let Y of D){if(Y.length>W.maxStringLength)throw new Error(`Object key too long: '${Y.substring(0,50)}...' exceeds limit of ${W.maxStringLength}`);let Q=$[Y];if(typeof Q==="string"&&Q.length>W.maxStringLength)throw new Error(`String value too long: property '${Y}' has ${Q.length} characters, exceeds limit of ${W.maxStringLength}`);B$(Q,W,Z+1)}},B$=($,W,Z)=>{if(Z>W.maxDepth)throw V.warn("[SECURITY] JSON nesting too deep - potential stack overflow attack",{currentDepth:Z,maxDepth:W.maxDepth}),new Error(`JSON nesting too deep: current depth ${Z} exceeds maximum depth of ${W.maxDepth}`);if($===null||typeof $!=="object"){C1($,W);return}if(Array.isArray($)){b1($,W,Z);return}let D=Object.keys($);u1(D,W),y1($,W,Z)};var h1=($)=>{let W=$.startsWith(`\r
|
|
6
|
+
`)?$.slice(2):$,Z=W.indexOf(`\r
|
|
9
7
|
\r
|
|
10
|
-
`);if(
|
|
11
|
-
`)?W.slice(0,-2):W,
|
|
12
|
-
`)?
|
|
13
|
-
`),[
|
|
8
|
+
`);if(Z===-1)return["",""];let D=W.slice(0,Z),Y=W.slice(Z+4);return[D,Y]},m1=($)=>{let W={name:""},Z=/name=(?:"(?<temp2>[^"]*)"|(?<temp1>[^;,\s]+))/i.exec($),D=/filename=(?:"(?<temp2>[^"]*)"|(?<temp1>[^;,\s]+))/i.exec($);if(Z)W.name=Z[1]??Z[2]??"";if(D){let Y=D[1]??D[2];if(Y)W.filename=Y}return W},f1=($)=>{let Z=$.split(/\r?\n/).find((D)=>D.toLowerCase().startsWith("content-type:"));if(!Z)return"application/octet-stream";return Z.slice(Z.indexOf(":")+1).trim().split(";")[0]?.trim()??"application/octet-stream"},l1=($)=>{return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/x-"].some((Z)=>$.toLowerCase().startsWith(Z))},p1=($)=>Buffer.isBuffer($)?$.length:Buffer.byteLength($,"utf8"),g1=($,W)=>{if(!W)return;if($.size>W.maxFileSize)throw V.warn("[SECURITY] File upload too large",{filename:$.filename,size:$.size,limit:W.maxFileSize,sizeMB:Math.round($.size/1024/1024)}),new Error(`File too large: ${$.filename} is ${$.size} bytes, exceeds limit of ${W.maxFileSize} bytes`);if($.filename&&$.filename.length>W.maxFilenameLength)throw new 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 V.warn("[SECURITY] Blocked file type upload attempt",{filename:$.filename,extension:Z,blockedExtensions:W.blockedExtensions}),new Error(`File type not allowed: ${Z} files are blocked for security reasons`);if(W.allowedExtensions.length>0&&!W.allowedExtensions.includes(Z))throw new Error(`File type not allowed: ${Z} is not in the allowed extensions list`)}},s1=({contentDisposition:$,contentSection:W,headersSection:Z,config:D})=>{let Y=f1(Z),Q=W.endsWith(`\r
|
|
9
|
+
`)?W.slice(0,-2):W,X=l1(Y)?Buffer.from(Q,"binary"):Q,O={filename:$.filename??"",contentType:Y,size:p1(X),content:X};return g1(O,D),O},p$=($,W,Z)=>{let D={fields:{},files:[]},Y=$.split(`--${W}`).slice(1),Q=0;for(let X of Y){if(!X||X.trim()===""||X.trim()==="--")continue;let[O,H]=h1(X);if(!O)continue;let I=O.split(/\r?\n/).find((L)=>L.toLowerCase().startsWith("content-disposition:"));if(!I)continue;let A=m1(I);if(!A.name)continue;if(A.filename!==void 0){if(Z&&D.files.length>=Z.maxFiles)throw V.warn("[SECURITY] Too many files in upload request",{fileCount:D.files.length,maxFiles:Z.maxFiles}),new Error(`Too many files: maximum of ${Z.maxFiles} files allowed per request`);let L=s1({contentDisposition:A,contentSection:H,headersSection:O,config:Z});if(Q+=L.size,Z&&Q>Z.maxTotalSize)throw V.warn("[SECURITY] Total upload size too large",{totalSize:Q,limit:Z.maxTotalSize,totalSizeMB:Math.round(Q/1024/1024)}),new Error(`Total file size too large: ${Q} bytes exceeds limit of ${Z.maxTotalSize} bytes`);D.files.push(L)}if(A.filename===void 0){let L=H.endsWith(`\r
|
|
10
|
+
`)?H.slice(0,-2):H;D.fields[A.name]=L}}return D};var c1=($,W)=>{if($.length>W.maxFields)throw new Error(`Too many form fields: ${$.length} exceeds limit of ${W.maxFields}`)},r1=($,W,Z)=>{if($.length>Z.maxFieldNameLength)throw new Error(`Form field name too long: ${$.length} characters exceeds limit of ${Z.maxFieldNameLength}`);if(W&&W.length>Z.maxFieldLength)throw new Error(`Form field value too long: field '${$}' has ${W.length} characters, exceeds limit of ${Z.maxFieldLength}`)},d1=($,W,Z)=>{if($.length>Z.maxFieldNameLength)throw new Error(`Decoded form field name too long: ${$.length} characters exceeds limit of ${Z.maxFieldNameLength}`);if(W.length>Z.maxFieldLength)throw new Error(`Decoded form field value too long: field '${$}' has ${W.length} characters, exceeds limit of ${Z.maxFieldLength}`)},i1=($,W,Z)=>{let[D,Y]=$.split("=");if(!D)return;if(Z)r1(D,Y,Z);try{let Q=decodeURIComponent(D),X=Y?decodeURIComponent(Y):"";if(Z)d1(Q,X,Z);W[Q]=X}catch(Q){if(Q instanceof Error&&Q.message.includes("exceeds limit"))throw Q;W[D]=Y??""}},g$=($,W)=>{let Z={},D=$.split("&");if(W)c1(D,W);for(let Y of D)i1(Y,Z,W);return Z};var J$={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]},K$=($,W)=>{if($.length<W.length)return!1;return W.every((Z,D)=>$[D]===Z)},a1=($)=>{if(K$($,J$.WEBP)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WEBP";if(K$($,J$.WAV)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="WAVE";if(K$($,J$.AVI)&&$.length>=12)return $.subarray(8,12).toString("ascii")==="AVI ";return!1},G$=($,W)=>{if(!$)return n1(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"},n1=($)=>{if(Buffer.isBuffer($))return t1($)?"base64":"utf8";if(typeof $==="object"&&$!==null)return"utf8";if(typeof $==="string")return"utf8";return"utf8"},t1=($)=>{if($.length===0)return!1;let W=Object.values(J$);for(let Y of W)if(K$($,Y))return!0;if(a1($))return!0;let Z=$.filter((Y)=>Y===0).length,D=$.filter((Y)=>Y<32&&Y!==9&&Y!==10&&Y!==13).length;return Z/$.length>0.1||D/$.length>0.3};var o1=($)=>{if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return!1;try{return JSON.parse($),!0}catch{return!1}},e1=($)=>$.includes("=")&&$.includes("&"),$0=($)=>$.includes("boundary="),W0=($)=>typeof $==="object"&&$!==null&&!Buffer.isBuffer($)&&!($ instanceof Uint8Array)&&!($ instanceof ArrayBuffer)&&!($ instanceof Date),Z0=($)=>$ instanceof Date,D0=($)=>{if(Buffer.isBuffer($))return $;return Buffer.from($)},Y0=($)=>{return G$(void 0,$)==="base64"?"application/octet-stream":"text/plain"},E$=($)=>{let W=$.trim();if(o1(W))return v.json;if(e1(W))return v.form;if($0(W))return v.multipart;return"text/plain"},s$=($)=>{if($===null||$===void 0)return"text/plain";if(Z0($))return"text/plain";if(W0($))return v.json;if(typeof $==="string")return E$($);if(Buffer.isBuffer($)||$ instanceof Uint8Array||$ instanceof ArrayBuffer){let W=D0($);return Y0(W)}return"text/plain"};var Q0=($,W,Z)=>{let D=Buffer.byteLength($,"utf8");if(W===v.json){if(D>Z.json.maxSize)throw new Error(`JSON body too large: ${D} bytes exceeds limit of ${Z.json.maxSize} bytes`)}else if(W===v.form){if(D>Z.urlEncoded.maxSize)throw new Error(`URL-encoded body too large: ${D} bytes exceeds limit of ${Z.urlEncoded.maxSize} bytes`)}else if(W===v.multipart){if(D>Z.fileUploads.maxTotalSize)throw new Error(`Multipart body too large: ${D} bytes exceeds limit of ${Z.fileUploads.maxTotalSize} bytes`)}},c$=($,W={})=>{let{headerContentType:Z,boundary:D,config:Y}=W;if(!$||!$.trim())return;let Q=Z??E$($);if(Y)Q0($,Q,Y);if(Q===v.json){if(!Y)throw new Error("Body parser configuration is required for JSON parsing");return l$($,Y.json)}if(Q===v.multipart){if(!D)throw new Error("Invalid multipart form data: missing boundary");return p$($,D,Y?.fileUploads)}if(Q===v.form)return g$($,Y?.urlEncoded);return $};var A$=($,W)=>{let Z=$.indexOf(W);if(Z===-1)return[$,""];let D=$.slice(0,Z),Y=$.slice(Z+W.length);return[D,Y]};var r$=($)=>{if(!$||!$.trim())return{method:"GET",path:"/",protocol:"HTTP/1.1",headersRaw:"",rawBody:""};let[W,Z]=A$($,`\r
|
|
11
|
+
`),[D,Y,Q]=W.split(" ",3),[X,O]=A$(Z,`\r
|
|
14
12
|
\r
|
|
15
|
-
`);if(!
|
|
13
|
+
`);if(!D||!Object.values(E).includes(D))return{method:"GET",path:Y??"/",protocol:Q??"HTTP/1.1",headersRaw:X,rawBody:O};return{method:D,path:Y??"/",protocol:Q??"HTTP/1.1",headersRaw:X,rawBody:O}};var d$=($)=>{if(!$)return{};if(!$.includes("?"))return{};let[,W]=$.split("?");if(!W)return{};let Z={},D=W.split("&");for(let Y of D){let[Q,X]=Y.split("=");if(Q)try{let O=decodeURIComponent(Q),H=X?decodeURIComponent(X):"";Z[O]=H}catch{Z[Q]=X??""}}return Z};var X0=[/^(?<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],i$=($)=>{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 Y=W.split(".");return Y.length===4&&Y.every((Q)=>{let X=parseInt(Q,10);return X>=0&&X<=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)},a$=($)=>{if(!$)return!1;let W=$.replace(/^\[|\]$/g,"");return X0.some((Z)=>Z.test(W))},n$=($,W)=>{if(!$||!W.length)return!1;if(W.includes("*"))return!0;return W.includes($)},J0=($,W)=>{if(!W.detectSpoofing||$.length<=1)return!1;if($.length>W.maxChainLength)return!0;if(new Set($).size!==$.length)return!0;let D=$.filter(i$).length;if(D>0&&D<$.length)return!0;return!1},K0=($,W)=>{if($.length<=1)return!0;let Z=$[$.length-1];return Boolean(Z&&n$(Z,W.trustedProxies))},G0=($,W)=>{if(W==="x-forwarded-for")return $[0];return $[$.length-1]},O0=($)=>{let{clientIp:W,headerName:Z,ipChain:D,config:Y}=$,Q=a$(W),X=Z==="x-forwarded-for"?n$(D[D.length-1]??"",Y.trustedProxies):!0;return{ip:W,isValid:!0,isPrivate:Q,source:Z,trusted:X}},M0=()=>({ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}),U0=($,W)=>{for(let Z of W.headerPreference){let D=$[Z];if(!D)continue;let Y=D.split(",").map((O)=>O.trim()).filter(Boolean);if(Y.length===0)continue;if(J0(Y,W))continue;if(Z==="x-forwarded-for"&&!K0(Y,W))continue;let Q=G0(Y,Z);if(!Q||!i$(Q))continue;if(a$(Q)&&!W.allowPrivateIps)continue;return O0({clientIp:Q,headerName:Z,ipChain:Y,config:W})}return M0()},j0=($,W,Z={})=>{let Y={...$._configuration.ipSecurity,...Z},Q=U0(W,Y);if(Q.isValid)return Q;return{ip:"",isValid:!1,isPrivate:!1,source:"socket",trusted:!1}},t$=($,W)=>{return j0($,W).ip};var o$=($)=>{if(!$)return;return/boundary\s*=\s*(?<temp1>[^;,\s]*)/i.exec($)?.[1]};var e$=($)=>{if(!$)return{};F0($);let W=_0($),Z=V0(W);return H0(Z)},F0=($)=>{if($.split(/\r\n|\r|\n/).length>100)throw new Error("Too many headers: maximum 100 allowed")},_0=($)=>{let W={},D=$.replace(/\r\n|\r|\n/g,`
|
|
16
14
|
`).split(`
|
|
17
|
-
`);for(let Y of
|
|
18
|
-
`))throw new Error(`Header value contains invalid line break characters: ${$}`);let
|
|
15
|
+
`);for(let Y of D){if(!Y.trim())continue;let Q=Y.indexOf(":");if(Q===-1)continue;let X=Y.slice(0,Q).trim(),O=Y.slice(Q+1).trim();if(!X)continue;if(!q0(X))throw new Error(`Invalid header name: ${X}`);if(X.length>200)throw new Error("Header name too long: maximum 200 characters allowed");if(O.length>8192)throw new Error("Header value too long: maximum 8192 characters allowed");W[X.toLowerCase()]=O}return W},V0=($)=>{let W={};for(let[Z,D]of Object.entries($))W[Z]=w0(D);return W},H0=($)=>$,q0=($)=>{return/^[a-zA-Z0-9!#$%&'*+\-.^_`|~]+$/.test($)},w0=($)=>{return $.replace(/[\x00-\x08\x0A-\x1F\x7F]/g,"")};class z${_rawRequest;_setup;method;path;protocol;headers;body;query;params;ipAddress;rawBody;constructor($,W,Z){this._rawRequest=$,this._setup=W,this.ipAddress=Z??"";let{method:D,path:Y,protocol:Q,headers:X,body:O,query:H,params:_,rawBody:I}=this._parseRequestIntoObject();this.method=D,this.path=Y,this.protocol=Q,this.headers=X,this.body=O,this.query=H??{},this.params=_??{},this.rawBody=I;let A=t$(this._setup,X);if(A)this.ipAddress=A}_parseRequestIntoObject(){let $=this._rawRequest.toString(),{method:W,path:Z,protocol:D,headersRaw:Y,rawBody:Q}=r$($),X=this._setup._routeRegistry._findRoute(W,Z),O=e$(Y),H=O["content-type"],_=H?.split(";")[0]?.trim().toLowerCase(),I=o$(H);return{method:W,path:Z,protocol:D,headers:O,body:c$(Q,{headerContentType:_,boundary:I,config:this._setup._configuration.bodyParser}),query:d$(Z),params:X?.params??{},rawBody:Q}}}var Y1=F$(Y$(),1);var $1=($,W)=>{let Z=W?.encoding??"utf8";if($===null||$===void 0)return"";if(Buffer.isBuffer($))return S$($,Z);if($ instanceof Uint8Array)return N0($,Z);if($ instanceof ArrayBuffer)return B0($,Z);if(typeof $==="string")return $;if(typeof $==="object")return E0($);return String($)},S$=($,W)=>{if(W==="base64")return $.toString("base64");if(W==="binary")return $.toString("binary");return $.toString("utf8")},N0=($,W)=>{let Z=Buffer.from($);return S$(Z,W)},B0=($,W)=>{let Z=Buffer.from($);return S$(Z,W)},E0=($)=>{try{return JSON.stringify($)}catch(W){return String($)}};var W1=new Map;for(let[$,W]of Object.entries(b)){let D=Q$[$];W1.set(W,D)}var Z1=($)=>{let W=W1.get($);if(!W)throw new Error(`Unknown status code: ${$}`);return W};var A0=($,W)=>{if(typeof W!=="string")throw new Error(`Header value must be a string, got ${typeof W}`);if(W.includes("\r")||W.includes(`
|
|
16
|
+
`))throw new 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 D of Z)if(D.test(W))throw new Error(`Header value contains suspicious injection pattern: ${$}`)},z0=($)=>{for(let[W,Z]of Object.entries($))A0(W,Z)},k$=($)=>{let W={};for(let[Z,D]of Object.entries($))if(D!==void 0)W[Z]=D;return z0(W),W};var D1=($,W)=>{if(!$)return"0";let Z=0;if(W===r.base64)Z=Buffer.byteLength($,"utf8");if(W===r.binary)Z=$.length;if(W===r.utf8)Z=Buffer.byteLength($,"utf8");return String(Z)};class I${_request;_statusCode=b.ok;_status=Q$.ok;_headers={};_body="";_stringBody="";_encoding=r.utf8;constructor($){this._request=$,this._setSecurityHeaders()}_parseResponseIntoString(){let $=`${this._request.protocol} ${this._statusCode} ${this._status}`,W=Object.entries(this._headers).map(([Q,X])=>`${Q}: ${X}`),Z=G$(this._headers["content-type"],this._body),D=$1(this._body,{encoding:Z});this._encoding=Z,this._stringBody=`${$}
|
|
19
17
|
${W.join(`
|
|
20
18
|
`)}
|
|
21
19
|
|
|
22
|
-
${Z}`}_setHeadersIfNotSet($){let W={};for(let[Z,Y]of Object.entries($))if(Y!==void 0&&!(Z in this._headers))W[Z]=Y;let D=H$(W);Object.assign(this._headers,D)}_setBody($){if(this._body=$,!this._headers["content-type"]){let W=y$($);this._setHeadersIfNotSet({"Content-Type":W})}}setStatusCode($){this._statusCode=$,this._status=n$($)}addHeaders($){let W=H$($);this._headers={...this._headers,...W}}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 k${_request;_response;request;response;constructor($,W,D){this._request=new _$($,W,D),this._response=new q$(this._request),this.request=this._request,this.response=this._response}}var z={off:"off",verbose:"verbose",network:"network"};var W0={enabled:!0,origin:"*",methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:"*",exposedHeaders:[],credentials:!1,maxAge:86400,preflightContinue:!1,optionsSuccessStatus:b.noContent},Q$={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}},a$={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},D0={port:5000,host:"0.0.0.0",logLevel:z.off,cors:{enabled:!1},bodyParser:Q$,ipSecurity:a$,connectionOptions:{socketTimeout:30000,gracefulShutdownTimeout:30000,keepAliveTimeout:65000,headersTimeout:66000}},Z0=($)=>{if($.maxSize<1)throw new Error("bodyParser.json.maxSize must be at least 1 byte");if($.maxDepth<1)throw new Error("bodyParser.json.maxDepth must be at least 1");if($.maxKeys<1)throw new Error("bodyParser.json.maxKeys must be at least 1");if($.maxStringLength<1)throw new Error("bodyParser.json.maxStringLength must be at least 1 byte");if($.maxArrayLength<1)throw new Error("bodyParser.json.maxArrayLength must be at least 1")},Y0=($)=>{if($.maxFileSize<1)throw new Error("bodyParser.fileUploads.maxFileSize must be at least 1 byte");if($.maxTotalSize<1)throw new Error("bodyParser.fileUploads.maxTotalSize must be at least 1 byte");if($.maxFiles<1)throw new Error("bodyParser.fileUploads.maxFiles must be at least 1");if($.maxFilenameLength<1)throw new Error("bodyParser.fileUploads.maxFilenameLength must be at least 1 character")},Q0=($)=>{if($.maxSize<1)throw new Error("bodyParser.urlEncoded.maxSize must be at least 1 byte");if($.maxFields<1)throw new Error("bodyParser.urlEncoded.maxFields must be at least 1");if($.maxFieldNameLength<1)throw new Error("bodyParser.urlEncoded.maxFieldNameLength must be at least 1 character");if($.maxFieldLength<1)throw new Error("bodyParser.urlEncoded.maxFieldLength must be at least 1 byte")},X0=($)=>{if(!Array.isArray($.trustedProxies))throw new Error("ipSecurity.trustedProxies must be an array");if(!Array.isArray($.headerPreference))throw new Error("ipSecurity.headerPreference must be an array");if($.headerPreference.length===0)throw new Error("ipSecurity.headerPreference must contain at least one header");if($.maxChainLength<1)throw new Error("ipSecurity.maxChainLength must be at least 1");if($.maxChainLength>50)throw new Error("ipSecurity.maxChainLength must not exceed 50 to prevent DoS attacks")},J0=($)=>{if($.allowPrototypeProperties)console.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)console.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)console.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.`)},w0=($)=>{if($.maxFileSize>104857600)console.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)console.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"],D=$.allowedExtensions.filter((Z)=>W.includes(Z.toLowerCase()));if(D.length>0)console.warn(`[SECURITY WARNING] bodyParser.fileUploads.allowedExtensions includes dangerous file types: ${D.join(", ")}. This could allow execution of malicious files. Only allow these if absolutely necessary.`);if($.blockedExtensions.length===0&&$.allowedExtensions.length===0)console.warn("[SECURITY WARNING] File uploads have no extension restrictions (no blockedExtensions and no allowedExtensions). Consider adding blockedExtensions or allowedExtensions to improve security.")},K0=($)=>{if($.trustedProxies.length===0)console.warn("[SECURITY WARNING] ipSecurity.trustedProxies is empty. No proxy headers will be trusted, which may prevent proper client IP detection.");if($.maxChainLength>20)console.warn(`[SECURITY WARNING] ipSecurity.maxChainLength is set to ${$.maxChainLength}. Very long proxy chains can consume significant resources and may indicate amplification attacks.`);if(!$.detectSpoofing)console.warn("[SECURITY WARNING] ipSecurity.detectSpoofing is disabled. This reduces protection against IP spoofing attacks. Only disable if you have other protective measures.")},G0=($,W)=>{if(W?.cors?.enabled)$.cors={...W0,...W.cors,enabled:!0}},O0=($,W)=>{if(W?.bodyParser)$.bodyParser={json:{...Q$.json,...W.bodyParser.json},fileUploads:{...Q$.fileUploads,...W.bodyParser.fileUploads},urlEncoded:{...Q$.urlEncoded,...W.bodyParser.urlEncoded}},j0($.bodyParser)},M0=($,W)=>{if(W?.ipSecurity)$.ipSecurity={...a$,...W.ipSecurity},X0($.ipSecurity),K0($.ipSecurity)},U0=($,W)=>{if(W?.port!==void 0){let D=Number(W.port);if(isNaN(D)||D<1||D>65535)throw new Error("Invalid port number");$.port=D}},j0=($)=>{Z0($.json),Y0($.fileUploads),Q0($.urlEncoded),J0($.json),w0($.fileUploads)},t$=($)=>{let W={...D0};return Object.assign(W,$),G0(W,$),O0(W,$),M0(W,$),U0(W,$),W};class N${_beforeAll;_afterAll;_onError;_onNotFound;constructor(){this._beforeAll=new Set,this._afterAll=new Set,this._onError=($)=>{return $.response.setStatusCode(b.internalServerError),{success:!1,message:"Internal Server Error"}},this._onNotFound=($)=>{return $.response.setStatusCode(b.notFound),{success:!1,message:"404 Not Found"}}}_addBeforeHooks($,W){for(let D of $)this._beforeAll.add({handler:D,options:W??{routesToExclude:[],routesToInclude:[]}})}_addAfterHooks($,W){for(let D of $)this._afterAll.add({handler:D,options:W??{routesToExclude:[],routesToInclude:[]}})}_addOnError($){this._onError=$}_addOnNotFound($){this._onNotFound=$}}var o$=($)=>{let W=[],D=$.path.replace(/:\w+/g,(Z)=>{let Y=Z.slice(1);return W.push(Y),"([^/]+)"}).replace(/\//g,"\\/");return{...$,pattern:new RegExp(`^${D}$`),paramNames:W,isParameterized:!0}};var B$=($)=>{let[W]=$.split("?");if(!W)return"";if([W]=W.split("#"),!W)return"";try{W=decodeURIComponent(W)}catch(D){console.warn("Failed to decode URL path:",W)}if(W=W.startsWith("/")?W:`/${W}`,W=W.replace(/\/\/+/g,"/"),W=F0(W),W.length>1&&W.endsWith("/"))W=W.slice(0,-1);return W},F0=($)=>{let W=$.split("/"),D=[];for(let Y of W){if(Y==="."||Y===""){if(Y===""&&D.length===0)D.push(Y);continue}if(Y===".."){if(D.length>1)D.pop()}else D.push(Y)}return D.join("/")||"/"},E$=($)=>$.replace(/:\w+/g,":param");var e$=($)=>{let W=$.match(/:\w+/g);if(!W)return;let D=W.map((Y)=>Y.slice(1)),Z=new Set(D);if(D.length!==Z.size){let Y=D.filter((Q,J)=>D.indexOf(Q)!==J);throw new Error(`Route ${$} has duplicate parameter names: ${Y.join(", ")}. Parameter names must be unique within a route for clarity and to prevent conflicts.`)}};class L${_exactRoutes=new Map;_parameterizedRoutes=new Map;_register({method:$,path:W,handler:D,options:Z}){let Y=B$(W),Q=Y.includes(":");if(Q)e$(Y);if(this._hasExactRoutePattern($,Y))throw new Error(`Route ${Y} already exists for method ${$}`);let J={method:$,path:Y,handler:D,options:Z,params:{}};if(Q)this._storeParameterizedRoute($,J);else this._storeExactRoute($,Y,J)}_findRoute($,W){let D=B$(W),Z=this._exactRoutes.get($)?.get(D);if(Z)return Z;return this._findParameterizedRoute($,D)}_hasExactRoutePattern($,W){if(this._exactRoutes.get($)?.has(W))return!0;if(W.includes(":")){let D=E$(W),Z=this._parameterizedRoutes.get($);if(Z)return Z.some((Y)=>E$(Y.path)===D)}else{let D=this._parameterizedRoutes.get($);if(D)return D.some((Z)=>Z.path===W)}return!1}_storeExactRoute($,W,D){if(!this._exactRoutes.has($))this._exactRoutes.set($,new Map);this._exactRoutes.get($)?.set(W,D)}_storeParameterizedRoute($,W){if(!this._parameterizedRoutes.has($))this._parameterizedRoutes.set($,[]);let D=o$(W);this._parameterizedRoutes.get($)?.push(D)}_findParameterizedRoute($,W){let D=this._parameterizedRoutes.get($);if(!D)return;for(let Z of D){let Y=W.match(Z.pattern);if(Y){let Q={};for(let J=0;J<Z.paramNames.length;J++){let O=Y[J+1],F=Z.paramNames[J];if(O!==void 0&&F!==void 0)Q[F]=O}return{...Z,params:Q}}}return}}class A${_configuration;_routeRegistry=new L$;_hooks=new N$;constructor($){this._configuration=t$($)}get($,W,D){let Z=D??{beforeHooks:[],afterHooks:[]};this._routeRegistry._register({method:E.get,handler:W,path:$,options:Z,params:{}}),this._routeRegistry._register({method:E.head,handler:W,path:$,options:Z,params:{}})}head($,W,D){this._routeRegistry._register({method:E.head,handler:W,path:$,options:D??{beforeHooks:[],afterHooks:[]},params:{}})}post($,W,D){this._routeRegistry._register({method:E.post,handler:W,path:$,options:D??{beforeHooks:[],afterHooks:[]},params:{}})}put($,W,D){this._routeRegistry._register({method:E.put,handler:W,path:$,options:D??{beforeHooks:[],afterHooks:[]},params:{}})}patch($,W,D){this._routeRegistry._register({method:E.patch,handler:W,path:$,options:D??{beforeHooks:[],afterHooks:[]},params:{}})}delete($,W,D){this._routeRegistry._register({method:E.delete,handler:W,path:$,options:D??{beforeHooks:[],afterHooks:[]},params:{}})}options($,W,D){this._routeRegistry._register({method:E.options,handler:W,path:$,options:D??{beforeHooks:[],afterHooks:[]},params:{}})}group($,W,D){let Z=(Q)=>(J,O,F)=>{let k=`${$}${J}`,V={beforeHooks:[...D?.beforeHooks??[],...F?.beforeHooks??[]],afterHooks:[...F?.afterHooks??[],...D?.afterHooks??[]]};if(this._routeRegistry._register({method:Q,handler:O,path:k,options:V,params:{}}),Q===E.get)this._routeRegistry._register({method:E.head,handler:O,path:k,options:V,params:{}})},Y={get:Z(E.get),head:Z(E.head),post:Z(E.post),put:Z(E.put),delete:Z(E.delete),patch:Z(E.patch),options:Z(E.options)};W(Y)}beforeAll($,W){this._hooks._addBeforeHooks($,W)}afterAll($,W){this._hooks._addAfterHooks($,W)}onError($){this._hooks._addOnError($)}onNotFound($){this._hooks._addOnNotFound($)}}var S$=T$(O$(),1),v="YINZER",s={info:1,warn:2,error:3},q={reset:"\x1B[0m",cyan:"\x1B[96m",orange:"\x1B[38;5;208m",red:"\x1B[91m",green:"\x1B[92m",yellow:"\x1B[93m",gray:"\x1B[90m"},_0={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"]},$1=s.info,C=()=>S$.default().format("YYYY-MM-DD HH:mm:ss.SSS"),V0=()=>S$.default().format("DD/MMM/YYYY:HH:mm:ss ZZ"),l=($)=>{let W=_0[$];return W[Math.floor(Math.random()*W.length)]??""},a=($)=>$>=$1,H0=($,W)=>{if(!a(s.info))return;let D=C(),Z=l("positive"),Y=W?` ${JSON.stringify(W,null,0)}`:"";console.info(`${q.cyan}[${v}] ✅ [${D}] [INFO] ${$}${Y} - ${Z}${q.reset}`)},q0=($,W)=>{if(!a(s.warn))return;let D=C(),Z=l("neutral"),Y=W?` ${JSON.stringify(W,null,0)}`:"";console.warn(`${q.yellow}[${v}] ⚠️ [${D}] [WARN] ${$}${Y} - ${Z}${q.reset}`)},k0=($,W)=>{if(!a(s.error))return;let D=C(),Z=l("negative"),Y=W?` ${JSON.stringify(W,null,0)}`:"";console.error(`${q.red}[${v}] ❌ [${D}] [ERROR] ${$}${Y} - ${Z}${q.reset}`)},N0=($,W)=>{if(!a(s.info))return;let D=C(),Z=l("positive"),Y=W?` ${JSON.stringify(W,null,0)}`:"";console.log(`${q.green}[${v}] \uD83C\uDF89 [${D}] [SUCCESS] ${$}${Y} - ${Z}${q.reset}`)},B0=($,W,D)=>{if(!a(s.info))return;let Z=C(),Y="❓",Q="";if(W<50)Y="⚡",Q=Math.random()<0.5?"lightning quick n'at!":"faster than a Stillers touchdown!";else if(W<100)Y="\uD83D\uDD25",Q=Math.random()<0.5?"that's the way!":"smooth as butter n'at!";else if(W<200)Y="✅",Q=Math.random()<0.5?"not bad yinz!":"keepin' up just fine!";else if(W<500)Y="⚠️",Q=Math.random()<0.5?"eh, could be better":"slowin' down a bit there";else if(W<1000)Y="\uD83D\uDC0C",Q=Math.random()<0.5?"that's draggin' n'at":"c'mon, pick up the pace!";else Y="\uD83D\uDCA5",Q=Math.random()<0.5?"what a jagoff response time!":"slower than traffic on the Parkway!";let J=D?{...D,executionTime:`${W}ms`}:{executionTime:`${W}ms`},O=` ${JSON.stringify(J,null,0)}`;console.log(`${q.orange}[${v}] ${Y} [${Z}] [PERF] ${$}${O} - ${Q}${q.reset}`)},E0=($)=>{if(typeof $==="string")return Buffer.byteLength($,"utf8");if(Buffer.isBuffer($))return $.length;if(typeof $==="object"&&$!==null)try{return Buffer.byteLength(JSON.stringify($),"utf8")}catch{return 0}return 0},L0=($)=>{if($>=200&&$<300)return"✅";if($>=300&&$<400)return"\uD83D\uDD04";if($>=400&&$<500)return"❌";if($>=500)return"\uD83D\uDCA5";return"❓"},A0=($)=>{if($<50)return{emoji:"⚡",phrase:Math.random()<0.5?"lightning quick n'at!":"faster than a Stillers touchdown!"};if($<100)return{emoji:"\uD83D\uDD25",phrase:Math.random()<0.5?"that's the way!":"smooth as butter n'at!"};if($<200)return{emoji:"✅",phrase:Math.random()<0.5?"not bad yinz!":"keepin' up just fine!"};if($<500)return{emoji:"⚠️",phrase:Math.random()<0.5?"eh, could be better":"slowin' down a bit there"};if($<1000)return{emoji:"\uD83D\uDC0C",phrase:Math.random()<0.5?"that's draggin' n'at":"c'mon, pick up the pace!"};return{emoji:"\uD83D\uDCA5",phrase:Math.random()<0.5?"what a jagoff response time!":"slower than traffic on the Parkway!"}},S0=($)=>{let W=C(),D=V0(),{clientIp:Z,method:Y,path:Q,protocol:J,statusCode:O,responseSize:F,referer:k,userAgent:V,responseTimeMs:N,statusEmoji:S}=$,p=`\uD83C\uDFE0 ${Z} - - [${D}] "${Y} ${Q} ${J}" ${O} ${F}b ${k} ${V} ${N}ms ${S}`;console.log(`${q.gray}[${v}] [${W}] [NETWORK] ${p}${q.reset}`)},z0=($)=>{let W=C(),D=parseFloat($),{emoji:Z,phrase:Y}=A0(D);console.log(`${q.orange}[${v}] ${Z} [${W}] [PERF] Response time: ${$}ms - ${Y}${q.reset}`)},I0=($,W,D)=>{let{request:Z}=$,Y=$._response,Q=(D-W).toFixed(1),J=Z.ipAddress||"unknown",{method:O,path:F,protocol:k}=Z,V=Y._statusCode,N=E0(Y._body),S=Z.headers.referer?`"${Z.headers.referer}"`:'"-"',p=Z.headers["user-agent"]?`"${Z.headers["user-agent"]}"`:'"-"',X$=L0(V);S0({clientIp:J,method:O,path:F,protocol:k,statusCode:V,responseSize:N,referer:S,userAgent:p,responseTimeMs:Q,statusEmoji:X$}),z0(Q)},R0=($,W,D)=>{let Z=C(),Y=W??"unknown",Q=D?` - ${D}`:"";if($==="connect")console.log(`${q.gray}[${v}] \uD83E\uDD1D [${Z}] [NETWORK] New visitor from ${Y} - Welcome to the 'Burgh!${q.reset}`);else if($==="disconnect")console.log(`${q.gray}[${v}] \uD83D\uDC4B [${Z}] [NETWORK] ${Y} headed out - Thanks for stopping by, yinz come back now!${q.reset}`);else console.log(`${q.red}[${v}] \uD83D\uDCA5 [${Z}] [NETWORK] Connection trouble with ${Y}${Q} - That's not good, n'at!${q.reset}`)},T0=($,W)=>{let D=C(),Z=$&&W?`${W}:${$}`:"unknown",Y=l("positive");console.log(`${q.gray}[${v}] \uD83D\uDE80 [${D}] [NETWORK] YinzerFlow server is up and running at ${Z} - Ready to serve yinz all, ${Y}!${q.reset}`)},v0=($,W)=>{let D=C(),Z=$&&W?`${W}:${$}`:"unknown",Y=l("neutral");console.log(`${q.gray}[${v}] \uD83D\uDED1 [${D}] [NETWORK] YinzerFlow server at ${Z} is shutting down - See yinz later, ${Y}!${q.reset}`)},P0=($,W,D)=>{let Z=C(),Y=$&&W?`${W}:${$}`:"unknown",Q=D?` - ${D}`:"",J=l("negative");console.log(`${q.red}[${v}] \uD83D\uDCA5 [${Z}] [NETWORK] Server error at ${Y}${Q} - Something's not right, ${J}!${q.reset}`)},x0=($)=>{$1=$},T={setLogLevel:x0,info:H0,warn:q0,error:k0,success:N0,perf:B0,network:{request:I0,connection:R0,serverStart:T0,serverStop:v0,serverError:P0}};class b0 extends A${_isListening=!1;_server;constructor($){super($);if(this._configuration.logLevel===z.verbose||this._configuration.logLevel===z.network)T.setLogLevel(1),T.success("YinzerFlow initialized with logging enabled",{level:this._configuration.logLevel});if(this._configuration.logLevel===z.off)T.setLogLevel(2)}_setupServer($,W,D){if(!this._server)return;this._server.on("error",(Z)=>{if(this._configuration.logLevel!==z.off)T.network.serverError(this._configuration.port,this._configuration.host,Z.message);console.error("An error occurred with yinzer flow. Please open an issue on github.",Z),W(Z)}),this._server.on("listening",()=>{if(this._isListening=!0,this._configuration.logLevel!==z.off)T.network.serverStart(this._configuration.port,this._configuration.host);$()}),this._server.on("connection",(Z)=>{this._handleConnection(Z,D)})}async _processRequest({data:$,socket:W,requestHandler:D,clientAddress:Z}){let Y=Date.now();if(this._configuration.logLevel===z.verbose)T.info("Processing incoming request",{clientAddress:Z,dataSize:$.length});let Q=new k$($,this,Z);await D.handle(Q),W.write(Q._response._stringBody),W.end();let J=Date.now(),O=J-Y;if(this._configuration.logLevel===z.network||this._configuration.logLevel===z.verbose)T.network.request(Q,Y,J);if(this._configuration.logLevel===z.off&&O>500)T.warn("Slow request detected",{method:Q.request.method,path:Q.request.path,statusCode:Q._response._statusCode,responseTime:`${O}ms`,clientAddress:Z})}_handleConnection($,W){let D=$.remoteAddress??"unknown";if(this._configuration.logLevel!==z.off)T.network.connection("connect",D);$.on("data",(Z)=>{this._processRequest({data:Z,socket:$,requestHandler:W,clientAddress:D}).catch((Y)=>{let Q=Y instanceof Error?Y.message:"Unknown error";if(this._configuration.logLevel!==z.off)T.network.connection("error",D,`Unexpected error: ${Q}`);console.error("Unexpected error in request processing:",Y),$.destroy()})}),$.on("error",(Z)=>{if(this._configuration.logLevel!==z.off)T.network.connection("error",D,Z.message);console.error("Socket error:",Z)}),$.on("close",()=>{if(this._configuration.logLevel!==z.off)T.network.connection("disconnect",D)})}async listen(){if(this._isListening)throw new Error("Server is already listening");return new Promise(($,W)=>{let D=new M$(this);this._server=C0(),this._setupServer($,W,D),this._server.listen(this._configuration.port,this._configuration.host)})}async close(){if(!this._isListening||!this._server)return;return new Promise(($)=>{if(!this._server){this._isListening=!1,$();return}this._server.close(()=>{if(this._isListening=!1,this._configuration.logLevel!==z.off)T.network.serverStop(this._configuration.port,this._configuration.host);$()})})}status(){return{isListening:this._isListening,port:this._configuration.port,host:this._configuration.host}}}export{b0 as YinzerFlow};
|
|
20
|
+
${D}`;let Y=D1(this._stringBody,this._encoding);this._setHeadersIfNotSet({Date:Y1.default().format("ddd, DD MMM YYYY HH:mm:ss [GMT]"),"Content-Length":Y})}_setHeadersIfNotSet($){let W={};for(let[D,Y]of Object.entries($))if(Y!==void 0&&!(D in this._headers))W[D]=Y;let Z=k$(W);Object.assign(this._headers,Z)}_setBody($){if(this._body=$,!this._headers["content-type"]){let W=s$($);this._setHeadersIfNotSet({"Content-Type":W})}}setStatusCode($){this._statusCode=$,this._status=Z1($)}addHeaders($){let W=k$($);this._headers={...this._headers,...W}}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 L${_request;_response;request;response;constructor($,W,Z){this._request=new z$($,W,Z),this._response=new I$(this._request),this.request=this._request,this.response=this._response}}var Q1={off:"off",error:"error",warn:"warn",info:"info"};var S0={enabled:!0,origin:"*",methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:"*",exposedHeaders:[],credentials:!1,maxAge:86400,preflightContinue:!1,optionsSuccessStatus:b.noContent},O$={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}},X1={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},k0={port:5000,host:"0.0.0.0",logLevel:Q1.warn,networkLogs:!1,cors:{enabled:!1},bodyParser:O$,ipSecurity:X1,connectionOptions:{socketTimeout:30000,gracefulShutdownTimeout:30000,keepAliveTimeout:65000,headersTimeout:66000}},I0=($)=>{if($.maxSize<1)throw new Error("bodyParser.json.maxSize must be at least 1 byte");if($.maxDepth<1)throw new Error("bodyParser.json.maxDepth must be at least 1");if($.maxKeys<1)throw new Error("bodyParser.json.maxKeys must be at least 1");if($.maxStringLength<1)throw new Error("bodyParser.json.maxStringLength must be at least 1 byte");if($.maxArrayLength<1)throw new Error("bodyParser.json.maxArrayLength must be at least 1")},L0=($)=>{if($.maxFileSize<1)throw new Error("bodyParser.fileUploads.maxFileSize must be at least 1 byte");if($.maxTotalSize<1)throw new Error("bodyParser.fileUploads.maxTotalSize must be at least 1 byte");if($.maxFiles<1)throw new Error("bodyParser.fileUploads.maxFiles must be at least 1");if($.maxFilenameLength<1)throw new Error("bodyParser.fileUploads.maxFilenameLength must be at least 1 character")},R0=($)=>{if($.maxSize<1)throw new Error("bodyParser.urlEncoded.maxSize must be at least 1 byte");if($.maxFields<1)throw new Error("bodyParser.urlEncoded.maxFields must be at least 1");if($.maxFieldNameLength<1)throw new Error("bodyParser.urlEncoded.maxFieldNameLength must be at least 1 character");if($.maxFieldLength<1)throw new Error("bodyParser.urlEncoded.maxFieldLength must be at least 1 byte")},T0=($)=>{if(!Array.isArray($.trustedProxies))throw new Error("ipSecurity.trustedProxies must be an array");if(!Array.isArray($.headerPreference))throw new Error("ipSecurity.headerPreference must be an array");if($.headerPreference.length===0)throw new Error("ipSecurity.headerPreference must contain at least one header");if($.maxChainLength<1)throw new Error("ipSecurity.maxChainLength must be at least 1");if($.maxChainLength>50)throw new Error("ipSecurity.maxChainLength must not exceed 50 to prevent DoS attacks")},v0=($)=>{if($.allowPrototypeProperties)V.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)V.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)V.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.`)},P0=($)=>{if($.maxFileSize>104857600)V.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)V.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((D)=>W.includes(D.toLowerCase()));if(Z.length>0)V.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)V.warn("[SECURITY WARNING] File uploads have no extension restrictions (no blockedExtensions and no allowedExtensions). Consider adding blockedExtensions or allowedExtensions to improve security.")},x0=($)=>{if($.trustedProxies.length===0)V.warn("[SECURITY WARNING] ipSecurity.trustedProxies is empty. No proxy headers will be trusted, which may prevent proper client IP detection.");if($.maxChainLength>20)V.warn(`[SECURITY WARNING] ipSecurity.maxChainLength is set to ${$.maxChainLength}. Very long proxy chains can consume significant resources and may indicate amplification attacks.`);if(!$.detectSpoofing)V.warn("[SECURITY WARNING] ipSecurity.detectSpoofing is disabled. This reduces protection against IP spoofing attacks. Only disable if you have other protective measures.")},C0=($,W)=>{if(W?.cors?.enabled)$.cors={...S0,...W.cors,enabled:!0}},b0=($,W)=>{if(W?.bodyParser)$.bodyParser={json:{...O$.json,...W.bodyParser.json},fileUploads:{...O$.fileUploads,...W.bodyParser.fileUploads},urlEncoded:{...O$.urlEncoded,...W.bodyParser.urlEncoded}},h0($.bodyParser)},u0=($,W)=>{if(W?.ipSecurity)$.ipSecurity={...X1,...W.ipSecurity},T0($.ipSecurity),x0($.ipSecurity)},y0=($,W)=>{if(W?.port!==void 0){let Z=Number(W.port);if(isNaN(Z)||Z<1||Z>65535)throw new Error("Invalid port number");$.port=Z}},h0=($)=>{I0($.json),L0($.fileUploads),R0($.urlEncoded),v0($.json),P0($.fileUploads)},J1=($)=>{let W={...k0};return Object.assign(W,$),C0(W,$),b0(W,$),u0(W,$),y0(W,$),W};class R${_beforeAll;_afterAll;_onError;_onNotFound;constructor(){this._beforeAll=new Set,this._afterAll=new Set,this._onError=($)=>{return $.response.setStatusCode(b.internalServerError),{success:!1,message:"Internal Server Error"}},this._onNotFound=($)=>{return $.response.setStatusCode(b.notFound),{success:!1,message:"404 Not Found"}}}_addBeforeHooks($,W){for(let Z of $)this._beforeAll.add({handler:Z,options:W??{routesToExclude:[],routesToInclude:[]}})}_addAfterHooks($,W){for(let Z of $)this._afterAll.add({handler:Z,options:W??{routesToExclude:[],routesToInclude:[]}})}_addOnError($){this._onError=$}_addOnNotFound($){this._onNotFound=$}}var K1=($)=>{let W=[],Z=$.path.replace(/:\w+/g,(D)=>{let Y=D.slice(1);return W.push(Y),"([^/]+)"}).replace(/\//g,"\\/");return{...$,pattern:new RegExp(`^${Z}$`),paramNames:W,isParameterized:!0}};var T$=($)=>{let[W]=$.split("?");if(!W)return"";if([W]=W.split("#"),!W)return"";try{W=decodeURIComponent(W)}catch(Z){V.warn("Failed to decode URL path",{path:W})}if(W=W.startsWith("/")?W:`/${W}`,W=W.replace(/\/\/+/g,"/"),W=m0(W),W.length>1&&W.endsWith("/"))W=W.slice(0,-1);return W},m0=($)=>{let W=$.split("/"),Z=[];for(let Y of W){if(Y==="."||Y===""){if(Y===""&&Z.length===0)Z.push(Y);continue}if(Y===".."){if(Z.length>1)Z.pop()}else Z.push(Y)}return Z.join("/")||"/"},v$=($)=>$.replace(/:\w+/g,":param");var G1=($)=>{let W=$.match(/:\w+/g);if(!W)return;let Z=W.map((Y)=>Y.slice(1)),D=new Set(Z);if(Z.length!==D.size){let Y=Z.filter((Q,X)=>Z.indexOf(Q)!==X);throw new Error(`Route ${$} has duplicate parameter names: ${Y.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:D}){let Y=T$(W),Q=Y.includes(":");if(Q)G1(Y);if(this._hasExactRoutePattern($,Y))throw new Error(`Route ${Y} already exists for method ${$}`);let X={method:$,path:Y,handler:Z,options:D,params:{}};if(Q)this._storeParameterizedRoute($,X);else this._storeExactRoute($,Y,X)}_findRoute($,W){let Z=T$(W),D=this._exactRoutes.get($)?.get(Z);if(D)return D;return this._findParameterizedRoute($,Z)}_hasExactRoutePattern($,W){if(this._exactRoutes.get($)?.has(W))return!0;if(W.includes(":")){let Z=v$(W),D=this._parameterizedRoutes.get($);if(D)return D.some((Y)=>v$(Y.path)===Z)}else{let Z=this._parameterizedRoutes.get($);if(Z)return Z.some((D)=>D.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=K1(W);this._parameterizedRoutes.get($)?.push(Z)}_findParameterizedRoute($,W){let Z=this._parameterizedRoutes.get($);if(!Z)return;for(let D of Z){let Y=W.match(D.pattern);if(Y){let Q={};for(let X=0;X<D.paramNames.length;X++){let O=Y[X+1],H=D.paramNames[X];if(O!==void 0&&H!==void 0)Q[H]=O}return{...D,params:Q}}}return}}class x${_configuration;_routeRegistry=new P$;_hooks=new R$;constructor($){this._configuration=J1($)}get($,W,Z){let D=Z??{beforeHooks:[],afterHooks:[]};this._routeRegistry._register({method:E.get,handler:W,path:$,options:D,params:{}}),this._routeRegistry._register({method:E.head,handler:W,path:$,options:D,params:{}})}head($,W,Z){this._routeRegistry._register({method:E.head,handler:W,path:$,options:Z??{beforeHooks:[],afterHooks:[]},params:{}})}post($,W,Z){this._routeRegistry._register({method:E.post,handler:W,path:$,options:Z??{beforeHooks:[],afterHooks:[]},params:{}})}put($,W,Z){this._routeRegistry._register({method:E.put,handler:W,path:$,options:Z??{beforeHooks:[],afterHooks:[]},params:{}})}patch($,W,Z){this._routeRegistry._register({method:E.patch,handler:W,path:$,options:Z??{beforeHooks:[],afterHooks:[]},params:{}})}delete($,W,Z){this._routeRegistry._register({method:E.delete,handler:W,path:$,options:Z??{beforeHooks:[],afterHooks:[]},params:{}})}options($,W,Z){this._routeRegistry._register({method:E.options,handler:W,path:$,options:Z??{beforeHooks:[],afterHooks:[]},params:{}})}group($,W,Z){let D=(Q)=>(X,O,H)=>{let _=`${$}${X}`,I={beforeHooks:[...Z?.beforeHooks??[],...H?.beforeHooks??[]],afterHooks:[...H?.afterHooks??[],...Z?.afterHooks??[]]};if(this._routeRegistry._register({method:Q,handler:O,path:_,options:I,params:{}}),Q===E.get)this._routeRegistry._register({method:E.head,handler:O,path:_,options:I,params:{}})},Y={get:D(E.get),head:D(E.head),post:D(E.post),put:D(E.put),delete:D(E.delete),patch:D(E.patch),options:D(E.options)};W(Y)}beforeAll($,W){this._hooks._addBeforeHooks($,W)}afterAll($,W){this._hooks._addAfterHooks($,W)}onError($){this._hooks._addOnError($)}onNotFound($){this._hooks._addOnNotFound($)}}class l0 extends x${_isListening=!1;_server;constructor($){super($);if(this._configuration.logger)V.setCustomLogger(this._configuration.logger);if(V.setLogLevel(this._configuration.logLevel),x.setEnabled(this._configuration.networkLogs),this._configuration.networkLogger)x.setNetworkLogger(this._configuration.networkLogger);V.info("YinzerFlow initialized with logging enabled",`${N.green}level: ${this._configuration.logLevel}, networkLogs: ${this._configuration.networkLogs}${N.reset}`)}_setupServer($,W,Z){if(!this._server)return;this._server.on("error",(D)=>{x.serverError(this._configuration.port,this._configuration.host,D.message),W(D)}),this._server.on("listening",()=>{this._isListening=!0,x.serverStart(this._configuration.port,this._configuration.host),$()}),this._server.on("connection",(D)=>{this._handleConnection(D,Z)})}async _processRequest({data:$,socket:W,requestHandler:Z,clientAddress:D}){let Y=Date.now();V.info("Processing incoming request",{clientAddress:D,dataSize:$.length});let Q=new L$($,this,D);await Z.handle(Q),W.write(Q._response._stringBody),W.end();let X=Date.now(),O=X-Y;if(x.request(Q,Y,X),O>500)V.warn("Slow request detected",{method:Q.request.method,path:Q.request.path,statusCode:Q._response._statusCode,responseTime:`${O}ms`,clientAddress:D})}_handleConnection($,W){let Z=$.remoteAddress??"unknown";x.connection("connect",Z),$.on("data",(D)=>{this._processRequest({data:D,socket:$,requestHandler:W,clientAddress:Z}).catch((Y)=>{let Q=Y instanceof Error?Y.message:"Unknown error";x.connection("error",Z,`Unexpected error: ${Q}`),$.destroy()})}),$.on("error",(D)=>{x.connection("error",Z,D.message)}),$.on("close",()=>{x.connection("disconnect",Z)})}async listen(){if(this._isListening)throw new Error("Server is already listening");return new Promise(($,W)=>{let Z=new N$(this);this._server=f0(),this._setupServer($,W,Z),this._server.listen(this._configuration.port,this._configuration.host)})}async close(){if(!this._isListening||!this._server)return;return new Promise(($)=>{if(!this._server){this._isListening=!1,$();return}this._server.close(()=>{this._isListening=!1,x.serverStop(this._configuration.port,this._configuration.host),$()})})}status(){return{isListening:this._isListening,port:this._configuration.port,host:this._configuration.host}}}export{l0 as YinzerFlow};
|
|
23
21
|
|
|
24
|
-
//# debugId=
|
|
22
|
+
//# debugId=529BD7F131C4E5FA64756E2164756E21
|