Socket
Socket
Sign inDemoInstall

elysia

Package Overview
Dependencies
Maintainers
1
Versions
408
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

elysia - npm Package Compare versions

Comparing version 1.1.0-exp.0 to 1.1.0-exp.1

3

.eslintrc.json

@@ -27,5 +27,6 @@ {

"no-extra-semi": "off",
"sonarjs/cognitive-complexity": "off"
"sonarjs/cognitive-complexity": "off",
"sonarjs/no-all-duplicated-branches": "off"
},
"ignorePatterns": ["example/*", "test/**/*"]
}

@@ -8,2 +8,3 @@ import { type Elysia } from '.';

export declare const hasTransform: (schema: TAnySchema) => any;
export declare const isAsyncName: (v: Function | HookContainer) => boolean;
export declare const isAsync: (v: Function | HookContainer) => boolean;

@@ -10,0 +11,0 @@ export declare const composeHandler: ({ app, path, method, localHook, hooks, validator, handler, allowMeta, inference }: {

@@ -1,2 +0,1 @@

/// <reference types="node" />
import type { StatusMap, InvertedStatusMap, redirect as Redirect } from './utils';

@@ -3,0 +2,0 @@ import type { Cookie, ElysiaCookie } from './cookies';

@@ -146,6 +146,6 @@ import type { Context } from './context';

}
export declare const createCookieJar: (set: Context['set'], store: Record<string, ElysiaCookie>, initial?: Partial<ElysiaCookie>) => Record<string, Cookie<unknown>>;
export declare const parseCookie: (set: Context['set'], cookieString?: string | null, { secrets, sign, ...initial }?: CookieOptions & {
export declare const createCookieJar: (set: Context["set"], store: Record<string, ElysiaCookie>, initial?: Partial<ElysiaCookie>) => Record<string, Cookie<unknown>>;
export declare const parseCookie: (set: Context["set"], cookieString?: string | null, { secrets, sign, ...initial }?: CookieOptions & {
sign?: true | string | string[];
}) => Promise<Record<string, Cookie<unknown>>>;
export {};

@@ -1,2 +0,1 @@

/// <reference types="node" />
import type { Elysia } from '.';

@@ -3,0 +2,0 @@ import { ElysiaErrors } from './error';

import type { TSchema } from '@sinclair/typebox';
import type { TypeCheck } from '@sinclair/typebox/compiler';
import type { TypeCheck, ValueError } from '@sinclair/typebox/compiler';
import { StatusMap } from './utils';
export declare const ERROR_CODE: unique symbol;
export type ERROR_CODE = typeof ERROR_CODE;
export declare const ELYSIA_RESPONSE: unique symbol;

@@ -8,3 +10,3 @@ export type ELYSIA_RESPONSE = typeof ELYSIA_RESPONSE;

export type ElysiaErrors = InternalServerError | NotFoundError | ParseError | ValidationError | InvalidCookieSignature;
export declare const error: <const Code extends number | "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required", const T = Code extends 100 | 101 | 102 | 103 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 300 | 301 | 302 | 303 | 304 | 307 | 308 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ? {
export declare const error: <const Code extends number | keyof StatusMap, const T = Code extends 100 | 101 | 102 | 103 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 300 | 301 | 302 | 303 | 304 | 307 | 308 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ? {
readonly 100: "Continue";

@@ -70,3 +72,3 @@ readonly 101: "Switching Protocols";

readonly 511: "Network Authentication Required";
}[Code] : Code, const Status extends Code extends "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required" ? {
}[Code] : Code, const Status extends Code extends keyof StatusMap ? StatusMap[Code] : Code = Code extends "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required" ? {
readonly Continue: 100;

@@ -132,67 +134,6 @@ readonly 'Switching Protocols': 101;

readonly 'Network Authentication Required': 511;
}[Code] : Code = Code extends "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required" ? {
readonly Continue: 100;
readonly 'Switching Protocols': 101;
readonly Processing: 102;
readonly 'Early Hints': 103;
readonly OK: 200;
readonly Created: 201;
readonly Accepted: 202;
readonly 'Non-Authoritative Information': 203;
readonly 'No Content': 204;
readonly 'Reset Content': 205;
readonly 'Partial Content': 206;
readonly 'Multi-Status': 207;
readonly 'Already Reported': 208;
readonly 'Multiple Choices': 300;
readonly 'Moved Permanently': 301;
readonly Found: 302;
readonly 'See Other': 303;
readonly 'Not Modified': 304;
readonly 'Temporary Redirect': 307;
readonly 'Permanent Redirect': 308;
readonly 'Bad Request': 400;
readonly Unauthorized: 401;
readonly 'Payment Required': 402;
readonly Forbidden: 403;
readonly 'Not Found': 404;
readonly 'Method Not Allowed': 405;
readonly 'Not Acceptable': 406;
readonly 'Proxy Authentication Required': 407;
readonly 'Request Timeout': 408;
readonly Conflict: 409;
readonly Gone: 410;
readonly 'Length Required': 411;
readonly 'Precondition Failed': 412;
readonly 'Payload Too Large': 413;
readonly 'URI Too Long': 414;
readonly 'Unsupported Media Type': 415;
readonly 'Range Not Satisfiable': 416;
readonly 'Expectation Failed': 417;
readonly "I'm a teapot": 418;
readonly 'Misdirected Request': 421;
readonly 'Unprocessable Content': 422;
readonly Locked: 423;
readonly 'Failed Dependency': 424;
readonly 'Too Early': 425;
readonly 'Upgrade Required': 426;
readonly 'Precondition Required': 428;
readonly 'Too Many Requests': 429;
readonly 'Request Header Fields Too Large': 431;
readonly 'Unavailable For Legal Reasons': 451;
readonly 'Internal Server Error': 500;
readonly 'Not Implemented': 501;
readonly 'Bad Gateway': 502;
readonly 'Service Unavailable': 503;
readonly 'Gateway Timeout': 504;
readonly 'HTTP Version Not Supported': 505;
readonly 'Variant Also Negotiates': 506;
readonly 'Insufficient Storage': 507;
readonly 'Loop Detected': 508;
readonly 'Not Extended': 510;
readonly 'Network Authentication Required': 511;
}[Code] : Code>(code: Code, response?: T) => {
[ELYSIA_RESPONSE]: Status;
response: T;
_type: { [ERROR_CODE in Status]: T; };
[ELYSIA_RESPONSE]: Status;
};

@@ -210,6 +151,6 @@ export declare class InternalServerError extends Error {

export declare class ParseError extends Error {
body?: unknown;
body?: unknown | undefined;
code: string;
status: number;
constructor(message?: string, body?: unknown);
constructor(message?: string, body?: unknown | undefined);
}

@@ -222,2 +163,10 @@ export declare class InvalidCookieSignature extends Error {

}
export declare const mapValueError: (error: ValueError) => {
summary: string;
type: import("@sinclair/typebox/value").ValueErrorType;
schema: TSchema;
path: string;
value: unknown;
message: string;
};
export declare class ValidationError extends Error {

@@ -230,3 +179,10 @@ type: string;

constructor(type: string, validator: TSchema | TypeCheck<any>, value: unknown);
get all(): any[];
get all(): {
summary: string;
type: import("@sinclair/typebox/value").ValueErrorType;
schema: TSchema;
path: string;
value: unknown;
message: string;
}[];
static simplifyModel(validator: TSchema | TypeCheck<any>): any;

@@ -233,0 +189,0 @@ get model(): any;

@@ -1,10 +0,8 @@

/// <reference types="node" />
/// <reference types="bun-types" />
import type { Context } from './context';
export declare const isNotEmpty: (obj?: Object) => boolean;
export declare const parseSetCookies: (headers: Headers, setCookie: string[]) => Headers;
export declare const serializeCookie: (cookies: Context['set']['cookie']) => string | string[] | undefined;
export declare const mapResponse: (response: unknown, set: Context['set'], request?: Request) => Response;
export declare const mapEarlyResponse: (response: unknown, set: Context['set'], request?: Request) => Response | undefined;
export declare const serializeCookie: (cookies: Context["set"]["cookie"]) => string | string[] | undefined;
export declare const mapResponse: (response: unknown, set: Context["set"], request?: Request) => Response;
export declare const mapEarlyResponse: (response: unknown, set: Context["set"], request?: Request) => Response | undefined;
export declare const mapCompactResponse: (response: unknown, request?: Request) => Response;
export declare const errorToResponse: (error: Error, set?: Context['set']) => import("undici-types").Response;
export declare const errorToResponse: (error: Error, set?: Context["set"]) => import("undici-types").Response;
import type { Handler, HookContainer, LifeCycleStore } from './types';
export declare namespace Sucrose {
interface Inference {
queries: string[];
unknownQueries: boolean;
query: boolean;

@@ -77,3 +75,2 @@ headers: boolean;

export declare const removeDefaultParameter: (parameter: string) => string;
export declare const validateInferencedQueries: (queries: string[]) => boolean;
export declare const sucrose: (lifeCycle: Sucrose.LifeCycle, inference?: Sucrose.Inference) => Sucrose.Inference;

@@ -33,4 +33,3 @@ "use strict";

separateFunction: () => separateFunction,
sucrose: () => sucrose,
validateInferencedQueries: () => validateInferencedQueries
sucrose: () => sucrose
});

@@ -79,4 +78,6 @@ module.exports = __toCommonJS(sucrose_exports);

if (start !== -1) {
const [parameter, body] = code.split("\n", 2);
const sep = code.indexOf("\n", 2);
const parameter = code.slice(0, sep);
const end = parameter.lastIndexOf(")") + 1;
const body = code.slice(sep + 1);
return [

@@ -242,4 +243,2 @@ parameter.slice(start, end),

inference.set = true;
inference.queries = [];
inference.unknownQueries = true;
break;

@@ -251,48 +250,3 @@ }

inference.query = true;
inference.unknownQueries = true;
inference.queries = [];
}
if (!inference.unknownQueries && inference.query) {
let keyword = alias + ".";
if (code.includes(keyword + "query"))
keyword = alias + ".query";
while (true) {
let start = code.indexOf(keyword);
if (start === -1 && code.indexOf(alias + "[") !== -1) {
inference.queries = [];
inference.unknownQueries = true;
break;
}
if (start !== -1) {
let end = findEndIndex(
"",
code,
start + keyword.length + 1
);
if (end === -1)
end = void 0;
const index = start + alias.length + 1;
code = code.slice(start + alias.length + 1);
let query = code.slice(0, end ? end - index : end).trimEnd();
while (start !== -1) {
start = query.indexOf(".");
if (start !== -1)
query = query.slice(start + 1);
}
if (query.charCodeAt(query.length - 1) === 59)
query = query.slice(0, -1);
if (query.charCodeAt(query.length - 1) === 44)
query = query.slice(0, -1);
if (query.charCodeAt(query.length - 1) === 93)
query = query.slice(0, -1);
if (query.charCodeAt(query.length - 1) === 41)
query = query.slice(0, -1);
if (query && !inference.queries.includes(query)) {
inference.queries.push(query);
continue;
}
}
break;
}
}
if (!inference.headers && access("headers", alias))

@@ -327,19 +281,3 @@ inference.headers = true;

};
var validateInferencedQueries = (queries) => {
for (const query of queries) {
if (query.charCodeAt(0) === 123)
return false;
if (query.indexOf("'") !== -1)
return false;
if (query.indexOf('"') !== -1)
return false;
if (query.indexOf("\n") !== -1)
return false;
if (query.indexOf(" ") !== -1)
return false;
}
return true;
};
var sucrose = (lifeCycle, inference = {
queries: [],
query: false,

@@ -349,4 +287,3 @@ headers: false,

cookie: false,
set: false,
unknownQueries: false
set: false
}) => {

@@ -356,2 +293,4 @@ const events = [];

events.push(lifeCycle.handler);
if (lifeCycle.request?.length)
events.push(...lifeCycle.request);
if (lifeCycle.beforeHandle?.length)

@@ -369,6 +308,4 @@ events.push(...lifeCycle.beforeHandle);

events.push(...lifeCycle.mapResponse);
if (lifeCycle.request?.length)
events.push(...lifeCycle.request);
if (lifeCycle.onResponse?.length)
events.push(...lifeCycle.onResponse);
if (lifeCycle.afterResponse?.length)
events.push(...lifeCycle.afterResponse);
for (const e of events) {

@@ -383,7 +320,2 @@ if (!e)

const mainParameter = extractMainParameter(rootParameters);
if (isArrowReturn && (body === "query" || rootParameters && body.startsWith(rootParameters + ".query"))) {
inference.query = true;
inference.unknownQueries = true;
inference.queries = [];
}
if (mainParameter) {

@@ -397,31 +329,6 @@ const aliases = findAlias(mainParameter, body);

inference.query = true;
inference.unknownQueries = true;
inference.queries = [];
}
if (inference.query) {
inferBodyReference(body, ["query"], inference);
const queryIndex = parameter.indexOf("query: {");
if (queryIndex !== -1) {
const part = parameter.slice(queryIndex + 7);
const [start, end] = bracketPairRange(part);
const queryBracket = removeDefaultParameter(
part.slice(start, end)
);
for (let query of queryBracket.slice(1, -1).split(",")) {
const index = query.indexOf(":");
if (index !== -1)
query = query.slice(0, index);
query = query.trim();
if (query && !inference.queries.includes(query))
inference.queries.push(query.trim());
}
}
}
if (inference.query && inference.headers && inference.body && inference.cookie && inference.set)
break;
}
if (!validateInferencedQueries(inference.queries)) {
inference.unknownQueries = true;
inference.queries = [];
}
return inference;

@@ -441,4 +348,3 @@ };

separateFunction,
sucrose,
validateInferencedQueries
sucrose
});
import type { Context } from './context';
import type { TraceHandler } from './types';
import type { Prettify, RouteSchema, SingletonBase } from './types';
export type TraceEvent = 'request' | 'parse' | 'transform' | 'beforeHandle' | 'handle' | 'afterHandle' | 'mapResponse' | 'afterResponse' | 'error';
export type TraceStream = {
id: number;
event: TraceEvent;
type: 'begin' | 'end';
begin: number;
name?: string;
total?: number;
};
type TraceEndDetail = {
/**
* Timestamp of a function after it's executed since the server start
*/
end: TraceProcess<'end'>;
/**
* Error that was thrown in the lifecycle
*/
error: Error | null;
/**
* Elapsed time of the lifecycle
*/
elapsed: number;
};
export type TraceProcess<Type extends 'begin' | 'end' = 'begin' | 'end', WithChildren extends boolean = true> = Type extends 'begin' ? Prettify<{
/**
* Function name
*/
name: string;
/**
* Timestamp of a function is called since the server start
*/
begin: number;
/**
* Timestamp of a function after it's executed since the server start
*/
end: Promise<number>;
/**
* Error that was thrown in the lifecycle
*/
error: Promise<Error | null>;
/**
* Listener to intercept the end of the lifecycle
*
* If you want to mutate the context, you must do it in this function
* as there's a lock mechanism to ensure the context is mutate successfully
*/
onStop(
/**
* A callback function that will be called when the function ends
*
* If you want to mutate the context, you must do it in this function
* as there's a lock mechanism to ensure the context is mutate successfully
*/
callback?: (detail: TraceEndDetail) => unknown): Promise<void>;
} & (WithChildren extends true ? {
/**
* total number of lifecycle's children and
* total number of `onEvent` will be called
* if there were no early exists or error thrown
*/
total: number;
/**
* Listener to intercept each child lifecycle
*/
onEvent(
/**
* Callback function that will be called for when each child start
*/
callback?: (process: TraceProcess<'begin', false>) => unknown): Promise<void>;
} : {
/**
* Index of the child event
*/
index: number;
})> : number;
export type TraceListener = (callback?: (process: TraceProcess<'begin'>) => unknown) => Promise<TraceProcess<'begin'>>;
export type TraceHandler<in out Route extends RouteSchema = {}, in out Singleton extends SingletonBase = {
decorator: {};
store: {};
derive: {};
resolve: {};
}> = {
(lifecycle: Prettify<{
id: number;
context: Context<Route, Singleton>;
set: Context['set'];
time: number;
store: Singleton['store'];
} & {
[x in `on${Capitalize<TraceEvent>}`]: TraceListener;
}>): unknown;
};
export declare const ELYSIA_TRACE: unique symbol;
export declare const createTracer: (callback: TraceHandler) => (context: Context) => {
request: (v: any) => () => void;
parse: (v: any) => () => void;
transform: (v: any) => () => void;
beforeHandle: (v: any) => () => void;
handle: (v: any) => () => void;
afterHandle: (v: any) => () => void;
error: (v: any) => () => void;
response: (v: any) => () => void;
export declare const createTracer: (traceListener: TraceHandler) => (context: Context) => {
request: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
parse: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
transform: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
beforeHandle: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
handle: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
afterHandle: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
error: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
mapResponse: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
afterResponse: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
};
export {};

@@ -1,6 +0,4 @@

/// <reference types="node" />
/// <reference types="bun-types" />
import { DateOptions, NumberOptions, TDate, TUnsafe } from '@sinclair/typebox';
import { type SchemaOptions, type TSchema, TProperties, ObjectOptions, TObject, TNumber, TBoolean } from '@sinclair/typebox';
import { type TypeCheck } from '@sinclair/typebox/compiler';
import { type ValueError, type TypeCheck } from '@sinclair/typebox/compiler';
import type { CookieOptions } from './cookies';

@@ -45,8 +43,8 @@ import type { MaybeArray } from './types';

readonly Files: (options?: ElysiaTypeOptions.Files) => import("@sinclair/typebox").TTransform<TUnsafe<File[]>, File[]>;
readonly Nullable: <T_1 extends TSchema>(schema: T_1) => import("@sinclair/typebox").TUnion<[T_1, import("@sinclair/typebox").TNull]>;
readonly Nullable: <T extends TSchema>(schema: T) => import("@sinclair/typebox").TUnion<[T, import("@sinclair/typebox").TNull]>;
/**
* Allow Optional, Nullable and Undefined
*/
readonly MaybeEmpty: <T_2 extends TSchema>(schema: T_2) => import("@sinclair/typebox").TUnion<[T_2, import("@sinclair/typebox").TNull, import("@sinclair/typebox").TUndefined]>;
readonly Cookie: <T_3 extends TProperties>(properties: T_3, { domain, expires, httpOnly, maxAge, path, priority, sameSite, secure, secrets, sign, ...options }?: ElysiaTypeOptions.CookieValidatorOption<T_3>) => TObject<T_3>;
readonly MaybeEmpty: <T extends TSchema>(schema: T) => import("@sinclair/typebox").TUnion<[T, import("@sinclair/typebox").TNull, import("@sinclair/typebox").TUndefined]>;
readonly Cookie: <T extends TProperties>(properties: T, { domain, expires, httpOnly, maxAge, path, priority, sameSite, secure, secrets, sign, ...options }?: ElysiaTypeOptions.CookieValidatorOption<T>) => TObject<T>;
};

@@ -66,3 +64,8 @@ export type TCookie = (typeof ElysiaType)['Cookie'];

interface SchemaOptions {
error?: string | ((type: string, validator: TypeCheck<any>, value: unknown) => string | void);
error?: string | boolean | number | Object | ((validation: {
errors: ValueError[];
type: string;
validator: TypeCheck<any>;
value: unknown;
}) => string | boolean | number | Object | void);
}

@@ -69,0 +72,0 @@ }

@@ -1,23 +0,47 @@

/// <reference types="bun-types" />
/// <reference types="node" />
/// <reference types="bun-types" />
import type { Elysia } from '.';
import type { Serve, Server, WebSocketHandler } from 'bun';
import type { TSchema, TObject, Static, TAnySchema, TNull, TUndefined } from '@sinclair/typebox';
import type { BunFile, Serve, Server, WebSocketHandler } from 'bun';
import type { TSchema, TObject, Static, TAnySchema, TNull, TUndefined, StaticDecode, OptionalKind } from '@sinclair/typebox';
import type { TypeCheck, ValueError } from '@sinclair/typebox/compiler';
import type { OpenAPIV3 } from 'openapi-types';
import type { CookieOptions } from './cookies';
import type { TraceHandler } from './trace';
import type { Context, ErrorContext, PreContext } from './context';
import type { ELYSIA_RESPONSE, InternalServerError, InvalidCookieSignature, NotFoundError, ParseError, ValidationError } from './error';
import { OptionalKind } from '@sinclair/typebox';
type PartialServe = Partial<Serve>;
export type ElysiaConfig<Prefix extends string | undefined, Scoped extends boolean | undefined> = {
/**
* Path prefix of the instance
*
* @default '''
*/
prefix?: Prefix;
/**
* If set to true, other Elysia handler will not inherits global life-cycle, store, decorators from the current instance
*
* @default false
*/
scoped?: Scoped;
name?: string;
seed?: unknown;
/**
* Bun serve
*
* @see https://bun.sh/docs/api/http
*/
serve?: PartialServe;
tags?: DocumentDecoration['tags'];
/**
* 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

@@ -54,2 +78,4 @@ *

/**
* @deprecated on 1.1, Elysia now use dynamic query by default
*
* Disable sucrose dynamic query inference

@@ -71,5 +97,5 @@ */

/**
* If set to true, other Elysia handler will not inherits global life-cycle, store, decorators from the current instance
* Override websocket configuration
*
* @default false
* @see https://bun.sh/docs/api/websockets
*/

@@ -118,9 +144,16 @@ websocket?: Omit<WebSocketHandler<any>, 'open' | 'close' | 'message' | 'drain'>;

} & {};
export type Reconcile<A extends Object, B extends Object> = {
type IsBothObject<A, B> = A extends Record<string | number | symbol, unknown> ? B extends Record<string | number | symbol, unknown> ? true : false : false;
export type Reconcile<A extends Object, B extends Object, Override extends boolean = false> = 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]: B[key];
[key in keyof B]: IsBothObject<A[key], B[key]> extends true ? Reconcile<A[key], B[key], Override> : B[key];
} : Prettify<Collision & {
[key in keyof B]: B[key];
}> : never;
}> : never : {
[key in keyof B as key extends keyof A ? never : key]: B[key];
} extends infer Collision ? {} extends Collision ? {
[key in keyof A]: IsBothObject<A[key], B[key]> extends true ? Reconcile<A[key], B[key], Override> : A[key];
} : Prettify<{
[key in keyof A]: A[key];
} & Collision> : never;
export interface SingletonBase {

@@ -145,2 +178,3 @@ decorator: Record<string, unknown>;

macro: BaseMacro;
macroFn: BaseMacroFn;
}

@@ -158,4 +192,4 @@ export interface RouteSchema {

};
export type UnwrapSchema<Schema extends TSchema | string | undefined, Definitions extends Record<string, unknown> = {}> = undefined extends Schema ? unknown : Schema extends TSchema ? Schema extends OptionalField ? Prettify<Partial<Static<Schema>>> : Static<Schema> : Schema extends string ? Definitions extends Record<Schema, infer NamedSchema> ? NamedSchema : Definitions : unknown;
export type UnwrapBodySchema<Schema extends TSchema | string | undefined, Definitions extends Record<string, unknown> = {}> = undefined extends Schema ? unknown : Schema extends TSchema ? Schema extends OptionalField ? Prettify<Partial<Static<Schema>>> | null : Static<Schema> : Schema extends string ? Definitions extends Record<Schema, infer NamedSchema> ? NamedSchema : Definitions : unknown;
export type UnwrapSchema<Schema extends TSchema | string | undefined, Definitions extends Record<string, unknown> = {}> = undefined extends Schema ? unknown : Schema extends TSchema ? Schema extends OptionalField ? Prettify<Partial<Static<Schema>>> : StaticDecode<Schema> : Schema extends string ? Definitions extends Record<Schema, infer NamedSchema> ? NamedSchema : Definitions : unknown;
export type UnwrapBodySchema<Schema extends TSchema | string | undefined, Definitions extends Record<string, unknown> = {}> = undefined extends Schema ? unknown : Schema extends TSchema ? Schema extends OptionalField ? Prettify<Partial<Static<Schema>>> | null : StaticDecode<Schema> : Schema extends string ? Definitions extends Record<Schema, infer NamedSchema> ? NamedSchema : Definitions : unknown;
export type SuccessfulResponse<T = unknown> = {

@@ -188,4 +222,4 @@ 200: T;

cookie: UnwrapSchema<Schema['cookie'], Definitions>;
response: Schema['response'] extends TSchema | string ? UnwrapSchema<Schema['response'], Definitions> : Schema['response'] extends SuccessfulResponse<TAnySchema | string> ? {
[k in keyof Schema['response']]: UnwrapSchema<Schema['response'][k], Definitions>;
response: Schema['response'] extends TSchema | string ? CoExist<UnwrapSchema<Schema['response'], Definitions>, File, BunFile> : Schema['response'] extends SuccessfulResponse<TAnySchema | string> ? {
[k in keyof Schema['response']]: CoExist<UnwrapSchema<Schema['response'][k], Definitions>, File, BunFile>;
} : unknown | void;

@@ -218,3 +252,3 @@ }

mapResponse: HookContainer<MapResponse<any, any>>[];
onResponse: HookContainer<VoidHandler<any, any>>[];
afterResponse: HookContainer<VoidHandler<any, any>>[];
trace: HookContainer<TraceHandler<any, any>>[];

@@ -249,2 +283,8 @@ error: HookContainer<ErrorHandler<any, any, any>>[];

}, Path extends string = ''> = (context: Context<Route, Singleton, Path>) => Route['response'] extends SuccessfulResponse ? Response | MaybePromise<Route['response'][keyof Route['response']]> : Response | MaybePromise<Route['response']>;
export type Replace<Original, Target, With> = Original extends Record<string, unknown> ? {
[K in keyof Original]: Original[K] extends Target ? With : Original[K];
} : Original extends Target ? With : Original;
export type CoExist<Original, Target, With> = Original extends Record<string, unknown> ? {
[K in keyof Original]: Original[K] extends Target ? Original[K] | With : Original[K];
} : Original extends Target ? Original | With : Original;
export type InlineHandler<Route extends RouteSchema = {}, Singleton extends SingletonBase = {

@@ -255,3 +295,3 @@ decorator: {};

resolve: {};
}, Path extends string = ''> = ((context: Context<Route, Singleton, Path>) => Route['response'] extends SuccessfulResponse ? Response | MaybePromise<Route['response'][keyof Route['response']] | {
}, Path extends string = '', MacroContext = {}> = ((context: MacroContext extends Record<string | number | symbol, unknown> ? Prettify<MacroContext & Context<Route, Singleton, Path>> : Context<Route, Singleton, Path>) => Route['response'] extends SuccessfulResponse ? Response | MaybePromise<Route['response'][keyof Route['response']] | {
[Status in keyof Route['response']]: {

@@ -304,35 +344,2 @@ _type: Record<Status, Route['response'][Status]>;

};
export type TraceEvent = 'request' | 'parse' | 'transform' | 'beforeHandle' | 'afterHandle' | 'error' | 'response' extends infer Events extends string ? Events | `${Events}.unit` | 'handle' | 'exit' : never;
export type TraceStream = {
id: number;
event: TraceEvent;
type: 'begin' | 'end';
time: number;
name?: string;
unit?: number;
};
export type TraceProcess<Type extends 'begin' | 'end' = 'begin' | 'end'> = Type extends 'begin' ? Prettify<{
name: string;
time: number;
skip: boolean;
end: Promise<TraceProcess<'end'>>;
children: Promise<TraceProcess<'begin'>>[];
}> : number;
export type TraceHandler<in out Route extends RouteSchema = {}, in out Singleton extends SingletonBase = {
decorator: {};
store: {};
derive: {};
resolve: {};
}> = {
(lifecycle: Prettify<{
context: Context<Route, Singleton>;
set: Context['set'];
id: number;
time: number;
} & {
[x in 'request' | 'parse' | 'transform' | 'beforeHandle' | 'handle' | 'afterHandle' | 'error' | 'response']: Promise<TraceProcess<'begin'>>;
} & {
store: Singleton['store'];
}>): MaybePromise<void>;
};
export type BodyHandler<in out Route extends RouteSchema = {}, in out Singleton extends SingletonBase = {

@@ -462,9 +469,9 @@ decorator: {};

/**
* Execute after response is sent
*/
afterResponse?: MaybeArray<VoidHandler<TypedRoute, Singleton>>;
/**
* Catch error
*/
error?: MaybeArray<ErrorHandler<Errors, TypedRoute, Singleton>>;
/**
* Custom body parser
*/
onResponse?: MaybeArray<VoidHandler<TypedRoute, Singleton>>;
tags?: DocumentDecoration['tags'];

@@ -525,4 +532,5 @@ };

};
export type BaseMacro = Record<string, Record<string, unknown> | ((...a: any) => unknown)>;
export type MacroToProperty<in out T extends BaseMacro> = Prettify<{
export type BaseMacro = Record<string, string | number | boolean | Object | undefined | null>;
export type BaseMacroFn = Record<string, (...a: any) => unknown>;
export type MacroToProperty<in out T extends BaseMacroFn> = Prettify<{
[K in keyof T]: T[K] extends Function ? T[K] extends (a: infer Params) => any ? Params | undefined : T[K] : T[K];

@@ -561,9 +569,9 @@ }>;

}, fn: MaybeArray<ErrorHandler<Errors, TypedRoute, Singleton>>): unknown;
onResponse(fn: MaybeArray<VoidHandler<TypedRoute, Singleton>>): unknown;
onResponse(options: {
mapResponse(fn: MaybeArray<VoidHandler<TypedRoute, Singleton>>): unknown;
mapResponse(options: {
insert?: 'before' | 'after';
stack?: 'global' | 'local';
}, fn: MaybeArray<VoidHandler<TypedRoute, Singleton>>): unknown;
mapResponse(fn: MaybeArray<MapResponse<TypedRoute, Singleton>>): unknown;
mapResponse(options: {
onAfterResponse(fn: MaybeArray<MapResponse<TypedRoute, Singleton>>): unknown;
onAfterResponse(options: {
insert?: 'before' | 'after';

@@ -584,3 +592,3 @@ stack?: 'global' | 'local';

export type CreateEden<Path extends string, Property extends Record<string, unknown> = {}> = Path extends `/${infer Rest}` ? _CreateEden<Rest, Property> : Path extends '' ? _CreateEden<'index', Property> : _CreateEden<Path, Property>;
export type ComposeElysiaResponse<Response, Handle> = Handle extends (...a: any[]) => infer A ? _ComposeElysiaResponse<Response, Awaited<A>> : _ComposeElysiaResponse<Response, Awaited<Handle>>;
export type ComposeElysiaResponse<Response, Handle> = Handle extends (...a: any[]) => infer A ? _ComposeElysiaResponse<Response, Replace<Awaited<A>, BunFile, File>> : _ComposeElysiaResponse<Response, Replace<Awaited<Handle>, BunFile, File>>;
type _ComposeElysiaResponse<Response, Handle> = Prettify<unknown extends Response ? {

@@ -610,2 +618,3 @@ 200: Exclude<Handle, {

macro: {};
macroFn: {};
}, Routes extends RouteBase = {}> = Instances extends [

@@ -625,2 +634,3 @@ infer Current extends Elysia<any, any, any, any, any, any>,

macro: Prettify<Metadata['macro']>;
macroFn: Prettify<Metadata['macroFn']>;
}, Routes>;

@@ -640,3 +650,3 @@ export type LifeCycleType = 'global' | 'local' | 'scoped';

export interface ModelValidatorError extends ValueError {
humanReadable: string;
summary: string;
}

@@ -656,2 +666,7 @@ export interface ModelValidator<T> extends TypeCheck<T> {

}
export type UnionToIntersect<U> = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never;
export type ResolveMacroContext<Macro extends BaseMacro, MacroFn extends BaseMacroFn> = UnionToIntersect<{
[K in keyof Macro]-?: undefined extends Macro[K] ? never : K extends keyof MacroFn ? ReturnType<MacroFn[K]> extends infer A extends Record<string | number | symbol, unknown> ? A : never : never;
}[keyof Macro]>;
export type ContextAppendType = 'append' | 'override';
export {};

@@ -0,14 +1,17 @@

import type { BunFile } from 'bun';
import { TSchema } from '@sinclair/typebox';
import { TypeCheck, ValueError } from '@sinclair/typebox/compiler';
import type { LifeCycleStore, LocalHook, MaybeArray, InputSchema, LifeCycleType, HookContainer } from './types';
import { TypeCheck } from '@sinclair/typebox/compiler';
import type { Sucrose } from './sucrose';
import type { LifeCycleStore, LocalHook, MaybeArray, InputSchema, LifeCycleType, HookContainer, Replace } from './types';
import type { CookieOptions } from './cookies';
import { Sucrose } from './sucrose';
export declare const replaceUrlPath: (url: string, pathname: string) => string;
export declare const mergeDeep: <A extends Record<string, any>, B extends Record<string, any>>(target: A, source: B, { skipKeys }?: {
export declare const isClass: (v: Object) => boolean;
export declare const mergeDeep: <A extends Record<string, any>, B extends Record<string, any>>(target: A, source: B, { skipKeys, override }?: {
skipKeys?: string[];
override?: boolean;
}) => A & B;
export declare const mergeCookie: <const A extends Object, const B extends Object>(a: A, b: B) => A & B;
export declare const mergeObjectArray: <T extends HookContainer>(a?: T | T[], b?: T | T[]) => T[];
export declare const primitiveHooks: readonly ["start", "request", "parse", "transform", "resolve", "beforeHandle", "afterHandle", "onResponse", "mapResponse", "trace", "error", "stop", "body", "headers", "params", "query", "response", "type", "detail"];
export declare const mergeResponse: (a: InputSchema['response'], b: InputSchema['response']) => string | TSchema | {
export declare const primitiveHooks: readonly ["start", "request", "parse", "transform", "resolve", "beforeHandle", "afterHandle", "mapResponse", "afterResponse", "trace", "error", "stop", "body", "headers", "params", "query", "response", "type", "detail"];
export declare const mergeResponse: (a: InputSchema["response"], b: InputSchema["response"]) => string | TSchema | {
[x: number]: any;

@@ -19,3 +22,3 @@ } | undefined;

}) => LifeCycleStore;
export declare const getSchemaValidator: (s: TSchema | string | undefined, { models, dynamic, normalize, additionalProperties }?: {
export declare const getSchemaValidator: <T extends TSchema | string | undefined>(s: T, { models, dynamic, normalize, additionalProperties }?: {
models?: Record<string, TSchema>;

@@ -25,12 +28,4 @@ additionalProperties?: boolean;

normalize?: boolean;
}) => TypeCheck<TSchema> | undefined;
export declare const mapValueError: (error: ValueError) => {
humanReadable: string;
type: import("@sinclair/typebox/value").ValueErrorType;
schema: TSchema;
path: string;
value: unknown;
message: string;
};
export declare const getResponseSchemaValidator: (s: InputSchema['response'] | undefined, { models, dynamic, normalize, additionalProperties }: {
}) => T extends TSchema ? TypeCheck<TSchema> : undefined;
export declare const getResponseSchemaValidator: (s: InputSchema["response"] | undefined, { models, dynamic, normalize, additionalProperties }: {
models?: Record<string, TSchema>;

@@ -116,64 +111,3 @@ additionalProperties?: boolean;

};
export declare const InvertedStatusMap: {
readonly 100: "Continue";
readonly 101: "Switching Protocols";
readonly 102: "Processing";
readonly 103: "Early Hints";
readonly 200: "OK";
readonly 201: "Created";
readonly 202: "Accepted";
readonly 203: "Non-Authoritative Information";
readonly 204: "No Content";
readonly 205: "Reset Content";
readonly 206: "Partial Content";
readonly 207: "Multi-Status";
readonly 208: "Already Reported";
readonly 300: "Multiple Choices";
readonly 301: "Moved Permanently";
readonly 302: "Found";
readonly 303: "See Other";
readonly 304: "Not Modified";
readonly 307: "Temporary Redirect";
readonly 308: "Permanent Redirect";
readonly 400: "Bad Request";
readonly 401: "Unauthorized";
readonly 402: "Payment Required";
readonly 403: "Forbidden";
readonly 404: "Not Found";
readonly 405: "Method Not Allowed";
readonly 406: "Not Acceptable";
readonly 407: "Proxy Authentication Required";
readonly 408: "Request Timeout";
readonly 409: "Conflict";
readonly 410: "Gone";
readonly 411: "Length Required";
readonly 412: "Precondition Failed";
readonly 413: "Payload Too Large";
readonly 414: "URI Too Long";
readonly 415: "Unsupported Media Type";
readonly 416: "Range Not Satisfiable";
readonly 417: "Expectation Failed";
readonly 418: "I'm a teapot";
readonly 421: "Misdirected Request";
readonly 422: "Unprocessable Content";
readonly 423: "Locked";
readonly 424: "Failed Dependency";
readonly 425: "Too Early";
readonly 426: "Upgrade Required";
readonly 428: "Precondition Required";
readonly 429: "Too Many Requests";
readonly 431: "Request Header Fields Too Large";
readonly 451: "Unavailable For Legal Reasons";
readonly 500: "Internal Server Error";
readonly 501: "Not Implemented";
readonly 502: "Bad Gateway";
readonly 503: "Service Unavailable";
readonly 504: "Gateway Timeout";
readonly 505: "HTTP Version Not Supported";
readonly 506: "Variant Also Negotiates";
readonly 507: "Insufficient Storage";
readonly 508: "Loop Detected";
readonly 510: "Not Extended";
readonly 511: "Network Authentication Required";
};
export declare const InvertedStatusMap: { [K in keyof StatusMap as StatusMap[K]]: K; };
export type StatusMap = typeof StatusMap;

@@ -188,4 +122,4 @@ export type InvertedStatusMap = typeof InvertedStatusMap;

}) => (stackName: keyof LifeCycleStore) => (type: {
insert?: 'before' | 'after';
stack?: 'global' | 'local';
insert?: "before" | "after";
stack?: "global" | "local";
} | MaybeArray<HookContainer>, fn?: MaybeArray<HookContainer>) => void;

@@ -217,6 +151,4 @@ export declare const isNumericString: (message: string) => boolean;

headers: boolean;
queries: string[];
query: boolean;
set: boolean;
unknownQueries: boolean;
};

@@ -228,4 +160,13 @@ /**

*/
export declare const redirect: (url: string, status?: number) => import("undici-types").Response;
export declare const redirect: (url: string, status?: 301 | 302 | 303 | 307 | 308) => import("undici-types").Response;
export type redirect = typeof redirect;
export declare const ELYSIA_FORM_DATA: unique symbol;
export type ELYSIA_FORM_DATA = typeof ELYSIA_FORM_DATA;
type ElysiaFormData<T extends Record<string | number, unknown>> = FormData & {
[ELYSIA_FORM_DATA]: Replace<T, BunFile, File>;
};
export declare const ELYSIA_REQUEST_ID: unique symbol;
export type ELYSIA_REQUEST_ID = typeof ELYSIA_REQUEST_ID;
export declare const form: <const T extends Record<string | number, unknown>>(items: T) => ElysiaFormData<T>;
export declare const randomId: () => number;
export {};

@@ -1,3 +0,1 @@

/// <reference types="bun-types" />
/// <reference types="bun-types" />
import type { ServerWebSocket, WebSocketHandler } from 'bun';

@@ -24,4 +22,4 @@ import type { TSchema } from '@sinclair/typebox';

set id(newID: string);
get publish(): (topic: string, data?: Route['response'], compress?: boolean) => this;
get send(): (data: Route['response']) => this;
get publish(): (topic: string, data?: Route["response"], compress?: boolean) => this;
get send(): (data: Route["response"]) => this;
get subscribe(): (room: string) => this;

@@ -28,0 +26,0 @@ get unsubscribe(): (room: string) => this;

@@ -1,4 +0,1 @@

/// <reference types="bun-types" />
/// <reference types="bun-types" />
/// <reference types="bun-types" />
import type { ServerWebSocket, WebSocketHandler } from 'bun';

@@ -5,0 +2,0 @@ import type { TSchema } from '@sinclair/typebox';

@@ -8,2 +8,3 @@ import { type Elysia } from '.';

export declare const hasTransform: (schema: TAnySchema) => any;
export declare const isAsyncName: (v: Function | HookContainer) => boolean;
export declare const isAsync: (v: Function | HookContainer) => boolean;

@@ -10,0 +11,0 @@ export declare const composeHandler: ({ app, path, method, localHook, hooks, validator, handler, allowMeta, inference }: {

@@ -1,2 +0,1 @@

/// <reference types="node" />
import type { StatusMap, InvertedStatusMap, redirect as Redirect } from './utils';

@@ -3,0 +2,0 @@ import type { Cookie, ElysiaCookie } from './cookies';

@@ -146,6 +146,6 @@ import type { Context } from './context';

}
export declare const createCookieJar: (set: Context['set'], store: Record<string, ElysiaCookie>, initial?: Partial<ElysiaCookie>) => Record<string, Cookie<unknown>>;
export declare const parseCookie: (set: Context['set'], cookieString?: string | null, { secrets, sign, ...initial }?: CookieOptions & {
export declare const createCookieJar: (set: Context["set"], store: Record<string, ElysiaCookie>, initial?: Partial<ElysiaCookie>) => Record<string, Cookie<unknown>>;
export declare const parseCookie: (set: Context["set"], cookieString?: string | null, { secrets, sign, ...initial }?: CookieOptions & {
sign?: true | string | string[];
}) => Promise<Record<string, Cookie<unknown>>>;
export {};

@@ -1,2 +0,1 @@

/// <reference types="node" />
import type { Elysia } from '.';

@@ -3,0 +2,0 @@ import { ElysiaErrors } from './error';

import type { TSchema } from '@sinclair/typebox';
import type { TypeCheck } from '@sinclair/typebox/compiler';
import type { TypeCheck, ValueError } from '@sinclair/typebox/compiler';
import { StatusMap } from './utils';
export declare const ERROR_CODE: unique symbol;
export type ERROR_CODE = typeof ERROR_CODE;
export declare const ELYSIA_RESPONSE: unique symbol;

@@ -8,3 +10,3 @@ export type ELYSIA_RESPONSE = typeof ELYSIA_RESPONSE;

export type ElysiaErrors = InternalServerError | NotFoundError | ParseError | ValidationError | InvalidCookieSignature;
export declare const error: <const Code extends number | "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required", const T = Code extends 100 | 101 | 102 | 103 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 300 | 301 | 302 | 303 | 304 | 307 | 308 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ? {
export declare const error: <const Code extends number | keyof StatusMap, const T = Code extends 100 | 101 | 102 | 103 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 300 | 301 | 302 | 303 | 304 | 307 | 308 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ? {
readonly 100: "Continue";

@@ -70,3 +72,3 @@ readonly 101: "Switching Protocols";

readonly 511: "Network Authentication Required";
}[Code] : Code, const Status extends Code extends "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required" ? {
}[Code] : Code, const Status extends Code extends keyof StatusMap ? StatusMap[Code] : Code = Code extends "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required" ? {
readonly Continue: 100;

@@ -132,67 +134,6 @@ readonly 'Switching Protocols': 101;

readonly 'Network Authentication Required': 511;
}[Code] : Code = Code extends "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required" ? {
readonly Continue: 100;
readonly 'Switching Protocols': 101;
readonly Processing: 102;
readonly 'Early Hints': 103;
readonly OK: 200;
readonly Created: 201;
readonly Accepted: 202;
readonly 'Non-Authoritative Information': 203;
readonly 'No Content': 204;
readonly 'Reset Content': 205;
readonly 'Partial Content': 206;
readonly 'Multi-Status': 207;
readonly 'Already Reported': 208;
readonly 'Multiple Choices': 300;
readonly 'Moved Permanently': 301;
readonly Found: 302;
readonly 'See Other': 303;
readonly 'Not Modified': 304;
readonly 'Temporary Redirect': 307;
readonly 'Permanent Redirect': 308;
readonly 'Bad Request': 400;
readonly Unauthorized: 401;
readonly 'Payment Required': 402;
readonly Forbidden: 403;
readonly 'Not Found': 404;
readonly 'Method Not Allowed': 405;
readonly 'Not Acceptable': 406;
readonly 'Proxy Authentication Required': 407;
readonly 'Request Timeout': 408;
readonly Conflict: 409;
readonly Gone: 410;
readonly 'Length Required': 411;
readonly 'Precondition Failed': 412;
readonly 'Payload Too Large': 413;
readonly 'URI Too Long': 414;
readonly 'Unsupported Media Type': 415;
readonly 'Range Not Satisfiable': 416;
readonly 'Expectation Failed': 417;
readonly "I'm a teapot": 418;
readonly 'Misdirected Request': 421;
readonly 'Unprocessable Content': 422;
readonly Locked: 423;
readonly 'Failed Dependency': 424;
readonly 'Too Early': 425;
readonly 'Upgrade Required': 426;
readonly 'Precondition Required': 428;
readonly 'Too Many Requests': 429;
readonly 'Request Header Fields Too Large': 431;
readonly 'Unavailable For Legal Reasons': 451;
readonly 'Internal Server Error': 500;
readonly 'Not Implemented': 501;
readonly 'Bad Gateway': 502;
readonly 'Service Unavailable': 503;
readonly 'Gateway Timeout': 504;
readonly 'HTTP Version Not Supported': 505;
readonly 'Variant Also Negotiates': 506;
readonly 'Insufficient Storage': 507;
readonly 'Loop Detected': 508;
readonly 'Not Extended': 510;
readonly 'Network Authentication Required': 511;
}[Code] : Code>(code: Code, response?: T) => {
[ELYSIA_RESPONSE]: Status;
response: T;
_type: { [ERROR_CODE in Status]: T; };
[ELYSIA_RESPONSE]: Status;
};

@@ -210,6 +151,6 @@ export declare class InternalServerError extends Error {

export declare class ParseError extends Error {
body?: unknown;
body?: unknown | undefined;
code: string;
status: number;
constructor(message?: string, body?: unknown);
constructor(message?: string, body?: unknown | undefined);
}

@@ -222,2 +163,10 @@ export declare class InvalidCookieSignature extends Error {

}
export declare const mapValueError: (error: ValueError) => {
summary: string;
type: import("@sinclair/typebox/value").ValueErrorType;
schema: TSchema;
path: string;
value: unknown;
message: string;
};
export declare class ValidationError extends Error {

@@ -230,3 +179,10 @@ type: string;

constructor(type: string, validator: TSchema | TypeCheck<any>, value: unknown);
get all(): any[];
get all(): {
summary: string;
type: import("@sinclair/typebox/value").ValueErrorType;
schema: TSchema;
path: string;
value: unknown;
message: string;
}[];
static simplifyModel(validator: TSchema | TypeCheck<any>): any;

@@ -233,0 +189,0 @@ get model(): any;

@@ -1,10 +0,8 @@

/// <reference types="node" />
/// <reference types="bun-types" />
import type { Context } from './context';
export declare const isNotEmpty: (obj?: Object) => boolean;
export declare const parseSetCookies: (headers: Headers, setCookie: string[]) => Headers;
export declare const serializeCookie: (cookies: Context['set']['cookie']) => string | string[] | undefined;
export declare const mapResponse: (response: unknown, set: Context['set'], request?: Request) => Response;
export declare const mapEarlyResponse: (response: unknown, set: Context['set'], request?: Request) => Response | undefined;
export declare const serializeCookie: (cookies: Context["set"]["cookie"]) => string | string[] | undefined;
export declare const mapResponse: (response: unknown, set: Context["set"], request?: Request) => Response;
export declare const mapEarlyResponse: (response: unknown, set: Context["set"], request?: Request) => Response | undefined;
export declare const mapCompactResponse: (response: unknown, request?: Request) => Response;
export declare const errorToResponse: (error: Error, set?: Context['set']) => import("undici-types").Response;
export declare const errorToResponse: (error: Error, set?: Context["set"]) => import("undici-types").Response;
import type { Handler, HookContainer, LifeCycleStore } from './types';
export declare namespace Sucrose {
interface Inference {
queries: string[];
unknownQueries: boolean;
query: boolean;

@@ -77,3 +75,2 @@ headers: boolean;

export declare const removeDefaultParameter: (parameter: string) => string;
export declare const validateInferencedQueries: (queries: string[]) => boolean;
export declare const sucrose: (lifeCycle: Sucrose.LifeCycle, inference?: Sucrose.Inference) => Sucrose.Inference;
import type { Context } from './context';
import type { TraceHandler } from './types';
import type { Prettify, RouteSchema, SingletonBase } from './types';
export type TraceEvent = 'request' | 'parse' | 'transform' | 'beforeHandle' | 'handle' | 'afterHandle' | 'mapResponse' | 'afterResponse' | 'error';
export type TraceStream = {
id: number;
event: TraceEvent;
type: 'begin' | 'end';
begin: number;
name?: string;
total?: number;
};
type TraceEndDetail = {
/**
* Timestamp of a function after it's executed since the server start
*/
end: TraceProcess<'end'>;
/**
* Error that was thrown in the lifecycle
*/
error: Error | null;
/**
* Elapsed time of the lifecycle
*/
elapsed: number;
};
export type TraceProcess<Type extends 'begin' | 'end' = 'begin' | 'end', WithChildren extends boolean = true> = Type extends 'begin' ? Prettify<{
/**
* Function name
*/
name: string;
/**
* Timestamp of a function is called since the server start
*/
begin: number;
/**
* Timestamp of a function after it's executed since the server start
*/
end: Promise<number>;
/**
* Error that was thrown in the lifecycle
*/
error: Promise<Error | null>;
/**
* Listener to intercept the end of the lifecycle
*
* If you want to mutate the context, you must do it in this function
* as there's a lock mechanism to ensure the context is mutate successfully
*/
onStop(
/**
* A callback function that will be called when the function ends
*
* If you want to mutate the context, you must do it in this function
* as there's a lock mechanism to ensure the context is mutate successfully
*/
callback?: (detail: TraceEndDetail) => unknown): Promise<void>;
} & (WithChildren extends true ? {
/**
* total number of lifecycle's children and
* total number of `onEvent` will be called
* if there were no early exists or error thrown
*/
total: number;
/**
* Listener to intercept each child lifecycle
*/
onEvent(
/**
* Callback function that will be called for when each child start
*/
callback?: (process: TraceProcess<'begin', false>) => unknown): Promise<void>;
} : {
/**
* Index of the child event
*/
index: number;
})> : number;
export type TraceListener = (callback?: (process: TraceProcess<'begin'>) => unknown) => Promise<TraceProcess<'begin'>>;
export type TraceHandler<in out Route extends RouteSchema = {}, in out Singleton extends SingletonBase = {
decorator: {};
store: {};
derive: {};
resolve: {};
}> = {
(lifecycle: Prettify<{
id: number;
context: Context<Route, Singleton>;
set: Context['set'];
time: number;
store: Singleton['store'];
} & {
[x in `on${Capitalize<TraceEvent>}`]: TraceListener;
}>): unknown;
};
export declare const ELYSIA_TRACE: unique symbol;
export declare const createTracer: (callback: TraceHandler) => (context: Context) => {
request: (v: any) => () => void;
parse: (v: any) => () => void;
transform: (v: any) => () => void;
beforeHandle: (v: any) => () => void;
handle: (v: any) => () => void;
afterHandle: (v: any) => () => void;
error: (v: any) => () => void;
response: (v: any) => () => void;
export declare const createTracer: (traceListener: TraceHandler) => (context: Context) => {
request: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
parse: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
transform: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
beforeHandle: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
handle: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
afterHandle: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
error: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
mapResponse: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
afterResponse: (process: TraceStream) => {
resolveChild: ((process: TraceStream) => () => void)[];
resolve(error?: Error | null): void;
};
};
export {};

@@ -1,6 +0,4 @@

/// <reference types="node" />
/// <reference types="bun-types" />
import { DateOptions, NumberOptions, TDate, TUnsafe } from '@sinclair/typebox';
import { type SchemaOptions, type TSchema, TProperties, ObjectOptions, TObject, TNumber, TBoolean } from '@sinclair/typebox';
import { type TypeCheck } from '@sinclair/typebox/compiler';
import { type ValueError, type TypeCheck } from '@sinclair/typebox/compiler';
import type { CookieOptions } from './cookies';

@@ -45,8 +43,8 @@ import type { MaybeArray } from './types';

readonly Files: (options?: ElysiaTypeOptions.Files) => import("@sinclair/typebox").TTransform<TUnsafe<File[]>, File[]>;
readonly Nullable: <T_1 extends TSchema>(schema: T_1) => import("@sinclair/typebox").TUnion<[T_1, import("@sinclair/typebox").TNull]>;
readonly Nullable: <T extends TSchema>(schema: T) => import("@sinclair/typebox").TUnion<[T, import("@sinclair/typebox").TNull]>;
/**
* Allow Optional, Nullable and Undefined
*/
readonly MaybeEmpty: <T_2 extends TSchema>(schema: T_2) => import("@sinclair/typebox").TUnion<[T_2, import("@sinclair/typebox").TNull, import("@sinclair/typebox").TUndefined]>;
readonly Cookie: <T_3 extends TProperties>(properties: T_3, { domain, expires, httpOnly, maxAge, path, priority, sameSite, secure, secrets, sign, ...options }?: ElysiaTypeOptions.CookieValidatorOption<T_3>) => TObject<T_3>;
readonly MaybeEmpty: <T extends TSchema>(schema: T) => import("@sinclair/typebox").TUnion<[T, import("@sinclair/typebox").TNull, import("@sinclair/typebox").TUndefined]>;
readonly Cookie: <T extends TProperties>(properties: T, { domain, expires, httpOnly, maxAge, path, priority, sameSite, secure, secrets, sign, ...options }?: ElysiaTypeOptions.CookieValidatorOption<T>) => TObject<T>;
};

@@ -66,3 +64,8 @@ export type TCookie = (typeof ElysiaType)['Cookie'];

interface SchemaOptions {
error?: string | ((type: string, validator: TypeCheck<any>, value: unknown) => string | void);
error?: string | boolean | number | Object | ((validation: {
errors: ValueError[];
type: string;
validator: TypeCheck<any>;
value: unknown;
}) => string | boolean | number | Object | void);
}

@@ -69,0 +72,0 @@ }

@@ -1,23 +0,47 @@

/// <reference types="bun-types" />
/// <reference types="node" />
/// <reference types="bun-types" />
import type { Elysia } from '.';
import type { Serve, Server, WebSocketHandler } from 'bun';
import type { TSchema, TObject, Static, TAnySchema, TNull, TUndefined } from '@sinclair/typebox';
import type { BunFile, Serve, Server, WebSocketHandler } from 'bun';
import type { TSchema, TObject, Static, TAnySchema, TNull, TUndefined, StaticDecode, OptionalKind } from '@sinclair/typebox';
import type { TypeCheck, ValueError } from '@sinclair/typebox/compiler';
import type { OpenAPIV3 } from 'openapi-types';
import type { CookieOptions } from './cookies';
import type { TraceHandler } from './trace';
import type { Context, ErrorContext, PreContext } from './context';
import type { ELYSIA_RESPONSE, InternalServerError, InvalidCookieSignature, NotFoundError, ParseError, ValidationError } from './error';
import { OptionalKind } from '@sinclair/typebox';
type PartialServe = Partial<Serve>;
export type ElysiaConfig<Prefix extends string | undefined, Scoped extends boolean | undefined> = {
/**
* Path prefix of the instance
*
* @default '''
*/
prefix?: Prefix;
/**
* If set to true, other Elysia handler will not inherits global life-cycle, store, decorators from the current instance
*
* @default false
*/
scoped?: Scoped;
name?: string;
seed?: unknown;
/**
* Bun serve
*
* @see https://bun.sh/docs/api/http
*/
serve?: PartialServe;
tags?: DocumentDecoration['tags'];
/**
* 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

@@ -54,2 +78,4 @@ *

/**
* @deprecated on 1.1, Elysia now use dynamic query by default
*
* Disable sucrose dynamic query inference

@@ -71,5 +97,5 @@ */

/**
* If set to true, other Elysia handler will not inherits global life-cycle, store, decorators from the current instance
* Override websocket configuration
*
* @default false
* @see https://bun.sh/docs/api/websockets
*/

@@ -118,9 +144,16 @@ websocket?: Omit<WebSocketHandler<any>, 'open' | 'close' | 'message' | 'drain'>;

} & {};
export type Reconcile<A extends Object, B extends Object> = {
type IsBothObject<A, B> = A extends Record<string | number | symbol, unknown> ? B extends Record<string | number | symbol, unknown> ? true : false : false;
export type Reconcile<A extends Object, B extends Object, Override extends boolean = false> = 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]: B[key];
[key in keyof B]: IsBothObject<A[key], B[key]> extends true ? Reconcile<A[key], B[key], Override> : B[key];
} : Prettify<Collision & {
[key in keyof B]: B[key];
}> : never;
}> : never : {
[key in keyof B as key extends keyof A ? never : key]: B[key];
} extends infer Collision ? {} extends Collision ? {
[key in keyof A]: IsBothObject<A[key], B[key]> extends true ? Reconcile<A[key], B[key], Override> : A[key];
} : Prettify<{
[key in keyof A]: A[key];
} & Collision> : never;
export interface SingletonBase {

@@ -145,2 +178,3 @@ decorator: Record<string, unknown>;

macro: BaseMacro;
macroFn: BaseMacroFn;
}

@@ -158,4 +192,4 @@ export interface RouteSchema {

};
export type UnwrapSchema<Schema extends TSchema | string | undefined, Definitions extends Record<string, unknown> = {}> = undefined extends Schema ? unknown : Schema extends TSchema ? Schema extends OptionalField ? Prettify<Partial<Static<Schema>>> : Static<Schema> : Schema extends string ? Definitions extends Record<Schema, infer NamedSchema> ? NamedSchema : Definitions : unknown;
export type UnwrapBodySchema<Schema extends TSchema | string | undefined, Definitions extends Record<string, unknown> = {}> = undefined extends Schema ? unknown : Schema extends TSchema ? Schema extends OptionalField ? Prettify<Partial<Static<Schema>>> | null : Static<Schema> : Schema extends string ? Definitions extends Record<Schema, infer NamedSchema> ? NamedSchema : Definitions : unknown;
export type UnwrapSchema<Schema extends TSchema | string | undefined, Definitions extends Record<string, unknown> = {}> = undefined extends Schema ? unknown : Schema extends TSchema ? Schema extends OptionalField ? Prettify<Partial<Static<Schema>>> : StaticDecode<Schema> : Schema extends string ? Definitions extends Record<Schema, infer NamedSchema> ? NamedSchema : Definitions : unknown;
export type UnwrapBodySchema<Schema extends TSchema | string | undefined, Definitions extends Record<string, unknown> = {}> = undefined extends Schema ? unknown : Schema extends TSchema ? Schema extends OptionalField ? Prettify<Partial<Static<Schema>>> | null : StaticDecode<Schema> : Schema extends string ? Definitions extends Record<Schema, infer NamedSchema> ? NamedSchema : Definitions : unknown;
export type SuccessfulResponse<T = unknown> = {

@@ -188,4 +222,4 @@ 200: T;

cookie: UnwrapSchema<Schema['cookie'], Definitions>;
response: Schema['response'] extends TSchema | string ? UnwrapSchema<Schema['response'], Definitions> : Schema['response'] extends SuccessfulResponse<TAnySchema | string> ? {
[k in keyof Schema['response']]: UnwrapSchema<Schema['response'][k], Definitions>;
response: Schema['response'] extends TSchema | string ? CoExist<UnwrapSchema<Schema['response'], Definitions>, File, BunFile> : Schema['response'] extends SuccessfulResponse<TAnySchema | string> ? {
[k in keyof Schema['response']]: CoExist<UnwrapSchema<Schema['response'][k], Definitions>, File, BunFile>;
} : unknown | void;

@@ -218,3 +252,3 @@ }

mapResponse: HookContainer<MapResponse<any, any>>[];
onResponse: HookContainer<VoidHandler<any, any>>[];
afterResponse: HookContainer<VoidHandler<any, any>>[];
trace: HookContainer<TraceHandler<any, any>>[];

@@ -249,2 +283,8 @@ error: HookContainer<ErrorHandler<any, any, any>>[];

}, Path extends string = ''> = (context: Context<Route, Singleton, Path>) => Route['response'] extends SuccessfulResponse ? Response | MaybePromise<Route['response'][keyof Route['response']]> : Response | MaybePromise<Route['response']>;
export type Replace<Original, Target, With> = Original extends Record<string, unknown> ? {
[K in keyof Original]: Original[K] extends Target ? With : Original[K];
} : Original extends Target ? With : Original;
export type CoExist<Original, Target, With> = Original extends Record<string, unknown> ? {
[K in keyof Original]: Original[K] extends Target ? Original[K] | With : Original[K];
} : Original extends Target ? Original | With : Original;
export type InlineHandler<Route extends RouteSchema = {}, Singleton extends SingletonBase = {

@@ -255,3 +295,3 @@ decorator: {};

resolve: {};
}, Path extends string = ''> = ((context: Context<Route, Singleton, Path>) => Route['response'] extends SuccessfulResponse ? Response | MaybePromise<Route['response'][keyof Route['response']] | {
}, Path extends string = '', MacroContext = {}> = ((context: MacroContext extends Record<string | number | symbol, unknown> ? Prettify<MacroContext & Context<Route, Singleton, Path>> : Context<Route, Singleton, Path>) => Route['response'] extends SuccessfulResponse ? Response | MaybePromise<Route['response'][keyof Route['response']] | {
[Status in keyof Route['response']]: {

@@ -304,35 +344,2 @@ _type: Record<Status, Route['response'][Status]>;

};
export type TraceEvent = 'request' | 'parse' | 'transform' | 'beforeHandle' | 'afterHandle' | 'error' | 'response' extends infer Events extends string ? Events | `${Events}.unit` | 'handle' | 'exit' : never;
export type TraceStream = {
id: number;
event: TraceEvent;
type: 'begin' | 'end';
time: number;
name?: string;
unit?: number;
};
export type TraceProcess<Type extends 'begin' | 'end' = 'begin' | 'end'> = Type extends 'begin' ? Prettify<{
name: string;
time: number;
skip: boolean;
end: Promise<TraceProcess<'end'>>;
children: Promise<TraceProcess<'begin'>>[];
}> : number;
export type TraceHandler<in out Route extends RouteSchema = {}, in out Singleton extends SingletonBase = {
decorator: {};
store: {};
derive: {};
resolve: {};
}> = {
(lifecycle: Prettify<{
context: Context<Route, Singleton>;
set: Context['set'];
id: number;
time: number;
} & {
[x in 'request' | 'parse' | 'transform' | 'beforeHandle' | 'handle' | 'afterHandle' | 'error' | 'response']: Promise<TraceProcess<'begin'>>;
} & {
store: Singleton['store'];
}>): MaybePromise<void>;
};
export type BodyHandler<in out Route extends RouteSchema = {}, in out Singleton extends SingletonBase = {

@@ -462,9 +469,9 @@ decorator: {};

/**
* Execute after response is sent
*/
afterResponse?: MaybeArray<VoidHandler<TypedRoute, Singleton>>;
/**
* Catch error
*/
error?: MaybeArray<ErrorHandler<Errors, TypedRoute, Singleton>>;
/**
* Custom body parser
*/
onResponse?: MaybeArray<VoidHandler<TypedRoute, Singleton>>;
tags?: DocumentDecoration['tags'];

@@ -525,4 +532,5 @@ };

};
export type BaseMacro = Record<string, Record<string, unknown> | ((...a: any) => unknown)>;
export type MacroToProperty<in out T extends BaseMacro> = Prettify<{
export type BaseMacro = Record<string, string | number | boolean | Object | undefined | null>;
export type BaseMacroFn = Record<string, (...a: any) => unknown>;
export type MacroToProperty<in out T extends BaseMacroFn> = Prettify<{
[K in keyof T]: T[K] extends Function ? T[K] extends (a: infer Params) => any ? Params | undefined : T[K] : T[K];

@@ -561,9 +569,9 @@ }>;

}, fn: MaybeArray<ErrorHandler<Errors, TypedRoute, Singleton>>): unknown;
onResponse(fn: MaybeArray<VoidHandler<TypedRoute, Singleton>>): unknown;
onResponse(options: {
mapResponse(fn: MaybeArray<VoidHandler<TypedRoute, Singleton>>): unknown;
mapResponse(options: {
insert?: 'before' | 'after';
stack?: 'global' | 'local';
}, fn: MaybeArray<VoidHandler<TypedRoute, Singleton>>): unknown;
mapResponse(fn: MaybeArray<MapResponse<TypedRoute, Singleton>>): unknown;
mapResponse(options: {
onAfterResponse(fn: MaybeArray<MapResponse<TypedRoute, Singleton>>): unknown;
onAfterResponse(options: {
insert?: 'before' | 'after';

@@ -584,3 +592,3 @@ stack?: 'global' | 'local';

export type CreateEden<Path extends string, Property extends Record<string, unknown> = {}> = Path extends `/${infer Rest}` ? _CreateEden<Rest, Property> : Path extends '' ? _CreateEden<'index', Property> : _CreateEden<Path, Property>;
export type ComposeElysiaResponse<Response, Handle> = Handle extends (...a: any[]) => infer A ? _ComposeElysiaResponse<Response, Awaited<A>> : _ComposeElysiaResponse<Response, Awaited<Handle>>;
export type ComposeElysiaResponse<Response, Handle> = Handle extends (...a: any[]) => infer A ? _ComposeElysiaResponse<Response, Replace<Awaited<A>, BunFile, File>> : _ComposeElysiaResponse<Response, Replace<Awaited<Handle>, BunFile, File>>;
type _ComposeElysiaResponse<Response, Handle> = Prettify<unknown extends Response ? {

@@ -610,2 +618,3 @@ 200: Exclude<Handle, {

macro: {};
macroFn: {};
}, Routes extends RouteBase = {}> = Instances extends [

@@ -625,2 +634,3 @@ infer Current extends Elysia<any, any, any, any, any, any>,

macro: Prettify<Metadata['macro']>;
macroFn: Prettify<Metadata['macroFn']>;
}, Routes>;

@@ -640,3 +650,3 @@ export type LifeCycleType = 'global' | 'local' | 'scoped';

export interface ModelValidatorError extends ValueError {
humanReadable: string;
summary: string;
}

@@ -656,2 +666,7 @@ export interface ModelValidator<T> extends TypeCheck<T> {

}
export type UnionToIntersect<U> = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never;
export type ResolveMacroContext<Macro extends BaseMacro, MacroFn extends BaseMacroFn> = UnionToIntersect<{
[K in keyof Macro]-?: undefined extends Macro[K] ? never : K extends keyof MacroFn ? ReturnType<MacroFn[K]> extends infer A extends Record<string | number | symbol, unknown> ? A : never : never;
}[keyof Macro]>;
export type ContextAppendType = 'append' | 'override';
export {};

@@ -0,14 +1,17 @@

import type { BunFile } from 'bun';
import { TSchema } from '@sinclair/typebox';
import { TypeCheck, ValueError } from '@sinclair/typebox/compiler';
import type { LifeCycleStore, LocalHook, MaybeArray, InputSchema, LifeCycleType, HookContainer } from './types';
import { TypeCheck } from '@sinclair/typebox/compiler';
import type { Sucrose } from './sucrose';
import type { LifeCycleStore, LocalHook, MaybeArray, InputSchema, LifeCycleType, HookContainer, Replace } from './types';
import type { CookieOptions } from './cookies';
import { Sucrose } from './sucrose';
export declare const replaceUrlPath: (url: string, pathname: string) => string;
export declare const mergeDeep: <A extends Record<string, any>, B extends Record<string, any>>(target: A, source: B, { skipKeys }?: {
export declare const isClass: (v: Object) => boolean;
export declare const mergeDeep: <A extends Record<string, any>, B extends Record<string, any>>(target: A, source: B, { skipKeys, override }?: {
skipKeys?: string[];
override?: boolean;
}) => A & B;
export declare const mergeCookie: <const A extends Object, const B extends Object>(a: A, b: B) => A & B;
export declare const mergeObjectArray: <T extends HookContainer>(a?: T | T[], b?: T | T[]) => T[];
export declare const primitiveHooks: readonly ["start", "request", "parse", "transform", "resolve", "beforeHandle", "afterHandle", "onResponse", "mapResponse", "trace", "error", "stop", "body", "headers", "params", "query", "response", "type", "detail"];
export declare const mergeResponse: (a: InputSchema['response'], b: InputSchema['response']) => string | TSchema | {
export declare const primitiveHooks: readonly ["start", "request", "parse", "transform", "resolve", "beforeHandle", "afterHandle", "mapResponse", "afterResponse", "trace", "error", "stop", "body", "headers", "params", "query", "response", "type", "detail"];
export declare const mergeResponse: (a: InputSchema["response"], b: InputSchema["response"]) => string | TSchema | {
[x: number]: any;

@@ -19,3 +22,3 @@ } | undefined;

}) => LifeCycleStore;
export declare const getSchemaValidator: (s: TSchema | string | undefined, { models, dynamic, normalize, additionalProperties }?: {
export declare const getSchemaValidator: <T extends TSchema | string | undefined>(s: T, { models, dynamic, normalize, additionalProperties }?: {
models?: Record<string, TSchema>;

@@ -25,12 +28,4 @@ additionalProperties?: boolean;

normalize?: boolean;
}) => TypeCheck<TSchema> | undefined;
export declare const mapValueError: (error: ValueError) => {
humanReadable: string;
type: import("@sinclair/typebox/value").ValueErrorType;
schema: TSchema;
path: string;
value: unknown;
message: string;
};
export declare const getResponseSchemaValidator: (s: InputSchema['response'] | undefined, { models, dynamic, normalize, additionalProperties }: {
}) => T extends TSchema ? TypeCheck<TSchema> : undefined;
export declare const getResponseSchemaValidator: (s: InputSchema["response"] | undefined, { models, dynamic, normalize, additionalProperties }: {
models?: Record<string, TSchema>;

@@ -116,64 +111,3 @@ additionalProperties?: boolean;

};
export declare const InvertedStatusMap: {
readonly 100: "Continue";
readonly 101: "Switching Protocols";
readonly 102: "Processing";
readonly 103: "Early Hints";
readonly 200: "OK";
readonly 201: "Created";
readonly 202: "Accepted";
readonly 203: "Non-Authoritative Information";
readonly 204: "No Content";
readonly 205: "Reset Content";
readonly 206: "Partial Content";
readonly 207: "Multi-Status";
readonly 208: "Already Reported";
readonly 300: "Multiple Choices";
readonly 301: "Moved Permanently";
readonly 302: "Found";
readonly 303: "See Other";
readonly 304: "Not Modified";
readonly 307: "Temporary Redirect";
readonly 308: "Permanent Redirect";
readonly 400: "Bad Request";
readonly 401: "Unauthorized";
readonly 402: "Payment Required";
readonly 403: "Forbidden";
readonly 404: "Not Found";
readonly 405: "Method Not Allowed";
readonly 406: "Not Acceptable";
readonly 407: "Proxy Authentication Required";
readonly 408: "Request Timeout";
readonly 409: "Conflict";
readonly 410: "Gone";
readonly 411: "Length Required";
readonly 412: "Precondition Failed";
readonly 413: "Payload Too Large";
readonly 414: "URI Too Long";
readonly 415: "Unsupported Media Type";
readonly 416: "Range Not Satisfiable";
readonly 417: "Expectation Failed";
readonly 418: "I'm a teapot";
readonly 421: "Misdirected Request";
readonly 422: "Unprocessable Content";
readonly 423: "Locked";
readonly 424: "Failed Dependency";
readonly 425: "Too Early";
readonly 426: "Upgrade Required";
readonly 428: "Precondition Required";
readonly 429: "Too Many Requests";
readonly 431: "Request Header Fields Too Large";
readonly 451: "Unavailable For Legal Reasons";
readonly 500: "Internal Server Error";
readonly 501: "Not Implemented";
readonly 502: "Bad Gateway";
readonly 503: "Service Unavailable";
readonly 504: "Gateway Timeout";
readonly 505: "HTTP Version Not Supported";
readonly 506: "Variant Also Negotiates";
readonly 507: "Insufficient Storage";
readonly 508: "Loop Detected";
readonly 510: "Not Extended";
readonly 511: "Network Authentication Required";
};
export declare const InvertedStatusMap: { [K in keyof StatusMap as StatusMap[K]]: K; };
export type StatusMap = typeof StatusMap;

@@ -188,4 +122,4 @@ export type InvertedStatusMap = typeof InvertedStatusMap;

}) => (stackName: keyof LifeCycleStore) => (type: {
insert?: 'before' | 'after';
stack?: 'global' | 'local';
insert?: "before" | "after";
stack?: "global" | "local";
} | MaybeArray<HookContainer>, fn?: MaybeArray<HookContainer>) => void;

@@ -217,6 +151,4 @@ export declare const isNumericString: (message: string) => boolean;

headers: boolean;
queries: string[];
query: boolean;
set: boolean;
unknownQueries: boolean;
};

@@ -228,4 +160,13 @@ /**

*/
export declare const redirect: (url: string, status?: number) => import("undici-types").Response;
export declare const redirect: (url: string, status?: 301 | 302 | 303 | 307 | 308) => import("undici-types").Response;
export type redirect = typeof redirect;
export declare const ELYSIA_FORM_DATA: unique symbol;
export type ELYSIA_FORM_DATA = typeof ELYSIA_FORM_DATA;
type ElysiaFormData<T extends Record<string | number, unknown>> = FormData & {
[ELYSIA_FORM_DATA]: Replace<T, BunFile, File>;
};
export declare const ELYSIA_REQUEST_ID: unique symbol;
export type ELYSIA_REQUEST_ID = typeof ELYSIA_REQUEST_ID;
export declare const form: <const T extends Record<string | number, unknown>>(items: T) => ElysiaFormData<T>;
export declare const randomId: () => number;
export {};

@@ -1,3 +0,1 @@

/// <reference types="bun-types" />
/// <reference types="bun-types" />
import type { ServerWebSocket, WebSocketHandler } from 'bun';

@@ -24,4 +22,4 @@ import type { TSchema } from '@sinclair/typebox';

set id(newID: string);
get publish(): (topic: string, data?: Route['response'], compress?: boolean) => this;
get send(): (data: Route['response']) => this;
get publish(): (topic: string, data?: Route["response"], compress?: boolean) => this;
get send(): (data: Route["response"]) => this;
get subscribe(): (room: string) => this;

@@ -28,0 +26,0 @@ get unsubscribe(): (room: string) => this;

@@ -1,4 +0,1 @@

/// <reference types="bun-types" />
/// <reference types="bun-types" />
/// <reference types="bun-types" />
import type { ServerWebSocket, WebSocketHandler } from 'bun';

@@ -5,0 +2,0 @@ import type { TSchema } from '@sinclair/typebox';

{
"name": "elysia",
"description": "Ergonomic Framework for Human",
"version": "1.1.0-exp.0",
"version": "1.1.0-exp.1",
"author": {

@@ -14,2 +14,3 @@ "name": "saltyAom",

"exports": {
"./package.json": "./package.json",
".": {

@@ -94,3 +95,3 @@ "types": "./dist/index.d.ts",

"test:node": "npm install --prefix ./test/node/cjs/ && npm install --prefix ./test/node/esm/ && node ./test/node/cjs/index.js && node ./test/node/esm/index.js && bun dist/bun/index.js",
"dev": "bun run --watch example/http.ts",
"dev": "bun run --watch example/a.ts",
"build": "rimraf dist && bun build.ts",

@@ -119,3 +120,3 @@ "release:local": "npm run build && npm run test && npm publish"

"tsup": "^8.0.2",
"typescript": "^5.4.5"
"typescript": "^5.5.1-rc"
},

@@ -122,0 +123,0 @@ "peerDependencies": {

@@ -39,3 +39,3 @@ {

// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
"resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

@@ -42,0 +42,0 @@

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc