elysia 1.2.23 → 1.2.25

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
@@ -105,7 +105,7 @@ const vEnd=value.charCodeAt(value.length - 1)
105
105
  if((vStart===91&&vEnd===93)||(vStart===123&&vEnd===125))
106
106
  try{a${index}.push(JSON.parse(value))}catch{a${index}.push(value)}if(deepMemory===-1)break}}`;fnLiteral+="}}"}index++,fnLiteral+=`
107
107
  `}fnLiteral+="c.query={"+destructured.map(({key},index2)=>`'${key}':a${index2}`).join(",")+"}",fnLiteral+=`} else c.query = {}
108
- `}}let isAsyncHandler=typeof handler==="function"&&isAsync(handler),saveResponse=hasTrace||hooks.afterResponse?.length?"c.response= ":"",maybeAsync=hasCookie||hasBody||isAsyncHandler||!!hooks.parse?.length||!!hooks.afterHandle?.some(isAsync)||!!hooks.beforeHandle?.some(isAsync)||!!hooks.transform?.some(isAsync)||!!hooks.mapResponse?.some(isAsync),maybeStream=(typeof handler==="function"?isGenerator(handler):!1)||!!hooks.beforeHandle?.some(isGenerator)||!!hooks.afterHandle?.some(isGenerator)||!!hooks.transform?.some(isGenerator),hasSet=inference.cookie||inference.set||hasHeaders||hasTrace||validator.response||isHandleFn&&hasDefaultHeaders||maybeStream,mapResponseContext=adapter.mapResponseContext?`,${adapter.mapResponseContext}`:"";if(inference.route)fnLiteral+=`c.route=\`${path}\`
108
+ `}}let isAsyncHandler=typeof handler==="function"&&isAsync(handler),saveResponse=hasTrace||hooks.afterResponse?.length?"c.response= ":"",maybeAsync=hasCookie||hasBody||isAsyncHandler||!!hooks.parse?.length||!!hooks.afterHandle?.some(isAsync)||!!hooks.beforeHandle?.some(isAsync)||!!hooks.transform?.some(isAsync)||!!hooks.mapResponse?.some(isAsync),maybeStream=(typeof handler==="function"?isGenerator(handler):!1)||!!hooks.beforeHandle?.some(isGenerator)||!!hooks.afterHandle?.some(isGenerator)||!!hooks.transform?.some(isGenerator),hasSet=inference.cookie||inference.set||hasHeaders||hasTrace||validator.response||isHandleFn&&hasDefaultHeaders||maybeStream,mapResponseContext=adapter.mapResponseContext?`,${adapter.mapResponseContext}`:"";if(hasTrace||inference.route)fnLiteral+=`c.route=\`${path}\`
109
109
  `;let parseReporter=report("parse",{total:hooks.parse?.length});if(hasBody){let isOptionalBody=isOptional(validator.body),hasBodyInference=!!hooks.parse?.length||inference.body||validator.body;if(adapter.parser.declare)fnLiteral+=adapter.parser.declare;fnLiteral+=`
110
110
  isParsing=true
111
111
  `;let parser=typeof hooks.parse==="string"?hooks.parse:Array.isArray(hooks.parse)&&hooks.parse.length===1?typeof hooks.parse[0]==="string"?hooks.parse[0]:typeof hooks.parse[0].fn==="string"?hooks.parse[0].fn:void 0:void 0;if(parser&&defaultParsers.includes(parser)){let reporter=report("parse",{total:hooks.parse?.length});switch(parser){case"json":case"application/json":fnLiteral+=adapter.parser.json(isOptionalBody);break;case"text":case"text/plain":fnLiteral+=adapter.parser.text(isOptionalBody);break;case"urlencoded":case"application/x-www-form-urlencoded":fnLiteral+=adapter.parser.urlencoded(isOptionalBody);break;case"arrayBuffer":case"application/octet-stream":fnLiteral+=adapter.parser.arrayBuffer(isOptionalBody);break;case"formdata":case"multipart/form-data":fnLiteral+=adapter.parser.formData(isOptionalBody);break;default:if(parser[0]in app["~parser"])fnLiteral+=hasHeaders?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')",fnLiteral+=`
@@ -171,9 +171,9 @@ else Object.assign(c,transformed)
171
171
  `}if(isOptional(validator.query))fnLiteral+="if(isNotEmpty(c.query)){";if(fnLiteral+="if(validator.query.Check(c.query)===false){"+composeValidation("query")+"}",hasTransform(validator.query.schema))fnLiteral+=`c.query=validator.query.Decode(Object.assign({},c.query))
172
172
  `;if(isOptional(validator.query))fnLiteral+="}"}if(validator.body){if(normalize&&"Clean"in validator.body&&!hasAdditionalProperties(validator.body))fnLiteral+=`c.body=validator.body.Clean(c.body)
173
173
  `;let doesHaveTransform=hasTransform(validator.body.schema);if(doesHaveTransform||isOptional(validator.body))fnLiteral+=`const isNotEmptyObject=c.body&&(typeof c.body==="object"&&isNotEmpty(c.body))
174
- `;if(hasProperty("default",validator.body)){let value=Value4.Default(validator.body.schema,validator.body.schema.type==="object"?{}:void 0),parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(fnLiteral+=`if(validator.body.Check(c.body)===false){if(typeof c.body==='object')c.body=Object.assign(${parsed},c.body)
174
+ `;if(hasProperty("default",validator.body)){let schema=validator.body.schema,value=Value4.Default(schema,schema.type==="object"||schema[TypeBoxSymbol.kind]==="Import"&&schema.$defs[schema.$ref][TypeBoxSymbol.kind]==="Object"?{}:void 0),parsed=typeof value==="object"?JSON.stringify(value):typeof value==="string"?`'${value}'`:value;if(fnLiteral+="if(validator.body.Check(c.body)===false){",value!==void 0&&value!==null)fnLiteral+=`if(typeof c.body==='object')c.body=Object.assign(${parsed},c.body)
175
175
  else c.body=${parsed}
176
- `,isOptional(validator.body))fnLiteral+="if(isNotEmptyObject&&validator.body.Check(c.body)===false){"+composeValidation("body")+"}";else fnLiteral+="if(validator.body.Check(c.body)===false){"+composeValidation("body")+"}";fnLiteral+="}"}else if(isOptional(validator.body))fnLiteral+="if(isNotEmptyObject&&validator.body.Check(c.body)===false){"+composeValidation("body")+"}";else fnLiteral+="if(validator.body.Check(c.body)===false){"+composeValidation("body")+"}";if(doesHaveTransform)fnLiteral+=`if(isNotEmptyObject)c.body=validator.body.Decode(c.body)
176
+ `;if(isOptional(validator.body))fnLiteral+="if(isNotEmptyObject&&validator.body.Check(c.body)===false){"+composeValidation("body")+"}";else fnLiteral+="if(validator.body.Check(c.body)===false){"+composeValidation("body")+"}";fnLiteral+="}"}else if(isOptional(validator.body))fnLiteral+="if(isNotEmptyObject&&validator.body.Check(c.body)===false){"+composeValidation("body")+"}";else fnLiteral+="if(validator.body.Check(c.body)===false){"+composeValidation("body")+"}";if(doesHaveTransform)fnLiteral+=`if(isNotEmptyObject)c.body=validator.body.Decode(c.body)
177
177
  `}if(cookieValidator&&isNotEmpty(cookieValidator?.schema?.properties??cookieValidator?.schema?.schema??{})){if(fnLiteral+=`const cookieValue={}
178
178
  for(const [key,value] of Object.entries(c.cookie))cookieValue[key]=value.value
179
179
  `,hasProperty("default",cookieValidator))for(let[key,value]of Object.entries(Value4.Default(cookieValidator.schema,{})))fnLiteral+=`cookieValue['${key}'] = ${typeof value==="object"?JSON.stringify(value):value}
@@ -324,4 +324,4 @@ return mapResponse(${saveResponse}error,set${adapter.mapResponseContext})}`,Func
324
324
  `;else staticRouter.map[path].code=`case '${method}':return ht[${index}].composed(${ctx})
325
325
  ${staticRouter.map[path].code}`;if(!this.config.strictPath&&this.config.nativeStaticResponse===!0&&nativeStaticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[getLoosePath(path)]=nativeStaticHandler()}else{if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath=getLoosePath(path);if(this.config.nativeStaticResponse===!0&&staticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[loosePath]=staticHandler();this.router.http.add(method,loosePath,handler)}let encoded=encodePath(path,{dynamic:!0});if(path!==encoded){if(this.router.http.add(method,encoded,handler),this.config.nativeStaticResponse===!0&&staticHandler&&(method==="GET"||method==="ALL"))this.router.static.http.static[encoded]=staticHandler();this.router.http.add(method,encoded,handler)}}}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 type2;switch(typeof optionsOrType){case"string":type2=optionsOrType,handlers=typeOrHandlers;break;case"object":if(type2=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",type2==="resolve"||type2==="derive")handle.subType=type2;if(type2!=="trace")sucrose({[type2]:handles.map((x)=>x.fn)},this.inference);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type2){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}propagate(){return promoteEvent(this.event.parse),promoteEvent(this.event.transform),promoteEvent(this.event.beforeHandle),promoteEvent(this.event.afterHandle),promoteEvent(this.event.mapResponse),promoteEvent(this.event.afterResponse),promoteEvent(this.event.trace),promoteEvent(this.event.error),this}as(type2){let castType={plugin:"scoped",scoped:"scoped",global:"global"}[type2];if(promoteEvent(this.event.parse,castType),promoteEvent(this.event.transform,castType),promoteEvent(this.event.beforeHandle,castType),promoteEvent(this.event.afterHandle,castType),promoteEvent(this.event.mapResponse,castType),promoteEvent(this.event.afterResponse,castType),promoteEvent(this.event.trace,castType),promoteEvent(this.event.error,castType),type2==="plugin")this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null;else if(type2==="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};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})=>{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||{}]}))}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0})}),this}guard(hook,run){if(!run){if(typeof hook==="object"){this.applyMacro(hook);let type2=hook.as??"local";if(this.validator[type2]={body:hook.body??this.validator[type2]?.body,headers:hook.headers??this.validator[type2]?.headers,params:hook.params??this.validator[type2]?.params,query:hook.query??this.validator[type2]?.query,response:hook.response??this.validator[type2]?.response,cookie:hook.cookie??this.validator[type2]?.cookie},hook.parse)this.on({as:type2},"parse",hook.parse);if(hook.transform)this.on({as:type2},"transform",hook.transform);if(hook.derive)this.on({as:type2},"derive",hook.derive);if(hook.beforeHandle)this.on({as:type2},"beforeHandle",hook.beforeHandle);if(hook.resolve)this.on({as:type2},"resolve",hook.resolve);if(hook.afterHandle)this.on({as:type2},"afterHandle",hook.afterHandle);if(hook.mapResponse)this.on({as:type2},"mapResponse",hook.mapResponse);if(hook.afterResponse)this.on({as:type2},"afterResponse",hook.afterResponse);if(hook.error)this.on({as:type2},"error",hook.error);if(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;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.model(this.definitions.type),plugin2.error(this.definitions.error);for(let{method,path,handler,hooks}of Object.values(plugin2.router.history))this.add(method,path,handler,mergeHook(hooks,{error:plugin2.event.error}));if(plugin2.compile(),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,seed}=plugin.config;if(plugin.getParent=()=>this,plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.model(this.definitions.type),plugin.error(this.definitions.error),this["~parser"]={...plugin["~parser"],...this["~parser"]},this.headers(plugin.setHeaders),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 this.extender.macros=this.extender.macros.concat(plugin.extender.macros),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)}}this.inference={body:this.inference.body||plugin.inference.body,cookie:this.inference.cookie||plugin.inference.cookie,headers:this.inference.headers||plugin.inference.headers,query:this.inference.query||plugin.inference.query,set:this.inference.set||plugin.inference.set,server:this.inference.server||plugin.inference.server,request:this.inference.request||plugin.inference.request,route:this.inference.route||plugin.inference.route},this.decorate(plugin.singleton.decorator),this.state(plugin.singleton.store),this.model(plugin.definitions.type),this.error(plugin.definitions.error),plugin.extender.macros=this.extender.macros.concat(plugin.extender.macros);for(let{method,path,handler,hooks}of Object.values(plugin.router.history))this.add(method,path,handler,mergeHook(hooks,{error:plugin.event.error}));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;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}),this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event),current)}else this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event));return this.validator.global=mergeHook(this.validator.global,{...plugin.validator.global}),this.validator.local=mergeHook(this.validator.local,{...plugin.validator.scoped}),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(([k,v])=>`${k}+${v}`).join(",")})),fn:()=>macro};this.extender.macros.push(hook)}return this}mount(path,handle){if(path instanceof Elysia||typeof path==="function"||path.length===0||path==="/"){let run=typeof path==="function"?path:path instanceof Elysia?path.compile().fetch:handle instanceof Elysia?handle.compile().fetch:handle,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.all("/*",handler2,{parse:"none"}),this}if(!handle)return this;let length=path.length-(path.endsWith("*")?1:0);if(handle instanceof Elysia)handle=handle.compile().fetch;let 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.all(path,handler,{parse:"none"}),this.all(path+(path.endsWith("/")?"*":"/*"),handler,{parse:"none"}),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(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){let coerce=(schema)=>replaceSchemaType(schema,[{from:t.Number(),to:(options)=>t.Numeric(options),untilObjectFound:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),untilObjectFound:!0}]);switch(typeof name){case"object":let parsedSchemas={},kvs=Object.entries(name);for(let[key,value]of kvs){if(key in this.definitions.type)continue;parsedSchemas[key]=this.definitions.type[key]=coerce(value),parsedSchemas[key].$id??=`#/components/schemas/${key}`}return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...parsedSchemas}),this;case"function":let result=coerce(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}mapDerive(optionsOrDerive,mapper){if(!mapper)mapper=optionsOrDerive,optionsOrDerive={as:"local"};let hook={subType:"mapDerive",fn:mapper};return this.onTransform(optionsOrDerive,hook)}affix(base,type2,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=(type3)=>{let store={};switch(type3){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(type2)?type2:[type2];for(let type3 of types.some((x)=>x==="all")?["decorator","state","model","error"]:types)remap(type3);return this}prefix(type2,word){return this.affix("prefix",type2,word)}suffix(type2,word){return this.affix("suffix",type2,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)};outerErrorHandler=(error2)=>new Response(error2.message||error2.name||"Error",{status:error2?.status??500});listen=(options,callback)=>{return this["~adapter"].listen(this)(options,callback),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,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};
326
326
 
327
- //# debugId=B27DE94378765A2E64756E2164756E21
327
+ //# debugId=7B471551AD67061D64756E2164756E21