elysia 1.3.12 → 1.3.13
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/adapter/bun/handler-native.mjs +4 -2
- package/dist/adapter/bun/index.mjs +4 -2
- package/dist/bun/index.js +5 -5
- package/dist/bun/index.js.map +6 -6
- package/dist/cjs/adapter/bun/handler-native.js +4 -2
- package/dist/cjs/adapter/bun/index.js +4 -2
- package/dist/cjs/compose.js +7 -2
- package/dist/cjs/index.js +11 -2
- package/dist/cjs/schema.d.ts +2 -1
- package/dist/cjs/schema.js +6 -2
- package/dist/compose.mjs +7 -2
- package/dist/index.mjs +11 -2
- package/dist/schema.d.ts +2 -1
- package/dist/schema.mjs +6 -2
- package/package.json +2 -2
|
@@ -2947,9 +2947,11 @@ var hasProperty = (expectedProperty, _schema) => {
|
|
|
2947
2947
|
} catch {
|
|
2948
2948
|
console.warn(
|
|
2949
2949
|
"Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"
|
|
2950
|
-
), console.
|
|
2950
|
+
), console.dir(schema, {
|
|
2951
|
+
depth: null
|
|
2952
|
+
}), compiled.Clean = createCleaner(schema);
|
|
2951
2953
|
}
|
|
2952
|
-
else compiled.Clean = createCleaner(schema);
|
|
2954
|
+
else normalize === "typebox" && (compiled.Clean = createCleaner(schema));
|
|
2953
2955
|
return compiled.parse = (v) => {
|
|
2954
2956
|
try {
|
|
2955
2957
|
return compiled.Decode(compiled.Clean?.(v) ?? v);
|
|
@@ -2947,9 +2947,11 @@ var hasProperty = (expectedProperty, _schema) => {
|
|
|
2947
2947
|
} catch {
|
|
2948
2948
|
console.warn(
|
|
2949
2949
|
"Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"
|
|
2950
|
-
), console.
|
|
2950
|
+
), console.dir(schema, {
|
|
2951
|
+
depth: null
|
|
2952
|
+
}), compiled.Clean = createCleaner(schema);
|
|
2951
2953
|
}
|
|
2952
|
-
else compiled.Clean = createCleaner(schema);
|
|
2954
|
+
else normalize === "typebox" && (compiled.Clean = createCleaner(schema));
|
|
2953
2955
|
return compiled.parse = (v) => {
|
|
2954
2956
|
try {
|
|
2955
2957
|
return compiled.Decode(compiled.Clean?.(v) ?? v);
|
package/dist/bun/index.js
CHANGED
|
@@ -33,8 +33,8 @@ const error404=new Response(error404Message,{status:404})
|
|
|
33
33
|
`,code:findDynamicRoute}}},composeError:{mapResponseContext:"",validationError:"return new Response(error.message,{headers:Object.assign({'content-type':'application/json'},set.headers),status:set.status})",unknownError:"return new Response(error.message,{headers:set.headers,status:error.status??set.status??500})"},listen(){return()=>{throw new Error("WebStandard does not support listen, you might want to export default Elysia.fetch instead")}}};var mapResponse2=(response,set2,request)=>{if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return new Response(response,set2);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleFile(response.value);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapResponse2(response.response,set2,request);case"ReadableStream":if(!set2.headers["content-type"]?.startsWith("text/event-stream"))set2.headers["content-type"]="text/event-stream; charset=utf-8";return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,set2);case void 0:if(!response)return new Response("",set2);return new Response(JSON.stringify(response),set2);case"Response":return handleResponse2(response,set2,request);case"Error":return errorToResponse2(response,set2);case"Promise":return response.then((x)=>mapResponse2(x,set2,request));case"Function":return mapResponse2(response(),set2,request);case"Number":case"Boolean":return new Response(response.toString(),set2);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response,set2);default:if(response instanceof Response)return handleResponse2(response,set2,request);if(response instanceof Promise)return response.then((x)=>mapResponse2(x,set2));if(response instanceof Error)return errorToResponse2(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapResponse2(response.response,set2,request);if(typeof response?.next==="function")return handleStream2(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse2(x,set2));if(typeof response?.toResponse==="function")return mapResponse2(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response,set2)}if(response instanceof Response&&!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream2(streamResponse(response),responseToSetHeaders(response,set2),request);if(typeof response?.next==="function"||response instanceof ReadableStream)return handleStream2(response,set2,request);return mapCompactResponse2(response,request)},mapEarlyResponse2=(response,set2,request)=>{if(response===void 0||response===null)return;if(isNotEmpty(set2.headers)||set2.status!==200||set2.cookie)switch(handleSet(set2),response?.constructor?.name){case"String":return new Response(response,set2);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleFile(response.value);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse2(response.response,set2,request);case"ReadableStream":if(!set2.headers["content-type"]?.startsWith("text/event-stream"))set2.headers["content-type"]="text/event-stream; charset=utf-8";return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,set2);case void 0:if(!response)return;return new Response(JSON.stringify(response),set2);case"Response":return handleResponse2(response,set2,request);case"Promise":return response.then((x)=>mapEarlyResponse2(x,set2));case"Error":return errorToResponse2(response,set2);case"Function":return mapEarlyResponse2(response(),set2);case"Number":case"Boolean":return new Response(response.toString(),set2);case"FormData":return new Response(response);case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);default:if(response instanceof Response)return handleResponse2(response,set2,request);if(response instanceof Promise)return response.then((x)=>mapEarlyResponse2(x,set2));if(response instanceof Error)return errorToResponse2(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapEarlyResponse2(response.response,set2,request);if(typeof response?.next==="function")return handleStream2(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse2(x,set2));if(typeof response?.toResponse==="function")return mapEarlyResponse2(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response,set2)}else switch(response?.constructor?.name){case"String":return new Response(response);case"Array":case"Object":return set2.headers["content-type"]="application/json",new Response(JSON.stringify(response),set2);case"ElysiaFile":return handleFile(response.value);case"File":return handleFile(response,set2);case"Blob":return handleFile(response,set2);case"ElysiaCustomStatusResponse":return set2.status=response.code,mapEarlyResponse2(response.response,set2,request);case"ReadableStream":return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(!response.headers.has("content-length")&&response.headers.get("transfer-encoding")==="chunked")return handleStream2(streamResponse(response),responseToSetHeaders(response),request);return response;case"Promise":return response.then((x)=>{let r=mapEarlyResponse2(x,set2);if(r!==void 0)return r});case"Error":return errorToResponse2(response,set2);case"Function":return mapCompactResponse2(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"Cookie":if(response instanceof Cookie)return new Response(response.value,set2);return new Response(response?.toString(),set2);case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapEarlyResponse2(x,set2));if(response instanceof Error)return errorToResponse2(response,set2);if(response instanceof ElysiaCustomStatusResponse)return set2.status=response.code,mapEarlyResponse2(response.response,set2,request);if(typeof response?.next==="function")return handleStream2(response,set2,request);if(typeof response?.then==="function")return response.then((x)=>mapEarlyResponse2(x,set2));if(typeof response?.toResponse==="function")return mapEarlyResponse2(response.toResponse(),set2);if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91){if(!set2.headers["Content-Type"])set2.headers["Content-Type"]="application/json";return new Response(JSON.stringify(response),set2)}}return new Response(response)}},mapCompactResponse2=(response,request)=>{switch(response?.constructor?.name){case"String":return new Response(response);case"Object":case"Array":return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}});case"ElysiaFile":return handleFile(response.value);case"File":return handleFile(response);case"Blob":return handleFile(response);case"ElysiaCustomStatusResponse":return mapResponse2(response.response,{status:response.code,headers:{}});case"ReadableStream":return request?.signal?.addEventListener("abort",{handleEvent(){if(request?.signal&&!request?.signal?.aborted)response.cancel()}},{once:!0}),new Response(response,{headers:{"Content-Type":"text/event-stream; charset=utf-8"}});case void 0:if(!response)return new Response("");return new Response(JSON.stringify(response),{headers:{"content-type":"application/json"}});case"Response":if(response.headers.get("transfer-encoding")==="chunked")return handleStream2(streamResponse(response),responseToSetHeaders(response),request);return response;case"Error":return errorToResponse2(response);case"Promise":return response.then((x)=>mapCompactResponse2(x,request));case"Function":return mapCompactResponse2(response(),request);case"Number":case"Boolean":return new Response(response.toString());case"FormData":return new Response(response);default:if(response instanceof Response)return response;if(response instanceof Promise)return response.then((x)=>mapCompactResponse2(x,request));if(response instanceof Error)return errorToResponse2(response);if(response instanceof ElysiaCustomStatusResponse)return mapResponse2(response.response,{status:response.code,headers:{}});if(typeof response?.next==="function")return handleStream2(response,void 0,request);if(typeof response?.then==="function")return response.then((x)=>mapResponse2(x,set));if(typeof response?.toResponse==="function")return mapCompactResponse2(response.toResponse());if("charCodeAt"in response){let code=response.charCodeAt(0);if(code===123||code===91)return new Response(JSON.stringify(response),{headers:{"Content-Type":"application/json"}})}return new Response(response)}},errorToResponse2=(error2,set2)=>new Response(JSON.stringify({name:error2?.name,message:error2?.message,cause:error2?.cause}),{status:set2?.status!==200?set2?.status??500:500,headers:set2?.headers}),createStaticHandler2=(handle,hooks,setHeaders={})=>{if(typeof handle==="function")return;let response=mapResponse2(handle,{headers:setHeaders});if(!hooks.parse?.length&&!hooks.transform?.length&&!hooks.beforeHandle?.length&&!hooks.afterHandle?.length)return response.clone.bind(response)},handleResponse2=createResponseHandler({mapResponse:mapResponse2,mapCompactResponse:mapCompactResponse2}),handleStream2=createStreamHandler({mapResponse:mapResponse2,mapCompactResponse:mapCompactResponse2});var import_fast_decode_uri_component3=__toESM(require_fast_decode_uri_component(),1);import{Value as Value4}from"@sinclair/typebox/value";import{Kind as Kind5,OptionalKind as OptionalKind2,TypeBoxError}from"@sinclair/typebox";var import_fast_decode_uri_component2=__toESM(require_fast_decode_uri_component(),1);function parseQueryFromURL(input,startIndex=0){let result=Object.create(null),KEY_PLUS_FLAG=1,KEY_DECODE_FLAG=2,VALUE_PLUS_FLAG=4,VALUE_DECODE_FLAG=8,flags=0,startingIndex=startIndex-1,equalityIndex=startingIndex,inputLength=input.length;for(let i=startIndex;i<inputLength;i++)switch(input.charCodeAt(i)){case 38:processKeyValuePair(i),startingIndex=i,equalityIndex=i,flags=0;break;case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else flags|=8;break;case 43:if(equalityIndex>startingIndex)flags|=4;else flags|=1;break;case 37:if(equalityIndex>startingIndex)flags|=8;else flags|=2;break}return processKeyValuePair(inputLength),result;function processKeyValuePair(endIndex){let hasBothKeyValuePair=equalityIndex>startingIndex,keyEndIndex=hasBothKeyValuePair?equalityIndex:endIndex;if(keyEndIndex<=startingIndex+1)return;let keySlice=input.slice(startingIndex+1,keyEndIndex);if(flags&1)keySlice=keySlice.replace(/\+/g," ");if(flags&2)keySlice=import_fast_decode_uri_component2.default(keySlice)||keySlice;if(result[keySlice]!==void 0)return;let finalValue="";if(hasBothKeyValuePair){if(finalValue=input.slice(equalityIndex+1,endIndex),flags&4)finalValue=finalValue.replace(/\+/g," ");if(flags&8)finalValue=import_fast_decode_uri_component2.default(finalValue)||finalValue}result[keySlice]=finalValue}}function parseQuery(input){let result=Object.create(null),flags=0,KEY_HAS_PLUS=1,KEY_NEEDS_DECODE=2,VALUE_HAS_PLUS=4,VALUE_NEEDS_DECODE=8,inputLength=input.length,startingIndex=-1,equalityIndex=-1;for(let i=0;i<inputLength;i++)switch(input.charCodeAt(i)){case 38:processKeyValuePair(input,i),startingIndex=i,equalityIndex=i,flags=0;break;case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else flags|=VALUE_NEEDS_DECODE;break;case 43:if(equalityIndex>startingIndex)flags|=VALUE_HAS_PLUS;else flags|=KEY_HAS_PLUS;break;case 37:if(equalityIndex>startingIndex)flags|=VALUE_NEEDS_DECODE;else flags|=KEY_NEEDS_DECODE;break}if(startingIndex<inputLength)processKeyValuePair(input,inputLength);return result;function processKeyValuePair(input2,endIndex){let hasBothKeyValuePair=equalityIndex>startingIndex,effectiveEqualityIndex=hasBothKeyValuePair?equalityIndex:endIndex,keySlice=input2.slice(startingIndex+1,effectiveEqualityIndex);if(!hasBothKeyValuePair&&keySlice.length===0)return;let finalKey=keySlice;if(flags&KEY_HAS_PLUS)finalKey=finalKey.replace(/\+/g," ");if(flags&KEY_NEEDS_DECODE)finalKey=import_fast_decode_uri_component2.default(finalKey)||finalKey;let finalValue="";if(hasBothKeyValuePair){let valueSlice=input2.slice(equalityIndex+1,endIndex);if(flags&VALUE_HAS_PLUS)valueSlice=valueSlice.replace(/\+/g," ");if(flags&VALUE_NEEDS_DECODE)valueSlice=import_fast_decode_uri_component2.default(valueSlice)||valueSlice;finalValue=valueSlice}let currentValue=result[finalKey];if(currentValue===void 0)result[finalKey]=finalValue;else if(Array.isArray(currentValue))currentValue.push(finalValue);else result[finalKey]=[currentValue,finalValue]}}var ELYSIA_TRACE=Symbol("ElysiaTrace"),createProcess=()=>{let{promise,resolve}=Promise.withResolvers(),{promise:end,resolve:resolveEnd}=Promise.withResolvers(),{promise:error2,resolve:resolveError}=Promise.withResolvers(),callbacks=[],callbacksEnd=[];return[(callback)=>{if(callback)callbacks.push(callback);return promise},(process2)=>{let processes=[],resolvers=[],groupError=null;for(let i=0;i<(process2.total??0);i++){let{promise:promise2,resolve:resolve2}=Promise.withResolvers(),{promise:end2,resolve:resolveEnd2}=Promise.withResolvers(),{promise:error3,resolve:resolveError2}=Promise.withResolvers(),callbacks2=[],callbacksEnd2=[];processes.push((callback)=>{if(callback)callbacks2.push(callback);return promise2}),resolvers.push((process3)=>{let result2={...process3,end:end2,error:error3,index:i,onStop(callback){if(callback)callbacksEnd2.push(callback);return end2}};resolve2(result2);for(let i2=0;i2<callbacks2.length;i2++)callbacks2[i2](result2);return(error4=null)=>{let end3=performance.now();if(error4)groupError=error4;let detail={end:end3,error:error4,get elapsed(){return end3-process3.begin}};for(let i2=0;i2<callbacksEnd2.length;i2++)callbacksEnd2[i2](detail);resolveEnd2(end3),resolveError2(error4)}})}let result={...process2,end,error:error2,onEvent(callback){for(let i=0;i<processes.length;i++)processes[i](callback)},onStop(callback){if(callback)callbacksEnd.push(callback);return end}};resolve(result);for(let i=0;i<callbacks.length;i++)callbacks[i](result);return{resolveChild:resolvers,resolve(error3=null){let end2=performance.now();if(!error3&&groupError)error3=groupError;let detail={end:end2,error:error3,get elapsed(){return end2-process2.begin}};for(let i=0;i<callbacksEnd.length;i++)callbacksEnd[i](detail);resolveEnd(end2),resolveError(error3)}}}]},createTracer=(traceListener)=>{return(context)=>{let[onRequest,resolveRequest]=createProcess(),[onParse,resolveParse]=createProcess(),[onTransform,resolveTransform]=createProcess(),[onBeforeHandle,resolveBeforeHandle]=createProcess(),[onHandle,resolveHandle]=createProcess(),[onAfterHandle,resolveAfterHandle]=createProcess(),[onError,resolveError]=createProcess(),[onMapResponse,resolveMapResponse]=createProcess(),[onAfterResponse,resolveAfterResponse]=createProcess();return traceListener({id:context[ELYSIA_REQUEST_ID],context,set:context.set,onRequest,onParse,onTransform,onBeforeHandle,onHandle,onAfterHandle,onMapResponse,onAfterResponse,onError,time:Date.now(),store:context.store}),{request:resolveRequest,parse:resolveParse,transform:resolveTransform,beforeHandle:resolveBeforeHandle,handle:resolveHandle,afterHandle:resolveAfterHandle,error:resolveError,mapResponse:resolveMapResponse,afterResponse:resolveAfterResponse}}};import{Kind as Kind4,OptionalKind,TransformKind}from"@sinclair/typebox";import{Value as Value3}from"@sinclair/typebox/value";import{TypeCompiler as TypeCompiler4}from"@sinclair/typebox/compiler";import{TypeCompiler as TypeCompiler3}from"@sinclair/typebox/compiler";var Kind3=Symbol.for("TypeBox.Kind"),Hint=Symbol.for("TypeBox.Hint"),isSpecialProperty=(name)=>/(\ |-|\t|\n)/.test(name)||!isNaN(+name[0]),joinProperty=(v1,v2,isOptional=!1)=>{if(typeof v2==="number")return`${v1}[${v2}]`;if(isSpecialProperty(v2))return`${v1}${isOptional?"?.":""}["${v2}"]`;return`${v1}${isOptional?"?":""}.${v2}`},encodeProperty=(v)=>isSpecialProperty(v)?`"${v}"`:v,sanitize=(key,sanitize2=0,schema)=>{if(schema.type!=="string"||schema.const||schema.trusted)return key;let hof="";for(let i=sanitize2-1;i>=0;i--)hof+=`d.h${i}(`;return hof+key+")".repeat(sanitize2)},mergeObjectIntersection=(schema)=>{if(!schema.allOf||Kind3 in schema&&(schema[Kind3]!=="Intersect"||schema.type!=="object"))return schema;let{allOf,...newSchema}=schema;if(newSchema.properties={},Kind3 in newSchema)newSchema[Kind3]="Object";for(let type of allOf){if(type.type!=="object")continue;let{properties,required,type:_2,[Kind3]:__,...rest}=type;if(required)newSchema.required=newSchema.required?newSchema.required.concat(required):required;Object.assign(newSchema,rest);for(let property in type.properties)newSchema.properties[property]=mergeObjectIntersection(type.properties[property])}return newSchema},handleRecord=(schema,property,instruction)=>{let child=schema.patternProperties["^(.*)$"]??schema.patternProperties[Object.keys(schema.patternProperties)[0]];if(!child)return property;let i=instruction.array;instruction.array++;let v=`(()=>{const ar${i}s=Object.keys(${property}),ar${i}v={};for(let i=0;i<ar${i}s.length;i++){const ar${i}p=${property}[ar${i}s[i]];ar${i}v[ar${i}s[i]]=${mirror(child,`ar${i}p`,instruction)}`,optionals=instruction.optionalsInArray[i+1];if(optionals)for(let oi=0;oi<optionals.length;oi++){let target=`ar${i}v[ar${i}s[i]].${optionals[oi]}`;v+=`;if(${target}===undefined)delete ${target}`}return v+=`}return ar${i}v})()`,v},handleTuple=(schema,property,instruction)=>{let i=instruction.array;instruction.array++;let isRoot=property==="v"&&!instruction.unions.length,v="";if(!isRoot)v="(()=>{";v+=`const ar${i}v=[`;for(let i2=0;i2<schema.length;i2++){if(i2!==0)v+=",";v+=mirror(schema[i2],joinProperty(property,i2,instruction.parentIsOptional),instruction)}if(v+="];",!isRoot)v+=`return ar${i}v})()`;return v};function deepClone(source,weak=new WeakMap){if(source===null||typeof source!=="object"||typeof source==="function")return source;if(weak.has(source))return weak.get(source);if(Array.isArray(source)){let copy=new Array(source.length);weak.set(source,copy);for(let i=0;i<source.length;i++)copy[i]=deepClone(source[i],weak);return copy}if(typeof source==="object"){let keys=Object.keys(source).concat(Object.getOwnPropertySymbols(source)),cloned={};for(let key of keys)cloned[key]=deepClone(source[key],weak);return cloned}return source}var handleUnion=(schemas,property,instruction)=>{if(instruction.TypeCompiler===void 0){if(!instruction.typeCompilerWanred)console.warn(new Error("[exact-mirror] TypeBox's TypeCompiler is required to use Union")),instruction.typeCompilerWanred=!0;return property}instruction.unionKeys[property]=1;let ui=instruction.unions.length,typeChecks=instruction.unions[ui]=[],v=`(()=>{
|
|
34
34
|
`,unwrapRef=(type)=>{if(!(Kind3 in type)||!type.$ref)return type;if(type[Kind3]==="This")return deepClone(instruction.definitions[type.$ref]);else if(type[Kind3]==="Ref")if(!instruction.modules)console.warn(new Error("[exact-mirror] modules is required when using nested cyclic reference"));else return instruction.modules.Import(type.$ref);return type};for(let i=0;i<schemas.length;i++){let type=unwrapRef(schemas[i]);if(Array.isArray(type.anyOf))for(let i2=0;i2<type.anyOf.length;i2++)type.anyOf[i2]=unwrapRef(type.anyOf[i2]);else if(type.items)if(Array.isArray(type.items))for(let i2=0;i2<type.items.length;i2++)type.items[i2]=unwrapRef(type.items[i2]);else type.items=unwrapRef(type.items);typeChecks.push(TypeCompiler3.Compile(type)),v+=`if(d.unions[${ui}][${i}].Check(${property})){return ${mirror(type,property,{...instruction,recursion:instruction.recursion+1,parentIsOptional:!0})}}
|
|
35
35
|
`}return v+=`return ${instruction.removeUnknownUnionType?"undefined":property}})()`,v},mirror=(schema,property,instruction)=>{if(!schema)return"";let isRoot=property==="v"&&!instruction.unions.length;if(Kind3 in schema&&schema[Kind3]==="Import"&&schema.$ref in schema.$defs)return mirror(schema.$defs[schema.$ref],property,{...instruction,definitions:Object.assign(instruction.definitions,schema.$defs)});if(isRoot&&schema.type!=="object"&&schema.type!=="array"&&!schema.anyOf)return`return ${sanitize("v",instruction.sanitize?.length,schema)}`;if(instruction.recursion>=instruction.recursionLimit)return property;let v="";if(schema.$id&&Hint in schema)instruction.definitions[schema.$id]=schema;switch(schema.type){case"object":if(schema[Kind3]==="Record"){v=handleRecord(schema,property,instruction);break}if(schema=mergeObjectIntersection(schema),v+="{",schema.additionalProperties)v+=`...${property},`;let keys=Object.keys(schema.properties);for(let i2=0;i2<keys.length;i2++){let key=keys[i2],isOptional=!schema.required||schema.required&&!schema.required.includes(key)||Array.isArray(schema.properties[key].anyOf),name=joinProperty(property,key,instruction.parentIsOptional);if(isOptional){let index=instruction.array;if(property.startsWith("ar")){let refName=name.slice(name.indexOf(".")+1),array=instruction.optionalsInArray;if(array[index])array[index].push(refName);else array[index]=[refName]}else instruction.optionals.push(name)}let child=schema.properties[key];if(i2!==0)v+=",";v+=`${encodeProperty(key)}:${isOptional?`${name}===undefined?undefined:`:""}${mirror(child,name,{...instruction,recursion:instruction.recursion+1,parentIsOptional:isOptional})}`}v+="}";break;case"array":if(schema.items.type!=="object"&&schema.items.type!=="array")if(Array.isArray(schema.items)){v=handleTuple(schema.items,property,instruction);break}else if(isRoot)return"return v";else if(Kind3 in schema.items&&schema.items.$ref&&(schema.items[Kind3]==="Ref"||schema.items[Kind3]==="This"))v=mirror(deepClone(instruction.definitions[schema.items.$ref]),property,{...instruction,parentIsOptional:!0,recursion:instruction.recursion+1});else{v=property;break}let i=instruction.array;instruction.array++;let reference=property;if(isRoot)v=`const ar${i}v=new Array(${property}.length);`;else reference=`ar${i}s`,v=`((${reference})=>{const ar${i}v=new Array(${reference}.length);`;v+=`for(let i=0;i<${reference}.length;i++){const ar${i}p=${reference}[i];ar${i}v[i]=${mirror(schema.items,`ar${i}p`,instruction)}`;let optionals=instruction.optionalsInArray[i+1];if(optionals)for(let oi=0;oi<optionals.length;oi++){let target=`ar${i}v[i].${optionals[oi]}`;v+=`;if(${target}===undefined)delete ${target}`}if(v+="}",!isRoot)v+=`return ar${i}v})(${property})`;break;default:if(schema.$ref&&schema.$ref in instruction.definitions)return mirror(instruction.definitions[schema.$ref],property,instruction);if(Array.isArray(schema.anyOf)){v=handleUnion(schema.anyOf,property,instruction);break}v=sanitize(property,instruction.sanitize?.length,schema);break}if(!isRoot)return v;if(schema.type==="array")v=`${v}const x=ar0v;`;else v=`const x=${v}
|
|
36
|
-
`;for(let i=0;i<instruction.optionals.length;i++){let key=instruction.optionals[i],prop=key.slice(1);if(v+=`if(${key}===undefined`,instruction.unionKeys[key])v+=`||x${prop}===undefined`;let shouldQuestion=prop.charCodeAt(0)!==63&&schema.type!=="array";v+=`)delete x${shouldQuestion?"?":""}${prop}
|
|
37
|
-
`}return`${v}return x`},createMirror=(schema,{TypeCompiler:TypeCompiler22,modules,definitions,sanitize:sanitize2,recursionLimit=8,removeUnknownUnionType=!1}={})=>{let unions=[];if(typeof sanitize2==="function")sanitize2=[sanitize2];let f=mirror(schema,"v",{optionals:[],optionalsInArray:[],array:0,parentIsOptional:!1,unions,unionKeys:{},TypeCompiler:TypeCompiler22,modules,definitions:definitions??modules?.$defs??{},sanitize:sanitize2,recursion:0,recursionLimit,removeUnknownUnionType});if(!unions.length&&!sanitize2?.length)return Function("v",f);let hof;if(sanitize2?.length){hof={};for(let i=0;i<sanitize2.length;i++)hof[`h${i}`]=sanitize2[i]}return Function("d",`return function mirror(v){${f}}`)({unions,...hof})};var isOptional=(schema)=>{if(!schema)return!1;if(schema?.[Kind4]==="Import"&&schema.References)return schema.References().some(isOptional);if(schema.schema)schema=schema.schema;return!!schema&&OptionalKind in schema},hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some(hasAdditionalProperties);if(schema.anyOf)return schema.anyOf.some(hasAdditionalProperties);if(schema.someOf)return schema.someOf.some(hasAdditionalProperties);if(schema.allOf)return schema.allOf.some(hasAdditionalProperties);if(schema.not)return schema.not.some(hasAdditionalProperties);if(schema.type==="object"){let properties=schema.properties;if("additionalProperties"in schema)return schema.additionalProperties;if("patternProperties"in schema)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasAdditionalProperties(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasAdditionalProperties(property.anyOf[i]))return!0}return property.additionalProperties}return!1}if(schema.type==="array"&&schema.items&&!Array.isArray(schema.items))return hasAdditionalProperties(schema.items);return!1},hasType=(type,schema)=>{if(!schema)return!1;if(Kind4 in schema&&schema[Kind4]===type)return!0;if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasType(type,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasType(type,property.anyOf[i]))return!0}if(Kind4 in property&&property[Kind4]===type)return!0}return!1}return!!schema.properties&&Kind4 in schema.properties&&schema.properties[Kind4]===type},hasProperty=(expectedProperty,_schema)=>{if(!_schema)return;let schema=_schema.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some((schema2)=>hasProperty(expectedProperty,schema2));if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(expectedProperty in property)return!0;if(property.type==="object"){if(hasProperty(expectedProperty,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasProperty(expectedProperty,property.anyOf[i]))return!0}}return!1}return expectedProperty in schema},hasRef=(schema)=>{if(!schema)return!1;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasRef(schema.anyOf[i]))return!0}if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasRef(schema.allOf[i]))return!0}if(schema.not&&hasRef(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasRef(property))return!0;if(property.type==="array"&&property.items&&hasRef(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasRef(schema.items))return!0;return schema[Kind4]==="Ref"&&"$ref"in schema},hasTransform=(schema)=>{if(!schema)return!1;if(schema.$ref&&schema.$defs&&schema.$ref in schema.$defs&&hasTransform(schema.$defs[schema.$ref]))return!0;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasTransform(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasTransform(schema.anyOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasTransform(schema.allOf[i]))return!0}if(schema.not&&hasTransform(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasTransform(property))return!0;if(property.type==="array"&&property.items&&hasTransform(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasTransform(schema.items))return!0;return TransformKind in schema},replaceSchemaType=(schema,options,_config={})=>{let config=_config;if(config.root=!0,!Array.isArray(options))return options.original=schema,_replaceSchemaType(schema,options,config);for(let option of options)option.original=schema,schema=_replaceSchemaType(schema,option,config);return schema},_replaceSchemaType=(schema,options,config)=>{if(!schema)return schema;let root=config.root;if(options.onlyFirst&&schema.type===options.onlyFirst)return options.to(schema)??schema;if(options.untilObjectFound&&!root&&schema.type==="object")return schema;let fromSymbol=options.from[Kind4];if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)schema.oneOf[i]=_replaceSchemaType(schema.oneOf[i],options,config);return schema}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)schema.anyOf[i]=_replaceSchemaType(schema.anyOf[i],options,config);return schema}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)schema.allOf[i]=_replaceSchemaType(schema.allOf[i],options,config);return schema}if(schema.not)return _replaceSchemaType(schema.not,options,config);let isRoot=root&&!!options.excludeRoot;if(schema[Kind4]===fromSymbol){let{anyOf,oneOf,allOf,not,properties:properties2,items,...rest}=schema,to=options.to(rest);if(!to)return schema;let transform,composeProperties=(schema2)=>{let v=_composeProperties(schema2);if(v.$id)delete v.$id;return v},_composeProperties=(v)=>{if(properties2&&v.type==="object"){let newProperties={};for(let[key,value2]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value2,options,{...config,root:!1});return{...rest,...v,properties:newProperties}}if(items&&v.type==="array")return{...rest,...v,items:_replaceSchemaType(items,options,{...config,root:!1})};let value={...rest,...v};if(delete value.required,properties2&&v.type==="string"&&v.format==="ObjectString"&&v.default==="{}")transform=t.ObjectString(properties2,rest),value.default=JSON.stringify(Value3.Create(t.Object(properties2))),value.properties=properties2;if(items&&v.type==="string"&&v.format==="ArrayString"&&v.default==="[]")transform=t.ArrayString(items,rest),value.default=JSON.stringify(Value3.Create(t.Array(items))),value.items=items;return value};if(isRoot){if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,properties:newProperties}}else if(items?.map)return{...rest,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return rest}if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]=composeProperties(to.anyOf[i]);else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]=composeProperties(to.oneOf[i]);else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]=composeProperties(to.allOf[i]);else if(to.not)to.not=composeProperties(to.not);if(transform)to[TransformKind]=transform[TransformKind];if(to.anyOf||to.oneOf||to.allOf||to.not)return to;if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,...to,properties:newProperties}}else if(items?.map)return{...rest,...to,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return{...rest,...to}}let properties=schema?.properties;if(properties&&root&&options.rootOnly!==!0)for(let[key,value]of Object.entries(properties))switch(value[Kind4]){case fromSymbol:let{anyOf,oneOf,allOf,not,type,...rest}=value,to=options.to(rest);if(!to)return schema;if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]={...rest,...to.anyOf[i]};else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]={...rest,...to.oneOf[i]};else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]={...rest,...to.allOf[i]};else if(to.not)to.not={...rest,...to.not};properties[key]={...rest,..._replaceSchemaType(rest,options,{...config,root:!1})};break;case"Object":case"Union":properties[key]=_replaceSchemaType(value,options,{...config,root:!1});break;default:if(Array.isArray(value.items))for(let i=0;i<value.items.length;i++)value.items[i]=_replaceSchemaType(value.items[i],options,{...config,root:!1});else if(value.anyOf||value.oneOf||value.allOf||value.not)properties[key]=_replaceSchemaType(value,options,{...config,root:!1});else if(value.type==="array")value.items=_replaceSchemaType(value.items,options,{...config,root:!1});break}if(schema.type==="array"&&schema.items)if(Array.isArray(schema.items))schema.items=schema.items.map((item)=>_replaceSchemaType(item,options,{...config,root:!1}));else schema.items=_replaceSchemaType(schema.items,options,{...config,root:!1});return schema},createCleaner=(schema)=>(value)=>{if(typeof value==="object")try{return Value3.Clean(schema,value)}catch{}return value},getSchemaValidator=(s,{models={},dynamic=!1,modules,normalize=!1,additionalProperties=!1,coerce=!1,additionalCoerce=[],validators,sanitize:sanitize2}={})=>{if(validators=validators?.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let doesHaveRef=void 0,replaceSchema=(schema2)=>{if(coerce)return replaceSchemaType(schema2,[{from:t.Number(),to:(options)=>t.Numeric(options),untilObjectFound:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),untilObjectFound:!0},...Array.isArray(additionalCoerce)?additionalCoerce:[additionalCoerce]]);return replaceSchemaType(schema2,additionalCoerce)},mapSchema=(s2)=>{let schema2;if(!s2)return;if(typeof s2!=="string")schema2=s2;else{let isArray=s2.endsWith("[]"),key=isArray?s2.substring(0,s2.length-2):s2;if(schema2=modules?.Import(key)??models[key],isArray)schema2=t.Array(schema2)}if(!schema2)return;let _doesHaveRef;if(schema2[Kind4]!=="Import"&&(_doesHaveRef=hasRef(schema2))){let id=randomId();if(doesHaveRef===void 0)doesHaveRef=_doesHaveRef;schema2=t.Module({...modules?.$defs,[id]:schema2}).Import(id)}if(schema2[Kind4]==="Import"){let newDefs={};for(let[key2,value]of Object.entries(schema2.$defs))newDefs[key2]=replaceSchema(value);let key=schema2.$ref;schema2=t.Module(newDefs).Import(key)}else if(coerce||additionalCoerce)schema2=replaceSchema(schema2);return schema2},schema=mapSchema(s);if(validators?.length){let hasAdditional=!1,{schema:mergedObjectSchema,notObjects}=mergeObjectSchemas([schema,...validators.map(mapSchema)]);if(notObjects){if(schema=t.Intersect([...mergedObjectSchema?[mergedObjectSchema]:[],...notObjects.map((x)=>{let schema2=mapSchema(x);if(schema2.type==="object"&&"additionalProperties"in schema2){if(!hasAdditional&&schema2.additionalProperties===!1)hasAdditional=!0;delete schema2.additionalProperties}return schema2})]),schema.type==="object"&&hasAdditional)schema.additionalProperties=!1}}else if(schema.type==="object"&&"additionalProperties"in schema===!1)schema.additionalProperties=additionalProperties;else schema=replaceSchemaType(schema,{onlyFirst:"object",from:t.Object({}),to({properties,...options}){if(!properties)return;if("additionalProperties"in schema)return;return t.Object(properties,{...options,additionalProperties:!1})}});if(dynamic){let validator={schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value3.Check(schema,value),Errors:(value)=>Value3.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value3.Decode(schema,value),Encode:(value)=>Value3.Encode(schema,value),get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(schema)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",schema)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(schema)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},"~hasRef":doesHaveRef,get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasTransform(schema)}};if(schema.config){if(validator.config=schema.config,validator?.schema?.config)delete validator.schema.config}if(normalize&&schema.additionalProperties===!1)if(normalize===!0||normalize==="exactMirror")try{validator.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch{console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema),validator.Clean=createCleaner(schema)}else validator.Clean=createCleaner(schema);return validator.parse=(v)=>{try{return validator.Decode(validator.Clean?.(v)??v)}catch(error2){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(validator.Clean?.(v)??v),error:null}}catch(error2){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}let compiled=TypeCompiler4.Compile(schema,Object.values(models));if(schema.config){if(compiled.config=schema.config,compiled?.schema?.config)delete compiled.schema.config}if(normalize===!0||normalize==="exactMirror")try{compiled.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch(error2){console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema),compiled.Clean=createCleaner(schema)}else compiled.Clean=createCleaner(schema);return compiled.parse=(v)=>{try{return compiled.Decode(compiled.Clean?.(v)??v)}catch(error2){throw[...compiled.Errors(v)].map(mapValueError)}},compiled.safeParse=(v)=>{try{return{success:!0,data:compiled.Decode(compiled.Clean?.(v)??v),error:null}}catch(error2){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},Object.assign(compiled,{get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(compiled)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",compiled)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(compiled)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasRef(schema)},"~hasRef":doesHaveRef}),compiled},isUnion=(schema)=>schema[Kind4]==="Union"||!schema.schema&&!!schema.anyOf,mergeObjectSchemas=(schemas)=>{if(schemas.length===0)return{schema:void 0,notObjects:[]};if(schemas.length===1)return schemas[0].type==="object"?{schema:schemas[0],notObjects:[]}:{schema:void 0,notObjects:schemas};let newSchema,notObjects=[],additionalPropertiesIsTrue=!1,additionalPropertiesIsFalse=!1;for(let schema of schemas){if(schema.type!=="object"){notObjects.push(schema);continue}if("additionalProperties"in schema){if(schema.additionalProperties===!0)additionalPropertiesIsTrue=!0;else if(schema.additionalProperties===!1)additionalPropertiesIsFalse=!0}if(!newSchema){newSchema=schema;continue}newSchema={...newSchema,...schema,properties:{...newSchema.properties,...schema.properties},required:[...newSchema?.required??[],...schema.required]}}if(newSchema){if(newSchema.required)newSchema.required=[...new Set(newSchema.required)];if(additionalPropertiesIsFalse)newSchema.additionalProperties=!1;else if(additionalPropertiesIsTrue)newSchema.additionalProperties=!0}return{schema:newSchema,notObjects}},getResponseSchemaValidator=(s,{models={},modules,dynamic=!1,normalize=!1,additionalProperties=!1,validators=[],sanitize:sanitize2})=>{if(validators=validators.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let maybeSchemaOrRecord;if(typeof s!=="string")maybeSchemaOrRecord=s;else{let isArray=s.endsWith("[]"),key=isArray?s.substring(0,s.length-2):s;if(maybeSchemaOrRecord=modules.Import(key)??models[key],isArray)maybeSchemaOrRecord=t.Array(maybeSchemaOrRecord)}if(!maybeSchemaOrRecord)return;if(Kind4 in maybeSchemaOrRecord)return{200:getSchemaValidator(maybeSchemaOrRecord,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[200]),sanitize:sanitize2})};let record={};return Object.keys(maybeSchemaOrRecord).forEach((status2)=>{if(isNaN(+status2))return;let maybeNameOrSchema=maybeSchemaOrRecord[+status2];if(typeof maybeNameOrSchema==="string"){if(maybeNameOrSchema in models){let schema=models[maybeNameOrSchema];record[+status2]=Kind4 in schema?getSchemaValidator(schema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):schema}return}record[+status2]=Kind4 in maybeNameOrSchema?getSchemaValidator(maybeNameOrSchema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):maybeNameOrSchema}),record},_stringToStructureCoercions,stringToStructureCoercions=()=>{if(!_stringToStructureCoercions)_stringToStructureCoercions=[{from:t.Object({}),to:()=>t.ObjectString({}),excludeRoot:!0},{from:t.Array(t.Any()),to:()=>t.ArrayString(t.Any())}];return _stringToStructureCoercions},_coercePrimitiveRoot,coercePrimitiveRoot=()=>{if(!_coercePrimitiveRoot)_coercePrimitiveRoot=[{from:t.Number(),to:(options)=>t.Numeric(options),rootOnly:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),rootOnly:!0}];return _coercePrimitiveRoot},getCookieValidator=({validator,modules,defaultConfig={},config,dynamic,models,validators,sanitize:sanitize2})=>{let cookieValidator=getSchemaValidator(validator,{modules,dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators,sanitize:sanitize2});if(cookieValidator)cookieValidator.config=mergeCookie(cookieValidator.config,config);else cookieValidator=getSchemaValidator(t.Cookie(t.Any()),{modules,dynamic,models,additionalProperties:!0,validators,sanitize:sanitize2}),cookieValidator.config=defaultConfig;return cookieValidator},unwrapImportSchema=(schema)=>schema[Kind4]==="Import"&&schema.$defs[schema.$ref][Kind4]==="Object"?schema.$defs[schema.$ref]:schema;var allocateIf=(value,condition)=>condition?value:"",defaultParsers=["json","text","urlencoded","arrayBuffer","formdata","application/json","text/plain","application/x-www-form-urlencoded","application/octet-stream","multipart/form-data"],createReport=({context="c",trace=[],addFn})=>{if(!trace.length)return()=>{return{resolveChild(){return()=>{}},resolve(){}}};for(let i=0;i<trace.length;i++)addFn(`let report${i},reportChild${i},reportErr${i},reportErrChild${i};let trace${i}=${context}[ELYSIA_TRACE]?.[${i}]??trace[${i}](${context});
|
|
36
|
+
`;for(let i=0;i<instruction.optionals.length;i++){let key=instruction.optionals[i],prop=key.slice(1);if(v+=`if(${key}===undefined`,instruction.unionKeys[key])v+=`||x${prop}===undefined`;let shouldQuestion=prop.charCodeAt(0)!==63&&schema.type!=="array";v+=`)delete x${shouldQuestion?prop.charCodeAt(0)===91?"?.":"?":""}${prop}
|
|
37
|
+
`}return`${v}return x`},createMirror=(schema,{TypeCompiler:TypeCompiler22,modules,definitions,sanitize:sanitize2,recursionLimit=8,removeUnknownUnionType=!1}={})=>{let unions=[];if(typeof sanitize2==="function")sanitize2=[sanitize2];let f=mirror(schema,"v",{optionals:[],optionalsInArray:[],array:0,parentIsOptional:!1,unions,unionKeys:{},TypeCompiler:TypeCompiler22,modules,definitions:definitions??modules?.$defs??{},sanitize:sanitize2,recursion:0,recursionLimit,removeUnknownUnionType});if(!unions.length&&!sanitize2?.length)return Function("v",f);let hof;if(sanitize2?.length){hof={};for(let i=0;i<sanitize2.length;i++)hof[`h${i}`]=sanitize2[i]}return Function("d",`return function mirror(v){${f}}`)({unions,...hof})};var isOptional=(schema)=>{if(!schema)return!1;if(schema?.[Kind4]==="Import"&&schema.References)return schema.References().some(isOptional);if(schema.schema)schema=schema.schema;return!!schema&&OptionalKind in schema},hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some(hasAdditionalProperties);if(schema.anyOf)return schema.anyOf.some(hasAdditionalProperties);if(schema.someOf)return schema.someOf.some(hasAdditionalProperties);if(schema.allOf)return schema.allOf.some(hasAdditionalProperties);if(schema.not)return schema.not.some(hasAdditionalProperties);if(schema.type==="object"){let properties=schema.properties;if("additionalProperties"in schema)return schema.additionalProperties;if("patternProperties"in schema)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasAdditionalProperties(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasAdditionalProperties(property.anyOf[i]))return!0}return property.additionalProperties}return!1}if(schema.type==="array"&&schema.items&&!Array.isArray(schema.items))return hasAdditionalProperties(schema.items);return!1},hasType=(type,schema)=>{if(!schema)return!1;if(Kind4 in schema&&schema[Kind4]===type)return!0;if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasType(type,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasType(type,property.anyOf[i]))return!0}if(Kind4 in property&&property[Kind4]===type)return!0}return!1}return!!schema.properties&&Kind4 in schema.properties&&schema.properties[Kind4]===type},hasProperty=(expectedProperty,_schema)=>{if(!_schema)return;let schema=_schema.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some((schema2)=>hasProperty(expectedProperty,schema2));if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(expectedProperty in property)return!0;if(property.type==="object"){if(hasProperty(expectedProperty,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasProperty(expectedProperty,property.anyOf[i]))return!0}}return!1}return expectedProperty in schema},hasRef=(schema)=>{if(!schema)return!1;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasRef(schema.anyOf[i]))return!0}if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasRef(schema.allOf[i]))return!0}if(schema.not&&hasRef(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasRef(property))return!0;if(property.type==="array"&&property.items&&hasRef(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasRef(schema.items))return!0;return schema[Kind4]==="Ref"&&"$ref"in schema},hasTransform=(schema)=>{if(!schema)return!1;if(schema.$ref&&schema.$defs&&schema.$ref in schema.$defs&&hasTransform(schema.$defs[schema.$ref]))return!0;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasTransform(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasTransform(schema.anyOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasTransform(schema.allOf[i]))return!0}if(schema.not&&hasTransform(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasTransform(property))return!0;if(property.type==="array"&&property.items&&hasTransform(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasTransform(schema.items))return!0;return TransformKind in schema},replaceSchemaType=(schema,options,_config={})=>{let config=_config;if(config.root=!0,!Array.isArray(options))return options.original=schema,_replaceSchemaType(schema,options,config);for(let option of options)option.original=schema,schema=_replaceSchemaType(schema,option,config);return schema},_replaceSchemaType=(schema,options,config)=>{if(!schema)return schema;let root=config.root;if(options.onlyFirst&&schema.type===options.onlyFirst)return options.to(schema)??schema;if(options.untilObjectFound&&!root&&schema.type==="object")return schema;let fromSymbol=options.from[Kind4];if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)schema.oneOf[i]=_replaceSchemaType(schema.oneOf[i],options,config);return schema}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)schema.anyOf[i]=_replaceSchemaType(schema.anyOf[i],options,config);return schema}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)schema.allOf[i]=_replaceSchemaType(schema.allOf[i],options,config);return schema}if(schema.not)return _replaceSchemaType(schema.not,options,config);let isRoot=root&&!!options.excludeRoot;if(schema[Kind4]===fromSymbol){let{anyOf,oneOf,allOf,not,properties:properties2,items,...rest}=schema,to=options.to(rest);if(!to)return schema;let transform,composeProperties=(schema2)=>{let v=_composeProperties(schema2);if(v.$id)delete v.$id;return v},_composeProperties=(v)=>{if(properties2&&v.type==="object"){let newProperties={};for(let[key,value2]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value2,options,{...config,root:!1});return{...rest,...v,properties:newProperties}}if(items&&v.type==="array")return{...rest,...v,items:_replaceSchemaType(items,options,{...config,root:!1})};let value={...rest,...v};if(delete value.required,properties2&&v.type==="string"&&v.format==="ObjectString"&&v.default==="{}")transform=t.ObjectString(properties2,rest),value.default=JSON.stringify(Value3.Create(t.Object(properties2))),value.properties=properties2;if(items&&v.type==="string"&&v.format==="ArrayString"&&v.default==="[]")transform=t.ArrayString(items,rest),value.default=JSON.stringify(Value3.Create(t.Array(items))),value.items=items;return value};if(isRoot){if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,properties:newProperties}}else if(items?.map)return{...rest,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return rest}if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]=composeProperties(to.anyOf[i]);else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]=composeProperties(to.oneOf[i]);else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]=composeProperties(to.allOf[i]);else if(to.not)to.not=composeProperties(to.not);if(transform)to[TransformKind]=transform[TransformKind];if(to.anyOf||to.oneOf||to.allOf||to.not)return to;if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,...to,properties:newProperties}}else if(items?.map)return{...rest,...to,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return{...rest,...to}}let properties=schema?.properties;if(properties&&root&&options.rootOnly!==!0)for(let[key,value]of Object.entries(properties))switch(value[Kind4]){case fromSymbol:let{anyOf,oneOf,allOf,not,type,...rest}=value,to=options.to(rest);if(!to)return schema;if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]={...rest,...to.anyOf[i]};else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]={...rest,...to.oneOf[i]};else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]={...rest,...to.allOf[i]};else if(to.not)to.not={...rest,...to.not};properties[key]={...rest,..._replaceSchemaType(rest,options,{...config,root:!1})};break;case"Object":case"Union":properties[key]=_replaceSchemaType(value,options,{...config,root:!1});break;default:if(Array.isArray(value.items))for(let i=0;i<value.items.length;i++)value.items[i]=_replaceSchemaType(value.items[i],options,{...config,root:!1});else if(value.anyOf||value.oneOf||value.allOf||value.not)properties[key]=_replaceSchemaType(value,options,{...config,root:!1});else if(value.type==="array")value.items=_replaceSchemaType(value.items,options,{...config,root:!1});break}if(schema.type==="array"&&schema.items)if(Array.isArray(schema.items))schema.items=schema.items.map((item)=>_replaceSchemaType(item,options,{...config,root:!1}));else schema.items=_replaceSchemaType(schema.items,options,{...config,root:!1});return schema},createCleaner=(schema)=>(value)=>{if(typeof value==="object")try{return Value3.Clean(schema,value)}catch{}return value},getSchemaValidator=(s,{models={},dynamic=!1,modules,normalize=!1,additionalProperties=!1,coerce=!1,additionalCoerce=[],validators,sanitize:sanitize2}={})=>{if(validators=validators?.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let doesHaveRef=void 0,replaceSchema=(schema2)=>{if(coerce)return replaceSchemaType(schema2,[{from:t.Number(),to:(options)=>t.Numeric(options),untilObjectFound:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),untilObjectFound:!0},...Array.isArray(additionalCoerce)?additionalCoerce:[additionalCoerce]]);return replaceSchemaType(schema2,additionalCoerce)},mapSchema=(s2)=>{let schema2;if(!s2)return;if(typeof s2!=="string")schema2=s2;else{let isArray=s2.endsWith("[]"),key=isArray?s2.substring(0,s2.length-2):s2;if(schema2=modules?.Import(key)??models[key],isArray)schema2=t.Array(schema2)}if(!schema2)return;let _doesHaveRef;if(schema2[Kind4]!=="Import"&&(_doesHaveRef=hasRef(schema2))){let id=randomId();if(doesHaveRef===void 0)doesHaveRef=_doesHaveRef;schema2=t.Module({...modules?.$defs,[id]:schema2}).Import(id)}if(schema2[Kind4]==="Import"){let newDefs={};for(let[key2,value]of Object.entries(schema2.$defs))newDefs[key2]=replaceSchema(value);let key=schema2.$ref;schema2=t.Module(newDefs).Import(key)}else if(coerce||additionalCoerce)schema2=replaceSchema(schema2);return schema2},schema=mapSchema(s);if(validators?.length){let hasAdditional=!1,{schema:mergedObjectSchema,notObjects}=mergeObjectSchemas([schema,...validators.map(mapSchema)]);if(notObjects){if(schema=t.Intersect([...mergedObjectSchema?[mergedObjectSchema]:[],...notObjects.map((x)=>{let schema2=mapSchema(x);if(schema2.type==="object"&&"additionalProperties"in schema2){if(!hasAdditional&&schema2.additionalProperties===!1)hasAdditional=!0;delete schema2.additionalProperties}return schema2})]),schema.type==="object"&&hasAdditional)schema.additionalProperties=!1}}else if(schema.type==="object"&&"additionalProperties"in schema===!1)schema.additionalProperties=additionalProperties;else schema=replaceSchemaType(schema,{onlyFirst:"object",from:t.Object({}),to({properties,...options}){if(!properties)return;if("additionalProperties"in schema)return;return t.Object(properties,{...options,additionalProperties:!1})}});if(dynamic){let validator={schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value3.Check(schema,value),Errors:(value)=>Value3.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value3.Decode(schema,value),Encode:(value)=>Value3.Encode(schema,value),get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(schema)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",schema)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(schema)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},"~hasRef":doesHaveRef,get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasTransform(schema)}};if(schema.config){if(validator.config=schema.config,validator?.schema?.config)delete validator.schema.config}if(normalize&&schema.additionalProperties===!1)if(normalize===!0||normalize==="exactMirror")try{validator.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch{console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema),validator.Clean=createCleaner(schema)}else validator.Clean=createCleaner(schema);return validator.parse=(v)=>{try{return validator.Decode(validator.Clean?.(v)??v)}catch(error2){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(validator.Clean?.(v)??v),error:null}}catch(error2){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}let compiled=TypeCompiler4.Compile(schema,Object.values(models));if(schema.config){if(compiled.config=schema.config,compiled?.schema?.config)delete compiled.schema.config}if(normalize===!0||normalize==="exactMirror")try{compiled.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch(error2){console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.dir(schema,{depth:null}),compiled.Clean=createCleaner(schema)}else if(normalize==="typebox")compiled.Clean=createCleaner(schema);return compiled.parse=(v)=>{try{return compiled.Decode(compiled.Clean?.(v)??v)}catch(error2){throw[...compiled.Errors(v)].map(mapValueError)}},compiled.safeParse=(v)=>{try{return{success:!0,data:compiled.Decode(compiled.Clean?.(v)??v),error:null}}catch(error2){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},Object.assign(compiled,{get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(compiled)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",compiled)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(compiled)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasRef(schema)},"~hasRef":doesHaveRef}),compiled},isUnion=(schema)=>schema[Kind4]==="Union"||!schema.schema&&!!schema.anyOf,mergeObjectSchemas=(schemas)=>{if(schemas.length===0)return{schema:void 0,notObjects:[]};if(schemas.length===1)return schemas[0].type==="object"?{schema:schemas[0],notObjects:[]}:{schema:void 0,notObjects:schemas};let newSchema,notObjects=[],additionalPropertiesIsTrue=!1,additionalPropertiesIsFalse=!1;for(let schema of schemas){if(schema.type!=="object"){notObjects.push(schema);continue}if("additionalProperties"in schema){if(schema.additionalProperties===!0)additionalPropertiesIsTrue=!0;else if(schema.additionalProperties===!1)additionalPropertiesIsFalse=!0}if(!newSchema){newSchema=schema;continue}newSchema={...newSchema,...schema,properties:{...newSchema.properties,...schema.properties},required:[...newSchema?.required??[],...schema.required]}}if(newSchema){if(newSchema.required)newSchema.required=[...new Set(newSchema.required)];if(additionalPropertiesIsFalse)newSchema.additionalProperties=!1;else if(additionalPropertiesIsTrue)newSchema.additionalProperties=!0}return{schema:newSchema,notObjects}},getResponseSchemaValidator=(s,{models={},modules,dynamic=!1,normalize=!1,additionalProperties=!1,validators=[],sanitize:sanitize2})=>{if(validators=validators.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let maybeSchemaOrRecord;if(typeof s!=="string")maybeSchemaOrRecord=s;else{let isArray=s.endsWith("[]"),key=isArray?s.substring(0,s.length-2):s;if(maybeSchemaOrRecord=modules.Import(key)??models[key],isArray)maybeSchemaOrRecord=t.Array(maybeSchemaOrRecord)}if(!maybeSchemaOrRecord)return;if(Kind4 in maybeSchemaOrRecord)return{200:getSchemaValidator(maybeSchemaOrRecord,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[200]),sanitize:sanitize2})};let record={};return Object.keys(maybeSchemaOrRecord).forEach((status2)=>{if(isNaN(+status2))return;let maybeNameOrSchema=maybeSchemaOrRecord[+status2];if(typeof maybeNameOrSchema==="string"){if(maybeNameOrSchema in models){let schema=models[maybeNameOrSchema];record[+status2]=Kind4 in schema?getSchemaValidator(schema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):schema}return}record[+status2]=Kind4 in maybeNameOrSchema?getSchemaValidator(maybeNameOrSchema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):maybeNameOrSchema}),record},_stringToStructureCoercions,stringToStructureCoercions=()=>{if(!_stringToStructureCoercions)_stringToStructureCoercions=[{from:t.Object({}),to:()=>t.ObjectString({}),excludeRoot:!0},{from:t.Array(t.Any()),to:()=>t.ArrayString(t.Any())}];return _stringToStructureCoercions},_coercePrimitiveRoot,coercePrimitiveRoot=()=>{if(!_coercePrimitiveRoot)_coercePrimitiveRoot=[{from:t.Number(),to:(options)=>t.Numeric(options),rootOnly:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),rootOnly:!0}];return _coercePrimitiveRoot},getCookieValidator=({validator,modules,defaultConfig={},config,dynamic,normalize=!1,models,validators,sanitize:sanitize2})=>{let cookieValidator=getSchemaValidator(validator,{modules,dynamic,models,normalize,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators,sanitize:sanitize2});if(cookieValidator)cookieValidator.config=mergeCookie(cookieValidator.config,config);else cookieValidator=getSchemaValidator(t.Cookie(t.Any()),{modules,dynamic,models,additionalProperties:!0,validators,sanitize:sanitize2}),cookieValidator.config=defaultConfig;return cookieValidator},unwrapImportSchema=(schema)=>schema[Kind4]==="Import"&&schema.$defs[schema.$ref][Kind4]==="Object"?schema.$defs[schema.$ref]:schema;var allocateIf=(value,condition)=>condition?value:"",defaultParsers=["json","text","urlencoded","arrayBuffer","formdata","application/json","text/plain","application/x-www-form-urlencoded","application/octet-stream","multipart/form-data"],createReport=({context="c",trace=[],addFn})=>{if(!trace.length)return()=>{return{resolveChild(){return()=>{}},resolve(){}}};for(let i=0;i<trace.length;i++)addFn(`let report${i},reportChild${i},reportErr${i},reportErrChild${i};let trace${i}=${context}[ELYSIA_TRACE]?.[${i}]??trace[${i}](${context});
|
|
38
38
|
`);return(event,{name,total=0}={})=>{if(!name)name="anonymous";let reporter=event==="error"?"reportErr":"report";for(let i=0;i<trace.length;i++)addFn(`${reporter}${i} = trace${i}.${event}({id,event:'${event}',name:'${name}',begin:performance.now(),total:${total}})
|
|
39
39
|
`);return{resolve(){for(let i=0;i<trace.length;i++)addFn(`${reporter}${i}.resolve()
|
|
40
40
|
`)},resolveChild(name2){for(let i=0;i<trace.length;i++)addFn(`${reporter}Child${i}=${reporter}${i}.resolveChild?.shift()?.({id,event:'${event}',name:'${name2}',begin:performance.now()})
|
|
@@ -196,7 +196,7 @@ c=transformed}`;else fnLiteral+="if(transformed instanceof ElysiaCustomStatusRes
|
|
|
196
196
|
`;validator2+="}",fnLiteral+=validator2,fileUnions.push(candidate)}}}}}else if(hasNonUnionFileWithDefault||!hasUnion&&(hasType("File",unwrapImportSchema(validator.body.schema))||hasType("Files",unwrapImportSchema(validator.body.schema)))){let validateFile2="",i=0;for(let[k2,v]of Object.entries(unwrapImportSchema(validator.body.schema).properties)){if(!v.extension||v[Kind5]!=="File"&&v[Kind5]!=="Files")continue;if(i)validateFile2+=",";validateFile2+=`validateFileExtension(c.body.${k2},${JSON.stringify(v.extension)},'body.${k2}')`,i++}if(i)fnLiteral+=`
|
|
197
197
|
`;if(i===1)fnLiteral+=`await ${validateFile2}
|
|
198
198
|
`;else if(i>1)fnLiteral+=`await Promise.all([${validateFile2}])
|
|
199
|
-
`}}if(validator.cookie){let cookieValidator=getCookieValidator({modules:app.definitions.typebox,validator:validator.cookie,defaultConfig:app.config.cookie,dynamic:!!app.config.aot,config:validator.cookie?.config??{},models:app.definitions.type});if(fnLiteral+=`const cookieValue={}
|
|
199
|
+
`}}if(validator.cookie){let cookieValidator=getCookieValidator({modules:app.definitions.typebox,validator:validator.cookie,defaultConfig:app.config.cookie,dynamic:!!app.config.aot,config:validator.cookie?.config??{},normalize:app.config.normalize,models:app.definitions.type});if(fnLiteral+=`const cookieValue={}
|
|
200
200
|
for(const [key,value] of Object.entries(c.cookie))cookieValue[key]=value.value
|
|
201
201
|
`,cookieValidator.hasDefault)for(let[key,value]of Object.entries(Value4.Default(cookieValidator.schema,{})))fnLiteral+=`cookieValue['${key}'] = ${typeof value==="object"?JSON.stringify(value):value}
|
|
202
202
|
`;if(cookieValidator.isOptional)fnLiteral+="if(isNotEmpty(c.cookie)){";if(validator.body?.schema?.noValidate!==!0)fnLiteral+="if(validator.cookie.Check(cookieValue)===false){"+validation.validate("cookie","cookieValue")+"}";if(cookieValidator.hasTransform)fnLiteral+=coerceTransformDecodeError(`for(const [key,value] of Object.entries(validator.cookie.Decode(cookieValue)))c.cookie[key].value=value
|
|
@@ -358,7 +358,7 @@ return u.substring(s,qi)
|
|
|
358
358
|
`:`c.headers={}
|
|
359
359
|
for(const [k,v] of c.request.headers.entries())c.headers[k]=v
|
|
360
360
|
`},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(`
|
|
361
|
-
`))}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};
|
|
361
|
+
`))}return this}wrap(fn){return this.extender.higherOrderFunctions.push({checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:fn.toString()})),fn}),this}applyMacro(localHook){if(this.extender.macros.length){let manage=createMacroManager({globalHook:this.event,localHook}),manager={events:{global:this.event,local:localHook},get onParse(){return manage("parse")},get onTransform(){return manage("transform")},get onBeforeHandle(){return manage("beforeHandle")},get onAfterHandle(){return manage("afterHandle")},get mapResponse(){return manage("mapResponse")},get onAfterResponse(){return manage("afterResponse")},get onError(){return manage("error")}};for(let macro of this.extender.macros)traceBackMacro(macro.fn(manager),localHook,manage)}}get models(){let models={};for(let name of Object.keys(this.definitions.type))models[name]=getSchemaValidator(this.definitions.typebox.Import(name));return models.modules=this.definitions.typebox,models}add(method,path,handle,localHook,options,standaloneValidators){let skipPrefix=options?.skipPrefix??!1,allowMeta=options?.allowMeta??!1;if(localHook??={},standaloneValidators===void 0){if(standaloneValidators=[],this.standaloneValidator.local)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.local);if(this.standaloneValidator.scoped)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.scoped);if(this.standaloneValidator.global)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.global)}if(path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix)path=this.config.prefix+path;if(localHook?.type)switch(localHook.type){case"text":localHook.type="text/plain";break;case"json":localHook.type="application/json";break;case"formdata":localHook.type="multipart/form-data";break;case"urlencoded":localHook.type="application/x-www-form-urlencoded";break;case"arrayBuffer":localHook.type="application/octet-stream";break;default:break}let instanceValidator=this.validator.getCandidate(),cloned={body:localHook?.body??instanceValidator?.body,headers:localHook?.headers??instanceValidator?.headers,params:localHook?.params??instanceValidator?.params,query:localHook?.query??instanceValidator?.query,cookie:localHook?.cookie??instanceValidator?.cookie,response:localHook?.response??instanceValidator?.response},shouldPrecompile=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.compose===!0,createValidator=()=>{let models=this.definitions.type,dynamic=!this.config.aot,normalize=this.config.normalize,modules=this.definitions.typebox,sanitize2=()=>this.config.sanitize,cookieValidator=()=>{if(cloned.cookie||standaloneValidators.find((x)=>x.cookie))return getCookieValidator({modules,validator:cloned.cookie,defaultConfig:this.config.cookie,normalize,config:cloned.cookie?.config??{},dynamic,models,validators:standaloneValidators.map((x)=>x.cookie),sanitize:sanitize2})};return shouldPrecompile?{body:getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2}),headers:getSchemaValidator(cloned.headers,{modules,dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2}),params:getSchemaValidator(cloned.params,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2}),query:getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{modules,dynamic,models,normalize,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}}};if(instanceValidator.body||instanceValidator.cookie||instanceValidator.headers||instanceValidator.params||instanceValidator.query||instanceValidator.response)localHook=mergeHook(localHook,instanceValidator);if(localHook.tags)if(!localHook.detail)localHook.detail={tags:localHook.tags};else localHook.detail.tags=localHook.tags;if(isNotEmpty(this.config.detail))localHook.detail=mergeDeep(Object.assign({},this.config.detail),localHook.detail);this.applyMacro(localHook);let hooks=isNotEmpty(this.event)?mergeHook(this.event,localHookToLifeCycleStore(localHook)):lifeCycleToArray(localHookToLifeCycleStore(localHook));if(this.config.aot===!1){let validator=createValidator();this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle,route:path});let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.dynamic.add(method,encoded,{validator,hooks,content:localHook?.type,handle,route:path});if(this.config.strictPath===!1){let loosePath=getLoosePath(path);this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path});let encoded2=encodePath(loosePath);if(loosePath!==encoded2)this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path})}this.router.history.push({method,path,composed:null,handler:handle,compile:void 0,hooks,standaloneValidators});return}let adapter=this["~adapter"].handler,nativeStaticHandler=typeof handle!=="function"?()=>{let context={redirect,request:this["~adapter"].isWebStandard?new Request(`http://e.ly${path}`,{method}):void 0,server:null,set:{headers:Object.assign({},this.setHeaders)},status,error:status,store:this.store};try{this.event.request?.map((x)=>{if(typeof x.fn==="function")return x.fn(context);if(typeof x==="function")return x(context)})}catch(error2){let res;if(context.error=error2,this.event.error?.some((x)=>{if(typeof x.fn==="function")return res=x.fn(context);if(typeof x==="function")return res=x(context)}),res!==void 0)handle=res}let fn=adapter.createNativeStaticHandler?.(handle,hooks,context.set);return fn instanceof Promise?fn.then((fn2)=>{if(fn2)return fn2}):fn?.()}:void 0,useNativeStaticResponse=this.config.nativeStaticResponse===!0,addResponsePath=(path2)=>{if(!useNativeStaticResponse||!nativeStaticHandler)return;if(supportPerMethodInlineHandler)if(this.router.response[path2])this.router.response[path2][method]=nativeStaticHandler();else this.router.response[path2]={[method]:nativeStaticHandler()};else this.router.response[path2]=nativeStaticHandler()};addResponsePath(path);let _compiled,compile2=()=>{if(_compiled)return _compiled;return _compiled=composeHandler({app:this,path,method,hooks,validator:createValidator(),handler:typeof handle!=="function"&&typeof adapter.createStaticHandler!=="function"?()=>handle:handle,allowMeta,inference:this.inference})},oldIndex;if(`${method}_${path}`in this.routeTree)for(let i=0;i<this.router.history.length;i++){let route=this.router.history[i];if(route.path===path&&route.method===method){oldIndex=i;break}}else this.routeTree[`${method}_${path}`]=this.router.history.length;let index=oldIndex??this.router.history.length,mainHandler=shouldPrecompile?compile2():(ctx)=>(this.router.history[index].composed=compile2())(ctx);if(oldIndex!==void 0)this.router.history[oldIndex]=Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0);else this.router.history.push(Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0));let handler={handler:shouldPrecompile?mainHandler:void 0,compile(){return this.handler=compile2()}},staticRouter=this.router.static,isStaticPath=path.indexOf(":")===-1&&path.indexOf("*")===-1;if(method==="WS"){if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};return}if(this.router.http.add("WS",path,handler),!this.config.strictPath)this.router.http.add("WS",getLoosePath(path),handler);let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add("WS",encoded,handler);return}if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};if(!this.config.strictPath)addResponsePath(getLoosePath(path))}else{if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath=getLoosePath(path);addResponsePath(loosePath),this.router.http.add(method,loosePath,handler)}let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add(method,encoded,handler),addResponsePath(encoded)}}setHeaders;headers(header){if(!header)return this;if(!this.setHeaders)this.setHeaders={};return this.setHeaders=mergeDeep(this.setHeaders,header),this}onStart(handler){return this.on("start",handler),this}onRequest(handler){return this.on("request",handler),this}onParse(options,handler){if(!handler){if(typeof options==="string")return this.on("parse",this["~parser"][options]);return this.on("parse",options)}return this.on(options,"parse",handler)}parser(name,parser){return this["~parser"][name]=parser,this}onTransform(options,handler){if(!handler)return this.on("transform",options);return this.on(options,"transform",handler)}resolve(optionsOrResolve,resolve){if(!resolve)resolve=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"resolve",fn:resolve};return this.onBeforeHandle(optionsOrResolve,hook)}mapResolve(optionsOrResolve,mapper){if(!mapper)mapper=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"mapResolve",fn:mapper};return this.onBeforeHandle(optionsOrResolve,hook)}onBeforeHandle(options,handler){if(!handler)return this.on("beforeHandle",options);return this.on(options,"beforeHandle",handler)}onAfterHandle(options,handler){if(!handler)return this.on("afterHandle",options);return this.on(options,"afterHandle",handler)}mapResponse(options,handler){if(!handler)return this.on("mapResponse",options);return this.on(options,"mapResponse",handler)}onAfterResponse(options,handler){if(!handler)return this.on("afterResponse",options);return this.on(options,"afterResponse",handler)}trace(options,handler){if(!handler)handler=options,options={as:"local"};if(!Array.isArray(handler))handler=[handler];for(let fn of handler)this.on(options,"trace",createTracer(fn));return this}error(name,error2){switch(typeof name){case"string":return error2.prototype[ERROR_CODE]=name,this.definitions.error[name]=error2,this;case"function":return this.definitions.error=name(this.definitions.error),this}for(let[code,error3]of Object.entries(name))error3.prototype[ERROR_CODE]=code,this.definitions.error[code]=error3;return this}onError(options,handler){if(!handler)return this.on("error",options);return this.on(options,"error",handler)}onStop(handler){return this.on("stop",handler),this}on(optionsOrType,typeOrHandlers,handlers){let type;switch(typeof optionsOrType){case"string":type=optionsOrType,handlers=typeOrHandlers;break;case"object":if(type=typeOrHandlers,!Array.isArray(typeOrHandlers)&&typeof typeOrHandlers==="object")handlers=typeOrHandlers;break}if(Array.isArray(handlers))handlers=fnToContainer(handlers);else if(typeof handlers==="function")handlers=[{fn:handlers}];else handlers=[handlers];let handles=handlers;for(let handle of handles)if(handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local",type==="resolve"||type==="derive")handle.subType=type;if(type!=="trace")this.inference=sucrose({[type]:handles.map((x)=>x.fn)},this.inference);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type){case"start":this.event.start??=[],this.event.start.push(fn);break;case"request":this.event.request??=[],this.event.request.push(fn);break;case"parse":this.event.parse??=[],this.event.parse.push(fn);break;case"transform":this.event.transform??=[],this.event.transform.push(fn);break;case"derive":this.event.transform??=[],this.event.transform.push(fnToContainer(fn,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(fn);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(fnToContainer(fn,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(fn);break;case"trace":this.event.trace??=[],this.event.trace.push(fn);break;case"error":this.event.error??=[],this.event.error.push(fn);break;case"stop":this.event.stop??=[],this.event.stop.push(fn);break}}return this}as(type){if(promoteEvent(this.event.parse,type),promoteEvent(this.event.transform,type),promoteEvent(this.event.beforeHandle,type),promoteEvent(this.event.afterHandle,type),promoteEvent(this.event.mapResponse,type),promoteEvent(this.event.afterResponse,type),promoteEvent(this.event.trace,type),promoteEvent(this.event.error,type),type==="scoped"){if(this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null}else if(type==="global"){if(this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null;if(this.standaloneValidator.scoped!==null)this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null}return this}group(prefix,schemaOrRun,run){let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.getServer=()=>this.getServer(),instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance["~parser"]=this["~parser"],instance.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let isSchema=typeof schemaOrRun==="object",sandbox=(isSchema?run:schemaOrRun)(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks,standaloneValidators})=>{if(path=(isSchema?"":this.config.prefix??"")+prefix+path,isSchema){let hook=schemaOrRun,localHook=hooks;this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]]}),void 0,standaloneValidators)}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0},standaloneValidators)}),this}guard(hook,run){if(!run){if(typeof hook==="object"){if(this.applyMacro(hook),hook.detail)if(this.config.detail)this.config.detail=mergeDeep(Object.assign({},this.config.detail),hook.detail);else this.config.detail=hook.detail;if(hook.tags)if(!this.config.detail)this.config.detail={tags:hook.tags};else this.config.detail.tags=hook.tags;let type=hook.as??"local";if(hook.schema==="standalone"){if(!this.standaloneValidator[type])this.standaloneValidator[type]=[];let response=hook?.response||typeof hook?.response==="string"||hook?.response&&Kind6 in hook.response?{200:hook.response}:hook?.response;this.standaloneValidator[type].push({body:hook.body,headers:hook.headers,params:hook.params,query:hook.query,response,cookie:hook.cookie})}else this.validator[type]={body:hook.body??this.validator[type]?.body,headers:hook.headers??this.validator[type]?.headers,params:hook.params??this.validator[type]?.params,query:hook.query??this.validator[type]?.query,response:hook.response??this.validator[type]?.response,cookie:hook.cookie??this.validator[type]?.cookie};if(hook.parse)this.on({as:type},"parse",hook.parse);if(hook.transform)this.on({as:type},"transform",hook.transform);if(hook.derive)this.on({as:type},"derive",hook.derive);if(hook.beforeHandle)this.on({as:type},"beforeHandle",hook.beforeHandle);if(hook.resolve)this.on({as:type},"resolve",hook.resolve);if(hook.afterHandle)this.on({as:type},"afterHandle",hook.afterHandle);if(hook.mapResponse)this.on({as:type},"mapResponse",hook.mapResponse);if(hook.afterResponse)this.on({as:type},"afterResponse",hook.afterResponse);if(hook.error)this.on({as:type},"error",hook.error);return this}return this.guard({},hook)}let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance.getServer=()=>this.getServer();let sandbox=run(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.getServer=()=>this.server,sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks:localHook})=>{this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]]}))}),this}use(plugin){if(!plugin)return this;if(Array.isArray(plugin)){let app=this;for(let p of plugin)app=app.use(p);return app}if(plugin instanceof Promise)return this.promisedModules.add(plugin.then((plugin2)=>{if(typeof plugin2==="function")return plugin2(this);if(plugin2 instanceof Elysia)return this._use(plugin2).compile();if(plugin2.constructor.name==="Elysia")return this._use(plugin2).compile();if(typeof plugin2.default==="function")return plugin2.default(this);if(plugin2.default instanceof Elysia)return this._use(plugin2.default);if(plugin2.constructor.name==="Elysia")return this._use(plugin2.default);if(plugin2.constructor.name==="_Elysia")return this._use(plugin2.default);try{return this._use(plugin2.default)}catch(error2){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),error2}}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return this._use(plugin)}propagatePromiseModules(plugin){if(plugin.promisedModules.size<=0)return this;for(let promise of plugin.promisedModules.promises)this.promisedModules.add(promise.then((v)=>{if(!v)return;let t2=this._use(v);if(t2 instanceof Promise)return t2.then((v2)=>{if(v2)v2.compile();else v.compile()});return v.compile()}));return this}_use(plugin){if(typeof plugin==="function"){let instance=plugin(this);if(instance instanceof Promise)return this.promisedModules.add(instance.then((plugin2)=>{if(plugin2 instanceof Elysia){plugin2.getServer=()=>this.getServer(),plugin2.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin2.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin2.model(this.definitions.type),plugin2.error(this.definitions.error);for(let{method,path,handler,hooks,standaloneValidators}of Object.values(plugin2.router.history))this.add(method,path,handler,hooks,void 0,standaloneValidators);if(plugin2===this)return;return this.propagatePromiseModules(plugin2),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return instance}this.propagatePromiseModules(plugin);let name=plugin.config.name,seed=plugin.config.seed;if(plugin.getParent=()=>this,plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin.standaloneValidator?.scoped)if(this.standaloneValidator.local)this.standaloneValidator.local=this.standaloneValidator.local.concat(plugin.standaloneValidator.scoped);else this.standaloneValidator.local=plugin.standaloneValidator.scoped;if(plugin.standaloneValidator?.global)if(this.standaloneValidator.global)this.standaloneValidator.global=this.standaloneValidator.global.concat(plugin.standaloneValidator.global);else this.standaloneValidator.global=plugin.standaloneValidator.global;if(isNotEmpty(plugin["~parser"]))this["~parser"]={...plugin["~parser"],...this["~parser"]};if(plugin.setHeaders)this.headers(plugin.setHeaders);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(!this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))this.extender.macros=this.extender.macros.concat(plugin.extender.macros),this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}else{if(plugin.extender.macros.length)this.extender.macros=this.extender.macros.concat(plugin.extender.macros);if(plugin.extender.higherOrderFunctions.length)this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}if(deduplicateChecksum(this.extender.macros),plugin.extender.higherOrderFunctions.length){deduplicateChecksum(this.extender.higherOrderFunctions);let hofHashes=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let hof=this.extender.higherOrderFunctions[i];if(hof.checksum){if(hofHashes.includes(hof.checksum))this.extender.higherOrderFunctions.splice(i,1),i--;hofHashes.push(hof.checksum)}}hofHashes.length=0}if(this.inference=mergeInference(this.inference,plugin.inference),isNotEmpty(plugin.singleton.decorator))this.decorate(plugin.singleton.decorator);if(isNotEmpty(plugin.singleton.store))this.state(plugin.singleton.store);if(isNotEmpty(plugin.definitions.type))this.model(plugin.definitions.type);if(isNotEmpty(plugin.definitions.error))this.error(plugin.definitions.error);if(isNotEmpty(plugin.definitions.error))plugin.extender.macros=this.extender.macros.concat(plugin.extender.macros);for(let{method,path,handler,hooks,standaloneValidators}of Object.values(plugin.router.history))this.add(method,path,handler,hooks,void 0,standaloneValidators);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))return this;if(this.dependencies[name].push(this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies,stack:plugin.telemetry?.stack,routes:plugin.router.history,decorators:plugin.singleton,store:plugin.singleton.store,error:plugin.definitions.error,derive:plugin.event.transform?.filter((x)=>x?.subType==="derive").map((x)=>({fn:x.toString(),stack:new Error().stack??""})),resolve:plugin.event.transform?.filter((x)=>x?.subType==="resolve").map((x)=>({fn:x.toString(),stack:new Error().stack??""}))}:{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}),isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event),current)}else if(isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event));if(plugin.validator.global)this.validator.global=mergeHook(this.validator.global,{...plugin.validator.global});if(plugin.validator.scoped)this.validator.local=mergeHook(this.validator.local,{...plugin.validator.scoped});return this}macro(macro){if(typeof macro==="function"){let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:macro.toString()})),fn:macro};this.extender.macros.push(hook)}else if(typeof macro==="object"){for(let name of Object.keys(macro))if(typeof macro[name]==="object"){let actualValue={...macro[name]};macro[name]=(v)=>{if(v===!0)return actualValue}}let hook={checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:Object.entries(macro).map(([k2,v])=>`${k2}+${v}`).join(",")})),fn:()=>macro};this.extender.macros.push(hook)}return this}mount(path,handleOrConfig,config){if(path instanceof Elysia||typeof path==="function"||path.length===0||path==="/"){let run=typeof path==="function"?path:path instanceof Elysia?path.compile().fetch:handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw new Error("Invalid handler")})(),handler2=({request,path:path2})=>run(new Request(replaceUrlPath(request.url,path2),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL","/*",handler2,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:run}}),this}let handle=handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw new Error("Invalid handler")})(),length=path.length-(path.endsWith("*")?1:0),handler=({request,path:path2})=>handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL",path,handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this.route("ALL",path+(path.endsWith("/")?"*":"/*"),handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this}get(path,handler,hook){return this.add("GET",path,handler,hook),this}post(path,handler,hook){return this.add("POST",path,handler,hook),this}put(path,handler,hook){return this.add("PUT",path,handler,hook),this}patch(path,handler,hook){return this.add("PATCH",path,handler,hook),this}delete(path,handler,hook){return this.add("DELETE",path,handler,hook),this}options(path,handler,hook){return this.add("OPTIONS",path,handler,hook),this}all(path,handler,hook){return this.add("ALL",path,handler,hook),this}head(path,handler,hook){return this.add("HEAD",path,handler,hook),this}connect(path,handler,hook){return this.add("CONNECT",path,handler,hook),this}route(method,path,handler,hook){return this.add(method.toUpperCase(),path,handler,hook,hook?.config),this}ws(path,options){if(this["~adapter"].ws)this["~adapter"].ws(this,path,options);else console.warn("Current adapter doesn't support WebSocket");return this}state(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(!value||!isNotEmpty(value))return this;if(name){if(name in this.singleton.store)this.singleton.store[name]=mergeDeep(this.singleton.store[name],value,{override:as==="override"});else this.singleton.store[name]=value;return this}if(value===null)return this;return this.singleton.store=mergeDeep(this.singleton.store,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value}else this.singleton.store=value(this.singleton.store);return this;default:if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value;return this}}decorate(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(name){if(name in this.singleton.decorator)this.singleton.decorator[name]=mergeDeep(this.singleton.decorator[name],value,{override:as==="override"});else this.singleton.decorator[name]=value;return this}if(value===null)return this;return this.singleton.decorator=mergeDeep(this.singleton.decorator,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value}else this.singleton.decorator=value(this.singleton.decorator);return this;default:if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value;return this}}derive(optionsOrTransform,transform){if(!transform)transform=optionsOrTransform,optionsOrTransform={as:"local"};let hook={subType:"derive",fn:transform};return this.onTransform(optionsOrTransform,hook)}model(name,model){switch(typeof name){case"object":let parsedSchemas={},kvs=Object.entries(name);if(!kvs.length)return this;for(let[key,value]of kvs){if(key in this.definitions.type)continue;parsedSchemas[key]=this.definitions.type[key]=value,parsedSchemas[key].$id??=`#/components/schemas/${key}`}return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...parsedSchemas}),this;case"function":let result=name(this.definitions.type);return this.definitions.type=result,this.definitions.typebox=t.Module(result),this;case"string":if(!model)break;let newModel={...model,id:model.$id??`#/components/schemas/${name}`};return this.definitions.type[name]=model,this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...newModel}),this}return this.definitions.type[name]=model,this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,[name]:model}),this}Ref(key){return t.Ref(key)}mapDerive(optionsOrDerive,mapper){if(!mapper)mapper=optionsOrDerive,optionsOrDerive={as:"local"};let hook={subType:"mapDerive",fn:mapper};return this.onTransform(optionsOrDerive,hook)}affix(base,type,word){if(word==="")return this;let delimieter=["_","-"," "],capitalize=(word2)=>word2[0].toUpperCase()+word2.slice(1),joinKey=base==="prefix"?(prefix,word2)=>delimieter.includes(prefix.at(-1)??"")?prefix+word2:prefix+capitalize(word2):delimieter.includes(word.at(-1)??"")?(suffix,word2)=>word2+suffix:(suffix,word2)=>word2+capitalize(suffix),remap=(type2)=>{let store={};switch(type2){case"decorator":for(let key in this.singleton.decorator)store[joinKey(word,key)]=this.singleton.decorator[key];this.singleton.decorator=store;break;case"state":for(let key in this.singleton.store)store[joinKey(word,key)]=this.singleton.store[key];this.singleton.store=store;break;case"model":for(let key in this.definitions.type)store[joinKey(word,key)]=this.definitions.type[key];this.definitions.type=store;break;case"error":for(let key in this.definitions.error)store[joinKey(word,key)]=this.definitions.error[key];this.definitions.error=store;break}},types=Array.isArray(type)?type:[type];for(let type2 of types.some((x)=>x==="all")?["decorator","state","model","error"]:types)remap(type2);return this}prefix(type,word){return this.affix("prefix",type,word)}suffix(type,word){return this.affix("suffix",type,word)}compile(){if(this["~adapter"].isWebStandard){if(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this),typeof this.server?.reload==="function")this.server.reload({...this.server||{},fetch:this.fetch});return this}if(typeof this.server?.reload==="function")this.server.reload(this.server||{});return this._handle=composeGeneralHandler(this),this}handle=async(request)=>this.fetch(request);fetch=(request)=>{return(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this))(request)};handleError=async(context,error2)=>{return(this.handleError=this.config.aot?composeErrorHandler(this):createDynamicErrorHandler(this))(context,error2)};listen=(options,callback)=>{if(this["~adapter"].listen(this)(options,callback),this.promisedModules.size)clearSucroseCache(5000);return this.promisedModules.then(()=>{clearSucroseCache(1000)}),this};stop=async(closeActiveConnections)=>{return await this["~adapter"].stop?.(this,closeActiveConnections),this};[Symbol.dispose]=()=>{if(this.server)this.stop()};get modules(){return this.promisedModules}}export{t,status,sse,serializeCookie,replaceUrlPath,replaceSchemaType,redirect,mergeObjectArray,mergeHook,mapValueError,getSchemaValidator,getResponseSchemaValidator,form,file,error,env2 as env,Elysia as default,deduplicateChecksum,cloneInference,checksum,ValidationError,TypeSystemPolicy2 as TypeSystemPolicy,StatusMap,ParseError,NotFoundError,InvertedStatusMap,InvalidCookieSignature,InternalServerError,ElysiaFile,ElysiaCustomStatusResponse,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
|
|
362
362
|
|
|
363
|
-
//# debugId=
|
|
363
|
+
//# debugId=1A54EAEDE0443A2F64756E2164756E21
|
|
364
364
|
//# sourceMappingURL=index.js.map
|