elysia 1.3.9 → 1.3.11
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 +5 -5
- package/dist/bun/index.js.map +4 -4
- package/dist/cjs/compose.js +2 -3
- package/dist/cjs/dynamic-handle.js +8 -7
- package/dist/cjs/index.js +10 -10
- package/dist/compose.mjs +2 -3
- package/dist/dynamic-handle.mjs +8 -7
- package/dist/index.mjs +10 -10
- package/package.json +1 -1
package/dist/bun/index.js
CHANGED
|
@@ -260,12 +260,12 @@ if(!set.status||set.status<300)set.status=error?.status||500
|
|
|
260
260
|
`;let errorReporter=report("error",{total:hooks.error?.length});if(hooks.error?.length){if(fnLiteral+=`c.error=error
|
|
261
261
|
`,hasValidation)fnLiteral+=`if(error instanceof TypeBoxError){c.code="VALIDATION"
|
|
262
262
|
c.set.status=422}else{c.code=error.code??error[ERROR_CODE]??"UNKNOWN"}`;else fnLiteral+=`c.code=error.code??error[ERROR_CODE]??"UNKNOWN"
|
|
263
|
-
`;fnLiteral+=`let er
|
|
263
|
+
`;if(fnLiteral+=`let er
|
|
264
|
+
`,hooks.mapResponse?.length)fnLiteral+=`let mep
|
|
264
265
|
`;for(let i=0;i<hooks.error.length;i++){let endUnit=errorReporter.resolveChild(hooks.error[i].fn.name);if(isAsync(hooks.error[i]))fnLiteral+=`er=await e.error[${i}](c)
|
|
265
266
|
`;else fnLiteral+=`er=e.error[${i}](c)
|
|
266
267
|
if(er instanceof Promise)er=await er
|
|
267
|
-
`;if(endUnit(),hooks.mapResponse?.length){let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse?.length});fnLiteral+=`
|
|
268
|
-
`;for(let i2=0;i2<hooks.mapResponse.length;i2++){let mapResponse4=hooks.mapResponse[i2],endUnit2=mapResponseReporter.resolveChild(mapResponse4.fn.name);fnLiteral+=`c.response=er
|
|
268
|
+
`;if(endUnit(),hooks.mapResponse?.length){let mapResponseReporter=report("mapResponse",{total:hooks.mapResponse?.length});for(let i2=0;i2<hooks.mapResponse.length;i2++){let mapResponse4=hooks.mapResponse[i2],endUnit2=mapResponseReporter.resolveChild(mapResponse4.fn.name);fnLiteral+=`c.response=er
|
|
269
269
|
mep=e.mapResponse[${i2}](c)
|
|
270
270
|
if(mep instanceof Promise)er=await er
|
|
271
271
|
if(mep!==undefined)er=mep
|
|
@@ -358,8 +358,8 @@ return u.substring(s,qi)
|
|
|
358
358
|
`;fnLiteral+=`${app.event.request?.find(isAsync)?"async":""} function map(request){`;let needsQuery=inference.query||!!route.hooks.query||!!route.standaloneValidators?.find((x)=>x.query);if(hasTrace||needsQuery||app.event.request?.length)fnLiteral+=createContext(app,route,inference),fnLiteral+=createOnRequestHandler(app),fnLiteral+="return handler(c)}";else fnLiteral+=`return handler(${createContext(app,route,inference,!0)})}`;return fnLiteral+=createHoc(app),Function("data",fnLiteral)({app,handler:route.compile?.()??route.composed,redirect,status,hoc:app.extender.higherOrderFunctions.map((x)=>x.fn),store:app.store,decorator:app.decorator,route:route.path,randomId:hasTrace?randomId:void 0,ELYSIA_TRACE:hasTrace?ELYSIA_TRACE:void 0,ELYSIA_REQUEST_ID:hasTrace?ELYSIA_REQUEST_ID:void 0,trace:hasTrace?app.event.trace?.map((x)=>x?.fn??x):void 0,mapEarlyResponse:mapEarlyResponse2})};var createNativeStaticHandler=(handle,hooks,set2)=>{if(typeof handle==="function"||handle instanceof Blob)return;if(isHTMLBundle(handle))return()=>handle;let response=mapResponse2(handle,set2??{headers:{}});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length){if(response instanceof Promise)return response.then((response2)=>{if(!response2)return;if(!response2.headers.has("content-type"))response2.headers.append("content-type","text/plain");return response2.clone()});if(!response.headers.has("content-type"))response.headers.append("content-type","text/plain");return()=>response.clone()}};var websocket={open(ws){ws.data.open?.(ws)},message(ws,message){ws.data.message?.(ws,message)},drain(ws){ws.data.drain?.(ws)},close(ws,code,reason){ws.data.close?.(ws,code,reason)}};class ElysiaWS{raw;data;body;constructor(raw,data,body=void 0){this.raw=raw;this.data=data;this.body=body;this.validator=raw.data?.validator,this.sendText=raw.sendText.bind(raw),this.sendBinary=raw.sendBinary.bind(raw),this.close=raw.close.bind(raw),this.terminate=raw.terminate.bind(raw),this.publishText=raw.publishText.bind(raw),this.publishBinary=raw.publishBinary.bind(raw),this.subscribe=raw.subscribe.bind(raw),this.unsubscribe=raw.unsubscribe.bind(raw),this.isSubscribed=raw.isSubscribed.bind(raw),this.cork=raw.cork.bind(raw),this.remoteAddress=raw.remoteAddress,this.binaryType=raw.binaryType,this.data=raw.data,this.send=this.send.bind(this),this.ping=this.ping.bind(this),this.pong=this.pong.bind(this),this.publish=this.publish.bind(this)}send(data,compress){if(Buffer.isBuffer(data))return this.raw.send(data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.send(data,compress)}ping(data){if(Buffer.isBuffer(data))return this.raw.ping(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.ping(data)}pong(data){if(Buffer.isBuffer(data))return this.raw.pong(data);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.pong(data)}publish(topic,data,compress){if(Buffer.isBuffer(data))return this.raw.publish(topic,data,compress);if(this.validator?.Check(data)===!1)return this.raw.send(new ValidationError("message",this.validator,data).message);if(typeof data==="object")data=JSON.stringify(data);return this.raw.publish(topic,data,compress)}sendText;sendBinary;close;terminate;publishText;publishBinary;subscribe;unsubscribe;isSubscribed;cork;remoteAddress;binaryType;get readyState(){return this.raw.readyState}validator;["~types"];get id(){return this.data.id}}var createWSMessageParser=(parse2)=>{let parsers=typeof parse2==="function"?[parse2]:parse2;return async function parseMessage(ws,message){if(typeof message==="string"){let start=message?.charCodeAt(0);if(start===34||start===47||start===91||start===123)try{message=JSON.parse(message)}catch{}else if(isNumericString(message))message=+message;else if(message==="true")message=!0;else if(message==="false")message=!1;else if(message==="null")message=null}if(parsers)for(let i=0;i<parsers.length;i++){let temp=parsers[i](ws,message);if(temp instanceof Promise)temp=await temp;if(temp!==void 0)return temp}return message}},createHandleWSResponse=(validateResponse)=>{let handleWSResponse=(ws,data)=>{if(data instanceof Promise)return data.then((data2)=>handleWSResponse(ws,data2));if(Buffer.isBuffer(data))return ws.send(data.toString());if(data===void 0)return;let send=(datum)=>{if(validateResponse?.Check(datum)===!1)return ws.send(new ValidationError("message",validateResponse,datum).message);if(typeof datum==="object")return ws.send(JSON.stringify(datum));ws.send(datum)};if(typeof data?.next!=="function")return void send(data);let init=data.next();if(init instanceof Promise)return(async()=>{let first=await init;if(validateResponse?.Check(first)===!1)return ws.send(new ValidationError("message",validateResponse,first).message);if(send(first.value),!first.done)for await(let datum of data)send(datum)})();if(send(init.value),!init.done)for(let datum of data)send(datum)};return handleWSResponse};var optionalParam=/:.+?\?(?=\/|$)/,getPossibleParams=(path)=>{let match=optionalParam.exec(path);if(!match)return[path];let routes=[],head=path.slice(0,match.index),param=match[0].slice(0,-1),tail=path.slice(match.index+match[0].length);routes.push(head.slice(0,-1)),routes.push(head+param);for(let fragment of getPossibleParams(tail)){if(!fragment)continue;if(!fragment.startsWith("/:"))routes.push(head.slice(0,-1)+fragment);routes.push(head+param+fragment)}return routes},isHTMLBundle=(handle)=>{return typeof handle==="object"&&handle!==null&&(handle.toString()==="[object HTMLBundle]"||typeof handle.index==="string")},supportedMethods={GET:!0,HEAD:!0,OPTIONS:!0,DELETE:!0,PATCH:!0,POST:!0,PUT:!0},mapRoutes=(app)=>{if(!app.config.aot||!app.config.systemRouter)return;let routes={},add=(route,handler)=>{if(routes[route.path]){if(!routes[route.path][route.method])routes[route.path][route.method]=handler}else routes[route.path]={[route.method]:handler}},tree=app.routeTree;for(let route of app.router.history){if(typeof route.handler!=="function")continue;let method=route.method;if(method==="GET"&&`WS_${route.path}`in tree||method==="WS"||route.path.charCodeAt(route.path.length-1)===42||!(method in supportedMethods))continue;if(method==="ALL"){if(!(`WS_${route.path}`in tree))routes[route.path]=route.hooks?.config?.mount?route.hooks.trace||app.event.trace||app.extender.higherOrderFunctions?createBunRouteHandler(app,route):route.hooks.mount||route.handler:route.handler;continue}let compiled,handler=app.config.precompile?createBunRouteHandler(app,route):(request)=>{if(compiled)return compiled(request);return(compiled=createBunRouteHandler(app,route))(request)};for(let path of getPossibleParams(route.path))add({method,path},handler)}return routes},mergeRoutes=(r1,r2)=>{if(!r2)return r1;for(let key of Object.keys(r2)){if(r1[key]===r2[key])continue;if(!r1[key]){r1[key]=r2[key];continue}if(r1[key]&&r2[key]){if(typeof r1[key]==="function"||r1[key]instanceof Response){r1[key]=r2[key];continue}r1[key]={...r1[key],...r2[key]}}}return r1},BunAdapter={...WebStandardAdapter,name:"bun",handler:{mapResponse:mapResponse2,mapEarlyResponse:mapEarlyResponse2,mapCompactResponse:mapCompactResponse2,createStaticHandler:createStaticHandler2,createNativeStaticHandler},composeHandler:{...WebStandardAdapter.composeHandler,headers:hasHeaderShorthand?`c.headers=c.request.headers.toJSON()
|
|
359
359
|
`:`c.headers={}
|
|
360
360
|
for(const [k,v] of c.request.headers.entries())c.headers[k]=v
|
|
361
|
-
`},listen(app){return(options,callback)=>{if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(app.compile(),typeof options==="string"){if(!isNumericString(options))throw new Error("Port must be a numeric value");options=parseInt(options)}let createStaticRoute=(iterator,{withAsync=!1}={})=>{let staticRoutes={},ops=[];for(let[path,route]of Object.entries(iterator))if(supportPerMethodInlineHandler){if(!route)continue;for(let[method,value]of Object.entries(route)){if(!value||!(method in supportedMethods))continue;if(value instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(value.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path][method]=awaited;if(isHTMLBundle(awaited))staticRoutes[path][method]=awaited}))}continue}if(!(value instanceof Response)&&!isHTMLBundle(value))continue;if(!staticRoutes[path])staticRoutes[path]={};staticRoutes[path][method]=value}}else{if(!route)continue;if(route instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(route.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path]=awaited}))}continue}if(!(route instanceof Response))continue;staticRoutes[path]=route}if(withAsync)return Promise.all(ops).then(()=>staticRoutes);return staticRoutes},serve=typeof options==="object"?{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},...options||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{}},fetch:app.fetch}:{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{}},port:options,fetch:app.fetch};if(app.server=Bun.serve(serve),app.event.start)for(let i=0;i<app.event.start.length;i++)app.event.start[i].fn(app);if(callback)callback(app.server);process.on("beforeExit",()=>{if(app.server){if(app.server.stop?.(),app.server=null,app.event.stop)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}}),app.promisedModules.then(async()=>{app.server?.reload({...serve,fetch:app.fetch,routes:mergeRoutes(mergeRoutes(await createStaticRoute(app.router.response,{withAsync:!0}),mapRoutes(app)),app.config.serve?.routes)}),Bun?.gc(!1)})}},async stop(app,closeActiveConnections){if(app.server){if(app.server.stop(closeActiveConnections),app.server=null,app.event.stop?.length)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}else console.log("Elysia isn't running. Call `app.listen` to start the server.",new Error().stack)},ws(app,path,options){let{parse:parse2,body,response,...rest}=options,validateMessage=getSchemaValidator(body,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize}),validateResponse=getSchemaValidator(response,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize});app.route("WS",path,async(context)=>{let server=context.server??app.server,{set:set2,path:path2,qi,headers,query,params}=context;if(context.validator=validateResponse,options.upgrade){if(typeof options.upgrade==="function"){let temp=options.upgrade(context);if(temp instanceof Promise)await temp}else if(options.upgrade)Object.assign(set2.headers,options.upgrade)}if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"]);let handleResponse3=createHandleWSResponse(validateResponse),parseMessage=createWSMessageParser(parse2),_id;if(typeof options.beforeHandle==="function"){let result=options.beforeHandle(context);if(result instanceof Promise)await result}let errorHandlers=[...options.error?Array.isArray(options.error)?options.error:[options.error]:[],...(app.event.error??[]).map((x)=>typeof x==="function"?x:x.fn)].filter((x)=>x),handleErrors=!errorHandlers.length?()=>{}:async(ws,error2)=>{for(let handleError of errorHandlers){let response2=handleError(Object.assign(context,{error:error2}));if(response2 instanceof Promise)response2=await response2;if(await handleResponse3(ws,response2),response2)break}};if(server?.upgrade(context.request,{headers:isNotEmpty(set2.headers)?set2.headers:void 0,data:{...context,get id(){if(_id)return _id;return _id=randomId()},validator:validateResponse,ping(data){options.ping?.(data)},pong(data){options.pong?.(data)},open:async(ws)=>{try{await handleResponse3(ws,options.open?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},message:async(ws,_message)=>{let message=await parseMessage(ws,_message);if(validateMessage?.Check(message)===!1)return void ws.send(new ValidationError("message",validateMessage,message).message);try{await handleResponse3(ws,options.message?.(new ElysiaWS(ws,context,message),message))}catch(error2){handleErrors(ws,error2)}},drain:async(ws)=>{try{await handleResponse3(ws,options.drain?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},close:async(ws,code,reason)=>{try{await handleResponse3(ws,options.close?.(new ElysiaWS(ws,context),code,reason))}catch(error2){handleErrors(ws,error2)}}}}))return;return set2.status=400,"Expected a websocket connection"},{...rest,websocket:options})}};var env2=isBun?Bun.env:typeof process!=="undefined"&&process?.env?process.env:{};import{TransformDecodeError}from"@sinclair/typebox/value";var injectDefaultValues=(typeChecker,obj)=>{for(let[key,keySchema]of Object.entries(typeChecker.schema.properties))obj[key]??=keySchema.default},createDynamicHandler=(app)=>{let{mapResponse:mapResponse3,mapEarlyResponse:mapEarlyResponse3}=app["~adapter"].handler,defaultHeader=app.setHeaders;return async(request)=>{let url=request.url,s=url.indexOf("/",11),qi=url.indexOf("?",s+1),path=qi===-1?url.substring(s):url.substring(s,qi),set2={cookie:{},status:200,headers:defaultHeader?{...defaultHeader}:{}},context=Object.assign({},app.singleton.decorator,{set:set2,store:app.singleton.store,request,path,qi,error:status,status,redirect});try{if(app.event.request)for(let i=0;i<app.event.request.length;i++){let onRequest=app.event.request[i].fn,response2=onRequest(context);if(response2 instanceof Promise)response2=await response2;if(response2=mapEarlyResponse3(response2,set2),response2)return context.response=response2}let methodKey=request.method==="GET"&&request.headers.get("upgrade")?.toLowerCase()==="websocket"?"WS":request.method,handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find(methodKey,path)??app.router.dynamic.find("ALL",path);if(!handler)throw context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),new NotFoundError;let{handle,hooks,validator,content,route}=handler.store,body;if(request.method!=="GET"&&request.method!=="HEAD")if(content)switch(content){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}else{let contentType;if(request.body)contentType=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);if(context.contentType=contentType,hooks.parse)for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn;if(typeof hook==="string")switch(hook){case"json":case"application/json":body=await request.json();break;case"text":case"text/plain":body=await request.text();break;case"urlencoded":case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"arrayBuffer":case"application/octet-stream":body=await request.arrayBuffer();break;case"formdata":case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break;default:let parser=app["~parser"][hook];if(parser){let temp=parser(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}break}else{let temp=hook(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}}if(delete context.contentType,body===void 0)switch(contentType){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}}context.route=route,context.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),context.headers={};for(let[key,value]of request.headers.entries())context.headers[key]=value;let cookieMeta={domain:app.config.cookie?.domain??validator?.cookie?.config.domain,expires:app.config.cookie?.expires??validator?.cookie?.config.expires,httpOnly:app.config.cookie?.httpOnly??validator?.cookie?.config.httpOnly,maxAge:app.config.cookie?.maxAge??validator?.cookie?.config.maxAge,path:app.config.cookie?.path??validator?.cookie?.config.path,priority:app.config.cookie?.priority??validator?.cookie?.config.priority,partitioned:app.config.cookie?.partitioned??validator?.cookie?.config.partitioned,sameSite:app.config.cookie?.sameSite??validator?.cookie?.config.sameSite,secure:app.config.cookie?.secure??validator?.cookie?.config.secure,secrets:app.config.cookie?.secrets??validator?.cookie?.config.secrets,sign:app.config.cookie?.sign??validator?.cookie?.config.sign},cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta);let headerValidator=validator?.createHeaders?.();if(headerValidator)injectDefaultValues(headerValidator,context.headers);let paramsValidator=validator?.createParams?.();if(paramsValidator)injectDefaultValues(paramsValidator,context.params);let queryValidator=validator?.createQuery?.();if(queryValidator)injectDefaultValues(queryValidator,context.query);if(hooks.transform)for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="derive")Object.assign(context,response2)}if(validator){if(headerValidator){let _header=structuredClone(context.headers);for(let[key,value]of request.headers)_header[key]=value;if(validator.headers.Check(_header)===!1)throw new ValidationError("header",validator.headers,_header)}else if(validator.headers?.Decode)context.headers=validator.headers.Decode(context.headers);if(paramsValidator?.Check(context.params)===!1)throw new ValidationError("params",validator.params,context.params);else if(validator.params?.Decode)context.params=validator.params.Decode(context.params);if(validator.query?.schema){let properties=validator.query?.schema.properties;for(let property of Object.keys(properties)){let value=properties[property];if((value.type==="array"||value.items?.type==="string")&&typeof context.query[property]==="string"&&context.query[property]?.includes(","))context.query[property]=context.query[property].split(",")}}if(queryValidator?.Check(context.query)===!1)throw new ValidationError("query",validator.query,context.query);else if(validator.query?.Decode)context.query=validator.query.Decode(context.query);if(validator.createCookie?.()){let cookieValue={};for(let[key,value]of Object.entries(context.cookie))cookieValue[key]=value.value;if(validator.cookie.Check(cookieValue)===!1)throw new ValidationError("cookie",validator.cookie,cookieValue);else if(validator.cookie?.Decode)cookieValue=validator.cookie.Decode(cookieValue)}if(validator.createBody?.()?.Check(body)===!1)throw new ValidationError("body",validator.body,body);else if(validator.body?.Decode)context.body=validator.body.Decode(body)}if(hooks.beforeHandle)for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="resolve"){Object.assign(context,response2);continue}if(response2!==void 0){if(context.response=response2,hooks.afterHandle)for(let i2=0;i2<hooks.afterHandle.length;i2++){let newResponse=hooks.afterHandle[i2].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;if(newResponse)response2=newResponse}let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}}let response=typeof handle==="function"?handle(context):handle;if(response instanceof Promise)response=await response;if(!hooks.afterHandle?.length){let isCustomStatuResponse=response instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response=response.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response);response=temp}else throw new ValidationError("response",responseValidator,response);if(responseValidator?.Encode)response=responseValidator.Encode(response);if(responseValidator?.Clean)response=responseValidator.Clean(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let response2=hooks.afterHandle[i].fn(context);if(response2 instanceof Promise)response2=await response2;let isCustomStatuResponse=response2 instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response2.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response2=response2.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response2)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response2);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response2);response2=temp}else throw new ValidationError("response",responseValidator,response2);if(responseValidator?.Encode)context.response=response2=responseValidator.Encode(response2);if(responseValidator?.Clean)context.response=response2=responseValidator.Clean(response2);let result=mapEarlyResponse3(response2,context.set);if(result!==void 0)return context.response=result}}if(context.set.cookie&&cookieMeta?.sign){let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(cookieMeta.sign===!0){if(secret)for(let[key,cookie]of Object.entries(context.set.cookie))context.set.cookie[key].value=await signCookie(cookie.value,secret)}else{let properties=validator?.cookie?.schema?.properties;if(secret)for(let name of cookieMeta.sign){if(!(name in properties))continue;if(context.set.cookie[name]?.value)context.set.cookie[name].value=await signCookie(context.set.cookie[name].value,secret)}}}return mapResponse3(context.response=response,context.set)}catch(error2){let reportedError=error2 instanceof TransformDecodeError&&error2.error?error2.error:error2;return app.handleError(context,reportedError)}finally{if(app.event.afterResponse)setImmediate(async()=>{for(let afterResponse of app.event.afterResponse)await afterResponse.fn(context)})}}},createDynamicErrorHandler=(app)=>{let{mapResponse:mapResponse3}=app["~adapter"].handler;return async(context,error2)=>{let errorContext=Object.assign(context,{error:error2,code:error2.code});if(errorContext.set=context.set,app.event.error)for(let i=0;i<app.event.error.length;i++){let response=app.event.error[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)return context.response=mapResponse3(response,context.set)}return new Response(typeof error2.cause==="string"?error2.cause:error2.message,{headers:context.set.headers,status:error2.status??500})}};import{TypeSystemPolicy as TypeSystemPolicy2}from"@sinclair/typebox/system";class Elysia{config;server=null;dependencies={};"~Prefix"="";"~Singleton"=null;"~Definitions"=null;"~Metadata"=null;"~Ephemeral"=null;"~Volatile"=null;"~Routes"=null;singleton={decorator:{},store:{},derive:{},resolve:{}};get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}definitions={typebox:t.Module({}),type:{},error:{}};extender={macros:[],higherOrderFunctions:[]};validator={global:null,scoped:null,local:null,getCandidate(){if(!this.global&&!this.scoped&&!this.local)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return mergeSchemaValidator(mergeSchemaValidator(this.global,this.scoped),this.local)}};standaloneValidator={global:null,scoped:null,local:null};event={};telemetry;router={"~http":void 0,get http(){if(!this["~http"])this["~http"]=new _({lazy:!0,onParam:import_fast_decode_uri_component4.default});return this["~http"]},"~dynamic":void 0,get dynamic(){if(!this["~dynamic"])this["~dynamic"]=new _({onParam:import_fast_decode_uri_component4.default});return this["~dynamic"]},static:{},response:{},history:[]};routeTree={};get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}getGlobalDefinitions(){return this.definitions}inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1,path:!1,route:!1,url:!1};getServer(){return this.server}getParent(){return null}"~parser"={};_promisedModules;get promisedModules(){if(!this._promisedModules)this._promisedModules=new PromiseGroup(console.error,()=>{});return this._promisedModules}constructor(config={}){if(config.tags)if(!config.detail)config.detail={tags:config.tags};else config.detail.tags=config.tags;if(this.config={aot:env2.ELYSIA_AOT!=="false",nativeStaticResponse:!0,systemRouter:!0,encodeSchema:!0,normalize:!0,...config,prefix:config.prefix?config.prefix.charCodeAt(0)===47?config.prefix:`/${config.prefix}`:void 0,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this["~adapter"]=config.adapter??(typeof Bun!=="undefined"?BunAdapter:WebStandardAdapter),config?.analytic&&(config?.name||config?.seed!==void 0))this.telemetry={stack:new Error().stack}}"~adapter";env(model,_env=env2){if(getSchemaValidator(model,{modules:this.definitions.typebox,dynamic:!0,additionalProperties:!0,coerce:!0,sanitize:()=>this.config.sanitize}).Check(_env)===!1){let error2=new ValidationError("env",model,_env);throw new Error(error2.all.map((x)=>x.summary).join(`
|
|
361
|
+
`},listen(app){return(options,callback)=>{if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(app.compile(),typeof options==="string"){if(!isNumericString(options))throw new Error("Port must be a numeric value");options=parseInt(options)}let createStaticRoute=(iterator,{withAsync=!1}={})=>{let staticRoutes={},ops=[];for(let[path,route]of Object.entries(iterator))if(supportPerMethodInlineHandler){if(!route)continue;for(let[method,value]of Object.entries(route)){if(!value||!(method in supportedMethods))continue;if(value instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(value.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path][method]=awaited;if(isHTMLBundle(awaited))staticRoutes[path][method]=awaited}))}continue}if(!(value instanceof Response)&&!isHTMLBundle(value))continue;if(!staticRoutes[path])staticRoutes[path]={};staticRoutes[path][method]=value}}else{if(!route)continue;if(route instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(route.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path]=awaited}))}continue}if(!(route instanceof Response))continue;staticRoutes[path]=route}if(withAsync)return Promise.all(ops).then(()=>staticRoutes);return staticRoutes},serve=typeof options==="object"?{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},...options||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{}},fetch:app.fetch}:{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{}},port:options,fetch:app.fetch};if(app.server=Bun.serve(serve),app.event.start)for(let i=0;i<app.event.start.length;i++)app.event.start[i].fn(app);if(callback)callback(app.server);process.on("beforeExit",()=>{if(app.server){if(app.server.stop?.(),app.server=null,app.event.stop)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}}),app.promisedModules.then(async()=>{app.server?.reload({...serve,fetch:app.fetch,routes:mergeRoutes(mergeRoutes(await createStaticRoute(app.router.response,{withAsync:!0}),mapRoutes(app)),app.config.serve?.routes)}),Bun?.gc(!1)})}},async stop(app,closeActiveConnections){if(app.server){if(app.server.stop(closeActiveConnections),app.server=null,app.event.stop?.length)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}else console.log("Elysia isn't running. Call `app.listen` to start the server.",new Error().stack)},ws(app,path,options){let{parse:parse2,body,response,...rest}=options,validateMessage=getSchemaValidator(body,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize}),validateResponse=getSchemaValidator(response,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize});app.route("WS",path,async(context)=>{let server=context.server??app.server,{set:set2,path:path2,qi,headers,query,params}=context;if(context.validator=validateResponse,options.upgrade){if(typeof options.upgrade==="function"){let temp=options.upgrade(context);if(temp instanceof Promise)await temp}else if(options.upgrade)Object.assign(set2.headers,options.upgrade)}if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"]);let handleResponse3=createHandleWSResponse(validateResponse),parseMessage=createWSMessageParser(parse2),_id;if(typeof options.beforeHandle==="function"){let result=options.beforeHandle(context);if(result instanceof Promise)await result}let errorHandlers=[...options.error?Array.isArray(options.error)?options.error:[options.error]:[],...(app.event.error??[]).map((x)=>typeof x==="function"?x:x.fn)].filter((x)=>x),handleErrors=!errorHandlers.length?()=>{}:async(ws,error2)=>{for(let handleError of errorHandlers){let response2=handleError(Object.assign(context,{error:error2}));if(response2 instanceof Promise)response2=await response2;if(await handleResponse3(ws,response2),response2)break}};if(server?.upgrade(context.request,{headers:isNotEmpty(set2.headers)?set2.headers:void 0,data:{...context,get id(){if(_id)return _id;return _id=randomId()},validator:validateResponse,ping(data){options.ping?.(data)},pong(data){options.pong?.(data)},open:async(ws)=>{try{await handleResponse3(ws,options.open?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},message:async(ws,_message)=>{let message=await parseMessage(ws,_message);if(validateMessage?.Check(message)===!1)return void ws.send(new ValidationError("message",validateMessage,message).message);try{await handleResponse3(ws,options.message?.(new ElysiaWS(ws,context,message),message))}catch(error2){handleErrors(ws,error2)}},drain:async(ws)=>{try{await handleResponse3(ws,options.drain?.(new ElysiaWS(ws,context)))}catch(error2){handleErrors(ws,error2)}},close:async(ws,code,reason)=>{try{await handleResponse3(ws,options.close?.(new ElysiaWS(ws,context),code,reason))}catch(error2){handleErrors(ws,error2)}}}}))return;return set2.status=400,"Expected a websocket connection"},{...rest,websocket:options})}};var env2=isBun?Bun.env:typeof process!=="undefined"&&process?.env?process.env:{};import{TransformDecodeError}from"@sinclair/typebox/value";var injectDefaultValues=(typeChecker,obj)=>{let schema=typeChecker.schema;if(!schema)return;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];if(!schema?.properties)return;for(let[key,keySchema]of Object.entries(schema.properties))obj[key]??=keySchema.default},createDynamicHandler=(app)=>{let{mapResponse:mapResponse3,mapEarlyResponse:mapEarlyResponse3}=app["~adapter"].handler,defaultHeader=app.setHeaders;return async(request)=>{let url=request.url,s=url.indexOf("/",11),qi=url.indexOf("?",s+1),path=qi===-1?url.substring(s):url.substring(s,qi),set2={cookie:{},status:200,headers:defaultHeader?{...defaultHeader}:{}},context=Object.assign({},app.singleton.decorator,{set:set2,store:app.singleton.store,request,path,qi,error:status,status,redirect});try{if(app.event.request)for(let i=0;i<app.event.request.length;i++){let onRequest=app.event.request[i].fn,response2=onRequest(context);if(response2 instanceof Promise)response2=await response2;if(response2=mapEarlyResponse3(response2,set2),response2)return context.response=response2}let methodKey=request.method==="GET"&&request.headers.get("upgrade")?.toLowerCase()==="websocket"?"WS":request.method,handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find(methodKey,path)??app.router.dynamic.find("ALL",path);if(!handler)throw context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),new NotFoundError;let{handle,hooks,validator,content,route}=handler.store,body;if(request.method!=="GET"&&request.method!=="HEAD")if(content)switch(content){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}else{let contentType;if(request.body)contentType=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);if(context.contentType=contentType,hooks.parse)for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn;if(typeof hook==="string")switch(hook){case"json":case"application/json":body=await request.json();break;case"text":case"text/plain":body=await request.text();break;case"urlencoded":case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"arrayBuffer":case"application/octet-stream":body=await request.arrayBuffer();break;case"formdata":case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break;default:let parser=app["~parser"][hook];if(parser){let temp=parser(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}break}else{let temp=hook(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}}if(delete context.contentType,body===void 0)switch(contentType){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}}context.route=route,context.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),context.headers={};for(let[key,value]of request.headers.entries())context.headers[key]=value;let cookieMeta={domain:app.config.cookie?.domain??validator?.cookie?.config.domain,expires:app.config.cookie?.expires??validator?.cookie?.config.expires,httpOnly:app.config.cookie?.httpOnly??validator?.cookie?.config.httpOnly,maxAge:app.config.cookie?.maxAge??validator?.cookie?.config.maxAge,path:app.config.cookie?.path??validator?.cookie?.config.path,priority:app.config.cookie?.priority??validator?.cookie?.config.priority,partitioned:app.config.cookie?.partitioned??validator?.cookie?.config.partitioned,sameSite:app.config.cookie?.sameSite??validator?.cookie?.config.sameSite,secure:app.config.cookie?.secure??validator?.cookie?.config.secure,secrets:app.config.cookie?.secrets??validator?.cookie?.config.secrets,sign:app.config.cookie?.sign??validator?.cookie?.config.sign},cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta);let headerValidator=validator?.createHeaders?.();if(headerValidator)injectDefaultValues(headerValidator,context.headers);let paramsValidator=validator?.createParams?.();if(paramsValidator)injectDefaultValues(paramsValidator,context.params);let queryValidator=validator?.createQuery?.();if(queryValidator)injectDefaultValues(queryValidator,context.query);if(hooks.transform)for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="derive")Object.assign(context,response2)}if(validator){if(headerValidator){let _header=structuredClone(context.headers);for(let[key,value]of request.headers)_header[key]=value;if(validator.headers.Check(_header)===!1)throw new ValidationError("header",validator.headers,_header)}else if(validator.headers?.Decode)context.headers=validator.headers.Decode(context.headers);if(paramsValidator?.Check(context.params)===!1)throw new ValidationError("params",validator.params,context.params);else if(validator.params?.Decode)context.params=validator.params.Decode(context.params);if(validator.query?.schema){let schema=validator.query.schema;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];let properties=schema.properties;for(let property of Object.keys(properties)){let value=properties[property];if((value.type==="array"||value.items?.type==="string")&&typeof context.query[property]==="string"&&context.query[property])context.query[property]=context.query[property].split(",")}}if(queryValidator?.Check(context.query)===!1)throw new ValidationError("query",validator.query,context.query);else if(validator.query?.Decode)context.query=validator.query.Decode(context.query);if(validator.createCookie?.()){let cookieValue={};for(let[key,value]of Object.entries(context.cookie))cookieValue[key]=value.value;if(validator.cookie.Check(cookieValue)===!1)throw new ValidationError("cookie",validator.cookie,cookieValue);else if(validator.cookie?.Decode)cookieValue=validator.cookie.Decode(cookieValue)}if(validator.createBody?.()?.Check(body)===!1)throw new ValidationError("body",validator.body,body);else if(validator.body?.Decode)context.body=validator.body.Decode(body)}if(hooks.beforeHandle)for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="resolve"){Object.assign(context,response2);continue}if(response2!==void 0){if(context.response=response2,hooks.afterHandle)for(let i2=0;i2<hooks.afterHandle.length;i2++){let newResponse=hooks.afterHandle[i2].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;if(newResponse)response2=newResponse}let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}}let response=typeof handle==="function"?handle(context):handle;if(response instanceof Promise)response=await response;if(!hooks.afterHandle?.length){let isCustomStatuResponse=response instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response=response.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response);response=temp}else throw new ValidationError("response",responseValidator,response);if(responseValidator?.Encode)response=responseValidator.Encode(response);if(responseValidator?.Clean)response=responseValidator.Clean(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let response2=hooks.afterHandle[i].fn(context);if(response2 instanceof Promise)response2=await response2;let isCustomStatuResponse=response2 instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response2.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response2=response2.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response2)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response2);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response2);response2=temp}else throw new ValidationError("response",responseValidator,response2);if(responseValidator?.Encode)context.response=response2=responseValidator.Encode(response2);if(responseValidator?.Clean)context.response=response2=responseValidator.Clean(response2);let result=mapEarlyResponse3(response2,context.set);if(result!==void 0)return context.response=result}}if(context.set.cookie&&cookieMeta?.sign){let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(cookieMeta.sign===!0){if(secret)for(let[key,cookie]of Object.entries(context.set.cookie))context.set.cookie[key].value=await signCookie(cookie.value,secret)}else{let properties=validator?.cookie?.schema?.properties;if(secret)for(let name of cookieMeta.sign){if(!(name in properties))continue;if(context.set.cookie[name]?.value)context.set.cookie[name].value=await signCookie(context.set.cookie[name].value,secret)}}}return mapResponse3(context.response=response,context.set)}catch(error2){let reportedError=error2 instanceof TransformDecodeError&&error2.error?error2.error:error2;return app.handleError(context,reportedError)}finally{if(app.event.afterResponse)setImmediate(async()=>{for(let afterResponse of app.event.afterResponse)await afterResponse.fn(context)})}}},createDynamicErrorHandler=(app)=>{let{mapResponse:mapResponse3}=app["~adapter"].handler;return async(context,error2)=>{let errorContext=Object.assign(context,{error:error2,code:error2.code});if(errorContext.set=context.set,app.event.error)for(let i=0;i<app.event.error.length;i++){let response=app.event.error[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)return context.response=mapResponse3(response,context.set)}return new Response(typeof error2.cause==="string"?error2.cause:error2.message,{headers:context.set.headers,status:error2.status??500})}};import{TypeSystemPolicy as TypeSystemPolicy2}from"@sinclair/typebox/system";class Elysia{config;server=null;dependencies={};"~Prefix"="";"~Singleton"=null;"~Definitions"=null;"~Metadata"=null;"~Ephemeral"=null;"~Volatile"=null;"~Routes"=null;singleton={decorator:{},store:{},derive:{},resolve:{}};get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}definitions={typebox:t.Module({}),type:{},error:{}};extender={macros:[],higherOrderFunctions:[]};validator={global:null,scoped:null,local:null,getCandidate(){if(!this.global&&!this.scoped&&!this.local)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return mergeSchemaValidator(mergeSchemaValidator(this.global,this.scoped),this.local)}};standaloneValidator={global:null,scoped:null,local:null};event={};telemetry;router={"~http":void 0,get http(){if(!this["~http"])this["~http"]=new _({lazy:!0,onParam:import_fast_decode_uri_component4.default});return this["~http"]},"~dynamic":void 0,get dynamic(){if(!this["~dynamic"])this["~dynamic"]=new _({onParam:import_fast_decode_uri_component4.default});return this["~dynamic"]},static:{},response:{},history:[]};routeTree={};get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}getGlobalDefinitions(){return this.definitions}inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1,path:!1,route:!1,url:!1};getServer(){return this.server}getParent(){return null}"~parser"={};_promisedModules;get promisedModules(){if(!this._promisedModules)this._promisedModules=new PromiseGroup(console.error,()=>{});return this._promisedModules}constructor(config={}){if(config.tags)if(!config.detail)config.detail={tags:config.tags};else config.detail.tags=config.tags;if(this.config={aot:env2.ELYSIA_AOT!=="false",nativeStaticResponse:!0,systemRouter:!0,encodeSchema:!0,normalize:!0,...config,prefix:config.prefix?config.prefix.charCodeAt(0)===47?config.prefix:`/${config.prefix}`:void 0,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this["~adapter"]=config.adapter??(typeof Bun!=="undefined"?BunAdapter:WebStandardAdapter),config?.analytic&&(config?.name||config?.seed!==void 0))this.telemetry={stack:new Error().stack}}"~adapter";env(model,_env=env2){if(getSchemaValidator(model,{modules:this.definitions.typebox,dynamic:!0,additionalProperties:!0,coerce:!0,sanitize:()=>this.config.sanitize}).Check(_env)===!1){let error2=new ValidationError("env",model,_env);throw new Error(error2.all.map((x)=>x.summary).join(`
|
|
362
362
|
`))}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 context={redirect,request:this["~adapter"].isWebStandard?new Request(`http://e.ly${path}`,{method}):void 0,server:null,set:{headers:Object.assign({},this.setHeaders)},status,error:status,store:this.store};try{this.event.request?.map((x)=>{if(typeof x.fn==="function")return x.fn(context);if(typeof x==="function")return x(context)})}catch(error2){let res;if(context.error=error2,this.event.error?.some((x)=>{if(typeof x.fn==="function")return res=x.fn(context);if(typeof x==="function")return res=x(context)}),res!==void 0)handle=res}let fn=adapter.createNativeStaticHandler?.(handle,hooks,context.set);return fn instanceof Promise?fn.then((fn2)=>{if(fn2)return fn2}):fn?.()}:void 0,useNativeStaticResponse=this.config.nativeStaticResponse===!0,addResponsePath=(path2)=>{if(!useNativeStaticResponse||!nativeStaticHandler)return;if(supportPerMethodInlineHandler)if(this.router.response[path2])this.router.response[path2][method]=nativeStaticHandler();else this.router.response[path2]={[method]:nativeStaticHandler()};else this.router.response[path2]=nativeStaticHandler()};addResponsePath(path);let _compiled,compile2=()=>{if(_compiled)return _compiled;return _compiled=composeHandler({app:this,path,method,hooks,validator:createValidator(),handler:typeof handle!=="function"&&typeof adapter.createStaticHandler!=="function"?()=>handle:handle,allowMeta,inference:this.inference})},oldIndex;if(`${method}_${path}`in this.routeTree)for(let i=0;i<this.router.history.length;i++){let route=this.router.history[i];if(route.path===path&&route.method===method){oldIndex=i;break}}else this.routeTree[`${method}_${path}`]=this.router.history.length;let index=oldIndex??this.router.history.length,mainHandler=shouldPrecompile?compile2():(ctx)=>(this.router.history[index].composed=compile2())(ctx);if(oldIndex!==void 0)this.router.history[oldIndex]=Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0);else this.router.history.push(Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0));let handler={handler:shouldPrecompile?mainHandler:void 0,compile(){return this.handler=compile2()}},staticRouter=this.router.static,isStaticPath=path.indexOf(":")===-1&&path.indexOf("*")===-1;if(method==="WS"){if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};return}if(this.router.http.add("WS",path,handler),!this.config.strictPath)this.router.http.add("WS",getLoosePath(path),handler);let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add("WS",encoded,handler);return}if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};if(!this.config.strictPath)addResponsePath(getLoosePath(path))}else{if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath=getLoosePath(path);addResponsePath(loosePath),this.router.http.add(method,loosePath,handler)}let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add(method,encoded,handler),addResponsePath(encoded)}}setHeaders;headers(header){if(!header)return this;if(!this.setHeaders)this.setHeaders={};return this.setHeaders=mergeDeep(this.setHeaders,header),this}onStart(handler){return this.on("start",handler),this}onRequest(handler){return this.on("request",handler),this}onParse(options,handler){if(!handler){if(typeof options==="string")return this.on("parse",this["~parser"][options]);return this.on("parse",options)}return this.on(options,"parse",handler)}parser(name,parser){return this["~parser"][name]=parser,this}onTransform(options,handler){if(!handler)return this.on("transform",options);return this.on(options,"transform",handler)}resolve(optionsOrResolve,resolve){if(!resolve)resolve=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"resolve",fn:resolve};return this.onBeforeHandle(optionsOrResolve,hook)}mapResolve(optionsOrResolve,mapper){if(!mapper)mapper=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"mapResolve",fn:mapper};return this.onBeforeHandle(optionsOrResolve,hook)}onBeforeHandle(options,handler){if(!handler)return this.on("beforeHandle",options);return this.on(options,"beforeHandle",handler)}onAfterHandle(options,handler){if(!handler)return this.on("afterHandle",options);return this.on(options,"afterHandle",handler)}mapResponse(options,handler){if(!handler)return this.on("mapResponse",options);return this.on(options,"mapResponse",handler)}onAfterResponse(options,handler){if(!handler)return this.on("afterResponse",options);return this.on(options,"afterResponse",handler)}trace(options,handler){if(!handler)handler=options,options={as:"local"};if(!Array.isArray(handler))handler=[handler];for(let fn of handler)this.on(options,"trace",createTracer(fn));return this}error(name,error2){switch(typeof name){case"string":return error2.prototype[ERROR_CODE]=name,this.definitions.error[name]=error2,this;case"function":return this.definitions.error=name(this.definitions.error),this}for(let[code,error3]of Object.entries(name))error3.prototype[ERROR_CODE]=code,this.definitions.error[code]=error3;return this}onError(options,handler){if(!handler)return this.on("error",options);return this.on(options,"error",handler)}onStop(handler){return this.on("stop",handler),this}on(optionsOrType,typeOrHandlers,handlers){let type;switch(typeof optionsOrType){case"string":type=optionsOrType,handlers=typeOrHandlers;break;case"object":if(type=typeOrHandlers,!Array.isArray(typeOrHandlers)&&typeof typeOrHandlers==="object")handlers=typeOrHandlers;break}if(Array.isArray(handlers))handlers=fnToContainer(handlers);else if(typeof handlers==="function")handlers=[{fn:handlers}];else handlers=[handlers];let handles=handlers;for(let handle of handles)if(handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local",type==="resolve"||type==="derive")handle.subType=type;if(type!=="trace")this.inference=sucrose({[type]:handles.map((x)=>x.fn)},this.inference);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type){case"start":this.event.start??=[],this.event.start.push(fn);break;case"request":this.event.request??=[],this.event.request.push(fn);break;case"parse":this.event.parse??=[],this.event.parse.push(fn);break;case"transform":this.event.transform??=[],this.event.transform.push(fn);break;case"derive":this.event.transform??=[],this.event.transform.push(fnToContainer(fn,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(fn);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(fnToContainer(fn,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(fn);break;case"trace":this.event.trace??=[],this.event.trace.push(fn);break;case"error":this.event.error??=[],this.event.error.push(fn);break;case"stop":this.event.stop??=[],this.event.stop.push(fn);break}}return this}as(type){if(promoteEvent(this.event.parse,type),promoteEvent(this.event.transform,type),promoteEvent(this.event.beforeHandle,type),promoteEvent(this.event.afterHandle,type),promoteEvent(this.event.mapResponse,type),promoteEvent(this.event.afterResponse,type),promoteEvent(this.event.trace,type),promoteEvent(this.event.error,type),type==="scoped"){if(this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null}else if(type==="global"){if(this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null;if(this.standaloneValidator.scoped!==null)this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null}return this}group(prefix,schemaOrRun,run){let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.getServer=()=>this.getServer(),instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance["~parser"]=this["~parser"],instance.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let isSchema=typeof schemaOrRun==="object",sandbox=(isSchema?run:schemaOrRun)(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks,standaloneValidators})=>{if(path=(isSchema?"":this.config.prefix??"")+prefix+path,isSchema){let hook=schemaOrRun,localHook=hooks;this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]]}),void 0,standaloneValidators)}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0},standaloneValidators)}),this}guard(hook,run){if(!run){if(typeof hook==="object"){if(this.applyMacro(hook),hook.detail)if(this.config.detail)this.config.detail=mergeDeep(Object.assign({},this.config.detail),hook.detail);else this.config.detail=hook.detail;if(hook.tags)if(!this.config.detail)this.config.detail={tags:hook.tags};else this.config.detail.tags=hook.tags;let type=hook.as??"local";if(hook.schema==="standalone"){if(!this.standaloneValidator[type])this.standaloneValidator[type]=[];let response=hook?.response||typeof hook?.response==="string"||hook?.response&&Kind6 in hook.response?{200:hook.response}:hook?.response;this.standaloneValidator[type].push({body:hook.body,headers:hook.headers,params:hook.params,query:hook.query,response,cookie:hook.cookie})}else this.validator[type]={body:hook.body??this.validator[type]?.body,headers:hook.headers??this.validator[type]?.headers,params:hook.params??this.validator[type]?.params,query:hook.query??this.validator[type]?.query,response:hook.response??this.validator[type]?.response,cookie:hook.cookie??this.validator[type]?.cookie};if(hook.parse)this.on({as:type},"parse",hook.parse);if(hook.transform)this.on({as:type},"transform",hook.transform);if(hook.derive)this.on({as:type},"derive",hook.derive);if(hook.beforeHandle)this.on({as:type},"beforeHandle",hook.beforeHandle);if(hook.resolve)this.on({as:type},"resolve",hook.resolve);if(hook.afterHandle)this.on({as:type},"afterHandle",hook.afterHandle);if(hook.mapResponse)this.on({as:type},"mapResponse",hook.mapResponse);if(hook.afterResponse)this.on({as:type},"afterResponse",hook.afterResponse);if(hook.error)this.on({as:type},"error",hook.error);return this}return this.guard({},hook)}let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance.getServer=()=>this.getServer();let sandbox=run(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.getServer=()=>this.server,sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks:localHook})=>{this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]]}))}),this}use(plugin){if(!plugin)return this;if(Array.isArray(plugin)){let app=this;for(let p of plugin)app=app.use(p);return app}if(plugin instanceof Promise)return this.promisedModules.add(plugin.then((plugin2)=>{if(typeof plugin2==="function")return plugin2(this);if(plugin2 instanceof Elysia)return this._use(plugin2).compile();if(plugin2.constructor.name==="Elysia")return this._use(plugin2).compile();if(typeof plugin2.default==="function")return plugin2.default(this);if(plugin2.default instanceof Elysia)return this._use(plugin2.default);if(plugin2.constructor.name==="Elysia")return this._use(plugin2.default);if(plugin2.constructor.name==="_Elysia")return this._use(plugin2.default);try{return this._use(plugin2.default)}catch(error2){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),error2}}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return this._use(plugin)}propagatePromiseModules(plugin){if(plugin.promisedModules.size<=0)return this;for(let promise of plugin.promisedModules.promises)this.promisedModules.add(promise.then((v)=>{if(!v)return;let t2=this._use(v);if(t2 instanceof Promise)return t2.then((v2)=>{if(v2)v2.compile();else v.compile()});return v.compile()}));return this}_use(plugin){if(typeof plugin==="function"){let instance=plugin(this);if(instance instanceof Promise)return this.promisedModules.add(instance.then((plugin2)=>{if(plugin2 instanceof Elysia){plugin2.getServer=()=>this.getServer(),plugin2.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin2.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin2.model(this.definitions.type),plugin2.error(this.definitions.error);for(let{method,path,handler,hooks,standaloneValidators}of Object.values(plugin2.router.history))this.add(method,path,handler,hooks,void 0,standaloneValidators);if(plugin2===this)return;return this.propagatePromiseModules(plugin2),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return instance}this.propagatePromiseModules(plugin);let name=plugin.config.name,seed=plugin.config.seed;if(plugin.getParent=()=>this,plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin.standaloneValidator?.scoped)if(this.standaloneValidator.local)this.standaloneValidator.local=this.standaloneValidator.local.concat(plugin.standaloneValidator.scoped);else this.standaloneValidator.local=plugin.standaloneValidator.scoped;if(plugin.standaloneValidator?.global)if(this.standaloneValidator.global)this.standaloneValidator.global=this.standaloneValidator.global.concat(plugin.standaloneValidator.global);else this.standaloneValidator.global=plugin.standaloneValidator.global;if(isNotEmpty(plugin["~parser"]))this["~parser"]={...plugin["~parser"],...this["~parser"]};if(plugin.setHeaders)this.headers(plugin.setHeaders);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(!this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))this.extender.macros=this.extender.macros.concat(plugin.extender.macros),this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}else{if(plugin.extender.macros.length)this.extender.macros=this.extender.macros.concat(plugin.extender.macros);if(plugin.extender.higherOrderFunctions.length)this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}if(deduplicateChecksum(this.extender.macros),plugin.extender.higherOrderFunctions.length){deduplicateChecksum(this.extender.higherOrderFunctions);let hofHashes=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let hof=this.extender.higherOrderFunctions[i];if(hof.checksum){if(hofHashes.includes(hof.checksum))this.extender.higherOrderFunctions.splice(i,1),i--;hofHashes.push(hof.checksum)}}hofHashes.length=0}if(this.inference=mergeInference(this.inference,plugin.inference),isNotEmpty(plugin.singleton.decorator))this.decorate(plugin.singleton.decorator);if(isNotEmpty(plugin.singleton.store))this.state(plugin.singleton.store);if(isNotEmpty(plugin.definitions.type))this.model(plugin.definitions.type);if(isNotEmpty(plugin.definitions.error))this.error(plugin.definitions.error);if(isNotEmpty(plugin.definitions.error))plugin.extender.macros=this.extender.macros.concat(plugin.extender.macros);for(let{method,path,handler,hooks,standaloneValidators}of Object.values(plugin.router.history))this.add(method,path,handler,hooks,void 0,standaloneValidators);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))return this;if(this.dependencies[name].push(this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies,stack:plugin.telemetry?.stack,routes:plugin.router.history,decorators:plugin.singleton,store:plugin.singleton.store,error:plugin.definitions.error,derive:plugin.event.transform?.filter((x)=>x?.subType==="derive").map((x)=>({fn:x.toString(),stack:new Error().stack??""})),resolve:plugin.event.transform?.filter((x)=>x?.subType==="resolve").map((x)=>({fn:x.toString(),stack:new Error().stack??""}))}:{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}),isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event),current)}else if(isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event));if(plugin.validator.global)this.validator.global=mergeHook(this.validator.global,{...plugin.validator.global});if(plugin.validator.scoped)this.validator.local=mergeHook(this.validator.local,{...plugin.validator.scoped});return this}macro(macro){if(typeof macro==="function"){let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:macro.toString()})),fn:macro};this.extender.macros.push(hook)}else if(typeof macro==="object"){for(let name of Object.keys(macro))if(typeof macro[name]==="object"){let actualValue={...macro[name]};macro[name]=(v)=>{if(v===!0)return actualValue}}let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:Object.entries(macro).map(([k2,v])=>`${k2}+${v}`).join(",")})),fn:()=>macro};this.extender.macros.push(hook)}return this}mount(path,handleOrConfig,config){if(path instanceof Elysia||typeof path==="function"||path.length===0||path==="/"){let run=typeof path==="function"?path:path instanceof Elysia?path.compile().fetch:handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw new Error("Invalid handler")})(),handler2=({request,path:path2})=>run(new Request(replaceUrlPath(request.url,path2),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL","/*",handler2,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:run}}),this}let handle=handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw new Error("Invalid handler")})(),length=path.length-(path.endsWith("*")?1:0),handler=({request,path:path2})=>handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL",path,handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this.route("ALL",path+(path.endsWith("/")?"*":"/*"),handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this}get(path,handler,hook){return this.add("GET",path,handler,hook),this}post(path,handler,hook){return this.add("POST",path,handler,hook),this}put(path,handler,hook){return this.add("PUT",path,handler,hook),this}patch(path,handler,hook){return this.add("PATCH",path,handler,hook),this}delete(path,handler,hook){return this.add("DELETE",path,handler,hook),this}options(path,handler,hook){return this.add("OPTIONS",path,handler,hook),this}all(path,handler,hook){return this.add("ALL",path,handler,hook),this}head(path,handler,hook){return this.add("HEAD",path,handler,hook),this}connect(path,handler,hook){return this.add("CONNECT",path,handler,hook),this}route(method,path,handler,hook){return this.add(method.toUpperCase(),path,handler,hook,hook?.config),this}ws(path,options){if(this["~adapter"].ws)this["~adapter"].ws(this,path,options);else console.warn("Current adapter doesn't support WebSocket");return this}state(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(!value||!isNotEmpty(value))return this;if(name){if(name in this.singleton.store)this.singleton.store[name]=mergeDeep(this.singleton.store[name],value,{override:as==="override"});else this.singleton.store[name]=value;return this}if(value===null)return this;return this.singleton.store=mergeDeep(this.singleton.store,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value}else this.singleton.store=value(this.singleton.store);return this;default:if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value;return this}}decorate(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(name){if(name in this.singleton.decorator)this.singleton.decorator[name]=mergeDeep(this.singleton.decorator[name],value,{override:as==="override"});else this.singleton.decorator[name]=value;return this}if(value===null)return this;return this.singleton.decorator=mergeDeep(this.singleton.decorator,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value}else this.singleton.decorator=value(this.singleton.decorator);return this;default:if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value;return this}}derive(optionsOrTransform,transform){if(!transform)transform=optionsOrTransform,optionsOrTransform={as:"local"};let hook={subType:"derive",fn:transform};return this.onTransform(optionsOrTransform,hook)}model(name,model){switch(typeof name){case"object":let parsedSchemas={},kvs=Object.entries(name);if(!kvs.length)return this;for(let[key,value]of kvs){if(key in this.definitions.type)continue;parsedSchemas[key]=this.definitions.type[key]=value,parsedSchemas[key].$id??=`#/components/schemas/${key}`}return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...parsedSchemas}),this;case"function":let result=name(this.definitions.type);return this.definitions.type=result,this.definitions.typebox=t.Module(result),this;case"string":if(!model)break;let newModel={...model,id:model.$id??`#/components/schemas/${name}`};return this.definitions.type[name]=model,this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...newModel}),this}return this.definitions.type[name]=model,this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,[name]:model}),this}Ref(key){return t.Ref(key)}mapDerive(optionsOrDerive,mapper){if(!mapper)mapper=optionsOrDerive,optionsOrDerive={as:"local"};let hook={subType:"mapDerive",fn:mapper};return this.onTransform(optionsOrDerive,hook)}affix(base,type,word){if(word==="")return this;let delimieter=["_","-"," "],capitalize=(word2)=>word2[0].toUpperCase()+word2.slice(1),joinKey=base==="prefix"?(prefix,word2)=>delimieter.includes(prefix.at(-1)??"")?prefix+word2:prefix+capitalize(word2):delimieter.includes(word.at(-1)??"")?(suffix,word2)=>word2+suffix:(suffix,word2)=>word2+capitalize(suffix),remap=(type2)=>{let store={};switch(type2){case"decorator":for(let key in this.singleton.decorator)store[joinKey(word,key)]=this.singleton.decorator[key];this.singleton.decorator=store;break;case"state":for(let key in this.singleton.store)store[joinKey(word,key)]=this.singleton.store[key];this.singleton.store=store;break;case"model":for(let key in this.definitions.type)store[joinKey(word,key)]=this.definitions.type[key];this.definitions.type=store;break;case"error":for(let key in this.definitions.error)store[joinKey(word,key)]=this.definitions.error[key];this.definitions.error=store;break}},types=Array.isArray(type)?type:[type];for(let type2 of types.some((x)=>x==="all")?["decorator","state","model","error"]:types)remap(type2);return this}prefix(type,word){return this.affix("prefix",type,word)}suffix(type,word){return this.affix("suffix",type,word)}compile(){if(this["~adapter"].isWebStandard){if(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this),typeof this.server?.reload==="function")this.server.reload({...this.server||{},fetch:this.fetch});return this}if(typeof this.server?.reload==="function")this.server.reload(this.server||{});return this._handle=composeGeneralHandler(this),this}handle=async(request)=>this.fetch(request);fetch=(request)=>{return(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this))(request)};handleError=async(context,error2)=>{return(this.handleError=this.config.aot?composeErrorHandler(this):createDynamicErrorHandler(this))(context,error2)};listen=(options,callback)=>{if(this["~adapter"].listen(this)(options,callback),this.promisedModules.size)clearSucroseCache(5000);return this.promisedModules.then(()=>{clearSucroseCache(1000)}),this};stop=async(closeActiveConnections)=>{return await this["~adapter"].stop?.(this,closeActiveConnections),this};[Symbol.dispose]=()=>{if(this.server)this.stop()};get modules(){return this.promisedModules}}export{t,status,sse,serializeCookie,replaceUrlPath,replaceSchemaType,redirect,mergeObjectArray,mergeHook,mapValueError,getSchemaValidator,getResponseSchemaValidator,form,file,error,env2 as env,Elysia as default,deduplicateChecksum,cloneInference,checksum,ValidationError,TypeSystemPolicy2 as TypeSystemPolicy,StatusMap,ParseError,NotFoundError,InvertedStatusMap,InvalidCookieSignature,InternalServerError,ElysiaFile,ElysiaCustomStatusResponse,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
|
|
363
363
|
|
|
364
|
-
//# debugId=
|
|
364
|
+
//# debugId=98EA029F72BD1F3764756E2164756E21
|
|
365
365
|
//# sourceMappingURL=index.js.map
|