web-dev-server
Version:
Node.js simple http server for common development or training purposes.
233 lines (232 loc) • 10.1 kB
TypeScript
/// <reference types="node" />
import { Server as HttpServer, RequestListener as HttpRequestListener } from "http";
import { Socket } from "net";
import { Stats as FsStats } from "fs";
import { Defaults } from "./Handlers/Defaults";
import { Register } from "./Applications/Register";
import { ErrorsHandler } from "./Handlers/Error";
import { FilesHandler } from "./Handlers/File";
import { DirectoriesHandler } from "./Handlers/Directory";
import { Event } from "./Event";
import { Request } from "./Request";
import { Response } from "./Response";
export * from "./Request";
export * from "./Response";
export * from "./Event";
export * from "./Tools/Namespace";
export * from "./Applications/IApplication";
import { Session as _Session } from "./Applications/Session";
export declare class Session extends _Session {
}
import { INamespace as _INamespace } from "./Applications/Sessions/INamespace";
export declare namespace Session {
interface INamespace extends _INamespace {
}
}
export declare class Server {
static readonly VERSION: string;
static readonly STATES: {
CLOSED: number;
STARTING: number;
CLOSING: number;
STARTED: number;
};
static DEFAULTS: {
PORT: number;
DOMAIN: string;
RESPONSES: typeof Defaults;
};
protected state: number;
protected documentRoot?: string;
protected basePath?: string;
protected port?: number;
protected hostName?: string;
protected development: boolean;
protected indexes: {
scripts: string[];
files: string[];
};
protected httpServer?: HttpServer;
protected netSockets?: Set<Socket>;
protected customServerHandler?: HttpRequestListener;
protected register?: Register;
protected errorsHandler?: ErrorsHandler;
protected filesHandler?: FilesHandler;
protected directoriesHandler?: DirectoriesHandler;
protected customErrorHandler?: (err: Error, code?: number, req?: Request, res?: Response) => Promise<void>;
protected customHttpPreHandlers: ((req: Request, res: Response, event?: Event) => Promise<void>)[];
protected forbiddenPaths: (string | RegExp)[];
/**
* @summary Create new server instance (no singleton implementation).
*/
static CreateNew(): Server;
/**
* @summary Set development mode, `true` by default. If `true`, directories contents and errors are displayed, `false` otherwise.
* @param development If `true`, directories contents and errors are displayed, `false` otherwise.
*/
SetDevelopment(development: boolean): Server;
/**
* @summary Set http server IP or domain to listening on, `127.0.0.1` by default.
* @param hostname Server ip or domain to listening on.
*/
SetHostname(hostname: string): Server;
/**
* @summary Set http server port number, `8000` by default.
* @param port Server port to listening on.
*/
SetPort(port: number): Server;
/**
* @summary Set http server root directory, required
* @param dirname Server root directory as absolute path.
*/
SetDocumentRoot(dirname: string): Server;
/**
* @summary Set http server base path, not required
* @param basePath Base path (proxy path, if you are running the server under proxy).
*/
SetBasePath(basePath: string): Server;
/**
* @summary Set custom http server handler like express module.
* @see https://stackoverflow.com/a/17697134/7032987
* @param httpHandler
*/
SetServerHandler(httpHandler: HttpRequestListener): Server;
/**
* @summary Set custom error handler for uncatched errors and warnings
* @param errorHandler Custom handler called on any uncatched error.
*/
SetErrorHandler(errorHandler: (err: Error, code?: number, req?: Request, res?: Response) => Promise<void>): Server;
/**
* Set forbidden request paths to prevent requesting dangerous places (`["/node_modules", /\/package\.json/g, /\/tsconfig\.json/g, /\/\.([^\.]+)/g]` by default). All previous configuration will be overwritten.
* @param forbiddenPaths Forbidden request path begins or regular expression patterns.
*/
SetForbiddenPaths(forbiddenPaths: (string | RegExp)[]): Server;
/**
* Add forbidden request paths to prevent requesting dangerous places (`["/node_modules", /\/package\.json/g, /\/tsconfig\.json/g, /\/\.([^\.]+)/g]` by default).
* @param forbiddenPaths Forbidden request path begins or regular expression patterns.
*/
AddForbiddenPaths(forbiddenPaths: (string | RegExp)[]): Server;
/**
* Set directory index/default server script file names executed on server side as directory content.
* All previous configuration will be replaced.
* Default value is: `['index.js']`.
* @param indexScripts Array of file names like `['index.js', 'default.js', 'app.js', ...]`.
*/
SetIndexScripts(indexScripts: string[]): Server;
/**
* Add directory index/default server script file names executed on server side as directory content.
* Default value is: `['index.js']`.
* @param indexScripts Array of file names like `['default.js', 'app.js', ...]`.
*/
AddIndexScripts(indexScripts: string[]): Server;
/**
* Set directory index/default server file names staticly send to client as default directory content.
* All previous configuration will be replaced.
* Default value is: `['index.html','index.htm','default.html','default.htm']`.
* @param indexFiles Array of file names like `['index.html','index.htm','default.html','default.htm', 'directory.html', ...]`.
*/
SetIndexFiles(indexFiles: string[]): Server;
/**
* Add directory index/default server file names staticly send to client as default directory content.
* Default value is: `['index.html','index.htm','default.html','default.htm']`.
* @param indexFiles Array of file names like `['directory.html', 'directory.htm', ...]`.
*/
AddIndexFiles(indexFiles: string[]): Server;
/**
* @summary Add custom express http handler
* @param handler Custom http request handler called every allowed request path before standard server handling.
*/
AddPreHandler(handler: (req: Request, res: Response, event?: Event) => Promise<void>): Server;
/**
* @summary Return `true` if development flag is used.
*/
IsDevelopment(): boolean;
/**
* @summary Return configured domain or ip address.
*/
GetHostname(): string;
/**
* @summary Return configured port number.
*/
GetPort(): number;
/**
* @summary Return configured document root directory full path.
*/
GetDocumentRoot(): string;
/**
* @summary Return configured base url.
*/
GetBasePath(): string;
/**
* @summary Return configured custom errors handler.
*/
GetErrorHandler(): ((err: Error, code: number, req?: Request, res?: Response) => Promise<void>) | null;
/**
* Get forbidden request paths to prevent requesting dangerous places.
*/
GetForbiddenPaths(): (string | RegExp)[];
/**
* Get directory index/default server script file names executed on server side as directory content.
* Default value is: `['index.js']`.
*/
GetIndexScripts(): string[];
/**
* Get directory index/default server file names staticly send to client as default directory content.
* Default value is: `['index.html','index.htm','default.html','default.htm']`.
*/
GetIndexFiles(): string[];
/**
* @summary Return used http server instance.
*/
GetHttpServer(): HttpServer | null;
/**
* @summary Return set of connected sockets.
*/
GetNetSockets(): Set<Socket>;
/**
* @summary Return server running state (`Server.STATES.<state>`).
*/
GetState(): number;
/**
* @summary Try to find cached record by server document root and requested path
* and return directory full path from the cache record.
* @param rawRequestUrl Raw requested path.
*/
TryToFindIndexPath(rawRequestUrl: string): string[] | null;
/**
* @summary Start HTTP server
*/
Start(callback?: (success?: boolean, error?: Error) => void): Server;
/**
* @summary Close all registered app instances, close and destroy all connected sockets and stop http server.
* @param callback
*/
Stop(callback?: (success?: boolean, error?: Error) => void): Server;
/**
* @summary Handle all HTTP requests
*/
protected handleReq(req: Request, res: Response): Promise<void>;
/**
* @summary Close all registered app instances, close and destroy all connected sockets and stop http server.
* @param callback
*/
protected stopHandler(callback?: (success?: boolean, error?: Error) => void): void;
/**
* Get if path is allowed by `this.forbiddenPaths` configuration.
* @param path Path including start slash, excluding base url and excluding params.
*/
protected isPathAllowed(path: string): boolean;
/**
* @summary Process request content found
*/
protected handleReqExistingPath(fullPath: string, requestPath: string, stats: FsStats, req: Request, res: Response): void;
/**
* @summary Display error 500/404 (and try to list first existing parent folder content):
*/
protected handleReqNonExistingPath(requestPath: string, req: Request, res: Response): void;
/**
* @summary Try to get file system directory stats - recursively on first existing parent directory.
*/
protected handleReqNonExistPath(pathsToFound: string[], index: number, successCallback: (newFullPath: string, newRequestPath: string, dirStats: FsStats) => void, errorCallback: (err: Error) => void): void;
protected getSearchingRequestPaths(requestPath: string): string[];
}