### Install hpagent via npm Source: https://github.com/delvedor/hpagent/blob/main/README.md Install the hpagent package using npm. This is the first step before using the library. ```bash npm install hpagent ``` -------------------------------- ### Use with node-fetch Source: https://github.com/delvedor/hpagent/blob/main/README.md Example of using HttpProxyAgent with node-fetch. The agent is passed in the fetch options. ```javascript fetch('http://localhost:9200', { agent: new HttpProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, scheduling: 'lifo', proxy: 'http://localhost:8080' }) }) ``` -------------------------------- ### Use with simple-get Source: https://github.com/delvedor/hpagent/blob/main/README.md Example of using HttpProxyAgent with simple-get. The agent is passed in the request options, and the callback handles the response. ```javascript sget.concat({ url: `http://${server.address().address}:${server.address().port}`, agent: new HttpProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, scheduling: 'lifo', proxy: `https://${proxy.address().address}:${proxy.address().port}` }) }, function (err, response, data) { // handle the response }) ``` -------------------------------- ### Use with got Source: https://github.com/delvedor/hpagent/blob/main/README.md Example of using HttpProxyAgent with the got library. The agent is passed in the request options under the agent property. ```javascript got('http://localhost:9200', { agent: { http: new HttpProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, scheduling: 'lifo', proxy: 'http://localhost:8080' }) } }) ``` -------------------------------- ### HttpsProxyAgent - Basic Usage Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/https-proxy-agent.md Creates an HttpsProxyAgent instance with proxy configuration and uses it to make an HTTPS GET request through the proxy. ```APIDOC ## HttpsProxyAgent - Basic Usage ### Description Creates an HttpsProxyAgent instance with proxy configuration and uses it to make an HTTPS GET request through the proxy. ### Constructor `new HttpsProxyAgent(options)` ### Parameters #### Options - **keepAlive** (boolean) - Optional - Whether to keep sockets alive. - **keepAliveMsecs** (number) - Optional - Initial delay for keep-alive sockets. - **maxSockets** (number) - Optional - Maximum number of sockets per host. - **maxFreeSockets** (number) - Optional - Maximum number of free sockets. - **scheduling** (string) - Optional - Scheduling strategy ('lifo' or 'fifo'). - **proxy** (string) - Required - The proxy URL (e.g., 'http://localhost:8080'). ### Usage Example ```js const https = require('https') const { HttpsProxyAgent } = require('hpagent') const agent = new HttpsProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, scheduling: 'lifo', proxy: 'http://localhost:8080' }) https.get('https://api.example.com/', { agent }, (response) => { console.log('status:', response.statusCode) }).on('error', (err) => { console.error('request failed:', err.message) }) ``` ``` -------------------------------- ### HttpProxyAgent with proxyConnectOptions Source: https://github.com/delvedor/hpagent/blob/main/README.md Pass custom options for the proxy CONNECT request using proxyConnectOptions, such as headers and tls.connect() options like ca. This example reads a custom certificate file. ```javascript const fs = require('fs') const http = require('http') const { HttpProxyAgent } = require('hpagent') const agent = new HttpProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, proxy: 'https://localhost:8080', proxyConnectOptions: { headers: { 'Proxy-Authorization': 'Basic YWxhZGRpbjpvcGVuc2VzYW1l', }, ca: [ fs.readFileSync('custom-proxy-cert.pem') ] } }) http.get('http://localhost:9200', { agent }) .on('response', console.log) .end() ``` -------------------------------- ### Use with needle Source: https://github.com/delvedor/hpagent/blob/main/README.md Example of using HttpProxyAgent with the needle library. The agent is passed as part of the request options. ```javascript needle('get', 'http://localhost:9200', { agent: new HttpProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, scheduling: 'lifo', proxy: 'http://localhost:8080' }) }) ``` -------------------------------- ### Basic HttpProxyAgent usage with plain-HTTP target Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/http-proxy-agent.md Creates an HttpProxyAgent with keep-alive and connection pool settings, then uses it to make a plain-HTTP GET request through the proxy. The response handler logs the status code. ```javascript const http = require('http') const { HttpProxyAgent } = require('hpagent') const agent = new HttpProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, scheduling: 'lifo', proxy: 'http://localhost:8080' }) http.get('http://localhost:9200', { agent }) .on('response', (response) => { console.log('status:', response.statusCode) }) .end() ``` -------------------------------- ### Basic usage with HTTPS target over HTTP proxy Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/https-proxy-agent.md Creates an HttpsProxyAgent with keep-alive and pooling options, then makes an HTTPS GET request through an HTTP proxy at localhost:8080. Logs the response status code or an error message. ```javascript const https = require('https') const { HttpsProxyAgent } = require('hpagent') const agent = new HttpsProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, scheduling: 'lifo', proxy: 'http://localhost:8080' }) https.get('https://api.example.com/', { agent }, (response) => { console.log('status:', response.statusCode) }).on('error', (err) => { console.error('request failed:', err.message) }) ``` -------------------------------- ### constructor Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/http-proxy-agent.md Documentation for the HttpProxyAgent constructor, including its signature, parameters, return value, and instance properties. ```APIDOC ## constructor ### Description Creates a new `HttpProxyAgent` instance, a subclass of `http.Agent` that routes requests through a specified HTTP proxy. ### Signature ```js constructor (options) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `options` | `HttpProxyAgentOptions` | yes | — | Agent options object | | `options.proxy` | `string \| URL` | yes | — | Proxy URL. A string is converted to a `URL` instance and stored on `this.proxy`. Basic auth credentials are read from the URL userinfo (`http://user:pwd@host:port`). | | `options.proxyRequestOptions` | `ProxyAgentRequestOptions` | no | `{}` | Extra options forwarded to the proxy `CONNECT` request (e.g. custom headers, TLS options for an HTTPS proxy). | | everything else | `http.AgentOptions` | no | core defaults | Destructured into `opts` and passed to `super(opts)`, i.e. `http.Agent`'s constructor. These control keep-alive behavior and the connection pool. | ### Returns A new `HttpProxyAgent` instance. It is a real `http.Agent` subclass, so it can be passed anywhere an `http.Agent` is expected (e.g. `http.request({ agent })`, `got`, `node-fetch`, `needle`, `simple-get`). ### Instance properties set by the constructor | Property | Type | Value | |----------|------|-------| | `this.proxy` | `URL` | The proxy URL (string input normalized to `URL`) | | `this.proxyRequestOptions` | `object` | The `proxyRequestOptions` value, or `{}` if not provided | | (inherited agent state) | `http.Agent` internals | keep-alive counters, free/busy socket lists from `super(opts)` | ``` -------------------------------- ### new HttpProxyAgent(options) Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/types.md Creates a new HttpProxyAgent instance with the provided options. The instance is structurally compatible with http.Agent and can be used in http.request options. ```APIDOC ## new HttpProxyAgent(options) ### Description Creates a new HttpProxyAgent instance. The instance is structurally compatible with http.Agent and can be used wherever an http.Agent is expected. ### Constructor `new HttpProxyAgent(options: HttpProxyAgentOptions)` ### Parameters #### options (HttpProxyAgentOptions) - Required Options for the proxy agent. See the HttpProxyAgentOptions type for details. ### Returns - **HttpProxyAgent** - An instance of the HttpProxyAgent class. ### Example ```ts import { HttpProxyAgent } from 'hpagent' const agent = new HttpProxyAgent({ // options }) ``` ``` -------------------------------- ### HttpProxyAgent with proxy authentication Source: https://github.com/delvedor/hpagent/blob/main/README.md Configure basic authentication by including credentials in the proxy URL. Also shows how to pass custom proxyConnectOptions such as headers and TLS options. ```javascript const http = require('http') const { HttpProxyAgent } = require('hpagent') const agent = new HttpProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, proxy: 'http://user:pwd@localhost:8080' }) http.get('http://localhost:9200', { agent }) .on('response', console.log) .end() ``` -------------------------------- ### package.json entry points Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/index.md Declares the main, types, and exports fields for the package, mapping CommonJS, ESM, and TypeScript entry points. ```json "main": "index.js", "types": "index.d.ts", "exports": { ".": { "require": "./index.js", "import": "./index.mjs", "types": "./index.d.ts" }, "./*": "./*.js" } ``` -------------------------------- ### new HttpsProxyAgent(options) Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/types.md Creates a new HttpsProxyAgent instance with the provided options. The instance is structurally compatible with https.Agent and can be used in https.request options. ```APIDOC ## new HttpsProxyAgent(options) ### Description Creates a new HttpsProxyAgent instance. The instance is structurally compatible with https.Agent and can be used wherever an https.Agent is expected. ### Constructor `new HttpsProxyAgent(options: HttpsProxyAgentOptions)` ### Parameters #### options (HttpsProxyAgentOptions) - Required Options for the proxy agent. See the HttpsProxyAgentOptions type for details. ### Returns - **HttpsProxyAgent** - An instance of the HttpsProxyAgent class. ### Example ```ts import { HttpsProxyAgent } from 'hpagent' const agent = new HttpsProxyAgent({ // options }) ``` ``` -------------------------------- ### Basic HttpProxyAgent usage Source: https://github.com/delvedor/hpagent/blob/main/README.md Create an HttpProxyAgent instance with keep-alive options and a proxy URL, then use it with http.get(). The agent accepts the same parameters as Node.js core http(s) agents plus a proxy option. ```javascript const http = require('http') const { HttpProxyAgent } = require('hpagent') const agent = new HttpProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, proxy: 'http://localhost:8080' }) http.get('http://localhost:9200', { agent }) .on('response', console.log) .end() ``` -------------------------------- ### HttpsProxyAgent class implementation (JavaScript) Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/https-proxy-agent.md Defines the HttpsProxyAgent class extending https.Agent. The constructor extracts proxy and proxyRequestOptions, and createConnection performs a CONNECT request through the proxy, handling proxy authentication and HTTPS proxy servername. On a 200 response it creates the secure socket via super.createConnection; otherwise it destroys the socket and calls back with an error. Timeout and error events are handled. ```javascript class HttpsProxyAgent extends https.Agent { constructor (options) { const { proxy, proxyRequestOptions, ...opts } = options super(opts) this.proxy = typeof proxy === 'string' ? new URL(proxy) : proxy this.proxyRequestOptions = proxyRequestOptions || {} } createConnection (options, callback) { const requestOptions = { ...this.proxyRequestOptions, method: 'CONNECT', host: this.proxy.hostname, port: this.proxy.port, path: `${options.host}:${options.port}`, setHost: false, headers: { ...this.proxyRequestOptions.headers, connection: this.keepAlive ? 'keep-alive' : 'close', host: `${options.host}:${options.port}` }, agent: false, timeout: options.timeout || 0 } if (this.proxy.username || this.proxy.password) { const base64 = Buffer.from(`${decodeURIComponent(this.proxy.username || '')}:${decodeURIComponent(this.proxy.password || '')}`).toString('base64') requestOptions.headers['proxy-authorization'] = `Basic ${base64}` } // Necessary for the TLS check with the proxy to succeed. if (this.proxy.protocol === 'https:') { requestOptions.servername = this.proxy.hostname } const request = (this.proxy.protocol === 'http:' ? http : https).request(requestOptions) request.once('connect', (response, socket, head) => { request.removeAllListeners() socket.removeAllListeners() if (response.statusCode === 200) { const secureSocket = super.createConnection({ ...options, socket }) callback(null, secureSocket) } else { socket.destroy() callback(new Error(`Bad response: ${response.statusCode}`), null) } }) request.once('timeout', () => { request.destroy(new Error('Proxy timeout')) }) request.once('error', err => { request.removeAllListeners() callback(err, null) }) request.end() } } ``` -------------------------------- ### HttpProxyAgent class implementation Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/http-proxy-agent.md Full implementation of the HttpProxyAgent class. It extends http.Agent and overrides createConnection to establish a CONNECT tunnel through the configured proxy. Handles proxy authentication via Basic auth, HTTPS proxies by setting servername, and emits errors on non-200 responses or timeouts. ```javascript class HttpProxyAgent extends http.Agent { constructor (options) { const { proxy, proxyRequestOptions, ...opts } = options super(opts) this.proxy = typeof proxy === 'string' ? new URL(proxy) : proxy this.proxyRequestOptions = proxyRequestOptions || {} } createConnection (options, callback) { const requestOptions = { ...this.proxyRequestOptions, method: 'CONNECT', host: this.proxy.hostname, port: this.proxy.port, path: `${options.host}:${options.port}`, setHost: false, headers: { ...this.proxyRequestOptions.headers, connection: this.keepAlive ? 'keep-alive' : 'close', host: `${options.host}:${options.port}` }, agent: false, timeout: options.timeout || 0 } if (this.proxy.username || this.proxy.password) { const base64 = Buffer.from(`${decodeURIComponent(this.proxy.username || '')}:${decodeURIComponent(this.proxy.password || '')}`).toString('base64') requestOptions.headers['proxy-authorization'] = `Basic ${base64}` } if (this.proxy.protocol === 'https:') { requestOptions.servername = this.proxy.hostname } const request = (this.proxy.protocol === 'http:' ? http : https).request(requestOptions) request.once('connect', (response, socket, head) => { request.removeAllListeners() socket.removeAllListeners() if (response.statusCode === 200) { callback(null, socket) } else { socket.destroy() callback(new Error(`Bad response: ${response.statusCode}`), null) } }) request.once('timeout', () => { request.destroy(new Error('Proxy timeout')) }) request.once('error', err => { request.removeAllListeners() callback(err, null) }) request.end() } } ``` -------------------------------- ### HttpsProxyAgent constructor Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/types.md Creates a new HTTPS proxy agent instance. The constructor accepts an options object with a required proxy URL and optional proxy request options. ```APIDOC ## HttpsProxyAgent constructor ### Description Creates a new HTTPS proxy agent instance. The constructor accepts an options object with a required proxy URL and optional proxy request options. ### Method constructor ### Endpoint new HttpsProxyAgent(options: HttpsProxyAgentOptions) ### Parameters #### Constructor Options - **options** (HttpsProxyAgentOptions) - Required - Options for the agent. - **proxy** (string | URL) - Required - URL of the forward proxy. Strings are normalized to a URL instance. Basic auth credentials are read from the URL userinfo. - **proxyRequestOptions** (ProxyAgentRequestOptions) - Optional - Extra options applied to the proxy CONNECT request. - **keepAlive** (boolean) - Optional - Inherited from https.AgentOptions. - **keepAliveMsecs** (number) - Optional - Inherited from https.AgentOptions. - **maxSockets** (number) - Optional - Inherited from https.AgentOptions. - **maxTotalSockets** (number) - Optional - Inherited from https.AgentOptions. - **maxFreeSockets** (number) - Optional - Inherited from https.AgentOptions. - **scheduling** (string) - Optional - Inherited from https.AgentOptions. - **timeout** (number) - Optional - Inherited from https.AgentOptions. - **noDelay** (boolean) - Optional - Inherited from https.AgentOptions. ### Response Returns an instance of HttpsProxyAgent. ### Response Example ```ts const agent = new HttpsProxyAgent({ proxy: 'https://proxy.example.com:8443' }) ``` ``` -------------------------------- ### HttpsProxyAgentOptions Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/types.md Options for the HttpsProxyAgent constructor, extending https.AgentOptions with proxy-specific fields. ```APIDOC ## HttpsProxyAgentOptions ### Description Configuration options for the HttpsProxyAgent, extending Node.js https.AgentOptions with proxy connection settings. ### Fields - **proxy** (string | URL) - Required - URL of the forward proxy. - **proxyRequestOptions** (ProxyAgentRequestOptions) - Optional - Extra options for the proxy CONNECT request. - **Inherited from https.AgentOptions** - Optional - All Node.js https.Agent options, including TLS options for the target connection: ca, cert, key, pfx, passphrase, rejectUnauthorized, servername, and shared agent options. ### Semantics Top-level TLS options apply to the TLS handshake with the target server. The same keys nested inside proxyRequestOptions apply to the TLS handshake with the proxy. ### Accepted By HttpsProxyAgent constructor. ``` -------------------------------- ### ProxyAgentRequestOptions Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/types.md Options for the proxy CONNECT request. ```APIDOC ## ProxyAgentRequestOptions ### Description Options for the proxy CONNECT request. ### Fields - **ca** (string[]) - Optional - Array of CA certificates. - **headers** (Object) - Optional - Additional headers for the CONNECT request. - **rejectUnauthorized** (boolean) - Optional - Whether to reject unauthorized certificates. ### Example ```ts const options: ProxyAgentRequestOptions = { ca: ['-----BEGIN CERTIFICATE-----...'], headers: { 'X-Custom': 'value' }, rejectUnauthorized: false } ``` ``` -------------------------------- ### HttpsProxyAgent - HTTPS Proxy with TLS Options and Error Handling Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/https-proxy-agent.md Creates an HttpsProxyAgent with separate TLS options for the proxy and target connections, and demonstrates error handling on the request. ```APIDOC ## HttpsProxyAgent - HTTPS Proxy with TLS Options and Error Handling ### Description Creates an HttpsProxyAgent with separate TLS options for the proxy and target connections, and demonstrates error handling on the request. ### Constructor `new HttpsProxyAgent(options)` ### Parameters #### Options - **keepAlive** (boolean) - Optional - Whether to keep sockets alive. - **proxy** (string) - Required - The proxy URL (e.g., 'https://proxy.example.com:443'). - **proxyRequestOptions** (object) - Optional - TLS options applied to the handshake with the proxy only. Note: The README documents this as `proxyConnectOptions`, but the source and type declarations use `proxyRequestOptions`. - **ca** (array) - Optional - TLS CA certificates applied to the handshake with the target only. - **rejectUnauthorized** (boolean) - Optional - Whether to reject unauthorized certificates (e.g., set to false for self-signed certs). ### Usage Example ```js const fs = require('fs') const https = require('https') const { HttpsProxyAgent } = require('hpagent') const agent = new HttpsProxyAgent({ keepAlive: true, proxy: 'https://proxy.example.com:443', proxyRequestOptions: { // Applied to the TLS handshake with the PROXY only ca: [fs.readFileSync('custom-proxy-cert.pem')] }, // Applied to the TLS handshake with the TARGET only ca: [fs.readFileSync('custom-server-cert.pem')], rejectUnauthorized: false // e.g. for internal servers with self-signed certs }) const req = https.request('https://server.example.com/', { agent }, (response) => { let body = '' response.setEncoding('utf8') response.on('data', chunk => { body += chunk }) response.on('end', () => console.log('body:', body)) }) req.on('error', (err) => { // 'Proxy timeout', 'Bad response: ', ECONNREFUSED, // UNABLE_TO_VERIFY_LEAF_SIGNATURE, ECONNRESET, ... console.error('request failed:', err.message) }) req.end() ``` ### Error Handling Possible error messages include: 'Proxy timeout', 'Bad response: ', ECONNREFUSED, UNABLE_TO_VERIFY_LEAF_SIGNATURE, ECONNRESET, etc. ``` -------------------------------- ### HttpProxyAgentOptions interface Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/types.md Options interface for the HttpProxyAgent constructor. Extends http.AgentOptions and adds a required proxy URL and optional proxyRequestOptions. The proxy string is normalized to a URL instance, and basic auth credentials are read from the URL userinfo and decoded before base64-encoding. ```ts interface HttpProxyAgentOptions extends http.AgentOptions { proxy: string | URL, proxyRequestOptions?: ProxyAgentRequestOptions } ``` -------------------------------- ### HttpProxyAgent class Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/index.md Documentation for the HttpProxyAgent class, which creates an HTTP agent that tunnels traffic through a forward proxy. ```APIDOC ## [CLASS] HttpProxyAgent ### Description Creates an HTTP agent that tunnels traffic through a forward proxy using the HTTP CONNECT method. It extends Node.js core's `http.Agent` and keeps connections alive for tunneled connections. ### Constructor `new HttpProxyAgent(options)` ### Parameters #### Constructor Options - **proxy** (object) - Required - Proxy configuration object containing `host` and `port` properties. - **proxy.host** (string) - Required - Hostname of the forward proxy. - **proxy.port** (number) - Required - Port of the forward proxy. - **Other options** (object) - Optional - Additional options passed to the underlying `http.Agent` constructor. ### Methods #### createConnection(options, callback) - **options** (object) - Required - Connection options passed by Node's agent machinery. - **callback** (function) - Required - Callback function invoked with the tunneled socket on success or an error on failure. ### Usage Example ```js const { HttpProxyAgent } = require('hpagent') const agent = new HttpProxyAgent({ proxy: { host: 'proxy.example.com', port: 3128 } }) ``` ### Notes - Issues a `CONNECT` request to the proxy. - On HTTP `200`, the tunneled socket is passed to the callback. - On any other status code, the socket is destroyed and an error is produced. - Compatible with HTTP and HTTPS proxies when the target server is HTTP. ``` -------------------------------- ### Require hpagent classes Source: https://github.com/delvedor/hpagent/blob/main/README.md Import the HttpProxyAgent and HttpsProxyAgent classes from the hpagent module. This is the standard way to access the agent classes. ```javascript const { HttpProxyAgent, HttpsProxyAgent } = require('hpagent') ``` -------------------------------- ### ProxyAgentRequestOptions Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/types.md Options for the proxy CONNECT request, including TLS validation and custom headers. ```APIDOC ## ProxyAgentRequestOptions ### Description Options for the proxy CONNECT request, used by both HttpProxyAgent and HttpsProxyAgent constructors. ### Fields - **ca** (string[]) - Optional - CA certificates for validating the proxy server certificate (HTTPS proxy only). - **headers** (Object) - Optional - Extra headers for the CONNECT request. Internal connection and host headers are set afterwards and always win. A proxy-authorization header from proxy URL credentials, if present, also wins. - **rejectUnauthorized** (boolean) - Optional - Whether to verify the proxy server certificate (HTTPS proxy only). ### Implementation Note The entire proxyRequestOptions object is spread into http.request/https.request options for the CONNECT. Any option those APIs accept can be passed. Keys method, host, port, path, setHost, agent, headers, timeout are overwritten by internal defaults. servername is overwritten when proxy protocol is https:. ### Accepted By HttpProxyAgent / HttpsProxyAgent constructors (via proxyRequestOptions). ``` -------------------------------- ### HTTPS proxy with proxyRequestOptions and error handling Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/http-proxy-agent.md Uses an HTTPS proxy with per-proxy TLS options (custom CA) and a Proxy-Authorization header via proxyRequestOptions. Includes error handling for proxy failures such as 'Proxy timeout', 'Bad response: ', ECONNREFUSED, and TLS errors. Note: the README calls this option proxyConnectOptions, but the source and types use proxyRequestOptions. ```javascript const fs = require('fs') const http = require('http') const { HttpProxyAgent } = require('hpagent') const agent = new HttpProxyAgent({ keepAlive: true, proxy: 'https://user:pwd@proxy.example.com:443', proxyRequestOptions: { // Only applied to the CONNECT request against the proxy (see http-proxy-agent docs) headers: { 'Proxy-Authorization': 'Basic YWxhZGRpbjpvcGVuc2VzYW1l' }, ca: [fs.readFileSync('custom-proxy-cert.pem')] } }) const req = http.get('http://localhost:9200', { agent }, (response) => { let body = '' response.setEncoding('utf8') response.on('data', chunk => { body += chunk }) response.on('end', () => console.log('body:', body)) }) req.on('error', (err) => { // 'Proxy timeout', 'Bad response: ', ECONNREFUSED, TLS errors, ... console.error('request failed:', err.message) }) ``` -------------------------------- ### Full TypeScript declaration file (index.d.ts) Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/types.md Full TypeScript declaration file for the hpagent package. It declares the HttpProxyAgent and HttpsProxyAgent classes, their options interfaces, and the ProxyAgentRequestOptions interface, and exports them all. Use this as the authoritative type definitions for the package. ```ts import * as http from 'http' import * as https from 'https' import { URL } from 'url' declare class HttpProxyAgent extends http.Agent { constructor(options: HttpProxyAgentOptions) } interface HttpProxyAgentOptions extends http.AgentOptions { proxy: string | URL, proxyRequestOptions?: ProxyAgentRequestOptions } declare class HttpsProxyAgent extends https.Agent { constructor(options: HttpsProxyAgentOptions) } interface HttpsProxyAgentOptions extends https.AgentOptions { proxy: string | URL, proxyRequestOptions?: ProxyAgentRequestOptions } interface ProxyAgentRequestOptions { ca?: string[], headers?: Object, rejectUnauthorized?: boolean } export { HttpProxyAgent, HttpProxyAgentOptions, HttpsProxyAgent, HttpsProxyAgentOptions, ProxyAgentRequestOptions, } ``` -------------------------------- ### Callback with core http/https Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/errors.md Shows how to catch hpagent errors when using the core 'http' module with a callback. The 'error' event on the request object fires with messages like 'Proxy timeout' or 'Bad response: '. Use this pattern when working with the standard 'http' or 'https' modules. ```javascript const http = require('http') const { HttpProxyAgent } = require('hpagent') const agent = new HttpProxyAgent({ proxy: 'http://localhost:8080' }) const req = http.request('http://www.example.com/', { agent }, (res) => { console.log('ok:', res.statusCode) }) req.on('error', (err) => { switch (err.message) { case 'Proxy timeout': // the CONNECT handshake timed out break case 'Bad response: 403': case 'Bad response: 407': // proxy refused the CONNECT (403 forbidden / 407 auth required) break default: // original transport error (ECONNREFUSED, ENOTFOUND, TLS errors, ...) break } }) req.end() ``` -------------------------------- ### Async/await with node-fetch Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/errors.md Shows how to catch hpagent errors when using 'node-fetch' with async/await. The promise rejects with an error whose message is one of 'Proxy timeout', 'Bad response: ', or the original transport error. Use this pattern when working with promise-based HTTP clients. ```javascript const fetch = require('node-fetch') const { HttpProxyAgent } = require('hpagent') const agent = new HttpProxyAgent({ proxy: 'http://localhost:8080' }) try { const res = await fetch('http://www.example.com/', { agent }) console.log('status:', res.status) } catch (err) { console.error(err.message) // 'Proxy timeout', 'Bad response: ', ... } ``` -------------------------------- ### ProxyAgentRequestOptions interface Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/types.md Options for the proxy CONNECT request, accepted by both HttpProxyAgent and HttpsProxyAgent constructors via proxyRequestOptions. The declaration is conservative; at runtime the whole object is spread into http.request/https.request options, with internal defaults overwriting certain keys. The headers field merges extra headers, but internal connection and host headers always win. ```ts interface ProxyAgentRequestOptions { ca?: string[], headers?: Object, rejectUnauthorized?: boolean } ``` -------------------------------- ### hpagent module Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/index.md Module-level documentation for the hpagent package, including exports, import paths, and compatibility information. ```APIDOC ## [MODULE] hpagent ### Description Zero-dependency Node.js package providing ready-to-use HTTP and HTTPS agents for working with proxies, keeping connections alive (connection pooling for tunneled connections). ### Exports - **HttpProxyAgent** (class) - HTTP agent that tunnels through a forward proxy. - **HttpsProxyAgent** (class) - HTTPS agent that tunnels through a forward proxy. - **HttpProxyAgentOptions** (TypeScript interface) - Options for `HttpProxyAgent`. - **HttpsProxyAgentOptions** (TypeScript interface) - Options for `HttpsProxyAgent`. - **ProxyAgentRequestOptions** (TypeScript interface) - Request options for proxy agents. ### Import Paths #### CommonJS ```js const { HttpProxyAgent, HttpsProxyAgent } = require('hpagent') ``` #### ESM ```js import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent' ``` #### TypeScript ```ts import { HttpProxyAgent, HttpsProxyAgent, HttpProxyAgentOptions, HttpsProxyAgentOptions, ProxyAgentRequestOptions } from 'hpagent' ``` ### Compatibility Matrix | Agent class | Proxy protocol | Server protocol | |-------------|----------------|-----------------| | `HttpProxyAgent` | HTTP | HTTP | | `HttpProxyAgent` | HTTPS | HTTP | | `HttpsProxyAgent` | HTTP | HTTPS | | `HttpsProxyAgent` | HTTPS | HTTPS | ### Tested Integrations - **got** — `agent: { http: new HttpProxyAgent({ ... }) }` - **needle** — `agent: new HttpProxyAgent({ ... })` - **node-fetch** — `agent: new HttpProxyAgent({ ... })` - **simple-get** — `agent: new HttpProxyAgent({ ... })` ``` -------------------------------- ### HttpsProxyAgent class Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/index.md Documentation for the HttpsProxyAgent class, which creates an HTTPS agent that tunnels traffic through a forward proxy. ```APIDOC ## [CLASS] HttpsProxyAgent ### Description Creates an HTTPS agent that tunnels traffic through a forward proxy using the HTTP CONNECT method. It extends Node.js core's `https.Agent` and keeps connections alive for tunneled connections. ### Constructor `new HttpsProxyAgent(options)` ### Parameters #### Constructor Options - **proxy** (object) - Required - Proxy configuration object containing `host` and `port` properties. - **proxy.host** (string) - Required - Hostname of the forward proxy. - **proxy.port** (number) - Required - Port of the forward proxy. - **Other options** (object) - Optional - Additional options passed to the underlying `https.Agent` constructor. ### Methods #### createConnection(options, callback) - **options** (object) - Required - Connection options passed by Node's agent machinery. - **callback** (function) - Required - Callback function invoked with the tunneled socket on success or an error on failure. ### Usage Example ```js const { HttpsProxyAgent } = require('hpagent') const agent = new HttpsProxyAgent({ proxy: { host: 'proxy.example.com', port: 3128 } }) ``` ### Notes - Issues a `CONNECT` request to the proxy. - On HTTP `200`, the tunneled socket is wrapped in TLS to the target via `super.createConnection({ ...options, socket })`. - On any other status code, the socket is destroyed and an error is produced. - Compatible with HTTP and HTTPS proxies when the target server is HTTPS. ``` -------------------------------- ### index.mjs ESM re-exports Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/index.md ESM entry point that re-exports the agent classes as named exports and a default export of the whole module. ```js import mod from './index.js' export default mod export const HttpProxyAgent = mod.HttpProxyAgent export const HttpsProxyAgent = mod.HttpsProxyAgent ``` -------------------------------- ### HttpsProxyAgentOptions interface Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/types.md Options for the HttpsProxyAgent constructor. Extends Node.js https.AgentOptions, adding a required proxy URL and optional proxyRequestOptions for the CONNECT request. Top-level TLS options apply to the target server, while the same keys inside proxyRequestOptions apply to the proxy. ```ts interface HttpsProxyAgentOptions extends https.AgentOptions { proxy: string | URL, proxyRequestOptions?: ProxyAgentRequestOptions } ``` -------------------------------- ### HttpsProxyAgent with proxyRequestOptions TLS config Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/configuration.md Creates an HTTPS proxy agent with proxy-side TLS settings via proxyRequestOptions and target-side CA. Use when the proxy requires custom headers, CA, or certificate verification. ```javascript const fs = require('fs') const { HttpsProxyAgent } = require('hpagent') const agent = new HttpsProxyAgent({ keepAlive: true, proxy: 'https://proxy.example.com:443', proxyRequestOptions: { headers: { 'Proxy-Authorization': 'Basic YWxhZGRpbjpvcGVuc2VzYW1l' }, ca: [fs.readFileSync('proxy-ca.pem')], rejectUnauthorized: true }, ca: [fs.readFileSync('server-ca.pem')] // target-side TLS }) ``` -------------------------------- ### HTTPS proxy with proxy-side and target-side TLS options, plus error handling Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/https-proxy-agent.md Configures an HttpsProxyAgent to use an HTTPS proxy with separate TLS options for the proxy and target connections. Includes error handling for common failures like proxy timeout, bad response, ECONNREFUSED, and certificate errors. Note: the correct option name is proxyRequestOptions, not proxyConnectOptions. ```javascript const fs = require('fs') const https = require('https') const { HttpsProxyAgent } = require('hpagent') const agent = new HttpsProxyAgent({ keepAlive: true, proxy: 'https://proxy.example.com:443', proxyRequestOptions: { // Applied to the TLS handshake with the PROXY only ca: [fs.readFileSync('custom-proxy-cert.pem')] }, // Applied to the TLS handshake with the TARGET only ca: [fs.readFileSync('custom-server-cert.pem')], rejectUnauthorized: false // e.g. for internal servers with self-signed certs }) const req = https.request('https://server.example.com/', { agent }, (response) => { let body = '' response.setEncoding('utf8') response.on('data', chunk => { body += chunk }) response.on('end', () => console.log('body:', body)) }) req.on('error', (err) => { // 'Proxy timeout', 'Bad response: ', ECONNREFUSED, // UNABLE_TO_VERIFY_LEAF_SIGNATURE, ECONNRESET, ... console.error('request failed:', err.message) }) req.end() ``` -------------------------------- ### createConnection signature Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/https-proxy-agent.md The method signature for createConnection, which takes an options object and a Node-style callback. It is not meant to be called directly by consumer code. ```javascript createConnection (options, callback) ``` -------------------------------- ### index.js export statement Source: https://github.com/delvedor/hpagent/blob/main/_autodocs/api-reference/index.md CommonJS export of the two agent classes from the main implementation file. ```js module.exports = { HttpProxyAgent, HttpsProxyAgent } ```