elysia 2.0.0-exp.11 → 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 | Record<string, unknown> | unknown[] | ArrayBuffer | Promise<unknown[] | Record<string | number | symbol, undefined>> | Promise<ArrayBuffer> | Promise<Record<string, unknown>> | Promise<string> | 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 | Record<string, unknown> | unknown[] | ArrayBuffer | Promise<unknown[] | Record<string | number | symbol, undefined>> | Promise<ArrayBuffer> | Promise<Record<string, unknown>> | Promise<string> | 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 | Record<string, unknown> | unknown[] | ArrayBuffer | Promise<unknown[] | Record<string | number | symbol, undefined>> | Promise<ArrayBuffer> | Promise<Record<string, unknown>> | Promise<string> | 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[]>>;
@@ -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 | Record<string, unknown> | unknown[] | ArrayBuffer | Promise<unknown[] | Record<string | number | symbol, undefined>> | Promise<ArrayBuffer> | Promise<Record<string, unknown>> | Promise<string> | 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;
@@ -990,7 +1005,22 @@ declare class Elysia<const in out BasePath extends string = '', const in out Sco
990
1005
  listen(options: string | number | Partial<Serve>, callback?: ListenCallback): this;
991
1006
  wrap<T extends (...params: any) => MaybePromise<Response> = (request: Request, ...rest: any[]) => MaybePromise<Response>>(callback: WrapFn<T>): this;
992
1007
  /**
993
- * 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()`.
994
1024
  *
995
1025
  * @param closeActiveConnections Pass `true` to terminate in-flight
996
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) {
@@ -518,7 +532,7 @@ var Elysia = class Elysia {
518
532
  }
519
533
  const hookChain = app["~hookChain"];
520
534
  if (app["~ext"]) {
521
- 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"];
522
536
  const ext = this["~ext"] ??= require_utils.nullObject();
523
537
  if (decorator) {
524
538
  const cloned = require_utils.clonePlainDecorators(decorator);
@@ -540,6 +554,12 @@ var Elysia = class Elysia {
540
554
  if (hoc) if (ext.hoc) {
541
555
  for (const fn of hoc) if (!ext.hoc.includes(fn)) ext.hoc.push(fn);
542
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();
543
563
  }
544
564
  if (app.#hasPlugin || app.#hasGlobal || hookChain) {
545
565
  let pluginEvents;
@@ -1014,7 +1034,27 @@ var Elysia = class Elysia {
1014
1034
  return this;
1015
1035
  }
1016
1036
  /**
1017
- * 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()`.
1018
1058
  *
1019
1059
  * @param closeActiveConnections Pass `true` to terminate in-flight
1020
1060
  * requests and WebSocket connections immediately. Defaults to
@@ -1025,6 +1065,12 @@ var Elysia = class Elysia {
1025
1065
  if (!server) return;
1026
1066
  const r = server.stop?.(closeActiveConnections);
1027
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?.();
1028
1074
  return r;
1029
1075
  }
1030
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) {
@@ -515,7 +529,7 @@ var Elysia = class Elysia {
515
529
  }
516
530
  const hookChain = app["~hookChain"];
517
531
  if (app["~ext"]) {
518
- 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"];
519
533
  const ext = this["~ext"] ??= nullObject();
520
534
  if (decorator) {
521
535
  const cloned = clonePlainDecorators(decorator);
@@ -537,6 +551,12 @@ var Elysia = class Elysia {
537
551
  if (hoc) if (ext.hoc) {
538
552
  for (const fn of hoc) if (!ext.hoc.includes(fn)) ext.hoc.push(fn);
539
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();
540
560
  }
541
561
  if (app.#hasPlugin || app.#hasGlobal || hookChain) {
542
562
  let pluginEvents;
@@ -1011,7 +1031,27 @@ var Elysia = class Elysia {
1011
1031
  return this;
1012
1032
  }
1013
1033
  /**
1014
- * 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()`.
1015
1055
  *
1016
1056
  * @param closeActiveConnections Pass `true` to terminate in-flight
1017
1057
  * requests and WebSocket connections immediately. Defaults to
@@ -1022,6 +1062,12 @@ var Elysia = class Elysia {
1022
1062
  if (!server) return;
1023
1063
  const r = server.stop?.(closeActiveConnections);
1024
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?.();
1025
1071
  return r;
1026
1072
  }
1027
1073
  };
@@ -3,9 +3,11 @@ import { FileTypeDetector, fileType, setFileTypeDetector } from "./elysia/file-t
3
3
  import { exports_d_exports } from "./exports.js";
4
4
  import { setupTypebox } from "./compat.js";
5
5
  import { TypeBoxValidator } from "./validator/index.js";
6
+ import * as TypeBoxType from "typebox/type";
6
7
  import { System as TypeSystem } from "typebox/system";
7
8
 
8
9
  //#region src/type/index.d.ts
9
- 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;
10
12
  //#endregion
11
13
  export { type AnySchema, type BaseSchema, type FileTypeDetector, type StandardJSONSchemaV1Like, type StandardSchemaV1Like, type TypeBoxSchema, 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'}`;
@@ -2,8 +2,8 @@ import { MaybePromise } from "../../types.js";
2
2
  import { Validator as Validator$1, ValidatorOptions } from "../../validator/index.js";
3
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
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.11",
4
+ "version": "2.0.0-exp.12",
5
5
  "author": {
6
6
  "name": "saltyAom",
7
7
  "url": "https://github.com/SaltyAom",