CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-undici-types

A stand-alone types package for Undici HTTP client library

Pending
Overview
Eval results
Files

connection-management.mddocs/

Connection Management

Advanced connection pooling, load balancing, and proxy support for high-performance applications. These components provide sophisticated routing and connection management capabilities.

Capabilities

Proxy Agent

HTTP proxy support with authentication and custom configuration.

/**
 * HTTP proxy agent supporting HTTP and HTTPS proxies
 * Handles proxy authentication and connection management
 */
class ProxyAgent extends Dispatcher {
  constructor(options: ProxyAgent.Options);
  
  readonly closed: boolean;
  readonly destroyed: boolean;
}

interface ProxyAgent.Options {
  /** Proxy server URI */
  uri: string;
  
  /** Proxy authentication token */
  token?: string;
  
  /** Proxy authentication (alternative to token) */
  auth?: string;
  
  /** Request timeout in milliseconds */
  requestTimeout?: number;
  
  /** Connection timeout in milliseconds */
  connectionTimeout?: number;
  
  /** Headers to send with proxy requests */
  headers?: Record<string, string>;
  
  /** Dispatcher factory for creating upstream connections */
  factory?: (origin: URL, opts: object) => Dispatcher;
}

Usage Examples:

import { ProxyAgent, request } from "undici-types";

// Basic proxy agent
const proxyAgent = new ProxyAgent({
  uri: "http://proxy.example.com:8080"
});

// Proxy with authentication
const authProxyAgent = new ProxyAgent({
  uri: "http://proxy.example.com:8080",
  auth: "username:password"
});

// Proxy with bearer token
const tokenProxyAgent = new ProxyAgent({
  uri: "https://proxy.example.com:8080",
  token: "Bearer your-token-here",
  requestTimeout: 30000,
  headers: {
    "User-Agent": "MyApp/1.0"
  }
});

// Use proxy for requests
const response = await request("https://api.example.com/data", {
  dispatcher: proxyAgent
});

// Set as global dispatcher
import { setGlobalDispatcher } from "undici-types";
setGlobalDispatcher(proxyAgent);

Environment HTTP Proxy Agent

Automatic proxy configuration from environment variables.

/**
 * HTTP proxy agent that automatically configures from environment variables
 * Reads HTTP_PROXY, HTTPS_PROXY, and NO_PROXY environment variables
 */
class EnvHttpProxyAgent extends Dispatcher {
  constructor(options?: EnvHttpProxyAgent.Options);
  
  readonly closed: boolean;
  readonly destroyed: boolean;
}

interface EnvHttpProxyAgent.Options {
  /** Request timeout in milliseconds */
  requestTimeout?: number;
  
  /** Connection timeout in milliseconds */
  connectionTimeout?: number;
  
  /** Headers to send with proxy requests */
  headers?: Record<string, string>;
  
  /** Dispatcher factory for creating upstream connections */
  factory?: (origin: URL, opts: object) => Dispatcher;
}

Usage Examples:

import { EnvHttpProxyAgent, setGlobalDispatcher } from "undici-types";

// Set environment variables (typically done by the system)
// HTTP_PROXY=http://proxy.example.com:8080
// HTTPS_PROXY=https://secure-proxy.example.com:8080  
// NO_PROXY=localhost,127.0.0.1,.example.com

// Create agent that reads environment
const envProxyAgent = new EnvHttpProxyAgent({
  requestTimeout: 30000,
  connectionTimeout: 10000
});

// Set as global dispatcher for automatic proxy usage
setGlobalDispatcher(envProxyAgent);

// All requests now use environment-configured proxy
const response1 = await request("https://api.example.com/data"); // Uses HTTPS_PROXY
const response2 = await request("http://api.example.com/data");  // Uses HTTP_PROXY
const response3 = await request("https://localhost:3000/data"); // Bypassed (NO_PROXY)

Retry Agent

Agent with automatic retry capabilities for failed requests.

/**
 * Agent with automatic retry capabilities
 * Handles transient failures with configurable retry strategies
 */
class RetryAgent extends Dispatcher {
  constructor(dispatcher: Dispatcher, options?: RetryAgent.Options);
  
  readonly closed: boolean;
  readonly destroyed: boolean;
}

interface RetryAgent.Options {
  /** Maximum number of retry attempts */
  retry?: number;
  
  /** Maximum timeout for retry attempts in milliseconds */
  maxTimeout?: number;
  
  /** Minimum timeout between retries in milliseconds */
  minTimeout?: number;
  
  /** Timeout multiplier for exponential backoff */
  timeoutFactor?: number;
  
  /** Maximum delay between retries in milliseconds */
  maxRetryAfter?: number;
  
  /** HTTP methods to retry */
  methods?: HttpMethod[];
  
  /** HTTP status codes to retry */
  statusCodes?: number[];
  
  /** Error codes to retry */
  errorCodes?: string[];
  
  /** Custom retry condition function */
  retryAfter?: boolean;
}

type HttpMethod = "GET" | "HEAD" | "OPTIONS" | "PUT" | "DELETE" | "TRACE";

Usage Examples:

import { RetryAgent, Agent } from "undici-types";

// Create base agent
const baseAgent = new Agent({
  connections: 100
});

// Wrap with retry capabilities
const retryAgent = new RetryAgent(baseAgent, {
  retry: 3,
  maxTimeout: 30000,
  minTimeout: 1000,
  timeoutFactor: 2,
  methods: ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"],
  statusCodes: [408, 413, 429, 500, 502, 503, 504],
  errorCodes: ["ECONNRESET", "ECONNREFUSED", "ENOTFOUND", "ENETDOWN"]
});

// Requests automatically retry on failure
const response = await retryAgent.request({
  path: "/api/unreliable-endpoint",
  method: "GET",
  origin: "https://api.example.com"
});

// Custom retry logic
const customRetryAgent = new RetryAgent(baseAgent, {
  retry: 5,
  retryAfter: true, // Respect Retry-After headers
  maxRetryAfter: 30000,
  statusCodes: [429, 500, 502, 503, 504]
});

Snapshot Agent

Agent for capturing and replaying HTTP interactions.

/**
 * Agent for snapshot testing and HTTP interaction recording
 * Captures requests and responses for testing scenarios
 */
class SnapshotAgent extends Dispatcher {
  constructor(options?: SnapshotAgent.Options);
  
  readonly closed: boolean;
  readonly destroyed: boolean;
  
  /** Capture snapshot of HTTP interactions */
  capture(): SnapshotAgent.Snapshot;
  
  /** Restore from snapshot */
  restore(snapshot: SnapshotAgent.Snapshot): void;
  
  /** Clear recorded interactions */
  clear(): void;
}

interface SnapshotAgent.Options {
  /** Base dispatcher for actual requests */
  dispatcher?: Dispatcher;
  
  /** Recording mode */
  mode?: "record" | "replay" | "passthrough";
  
  /** Snapshot storage path */
  snapshotPath?: string;
  
  /** Whether to update snapshots */
  updateSnapshot?: boolean;
}

interface SnapshotAgent.Snapshot {
  interactions: Array<{
    request: {
      method: string;
      url: string;
      headers: Record<string, string>;
      body?: string;
    };
    response: {
      status: number;
      headers: Record<string, string>;
      body: string;
    };
  }>;
  timestamp: string;
  version: string;
}

Usage Examples:

import { SnapshotAgent } from "undici-types";

// Recording mode - captures real HTTP interactions
const recordingAgent = new SnapshotAgent({
  mode: "record",
  snapshotPath: "./snapshots/api-interactions.json"
});

// Make requests that get recorded
await recordingAgent.request({
  origin: "https://api.example.com",
  path: "/users",
  method: "GET"
});

await recordingAgent.request({
  origin: "https://api.example.com", 
  path: "/posts",
  method: "GET"
});

// Capture the recorded interactions
const snapshot = recordingAgent.capture();

// Replay mode - replays captured interactions
const replayAgent = new SnapshotAgent({
  mode: "replay",
  snapshotPath: "./snapshots/api-interactions.json"
});

// Restore from snapshot
replayAgent.restore(snapshot);

// These requests return recorded responses
const usersResponse = await replayAgent.request({
  origin: "https://api.example.com",
  path: "/users", 
  method: "GET"
});

const postsResponse = await replayAgent.request({
  origin: "https://api.example.com",
  path: "/posts",
  method: "GET"
});

Connection Builder

Low-level connection building utilities for custom connection logic.

/**
 * Build custom connection function for clients
 * @param options - Connection building options
 * @returns Connection function
 */
function buildConnector(options?: buildConnector.Options): buildConnector.connector;

namespace buildConnector {
  interface Options {
    /** Maximum number of cached sessions */
    maxCachedSessions?: number;
    
    /** Socket path for Unix domain sockets */
    socketPath?: string;
    
    /** Connection timeout in milliseconds */
    timeout?: number;
    
    /** Keep alive timeout in milliseconds */
    keepAlive?: number;
    
    /** Keep alive initial delay in milliseconds */
    keepAliveInitialDelay?: number;
    
    /** TLS connection options */
    tls?: TLSSocket.Options;
    
    /** Whether to allow half-open connections */
    allowHalfOpen?: boolean;
  }
  
  interface connector {
    (options: {
      hostname: string;
      host?: string;
      protocol: string;
      port: string;
      servername?: string;
      localAddress?: string;
      httpSocket?: Socket;
    }, callback: (error: Error | null, socket?: Socket | TLSSocket) => void): void;
  }
  
  interface TLSSocket extends Socket {
    authorized: boolean;
    authorizationError?: Error;
    encrypted: boolean;
    getCertificate(): PeerCertificate | null;
    getPeerCertificate(detailed?: boolean): PeerCertificate | null;
    getSession(): Buffer | null;
    getTLSTicket(): Buffer | null;
    renegotiate(options: object, callback: (err: Error | null) => void): boolean;
    setMaxSendFragment(size: number): boolean;
  }
}

Usage Examples:

import { buildConnector, Client } from "undici-types";

// Custom connector with Unix socket
const unixConnector = buildConnector({
  socketPath: "/var/run/app.sock",
  timeout: 10000
});

const unixClient = new Client("http://localhost", {
  connect: unixConnector
});

// Custom connector with TLS options
const tlsConnector = buildConnector({
  timeout: 15000,
  keepAlive: true,
  keepAliveInitialDelay: 1000,
  tls: {
    rejectUnauthorized: false,
    ca: customCertificate,
    cert: clientCertificate,
    key: clientKey
  }
});

const secureClient = new Client("https://secure.example.com", {
  connect: tlsConnector
});

// Custom connector with connection caching
const cachingConnector = buildConnector({
  maxCachedSessions: 100,
  timeout: 30000,
  keepAlive: true
});

const cachingClient = new Client("https://api.example.com", {
  connect: cachingConnector
});

Advanced Configuration

Global Origin Management

/**
 * Set global origin for relative URL resolution
 * @param origin - The base origin URL
 */
function setGlobalOrigin(origin: string | URL): void;

/**
 * Get the current global origin
 * @returns Current global origin or undefined
 */
function getGlobalOrigin(): string | undefined;

Global Dispatcher Management

/**
 * Set the global dispatcher for all HTTP operations
 * @param dispatcher - The dispatcher to use globally
 */
function setGlobalDispatcher(dispatcher: Dispatcher): void;

/**
 * Get the current global dispatcher
 * @returns Current global dispatcher
 */
function getGlobalDispatcher(): Dispatcher;

Usage Examples:

import { 
  setGlobalDispatcher, 
  setGlobalOrigin,
  ProxyAgent,
  RetryAgent,
  Agent 
} from "undici-types";

// Set up sophisticated global configuration
const baseAgent = new Agent({ connections: 200 });
const proxyAgent = new ProxyAgent({
  uri: process.env.HTTP_PROXY || "http://proxy.company.com:8080"
});
const retryAgent = new RetryAgent(proxyAgent, {
  retry: 3,
  methods: ["GET", "HEAD", "PUT", "DELETE"]
});

// Configure global settings
setGlobalDispatcher(retryAgent);
setGlobalOrigin("https://api.company.com");

// All requests now use proxy + retry + connection pooling
const response = await request("/users"); // Relative URL resolved with global origin

Install with Tessl CLI

npx tessl i tessl/npm-undici-types

docs

connection-management.md

cookies.md

error-handling.md

http-api.md

http-clients.md

index.md

interceptors.md

testing-mocking.md

utilities.md

web-standards.md

tile.json