elysia 2.0.0-exp.10 → 2.0.0-exp.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,7 +6,7 @@ import { AnyElysia } from "../../base.js";
6
6
  declare function collectStaticRoutes(app: AnyElysia): readonly [Record<string, Record<string, Response>>, Promise<void>[]] | undefined;
7
7
  declare const BunAdapter: {
8
8
  parse: {
9
- default: (context: Context, contentType: string) => string | ArrayBuffer | unknown[] | Record<string, unknown> | Promise<Record<string, unknown>> | Promise<ArrayBuffer> | Promise<string> | Promise<unknown[] | Record<string | number | symbol, undefined>> | undefined;
9
+ default: (context: Context, contentType: string) => string | unknown[] | ArrayBuffer | Record<string, unknown> | Promise<unknown[] | Record<string | number | symbol, undefined>> | Promise<ArrayBuffer> | Promise<Record<string, unknown>> | Promise<string> | undefined;
10
10
  json: (context: Context) => MaybePromise<Record<keyof any, undefined> | unknown[]>;
11
11
  text: (context: Context) => MaybePromise<string>;
12
12
  urlencoded: (context: Context) => MaybePromise<Record<string, string | string[]>>;
@@ -47,6 +47,8 @@ const BunAdapter = require_adapter_index.createAdapter({
47
47
  const hasWs = app["~hasWS"];
48
48
  if (!serve.fetch) serve.fetch = (request, server) => app.fetch(request, server);
49
49
  app.server = Bun.serve(serve);
50
+ const onSetup = app["~ext"]?.setup;
51
+ if (onSetup) for (let i = 0; i < onSetup.length; i++) onSetup[i](app);
50
52
  if (!hasWs) callback?.(app.server);
51
53
  queueMicrotask(() => {
52
54
  if (!app.pending) serve.fetch = app.fetch;
@@ -46,6 +46,8 @@ const BunAdapter = createAdapter({
46
46
  const hasWs = app["~hasWS"];
47
47
  if (!serve.fetch) serve.fetch = (request, server) => app.fetch(request, server);
48
48
  app.server = Bun.serve(serve);
49
+ const onSetup = app["~ext"]?.setup;
50
+ if (onSetup) for (let i = 0; i < onSetup.length; i++) onSetup[i](app);
49
51
  if (!hasWs) callback?.(app.server);
50
52
  queueMicrotask(() => {
51
53
  if (!app.pending) serve.fetch = app.fetch;
@@ -5,7 +5,7 @@ import { AnyElysia } from "../base.js";
5
5
  //#region src/adapter/constants.d.ts
6
6
  declare const defaultAdapter: {
7
7
  parse: {
8
- default: (context: Context, contentType: string) => string | ArrayBuffer | unknown[] | Record<string, unknown> | Promise<Record<string, unknown>> | Promise<ArrayBuffer> | Promise<string> | Promise<unknown[] | Record<string | number | symbol, undefined>> | undefined;
8
+ default: (context: Context, contentType: string) => string | unknown[] | ArrayBuffer | Record<string, unknown> | Promise<unknown[] | Record<string | number | symbol, undefined>> | Promise<ArrayBuffer> | Promise<Record<string, unknown>> | Promise<string> | undefined;
9
9
  json: (context: Context) => MaybePromise<Record<keyof any, undefined> | unknown[]>;
10
10
  text: (context: Context) => MaybePromise<string>;
11
11
  urlencoded: (context: Context) => MaybePromise<Record<string, string | string[]>>;
@@ -7,7 +7,7 @@ import { AnyElysia } from "../base.js";
7
7
  //#region src/adapter/index.d.ts
8
8
  declare function createAdapter(adapter: ElysiaAdapterOptions): {
9
9
  parse: {
10
- default: (context: Context, contentType: string) => string | ArrayBuffer | unknown[] | Record<string, unknown> | Promise<Record<string, unknown>> | Promise<ArrayBuffer> | Promise<string> | Promise<unknown[] | Record<string | number | symbol, undefined>> | undefined;
10
+ default: (context: Context, contentType: string) => string | unknown[] | ArrayBuffer | Record<string, unknown> | Promise<unknown[] | Record<string | number | symbol, undefined>> | Promise<ArrayBuffer> | Promise<Record<string, unknown>> | Promise<string> | undefined;
11
11
  json: (context: Context) => MaybePromise<Record<keyof any, undefined> | unknown[]>;
12
12
  text: (context: Context) => MaybePromise<string>;
13
13
  urlencoded: (context: Context) => MaybePromise<Record<string, string | string[]>>;
@@ -12,7 +12,7 @@ declare function responseToSetHeaders(response: Response, set?: Context['set']):
12
12
  cookie?: Record<string, BaseCookie>;
13
13
  } | {
14
14
  headers: any;
15
- status: number | "Bad Request" | "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" | "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" | "Enhance Your Calm" | "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";
15
+ status: 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" | "Enhance Your Calm" | "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";
16
16
  };
17
17
  interface CreateHandlerParameter {
18
18
  mapResponse(response: unknown, set: Context['set'], request?: Request): Response;
@@ -5,7 +5,7 @@ import { AnyElysia } from "../../base.js";
5
5
  //#region src/adapter/web-standard/index.d.ts
6
6
  declare const WebStandardAdapter: {
7
7
  parse: {
8
- default: (context: Context, contentType: string) => string | ArrayBuffer | unknown[] | Record<string, unknown> | Promise<Record<string, unknown>> | Promise<ArrayBuffer> | Promise<string> | Promise<unknown[] | Record<string | number | symbol, undefined>> | undefined;
8
+ default: (context: Context, contentType: string) => string | unknown[] | ArrayBuffer | Record<string, unknown> | Promise<unknown[] | Record<string | number | symbol, undefined>> | Promise<ArrayBuffer> | Promise<Record<string, unknown>> | Promise<string> | undefined;
9
9
  json: (context: Context) => MaybePromise<Record<keyof any, undefined> | unknown[]>;
10
10
  text: (context: Context) => MaybePromise<string>;
11
11
  urlencoded: (context: Context) => MaybePromise<Record<string, string | string[]>>;
package/dist/base.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ElysiaStatus } from "./error.js";
2
2
  import { TraceHandler } from "./trace.js";
3
3
  import { ListenCallback, Serve, Server } from "./universal/server.js";
4
- import { AddRoute, AddWSRoute, AfterHandler, AfterResponseHandler, AnyErrorConstructor, AnyLocalHook, BodyHandler, CompiledHandler, CreateEden, DefaultEphemeral, DefaultMetadata, DefaultSingleton, DefinitionBase, DocumentDecoration, ElysiaConfig, ElysiaHandlerToResponseSchemaAmbiguous, EphemeralType, ErrorDefinitionEntry, ErrorHandler, EventScope, ExcludeElysiaResponse, ExtractErrorFromHandle, GuardLocalHook, HTTPMethod, InlineHandler, InlineHandlerNonMacro, InputSchema, InputSchemaKey, InternalRoute, IntersectIfObjectSchema, JoinPath, LocalHook, Macro, MacroToContext, MacroToProperty, MapResponse, MaybeArray, MaybePromise, MergeElysiaInstances, MergeSchema, MergeScopedSchemas, MetadataBase, NonResolvableMacroKey, ObjectMacroDefs, OptionalHandler, PreHandler, Prettify, PublicRoute, ResolveRouteErrors, RouteBase, SingletonBase, TransformHandler, UnionResponseStatus, UnwrapRoute, WrapFn } from "./types.js";
4
+ import { AddRoute, AddWSRoute, AfterHandler, AfterResponseHandler, AnyErrorConstructor, AnyLocalHook, BodyHandler, CompiledHandler, CreateEden, DefaultEphemeral, DefaultMetadata, DefaultSingleton, DefinitionBase, DocumentDecoration, ElysiaConfig, ElysiaHandlerToResponseSchemaAmbiguous, EphemeralType, ErrorDefinitionEntry, ErrorHandler, EventScope, ExcludeElysiaResponse, ExtractErrorFromHandle, GracefulHandler, GuardLocalHook, HTTPMethod, InlineHandler, InlineHandlerNonMacro, InputSchema, InputSchemaKey, InternalRoute, IntersectIfObjectSchema, JoinPath, LocalHook, Macro, MacroToContext, MacroToProperty, MapResponse, MaybeArray, MaybePromise, MergeElysiaInstances, MergeSchema, MergeScopedSchemas, MetadataBase, NonResolvableMacroKey, ObjectMacroDefs, OptionalHandler, PreHandler, Prettify, PublicRoute, ResolveRouteErrors, RouteBase, SingletonBase, TransformHandler, UnionResponseStatus, UnwrapRoute, WrapFn } from "./types.js";
5
5
  import { AnySchema } from "./type/types.js";
6
6
  import { ChainNode } from "./utils.js";
7
7
  import { Context, ErrorContext, LifecycleContext } from "./context.js";
@@ -34,6 +34,8 @@ declare class Elysia<const in out BasePath extends string = '', const in out Sco
34
34
  error?: Map<AnyErrorConstructor, string>;
35
35
  parser?: Record<string, BodyHandler<any, any>>;
36
36
  hoc?: WrapFn<any>[];
37
+ setup?: GracefulHandler<any>[];
38
+ cleanup?: GracefulHandler<any>[];
37
39
  };
38
40
  '~hookChain'?: ChainNode;
39
41
  server?: Server;
@@ -175,8 +177,21 @@ declare class Elysia<const in out BasePath extends string = '', const in out Sco
175
177
  parser: Metadata['parser'] & { [name in Name]: BodyHandler<any, any> };
176
178
  response: Metadata['response'];
177
179
  }, Routes, Ephemeral, Volatile>;
178
- onStart(_listener?: unknown): this;
179
- onStop(_listener?: unknown): this;
180
+ /**
181
+ * ### setup | Life cycle event
182
+ * Called after server is ready for serving
183
+ *
184
+ * ---
185
+ * @example
186
+ * ```typescript
187
+ * new Elysia()
188
+ * .setup(({ server }) => {
189
+ * console.log("Running at ${server?.url}:${server?.port}")
190
+ * })
191
+ * .listen(3000)
192
+ * ```
193
+ */
194
+ setup(handler: MaybeArray<GracefulHandler<this>>): this;
180
195
  transform(fn: MaybeArray<TransformHandler<MergeSchema<{}, {}, BasePath>, Singleton & {
181
196
  derive: Ephemeral['derive'] & Volatile['derive'];
182
197
  }>>): this;
@@ -495,62 +510,6 @@ declare class Elysia<const in out BasePath extends string = '', const in out Sco
495
510
  parser: Metadata['parser'];
496
511
  response: UnionResponseStatus<Metadata['response'], UnionResponseStatus<Ephemeral['response'], Volatile['response']>>;
497
512
  }, Routes, DefaultEphemeral, DefaultEphemeral>;
498
- guard<const Input extends Metadata['macro'] & InputSchema<keyof Definitions['typebox'] & string>, const Schema extends MergeSchema<UnwrapRoute<Input, Definitions['typebox'], BasePath>, MergeSchema<Volatile['schema'], MergeSchema<Ephemeral['schema'], Metadata['schema']>>> & Metadata['schemas'] & Ephemeral['schemas'] & Volatile['schemas'], const MacroContext extends ({} extends Metadata['macroFn'] ? {} : MacroToContext<Metadata['macroFn'], Omit<Input, NonResolvableMacroKey>, Definitions['typebox']>), const BeforeHandle extends MaybeArray<OptionalHandler<Schema, Singleton>>, const AfterHandle extends MaybeArray<AfterHandler<Schema, Singleton>>, const ErrorHandle extends MaybeArray<ErrorHandler<Definitions['error'], Schema, Singleton>>>(hook: GuardLocalHook<Input, Schema & MacroContext, Singleton & {
499
- derive: Ephemeral['derive'] & Volatile['derive'] & MacroContext['response'];
500
- }, keyof Metadata['parser'], BeforeHandle, AfterHandle, ErrorHandle> & {
501
- as: 'plugin';
502
- schema: 'standalone';
503
- }): Elysia<BasePath, Scope, Singleton, Definitions, Metadata, Routes, {
504
- derive: Ephemeral['derive'] & MacroContext['resolve'];
505
- schema: Ephemeral['schema'];
506
- schemas: Ephemeral['schemas'] & UnwrapRoute<Input, Definitions['typebox']> & MacroContext;
507
- response: UnionResponseStatus<Ephemeral['response'], ElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> & ElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> & ElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle> & MacroContext['return']>;
508
- error: Ephemeral['error'];
509
- }, Volatile>;
510
- guard<const Input extends Metadata['macro'] & InputSchema<keyof Definitions['typebox'] & string>, const Schema extends MergeSchema<UnwrapRoute<Input, Definitions['typebox'], BasePath>, MergeSchema<Volatile['schema'], MergeSchema<Ephemeral['schema'], Metadata['schema']>>> & Metadata['schemas'] & Ephemeral['schemas'] & Volatile['schemas'], const MacroContext extends ({} extends Metadata['macroFn'] ? {} : MacroToContext<Metadata['macroFn'], Omit<Input, NonResolvableMacroKey>, Definitions['typebox']>), const BeforeHandle extends MaybeArray<OptionalHandler<Schema, Singleton>>, const AfterHandle extends MaybeArray<AfterHandler<Schema, Singleton>>, const ErrorHandle extends MaybeArray<ErrorHandler<Definitions['error'], Schema, Singleton>>>(hook: GuardLocalHook<Input, Schema & MacroContext, Singleton & {
511
- derive: Ephemeral['derive'] & Volatile['derive'] & MacroContext['response'];
512
- }, keyof Metadata['parser'], BeforeHandle, AfterHandle, ErrorHandle, 'override'> & {
513
- as: 'plugin';
514
- }): Elysia<BasePath, Scope, Singleton, Definitions, Metadata, Routes, {
515
- derive: Ephemeral['derive'] & MacroContext['resolve'];
516
- schema: {} extends Pick<Input, Extract<keyof Input, InputSchemaKey>> ? Ephemeral['schema'] : MergeSchema<UnwrapRoute<Input, Definitions['typebox']>, Ephemeral['schema']>;
517
- schemas: Ephemeral['schemas'] & MacroContext;
518
- response: UnionResponseStatus<Ephemeral['response'], ElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> & ElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> & ElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle> & MacroContext['return']>;
519
- error: Ephemeral['error'];
520
- }, Volatile>;
521
- guard<const Input extends Metadata['macro'] & InputSchema<keyof Definitions['typebox'] & string>, const Schema extends MergeSchema<UnwrapRoute<Input, Definitions['typebox'], BasePath>, MergeSchema<Volatile['schema'], MergeSchema<Ephemeral['schema'], Metadata['schema']>>> & Metadata['schemas'] & Ephemeral['schemas'] & Volatile['schemas'], const MacroContext extends ({} extends Metadata['macroFn'] ? {} : MacroToContext<Metadata['macroFn'], Omit<Input, NonResolvableMacroKey>, Definitions['typebox']>), const BeforeHandle extends MaybeArray<OptionalHandler<Schema, Singleton>>, const AfterHandle extends MaybeArray<AfterHandler<Schema, Singleton>>, const ErrorHandle extends MaybeArray<ErrorHandler<Definitions['error'], Schema, Singleton>>>(hook: GuardLocalHook<Input, Schema & MacroContext, Singleton & {
522
- derive: Ephemeral['derive'] & Volatile['derive'] & MacroContext['response'];
523
- }, keyof Metadata['parser'], BeforeHandle, AfterHandle, ErrorHandle> & {
524
- as: 'global';
525
- schema: 'standalone';
526
- }): Elysia<BasePath, Scope, {
527
- decorator: Singleton['decorator'];
528
- store: Singleton['store'];
529
- derive: Singleton['derive'] & MacroContext['resolve'];
530
- }, Definitions, {
531
- schema: Metadata['schema'];
532
- schemas: Metadata['schemas'] & UnwrapRoute<Input, Definitions['typebox']> & MacroContext;
533
- macro: Metadata['macro'];
534
- macroFn: Metadata['macroFn'];
535
- parser: Metadata['parser'];
536
- response: UnionResponseStatus<Metadata['response'], ElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> & ElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> & ElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle> & MacroContext['return']>;
537
- }, Routes, Ephemeral, Volatile>;
538
- guard<const Input extends Metadata['macro'] & InputSchema<keyof Definitions['typebox'] & string>, const Schema extends MergeSchema<UnwrapRoute<Input, Definitions['typebox'], BasePath>, MergeSchema<Volatile['schema'], MergeSchema<Ephemeral['schema'], Metadata['schema']>>> & Metadata['schemas'] & Ephemeral['schemas'] & Volatile['schemas'], const MacroContext extends ({} extends Metadata['macroFn'] ? {} : MacroToContext<Metadata['macroFn'], Omit<Input, NonResolvableMacroKey>, Definitions['typebox']>), const BeforeHandle extends MaybeArray<OptionalHandler<Schema, Singleton>>, const AfterHandle extends MaybeArray<AfterHandler<Schema, Singleton>>, const ErrorHandle extends MaybeArray<ErrorHandler<Definitions['error'], Schema, Singleton>>>(hook: GuardLocalHook<Input, Schema & MacroContext, Singleton & {
539
- derive: Ephemeral['derive'] & Volatile['derive'] & MacroContext['response'];
540
- }, keyof Metadata['parser'], BeforeHandle, AfterHandle, ErrorHandle, 'override'> & {
541
- as: 'global';
542
- }): Elysia<BasePath, Scope, {
543
- decorator: Singleton['decorator'];
544
- store: Singleton['store'];
545
- derive: Singleton['derive'] & MacroContext['resolve'];
546
- }, Definitions, {
547
- schema: {} extends Pick<Input, Extract<keyof Input, InputSchemaKey>> ? Metadata['schema'] : MergeSchema<UnwrapRoute<Input, Definitions['typebox']>, Metadata['schema']>;
548
- schemas: Metadata['schemas'] & MacroContext;
549
- macro: Metadata['macro'];
550
- macroFn: Metadata['macroFn'];
551
- parser: Metadata['parser'];
552
- response: UnionResponseStatus<Metadata['response'], ElysiaHandlerToResponseSchemaAmbiguous<BeforeHandle> & ElysiaHandlerToResponseSchemaAmbiguous<AfterHandle> & ElysiaHandlerToResponseSchemaAmbiguous<ErrorHandle> & MacroContext['return']>;
553
- }, Routes, Ephemeral, Volatile>;
554
513
  guard<const Input extends Metadata['macro'] & InputSchema<keyof Definitions['typebox'] & string>, const Schema extends MergeSchema<UnwrapRoute<Input, Definitions['typebox'], BasePath>, MergeSchema<Volatile['schema'], MergeSchema<Ephemeral['schema'], Metadata['schema']>>> & Metadata['schemas'] & Ephemeral['schemas'] & Volatile['schemas'], const MacroContext extends ({} extends Metadata['macroFn'] ? {} : MacroToContext<Metadata['macroFn'], Omit<Input, NonResolvableMacroKey>, Definitions['typebox']>), const BeforeHandle extends MaybeArray<OptionalHandler<Schema, Singleton>>, const AfterHandle extends MaybeArray<AfterHandler<Schema, Singleton>>, const ErrorHandle extends MaybeArray<ErrorHandler<Definitions['error'], Schema, Singleton>>>(hook: GuardLocalHook<Input, Schema & MacroContext, Singleton & {
555
514
  derive: Ephemeral['derive'] & Volatile['derive'] & MacroContext['response'];
556
515
  }, keyof Metadata['parser'], BeforeHandle, AfterHandle, ErrorHandle> & {
@@ -1046,7 +1005,22 @@ declare class Elysia<const in out BasePath extends string = '', const in out Sco
1046
1005
  listen(options: string | number | Partial<Serve>, callback?: ListenCallback): this;
1047
1006
  wrap<T extends (...params: any) => MaybePromise<Response> = (request: Request, ...rest: any[]) => MaybePromise<Response>>(callback: WrapFn<T>): this;
1048
1007
  /**
1049
- * Stop the underlying server (if any). Mirrors `Server.stop()`.
1008
+ * ### cleanup | Life cycle event
1009
+ * Called after server stop serving request
1010
+ *
1011
+ * ---
1012
+ * @example
1013
+ * ```typescript
1014
+ * new Elysia()
1015
+ * .cleanup((app) => {
1016
+ * closeDatabase()
1017
+ * })
1018
+ * ```
1019
+ */
1020
+ cleanup(handler: MaybeArray<GracefulHandler<this>>): this;
1021
+ /**
1022
+ * Stop the underlying server (if any), running every `cleanup` handler once
1023
+ * it has stopped. Mirrors `Server.stop()`.
1050
1024
  *
1051
1025
  * @param closeActiveConnections Pass `true` to terminate in-flight
1052
1026
  * requests and WebSocket connections immediately. Defaults to
package/dist/base.js CHANGED
@@ -173,10 +173,24 @@ var Elysia = class Elysia {
173
173
  parsers[name] = fn;
174
174
  return this;
175
175
  }
176
- onStart(_listener) {
177
- return this;
178
- }
179
- onStop(_listener) {
176
+ /**
177
+ * ### setup | Life cycle event
178
+ * Called after server is ready for serving
179
+ *
180
+ * ---
181
+ * @example
182
+ * ```typescript
183
+ * new Elysia()
184
+ * .setup(({ server }) => {
185
+ * console.log("Running at ${server?.url}:${server?.port}")
186
+ * })
187
+ * .listen(3000)
188
+ * ```
189
+ */
190
+ setup(handler) {
191
+ const arr = this.#ext.setup ??= [];
192
+ if (Array.isArray(handler)) arr.push(...handler);
193
+ else arr.push(handler);
180
194
  return this;
181
195
  }
182
196
  transform(scopeOrFn, fn) {
@@ -258,15 +272,7 @@ var Elysia = class Elysia {
258
272
  }
259
273
  }
260
274
  guard() {
261
- if (arguments.length === 1) {
262
- const arg = arguments[0];
263
- let scope = "local";
264
- if (arg && typeof arg === "object" && "as" in arg && arg.as) {
265
- scope = arg.as;
266
- delete arg.as;
267
- }
268
- return this.#guard(scope, arg);
269
- }
275
+ if (arguments.length === 1) return this.#guard("local", arguments[0]);
270
276
  if (arguments.length === 2) {
271
277
  if (typeof arguments[1] === "function") return this.group("", arguments[0], arguments[1]);
272
278
  return this.#guard(arguments[0], arguments[1]);
@@ -526,7 +532,7 @@ var Elysia = class Elysia {
526
532
  }
527
533
  const hookChain = app["~hookChain"];
528
534
  if (app["~ext"]) {
529
- const { decorator, store, headers, models, parser, macro, error, hoc } = app["~ext"];
535
+ const { decorator, store, headers, models, parser, macro, error, hoc, setup, cleanup } = app["~ext"];
530
536
  const ext = this["~ext"] ??= require_utils.nullObject();
531
537
  if (decorator) {
532
538
  const cloned = require_utils.clonePlainDecorators(decorator);
@@ -548,6 +554,12 @@ var Elysia = class Elysia {
548
554
  if (hoc) if (ext.hoc) {
549
555
  for (const fn of hoc) if (!ext.hoc.includes(fn)) ext.hoc.push(fn);
550
556
  } else ext.hoc = hoc.slice();
557
+ if (setup) if (ext.setup) {
558
+ for (const fn of setup) if (!ext.setup.includes(fn)) ext.setup.push(fn);
559
+ } else ext.setup = setup.slice();
560
+ if (cleanup) if (ext.cleanup) {
561
+ for (const fn of cleanup) if (!ext.cleanup.includes(fn)) ext.cleanup.push(fn);
562
+ } else ext.cleanup = cleanup.slice();
551
563
  }
552
564
  if (app.#hasPlugin || app.#hasGlobal || hookChain) {
553
565
  let pluginEvents;
@@ -1022,7 +1034,27 @@ var Elysia = class Elysia {
1022
1034
  return this;
1023
1035
  }
1024
1036
  /**
1025
- * Stop the underlying server (if any). Mirrors `Server.stop()`.
1037
+ * ### cleanup | Life cycle event
1038
+ * Called after server stop serving request
1039
+ *
1040
+ * ---
1041
+ * @example
1042
+ * ```typescript
1043
+ * new Elysia()
1044
+ * .cleanup((app) => {
1045
+ * closeDatabase()
1046
+ * })
1047
+ * ```
1048
+ */
1049
+ cleanup(handler) {
1050
+ const arr = this.#ext.cleanup ??= [];
1051
+ if (Array.isArray(handler)) arr.push(...handler);
1052
+ else arr.push(handler);
1053
+ return this;
1054
+ }
1055
+ /**
1056
+ * Stop the underlying server (if any), running every `cleanup` handler once
1057
+ * it has stopped. Mirrors `Server.stop()`.
1026
1058
  *
1027
1059
  * @param closeActiveConnections Pass `true` to terminate in-flight
1028
1060
  * requests and WebSocket connections immediately. Defaults to
@@ -1033,6 +1065,12 @@ var Elysia = class Elysia {
1033
1065
  if (!server) return;
1034
1066
  const r = server.stop?.(closeActiveConnections);
1035
1067
  this.server = void 0;
1068
+ const handlers = this["~ext"]?.cleanup;
1069
+ const fire = handlers ? () => {
1070
+ for (let i = 0; i < handlers.length; i++) handlers[i](this);
1071
+ } : void 0;
1072
+ if (r && typeof r.then === "function") return fire ? r.then(fire) : r;
1073
+ fire?.();
1036
1074
  return r;
1037
1075
  }
1038
1076
  };
package/dist/base.mjs CHANGED
@@ -170,10 +170,24 @@ var Elysia = class Elysia {
170
170
  parsers[name] = fn;
171
171
  return this;
172
172
  }
173
- onStart(_listener) {
174
- return this;
175
- }
176
- onStop(_listener) {
173
+ /**
174
+ * ### setup | Life cycle event
175
+ * Called after server is ready for serving
176
+ *
177
+ * ---
178
+ * @example
179
+ * ```typescript
180
+ * new Elysia()
181
+ * .setup(({ server }) => {
182
+ * console.log("Running at ${server?.url}:${server?.port}")
183
+ * })
184
+ * .listen(3000)
185
+ * ```
186
+ */
187
+ setup(handler) {
188
+ const arr = this.#ext.setup ??= [];
189
+ if (Array.isArray(handler)) arr.push(...handler);
190
+ else arr.push(handler);
177
191
  return this;
178
192
  }
179
193
  transform(scopeOrFn, fn) {
@@ -255,15 +269,7 @@ var Elysia = class Elysia {
255
269
  }
256
270
  }
257
271
  guard() {
258
- if (arguments.length === 1) {
259
- const arg = arguments[0];
260
- let scope = "local";
261
- if (arg && typeof arg === "object" && "as" in arg && arg.as) {
262
- scope = arg.as;
263
- delete arg.as;
264
- }
265
- return this.#guard(scope, arg);
266
- }
272
+ if (arguments.length === 1) return this.#guard("local", arguments[0]);
267
273
  if (arguments.length === 2) {
268
274
  if (typeof arguments[1] === "function") return this.group("", arguments[0], arguments[1]);
269
275
  return this.#guard(arguments[0], arguments[1]);
@@ -523,7 +529,7 @@ var Elysia = class Elysia {
523
529
  }
524
530
  const hookChain = app["~hookChain"];
525
531
  if (app["~ext"]) {
526
- const { decorator, store, headers, models, parser, macro, error, hoc } = app["~ext"];
532
+ const { decorator, store, headers, models, parser, macro, error, hoc, setup, cleanup } = app["~ext"];
527
533
  const ext = this["~ext"] ??= nullObject();
528
534
  if (decorator) {
529
535
  const cloned = clonePlainDecorators(decorator);
@@ -545,6 +551,12 @@ var Elysia = class Elysia {
545
551
  if (hoc) if (ext.hoc) {
546
552
  for (const fn of hoc) if (!ext.hoc.includes(fn)) ext.hoc.push(fn);
547
553
  } else ext.hoc = hoc.slice();
554
+ if (setup) if (ext.setup) {
555
+ for (const fn of setup) if (!ext.setup.includes(fn)) ext.setup.push(fn);
556
+ } else ext.setup = setup.slice();
557
+ if (cleanup) if (ext.cleanup) {
558
+ for (const fn of cleanup) if (!ext.cleanup.includes(fn)) ext.cleanup.push(fn);
559
+ } else ext.cleanup = cleanup.slice();
548
560
  }
549
561
  if (app.#hasPlugin || app.#hasGlobal || hookChain) {
550
562
  let pluginEvents;
@@ -1019,7 +1031,27 @@ var Elysia = class Elysia {
1019
1031
  return this;
1020
1032
  }
1021
1033
  /**
1022
- * Stop the underlying server (if any). Mirrors `Server.stop()`.
1034
+ * ### cleanup | Life cycle event
1035
+ * Called after server stop serving request
1036
+ *
1037
+ * ---
1038
+ * @example
1039
+ * ```typescript
1040
+ * new Elysia()
1041
+ * .cleanup((app) => {
1042
+ * closeDatabase()
1043
+ * })
1044
+ * ```
1045
+ */
1046
+ cleanup(handler) {
1047
+ const arr = this.#ext.cleanup ??= [];
1048
+ if (Array.isArray(handler)) arr.push(...handler);
1049
+ else arr.push(handler);
1050
+ return this;
1051
+ }
1052
+ /**
1053
+ * Stop the underlying server (if any), running every `cleanup` handler once
1054
+ * it has stopped. Mirrors `Server.stop()`.
1023
1055
  *
1024
1056
  * @param closeActiveConnections Pass `true` to terminate in-flight
1025
1057
  * requests and WebSocket connections immediately. Defaults to
@@ -1030,6 +1062,12 @@ var Elysia = class Elysia {
1030
1062
  if (!server) return;
1031
1063
  const r = server.stop?.(closeActiveConnections);
1032
1064
  this.server = void 0;
1065
+ const handlers = this["~ext"]?.cleanup;
1066
+ const fire = handlers ? () => {
1067
+ for (let i = 0; i < handlers.length; i++) handlers[i](this);
1068
+ } : void 0;
1069
+ if (r && typeof r.then === "function") return fire ? r.then(fire) : r;
1070
+ fire?.();
1033
1071
  return r;
1034
1072
  }
1035
1073
  };
package/dist/error.d.ts CHANGED
@@ -85,7 +85,7 @@ declare class ElysiaStatus<const in out Code extends number | keyof StatusMap, T
85
85
  constructor(code: Code, res: T);
86
86
  get status(): number;
87
87
  }
88
- declare const status: <const Code extends number | keyof StatusMap, const T = (Code extends keyof StatusMapBack ? StatusMapBack[Code] : Code)>(code: Code, response?: T) => ElysiaStatus<Code, T, Code extends "Bad Request" | "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" | "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" | "Enhance Your Calm" | "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" ? {
88
+ declare const status: <const Code extends number | keyof StatusMap, const T = (Code extends keyof StatusMapBack ? StatusMapBack[Code] : Code)>(code: Code, response?: T) => ElysiaStatus<Code, T, 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" | "Enhance Your Calm" | "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" ? {
89
89
  readonly Continue: 100;
90
90
  readonly 'Switching Protocols': 101;
91
91
  readonly Processing: 102;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { StatusMap } from "./constants.js";
1
+ import { StatusMap, StatusMapBack } from "./constants.js";
2
2
  import { ElysiaError, ElysiaStatus, InternalServerError, InvalidCookieSignature, NotFound, ParseError, ValidationError, status, validationDetail } from "./error.js";
3
3
  import { Cookie } from "./cookie/cookie.js";
4
4
  import { serializeCookie } from "./cookie/serialize.js";
@@ -8,9 +8,12 @@ import { env } from "./universal/env.js";
8
8
  import { SSEPayload } from "./types.js";
9
9
  import { AnySchema, BaseSchema, StandardJSONSchemaV1Like, StandardSchemaV1Like } from "./type/types.js";
10
10
  import { FileTypeDetector, fileType, setFileTypeDetector } from "./type/elysia/file-type.js";
11
+ import { setupTypebox } from "./type/compat.js";
12
+ import { Capture, Compiled } from "./compile/aot.js";
13
+ import { MultiValidator, StandardValidator, Validator } from "./validator/index.js";
14
+ import { TypeBoxValidator } from "./type/validator/index.js";
11
15
  import { TypeSystem, t } from "./type/index.js";
12
16
  import { form, redirect, sse } from "./utils.js";
13
17
  import { Context, ErrorContext, createBaseContext, createContext } from "./context.js";
14
18
  import { Elysia } from "./base.js";
15
- import { Compiled } from "./compile/aot.js";
16
- export { type AnySchema, type BaseSchema, Compiled, type Context, Cookie, Elysia, Elysia as default, ElysiaError, ElysiaFile, ElysiaStatus, type ErrorContext, type FileTypeDetector, InternalServerError, InvalidCookieSignature, NotFound, ParseError, type SSEPayload, type StandardJSONSchemaV1Like, type StandardSchemaV1Like, StatusMap, type TraceEvent, type TraceHandler, type TraceListener, type TraceProcess, type TraceStream, TypeSystem, ValidationError, createBaseContext, createContext, env, file, fileType, form, redirect, serializeCookie, setFileTypeDetector, sse, status, t, validationDetail };
19
+ export { type AnySchema, type BaseSchema, Compiled, type Context, Cookie, Elysia, Elysia as default, ElysiaError, ElysiaFile, ElysiaStatus, type ErrorContext, type FileTypeDetector, InternalServerError, InvalidCookieSignature, Capture as Manifest, MultiValidator, NotFound, ParseError, type SSEPayload, type StandardJSONSchemaV1Like, type StandardSchemaV1Like, StandardValidator, StatusMap, StatusMapBack, type TraceEvent, type TraceHandler, type TraceListener, type TraceProcess, type TraceStream, TypeBoxValidator, TypeSystem, ValidationError, Validator, createBaseContext, createContext, env, file, fileType, form, redirect, serializeCookie, setFileTypeDetector, setupTypebox, sse, status, t, validationDetail };
package/dist/index.js CHANGED
@@ -8,9 +8,12 @@ const require_universal_env = require('./universal/env.js');
8
8
  const require_error = require('./error.js');
9
9
  const require_context = require('./context.js');
10
10
  const require_compile_aot = require('./compile/aot.js');
11
+ const require_validator_index = require('./validator/index.js');
11
12
  const require_cookie_cookie = require('./cookie/cookie.js');
12
13
  const require_base = require('./base.js');
13
14
  const require_type_elysia_file_type = require('./type/elysia/file-type.js');
15
+ const require_type_validator_index = require('./type/validator/index.js');
16
+ const require_type_compat = require('./type/compat.js');
14
17
  const require_type_index = require('./type/index.js');
15
18
  let typebox_system = require("typebox/system");
16
19
 
@@ -26,9 +29,14 @@ exports.ElysiaFile = require_universal_file.ElysiaFile;
26
29
  exports.ElysiaStatus = require_error.ElysiaStatus;
27
30
  exports.InternalServerError = require_error.InternalServerError;
28
31
  exports.InvalidCookieSignature = require_error.InvalidCookieSignature;
32
+ exports.Manifest = require_compile_aot.Capture;
33
+ exports.MultiValidator = require_validator_index.MultiValidator;
29
34
  exports.NotFound = require_error.NotFound;
30
35
  exports.ParseError = require_error.ParseError;
36
+ exports.StandardValidator = require_validator_index.StandardValidator;
31
37
  exports.StatusMap = require_constants.StatusMap;
38
+ exports.StatusMapBack = require_constants.StatusMapBack;
39
+ exports.TypeBoxValidator = require_type_validator_index.TypeBoxValidator;
32
40
  Object.defineProperty(exports, 'TypeSystem', {
33
41
  enumerable: true,
34
42
  get: function () {
@@ -36,6 +44,7 @@ Object.defineProperty(exports, 'TypeSystem', {
36
44
  }
37
45
  });
38
46
  exports.ValidationError = require_error.ValidationError;
47
+ exports.Validator = require_validator_index.Validator;
39
48
  exports.createBaseContext = require_context.createBaseContext;
40
49
  exports.createContext = require_context.createContext;
41
50
  exports.default = src_default;
@@ -46,6 +55,7 @@ exports.form = require_utils.form;
46
55
  exports.redirect = require_utils.redirect;
47
56
  exports.serializeCookie = require_cookie_serialize.serializeCookie;
48
57
  exports.setFileTypeDetector = require_type_elysia_file_type.setFileTypeDetector;
58
+ exports.setupTypebox = require_type_compat.setupTypebox;
49
59
  exports.sse = require_utils.sse;
50
60
  exports.status = require_error.status;
51
61
  exports.t = require_type_index.t;
package/dist/index.mjs CHANGED
@@ -1,18 +1,21 @@
1
- import { StatusMap } from "./constants.mjs";
1
+ import { StatusMap, StatusMapBack } from "./constants.mjs";
2
2
  import { ElysiaFile, file } from "./universal/file.mjs";
3
3
  import { form, redirect, sse } from "./utils.mjs";
4
4
  import { serializeCookie } from "./cookie/serialize.mjs";
5
5
  import { env } from "./universal/env.mjs";
6
6
  import { ElysiaError, ElysiaStatus, InternalServerError, InvalidCookieSignature, NotFound, ParseError, ValidationError, status, validationDetail } from "./error.mjs";
7
7
  import { createBaseContext, createContext } from "./context.mjs";
8
- import { Compiled } from "./compile/aot.mjs";
8
+ import { Capture, Compiled } from "./compile/aot.mjs";
9
+ import { MultiValidator, StandardValidator, Validator } from "./validator/index.mjs";
9
10
  import { Cookie } from "./cookie/cookie.mjs";
10
11
  import { Elysia } from "./base.mjs";
11
12
  import { fileType, setFileTypeDetector } from "./type/elysia/file-type.mjs";
13
+ import { TypeBoxValidator } from "./type/validator/index.mjs";
14
+ import { setupTypebox } from "./type/compat.mjs";
12
15
  import { TypeSystem, t } from "./type/index.mjs";
13
16
 
14
17
  //#region src/index.ts
15
18
  var src_default = Elysia;
16
19
 
17
20
  //#endregion
18
- export { Compiled, Cookie, Elysia, ElysiaError, ElysiaFile, ElysiaStatus, InternalServerError, InvalidCookieSignature, NotFound, ParseError, StatusMap, TypeSystem, ValidationError, createBaseContext, createContext, src_default as default, env, file, fileType, form, redirect, serializeCookie, setFileTypeDetector, sse, status, t, validationDetail };
21
+ export { Compiled, Cookie, Elysia, ElysiaError, ElysiaFile, ElysiaStatus, InternalServerError, InvalidCookieSignature, Capture as Manifest, MultiValidator, NotFound, ParseError, StandardValidator, StatusMap, StatusMapBack, TypeBoxValidator, TypeSystem, ValidationError, Validator, createBaseContext, createContext, src_default as default, env, file, fileType, form, redirect, serializeCookie, setFileTypeDetector, setupTypebox, sse, status, t, validationDetail };
@@ -1,5 +1,5 @@
1
- import { AnyElysia } from "../base.js";
2
1
  import { CapturedHandler, CapturedValidator } from "../compile/aot.js";
2
+ import { AnyElysia } from "../base.js";
3
3
  import { JITProbeReason } from "../compile/jit-probe.js";
4
4
 
5
5
  //#region src/plugin/source.d.ts
@@ -1,8 +1,8 @@
1
1
  import { Intersect as Intersect$1 } from "./elysia/intersect.js";
2
2
  import { applyCoercions as applyCoercions$1, coerceBody as coerceBody$1, coerceFormData as coerceFormData$1, coerceQuery as coerceQuery$1, coerceRoot as coerceRoot$1, coerceStringToStructure as coerceStringToStructure$1 } from "./coerce.js";
3
+ import { hasTypes as hasTypes$1 } from "./utils.js";
3
4
  import { TypeBoxValidatorCache as TypeBoxValidatorCache$1 } from "./validator/validator-cache.js";
4
5
  import { TypeBoxValidator as TypeBoxValidator$1 } from "./validator/index.js";
5
- import { hasTypes as hasTypes$1 } from "./utils.js";
6
6
  import { Ref as Ref$1, TAny, TSchema } from "typebox/type";
7
7
  import { Compile as Compile$1 } from "typebox/compile";
8
8
  import { Decode as Decode$1, Default as Default$1, HasCodec as HasCodec$1 } from "typebox/value";
@@ -1,9 +1,13 @@
1
1
  import { AnySchema, BaseSchema, StandardJSONSchemaV1Like, StandardSchemaV1Like, TypeBoxSchema } from "./types.js";
2
2
  import { FileTypeDetector, fileType, setFileTypeDetector } from "./elysia/file-type.js";
3
3
  import { exports_d_exports } from "./exports.js";
4
+ import { setupTypebox } from "./compat.js";
5
+ import { TypeBoxValidator } from "./validator/index.js";
6
+ import * as TypeBoxType from "typebox/type";
4
7
  import { System as TypeSystem } from "typebox/system";
5
8
 
6
9
  //#region src/type/index.d.ts
7
- declare const t: typeof exports_d_exports;
10
+ type TypeBuilder = Omit<typeof TypeBoxType, keyof typeof exports_d_exports> & typeof exports_d_exports;
11
+ declare const t: TypeBuilder;
8
12
  //#endregion
9
- export { type AnySchema, type BaseSchema, type FileTypeDetector, type StandardJSONSchemaV1Like, type StandardSchemaV1Like, type TypeBoxSchema, TypeSystem, fileType, setFileTypeDetector, t };
13
+ export { type AnySchema, type BaseSchema, type FileTypeDetector, type StandardJSONSchemaV1Like, type StandardSchemaV1Like, type TypeBoxSchema, TypeBoxValidator, TypeSystem, fileType, setFileTypeDetector, setupTypebox, t };
@@ -1,6 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('../_virtual/_rolldown/runtime.js');
3
3
  const require_type_elysia_file_type = require('./elysia/file-type.js');
4
+ const require_type_validator_index = require('./validator/index.js');
5
+ const require_type_compat = require('./compat.js');
4
6
  const require_type_exports = require('./exports.js');
5
7
  let typebox_system = require("typebox/system");
6
8
 
@@ -8,6 +10,7 @@ let typebox_system = require("typebox/system");
8
10
  const t = require_type_exports.exports_exports;
9
11
 
10
12
  //#endregion
13
+ exports.TypeBoxValidator = require_type_validator_index.TypeBoxValidator;
11
14
  Object.defineProperty(exports, 'TypeSystem', {
12
15
  enumerable: true,
13
16
  get: function () {
@@ -16,4 +19,5 @@ Object.defineProperty(exports, 'TypeSystem', {
16
19
  });
17
20
  exports.fileType = require_type_elysia_file_type.fileType;
18
21
  exports.setFileTypeDetector = require_type_elysia_file_type.setFileTypeDetector;
22
+ exports.setupTypebox = require_type_compat.setupTypebox;
19
23
  exports.t = t;
@@ -1,4 +1,6 @@
1
1
  import { fileType, setFileTypeDetector } from "./elysia/file-type.mjs";
2
+ import { TypeBoxValidator } from "./validator/index.mjs";
3
+ import { setupTypebox } from "./compat.mjs";
2
4
  import { exports_exports } from "./exports.mjs";
3
5
  import { System as TypeSystem } from "typebox/system";
4
6
 
@@ -6,4 +8,4 @@ import { System as TypeSystem } from "typebox/system";
6
8
  const t = exports_exports;
7
9
 
8
10
  //#endregion
9
- export { TypeSystem, fileType, setFileTypeDetector, t };
11
+ export { TypeBoxValidator, TypeSystem, fileType, setFileTypeDetector, setupTypebox, t };
@@ -1,9 +1,9 @@
1
1
  import { ELYSIA_TYPES } from "./constants.js";
2
2
  import { CookieOptions } from "../cookie/types.js";
3
3
  import { MaybeArray } from "../types.js";
4
+ import { Validator } from "typebox/schema";
4
5
  import { TObjectOptions, TSchemaOptions } from "typebox";
5
6
  import { TLocalizedValidationError } from "typebox/error";
6
- import { Validator } from "typebox/schema";
7
7
 
8
8
  //#region src/type/types.d.ts
9
9
  type FileUnit = number | `${number}${'k' | 'm'}`;
@@ -1,9 +1,9 @@
1
1
  import { MaybePromise } from "../../types.js";
2
- import { TypeBoxValidatorCache } from "./validator-cache.js";
3
2
  import { Validator as Validator$1, ValidatorOptions } from "../../validator/index.js";
3
+ import { TypeBoxValidatorCache } from "./validator-cache.js";
4
4
  import { Static, StaticDecode, StaticEncode, TAny, TSchema } from "typebox/type";
5
- import { TLocalizedValidationError } from "typebox/error";
6
5
  import { Validator } from "typebox/schema";
6
+ import { TLocalizedValidationError } from "typebox/error";
7
7
 
8
8
  //#region src/type/validator/index.d.ts
9
9
  declare function shallowMergeObjects(members: any[]): TSchema | null;
package/dist/types.d.ts CHANGED
@@ -10,8 +10,8 @@ import { ChainNode } from "./utils.js";
10
10
  import { Context, ErrorContext, LifecycleContext, PreContext } from "./context.js";
11
11
  import { WebSocketHandler } from "./ws/types.js";
12
12
  import { AnyElysia, Elysia } from "./base.js";
13
- import { Static, StaticDecode, StaticEncode, TIntersect, TObject, TSchema } from "typebox";
14
13
  import { Instruction } from "exact-mirror";
14
+ import { Static, StaticDecode, StaticEncode, TIntersect, TObject, TSchema } from "typebox";
15
15
  import { OpenAPIV3 } from "openapi-types";
16
16
 
17
17
  //#region src/types.d.ts
@@ -5,10 +5,10 @@ declare const mime: {
5
5
  readonly html: "text/html";
6
6
  readonly htm: "text/html";
7
7
  readonly css: "text/css";
8
- readonly js: "application/javascript";
9
- readonly ts: "application/typescript";
10
- readonly json: "application/json";
11
- readonly xml: "application/xml";
8
+ readonly js: "application//javascript";
9
+ readonly ts: "application//typescript";
10
+ readonly json: "application//json";
11
+ readonly xml: "application//xml";
12
12
  readonly jpg: "image/jpeg";
13
13
  readonly jpeg: "image/jpeg";
14
14
  readonly png: "image/png";
@@ -25,18 +25,18 @@ declare const mime: {
25
25
  readonly woff2: "font/woff2";
26
26
  readonly ttf: "font/ttf";
27
27
  readonly otf: "font/otf";
28
- readonly pdf: "application/pdf";
28
+ readonly pdf: "application//pdf";
29
29
  readonly txt: "text/plain";
30
30
  readonly csv: "text/csv";
31
31
  readonly zip: "application/zip";
32
- readonly doc: "application/msword";
32
+ readonly doc: "application//msword";
33
33
  readonly docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
34
- readonly xls: "application/vnd.ms-excel";
34
+ readonly xls: "application//vnd.ms-excel";
35
35
  readonly xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
36
- readonly ppt: "application/vnd.ms-powerpoint";
36
+ readonly ppt: "application//vnd.ms-powerpoint";
37
37
  readonly pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation";
38
38
  };
39
- declare const getFileExtension: (path: string) => string;
39
+ declare function getFileExtension(path: string): string;
40
40
  declare const file: (path: string) => ElysiaFile;
41
41
  declare class ElysiaFile {
42
42
  path: string;
@@ -2,23 +2,26 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_universal_constants = require('./constants.js');
3
3
 
4
4
  //#region src/universal/file.ts
5
+ const text = "text/";
6
+ const application = "application/";
7
+ const image = "image/";
5
8
  const msft365 = "application/vnd.openxmlformats-officedocument.";
6
9
  const mime = {
7
- html: "text/html",
8
- htm: "text/html",
9
- css: "text/css",
10
- js: "application/javascript",
11
- ts: "application/typescript",
12
- json: "application/json",
13
- xml: "application/xml",
14
- jpg: "image/jpeg",
15
- jpeg: "image/jpeg",
16
- png: "image/png",
17
- gif: "image/gif",
18
- webp: "image/webp",
19
- avif: "image/avif",
20
- svg: "image/svg+xml",
21
- ico: "image/x-icon",
10
+ html: `${text}html`,
11
+ htm: `${text}html`,
12
+ css: `${text}css`,
13
+ js: `${application}/javascript`,
14
+ ts: `${application}/typescript`,
15
+ json: `${application}/json`,
16
+ xml: `${application}/xml`,
17
+ jpg: `${image}jpeg`,
18
+ jpeg: `${image}jpeg`,
19
+ png: `${image}png`,
20
+ gif: `${image}gif`,
21
+ webp: `${image}webp`,
22
+ avif: `${image}avif`,
23
+ svg: `${image}svg+xml`,
24
+ ico: `${image}x-icon`,
22
25
  mp4: "video/mp4",
23
26
  webm: "video/webm",
24
27
  mp3: "audio/mpeg",
@@ -27,26 +30,28 @@ const mime = {
27
30
  woff2: "font/woff2",
28
31
  ttf: "font/ttf",
29
32
  otf: "font/otf",
30
- pdf: "application/pdf",
31
- txt: "text/plain",
32
- csv: "text/csv",
33
- zip: "application/zip",
34
- doc: "application/msword",
33
+ pdf: `${application}/pdf`,
34
+ txt: `${text}plain`,
35
+ csv: `${text}csv`,
36
+ zip: `${application}zip`,
37
+ doc: `${application}/msword`,
35
38
  docx: `${msft365}wordprocessingml.document`,
36
- xls: "application/vnd.ms-excel",
39
+ xls: `${application}/vnd.ms-excel`,
37
40
  xlsx: `${msft365}spreadsheetml.sheet`,
38
- ppt: "application/vnd.ms-powerpoint",
41
+ ppt: `${application}/vnd.ms-powerpoint`,
39
42
  pptx: `${msft365}presentationml.presentation`
40
43
  };
41
- const getFileExtension = (path) => {
44
+ function getFileExtension(path) {
42
45
  const index = path.lastIndexOf(".");
43
46
  if (index === -1) return "";
44
47
  return path.slice(index + 1).toLowerCase();
45
- };
48
+ }
46
49
  const file = (path) => new ElysiaFile(path);
47
50
  let createReadStream;
48
51
  let stat;
49
- const warnMissing = (name) => console.warn(/* @__PURE__ */ new Error(`[Elysia] \`file\` require \`fs${name ? "." + name : ""}\` ${name?.includes(".") ? "module " : ""}which is not available in this environment`));
52
+ function warnMissing(name) {
53
+ console.warn(/* @__PURE__ */ new Error(`[Elysia] \`file\` require \`fs${name ? "." + name : ""}\` ${name?.includes(".") ? "module " : ""}which is not available in this environment`));
54
+ }
50
55
  var ElysiaFile = class {
51
56
  constructor(path) {
52
57
  this.path = path;
@@ -1,23 +1,26 @@
1
1
  import { isBun } from "./constants.mjs";
2
2
 
3
3
  //#region src/universal/file.ts
4
+ const text = "text/";
5
+ const application = "application/";
6
+ const image = "image/";
4
7
  const msft365 = "application/vnd.openxmlformats-officedocument.";
5
8
  const mime = {
6
- html: "text/html",
7
- htm: "text/html",
8
- css: "text/css",
9
- js: "application/javascript",
10
- ts: "application/typescript",
11
- json: "application/json",
12
- xml: "application/xml",
13
- jpg: "image/jpeg",
14
- jpeg: "image/jpeg",
15
- png: "image/png",
16
- gif: "image/gif",
17
- webp: "image/webp",
18
- avif: "image/avif",
19
- svg: "image/svg+xml",
20
- ico: "image/x-icon",
9
+ html: `${text}html`,
10
+ htm: `${text}html`,
11
+ css: `${text}css`,
12
+ js: `${application}/javascript`,
13
+ ts: `${application}/typescript`,
14
+ json: `${application}/json`,
15
+ xml: `${application}/xml`,
16
+ jpg: `${image}jpeg`,
17
+ jpeg: `${image}jpeg`,
18
+ png: `${image}png`,
19
+ gif: `${image}gif`,
20
+ webp: `${image}webp`,
21
+ avif: `${image}avif`,
22
+ svg: `${image}svg+xml`,
23
+ ico: `${image}x-icon`,
21
24
  mp4: "video/mp4",
22
25
  webm: "video/webm",
23
26
  mp3: "audio/mpeg",
@@ -26,26 +29,28 @@ const mime = {
26
29
  woff2: "font/woff2",
27
30
  ttf: "font/ttf",
28
31
  otf: "font/otf",
29
- pdf: "application/pdf",
30
- txt: "text/plain",
31
- csv: "text/csv",
32
- zip: "application/zip",
33
- doc: "application/msword",
32
+ pdf: `${application}/pdf`,
33
+ txt: `${text}plain`,
34
+ csv: `${text}csv`,
35
+ zip: `${application}zip`,
36
+ doc: `${application}/msword`,
34
37
  docx: `${msft365}wordprocessingml.document`,
35
- xls: "application/vnd.ms-excel",
38
+ xls: `${application}/vnd.ms-excel`,
36
39
  xlsx: `${msft365}spreadsheetml.sheet`,
37
- ppt: "application/vnd.ms-powerpoint",
40
+ ppt: `${application}/vnd.ms-powerpoint`,
38
41
  pptx: `${msft365}presentationml.presentation`
39
42
  };
40
- const getFileExtension = (path) => {
43
+ function getFileExtension(path) {
41
44
  const index = path.lastIndexOf(".");
42
45
  if (index === -1) return "";
43
46
  return path.slice(index + 1).toLowerCase();
44
- };
47
+ }
45
48
  const file = (path) => new ElysiaFile(path);
46
49
  let createReadStream;
47
50
  let stat;
48
- const warnMissing = (name) => console.warn(/* @__PURE__ */ new Error(`[Elysia] \`file\` require \`fs${name ? "." + name : ""}\` ${name?.includes(".") ? "module " : ""}which is not available in this environment`));
51
+ function warnMissing(name) {
52
+ console.warn(/* @__PURE__ */ new Error(`[Elysia] \`file\` require \`fs${name ? "." + name : ""}\` ${name?.includes(".") ? "module " : ""}which is not available in this environment`));
53
+ }
49
54
  var ElysiaFile = class {
50
55
  constructor(path) {
51
56
  this.path = path;
@@ -1,6 +1,5 @@
1
1
  import { AnySchema } from "../type/types.js";
2
2
  import { ToSubTypeValidator, ValidatorOptions } from "./index.js";
3
-
4
3
  //#region src/validator/route.d.ts
5
4
  interface RouteSchema {
6
5
  body?: AnySchema;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "elysia",
3
3
  "description": "Ergonomic Framework for Human",
4
- "version": "2.0.0-exp.10",
4
+ "version": "2.0.0-exp.12",
5
5
  "author": {
6
6
  "name": "saltyAom",
7
7
  "url": "https://github.com/SaltyAom",