elysia 1.3.19 → 1.3.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bun/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;var __toESM=(mod,isNodeMode,target)=>{target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:()=>mod[key],enumerable:!0});return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __require=import.meta.require;var require_fast_decode_uri_component=__commonJS((exports,module)=>{var UTF8_ACCEPT=12,UTF8_REJECT=0,UTF8_DATA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7];function decodeURIComponent2(uri){var percentPosition=uri.indexOf("%");if(percentPosition===-1)return uri;var length=uri.length,decoded="",last=0,codepoint=0,startOfOctets=percentPosition,state=UTF8_ACCEPT;while(percentPosition>-1&&percentPosition<length){var high=hexCodeToInt(uri[percentPosition+1],4),low=hexCodeToInt(uri[percentPosition+2],0),byte=high|low,type=UTF8_DATA[byte];if(state=UTF8_DATA[256+state+type],codepoint=codepoint<<6|byte&UTF8_DATA[364+type],state===UTF8_ACCEPT)decoded+=uri.slice(last,startOfOctets),decoded+=codepoint<=65535?String.fromCharCode(codepoint):String.fromCharCode(55232+(codepoint>>10),56320+(codepoint&1023)),codepoint=0,last=percentPosition+3,percentPosition=startOfOctets=uri.indexOf("%",last);else if(state===UTF8_REJECT)return null;else{if(percentPosition+=3,percentPosition<length&&uri.charCodeAt(percentPosition)===37)continue;return null}}return decoded+uri.slice(last)}var HEX={"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};function hexCodeToInt(c,shift){var i=HEX[c];return i===void 0?255:i<<shift}module.exports=decodeURIComponent2});var require_dist=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.parse=parse;exports.serialize=serialize;var cookieNameRegExp=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,cookieValueRegExp=/^[\u0021-\u003A\u003C-\u007E]*$/,domainValueRegExp=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,pathValueRegExp=/^[\u0020-\u003A\u003D-\u007E]*$/,__toString=Object.prototype.toString,NullObject=(()=>{let C=function(){};return C.prototype=Object.create(null),C})();function parse(str,options){let obj=new NullObject,len=str.length;if(len<2)return obj;let dec=options?.decode||decode,index=0;do{let eqIdx=str.indexOf("=",index);if(eqIdx===-1)break;let colonIdx=str.indexOf(";",index),endIdx=colonIdx===-1?len:colonIdx;if(eqIdx>endIdx){index=str.lastIndexOf(";",eqIdx-1)+1;continue}let keyStartIdx=startIndex(str,index,eqIdx),keyEndIdx=endIndex(str,eqIdx,keyStartIdx),key=str.slice(keyStartIdx,keyEndIdx);if(obj[key]===void 0){let valStartIdx=startIndex(str,eqIdx+1,endIdx),valEndIdx=endIndex(str,endIdx,valStartIdx),value=dec(str.slice(valStartIdx,valEndIdx));obj[key]=value}index=endIdx+1}while(index<len);return obj}function startIndex(str,index,max){do{let code=str.charCodeAt(index);if(code!==32&&code!==9)return index}while(++index<max);return max}function endIndex(str,index,min){while(index>min){let code=str.charCodeAt(--index);if(code!==32&&code!==9)return index+1}return min}function serialize(name,val,options){let enc=options?.encode||encodeURIComponent;if(!cookieNameRegExp.test(name))throw new TypeError(`argument name is invalid: ${name}`);let value=enc(val);if(!cookieValueRegExp.test(value))throw new TypeError(`argument val is invalid: ${val}`);let str=name+"="+value;if(!options)return str;if(options.maxAge!==void 0){if(!Number.isInteger(options.maxAge))throw new TypeError(`option maxAge is invalid: ${options.maxAge}`);str+="; Max-Age="+options.maxAge}if(options.domain){if(!domainValueRegExp.test(options.domain))throw new TypeError(`option domain is invalid: ${options.domain}`);str+="; Domain="+options.domain}if(options.path){if(!pathValueRegExp.test(options.path))throw new TypeError(`option path is invalid: ${options.path}`);str+="; Path="+options.path}if(options.expires){if(!isDate(options.expires)||!Number.isFinite(options.expires.valueOf()))throw new TypeError(`option expires is invalid: ${options.expires}`);str+="; Expires="+options.expires.toUTCString()}if(options.httpOnly)str+="; HttpOnly";if(options.secure)str+="; Secure";if(options.partitioned)str+="; Partitioned";if(options.priority)switch(typeof options.priority==="string"?options.priority.toLowerCase():void 0){case"low":str+="; Priority=Low";break;case"medium":str+="; Priority=Medium";break;case"high":str+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${options.priority}`)}if(options.sameSite)switch(typeof options.sameSite==="string"?options.sameSite.toLowerCase():options.sameSite){case!0:case"strict":str+="; SameSite=Strict";break;case"lax":str+="; SameSite=Lax";break;case"none":str+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${options.sameSite}`)}return str}function decode(str){if(str.indexOf("%")===-1)return str;try{return decodeURIComponent(str)}catch(e){return str}}function isDate(val){return __toString.call(val)==="[object Date]"}});var Y=(v,b)=>{let A=b?.length?{}:null;if(A)for(let Q of b)A[Q.part.charCodeAt(0)]=Q;return{part:v,store:null,inert:A,params:null,wildcardStore:null}},k=(v,b)=>({...v,part:b}),T=(v)=>({name:v,store:null,inert:null});class _{config;root={};history=[];deferred=[];constructor(v={}){if(this.config=v,v.lazy)this.find=this.lazyFind;if(v.onParam&&!Array.isArray(v.onParam))this.config.onParam=[this.config.onParam]}static regex={static:/:.+?(?=\/|$)/,params:/:.+?(?=\/|$)/g,optionalParams:/(\/:\w+\?)/g};lazyFind=(v,b)=>{if(!this.config.lazy)return this.find;return this.build(),this.find(v,b)};build(){if(!this.config.lazy)return;for(let[v,b,A]of this.deferred)this.add(v,b,A,{lazy:!1,ignoreHistory:!0});this.deferred=[],this.find=(v,b)=>{let A=this.root[v];if(!A)return null;return $(b,b.length,A,0,this.config.onParam)}}add(v,b,A,{ignoreError:Q=!1,ignoreHistory:O=!1,lazy:V=this.config.lazy}={}){if(V)return this.find=this.lazyFind,this.deferred.push([v,b,A]),A;if(typeof b!=="string")throw new TypeError("Route path must be a string");if(b==="")b="/";else if(b[0]!=="/")b=`/${b}`;let X=b[b.length-1]==="*",J=b.match(_.regex.optionalParams);if(J){let F=b.replaceAll("?","");this.add(v,F,A,{ignoreError:Q,ignoreHistory:O,lazy:V});for(let B=0;B<J.length;B++){let D=b.replace(J[B],"");this.add(v,D,A,{ignoreError:!0,ignoreHistory:O,lazy:V})}return A}if(J)b=b.replaceAll("?","");if(this.history.find(([F,B,D])=>F===v&&B===b))return A;if(X||J&&b.charCodeAt(b.length-1)===63)b=b.slice(0,-1);if(!O)this.history.push([v,b,A]);let K=b.split(_.regex.static),G=b.match(_.regex.params)||[];if(K[K.length-1]==="")K.pop();let q;if(!this.root[v])q=this.root[v]=Y("/");else q=this.root[v];let U=0;for(let F=0;F<K.length;++F){let B=K[F];if(F>0){let D=G[U++].slice(1);if(q.params===null)q.params=T(D);else if(q.params.name!==D)if(Q)return A;else throw new Error(`Cannot create route "${b}" with parameter "${D}" because a route already exists with a different parameter name ("${q.params.name}") in the same location`);let S=q.params;if(S.inert===null){q=S.inert=Y(B);continue}q=S.inert}for(let D=0;;){if(D===B.length){if(D<q.part.length){let S=k(q,q.part.slice(D));Object.assign(q,Y(B,[S]))}break}if(D===q.part.length){if(q.inert===null)q.inert={};let S=q.inert[B.charCodeAt(D)];if(S){q=S,B=B.slice(D),D=0;continue}let Z=Y(B.slice(D));q.inert[B.charCodeAt(D)]=Z,q=Z;break}if(B[D]!==q.part[D]){let S=k(q,q.part.slice(D)),Z=Y(B.slice(D));Object.assign(q,Y(q.part.slice(0,D),[S,Z])),q=Z;break}++D}}if(U<G.length){let B=G[U].slice(1);if(q.params===null)q.params=T(B);else if(q.params.name!==B)if(Q)return A;else throw new Error(`Cannot create route "${b}" with parameter "${B}" because a route already exists with a different parameter name ("${q.params.name}") in the same location`);if(q.params.store===null)q.params.store=A;return q.params.store}if(X){if(q.wildcardStore===null)q.wildcardStore=A;return q.wildcardStore}if(q.store===null)q.store=A;return q.store}find(v,b){let A=this.root[v];if(!A)return null;return $(b,b.length,A,0,this.config.onParam)}}var $=(v,b,A,Q,O)=>{let V=A.part,X=V.length,J=Q+X;if(X>1){if(J>b)return null;if(X<15){for(let K=1,G=Q+1;K<X;++K,++G)if(V.charCodeAt(K)!==v.charCodeAt(G))return null}else if(v.slice(Q,J)!==V)return null}if(J===b){if(A.store!==null)return{store:A.store,params:{}};if(A.wildcardStore!==null)return{store:A.wildcardStore,params:{"*":""}};return null}if(A.inert!==null){let K=A.inert[v.charCodeAt(J)];if(K!==void 0){let G=$(v,b,K,J,O);if(G!==null)return G}}if(A.params!==null){let{store:K,name:G,inert:q}=A.params,U=v.indexOf("/",J);if(U!==J){if(U===-1||U>=b){if(K!==null){let F={};if(F[G]=v.substring(J,b),O)for(let B=0;B<O.length;B++){let D=O[B](F[G],G);if(D!==void 0)F[G]=D}return{store:K,params:F}}}else if(q!==null){let F=$(v,b,q,U,O);if(F!==null){if(F.params[G]=v.substring(J,U),O)for(let B=0;B<O.length;B++){let D=O[B](F.params[G],G);if(D!==void 0)F.params[G]=D}return F}}}}if(A.wildcardStore!==null)return{store:A.wildcardStore,params:{"*":v.substring(J,b)}};return null};var import_fast_decode_uri_component4=__toESM(require_fast_decode_uri_component(),1);import{Kind as Kind6}from"@sinclair/typebox";import{Type,Kind as Kind2}from"@sinclair/typebox";import{FormatRegistry}from"@sinclair/typebox";var fullFormats={date,time:getTime(!0),"date-time":getDateTime(!0),"iso-time":getTime(!1),"iso-date-time":getDateTime(!1),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:!0,binary:!0};function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date(str){let matches=DATE.exec(str);if(!matches)return!1;let year=+matches[1],month=+matches[2],day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}var TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function time(str){let matches=TIME.exec(str);if(!matches)return!1;let hr=+matches[1],min=+matches[2],sec=+matches[3],tz=matches[4],tzSign=matches[5]==="-"?-1:1,tzH=+(matches[6]||0),tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return!1;if(hr<=23&&min<=59&&sec<60)return!0;let utcMin=min-tzM*tzSign,utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}var parseDateTimeEmptySpace=(str)=>{if(str.charCodeAt(str.length-6)===32)return str.slice(0,-6)+"+"+str.slice(-5);return str},DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){let time=getTime(strictTimeZone);return function date_time(str){let dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date(dateTime[0])&&time(dateTime[1])}}var NOT_URI_FRAGMENT=/\/|:/,URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}var BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str){return BYTE.lastIndex=0,BYTE.test(str)}var MIN_INT32=-2147483648,MAX_INT32=2147483647;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return!0}var Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return!1;try{return new RegExp(str),!0}catch(e){return!1}}var isISO8601=/(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/,isFormalDate=/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT(?:\+|-)\d{4}\s\([^)]+\)/,isShortenDate=/^(?:(?:(?:(?:0?[1-9]|[12][0-9]|3[01])[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:19|20)\d{2})|(?:(?:19|20)\d{2}[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:0?[1-9]|[12][0-9]|3[01]))))(?:\s(?:1[012]|0?[1-9]):[0-5][0-9](?::[0-5][0-9])?(?:\s[AP]M)?)?$/,_validateDate=fullFormats.date,_validateDateTime=fullFormats["date-time"];if(!FormatRegistry.Has("date"))FormatRegistry.Set("date",(value)=>{let temp=parseDateTimeEmptySpace(value).replace(/"/g,"");if(isISO8601.test(temp)||isFormalDate.test(temp)||isShortenDate.test(temp)||_validateDate(temp)){let date2=new Date(temp);if(!Number.isNaN(date2.getTime()))return!0}return!1});if(!FormatRegistry.Has("date-time"))FormatRegistry.Set("date-time",(value)=>{let temp=value.replace(/"/g,"");if(isISO8601.test(temp)||isFormalDate.test(temp)||isShortenDate.test(temp)||_validateDateTime(temp)){let date2=new Date(temp);if(!Number.isNaN(date2.getTime()))return!0}return!1});Object.entries(fullFormats).forEach((formatEntry)=>{let[formatName,formatValue]=formatEntry;if(!FormatRegistry.Has(formatName)){if(formatValue instanceof RegExp)FormatRegistry.Set(formatName,(value)=>formatValue.test(value));else if(typeof formatValue==="function")FormatRegistry.Set(formatName,formatValue)}});if(!FormatRegistry.Has("numeric"))FormatRegistry.Set("numeric",(value)=>!!value&&!isNaN(+value));if(!FormatRegistry.Has("integer"))FormatRegistry.Set("integer",(value)=>!!value&&Number.isInteger(+value));if(!FormatRegistry.Has("boolean"))FormatRegistry.Set("boolean",(value)=>value==="true"||value==="false");if(!FormatRegistry.Has("ObjectString"))FormatRegistry.Set("ObjectString",(value)=>{let start=value.charCodeAt(0);if(start===9||start===10||start===32)start=value.trimStart().charCodeAt(0);if(start!==123&&start!==91)return!1;try{return JSON.parse(value),!0}catch{return!1}});if(!FormatRegistry.Has("ArrayString"))FormatRegistry.Set("ArrayString",(value)=>{let start=value.charCodeAt(0);if(start===9||start===10||start===32)start=value.trimStart().charCodeAt(0);if(start!==123&&start!==91)return!1;try{return JSON.parse(value),!0}catch{return!1}});import{Kind,TypeRegistry,Unsafe}from"@sinclair/typebox";import{Value as Value2}from"@sinclair/typebox/value";import{TypeCompiler}from"@sinclair/typebox/compiler";var isBun=typeof Bun!=="undefined";var mime2={aac:"audio/aac",abw:"application/x-abiword",ai:"application/postscript",arc:"application/octet-stream",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",dll:"application/octet-stream",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",mid:"audio/midi",midi:"audio/midi",mp2:"audio/mpeg",mp3:"audio/mpeg",mp4:"video/mp4",mpa:"video/mpeg",mpe:"video/mpeg",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",otf:"font/otf",png:"image/png",pdf:"application/pdf",ppt:"application/vnd.ms-powerpoint",rar:"application/x-rar-compressed",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"application/typescript",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/x-wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.ms-excel",xlsx_OLD:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3gp_DOES_NOT_CONTAIN_VIDEO":"audio/3gpp","3gp2":"video/3gpp2","3gp2_DOES_NOT_CONTAIN_VIDEO":"audio/3gpp2","7z":"application/x-7z-compressed"},getFileExtension=(path)=>{let index=path.lastIndexOf(".");if(index===-1)return"";return path.slice(index+1)},file=(path)=>new ElysiaFile(path),createReadStream,stat;class ElysiaFile{path;value;stats;constructor(path){this.path=path;if(isBun)this.value=Bun.file(path);else if(typeof window!=="undefined")console.warn("Browser environment does not support file");else if(!createReadStream||!stat)try{this.value=import("fs").then((fs)=>{return createReadStream=fs.createReadStream,fs.createReadStream(path)}),this.stats=import("fs/promises").then((fs)=>{return stat=fs.stat,fs.stat(path)})}catch{}else this.value=createReadStream(path),this.stats=stat(path)}get type(){return mime2[getFileExtension(this.path)]||"application/octet-stream"}get length(){if(isBun)return this.value.size;return this.stats?.then((x)=>x.size)??0}}import{Value}from"@sinclair/typebox/value";var hasHeaderShorthand="toJSON"in new Headers,replaceUrlPath=(url,pathname)=>{let urlObject=new URL(url);return urlObject.pathname=pathname,urlObject.toString()},isClass=(v)=>typeof v==="function"&&/^\s*class\s+/.test(v.toString())||v.toString&&v.toString().startsWith("[object ")&&v.toString()!=="[object Object]"||isNotEmpty(Object.getPrototypeOf(v)),isObject=(item)=>item&&typeof item==="object"&&!Array.isArray(item),mergeDeep=(target,source,options)=>{let skipKeys=options?.skipKeys,override=options?.override??!0;if(!isObject(target)||!isObject(source))return target;for(let[key,value]of Object.entries(source)){if(skipKeys?.includes(key))continue;if(!isObject(value)||!(key in target)||isClass(value)){if(override||!(key in target))target[key]=value;continue}target[key]=mergeDeep(target[key],value,{skipKeys,override})}return target},mergeCookie=(a,b)=>{let v=mergeDeep(Object.assign({},a),b,{skipKeys:["properties"]});if(v.properties)delete v.properties;return v},mergeObjectArray=(a,b)=>{if(!b)return a;let array=[],checksums=[];if(a){if(!Array.isArray(a))a=[a];for(let item of a)if(array.push(item),item.checksum)checksums.push(item.checksum)}if(b){if(!Array.isArray(b))b=[b];for(let item of b)if(!checksums.includes(item.checksum))array.push(item)}return array},primitiveHooks=["start","request","parse","transform","resolve","beforeHandle","afterHandle","mapResponse","afterResponse","trace","error","stop","body","headers","params","query","response","type","detail"],primitiveHookMap=primitiveHooks.reduce((acc,x)=>(acc[x]=!0,acc),{}),isRecordNumber=(x)=>typeof x==="object"&&Object.keys(x).every((x2)=>!isNaN(+x2)),mergeResponse=(a,b)=>{if(isRecordNumber(a)&&isRecordNumber(b))return Object.assign({},a,b);else if(a&&!isRecordNumber(a)&&isRecordNumber(b))return Object.assign({200:a},b);return b??a},mergeSchemaValidator=(a,b)=>{if(!a&&!b)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return{body:b?.body??a?.body,headers:b?.headers??a?.headers,params:b?.params??a?.params,query:b?.query??a?.query,cookie:b?.cookie??a?.cookie,response:mergeResponse(a?.response,b?.response)}},mergeHook=(a,b)=>{if(!Object.values(b).find((x)=>x!==void 0&&x!==null))return{...a};let hook={...a,...b,body:b?.body??a?.body,headers:b?.headers??a?.headers,params:b?.params??a?.params,query:b?.query??a?.query,cookie:b?.cookie??a?.cookie,response:mergeResponse(a?.response,b?.response),type:a?.type||b?.type,detail:mergeDeep(b?.detail??{},a?.detail??{}),parse:mergeObjectArray(a?.parse,b?.parse),transform:mergeObjectArray(a?.transform,b?.transform),beforeHandle:mergeObjectArray(mergeObjectArray(fnToContainer(a?.resolve,"resolve"),a?.beforeHandle),mergeObjectArray(fnToContainer(b.resolve,"resolve"),b?.beforeHandle)),afterHandle:mergeObjectArray(a?.afterHandle,b?.afterHandle),mapResponse:mergeObjectArray(a?.mapResponse,b?.mapResponse),afterResponse:mergeObjectArray(a?.afterResponse,b?.afterResponse),trace:mergeObjectArray(a?.trace,b?.trace),error:mergeObjectArray(a?.error,b?.error)};if(hook.resolve)delete hook.resolve;return hook},lifeCycleToArray=(a)=>{if(a.parse&&!Array.isArray(a.parse))a.parse=[a.parse];if(a.transform&&!Array.isArray(a.transform))a.transform=[a.transform];if(a.afterHandle&&!Array.isArray(a.afterHandle))a.afterHandle=[a.afterHandle];if(a.mapResponse&&!Array.isArray(a.mapResponse))a.mapResponse=[a.mapResponse];if(a.afterResponse&&!Array.isArray(a.afterResponse))a.afterResponse=[a.afterResponse];if(a.trace&&!Array.isArray(a.trace))a.trace=[a.trace];if(a.error&&!Array.isArray(a.error))a.error=[a.error];let beforeHandle=[];if(a.resolve)beforeHandle=fnToContainer(Array.isArray(a.resolve)?a.resolve:[a.resolve],"resolve"),delete a.resolve;if(a.beforeHandle)if(beforeHandle.length)beforeHandle=beforeHandle.concat(Array.isArray(a.beforeHandle)?a.beforeHandle:[a.beforeHandle]);else beforeHandle=Array.isArray(a.beforeHandle)?a.beforeHandle:[a.beforeHandle];if(beforeHandle.length)a.beforeHandle=beforeHandle;return a},isBun2=typeof Bun!=="undefined",hasBunHash=isBun2&&typeof Bun.hash==="function",checksum=(s)=>{if(hasBunHash)return Bun.hash(s);let h=9;for(let i=0;i<s.length;)h=Math.imul(h^s.charCodeAt(i++),387420489);return h=h^h>>>9},injectChecksum=(checksum2,x)=>{if(!x)return;if(!Array.isArray(x)){let fn=x;if(checksum2&&!fn.checksum)fn.checksum=checksum2;if(fn.scope==="scoped")fn.scope="local";return fn}let fns=[...x];for(let fn of fns){if(checksum2&&!fn.checksum)fn.checksum=checksum2;if(fn.scope==="scoped")fn.scope="local"}return fns},mergeLifeCycle=(a,b,checksum2)=>{return{start:mergeObjectArray(a.start,injectChecksum(checksum2,b?.start)),request:mergeObjectArray(a.request,injectChecksum(checksum2,b?.request)),parse:mergeObjectArray(a.parse,injectChecksum(checksum2,b?.parse)),transform:mergeObjectArray(a.transform,injectChecksum(checksum2,b?.transform)),beforeHandle:mergeObjectArray(mergeObjectArray(fnToContainer(a.resolve,"resolve"),a.beforeHandle),injectChecksum(checksum2,mergeObjectArray(fnToContainer(b?.resolve,"resolve"),b?.beforeHandle))),afterHandle:mergeObjectArray(a.afterHandle,injectChecksum(checksum2,b?.afterHandle)),mapResponse:mergeObjectArray(a.mapResponse,injectChecksum(checksum2,b?.mapResponse)),afterResponse:mergeObjectArray(a.afterResponse,injectChecksum(checksum2,b?.afterResponse)),trace:mergeObjectArray(a.trace,injectChecksum(checksum2,b?.trace)),error:mergeObjectArray(a.error,injectChecksum(checksum2,b?.error)),stop:mergeObjectArray(a.stop,injectChecksum(checksum2,b?.stop))}},asHookType=(fn,inject,{skipIfHasType=!1})=>{if(!fn)return fn;if(!Array.isArray(fn)){if(skipIfHasType)fn.scope??=inject;else fn.scope=inject;return fn}for(let x of fn)if(skipIfHasType)x.scope??=inject;else x.scope=inject;return fn},filterGlobal=(fn)=>{if(!fn)return fn;if(!Array.isArray(fn))switch(fn.scope){case"global":case"scoped":return{...fn};default:return{fn}}let array=[];for(let x of fn)switch(x.scope){case"global":case"scoped":array.push({...x});break}return array},filterGlobalHook=(hook)=>{return{...hook,type:hook?.type,detail:hook?.detail,parse:filterGlobal(hook?.parse),transform:filterGlobal(hook?.transform),beforeHandle:filterGlobal(hook?.beforeHandle),afterHandle:filterGlobal(hook?.afterHandle),mapResponse:filterGlobal(hook?.mapResponse),afterResponse:filterGlobal(hook?.afterResponse),error:filterGlobal(hook?.error),trace:filterGlobal(hook?.trace)}},StatusMap={Continue:100,"Switching Protocols":101,Processing:102,"Early Hints":103,OK:200,Created:201,Accepted:202,"Non-Authoritative Information":203,"No Content":204,"Reset Content":205,"Partial Content":206,"Multi-Status":207,"Already Reported":208,"Multiple Choices":300,"Moved Permanently":301,Found:302,"See Other":303,"Not Modified":304,"Temporary Redirect":307,"Permanent Redirect":308,"Bad Request":400,Unauthorized:401,"Payment Required":402,Forbidden:403,"Not Found":404,"Method Not Allowed":405,"Not Acceptable":406,"Proxy Authentication Required":407,"Request Timeout":408,Conflict:409,Gone:410,"Length Required":411,"Precondition Failed":412,"Payload Too Large":413,"URI Too Long":414,"Unsupported Media Type":415,"Range Not Satisfiable":416,"Expectation Failed":417,"I'm a teapot":418,"Misdirected Request":421,"Unprocessable Content":422,Locked:423,"Failed Dependency":424,"Too Early":425,"Upgrade Required":426,"Precondition Required":428,"Too Many Requests":429,"Request Header Fields Too Large":431,"Unavailable For Legal Reasons":451,"Internal Server Error":500,"Not Implemented":501,"Bad Gateway":502,"Service Unavailable":503,"Gateway Timeout":504,"HTTP Version Not Supported":505,"Variant Also Negotiates":506,"Insufficient Storage":507,"Loop Detected":508,"Not Extended":510,"Network Authentication Required":511},InvertedStatusMap=Object.fromEntries(Object.entries(StatusMap).map(([k2,v])=>[v,k2]));function removeTrailingEquals(digest){let trimmedDigest=digest;while(trimmedDigest.endsWith("="))trimmedDigest=trimmedDigest.slice(0,-1);return trimmedDigest}var encoder=new TextEncoder,signCookie=async(val,secret)=>{if(typeof val==="object")val=JSON.stringify(val);else if(typeof val!=="string")val=val+"";if(secret===null)throw new TypeError("Secret key must be provided.");let secretKey=await crypto.subtle.importKey("raw",encoder.encode(secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),hmacBuffer=await crypto.subtle.sign("HMAC",secretKey,encoder.encode(val));return val+"."+removeTrailingEquals(Buffer.from(hmacBuffer).toString("base64"))},unsignCookie=async(input,secret)=>{if(typeof input!=="string")throw new TypeError("Signed cookie string must be provided.");if(secret===null)throw new TypeError("Secret key must be provided.");let tentativeValue=input.slice(0,input.lastIndexOf("."));return await signCookie(tentativeValue,secret)===input?tentativeValue:!1},traceBackMacro=(extension,property,manage)=>{if(!extension||typeof extension!=="object"||!property)return;for(let[key,value]of Object.entries(property)){if(primitiveHookMap[key]||!(key in extension))continue;let v=extension[key];if(typeof v==="function"){let hook=v(value);if(typeof hook==="object")for(let[k2,v2]of Object.entries(hook))manage(k2)({fn:v2})}delete property[key]}},createMacroManager=({globalHook,localHook})=>(stackName)=>(type,fn)=>{if(typeof type==="function")type={fn:type};if(stackName==="resolve")type={...type,subType:"resolve"};if(!localHook[stackName])localHook[stackName]=[];if(typeof localHook[stackName]==="function")localHook[stackName]=[localHook[stackName]];if(!Array.isArray(localHook[stackName]))localHook[stackName]=[localHook[stackName]];if("fn"in type||Array.isArray(type)){if(Array.isArray(type))localHook[stackName]=localHook[stackName].concat(type);else localHook[stackName].push(type);return}let{insert="after",stack="local"}=type;if(typeof fn==="function")fn={fn};if(stack==="global")if(!Array.isArray(fn))if(insert==="before")globalHook[stackName].unshift(fn);else globalHook[stackName].push(fn);else if(insert==="before")globalHook[stackName]=fn.concat(globalHook[stackName]);else globalHook[stackName]=globalHook[stackName].concat(fn);else if(!Array.isArray(fn))if(insert==="before")localHook[stackName].unshift(fn);else localHook[stackName].push(fn);else if(insert==="before")localHook[stackName]=fn.concat(localHook[stackName]);else localHook[stackName]=localHook[stackName].concat(fn)},parseNumericString=(message)=>{if(typeof message==="number")return message;if(message.length<16){if(message.trim().length===0)return null;let length=Number(message);if(Number.isNaN(length))return null;return length}if(message.length===16){if(message.trim().length===0)return null;let number=Number(message);if(Number.isNaN(number)||number.toString()!==message)return null;return number}return null},isNumericString=(message)=>parseNumericString(message)!==null;class PromiseGroup{onError;onFinally;root=null;promises=[];constructor(onError=console.error,onFinally=()=>{}){this.onError=onError;this.onFinally=onFinally}get size(){return this.promises.length}add(promise){if(this.promises.push(promise),this.root||=this.drain(),this.promises.length===1)this.then(this.onFinally);return promise}async drain(){while(this.promises.length>0){try{await this.promises[0]}catch(error){this.onError(error)}this.promises.shift()}this.root=null}then(onfulfilled,onrejected){return(this.root??Promise.resolve()).then(onfulfilled,onrejected)}}var fnToContainer=(fn,subType)=>{if(!fn)return fn;if(!Array.isArray(fn)){if(typeof fn==="function"||typeof fn==="string")return subType?{fn,subType}:{fn};else if("fn"in fn)return fn}let fns=[];for(let x of fn)if(typeof x==="function"||typeof x==="string")fns.push(subType?{fn:x,subType}:{fn:x});else if("fn"in x)fns.push(x);return fns},localHookToLifeCycleStore=(a)=>{if(a.start)a.start=fnToContainer(a.start);if(a.request)a.request=fnToContainer(a.request);if(a.parse)a.parse=fnToContainer(a.parse);if(a.transform)a.transform=fnToContainer(a.transform);if(a.beforeHandle)a.beforeHandle=fnToContainer(a.beforeHandle);if(a.afterHandle)a.afterHandle=fnToContainer(a.afterHandle);if(a.mapResponse)a.mapResponse=fnToContainer(a.mapResponse);if(a.afterResponse)a.afterResponse=fnToContainer(a.afterResponse);if(a.trace)a.trace=fnToContainer(a.trace);if(a.error)a.error=fnToContainer(a.error);if(a.stop)a.stop=fnToContainer(a.stop);return a},lifeCycleToFn=(a)=>{let lifecycle=Object.create(null);if(a.start?.map)lifecycle.start=a.start.map((x)=>x.fn);if(a.request?.map)lifecycle.request=a.request.map((x)=>x.fn);if(a.parse?.map)lifecycle.parse=a.parse.map((x)=>x.fn);if(a.transform?.map)lifecycle.transform=a.transform.map((x)=>x.fn);if(a.beforeHandle?.map)lifecycle.beforeHandle=a.beforeHandle.map((x)=>x.fn);if(a.afterHandle?.map)lifecycle.afterHandle=a.afterHandle.map((x)=>x.fn);if(a.mapResponse?.map)lifecycle.mapResponse=a.mapResponse.map((x)=>x.fn);if(a.afterResponse?.map)lifecycle.afterResponse=a.afterResponse.map((x)=>x.fn);if(a.error?.map)lifecycle.error=a.error.map((x)=>x.fn);if(a.stop?.map)lifecycle.stop=a.stop.map((x)=>x.fn);if(a.trace?.map)lifecycle.trace=a.trace.map((x)=>x.fn);else lifecycle.trace=[];return lifecycle},cloneInference=(inference)=>({body:inference.body,cookie:inference.cookie,headers:inference.headers,query:inference.query,set:inference.set,server:inference.server,path:inference.path,route:inference.route,url:inference.url}),redirect=(url,status=302)=>Response.redirect(url,status),ELYSIA_FORM_DATA=Symbol("ElysiaFormData"),ELYSIA_REQUEST_ID=Symbol("ElysiaRequestId"),form=(items)=>{let formData=new FormData;if(formData[ELYSIA_FORM_DATA]={},items)for(let[key,value]of Object.entries(items)){if(Array.isArray(value)){formData[ELYSIA_FORM_DATA][key]=[];for(let v of value){if(value instanceof File)formData.append(key,value,value.name);else if(value instanceof ElysiaFile)formData.append(key,value.value,value.value?.name);else formData.append(key,value);formData[ELYSIA_FORM_DATA][key].push(value)}continue}if(value instanceof File)formData.append(key,value,value.name);else if(value instanceof ElysiaFile)formData.append(key,value.value,value.value?.name);else formData.append(key,value);formData[ELYSIA_FORM_DATA][key]=value}return formData},randomId=()=>{let uuid=crypto.randomUUID();return uuid.slice(0,8)+uuid.slice(24,32)},deduplicateChecksum=(array)=>{if(!array.length)return[];let hashes=[];for(let i=0;i<array.length;i++){let item=array[i];if(item.checksum){if(hashes.includes(item.checksum))array.splice(i,1),i--;hashes.push(item.checksum)}}return array},promoteEvent=(events,as="scoped")=>{if(!events)return;if(as==="scoped"){for(let event of events)if("scope"in event&&event.scope==="local")event.scope="scoped";return}for(let event of events)if("scope"in event)event.scope="global"},getLoosePath=(path)=>{if(path.charCodeAt(path.length-1)===47)return path.slice(0,path.length-1);return path+"/"},isNotEmpty=(obj)=>{if(!obj)return!1;for(let _2 in obj)return!0;return!1},encodePath=(path,{dynamic=!1}={})=>{let encoded=encodeURIComponent(path).replace(/%2F/g,"/");if(dynamic)encoded=encoded.replace(/%3A/g,":").replace(/%3F/g,"?");return encoded},supportPerMethodInlineHandler=(()=>{if(typeof Bun==="undefined")return!0;let semver=Bun.version.split(".");if(+semver[0]<1||+semver[1]<2||+semver[2]<14)return!1;return!0})(),sse=(_payload)=>{if(_payload instanceof ReadableStream)return _payload.sse=!0,_payload;let payload=typeof _payload==="string"?{data:_payload}:_payload;return payload.sse=!0,payload.toSSE=()=>{let payloadString="";if(payload.id!==void 0&&payload.id!==null)payloadString+=`id: ${payload.id}
2
+ var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;var __toESM=(mod,isNodeMode,target)=>{target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:()=>mod[key],enumerable:!0});return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __require=import.meta.require;var require_fast_decode_uri_component=__commonJS((exports,module)=>{var UTF8_ACCEPT=12,UTF8_REJECT=0,UTF8_DATA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7];function decodeURIComponent2(uri){var percentPosition=uri.indexOf("%");if(percentPosition===-1)return uri;var length=uri.length,decoded="",last=0,codepoint=0,startOfOctets=percentPosition,state=UTF8_ACCEPT;while(percentPosition>-1&&percentPosition<length){var high=hexCodeToInt(uri[percentPosition+1],4),low=hexCodeToInt(uri[percentPosition+2],0),byte=high|low,type=UTF8_DATA[byte];if(state=UTF8_DATA[256+state+type],codepoint=codepoint<<6|byte&UTF8_DATA[364+type],state===UTF8_ACCEPT)decoded+=uri.slice(last,startOfOctets),decoded+=codepoint<=65535?String.fromCharCode(codepoint):String.fromCharCode(55232+(codepoint>>10),56320+(codepoint&1023)),codepoint=0,last=percentPosition+3,percentPosition=startOfOctets=uri.indexOf("%",last);else if(state===UTF8_REJECT)return null;else{if(percentPosition+=3,percentPosition<length&&uri.charCodeAt(percentPosition)===37)continue;return null}}return decoded+uri.slice(last)}var HEX={"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};function hexCodeToInt(c,shift){var i=HEX[c];return i===void 0?255:i<<shift}module.exports=decodeURIComponent2});var require_dist=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.parse=parse;exports.serialize=serialize;var cookieNameRegExp=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,cookieValueRegExp=/^[\u0021-\u003A\u003C-\u007E]*$/,domainValueRegExp=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,pathValueRegExp=/^[\u0020-\u003A\u003D-\u007E]*$/,__toString=Object.prototype.toString,NullObject=(()=>{let C=function(){};return C.prototype=Object.create(null),C})();function parse(str,options){let obj=new NullObject,len=str.length;if(len<2)return obj;let dec=options?.decode||decode,index=0;do{let eqIdx=str.indexOf("=",index);if(eqIdx===-1)break;let colonIdx=str.indexOf(";",index),endIdx=colonIdx===-1?len:colonIdx;if(eqIdx>endIdx){index=str.lastIndexOf(";",eqIdx-1)+1;continue}let keyStartIdx=startIndex(str,index,eqIdx),keyEndIdx=endIndex(str,eqIdx,keyStartIdx),key=str.slice(keyStartIdx,keyEndIdx);if(obj[key]===void 0){let valStartIdx=startIndex(str,eqIdx+1,endIdx),valEndIdx=endIndex(str,endIdx,valStartIdx),value=dec(str.slice(valStartIdx,valEndIdx));obj[key]=value}index=endIdx+1}while(index<len);return obj}function startIndex(str,index,max){do{let code=str.charCodeAt(index);if(code!==32&&code!==9)return index}while(++index<max);return max}function endIndex(str,index,min){while(index>min){let code=str.charCodeAt(--index);if(code!==32&&code!==9)return index+1}return min}function serialize(name,val,options){let enc=options?.encode||encodeURIComponent;if(!cookieNameRegExp.test(name))throw new TypeError(`argument name is invalid: ${name}`);let value=enc(val);if(!cookieValueRegExp.test(value))throw new TypeError(`argument val is invalid: ${val}`);let str=name+"="+value;if(!options)return str;if(options.maxAge!==void 0){if(!Number.isInteger(options.maxAge))throw new TypeError(`option maxAge is invalid: ${options.maxAge}`);str+="; Max-Age="+options.maxAge}if(options.domain){if(!domainValueRegExp.test(options.domain))throw new TypeError(`option domain is invalid: ${options.domain}`);str+="; Domain="+options.domain}if(options.path){if(!pathValueRegExp.test(options.path))throw new TypeError(`option path is invalid: ${options.path}`);str+="; Path="+options.path}if(options.expires){if(!isDate(options.expires)||!Number.isFinite(options.expires.valueOf()))throw new TypeError(`option expires is invalid: ${options.expires}`);str+="; Expires="+options.expires.toUTCString()}if(options.httpOnly)str+="; HttpOnly";if(options.secure)str+="; Secure";if(options.partitioned)str+="; Partitioned";if(options.priority)switch(typeof options.priority==="string"?options.priority.toLowerCase():void 0){case"low":str+="; Priority=Low";break;case"medium":str+="; Priority=Medium";break;case"high":str+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${options.priority}`)}if(options.sameSite)switch(typeof options.sameSite==="string"?options.sameSite.toLowerCase():options.sameSite){case!0:case"strict":str+="; SameSite=Strict";break;case"lax":str+="; SameSite=Lax";break;case"none":str+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${options.sameSite}`)}return str}function decode(str){if(str.indexOf("%")===-1)return str;try{return decodeURIComponent(str)}catch(e){return str}}function isDate(val){return __toString.call(val)==="[object Date]"}});var Y=(v,b)=>{let A=b?.length?{}:null;if(A)for(let Q of b)A[Q.part.charCodeAt(0)]=Q;return{part:v,store:null,inert:A,params:null,wildcardStore:null}},k=(v,b)=>({...v,part:b}),T=(v)=>({name:v,store:null,inert:null});class _{config;root={};history=[];deferred=[];constructor(v={}){if(this.config=v,v.lazy)this.find=this.lazyFind;if(v.onParam&&!Array.isArray(v.onParam))this.config.onParam=[this.config.onParam]}static regex={static:/:.+?(?=\/|$)/,params:/:.+?(?=\/|$)/g,optionalParams:/(\/:\w+\?)/g};lazyFind=(v,b)=>{if(!this.config.lazy)return this.find;return this.build(),this.find(v,b)};build(){if(!this.config.lazy)return;for(let[v,b,A]of this.deferred)this.add(v,b,A,{lazy:!1,ignoreHistory:!0});this.deferred=[],this.find=(v,b)=>{let A=this.root[v];if(!A)return null;return $(b,b.length,A,0,this.config.onParam)}}add(v,b,A,{ignoreError:Q=!1,ignoreHistory:O=!1,lazy:V=this.config.lazy}={}){if(V)return this.find=this.lazyFind,this.deferred.push([v,b,A]),A;if(typeof b!=="string")throw new TypeError("Route path must be a string");if(b==="")b="/";else if(b[0]!=="/")b=`/${b}`;let X=b[b.length-1]==="*",J=b.match(_.regex.optionalParams);if(J){let F=b.replaceAll("?","");this.add(v,F,A,{ignoreError:Q,ignoreHistory:O,lazy:V});for(let B=0;B<J.length;B++){let D=b.replace(J[B],"");this.add(v,D,A,{ignoreError:!0,ignoreHistory:O,lazy:V})}return A}if(J)b=b.replaceAll("?","");if(this.history.find(([F,B,D])=>F===v&&B===b))return A;if(X||J&&b.charCodeAt(b.length-1)===63)b=b.slice(0,-1);if(!O)this.history.push([v,b,A]);let K=b.split(_.regex.static),G=b.match(_.regex.params)||[];if(K[K.length-1]==="")K.pop();let q;if(!this.root[v])q=this.root[v]=Y("/");else q=this.root[v];let U=0;for(let F=0;F<K.length;++F){let B=K[F];if(F>0){let D=G[U++].slice(1);if(q.params===null)q.params=T(D);else if(q.params.name!==D)if(Q)return A;else throw new Error(`Cannot create route "${b}" with parameter "${D}" because a route already exists with a different parameter name ("${q.params.name}") in the same location`);let S=q.params;if(S.inert===null){q=S.inert=Y(B);continue}q=S.inert}for(let D=0;;){if(D===B.length){if(D<q.part.length){let S=k(q,q.part.slice(D));Object.assign(q,Y(B,[S]))}break}if(D===q.part.length){if(q.inert===null)q.inert={};let S=q.inert[B.charCodeAt(D)];if(S){q=S,B=B.slice(D),D=0;continue}let Z=Y(B.slice(D));q.inert[B.charCodeAt(D)]=Z,q=Z;break}if(B[D]!==q.part[D]){let S=k(q,q.part.slice(D)),Z=Y(B.slice(D));Object.assign(q,Y(q.part.slice(0,D),[S,Z])),q=Z;break}++D}}if(U<G.length){let B=G[U].slice(1);if(q.params===null)q.params=T(B);else if(q.params.name!==B)if(Q)return A;else throw new Error(`Cannot create route "${b}" with parameter "${B}" because a route already exists with a different parameter name ("${q.params.name}") in the same location`);if(q.params.store===null)q.params.store=A;return q.params.store}if(X){if(q.wildcardStore===null)q.wildcardStore=A;return q.wildcardStore}if(q.store===null)q.store=A;return q.store}find(v,b){let A=this.root[v];if(!A)return null;return $(b,b.length,A,0,this.config.onParam)}}var $=(v,b,A,Q,O)=>{let V=A.part,X=V.length,J=Q+X;if(X>1){if(J>b)return null;if(X<15){for(let K=1,G=Q+1;K<X;++K,++G)if(V.charCodeAt(K)!==v.charCodeAt(G))return null}else if(v.slice(Q,J)!==V)return null}if(J===b){if(A.store!==null)return{store:A.store,params:{}};if(A.wildcardStore!==null)return{store:A.wildcardStore,params:{"*":""}};return null}if(A.inert!==null){let K=A.inert[v.charCodeAt(J)];if(K!==void 0){let G=$(v,b,K,J,O);if(G!==null)return G}}if(A.params!==null){let{store:K,name:G,inert:q}=A.params,U=v.indexOf("/",J);if(U!==J){if(U===-1||U>=b){if(K!==null){let F={};if(F[G]=v.substring(J,b),O)for(let B=0;B<O.length;B++){let D=O[B](F[G],G);if(D!==void 0)F[G]=D}return{store:K,params:F}}}else if(q!==null){let F=$(v,b,q,U,O);if(F!==null){if(F.params[G]=v.substring(J,U),O)for(let B=0;B<O.length;B++){let D=O[B](F.params[G],G);if(D!==void 0)F.params[G]=D}return F}}}}if(A.wildcardStore!==null)return{store:A.wildcardStore,params:{"*":v.substring(J,b)}};return null};var import_fast_decode_uri_component4=__toESM(require_fast_decode_uri_component(),1);import{Kind as Kind6}from"@sinclair/typebox";import{Type,Kind as Kind2}from"@sinclair/typebox";import{FormatRegistry}from"@sinclair/typebox";var fullFormats={date,time:getTime(!0),"date-time":getDateTime(!0),"iso-time":getTime(!1),"iso-date-time":getDateTime(!1),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:!0,binary:!0};function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date(str){let matches=DATE.exec(str);if(!matches)return!1;let year=+matches[1],month=+matches[2],day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}var TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function time(str){let matches=TIME.exec(str);if(!matches)return!1;let hr=+matches[1],min=+matches[2],sec=+matches[3],tz=matches[4],tzSign=matches[5]==="-"?-1:1,tzH=+(matches[6]||0),tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return!1;if(hr<=23&&min<=59&&sec<60)return!0;let utcMin=min-tzM*tzSign,utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}var parseDateTimeEmptySpace=(str)=>{if(str.charCodeAt(str.length-6)===32)return str.slice(0,-6)+"+"+str.slice(-5);return str},DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){let time=getTime(strictTimeZone);return function date_time(str){let dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date(dateTime[0])&&time(dateTime[1])}}var NOT_URI_FRAGMENT=/\/|:/,URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}var BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str){return BYTE.lastIndex=0,BYTE.test(str)}var MIN_INT32=-2147483648,MAX_INT32=2147483647;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return!0}var Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return!1;try{return new RegExp(str),!0}catch(e){return!1}}var isISO8601=/(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/,isFormalDate=/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT(?:\+|-)\d{4}\s\([^)]+\)/,isShortenDate=/^(?:(?:(?:(?:0?[1-9]|[12][0-9]|3[01])[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:19|20)\d{2})|(?:(?:19|20)\d{2}[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:0?[1-9]|[12][0-9]|3[01]))))(?:\s(?:1[012]|0?[1-9]):[0-5][0-9](?::[0-5][0-9])?(?:\s[AP]M)?)?$/,_validateDate=fullFormats.date,_validateDateTime=fullFormats["date-time"];if(!FormatRegistry.Has("date"))FormatRegistry.Set("date",(value)=>{let temp=parseDateTimeEmptySpace(value).replace(/"/g,"");if(isISO8601.test(temp)||isFormalDate.test(temp)||isShortenDate.test(temp)||_validateDate(temp)){let date2=new Date(temp);if(!Number.isNaN(date2.getTime()))return!0}return!1});if(!FormatRegistry.Has("date-time"))FormatRegistry.Set("date-time",(value)=>{let temp=value.replace(/"/g,"");if(isISO8601.test(temp)||isFormalDate.test(temp)||isShortenDate.test(temp)||_validateDateTime(temp)){let date2=new Date(temp);if(!Number.isNaN(date2.getTime()))return!0}return!1});Object.entries(fullFormats).forEach((formatEntry)=>{let[formatName,formatValue]=formatEntry;if(!FormatRegistry.Has(formatName)){if(formatValue instanceof RegExp)FormatRegistry.Set(formatName,(value)=>formatValue.test(value));else if(typeof formatValue==="function")FormatRegistry.Set(formatName,formatValue)}});if(!FormatRegistry.Has("numeric"))FormatRegistry.Set("numeric",(value)=>!!value&&!isNaN(+value));if(!FormatRegistry.Has("integer"))FormatRegistry.Set("integer",(value)=>!!value&&Number.isInteger(+value));if(!FormatRegistry.Has("boolean"))FormatRegistry.Set("boolean",(value)=>value==="true"||value==="false");if(!FormatRegistry.Has("ObjectString"))FormatRegistry.Set("ObjectString",(value)=>{let start=value.charCodeAt(0);if(start===9||start===10||start===32)start=value.trimStart().charCodeAt(0);if(start!==123&&start!==91)return!1;try{return JSON.parse(value),!0}catch{return!1}});if(!FormatRegistry.Has("ArrayString"))FormatRegistry.Set("ArrayString",(value)=>{let start=value.charCodeAt(0);if(start===9||start===10||start===32)start=value.trimStart().charCodeAt(0);if(start!==123&&start!==91)return!1;try{return JSON.parse(value),!0}catch{return!1}});import{Kind,TypeRegistry,Unsafe}from"@sinclair/typebox";import{Value as Value2}from"@sinclair/typebox/value";import{TypeCompiler}from"@sinclair/typebox/compiler";var isBun=typeof Bun!=="undefined";var mime={aac:"audio/aac",abw:"application/x-abiword",ai:"application/postscript",arc:"application/octet-stream",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",dll:"application/octet-stream",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",mid:"audio/midi",midi:"audio/midi",mp2:"audio/mpeg",mp3:"audio/mpeg",mp4:"video/mp4",mpa:"video/mpeg",mpe:"video/mpeg",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",otf:"font/otf",png:"image/png",pdf:"application/pdf",ppt:"application/vnd.ms-powerpoint",rar:"application/x-rar-compressed",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"application/typescript",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/x-wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.ms-excel",xlsx_OLD:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3gp_DOES_NOT_CONTAIN_VIDEO":"audio/3gpp","3gp2":"video/3gpp2","3gp2_DOES_NOT_CONTAIN_VIDEO":"audio/3gpp2","7z":"application/x-7z-compressed"},getFileExtension=(path)=>{let index=path.lastIndexOf(".");if(index===-1)return"";return path.slice(index+1)},file=(path)=>new ElysiaFile(path),createReadStream,stat;class ElysiaFile{path;value;stats;constructor(path){this.path=path;if(isBun)this.value=Bun.file(path);else if(typeof window!=="undefined")console.warn("Browser environment does not support file");else if(!createReadStream||!stat)try{this.value=import("fs").then((fs)=>{return createReadStream=fs.createReadStream,fs.createReadStream(path)}),this.stats=import("fs/promises").then((fs)=>{return stat=fs.stat,fs.stat(path)})}catch{}else this.value=createReadStream(path),this.stats=stat(path)}get type(){return mime[getFileExtension(this.path)]||"application/octet-stream"}get length(){if(isBun)return this.value.size;return this.stats?.then((x)=>x.size)??0}}import{Value}from"@sinclair/typebox/value";var hasHeaderShorthand="toJSON"in new Headers,replaceUrlPath=(url,pathname)=>{let urlObject=new URL(url);return urlObject.pathname=pathname,urlObject.toString()},isClass=(v)=>typeof v==="function"&&/^\s*class\s+/.test(v.toString())||v.toString&&v.toString().startsWith("[object ")&&v.toString()!=="[object Object]"||isNotEmpty(Object.getPrototypeOf(v)),isObject=(item)=>item&&typeof item==="object"&&!Array.isArray(item),mergeDeep=(target,source,options)=>{let skipKeys=options?.skipKeys,override=options?.override??!0;if(!isObject(target)||!isObject(source))return target;for(let[key,value]of Object.entries(source)){if(skipKeys?.includes(key))continue;if(!isObject(value)||!(key in target)||isClass(value)){if(override||!(key in target))target[key]=value;continue}target[key]=mergeDeep(target[key],value,{skipKeys,override})}return target},mergeCookie=(a,b)=>{let v=mergeDeep(Object.assign({},a),b,{skipKeys:["properties"]});if(v.properties)delete v.properties;return v},mergeObjectArray=(a,b)=>{if(!b)return a;let array=[],checksums=[];if(a){if(!Array.isArray(a))a=[a];for(let item of a)if(array.push(item),item.checksum)checksums.push(item.checksum)}if(b){if(!Array.isArray(b))b=[b];for(let item of b)if(!checksums.includes(item.checksum))array.push(item)}return array},primitiveHooks=["start","request","parse","transform","resolve","beforeHandle","afterHandle","mapResponse","afterResponse","trace","error","stop","body","headers","params","query","response","type","detail"],primitiveHookMap=primitiveHooks.reduce((acc,x)=>(acc[x]=!0,acc),{}),isRecordNumber=(x)=>typeof x==="object"&&Object.keys(x).every((x2)=>!isNaN(+x2)),mergeResponse=(a,b)=>{if(isRecordNumber(a)&&isRecordNumber(b))return Object.assign({},a,b);else if(a&&!isRecordNumber(a)&&isRecordNumber(b))return Object.assign({200:a},b);return b??a},mergeSchemaValidator=(a,b)=>{if(!a&&!b)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return{body:b?.body??a?.body,headers:b?.headers??a?.headers,params:b?.params??a?.params,query:b?.query??a?.query,cookie:b?.cookie??a?.cookie,response:mergeResponse(a?.response,b?.response)}},mergeHook=(a,b)=>{if(!Object.values(b).find((x)=>x!==void 0&&x!==null))return{...a};let hook={...a,...b,body:b?.body??a?.body,headers:b?.headers??a?.headers,params:b?.params??a?.params,query:b?.query??a?.query,cookie:b?.cookie??a?.cookie,response:mergeResponse(a?.response,b?.response),type:a?.type||b?.type,detail:mergeDeep(b?.detail??{},a?.detail??{}),parse:mergeObjectArray(a?.parse,b?.parse),transform:mergeObjectArray(a?.transform,b?.transform),beforeHandle:mergeObjectArray(mergeObjectArray(fnToContainer(a?.resolve,"resolve"),a?.beforeHandle),mergeObjectArray(fnToContainer(b.resolve,"resolve"),b?.beforeHandle)),afterHandle:mergeObjectArray(a?.afterHandle,b?.afterHandle),mapResponse:mergeObjectArray(a?.mapResponse,b?.mapResponse),afterResponse:mergeObjectArray(a?.afterResponse,b?.afterResponse),trace:mergeObjectArray(a?.trace,b?.trace),error:mergeObjectArray(a?.error,b?.error)};if(hook.resolve)delete hook.resolve;return hook},lifeCycleToArray=(a)=>{if(a.parse&&!Array.isArray(a.parse))a.parse=[a.parse];if(a.transform&&!Array.isArray(a.transform))a.transform=[a.transform];if(a.afterHandle&&!Array.isArray(a.afterHandle))a.afterHandle=[a.afterHandle];if(a.mapResponse&&!Array.isArray(a.mapResponse))a.mapResponse=[a.mapResponse];if(a.afterResponse&&!Array.isArray(a.afterResponse))a.afterResponse=[a.afterResponse];if(a.trace&&!Array.isArray(a.trace))a.trace=[a.trace];if(a.error&&!Array.isArray(a.error))a.error=[a.error];let beforeHandle=[];if(a.resolve)beforeHandle=fnToContainer(Array.isArray(a.resolve)?a.resolve:[a.resolve],"resolve"),delete a.resolve;if(a.beforeHandle)if(beforeHandle.length)beforeHandle=beforeHandle.concat(Array.isArray(a.beforeHandle)?a.beforeHandle:[a.beforeHandle]);else beforeHandle=Array.isArray(a.beforeHandle)?a.beforeHandle:[a.beforeHandle];if(beforeHandle.length)a.beforeHandle=beforeHandle;return a},isBun2=typeof Bun!=="undefined",hasBunHash=isBun2&&typeof Bun.hash==="function",checksum=(s)=>{if(hasBunHash)return Bun.hash(s);let h=9;for(let i=0;i<s.length;)h=Math.imul(h^s.charCodeAt(i++),387420489);return h=h^h>>>9},injectChecksum=(checksum2,x)=>{if(!x)return;if(!Array.isArray(x)){let fn=x;if(checksum2&&!fn.checksum)fn.checksum=checksum2;if(fn.scope==="scoped")fn.scope="local";return fn}let fns=[...x];for(let fn of fns){if(checksum2&&!fn.checksum)fn.checksum=checksum2;if(fn.scope==="scoped")fn.scope="local"}return fns},mergeLifeCycle=(a,b,checksum2)=>{return{start:mergeObjectArray(a.start,injectChecksum(checksum2,b?.start)),request:mergeObjectArray(a.request,injectChecksum(checksum2,b?.request)),parse:mergeObjectArray(a.parse,injectChecksum(checksum2,b?.parse)),transform:mergeObjectArray(a.transform,injectChecksum(checksum2,b?.transform)),beforeHandle:mergeObjectArray(mergeObjectArray(fnToContainer(a.resolve,"resolve"),a.beforeHandle),injectChecksum(checksum2,mergeObjectArray(fnToContainer(b?.resolve,"resolve"),b?.beforeHandle))),afterHandle:mergeObjectArray(a.afterHandle,injectChecksum(checksum2,b?.afterHandle)),mapResponse:mergeObjectArray(a.mapResponse,injectChecksum(checksum2,b?.mapResponse)),afterResponse:mergeObjectArray(a.afterResponse,injectChecksum(checksum2,b?.afterResponse)),trace:mergeObjectArray(a.trace,injectChecksum(checksum2,b?.trace)),error:mergeObjectArray(a.error,injectChecksum(checksum2,b?.error)),stop:mergeObjectArray(a.stop,injectChecksum(checksum2,b?.stop))}},asHookType=(fn,inject,{skipIfHasType=!1})=>{if(!fn)return fn;if(!Array.isArray(fn)){if(skipIfHasType)fn.scope??=inject;else fn.scope=inject;return fn}for(let x of fn)if(skipIfHasType)x.scope??=inject;else x.scope=inject;return fn},filterGlobal=(fn)=>{if(!fn)return fn;if(!Array.isArray(fn))switch(fn.scope){case"global":case"scoped":return{...fn};default:return{fn}}let array=[];for(let x of fn)switch(x.scope){case"global":case"scoped":array.push({...x});break}return array},filterGlobalHook=(hook)=>{return{...hook,type:hook?.type,detail:hook?.detail,parse:filterGlobal(hook?.parse),transform:filterGlobal(hook?.transform),beforeHandle:filterGlobal(hook?.beforeHandle),afterHandle:filterGlobal(hook?.afterHandle),mapResponse:filterGlobal(hook?.mapResponse),afterResponse:filterGlobal(hook?.afterResponse),error:filterGlobal(hook?.error),trace:filterGlobal(hook?.trace)}},StatusMap={Continue:100,"Switching Protocols":101,Processing:102,"Early Hints":103,OK:200,Created:201,Accepted:202,"Non-Authoritative Information":203,"No Content":204,"Reset Content":205,"Partial Content":206,"Multi-Status":207,"Already Reported":208,"Multiple Choices":300,"Moved Permanently":301,Found:302,"See Other":303,"Not Modified":304,"Temporary Redirect":307,"Permanent Redirect":308,"Bad Request":400,Unauthorized:401,"Payment Required":402,Forbidden:403,"Not Found":404,"Method Not Allowed":405,"Not Acceptable":406,"Proxy Authentication Required":407,"Request Timeout":408,Conflict:409,Gone:410,"Length Required":411,"Precondition Failed":412,"Payload Too Large":413,"URI Too Long":414,"Unsupported Media Type":415,"Range Not Satisfiable":416,"Expectation Failed":417,"I'm a teapot":418,"Misdirected Request":421,"Unprocessable Content":422,Locked:423,"Failed Dependency":424,"Too Early":425,"Upgrade Required":426,"Precondition Required":428,"Too Many Requests":429,"Request Header Fields Too Large":431,"Unavailable For Legal Reasons":451,"Internal Server Error":500,"Not Implemented":501,"Bad Gateway":502,"Service Unavailable":503,"Gateway Timeout":504,"HTTP Version Not Supported":505,"Variant Also Negotiates":506,"Insufficient Storage":507,"Loop Detected":508,"Not Extended":510,"Network Authentication Required":511},InvertedStatusMap=Object.fromEntries(Object.entries(StatusMap).map(([k2,v])=>[v,k2]));function removeTrailingEquals(digest){let trimmedDigest=digest;while(trimmedDigest.endsWith("="))trimmedDigest=trimmedDigest.slice(0,-1);return trimmedDigest}var encoder=new TextEncoder,signCookie=async(val,secret)=>{if(typeof val==="object")val=JSON.stringify(val);else if(typeof val!=="string")val=val+"";if(secret===null)throw new TypeError("Secret key must be provided.");let secretKey=await crypto.subtle.importKey("raw",encoder.encode(secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),hmacBuffer=await crypto.subtle.sign("HMAC",secretKey,encoder.encode(val));return val+"."+removeTrailingEquals(Buffer.from(hmacBuffer).toString("base64"))},unsignCookie=async(input,secret)=>{if(typeof input!=="string")throw new TypeError("Signed cookie string must be provided.");if(secret===null)throw new TypeError("Secret key must be provided.");let tentativeValue=input.slice(0,input.lastIndexOf("."));return await signCookie(tentativeValue,secret)===input?tentativeValue:!1},traceBackMacro=(extension,property,manage)=>{if(!extension||typeof extension!=="object"||!property)return;for(let[key,value]of Object.entries(property)){if(primitiveHookMap[key]||!(key in extension))continue;let v=extension[key];if(typeof v==="function"){let hook=v(value);if(typeof hook==="object")for(let[k2,v2]of Object.entries(hook))manage(k2)({fn:v2})}delete property[key]}},createMacroManager=({globalHook,localHook})=>(stackName)=>(type,fn)=>{if(typeof type==="function")type={fn:type};if(stackName==="resolve")type={...type,subType:"resolve"};if(!localHook[stackName])localHook[stackName]=[];if(typeof localHook[stackName]==="function")localHook[stackName]=[localHook[stackName]];if(!Array.isArray(localHook[stackName]))localHook[stackName]=[localHook[stackName]];if("fn"in type||Array.isArray(type)){if(Array.isArray(type))localHook[stackName]=localHook[stackName].concat(type);else localHook[stackName].push(type);return}let{insert="after",stack="local"}=type;if(typeof fn==="function")fn={fn};if(stack==="global")if(!Array.isArray(fn))if(insert==="before")globalHook[stackName].unshift(fn);else globalHook[stackName].push(fn);else if(insert==="before")globalHook[stackName]=fn.concat(globalHook[stackName]);else globalHook[stackName]=globalHook[stackName].concat(fn);else if(!Array.isArray(fn))if(insert==="before")localHook[stackName].unshift(fn);else localHook[stackName].push(fn);else if(insert==="before")localHook[stackName]=fn.concat(localHook[stackName]);else localHook[stackName]=localHook[stackName].concat(fn)},parseNumericString=(message)=>{if(typeof message==="number")return message;if(message.length<16){if(message.trim().length===0)return null;let length=Number(message);if(Number.isNaN(length))return null;return length}if(message.length===16){if(message.trim().length===0)return null;let number=Number(message);if(Number.isNaN(number)||number.toString()!==message)return null;return number}return null},isNumericString=(message)=>parseNumericString(message)!==null;class PromiseGroup{onError;onFinally;root=null;promises=[];constructor(onError=console.error,onFinally=()=>{}){this.onError=onError;this.onFinally=onFinally}get size(){return this.promises.length}add(promise){if(this.promises.push(promise),this.root||=this.drain(),this.promises.length===1)this.then(this.onFinally);return promise}async drain(){while(this.promises.length>0){try{await this.promises[0]}catch(error){this.onError(error)}this.promises.shift()}this.root=null}then(onfulfilled,onrejected){return(this.root??Promise.resolve()).then(onfulfilled,onrejected)}}var fnToContainer=(fn,subType)=>{if(!fn)return fn;if(!Array.isArray(fn)){if(typeof fn==="function"||typeof fn==="string")return subType?{fn,subType}:{fn};else if("fn"in fn)return fn}let fns=[];for(let x of fn)if(typeof x==="function"||typeof x==="string")fns.push(subType?{fn:x,subType}:{fn:x});else if("fn"in x)fns.push(x);return fns},localHookToLifeCycleStore=(a)=>{if(a.start)a.start=fnToContainer(a.start);if(a.request)a.request=fnToContainer(a.request);if(a.parse)a.parse=fnToContainer(a.parse);if(a.transform)a.transform=fnToContainer(a.transform);if(a.beforeHandle)a.beforeHandle=fnToContainer(a.beforeHandle);if(a.afterHandle)a.afterHandle=fnToContainer(a.afterHandle);if(a.mapResponse)a.mapResponse=fnToContainer(a.mapResponse);if(a.afterResponse)a.afterResponse=fnToContainer(a.afterResponse);if(a.trace)a.trace=fnToContainer(a.trace);if(a.error)a.error=fnToContainer(a.error);if(a.stop)a.stop=fnToContainer(a.stop);return a},lifeCycleToFn=(a)=>{let lifecycle=Object.create(null);if(a.start?.map)lifecycle.start=a.start.map((x)=>x.fn);if(a.request?.map)lifecycle.request=a.request.map((x)=>x.fn);if(a.parse?.map)lifecycle.parse=a.parse.map((x)=>x.fn);if(a.transform?.map)lifecycle.transform=a.transform.map((x)=>x.fn);if(a.beforeHandle?.map)lifecycle.beforeHandle=a.beforeHandle.map((x)=>x.fn);if(a.afterHandle?.map)lifecycle.afterHandle=a.afterHandle.map((x)=>x.fn);if(a.mapResponse?.map)lifecycle.mapResponse=a.mapResponse.map((x)=>x.fn);if(a.afterResponse?.map)lifecycle.afterResponse=a.afterResponse.map((x)=>x.fn);if(a.error?.map)lifecycle.error=a.error.map((x)=>x.fn);if(a.stop?.map)lifecycle.stop=a.stop.map((x)=>x.fn);if(a.trace?.map)lifecycle.trace=a.trace.map((x)=>x.fn);else lifecycle.trace=[];return lifecycle},cloneInference=(inference)=>({body:inference.body,cookie:inference.cookie,headers:inference.headers,query:inference.query,set:inference.set,server:inference.server,path:inference.path,route:inference.route,url:inference.url}),redirect=(url,status=302)=>Response.redirect(url,status),ELYSIA_FORM_DATA=Symbol("ElysiaFormData"),ELYSIA_REQUEST_ID=Symbol("ElysiaRequestId"),form=(items)=>{let formData=new FormData;if(formData[ELYSIA_FORM_DATA]={},items)for(let[key,value]of Object.entries(items)){if(Array.isArray(value)){formData[ELYSIA_FORM_DATA][key]=[];for(let v of value){if(value instanceof File)formData.append(key,value,value.name);else if(value instanceof ElysiaFile)formData.append(key,value.value,value.value?.name);else formData.append(key,value);formData[ELYSIA_FORM_DATA][key].push(value)}continue}if(value instanceof File)formData.append(key,value,value.name);else if(value instanceof ElysiaFile)formData.append(key,value.value,value.value?.name);else formData.append(key,value);formData[ELYSIA_FORM_DATA][key]=value}return formData},randomId=()=>{let uuid=crypto.randomUUID();return uuid.slice(0,8)+uuid.slice(24,32)},deduplicateChecksum=(array)=>{if(!array.length)return[];let hashes=[];for(let i=0;i<array.length;i++){let item=array[i];if(item.checksum){if(hashes.includes(item.checksum))array.splice(i,1),i--;hashes.push(item.checksum)}}return array},promoteEvent=(events,as="scoped")=>{if(!events)return;if(as==="scoped"){for(let event of events)if("scope"in event&&event.scope==="local")event.scope="scoped";return}for(let event of events)if("scope"in event)event.scope="global"},getLoosePath=(path)=>{if(path.charCodeAt(path.length-1)===47)return path.slice(0,path.length-1);return path+"/"},isNotEmpty=(obj)=>{if(!obj)return!1;for(let _2 in obj)return!0;return!1},encodePath=(path,{dynamic=!1}={})=>{let encoded=encodeURIComponent(path).replace(/%2F/g,"/");if(dynamic)encoded=encoded.replace(/%3A/g,":").replace(/%3F/g,"?");return encoded},supportPerMethodInlineHandler=(()=>{if(typeof Bun==="undefined")return!0;let semver=Bun.version.split(".");if(+semver[0]<1||+semver[1]<2||+semver[2]<14)return!1;return!0})(),sse=(_payload)=>{if(_payload instanceof ReadableStream)return _payload.sse=!0,_payload;let payload=typeof _payload==="string"?{data:_payload}:_payload;return payload.sse=!0,payload.toSSE=()=>{let payloadString="";if(payload.id!==void 0&&payload.id!==null)payloadString+=`id: ${payload.id}
3
3
  `;if(payload.event)payloadString+=`event: ${payload.event}
4
4
  `;if(payload.retry!==void 0)payloadString+=`retry: ${payload.retry}
5
5
  `;if(payload.data===null)payloadString+=`data: null
@@ -10,7 +10,7 @@ var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defP
10
10
  `,2),parameter=code.slice(0,sep),end=parameter.lastIndexOf(")")+1,body=code.slice(sep+1);return[parameter.slice(start,end),"{"+body,{isArrowReturn:!1}]}let x=code.split(`
11
11
  `,2);return[x[0],x[1],{isArrowReturn:!1}]},bracketPairRange=(parameter)=>{let start=parameter.indexOf("{");if(start===-1)return[-1,0];let end=start+1,deep=1;for(;end<parameter.length;end++){let char=parameter.charCodeAt(end);if(char===123)deep++;else if(char===125)deep--;if(deep===0)break}if(deep!==0)return[0,parameter.length];return[start,end+1]},bracketPairRangeReverse=(parameter)=>{let end=parameter.lastIndexOf("}");if(end===-1)return[-1,0];let start=end-1,deep=1;for(;start>=0;start--){let char=parameter.charCodeAt(start);if(char===125)deep++;else if(char===123)deep--;if(deep===0)break}if(deep!==0)return[-1,0];return[start,end+1]},removeColonAlias=(parameter)=>{while(!0){let start=parameter.indexOf(":");if(start===-1)break;let end=parameter.indexOf(",",start);if(end===-1)end=parameter.indexOf("}",start)-1;if(end===-2)end=parameter.length;parameter=parameter.slice(0,start)+parameter.slice(end)}return parameter},retrieveRootParamters=(parameter)=>{let hasParenthesis=!1;if(parameter.charCodeAt(0)===40)parameter=parameter.slice(1,-1);if(parameter.charCodeAt(0)===123)hasParenthesis=!0,parameter=parameter.slice(1,-1);parameter=parameter.replace(/( |\t|\n)/g,"").trim();let parameters=[];while(!0){let[start,end]=bracketPairRange(parameter);if(start===-1)break;if(parameters.push(parameter.slice(0,start-1)),parameter.charCodeAt(end)===44)end++;parameter=parameter.slice(end)}if(parameter=removeColonAlias(parameter),parameter)parameters=parameters.concat(parameter.split(","));let parameterMap=Object.create(null);for(let p of parameters){if(p.indexOf(",")===-1){parameterMap[p]=!0;continue}for(let q of p.split(","))parameterMap[q.trim()]=!0}return{hasParenthesis,parameters:parameterMap}},findParameterReference=(parameter,inference)=>{let{parameters,hasParenthesis}=retrieveRootParamters(parameter);if(parameters.query)inference.query=!0;if(parameters.headers)inference.headers=!0;if(parameters.body)inference.body=!0;if(parameters.cookie)inference.cookie=!0;if(parameters.set)inference.set=!0;if(parameters.server)inference.server=!0;if(parameters.route)inference.route=!0;if(parameters.url)inference.url=!0;if(parameters.path)inference.path=!0;if(hasParenthesis)return`{ ${Object.keys(parameters).join(", ")} }`;return Object.keys(parameters).join(", ")},findEndIndex=(type,content,index)=>{let regex2=new RegExp(`${type.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\n\\t,; ]`);if(index!==void 0)regex2.lastIndex=index;let match=regex2.exec(content);return match?match.index:-1};var findAlias=(type,body,depth=0)=>{if(depth>5)return[];let aliases=[],content=body;while(!0){let index=findEndIndex(" = "+type,content);if(index===-1)index=findEndIndex("="+type,content);if(index===-1){let lastIndex=content.indexOf(" = "+type);if(lastIndex===-1)lastIndex=content.indexOf("="+type);if(lastIndex+3+type.length!==content.length)break;index=lastIndex}let part=content.slice(0,index),lastPart=part.lastIndexOf(" "),variable=part.slice(lastPart!==-1?lastPart+1:-1);if(variable==="}"){let[start,end]=bracketPairRangeReverse(part);aliases.push(removeColonAlias(content.slice(start,end))),content=content.slice(index+3+type.length);continue}while(variable.charCodeAt(0)===44)variable=variable.slice(1);while(variable.charCodeAt(0)===9)variable=variable.slice(1);if(!variable.includes("("))aliases.push(variable);content=content.slice(index+3+type.length)}for(let alias of aliases){if(alias.charCodeAt(0)===123)continue;let deepAlias=findAlias(alias,body);if(deepAlias.length>0)aliases.push(...deepAlias)}return aliases},extractMainParameter=(parameter)=>{if(!parameter)return;if(parameter.charCodeAt(0)!==123)return parameter;if(parameter=parameter.slice(2,-2),!parameter.includes(",")){if(parameter.indexOf("...")!==-1)return parameter.slice(parameter.indexOf("...")+3);return}let spreadIndex=parameter.indexOf("...");if(spreadIndex===-1)return;return parameter.slice(spreadIndex+3).trimEnd()},inferBodyReference=(code,aliases,inference)=>{let access=(type,alias)=>new RegExp(`${alias}\\.(${type})|${alias}\\["${type}"\\]|${alias}\\['${type}'\\]`).test(code);for(let alias of aliases){if(!alias)continue;if(alias.charCodeAt(0)===123){let parameters=retrieveRootParamters(alias).parameters;if(parameters.query)inference.query=!0;if(parameters.headers)inference.headers=!0;if(parameters.body)inference.body=!0;if(parameters.cookie)inference.cookie=!0;if(parameters.set)inference.set=!0;if(parameters.server)inference.server=!0;if(parameters.url)inference.url=!0;if(parameters.route)inference.route=!0;if(parameters.path)inference.path=!0;continue}if(!inference.query&&(access("query",alias)||code.includes("return "+alias)||code.includes("return "+alias+".query")))inference.query=!0;if(!inference.headers&&access("headers",alias))inference.headers=!0;if(!inference.body&&access("body",alias))inference.body=!0;if(!inference.cookie&&access("cookie",alias))inference.cookie=!0;if(!inference.set&&access("set",alias))inference.set=!0;if(!inference.server&&access("server",alias))inference.server=!0;if(!inference.route&&access("route",alias))inference.route=!0;if(!inference.url&&access("url",alias))inference.url=!0;if(!inference.path&&access("path",alias))inference.path=!0;if(inference.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server&&inference.route&&inference.url&&inference.path)break}return aliases};var isContextPassToFunction=(context,body,inference)=>{try{let captureFunction=new RegExp(`\\w\\((.*?)?${context}`,"gs");captureFunction.test(body);let nextChar=body.charCodeAt(captureFunction.lastIndex);if(nextChar===41||nextChar===44)return inference.query=!0,inference.headers=!0,inference.body=!0,inference.cookie=!0,inference.set=!0,inference.server=!0,inference.url=!0,inference.route=!0,inference.path=!0,!0;return!1}catch(error2){return console.log("[Sucrose] warning: unexpected isContextPassToFunction error, you may continue development as usual but please report the following to maintainers:"),console.log("--- body ---"),console.log(body),console.log("--- context ---"),console.log(context),!0}},pendingGC,caches={},clearSucroseCache=(delay=0)=>{if(pendingGC)clearTimeout(pendingGC);pendingGC=setTimeout(()=>{if(caches={},pendingGC=void 0,isBun)Bun.gc(!1)},delay)},mergeInference=(a,b)=>{return{body:a.body||b.body,cookie:a.cookie||b.cookie,headers:a.headers||b.headers,query:a.query||b.query,set:a.set||b.set,server:a.server||b.server,url:a.url||b.url,route:a.route||b.route,path:a.path||b.path}},sucrose=(lifeCycle,inference={query:!1,headers:!1,body:!1,cookie:!1,set:!1,server:!1,url:!1,route:!1,path:!1})=>{let events=[];if(lifeCycle.request?.length)events.push(...lifeCycle.request);if(lifeCycle.beforeHandle?.length)events.push(...lifeCycle.beforeHandle);if(lifeCycle.parse?.length)events.push(...lifeCycle.parse);if(lifeCycle.error?.length)events.push(...lifeCycle.error);if(lifeCycle.transform?.length)events.push(...lifeCycle.transform);if(lifeCycle.afterHandle?.length)events.push(...lifeCycle.afterHandle);if(lifeCycle.mapResponse?.length)events.push(...lifeCycle.mapResponse);if(lifeCycle.afterResponse?.length)events.push(...lifeCycle.afterResponse);if(lifeCycle.handler&&typeof lifeCycle.handler==="function")events.push(lifeCycle.handler);for(let i=0;i<events.length;i++){let e=events[i];if(!e)continue;let event=typeof e==="object"?e.fn:e;if(typeof event!=="function")continue;let content=event.toString(),key=checksum(content),cachedInference=caches[key];if(cachedInference){inference=mergeInference(inference,cachedInference);continue}let fnInference={query:!1,headers:!1,body:!1,cookie:!1,set:!1,server:!1,url:!1,route:!1,path:!1},[parameter,body]=separateFunction(content),rootParameters=findParameterReference(parameter,fnInference),mainParameter=extractMainParameter(rootParameters);if(mainParameter){let aliases=findAlias(mainParameter,body.slice(1,-1));aliases.splice(0,-1,mainParameter);let code=body;if(code.charCodeAt(0)===123&&code.charCodeAt(body.length-1)===125)code=code.slice(1,-1);if(!isContextPassToFunction(mainParameter,code,fnInference))inferBodyReference(code,aliases,fnInference);if(!fnInference.query&&code.includes("return "+mainParameter+".query"))fnInference.query=!0}if(!caches[key])caches[key]=fnInference;if(inference=mergeInference(inference,fnInference),inference.query&&inference.headers&&inference.body&&inference.cookie&&inference.set&&inference.server&&inference.url&&inference.route&&inference.path)break}return inference};var import_cookie=__toESM(require_dist(),1),import_fast_decode_uri_component=__toESM(require_fast_decode_uri_component(),1);class Cookie{name;jar;initial;constructor(name,jar,initial={}){this.name=name;this.jar=jar;this.initial=initial}get cookie(){return this.jar[this.name]??this.initial}set cookie(jar){if(!(this.name in this.jar))this.jar[this.name]=this.initial;this.jar[this.name]=jar}get setCookie(){if(!(this.name in this.jar))this.jar[this.name]=this.initial;return this.jar[this.name]}set setCookie(jar){this.cookie=jar}get value(){return this.cookie.value}set value(value){this.setCookie.value=value}get expires(){return this.cookie.expires}set expires(expires){this.setCookie.expires=expires}get maxAge(){return this.cookie.maxAge}set maxAge(maxAge){this.setCookie.maxAge=maxAge}get domain(){return this.cookie.domain}set domain(domain){this.setCookie.domain=domain}get path(){return this.cookie.path}set path(path){this.setCookie.path=path}get secure(){return this.cookie.secure}set secure(secure){this.setCookie.secure=secure}get httpOnly(){return this.cookie.httpOnly}set httpOnly(httpOnly){this.setCookie.httpOnly=httpOnly}get sameSite(){return this.cookie.sameSite}set sameSite(sameSite){this.setCookie.sameSite=sameSite}get priority(){return this.cookie.priority}set priority(priority){this.setCookie.priority=priority}get partitioned(){return this.cookie.partitioned}set partitioned(partitioned){this.setCookie.partitioned=partitioned}get secrets(){return this.cookie.secrets}set secrets(secrets){this.setCookie.secrets=secrets}update(config){return this.setCookie=Object.assign(this.cookie,typeof config==="function"?config(this.cookie):config),this}set(config){return this.setCookie=Object.assign({...this.initial,value:this.value},typeof config==="function"?config(this.cookie):config),this}remove(){if(this.value===void 0)return;return this.set({expires:new Date(0),maxAge:0,value:""}),this}toString(){return typeof this.value==="object"?JSON.stringify(this.value):this.value?.toString()??""}}var createCookieJar=(set2,store,initial)=>{if(!set2.cookie)set2.cookie={};return new Proxy(store,{get(_2,key){if(key in store)return new Cookie(key,set2.cookie,Object.assign({},initial??{},store[key]));return new Cookie(key,set2.cookie,Object.assign({},initial))}})},parseCookie=async(set2,cookieString,{secrets,sign,...initial}={})=>{if(!cookieString)return createCookieJar(set2,{},initial);let isStringKey=typeof secrets==="string";if(sign&&sign!==!0&&!Array.isArray(sign))sign=[sign];let jar={},cookies=import_cookie.parse(cookieString);for(let[name,v]of Object.entries(cookies)){if(v===void 0)continue;let value=import_fast_decode_uri_component.default(v);if(sign===!0||sign?.includes(name)){if(!secrets)throw new Error("No secret is provided to cookie plugin");if(isStringKey){let temp=await unsignCookie(value,secrets);if(temp===!1)throw new InvalidCookieSignature(name);value=temp}else{let decoded=!0;for(let i=0;i<secrets.length;i++){let temp=await unsignCookie(value,secrets[i]);if(temp!==!1){decoded=!0,value=temp;break}}if(!decoded)throw new InvalidCookieSignature(name)}}jar[name]={value}}return createCookieJar(set2,jar,initial)},serializeCookie=(cookies)=>{if(!cookies||!isNotEmpty(cookies))return;let set2=[];for(let[key,property]of Object.entries(cookies)){if(!key||!property)continue;let value=property.value;if(value===void 0||value===null)continue;set2.push(import_cookie.serialize(key,typeof value==="object"?JSON.stringify(value):value+"",property))}if(set2.length===0)return;if(set2.length===1)return set2[0];return set2};var handleFile=(response,set2)=>{if(!isBun&&response instanceof Promise)return response.then((res)=>handleFile(res,set2));let size=response.size,immutable=set2&&(set2.status===206||set2.status===304||set2.status===412||set2.status===416),defaultHeader=immutable?{"transfer-encoding":"chunked"}:{"accept-ranges":"bytes","content-range":size?`bytes 0-${size-1}/${size}`:void 0,"transfer-encoding":"chunked"};if(!set2&&!size)return new Response(response);if(!set2)return new Response(response,{headers:defaultHeader});if(set2.headers instanceof Headers){for(let key of Object.keys(defaultHeader))if(key in set2.headers)set2.headers.append(key,defaultHeader[key]);if(immutable)set2.headers.delete("content-length"),set2.headers.delete("accept-ranges");return new Response(response,set2)}if(isNotEmpty(set2.headers))return new Response(response,{status:set2.status,headers:Object.assign(defaultHeader,set2.headers)});return new Response(response,{status:set2.status,headers:defaultHeader})},parseSetCookies=(headers,setCookie)=>{if(!headers)return headers;headers.delete("set-cookie");for(let i=0;i<setCookie.length;i++){let index=setCookie[i].indexOf("=");headers.append("set-cookie",`${setCookie[i].slice(0,index)}=${setCookie[i].slice(index+1)||""}`)}return headers},responseToSetHeaders=(response,set2)=>{if(set2?.headers){if(response){if(hasHeaderShorthand)Object.assign(set2.headers,response.headers.toJSON());else for(let[key,value]of response.headers.entries())if(key in set2.headers)set2.headers[key]=value}if(set2.status===200)set2.status=response.status;if(set2.headers["content-encoding"])delete set2.headers["content-encoding"];return set2}if(!response)return{headers:{},status:set2?.status??200};if(hasHeaderShorthand){if(set2={headers:response.headers.toJSON(),status:set2?.status??200},set2.headers["content-encoding"])delete set2.headers["content-encoding"];return set2}set2={headers:{},status:set2?.status??200};for(let[key,value]of response.headers.entries()){if(key==="content-encoding")continue;if(key in set2.headers)set2.headers[key]=value}return set2},createStreamHandler=({mapResponse,mapCompactResponse})=>async(generator,set2,request)=>{let init=generator.next?.();if(init instanceof Promise)init=await init;if(init?.value instanceof ReadableStream)generator=init.value;else if(init&&(typeof init?.done==="undefined"||init?.done)){if(set2)return mapResponse(init.value,set2,request);return mapCompactResponse(init.value,request)}let isSSE=init?.value?.sse??generator?.sse??set2?.headers["content-type"]?.startsWith("text/event-stream"),format=isSSE?(data)=>`data: ${data}
12
12
 
13
- `:(data)=>data,contentType=isSSE?"text/event-stream":init?.value&&typeof init?.value==="object"?"application/json":"text/plain";if(set2?.headers){if(!set2.headers["transfer-encoding"])set2.headers["transfer-encoding"]="chunked";if(!set2.headers["content-type"])set2.headers["content-type"]=contentType;if(!set2.headers["cache-control"])set2.headers["cache-control"]="no-cache"}else set2={status:200,headers:{"content-type":contentType,"transfer-encoding":"chunked","cache-control":"no-cache",connection:"keep-alive"}};return new Response(new ReadableStream({async start(controller){let end=!1;if(request?.signal?.addEventListener("abort",()=>{end=!0;try{controller.close()}catch{}}),!init||init.value instanceof ReadableStream);else if(init.value!==void 0&&init.value!==null)if(init.value.toSSE)controller.enqueue(init.value.toSSE());else if(typeof init.value==="object")try{controller.enqueue(format(JSON.stringify(init.value)))}catch{controller.enqueue(format(init.value.toString()))}else controller.enqueue(format(init.value.toString()));try{for await(let chunk of generator){if(end)break;if(chunk===void 0||chunk===null)continue;if(chunk.toSSE)controller.enqueue(chunk.toSSE());else if(typeof chunk==="object")try{controller.enqueue(format(JSON.stringify(chunk)))}catch{controller.enqueue(format(chunk.toString()))}else controller.enqueue(format(chunk.toString()));await new Promise((resolve)=>setTimeout(()=>resolve(),0))}}catch(error2){console.warn(error2)}try{controller.close()}catch{}}}),set2)};async function*streamResponse(response){let body=response.body;if(!body)return;let reader=body.getReader(),decoder=new TextDecoder;try{while(!0){let{done,value}=await reader.read();if(done)break;if(typeof value==="string")yield value;else yield decoder.decode(value)}}finally{reader.releaseLock()}}var handleSet=(set2)=>{if(typeof set2.status==="string")set2.status=StatusMap[set2.status];if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"])},createResponseHandler=(handler)=>{let handleStream=createStreamHandler(handler);return(response,set2,request)=>{let isCookieSet=!1;if(set2.headers instanceof Headers)for(let key of set2.headers.keys())if(key==="set-cookie"){if(isCookieSet)continue;isCookieSet=!0;for(let cookie of set2.headers.getSetCookie())response.headers.append("set-cookie",cookie)}else response.headers.append(key,set2.headers?.get(key)??"");else for(let key in set2.headers)response.headers.append(key,set2.headers[key]);let status2=set2.status??200;if(response.status!==status2&&status2!==200&&(response.status<=300||response.status>400))return response.text().then((value)=>{let newResponse=new Response(value,{headers:response.headers,status:set2.status});if(!newResponse.headers.has("content-length")&&newResponse.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(newResponse),responseToSetHeaders(newResponse,set2),request);return newResponse});if(!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);return response}};var handleElysiaFile=(file2,set2={headers:{}})=>{let path=file2.path,contentType=mime[path.slice(path.lastIndexOf(".")+1)];if(contentType)set2.headers["content-type"]=contentType;if(file2.stats&&set2.status!==206&&set2.status!==304&&set2.status!==412&&set2.status!==416)return file2.stats.then((stat2)=>{let size=stat2.size;if(size!==void 0)set2.headers["content-range"]=`bytes 0-${size-1}/${size}`,set2.headers["content-length"]=size;return handleFile(file2.value,set2)});return handleFile(file2.value,set2)},mapResponse=(response,set2,request)=>{if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return set2.headers["content-type"]="text/plain",new Response(response,set2);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleElysiaFile(response,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapResponse(response.response,set2,request);case void 0:if(!response)return new Response("",set2);return new Response(JSON.stringify(response),set2);case"Response":return handleResponse(response,set2,request);case"Error":return errorToResponse(response,set2);case"Promise":return response.then((x)=>mapResponse(x,set2,request));case"Function":return mapResponse(response(),set2,request);case"Number":case"Boolean":return new Response(response.toString(),set2);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response,set2);default:if(response instanceof Response)return handleResponse(response,set2,request);if(response instanceof Promise)return response.then((x)=>mapResponse(x,set2));if(response instanceof Error)return errorToResponse(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapResponse(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse(x,set2));if(typeof response?.toResponse==="function")return mapResponse(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response,set2)}if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);return mapCompactResponse(response,request)},mapEarlyResponse=(response,set2,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return set2.headers["content-type"]="text/plain",new Response(response,set2);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleElysiaFile(response,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse(response.response,set2,request);case void 0:if(!response)return;return new Response(JSON.stringify(response),set2);case"Response":return handleResponse(response,set2,request);case"Promise":return response.then((x)=>mapEarlyResponse(x,set2));case"Error":return errorToResponse(response,set2);case"Function":return mapEarlyResponse(response(),set2);case"Number":case"Boolean":return new Response(response.toString(),set2);case"FormData":return new Response(response);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);default:if(response instanceof Response)return handleResponse(response,set2,request);if(response instanceof Promise)return response.then((x)=>mapEarlyResponse(x,set2));if(response instanceof Error)return errorToResponse(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapEarlyResponse(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse(x,set2));if(typeof response?.toResponse==="function")return mapEarlyResponse(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response,set2)}else switch(response?.constructor?.name){case"String":return set2.headers["content-type"]="text/plain",new Response(response);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleElysiaFile(response,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse(response.response,set2,request);case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Promise":return response.then((x)=>{let r=mapEarlyResponse(x,set2);if(r!==void 0)return r});case"Error":return errorToResponse(response,set2);case"Function":return mapCompactResponse(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapEarlyResponse(x,set2));if(response instanceof Error)return errorToResponse(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapEarlyResponse(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse(x,set2));if(typeof response?.toResponse==="function")return mapEarlyResponse(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response)}},mapCompactResponse=(response,request)=>{switch(response?.constructor?.name){case"String":return new Response(response,{headers:{"Content-Type":"text/plain"}});case"Object":case"Array":return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}});case"ElysiaFile":return handleElysiaFile(response);case"File":return handleFile(response);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse(response.response,{status:response.code,headers:{}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Error":return errorToResponse(response);case"Promise":return response.then((x)=>mapCompactResponse(x,request));case"Function":return mapCompactResponse(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapCompactResponse(x,request));if(response instanceof Error)return errorToResponse(response);if(response instanceof ElysiaCustomStatusResponse)return mapResponse(response.response,{status:response.code,headers:{}});if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,void 0,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse(x,set));if(typeof response?.toResponse==="function")return mapCompactResponse(response.toResponse());if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91)return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}})}return new Response(response)}},errorToResponse=(error2,set2)=>new Response(JSON.stringify({name:error2?.name,message:error2?.message,cause:error2?.cause}),{status:set2?.status!==200?set2?.status??500:500,headers:set2?.headers}),createStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function")return;let response=mapResponse(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length)return()=>response.clone()},handleResponse=createResponseHandler({mapResponse,mapCompactResponse}),handleStream=createStreamHandler({mapResponse,mapCompactResponse});var WebStandardAdapter={name:"web-standard",isWebStandard:!0,handler:{mapResponse,mapEarlyResponse,mapCompactResponse,createStaticHandler},composeHandler:{mapResponseContext:"c.request",preferWebstandardHeaders:!0,headers:`c.headers={}
13
+ `:(data)=>data,contentType=isSSE?"text/event-stream":init?.value&&typeof init?.value==="object"?"application/json":"text/plain";if(set2?.headers){if(!set2.headers["transfer-encoding"])set2.headers["transfer-encoding"]="chunked";if(!set2.headers["content-type"])set2.headers["content-type"]=contentType;if(!set2.headers["cache-control"])set2.headers["cache-control"]="no-cache"}else set2={status:200,headers:{"content-type":contentType,"transfer-encoding":"chunked","cache-control":"no-cache",connection:"keep-alive"}};return new Response(new ReadableStream({async start(controller){let end=!1;if(request?.signal?.addEventListener("abort",()=>{end=!0;try{controller.close()}catch{}}),!init||init.value instanceof ReadableStream);else if(init.value!==void 0&&init.value!==null)if(init.value.toSSE)controller.enqueue(init.value.toSSE());else if(typeof init.value==="object")try{controller.enqueue(format(JSON.stringify(init.value)))}catch{controller.enqueue(format(init.value.toString()))}else controller.enqueue(format(init.value.toString()));try{for await(let chunk of generator){if(end)break;if(chunk===void 0||chunk===null)continue;if(chunk.toSSE)controller.enqueue(chunk.toSSE());else{if(typeof chunk==="object")try{controller.enqueue(format(JSON.stringify(chunk)))}catch{controller.enqueue(format(chunk.toString()))}else controller.enqueue(format(chunk.toString()));if(!isSSE)await new Promise((resolve)=>setTimeout(()=>resolve(),0))}}}catch(error2){console.warn(error2)}try{controller.close()}catch{}}}),set2)};async function*streamResponse(response){let body=response.body;if(!body)return;let reader=body.getReader(),decoder=new TextDecoder;try{while(!0){let{done,value}=await reader.read();if(done)break;if(typeof value==="string")yield value;else yield decoder.decode(value)}}finally{reader.releaseLock()}}var handleSet=(set2)=>{if(typeof set2.status==="string")set2.status=StatusMap[set2.status];if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"])},createResponseHandler=(handler)=>{let handleStream=createStreamHandler(handler);return(response,set2,request)=>{let isCookieSet=!1;if(set2.headers instanceof Headers)for(let key of set2.headers.keys())if(key==="set-cookie"){if(isCookieSet)continue;isCookieSet=!0;for(let cookie of set2.headers.getSetCookie())response.headers.append("set-cookie",cookie)}else response.headers.append(key,set2.headers?.get(key)??"");else for(let key in set2.headers)response.headers.append(key,set2.headers[key]);let status2=set2.status??200;if(response.status!==status2&&status2!==200&&(response.status<=300||response.status>400))return response.text().then((value)=>{let newResponse=new Response(value,{headers:response.headers,status:set2.status});if(!newResponse.headers.has("content-length")&&newResponse.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(newResponse),responseToSetHeaders(newResponse,set2),request);return newResponse});if(!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);return response}};var handleElysiaFile=(file2,set2={headers:{}})=>{let path=file2.path,contentType=mime[path.slice(path.lastIndexOf(".")+1)];if(contentType)set2.headers["content-type"]=contentType;if(file2.stats&&set2.status!==206&&set2.status!==304&&set2.status!==412&&set2.status!==416)return file2.stats.then((stat2)=>{let size=stat2.size;if(size!==void 0)set2.headers["content-range"]=`bytes 0-${size-1}/${size}`,set2.headers["content-length"]=size;return handleFile(file2.value,set2)});return handleFile(file2.value,set2)},mapResponse=(response,set2,request)=>{if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return set2.headers["content-type"]="text/plain",new Response(response,set2);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleElysiaFile(response,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapResponse(response.response,set2,request);case void 0:if(!response)return new Response("",set2);return new Response(JSON.stringify(response),set2);case"Response":return handleResponse(response,set2,request);case"Error":return errorToResponse(response,set2);case"Promise":return response.then((x)=>mapResponse(x,set2,request));case"Function":return mapResponse(response(),set2,request);case"Number":case"Boolean":return new Response(response.toString(),set2);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response,set2);default:if(response instanceof Response)return handleResponse(response,set2,request);if(response instanceof Promise)return response.then((x)=>mapResponse(x,set2));if(response instanceof Error)return errorToResponse(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapResponse(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse(x,set2));if(typeof response?.toResponse==="function")return mapResponse(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response,set2)}if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);return mapCompactResponse(response,request)},mapEarlyResponse=(response,set2,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return set2.headers["content-type"]="text/plain",new Response(response,set2);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleElysiaFile(response,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse(response.response,set2,request);case void 0:if(!response)return;return new Response(JSON.stringify(response),set2);case"Response":return handleResponse(response,set2,request);case"Promise":return response.then((x)=>mapEarlyResponse(x,set2));case"Error":return errorToResponse(response,set2);case"Function":return mapEarlyResponse(response(),set2);case"Number":case"Boolean":return new Response(response.toString(),set2);case"FormData":return new Response(response);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);default:if(response instanceof Response)return handleResponse(response,set2,request);if(response instanceof Promise)return response.then((x)=>mapEarlyResponse(x,set2));if(response instanceof Error)return errorToResponse(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapEarlyResponse(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse(x,set2));if(typeof response?.toResponse==="function")return mapEarlyResponse(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response,set2)}else switch(response?.constructor?.name){case"String":return set2.headers["content-type"]="text/plain",new Response(response);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleElysiaFile(response,set2);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse(response.response,set2,request);case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Promise":return response.then((x)=>{let r=mapEarlyResponse(x,set2);if(r!==void 0)return r});case"Error":return errorToResponse(response,set2);case"Function":return mapCompactResponse(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapEarlyResponse(x,set2));if(response instanceof Error)return errorToResponse(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapEarlyResponse(response.response,set2,request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse(x,set2));if(typeof response?.toResponse==="function")return mapEarlyResponse(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response)}},mapCompactResponse=(response,request)=>{switch(response?.constructor?.name){case"String":return new Response(response,{headers:{"Content-Type":"text/plain"}});case"Object":case"Array":return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}});case"ElysiaFile":return handleElysiaFile(response);case"File":return handleFile(response);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse(response.response,{status:response.code,headers:{}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":return response;case"Error":return errorToResponse(response);case"Promise":return response.then((x)=>mapCompactResponse(x,request));case"Function":return mapCompactResponse(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapCompactResponse(x,request));if(response instanceof Error)return errorToResponse(response);if(response instanceof ElysiaCustomStatusResponse)return mapResponse(response.response,{status:response.code,headers:{}});if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream(response,void 0,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse(x,set));if(typeof response?.toResponse==="function")return mapCompactResponse(response.toResponse());if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91)return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}})}return new Response(response)}},errorToResponse=(error2,set2)=>new Response(JSON.stringify({name:error2?.name,message:error2?.message,cause:error2?.cause}),{status:set2?.status!==200?set2?.status??500:500,headers:set2?.headers}),createStaticHandler=(handle,hooks,setHeaders={})=>{if(typeof handle==="function")return;let response=mapResponse(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length)return()=>response.clone()},handleResponse=createResponseHandler({mapResponse,mapCompactResponse}),handleStream=createStreamHandler({mapResponse,mapCompactResponse});var WebStandardAdapter={name:"web-standard",isWebStandard:!0,handler:{mapResponse,mapEarlyResponse,mapCompactResponse,createStaticHandler},composeHandler:{mapResponseContext:"c.request",preferWebstandardHeaders:!0,headers:`c.headers={}
14
14
  for(const [k,v] of c.request.headers.entries())c.headers[k]=v
15
15
  `,parser:{json(isOptional){if(isOptional)return`try{c.body=await c.request.json()}catch{}
16
16
  `;return`c.body=await c.request.json()
@@ -118,12 +118,12 @@ const vEnd=value.charCodeAt(value.length - 1)
118
118
  if((vStart===91&&vEnd===93)||(vStart===123&&vEnd===125))
119
119
  try{a${index}.push(JSON.parse(value))}catch{a${index}.push(value)}if(deepMemory===-1)break}}`;fnLiteral+="}}"}index++,fnLiteral+=`
120
120
  `}fnLiteral+="c.query={"+destructured.map(({key},index2)=>`'${key}':a${index2}`).join(",")+"}",fnLiteral+=`} else c.query = {}
121
- `}}let isAsyncHandler=typeof handler==="function"&&isAsync(handler),saveResponse=hasTrace||hooks.afterResponse?.length?"c.response= ":"",maybeAsync=hasCookie||hasBody||isAsyncHandler||!!hooks.parse?.length||!!hooks.afterHandle?.some(isAsync)||!!hooks.beforeHandle?.some(isAsync)||!!hooks.transform?.some(isAsync)||!!hooks.mapResponse?.some(isAsync),maybeStream=(typeof handler==="function"?isGenerator(handler):!1)||!!hooks.beforeHandle?.some(isGenerator)||!!hooks.afterHandle?.some(isGenerator)||!!hooks.transform?.some(isGenerator),responseKeys=Object.keys(validator.response??{}),hasMultipleResponses=responseKeys.length>1,hasSingle200=responseKeys.length===0||responseKeys.length===1&&responseKeys[0]==="200",hasSet=inference.cookie||inference.set||hasHeaders||hasTrace||hasMultipleResponses||!hasSingle200||isHandleFn&&hasDefaultHeaders||maybeStream,afterResponse=()=>{if(!hooks.afterResponse?.length)return"";let afterResponse2="",prefix=hooks.afterResponse?.some(isAsync)?"async ":"";afterResponse2+=`
122
- setImmediate(${prefix}()=>{`;let reporter=report("afterResponse",{total:hooks.afterResponse?.length});if(hooks.afterResponse?.length&&hooks.afterResponse)for(let i=0;i<hooks.afterResponse.length;i++){let endUnit=reporter.resolveChild(hooks.afterResponse[i].fn.name),prefix2=isAsync(hooks.afterResponse[i])?"await ":"";afterResponse2+=`
121
+ `}}let isAsyncHandler=typeof handler==="function"&&isAsync(handler),saveResponse=hasTrace||hooks.afterResponse?.length?"c.response= ":"",maybeAsync=hasCookie||hasBody||isAsyncHandler||!!hooks.parse?.length||!!hooks.afterHandle?.some(isAsync)||!!hooks.beforeHandle?.some(isAsync)||!!hooks.transform?.some(isAsync)||!!hooks.mapResponse?.some(isAsync),maybeStream=(typeof handler==="function"?isGenerator(handler):!1)||!!hooks.beforeHandle?.some(isGenerator)||!!hooks.afterHandle?.some(isGenerator)||!!hooks.transform?.some(isGenerator),responseKeys=Object.keys(validator.response??{}),hasMultipleResponses=responseKeys.length>1,hasSingle200=responseKeys.length===0||responseKeys.length===1&&responseKeys[0]==="200",hasSet=inference.cookie||inference.set||hasHeaders||hasTrace||hasMultipleResponses||!hasSingle200||isHandleFn&&hasDefaultHeaders||maybeStream,afterResponse=()=>{if(!hooks.afterResponse?.length&&!hasTrace)return"";let afterResponse2="",prefix=hooks.afterResponse?.some(isAsync)?"async ":"";afterResponse2+=`
122
+ setImmediate(${prefix}()=>{`;let reporter=createReport({trace:hooks.trace,addFn:(word)=>{afterResponse2+=word}})("afterResponse",{total:hooks.afterResponse?.length});if(hooks.afterResponse?.length&&hooks.afterResponse)for(let i=0;i<hooks.afterResponse.length;i++){let endUnit=reporter.resolveChild(hooks.afterResponse[i].fn.name),prefix2=isAsync(hooks.afterResponse[i])?"await ":"";afterResponse2+=`
123
123
  ${prefix2}e.afterResponse[${i}](c)
124
124
  `,endUnit()}return reporter.resolve(),afterResponse2+=`})
125
125
  `,afterResponse2},mapResponse3=(r="r")=>{let after=afterResponse(),response=`${hasSet?"mapResponse":"mapCompactResponse"}(${saveResponse}${r}${hasSet?",c.set":""}${mapResponseContext})
126
- `;if(!after)`return ${response}`;return`const _res=${response}`+after+"return _res"},mapResponseContext=maybeStream||adapter.mapResponseContext?`,${adapter.mapResponseContext}`:"";if(hasTrace||inference.route)fnLiteral+=`c.route=\`${path}\`
126
+ `;if(!after)return`return ${response}`;return`const _res=${response}`+after+"return _res"},mapResponseContext=maybeStream||adapter.mapResponseContext?`,${adapter.mapResponseContext}`:"";if(hasTrace||inference.route)fnLiteral+=`c.route=\`${path}\`
127
127
  `;let parseReporter=report("parse",{total:hooks.parse?.length});if(hasBody){let hasBodyInference=!!hooks.parse?.length||inference.body||validator.body;if(adapter.parser.declare)fnLiteral+=adapter.parser.declare;fnLiteral+=`
128
128
  try{`;let parser=typeof hooks.parse==="string"?hooks.parse:Array.isArray(hooks.parse)&&hooks.parse.length===1?typeof hooks.parse[0]==="string"?hooks.parse[0]:typeof hooks.parse[0].fn==="string"?hooks.parse[0].fn:void 0:void 0;if(!parser&&validator.body&&!hooks.parse?.length){let schema=validator.body.schema;if(schema&&schema.anyOf&&schema[Kind5]==="Union"&&schema.anyOf?.length===2&&schema.anyOf?.find((x)=>x[Kind5]==="ElysiaForm"))parser="formdata"}if(parser&&defaultParsers.includes(parser)){let reporter=report("parse",{total:hooks.parse?.length}),isOptionalBody=!!validator.body?.isOptional;switch(parser){case"json":case"application/json":fnLiteral+=adapter.parser.json(isOptionalBody);break;case"text":case"text/plain":fnLiteral+=adapter.parser.text(isOptionalBody);break;case"urlencoded":case"application/x-www-form-urlencoded":fnLiteral+=adapter.parser.urlencoded(isOptionalBody);break;case"arrayBuffer":case"application/octet-stream":fnLiteral+=adapter.parser.arrayBuffer(isOptionalBody);break;case"formdata":case"multipart/form-data":fnLiteral+=adapter.parser.formData(isOptionalBody);break;default:if(parser[0]in app["~parser"])fnLiteral+=hasHeaders?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')",fnLiteral+=`
129
129
  if(contentType){const index=contentType.indexOf(';')
@@ -169,7 +169,7 @@ if(bo${key} instanceof Promise)bo${key}=await bo${key}
169
169
  if(bo${key} instanceof ElysiaCustomStatusResponse){`+mapResponse3(`bo${key}`)+`}if(bo${key}!==undefined)c.body=bo${key}
170
170
  break
171
171
  `;if(hooks.parse?.length)fnLiteral+="}";fnLiteral+="}"}if(hooks.parse?.length)fnLiteral+=`
172
- delete c.contentType`}fnLiteral+="}catch(error){throw new ParseError(error)}"}if(parseReporter.resolve(),hooks?.transform){let reporter=report("transform",{total:hooks.transform.length});if(hooks.transform.length)fnLiteral+=`let transformed
172
+ delete c.contentType`}fnLiteral+="}catch(error){throw new ParseError(error)}"}if(parseReporter.resolve(),hooks?.transform||hasTrace){let reporter=report("transform",{total:hooks.transform?.length});if(hooks.transform?.length){fnLiteral+=`let transformed
173
173
  `;for(let i=0;i<hooks.transform.length;i++){let transform=hooks.transform[i],endUnit=reporter.resolveChild(transform.fn.name);if(fnLiteral+=isAsync(transform)?`transformed=await e.transform[${i}](c)
174
174
  `:`transformed=e.transform[${i}](c)
175
175
  `,transform.subType==="mapDerive")fnLiteral+="if(transformed instanceof ElysiaCustomStatusResponse){"+mapResponse3("transformed")+`}else{transformed.request=c.request
@@ -181,7 +181,7 @@ transformed.redirect=c.redirect
181
181
  transformed.set=c.set
182
182
  transformed.error=c.error
183
183
  c=transformed}`;else fnLiteral+="if(transformed instanceof ElysiaCustomStatusResponse){"+mapResponse3("transformed")+`}else Object.assign(c,transformed)
184
- `;endUnit()}reporter.resolve()}let fileUnions=[];if(validator){if(validator.headers){if(validator.headers.hasDefault)for(let[key,value]of Object.entries(Value4.Default(validator.headers.schema,{}))){let parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(parsed!==void 0)fnLiteral+=`c.headers['${key}']??=${parsed}
184
+ `;endUnit()}}reporter.resolve()}let fileUnions=[];if(validator){if(validator.headers){if(validator.headers.hasDefault)for(let[key,value]of Object.entries(Value4.Default(validator.headers.schema,{}))){let parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(parsed!==void 0)fnLiteral+=`c.headers['${key}']??=${parsed}
185
185
  `}if(fnLiteral+=composeCleaner({name:"c.headers",schema:validator.headers,type:"headers",normalize}),validator.headers.isOptional)fnLiteral+="if(isNotEmpty(c.headers)){";if(validator.body?.schema?.noValidate!==!0)fnLiteral+="if(validator.headers.Check(c.headers) === false){"+validation.validate("headers")+"}";if(validator.headers.hasTransform)fnLiteral+=coerceTransformDecodeError(`c.headers=validator.headers.Decode(c.headers)
186
186
  `,"headers");if(validator.headers.isOptional)fnLiteral+="}"}if(validator.params){if(validator.params.hasDefault)for(let[key,value]of Object.entries(Value4.Default(validator.params.schema,{}))){let parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(parsed!==void 0)fnLiteral+=`c.params['${key}']??=${parsed}
187
187
  `}if(validator.params?.schema?.noValidate!==!0)fnLiteral+="if(validator.params.Check(c.params)===false){"+validation.validate("params")+"}";if(validator.params.hasTransform)fnLiteral+=coerceTransformDecodeError(`c.params=validator.params.Decode(c.params)
@@ -202,7 +202,7 @@ c=transformed}`;else fnLiteral+="if(transformed instanceof ElysiaCustomStatusRes
202
202
  for(const [key,value] of Object.entries(c.cookie))cookieValue[key]=value.value
203
203
  `,cookieValidator.hasDefault)for(let[key,value]of Object.entries(Value4.Default(cookieValidator.schema,{})))fnLiteral+=`cookieValue['${key}'] = ${typeof value==="object"?JSON.stringify(value):value}
204
204
  `;if(cookieValidator.isOptional)fnLiteral+="if(isNotEmpty(c.cookie)){";if(validator.body?.schema?.noValidate!==!0)fnLiteral+="if(validator.cookie.Check(cookieValue)===false){"+validation.validate("cookie","cookieValue")+"}";if(cookieValidator.hasTransform)fnLiteral+=coerceTransformDecodeError(`for(const [key,value] of Object.entries(validator.cookie.Decode(cookieValue)))c.cookie[key].value=value
205
- `,"cookie");if(cookieValidator.isOptional)fnLiteral+="}"}}if(hooks?.beforeHandle){let reporter=report("beforeHandle",{total:hooks.beforeHandle.length}),hasResolve=!1;for(let i=0;i<hooks.beforeHandle.length;i++){let beforeHandle=hooks.beforeHandle[i],endUnit=reporter.resolveChild(beforeHandle.fn.name),returning=hasReturn(beforeHandle);if(beforeHandle.subType==="resolve"||beforeHandle.subType==="mapResolve"){if(!hasResolve)hasResolve=!0,fnLiteral+=`
205
+ `,"cookie");if(cookieValidator.isOptional)fnLiteral+="}"}}if(hooks?.beforeHandle||hasTrace){let reporter=report("beforeHandle",{total:hooks.beforeHandle?.length}),hasResolve=!1;if(hooks.beforeHandle?.length)for(let i=0;i<hooks.beforeHandle.length;i++){let beforeHandle=hooks.beforeHandle[i],endUnit=reporter.resolveChild(beforeHandle.fn.name),returning=hasReturn(beforeHandle);if(beforeHandle.subType==="resolve"||beforeHandle.subType==="mapResolve"){if(!hasResolve)hasResolve=!0,fnLiteral+=`
206
206
  let resolved
207
207
  `;if(fnLiteral+=isAsync(beforeHandle)?`resolved=await e.beforeHandle[${i}](c);
208
208
  `:`resolved=e.beforeHandle[${i}](c);
@@ -215,11 +215,11 @@ resolved.redirect=c.redirect
215
215
  resolved.set=c.set
216
216
  resolved.error=c.error
217
217
  c=resolved}`;else fnLiteral+="if(resolved instanceof ElysiaCustomStatusResponse){"+mapResponse3("resolved")+`}else Object.assign(c, resolved)
218
- `}else if(!returning)fnLiteral+=isAsync(beforeHandle)?`await e.beforeHandle[${i}](c)
218
+ `;endUnit()}else if(!returning)fnLiteral+=isAsync(beforeHandle)?`await e.beforeHandle[${i}](c)
219
219
  `:`e.beforeHandle[${i}](c)
220
220
  `,endUnit();else{if(fnLiteral+=isAsync(beforeHandle)?`be=await e.beforeHandle[${i}](c)
221
221
  `:`be=e.beforeHandle[${i}](c)
222
- `,endUnit("be"),fnLiteral+="if(be!==undefined){",reporter.resolve(),hooks.afterHandle?.length){report("handle",{name:isHandleFn?handler.name:void 0}).resolve();let reporter2=report("afterHandle",{total:hooks.afterHandle.length});for(let i2=0;i2<hooks.afterHandle.length;i2++){let hook=hooks.afterHandle[i2],returning2=hasReturn(hook),endUnit2=reporter2.resolveChild(hook.fn.name);if(fnLiteral+=`c.response = be
222
+ `,endUnit("be"),fnLiteral+="if(be!==undefined){",reporter.resolve(),hooks.afterHandle?.length||hasTrace){report("handle",{name:isHandleFn?handler.name:void 0}).resolve();let reporter2=report("afterHandle",{total:hooks.afterHandle?.length});if(hooks.afterHandle?.length)for(let i2=0;i2<hooks.afterHandle.length;i2++){let hook=hooks.afterHandle[i2],returning2=hasReturn(hook),endUnit2=reporter2.resolveChild(hook.fn.name);if(fnLiteral+=`c.response = be
223
223
  `,!returning2)fnLiteral+=isAsync(hook.fn)?`await e.afterHandle[${i2}](c, be)
224
224
  `:`e.afterHandle[${i2}](c, be)
225
225
  `;else fnLiteral+=isAsync(hook.fn)?`af=await e.afterHandle[${i2}](c)
@@ -228,18 +228,18 @@ c=resolved}`;else fnLiteral+="if(resolved instanceof ElysiaCustomStatusResponse)
228
228
  `;endUnit2("af")}reporter2.resolve()}if(validator.response)fnLiteral+=validation.response("be");let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse?.length});if(hooks.mapResponse?.length){fnLiteral+=`c.response=be
229
229
  `;for(let i2=0;i2<hooks.mapResponse.length;i2++){let mapResponse4=hooks.mapResponse[i2],endUnit2=mapResponseReporter.resolveChild(mapResponse4.fn.name);fnLiteral+=`if(mr===undefined){mr=${isAsyncName(mapResponse4)?"await ":""}e.mapResponse[${i2}](c)
230
230
  if(mr!==undefined)be=c.response=mr}`,endUnit2()}}mapResponseReporter.resolve(),fnLiteral+=encodeCookie(),fnLiteral+=`return mapEarlyResponse(${saveResponse}be,c.set${mapResponseContext})}
231
- `}}reporter.resolve()}if(hooks.afterHandle?.length){let handleReporter=report("handle",{name:isHandleFn?handler.name:void 0});if(hooks.afterHandle.length)fnLiteral+=isAsyncHandler?`let r=c.response=await ${handle}
231
+ `}}reporter.resolve()}if(hooks.afterHandle?.length||hasTrace){let handleReporter=report("handle",{name:isHandleFn?handler.name:void 0});if(hooks.afterHandle?.length)fnLiteral+=isAsyncHandler?`let r=c.response=await ${handle}
232
232
  `:`let r=c.response=${handle}
233
233
  `;else fnLiteral+=isAsyncHandler?`let r=await ${handle}
234
234
  `:`let r=${handle}
235
- `;handleReporter.resolve();let reporter=report("afterHandle",{total:hooks.afterHandle.length});for(let i=0;i<hooks.afterHandle.length;i++){let hook=hooks.afterHandle[i],returning=hasReturn(hook),endUnit=reporter.resolveChild(hook.fn.name);if(!returning)fnLiteral+=isAsync(hook.fn)?`await e.afterHandle[${i}](c)
235
+ `;handleReporter.resolve();let reporter=report("afterHandle",{total:hooks.afterHandle?.length});if(hooks.afterHandle?.length)for(let i=0;i<hooks.afterHandle.length;i++){let hook=hooks.afterHandle[i],returning=hasReturn(hook),endUnit=reporter.resolveChild(hook.fn.name);if(!returning)fnLiteral+=isAsync(hook.fn)?`await e.afterHandle[${i}](c)
236
236
  `:`e.afterHandle[${i}](c)
237
237
  `,endUnit();else if(fnLiteral+=isAsync(hook.fn)?`af=await e.afterHandle[${i}](c)
238
238
  `:`af=e.afterHandle[${i}](c)
239
- `,endUnit("af"),validator.response)fnLiteral+="if(af!==undefined){",reporter.resolve(),fnLiteral+=validation.response("af"),fnLiteral+="c.response=af}";else fnLiteral+="if(af!==undefined){",reporter.resolve(),fnLiteral+="c.response=af}"}if(reporter.resolve(),fnLiteral+=`r=c.response
240
- `,validator.response)fnLiteral+=validation.response();fnLiteral+=encodeCookie();let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse?.length});if(hooks.mapResponse?.length)for(let i=0;i<hooks.mapResponse.length;i++){let mapResponse4=hooks.mapResponse[i],endUnit=mapResponseReporter.resolveChild(mapResponse4.fn.name);fnLiteral+=`mr=${isAsyncName(mapResponse4)?"await ":""}e.mapResponse[${i}](c)
239
+ `,endUnit("af"),validator.response)fnLiteral+="if(af!==undefined){",reporter.resolve(),fnLiteral+=validation.response("af"),fnLiteral+="c.response=af}";else fnLiteral+="if(af!==undefined){",reporter.resolve(),fnLiteral+="c.response=af}"}if(reporter.resolve(),hooks.afterHandle?.length)fnLiteral+=`r=c.response
240
+ `;if(validator.response)fnLiteral+=validation.response();fnLiteral+=encodeCookie();let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse?.length});if(hooks.mapResponse?.length)for(let i=0;i<hooks.mapResponse.length;i++){let mapResponse4=hooks.mapResponse[i],endUnit=mapResponseReporter.resolveChild(mapResponse4.fn.name);fnLiteral+=`mr=${isAsyncName(mapResponse4)?"await ":""}e.mapResponse[${i}](c)
241
241
  if(mr!==undefined)r=c.response=mr
242
- `,endUnit()}mapResponseReporter.resolve(),fnLiteral+=mapResponse3()}else{let handleReporter=report("handle",{name:isHandleFn?handler.name:void 0});if(validator.response||hooks.mapResponse?.length){if(fnLiteral+=isAsyncHandler?`let r=await ${handle}
242
+ `,endUnit()}mapResponseReporter.resolve(),fnLiteral+=mapResponse3()}else{let handleReporter=report("handle",{name:isHandleFn?handler.name:void 0});if(validator.response||hooks.mapResponse?.length||hasTrace){if(fnLiteral+=isAsyncHandler?`let r=await ${handle}
243
243
  `:`let r=${handle}
244
244
  `,handleReporter.resolve(),validator.response)fnLiteral+=validation.response();let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse?.length});if(hooks.mapResponse?.length){fnLiteral+=`
245
245
  c.response=r
@@ -321,16 +321,16 @@ map: switch(p){
321
321
  `+createHoc(app);let handleError=composeErrorHandler(app);app.handleError=handleError;let fn=Function("data",`"use strict";
322
322
  `+fnLiteral)({app,mapEarlyResponse:app["~adapter"].handler.mapEarlyResponse,NotFoundError,randomId,handleError,status,redirect,parseQueryFromURL:app.inference.query?parseQueryFromURL:void 0,ELYSIA_TRACE:hasTrace?ELYSIA_TRACE:void 0,ELYSIA_REQUEST_ID:hasTrace?ELYSIA_REQUEST_ID:void 0,...adapter.inject});if(isBun)Bun.gc(!1);return fn},composeErrorHandler=(app)=>{let hooks=app.event,fnLiteral="",adapter=app["~adapter"].composeError,adapterVariables=adapter.inject?Object.keys(adapter.inject).join(",")+",":"",hasTrace=!!app.event.trace?.length;if(fnLiteral+="const {mapResponse,ERROR_CODE,ElysiaCustomStatusResponse,"+allocateIf("onError,",app.event.error)+allocateIf("afterResponse,",app.event.afterResponse)+allocateIf("trace,",app.event.trace)+allocateIf("onMapResponse,",app.event.mapResponse)+allocateIf("ELYSIA_TRACE,",hasTrace)+allocateIf("ELYSIA_REQUEST_ID,",hasTrace)+adapterVariables+`}=inject
323
323
  `,fnLiteral+=`return ${app.event.error?.find(isAsync)||app.event.mapResponse?.find(isAsync)?"async ":""}function(context,error,skipGlobal){`,fnLiteral+="",hasTrace)fnLiteral+=`const id=context[ELYSIA_REQUEST_ID]
324
- `;let report=createReport({context:"context",trace:hooks.trace,addFn:(word)=>{fnLiteral+=word}}),afterResponse=()=>{if(!hooks.afterResponse?.length)return"";let afterResponse2="",prefix=hooks.afterResponse.some(isAsync)?"async":"";afterResponse2+=`
325
- setImmediate(${prefix}()=>{`;let reporter=report("afterResponse",{total:hooks.afterResponse?.length,name:"context"});for(let i=0;i<hooks.afterResponse.length;i++){let fn=hooks.afterResponse[i].fn,endUnit=reporter.resolveChild(fn.name);afterResponse2+=`
324
+ `;let report=createReport({context:"context",trace:hooks.trace,addFn:(word)=>{fnLiteral+=word}}),afterResponse=()=>{if(!hooks.afterResponse?.length&&!hasTrace)return"";let afterResponse2="",prefix=hooks.afterResponse?.some(isAsync)?"async":"";afterResponse2+=`
325
+ setImmediate(${prefix}()=>{`;let reporter=createReport({context:"context",trace:hooks.trace,addFn:(word)=>{afterResponse2+=word}})("afterResponse",{total:hooks.afterResponse?.length,name:"context"});if(hooks.afterResponse?.length&&hooks.afterResponse)for(let i=0;i<hooks.afterResponse.length;i++){let fn=hooks.afterResponse[i].fn,endUnit=reporter.resolveChild(fn.name);afterResponse2+=`
326
326
  ${isAsyncName(fn)?"await ":""}afterResponse[${i}](context)
327
- `,endUnit()}return afterResponse2+=`})
328
- `,reporter.resolve(),afterResponse2};if(fnLiteral+=`const set=context.set
327
+ `,endUnit()}return reporter.resolve(),afterResponse2+=`})
328
+ `,afterResponse2};if(fnLiteral+=`const set=context.set
329
329
  let _r
330
330
  if(!context.code)context.code=error.code??error[ERROR_CODE]
331
331
  if(!(context.error instanceof Error))context.error=error
332
332
  if(error instanceof ElysiaCustomStatusResponse){set.status=error.status=error.code
333
- error.message=error.response}`,adapter.declare)fnLiteral+=adapter.declare;let saveResponse=hasTrace||!!hooks.afterResponse?.length||!!hooks.afterResponse?.length?"context.response = ":"";if(app.event.error)for(let i=0;i<app.event.error.length;i++){let handler=app.event.error[i],response=`${isAsync(handler)?"await ":""}onError[${i}](context)
333
+ error.message=error.response}`,adapter.declare)fnLiteral+=adapter.declare;let saveResponse=hasTrace||!!hooks.afterResponse?.length?"context.response = ":"";if(app.event.error)for(let i=0;i<app.event.error.length;i++){let handler=app.event.error[i],response=`${isAsync(handler)?"await ":""}onError[${i}](context)
334
334
  `;if(fnLiteral+="if(skipGlobal!==true){",hasReturn(handler)){fnLiteral+=`_r=${response}
335
335
  if(_r!==undefined){if(_r instanceof Response){`+afterResponse()+`return mapResponse(_r,set${adapter.mapResponseContext})}if(_r instanceof ElysiaCustomStatusResponse){error.status=error.code
336
336
  error.message = error.response}if(set.status===200||!set.status)set.status=error.status
@@ -359,8 +359,8 @@ return u.substring(s,qi)
359
359
  `;fnLiteral+=`${app.event.request?.find(isAsync)?"async":""} function map(request){`;let needsQuery=inference.query||!!route.hooks.query||!!route.standaloneValidators?.find((x)=>x.query);if(hasTrace||needsQuery||app.event.request?.length)fnLiteral+=createContext(app,route,inference),fnLiteral+=createOnRequestHandler(app),fnLiteral+="return handler(c)}";else fnLiteral+=`return handler(${createContext(app,route,inference,!0)})}`;return fnLiteral+=createHoc(app),Function("data",fnLiteral)({app,handler:route.compile?.()??route.composed,redirect,status,hoc:app.extender.higherOrderFunctions.map((x)=>x.fn),store:app.store,decorator:app.decorator,route:route.path,randomId:hasTrace?randomId:void 0,ELYSIA_TRACE:hasTrace?ELYSIA_TRACE:void 0,ELYSIA_REQUEST_ID:hasTrace?ELYSIA_REQUEST_ID:void 0,trace:hasTrace?app.event.trace?.map((x)=>x?.fn??x):void 0,mapEarlyResponse:mapEarlyResponse2})};var createNativeStaticHandler=(handle,hooks,set2)=>{if(typeof handle==="function"||handle instanceof Blob)return;if(isHTMLBundle(handle))return()=>handle;let response=mapResponse2(handle,set2??{headers:{}});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length){if(response instanceof Promise)return response.then((response2)=>{if(!response2)return;if(!response2.headers.has("content-type"))response2.headers.append("content-type","text/plain");return response2.clone()});if(!response.headers.has("content-type"))response.headers.append("content-type","text/plain");return()=>response.clone()}};var websocket={open(ws){ws.data.open?.(ws)},message(ws,message){ws.data.message?.(ws,message)},drain(ws){ws.data.drain?.(ws)},close(ws,code,reason){ws.data.close?.(ws,code,reason)}};class ElysiaWS{raw;data;body;constructor(raw,data,body=void 0){this.raw=raw;this.data=data;this.body=body;this.validator=raw.data?.validator,this.sendText=raw.sendText.bind(raw),this.sendBinary=raw.sendBinary.bind(raw),this.close=raw.close.bind(raw),this.terminate=raw.terminate.bind(raw),this.publishText=raw.publishText.bind(raw),this.publishBinary=raw.publishBinary.bind(raw),this.subscribe=raw.subscribe.bind(raw),this.unsubscribe=raw.unsubscribe.bind(raw),this.isSubscribed=raw.isSubscribed.bind(raw),this.cork=raw.cork.bind(raw),this.remoteAddress=raw.remoteAddress,this.binaryType=raw.binaryType,this.data=raw.data,this.send=this.send.bind(this),this.ping=this.ping.bind(this),this.pong=this.pong.bind(this),this.publish=this.publish.bind(this)}send(data,compress){if(Buffer.isBuffer(data))return this.raw.send(data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.send(data,compress)}ping(data){if(Buffer.isBuffer(data))return this.raw.ping(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.ping(data)}pong(data){if(Buffer.isBuffer(data))return this.raw.pong(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.pong(data)}publish(topic,data,compress){if(Buffer.isBuffer(data))return this.raw.publish(topic,data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.publish(topic,data,compress)}sendText;sendBinary;close;terminate;publishText;publishBinary;subscribe;unsubscribe;isSubscribed;cork;remoteAddress;binaryType;get readyState(){return this.raw.readyState}validator;["~types"];get id(){return this.data.id}}var createWSMessageParser=(parse2)=>{let parsers=typeof parse2==="function"?[parse2]:parse2;return async function parseMessage(ws,message){if(typeof message==="string"){let start=message?.charCodeAt(0);if(start===34||start===47||start===91||start===123)try{message=JSON.parse(message)}catch{}else if(isNumericString(message))message=+message;else if(message==="true")message=!0;else if(message==="false")message=!1;else if(message==="null")message=null}if(parsers)for(let i=0;i<parsers.length;i++){let temp=parsers[i](ws,message);if(temp instanceof Promise)temp=await temp;if(temp!==void 0)return temp}return message}},createHandleWSResponse=(validateResponse)=>{let handleWSResponse=(ws,data)=>{if(data instanceof Promise)return data.then((data2)=>handleWSResponse(ws,data2));if(Buffer.isBuffer(data))return ws.send(data.toString());if(data===void 0)return;let send=(datum)=>{if(validateResponse?.Check(datum)===!1)return ws.send(new ValidationError("message",validateResponse,datum).message);if(typeof datum==="object")return ws.send(JSON.stringify(datum));ws.send(datum)};if(typeof data?.next!=="function")return void send(data);let init=data.next();if(init instanceof Promise)return(async()=>{let first=await init;if(validateResponse?.Check(first)===!1)return ws.send(new ValidationError("message",validateResponse,first).message);if(send(first.value),!first.done)for await(let datum of data)send(datum)})();if(send(init.value),!init.done)for(let datum of data)send(datum)};return handleWSResponse};var optionalParam=/:.+?\?(?=\/|$)/,getPossibleParams=(path)=>{let match=optionalParam.exec(path);if(!match)return[path];let routes=[],head=path.slice(0,match.index),param=match[0].slice(0,-1),tail=path.slice(match.index+match[0].length);routes.push(head.slice(0,-1)),routes.push(head+param);for(let fragment of getPossibleParams(tail)){if(!fragment)continue;if(!fragment.startsWith("/:"))routes.push(head.slice(0,-1)+fragment);routes.push(head+param+fragment)}return routes},isHTMLBundle=(handle)=>{return typeof handle==="object"&&handle!==null&&(handle.toString()==="[object HTMLBundle]"||typeof handle.index==="string")},supportedMethods={GET:!0,HEAD:!0,OPTIONS:!0,DELETE:!0,PATCH:!0,POST:!0,PUT:!0},mapRoutes=(app)=>{if(!app.config.aot||!app.config.systemRouter)return;let routes={},add=(route,handler)=>{if(routes[route.path]){if(!routes[route.path][route.method])routes[route.path][route.method]=handler}else routes[route.path]={[route.method]:handler}},tree=app.routeTree;for(let route of app.router.history){if(typeof route.handler!=="function")continue;let method=route.method;if(method==="GET"&&`WS_${route.path}`in tree||method==="WS"||route.path.charCodeAt(route.path.length-1)===42||!(method in supportedMethods))continue;if(method==="ALL"){if(!(`WS_${route.path}`in tree))routes[route.path]=route.hooks?.config?.mount?route.hooks.trace||app.event.trace||app.extender.higherOrderFunctions?createBunRouteHandler(app,route):route.hooks.mount||route.handler:route.handler;continue}let compiled,handler=app.config.precompile?createBunRouteHandler(app,route):(request)=>{if(compiled)return compiled(request);return(compiled=createBunRouteHandler(app,route))(request)};for(let path of getPossibleParams(route.path))add({method,path},handler)}return routes},mergeRoutes=(r1,r2)=>{if(!r2)return r1;for(let key of Object.keys(r2)){if(r1[key]===r2[key])continue;if(!r1[key]){r1[key]=r2[key];continue}if(r1[key]&&r2[key]){if(typeof r1[key]==="function"||r1[key]instanceof Response){r1[key]=r2[key];continue}r1[key]={...r1[key],...r2[key]}}}return r1},BunAdapter={...WebStandardAdapter,name:"bun",handler:{mapResponse:mapResponse2,mapEarlyResponse:mapEarlyResponse2,mapCompactResponse:mapCompactResponse2,createStaticHandler:createStaticHandler2,createNativeStaticHandler},composeHandler:{...WebStandardAdapter.composeHandler,headers:hasHeaderShorthand?`c.headers=c.request.headers.toJSON()
360
360
  `:`c.headers={}
361
361
  for(const [k,v] of c.request.headers.entries())c.headers[k]=v
362
- `},listen(app){return(options,callback)=>{if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(app.compile(),typeof options==="string"){if(!isNumericString(options))throw new Error("Port must be a numeric value");options=parseInt(options)}let createStaticRoute=(iterator,{withAsync=!1}={})=>{let staticRoutes={},ops=[];for(let[path,route]of Object.entries(iterator))if(supportPerMethodInlineHandler){if(!route)continue;for(let[method,value]of Object.entries(route)){if(!value||!(method in supportedMethods))continue;if(value instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(value.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path][method]=awaited;if(isHTMLBundle(awaited))staticRoutes[path][method]=awaited}))}continue}if(!(value instanceof Response)&&!isHTMLBundle(value))continue;if(!staticRoutes[path])staticRoutes[path]={};staticRoutes[path][method]=value}}else{if(!route)continue;if(route instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(route.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path]=awaited}))}continue}if(!(route instanceof Response))continue;staticRoutes[path]=route}if(withAsync)return Promise.all(ops).then(()=>staticRoutes);return staticRoutes},serve=typeof options==="object"?{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},...options||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{}},fetch:app.fetch}:{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{}},port:options,fetch:app.fetch};if(app.server=Bun.serve(serve),app.event.start)for(let i=0;i<app.event.start.length;i++)app.event.start[i].fn(app);if(callback)callback(app.server);process.on("beforeExit",()=>{if(app.server){if(app.server.stop?.(),app.server=null,app.event.stop)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}}),app.promisedModules.then(async()=>{app.server?.reload({...serve,fetch:app.fetch,routes:mergeRoutes(mergeRoutes(await createStaticRoute(app.router.response,{withAsync:!0}),mapRoutes(app)),app.config.serve?.routes)}),Bun?.gc(!1)})}},async stop(app,closeActiveConnections){if(app.server){if(app.server.stop(closeActiveConnections),app.server=null,app.event.stop?.length)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}else console.log("Elysia isn't running. Call `app.listen` to start the server.",new Error().stack)},ws(app,path,options){let{parse:parse2,body,response,...rest}=options,validateMessage=getSchemaValidator(body,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize}),validateResponse=getSchemaValidator(response,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize});app.route("WS",path,async(context)=>{let server=context.server??app.server,{set:set2,path:path2,qi,headers,query,params}=context;if(context.validator=validateResponse,options.upgrade){if(typeof options.upgrade==="function"){let temp=options.upgrade(context);if(temp instanceof Promise)await temp}else if(options.upgrade)Object.assign(set2.headers,options.upgrade)}if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"]);let handleResponse3=createHandleWSResponse(validateResponse),parseMessage=createWSMessageParser(parse2),_id;if(typeof options.beforeHandle==="function"){let result=options.beforeHandle(context);if(result instanceof Promise)await result}let errorHandlers=[...options.error?Array.isArray(options.error)?options.error:[options.error]:[],...(app.event.error??[]).map((x)=>typeof x==="function"?x:x.fn)].filter((x)=>x),handleErrors=!errorHandlers.length?()=>{}:async(ws,error2)=>{for(let handleError of errorHandlers){let response2=handleError(Object.assign(context,{error:error2}));if(response2 instanceof Promise)response2=await response2;if(await handleResponse3(ws,response2),response2)break}};if(server?.upgrade(context.request,{headers:isNotEmpty(set2.headers)?set2.headers:void 0,data:{...context,get id(){if(_id)return _id;return _id=randomId()},validator:validateResponse,ping(data){options.ping?.(data)},pong(data){options.pong?.(data)},open:async(ws)=>{try{await handleResponse3(ws,options.open?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},message:async(ws,_message)=>{let message=await parseMessage(ws,_message);if(validateMessage?.Check(message)===!1)return void ws.send(new ValidationError("message",validateMessage,message).message);try{await handleResponse3(ws,options.message?.(new ElysiaWS(ws,context,message),message))}catch(error2){handleErrors(ws,error2)}},drain:async(ws)=>{try{await handleResponse3(ws,options.drain?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},close:async(ws,code,reason)=>{try{await handleResponse3(ws,options.close?.(new ElysiaWS(ws,context),code,reason))}catch(error2){handleErrors(ws,error2)}}}}))return;return set2.status=400,"Expected a websocket connection"},{...rest,websocket:options})}};var env2=isBun?Bun.env:typeof process!=="undefined"&&process?.env?process.env:{};import{TransformDecodeError}from"@sinclair/typebox/value";var injectDefaultValues=(typeChecker,obj)=>{let schema=typeChecker.schema;if(!schema)return;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];if(!schema?.properties)return;for(let[key,keySchema]of Object.entries(schema.properties))obj[key]??=keySchema.default},createDynamicHandler=(app)=>{let{mapResponse:mapResponse3,mapEarlyResponse:mapEarlyResponse3}=app["~adapter"].handler,defaultHeader=app.setHeaders;return async(request)=>{let url=request.url,s=url.indexOf("/",11),qi=url.indexOf("?",s+1),path=qi===-1?url.substring(s):url.substring(s,qi),set2={cookie:{},status:200,headers:defaultHeader?{...defaultHeader}:{}},context=Object.assign({},app.singleton.decorator,{set:set2,store:app.singleton.store,request,path,qi,error:status,status,redirect});try{if(app.event.request)for(let i=0;i<app.event.request.length;i++){let onRequest=app.event.request[i].fn,response2=onRequest(context);if(response2 instanceof Promise)response2=await response2;if(response2=mapEarlyResponse3(response2,set2),response2)return context.response=response2}let methodKey=request.method==="GET"&&request.headers.get("upgrade")?.toLowerCase()==="websocket"?"WS":request.method,handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find(methodKey,path)??app.router.dynamic.find("ALL",path);if(!handler)throw context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),new NotFoundError;let{handle,hooks,validator,content,route}=handler.store,body;if(request.method!=="GET"&&request.method!=="HEAD")if(content)switch(content){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}else{let contentType;if(request.body)contentType=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);if(context.contentType=contentType,hooks.parse)for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn;if(typeof hook==="string")switch(hook){case"json":case"application/json":body=await request.json();break;case"text":case"text/plain":body=await request.text();break;case"urlencoded":case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"arrayBuffer":case"application/octet-stream":body=await request.arrayBuffer();break;case"formdata":case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break;default:let parser=app["~parser"][hook];if(parser){let temp=parser(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}break}else{let temp=hook(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}}if(delete context.contentType,body===void 0)switch(contentType){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}}context.route=route,context.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),context.headers={};for(let[key,value]of request.headers.entries())context.headers[key]=value;let cookieMeta={domain:app.config.cookie?.domain??validator?.cookie?.config.domain,expires:app.config.cookie?.expires??validator?.cookie?.config.expires,httpOnly:app.config.cookie?.httpOnly??validator?.cookie?.config.httpOnly,maxAge:app.config.cookie?.maxAge??validator?.cookie?.config.maxAge,path:app.config.cookie?.path??validator?.cookie?.config.path,priority:app.config.cookie?.priority??validator?.cookie?.config.priority,partitioned:app.config.cookie?.partitioned??validator?.cookie?.config.partitioned,sameSite:app.config.cookie?.sameSite??validator?.cookie?.config.sameSite,secure:app.config.cookie?.secure??validator?.cookie?.config.secure,secrets:app.config.cookie?.secrets??validator?.cookie?.config.secrets,sign:app.config.cookie?.sign??validator?.cookie?.config.sign},cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta);let headerValidator=validator?.createHeaders?.();if(headerValidator)injectDefaultValues(headerValidator,context.headers);let paramsValidator=validator?.createParams?.();if(paramsValidator)injectDefaultValues(paramsValidator,context.params);let queryValidator=validator?.createQuery?.();if(queryValidator)injectDefaultValues(queryValidator,context.query);if(hooks.transform)for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="derive")Object.assign(context,response2)}if(validator){if(headerValidator){let _header=structuredClone(context.headers);for(let[key,value]of request.headers)_header[key]=value;if(validator.headers.Check(_header)===!1)throw new ValidationError("header",validator.headers,_header)}else if(validator.headers?.Decode)context.headers=validator.headers.Decode(context.headers);if(paramsValidator?.Check(context.params)===!1)throw new ValidationError("params",validator.params,context.params);else if(validator.params?.Decode)context.params=validator.params.Decode(context.params);if(validator.query?.schema){let schema=validator.query.schema;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];let properties=schema.properties;for(let property of Object.keys(properties)){let value=properties[property];if((value.type==="array"||value.items?.type==="string")&&typeof context.query[property]==="string"&&context.query[property])context.query[property]=context.query[property].split(",")}}if(queryValidator?.Check(context.query)===!1)throw new ValidationError("query",validator.query,context.query);else if(validator.query?.Decode)context.query=validator.query.Decode(context.query);if(validator.createCookie?.()){let cookieValue={};for(let[key,value]of Object.entries(context.cookie))cookieValue[key]=value.value;if(validator.cookie.Check(cookieValue)===!1)throw new ValidationError("cookie",validator.cookie,cookieValue);else if(validator.cookie?.Decode)cookieValue=validator.cookie.Decode(cookieValue)}if(validator.createBody?.()?.Check(body)===!1)throw new ValidationError("body",validator.body,body);else if(validator.body?.Decode)context.body=validator.body.Decode(body)}if(hooks.beforeHandle)for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="resolve"){Object.assign(context,response2);continue}if(response2!==void 0){if(context.response=response2,hooks.afterHandle)for(let i2=0;i2<hooks.afterHandle.length;i2++){let newResponse=hooks.afterHandle[i2].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;if(newResponse)response2=newResponse}let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}}let response=typeof handle==="function"?handle(context):handle;if(response instanceof Promise)response=await response;if(!hooks.afterHandle?.length){let isCustomStatuResponse=response instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response=response.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response);response=temp}else throw new ValidationError("response",responseValidator,response);if(responseValidator?.Encode)response=responseValidator.Encode(response);if(responseValidator?.Clean)response=responseValidator.Clean(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let response2=hooks.afterHandle[i].fn(context);if(response2 instanceof Promise)response2=await response2;let isCustomStatuResponse=response2 instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response2.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response2=response2.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response2)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response2);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response2);response2=temp}else throw new ValidationError("response",responseValidator,response2);if(responseValidator?.Encode)context.response=response2=responseValidator.Encode(response2);if(responseValidator?.Clean)context.response=response2=responseValidator.Clean(response2);let result=mapEarlyResponse3(response2,context.set);if(result!==void 0)return context.response=result}}if(context.set.cookie&&cookieMeta?.sign){let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(cookieMeta.sign===!0){if(secret)for(let[key,cookie]of Object.entries(context.set.cookie))context.set.cookie[key].value=await signCookie(cookie.value,secret)}else{let properties=validator?.cookie?.schema?.properties;if(secret)for(let name of cookieMeta.sign){if(!(name in properties))continue;if(context.set.cookie[name]?.value)context.set.cookie[name].value=await signCookie(context.set.cookie[name].value,secret)}}}return mapResponse3(context.response=response,context.set)}catch(error2){let reportedError=error2 instanceof TransformDecodeError&&error2.error?error2.error:error2;return app.handleError(context,reportedError)}finally{if(app.event.afterResponse)setImmediate(async()=>{for(let afterResponse of app.event.afterResponse)await afterResponse.fn(context)})}}},createDynamicErrorHandler=(app)=>{let{mapResponse:mapResponse3}=app["~adapter"].handler;return async(context,error2)=>{let errorContext=Object.assign(context,{error:error2,code:error2.code});if(errorContext.set=context.set,app.event.error)for(let i=0;i<app.event.error.length;i++){let response=app.event.error[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)return context.response=mapResponse3(response,context.set)}return new Response(typeof error2.cause==="string"?error2.cause:error2.message,{headers:context.set.headers,status:error2.status??500})}};import{TypeSystemPolicy as TypeSystemPolicy2}from"@sinclair/typebox/system";class Elysia{config;server=null;dependencies={};"~Prefix"="";"~Singleton"=null;"~Definitions"=null;"~Metadata"=null;"~Ephemeral"=null;"~Volatile"=null;"~Routes"=null;singleton={decorator:{},store:{},derive:{},resolve:{}};get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}definitions={typebox:t.Module({}),type:{},error:{}};extender={macros:[],higherOrderFunctions:[]};validator={global:null,scoped:null,local:null,getCandidate(){if(!this.global&&!this.scoped&&!this.local)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return mergeSchemaValidator(mergeSchemaValidator(this.global,this.scoped),this.local)}};standaloneValidator={global:null,scoped:null,local:null};event={};telemetry;router={"~http":void 0,get http(){if(!this["~http"])this["~http"]=new _({lazy:!0,onParam:import_fast_decode_uri_component4.default});return this["~http"]},"~dynamic":void 0,get dynamic(){if(!this["~dynamic"])this["~dynamic"]=new _({onParam:import_fast_decode_uri_component4.default});return this["~dynamic"]},static:{},response:{},history:[]};routeTree={};get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}getGlobalDefinitions(){return this.definitions}inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1,path:!1,route:!1,url:!1};getServer(){return this.server}getParent(){return null}"~parser"={};_promisedModules;get promisedModules(){if(!this._promisedModules)this._promisedModules=new PromiseGroup(console.error,()=>{});return this._promisedModules}constructor(config={}){if(config.tags)if(!config.detail)config.detail={tags:config.tags};else config.detail.tags=config.tags;if(this.config={aot:env2.ELYSIA_AOT!=="false",nativeStaticResponse:!0,systemRouter:!0,encodeSchema:!0,normalize:!0,...config,prefix:config.prefix?config.prefix.charCodeAt(0)===47?config.prefix:`/${config.prefix}`:void 0,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this["~adapter"]=config.adapter??(typeof Bun!=="undefined"?BunAdapter:WebStandardAdapter),config?.analytic&&(config?.name||config?.seed!==void 0))this.telemetry={stack:new Error().stack}}"~adapter";env(model,_env=env2){if(getSchemaValidator(model,{modules:this.definitions.typebox,dynamic:!0,additionalProperties:!0,coerce:!0,sanitize:()=>this.config.sanitize}).Check(_env)===!1){let error2=new ValidationError("env",model,_env);throw new Error(error2.all.map((x)=>x.summary).join(`
363
- `))}return this}wrap(fn){return this.extender.higherOrderFunctions.push({checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:fn.toString()})),fn}),this}applyMacro(localHook){if(this.extender.macros.length){let manage=createMacroManager({globalHook:this.event,localHook}),manager={events:{global:this.event,local:localHook},get onParse(){return manage("parse")},get onTransform(){return manage("transform")},get onBeforeHandle(){return manage("beforeHandle")},get onAfterHandle(){return manage("afterHandle")},get mapResponse(){return manage("mapResponse")},get onAfterResponse(){return manage("afterResponse")},get onError(){return manage("error")}};for(let macro of this.extender.macros)traceBackMacro(macro.fn(manager),localHook,manage)}}get models(){let models={};for(let name of Object.keys(this.definitions.type))models[name]=getSchemaValidator(this.definitions.typebox.Import(name));return models.modules=this.definitions.typebox,models}add(method,path,handle,localHook,options,standaloneValidators){let skipPrefix=options?.skipPrefix??!1,allowMeta=options?.allowMeta??!1;if(localHook??={},standaloneValidators===void 0){if(standaloneValidators=[],this.standaloneValidator.local)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.local);if(this.standaloneValidator.scoped)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.scoped);if(this.standaloneValidator.global)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.global)}if(path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix)path=this.config.prefix+path;if(localHook?.type)switch(localHook.type){case"text":localHook.type="text/plain";break;case"json":localHook.type="application/json";break;case"formdata":localHook.type="multipart/form-data";break;case"urlencoded":localHook.type="application/x-www-form-urlencoded";break;case"arrayBuffer":localHook.type="application/octet-stream";break;default:break}let instanceValidator=this.validator.getCandidate(),cloned={body:localHook?.body??instanceValidator?.body,headers:localHook?.headers??instanceValidator?.headers,params:localHook?.params??instanceValidator?.params,query:localHook?.query??instanceValidator?.query,cookie:localHook?.cookie??instanceValidator?.cookie,response:localHook?.response??instanceValidator?.response},shouldPrecompile=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.compose===!0,createValidator=()=>{let models=this.definitions.type,dynamic=!this.config.aot,normalize=this.config.normalize,modules=this.definitions.typebox,sanitize2=()=>this.config.sanitize,cookieValidator=()=>{if(cloned.cookie||standaloneValidators.find((x)=>x.cookie))return getCookieValidator({modules,validator:cloned.cookie,defaultConfig:this.config.cookie,normalize,config:cloned.cookie?.config??{},dynamic,models,validators:standaloneValidators.map((x)=>x.cookie),sanitize:sanitize2})};return shouldPrecompile?{body:getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2}),headers:getSchemaValidator(cloned.headers,{modules,dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2}),params:getSchemaValidator(cloned.params,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2}),query:getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{modules,dynamic,models,normalize,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}}};if(instanceValidator.body||instanceValidator.cookie||instanceValidator.headers||instanceValidator.params||instanceValidator.query||instanceValidator.response)localHook=mergeHook(localHook,instanceValidator);if(localHook.tags)if(!localHook.detail)localHook.detail={tags:localHook.tags};else localHook.detail.tags=localHook.tags;if(isNotEmpty(this.config.detail))localHook.detail=mergeDeep(Object.assign({},this.config.detail),localHook.detail);this.applyMacro(localHook);let hooks=isNotEmpty(this.event)?mergeHook(this.event,localHookToLifeCycleStore(localHook)):lifeCycleToArray(localHookToLifeCycleStore(localHook));if(this.config.aot===!1){let validator=createValidator();this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle,route:path});let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.dynamic.add(method,encoded,{validator,hooks,content:localHook?.type,handle,route:path});if(this.config.strictPath===!1){let loosePath=getLoosePath(path);this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path});let encoded2=encodePath(loosePath);if(loosePath!==encoded2)this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path})}this.router.history.push({method,path,composed:null,handler:handle,compile:void 0,hooks,standaloneValidators});return}let adapter=this["~adapter"].handler,nativeStaticHandler=typeof handle!=="function"?()=>{let context={redirect,request:this["~adapter"].isWebStandard?new Request(`http://e.ly${path}`,{method}):void 0,server:null,set:{headers:Object.assign({},this.setHeaders)},status,error:status,store:this.store};try{this.event.request?.map((x)=>{if(typeof x.fn==="function")return x.fn(context);if(typeof x==="function")return x(context)})}catch(error2){let res;if(context.error=error2,this.event.error?.some((x)=>{if(typeof x.fn==="function")return res=x.fn(context);if(typeof x==="function")return res=x(context)}),res!==void 0)handle=res}let fn=adapter.createNativeStaticHandler?.(handle,hooks,context.set);return fn instanceof Promise?fn.then((fn2)=>{if(fn2)return fn2}):fn?.()}:void 0,useNativeStaticResponse=this.config.nativeStaticResponse===!0,addResponsePath=(path2)=>{if(!useNativeStaticResponse||!nativeStaticHandler)return;if(supportPerMethodInlineHandler)if(this.router.response[path2])this.router.response[path2][method]=nativeStaticHandler();else this.router.response[path2]={[method]:nativeStaticHandler()};else this.router.response[path2]=nativeStaticHandler()};addResponsePath(path);let _compiled,compile2=()=>{if(_compiled)return _compiled;return _compiled=composeHandler({app:this,path,method,hooks,validator:createValidator(),handler:typeof handle!=="function"&&typeof adapter.createStaticHandler!=="function"?()=>handle:handle,allowMeta,inference:this.inference})},oldIndex;if(`${method}_${path}`in this.routeTree)for(let i=0;i<this.router.history.length;i++){let route=this.router.history[i];if(route.path===path&&route.method===method){oldIndex=i;break}}else this.routeTree[`${method}_${path}`]=this.router.history.length;let index=oldIndex??this.router.history.length,mainHandler=shouldPrecompile?compile2():(ctx)=>(this.router.history[index].composed=compile2())(ctx);if(oldIndex!==void 0)this.router.history[oldIndex]=Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0);else this.router.history.push(Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0));let handler={handler:shouldPrecompile?mainHandler:void 0,compile(){return this.handler=compile2()}},staticRouter=this.router.static,isStaticPath=path.indexOf(":")===-1&&path.indexOf("*")===-1;if(method==="WS"){if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};return}if(this.router.http.add("WS",path,handler),!this.config.strictPath)this.router.http.add("WS",getLoosePath(path),handler);let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add("WS",encoded,handler);return}if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};if(!this.config.strictPath)addResponsePath(getLoosePath(path))}else{if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath=getLoosePath(path);addResponsePath(loosePath),this.router.http.add(method,loosePath,handler)}let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add(method,encoded,handler),addResponsePath(encoded)}}setHeaders;headers(header){if(!header)return this;if(!this.setHeaders)this.setHeaders={};return this.setHeaders=mergeDeep(this.setHeaders,header),this}onStart(handler){return this.on("start",handler),this}onRequest(handler){return this.on("request",handler),this}onParse(options,handler){if(!handler){if(typeof options==="string")return this.on("parse",this["~parser"][options]);return this.on("parse",options)}return this.on(options,"parse",handler)}parser(name,parser){return this["~parser"][name]=parser,this}onTransform(options,handler){if(!handler)return this.on("transform",options);return this.on(options,"transform",handler)}resolve(optionsOrResolve,resolve){if(!resolve)resolve=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"resolve",fn:resolve};return this.onBeforeHandle(optionsOrResolve,hook)}mapResolve(optionsOrResolve,mapper){if(!mapper)mapper=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"mapResolve",fn:mapper};return this.onBeforeHandle(optionsOrResolve,hook)}onBeforeHandle(options,handler){if(!handler)return this.on("beforeHandle",options);return this.on(options,"beforeHandle",handler)}onAfterHandle(options,handler){if(!handler)return this.on("afterHandle",options);return this.on(options,"afterHandle",handler)}mapResponse(options,handler){if(!handler)return this.on("mapResponse",options);return this.on(options,"mapResponse",handler)}onAfterResponse(options,handler){if(!handler)return this.on("afterResponse",options);return this.on(options,"afterResponse",handler)}trace(options,handler){if(!handler)handler=options,options={as:"local"};if(!Array.isArray(handler))handler=[handler];for(let fn of handler)this.on(options,"trace",createTracer(fn));return this}error(name,error2){switch(typeof name){case"string":return error2.prototype[ERROR_CODE]=name,this.definitions.error[name]=error2,this;case"function":return this.definitions.error=name(this.definitions.error),this}for(let[code,error3]of Object.entries(name))error3.prototype[ERROR_CODE]=code,this.definitions.error[code]=error3;return this}onError(options,handler){if(!handler)return this.on("error",options);return this.on(options,"error",handler)}onStop(handler){return this.on("stop",handler),this}on(optionsOrType,typeOrHandlers,handlers){let type;switch(typeof optionsOrType){case"string":type=optionsOrType,handlers=typeOrHandlers;break;case"object":if(type=typeOrHandlers,!Array.isArray(typeOrHandlers)&&typeof typeOrHandlers==="object")handlers=typeOrHandlers;break}if(Array.isArray(handlers))handlers=fnToContainer(handlers);else if(typeof handlers==="function")handlers=[{fn:handlers}];else handlers=[handlers];let handles=handlers;for(let handle of handles)if(handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local",type==="resolve"||type==="derive")handle.subType=type;if(type!=="trace")this.inference=sucrose({[type]:handles.map((x)=>x.fn)},this.inference);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type){case"start":this.event.start??=[],this.event.start.push(fn);break;case"request":this.event.request??=[],this.event.request.push(fn);break;case"parse":this.event.parse??=[],this.event.parse.push(fn);break;case"transform":this.event.transform??=[],this.event.transform.push(fn);break;case"derive":this.event.transform??=[],this.event.transform.push(fnToContainer(fn,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(fn);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(fnToContainer(fn,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(fn);break;case"trace":this.event.trace??=[],this.event.trace.push(fn);break;case"error":this.event.error??=[],this.event.error.push(fn);break;case"stop":this.event.stop??=[],this.event.stop.push(fn);break}}return this}as(type){if(promoteEvent(this.event.parse,type),promoteEvent(this.event.transform,type),promoteEvent(this.event.beforeHandle,type),promoteEvent(this.event.afterHandle,type),promoteEvent(this.event.mapResponse,type),promoteEvent(this.event.afterResponse,type),promoteEvent(this.event.trace,type),promoteEvent(this.event.error,type),type==="scoped"){if(this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null}else if(type==="global"){if(this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null;if(this.standaloneValidator.scoped!==null)this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null}return this}group(prefix,schemaOrRun,run){let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.getServer=()=>this.getServer(),instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance["~parser"]=this["~parser"],instance.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let isSchema=typeof schemaOrRun==="object",sandbox=(isSchema?run:schemaOrRun)(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks,standaloneValidators})=>{if(path=(isSchema?"":this.config.prefix??"")+prefix+path,isSchema){let hook=schemaOrRun,localHook=hooks;this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]]}),void 0,standaloneValidators)}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0},standaloneValidators)}),this}guard(hook,run){if(!run){if(typeof hook==="object"){if(this.applyMacro(hook),hook.detail)if(this.config.detail)this.config.detail=mergeDeep(Object.assign({},this.config.detail),hook.detail);else this.config.detail=hook.detail;if(hook.tags)if(!this.config.detail)this.config.detail={tags:hook.tags};else this.config.detail.tags=hook.tags;let type=hook.as??"local";if(hook.schema==="standalone"){if(!this.standaloneValidator[type])this.standaloneValidator[type]=[];let response=hook?.response||typeof hook?.response==="string"||hook?.response&&Kind6 in hook.response?{200:hook.response}:hook?.response;this.standaloneValidator[type].push({body:hook.body,headers:hook.headers,params:hook.params,query:hook.query,response,cookie:hook.cookie})}else this.validator[type]={body:hook.body??this.validator[type]?.body,headers:hook.headers??this.validator[type]?.headers,params:hook.params??this.validator[type]?.params,query:hook.query??this.validator[type]?.query,response:hook.response??this.validator[type]?.response,cookie:hook.cookie??this.validator[type]?.cookie};if(hook.parse)this.on({as:type},"parse",hook.parse);if(hook.transform)this.on({as:type},"transform",hook.transform);if(hook.derive)this.on({as:type},"derive",hook.derive);if(hook.beforeHandle)this.on({as:type},"beforeHandle",hook.beforeHandle);if(hook.resolve)this.on({as:type},"resolve",hook.resolve);if(hook.afterHandle)this.on({as:type},"afterHandle",hook.afterHandle);if(hook.mapResponse)this.on({as:type},"mapResponse",hook.mapResponse);if(hook.afterResponse)this.on({as:type},"afterResponse",hook.afterResponse);if(hook.error)this.on({as:type},"error",hook.error);return this}return this.guard({},hook)}let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance.getServer=()=>this.getServer();let sandbox=run(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.getServer=()=>this.server,sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks:localHook})=>{this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]]}))}),this}use(plugin){if(!plugin)return this;if(Array.isArray(plugin)){let app=this;for(let p of plugin)app=app.use(p);return app}if(plugin instanceof Promise)return this.promisedModules.add(plugin.then((plugin2)=>{if(typeof plugin2==="function")return plugin2(this);if(plugin2 instanceof Elysia)return this._use(plugin2).compile();if(plugin2.constructor.name==="Elysia")return this._use(plugin2).compile();if(typeof plugin2.default==="function")return plugin2.default(this);if(plugin2.default instanceof Elysia)return this._use(plugin2.default);if(plugin2.constructor.name==="Elysia")return this._use(plugin2.default);if(plugin2.constructor.name==="_Elysia")return this._use(plugin2.default);try{return this._use(plugin2.default)}catch(error2){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),error2}}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return this._use(plugin)}propagatePromiseModules(plugin){if(plugin.promisedModules.size<=0)return this;for(let promise of plugin.promisedModules.promises)this.promisedModules.add(promise.then((v)=>{if(!v)return;let t2=this._use(v);if(t2 instanceof Promise)return t2.then((v2)=>{if(v2)v2.compile();else v.compile()});return v.compile()}));return this}_use(plugin){if(typeof plugin==="function"){let instance=plugin(this);if(instance instanceof Promise)return this.promisedModules.add(instance.then((plugin2)=>{if(plugin2 instanceof Elysia){plugin2.getServer=()=>this.getServer(),plugin2.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin2.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin2.model(this.definitions.type),plugin2.error(this.definitions.error);for(let{method,path,handler,hooks,standaloneValidators}of Object.values(plugin2.router.history))this.add(method,path,handler,hooks,void 0,standaloneValidators);if(plugin2===this)return;return this.propagatePromiseModules(plugin2),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return instance}this.propagatePromiseModules(plugin);let name=plugin.config.name,seed=plugin.config.seed;if(plugin.getParent=()=>this,plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin.standaloneValidator?.scoped)if(this.standaloneValidator.local)this.standaloneValidator.local=this.standaloneValidator.local.concat(plugin.standaloneValidator.scoped);else this.standaloneValidator.local=plugin.standaloneValidator.scoped;if(plugin.standaloneValidator?.global)if(this.standaloneValidator.global)this.standaloneValidator.global=this.standaloneValidator.global.concat(plugin.standaloneValidator.global);else this.standaloneValidator.global=plugin.standaloneValidator.global;if(isNotEmpty(plugin["~parser"]))this["~parser"]={...plugin["~parser"],...this["~parser"]};if(plugin.setHeaders)this.headers(plugin.setHeaders);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(!this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))this.extender.macros=this.extender.macros.concat(plugin.extender.macros),this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}else{if(plugin.extender.macros.length)this.extender.macros=this.extender.macros.concat(plugin.extender.macros);if(plugin.extender.higherOrderFunctions.length)this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}if(deduplicateChecksum(this.extender.macros),plugin.extender.higherOrderFunctions.length){deduplicateChecksum(this.extender.higherOrderFunctions);let hofHashes=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let hof=this.extender.higherOrderFunctions[i];if(hof.checksum){if(hofHashes.includes(hof.checksum))this.extender.higherOrderFunctions.splice(i,1),i--;hofHashes.push(hof.checksum)}}hofHashes.length=0}if(this.inference=mergeInference(this.inference,plugin.inference),isNotEmpty(plugin.singleton.decorator))this.decorate(plugin.singleton.decorator);if(isNotEmpty(plugin.singleton.store))this.state(plugin.singleton.store);if(isNotEmpty(plugin.definitions.type))this.model(plugin.definitions.type);if(isNotEmpty(plugin.definitions.error))this.error(plugin.definitions.error);if(isNotEmpty(plugin.definitions.error))plugin.extender.macros=this.extender.macros.concat(plugin.extender.macros);for(let{method,path,handler,hooks,standaloneValidators}of Object.values(plugin.router.history))this.add(method,path,handler,hooks,void 0,standaloneValidators);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))return this;if(this.dependencies[name].push(this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies,stack:plugin.telemetry?.stack,routes:plugin.router.history,decorators:plugin.singleton,store:plugin.singleton.store,error:plugin.definitions.error,derive:plugin.event.transform?.filter((x)=>x?.subType==="derive").map((x)=>({fn:x.toString(),stack:new Error().stack??""})),resolve:plugin.event.transform?.filter((x)=>x?.subType==="resolve").map((x)=>({fn:x.toString(),stack:new Error().stack??""}))}:{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}),isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event),current)}else if(isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event));if(plugin.validator.global)this.validator.global=mergeHook(this.validator.global,{...plugin.validator.global});if(plugin.validator.scoped)this.validator.local=mergeHook(this.validator.local,{...plugin.validator.scoped});return this}macro(macro){if(typeof macro==="function"){let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:macro.toString()})),fn:macro};this.extender.macros.push(hook)}else if(typeof macro==="object"){for(let name of Object.keys(macro))if(typeof macro[name]==="object"){let actualValue={...macro[name]};macro[name]=(v)=>{if(v===!0)return actualValue}}let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:Object.entries(macro).map(([k2,v])=>`${k2}+${v}`).join(",")})),fn:()=>macro};this.extender.macros.push(hook)}return this}mount(path,handleOrConfig,config){if(path instanceof Elysia||typeof path==="function"||path.length===0||path==="/"){let run=typeof path==="function"?path:path instanceof Elysia?path.compile().fetch:handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw new Error("Invalid handler")})(),handler2=({request,path:path2})=>run(new Request(replaceUrlPath(request.url,path2),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL","/*",handler2,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:run}}),this}let handle=handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw new Error("Invalid handler")})(),length=path.length-(path.endsWith("*")?1:0),handler=({request,path:path2})=>handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL",path,handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this.route("ALL",path+(path.endsWith("/")?"*":"/*"),handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this}get(path,handler,hook){return this.add("GET",path,handler,hook),this}post(path,handler,hook){return this.add("POST",path,handler,hook),this}put(path,handler,hook){return this.add("PUT",path,handler,hook),this}patch(path,handler,hook){return this.add("PATCH",path,handler,hook),this}delete(path,handler,hook){return this.add("DELETE",path,handler,hook),this}options(path,handler,hook){return this.add("OPTIONS",path,handler,hook),this}all(path,handler,hook){return this.add("ALL",path,handler,hook),this}head(path,handler,hook){return this.add("HEAD",path,handler,hook),this}connect(path,handler,hook){return this.add("CONNECT",path,handler,hook),this}route(method,path,handler,hook){return this.add(method.toUpperCase(),path,handler,hook,hook?.config),this}ws(path,options){if(this["~adapter"].ws)this["~adapter"].ws(this,path,options);else console.warn("Current adapter doesn't support WebSocket");return this}state(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(!value||!isNotEmpty(value))return this;if(name){if(name in this.singleton.store)this.singleton.store[name]=mergeDeep(this.singleton.store[name],value,{override:as==="override"});else this.singleton.store[name]=value;return this}if(value===null)return this;return this.singleton.store=mergeDeep(this.singleton.store,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value}else this.singleton.store=value(this.singleton.store);return this;default:if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value;return this}}decorate(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(name){if(name in this.singleton.decorator)this.singleton.decorator[name]=mergeDeep(this.singleton.decorator[name],value,{override:as==="override"});else this.singleton.decorator[name]=value;return this}if(value===null)return this;return this.singleton.decorator=mergeDeep(this.singleton.decorator,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value}else this.singleton.decorator=value(this.singleton.decorator);return this;default:if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value;return this}}derive(optionsOrTransform,transform){if(!transform)transform=optionsOrTransform,optionsOrTransform={as:"local"};let hook={subType:"derive",fn:transform};return this.onTransform(optionsOrTransform,hook)}model(name,model){switch(typeof name){case"object":let parsedSchemas={},kvs=Object.entries(name);if(!kvs.length)return this;for(let[key,value]of kvs){if(key in this.definitions.type)continue;parsedSchemas[key]=this.definitions.type[key]=value,parsedSchemas[key].$id??=`#/components/schemas/${key}`}return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...parsedSchemas}),this;case"function":let result=name(this.definitions.type);return this.definitions.type=result,this.definitions.typebox=t.Module(result),this;case"string":if(!model)break;let newModel={...model,id:model.$id??`#/components/schemas/${name}`};return this.definitions.type[name]=model,this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...newModel}),this}return this.definitions.type[name]=model,this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,[name]:model}),this}Ref(key){return t.Ref(key)}mapDerive(optionsOrDerive,mapper){if(!mapper)mapper=optionsOrDerive,optionsOrDerive={as:"local"};let hook={subType:"mapDerive",fn:mapper};return this.onTransform(optionsOrDerive,hook)}affix(base,type,word){if(word==="")return this;let delimieter=["_","-"," "],capitalize=(word2)=>word2[0].toUpperCase()+word2.slice(1),joinKey=base==="prefix"?(prefix,word2)=>delimieter.includes(prefix.at(-1)??"")?prefix+word2:prefix+capitalize(word2):delimieter.includes(word.at(-1)??"")?(suffix,word2)=>word2+suffix:(suffix,word2)=>word2+capitalize(suffix),remap=(type2)=>{let store={};switch(type2){case"decorator":for(let key in this.singleton.decorator)store[joinKey(word,key)]=this.singleton.decorator[key];this.singleton.decorator=store;break;case"state":for(let key in this.singleton.store)store[joinKey(word,key)]=this.singleton.store[key];this.singleton.store=store;break;case"model":for(let key in this.definitions.type)store[joinKey(word,key)]=this.definitions.type[key];this.definitions.type=store;break;case"error":for(let key in this.definitions.error)store[joinKey(word,key)]=this.definitions.error[key];this.definitions.error=store;break}},types=Array.isArray(type)?type:[type];for(let type2 of types.some((x)=>x==="all")?["decorator","state","model","error"]:types)remap(type2);return this}prefix(type,word){return this.affix("prefix",type,word)}suffix(type,word){return this.affix("suffix",type,word)}compile(){if(this["~adapter"].isWebStandard){if(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this),typeof this.server?.reload==="function")this.server.reload({...this.server||{},fetch:this.fetch});return this}if(typeof this.server?.reload==="function")this.server.reload(this.server||{});return this._handle=composeGeneralHandler(this),this}handle=async(request)=>this.fetch(request);fetch=(request)=>{return(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this))(request)};handleError=async(context,error2)=>{return(this.handleError=this.config.aot?composeErrorHandler(this):createDynamicErrorHandler(this))(context,error2)};listen=(options,callback)=>{if(this["~adapter"].listen(this)(options,callback),this.promisedModules.size)clearSucroseCache(5000);return this.promisedModules.then(()=>{clearSucroseCache(1000)}),this};stop=async(closeActiveConnections)=>{return await this["~adapter"].stop?.(this,closeActiveConnections),this};[Symbol.dispose]=()=>{if(this.server)this.stop()};get modules(){return this.promisedModules}}export{validationDetail,t,status,sse,serializeCookie,replaceUrlPath,replaceSchemaType,redirect,mergeObjectArray,mergeHook,mapValueError,getSchemaValidator,getResponseSchemaValidator,form,file,error,env2 as env,Elysia as default,deduplicateChecksum,cloneInference,checksum,ValidationError,TypeSystemPolicy2 as TypeSystemPolicy,StatusMap,ParseError,NotFoundError,InvertedStatusMap,InvalidCookieSignature,InternalServerError,ElysiaFile,ElysiaCustomStatusResponse,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
362
+ `},listen(app){return(options,callback)=>{if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(app.compile(),typeof options==="string"){if(!isNumericString(options))throw new Error("Port must be a numeric value");options=parseInt(options)}let createStaticRoute=(iterator,{withAsync=!1}={})=>{let staticRoutes={},ops=[];for(let[path,route]of Object.entries(iterator))if(supportPerMethodInlineHandler){if(!route)continue;for(let[method,value]of Object.entries(route)){if(!value||!(method in supportedMethods))continue;if(value instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(value.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path][method]=awaited;if(isHTMLBundle(awaited))staticRoutes[path][method]=awaited}))}continue}if(!(value instanceof Response)&&!isHTMLBundle(value))continue;if(!staticRoutes[path])staticRoutes[path]={};staticRoutes[path][method]=value}}else{if(!route)continue;if(route instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(route.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path]=awaited}))}continue}if(!(route instanceof Response))continue;staticRoutes[path]=route}if(withAsync)return Promise.all(ops).then(()=>staticRoutes);return staticRoutes},serve=typeof options==="object"?{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},...options||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{},...options.websocket||{}},fetch:app.fetch}:{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{}},port:options,fetch:app.fetch};if(app.server=Bun.serve(serve),app.event.start)for(let i=0;i<app.event.start.length;i++)app.event.start[i].fn(app);if(callback)callback(app.server);process.on("beforeExit",()=>{if(app.server){if(app.server.stop?.(),app.server=null,app.event.stop)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}}),app.promisedModules.then(async()=>{app.server?.reload({...serve,fetch:app.fetch,routes:mergeRoutes(mergeRoutes(await createStaticRoute(app.router.response,{withAsync:!0}),mapRoutes(app)),app.config.serve?.routes)}),Bun?.gc(!1)})}},async stop(app,closeActiveConnections){if(app.server){if(app.server.stop(closeActiveConnections),app.server=null,app.event.stop?.length)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}else console.log("Elysia isn't running. Call `app.listen` to start the server.",new Error().stack)},ws(app,path,options){let{parse:parse2,body,response,...rest}=options,validateMessage=getSchemaValidator(body,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize}),validateResponse=getSchemaValidator(response,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize});app.route("WS",path,async(context)=>{let server=context.server??app.server,{set:set2,path:path2,qi,headers,query,params}=context;if(context.validator=validateResponse,options.upgrade){if(typeof options.upgrade==="function"){let temp=options.upgrade(context);if(temp instanceof Promise)await temp}else if(options.upgrade)Object.assign(set2.headers,options.upgrade)}if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"]);let handleResponse3=createHandleWSResponse(validateResponse),parseMessage=createWSMessageParser(parse2),_id;if(typeof options.beforeHandle==="function"){let result=options.beforeHandle(context);if(result instanceof Promise)await result}let errorHandlers=[...options.error?Array.isArray(options.error)?options.error:[options.error]:[],...(app.event.error??[]).map((x)=>typeof x==="function"?x:x.fn)].filter((x)=>x),hasCustomErrorHandlers=errorHandlers.length>0,handleErrors=!hasCustomErrorHandlers?()=>{}:async(ws,error2)=>{for(let handleError of errorHandlers){let response2=handleError(Object.assign(context,{error:error2}));if(response2 instanceof Promise)response2=await response2;if(await handleResponse3(ws,response2),response2)break}};if(server?.upgrade(context.request,{headers:isNotEmpty(set2.headers)?set2.headers:void 0,data:{...context,get id(){if(_id)return _id;return _id=randomId()},validator:validateResponse,ping(data){options.ping?.(data)},pong(data){options.pong?.(data)},open:async(ws)=>{try{await handleResponse3(ws,options.open?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},message:async(ws,_message)=>{let message=await parseMessage(ws,_message);if(validateMessage?.Check(message)===!1){let validationError=new ValidationError("message",validateMessage,message);if(!hasCustomErrorHandlers)return void ws.send(validationError.message);return handleErrors(ws,validationError)}try{await handleResponse3(ws,options.message?.(new ElysiaWS(ws,context,message),message))}catch(error2){handleErrors(ws,error2)}},drain:async(ws)=>{try{await handleResponse3(ws,options.drain?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},close:async(ws,code,reason)=>{try{await handleResponse3(ws,options.close?.(new ElysiaWS(ws,context),code,reason))}catch(error2){handleErrors(ws,error2)}}}}))return;return set2.status=400,"Expected a websocket connection"},{...rest,websocket:options})}};var env2=isBun?Bun.env:typeof process!=="undefined"&&process?.env?process.env:{};import{TransformDecodeError}from"@sinclair/typebox/value";var injectDefaultValues=(typeChecker,obj)=>{let schema=typeChecker.schema;if(!schema)return;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];if(!schema?.properties)return;for(let[key,keySchema]of Object.entries(schema.properties))obj[key]??=keySchema.default},createDynamicHandler=(app)=>{let{mapResponse:mapResponse3,mapEarlyResponse:mapEarlyResponse3}=app["~adapter"].handler,defaultHeader=app.setHeaders;return async(request)=>{let url=request.url,s=url.indexOf("/",11),qi=url.indexOf("?",s+1),path=qi===-1?url.substring(s):url.substring(s,qi),set2={cookie:{},status:200,headers:defaultHeader?{...defaultHeader}:{}},context=Object.assign({},app.singleton.decorator,{set:set2,store:app.singleton.store,request,path,qi,error:status,status,redirect});try{if(app.event.request)for(let i=0;i<app.event.request.length;i++){let onRequest=app.event.request[i].fn,response2=onRequest(context);if(response2 instanceof Promise)response2=await response2;if(response2=mapEarlyResponse3(response2,set2),response2)return context.response=response2}let methodKey=request.method==="GET"&&request.headers.get("upgrade")?.toLowerCase()==="websocket"?"WS":request.method,handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find(methodKey,path)??app.router.dynamic.find("ALL",path);if(!handler)throw context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),new NotFoundError;let{handle,hooks,validator,content,route}=handler.store,body;if(request.method!=="GET"&&request.method!=="HEAD")if(content)switch(content){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}else{let contentType;if(request.body)contentType=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);if(context.contentType=contentType,hooks.parse)for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn;if(typeof hook==="string")switch(hook){case"json":case"application/json":body=await request.json();break;case"text":case"text/plain":body=await request.text();break;case"urlencoded":case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"arrayBuffer":case"application/octet-stream":body=await request.arrayBuffer();break;case"formdata":case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break;default:let parser=app["~parser"][hook];if(parser){let temp=parser(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}break}else{let temp=hook(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}}if(delete context.contentType,body===void 0)switch(contentType){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}}context.route=route,context.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),context.headers={};for(let[key,value]of request.headers.entries())context.headers[key]=value;let cookieMeta={domain:app.config.cookie?.domain??validator?.cookie?.config.domain,expires:app.config.cookie?.expires??validator?.cookie?.config.expires,httpOnly:app.config.cookie?.httpOnly??validator?.cookie?.config.httpOnly,maxAge:app.config.cookie?.maxAge??validator?.cookie?.config.maxAge,path:app.config.cookie?.path??validator?.cookie?.config.path,priority:app.config.cookie?.priority??validator?.cookie?.config.priority,partitioned:app.config.cookie?.partitioned??validator?.cookie?.config.partitioned,sameSite:app.config.cookie?.sameSite??validator?.cookie?.config.sameSite,secure:app.config.cookie?.secure??validator?.cookie?.config.secure,secrets:app.config.cookie?.secrets??validator?.cookie?.config.secrets,sign:app.config.cookie?.sign??validator?.cookie?.config.sign},cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta);let headerValidator=validator?.createHeaders?.();if(headerValidator)injectDefaultValues(headerValidator,context.headers);let paramsValidator=validator?.createParams?.();if(paramsValidator)injectDefaultValues(paramsValidator,context.params);let queryValidator=validator?.createQuery?.();if(queryValidator)injectDefaultValues(queryValidator,context.query);if(hooks.transform)for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="derive")Object.assign(context,response2)}if(validator){if(headerValidator){let _header=structuredClone(context.headers);for(let[key,value]of request.headers)_header[key]=value;if(validator.headers.Check(_header)===!1)throw new ValidationError("header",validator.headers,_header)}else if(validator.headers?.Decode)context.headers=validator.headers.Decode(context.headers);if(paramsValidator?.Check(context.params)===!1)throw new ValidationError("params",validator.params,context.params);else if(validator.params?.Decode)context.params=validator.params.Decode(context.params);if(validator.query?.schema){let schema=validator.query.schema;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];let properties=schema.properties;for(let property of Object.keys(properties)){let value=properties[property];if((value.type==="array"||value.items?.type==="string")&&typeof context.query[property]==="string"&&context.query[property])context.query[property]=context.query[property].split(",")}}if(queryValidator?.Check(context.query)===!1)throw new ValidationError("query",validator.query,context.query);else if(validator.query?.Decode)context.query=validator.query.Decode(context.query);if(validator.createCookie?.()){let cookieValue={};for(let[key,value]of Object.entries(context.cookie))cookieValue[key]=value.value;if(validator.cookie.Check(cookieValue)===!1)throw new ValidationError("cookie",validator.cookie,cookieValue);else if(validator.cookie?.Decode)cookieValue=validator.cookie.Decode(cookieValue)}if(validator.createBody?.()?.Check(body)===!1)throw new ValidationError("body",validator.body,body);else if(validator.body?.Decode)context.body=validator.body.Decode(body)}if(hooks.beforeHandle)for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="resolve"){Object.assign(context,response2);continue}if(response2!==void 0){if(context.response=response2,hooks.afterHandle)for(let i2=0;i2<hooks.afterHandle.length;i2++){let newResponse=hooks.afterHandle[i2].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;if(newResponse)response2=newResponse}let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}}let response=typeof handle==="function"?handle(context):handle;if(response instanceof Promise)response=await response;if(!hooks.afterHandle?.length){let isCustomStatuResponse=response instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response=response.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response);response=temp}else throw new ValidationError("response",responseValidator,response);if(responseValidator?.Encode)response=responseValidator.Encode(response);if(responseValidator?.Clean)response=responseValidator.Clean(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let response2=hooks.afterHandle[i].fn(context);if(response2 instanceof Promise)response2=await response2;let isCustomStatuResponse=response2 instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response2.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response2=response2.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response2)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response2);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response2);response2=temp}else throw new ValidationError("response",responseValidator,response2);if(responseValidator?.Encode)context.response=response2=responseValidator.Encode(response2);if(responseValidator?.Clean)context.response=response2=responseValidator.Clean(response2);let result=mapEarlyResponse3(response2,context.set);if(result!==void 0)return context.response=result}}if(context.set.cookie&&cookieMeta?.sign){let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(cookieMeta.sign===!0){if(secret)for(let[key,cookie]of Object.entries(context.set.cookie))context.set.cookie[key].value=await signCookie(cookie.value,secret)}else{let properties=validator?.cookie?.schema?.properties;if(secret)for(let name of cookieMeta.sign){if(!(name in properties))continue;if(context.set.cookie[name]?.value)context.set.cookie[name].value=await signCookie(context.set.cookie[name].value,secret)}}}return mapResponse3(context.response=response,context.set)}catch(error2){let reportedError=error2 instanceof TransformDecodeError&&error2.error?error2.error:error2;return app.handleError(context,reportedError)}finally{if(app.event.afterResponse)setImmediate(async()=>{for(let afterResponse of app.event.afterResponse)await afterResponse.fn(context)})}}},createDynamicErrorHandler=(app)=>{let{mapResponse:mapResponse3}=app["~adapter"].handler;return async(context,error2)=>{let errorContext=Object.assign(context,{error:error2,code:error2.code});if(errorContext.set=context.set,app.event.error)for(let i=0;i<app.event.error.length;i++){let response=app.event.error[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)return context.response=mapResponse3(response,context.set)}return new Response(typeof error2.cause==="string"?error2.cause:error2.message,{headers:context.set.headers,status:error2.status??500})}};import{TypeSystemPolicy as TypeSystemPolicy2}from"@sinclair/typebox/system";class Elysia{config;server=null;dependencies={};"~Prefix"="";"~Singleton"=null;"~Definitions"=null;"~Metadata"=null;"~Ephemeral"=null;"~Volatile"=null;"~Routes"=null;singleton={decorator:{},store:{},derive:{},resolve:{}};get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}definitions={typebox:t.Module({}),type:{},error:{}};extender={macros:[],higherOrderFunctions:[]};validator={global:null,scoped:null,local:null,getCandidate(){if(!this.global&&!this.scoped&&!this.local)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return mergeSchemaValidator(mergeSchemaValidator(this.global,this.scoped),this.local)}};standaloneValidator={global:null,scoped:null,local:null};event={};telemetry;router={"~http":void 0,get http(){if(!this["~http"])this["~http"]=new _({lazy:!0,onParam:import_fast_decode_uri_component4.default});return this["~http"]},"~dynamic":void 0,get dynamic(){if(!this["~dynamic"])this["~dynamic"]=new _({onParam:import_fast_decode_uri_component4.default});return this["~dynamic"]},static:{},response:{},history:[]};routeTree={};get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}getGlobalDefinitions(){return this.definitions}inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1,path:!1,route:!1,url:!1};getServer(){return this.server}getParent(){return null}"~parser"={};_promisedModules;get promisedModules(){if(!this._promisedModules)this._promisedModules=new PromiseGroup(console.error,()=>{});return this._promisedModules}constructor(config={}){if(config.tags)if(!config.detail)config.detail={tags:config.tags};else config.detail.tags=config.tags;if(this.config={aot:env2.ELYSIA_AOT!=="false",nativeStaticResponse:!0,systemRouter:!0,encodeSchema:!0,normalize:!0,...config,prefix:config.prefix?config.prefix.charCodeAt(0)===47?config.prefix:`/${config.prefix}`:void 0,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this["~adapter"]=config.adapter??(typeof Bun!=="undefined"?BunAdapter:WebStandardAdapter),config?.analytic&&(config?.name||config?.seed!==void 0))this.telemetry={stack:new Error().stack}}"~adapter";env(model,_env=env2){if(getSchemaValidator(model,{modules:this.definitions.typebox,dynamic:!0,additionalProperties:!0,coerce:!0,sanitize:()=>this.config.sanitize}).Check(_env)===!1){let error2=new ValidationError("env",model,_env);throw new Error(error2.all.map((x)=>x.summary).join(`
363
+ `))}return this}wrap(fn){return this.extender.higherOrderFunctions.push({checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:fn.toString()})),fn}),this}applyMacro(localHook){if(this.extender.macros.length){let manage=createMacroManager({globalHook:this.event,localHook}),manager={events:{global:this.event,local:localHook},get onParse(){return manage("parse")},get onTransform(){return manage("transform")},get onBeforeHandle(){return manage("beforeHandle")},get onAfterHandle(){return manage("afterHandle")},get mapResponse(){return manage("mapResponse")},get onAfterResponse(){return manage("afterResponse")},get onError(){return manage("error")}};for(let macro of this.extender.macros)traceBackMacro(macro.fn(manager),localHook,manage)}}get models(){let models={};for(let name of Object.keys(this.definitions.type))models[name]=getSchemaValidator(this.definitions.typebox.Import(name));return models.modules=this.definitions.typebox,models}add(method,path,handle,localHook,options,standaloneValidators){let skipPrefix=options?.skipPrefix??!1,allowMeta=options?.allowMeta??!1;if(localHook??={},standaloneValidators===void 0){if(standaloneValidators=[],this.standaloneValidator.local)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.local);if(this.standaloneValidator.scoped)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.scoped);if(this.standaloneValidator.global)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.global)}if(path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix)path=this.config.prefix+path;if(localHook?.type)switch(localHook.type){case"text":localHook.type="text/plain";break;case"json":localHook.type="application/json";break;case"formdata":localHook.type="multipart/form-data";break;case"urlencoded":localHook.type="application/x-www-form-urlencoded";break;case"arrayBuffer":localHook.type="application/octet-stream";break;default:break}let instanceValidator=this.validator.getCandidate(),cloned={body:localHook?.body??instanceValidator?.body,headers:localHook?.headers??instanceValidator?.headers,params:localHook?.params??instanceValidator?.params,query:localHook?.query??instanceValidator?.query,cookie:localHook?.cookie??instanceValidator?.cookie,response:localHook?.response??instanceValidator?.response},shouldPrecompile=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.compose===!0,createValidator=()=>{let models=this.definitions.type,dynamic=!this.config.aot,normalize=this.config.normalize,modules=this.definitions.typebox,sanitize2=()=>this.config.sanitize,cookieValidator=()=>{if(cloned.cookie||standaloneValidators.find((x)=>x.cookie))return getCookieValidator({modules,validator:cloned.cookie,defaultConfig:this.config.cookie,normalize,config:cloned.cookie?.config??{},dynamic,models,validators:standaloneValidators.map((x)=>x.cookie),sanitize:sanitize2})};return shouldPrecompile?{body:getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2}),headers:getSchemaValidator(cloned.headers,{modules,dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2}),params:getSchemaValidator(cloned.params,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2}),query:getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{modules,dynamic,models,normalize,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}}};if(instanceValidator.body||instanceValidator.cookie||instanceValidator.headers||instanceValidator.params||instanceValidator.query||instanceValidator.response)localHook=mergeHook(localHook,instanceValidator);if(localHook.tags)if(!localHook.detail)localHook.detail={tags:localHook.tags};else localHook.detail.tags=localHook.tags;if(isNotEmpty(this.config.detail))localHook.detail=mergeDeep(Object.assign({},this.config.detail),localHook.detail);this.applyMacro(localHook);let hooks=isNotEmpty(this.event)?mergeHook(this.event,localHookToLifeCycleStore(localHook)):lifeCycleToArray(localHookToLifeCycleStore(localHook));if(this.config.aot===!1){let validator=createValidator();this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle,route:path});let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.dynamic.add(method,encoded,{validator,hooks,content:localHook?.type,handle,route:path});if(this.config.strictPath===!1){let loosePath=getLoosePath(path);this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path});let encoded2=encodePath(loosePath);if(loosePath!==encoded2)this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path})}this.router.history.push({method,path,composed:null,handler:handle,compile:void 0,hooks,standaloneValidators});return}let adapter=this["~adapter"].handler,nativeStaticHandler=typeof handle!=="function"?()=>{let context={redirect,request:this["~adapter"].isWebStandard?new Request(`http://e.ly${path}`,{method}):void 0,server:null,set:{headers:Object.assign({},this.setHeaders)},status,error:status,store:this.store};try{this.event.request?.map((x)=>{if(typeof x.fn==="function")return x.fn(context);if(typeof x==="function")return x(context)})}catch(error2){let res;if(context.error=error2,this.event.error?.some((x)=>{if(typeof x.fn==="function")return res=x.fn(context);if(typeof x==="function")return res=x(context)}),res!==void 0)handle=res}let fn=adapter.createNativeStaticHandler?.(handle,hooks,context.set);return fn instanceof Promise?fn.then((fn2)=>{if(fn2)return fn2}):fn?.()}:void 0,useNativeStaticResponse=this.config.nativeStaticResponse===!0,addResponsePath=(path2)=>{if(!useNativeStaticResponse||!nativeStaticHandler)return;if(supportPerMethodInlineHandler)if(this.router.response[path2])this.router.response[path2][method]=nativeStaticHandler();else this.router.response[path2]={[method]:nativeStaticHandler()};else this.router.response[path2]=nativeStaticHandler()};addResponsePath(path);let _compiled,compile2=()=>{if(_compiled)return _compiled;return _compiled=composeHandler({app:this,path,method,hooks,validator:createValidator(),handler:typeof handle!=="function"&&typeof adapter.createStaticHandler!=="function"?()=>handle:handle,allowMeta,inference:this.inference})},oldIndex;if(`${method}_${path}`in this.routeTree)for(let i=0;i<this.router.history.length;i++){let route=this.router.history[i];if(route.path===path&&route.method===method){oldIndex=i;break}}else this.routeTree[`${method}_${path}`]=this.router.history.length;let index=oldIndex??this.router.history.length,mainHandler=shouldPrecompile?compile2():(ctx)=>(this.router.history[index].composed=compile2())(ctx);if(oldIndex!==void 0)this.router.history[oldIndex]=Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0);else this.router.history.push(Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0));let handler={handler:shouldPrecompile?mainHandler:void 0,compile(){return this.handler=compile2()}},staticRouter=this.router.static,isStaticPath=path.indexOf(":")===-1&&path.indexOf("*")===-1;if(method==="WS"){if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};return}if(this.router.http.add("WS",path,handler),!this.config.strictPath)this.router.http.add("WS",getLoosePath(path),handler);let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add("WS",encoded,handler);return}if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};if(!this.config.strictPath)addResponsePath(getLoosePath(path))}else{if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath=getLoosePath(path);addResponsePath(loosePath),this.router.http.add(method,loosePath,handler)}let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add(method,encoded,handler),addResponsePath(encoded)}}setHeaders;headers(header){if(!header)return this;if(!this.setHeaders)this.setHeaders={};return this.setHeaders=mergeDeep(this.setHeaders,header),this}onStart(handler){return this.on("start",handler),this}onRequest(handler){return this.on("request",handler),this}onParse(options,handler){if(!handler){if(typeof options==="string")return this.on("parse",this["~parser"][options]);return this.on("parse",options)}return this.on(options,"parse",handler)}parser(name,parser){return this["~parser"][name]=parser,this}onTransform(options,handler){if(!handler)return this.on("transform",options);return this.on(options,"transform",handler)}resolve(optionsOrResolve,resolve){if(!resolve)resolve=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"resolve",fn:resolve};return this.onBeforeHandle(optionsOrResolve,hook)}mapResolve(optionsOrResolve,mapper){if(!mapper)mapper=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"mapResolve",fn:mapper};return this.onBeforeHandle(optionsOrResolve,hook)}onBeforeHandle(options,handler){if(!handler)return this.on("beforeHandle",options);return this.on(options,"beforeHandle",handler)}onAfterHandle(options,handler){if(!handler)return this.on("afterHandle",options);return this.on(options,"afterHandle",handler)}mapResponse(options,handler){if(!handler)return this.on("mapResponse",options);return this.on(options,"mapResponse",handler)}onAfterResponse(options,handler){if(!handler)return this.on("afterResponse",options);return this.on(options,"afterResponse",handler)}trace(options,handler){if(!handler)handler=options,options={as:"local"};if(!Array.isArray(handler))handler=[handler];for(let fn of handler)this.on(options,"trace",createTracer(fn));return this}error(name,error2){switch(typeof name){case"string":return error2.prototype[ERROR_CODE]=name,this.definitions.error[name]=error2,this;case"function":return this.definitions.error=name(this.definitions.error),this}for(let[code,error3]of Object.entries(name))error3.prototype[ERROR_CODE]=code,this.definitions.error[code]=error3;return this}onError(options,handler){if(!handler)return this.on("error",options);return this.on(options,"error",handler)}onStop(handler){return this.on("stop",handler),this}on(optionsOrType,typeOrHandlers,handlers){let type;switch(typeof optionsOrType){case"string":type=optionsOrType,handlers=typeOrHandlers;break;case"object":if(type=typeOrHandlers,!Array.isArray(typeOrHandlers)&&typeof typeOrHandlers==="object")handlers=typeOrHandlers;break}if(Array.isArray(handlers))handlers=fnToContainer(handlers);else if(typeof handlers==="function")handlers=[{fn:handlers}];else handlers=[handlers];let handles=handlers;for(let handle of handles)if(handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local",type==="resolve"||type==="derive")handle.subType=type;if(type!=="trace")this.inference=sucrose({[type]:handles.map((x)=>x.fn)},this.inference);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type){case"start":this.event.start??=[],this.event.start.push(fn);break;case"request":this.event.request??=[],this.event.request.push(fn);break;case"parse":this.event.parse??=[],this.event.parse.push(fn);break;case"transform":this.event.transform??=[],this.event.transform.push(fn);break;case"derive":this.event.transform??=[],this.event.transform.push(fnToContainer(fn,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(fn);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(fnToContainer(fn,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(fn);break;case"trace":this.event.trace??=[],this.event.trace.push(fn);break;case"error":this.event.error??=[],this.event.error.push(fn);break;case"stop":this.event.stop??=[],this.event.stop.push(fn);break}}return this}as(type){if(promoteEvent(this.event.parse,type),promoteEvent(this.event.transform,type),promoteEvent(this.event.beforeHandle,type),promoteEvent(this.event.afterHandle,type),promoteEvent(this.event.mapResponse,type),promoteEvent(this.event.afterResponse,type),promoteEvent(this.event.trace,type),promoteEvent(this.event.error,type),type==="scoped"){if(this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null}else if(type==="global"){if(this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null;if(this.standaloneValidator.scoped!==null)this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null}return this}group(prefix,schemaOrRun,run){let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.getServer=()=>this.getServer(),instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance["~parser"]=this["~parser"],instance.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let isSchema=typeof schemaOrRun==="object",sandbox=(isSchema?run:schemaOrRun)(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks,standaloneValidators})=>{if(path=(isSchema?"":this.config.prefix??"")+prefix+path,isSchema){let hook=schemaOrRun,localHook=hooks;this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]]}),void 0,standaloneValidators)}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0},standaloneValidators)}),this}guard(hook,run){if(!run){if(typeof hook==="object"){if(this.applyMacro(hook),hook.detail)if(this.config.detail)this.config.detail=mergeDeep(Object.assign({},this.config.detail),hook.detail);else this.config.detail=hook.detail;if(hook.tags)if(!this.config.detail)this.config.detail={tags:hook.tags};else this.config.detail.tags=hook.tags;let type=hook.as??"local";if(hook.schema==="standalone"){if(!this.standaloneValidator[type])this.standaloneValidator[type]=[];let response=hook?.response||typeof hook?.response==="string"||hook?.response&&Kind6 in hook.response?{200:hook.response}:hook?.response;this.standaloneValidator[type].push({body:hook.body,headers:hook.headers,params:hook.params,query:hook.query,response,cookie:hook.cookie})}else this.validator[type]={body:hook.body??this.validator[type]?.body,headers:hook.headers??this.validator[type]?.headers,params:hook.params??this.validator[type]?.params,query:hook.query??this.validator[type]?.query,response:hook.response??this.validator[type]?.response,cookie:hook.cookie??this.validator[type]?.cookie};if(hook.parse)this.on({as:type},"parse",hook.parse);if(hook.transform)this.on({as:type},"transform",hook.transform);if(hook.derive)this.on({as:type},"derive",hook.derive);if(hook.beforeHandle)this.on({as:type},"beforeHandle",hook.beforeHandle);if(hook.resolve)this.on({as:type},"resolve",hook.resolve);if(hook.afterHandle)this.on({as:type},"afterHandle",hook.afterHandle);if(hook.mapResponse)this.on({as:type},"mapResponse",hook.mapResponse);if(hook.afterResponse)this.on({as:type},"afterResponse",hook.afterResponse);if(hook.error)this.on({as:type},"error",hook.error);return this}return this.guard({},hook)}let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance.getServer=()=>this.getServer();let sandbox=run(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.getServer=()=>this.server,sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks:localHook})=>{this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]]}))}),this}use(plugin){if(!plugin)return this;if(Array.isArray(plugin)){let app=this;for(let p of plugin)app=app.use(p);return app}if(plugin instanceof Promise)return this.promisedModules.add(plugin.then((plugin2)=>{if(typeof plugin2==="function")return plugin2(this);if(plugin2 instanceof Elysia)return this._use(plugin2).compile();if(plugin2.constructor?.name==="Elysia")return this._use(plugin2).compile();if(typeof plugin2.default==="function")return plugin2.default(this);if(plugin2.default instanceof Elysia)return this._use(plugin2.default);if(plugin2.constructor?.name==="Elysia")return this._use(plugin2.default);if(plugin2.constructor?.name==="_Elysia")return this._use(plugin2.default);try{return this._use(plugin2.default)}catch(error2){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),error2}}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return this._use(plugin)}propagatePromiseModules(plugin){if(plugin.promisedModules.size<=0)return this;for(let promise of plugin.promisedModules.promises)this.promisedModules.add(promise.then((v)=>{if(!v)return;let t2=this._use(v);if(t2 instanceof Promise)return t2.then((v2)=>{if(v2)v2.compile();else v.compile()});return v.compile()}));return this}_use(plugin){if(typeof plugin==="function"){let instance=plugin(this);if(instance instanceof Promise)return this.promisedModules.add(instance.then((plugin2)=>{if(plugin2 instanceof Elysia){plugin2.getServer=()=>this.getServer(),plugin2.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin2.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin2.model(this.definitions.type),plugin2.error(this.definitions.error);for(let{method,path,handler,hooks,standaloneValidators}of Object.values(plugin2.router.history))this.add(method,path,handler,hooks,void 0,standaloneValidators);if(plugin2===this)return;return this.propagatePromiseModules(plugin2),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return instance}this.propagatePromiseModules(plugin);let name=plugin.config.name,seed=plugin.config.seed;if(plugin.getParent=()=>this,plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin.standaloneValidator?.scoped)if(this.standaloneValidator.local)this.standaloneValidator.local=this.standaloneValidator.local.concat(plugin.standaloneValidator.scoped);else this.standaloneValidator.local=plugin.standaloneValidator.scoped;if(plugin.standaloneValidator?.global)if(this.standaloneValidator.global)this.standaloneValidator.global=this.standaloneValidator.global.concat(plugin.standaloneValidator.global);else this.standaloneValidator.global=plugin.standaloneValidator.global;if(isNotEmpty(plugin["~parser"]))this["~parser"]={...plugin["~parser"],...this["~parser"]};if(plugin.setHeaders)this.headers(plugin.setHeaders);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(!this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))this.extender.macros=this.extender.macros.concat(plugin.extender.macros),this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}else{if(plugin.extender.macros.length)this.extender.macros=this.extender.macros.concat(plugin.extender.macros);if(plugin.extender.higherOrderFunctions.length)this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}if(deduplicateChecksum(this.extender.macros),plugin.extender.higherOrderFunctions.length){deduplicateChecksum(this.extender.higherOrderFunctions);let hofHashes=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let hof=this.extender.higherOrderFunctions[i];if(hof.checksum){if(hofHashes.includes(hof.checksum))this.extender.higherOrderFunctions.splice(i,1),i--;hofHashes.push(hof.checksum)}}hofHashes.length=0}if(this.inference=mergeInference(this.inference,plugin.inference),isNotEmpty(plugin.singleton.decorator))this.decorate(plugin.singleton.decorator);if(isNotEmpty(plugin.singleton.store))this.state(plugin.singleton.store);if(isNotEmpty(plugin.definitions.type))this.model(plugin.definitions.type);if(isNotEmpty(plugin.definitions.error))this.error(plugin.definitions.error);if(isNotEmpty(plugin.definitions.error))plugin.extender.macros=this.extender.macros.concat(plugin.extender.macros);for(let{method,path,handler,hooks,standaloneValidators}of Object.values(plugin.router.history))this.add(method,path,handler,hooks,void 0,standaloneValidators);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))return this;if(this.dependencies[name].push(this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies,stack:plugin.telemetry?.stack,routes:plugin.router.history,decorators:plugin.singleton,store:plugin.singleton.store,error:plugin.definitions.error,derive:plugin.event.transform?.filter((x)=>x?.subType==="derive").map((x)=>({fn:x.toString(),stack:new Error().stack??""})),resolve:plugin.event.transform?.filter((x)=>x?.subType==="resolve").map((x)=>({fn:x.toString(),stack:new Error().stack??""}))}:{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}),isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event),current)}else if(isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event));if(plugin.validator.global)this.validator.global=mergeHook(this.validator.global,{...plugin.validator.global});if(plugin.validator.scoped)this.validator.local=mergeHook(this.validator.local,{...plugin.validator.scoped});return this}macro(macro){if(typeof macro==="function"){let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:macro.toString()})),fn:macro};this.extender.macros.push(hook)}else if(typeof macro==="object"){for(let name of Object.keys(macro))if(typeof macro[name]==="object"){let actualValue={...macro[name]};macro[name]=(v)=>{if(v===!0)return actualValue}}let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:Object.entries(macro).map(([k2,v])=>`${k2}+${v}`).join(",")})),fn:()=>macro};this.extender.macros.push(hook)}return this}mount(path,handleOrConfig,config){if(path instanceof Elysia||typeof path==="function"||path.length===0||path==="/"){let run=typeof path==="function"?path:path instanceof Elysia?path.compile().fetch:handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw new Error("Invalid handler")})(),handler2=({request,path:path2})=>run(new Request(replaceUrlPath(request.url,path2),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL","/*",handler2,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:run}}),this}let handle=handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw new Error("Invalid handler")})(),length=path.length-(path.endsWith("*")?1:0),handler=({request,path:path2})=>handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL",path,handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this.route("ALL",path+(path.endsWith("/")?"*":"/*"),handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this}get(path,handler,hook){return this.add("GET",path,handler,hook),this}post(path,handler,hook){return this.add("POST",path,handler,hook),this}put(path,handler,hook){return this.add("PUT",path,handler,hook),this}patch(path,handler,hook){return this.add("PATCH",path,handler,hook),this}delete(path,handler,hook){return this.add("DELETE",path,handler,hook),this}options(path,handler,hook){return this.add("OPTIONS",path,handler,hook),this}all(path,handler,hook){return this.add("ALL",path,handler,hook),this}head(path,handler,hook){return this.add("HEAD",path,handler,hook),this}connect(path,handler,hook){return this.add("CONNECT",path,handler,hook),this}route(method,path,handler,hook){return this.add(method.toUpperCase(),path,handler,hook,hook?.config),this}ws(path,options){if(this["~adapter"].ws)this["~adapter"].ws(this,path,options);else console.warn("Current adapter doesn't support WebSocket");return this}state(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(!value||!isNotEmpty(value))return this;if(name){if(name in this.singleton.store)this.singleton.store[name]=mergeDeep(this.singleton.store[name],value,{override:as==="override"});else this.singleton.store[name]=value;return this}if(value===null)return this;return this.singleton.store=mergeDeep(this.singleton.store,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value}else this.singleton.store=value(this.singleton.store);return this;default:if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value;return this}}decorate(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(name){if(name in this.singleton.decorator)this.singleton.decorator[name]=mergeDeep(this.singleton.decorator[name],value,{override:as==="override"});else this.singleton.decorator[name]=value;return this}if(value===null)return this;return this.singleton.decorator=mergeDeep(this.singleton.decorator,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value}else this.singleton.decorator=value(this.singleton.decorator);return this;default:if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value;return this}}derive(optionsOrTransform,transform){if(!transform)transform=optionsOrTransform,optionsOrTransform={as:"local"};let hook={subType:"derive",fn:transform};return this.onTransform(optionsOrTransform,hook)}model(name,model){switch(typeof name){case"object":let parsedSchemas={},kvs=Object.entries(name);if(!kvs.length)return this;for(let[key,value]of kvs){if(key in this.definitions.type)continue;parsedSchemas[key]=this.definitions.type[key]=value,parsedSchemas[key].$id??=`#/components/schemas/${key}`}return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...parsedSchemas}),this;case"function":let result=name(this.definitions.type);return this.definitions.type=result,this.definitions.typebox=t.Module(result),this;case"string":if(!model)break;let newModel={...model,id:model.$id??`#/components/schemas/${name}`};return this.definitions.type[name]=model,this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...newModel}),this}return this.definitions.type[name]=model,this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,[name]:model}),this}Ref(key){return t.Ref(key)}mapDerive(optionsOrDerive,mapper){if(!mapper)mapper=optionsOrDerive,optionsOrDerive={as:"local"};let hook={subType:"mapDerive",fn:mapper};return this.onTransform(optionsOrDerive,hook)}affix(base,type,word){if(word==="")return this;let delimieter=["_","-"," "],capitalize=(word2)=>word2[0].toUpperCase()+word2.slice(1),joinKey=base==="prefix"?(prefix,word2)=>delimieter.includes(prefix.at(-1)??"")?prefix+word2:prefix+capitalize(word2):delimieter.includes(word.at(-1)??"")?(suffix,word2)=>word2+suffix:(suffix,word2)=>word2+capitalize(suffix),remap=(type2)=>{let store={};switch(type2){case"decorator":for(let key in this.singleton.decorator)store[joinKey(word,key)]=this.singleton.decorator[key];this.singleton.decorator=store;break;case"state":for(let key in this.singleton.store)store[joinKey(word,key)]=this.singleton.store[key];this.singleton.store=store;break;case"model":for(let key in this.definitions.type)store[joinKey(word,key)]=this.definitions.type[key];this.definitions.type=store;break;case"error":for(let key in this.definitions.error)store[joinKey(word,key)]=this.definitions.error[key];this.definitions.error=store;break}},types=Array.isArray(type)?type:[type];for(let type2 of types.some((x)=>x==="all")?["decorator","state","model","error"]:types)remap(type2);return this}prefix(type,word){return this.affix("prefix",type,word)}suffix(type,word){return this.affix("suffix",type,word)}compile(){if(this["~adapter"].isWebStandard){if(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this),typeof this.server?.reload==="function")this.server.reload({...this.server||{},fetch:this.fetch});return this}if(typeof this.server?.reload==="function")this.server.reload(this.server||{});return this._handle=composeGeneralHandler(this),this}handle=async(request)=>this.fetch(request);fetch=(request)=>{return(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this))(request)};handleError=async(context,error2)=>{return(this.handleError=this.config.aot?composeErrorHandler(this):createDynamicErrorHandler(this))(context,error2)};listen=(options,callback)=>{if(this["~adapter"].listen(this)(options,callback),this.promisedModules.size)clearSucroseCache(5000);return this.promisedModules.then(()=>{clearSucroseCache(1000)}),this};stop=async(closeActiveConnections)=>{return await this["~adapter"].stop?.(this,closeActiveConnections),this};[Symbol.dispose]=()=>{if(this.server)this.stop()};get modules(){return this.promisedModules}}export{validationDetail,t,status,sse,serializeCookie,replaceUrlPath,replaceSchemaType,redirect,mergeObjectArray,mergeHook,mapValueError,getSchemaValidator,getResponseSchemaValidator,form,file,error,env2 as env,Elysia as default,deduplicateChecksum,cloneInference,checksum,ValidationError,TypeSystemPolicy2 as TypeSystemPolicy,StatusMap,ParseError,NotFoundError,InvertedStatusMap,InvalidCookieSignature,InternalServerError,ElysiaFile,ElysiaCustomStatusResponse,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
364
364
 
365
- //# debugId=FB438C280C6B36C464756E2164756E21
365
+ //# debugId=F2851B3850DAB97064756E2164756E21
366
366
  //# sourceMappingURL=index.js.map