import type { Elysia, AnyElysia, InvertedStatusMap } from './index'; import type { ElysiaFile } from './universal/file'; import type { Serve } from './universal/server'; import { TSchema, TAnySchema, OptionalKind, TModule, TImport, TProperties } from '@sinclair/typebox'; import type { TypeCheck, ValueError } from '@sinclair/typebox/compiler'; import type { OpenAPIV3 } from 'openapi-types'; import type { ElysiaAdapter } from './adapter'; import type { ElysiaTypeCheck } from './schema'; import type { Context, ErrorContext, PreContext } from './context'; import type { ComposerGeneralHandlerOptions } from './compose'; import type { CookieOptions } from './cookies'; import type { TraceHandler } from './trace'; import type { ElysiaCustomStatusResponse, InternalServerError, InvalidCookieSignature, InvalidFileType, NotFoundError, ParseError, ValidationError } from './error'; import type { AnyWSLocalHook } from './ws/types'; import type { WebSocketHandler } from './ws/bun'; import type { Instruction as ExactMirrorInstruction } from 'exact-mirror'; import { BunHTMLBundlelike } from './universal/types'; import { Sucrose } from './sucrose'; import type Memoirist from 'memoirist'; import type { DynamicHandler } from './dynamic-handle'; export type Equal = (() => T extends X ? 1 : 2) extends () => T extends Y ? 1 : 2 ? true : false; export type IsNever = [T] extends [never] ? true : false; export type PickIfExists = {} extends T ? {} : { [P in K as P extends keyof T ? P : never]: T[P]; }; export interface StandardSchemaV1Like { readonly '~standard': { readonly types?: { readonly input: Input; readonly output: Output; } | undefined; }; } export interface FastStandardSchemaV1Like { readonly '~standard': {}; } export type StandardSchemaV1LikeValidate = (v: T) => MaybePromise<{ value: T; issues?: never; } | { value?: never; issues: unknown[]; }>; export type AnySchema = TSchema | StandardSchemaV1Like; export type FastAnySchema = TAnySchema | FastStandardSchemaV1Like; export interface ElysiaConfig { /** * @default BunAdapter * @since 1.1.11 */ adapter?: ElysiaAdapter; /** * Path prefix of the instance * * @default ''' */ prefix?: Prefix; /** * Name of the instance for debugging, and plugin deduplication purpose */ name?: string; /** * Seed for generating checksum for plugin deduplication * * @see https://elysiajs.com/essential/plugin.html#plugin-deduplication */ seed?: unknown; /** * Bun serve * * @see https://bun.sh/docs/api/http */ serve?: Partial; /** * OpenAPI documentation (use in Swagger) * * @see https://swagger.io/specification/ */ detail?: DocumentDecoration; /** * OpenAPI tags * * current instance' routes with tags * * @see https://swagger.io/specification/#tag-object */ tags?: DocumentDecoration['tags']; /** * Warm up Elysia before starting the server * * This will perform Ahead of Time compilation and generate code for route handlers * * If set to false, Elysia will perform Just in Time compilation * * Only required for root instance (instance which use listen) to effect * * ! If performing a benchmark, it's recommended to set this to `true` * * @default false */ precompile?: boolean | { /** * Perform dynamic code generation for route handlers before starting the server * * @default false */ compose?: boolean; /** * Perform Ahead of Time compilation for schema before starting the server * * @default false */ schema?: boolean; }; /** * Enable Ahead of Time compilation * * Trade significant performance with slightly faster startup time and reduced memory usage */ aot?: boolean; /** * Whether should Elysia tolerate suffix '/' or vice-versa * * @default false */ strictPath?: boolean; /** * Override websocket configuration * * @see https://bun.sh/docs/api/websockets */ websocket?: Omit, 'open' | 'close' | 'message' | 'drain'>; cookie?: CookieOptions & { /** * Specified cookie name to be signed globally */ sign?: true | string | string[]; }; /** * Capture more detail information for each dependencies */ analytic?: boolean; /** * If enabled, the schema with `t.Transform` will call `Encode` before sending the response * * @default true * @since 1.3.0 * @since 1.2.16 (experimental) **/ encodeSchema?: boolean; /** * Enable experimental features */ experimental?: {}; /** * If enabled, Elysia will attempt to coerce value to defined type on incoming and outgoing bodies. * * This allows for sending unknown or disallowed properties in the bodies. These will simply be filtered out instead of failing the request. * This has no effect when the schemas allow additional properties. * Since this uses dynamic schema it may have an impact on performance. * * options: * - true: use 'exactMirror' * - false: do not normalize the value * - 'exactMirror': use Elysia's custom exact-mirror which precompile a schema * - 'typebox': Since this uses dynamic Value.Clean, it have performance impact * * Note: This option only works when Elysia schema is provided, doesn't work with Standard Schema * * @default true */ normalize?: boolean | 'exactMirror' | 'typebox'; handler?: ComposerGeneralHandlerOptions; /** * Enable Bun static response * * @default true * @since 1.1.11 */ nativeStaticResponse?: boolean; /** * Use runtime/framework provided router if possible * * @default true * @since 1.3.0 */ systemRouter?: boolean; /** * Array of callback function to transform a string value defined in a schema * * This option only works when `sanitlize` is `exactMirror` * * This only works when set on the main instance * * @default true * @since 1.3.0 */ sanitize?: ExactMirrorInstruction['sanitize']; /** * Sucrose (Static Code Analysis) configuration */ sucrose?: Sucrose.Settings; /** * Allow unsafe validation details in errors thrown by Elysia's schema validator (422 status code) * * Ideally, this should only be used in development environment or public APIs * This may leak sensitive information about the server implementation and should be used with caution in production environments. * * @default false */ allowUnsafeValidationDetails?: boolean; } export interface ValidatorLayer { global: SchemaValidator | null; scoped: SchemaValidator | null; local: SchemaValidator | null; getCandidate(): SchemaValidator; } export interface StandaloneInputSchema { body?: AnySchema | Name | `${Name}[]`; headers?: AnySchema | Name | `${Name}[]`; query?: AnySchema | Name | `${Name}[]`; params?: AnySchema | Name | `${Name}[]`; cookie?: AnySchema | Name | `${Name}[]`; response?: { [status in number]: `${Name}[]` | Name | AnySchema; }; } export interface StandaloneValidator { global: InputSchema[] | null; scoped: InputSchema[] | null; local: InputSchema[] | null; } export type MaybeArray = T | T[]; export type MaybeReadonlyArray = T | readonly T[]; export type MaybePromise = T | Promise; export type ObjectValues = T[keyof T]; type IsPathParameter = Part extends `:${infer Parameter}` ? Parameter : Part extends `*` ? '*' : never; export type GetPathParameter = Path extends `${infer A}/${infer B}` ? IsPathParameter | GetPathParameter : IsPathParameter; type _ResolvePath = { [Param in GetPathParameter as Param extends `${string}?` ? never : Param]: string; } & { [Param in GetPathParameter as Param extends `${infer OptionalParam}?` ? OptionalParam : never]?: string; }; export type ResolvePath = Path extends '' ? {} : Path extends PathParameterLike ? _ResolvePath : {}; export type Or = T1 extends true ? true : T2 extends true ? true : false; export type Prettify = { [K in keyof T]: T[K]; } & {}; export type NeverKey = { [K in keyof T]?: never; } & {}; type IsBothObject = A extends Record ? B extends Record ? IsClass extends false ? IsClass extends false ? true : false : false : false : false; type IsClass = V extends abstract new (...args: any) => any ? true : false; export type Reconcile = Stack['length'] extends 16 ? A : Override extends true ? { [key in keyof A as key extends keyof B ? never : key]: A[key]; } extends infer Collision ? {} extends Collision ? { [key in keyof B]: IsBothObject extends true ? Reconcile : B[key]; } : Prettify : never : { [key in keyof B as key extends keyof A ? never : key]: B[key]; } extends infer Collision ? {} extends Collision ? { [key in keyof A]: IsBothObject extends true ? Reconcile : A[key]; } : Prettify<{ [key in keyof A]: A[key]; } & Collision> : never; export interface SingletonBase { decorator: Record; store: Record; derive: Record; resolve: Record; } export interface PossibleResponse { [status: number]: unknown; } export interface EphemeralType { derive: SingletonBase['derive']; resolve: SingletonBase['resolve']; schema: MetadataBase['schema']; standaloneSchema: MetadataBase['schema']; response: PossibleResponse; } export interface DefinitionBase { typebox: Record; error: Record; } export type RouteBase = Record; export interface MetadataBase { schema: RouteSchema; standaloneSchema: MetadataBase['schema']; macro: BaseMacro; macroFn: Macro; parser: Record>; response: PossibleResponse; } export interface RouteSchema { body?: unknown; headers?: unknown; query?: unknown; params?: unknown; cookie?: unknown; response?: unknown; } interface OptionalField { [OptionalKind]: 'Optional'; } export type UnwrapSchema = Schema extends undefined ? unknown : Schema extends TSchema ? Schema extends OptionalField ? Partial['static']> : TImport['static'] : Schema extends FastStandardSchemaV1Like ? NonNullable['output'] : Schema extends string ? Schema extends keyof Definitions ? Definitions[Schema] extends TAnySchema ? TImport['static'] : NonNullable['output'] : unknown : unknown; export type UnwrapBodySchema = undefined extends Schema ? unknown : Schema extends TSchema ? Schema extends OptionalField ? Partial['static']> | null : TImport['static'] : Schema extends FastStandardSchemaV1Like ? NonNullable['output'] : Schema extends string ? Schema extends keyof Definitions ? Definitions[Schema] extends TAnySchema ? TImport['static'] : NonNullable['output'] : unknown : unknown; export interface UnwrapRoute, in out Definitions extends DefinitionBase['typebox'] = {}, in out Path extends string = ''> { body: UnwrapBodySchema; headers: UnwrapSchema; query: UnwrapSchema; params: {} extends Schema['params'] ? ResolvePath : {} extends Schema ? ResolvePath : UnwrapSchema; cookie: UnwrapSchema; response: Schema['response'] extends FastAnySchema | string ? { 200: UnwrapSchema extends infer A ? A extends File ? File | ElysiaFile : A : unknown; } : Schema['response'] extends { [status in number]: FastAnySchema | string; } ? { [k in keyof Schema['response']]: UnwrapSchema extends infer A ? A extends File ? File | ElysiaFile : A : unknown; } : unknown | void; } export interface UnwrapGroupGuardRoute, in out Definitions extends DefinitionBase['typebox'] = {}, Path extends string | undefined = undefined> { body: UnwrapBodySchema; headers: UnwrapSchema extends infer A extends Record ? A : undefined; query: UnwrapSchema extends infer A extends Record ? A : undefined; params: UnwrapSchema extends infer A extends Record ? A : Path extends PathParameterLike ? Record, string> : never; cookie: UnwrapSchema extends infer A extends Record ? A : undefined; response: Schema['response'] extends TSchema | string ? UnwrapSchema : Schema['response'] extends { [k in string]: TSchema | string; } ? UnwrapSchema : unknown | void; } export type HookContainer = { checksum?: number; scope?: LifeCycleType; subType?: 'derive' | 'resolve' | 'mapDerive' | 'mapResolve' | (string & {}); fn: T; isAsync?: boolean; hasReturn?: boolean; }; export interface LifeCycleStore { type?: ContentType; start: HookContainer>[]; request: HookContainer>[]; parse: HookContainer>[]; transform: HookContainer>[]; beforeHandle: HookContainer>[]; afterHandle: HookContainer>[]; mapResponse: HookContainer>[]; afterResponse: HookContainer>[]; trace: HookContainer>[]; error: HookContainer>[]; stop: HookContainer>[]; } export type LifeCycleEvent = 'start' | 'request' | 'parse' | 'transform' | 'beforeHandle' | 'afterHandle' | 'response' | 'error' | 'stop'; export type ContentType = MaybeArray<'none' | 'text' | 'json' | 'formdata' | 'urlencoded' | 'arrayBuffer' | 'text/plain' | 'application/json' | 'multipart/form-data' | 'application/x-www-form-urlencoded' | 'application/octet-stream'>; export type HTTPMethod = (string & {}) | 'ACL' | 'BIND' | 'CHECKOUT' | 'CONNECT' | 'COPY' | 'DELETE' | 'GET' | 'HEAD' | 'LINK' | 'LOCK' | 'M-SEARCH' | 'MERGE' | 'MKACTIVITY' | 'MKCALENDAR' | 'MKCOL' | 'MOVE' | 'NOTIFY' | 'OPTIONS' | 'PATCH' | 'POST' | 'PROPFIND' | 'PROPPATCH' | 'PURGE' | 'PUT' | 'REBIND' | 'REPORT' | 'SEARCH' | 'SOURCE' | 'SUBSCRIBE' | 'TRACE' | 'UNBIND' | 'UNLINK' | 'UNLOCK' | 'UNSUBSCRIBE' | 'ALL'; export interface InputSchema { body?: AnySchema | Name; headers?: AnySchema | Name; query?: AnySchema | Name; params?: AnySchema | Name; cookie?: AnySchema | Name; response?: AnySchema | { [status in number]: AnySchema; } | Name | { [status in number]: Name | AnySchema; }; } type PathParameterLike = `${string}/${':' | '*'}${string}`; export type IntersectIfObject = A extends Record ? B extends Record ? A & B : A : B extends Record ? B : A; export interface IntersectIfObjectSchema { body: IntersectIfObject; headers: IntersectIfObject; query: IntersectIfObject; params: IntersectIfObject; cookie: IntersectIfObject; response: IntersectIfObject; } export type MergeSchema = {} extends A ? Path extends PathParameterLike ? Omit & { params: ResolvePath; } : B : {} extends B ? Path extends PathParameterLike ? Omit & { params: ResolvePath; } : A : { body: undefined extends A['body'] ? B['body'] : A['body']; headers: undefined extends A['headers'] ? B['headers'] : A['headers']; query: undefined extends A['query'] ? B['query'] : A['query']; params: IsNever extends true ? IsNever extends true ? ResolvePath : B['params'] : IsNever extends true ? A['params'] : Prettify>; cookie: undefined extends A['cookie'] ? B['cookie'] : A['cookie']; response: {} extends A['response'] ? {} extends B['response'] ? {} : B['response'] : {} extends B['response'] ? A['response'] : A['response'] & Omit; }; export interface MergeStandaloneSchema { body: undefined extends A['body'] ? undefined extends B['body'] ? undefined : B['body'] : undefined extends B['body'] ? A['body'] : Prettify; headers: undefined extends A['headers'] ? undefined extends B['headers'] ? undefined : B['headers'] : undefined extends B['headers'] ? A['headers'] : Prettify; query: undefined extends A['query'] ? undefined extends B['query'] ? undefined : B['query'] : undefined extends B['query'] ? A['query'] : Prettify; params: IsNever extends true ? IsNever extends true ? ResolvePath : B['params'] : IsNever extends true ? A['params'] : Prettify; cookie: undefined extends A['cookie'] ? undefined extends B['cookie'] ? undefined : B['cookie'] : undefined extends B['cookie'] ? A['cookie'] : Prettify; response: {} extends A['response'] ? {} extends B['response'] ? {} : B['response'] : {} extends B['response'] ? A['response'] : Prettify; } export type Handler = (context: Context) => MaybePromise<{} extends Route['response'] ? unknown : Route['response'][keyof Route['response']]>; export type IsAny = 0 extends 1 & T ? true : false; export type Replace = IsAny extends true ? Original : Original extends Record ? { [K in keyof Original]: Original[K] extends Target ? With : Original[K]; } : Original extends Target ? With : Original; export type CoExist = IsAny extends true ? Original : Original extends Record ? { [K in keyof Original]: Original[K] extends Target ? Original[K] | With : Original[K]; } : Original extends Target ? Original | With : Original; export type MacroContextBlacklistKey = 'type' | 'detail' | 'parse' | 'transform' | 'resolve' | 'beforeHandle' | 'afterHandle' | 'mapResponse' | 'afterResponse' | 'error' | 'tags' | keyof RouteSchema; type ReturnTypeIfPossible = false extends Enabled ? {} : T extends (...a: any) => infer R ? R : T; type AnyElysiaCustomStatusResponse = ElysiaCustomStatusResponse; type FunctionArrayReturnType = any[] extends T ? never : T extends any[] ? _FunctionArrayReturnType : Awaited>; type _FunctionArrayReturnType = T extends [ infer Fn, ...infer Rest ] ? _FunctionArrayReturnType> extends infer A ? IsNever extends true ? Carry : A | Carry : Carry> : Carry; type FunctionArrayReturnTypeNonNullable = any[] extends T ? never : T extends any[] ? _FunctionArrayReturnTypeNonNullable : NonNullable>>; type _FunctionArrayReturnTypeNonNullable = T extends [ infer Fn, ...infer Rest ] ? _FunctionArrayReturnTypeNonNullable>> extends infer A ? IsNever extends true ? Carry : A | Carry : Carry> : Carry; type ExtractResolveFromMacro = IsNever extends true ? {} : A extends AnyElysiaCustomStatusResponse ? A : Exclude extends infer A ? IsAny extends true ? {} : A : {}; type ExtractOnlyResponseFromMacro = IsNever extends true ? {} : Extract extends infer A ? IsNever extends true ? {} : { return: MergeResponseStatus; } : {}; type MergeResponseStatus = { [status in keyof UnionToIntersect ? { [A in Status]: 1; } : never>]: Extract['response'] extends infer Value ? IsAny extends true ? InvertedStatusMap[status] : Value : never; }; type MergeAllStatus = { [K in T extends any ? keyof T : never]: T extends Record ? V : never; }; type ExtractAllResponseFromMacro = IsNever extends true ? {} : { return: MergeResponseStatus & (Exclude extends infer A ? IsAny extends true ? {} : IsNever extends true ? {} : NonNullable extends A ? {} : undefined extends A ? {} : { 200: A; } : {}); }; type FlattenMacroResponse = T extends object ? '_' extends keyof T ? MergeFlattenMacroResponse, FlattenMacroResponse>> : T : T; type MergeFlattenMacroResponse = { [K in keyof A | keyof B]: K extends keyof A ? K extends keyof B ? A[K] | B[K] : A[K] : K extends keyof B ? B[K] : never; }; type UnionMacroContext = UnionToIntersect<{ [K in Exclude]: A[K]; }> & { return: { _: A['return']; }; }; export type MacroToContext = Prettify>, Definitions, R> extends infer A ? { [K in Exclude]: UnionToIntersect; } & Prettify<{ return: FlattenMacroResponse; }> : {}>; type InnerMacroToContext = {} extends SelectedMacro ? {} : R['length'] extends 15 ? {} : UnionMacroContext<{ [key in keyof SelectedMacro]: ReturnTypeIfPossible extends infer Value ? { resolve: ExtractResolveFromMacro, AnyElysiaCustomStatusResponse>, Record>>; } & UnwrapMacroSchema & ExtractAllResponseFromMacro> & ExtractAllResponseFromMacro> & ExtractAllResponseFromMacro> & ExtractOnlyResponseFromMacro> & InnerMacroToContext>, Definitions, [ ...R, 1 ]> : {}; }[keyof SelectedMacro]>; type UnwrapMacroSchema>, Definitions extends DefinitionBase['typebox'] = {}> = UnwrapRoute<{ body: 'body' extends keyof T ? T['body'] : undefined; headers: 'headers' extends keyof T ? T['headers'] : undefined; query: 'query' extends keyof T ? T['query'] : undefined; params: 'params' extends keyof T ? T['params'] : undefined; cookie: 'cookie' extends keyof T ? T['cookie'] : undefined; response: 'response' extends keyof T ? T['response'] : undefined; }, Definitions>; export type SimplifyToSchema> = IsUnknown extends false ? _SimplifyToSchema : IsUnknown extends false ? _SimplifyToSchema : IsUnknown extends false ? _SimplifyToSchema : IsUnknown extends false ? _SimplifyToSchema : IsUnknown extends false ? _SimplifyToSchema : IsUnknown extends false ? _SimplifyToSchema : {}; export type _SimplifyToSchema> = Omit<{ body: T['body']; headers: T['headers']; query: T['query']; params: T['params']; cookie: T['cookie']; response: T['response']; }, ('body' extends keyof T ? never : 'body') | ('headers' extends keyof T ? never : 'headers') | ('query' extends keyof T ? never : 'query') | ('params' extends keyof T ? never : 'params') | ('cookie' extends keyof T ? never : 'cookie') | ('response' extends keyof T ? never : 'response')>; type InlineHandlerResponse = { [Status in keyof Route]: ElysiaCustomStatusResponse; }[keyof Route]; type InlineResponse = string | number | boolean | Record | Response | AnyElysiaCustomStatusResponse | ElysiaFile | Record | BunHTMLBundlelike; type LastOf = UnionToIntersect T : never> extends () => infer R ? R : never; type Push = [...T, V]; type TuplifyUnion, N = [T] extends [never] ? true : false> = true extends N ? [] : Push>, L>; export type Tuple = TuplifyUnion['length'] extends A['length'] ? [...A] : Tuple; export type InlineHandler; } = { response: {}; return: {}; resolve: {}; }> = MaybePromise | ((context: Context) => MaybePromise | MaybePromise<{} extends Route['response'] ? unknown : (Route['response'] extends { 200: any; } ? Route['response'][200] | ElysiaCustomStatusResponse<200, Route['response'][200], 200> | Generator | AsyncGenerator : unknown) | Route['response'][keyof Route['response']] | InlineHandlerResponse>); export type InlineHandlerNonMacro = MaybePromise | ((context: Context) => MaybePromise | MaybePromise<{} extends Route['response'] ? unknown : (Route['response'] extends { 200: any; } ? Route['response'][200] | ElysiaCustomStatusResponse<200, Route['response'][200], 200> | Generator | AsyncGenerator : unknown) | Route['response'][keyof Route['response']] | InlineHandlerResponse>); export type OptionalHandler = (context: Context) => MaybePromise<{} extends Route['response'] ? unknown : Route['response'][keyof Route['response']] | InlineHandlerResponse | void>; export type AfterHandler = (context: Context & { responseValue: {} extends Route['response'] ? unknown : Route['response'][keyof Route['response']]; /** * @deprecated use `context.responseValue` instead */ response: {} extends Route['response'] ? unknown : Route['response'][keyof Route['response']]; }) => MaybePromise<{} extends Route['response'] ? unknown : Route['response'][keyof Route['response']] | InlineHandlerResponse | void>; export type MapResponse = (context: Context & { responseValue: {} extends Route['response'] ? unknown : Route['response'][keyof Route['response']]; /** * @deprecated use `context.responseValue` instead */ response: {} extends Route['response'] ? unknown : Route['response'][keyof Route['response']]; }) => MaybePromise; export type VoidHandler = (context: Context) => MaybePromise; export type TransformHandler = (context: Context & { resolve: {}; }, Path>) => MaybePromise; export type BodyHandler = (context: Context, /** * @deprecated * * use `context.contentType` instead * * @example * ```ts * new Elysia() * .onParse(({ contentType, request }) => { * if (contentType === 'application/json') * return request.json() * }) * ``` */ contentType: string) => MaybePromise; export type PreHandler = (context: PreContext) => MaybePromise | void>; export type AfterResponseHandler = (context: Context & { responseValue: {} extends Route['response'] ? unknown : Route['response'][keyof Route['response']]; /** * @deprecated use `context.responseValue` instead */ response: {} extends Route['response'] ? unknown : Route['response'][keyof Route['response']] | InlineHandlerResponse; }) => MaybePromise; export type GracefulHandler = (data: Instance) => any; export type ErrorHandler = {}, in out Route extends RouteSchema = {}, in out Singleton extends SingletonBase = { decorator: {}; store: {}; derive: {}; resolve: {}; }, in out Ephemeral extends EphemeralType = { derive: {}; resolve: {}; schema: {}; standaloneSchema: {}; response: {}; }, in out Volatile extends EphemeralType = { derive: {}; resolve: {}; schema: {}; standaloneSchema: {}; response: {}; }> = (context: ErrorContext & (Prettify<{ request: Request; code: 'UNKNOWN'; error: Readonly; set: Context['set']; } & Partial> | Prettify<{ request: Request; code: 'VALIDATION'; error: Readonly; set: Context['set']; } & Singleton['derive'] & Ephemeral['derive'] & Volatile['derive'] & NeverKey> | Prettify<{ request: Request; code: 'NOT_FOUND'; error: Readonly; set: Context['set']; } & NeverKey> | Prettify<{ request: Request; code: 'PARSE'; error: Readonly; set: Context['set']; } & NeverKey> | Prettify<{ request: Request; code: 'INTERNAL_SERVER_ERROR'; error: Readonly; set: Context['set']; } & Partial> | Prettify<{ request: Request; code: 'INVALID_COOKIE_SIGNATURE'; error: Readonly; set: Context['set']; } & NeverKey> | Prettify<{ request: Request; code: 'INVALID_FILE_TYPE'; error: Readonly; set: Context['set']; } & Singleton['derive'] & Ephemeral['derive'] & Volatile['derive'] & NeverKey> | Prettify<{ request: Request; code: number; error: Readonly>; set: Context['set']; } & Partial> | Prettify<{ [K in keyof T]: { request: Request; code: K; error: Readonly; set: Context['set']; }; }[keyof T] & Partial>)) => any | Promise; export interface DocumentDecoration extends Partial { /** * Pass `true` to hide route from OpenAPI/swagger document * */ hide?: boolean; } export type ResolveHandler | AnyElysiaCustomStatusResponse | void = Record | AnyElysiaCustomStatusResponse | void> = (context: Context) => MaybePromise; export type ResolveReturnType> = any[] extends T ? {} : T extends any[] ? _ResolveReturnTypeArray : Exclude>, AnyElysiaCustomStatusResponse> extends infer Value extends Record ? Value : {}; type _ResolveReturnTypeArray = T extends [ infer Fn, ...infer Rest ] ? Exclude>, AnyElysiaCustomStatusResponse> extends infer Value extends Record ? _ResolveReturnTypeArray : _ResolveReturnTypeArray : Prettify; export type AnyLocalHook = LocalHook; export interface BaseHookLifeCycle { detail?: DocumentDecoration; /** * Short for 'Content-Type' * * Available: * - 'none': do not parse body * - 'text' / 'text/plain': parse body as string * - 'json' / 'application/json': parse body as json * - 'formdata' / 'multipart/form-data': parse body as form-data * - 'urlencoded' / 'application/x-www-form-urlencoded: parse body as urlencoded * - 'arraybuffer': parse body as readable stream */ parse?: MaybeArray | ContentType | Parser>; /** * Transform context's value */ transform?: MaybeArray>; /** * Execute before main handler */ beforeHandle?: MaybeArray>; /** * Execute after main handler */ afterHandle?: MaybeArray>; /** * Execute after main handler */ mapResponse?: MaybeArray>; /** * Execute after response is sent */ afterResponse?: MaybeArray>; /** * Catch error */ error?: MaybeArray>; tags?: DocumentDecoration['tags']; } export type CreateDecorator = {} extends Ephemeral ? {} extends Volatile ? Singleton : Singleton & Volatile : {} extends Volatile ? Singleton & Ephemeral : Singleton & Ephemeral & Volatile; export type AnyBaseHookLifeCycle = BaseHookLifeCycle; export type NonResolvableMacroKey = keyof AnyBaseHookLifeCycle | keyof InputSchema | 'resolve'; interface RouteSchemaWithResolvedMacro extends RouteSchema { response: PossibleResponse; return: PossibleResponse; resolve: Record; } export type LocalHook = { detail?: DocumentDecoration; /** * Short for 'Content-Type' * * Available: * - 'none': do not parse body * - 'text' / 'text/plain': parse body as string * - 'json' / 'application/json': parse body as json * - 'formdata' / 'multipart/form-data': parse body as form-data * - 'urlencoded' / 'application/x-www-form-urlencoded: parse body as urlencoded * - 'arraybuffer': parse body as readable stream */ parse?: MaybeArray | ContentType | Parser>; /** * Transform context's value */ transform?: MaybeArray>; /** * Execute before main handler */ beforeHandle?: MaybeArray>; /** * Execute after main handler */ afterHandle?: MaybeArray>; /** * Execute after main handler */ mapResponse?: MaybeArray>; /** * Execute after response is sent */ afterResponse?: MaybeArray>; /** * Catch error */ error?: MaybeArray>; tags?: DocumentDecoration['tags']; } & (Input extends any ? Input : Prettify); export type GuardLocalHook>, AfterHandle extends MaybeArray>, ErrorHandle extends MaybeArray>, GuardType extends GuardSchemaType = 'standalone', AsType extends LifeCycleType = 'local'> = (Input extends any ? Input : Prettify) & { /** * @default 'override' */ as?: AsType; /** * @default 'standalone' * @since 1.3.0 */ schema?: GuardType; detail?: DocumentDecoration; /** * Short for 'Content-Type' * * Available: * - 'none': do not parse body * - 'text' / 'text/plain': parse body as string * - 'json' / 'application/json': parse body as json * - 'formdata' / 'multipart/form-data': parse body as form-data * - 'urlencoded' / 'application/x-www-form-urlencoded: parse body as urlencoded * - 'arraybuffer': parse body as readable stream */ parse?: MaybeArray | ContentType | Parser>; /** * Transform context's value */ transform?: MaybeArray>; /** * Execute before main handler */ beforeHandle?: BeforeHandle; /** * Execute after main handler */ afterHandle?: AfterHandle; /** * Execute after main handler */ mapResponse?: MaybeArray>; /** * Execute after response is sent */ afterResponse?: MaybeArray>; /** * Catch error */ error?: ErrorHandle; tags?: DocumentDecoration['tags']; }; export type ComposedHandler = (context: Context) => MaybePromise; export interface InternalRoute { method: HTTPMethod; path: string; composed: ComposedHandler | Response | null; compile(): ComposedHandler; handler: Handler; hooks: AnyLocalHook; websocket?: AnyWSLocalHook; } export interface SchemaValidator { createBody?(): ElysiaTypeCheck; createHeaders?(): ElysiaTypeCheck; createQuery?(): ElysiaTypeCheck; createParams?(): ElysiaTypeCheck; createCookie?(): ElysiaTypeCheck; createResponse?(): Record>; body?: ElysiaTypeCheck; headers?: ElysiaTypeCheck; query?: ElysiaTypeCheck; params?: ElysiaTypeCheck; cookie?: ElysiaTypeCheck; response?: Record>; } export type AddPrefix = { [K in keyof T as Prefix extends string ? `${Prefix}${K & string}` : K]: T[K]; }; export type AddPrefixCapitalize = { [K in keyof T as `${Prefix}${Capitalize}`]: T[K]; }; export type AddSuffix = { [K in keyof T as `${K & string}${Suffix}`]: T[K]; }; export type AddSuffixCapitalize = { [K in keyof T as `${K & string}${Capitalize}`]: T[K]; }; export interface Checksum { name?: string; seed?: unknown; checksum: number; stack?: string; routes?: InternalRoute[]; decorators?: SingletonBase['decorator']; store?: SingletonBase['store']; error?: DefinitionBase['error']; dependencies?: Record; derive?: { fn: string; stack: string; }[]; resolve?: { fn: string; stack: string; }[]; } export type BaseMacro = Record; export type MaybeValueOrVoidFunction = T | ((...a: any) => void | T); export interface MacroProperty = {}> { /** * Deduplication similar to Elysia.constructor.seed */ seed?: unknown; parse?: MaybeArray>; transform?: MaybeArray>; beforeHandle?: MaybeArray>; afterHandle?: MaybeArray>; error?: MaybeArray>; mapResponse?: MaybeArray>; afterResponse?: MaybeArray>; resolve?: MaybeArray>; detail?: DocumentDecoration; /** * Introspect hook option for documentation generation or analysis * * @param option */ introspect?(option: Prettify): unknown; } export interface Macro = {}> { [K: keyof any]: MaybeValueOrVoidFunction>; } export type MaybeFunction = T | ((...args: any[]) => T); export type MacroToProperty> = Prettify<{ [K in keyof T]: T[K] extends Function ? T[K] extends (a: infer Params) => any ? Params : boolean : boolean; }>; interface MacroOptions { insert?: 'before' | 'after'; stack?: 'global' | 'local'; } export interface MacroManager = {}> { body(schema: InputSchema['body']): unknown; headers(schema: InputSchema['headers']): unknown; query(schema: InputSchema['query']): unknown; params(schema: InputSchema['params']): unknown; cookie(schema: InputSchema['cookie']): unknown; response(schema: InputSchema['response']): unknown; detail(detail: DocumentDecoration): unknown; onParse(fn: MaybeArray>): unknown; onParse(options: MacroOptions, fn: MaybeArray>): unknown; onTransform(fn: MaybeArray>): unknown; onTransform(options: MacroOptions, fn: MaybeArray>): unknown; onBeforeHandle(fn: MaybeArray>): unknown; onBeforeHandle(options: MacroOptions, fn: MaybeArray>): unknown; onAfterHandle(fn: MaybeArray>): unknown; onAfterHandle(options: MacroOptions, fn: MaybeArray>): unknown; onError(fn: MaybeArray>): unknown; onError(options: MacroOptions, fn: MaybeArray>): unknown; mapResponse(fn: MaybeArray>): unknown; mapResponse(options: MacroOptions, fn: MaybeArray>): unknown; onAfterResponse(fn: MaybeArray>): unknown; onAfterResponse(options: MacroOptions, fn: MaybeArray>): unknown; events: { global: Partial; local: Partial; }; } type _CreateEden = {}> = Path extends `${infer Start}/${infer Rest}` ? { [x in Start]: _CreateEden; } : Path extends '' ? Property : { [x in Path]: Property; }; export type CreateEden = {}> = Path extends `/${infer Rest}` ? _CreateEden : Path extends '' | '/' ? Property : _CreateEden; export interface EmptyRouteSchema { body: unknown; headers: unknown; query: unknown; params: {}; cookie: unknown; response: unknown; } export interface UnknownRouteSchema { body: unknown; headers: { [name: string]: string | undefined; }; query: { [name: string]: string | undefined; }; params: Params; cookie: {}; response: unknown; } type Extract200 = T extends AnyElysiaCustomStatusResponse ? Exclude | Extract>['response'] : T; export type IsUnknown = [unknown] extends [T] ? IsAny extends true ? false : true : false; export type ValueToResponseSchema = ExtractErrorFromHandle & (Extract200 extends infer R200 ? undefined extends R200 ? {} : IsNever extends true ? {} : { 200: R200; } : {}); export type ValueOrFunctionToResponseSchema = T extends (...a: any) => MaybePromise ? ValueToResponseSchema : ValueToResponseSchema; export type ElysiaHandlerToResponseSchema = Prettify MaybePromise ? ValueToResponseSchema> : {}>; export type ElysiaHandlerToResponseSchemas = Handle extends [infer Current, ...infer Rest] ? ElysiaHandlerToResponseSchemas, Carry>> : Prettify; export type ElysiaHandlerToResponseSchemaAmbiguous> = MaybeArray<(...a: any) => any> extends Schemas ? {} : Schemas extends Function ? ElysiaHandlerToResponseSchema : Schemas extends Function[] ? ElysiaHandlerToResponseSchemas : {}; type ReconcileStatus, in out B extends Record> = { [K in keyof A | keyof B]: K extends keyof A ? A[K] : B[K]; }; export type ComposeElysiaResponse = ReconcileStatus, Possibility & (EmptyRouteSchema extends Pick ? {} : { 422: { type: 'validation'; on: string; summary?: string; message?: string; found?: unknown; property?: string; expected?: string; }; })>>; export type ExtractErrorFromHandle = { [ErrorResponse in Extract as ErrorResponse extends AnyElysiaCustomStatusResponse ? ErrorResponse['code'] : never]: Prettify; }; export type MergeElysiaInstances = Instances extends [ infer Current extends AnyElysia, ...infer Rest extends AnyElysia[] ] ? MergeElysiaInstances)> : Elysia; derive: Singleton['derive']; resolve: Singleton['resolve']; }, Definitions, Metadata, Routes, Ephemeral, Volatile>; export type LifeCycleType = 'global' | 'local' | 'scoped'; export type GuardSchemaType = 'override' | 'standalone'; type PartialIf = Condition extends true ? Partial : T; export type ExcludeElysiaResponse = PartialIf, AnyElysiaCustomStatusResponse> extends infer A ? IsNever extends true ? {} : // Intersect all union and fallback never to {} A & {} : {}, undefined extends Awaited ? true : false>; /** * @deprecated */ export type InferContext = Context, T['~Singleton'] & { derive: T['~Ephemeral']['derive'] & T['~Volatile']['derive']; resolve: T['~Ephemeral']['resolve'] & T['~Volatile']['resolve']; }, Path>; /** * @deprecated */ export type InferHandler = InlineHandler, T['~Singleton'] & { derive: T['~Ephemeral']['derive'] & T['~Volatile']['derive']; resolve: T['~Ephemeral']['resolve'] & T['~Volatile']['resolve']; }>; export interface ModelValidatorError extends ValueError { summary: string; } export interface ModelValidator extends TypeCheck { schema: T; parse(a: T): T; safeParse(a: T): { success: true; data: T; error: null; } | { success: true; data: null; error: string; errors: ModelValidatorError[]; }; } export type UnionToIntersect = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never; export type ContextAppendType = 'append' | 'override'; export type HigherOrderFunction Function = (...arg: unknown[]) => Function> = (fn: T, request: Request) => ReturnType; type SetContentType = 'application/octet-stream' | 'application/vnd.ms-fontobject' | 'application/epub+zip' | 'application/gzip' | 'application/json' | 'application/ld+json' | 'application/ogg' | 'application/pdf' | 'application/rtf' | 'application/wasm' | 'application/xhtml+xml' | 'application/xml' | 'application/zip' | 'text/css' | 'text/csv' | 'text/calendar' | 'text/event-stream' | 'text/html' | 'text/javascript' | 'text/plain' | 'text/xml' | 'image/avif' | 'image/bmp' | 'image/gif' | 'image/x-icon' | 'image/jpeg' | 'image/png' | 'image/svg+xml' | 'image/tiff' | 'image/webp' | 'multipart/mixed' | 'multipart/alternative' | 'multipart/form-data' | 'audio/aac' | 'audio/x-midi' | 'audio/mpeg' | 'audio/ogg' | 'audio/opus' | 'audio/webm' | 'video/x-msvideo' | 'video/quicktime' | 'video/x-ms-wmv' | 'video/x-msvideo' | 'video/x-flv' | 'video/av1' | 'video/mp4' | 'video/mpeg' | 'video/ogg' | 'video/mp2t' | 'video/webm' | 'video/3gpp' | 'video/3gpp2' | 'font/otf' | 'font/ttf' | 'font/woff' | 'font/woff2' | 'model/gltf+json' | 'model/gltf-binary'; export type HTTPHeaders = Record & { 'www-authenticate'?: string; authorization?: string; 'proxy-authenticate'?: string; 'proxy-authorization'?: string; age?: string; 'cache-control'?: string; 'clear-site-data'?: string; expires?: string; 'no-vary-search'?: string; pragma?: string; 'last-modified'?: string; etag?: string; 'if-match'?: string; 'if-none-match'?: string; 'if-modified-since'?: string; 'if-unmodified-since'?: string; vary?: string; connection?: string; 'keep-alive'?: string; accept?: string; 'accept-encoding'?: string; 'accept-language'?: string; expect?: string; 'max-forwards'?: string; cookie?: string; 'set-cookie'?: string | string[]; 'access-control-allow-origin'?: string; 'access-control-allow-credentials'?: string; 'access-control-allow-headers'?: string; 'access-control-allow-methods'?: string; 'access-control-expose-headers'?: string; 'access-control-max-age'?: string; 'access-control-request-headers'?: string; 'access-control-request-method'?: string; origin?: string; 'timing-allow-origin'?: string; 'content-disposition'?: string; 'content-length'?: string | number; 'content-type'?: SetContentType | (string & {}); 'content-encoding'?: string; 'content-language'?: string; 'content-location'?: string; forwarded?: string; via?: string; location?: string; refresh?: string; allow?: string; server?: 'Elysia' | (string & {}); 'accept-ranges'?: string; range?: string; 'if-range'?: string; 'content-range'?: string; 'content-security-policy'?: string; 'content-security-policy-report-only'?: string; 'cross-origin-embedder-policy'?: string; 'cross-origin-opener-policy'?: string; 'cross-origin-resource-policy'?: string; 'expect-ct'?: string; 'permission-policy'?: string; 'strict-transport-security'?: string; 'upgrade-insecure-requests'?: string; 'x-content-type-options'?: string; 'x-frame-options'?: string; 'x-xss-protection'?: string; 'last-event-id'?: string; 'ping-from'?: string; 'ping-to'?: string; 'report-to'?: string; te?: string; trailer?: string; 'transfer-encoding'?: string; 'alt-svg'?: string; 'alt-used'?: string; date?: string; dnt?: string; 'early-data'?: string; 'large-allocation'?: string; link?: string; 'retry-after'?: string; 'service-worker-allowed'?: string; 'source-map'?: string; upgrade?: string; 'x-dns-prefetch-control'?: string; 'x-forwarded-for'?: string; 'x-forwarded-host'?: string; 'x-forwarded-proto'?: string; 'x-powered-by'?: 'Elysia' | (string & {}); 'x-request-id'?: string; 'x-requested-with'?: string; 'x-robots-tag'?: string; 'x-ua-compatible'?: string; }; export type JoinPath = B extends `/${string}` ? `${A}${B}` : `${A}/${B}`; export type UnwrapTypeModule> = Module extends TModule ? Type : {}; export type MergeTypeModule, B extends TModule> = TModule & UnwrapTypeModule>>; export type SSEPayload = { /** id of the event */ id?: string | number | null; /** event name */ event?: Event; /** retry in millisecond */ retry?: number; /** data to send */ data?: Data; }; export type UnionResponseStatus = {} extends A ? B : {} extends B ? A : { [key in keyof A | keyof B]: key extends keyof A ? key extends keyof B ? A[key] | B[key] : A[key] : key extends keyof B ? B[key] : never; }; export type CreateEdenResponse = RouteSchema extends MacroContext ? { body: Schema['body']; params: IsNever extends true ? ResolvePath : Schema['params']; query: Schema['query']; headers: Schema['headers']; response: Prettify; } : { body: Prettify; params: IsNever extends true ? ResolvePath : Prettify; query: Prettify; headers: Prettify; response: Prettify; }; export interface Router { '~http': Memoirist<{ compile: Function; handler?: ComposedHandler; }> | undefined; get http(): Memoirist<{ compile: Function; handler?: ComposedHandler; }>; '~dynamic': Memoirist | undefined; get dynamic(): Memoirist; static: { [path: string]: { [method: string]: number; }; }; response: { [path: string]: MaybePromise | { [method: string]: MaybePromise; }; }; history: InternalRoute[]; } export type ModelsToTypes> = { [K in keyof T]: UnwrapSchema; }; export {};