import type { BuildOptions, BuildResult, TransformOptions, TransformResult } from 'esbuild'; import type { ChildProcess } from 'node:child_process'; import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http'; import type { Http2ServerRequest, Http2ServerResponse } from 'node:http2'; import type { Worker } from 'node:worker_threads'; import type { MatchFunction, ParamData } from 'path-to-regexp'; export interface ApplicationWorker { readonly activeProcess?: Worker; readonly origins: Set; readonly isListening: boolean; /** * Add `filePaths` to file watcher */ addWatchFiles(filePaths: string | Array): void; /** * Send message to the application thread */ sendMessage(message: string | object | number | boolean | bigint): void; } /** * Server instance factory */ export declare function server(filePath?: string | Array, { argv, certsPath, directories, electron, hooksPath, mockPath, port, reload, silent, verbose, }?: ServerOptions): Promise; export interface ElectronProcess { readonly activeThread?: ChildProcess; readonly origins: Set; readonly isListening: boolean; /** * Add `filePaths` to file watcher */ addWatchFiles(filePaths: string | Array): void; /** * Send message to the electron process */ sendMessage(message: string | object | number | boolean | bigint): void; } export interface Hooks { /** * Bundle non-esm node_modules dependency requested by the browser. * This hook is run after file read. */ onDependencyBundle?(id: string, filePath: string, fileContents: string, context: DependencyBundleHookContext): Promise | string | undefined; /** * Transform file contents for file requested by the browser. * This hook is run after file read, and before any modifications by dvlp. */ onTransform?(filePath: string, fileContents: string, context: TransformHookContext): Promise | string | undefined; /** * Manually resolve import specifier. * This hook is run for each import statement. * If returns "false", import re-writing is skipped. * If returns "undefined", import specifier is re-written using default resolver. * If "context.isDynamic", also possible to return replacement for whole expression. */ onResolveImport?(specifier: string, context: ResolveHookContext, defaultResolve: DefaultResolve): string | false | undefined; /** * Manually handle response for incoming server request. * If returns "true", further processing by dvlp will be aborted. */ onRequest?(request: IncomingMessage | Http2ServerRequest, response: ServerResponse | Http2ServerResponse): Promise | boolean | undefined; /** * Modify response body before sending to the browser. * This hook is run after all modifications by dvlp, and before sending to the browser. */ onSend?(filePath: string, responseBody: string): string | undefined; /** * Manually resolve import specifiers for application server. * @see https://nodejs.org/api/esm.html#resolvespecifier-context-nextresolve */ onServerResolve?(specifier: string, context: { conditions: Array; parentURL?: string; }, nextResolve: NodeResolveLoaderHook): { format?: string; url: string; }; /** * Transform file contents for application server. * @see https://nodejs.org/api/esm.html#loadurl-context-nextload */ onServerTransform?(filePath: string, context: { format?: string; }, nextLoad: NodeLoadLoaderHook): { format: string; source: string | SharedArrayBuffer | Uint8Array; }; } export interface DependencyBundleHookContext { esbuild: Pick; } export interface TransformHookContext { client: { manufacturer?: string; name?: string; ua: string; version?: string; }; esbuild: esbuild; } export interface ResolveHookContext { importer: string; isDynamic: boolean; } export type DefaultResolve = (specifier: string, importer: string) => string | undefined; export type NodeResolveLoaderHook = (specifier: string, context: { conditions: Array; parentURL?: string; }, nextResolve: NodeResolveLoaderHook) => { format?: string; url: string; }; export type NodeLoadLoaderHook = (url: string, context: { format?: string; }, defaultLoad: NodeLoadLoaderHook) => { format: string; source: string | SharedArrayBuffer | Uint8Array; }; export interface Mocks { addResponse(req: string | MockRequest, res: MockResponse | MockResponseHandler, once?: boolean, onMock?: () => void): MockedResponse; addPushEvents(stream: string | MockPushStream, events: MockPushEvent | Array): () => void; load(filePaths: string | Array): void; matchResponse(href: string, req?: Req, res?: Res): boolean | MockResponseData; matchPushEvent(stream: string | MockPushStream, name: string, push: (stream: string | PushStream, event: PushEvent) => void): boolean; hasMatch(reqOrMockData: string | URL | { url: string; } | MockResponseData | MockStreamData): boolean; remove(reqOrMockData: string | URL | { url: string; } | MockResponseData | MockStreamData): void; clear(): void; /** @deprecated */ clean(): void; } 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 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 interface ServerOptions { /** * The command-line arguments to pass to the application thread or electron process (default `[]`). */ argv?: Array; /** * The path or glob pattern containing ".crt" and ".key" files. * This enables secure https mode by proxying all requests through a secure server (default `''`). */ certsPath?: string | Array; /** * Additional directories to use for resolving file requests (default `[]`). */ directories?: Array; /** * Run file as electron.js entry file (default `false`). */ electron?: boolean; /** * The path to a custom hooks registration file (default `''`). */ hooksPath?: string; /** * The path(s) to load mock files from. */ mockPath?: string | Array; /** * Port to expose on `localhost`. * Will use `process.env.PORT` if not specified here (default `8080`). */ port?: number; /** * Enable/disable browser reloading (default `true`). */ reload?: boolean; /** * Disable/enable all logging (default `false`). */ silent?: boolean; /** * Disable/enable verbose logging (default `false`). */ verbose?: boolean; } export interface Server { /** * The entry config */ readonly entry: Entry; /** * The listening state */ readonly isListening: boolean; /** * The localhost origin */ readonly origin: string; /** * The `Mocks` instance */ readonly mocks: Mocks; /** * The localhost port number */ readonly port: number; /** * The active application worker thread, if initialised */ readonly applicationWorker?: ApplicationWorker; /** * The active electron process, if initialised */ readonly electronProcess?: ElectronProcess; /** * Add `filePaths` to file watcher */ addWatchFiles(filePaths: string | Array): void; /** * Destroy server instance */ destroy(): Promise; } export type ContentType = 'css' | 'html' | 'js'; export interface Entry { directories: Array; isApp: boolean; isElectron: boolean; isSecure: boolean; isStatic: boolean; main: string | undefined; } export type esbuild = { build(options: BuildOptions & { write: false; }): Promise; transform(input: string, options?: TransformOptions): Promise; }; 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; } /** * Retrieve all dependencies for "filePath" */ export declare function getDependencies(filePath: string, platform: 'browser' | 'node'): Promise>; export interface RequestContext { assert: ImportAssertionType; dynamic: boolean; filePath?: string; href: string; imported: boolean; type?: ContentType; } export type ImportAssertionType = 'css' | 'json' | undefined;