elysia 1.2.21 → 1.2.22
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 +3 -3
- package/dist/cjs/compose.js +7 -10
- package/dist/compose.mjs +7 -10
- package/package.json +1 -1
package/dist/bun/index.js
CHANGED
|
@@ -40,11 +40,11 @@ for (const [key, value] of c.request.headers.entries())c.headers[key] = value
|
|
|
40
40
|
${name}=${name}.response}const isResponse=${name} instanceof Response
|
|
41
41
|
switch(c.set.status){`;for(let[status,value]of Object.entries(validator.response)){if(code+=`
|
|
42
42
|
case ${status}:if(!isResponse){`,normalize&&"Clean"in value&&!hasAdditionalProperties(value))code+=`${name}=validator.response['${status}'].Clean(${name})
|
|
43
|
-
`;if(code
|
|
43
|
+
`;if(encodeSchema&&(value.hasTransform||typeof value.Decode==="function"))code+=`${name}=validator.response['${status}'].Encode(${name})
|
|
44
|
+
`;code+=`if(validator.response['${status}'].Check(${name})===false){c.set.status=422
|
|
44
45
|
throw new ValidationError('response',validator.response['${status}'],${name})}c.set.status = ${status}}
|
|
45
|
-
`,
|
|
46
|
-
|
|
47
|
-
`}return code+"}"}}),KindSymbol=Symbol.for("TypeBox.Kind");var hasProperty=(expectedProperty,_schema)=>{if(!_schema)return;let schema=_schema.schema??_schema;if(schema[TypeBoxSymbol.kind]==="Import")return _schema.References().some((schema2)=>hasProperty(expectedProperty,schema2));if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(expectedProperty in property)return!0;if(property.type==="object"){if(hasProperty(expectedProperty,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasProperty(expectedProperty,property.anyOf[i]))return!0}}return!1}return expectedProperty in schema},TransformSymbol=Symbol.for("TypeBox.Transform");var hasTransform=(schema)=>{if(!schema)return!1;if(schema.$ref&&schema.$defs&&schema.$ref in schema.$defs)return hasTransform(schema.$defs[schema.$ref]);if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasTransform(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasTransform(schema.anyOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasTransform(schema.allOf[i]))return!0}if(schema.not&&hasTransform(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasTransform(property))return!0;if(property.type==="array"&&property.items&&hasTransform(property.items))return!0}return!1}if(schema.type==="array"&&schema.items&&hasTransform(schema.items))return!0;return TransformSymbol in schema||!!schema.properties&&TransformSymbol in schema.properties},matchFnReturn=/(?:return|=>) \S+\(/g,isAsyncName=(v)=>{return(v?.fn??v).constructor.name==="AsyncFunction"},isAsync=(v)=>{let fn=v?.fn??v;if(fn.constructor.name==="AsyncFunction")return!0;let literal=fn.toString();if(literal.includes("=> response.clone("))return!1;if(literal.includes("await"))return!0;if(literal.includes("async"))return!0;if(literal.includes("=>response.clone("))return!1;return!!literal.match(matchFnReturn)},isGenerator=(v)=>{let fn=v?.fn??v;return fn.constructor.name==="AsyncGeneratorFunction"||fn.constructor.name==="GeneratorFunction"},composeHandler=({app,path,method,hooks,validator,handler,allowMeta=!1,inference,asManifest=!1})=>{let adapter=app["~adapter"].composeHandler,adapterHandler=app["~adapter"].handler,isHandleFn=typeof handler==="function";if(!isHandleFn){if(handler=adapterHandler.mapResponse(handler,{headers:app.setHeaders??{}}),hooks.parse?.length&&hooks.transform?.length&&hooks.beforeHandle?.length&&hooks.afterHandle?.length){if(handler instanceof Response)return Function("a","return function(){return a.clone()}")(handler);return Function("a","return function(){return a}")(handler)}}let handle=isHandleFn?"handler(c)":"handler",hasAfterResponse=!!hooks.afterResponse?.length,hasTrace=!!hooks.trace?.length,fnLiteral="";if(inference=sucrose(Object.assign({},hooks,{handler}),inference),adapter.declare){let literal=adapter.declare(inference);if(literal)fnLiteral+=literal}if(inference.server)fnLiteral+=`Object.defineProperty(c,'server',{get:function(){return getServer()}})
|
|
46
|
+
`,code+=`break
|
|
47
|
+
`}return code+"}"}}),KindSymbol=Symbol.for("TypeBox.Kind");var hasProperty=(expectedProperty,_schema)=>{if(!_schema)return;let schema=_schema.schema??_schema;if(schema[TypeBoxSymbol.kind]==="Import")return _schema.References().some((schema2)=>hasProperty(expectedProperty,schema2));if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(expectedProperty in property)return!0;if(property.type==="object"){if(hasProperty(expectedProperty,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasProperty(expectedProperty,property.anyOf[i]))return!0}}return!1}return expectedProperty in schema},TransformSymbol=Symbol.for("TypeBox.Transform");var hasTransform=(schema)=>{if(!schema)return!1;if(schema.$ref&&schema.$defs&&schema.$ref in schema.$defs&&hasTransform(schema.$defs[schema.$ref]))return!0;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasTransform(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasTransform(schema.anyOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasTransform(schema.allOf[i]))return!0}if(schema.not&&hasTransform(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasTransform(property))return!0;if(property.type==="array"&&property.items&&hasTransform(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasTransform(schema.items))return!0;return TransformSymbol in schema},matchFnReturn=/(?:return|=>) \S+\(/g,isAsyncName=(v)=>{return(v?.fn??v).constructor.name==="AsyncFunction"},isAsync=(v)=>{let fn=v?.fn??v;if(fn.constructor.name==="AsyncFunction")return!0;let literal=fn.toString();if(literal.includes("=> response.clone("))return!1;if(literal.includes("await"))return!0;if(literal.includes("async"))return!0;if(literal.includes("=>response.clone("))return!1;return!!literal.match(matchFnReturn)},isGenerator=(v)=>{let fn=v?.fn??v;return fn.constructor.name==="AsyncGeneratorFunction"||fn.constructor.name==="GeneratorFunction"},composeHandler=({app,path,method,hooks,validator,handler,allowMeta=!1,inference,asManifest=!1})=>{let adapter=app["~adapter"].composeHandler,adapterHandler=app["~adapter"].handler,isHandleFn=typeof handler==="function";if(!isHandleFn){if(handler=adapterHandler.mapResponse(handler,{headers:app.setHeaders??{}}),hooks.parse?.length&&hooks.transform?.length&&hooks.beforeHandle?.length&&hooks.afterHandle?.length){if(handler instanceof Response)return Function("a","return function(){return a.clone()}")(handler);return Function("a","return function(){return a}")(handler)}}let handle=isHandleFn?"handler(c)":"handler",hasAfterResponse=!!hooks.afterResponse?.length,hasTrace=!!hooks.trace?.length,fnLiteral="";if(inference=sucrose(Object.assign({},hooks,{handler}),inference),adapter.declare){let literal=adapter.declare(inference);if(literal)fnLiteral+=literal}if(inference.server)fnLiteral+=`Object.defineProperty(c,'server',{get:function(){return getServer()}})
|
|
48
48
|
`;validator.createBody?.(),validator.createQuery?.(),validator.createHeaders?.(),validator.createParams?.(),validator.createCookie?.(),validator.createResponse?.();let hasValidation=validator.body||validator.headers||validator.params||validator.query||validator.cookie||validator.response,hasQuery=inference.query||!!validator.query,requestNoBody=hooks.parse?.length===1&&hooks.parse[0].fn==="none",hasBody=method!=="$INTERNALWS"&&method!=="GET"&&method!=="HEAD"&&(inference.body||!!validator.body||!!hooks.parse?.length)&&!requestNoBody;if(hasBody)fnLiteral+=`let isParsing=false
|
|
49
49
|
`;let defaultHeaders=app.setHeaders,hasDefaultHeaders=defaultHeaders&&!!Object.keys(defaultHeaders).length,hasHeaders=inference.headers||validator.headers||adapter.preferWebstandardHeaders!==!0&&inference.body,hasCookie=inference.cookie||!!validator.cookie,cookieValidator=hasCookie?getCookieValidator({modules:app.definitions.typebox,validator:validator.cookie,defaultConfig:app.config.cookie,dynamic:!!app.config.aot,config:validator.cookie?.config??{},models:app.definitions.type}):void 0,cookieMeta=cookieValidator?.config,encodeCookie="";if(cookieMeta?.sign){if(!cookieMeta.secrets)throw new Error(`t.Cookie required secret which is not set in (${method}) ${path}.`);let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(encodeCookie+=`const _setCookie = c.set.cookie
|
|
50
50
|
if(_setCookie){`,cookieMeta.sign===!0)encodeCookie+=`for(const [key, cookie] of Object.entries(_setCookie)){c.set.cookie[key].value=await signCookie(cookie.value,'${secret}')}`;else for(let name of cookieMeta.sign)encodeCookie+=`if(_setCookie['${name}']?.value){c.set.cookie['${name}'].value=await signCookie(_setCookie['${name}'].value,'${secret}')}`;encodeCookie+=`}
|
|
@@ -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=
|
|
327
|
+
//# debugId=58E99CAFB75745FB64756E2164756E21
|