elysia 1.3.3 → 1.3.4-exp.0

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,7 +1,14 @@
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_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 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(uri2){var percentPosition=uri2.indexOf("%");if(percentPosition===-1)return uri2;var length=uri2.length,decoded="",last=0,codepoint=0,startOfOctets=percentPosition,state=UTF8_ACCEPT;while(percentPosition>-1&&percentPosition<length){var high=hexCodeToInt(uri2[percentPosition+1],4),low=hexCodeToInt(uri2[percentPosition+2],0),byte2=high|low,type=UTF8_DATA[byte2];if(state=UTF8_DATA[256+state+type],codepoint=codepoint<<6|byte2&UTF8_DATA[364+type],state===UTF8_ACCEPT)decoded+=uri2.slice(last,startOfOctets),decoded+=codepoint<=65535?String.fromCharCode(codepoint):String.fromCharCode(55232+(codepoint>>10),56320+(codepoint&1023)),codepoint=0,last=percentPosition+3,percentPosition=startOfOctets=uri2.indexOf("%",last);else if(state===UTF8_REJECT)return null;else{if(percentPosition+=3,percentPosition<length&&uri2.charCodeAt(percentPosition)===37)continue;return null}}return decoded+uri2.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 Y=(A,b)=>{let v=b?.length?{}:null;if(v)for(let K of b)v[K.part.charCodeAt(0)]=K;return{part:A,store:null,inert:v,params:null,wildcardStore:null}},k=(A,b)=>({...A,part:b}),T=(A)=>({name:A,store:null,inert:null});class _{config;root={};history=[];deferred=[];constructor(A={}){if(this.config=A,A.lazy)this.find=this.lazyFind}static regex={static:/:.+?(?=\/|$)/,params:/:.+?(?=\/|$)/g,optionalParams:/:.+?\?(?=\/|$)/g};lazyFind=(A,b)=>{if(!this.config.lazy)return this.find;return this.build(),this.find(A,b)};build(){if(!this.config.lazy)return;for(let[A,b,v]of this.deferred)this.add(A,b,v,{lazy:!1,ignoreHistory:!0});this.deferred=[],this.find=(A,b)=>{let v=this.root[A];if(!v)return null;return $(b,b.length,v,0)}}add(A,b,v,{ignoreError:K=!1,ignoreHistory:V=!1,lazy:U=this.config.lazy}={}){if(U)return this.find=this.lazyFind,this.deferred.push([A,b,v]),v;if(typeof b!=="string")throw new TypeError("Route path must be a string");if(b==="")b="/";else if(b[0]!=="/")b=`/${b}`;let J=b[b.length-1]==="*",F=b.match(_.regex.optionalParams);if(F){let S=b.replaceAll("?","");this.add(A,S,v,{ignoreError:K,ignoreHistory:V,lazy:U});for(let D=0;D<F.length;D++){let B=b.replace("/"+F[D],"");this.add(A,B,v,{ignoreError:!0,ignoreHistory:V,lazy:U})}return v}if(F)b=b.replaceAll("?","");if(this.history.find(([S,D,B])=>S===A&&D===b))return v;if(J||F&&b.charCodeAt(b.length-1)===63)b=b.slice(0,-1);if(!V)this.history.push([A,b,v]);let G=b.split(_.regex.static),X=b.match(_.regex.params)||[];if(G[G.length-1]==="")G.pop();let q;if(!this.root[A])q=this.root[A]=Y("/");else q=this.root[A];let O=0;for(let S=0;S<G.length;++S){let D=G[S];if(S>0){let B=X[O++].slice(1);if(q.params===null)q.params=T(B);else if(q.params.name!==B)if(K)return v;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`);let Q=q.params;if(Q.inert===null){q=Q.inert=Y(D);continue}q=Q.inert}for(let B=0;;){if(B===D.length){if(B<q.part.length){let Q=k(q,q.part.slice(B));Object.assign(q,Y(D,[Q]))}break}if(B===q.part.length){if(q.inert===null)q.inert={};let Q=q.inert[D.charCodeAt(B)];if(Q){q=Q,D=D.slice(B),B=0;continue}let Z=Y(D.slice(B));q.inert[D.charCodeAt(B)]=Z,q=Z;break}if(D[B]!==q.part[B]){let Q=k(q,q.part.slice(B)),Z=Y(D.slice(B));Object.assign(q,Y(q.part.slice(0,B),[Q,Z])),q=Z;break}++B}}if(O<X.length){let D=X[O].slice(1);if(q.params===null)q.params=T(D);else if(q.params.name!==D)if(K)return v;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`);if(q.params.store===null)q.params.store=v;return q.params.store}if(J){if(q.wildcardStore===null)q.wildcardStore=v;return q.wildcardStore}if(q.store===null)q.store=v;return q.store}find(A,b){let v=this.root[A];if(!v)return null;return $(b,b.length,v,0)}}var $=(A,b,v,K)=>{let V=v.part,U=V.length,J=K+U;if(U>1){if(J>b)return null;if(U<15){for(let F=1,G=K+1;F<U;++F,++G)if(V.charCodeAt(F)!==A.charCodeAt(G))return null}else if(A.slice(K,J)!==V)return null}if(J===b){if(v.store!==null)return{store:v.store,params:{}};if(v.wildcardStore!==null)return{store:v.wildcardStore,params:{"*":""}};return null}if(v.inert!==null){let F=v.inert[A.charCodeAt(J)];if(F!==void 0){let G=$(A,b,F,J);if(G!==null)return G}}if(v.params!==null){let{store:F,name:G,inert:X}=v.params,q=A.indexOf("/",J);if(q!==J){if(q===-1||q>=b){if(F!==null){let O={};return O[G]=A.substring(J,b),{store:F,params:O}}}else if(X!==null){let O=$(A,b,X,q);if(O!==null)return O.params[G]=A.substring(J,q),O}}}if(v.wildcardStore!==null)return{store:v.wildcardStore,params:{"*":A.substring(J,b)}};return null};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),{}),mergeResponse=(a,b)=>{let isRecordNumber=(x)=>typeof x==="object"&&Object.keys(x).every(isNumericString);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)=>{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)=>{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!=="string")throw new TypeError("Cookie value must be provided as a string.");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)=>{if(a.start?.map)a.start=a.start.map((x)=>x.fn);if(a.request?.map)a.request=a.request.map((x)=>x.fn);if(a.parse?.map)a.parse=a.parse.map((x)=>x.fn);if(a.transform?.map)a.transform=a.transform.map((x)=>x.fn);if(a.beforeHandle?.map)a.beforeHandle=a.beforeHandle.map((x)=>x.fn);if(a.afterHandle?.map)a.afterHandle=a.afterHandle.map((x)=>x.fn);if(a.mapResponse?.map)a.mapResponse=a.mapResponse.map((x)=>x.fn);if(a.afterResponse?.map)a.afterResponse=a.afterResponse.map((x)=>x.fn);if(a.trace?.map)a.trace=a.trace.map((x)=>x.fn);else a.trace=[];if(a.error?.map)a.error=a.error.map((x)=>x.fn);if(a.stop?.map)a.stop=a.stop.map((x)=>x.fn);return a},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)=>{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 x in obj)return!0;return!1};var 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})();var env=typeof Bun!=="undefined"?Bun.env:typeof process!=="undefined"?process?.env:void 0,ERROR_CODE=Symbol("ElysiaErrorCode"),isProduction=(env?.NODE_ENV??env?.ENV)==="production";class ElysiaCustomStatusResponse{code;response;constructor(code,response){let res=response??(code in InvertedStatusMap?InvertedStatusMap[code]:code);this.code=StatusMap[code]??code,this.response=res}}var status=(code,response)=>new ElysiaCustomStatusResponse(code,response),error=status;class InternalServerError extends Error{code="INTERNAL_SERVER_ERROR";status=500;constructor(message){super(message??"INTERNAL_SERVER_ERROR")}}class NotFoundError extends Error{code="NOT_FOUND";status=404;constructor(message){super(message??"NOT_FOUND")}}class ParseError extends Error{code="PARSE";status=400;constructor(cause){super("Bad Request",{cause})}}class InvalidCookieSignature extends Error{key;code="INVALID_COOKIE_SIGNATURE";status=400;constructor(key,message){super(message??`"${key}" has invalid cookie signature`);this.key=key}}var mapValueError=(error2)=>{if(!error2)return{summary:void 0};let{message,path,value,type}=error2,property=path.slice(1).replaceAll("/","."),isRoot=path==="";switch(type){case 42:return{...error2,summary:isRoot?"Value should not be provided":`Property '${property}' should not be provided`};case 45:return{...error2,summary:isRoot?"Value is missing":`Property '${property}' is missing`};case 50:let quoteIndex=message.indexOf("'"),format=message.slice(quoteIndex+1,message.indexOf("'",quoteIndex+1));return{...error2,summary:isRoot?"Value should be an email":`Property '${property}' should be ${format}`};case 54:return{...error2,summary:`${message.slice(0,9).trim()} property '${property}' to be ${message.slice(8).trim()} but found: ${value}`};case 62:let union=error2.schema.anyOf.map((x)=>`'${x?.format??x.type}'`).join(", ");return{...error2,summary:isRoot?`Value should be one of ${union}`:`Property '${property}' should be one of: ${union}`};default:return{summary:message,...error2}}};class InvalidFileType extends Error{property;expected;message;code="INVALID_FILE_TYPE";status=422;constructor(property,expected,message=`"${property}" has invalid file type`){super(message);this.property=property;this.expected=expected;this.message=message;Object.setPrototypeOf(this,InvalidFileType.prototype)}toResponse(headers){if(isProduction)return new Response(JSON.stringify({type:"validation",on:"body"}),{status:422,headers:{...headers,"content-type":"application/json"}});return new Response(JSON.stringify({type:"validation",on:"body",summary:"Invalid file type",message:this.message,property:this.property,expected:this.expected}),{status:422,headers:{...headers,"content-type":"application/json"}})}}class ValidationError extends Error{type;validator;value;code="VALIDATION";status=422;constructor(type,validator,value,errors){if(value&&typeof value==="object"&&value instanceof ElysiaCustomStatusResponse)value=value.response;let error2=errors?.First()||(isProduction?void 0:("Errors"in validator)?validator.Errors(value).First():Value.Errors(validator,value).First()),customError=error2?.schema?.message||error2?.schema?.error!==void 0?typeof error2.schema.error==="function"?error2.schema.error({type,validator,value,get errors(){return[...validator.Errors(value)].map(mapValueError)}}):error2.schema.error:void 0,accessor=error2?.path||"root",message="";if(customError!==void 0)message=typeof customError==="object"?JSON.stringify(customError):customError+"";else if(isProduction)message=JSON.stringify({type:"validation",on:type,summary:mapValueError(error2).summary,message:error2?.message,found:value});else{let schema=validator?.schema??validator,errors2="Errors"in validator?[...validator.Errors(value)].map(mapValueError):[...Value.Errors(validator,value)].map(mapValueError),expected;try{expected=Value.Create(schema)}catch(error3){expected={type:"Could not create expected value",message:error3?.message,error:error3}}message=JSON.stringify({type:"validation",on:type,summary:mapValueError(error2).summary,property:accessor,message:error2?.message,expected,found:value,errors:errors2},null,2)}super(message);this.type=type;this.validator=validator;this.value=value;Object.setPrototypeOf(this,ValidationError.prototype)}get all(){return"Errors"in this.validator?[...this.validator.Errors(this.value)].map(mapValueError):[...Value.Errors(this.validator,this.value)].map(mapValueError)}static simplifyModel(validator){let model="schema"in validator?validator.schema:validator;try{return Value.Create(model)}catch{return model}}get model(){return ValidationError.simplifyModel(this.validator)}toResponse(headers){return new Response(this.message,{status:400,headers:{...headers,"content-type":"application/json"}})}}var tryParse=(v,schema)=>{try{return JSON.parse(v)}catch{throw new ValidationError("property",schema,v)}};function createType(kind,func){if(!TypeRegistry.Has(kind))TypeRegistry.Set(kind,func);return(options={})=>Unsafe({...options,[Kind]:kind})}var compile=(schema)=>{try{let compiler=TypeCompiler.Compile(schema);return compiler.Create=()=>Value2.Create(schema),compiler.Error=(v)=>new ValidationError("property",schema,v,compiler.Errors(v)),compiler}catch{return{Check:(v)=>Value2.Check(schema,v),CheckThrow:(v)=>{if(!Value2.Check(schema,v))throw new ValidationError("property",schema,v,Value2.Errors(schema,v))},Decode:(v)=>Value2.Decode(schema,v),Create:()=>Value2.Create(schema),Error:(v)=>new ValidationError("property",schema,v,Value2.Errors(schema,v))}}},parseFileUnit=(size)=>{if(typeof size==="string")switch(size.slice(-1)){case"k":return+size.slice(0,size.length-1)*1024;case"m":return+size.slice(0,size.length-1)*1048576;default:return+size}return size},checkFileExtension=(type,extension)=>{if(type.startsWith(extension))return!0;return extension.charCodeAt(extension.length-1)===42&&extension.charCodeAt(extension.length-2)===47&&type.startsWith(extension.slice(0,-1))},_fileTypeFromBlobWarn=!1,warnIfFileTypeIsNotInstalled=()=>{if(!_fileTypeFromBlobWarn)console.warn("[Elysia] Attempt to validate file type without 'file-type'. This may lead to security risks. We recommend installing 'file-type' to properly validate file extension."),_fileTypeFromBlobWarn=!0},loadFileType=async()=>import("file-type").then((x)=>{return _fileTypeFromBlob=x.fileTypeFromBlob,_fileTypeFromBlob}).catch(warnIfFileTypeIsNotInstalled),_fileTypeFromBlob,fileTypeFromBlob=(file2)=>{if(_fileTypeFromBlob)return _fileTypeFromBlob(file2);return loadFileType().then((mod)=>{if(mod)return mod(file2)})},validateFileExtension=async(file2,extension,name=file2?.name??"")=>{if(!file2)return;let result=await fileTypeFromBlob(file2);if(!result)throw new InvalidFileType(name,extension);if(typeof extension==="string"){if(!checkFileExtension(result.mime,extension))throw new InvalidFileType(name,extension)}for(let i=0;i<extension.length;i++)if(checkFileExtension(result.mime,extension[i]))return!0;throw new InvalidFileType(name,extension)},validateFile=(options,value)=>{if(value instanceof ElysiaFile)return!0;if(!(value instanceof Blob))return!1;if(options.minSize&&value.size<parseFileUnit(options.minSize))return!1;if(options.maxSize&&value.size>parseFileUnit(options.maxSize))return!1;if(options.extension){if(typeof options.extension==="string")return checkFileExtension(value.type,options.extension);for(let i=0;i<options.extension.length;i++)if(checkFileExtension(value.type,options.extension[i]))return!0;return!1}return!0};import{TypeSystemPolicy,TypeSystem,TypeSystemDuplicateFormat,TypeSystemDuplicateTypeKind}from"@sinclair/typebox/system";import{TypeRegistry as TypeRegistry2,FormatRegistry as FormatRegistry2}from"@sinclair/typebox";import{TypeCompiler as TypeCompiler2,TypeCheck as TypeCheck2}from"@sinclair/typebox/compiler";var t=Object.assign({},Type);createType("UnionEnum",(schema,value)=>(typeof value==="number"||typeof value==="string"||value===null)&&schema.enum.includes(value));var internalFiles=createType("Files",(options,value)=>{if(!Array.isArray(value))return validateFile(options,value);if(options.minItems&&value.length<options.minItems)return!1;if(options.maxItems&&value.length>options.maxItems)return!1;for(let i=0;i<value.length;i++)if(!validateFile(options,value[i]))return!1;return!0}),internalFormData=createType("ElysiaForm",({compiler,...schema},value)=>{if(!(value instanceof FormData))return!1;if(compiler){if(!(ELYSIA_FORM_DATA in value))throw new ValidationError("property",schema,value);if(!compiler.Check(value[ELYSIA_FORM_DATA]))throw compiler.Error(value[ELYSIA_FORM_DATA])}return!0}),ElysiaType={String:(property)=>Type.String(property),Numeric:(property)=>{let schema=Type.Number(property),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"numeric",default:0}),t.Number(property)],property)).Decode((value)=>{let number=+value;if(isNaN(number))return value;if(property&&!compiler.Check(number))throw compiler.Error(value);return number}).Encode((value)=>value)},Integer:(property)=>{let schema=Type.Integer(property),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"integer",default:0}),Type.Integer(property)],property)).Decode((value)=>{let number=+value;if(!compiler.Check(number))throw compiler.Error(number);return number}).Encode((value)=>value)},Date:(property)=>{let schema=Type.Date(property),compiler=compile(schema),_default=property?.default?new Date(property.default):void 0;return t.Transform(t.Union([Type.Date(property),t.String({format:"date-time",default:_default?.toISOString()}),t.String({format:"date",default:_default?.toISOString()}),t.Number({default:_default?.getTime()})],property)).Decode((value)=>{if(typeof value==="number"){let date3=new Date(value);if(!compiler.Check(date3))throw compiler.Error(date3);return date3}if(value instanceof Date)return value;let date2=new Date(parseDateTimeEmptySpace(value));if(!date2||isNaN(date2.getTime()))throw new ValidationError("property",schema,date2);if(!compiler.Check(date2))throw compiler.Error(date2);return date2}).Encode((value)=>value.toISOString())},BooleanString:(property)=>{let schema=Type.Boolean(property),compiler=compile(schema);return t.Transform(t.Union([t.Boolean(property),t.String({format:"boolean",default:!1})],property)).Decode((value)=>{if(typeof value==="string")return value==="true";if(value!==void 0&&!compiler.Check(value))throw compiler.Error(value);return value}).Encode((value)=>value)},ObjectString:(properties,options)=>{let schema=t.Object(properties,options),compiler=compile(schema),defaultValue=JSON.stringify(compiler.Create());return t.Transform(t.Union([t.String({format:"ObjectString",default:defaultValue}),schema])).Decode((value)=>{if(typeof value==="string"){if(value.charCodeAt(0)!==123)throw new ValidationError("property",schema,value);if(!compiler.Check(value=tryParse(value,schema)))throw compiler.Error(value);return compiler.Decode(value)}return value}).Encode((value)=>{let original;if(typeof value==="string")value=tryParse(original=value,schema);if(!compiler.Check(value))throw compiler.Error(value);return original??JSON.stringify(value)})},ArrayString:(children=t.String(),options)=>{let schema=t.Array(children,options),compiler=compile(schema),decode=(value,isProperty=!1)=>{if(value.charCodeAt(0)===91){if(!compiler.Check(value=tryParse(value,schema)))throw compiler.Error(value);return compiler.Decode(value)}if(value.indexOf(",")!==-1){if(!compiler.Check(value))throw compiler.Error(value);return compiler.Decode(value)}if(isProperty)return value;throw new ValidationError("property",schema,value)};return t.Transform(t.Union([t.String({format:"ArrayString",default:options?.default}),schema])).Decode((value)=>{if(Array.isArray(value)){let values=[];for(let i=0;i<value.length;i++){let v=value[i];if(typeof v==="string"){let t2=decode(v,!0);if(Array.isArray(t2))values=values.concat(t2);else values.push(t2);continue}values.push(v)}return values}if(typeof value==="string")return decode(value);return value}).Encode((value)=>{let original;if(typeof value==="string")value=tryParse(original=value,schema);if(!compiler.Check(value))throw new ValidationError("property",schema,value);return original??JSON.stringify(value)})},File:createType("File",validateFile),Files:(options={})=>t.Transform(internalFiles(options)).Decode((value)=>{if(Array.isArray(value))return value;return[value]}).Encode((value)=>value),Nullable:(schema,options)=>t.Union([schema,t.Null()],options),MaybeEmpty:(schema,options)=>t.Union([schema,t.Null(),t.Undefined()],options),Cookie:(properties,{domain,expires,httpOnly,maxAge,path,priority,sameSite,secure,secrets,sign,...options}={})=>{let v=t.Object(properties,options);return v.config={domain,expires,httpOnly,maxAge,path,priority,sameSite,secure,secrets,sign},v},UnionEnum:(values,options={})=>{let type=values.every((value)=>typeof value==="string")?{type:"string"}:values.every((value)=>typeof value==="number")?{type:"number"}:values.every((value)=>value===null)?{type:"null"}:{};if(values.some((x)=>typeof x==="object"&&x!==null))throw new Error("This type does not support objects or arrays");return{default:values[0],...options,[Kind2]:"UnionEnum",...type,enum:values}},NoValidate:(v,enabled=!0)=>{return v.noValidate=enabled,v},Form:(v,options={})=>{let schema=t.Object(v,{default:form({}),...options}),compiler=compile(schema);return t.Union([schema,internalFormData({compiler})])}};t.BooleanString=ElysiaType.BooleanString;t.ObjectString=ElysiaType.ObjectString;t.ArrayString=ElysiaType.ArrayString;t.Numeric=ElysiaType.Numeric;t.Integer=ElysiaType.Integer;t.File=(arg)=>{if(arg?.type)loadFileType();return ElysiaType.File({default:"File",...arg,extension:arg?.type,type:"string",format:"binary"})};t.Files=(arg)=>{if(arg?.type)loadFileType();return ElysiaType.Files({...arg,elysiaMeta:"Files",default:"Files",extension:arg?.type,type:"array",items:{...arg,default:"Files",type:"string",format:"binary"}})};t.Nullable=(schema)=>ElysiaType.Nullable(schema);t.MaybeEmpty=ElysiaType.MaybeEmpty;t.Cookie=ElysiaType.Cookie;t.Date=ElysiaType.Date;t.UnionEnum=ElysiaType.UnionEnum;t.NoValidate=ElysiaType.NoValidate;t.Form=ElysiaType.Form;var separateFunction=(code)=>{if(code.startsWith("async"))code=code.slice(5);code=code.trimStart();let index=-1;if(code.charCodeAt(0)===40){if(index=code.indexOf("=>",code.indexOf(")")),index!==-1){let bracketEndIndex=index;while(bracketEndIndex>0)if(code.charCodeAt(--bracketEndIndex)===41)break;let body=code.slice(index+2);if(body.charCodeAt(0)===32)body=body.trimStart();return[code.slice(1,bracketEndIndex),body,{isArrowReturn:body.charCodeAt(0)!==123}]}}if(/^(\w+)=>/g.test(code)){if(index=code.indexOf("=>"),index!==-1){let body=code.slice(index+2);if(body.charCodeAt(0)===32)body=body.trimStart();return[code.slice(0,index),body,{isArrowReturn:body.charCodeAt(0)!==123}]}}if(code.startsWith("function")){index=code.indexOf("(");let end=code.indexOf(")");return[code.slice(index+1,end),code.slice(end+2),{isArrowReturn:!1}]}let start=code.indexOf("(");if(start!==-1){let sep=code.indexOf(`
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_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 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(uri2){var percentPosition=uri2.indexOf("%");if(percentPosition===-1)return uri2;var length=uri2.length,decoded="",last=0,codepoint=0,startOfOctets=percentPosition,state=UTF8_ACCEPT;while(percentPosition>-1&&percentPosition<length){var high=hexCodeToInt(uri2[percentPosition+1],4),low=hexCodeToInt(uri2[percentPosition+2],0),byte2=high|low,type=UTF8_DATA[byte2];if(state=UTF8_DATA[256+state+type],codepoint=codepoint<<6|byte2&UTF8_DATA[364+type],state===UTF8_ACCEPT)decoded+=uri2.slice(last,startOfOctets),decoded+=codepoint<=65535?String.fromCharCode(codepoint):String.fromCharCode(55232+(codepoint>>10),56320+(codepoint&1023)),codepoint=0,last=percentPosition+3,percentPosition=startOfOctets=uri2.indexOf("%",last);else if(state===UTF8_REJECT)return null;else{if(percentPosition+=3,percentPosition<length&&uri2.charCodeAt(percentPosition)===37)continue;return null}}return decoded+uri2.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 Y=(A,b)=>{let v=b?.length?{}:null;if(v)for(let K of b)v[K.part.charCodeAt(0)]=K;return{part:A,store:null,inert:v,params:null,wildcardStore:null}},k=(A,b)=>({...A,part:b}),T=(A)=>({name:A,store:null,inert:null});class _{config;root={};history=[];deferred=[];constructor(A={}){if(this.config=A,A.lazy)this.find=this.lazyFind}static regex={static:/:.+?(?=\/|$)/,params:/:.+?(?=\/|$)/g,optionalParams:/:.+?\?(?=\/|$)/g};lazyFind=(A,b)=>{if(!this.config.lazy)return this.find;return this.build(),this.find(A,b)};build(){if(!this.config.lazy)return;for(let[A,b,v]of this.deferred)this.add(A,b,v,{lazy:!1,ignoreHistory:!0});this.deferred=[],this.find=(A,b)=>{let v=this.root[A];if(!v)return null;return $(b,b.length,v,0)}}add(A,b,v,{ignoreError:K=!1,ignoreHistory:V=!1,lazy:U=this.config.lazy}={}){if(U)return this.find=this.lazyFind,this.deferred.push([A,b,v]),v;if(typeof b!=="string")throw new TypeError("Route path must be a string");if(b==="")b="/";else if(b[0]!=="/")b=`/${b}`;let J=b[b.length-1]==="*",F=b.match(_.regex.optionalParams);if(F){let S=b.replaceAll("?","");this.add(A,S,v,{ignoreError:K,ignoreHistory:V,lazy:U});for(let D=0;D<F.length;D++){let B=b.replace("/"+F[D],"");this.add(A,B,v,{ignoreError:!0,ignoreHistory:V,lazy:U})}return v}if(F)b=b.replaceAll("?","");if(this.history.find(([S,D,B])=>S===A&&D===b))return v;if(J||F&&b.charCodeAt(b.length-1)===63)b=b.slice(0,-1);if(!V)this.history.push([A,b,v]);let G=b.split(_.regex.static),X=b.match(_.regex.params)||[];if(G[G.length-1]==="")G.pop();let q;if(!this.root[A])q=this.root[A]=Y("/");else q=this.root[A];let O=0;for(let S=0;S<G.length;++S){let D=G[S];if(S>0){let B=X[O++].slice(1);if(q.params===null)q.params=T(B);else if(q.params.name!==B)if(K)return v;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`);let Q=q.params;if(Q.inert===null){q=Q.inert=Y(D);continue}q=Q.inert}for(let B=0;;){if(B===D.length){if(B<q.part.length){let Q=k(q,q.part.slice(B));Object.assign(q,Y(D,[Q]))}break}if(B===q.part.length){if(q.inert===null)q.inert={};let Q=q.inert[D.charCodeAt(B)];if(Q){q=Q,D=D.slice(B),B=0;continue}let Z=Y(D.slice(B));q.inert[D.charCodeAt(B)]=Z,q=Z;break}if(D[B]!==q.part[B]){let Q=k(q,q.part.slice(B)),Z=Y(D.slice(B));Object.assign(q,Y(q.part.slice(0,B),[Q,Z])),q=Z;break}++B}}if(O<X.length){let D=X[O].slice(1);if(q.params===null)q.params=T(D);else if(q.params.name!==D)if(K)return v;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`);if(q.params.store===null)q.params.store=v;return q.params.store}if(J){if(q.wildcardStore===null)q.wildcardStore=v;return q.wildcardStore}if(q.store===null)q.store=v;return q.store}find(A,b){let v=this.root[A];if(!v)return null;return $(b,b.length,v,0)}}var $=(A,b,v,K)=>{let V=v.part,U=V.length,J=K+U;if(U>1){if(J>b)return null;if(U<15){for(let F=1,G=K+1;F<U;++F,++G)if(V.charCodeAt(F)!==A.charCodeAt(G))return null}else if(A.slice(K,J)!==V)return null}if(J===b){if(v.store!==null)return{store:v.store,params:{}};if(v.wildcardStore!==null)return{store:v.wildcardStore,params:{"*":""}};return null}if(v.inert!==null){let F=v.inert[A.charCodeAt(J)];if(F!==void 0){let G=$(A,b,F,J);if(G!==null)return G}}if(v.params!==null){let{store:F,name:G,inert:X}=v.params,q=A.indexOf("/",J);if(q!==J){if(q===-1||q>=b){if(F!==null){let O={};return O[G]=A.substring(J,b),{store:F,params:O}}}else if(X!==null){let O=$(A,b,X,q);if(O!==null)return O.params[G]=A.substring(J,q),O}}}if(v.wildcardStore!==null)return{store:v.wildcardStore,params:{"*":A.substring(J,b)}};return null};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),{}),mergeResponse=(a,b)=>{let isRecordNumber=(x)=>typeof x==="object"&&Object.keys(x).every(isNumericString);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)=>{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!=="string")throw new TypeError("Cookie value must be provided as a string.");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)=>{if(a.start?.map)a.start=a.start.map((x)=>x.fn);if(a.request?.map)a.request=a.request.map((x)=>x.fn);if(a.parse?.map)a.parse=a.parse.map((x)=>x.fn);if(a.transform?.map)a.transform=a.transform.map((x)=>x.fn);if(a.beforeHandle?.map)a.beforeHandle=a.beforeHandle.map((x)=>x.fn);if(a.afterHandle?.map)a.afterHandle=a.afterHandle.map((x)=>x.fn);if(a.mapResponse?.map)a.mapResponse=a.mapResponse.map((x)=>x.fn);if(a.afterResponse?.map)a.afterResponse=a.afterResponse.map((x)=>x.fn);if(a.trace?.map)a.trace=a.trace.map((x)=>x.fn);else a.trace=[];if(a.error?.map)a.error=a.error.map((x)=>x.fn);if(a.stop?.map)a.stop=a.stop.map((x)=>x.fn);return a},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(typeof payload==="string")payload={data:payload};if(payload.id===void 0)payload.id=randomId();return payload.toStream=()=>{let payloadString="";if(payload.id!==void 0&&payload.id!==null)payloadString+=`id: ${payload.id}
3
+ `;if(payload.event)payloadString+=`event: ${payload.event}
4
+ `;if(payload.retry!==void 0)payloadString+=`retry: ${payload.retry}
5
+ `;if(payload.data===null)payloadString+=`data: null
6
+ `;else if(typeof payload.data==="string")payloadString+=`data: ${payload.data}
7
+ `;else if(typeof payload.data==="object")payloadString+=`data: ${JSON.stringify(payload.data)}
8
+ `;if(payloadString)payloadString+=`
9
+ `;return payloadString},payload};var env=typeof Bun!=="undefined"?Bun.env:typeof process!=="undefined"?process?.env:void 0,ERROR_CODE=Symbol("ElysiaErrorCode"),isProduction=(env?.NODE_ENV??env?.ENV)==="production";class ElysiaCustomStatusResponse{code;response;constructor(code,response){let res=response??(code in InvertedStatusMap?InvertedStatusMap[code]:code);this.code=StatusMap[code]??code,this.response=res}}var status=(code,response)=>new ElysiaCustomStatusResponse(code,response),error=status;class InternalServerError extends Error{code="INTERNAL_SERVER_ERROR";status=500;constructor(message){super(message??"INTERNAL_SERVER_ERROR")}}class NotFoundError extends Error{code="NOT_FOUND";status=404;constructor(message){super(message??"NOT_FOUND")}}class ParseError extends Error{code="PARSE";status=400;constructor(cause){super("Bad Request",{cause})}}class InvalidCookieSignature extends Error{key;code="INVALID_COOKIE_SIGNATURE";status=400;constructor(key,message){super(message??`"${key}" has invalid cookie signature`);this.key=key}}var mapValueError=(error2)=>{if(!error2)return{summary:void 0};let{message,path,value,type}=error2,property=path.slice(1).replaceAll("/","."),isRoot=path==="";switch(type){case 42:return{...error2,summary:isRoot?"Value should not be provided":`Property '${property}' should not be provided`};case 45:return{...error2,summary:isRoot?"Value is missing":`Property '${property}' is missing`};case 50:let quoteIndex=message.indexOf("'"),format=message.slice(quoteIndex+1,message.indexOf("'",quoteIndex+1));return{...error2,summary:isRoot?"Value should be an email":`Property '${property}' should be ${format}`};case 54:return{...error2,summary:`${message.slice(0,9).trim()} property '${property}' to be ${message.slice(8).trim()} but found: ${value}`};case 62:let union=error2.schema.anyOf.map((x)=>`'${x?.format??x.type}'`).join(", ");return{...error2,summary:isRoot?`Value should be one of ${union}`:`Property '${property}' should be one of: ${union}`};default:return{summary:message,...error2}}};class InvalidFileType extends Error{property;expected;message;code="INVALID_FILE_TYPE";status=422;constructor(property,expected,message=`"${property}" has invalid file type`){super(message);this.property=property;this.expected=expected;this.message=message;Object.setPrototypeOf(this,InvalidFileType.prototype)}toResponse(headers){if(isProduction)return new Response(JSON.stringify({type:"validation",on:"body"}),{status:422,headers:{...headers,"content-type":"application/json"}});return new Response(JSON.stringify({type:"validation",on:"body",summary:"Invalid file type",message:this.message,property:this.property,expected:this.expected}),{status:422,headers:{...headers,"content-type":"application/json"}})}}class ValidationError extends Error{type;validator;value;code="VALIDATION";status=422;constructor(type,validator,value,errors){if(value&&typeof value==="object"&&value instanceof ElysiaCustomStatusResponse)value=value.response;let error2=errors?.First()||(isProduction?void 0:("Errors"in validator)?validator.Errors(value).First():Value.Errors(validator,value).First()),customError=error2?.schema?.message||error2?.schema?.error!==void 0?typeof error2.schema.error==="function"?error2.schema.error({type,validator,value,get errors(){return[...validator.Errors(value)].map(mapValueError)}}):error2.schema.error:void 0,accessor=error2?.path||"root",message="";if(customError!==void 0)message=typeof customError==="object"?JSON.stringify(customError):customError+"";else if(isProduction)message=JSON.stringify({type:"validation",on:type,summary:mapValueError(error2).summary,message:error2?.message,found:value});else{let schema=validator?.schema??validator,errors2="Errors"in validator?[...validator.Errors(value)].map(mapValueError):[...Value.Errors(validator,value)].map(mapValueError),expected;try{expected=Value.Create(schema)}catch(error3){expected={type:"Could not create expected value",message:error3?.message,error:error3}}message=JSON.stringify({type:"validation",on:type,summary:mapValueError(error2).summary,property:accessor,message:error2?.message,expected,found:value,errors:errors2},null,2)}super(message);this.type=type;this.validator=validator;this.value=value;Object.setPrototypeOf(this,ValidationError.prototype)}get all(){return"Errors"in this.validator?[...this.validator.Errors(this.value)].map(mapValueError):[...Value.Errors(this.validator,this.value)].map(mapValueError)}static simplifyModel(validator){let model="schema"in validator?validator.schema:validator;try{return Value.Create(model)}catch{return model}}get model(){return ValidationError.simplifyModel(this.validator)}toResponse(headers){return new Response(this.message,{status:400,headers:{...headers,"content-type":"application/json"}})}}var tryParse=(v,schema)=>{try{return JSON.parse(v)}catch{throw new ValidationError("property",schema,v)}};function createType(kind,func){if(!TypeRegistry.Has(kind))TypeRegistry.Set(kind,func);return(options={})=>Unsafe({...options,[Kind]:kind})}var compile=(schema)=>{try{let compiler=TypeCompiler.Compile(schema);return compiler.Create=()=>Value2.Create(schema),compiler.Error=(v)=>new ValidationError("property",schema,v,compiler.Errors(v)),compiler}catch{return{Check:(v)=>Value2.Check(schema,v),CheckThrow:(v)=>{if(!Value2.Check(schema,v))throw new ValidationError("property",schema,v,Value2.Errors(schema,v))},Decode:(v)=>Value2.Decode(schema,v),Create:()=>Value2.Create(schema),Error:(v)=>new ValidationError("property",schema,v,Value2.Errors(schema,v))}}},parseFileUnit=(size)=>{if(typeof size==="string")switch(size.slice(-1)){case"k":return+size.slice(0,size.length-1)*1024;case"m":return+size.slice(0,size.length-1)*1048576;default:return+size}return size},checkFileExtension=(type,extension)=>{if(type.startsWith(extension))return!0;return extension.charCodeAt(extension.length-1)===42&&extension.charCodeAt(extension.length-2)===47&&type.startsWith(extension.slice(0,-1))},_fileTypeFromBlobWarn=!1,warnIfFileTypeIsNotInstalled=()=>{if(!_fileTypeFromBlobWarn)console.warn("[Elysia] Attempt to validate file type without 'file-type'. This may lead to security risks. We recommend installing 'file-type' to properly validate file extension."),_fileTypeFromBlobWarn=!0},loadFileType=async()=>import("file-type").then((x)=>{return _fileTypeFromBlob=x.fileTypeFromBlob,_fileTypeFromBlob}).catch(warnIfFileTypeIsNotInstalled),_fileTypeFromBlob,fileTypeFromBlob=(file2)=>{if(_fileTypeFromBlob)return _fileTypeFromBlob(file2);return loadFileType().then((mod)=>{if(mod)return mod(file2)})},validateFileExtension=async(file2,extension,name=file2?.name??"")=>{if(!file2)return;let result=await fileTypeFromBlob(file2);if(!result)throw new InvalidFileType(name,extension);if(typeof extension==="string"){if(!checkFileExtension(result.mime,extension))throw new InvalidFileType(name,extension)}for(let i=0;i<extension.length;i++)if(checkFileExtension(result.mime,extension[i]))return!0;throw new InvalidFileType(name,extension)},validateFile=(options,value)=>{if(value instanceof ElysiaFile)return!0;if(!(value instanceof Blob))return!1;if(options.minSize&&value.size<parseFileUnit(options.minSize))return!1;if(options.maxSize&&value.size>parseFileUnit(options.maxSize))return!1;if(options.extension){if(typeof options.extension==="string")return checkFileExtension(value.type,options.extension);for(let i=0;i<options.extension.length;i++)if(checkFileExtension(value.type,options.extension[i]))return!0;return!1}return!0};import{TypeSystemPolicy,TypeSystem,TypeSystemDuplicateFormat,TypeSystemDuplicateTypeKind}from"@sinclair/typebox/system";import{TypeRegistry as TypeRegistry2,FormatRegistry as FormatRegistry2}from"@sinclair/typebox";import{TypeCompiler as TypeCompiler2,TypeCheck as TypeCheck2}from"@sinclair/typebox/compiler";var t=Object.assign({},Type);createType("UnionEnum",(schema,value)=>(typeof value==="number"||typeof value==="string"||value===null)&&schema.enum.includes(value));var internalFiles=createType("Files",(options,value)=>{if(!Array.isArray(value))return validateFile(options,value);if(options.minItems&&value.length<options.minItems)return!1;if(options.maxItems&&value.length>options.maxItems)return!1;for(let i=0;i<value.length;i++)if(!validateFile(options,value[i]))return!1;return!0}),internalFormData=createType("ElysiaForm",({compiler,...schema},value)=>{if(!(value instanceof FormData))return!1;if(compiler){if(!(ELYSIA_FORM_DATA in value))throw new ValidationError("property",schema,value);if(!compiler.Check(value[ELYSIA_FORM_DATA]))throw compiler.Error(value[ELYSIA_FORM_DATA])}return!0}),ElysiaType={String:(property)=>Type.String(property),Numeric:(property)=>{let schema=Type.Number(property),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"numeric",default:0}),t.Number(property)],property)).Decode((value)=>{let number=+value;if(isNaN(number))return value;if(property&&!compiler.Check(number))throw compiler.Error(value);return number}).Encode((value)=>value)},Integer:(property)=>{let schema=Type.Integer(property),compiler=compile(schema);return t.Transform(t.Union([t.String({format:"integer",default:0}),Type.Integer(property)],property)).Decode((value)=>{let number=+value;if(!compiler.Check(number))throw compiler.Error(number);return number}).Encode((value)=>value)},Date:(property)=>{let schema=Type.Date(property),compiler=compile(schema),_default=property?.default?new Date(property.default):void 0;return t.Transform(t.Union([Type.Date(property),t.String({format:"date-time",default:_default?.toISOString()}),t.String({format:"date",default:_default?.toISOString()}),t.Number({default:_default?.getTime()})],property)).Decode((value)=>{if(typeof value==="number"){let date3=new Date(value);if(!compiler.Check(date3))throw compiler.Error(date3);return date3}if(value instanceof Date)return value;let date2=new Date(parseDateTimeEmptySpace(value));if(!date2||isNaN(date2.getTime()))throw new ValidationError("property",schema,date2);if(!compiler.Check(date2))throw compiler.Error(date2);return date2}).Encode((value)=>value.toISOString())},BooleanString:(property)=>{let schema=Type.Boolean(property),compiler=compile(schema);return t.Transform(t.Union([t.Boolean(property),t.String({format:"boolean",default:!1})],property)).Decode((value)=>{if(typeof value==="string")return value==="true";if(value!==void 0&&!compiler.Check(value))throw compiler.Error(value);return value}).Encode((value)=>value)},ObjectString:(properties,options)=>{let schema=t.Object(properties,options),compiler=compile(schema),defaultValue=JSON.stringify(compiler.Create());return t.Transform(t.Union([t.String({format:"ObjectString",default:defaultValue}),schema])).Decode((value)=>{if(typeof value==="string"){if(value.charCodeAt(0)!==123)throw new ValidationError("property",schema,value);if(!compiler.Check(value=tryParse(value,schema)))throw compiler.Error(value);return compiler.Decode(value)}return value}).Encode((value)=>{let original;if(typeof value==="string")value=tryParse(original=value,schema);if(!compiler.Check(value))throw compiler.Error(value);return original??JSON.stringify(value)})},ArrayString:(children=t.String(),options)=>{let schema=t.Array(children,options),compiler=compile(schema),decode=(value,isProperty=!1)=>{if(value.charCodeAt(0)===91){if(!compiler.Check(value=tryParse(value,schema)))throw compiler.Error(value);return compiler.Decode(value)}if(value.indexOf(",")!==-1){if(!compiler.Check(value))throw compiler.Error(value);return compiler.Decode(value)}if(isProperty)return value;throw new ValidationError("property",schema,value)};return t.Transform(t.Union([t.String({format:"ArrayString",default:options?.default}),schema])).Decode((value)=>{if(Array.isArray(value)){let values=[];for(let i=0;i<value.length;i++){let v=value[i];if(typeof v==="string"){let t2=decode(v,!0);if(Array.isArray(t2))values=values.concat(t2);else values.push(t2);continue}values.push(v)}return values}if(typeof value==="string")return decode(value);return value}).Encode((value)=>{let original;if(typeof value==="string")value=tryParse(original=value,schema);if(!compiler.Check(value))throw new ValidationError("property",schema,value);return original??JSON.stringify(value)})},File:createType("File",validateFile),Files:(options={})=>t.Transform(internalFiles(options)).Decode((value)=>{if(Array.isArray(value))return value;return[value]}).Encode((value)=>value),Nullable:(schema,options)=>t.Union([schema,t.Null()],options),MaybeEmpty:(schema,options)=>t.Union([schema,t.Null(),t.Undefined()],options),Cookie:(properties,{domain,expires,httpOnly,maxAge,path,priority,sameSite,secure,secrets,sign,...options}={})=>{let v=t.Object(properties,options);return v.config={domain,expires,httpOnly,maxAge,path,priority,sameSite,secure,secrets,sign},v},UnionEnum:(values,options={})=>{let type=values.every((value)=>typeof value==="string")?{type:"string"}:values.every((value)=>typeof value==="number")?{type:"number"}:values.every((value)=>value===null)?{type:"null"}:{};if(values.some((x)=>typeof x==="object"&&x!==null))throw new Error("This type does not support objects or arrays");return{default:values[0],...options,[Kind2]:"UnionEnum",...type,enum:values}},NoValidate:(v,enabled=!0)=>{return v.noValidate=enabled,v},Form:(v,options={})=>{let schema=t.Object(v,{default:form({}),...options}),compiler=compile(schema);return t.Union([schema,internalFormData({compiler})])}};t.BooleanString=ElysiaType.BooleanString;t.ObjectString=ElysiaType.ObjectString;t.ArrayString=ElysiaType.ArrayString;t.Numeric=ElysiaType.Numeric;t.Integer=ElysiaType.Integer;t.File=(arg)=>{if(arg?.type)loadFileType();return ElysiaType.File({default:"File",...arg,extension:arg?.type,type:"string",format:"binary"})};t.Files=(arg)=>{if(arg?.type)loadFileType();return ElysiaType.Files({...arg,elysiaMeta:"Files",default:"Files",extension:arg?.type,type:"array",items:{...arg,default:"Files",type:"string",format:"binary"}})};t.Nullable=(schema)=>ElysiaType.Nullable(schema);t.MaybeEmpty=ElysiaType.MaybeEmpty;t.Cookie=ElysiaType.Cookie;t.Date=ElysiaType.Date;t.UnionEnum=ElysiaType.UnionEnum;t.NoValidate=ElysiaType.NoValidate;t.Form=ElysiaType.Form;var separateFunction=(code)=>{if(code.startsWith("async"))code=code.slice(5);code=code.trimStart();let index=-1;if(code.charCodeAt(0)===40){if(index=code.indexOf("=>",code.indexOf(")")),index!==-1){let bracketEndIndex=index;while(bracketEndIndex>0)if(code.charCodeAt(--bracketEndIndex)===41)break;let body=code.slice(index+2);if(body.charCodeAt(0)===32)body=body.trimStart();return[code.slice(1,bracketEndIndex),body,{isArrowReturn:body.charCodeAt(0)!==123}]}}if(/^(\w+)=>/g.test(code)){if(index=code.indexOf("=>"),index!==-1){let body=code.slice(index+2);if(body.charCodeAt(0)===32)body=body.trimStart();return[code.slice(0,index),body,{isArrowReturn:body.charCodeAt(0)!==123}]}}if(code.startsWith("function")){index=code.indexOf("(");let end=code.indexOf(")");return[code.slice(index+1,end),code.slice(end+2),{isArrowReturn:!1}]}let start=code.indexOf("(");if(start!==-1){let sep=code.indexOf(`
3
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(`
4
- `,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;if(!set2&&size||size&&set2&&set2.status!==206&&set2.status!==304&&set2.status!==412&&set2.status!==416){if(set2){if(set2.headers instanceof Headers){let setHeaders={"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"};if(hasHeaderShorthand)setHeaders=set2.headers.toJSON();else{setHeaders={};for(let[key,value]of set2.headers.entries())if(key in set2.headers)setHeaders[key]=value}return new Response(response,{status:set2.status,headers:setHeaders})}if(isNotEmpty(set2.headers))return new Response(response,{status:set2.status,headers:Object.assign({"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"},set2.headers)})}return new Response(response,{headers:{"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"}})}return new Response(response)},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.done){if(set2)return mapResponse(init.value,set2,request);return mapCompactResponse(init.value,request)}if(set2?.headers){if(!set2.headers["transfer-encoding"])set2.headers["transfer-encoding"]="chunked";if(!set2.headers["content-type"])set2.headers["content-type"]="text/event-stream; charset=utf-8"}else set2={status:200,headers:{"content-type":"text/event-stream; charset=utf-8","transfer-encoding":"chunked"}};return new Response(new ReadableStream({async start(controller){let end=!1;if(request?.signal?.addEventListener("abort",()=>{end=!0;try{controller.close()}catch{}}),init.value!==void 0&&init.value!==null)if(typeof init.value==="object")try{controller.enqueue(Buffer.from(JSON.stringify(init.value)))}catch{controller.enqueue(Buffer.from(init.value.toString()))}else controller.enqueue(Buffer.from(init.value.toString()));for await(let chunk of generator){if(end)break;if(chunk===void 0||chunk===null)continue;if(typeof chunk==="object")try{controller.enqueue(Buffer.from(JSON.stringify(chunk)))}catch{controller.enqueue(Buffer.from(chunk.toString()))}else controller.enqueue(Buffer.from(chunk.toString()));await new Promise((resolve)=>setTimeout(()=>resolve(),0))}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;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 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 handleFile(response.value);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"ReadableStream":if(!set2.headers["content-type"]?.startsWith("text/event-stream"))set2.headers["content-type"]="text/event-stream; charset=utf-8";return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,set2);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")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(response instanceof Response&&!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);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 handleFile(response.value);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"ReadableStream":if(!set2.headers["content-type"]?.startsWith("text/event-stream"))set2.headers["content-type"]="text/event-stream; charset=utf-8";return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,set2);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")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 handleFile(response.value);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"ReadableStream":return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response),request);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")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 handleFile(response.value);case"File":return handleFile(response);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse(response.response,{status:response.code,headers:{}});case"ReadableStream":return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response),request);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")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.bind(response)},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={}
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;if(!set2&&size||size&&set2&&set2.status!==206&&set2.status!==304&&set2.status!==412&&set2.status!==416){if(set2){if(set2.headers instanceof Headers){let setHeaders={"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"};if(hasHeaderShorthand)setHeaders=set2.headers.toJSON();else{setHeaders={};for(let[key,value]of set2.headers.entries())if(key in set2.headers)setHeaders[key]=value}return new Response(response,{status:set2.status,headers:setHeaders})}if(isNotEmpty(set2.headers))return new Response(response,{status:set2.status,headers:Object.assign({"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"},set2.headers)})}return new Response(response,{headers:{"accept-ranges":"bytes","content-range":`bytes 0-${size-1}/${size}`,"transfer-encoding":"chunked"}})}return new Response(response)},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(typeof init?.done==="undefined"||init?.done){if(set2)return mapResponse(init.value,set2,request);return mapCompactResponse(init.value,request)}let contentType=init.value&&typeof init.value?.stream?"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.value!==void 0&&init.value!==null)if(init.value.toStream)controller.enqueue(init.value.toStream());else if(typeof init.value==="object")try{controller.enqueue(Buffer.from(JSON.stringify(init.value)))}catch{controller.enqueue(Buffer.from(init.value.toString()))}else controller.enqueue(Buffer.from(init.value.toString()));for await(let chunk of generator){if(end)break;if(chunk===void 0||chunk===null)continue;if(chunk.toStream)controller.enqueue(chunk.toStream());else if(typeof chunk==="object")try{controller.enqueue(Buffer.from(JSON.stringify(chunk)))}catch{controller.enqueue(Buffer.from(chunk.toString()))}else controller.enqueue(Buffer.from(chunk.toString()));await new Promise((resolve)=>setTimeout(()=>resolve(),0))}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;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 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 handleFile(response.value);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"ReadableStream":if(!set2.headers["content-type"]?.startsWith("text/event-stream"))set2.headers["content-type"]="text/event-stream; charset=utf-8";return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,set2);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")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(response instanceof Response&&!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response,set2),request);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 handleFile(response.value);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"ReadableStream":if(!set2.headers["content-type"]?.startsWith("text/event-stream"))set2.headers["content-type"]="text/event-stream; charset=utf-8";return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,set2);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")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 handleFile(response.value);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"ReadableStream":return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response),request);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")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 handleFile(response.value);case"File":return handleFile(response);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse(response.response,{status:response.code,headers:{}});case"ReadableStream":return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(response.headers.get("transfer-encoding")==="chunked")return handleStream(streamResponse(response),responseToSetHeaders(response),request);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")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.bind(response)},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={}
5
12
  for(const [k,v] of c.request.headers.entries())c.headers[k]=v
6
13
  `,parser:{json(isOptional){if(isOptional)return`try{c.body=await c.request.json()}catch{}
7
14
  `;return`c.body=await c.request.json()
@@ -26,7 +33,7 @@ const error404=new Response(error404Message,{status:404})
26
33
  `,unwrapRef=(type)=>{if(!(Kind3 in type)||!type.$ref)return type;if(type[Kind3]==="This")return deepClone(instruction.definitions[type.$ref]);else if(type[Kind3]==="Ref")if(!instruction.modules)console.warn(new Error("[exact-mirror] modules is required when using nested cyclic reference"));else return instruction.modules.Import(type.$ref);return type};for(let i=0;i<schemas.length;i++){let type=unwrapRef(schemas[i]);if(Array.isArray(type.anyOf))for(let i2=0;i2<type.anyOf.length;i2++)type.anyOf[i2]=unwrapRef(type.anyOf[i2]);else if(type.items)if(Array.isArray(type.items))for(let i2=0;i2<type.items.length;i2++)type.items[i2]=unwrapRef(type.items[i2]);else type.items=unwrapRef(type.items);typeChecks.push(TypeCompiler3.Compile(type)),v+=`if(d.unions[${ui}][${i}].Check(${property})){return ${mirror(type,property,{...instruction,recursion:instruction.recursion+1,parentIsOptional:!0})}}
27
34
  `}return v+=`return ${instruction.removeUnknownUnionType?"undefined":property}})()`,v},mirror=(schema,property,instruction)=>{if(!schema)return"";let isRoot=property==="v"&&!instruction.unions.length;if(Kind3 in schema&&schema[Kind3]==="Import"&&schema.$ref in schema.$defs)return mirror(schema.$defs[schema.$ref],property,{...instruction,definitions:Object.assign(instruction.definitions,schema.$defs)});if(isRoot&&schema.type!=="object"&&schema.type!=="array"&&!schema.anyOf)return`return ${sanitize("v",instruction.sanitize?.length,schema)}`;if(instruction.recursion>=instruction.recursionLimit)return property;let v="";if(schema.$id&&Hint in schema)instruction.definitions[schema.$id]=schema;switch(schema.type){case"object":if(schema[Kind3]==="Record"){v=handleRecord(schema,property,instruction);break}if(schema=mergeObjectIntersection(schema),v+="{",schema.additionalProperties)v+=`...${property}`;let keys=Object.keys(schema.properties);for(let i2=0;i2<keys.length;i2++){let key=keys[i2],isOptional=schema.required&&!schema.required.includes(key)||Array.isArray(schema.properties[key].anyOf),name=joinProperty(property,key,instruction.parentIsOptional);if(isOptional){let index=instruction.array;if(property.startsWith("ar")){let refName=name.slice(name.indexOf(".")+1),array=instruction.optionalsInArray;if(array[index])array[index].push(refName);else array[index]=[refName]}else instruction.optionals.push(name)}let child=schema.properties[key];if(schema.additionalProperties&&child.type!=="object")continue;if(i2!==0)v+=",";v+=`${encodeProperty(key)}:${isOptional?`${name}===undefined?undefined:`:""}${mirror(child,name,{...instruction,recursion:instruction.recursion+1,parentIsOptional:isOptional})}`}v+="}";break;case"array":if(schema.items.type!=="object"&&schema.items.type!=="array")if(Array.isArray(schema.items)){v=handleTuple(schema.items,property,instruction);break}else if(isRoot)return"return v";else if(Kind3 in schema.items&&schema.items.$ref&&(schema.items[Kind3]==="Ref"||schema.items[Kind3]==="This"))v=mirror(deepClone(instruction.definitions[schema.items.$ref]),property,{...instruction,parentIsOptional:!0,recursion:instruction.recursion+1});else{v=property;break}let i=instruction.array;instruction.array++;let reference=property;if(isRoot)v=`const ar${i}v=new Array(${property}.length);`;else reference=`ar${i}s`,v=`((${reference})=>{const ar${i}v=new Array(${reference}.length);`;v+=`for(let i=0;i<${reference}.length;i++){const ar${i}p=${reference}[i];ar${i}v[i]=${mirror(schema.items,`ar${i}p`,instruction)}`;let optionals=instruction.optionalsInArray[i+1];if(optionals)for(let oi=0;oi<optionals.length;oi++){let target=`ar${i}v[i].${optionals[oi]}`;v+=`;if(${target}===undefined)delete ${target}`}if(v+="}",!isRoot)v+=`return ar${i}v})(${property})`;break;default:if(schema.$ref&&schema.$ref in instruction.definitions)return mirror(instruction.definitions[schema.$ref],property,instruction);if(Array.isArray(schema.anyOf)){v=handleUnion(schema.anyOf,property,instruction);break}v=sanitize(property,instruction.sanitize?.length,schema);break}if(!isRoot)return v;if(schema.type==="array")return`${v}return ar0v`;v=`const x=${v}
28
35
  `;for(let i=0;i<instruction.optionals.length;i++){let key=instruction.optionals[i],prop=key.slice(1);if(v+=`if(${key}===undefined`,instruction.unionKeys[key])v+=`||x${prop}===undefined`;v+=`)delete x${prop.charCodeAt(0)!==63?"?":""}${prop}
29
- `}return`${v}return x`},createMirror=(schema,{TypeCompiler:TypeCompiler22,modules,definitions,sanitize:sanitize2,recursionLimit=8,removeUnknownUnionType=!1}={})=>{let unions=[];if(typeof sanitize2==="function")sanitize2=[sanitize2];let f=mirror(schema,"v",{optionals:[],optionalsInArray:[],array:0,parentIsOptional:!1,unions,unionKeys:{},TypeCompiler:TypeCompiler22,modules,definitions:definitions??modules?.$defs??{},sanitize:sanitize2,recursion:0,recursionLimit,removeUnknownUnionType});if(!unions.length&&!sanitize2?.length)return Function("v",f);let hof;if(sanitize2?.length){hof={};for(let i=0;i<sanitize2.length;i++)hof[`h${i}`]=sanitize2[i]}return Function("d",`return function mirror(v){${f}}`)({unions,...hof})};var isOptional=(schema)=>{if(!schema)return!1;if(schema?.[Kind4]==="Import"&&schema.References)return schema.References().some(isOptional);if(schema.schema)schema=schema.schema;return!!schema&&OptionalKind in schema},hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some(hasAdditionalProperties);if(schema.anyOf)return schema.anyOf.some(hasAdditionalProperties);if(schema.someOf)return schema.someOf.some(hasAdditionalProperties);if(schema.allOf)return schema.allOf.some(hasAdditionalProperties);if(schema.not)return schema.not.some(hasAdditionalProperties);if(schema.type==="object"){let properties=schema.properties;if("additionalProperties"in schema)return schema.additionalProperties;if("patternProperties"in schema)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasAdditionalProperties(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasAdditionalProperties(property.anyOf[i]))return!0}return property.additionalProperties}return!1}if(schema.type==="array"&&schema.items&&!Array.isArray(schema.items))return hasAdditionalProperties(schema.items);return!1},hasType=(type,schema)=>{if(!schema)return!1;if(Kind4 in schema&&schema[Kind4]===type)return!0;if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasType(type,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasType(type,property.anyOf[i]))return!0}if(Kind4 in property&&property[Kind4]===type)return!0}return!1}return!!schema.properties&&Kind4 in schema.properties&&schema.properties[Kind4]===type},hasProperty=(expectedProperty,_schema)=>{if(!_schema)return;let schema=_schema.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some((schema2)=>hasProperty(expectedProperty,schema2));if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(expectedProperty in property)return!0;if(property.type==="object"){if(hasProperty(expectedProperty,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasProperty(expectedProperty,property.anyOf[i]))return!0}}return!1}return expectedProperty in schema},hasRef=(schema)=>{if(!schema)return!1;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasRef(schema.anyOf[i]))return!0}if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasRef(schema.allOf[i]))return!0}if(schema.not&&hasRef(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasRef(property))return!0;if(property.type==="array"&&property.items&&hasRef(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasRef(schema.items))return!0;return schema[Kind4]==="Ref"&&"$ref"in schema},hasTransform=(schema)=>{if(!schema)return!1;if(schema.$ref&&schema.$defs&&schema.$ref in schema.$defs&&hasTransform(schema.$defs[schema.$ref]))return!0;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasTransform(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasTransform(schema.anyOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasTransform(schema.allOf[i]))return!0}if(schema.not&&hasTransform(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasTransform(property))return!0;if(property.type==="array"&&property.items&&hasTransform(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasTransform(schema.items))return!0;return TransformKind in schema},replaceSchemaType=(schema,options,_config={})=>{let config=_config;if(config.root=!0,!Array.isArray(options))return options.original=schema,_replaceSchemaType(schema,options,config);for(let option of options)option.original=schema,schema=_replaceSchemaType(schema,option,config);return schema},_replaceSchemaType=(schema,options,config)=>{if(!schema)return schema;let root=config.root;if(options.untilObjectFound&&!root&&schema.type==="object")return schema;let fromSymbol=options.from[Kind4];if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)schema.oneOf[i]=_replaceSchemaType(schema.oneOf[i],options,config);return schema}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)schema.anyOf[i]=_replaceSchemaType(schema.anyOf[i],options,config);return schema}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)schema.allOf[i]=_replaceSchemaType(schema.allOf[i],options,config);return schema}if(schema.not)return _replaceSchemaType(schema.not,options,config);let isRoot=root&&!!options.excludeRoot;if(schema[Kind4]===fromSymbol){let{anyOf,oneOf,allOf,not,properties:properties2,items,...rest}=schema,to=options.to(rest);if(!to)return schema;let transform,composeProperties=(schema2)=>{let v=_composeProperties(schema2);if(v.$id)delete v.$id;return v},_composeProperties=(v)=>{if(properties2&&v.type==="object"){let newProperties={};for(let[key,value2]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value2,options,{...config,root:!1});return{...rest,...v,properties:newProperties}}if(items&&v.type==="array")return{...rest,...v,items:_replaceSchemaType(items,options,{...config,root:!1})};let value={...rest,...v};if(delete value.required,properties2&&v.type==="string"&&v.format==="ObjectString"&&v.default==="{}")transform=t.ObjectString(properties2,rest),value.default=JSON.stringify(Value3.Create(t.Object(properties2))),value.properties=properties2;if(items&&v.type==="string"&&v.format==="ArrayString"&&v.default==="[]")transform=t.ArrayString(items,rest),value.default=JSON.stringify(Value3.Create(t.Array(items))),value.items=items;return value};if(isRoot){if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,properties:newProperties}}else if(items?.map)return{...rest,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return rest}if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]=composeProperties(to.anyOf[i]);else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]=composeProperties(to.oneOf[i]);else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]=composeProperties(to.allOf[i]);else if(to.not)to.not=composeProperties(to.not);if(transform)to[TransformKind]=transform[TransformKind];if(to.anyOf||to.oneOf||to.allOf||to.not)return to;if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,...to,properties:newProperties}}else if(items?.map)return{...rest,...to,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return{...rest,...to}}let properties=schema?.properties;if(properties&&root&&options.rootOnly!==!0)for(let[key,value]of Object.entries(properties))switch(value[Kind4]){case fromSymbol:let{anyOf,oneOf,allOf,not,type,...rest}=value,to=options.to(rest);if(!to)return schema;if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]={...rest,...to.anyOf[i]};else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]={...rest,...to.oneOf[i]};else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]={...rest,...to.allOf[i]};else if(to.not)to.not={...rest,...to.not};properties[key]={...rest,..._replaceSchemaType(rest,options,{...config,root:!1})};break;case"Object":case"Union":properties[key]=_replaceSchemaType(value,options,{...config,root:!1});break;default:if(Array.isArray(value.items))for(let i=0;i<value.items.length;i++)value.items[i]=_replaceSchemaType(value.items[i],options,{...config,root:!1});else if(value.anyOf||value.oneOf||value.allOf||value.not)properties[key]=_replaceSchemaType(value,options,{...config,root:!1});else if(value.type==="array")value.items=_replaceSchemaType(value.items,options,{...config,root:!1});break}return schema},createCleaner=(schema)=>(value)=>{if(typeof value==="object")try{return Value3.Clean(schema,value)}catch{try{return Value3.Clean(schema,value)}catch{return value}}return value},getSchemaValidator=(s,{models={},dynamic=!1,modules,normalize=!1,additionalProperties=!1,coerce=!1,additionalCoerce=[],validators,sanitize:sanitize2}={})=>{if(validators=validators?.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let doesHaveRef=void 0,replaceSchema=(schema2)=>{if(coerce)return replaceSchemaType(schema2,[{from:t.Number(),to:(options)=>t.Numeric(options),untilObjectFound:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),untilObjectFound:!0},...Array.isArray(additionalCoerce)?additionalCoerce:[additionalCoerce]]);return replaceSchemaType(schema2,additionalCoerce)},mapSchema=(s2)=>{let schema2;if(!s2)return;if(typeof s2!=="string")schema2=s2;else{let isArray=s2.endsWith("[]"),key=isArray?s2.substring(0,s2.length-2):s2;if(schema2=modules?.Import(key)??models[key],isArray)schema2=t.Array(schema2)}if(!schema2)return;let _doesHaveRef;if(schema2[Kind4]!=="Import"&&(_doesHaveRef=hasRef(schema2))){let id=randomId();if(doesHaveRef===void 0)doesHaveRef=_doesHaveRef;schema2=t.Module({...modules?.$defs,[id]:schema2}).Import(id)}if(schema2[Kind4]==="Import"){let newDefs={};for(let[key2,value]of Object.entries(schema2.$defs))newDefs[key2]=replaceSchema(value);let key=schema2.$ref;schema2=t.Module(newDefs).Import(key)}else if(coerce||additionalCoerce)schema2=replaceSchema(schema2);return schema2},schema=mapSchema(s);if(validators?.length){let hasAdditional=!1,{schema:mergedObjectSchema,notObjects}=mergeObjectSchemas([schema,...validators.map(mapSchema)]);if(notObjects){if(schema=t.Intersect([...mergedObjectSchema?[mergedObjectSchema]:[],...notObjects.map((x)=>{let schema2=mapSchema(x);if(schema2.type==="object"&&"additionalProperties"in schema2){if(!hasAdditional&&schema2.additionalProperties===!1)hasAdditional=!0;delete schema2.additionalProperties}return schema2})]),schema.type==="object"&&hasAdditional)schema.additionalProperties=!1}}else if(schema.type==="object"&&"additionalProperties"in schema===!1)schema.additionalProperties=additionalProperties;if(dynamic){let validator={schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value3.Check(schema,value),Errors:(value)=>Value3.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value3.Decode(schema,value),Encode:(value)=>Value3.Encode(schema,value),get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(schema)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",schema)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(schema)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},"~hasRef":doesHaveRef,get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasTransform(schema)}};if(schema.config){if(validator.config=schema.config,validator?.schema?.config)delete validator.schema.config}if(normalize&&schema.additionalProperties===!1)if(normalize===!0||normalize==="exactMirror")try{validator.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch{console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema),validator.Clean=createCleaner(schema)}else validator.Clean=createCleaner(schema);return validator.parse=(v)=>{try{return validator.Decode(v)}catch(error2){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(v),error:null}}catch(error2){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}let compiled=TypeCompiler4.Compile(schema,Object.values(models));if(schema.config){if(compiled.config=schema.config,compiled?.schema?.config)delete compiled.schema.config}if(normalize===!0||normalize==="exactMirror")try{compiled.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch(error2){console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema),compiled.Clean=createCleaner(schema)}else compiled.Clean=createCleaner(schema);return compiled.parse=(v)=>{try{return compiled.Decode(v)}catch(error2){throw[...compiled.Errors(v)].map(mapValueError)}},compiled.safeParse=(v)=>{try{return{success:!0,data:compiled.Decode(v),error:null}}catch(error2){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},Object.assign(compiled,{get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(compiled)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",compiled)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(compiled)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasRef(schema)},"~hasRef":doesHaveRef}),compiled},isUnion=(schema)=>schema[Kind4]==="Union"||!schema.schema&&!!schema.anyOf,mergeObjectSchemas=(schemas)=>{if(schemas.length===0)return{schema:void 0,notObjects:[]};if(schemas.length===1)return schemas[0].type==="object"?{schema:schemas[0],notObjects:[]}:{schema:void 0,notObjects:schemas};let newSchema,notObjects=[],additionalPropertiesIsTrue=!1,additionalPropertiesIsFalse=!1;for(let schema of schemas){if(schema.type!=="object"){notObjects.push(schema);continue}if("additionalProperties"in schema){if(schema.additionalProperties===!0)additionalPropertiesIsTrue=!0;else if(schema.additionalProperties===!1)additionalPropertiesIsFalse=!0}if(!newSchema){newSchema=schema;continue}newSchema={...newSchema,...schema,properties:{...newSchema.properties,...schema.properties},required:[...newSchema?.required??[],...schema.required]}}if(newSchema){if(newSchema.required)newSchema.required=[...new Set(newSchema.required)];if(additionalPropertiesIsFalse)newSchema.additionalProperties=!1;else if(additionalPropertiesIsTrue)newSchema.additionalProperties=!0}return{schema:newSchema,notObjects}},getResponseSchemaValidator=(s,{models={},modules,dynamic=!1,normalize=!1,additionalProperties=!1,validators=[],sanitize:sanitize2})=>{if(validators=validators.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let maybeSchemaOrRecord;if(typeof s!=="string")maybeSchemaOrRecord=s;else{let isArray=s.endsWith("[]"),key=isArray?s.substring(0,s.length-2):s;if(maybeSchemaOrRecord=modules.Import(key)??models[key],isArray)maybeSchemaOrRecord=t.Array(maybeSchemaOrRecord)}if(!maybeSchemaOrRecord)return;if(Kind4 in maybeSchemaOrRecord)return{200:getSchemaValidator(maybeSchemaOrRecord,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[200]),sanitize:sanitize2})};let record={};return Object.keys(maybeSchemaOrRecord).forEach((status2)=>{if(isNaN(+status2))return;let maybeNameOrSchema=maybeSchemaOrRecord[+status2];if(typeof maybeNameOrSchema==="string"){if(maybeNameOrSchema in models){let schema=models[maybeNameOrSchema];record[+status2]=Kind4 in schema?getSchemaValidator(schema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):schema}return}record[+status2]=Kind4 in maybeNameOrSchema?getSchemaValidator(maybeNameOrSchema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):maybeNameOrSchema}),record},_stringToStructureCoercions,stringToStructureCoercions=()=>{if(!_stringToStructureCoercions)_stringToStructureCoercions=[{from:t.Object({}),to:()=>t.ObjectString({}),excludeRoot:!0},{from:t.Array(t.Any()),to:()=>t.ArrayString(t.Any())}];return _stringToStructureCoercions},_coercePrimitiveRoot,coercePrimitiveRoot=()=>{if(!_coercePrimitiveRoot)_coercePrimitiveRoot=[{from:t.Number(),to:(options)=>t.Numeric(options),rootOnly:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),rootOnly:!0}];return _coercePrimitiveRoot},getCookieValidator=({validator,modules,defaultConfig={},config,dynamic,models,validators,sanitize:sanitize2})=>{let cookieValidator=getSchemaValidator(validator,{modules,dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators,sanitize:sanitize2});if(cookieValidator)cookieValidator.config=mergeCookie(cookieValidator.config,config);else cookieValidator=getSchemaValidator(t.Cookie(t.Any()),{modules,dynamic,models,additionalProperties:!0,validators,sanitize:sanitize2}),cookieValidator.config=defaultConfig;return cookieValidator};var allocateIf=(value,condition)=>condition?value:"",defaultParsers=["json","text","urlencoded","arrayBuffer","formdata","application/json","text/plain","application/x-www-form-urlencoded","application/octet-stream","multipart/form-data"],createReport=({context="c",trace=[],addFn})=>{if(!trace.length)return()=>{return{resolveChild(){return()=>{}},resolve(){}}};for(let i=0;i<trace.length;i++)addFn(`let report${i},reportChild${i},reportErr${i},reportErrChild${i};let trace${i}=${context}[ELYSIA_TRACE]?.[${i}]??trace[${i}](${context});
36
+ `}return`${v}return x`},createMirror=(schema,{TypeCompiler:TypeCompiler22,modules,definitions,sanitize:sanitize2,recursionLimit=8,removeUnknownUnionType=!1}={})=>{let unions=[];if(typeof sanitize2==="function")sanitize2=[sanitize2];let f=mirror(schema,"v",{optionals:[],optionalsInArray:[],array:0,parentIsOptional:!1,unions,unionKeys:{},TypeCompiler:TypeCompiler22,modules,definitions:definitions??modules?.$defs??{},sanitize:sanitize2,recursion:0,recursionLimit,removeUnknownUnionType});if(!unions.length&&!sanitize2?.length)return Function("v",f);let hof;if(sanitize2?.length){hof={};for(let i=0;i<sanitize2.length;i++)hof[`h${i}`]=sanitize2[i]}return Function("d",`return function mirror(v){${f}}`)({unions,...hof})};var isOptional=(schema)=>{if(!schema)return!1;if(schema?.[Kind4]==="Import"&&schema.References)return schema.References().some(isOptional);if(schema.schema)schema=schema.schema;return!!schema&&OptionalKind in schema},hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some(hasAdditionalProperties);if(schema.anyOf)return schema.anyOf.some(hasAdditionalProperties);if(schema.someOf)return schema.someOf.some(hasAdditionalProperties);if(schema.allOf)return schema.allOf.some(hasAdditionalProperties);if(schema.not)return schema.not.some(hasAdditionalProperties);if(schema.type==="object"){let properties=schema.properties;if("additionalProperties"in schema)return schema.additionalProperties;if("patternProperties"in schema)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasAdditionalProperties(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasAdditionalProperties(property.anyOf[i]))return!0}return property.additionalProperties}return!1}if(schema.type==="array"&&schema.items&&!Array.isArray(schema.items))return hasAdditionalProperties(schema.items);return!1},hasType=(type,schema)=>{if(!schema)return!1;if(Kind4 in schema&&schema[Kind4]===type)return!0;if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasType(type,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasType(type,property.anyOf[i]))return!0}if(Kind4 in property&&property[Kind4]===type)return!0}return!1}return!!schema.properties&&Kind4 in schema.properties&&schema.properties[Kind4]===type},hasProperty=(expectedProperty,_schema)=>{if(!_schema)return;let schema=_schema.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some((schema2)=>hasProperty(expectedProperty,schema2));if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(expectedProperty in property)return!0;if(property.type==="object"){if(hasProperty(expectedProperty,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasProperty(expectedProperty,property.anyOf[i]))return!0}}return!1}return expectedProperty in schema},hasRef=(schema)=>{if(!schema)return!1;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasRef(schema.anyOf[i]))return!0}if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasRef(schema.allOf[i]))return!0}if(schema.not&&hasRef(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasRef(property))return!0;if(property.type==="array"&&property.items&&hasRef(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasRef(schema.items))return!0;return schema[Kind4]==="Ref"&&"$ref"in schema},hasTransform=(schema)=>{if(!schema)return!1;if(schema.$ref&&schema.$defs&&schema.$ref in schema.$defs&&hasTransform(schema.$defs[schema.$ref]))return!0;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasTransform(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasTransform(schema.anyOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasTransform(schema.allOf[i]))return!0}if(schema.not&&hasTransform(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasTransform(property))return!0;if(property.type==="array"&&property.items&&hasTransform(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasTransform(schema.items))return!0;return TransformKind in schema},replaceSchemaType=(schema,options,_config={})=>{let config=_config;if(config.root=!0,!Array.isArray(options))return options.original=schema,_replaceSchemaType(schema,options,config);for(let option of options)option.original=schema,schema=_replaceSchemaType(schema,option,config);return schema},_replaceSchemaType=(schema,options,config)=>{if(!schema)return schema;let root=config.root;if(options.untilObjectFound&&!root&&schema.type==="object")return schema;let fromSymbol=options.from[Kind4];if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)schema.oneOf[i]=_replaceSchemaType(schema.oneOf[i],options,config);return schema}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)schema.anyOf[i]=_replaceSchemaType(schema.anyOf[i],options,config);return schema}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)schema.allOf[i]=_replaceSchemaType(schema.allOf[i],options,config);return schema}if(schema.not)return _replaceSchemaType(schema.not,options,config);let isRoot=root&&!!options.excludeRoot;if(schema[Kind4]===fromSymbol){let{anyOf,oneOf,allOf,not,properties:properties2,items,...rest}=schema,to=options.to(rest);if(!to)return schema;let transform,composeProperties=(schema2)=>{let v=_composeProperties(schema2);if(v.$id)delete v.$id;return v},_composeProperties=(v)=>{if(properties2&&v.type==="object"){let newProperties={};for(let[key,value2]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value2,options,{...config,root:!1});return{...rest,...v,properties:newProperties}}if(items&&v.type==="array")return{...rest,...v,items:_replaceSchemaType(items,options,{...config,root:!1})};let value={...rest,...v};if(delete value.required,properties2&&v.type==="string"&&v.format==="ObjectString"&&v.default==="{}")transform=t.ObjectString(properties2,rest),value.default=JSON.stringify(Value3.Create(t.Object(properties2))),value.properties=properties2;if(items&&v.type==="string"&&v.format==="ArrayString"&&v.default==="[]")transform=t.ArrayString(items,rest),value.default=JSON.stringify(Value3.Create(t.Array(items))),value.items=items;return value};if(isRoot){if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,properties:newProperties}}else if(items?.map)return{...rest,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return rest}if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]=composeProperties(to.anyOf[i]);else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]=composeProperties(to.oneOf[i]);else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]=composeProperties(to.allOf[i]);else if(to.not)to.not=composeProperties(to.not);if(transform)to[TransformKind]=transform[TransformKind];if(to.anyOf||to.oneOf||to.allOf||to.not)return to;if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,...to,properties:newProperties}}else if(items?.map)return{...rest,...to,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return{...rest,...to}}let properties=schema?.properties;if(properties&&root&&options.rootOnly!==!0)for(let[key,value]of Object.entries(properties))switch(value[Kind4]){case fromSymbol:let{anyOf,oneOf,allOf,not,type,...rest}=value,to=options.to(rest);if(!to)return schema;if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]={...rest,...to.anyOf[i]};else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]={...rest,...to.oneOf[i]};else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]={...rest,...to.allOf[i]};else if(to.not)to.not={...rest,...to.not};properties[key]={...rest,..._replaceSchemaType(rest,options,{...config,root:!1})};break;case"Object":case"Union":properties[key]=_replaceSchemaType(value,options,{...config,root:!1});break;default:if(Array.isArray(value.items))for(let i=0;i<value.items.length;i++)value.items[i]=_replaceSchemaType(value.items[i],options,{...config,root:!1});else if(value.anyOf||value.oneOf||value.allOf||value.not)properties[key]=_replaceSchemaType(value,options,{...config,root:!1});else if(value.type==="array")value.items=_replaceSchemaType(value.items,options,{...config,root:!1});break}return schema},createCleaner=(schema)=>(value)=>{if(typeof value==="object")try{return Value3.Clean(schema,value)}catch{try{return Value3.Clean(schema,value)}catch{return value}}return value},getSchemaValidator=(s,{models={},dynamic=!1,modules,normalize=!1,additionalProperties=!1,coerce=!1,additionalCoerce=[],validators,sanitize:sanitize2}={})=>{if(validators=validators?.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let doesHaveRef=void 0,replaceSchema=(schema2)=>{if(coerce)return replaceSchemaType(schema2,[{from:t.Number(),to:(options)=>t.Numeric(options),untilObjectFound:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),untilObjectFound:!0},...Array.isArray(additionalCoerce)?additionalCoerce:[additionalCoerce]]);return replaceSchemaType(schema2,additionalCoerce)},mapSchema=(s2)=>{let schema2;if(!s2)return;if(typeof s2!=="string")schema2=s2;else{let isArray=s2.endsWith("[]"),key=isArray?s2.substring(0,s2.length-2):s2;if(schema2=modules?.Import(key)??models[key],isArray)schema2=t.Array(schema2)}if(!schema2)return;let _doesHaveRef;if(schema2[Kind4]!=="Import"&&(_doesHaveRef=hasRef(schema2))){let id=randomId();if(doesHaveRef===void 0)doesHaveRef=_doesHaveRef;schema2=t.Module({...modules?.$defs,[id]:schema2}).Import(id)}if(schema2[Kind4]==="Import"){let newDefs={};for(let[key2,value]of Object.entries(schema2.$defs))newDefs[key2]=replaceSchema(value);let key=schema2.$ref;schema2=t.Module(newDefs).Import(key)}else if(coerce||additionalCoerce)schema2=replaceSchema(schema2);return schema2},schema=mapSchema(s);if(validators?.length){let hasAdditional=!1,{schema:mergedObjectSchema,notObjects}=mergeObjectSchemas([schema,...validators.map(mapSchema)]);if(notObjects){if(schema=t.Intersect([...mergedObjectSchema?[mergedObjectSchema]:[],...notObjects.map((x)=>{let schema2=mapSchema(x);if(schema2.type==="object"&&"additionalProperties"in schema2){if(!hasAdditional&&schema2.additionalProperties===!1)hasAdditional=!0;delete schema2.additionalProperties}return schema2})]),schema.type==="object"&&hasAdditional)schema.additionalProperties=!1}}else if(schema.type==="object"&&"additionalProperties"in schema===!1)schema.additionalProperties=additionalProperties;if(dynamic){let validator={schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value3.Check(schema,value),Errors:(value)=>Value3.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value3.Decode(schema,value),Encode:(value)=>Value3.Encode(schema,value),get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(schema)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",schema)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(schema)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},"~hasRef":doesHaveRef,get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasTransform(schema)}};if(schema.config){if(validator.config=schema.config,validator?.schema?.config)delete validator.schema.config}if(normalize&&schema.additionalProperties===!1)if(normalize===!0||normalize==="exactMirror")try{validator.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch{console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema),validator.Clean=createCleaner(schema)}else validator.Clean=createCleaner(schema);return validator.parse=(v)=>{try{return validator.Decode(v)}catch(error2){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(v),error:null}}catch(error2){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}let compiled=TypeCompiler4.Compile(schema,Object.values(models));if(schema.config){if(compiled.config=schema.config,compiled?.schema?.config)delete compiled.schema.config}if(normalize===!0||normalize==="exactMirror")try{compiled.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch(error2){console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema),compiled.Clean=createCleaner(schema)}else compiled.Clean=createCleaner(schema);return compiled.parse=(v)=>{try{return compiled.Decode(v)}catch(error2){throw[...compiled.Errors(v)].map(mapValueError)}},compiled.safeParse=(v)=>{try{return{success:!0,data:compiled.Decode(v),error:null}}catch(error2){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},Object.assign(compiled,{get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(compiled)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",compiled)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(compiled)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasRef(schema)},"~hasRef":doesHaveRef}),compiled},isUnion=(schema)=>schema[Kind4]==="Union"||!schema.schema&&!!schema.anyOf,mergeObjectSchemas=(schemas)=>{if(schemas.length===0)return{schema:void 0,notObjects:[]};if(schemas.length===1)return schemas[0].type==="object"?{schema:schemas[0],notObjects:[]}:{schema:void 0,notObjects:schemas};let newSchema,notObjects=[],additionalPropertiesIsTrue=!1,additionalPropertiesIsFalse=!1;for(let schema of schemas){if(schema.type!=="object"){notObjects.push(schema);continue}if("additionalProperties"in schema){if(schema.additionalProperties===!0)additionalPropertiesIsTrue=!0;else if(schema.additionalProperties===!1)additionalPropertiesIsFalse=!0}if(!newSchema){newSchema=schema;continue}newSchema={...newSchema,...schema,properties:{...newSchema.properties,...schema.properties},required:[...newSchema?.required??[],...schema.required]}}if(newSchema){if(newSchema.required)newSchema.required=[...new Set(newSchema.required)];if(additionalPropertiesIsFalse)newSchema.additionalProperties=!1;else if(additionalPropertiesIsTrue)newSchema.additionalProperties=!0}return{schema:newSchema,notObjects}},getResponseSchemaValidator=(s,{models={},modules,dynamic=!1,normalize=!1,additionalProperties=!1,validators=[],sanitize:sanitize2})=>{if(validators=validators.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let maybeSchemaOrRecord;if(typeof s!=="string")maybeSchemaOrRecord=s;else{let isArray=s.endsWith("[]"),key=isArray?s.substring(0,s.length-2):s;if(maybeSchemaOrRecord=modules.Import(key)??models[key],isArray)maybeSchemaOrRecord=t.Array(maybeSchemaOrRecord)}if(!maybeSchemaOrRecord)return;if(Kind4 in maybeSchemaOrRecord)return{200:getSchemaValidator(maybeSchemaOrRecord,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[200]),sanitize:sanitize2})};let record={};return Object.keys(maybeSchemaOrRecord).forEach((status2)=>{if(isNaN(+status2))return;let maybeNameOrSchema=maybeSchemaOrRecord[+status2];if(typeof maybeNameOrSchema==="string"){if(maybeNameOrSchema in models){let schema=models[maybeNameOrSchema];record[+status2]=Kind4 in schema?getSchemaValidator(schema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):schema}return}record[+status2]=Kind4 in maybeNameOrSchema?getSchemaValidator(maybeNameOrSchema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):maybeNameOrSchema}),record},_stringToStructureCoercions,stringToStructureCoercions=()=>{if(!_stringToStructureCoercions)_stringToStructureCoercions=[{from:t.Object({}),to:()=>t.ObjectString({}),excludeRoot:!0},{from:t.Array(t.Any()),to:()=>t.ArrayString(t.Any())}];return _stringToStructureCoercions},_coercePrimitiveRoot,coercePrimitiveRoot=()=>{if(!_coercePrimitiveRoot)_coercePrimitiveRoot=[{from:t.Number(),to:(options)=>t.Numeric(options),rootOnly:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),rootOnly:!0}];return _coercePrimitiveRoot},getCookieValidator=({validator,modules,defaultConfig={},config,dynamic,models,validators,sanitize:sanitize2})=>{let cookieValidator=getSchemaValidator(validator,{modules,dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators,sanitize:sanitize2});if(cookieValidator)cookieValidator.config=mergeCookie(cookieValidator.config,config);else cookieValidator=getSchemaValidator(t.Cookie(t.Any()),{modules,dynamic,models,additionalProperties:!0,validators,sanitize:sanitize2}),cookieValidator.config=defaultConfig;return cookieValidator},unwrapImportSchema=(schema)=>schema[Kind4]==="Import"&&schema.$defs[schema.$ref][Kind4]==="Object"?schema.$defs[schema.$ref]:schema;var allocateIf=(value,condition)=>condition?value:"",defaultParsers=["json","text","urlencoded","arrayBuffer","formdata","application/json","text/plain","application/x-www-form-urlencoded","application/octet-stream","multipart/form-data"],createReport=({context="c",trace=[],addFn})=>{if(!trace.length)return()=>{return{resolveChild(){return()=>{}},resolve(){}}};for(let i=0;i<trace.length;i++)addFn(`let report${i},reportChild${i},reportErr${i},reportErrChild${i};let trace${i}=${context}[ELYSIA_TRACE]?.[${i}]??trace[${i}](${context});
30
37
  `);return(event,{name,total=0}={})=>{if(!name)name="anonymous";let reporter=event==="error"?"reportErr":"report";for(let i=0;i<trace.length;i++)addFn(`${reporter}${i} = trace${i}.${event}({id,event:'${event}',name:'${name}',begin:performance.now(),total:${total}})
31
38
  `);return{resolve(){for(let i=0;i<trace.length;i++)addFn(`${reporter}${i}.resolve()
32
39
  `)},resolveChild(name2){for(let i=0;i<trace.length;i++)addFn(`${reporter}Child${i}=${reporter}${i}.resolveChild?.shift()?.({id,event:'${event}',name:'${name2}',begin:performance.now()})
@@ -176,14 +183,14 @@ else Object.assign(c,transformed)
176
183
  `}if(validator.query){if(validator.query.hasDefault)for(let[key,value]of Object.entries(Value4.Default(validator.query.schema,{}))){let parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(parsed!==void 0)fnLiteral+=`if(c.query['${key}']===undefined)c.query['${key}']=${parsed}
177
184
  `;fnLiteral+=composeCleaner({name:"c.query",schema:validator.query,type:"query",normalize})}if(validator.query.isOptional)fnLiteral+="if(isNotEmpty(c.query)){";if(validator.query?.schema?.noValidate!==!0)fnLiteral+="if(validator.query.Check(c.query)===false){"+validation.validate("query")+"}";if(validator.query.hasTransform)fnLiteral+=`c.query=validator.query.Decode(Object.assign({},c.query))
178
185
  `;if(validator.query.isOptional)fnLiteral+="}"}if(hasBody&&validator.body){if(validator.body.hasTransform||validator.body.isOptional)fnLiteral+=`const isNotEmptyObject=c.body&&(typeof c.body==="object"&&isNotEmpty(c.body))
179
- `;let hasUnion=isUnion(validator.body.schema),hasNonUnionFileWithDefault=!1;if(validator.body.hasDefault){let value=Value4.Default(validator.body.schema,validator.body.schema.type==="object"||validator.body.schema[Kind5]==="Import"&&validator.body.schema.$defs[validator.body.schema.$ref][Kind5]==="Object"?{}:void 0);if(!hasUnion&&value&&typeof value==="object"&&(hasType("File",validator.body.schema)||hasType("Files",validator.body.schema))){hasNonUnionFileWithDefault=!0;for(let[k2,v]of Object.entries(value))if(v==="File"||v==="Files")delete value[k2];if(!isNotEmpty(value))value=void 0}let parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(value!==void 0&&value!==null)if(Array.isArray(value))fnLiteral+=`if(!c.body)c.body=${parsed}
186
+ `;let hasUnion=isUnion(validator.body.schema),hasNonUnionFileWithDefault=!1;if(validator.body.hasDefault){let value=Value4.Default(validator.body.schema,validator.body.schema.type==="object"||validator.body.schema[Kind5]==="Import"&&validator.body.schema.$defs[validator.body.schema.$ref][Kind5]==="Object"?{}:void 0),schema=unwrapImportSchema(validator.body.schema);if(!hasUnion&&value&&typeof value==="object"&&(hasType("File",schema)||hasType("Files",schema))){hasNonUnionFileWithDefault=!0;for(let[k2,v]of Object.entries(value))if(v==="File"||v==="Files")delete value[k2];if(!isNotEmpty(value))value=void 0}let parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(value!==void 0&&value!==null)if(Array.isArray(value))fnLiteral+=`if(!c.body)c.body=${parsed}
180
187
  `;else if(typeof value==="object")fnLiteral+=`c.body=Object.assign(${parsed},c.body)
181
188
  `;else fnLiteral+=`c.body=${parsed}
182
189
  `;if(fnLiteral+=composeCleaner({name:"c.body",schema:validator.body,type:"body",normalize}),validator.body?.schema?.noValidate!==!0)if(validator.body.isOptional)fnLiteral+="if(isNotEmptyObject&&validator.body.Check(c.body)===false){"+validation.validate("body")+"}";else fnLiteral+="if(validator.body.Check(c.body)===false){"+validation.validate("body")+"}"}else if(fnLiteral+=composeCleaner({name:"c.body",schema:validator.body,type:"body",normalize}),validator.body?.schema?.noValidate!==!0)if(validator.body.isOptional)fnLiteral+="if(isNotEmptyObject&&validator.body.Check(c.body)===false){"+validation.validate("body")+"}";else fnLiteral+="if(validator.body.Check(c.body)===false){"+validation.validate("body")+"}";if(validator.body.hasTransform)fnLiteral+=`if(isNotEmptyObject)c.body=validator.body.Decode(c.body)
183
190
  `;if(hasUnion&&validator.body.schema.anyOf?.length){let iterator=Object.values(validator.body.schema.anyOf);for(let i=0;i<iterator.length;i++){let type=iterator[i];if(hasType("File",type)||hasType("Files",type)){let candidate=getSchemaValidator(type,{modules:app.definitions.typebox,dynamic:!app.config.aot,models:app.definitions.type,normalize:app.config.normalize,additionalCoerce:coercePrimitiveRoot(),sanitize:()=>app.config.sanitize});if(candidate){let isFirst=fileUnions.length===0,iterator2=Object.entries(type.properties),validator2=isFirst?`
184
191
  `:" else ";validator2+=`if(fileUnions[${fileUnions.length}].Check(c.body)){`;let validateFile2="",validatorLength=0;for(let i2=0;i2<iterator2.length;i2++){let[k2,v]=iterator2[i2];if(!v.extension||v[Kind5]!=="File"&&v[Kind5]!=="Files")continue;if(validatorLength)validateFile2+=",";validateFile2+=`validateFileExtension(c.body.${k2},${JSON.stringify(v.extension)},'body.${k2}')`,validatorLength++}if(validateFile2){if(validatorLength===1)validator2+=`await ${validateFile2}
185
192
  `;else if(validatorLength>1)validator2+=`await Promise.all([${validateFile2}])
186
- `;validator2+="}",fnLiteral+=validator2,fileUnions.push(candidate)}}}}}else if(hasNonUnionFileWithDefault||!hasUnion&&(hasType("File",validator.body.schema)||hasType("Files",validator.body.schema))){let validateFile2="",i=0;for(let[k2,v]of Object.entries(validator.body.schema.properties)){if(!v.extension||v[Kind5]!=="File"&&v[Kind5]!=="Files")continue;if(i)validateFile2+=",";validateFile2+=`validateFileExtension(c.body.${k2},${JSON.stringify(v.extension)},'body.${k2}')`,i++}if(i)fnLiteral+=`
193
+ `;validator2+="}",fnLiteral+=validator2,fileUnions.push(candidate)}}}}}else if(hasNonUnionFileWithDefault||!hasUnion&&(hasType("File",unwrapImportSchema(validator.body.schema))||hasType("Files",unwrapImportSchema(validator.body.schema)))){let validateFile2="",i=0;for(let[k2,v]of Object.entries(unwrapImportSchema(validator.body.schema).properties)){if(!v.extension||v[Kind5]!=="File"&&v[Kind5]!=="Files")continue;if(i)validateFile2+=",";validateFile2+=`validateFileExtension(c.body.${k2},${JSON.stringify(v.extension)},'body.${k2}')`,i++}if(i)fnLiteral+=`
187
194
  `;if(i===1)fnLiteral+=`await ${validateFile2}
188
195
  `;else if(i>1)fnLiteral+=`await Promise.all([${validateFile2}])
189
196
  `}}if(validator.cookie){let cookieValidator=getCookieValidator({modules:app.definitions.typebox,validator:validator.cookie,defaultConfig:app.config.cookie,dynamic:!!app.config.aot,config:validator.cookie?.config??{},models:app.definitions.type});if(fnLiteral+=`const cookieValue={}
@@ -339,8 +346,8 @@ return u.substring(s,qi)
339
346
  `;if(fnLiteral+=`${app.event.request?.find(isAsync)?"async":""} function map(request){`,hasTrace||inference.query||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,setHeaders={})=>{if(typeof handle==="function"||handle instanceof Blob)return;if(typeof handle==="object"&&handle?.toString()==="[object HTMLBundle]")return()=>handle;let response=mapResponse2(handle,{headers:setHeaders});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.bind(response)}};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;validator;["~types"];get id(){return this.data.id}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}}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},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()
340
347
  `:`c.headers={}
341
348
  for(const [k,v] of c.request.headers.entries())c.headers[k]=v
342
- `},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}))}continue}if(!(value instanceof Response))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,...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,...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)})}},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=app.getServer(),{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,errorHandlers=[...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(ws){try{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{handleResponse3(ws,options.message?.(new ElysiaWS(ws,context,message),message))}catch(error2){handleErrors(ws,error2)}},drain(ws){try{handleResponse3(ws,options.drain?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},close(ws,code,reason){try{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)=>{for(let[key,keySchema]of Object.entries(typeChecker.schema.properties))obj[key]??=keySchema.default},createDynamicHandler=(app)=>{let{mapResponse:mapResponse3,mapEarlyResponse:mapEarlyResponse3}=app["~adapter"].handler;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:{}},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 handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find("ALL",path);if(!handler)throw 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=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,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=Object.assign({},app.config?.cookie,validator?.cookie?.config),cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta?{secrets:cookieMeta.secrets!==void 0?typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets.join(","):void 0,sign:cookieMeta.sign===!0?!0:cookieMeta.sign!==void 0?typeof cookieMeta.sign==="string"?cookieMeta.sign:cookieMeta.sign.join(","):void 0}:void 0);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],operation=hook.fn(context);if(hook.subType==="derive")if(operation instanceof Promise)Object.assign(context,await operation);else Object.assign(context,operation);else if(operation instanceof Promise)await operation}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(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(hook.subType==="resolve"){if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(response2 instanceof Promise)Object.assign(context,await response2);else Object.assign(context,response2);continue}else if(response2 instanceof Promise)response2=await response2;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)if(!hooks.afterHandle.length){let status2=response instanceof ElysiaCustomStatusResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200,responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response)===!1)throw new ValidationError("response",responseValidator,response);else if(responseValidator?.Decode)response=responseValidator.Decode(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let newResponse=hooks.afterHandle[i].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;let result=mapEarlyResponse3(newResponse,context.set);if(result!==void 0){let responseValidator=validator?.response?.[result.status];if(responseValidator?.Check(result)===!1)throw new ValidationError("response",responseValidator,result);else if(responseValidator?.Decode)response=responseValidator.Decode(response);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)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;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)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(){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});return this["~http"]},"~dynamic":void 0,get dynamic(){if(!this["~dynamic"])this["~dynamic"]=new _;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={prefix:"",aot:env2.ELYSIA_AOT!=="false",nativeStaticResponse:!0,systemRouter:!0,encodeSchema:!0,normalize:!0,...config,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(`
343
- `))}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,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,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,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,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 fn=adapter.createNativeStaticHandler?.(handle,hooks,this.setHeaders);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{this.router.http.add(method,path,handler);let staticHandler=typeof handle!=="function"&&typeof adapter.createStaticHandler==="function"?adapter.createStaticHandler(handle,hooks,this.setHeaders):void 0;if(!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")this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null;else if(type==="global")this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=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;return this.standaloneValidator[type].push({body:hook.body,headers:hook.headers,params:hook.params,query:hook.query,response,cookie:hook.cookie}),this}if(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},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};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,options){if(Array.isArray(plugin)){let app=this;for(let p of plugin)app=app.use(p);return app}if(options?.scoped)return this.guard({},(app)=>app.use(plugin));if(Array.isArray(plugin)){let current=this;for(let p of plugin)current=this.use(p);return current}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,isNotEmpty(plugin2.event.error)?mergeHook(hooks,{error:plugin2.event.error}):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)}deduplicateChecksum(this.extender.macros),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)}}if(hofHashes.length=0,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,isNotEmpty(plugin.event.error)?mergeHook(hooks,{error:plugin.event.error}):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)=>{if(!this.server)throw new Error("Elysia isn't running. Call `app.listen` to start the server.");if(this.server){if(this.server.stop(closeActiveConnections),this.server=null,this.event.stop?.length)for(let i=0;i<this.event.stop.length;i++)this.event.stop[i].fn(this)}};get modules(){return this.promisedModules}}export{t,status,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,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
349
+ `},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}))}continue}if(!(value instanceof Response))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,...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,...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)})}},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=app.getServer(),{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,errorHandlers=[...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(ws){try{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{handleResponse3(ws,options.message?.(new ElysiaWS(ws,context,message),message))}catch(error2){handleErrors(ws,error2)}},drain(ws){try{handleResponse3(ws,options.drain?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},close(ws,code,reason){try{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)=>{for(let[key,keySchema]of Object.entries(typeChecker.schema.properties))obj[key]??=keySchema.default},createDynamicHandler=(app)=>{let{mapResponse:mapResponse3,mapEarlyResponse:mapEarlyResponse3}=app["~adapter"].handler;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:{}},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 handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find("ALL",path);if(!handler)throw 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=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,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=Object.assign({},app.config?.cookie,validator?.cookie?.config),cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta?{secrets:cookieMeta.secrets!==void 0?typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets.join(","):void 0,sign:cookieMeta.sign===!0?!0:cookieMeta.sign!==void 0?typeof cookieMeta.sign==="string"?cookieMeta.sign:cookieMeta.sign.join(","):void 0}:void 0);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],operation=hook.fn(context);if(hook.subType==="derive")if(operation instanceof Promise)Object.assign(context,await operation);else Object.assign(context,operation);else if(operation instanceof Promise)await operation}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(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(hook.subType==="resolve"){if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(response2 instanceof Promise)Object.assign(context,await response2);else Object.assign(context,response2);continue}else if(response2 instanceof Promise)response2=await response2;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)if(!hooks.afterHandle.length){let status2=response instanceof ElysiaCustomStatusResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200,responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response)===!1)throw new ValidationError("response",responseValidator,response);else if(responseValidator?.Decode)response=responseValidator.Decode(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let newResponse=hooks.afterHandle[i].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;let result=mapEarlyResponse3(newResponse,context.set);if(result!==void 0){let responseValidator=validator?.response?.[result.status];if(responseValidator?.Check(result)===!1)throw new ValidationError("response",responseValidator,result);else if(responseValidator?.Decode)response=responseValidator.Decode(response);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)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;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)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});return this["~http"]},"~dynamic":void 0,get dynamic(){if(!this["~dynamic"])this["~dynamic"]=new _;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={prefix:"",aot:env2.ELYSIA_AOT!=="false",nativeStaticResponse:!0,systemRouter:!0,encodeSchema:!0,normalize:!0,...config,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(`
350
+ `))}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,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,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,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,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 fn=adapter.createNativeStaticHandler?.(handle,hooks,this.setHeaders);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")this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null;else if(type==="global")this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=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;return this.standaloneValidator[type].push({body:hook.body,headers:hook.headers,params:hook.params,query:hook.query,response,cookie:hook.cookie}),this}if(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},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};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(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,isNotEmpty(plugin2.event.error)?mergeHook(hooks,{error:plugin2.event.error}):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,isNotEmpty(plugin.event.error)?mergeHook(hooks,{error:plugin.event.error}):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)=>{if(!this.server)throw new Error("Elysia isn't running. Call `app.listen` to start the server.");if(this.server){if(this.server.stop(closeActiveConnections),this.server=null,this.event.stop?.length)for(let i=0;i<this.event.stop.length;i++)this.event.stop[i].fn(this)}};get modules(){return this.promisedModules}}export{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,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
344
351
 
345
- //# debugId=7F364F51641AE27C64756E2164756E21
352
+ //# debugId=E887E2CC63FED70664756E2164756E21
346
353
  //# sourceMappingURL=index.js.map