alepha
Version:
Alepha is a convention-driven TypeScript framework for building robust, end-to-end type-safe applications, from serverless APIs to full-stack React apps.
848 lines (847 loc) • 30.5 kB
TypeScript
import * as _alepha_core11 from "alepha";
import { Alepha, AlephaError, Async, Descriptor, FileLike, KIND, Static, StreamLike, TArray, TFile, TObject, TRecord, TSchema, TStream, TString, TVoid } from "alepha";
import * as _alepha_logger3 from "alepha/logger";
import { Readable } from "node:stream";
import { ReadableStream } from "node:stream/web";
import { Route, RouterProvider } from "alepha/router";
import * as _alepha_cache0 from "alepha/cache";
import { IncomingMessage, ServerResponse as ServerResponse$1 } from "node:http";
import { DateTimeProvider, DurationLike } from "alepha/datetime";
import * as typebox0 from "typebox";
import * as http0 from "http";
//#region src/constants/routeMethods.d.ts
declare const routeMethods: readonly ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "CONNECT", "TRACE"];
type RouteMethod = (typeof routeMethods)[number];
//#endregion
//#region src/helpers/ServerReply.d.ts
/**
* Helper for building server replies.
*/
declare class ServerReply {
headers: Record<string, string> & {
"set-cookie"?: string[];
};
status?: number;
body?: any;
/**
* Redirect to a given URL with optional status code (default 302).
*/
redirect(url: string, status?: number): void;
/**
* Set the response status code.
*/
setStatus(status: number): this;
/**
* Set a response header.
*/
setHeader(name: string, value: string): this;
/**
* Set the response body.
*/
setBody(body: any): this;
}
//#endregion
//#region src/services/UserAgentParser.d.ts
interface UserAgentInfo {
os: "Windows" | "Android" | "Ubuntu" | "MacOS" | "iOS" | "Linux" | "FreeBSD" | "OpenBSD" | "ChromeOS" | "BlackBerry" | "Symbian" | "Windows Phone";
browser: "Chrome" | "Firefox" | "Safari" | "Edge" | "Opera" | "Internet Explorer" | "Brave" | "Vivaldi" | "Samsung Browser" | "UC Browser" | "Yandex";
device: "MOBILE" | "DESKTOP" | "TABLET";
}
/**
* Simple User-Agent parser to detect OS, browser, and device type.
* This parser is not exhaustive and may not cover all edge cases.
*
* Use result for non
*/
declare class UserAgentParser {
parse(userAgent?: string): UserAgentInfo;
}
//#endregion
//#region src/interfaces/ServerRequest.d.ts
type TRequestBody = TObject | TString | TArray | TRecord | TStream;
type TResponseBody = TObject | TString | TRecord | TFile | TArray | TStream | TVoid;
interface RequestConfigSchema {
body?: TRequestBody;
params?: TObject;
query?: TObject;
headers?: TObject;
response?: TResponseBody;
}
interface ServerRequestConfig<TConfig extends RequestConfigSchema = RequestConfigSchema> {
body: TConfig["body"] extends TRequestBody ? Static<TConfig["body"]> : any;
headers: TConfig["headers"] extends TObject ? Static<TConfig["headers"]> : Record<string, string>;
params: TConfig["params"] extends TObject ? Static<TConfig["params"]> : Record<string, string>;
query: TConfig["query"] extends TObject ? Static<TConfig["query"]> : Record<string, any>;
}
type ServerRequestConfigEntry<TConfig extends RequestConfigSchema = RequestConfigSchema> = Partial<ServerRequestConfig<TConfig>>;
interface ServerRequest<TConfig extends RequestConfigSchema = RequestConfigSchema> extends ServerRequestConfig<TConfig> {
method: RouteMethod;
url: URL;
requestId: string;
/**
* Client IP address.
* Will parse `X-Forwarded-For` header if present.
*/
ip?: string;
/**
* Value of the `Host` header sent by the client.
*/
host?: string;
/**
* Browser user agent information.
* Information are not guaranteed to be accurate. Use with caution.
*
* @see {@link UserAgentParser}
*/
userAgent: UserAgentInfo;
metadata: Record<string, any>;
/**
* Reply object to be used to send response.
*/
reply: ServerReply;
/**
* Raw request and response objects from platform.
* You should avoid using this property as much as possible to keep your code platform-agnostic.
*/
raw: {
/**
* Node.js request and response objects.
*/
node?: {
/**
* Node.js IncomingMessage object. (request)
*/
req: IncomingMessage;
/**
* Node.js ServerResponse object. (response)
*/
res: ServerResponse$1;
};
};
}
interface ServerRoute<TConfig extends RequestConfigSchema = RequestConfigSchema> extends Route {
handler: ServerHandler<TConfig>;
method?: RouteMethod;
schema?: TConfig;
/**
* @see ServerLoggerProvider
*/
silent?: boolean;
}
type ServerResponseBody<TConfig extends RequestConfigSchema = RequestConfigSchema> = TConfig["response"] extends TResponseBody ? Static<TConfig["response"]> : ResponseBodyType;
type ResponseKind = "json" | "text" | "void" | "file" | "any";
type ResponseBodyType = string | Buffer | StreamLike | undefined | null | void;
type ServerHandler<TConfig extends RequestConfigSchema = RequestConfigSchema> = (request: ServerRequest<TConfig>) => Async<ServerResponseBody<TConfig>>;
interface ServerResponse {
body: string | Buffer | ArrayBuffer | Readable | ReadableStream;
headers: Record<string, string>;
status: number;
}
type ServerRouteRequestHandler = (request: ServerRawRequest) => Promise<ServerResponse>;
interface ServerRouteMatcher extends Route {
handler: ServerRouteRequestHandler;
}
interface ServerRawRequest {
method: RouteMethod;
url: URL;
headers: Record<string, string>;
query: Record<string, string>;
params: Record<string, string>;
raw: {
node?: {
req: IncomingMessage;
res: ServerResponse$1;
};
web?: {
req: Request;
res?: Response;
};
};
}
//#endregion
//#region src/providers/ServerProvider.d.ts
declare abstract class ServerProvider {
protected readonly alepha: Alepha;
abstract get hostname(): string;
protected isViteNotFound(url?: string, route?: Route, params?: Record<string, string>): boolean;
protected createRouterRequest(req: {
method?: string;
url?: string;
headers?: Record<string, string | string[] | undefined>;
}, params?: Record<string, string>): ServerRawRequest;
protected getProtocol(headers: Record<string, string>): "http" | "https";
}
//#endregion
//#region src/services/ServerRequestParser.d.ts
declare class ServerRequestParser {
protected readonly alepha: Alepha;
protected readonly userAgentParser: UserAgentParser;
createServerRequest(rawRequest: ServerRawRequest): ServerRequest;
getRequestId(request: ServerRawRequest): string | undefined;
getRequestUserAgent(request: ServerRawRequest): UserAgentInfo;
getRequestIp(request: ServerRawRequest): string | undefined;
}
//#endregion
//#region src/providers/ServerTimingProvider.d.ts
type TimingMap = Record<string, [number, number]>;
declare class ServerTimingProvider {
protected readonly log: _alepha_logger3.Logger;
protected readonly alepha: Alepha;
options: {
prefix: string;
disabled: boolean;
};
readonly onRequest: _alepha_core11.HookDescriptor<"server:onRequest">;
readonly onResponse: _alepha_core11.HookDescriptor<"server:onResponse">;
protected get handlerName(): string;
beginTiming(name: string): void;
endTiming(name: string): void;
protected setDuration(name: string, timing: TimingMap): void;
}
//#endregion
//#region src/providers/ServerRouterProvider.d.ts
/**
* Main router for all routes on the server side.
*
* - $route => generic route
* - $action => action route (for API calls)
* - $page => React route (for SSR)
*/
declare class ServerRouterProvider extends RouterProvider<ServerRouteMatcher> {
protected readonly alepha: Alepha;
protected readonly routes: ServerRoute[];
protected readonly serverTimingProvider: ServerTimingProvider;
protected readonly serverRequestParser: ServerRequestParser;
getRoutes(): ServerRoute[];
createRoute<TConfig extends RequestConfigSchema = RequestConfigSchema>(route: ServerRoute<TConfig>): void;
protected processRequest(request: ServerRequest, route: ServerRoute, responseKind: ResponseKind): Promise<{
status: number;
headers: Record<string, string> & {
"set-cookie"?: string[];
};
body: any;
}>;
protected runRouteHandler(route: ServerRoute, request: ServerRequest, responseKind: ResponseKind): Promise<void>;
serializeResponse(route: ServerRoute, reply: ServerReply, responseKind: ResponseKind): void;
protected getResponseType(schema?: RequestConfigSchema): ResponseKind;
protected errorHandler(route: ServerRoute, request: ServerRequest, error: Error): Promise<void>;
validateRequest(route: {
schema?: RequestConfigSchema;
}, request: ServerRequestConfig): void;
}
//#endregion
//#region src/services/HttpClient.d.ts
declare class HttpClient {
protected readonly log: _alepha_logger3.Logger;
protected readonly alepha: Alepha;
readonly cache: _alepha_cache0.CacheDescriptorFn<HttpClientCache, any[]>;
protected readonly pendingRequests: HttpClientPendingRequests;
fetchAction(args: FetchActionArgs): Promise<FetchResponse>;
fetch<T extends TSchema>(url: string, request?: RequestInitWithOptions<T>): Promise<FetchResponse<Static<T>>>;
protected url(host: string, action: HttpAction, args: ServerRequestConfigEntry): string;
protected body(init: RequestInit, headers: Record<string, string>, action: HttpAction, args?: ServerRequestConfigEntry): Promise<void>;
protected responseData(response: Response, options: FetchOptions): Promise<any>;
protected isMaybeFile(response: Response): boolean;
protected createFileLike(response: Response, defaultFileName?: string): FileLike;
pathVariables(url: string, action: {
schema?: {
params?: TObject;
};
}, args?: ServerRequestConfigEntry): string;
queryParams(url: string, action: {
schema?: {
query?: TObject;
};
}, args?: ServerRequestConfigEntry): string;
}
interface FetchOptions<T extends TSchema = TSchema> {
/**
* Key to identify the request in the pending requests.
*/
key?: string;
/**
* The schema to validate the response against.
*/
schema?: {
response?: T;
};
/**
* Built-in cache options.
*/
localCache?: boolean | number | DurationLike;
}
type RequestInitWithOptions<T extends TSchema = TSchema> = RequestInit & FetchOptions<T>;
interface FetchResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: Headers;
raw?: Response;
}
type HttpClientPendingRequests = Record<string, Promise<any> | undefined>;
interface HttpClientCache {
data: any;
etag?: string;
}
interface FetchActionArgs {
action: HttpAction;
host?: string;
config?: ServerRequestConfigEntry;
options?: ClientRequestOptions;
}
interface HttpAction {
method?: string;
prefix?: string;
path: string;
requestBodyType?: string;
schema?: {
params?: TObject;
query?: TObject;
body?: TRequestBody;
response?: TResponseBody;
};
}
//#endregion
//#region src/descriptors/$action.d.ts
/**
* Creates a server action descriptor for defining type-safe HTTP endpoints.
*
* Server actions are the core building blocks for REST APIs in the Alepha framework. They provide
* a declarative way to define HTTP endpoints with full TypeScript type safety, automatic schema
* validation, and integrated security features. Actions automatically handle routing, request
* parsing, response serialization, and OpenAPI documentation generation.
*
* **Key Features**
*
* - **Type Safety**: Full TypeScript inference for request/response types
* - **Schema Validation**: Automatic validation using TypeBox schemas
* - **Auto-routing**: Convention-based URL generation with customizable paths
* - **Multiple Invocation**: Call directly (`run()`) or via HTTP (`fetch()`)
* - **OpenAPI Integration**: Automatic documentation generation
* - **Security Integration**: Built-in authentication and authorization support
* - **Content Type Detection**: Automatic handling of JSON, form-data, and plain text
*
* **URL Generation**
*
* By default, actions are prefixed with `/api` (configurable via `SERVER_API_PREFIX`):
* - Property name becomes the endpoint path
* - Path parameters are automatically detected from schema
* - HTTP method defaults to GET, or POST if body schema is provided
*
* **Use Cases**
*
* Perfect for building robust REST APIs:
* - CRUD operations with full type safety
* - File upload and download endpoints
* - Real-time data processing APIs
* - Integration with external services
* - Microservice communication
* - Admin and management interfaces
*
* @example
* **Basic CRUD operations:**
* ```ts
* import { $action } from "alepha/server";
* import { t } from "alepha";
*
* class UserController {
*
* getUsers = $action({
* path: "/users",
* description: "Retrieve all users with pagination",
* schema: {
* query: t.object({
* page: t.optional(t.number({ default: 1 })),
* limit: t.optional(t.number({ default: 10, maximum: 100 })),
* search: t.optional(t.text())
* }),
* response: t.object({
* users: t.array(t.object({
* id: t.text(),
* name: t.text(),
* email: t.text(),
* createdAt: t.datetime()
* })),
* total: t.number(),
* hasMore: t.boolean()
* })
* },
* handler: async ({ query }) => {
* const { page, limit, search } = query;
* const users = await this.userService.findUsers({ page, limit, search });
*
* return {
* users: users.items,
* total: users.total,
* hasMore: (page * limit) < users.total
* };
* }
* });
*
* createUser = $action({
* method: "POST",
* path: "/users",
* description: "Create a new user account",
* schema: {
* body: t.object({
* name: t.text({ minLength: 2, maxLength: 100 }),
* email: t.text({ format: "email" }),
* password: t.text({ minLength: 8 }),
* role: t.optional(t.enum(["user", "admin"]))
* }),
* response: t.object({
* id: t.text(),
* name: t.text(),
* email: t.text(),
* role: t.text(),
* createdAt: t.datetime()
* })
* },
* handler: async ({ body }) => {
* // Password validation and hashing
* await this.authService.validatePassword(body.password);
* const hashedPassword = await this.authService.hashPassword(body.password);
*
* // Create user with default role
* const user = await this.userService.create({
* ...body,
* password: hashedPassword,
* role: body.role || "user"
* });
*
* // Return user without password
* const { password, ...publicUser } = user;
* return publicUser;
* }
* });
*
* getUser = $action({
* path: "/users/:id",
* description: "Retrieve user by ID",
* schema: {
* params: t.object({
* id: t.text()
* }),
* response: t.object({
* id: t.text(),
* name: t.text(),
* email: t.text(),
* role: t.text(),
* profile: t.optional(t.object({
* bio: t.text(),
* avatar: t.text({ format: "uri" }),
* location: t.text()
* }))
* })
* },
* handler: async ({ params }) => {
* const user = await this.userService.findById(params.id);
* if (!user) {
* throw new Error(`User not found: ${params.id}`);
* }
* return user;
* }
* });
*
* updateUser = $action({
* method: "PUT",
* path: "/users/:id",
* description: "Update user information",
* schema: {
* params: t.object({ id: t.text() }),
* body: t.object({
* name: t.optional(t.text({ minLength: 2 })),
* email: t.optional(t.text({ format: "email" })),
* profile: t.optional(t.object({
* bio: t.optional(t.text()),
* avatar: t.optional(t.text({ format: "uri" })),
* location: t.optional(t.text())
* }))
* }),
* response: t.object({
* id: t.text(),
* name: t.text(),
* email: t.text(),
* updatedAt: t.datetime()
* })
* },
* handler: async ({ params, body }) => {
* const updatedUser = await this.userService.update(params.id, body);
* return updatedUser;
* }
* });
* }
* ```
*
* **Important Notes**:
* - Actions are automatically registered with the HTTP server when the service is initialized
* - Use `run()` for direct invocation (testing, internal calls, or remote services)
* - Use `fetch()` for explicit HTTP requests (client-side, external services)
* - Schema validation occurs automatically for all requests and responses
* - Path parameters are automatically extracted from schema definitions
* - Content-Type headers are automatically set based on schema types
*/
declare const $action: {
<TConfig extends RequestConfigSchema>(options: ActionDescriptorOptions<TConfig>): ActionDescriptorFn<TConfig>;
[KIND]: typeof ActionDescriptor;
};
interface ActionDescriptorOptions<TConfig extends RequestConfigSchema> extends Omit<ServerRoute, "handler" | "path" | "schema" | "mapParams"> {
/**
* Name of the action.
*
* - It will be used to generate the route path if `path` is not provided.
* - It will be used to generate the permission name if `security` is enabled.
*/
name?: string;
/**
* Group actions together.
*
* - If not provided, the service name containing the route will be used.
* - It will be used as Tag for documentation purposes.
* - It will be used for permission name generation if `security` is enabled.
*
* @example
* ```ts
* // group = "MyController"
* class MyController {
* hello = $action({ handler: () => "Hello World" });
* }
*
* // group = "users"
* class MyOtherController {
* group = "users";
* a1 = $action({ handler: () => "Action 1", group: this.group });
* a2 = $action({ handler: () => "Action 2", group: this.group });
* }
* ```
*/
group?: string;
/**
* Pathname of the route. If not provided, property key is used.
*/
path?: string;
/**
* The route method.
*
* - If not provided, it will be set to "GET" by default.
* - If not provider and a body is provided, it will be set to "POST".
*
* Wildcard methods are not supported for now. (e.g. "ALL", "ANY", etc.)
*/
method?: RouteMethod;
/**
* The config schema of the route.
* - body: The request body schema.
* - params: Path variables schema.
* - query: The request query-params schema.
* - response: The response schema.
*/
schema?: TConfig;
/**
* A short description of the action. Used for documentation purposes.
*/
description?: string;
/**
* Disable the route. Useful with env variables do disable one specific route.
* Route won't be available in the API but can still be called locally!
*/
disabled?: boolean;
/**
* Main route handler. This is where the route logic is implemented.
*/
handler: ServerActionHandler<TConfig>;
}
declare class ActionDescriptor<TConfig extends RequestConfigSchema> extends Descriptor<ActionDescriptorOptions<TConfig>> {
protected readonly log: _alepha_logger3.Logger;
protected readonly env: {
SERVER_API_PREFIX: string;
};
protected readonly httpClient: HttpClient;
protected readonly serverProvider: ServerProvider;
protected readonly serverRouterProvider: ServerRouterProvider;
protected onInit(): void;
get prefix(): string;
get route(): ServerRoute;
/**
* Returns the name of the action.
*/
get name(): string;
/**
* Returns the group of the action. (e.g. "orders", "admin", etc.)
*/
get group(): string;
/**
* Returns the HTTP method of the action.
*/
get method(): RouteMethod;
/**
* Returns the path of the action.
*
* Path is prefixed by `/api` by default.
*/
get path(): string;
get schema(): TConfig | undefined;
getBodyContentType(): string | undefined;
/**
* Call the action handler directly.
* There is no HTTP layer involved.
*/
run(config?: ClientRequestEntry<TConfig>, options?: ClientRequestOptions): Promise<ClientRequestResponse<TConfig>>;
/**
* Works like `run`, but always fetches (http request) the route.
*/
fetch(config?: ClientRequestEntry<TConfig>, options?: ClientRequestOptions): Promise<FetchResponse<ClientRequestResponse<TConfig>>>;
}
interface ActionDescriptorFn<TConfig extends RequestConfigSchema> extends ActionDescriptor<TConfig> {
(config?: ClientRequestEntry<TConfig>, options?: ClientRequestOptions): Promise<ClientRequestResponse<TConfig>>;
}
type ClientRequestEntry<TConfig extends RequestConfigSchema, T = ClientRequestEntryContainer<TConfig>> = { [K in keyof T as T[K] extends undefined ? never : K]: T[K] };
type ClientRequestEntryContainer<TConfig extends RequestConfigSchema> = {
body: TConfig["body"] extends TObject ? Static<TConfig["body"]> : undefined;
params: TConfig["params"] extends TObject ? Static<TConfig["params"]> : undefined;
headers?: TConfig["headers"] extends TObject ? Static<TConfig["headers"]> : undefined;
query?: TConfig["query"] extends TObject ? Partial<Static<TConfig["query"]>> : undefined;
};
interface ClientRequestOptions extends FetchOptions {
/**
* Standard request fetch options.
*/
request?: RequestInit;
}
type ClientRequestResponse<TConfig extends RequestConfigSchema> = TConfig["response"] extends TSchema ? Static<TConfig["response"]> : any;
/**
* Specific handler for server actions.
*/
type ServerActionHandler<TConfig extends RequestConfigSchema = RequestConfigSchema> = (request: ServerActionRequest<TConfig>) => Async<ServerResponseBody<TConfig>>;
/**
* Server Action Request Interface
*
* Can be extended with module augmentation to add custom properties (like `user` in Server Security).
*
* This is NOT Server Request, but a specific type for actions.
*/
interface ServerActionRequest<TConfig extends RequestConfigSchema> extends ServerRequest<TConfig> {}
//#endregion
//#region src/schemas/errorSchema.d.ts
declare const errorSchema: typebox0.TObject<{
error: typebox0.TString;
status: typebox0.TInteger;
message: typebox0.TString;
details: typebox0.TOptional<typebox0.TString>;
requestId: typebox0.TOptional<typebox0.TString>;
cause: typebox0.TOptional<typebox0.TObject<{
name: typebox0.TString;
message: typebox0.TString;
}>>;
}>;
type ErrorSchema = Static<typeof errorSchema>;
//#endregion
//#region src/errors/HttpError.d.ts
declare const isHttpError: (error: unknown, status?: number) => error is HttpErrorLike;
declare class HttpError extends AlephaError {
name: string;
static is: (error: unknown, status?: number) => error is HttpErrorLike;
static toJSON(error: HttpError): ErrorSchema;
readonly error: string;
readonly status: number;
readonly requestId?: string;
readonly details?: string;
readonly reason?: {
name: string;
message: string;
};
constructor(options: Partial<ErrorSchema>, cause?: unknown);
}
declare const errorNameByStatus: Record<number, string>;
interface HttpErrorLike extends Error {
status: number;
}
//#endregion
//#region src/descriptors/$route.d.ts
/**
* Create a basic endpoint.
*
* It's a low level descriptor. You probably want to use `$action` instead.
*
* @see {@link $action}
* @see {@link $page}
*/
declare const $route: {
<TConfig extends RequestConfigSchema>(options: RouteDescriptorOptions<TConfig>): RouteDescriptor<TConfig>;
[KIND]: typeof RouteDescriptor;
};
interface RouteDescriptorOptions<TConfig extends RequestConfigSchema = RequestConfigSchema> extends ServerRoute<TConfig> {}
declare class RouteDescriptor<TConfig extends RequestConfigSchema> extends Descriptor<RouteDescriptorOptions<TConfig>> {
protected readonly serverRouterProvider: ServerRouterProvider;
protected onInit(): void;
}
//#endregion
//#region src/errors/BadRequestError.d.ts
declare class BadRequestError extends HttpError {
constructor(message?: string, cause?: unknown);
}
//#endregion
//#region src/errors/ConflictError.d.ts
declare class ConflictError extends HttpError {
constructor(message?: string, cause?: unknown);
}
//#endregion
//#region src/errors/ForbiddenError.d.ts
declare class ForbiddenError extends HttpError {
constructor(message?: string, cause?: unknown);
}
//#endregion
//#region src/errors/NotFoundError.d.ts
declare class NotFoundError extends HttpError {
constructor(message?: string, cause?: unknown);
}
//#endregion
//#region src/errors/UnauthorizedError.d.ts
declare class UnauthorizedError extends HttpError {
constructor(message?: string, cause?: unknown);
}
//#endregion
//#region src/errors/ValidationError.d.ts
declare class ValidationError extends HttpError {
constructor(message?: string, cause?: unknown);
}
//#endregion
//#region src/helpers/isMultipart.d.ts
/**
* Checks if the route has multipart/form-data request body.
*/
declare const isMultipart: (options: {
schema?: RequestConfigSchema;
requestBodyType?: string;
}) => boolean;
//#endregion
//#region src/schemas/okSchema.d.ts
declare const okSchema: typebox0.TObject<{
ok: typebox0.TBoolean;
id: typebox0.TOptional<typebox0.TUnion<[typebox0.TString, typebox0.TInteger]>>;
count: typebox0.TOptional<typebox0.TNumber>;
}>;
type Ok = Static<typeof okSchema>;
//#endregion
//#region src/providers/NodeHttpServerProvider.d.ts
declare const envSchema: _alepha_core11.TObject<{
SERVER_PORT: _alepha_core11.TInteger;
SERVER_HOST: _alepha_core11.TString;
}>;
declare module "alepha" {
interface Env extends Partial<Static<typeof envSchema>> {}
}
declare class NodeHttpServerProvider extends ServerProvider {
protected readonly alepha: Alepha;
protected readonly dateTimeProvider: DateTimeProvider;
protected readonly log: _alepha_logger3.Logger;
protected readonly env: {
SERVER_PORT: number;
SERVER_HOST: string;
};
protected readonly router: ServerRouterProvider;
protected readonly server: http0.Server<typeof IncomingMessage, typeof ServerResponse$1>;
protected readonly onNodeRequest: _alepha_core11.HookDescriptor<"node:request">;
handle(req: IncomingMessage, res: ServerResponse$1): Promise<void>;
get hostname(): string;
readonly start: _alepha_core11.HookDescriptor<"start">;
protected readonly stop: _alepha_core11.HookDescriptor<"stop">;
protected listen(): Promise<void>;
protected close(): Promise<void>;
}
//#endregion
//#region src/providers/ServerLoggerProvider.d.ts
declare class ServerLoggerProvider {
protected readonly log: _alepha_logger3.Logger;
protected readonly alepha: Alepha;
readonly onRequest: _alepha_core11.HookDescriptor<"server:onRequest">;
readonly onError: _alepha_core11.HookDescriptor<"server:onError">;
readonly onResponse: _alepha_core11.HookDescriptor<"server:onResponse">;
}
//#endregion
//#region src/providers/ServerNotReadyProvider.d.ts
/**
* On every request, this provider checks if the server is ready.
*
* If the server is not ready, it responds with a 503 status code and a message indicating that the server is not ready yet.
*
* The response also includes a `Retry-After` header indicating that the client should retry after 5 seconds.
*/
declare class ServerNotReadyProvider {
protected readonly alepha: Alepha;
readonly onRequest: _alepha_core11.HookDescriptor<"server:onRequest">;
}
//#endregion
//#region src/index.d.ts
declare module "alepha" {
interface Hooks {
"action:onRequest": {
action: ActionDescriptor<RequestConfigSchema>;
request: ServerRequest;
options: ClientRequestOptions;
};
"action:onResponse": {
action: ActionDescriptor<RequestConfigSchema>;
request: ServerRequest;
options: ClientRequestOptions;
response: any;
};
"server:onRequest": {
route: ServerRoute;
request: ServerRequest;
};
"server:onError": {
route: ServerRoute;
request: ServerRequest;
error: Error;
};
"server:onSend": {
route: ServerRoute;
request: ServerRequest;
};
"server:onResponse": {
route: ServerRoute;
request: ServerRequest;
response: ServerResponse;
};
"client:onRequest": {
route: HttpAction;
config: ServerRequestConfigEntry;
options: ClientRequestOptions;
headers: Record<string, string>;
request: RequestInit;
};
"client:beforeFetch": {
url: string;
options: FetchOptions;
request: RequestInit;
};
"client:onError": {
route?: HttpAction;
error: HttpError;
};
"node:request": {
req: IncomingMessage;
res: ServerResponse$1;
};
"web:request": {
req: Request;
res?: Response;
};
}
}
/**
* Provides high-performance HTTP server capabilities with declarative routing and action descriptors.
*
* The server module enables building REST APIs and web applications using `$route` and `$action` descriptors
* on class properties. It provides automatic request/response handling, schema validation, middleware support,
* and seamless integration with other Alepha modules for a complete backend solution.
*
* @see {@link $route}
* @see {@link $action}
* @module alepha.server
*/
declare const AlephaServer: _alepha_core11.Service<_alepha_core11.Module<{}>>;
//#endregion
export { $action, $route, ActionDescriptor, ActionDescriptorFn, ActionDescriptorOptions, AlephaServer, BadRequestError, ClientRequestEntry, ClientRequestEntryContainer, ClientRequestOptions, ClientRequestResponse, ConflictError, ErrorSchema, FetchActionArgs, FetchOptions, FetchResponse, ForbiddenError, HttpAction, HttpClient, HttpClientPendingRequests, HttpError, HttpErrorLike, NodeHttpServerProvider, NotFoundError, Ok, RequestConfigSchema, RequestInitWithOptions, ResponseBodyType, ResponseKind, RouteDescriptor, RouteDescriptorOptions, RouteMethod, ServerActionHandler, ServerActionRequest, ServerHandler, ServerLoggerProvider, ServerNotReadyProvider, ServerProvider, ServerRawRequest, ServerReply, ServerRequest, ServerRequestConfig, ServerRequestConfigEntry, ServerResponse, ServerResponseBody, ServerRoute, ServerRouteMatcher, ServerRouteRequestHandler, ServerRouterProvider, ServerTimingProvider, TRequestBody, TResponseBody, UnauthorizedError, ValidationError, errorNameByStatus, errorSchema, isHttpError, isMultipart, okSchema, routeMethods };
//# sourceMappingURL=index.d.ts.map