or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

errors.mdhooks.mdhttp-methods.mdindex.mdinstances.mdoptions.mdpagination.mdresponses.mdstreams.mdutilities.md
tile.json

options.mddocs/

Request Options

Comprehensive configuration system for customizing HTTP requests including URLs, methods, headers, body data, timeouts, retries, and advanced features.

Capabilities

Options Class

The core Options class manages and validates all request configuration.

/**
 * Options class for configuring HTTP requests
 */
class Options {
  /**
   * Creates a new Options instance
   * @param input - Initial options to set
   * @param defaults - Default options to merge with
   * @param parent - Parent options for inheritance
   */
  constructor(input?: OptionsInit, defaults?: Options, parent?: Options);
}

Core Request Options

Basic request configuration options for URL, method, headers, and body data.

interface OptionsInit {
  /**
   * Request URL - can be string or URL object
   */
  url?: string | URL;
  
  /**
   * HTTP method for the request
   * @default "GET"
   */
  method?: Method;
  
  /**
   * Request headers as key-value pairs
   */
  headers?: Headers;
  
  /**
   * Request body - can be string, Buffer, stream, or FormData
   */
  body?: string | Buffer | Readable | FormDataLike;
  
  /**
   * JSON body - automatically serialized and sets content-type
   */
  json?: unknown;
  
  /**
   * Form data as key-value pairs - sets application/x-www-form-urlencoded
   */
  form?: Record<string, any>;
  
  /**
   * URL search parameters/query string
   */
  searchParams?: SearchParameters;
  
  /**
   * Base URL for relative requests
   */
  prefixUrl?: string | URL;
  
  /**
   * Enable Unix Domain Socket support
   * @default false
   */
  enableUnixSockets?: boolean;
}

type Headers = Record<string, string | string[] | undefined>;

type Method = 
  | "GET" | "POST" | "PUT" | "PATCH" | "HEAD" | "DELETE"
  | "OPTIONS" | "TRACE" | "CONNECT";

type SearchParameters = 
  | string 
  | Record<string, string | number | boolean | null | undefined>
  | URLSearchParams
  | Array<[string, string | number | boolean]>;

Usage Examples:

import got from "got";

// Basic request options
const response = await got({
  url: "https://api.example.com/users",
  method: "POST",
  headers: {
    "Authorization": "Bearer token",
    "Content-Type": "application/json"
  },
  json: {
    name: "Alice",
    email: "alice@example.com"
  }
});

// Using search parameters
const users = await got("https://api.example.com/users", {
  searchParams: {
    page: 1,
    limit: 10,
    sort: "name"
  }
});

// Using form data
const response = await got.post("https://api.example.com/login", {
  form: {
    username: "alice",
    password: "secret"
  }
});

Response Handling Options

Options for controlling response parsing and body handling.

interface ResponseOptions {
  /**
   * Response body parsing type
   * @default "text"
   */
  responseType?: ResponseType;
  
  /**
   * Return only the response body instead of full response object
   * @default false
   */
  resolveBodyOnly?: boolean;
  
  /**
   * Custom JSON parsing function
   */
  parseJson?: ParseJsonFunction;
  
  /**
   * Custom JSON stringification function
   */
  stringifyJson?: StringifyJsonFunction;
  
  /**
   * Response encoding for text responses
   * @default "utf8"
   */
  encoding?: BufferEncoding;
  
  /**
   * Maximum response body size in bytes
   */
  maxBuffer?: number;
  
  /**
   * Throw HTTP errors for non-2xx status codes
   * @default true
   */
  throwHttpErrors?: boolean;
  
  /**
   * Accept HTTP error status codes (won't throw)
   */
  allowGetBody?: boolean;
}

type ResponseType = "text" | "json" | "buffer";

type ParseJsonFunction = (text: string) => unknown;
type StringifyJsonFunction = (object: unknown) => string;

Usage Examples:

// Response type configuration
const data = await got("https://api.example.com/data.json", {
  responseType: "json",
  resolveBodyOnly: true
});

// Custom JSON parsing
const response = await got("https://api.example.com/data", {
  responseType: "json",
  parseJson: (text) => JSON.parse(text, (key, value) => {
    // Custom date parsing
    if (key.endsWith("Date")) {
      return new Date(value);
    }
    return value;
  })
});

// Don't throw on HTTP errors
const response = await got("https://api.example.com/might-fail", {
  throwHttpErrors: false
});
console.log(response.statusCode); // Could be 404, 500, etc.

Timeout and Retry Options

Configuration for request timeouts and automatic retry behavior.

interface TimeoutOptions {
  /**
   * Timeout configuration - can be number (ms) or detailed object
   */
  timeout?: Delays | number;
  
  /**
   * Retry configuration
   */
  retry?: RetryOptions;
}

interface Delays {
  /**
   * Timeout for DNS lookup
   */
  lookup?: number;
  
  /**
   * Timeout for socket connection
   */
  connect?: number;
  
  /**
   * Timeout for TLS handshake
   */
  secureConnect?: number;
  
  /**
   * Timeout for socket inactivity
   */
  socket?: number;
  
  /**
   * Timeout for sending request
   */
  send?: number;
  
  /**
   * Timeout for receiving response
   */
  response?: number;
  
  /**
   * Overall request timeout
   */
  request?: number;
}

interface RetryOptions {
  /**
   * Maximum number of retry attempts
   * @default 2
   */
  limit?: number;
  
  /**
   * HTTP methods to retry
   * @default ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "TRACE"]
   */
  methods?: Method[];
  
  /**
   * Status codes to retry
   * @default [408, 413, 429, 500, 502, 503, 504, 521, 522, 524]
   */
  statusCodes?: number[];
  
  /**
   * Error codes to retry
   */
  errorCodes?: string[];
  
  /**
   * Maximum retry delay in milliseconds
   * @default Infinity
   */
  maxRetryAfter?: number;
  
  /**
   * Calculate retry delay function
   */
  calculateDelay?: (retryObject: RetryObject) => number;
  
  /**
   * Backoff factor for exponential backoff
   * @default 2
   */
  backoffLimit?: number;
  
  /**
   * Noise to add to delay calculation
   * @default 100
   */
  noise?: number;
}

interface RetryObject {
  attemptCount: number;
  retryOptions: RetryOptions;
  error: RequestError;
  computedValue: number;
  retryAfter?: number;
}

Usage Examples:

// Timeout configuration
const response = await got("https://slow-api.example.com", {
  timeout: {
    request: 30000, // 30 second overall timeout
    connect: 5000,  // 5 second connection timeout
    response: 10000 // 10 second response timeout
  }
});

// Retry configuration
const response = await got("https://unreliable-api.example.com", {
  retry: {
    limit: 5,
    methods: ["GET", "POST"],
    statusCodes: [408, 429, 500, 502, 503, 504],
    calculateDelay: ({ attemptCount }) => {
      return Math.min(1000 * Math.pow(2, attemptCount), 30000);
    }
  }
});

HTTP Behavior Options

Options controlling HTTP-specific behavior like redirects, compression, and caching.

interface HttpBehaviorOptions {
  /**
   * Follow HTTP redirects
   * @default true
   */
  followRedirect?: boolean;
  
  /**
   * Maximum number of redirects to follow
   * @default 10
   */
  maxRedirects?: number;
  
  /**
   * Decompress gzipped/deflated responses
   * @default true
   */
  decompress?: boolean;
  
  /**
   * Cache configuration
   */
  cache?: CacheOptions | boolean;
  
  /**
   * DNS cache instance
   */
  dnsCache?: CacheableLookup | boolean;
  
  /**
   * DNS lookup IP version preference
   */
  dnsLookupIpVersion?: DnsLookupIpVersion;
  
  /**
   * Cookie jar for automatic cookie handling
   */
  cookieJar?: ToughCookieJar | PromiseCookieJar;
  
  /**
   * Ignore invalid SSL certificates
   * @default false
   */
  rejectUnauthorized?: boolean;
}

interface CacheOptions {
  shared?: boolean;
  cacheHeuristic?: number;
  immutableMinTtl?: number;
  ignoreCargoCult?: boolean;
}

type DnsLookupIpVersion = 4 | 6 | undefined;

interface ToughCookieJar {
  getCookieString(url: string): Promise<string>;
  setCookie(rawCookie: string, url: string): Promise<unknown>;
}

interface PromiseCookieJar {
  getCookieString(url: string): Promise<string>;
  setCookie(rawCookie: string, url: string): Promise<unknown>;
}

Usage Examples:

// Redirect handling
const response = await got("https://example.com/redirect", {
  followRedirect: true,
  maxRedirects: 5
});

// Caching
const response = await got("https://api.example.com/data", {
  cache: {
    shared: false,
    cacheHeuristic: 0.1
  }
});

// Cookie jar
import { CookieJar } from "tough-cookie";
const cookieJar = new CookieJar();

const response = await got("https://example.com/login", {
  cookieJar,
  form: { username: "user", password: "pass" }
});

Advanced Options

Advanced configuration for agents, HTTPS, HTTP/2, and request lifecycle hooks.

interface AdvancedOptions {
  /**
   * HTTP/HTTPS agents for connection pooling
   */
  agents?: Agents;
  
  /**
   * HTTPS/TLS specific options
   */
  https?: HttpsOptions;
  
  /**
   * Enable HTTP/2 support
   * @default false
   */
  http2?: boolean;
  
  /**
   * Request/response lifecycle hooks
   */
  hooks?: Hooks;
  
  /**
   * Stream mode - return duplex stream instead of promise
   * @default false
   */
  isStream?: boolean;
  
  /**
   * Custom request function
   */
  request?: RequestFunction;
  
  /**
   * Context object passed to hooks
   */
  context?: Record<string, unknown>;
  
  /**
   * Request metadata for debugging
   */
  methodRewriting?: boolean;
  
  /**
   * Allow setting User-Agent header
   * @default true
   */
  setHost?: boolean;
}

interface Agents {
  http?: HttpAgent | false;
  https?: HttpsAgent | false;
  http2?: unknown | false;
}

interface HttpsOptions extends SecureContextOptions {
  rejectUnauthorized?: boolean;
  checkServerIdentity?: CheckServerIdentityFunction;
  certificateAuthority?: string | Buffer | Array<string | Buffer>;
  key?: string | Buffer | Array<Buffer | KeyObject>;
  certificate?: string | Buffer | Array<string | Buffer>;
  passphrase?: string;
  pfx?: string | Buffer | Array<string | Buffer | PxfObject>;
  servername?: string;
  minVersion?: SecureVersion;
  maxVersion?: SecureVersion;
}

type CheckServerIdentityFunction = (hostname: string, cert: DetailedPeerCertificate) => Error | undefined;

Usage Examples:

import https from "https";

// Custom HTTPS agent
const agent = new https.Agent({
  keepAlive: true,
  maxSockets: 15
});

const response = await got("https://api.example.com", {
  agents: {
    https: agent
  }
});

// HTTP/2 support
const response = await got("https://http2.example.com", {
  http2: true
});

// Custom HTTPS options
const response = await got("https://self-signed.example.com", {
  https: {
    rejectUnauthorized: false,
    checkServerIdentity: () => undefined
  }
});

Pagination Options

Configuration for paginated API responses.

interface PaginationOptions<ElementType = unknown, BodyType = unknown> {
  /**
   * Pagination mode
   */
  pagination?: {
    /**
     * Transform function to extract items from response
     */
    transform?: (response: Response<BodyType>) => Promise<ElementType[]> | ElementType[];
    
    /**
     * Filter function for items
     */
    filter?: (item: ElementType, allItems: ElementType[], currentItems: ElementType[]) => boolean;
    
    /**
     * Function to determine if there are more pages
     */
    shouldContinue?: (item: ElementType, allItems: ElementType[], currentItems: ElementType[]) => boolean;
    
    /**
     * Function to generate next page URL
     */
    paginate?: (response: Response<BodyType>, allItems: ElementType[], currentItems: ElementType[]) => OptionsInit | false;
    
    /**
     * Maximum number of items to return
     */
    countLimit?: number;
    
    /**
     * Maximum number of requests to make
     */
    requestLimit?: number;
    
    /**
     * Stack all items instead of yielding them one by one
     * @default false
     */
    stackAllItems?: boolean;
  };
}

Usage Example:

// GitHub API pagination
const commits = await got.paginate.all("https://api.github.com/repos/user/repo/commits", {
  pagination: {
    transform: (response: any) => response.body,
    paginate: (response) => {
      const linkHeader = response.headers.link;
      if (linkHeader?.includes('rel="next"')) {
        // Parse next URL from Link header
        const links = parseLinkHeader(linkHeader);
        const nextLink = links.find(link => link.parameters.rel === '"next"');
        if (nextLink) {
          return { url: nextLink.reference };
        }
      }
      return false;
    },
    countLimit: 100
  }
});