import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http'; import type { Http2ServerRequest, Http2ServerResponse } from 'node:http2'; import type { MatchFunction, ParamData } from 'path-to-regexp'; export interface TestServerFactory { (options?: TestServerOptions): Promise; disableNetwork(rerouteAllRequests?: boolean): void; enableNetwork(): void; mockHangResponseHandler(req: Req, res: MockHandlerResponse): void; mockErrorResponseHandler(req: Req, res: MockHandlerResponse): void; mockMissingResponseHandler(req: Req, res: MockHandlerResponse): void; mockOfflineResponseHandler(req: Req, res: MockHandlerResponse): void; } /** * Create test server */ export declare const testServer: TestServerFactory; export declare class Mocks { /** * The port relative mock urls resolve against, and the reroute target for * intercepted requests. Falls back to the process-wide `config.activePort` * when not assigned by the owning server instance. */ activePort?: number; cache: Set; client: string; loaded: Promise; _uninterceptClientRequest?: () => void; private cacheList; /** * Constructor */ constructor(filePaths?: string | Array); /** * Add new mock for 'res' * * @returns remove mock instance */ addResponse(req: string | MockRequest, res: MockResponse | MockResponseHandler, once?: boolean, onMockCallback?: () => void): MockedResponse; /** * Add new push mock for 'events' * * @returns remove mock instance */ addPushEvents(stream: string | MockPushStream, events: MockPushEvent | Array): () => void; /** * Load mock files from disk */ load(filePaths: string | Array): Promise; /** * Match and handle mock response for 'key' * Will respond if 'res' passed */ matchResponse(href: string, req?: Req, res?: Res): boolean | MockResponseData; /** * Match and handle mock push event for 'stream' */ matchPushEvent(stream: string | MockPushStream, name: string, push: (stream: string | PushStream, event: PushEvent) => void): boolean; /** * Determine if 'reqOrMockData' matches cached mock data */ hasMatch(reqOrMockData: string | URL | { url: string; } | MockResponseData | MockStreamData): boolean; /** * Remove existing mock data */ remove(reqOrMockData: string | URL | { url: string; } | MockResponseData | MockStreamData): void; /** * Clear all mock data * @deprecated - use clear() */ clean(): void; /** * Clear all mock data */ clear(): void; /** * Initialize request interception * * @private */ enableRequestIntercept(): void; /** * Retrieve mock response/stream data * * @private */ getMockData(req: string | URL | { url: string; }, method?: string): MockResponseData | MockStreamData | undefined; /** * @private */ loadFilePath(filePath: string): Promise; /** * Load directory at 'dirpath' * * @private */ loadDirectory(dirpath: string): Promise; /** * Load file at 'filePath' * * @private */ loadFile(filePath: string): Promise; /** * Serialize cache content for transport */ toJSON(): Array; } export type MockResponseDataType = 'html' | 'file' | 'json'; export type MockStreamDataType = 'ws' | 'es'; export interface MockResponseData { url: URL; originRegex: RegExp; pathRegex: RegExp; paramsMatch: MatchFunction; searchParams: URLSearchParams; ignoreSearch: boolean; method?: string; once: boolean; filePath: string; type: MockResponseDataType; response: MockResponse | MockResponseHandler; callback?: () => void; calls: Array; } export interface MockStreamEventData { name?: string; message: Buffer | ArrayBuffer | ArrayBufferView | string | Record; options: MockPushEventOptions & { protocol?: string; }; } export interface MockStreamData { url: URL; originRegex: RegExp; pathRegex: RegExp; paramsMatch: MatchFunction; searchParams: URLSearchParams; ignoreSearch: boolean; filePath: string; type: MockStreamDataType; protocol: string; events: { [name: string]: Array; }; } export interface MockRequest { url: string; filePath?: string; ignoreSearch?: boolean; /** * Match a specific HTTP method (any method matches when omitted). * A method-specific mock is preferred over a method-less one for the same url. */ method?: string; } /** * Handlers receive the plain http response type so header/writeHead overloads * resolve cleanly. Under https/http2 the compat response supports the same api. */ export type MockHandlerResponse = ServerResponse & { error?: Error; }; export type MockResponseHandler = (req: Req, res: MockHandlerResponse) => void; export interface MockResponse { body: string | Record; /** * Delay responding by `delay` ms (ignored for handler responses) */ delay?: number; hang?: boolean; headers?: Record; error?: boolean; missing?: boolean; offline?: boolean; status?: number; } /** * A request that matched a registered mock */ export interface MockRequestCall { /** * Raw request body ("undefined" when the request had none) */ body: string | undefined; headers: IncomingHttpHeaders; method: string | undefined; params?: Record; url: string; } /** * Handle returned when registering a mock response. * Call it to remove the mock; inspect "calls" to assert matched requests. */ export interface MockedResponse { (): void; /** * Requests that matched this mock, in call order */ calls: Array; } export interface MockPushStream { url: string; type: string; filePath?: string; ignoreSearch?: boolean; protocol?: string; } export interface MockPushEventOptions { delay?: number; connect?: boolean; event?: string; id?: string; namespace?: string; } export interface MockPushEvent { name: string; message?: Buffer | ArrayBuffer | ArrayBufferView | string | Record; sequence?: Array; options?: MockPushEventOptions; } export interface SerializedMock { href: string; originRegex: string; pathRegex: string; search: string; ignoreSearch: boolean; events?: Array; } export interface PushStream { url: string; type: string; } export interface PushEvent { message: Buffer | ArrayBuffer | ArrayBufferView | string | Record; options?: PushEventOptions; } export interface PushEventOptions { id?: string; event?: string; namespace?: string; protocol?: string; } export declare class TestServer { #private; latency: number; webroot: string; port: number; mocks: Mocks; /** * Constructor */ constructor(options: TestServerOptions); /** * Start server */ private _start; /** * Load mock files at 'filePath' */ loadMockFiles(filePath: string | Array): Promise; /** * Register mock 'response' for 'request'. * Returns a handle that removes the mock when called, * and exposes matched requests via its "calls" array. */ mockResponse(request: string | MockRequest, response: MockResponse | MockResponseHandler, once?: boolean, onMockCallback?: () => void): MockedResponse; /** * Register a mock stream at 'url', returning a handle exposing live * connections for request/reply, per-connection send, and close with code */ mockStream(url: string, options?: MockStreamOptions): MockStream; /** * Register mock push 'events' for 'stream' * * @param onSendCallback - WS client send callback. * Superseded by `mockStream()`, which exposes per-connection handles. */ mockPushEvents(stream: string | MockPushStream, events: MockPushEvent | Array, onSendCallback?: (data: any) => void): () => void; /** * Push data to WebSocket/EventSource clients * A string passed as 'event' will be handled as a named mock push event */ pushEvent(stream: string | PushStream, event?: string | PushEvent): void; /** * Clear all mock data */ clearMockFiles(): void; ref(): void; unref(): void; /** * Stop running server */ private _stop; /** * Destroy instance */ destroy(): Promise; } export interface MockStreamOptions { /** * Inspect the connection request (headers, Sec-WebSocket-Protocol entries, url) * and return `false` to reject it with a `401` response (default: always authorized). */ authorize?: (context: MockStreamContext) => boolean; /** * WebSocket ping-frame / EventSource comment interval in `ms`, or `false` to disable * (default `false` for WebSocket, `15000` for EventSource). */ ping?: number | false; /** * EventSource reconnect interval in `ms`, sent to clients as the * `retry:` field (default `5000`; ignored for WebSocket). */ retry?: number; /** * Called with a connection handle each time a client connects. */ onConnection?: (connection: MockStreamConnection) => void; } export interface MockStreamContext { headers: IncomingHttpHeaders; /** * Parsed and trimmed `Sec-WebSocket-Protocol` entries (empty for EventSource). */ protocols: Array; url: URL; } export interface MockStreamConnection { /** * Unique per-connection id (new on every (re)connect). */ id: string; type: 'ws' | 'es'; url: URL; headers: IncomingHttpHeaders; protocols: Array; readonly closed: boolean; /** * Send a message on this connection only (same encoding rules as `pushEvent`). */ send(message: PushEvent['message'], options?: PushEventOptions): void; /** * Send a WebSocket ping frame (`onPong` fires when the client answers), * or an EventSource comment. */ ping(message?: string, onPong?: () => void): void; /** * Close this connection. For WebSocket, `code` may be any close code: * `1000`/`3000-4999` use the spec-compliant path, others are framed directly. */ close(code?: number, reason?: string): void; on(event: 'message', handler: (data: string | Buffer) => void): this; on(event: 'close', handler: (event: { code?: number; reason?: string; }) => void): this; once(event: 'message', handler: (data: string | Buffer) => void): this; once(event: 'close', handler: (event: { code?: number; reason?: string; }) => void): this; off(event: 'message', handler: (data: string | Buffer) => void): this; off(event: 'close', handler: (event: { code?: number; reason?: string; }) => void): this; } export interface MockStream { url: URL; type: 'ws' | 'es'; /** * Live connections in connect order. */ connections: Array; /** * Broadcast to all connections (same semantics as `TestServer.pushEvent`). */ pushEvent(event: string | PushEvent): void; /** * Close all connections and unregister the stream. */ destroy(): void; } export interface TestServerOptions { /** * Enable/disable automatic dummy responses. * If unable to resolve a request to a local file or mock, * the server will respond with a dummy file of the appropriate type (default `true`). */ autorespond?: boolean; /** * The amount of artificial latency to introduce (in `ms`) for responses (default `50`). */ latency?: number; /** * The port to expose on `localhost`. Will use `process.env.PORT` if not specified here (default `8080`). */ port?: number; /** * The subpath from `process.cwd()` to prepend to relative paths (default `''`). */ webroot?: string; } export type ContentType = 'css' | 'html' | 'js'; export type Req = (IncomingMessage | Http2ServerRequest) & { filePath: string; type?: ContentType; url: string; params?: Record; context?: RequestContext; contextUrl?: string; }; export type Res = (ServerResponse & Http2ServerResponse) & { bundled: boolean; cached: boolean; encoding: string; metrics: Metrics; mocked: boolean; rerouted: boolean; transformed: boolean; unhandled: boolean; url: string; error?: Error; }; export declare class Metrics { static readonly EVENT_NAMES: { readonly bundle: 'bundle file'; readonly csp: 'inject CSP header'; readonly imports: 'rewrite imports'; readonly mock: 'mock response'; readonly response: 'response'; readonly scripts: 'inject HTML scripts'; readonly transform: 'transform file'; }; events: Map; /** * Constructor */ constructor(res: Res); /** * Register new event with "name", * or complete existing event if already registered. */ recordEvent(name: string): void; /** * Retrieve results for event with "name" */ getEvent(name: string, formatted?: boolean): string | number; } /** * Read the full request body as a string. * Memoised per request, so repeated calls (and dvlp's own mock-call capture) * share a single read of the stream. */ export declare function readBody(req: IncomingMessage | Http2ServerRequest): Promise; export interface RequestContext { assert: ImportAssertionType; dynamic: boolean; filePath?: string; href: string; imported: boolean; type?: ContentType; } export type ImportAssertionType = 'css' | 'json' | undefined;