egg
Version:
A web application framework for Node.js
324 lines • 12.6 kB
TypeScript
import { EggContextHttpClient as HttpClient, HttpClientOptions, HttpClientRequestOptions, HttpClientRequestURL, HttpClientResponse } from "./core/httpclient.js";
import { EggAppConfig as EggAppConfig$1 } from "./types.js";
import Response from "../app/extend/response.js";
import Request from "../app/extend/request.js";
import Context from "../app/extend/context.js";
import { EggApplicationLoader } from "./loader/EggApplicationLoader.js";
import "./loader/index.js";
import { Agent } from "./agent.js";
import { ContextHttpClient } from "./core/context_httpclient.js";
import { IMessenger } from "./core/messenger/IMessenger.js";
import "./core/messenger/index.js";
import { Application } from "./application.js";
import { BaseContextClass as BaseContextClass$1 } from "./core/base_context_class.js";
import { BaseHookClass } from "./core/base_hook_class.js";
import { EggCore, EggCoreOptions, ILifecycleBoot, MiddlewareFunc as MiddlewareFunc$1, Next, Router } from "@eggjs/core";
import { IncomingMessage, ServerResponse } from "node:http";
import { Cookies } from "@eggjs/cookies";
import { EggContextLogger, EggLogger, EggLoggers } from "egg-logger";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/lib/egg.d.ts
export interface EggApplicationCoreOptions extends Omit<EggCoreOptions, "baseDir"> {
mode?: "cluster" | "single";
clusterPort?: number;
baseDir?: string;
}
export type EggContext = Context;
export type MiddlewareFunc<T extends Context = Context> = MiddlewareFunc$1<T>;
/**
* Based on koa's Application
* @see https://github.com/eggjs/egg-core
* @see https://github.com/eggjs/koa/blob/master/src/application.ts
* @augments EggCore
*/
export declare class EggApplicationCore extends EggCore {
#private;
ctxStorage: AsyncLocalStorage<Context>;
/**
* Get the current request context from AsyncLocalStorage.
* This provides access to the context object for the current request lifecycle.
* @returns {Context | undefined} The current request context, or undefined if not in a request scope.
*/
get currentContext(): Context | undefined;
ContextCookies: typeof Cookies;
ContextLogger: typeof EggContextLogger;
ContextHttpClient: typeof ContextHttpClient;
HttpClient: typeof HttpClient;
HttpClientNext: typeof HttpClient;
/**
* Retrieve base context class
* @member {BaseContextClass} BaseContextClass
* @since 1.0.0
*/
BaseContextClass: typeof BaseContextClass$1;
/**
* Retrieve base controller
* @member {Controller} Controller
* @since 1.0.0
*/
Controller: typeof BaseContextClass$1;
/**
* Retrieve base service
* @member {Service} Service
* @since 1.0.0
*/
Service: typeof BaseContextClass$1;
/**
* Retrieve base subscription
* @member {Subscription} Subscription
* @since 2.12.0
*/
Subscription: typeof BaseContextClass$1;
/**
* Retrieve base context class
* @member {BaseHookClass} BaseHookClass
*/
BaseHookClass: typeof BaseHookClass;
/**
* Retrieve base boot
* @member {Boot}
* @alias BaseHookClass
*/
Boot: typeof BaseHookClass;
options: Required<EggApplicationCoreOptions>;
/**
* Promise that resolves when the `load()` method has finished.
* This is useful for callers that need to ensure config and metadata
* are fully loaded before proceeding.
*/
readonly loadFinished: Promise<void>;
readonly messenger: IMessenger;
agent?: Agent;
application?: Application;
loader: EggApplicationLoader;
/**
* @class
* @param {Object} options
* - {Object} [type] - type of instance, Agent and Application both extend koa, type can determine what it is.
* - {String} [baseDir] - app root dir, default is `process.cwd()`
* - {Object} [plugins] - custom plugin config, use it in unittest
* - {String} [mode] - process mode, can be cluster / single, default is `cluster`
*/
constructor(options?: EggApplicationCoreOptions);
/**
* @deprecated please use `options` property instead
*/
get _options(): Required<EggApplicationCoreOptions>;
protected loadConfig(): Promise<void>;
protected load(): Promise<void>;
/**
* Usage: new ApiClient({ cluster: app.cluster })
*/
get cluster(): (clientClass: unknown, options?: object) => any;
/**
* Wrap the Client with Leader/Follower Pattern
*
* @description almost the same as Agent.cluster API, the only different is that this method create Follower.
*
* @see https://github.com/node-modules/cluster-client
* @param {Function} clientClass - client class function
* @param {Object} [options]
* - {Boolean} [autoGenerate] - whether generate delegate rule automatically, default is true
* - {Function} [formatKey] - a method to transform the subscription info into a string,default is JSON.stringify
* - {Object} [transcode|JSON.stringify/parse]
* - {Function} encode - custom serialize method
* - {Function} decode - custom deserialize method
* - {Boolean} [isBroadcast] - whether broadcast subscription result to all followers or just one, default is true
* - {Number} [responseTimeout] - response timeout, default is 3 seconds
* - {Number} [maxWaitTime|30000] - leader startup max time, default is 30 seconds
* @return {ClientWrapper} wrapper
*/
clusterWrapper(clientClass: unknown, options?: object): any;
/**
* print the information when console.log(app)
* @return {Object} inspected app.
* @since 1.0.0
* @example
* ```js
* console.log(app);
* =>
* {
* name: 'mock-app',
* env: 'test',
* subdomainOffset: 2,
* config: '<egg config>',
* controller: '<egg controller>',
* service: '<egg service>',
* middlewares: '<egg middlewares>',
* urllib: '<egg urllib>',
* loggers: '<egg loggers>'
* }
* ```
*/
inspect(): any;
toJSON(): any;
/**
* http request helper base on {@link httpclient}, it will auto save httpclient log.
* Keep the same api with `httpclient.request(url, args)`.
*
* See https://github.com/node-modules/urllib#api-doc for more details.
*
* @param {String} url request url address.
* @param {Object} options
* - method {String} - Request method, defaults to GET. Could be GET, POST, DELETE or PUT. Alias 'type'.
* - data {Object} - Data to be sent. Will be stringify automatically.
* - dataType {String} - String - Type of response data. Could be `text` or `json`.
* If it's `text`, the callback data would be a String.
* If it's `json`, the data of callback would be a parsed JSON Object.
* Default callback data would be a Buffer.
* - headers {Object} - Request headers.
* - timeout {Number} - Request timeout in milliseconds. Defaults to exports.TIMEOUT.
* Include remote server connecting timeout and response timeout.
* When timeout happen, will return ConnectionTimeout or ResponseTimeout.
* - auth {String} - `username:password` used in HTTP Basic Authorization.
* - followRedirect {Boolean} - follow HTTP 3xx responses as redirects. defaults to false.
* - gzip {Boolean} - let you get the res object when request connected, default false. alias customResponse
* - nestedQuerystring {Boolean} - urllib default use querystring to stringify form data which don't
* support nested object, will use qs instead of querystring to support nested object by set this option to true.
* - more options see https://github.com/node-modules/urllib
* @return {Object}
* - status {Number} - HTTP response status
* - headers {Object} - HTTP response headers
* - res {Object} - HTTP response meta
* - data {Object} - HTTP response body
*
* @example
* ```js
* const result = await app.curl('http://example.com/foo.json', {
* method: 'GET',
* dataType: 'json',
* });
* console.log(result.status, result.headers, result.data);
* ```
*/
curl<T = any>(url: HttpClientRequestURL, options?: HttpClientRequestOptions): Promise<HttpClientResponse<T>>;
/**
* Create a new HttpClient instance with custom options
* @param {Object} [options] HttpClient init options
*/
createHttpClient(options?: HttpClientOptions): HttpClient;
/**
* HttpClient instance
*
* Returns a transparent proxy that defers actual HttpClient construction
* until a method/property is first accessed. This allows plugins to modify
* `config.httpclient.lookup` or other options during lifecycle hooks
* (e.g. `configWillLoad`, `didLoad`) even after `app.httpClient` is
* first referenced.
*
* @see https://github.com/node-modules/urllib
* @member {HttpClient}
*/
get httpClient(): HttpClient;
/**
* @deprecated please use httpClient instead
* @alias httpClient
* @member {HttpClient}
*/
get httpclient(): HttpClient;
/**
* All loggers contain logger, coreLogger and customLogger
* @member {Object}
* @since 1.0.0
*/
get loggers(): EggLoggers;
/**
* Get logger by name, it's equal to app.loggers['name'],
* but you can extend it with your own logical.
* @param {String} name - logger name
* @return {Logger} logger
*/
getLogger(name: string): EggLogger;
/**
* application logger, log file is `$HOME/logs/{appname}/{appname}-web`
* @member {Logger}
* @since 1.0.0
*/
get logger(): EggLogger;
/**
* core logger for framework and plugins, log file is `$HOME/logs/{appname}/egg-web`
* @member {Logger}
* @since 1.0.0
*/
get coreLogger(): EggLogger;
_unhandledRejectionHandler(err: any): void;
/**
* Clean up non-serializable resources before V8 heap serialization.
* Closes messenger (IPC listeners), logger streams and flush timers
* (file descriptors), and removes the process-level unhandledRejection
* listener.
*
* The `EggLoggers` instance is intentionally kept (not discarded): plugins
* such as `@eggjs/schedule` capture individual logger references during the
* load phase, before serialization. Replacing them with a fresh `EggLoggers`
* on restore would leave those captured references pointing at closed
* streams (`... log stream had been closed`). Instead, `snapshotDidDeserialize`
* reopens these same logger objects in place.
*/
protected snapshotWillSerialize(): void;
/**
* Restore non-serializable resources after V8 heap deserialization.
* Recreates messenger, re-registers the egg-ready listener, reopens the
* logger streams closed during serialize, and re-attaches the process-level
* unhandledRejection listener.
*/
protected snapshotDidDeserialize(): void;
/**
* dump out the config and meta object
* @private
*/
dumpConfigToObject(): {
config: any;
meta: any;
};
/**
* save app.config to `run/${type}_config.json`
* @private
*/
dumpConfig(): void;
dumpTiming(): void;
/**
* Generate and save startup manifest for faster subsequent startups.
* Only generates when no valid manifest was loaded (avoids overwriting during manifest-accelerated starts).
*/
dumpManifest(): void;
protected override customEggPaths(): string[];
get config(): EggAppConfig$1;
/**
* app.env delegate app.config.env
* @deprecated
*/
get env(): string;
set env(_: any);
/**
* app.proxy delegate app.config.proxy
* @deprecated
*/
get proxy(): boolean;
set proxy(_: any);
/**
* Create an anonymous context, the context isn't request level, so the request is mocked.
* then you can use context level API like `ctx.service`
* @member {String} EggApplication#createAnonymousContext
* @param {Request} [req] - if you want to mock request like querystring, you can pass an object to this function.
* @return {Context} context
*/
createAnonymousContext(req?: any): EggContext;
/**
* Run async function in the anonymous context scope
* @see Context#runInAnonymousContextScope
* @param {Function} scope - the first args is an anonymous ctx, scope should be async function
* @param {Request} [req] - if you want to mock request like querystring, you can pass an object to this function.
*/
runInAnonymousContextScope<T = void>(scope: (ctx: Context) => Promise<T>, req?: unknown): Promise<T>;
/**
* Create egg context
* @function EggApplication#createContext
* @param {Req} req - node native Request object
* @param {Res} res - node native Response object
* @return {Context} context object
*/
createContext(req: IncomingMessage, res: ServerResponse): Context;
}
//#endregion
export { Context, type ILifecycleBoot as IBoot, type ILifecycleBoot, type Next, Request, Response, Router };