@push.rocks/smartrequest
v6.5.1
Published
A module for modern HTTP/HTTPS requests with support for form data, file uploads, JSON, binary data, streams, and more.
Downloads
17,336
Maintainers
Readme
@push.rocks/smartrequest
A modern, cross-platform HTTP/HTTPS request library for Node.js, Bun and browsers with a unified API, supporting form data, file uploads, JSON, binary data, streams, and unix sockets.
Install
# Using npm
npm install @push.rocks/smartrequest --save
# Using pnpm
pnpm add @push.rocks/smartrequest
# Using yarn
yarn add @push.rocks/smartrequestKey Features
- 🚀 Modern Fetch-like API - Familiar response methods (
.json(),.text(),.arrayBuffer(),.stream()) - 🌐 Cross-Platform - Works in Node.js, Bun and browsers with a unified API
- 🔌 Unix Socket Support - Connect to local services like Docker (Node.js and Bun)
- 📦 Form Data & File Uploads - Built-in support for multipart/form-data
- 🔁 Pagination Support - Multiple strategies (offset, cursor, Link headers)
- ⚡ Keep-Alive Connections - Efficient connection pooling in Node.js
- 🛡️ TypeScript First - Full type safety and IntelliSense support
- 🎯 Zero Magic Defaults - Explicit configuration following fetch API principles
- 📡 Streaming Support - Stream buffers, files, and custom data without loading into memory
- 🔧 Highly Configurable - Timeouts, retries, headers, rate limiting, and more
- 🔒 Public-Only Requests - Fetch URLs from untrusted input without reaching your own network, and check plain socket targets (IMAP, SMTP) the same way
- 🧭 Fetch-Compatible Client -
SmartFetchreturns nativeResponseobjects, with retries and backoff, URL failover, timeouts, interceptors and deduplication (@push.rocks/smartrequest/fetch) - 💾 HTTP Cache - Opt-in persistent caching that honours
Cache-ControlandETag(@push.rocks/smartrequest/cache, IndexedDB) - 🔑 HTTP Digest Authentication - RFC 7616 (MD5, SHA-256, SHA-512-256,
-sess, userhash) with challenge reuse, for cameras, printers and other devices (Node.js and Bun) - 📌 Certificate Pinning - Trust exactly one self-signed device certificate by its SHA-256 fingerprint, also for IP addresses, with a probe for trust on first use (Node.js and Bun)
- 📻 Server-Sent Events - An async iterator over an event stream, with optional reconnection and
Last-Event-ID(Node.js, Bun and browsers)
Architecture
SmartRequest features a multi-layer architecture that provides consistent behavior across platforms:
- Core Base - Abstract classes and unified types shared across implementations
- Core Node - Node.js implementation using native http/https modules with unix socket support
- Core Bun - Bun implementation using native fetch with unix socket support via
unixoption - Core Fetch - Browser implementation using the Fetch API
- Core - Dynamic runtime detection and implementation selection using @push.rocks/smartenv
- Client - High-level fluent API for everyday use
- Fetch - Fetch-compatible
SmartFetchclient onglobalThis.fetch(subpath/fetch) - Cache - IndexedDB-backed
HttpCacheforSmartFetch(subpath/cache)
The library automatically detects the runtime environment (Node.js, Bun or browser) and loads the appropriate implementation, ensuring optimal performance and native feature support for each platform. Deno is unsupported and untested.
The implementations are loaded through literal import() specifiers, so a Node.js bundle and the main module of a Node.js single executable application (SEA) carry the Node.js implementation and the public-only engine. The browser field of package.json maps both Node.js modules (core_node/index.js and core_node/publiconly.js, under dist_ts/ and, for bundles built from the TypeScript sources, ts/) to false, so browser bundlers that honour it (esbuild with its browser defaults, @git.zone/tsbundle) leave them out.
Usage
@push.rocks/smartrequest provides a clean, type-safe API inspired by the native fetch API but with additional features needed for modern applications.
Basic Usage
import { SmartRequest } from '@push.rocks/smartrequest';
// Simple GET request
async function fetchUserData(userId: number) {
const response = await SmartRequest.create()
.url(`https://jsonplaceholder.typicode.com/users/${userId}`)
.get();
// Use the fetch-like response API
const userData = await response.json();
console.log(userData); // The parsed JSON response
}
// POST request with JSON body
async function createPost(title: string, body: string, userId: number) {
const response = await SmartRequest.create()
.url('https://jsonplaceholder.typicode.com/posts')
.json({ title, body, userId })
.post();
const createdPost = await response.json();
console.log(createdPost); // The created post
}Direct Core API Usage
For advanced use cases, you can use the Core API directly:
import { CoreRequest } from '@push.rocks/smartrequest';
async function directCoreRequest() {
const request = new CoreRequest('https://api.example.com/data', {
method: 'GET',
headers: {
Accept: 'application/json',
},
});
const response = await request.fire();
const data = await response.json();
return data;
}Setting Headers and Query Parameters
import { SmartRequest } from '@push.rocks/smartrequest';
async function searchRepositories(query: string, perPage: number = 10) {
const response = await SmartRequest.create()
.url('https://api.github.com/search/repositories')
.header('Accept', 'application/vnd.github.v3+json')
.query({
q: query,
per_page: perPage.toString(),
})
.get();
const data = await response.json();
return data.items;
}Handling Timeouts and Retries
import { SmartRequest } from '@push.rocks/smartrequest';
async function fetchWithRetry(url: string) {
const response = await SmartRequest.create()
.url(url)
.timeout(5000) // 5 seconds timeout
.retry(3) // Retry up to 3 times on failure
.get();
return await response.json();
}Setting Request Options
Use the options() method to set any request options supported by the underlying implementation:
import { SmartRequest } from '@push.rocks/smartrequest';
// Set various options
const response = await SmartRequest.create()
.url('https://api.example.com/data')
.options({
keepAlive: true, // Enable connection reuse (Node.js)
timeout: 10000, // 10 second timeout
hardDataCuttingTimeout: 15000, // 15 second hard timeout
// Platform-specific options are also supported
})
.get();Working with Different Response Types
The API provides a fetch-like interface for handling different response types:
import { SmartRequest } from '@push.rocks/smartrequest';
// JSON response (default)
async function fetchJson(url: string) {
const response = await SmartRequest.create().url(url).get();
return await response.json(); // Parses JSON automatically
}
// Text response
async function fetchText(url: string) {
const response = await SmartRequest.create().url(url).get();
return await response.text(); // Returns response as string
}
// Binary data
async function downloadImage(url: string) {
const response = await SmartRequest.create()
.url(url)
.accept('binary') // Optional: hints to server we want binary
.get();
const buffer = await response.arrayBuffer();
return Buffer.from(buffer); // Convert ArrayBuffer to Buffer if needed
}
// Streaming response (Web Streams API - cross-platform)
async function streamLargeFile(url: string) {
const response = await SmartRequest.create().url(url).get();
// Get a web-style ReadableStream (works everywhere)
const stream = response.stream();
if (stream) {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(`Received ${value.length} bytes of data`);
}
} finally {
reader.releaseLock();
}
}
}
// Convert to Node.js stream if needed (Node.js only)
async function streamWithNodeApi(url: string) {
const response = await SmartRequest.create().url(url).get();
// Convert web stream to Node.js stream
import { Readable } from 'stream';
const webStream = response.stream();
const nodeStream = Readable.fromWeb(webStream);
nodeStream.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data`);
});
return new Promise((resolve, reject) => {
nodeStream.on('end', resolve);
nodeStream.on('error', reject);
});
}Response Object Methods
The response object provides these methods:
json<T>(): Promise<T>- Parse response as JSONtext(): Promise<string>- Get response as textarrayBuffer(): Promise<ArrayBuffer>- Get response as ArrayBufferstream(): ReadableStream<Uint8Array> | null- Get web-style ReadableStream (cross-platform)raw(): Response | http.IncomingMessage- Get the underlying platform response object; its body is the body of the response, so read it through one of the two only
Each body method can only be called once per response, similar to the fetch API.
Important: Always Consume Response Bodies
You should always consume response bodies, even if you don't need the data. Unconsumed response bodies can cause:
- Memory leaks as data accumulates in buffers
- Socket hanging with keep-alive connections
- Connection pool exhaustion
// ❌ BAD - Response body is not consumed
const response = await SmartRequest.create()
.url('https://api.example.com/status')
.get();
if (response.ok) {
console.log('Success!');
}
// Socket may hang here!
// ✅ GOOD - Response body is consumed
const response = await SmartRequest.create()
.url('https://api.example.com/status')
.get();
if (response.ok) {
console.log('Success!');
}
await response.text(); // Consume the body even if not neededIn Node.js, SmartRequest automatically drains unconsumed responses to prevent socket hanging, but it's still best practice to explicitly consume response bodies.
You can disable auto-drain if needed:
// Disable auto-drain (not recommended unless you have specific requirements)
const response = await SmartRequest.create()
.url('https://api.example.com/data')
.autoDrain(false) // Disable auto-drain
.get();
// Now you MUST consume the body or the socket will hang
await response.text();Advanced Features
Form Data with File Uploads
import { SmartRequest } from '@push.rocks/smartrequest';
import * as fs from 'fs';
async function uploadMultipleFiles(
files: Array<{ name: string; path: string }>,
) {
const formFields = files.map((file) => ({
name: 'files',
value: fs.readFileSync(file.path),
filename: file.name,
contentType: 'application/octet-stream',
}));
const response = await SmartRequest.create()
.url('https://api.example.com/upload')
.formData(formFields)
.post();
return await response.json();
}Streaming Request Bodies
SmartRequest provides multiple ways to stream data in requests, making it easy to upload large files or send real-time data without loading everything into memory:
import { SmartRequest } from '@push.rocks/smartrequest';
import * as fs from 'fs';
import { Readable } from 'stream';
// Stream a Buffer directly (works everywhere)
async function uploadBuffer() {
const buffer = Buffer.from('Hello, World!');
const response = await SmartRequest.create()
.url('https://api.example.com/upload')
.buffer(buffer, 'text/plain')
.post();
return await response.json();
}
// Stream using web ReadableStream (cross-platform!)
async function uploadWebStream() {
const stream = new ReadableStream({
start(controller) {
const data = new TextEncoder().encode('Stream data');
controller.enqueue(data);
controller.close();
},
});
const response = await SmartRequest.create()
.url('https://api.example.com/upload')
.stream(stream, 'text/plain')
.post();
return await response.json();
}
// Stream a file using Node.js streams (Node.js only)
async function uploadLargeFile(filePath: string) {
const fileStream = fs.createReadStream(filePath);
const response = await SmartRequest.create()
.url('https://api.example.com/upload')
.stream(fileStream, 'application/octet-stream')
.post();
return await response.json();
}
// Stream data from any readable source (Node.js only)
async function streamData(dataSource: Readable) {
const response = await SmartRequest.create()
.url('https://api.example.com/stream')
.stream(dataSource)
.post();
return await response.json();
}
// Send Uint8Array (works everywhere)
async function uploadBinaryData() {
const data = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"
const response = await SmartRequest.create()
.url('https://api.example.com/binary')
.buffer(data, 'application/octet-stream')
.post();
return await response.json();
}Streaming Methods
.buffer(data, contentType?)- Stream a Buffer or Uint8Array directlydata: Buffer (Node.js) or Uint8Array (cross-platform) to sendcontentType: Optional content type (defaults to 'application/octet-stream')- ✅ Works everywhere (Node.js, Bun, browsers)
.stream(stream, contentType?)- Stream from ReadableStream or Node.js streamstream: Web ReadableStream (cross-platform) or Node.js stream (Node.js only)contentType: Optional content type- ✅ Web ReadableStream works everywhere (Node.js, Bun, browsers)
- ⚠️ Node.js streams only work in Node.js (automatically converted to web streams in Bun)
These methods are particularly useful for:
- Uploading large files without loading them into memory
- Streaming real-time data to servers
- Proxying data between services
- Implementing chunked transfer encoding
Unix Socket Support (Node.js and Bun)
SmartRequest supports unix sockets across all server-side runtimes with a unified API:
import { SmartRequest } from '@push.rocks/smartrequest';
// Connect to a service via Unix socket (works on Node.js and Bun)
async function queryViaUnixSocket() {
const response = await SmartRequest.create()
.url('http://unix:/var/run/docker.sock:/v1.24/containers/json')
.get();
return await response.json();
}
// Alternative: Use socketPath option (works on all server runtimes)
async function queryWithSocketPath() {
const response = await SmartRequest.create()
.url('http://localhost/version')
.options({ socketPath: '/var/run/docker.sock' })
.get();
return await response.json();
}Runtime-Specific Unix Socket APIs
Each runtime implements unix sockets using its native capabilities:
Bun:
import { CoreRequest } from '@push.rocks/smartrequest/core_bun';
// Bun uses the native `unix` fetch option
const response = await CoreRequest.create('http://localhost/version', {
unix: '/var/run/docker.sock'
});Node.js:
import { CoreRequest } from '@push.rocks/smartrequest/core_node';
// Node.js uses native socketPath option
const response = await CoreRequest.create('http://localhost/version', {
socketPath: '/var/run/docker.sock'
});Pagination Support
The library includes built-in support for various pagination strategies:
import { SmartRequest } from '@push.rocks/smartrequest';
// Offset-based pagination (page & limit)
async function fetchAllUsers() {
const client = SmartRequest.create()
.url('https://api.example.com/users')
.withOffsetPagination({
pageParam: 'page',
limitParam: 'limit',
startPage: 1,
pageSize: 20,
totalPath: 'meta.total',
});
// Get first page with pagination info
const firstPage = await client.getPaginated();
console.log(`Found ${firstPage.items.length} users on first page`);
console.log(`Has more pages: ${firstPage.hasNextPage}`);
if (firstPage.hasNextPage) {
// Get next page
const secondPage = await firstPage.getNextPage();
console.log(`Found ${secondPage.items.length} more users`);
}
// Or get all pages at once (use with caution for large datasets)
const allUsers = await client.getAllPages();
console.log(`Retrieved ${allUsers.length} users in total`);
}
// Cursor-based pagination
async function fetchAllPosts() {
const allPosts = await SmartRequest.create()
.url('https://api.example.com/posts')
.withCursorPagination({
cursorParam: 'cursor',
cursorPath: 'meta.nextCursor',
hasMorePath: 'meta.hasMore',
})
.getAllPages();
console.log(`Retrieved ${allPosts.length} posts in total`);
}
// Link header-based pagination (GitHub API style)
async function fetchAllIssues(repo: string) {
const paginatedResponse = await SmartRequest.create()
.url(`https://api.github.com/repos/${repo}/issues`)
.header('Accept', 'application/vnd.github.v3+json')
.withLinkPagination()
.getPaginated();
return paginatedResponse.getAllPages();
}Keep-Alive Connections (Node.js)
import { SmartRequest } from '@push.rocks/smartrequest';
// Enable keep-alive for better performance with multiple requests
async function performMultipleRequests() {
// Note: keepAlive is NOT enabled by default
const response1 = await SmartRequest.create()
.url('https://api.example.com/endpoint1')
.options({ keepAlive: true })
.get();
const response2 = await SmartRequest.create()
.url('https://api.example.com/endpoint2')
.options({ keepAlive: true })
.get();
// Connections are pooled and reused when keepAlive is enabled
return [await response1.json(), await response2.json()];
}Rate Limiting (429 Too Many Requests) Handling
The library includes built-in support for handling HTTP 429 (Too Many Requests) responses with intelligent backoff:
import { SmartRequest } from '@push.rocks/smartrequest';
// Simple usage - handle 429 with defaults
async function fetchWithRateLimitHandling() {
const response = await SmartRequest.create()
.url('https://api.example.com/data')
.handle429Backoff() // Automatically retry on 429
.get();
return await response.json();
}
// Advanced usage with custom configuration
async function fetchWithCustomRateLimiting() {
const response = await SmartRequest.create()
.url('https://api.example.com/data')
.handle429Backoff({
maxRetries: 5, // Try up to 5 times (default: 3)
respectRetryAfter: true, // Honor Retry-After header (default: true)
maxWaitTime: 30000, // Max 30 seconds wait (default: 60000)
fallbackDelay: 2000, // 2s initial delay if no Retry-After (default: 1000)
backoffFactor: 2, // Exponential backoff multiplier (default: 2)
onRateLimit: (attempt, waitTime) => {
console.log(`Rate limited. Attempt ${attempt}, waiting ${waitTime}ms`);
},
})
.get();
return await response.json();
}
// Example: API client with rate limit handling
class RateLimitedApiClient {
private async request(path: string) {
return SmartRequest.create()
.url(`https://api.example.com${path}`)
.handle429Backoff({
maxRetries: 3,
onRateLimit: (attempt, waitTime) => {
console.log(
`API rate limit hit. Waiting ${waitTime}ms before retry ${attempt}`,
);
},
});
}
async fetchData(id: string) {
const response = await this.request(`/data/${id}`).get();
return response.json();
}
}The rate limiting feature:
- Automatically detects 429 responses and retries with backoff
- Respects a valid
Retry-Afterheader (seconds or an HTTP-date, parsed byparseRetryAfterbelow) - Uses exponential backoff when the
Retry-Afterheader is absent or invalid - Allows custom callbacks for monitoring rate limit events
- Caps maximum wait time to prevent excessive delays
Parsing Retry-After yourself
parseRetryAfter(value, now?) is the parser behind handle429Backoff(), exported from the main entry for Node.js, Bun and browsers. It turns a Retry-After value into the delay it asks for, in milliseconds, or null when the value is not valid:
import { parseRetryAfter } from '@push.rocks/smartrequest';
parseRetryAfter('120'); // 120000
parseRetryAfter(' 120\t'); // 120000: surrounding spaces and tabs are ignored
parseRetryAfter('Sun, 06 Nov 1994 08:49:37 GMT'); // 0: a date in the past
parseRetryAfter('Sun, 06 Nov 1994 08:49:37 GMT', Date.UTC(1994, 10, 6, 8, 49)); // 37000
parseRetryAfter('120abc'); // null, as are '-5', '1.5', '', 'garbage', null and undefined
parseRetryAfter(['120']); // 120000
parseRetryAfter(['120', '60']); // null- delta-seconds: digits only, times 1000, capped at
Number.MAX_SAFE_INTEGER. A sign, a fraction, an exponent or anything after the digits makes the valuenull. - HTTP-date: the time from
now(defaultDate.now()) until the date, and 0 for a date in the past. The three formats RFC 9110 obliges a recipient to accept are parsed by their grammar: the IMF-fixdateSun, 06 Nov 1994 08:49:37 GMTand the obsoleteSunday, 06-Nov-94 08:49:37 GMT(when its two-digit year puts the timestamp more than 50 years afternow, it is read in the most recent past year with those two digits, and the weekday must match that year) andSun Nov 6 08:49:37 1994. Names andGMTare case-sensitive, and an impossible date (31 April, hour 24, a weekday that does not match the date) isnull.Date.parseis not used: outside ISO 8601 its accepted input differs between runtimes, and Node.js and Bun take strings such as"Nov 6 1994"or"garbage 2024"as dates. - Arrays:
Retry-Afteris a single-value field, so an array (a repeated header) is parsed only when it holds exactly one value; with several values it isnull, as is the comma-joined value ("120, 60") that fetch makes of a repeated header. nowmust be a finite number of milliseconds since the epoch; anything else throws aTypeError.
Public-Only Requests (Untrusted URLs)
When a URL comes from someone else (a form field, a webhook setting, a link in a document), the request must not reach your own network: no localhost, no private or link-local address, no cloud metadata endpoint at 169.254.169.254. publicOnly() makes a request that only reaches public internet hosts, and bounds what comes back:
import { SmartRequest, PublicOnlyError } from '@push.rocks/smartrequest';
async function readImprint(untrustedUrl: string) {
try {
const response = await SmartRequest.create()
.url(untrustedUrl)
.header('User-Agent', 'ExampleBot/1.0 (+https://example.com/bot)')
.publicOnly({
maxRedirects: 5,
maxResponseSize: 2 * 1024 * 1024, // bytes, also counted after decompression
allowedContentTypes: ['text/html', 'application/xhtml+xml', 'text/plain'],
connectTimeout: 5_000,
responseTimeout: 10_000,
totalTimeout: 15_000,
})
.get();
if (!response.ok) {
return { status: response.status }; // e.g. 403 or 404, returned as it is
}
// The body was read completely, within the limits, and decoded
const html = await response.text();
return { url: response.url, html }; // response.url is the final URL after redirects
} catch (error) {
if (error instanceof PublicOnlyError) {
// error.code says why (see the table below), error.detail carries the specifics
console.log(error.code, error.message);
}
throw error;
}
}For the first request and for every redirect:
- URL:
http:andhttps:only (orallowedProtocols: ['https:']), no user name or password in the URL, and only the allowed ports (allowedPorts, default 80 and 443;'any'allows every port from 1 to 65535, for a server whose port its operator chooses — the address checks apply either way). The URL is parsed as a browser parses it: an IDN becomes punycode, and2130706433,0x7f.1,0177.0.0.1and127.0.0.1.are all 127.0.0.1. - Host names: special-use names are refused before any lookup:
localhost,.local,.internal,.arpa(includinghome.arpa),.test,.invalid,.example,.onion,.alt, and single-label names such asintranet. A service that runs in its operator's own network can admit some of them by name:allowSpecialUseDomains: ['internal', 'arpa']letsmail.corp.internalandmail.home.arpabe looked up, andallowSingleLabelNames: truea name such asintranet. Admitting a name never admits an address: every address it resolves to still has to passallowAddress, so a private network needs both. Any other special-use name stays refused. - Addresses: the host name is resolved once, and every address must be public; one non-public answer refuses the request. The connection then goes to exactly the checked addresses, so a second DNS answer cannot change the target (DNS rebinding), and nothing of the request is sent before the connection's peer is confirmed to be one of them. TLS still sends the host name (SNI) and verifies the certificate for it, and the
Hostheader is the host of the URL. - Redirects: followed up to
maxRedirects(default 5), and every target is checked like the first URL. Loops are detected.Authorization,CookieandProxy-Authorizationare dropped when a redirect leaves the origin. As in the Fetch standard, 301 and 302 turn a POST, and 303 any method but HEAD, into a GET without a body; 307 and 308 send the body again, which a stream body cannot, so that redirect is refused. - Response: the body is read completely before the response is returned. Its size is counted as the bytes arrive and again after each decoding step (
gzip,deflate,br), so neither a wrongContent-Lengthnor a compression bomb gets pastmaxResponseSize(default 5 MiB): decoding stops at the limit.allowedContentTypes(type/subtypeortype/*, default any) applies to successful (2xx) responses; an error response is returned as it is, so its status stays visible. - Error responses: by default (
nonSuccessBody: 'read') the body of a response outside 2xx is read like any other, withinmaxResponseSize.nonSuccessBody: 'discard'returns it with its status and headers (aRetry-After, for example) and an empty body: the connection is closed at once instead of reading the body, so neithermaxResponseSizenor the content encoding applies to it. Redirects that are followed are not affected. - Certificates:
https:is verified against the runtime's root certificates.ca(one PEM certificate or a list) replaces them for a server whose certificate a private certificate authority issued, as a self-hosted installation's own servers often have; the host name is still verified. To trust the usual roots as well, pass them too:[...tls.rootCertificates, privateCa]withnode:tlsin Node.js and Bun. - Time:
connectTimeoutcovers TCP and the TLS handshake (default 10 s),responseTimeoutthe wait for the response headers (default 15 s), andtotalTimeouteverything, including redirects and the body (default 30 s)..timeout(ms)and anAbortSignalpassed with.options({ signal })apply as well.
Refused addresses (IANA special-purpose registries):
| Family | Ranges |
| --- | --- |
| IPv4 | 0.0.0.0/8, 10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.0.0.0/24, 192.0.2.0/24, 192.31.196.0/24, 192.52.193.0/24, 192.88.99.0/24, 192.168.0.0/16, 192.175.48.0/24, 198.18.0.0/15, 198.51.100.0/24, 203.0.113.0/24, 224.0.0.0/4, 240.0.0.0/4, 255.255.255.255 |
| IPv6 | ::, ::1, 64:ff9b:1::/48, 100::/64, 2001::/23, 2001:db8::/32, 2620:4f:8000::/48, 3fff::/20, 5f00::/16, fc00::/7, fe80::/10, fec0::/10, ff00::/8, and everything outside 2000::/3 |
| IPv6 carrying IPv4 | IPv4-mapped ::ffff:0:0/96, NAT64 64:ff9b::/96, 6to4 2002::/16 and Teredo 2001::/32 are judged by the IPv4 address they carry; the deprecated IPv4-compatible ::/96 is never public |
Errors (error.code, with the specifics in error.detail):
| Code | Meaning |
| --- | --- |
| option_not_allowed, header_not_allowed, method_not_allowed | The request itself is refused: an option that would choose the connection or bypass the checks (detail.option), a Host header, or a method other than GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS |
| runtime_not_supported | A browser, which cannot run public-only requests (see below) |
| invalid_url, scheme_not_allowed, credentials_in_url, port_not_allowed | The URL itself is refused |
| host_not_allowed | A special-use, single-label or invalid host name |
| address_not_public | The host is, or resolves to, a non-public address (detail.address says which and why) |
| dns_failed | The host name could not be resolved |
| connect_failed, connect_timeout, tls_failed | No connection, or no TLS connection |
| response_timeout, total_timeout, response_failed, aborted | The response did not arrive completely |
| too_many_redirects, redirect_loop, invalid_redirect, redirect_body_not_replayable | A redirect that is not followed |
| content_type_not_allowed, content_encoding_not_supported, content_decoding_failed, response_too_large | The response is refused (detail.status has its status) |
Every error carries url (the URL being requested when it happened, empty when the URL does not parse) and redirects (the URLs that redirected before). Every error raised after the head of the final response arrived (the four response codes in the last row, and response_failed, total_timeout and aborted while the body was read) has detail.bodyBytesRead, the bytes of the body read before the failure; it is 0 when the response was refused before any of its body was read, and absent when the request failed before that head (response_timeout ends with the head, so it never has it). No part of an error contains a user name or password from a URL: not url, redirects, detail (an invalid Location is shown without them) or the message. A successful response is a PublicOnlyResponse, which also has redirects, remoteAddress (the address the final response came from) and bodyBytesRead. Its text() decodes the body by the charset of the Content-Type, as a browser reads responseText: a byte order mark decides over the charset, and a body without a charset, or with one no TextDecoder knows, is read as UTF-8. json() always reads UTF-8, as JSON requires. arrayBuffer() holds exactly the bytes of the body. PublicOnlyError extends Error. An invalid configuration (a negative timeout, a port outside 1 to 65535) is a programming error and throws a plain Error when the request is sent.
Counting the Bytes a Request Read
bodyBytesRead counts the bytes of the final body as they came off the connection: after the chunked transfer coding is removed and before content decoding, so a compressed body counts what the server sent, not what it decodes to. A PublicOnlyResponse has it for its body (0 for HEAD, 204, 304 and a discarded body), and the errors raised after the head of the final response have it as detail.bodyBytesRead for the part read before the failure. Together they let a service meter what each of its users pulls from third parties, failures included:
import { SmartRequest, PublicOnlyError, PublicOnlyResponse } from '@push.rocks/smartrequest';
async function fetchForUser(untrustedUrl: string, meter: { add(bytes: number): void }) {
try {
const response = await SmartRequest.create()
.url(untrustedUrl)
.publicOnly({ maxResponseSize: 10 * 1024 * 1024, nonSuccessBody: 'discard' })
.get();
if (response instanceof PublicOnlyResponse) {
meter.add(response.bodyBytesRead); // 0 for a discarded 404
}
return response;
} catch (error) {
if (error instanceof PublicOnlyError && 'bodyBytesRead' in error.detail) {
meter.add(error.detail.bodyBytesRead ?? 0); // a body cut at the limit, a timeout in the body, ...
}
throw error;
}
}The count covers what the request read, not every byte that reached the machine. Redirect bodies are never read, and a discarded body is not read at all: their connection is closed as soon as the head arrived, but what arrived until then is not counted: on a local connection, Node.js and Bun had received 64 to 128 KiB of a large body along with its head, and the operating system had taken in about 4 MiB before the connection closed. With .retry() or .handle429Backoff() a call can make several requests; the response or error has the count of the last one.
Checking a URL Without a Request
checkPublicOnlyUrl() applies the rules of publicOnly() that need no network to a URL on its own, synchronously and without any lookup: for refusing a saved link, a feed address or an imported list of URLs at once, before anything is fetched. It is the check that publicOnly() and createPublicOnlyFetch run for every URL they request. In Node.js and Bun a URL refused here is refused there with the same code, detail and url, unless the request is refused first for its options, its method or a Host header (option_not_allowed, method_not_allowed, header_not_allowed), which they check before the URL. A browser refuses every public-only request with runtime_not_supported. It takes the URL options of publicOnly() (allowedProtocols, allowedPorts, allowAddress, allowSpecialUseDomains, allowSingleLabelNames), so one policy object serves both:
import { checkPublicOnlyUrl, PublicOnlyError } from '@push.rocks/smartrequest';
function acceptFeedUrl(untrustedUrl: string): URL {
try {
const { url, hostKind } = checkPublicOnlyUrl(untrustedUrl);
// url: a new URL object, the host in punycode and IPv4 literals normalized
// hostKind: 'ip' for an IP literal (already checked), 'name' for a host name
return url;
} catch (error) {
if (error instanceof PublicOnlyError) {
// invalid_url, scheme_not_allowed, credentials_in_url, port_not_allowed,
// host_not_allowed or address_not_public, as publicOnly() reports them
throw new Error(`This address cannot be fetched: ${error.code}`);
}
throw error; // an invalid configuration is a plain Error
}
}It checks the scheme, a user name or password in the URL, the port, the host name (special-use and single-label names) and an IP literal host in every form the URL parser reads (2130706433, 0x7f.1, [::ffff:127.0.0.1] and the others above). It does not see the request and does not resolve the host name, so a pass is no promise that a request will be made: the request options, the method, the addresses a name resolves to, DNS rebinding, every redirect target and the response are checked only by publicOnly() and createPublicOnlyFetch when they request the URL. The answer comes from the URL parser of the runtime it runs in, and parsers differ at the edges: Chromium passes http://127.0.0.1%20/ as a host name, which Node.js and Bun refuse as invalid_url. In a browser a pass is therefore early feedback only; the request your server makes with publicOnly() is authoritative.
Testing Against Local Servers
The default policy refuses local test servers as well. Give the request a stub resolver and admit the test address explicitly, only for the names your test uses:
const response = await SmartRequest.create()
.url(`http://shop.example.com:${port}/impressum`)
.publicOnly({
resolve: async (hostname) => (hostname === 'shop.example.com' ? ['127.0.0.1'] : []),
allowedPorts: [port],
allowAddress: (address, target) =>
address.isPublic ||
(address.address === '127.0.0.1' && target.hostname === 'shop.example.com'),
})
.get();A Public-Only fetch With a Streamed Body
publicOnly() reads the body completely. A client library that takes a fetch function and reads a stream (a model provider's SDK, for example) gets createPublicOnlyFetch(config) instead: a fetch with the same policy, whose Response arrives with the headers and whose body streams.
import { createPublicOnlyFetch, PublicOnlyError } from '@push.rocks/smartrequest';
// An endpoint a customer entered: HTTPS on port 443 only, no redirects, a long stream allowed
const customerFetch = createPublicOnlyFetch({
allowedProtocols: ['https:'],
allowedPorts: [443],
maxRedirects: 0,
maxResponseSize: 20 * 1024 * 1024,
totalTimeout: 10 * 60_000,
});
const response = await customerFetch('https://models.example.com/v1/chat/completions', {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },
body: JSON.stringify(request),
signal: AbortSignal.timeout(120_000),
});
for await (const chunk of response.body!) {
// decoded bytes, as they arrive
}- Same checks as
publicOnly(): the URL, the host name, every resolved address (one resolution per request, the connection pinned to the checked addresses) and every redirect target.redirect: 'error'refuses any redirect (asmaxRedirects: 0does),redirect: 'manual'returns the redirect response without following it. - The response is a standard
Response(aPublicOnlyFetchResponse) withurl(the final URL),redirected,redirectsandremoteAddress. The body is decoded (gzip,deflate,br); it isnullfor HEAD, for 204, 205 and 304, and withnonSuccessBody: 'discard'for a response outside 2xx (a redirect returned byredirect: 'manual'included). - Limits while the body streams:
maxResponseSizecounts the body as it arrives and after each decoding step, andtotalTimeoutcovers the whole request including the body. A limit reached while the body is read errors the stream with aPublicOnlyError. The connection is released when the body was read, cancelled (response.body.cancel()) or failed; a body nobody reads holds its connection untiltotalTimeout. - Errors: an abort through
init.signalrejects, or errors the body, with the signal's reason, asfetchdoes. Arguments the Fetch standard refuses reject with aTypeError, as infetch: a body with GET or HEAD, an unknownredirectmode, and what theRequestandHeadersconstructors and the body extraction refuse. Every other refusal and every other failure is aPublicOnlyErrorwith the codes above, including a response the runtime'sResponsecannot represent (response_failed, for example a status text with a control character; its connection is closed). An invalid configuration throws a plainErrorwhencreatePublicOnlyFetchis called. - Arguments: the arguments of
fetch(a URL string, aURLor aRequest, and aRequestInit). A body other than aReadableStream(or aRequest's body) is read first, so a 307 or 308 redirect can send it again. The options that would choose another connection (dispatcher,proxy,unix,agent) andintegrityare refused with aPublicOnlyError(option_not_allowed), aHostheader withheader_not_allowed; the browser options (mode,credentials,cache,referrer,referrerPolicy,keepalive,priority) are ignored, as thefetchof Node.js ignores them.
Public-Only Sockets (IMAP, SMTP and Other Protocols)
A protocol that is not HTTP opens its own socket. resolvePublicOnlySocket(target, config) checks such a target with the same policy and resolves it once; the answer is what to connect with.
import * as tls from 'node:tls';
import { resolvePublicOnlySocket, PublicOnlyError } from '@push.rocks/smartrequest';
// A mail server a customer entered: IMAP over TLS or STARTTLS only
const target = await resolvePublicOnlySocket(
{ host: 'imap.example.com', port: 993 },
{ allowedPorts: [993, 143], resolveTimeout: 5_000, signal },
);
const socket = tls.connect({
host: target.host, // the checked name, in ASCII form
port: target.port,
lookup: target.lookup, // answers only with the checked addresses
servername: target.servername, // SNI, and the name the certificate is verified for
});- Checks: the port must be one of
allowedPorts(there is no default; every protocol has its own ports). An IP literal (IPv6 with or without brackets) must be a public address. A host name is taken in its ASCII form (Bücher.examplebecomesxn--bcher-kva.example) and must not be special-use or single-label (unlessallowSpecialUseDomainsorallowSingleLabelNamesadmits it, as for requests), and every address it resolves to must be public: one private address refuses the host. - Pinned:
lookupanswers only fortarget.hostand only with the checkedaddresses, so a second DNS answer cannot change where the socket goes. Passhostandlookuptogether, tonet.connect,tls.connector a library that hands these options on to them. An IP literal needs no lookup: connect totarget.host. - TLS:
servernameis the host name without a trailing dot; it is sent as SNI and the certificate is verified for it. Node.js verifies the certificate againstservernamewhenever it is given, also whenhostis an IP address; without it, againsthost. An IP literal target has noservername. - Errors: every refusal and failure is a
PublicOnlyErrorwhoseurlishost:port:port_not_allowed,host_not_allowed,address_not_public,dns_failed(also when the resolver gives no answer withinresolveTimeout, default 10 seconds) andaborted(throughsignal). An invalid configuration rejects with a plainError.resolveandallowAddresswork as for requests, so local test servers are admitted the same way (see above). - Scope: the check covers where the socket connects. The protocol on top (its own redirects or referrals, for example) is the caller's; check any further host the same way.
Classifying Addresses
The classification is available on its own and runs in every runtime, browsers included:
import { classifyAddress, isPublicAddress } from '@push.rocks/smartrequest';
isPublicAddress('8.8.8.8'); // true
classifyAddress('::ffff:169.254.169.254');
// {
// address: '::ffff:a9fe:a9fe', family: 6, category: 'link-local', isPublic: false,
// range: '169.254.0.0/16',
// embedded: { mechanism: 'ipv4-mapped', prefix: '::ffff:0:0/96', ipv4: '169.254.169.254' },
// }Runtimes and Limits
- Node.js runs public-only requests natively; Bun runs them through its Node.js compatibility layer (
node:http,node:https,node:dns,node:zlib). The tests run in both. - Browsers refuse them with a
PublicOnlyError(runtime_not_supported): a browser can neither resolve host names nor choose the address it connects to.publicOnly()andcreatePublicOnlyFetchrefuse there for every URL;checkPublicOnlyUrl,classifyAddressandisPublicAddressneed no network and run in browsers as well. - A public-only request always connects directly and never through an HTTP proxy. Every request gets its own connection; the options that would choose the target or share connections (
agent,socketPath,hostname,port,path,keepAlive: true, aHostheader) are refused with aPublicOnlyError(option_not_allowed,header_not_allowed). - The policy judges addresses. A host with a public address that only your network can reach (behind your firewall) looks like any other public host; if that matters, run the requests from where such hosts are not reachable.
HTTP Digest Authentication
Cameras, printers, meters and other devices on a local network protect their APIs with HTTP Digest authentication. digestAuth() answers their challenges (Node.js and Bun):
import { SmartRequest, DigestAuth } from '@push.rocks/smartrequest';
// One DigestAuth per device: it remembers the device's challenge between requests.
const camera = new DigestAuth({ username: 'admin', password: process.env.CAMERA_PASSWORD! });
const snapshot = await SmartRequest.create()
.url('http://192.168.1.40/cgi-bin/snapshot.cgi')
.query({ channel: '1' })
.digestAuth(camera)
.get();
const jpeg = await snapshot.arrayBuffer();
// For a single request, the credentials can be passed directly
await SmartRequest.create()
.url('http://192.168.1.41/api/v1/status')
.digestAuth('maker', 'secret')
.get();- Protocol: RFC 7616 with the RFC 2617 forms that devices still send. The algorithms
MD5,SHA-256andSHA-512-256, each also as-sess; qopauth, and challenges without qop (RFC 2069); a client nonce and nonce count with every answer; the username hashed when the server asks for it (userhash=true), and sent asusername*(RFC 8187) when it is not printable ASCII. When a server offers several challenges, the first one this client supports is answered, as RFC 7616 asks. A challenge that offers only qopauth-int, or only another algorithm, is not answered: the 401 is returned. - One round per request: a 401 with a Digest challenge is answered exactly once: the request is sent again with credentials, and the response to that is returned whatever its status. A server that refuses the answer gets two requests, never more.
- Challenge reuse: a DigestAuth remembers the challenge per origin and realm (within the challenge's
domain, when it names one). Further requests to that origin carry anAuthorizationright away, with the remembered nonce and an incremented nonce count, and need no 401 round. When the server marks the noncestale=true, or no longer knows it, the request's round answers the new challenge;nextnonceinAuthentication-Infois used for the next request. A refusal withoutstale=trueforgets the realm, so the next request starts over.auth.clear()forgets every challenge. - Request bodies: the body is sent a second time after a challenge, so it must be replayable: a string, bytes, JSON or form data. A stream body (
.stream()) is refused with aDigestAuthError(body_not_replayable) before anything is sent; a stream cannot be replayed, and sending it only after a challenge would need a request whose side effects are unknown. Buffer a small stream yourself. - Credentials: the password is only ever hashed. It is never part of a header, a URL, an error message, or the DigestAuth instance's enumerable or inspectable state. The
Authorizationheader belongs to the exchange: one set withheader()is replaced. - Redirects: a 401 is answered only when it comes from the requested origin. Bun's fetch (and the fetch of
createDigestFetch) follows redirects; Node.js requests do not. When a redirect within the origin led to the 401, the answer is sent to the redirect target and signs its path and query, still in the request's one round; this applies to GET and HEAD only, because a 301, 302 or 303 turns another method into a GET, which the response does not reveal, so for other methods that 401 is returned unanswered. - Runtimes: digest hashing needs MD5, which Web Crypto does not offer, so Node.js and Bun use
node:crypto. Browsers reject with aDigestAuthError(runtime_not_supported): a browser answers HTTP authentication challenges itself (a same-origin 401 makes it ask the user), and a cross-origin device'sWWW-Authenticateheader is hidden from the page unless the device exposes it with CORS, so a page cannot run the exchange reliably, and the package ships no MD5 of its own for it.
createDigestFetch(auth, fetch?) gives the same exchange to fetch-style code, and to SmartFetch as its transport:
import { DigestAuth, createDigestFetch } from '@push.rocks/smartrequest';
import { SmartFetch } from '@push.rocks/smartrequest/fetch';
const printer = new SmartFetch({ fetch: createDigestFetch(new DigestAuth({ username: 'maker', password })) });
const job = await printer.getJson('http://192.168.1.41/api/v1/job');It reads the request body into memory before the first attempt (as SmartFetch does for its retries), so the body can be sent again; a ReadableStream in init.body is refused with body_not_replayable.
Certificate Pinning for Devices with Self-Signed Certificates
Devices on a local network serve HTTPS with self-signed certificates and are often reached by IP address, so neither the certificate chain nor the host name can be verified. Turning verification off would accept any certificate. pinCertificate() trusts exactly one instead (Node.js and Bun):
import { SmartRequest, CertificatePinError, probeCertificateFingerprints } from '@push.rocks/smartrequest';
// Enrolment (trust on first use): read the device's certificate, show the fingerprint, store it.
const observed = await probeCertificateFingerprints({ host: '192.168.1.20', port: 443, timeout: 5_000 });
console.log(`Device certificate SHA-256: ${observed.certificateSha256}`);
// …after the user confirmed it:
const pin = { certificateSha256: observed.certificateSha256 };
// Every later request trusts exactly that certificate.
try {
const response = await SmartRequest.create()
.url('https://192.168.1.20/api/v1/data')
.pinCertificate(pin)
.get();
console.log(await response.json());
} catch (error) {
if (error instanceof CertificatePinError && error.code === 'certificate_mismatch') {
// The device presented another certificate: nothing was sent. Ask the user to confirm
// error.observed before pinning it.
console.log('New certificate:', error.observed?.certificateSha256);
}
throw error;
}- What is pinned:
certificateSha256is the SHA-256 of the leaf certificate's DER encoding, and trusts exactly that certificate;publicKeySha256is the SHA-256 of its SubjectPublicKeyInfo (DER), and trusts the key, which survives a device renewing its certificate with the same key. Give one or both; with both, both must match. Hex, upper or lower case, with or without colons (AB:CD:…, asX509Certificate.fingerprint256prints it). An invalid pin throws aTypeErrorinpinCertificate(). - The check: chain and host name are not verified; instead the fingerprints of the certificate the device presents are compared with the pin when the TLS handshake completed, and only then is the connection handed to the request. A mismatch closes the connection and rejects with a
CertificatePinError(certificate_mismatch) whoseobservedholds both fingerprints of the presented certificate, andexpectedthe pin; nothing of the request (not even its headers) was sent, and there is no fallback to an unverified connection. A server that presents no certificate fails withno_certificate. TLS sessions are never resumed, so every connection presents its certificate. - Connections: pinned requests use their own connection pools, never the shared keep-alive agents, and the pin is part of every pooled connection's name: a pinned request never reuses a connection that was verified another way or for another pin, and an unpinned request never reuses a pinned one.
keepAlive: trueandkeepAlive: falsekeep the socket timeouts of the unpinned agents (see Keep-Alive Connections); withoutkeepAlive, a pinned request opens its own connection and has no socket timeout beyond.timeout(), which also bounds the TLS handshake. - Restrictions:
https:URLs only; not combinable withagent(the pin chooses the connection), with a unix socket or withpublicOnly().ca,rejectUnauthorizedandcheckServerIdentityhave no effect on a pinned request. - Runtimes: Node.js, and Bun through its
node:httpslayer, because Bun's fetch does not hand a certificate that fails verification tocheckServerIdentity, so it cannot check a pin (the response of a pinned request in Bun is therefore the Node.js one, andraw()returns anhttp.IncomingMessage). Browsers verify certificates themselves and show none to a page: pinned requests and probes reject with aCertificatePinError(runtime_not_supported).CoreRequestof the Bun and browser implementations throws for thepinnedCertificateoption.
probeCertificateFingerprints({ host, port?, servername?, timeout?, signal? }) connects, completes the TLS handshake without verifying the certificate, and returns { certificateSha256, publicKeySha256, certificatePem }; it sends no request and closes the connection. port defaults to 443 and timeout (TCP connection and handshake together) to 10 s, rejecting with an Error whose code is ETIMEDOUT; the server name (SNI) is the host when it is a name and none for an IP address, unless servername says otherwise; an abort by signal rejects with its reason. The result can be passed to pinCertificate() directly.
Server-Sent Events
eventStream() sends the configured request with Accept: text/event-stream and iterates over the events as they arrive (Node.js, Bun and browsers). Headers, query parameters, digestAuth(), pinCertificate(), timeout() and retry() apply to every connection:
import { SmartRequest, EventStreamError } from '@push.rocks/smartrequest';
const controller = new AbortController();
const events = SmartRequest.create()
.url('https://192.168.1.30/eventstream/clip/v2')
.header('hue-application-key', applicationKey)
.pinCertificate(bridgePin)
.eventStream({ signal: controller.signal, reconnect: { maxAttempts: 10, maxDelay: 30_000 } });
try {
for await (const event of events) {
// event.type ('message' unless the server named it), event.data, event.lastEventId
console.log(event.type, JSON.parse(event.data));
}
} catch (error) {
if (error instanceof EventStreamError) {
console.log(error.code, error.status); // unexpected_status, unexpected_content_type, reconnect_failed, connect_timeout
}
}- Parsing: the event stream format of the HTML standard:
datalines joined with line feeds,event,id(persisting across events; a value with U+0000 is ignored),retry(ASCII digits only), comments, unknown fields ignored, CR, LF and CRLF line ends (also split between chunks), one leading byte order mark skipped, UTF-8 decoded as it arrives (split characters included), an event without data not dispatched, and an incomplete last event discarded at the end of the stream. - Limits: nothing a server sends grows without bound.
maxLineLength(default 1048576) bounds one line andmaxEventSize(default 4194304) thedataof one event, both in characters (UTF-16 code units) of the decoded stream;Infinityturns a limit off. A stream over a limit delivers the events before it, then its connection fails with aServerSentEventLimitError(line_too_longorevent_too_large, with thelimit), whichreconnectretries like any other failed connection. - Lifecycle: nothing is sent before the iteration starts. Leaving the loop (
break,return, an exception) closes the connection; abortingsignal(default: thesignalofoptions()) closes it too and rejects with the signal's reason. Either settles only once the connection is closed: in Node.js (and for pinned streams in Bun) after its socket emittedclose, also for an abort while connecting; with Bun's fetch and in browsers, once the body's cancel completed. - Responses: a status other than 200 rejects with an
EventStreamError(unexpected_status), and a content type other thantext/event-streamwithunexpected_content_type; neither is retried unlessreconnect.retryStatussays so for the status. A 204 ends the iteration without an error: it is how a server says that the client should not reconnect. - Reconnection (
reconnect: trueor options; off by default, when the iteration ends with the connection): a connection that ends or fails is reopened after the stream's reconnection time, withLast-Event-IDset to the last event ID. The reconnection time is the server'sretry, orinitialDelay(default 3000 ms) until it sent one; every further attempt without an event in between doubles it, andmaxDelay(default 60000 ms) caps every delay, the server'sretryincluded.jitter(0 to 1, default 0) shortens each delay by a random share of up to that fraction, so that the clients of a server that restarted do not return in lockstep. AftermaxAttemptsreconnections in a row without an event (default 5;Infinityfor no limit) the iteration rejects withreconnect_failed, whosecauseis the last failure.lastEventIdresumes a stream with the first connection. - Statuses:
reconnect.retryStatus(status)decides for a status other than 200 and 204 whether it is retried like a failed connection (it counts as an attempt, andreconnect_failedcarries it as thecause) or ends the iteration. The default retries none, as a browser'sEventSourcefails the connection for good. A device that refuses a wrong credential with 401 and has no stream behind 404, but answers other errors while it restarts:retryStatus: (status) => status !== 401 && status !== 404. - Time:
connectTimeout(milliseconds, default none) bounds each connection until its response head arrived: connecting, the TLS handshake and the wait for the head, in every runtime. A connection that takes longer fails withconnect_timeout, whichreconnectretries; the stream itself has no time limit. In Node.js (and for pinned streams in Bun),timeout()is an inactivity timeout of the connection: a stream that is idle for longer fails (and reconnects, withreconnect); with Bun's fetch and in browsers it bounds the wait for the response headers only. A server that sends nothing while nothing happens needsconnectTimeout, nottimeout().keepAlive: truein Node.js destroys a connection that is silent for 8 s unless the request sets a timeout (see Keep-Alive Connections), so leave it off for an event stream, or settimeout()above the server's keep-alive interval.
A device stream that never ends by itself, with every failure but a refused credential retried:
const events = SmartRequest.create()
.url(`http://192.168.1.40:16021/api/v1/${token}/events?id=1,3,4`)
.eventStream({
signal: controller.signal,
connectTimeout: 5_000,
maxLineLength: 65_536,
maxEventSize: 65_536,
reconnect: {
maxAttempts: Infinity,
initialDelay: 1_000,
maxDelay: 30_000,
jitter: 0.5,
retryStatus: (status) => status !== 401 && status !== 404,
},
});readServerSentEvents(body, { signal?, maxLineLength?, maxEventSize? }) parses any event stream body, such as the body of a fetch or SmartFetch response, with the same rules, and ServerSentEventParser ({ lastEventId?, maxLineLength?, maxEventSize? }) takes decoded text in pieces for other transports; its push() throws the ServerSentEventLimitError, whose events holds the events the piece completed before the limit.
Fetch-Compatible Client and HTTP Cache
Two subpath entry points add a client that speaks the native fetch contract (Request in, Response out), for code that wants standard responses, retries with backoff, URL failover and a persistent HTTP cache:
| Entry point | Exports | Dependencies |
|---|---|---|
| @push.rocks/smartrequest/fetch | SmartFetch, FetchStatusError, isFetchStatusError, FetchTimeoutError, isFetchTimeoutError, types | none: dispatches with globalThis.fetch (Node.js, Bun, browsers) |
| @push.rocks/smartrequest/cache | HttpCache | @push.rocks/webstore (IndexedDB) |
The main entry point (SmartRequest) does not load either of them, and /fetch never loads /cache: a browser bundle pays for IndexedDB code only when it imports HttpCache.
Use SmartRequest for unix sockets, streaming uploads, multipart forms, pagination, public-only requests, certificate pinning and event streams; use SmartFetch where a standard Response and the features below are wanted.
SmartFetch
import { SmartFetch, isFetchStatusError, isFetchTimeoutError } from '@push.rocks/smartrequest/fetch';
const client = new SmartFetch({
defaults: { headers: { authorization: 'Bearer …' }, timeout: 10_000 },
});
// fetch-compatible: a native Response
const response = await client.fetch('https://api.example.com/items', { method: 'GET' });
// JSON helpers reject an unsuccessful response with a FetchStatusError, see below
const item = await client.getJson<IItem>('https://api.example.com/items/1');
const created = await client.postJson<IItem>('https://api.example.com/items', { name: 'new' });
await client.putJson('https://api.example.com/items/1', { name: 'renamed' });
await client.deleteJson('https://api.example.com/items/1');
// Retries with backoff (by default on status 408, 429, 500, 502, 503 and 504; network errors and timeouts too)
await client.getJson(url, {
retry: { maxAttempts: 4, backoff: 'exponential', initialDelay: 250, maxDelay: 5_000 },
});
// Failover: the next URL after a network error, 408 or 5xx; a 4xx is final
await client.postJson(primaryUrl, payload, { fallbackUrls: [backupUrl] });
// Timeouts reject with a FetchTimeoutError
try {
await client.getJson(url, { timeout: 2_000 });
} catch (error) {
if (isFetchTimeoutError(error)) {
// error.url, error.timeoutMs
}
}
// An answer outside 2xx rejects with a FetchStatusError that keeps the status and the body
try {
await client.postJson(url, payload);
} catch (error) {
if (isFetchStatusError(error) && error.status === 401) {
// error.body: { type, title, status, code: 'sign_in_required' } from application/problem+json
}
}A FetchStatusError is an Error with the message HTTP <status>: <statusText> (the status text is empty over HTTP/2) and these fields:
| Field | Meaning |
|---|---|
| status, statusText | Status of the response |
| headers | Response Headers |
| url | URL that answered |
| body | Parsed JSON for application/json and every +json type such as application/problem+json, text for other types and for JSON that does not parse; undefined when the body is empty, larger than 64 KiB, or not complete within the call's timeout |
The error body is read under the same timeout and signal as a successful one: when the call's deadline runs out first the error keeps its status with body: undefined, and an aborted signal rejects with its reason. isFetchStatusError() also recognizes an error created by another copy of the package.
Options of a call are the standard RequestInit plus:
| Option | Meaning |
|---|---|
| retry | true or { maxAttempts, backoff: 'exponential' \| 'linear' \| 'constant', initialDelay, maxDelay, retryOn, onRetry } |
| fallbackUrls | URLs tried in order after the request URL fails; works with or without retry |
| timeout | Milliseconds for the response headers of each attempt (default 60000). The JSON helpers also bound the body; without retry and fallbackUrls it is one deadline for the whole call |
| interceptors | { request, response, error } arrays for this call, run after the instance interceptors (addRequestInterceptor, addResponseInterceptor, addErrorInterceptor, remove…, clearInterceptors) |
| deduplicate | Concurrent GET or HEAD calls with the same URL and headers share one request; each caller gets its own response, see below |
| cacheStrategy, cacheKey, cacheMaxAge | HTTP cache, see below |
| logging | Log cache decisions to the console |
The standard cache option ('no-store', 'force-cache', …) goes to the runtime's fetch unchanged.
Deduplicated calls share one request but not their fate:
- The first call starts the request with its options (
timeout,retry, interceptors); later calls withdeduplicate: trueand the same method, URL and headers attach to it. - A joining call inherits every option of the first call, not only
timeout,retryand interceptors but alsocacheStrategy,redirectandcredentials; of its own options only itssignalapplies. A'network-only'joiner can receive a response withfromCache: true. Disablededuplicatewhen concurrent calls to one URL differ in these options. - Every caller keeps its own
signal. A caller that aborts is rejected at once with its signal's reason and detached; the request continues for the callers still attached, the first one included. - The shared request is aborted only when every attached caller has aborted. A call that arrives afterwards starts a new request.
- Each caller receives an independent
Responseit can read on its own.
SmartFetch reads a request body once and sends the same bytes with every attempt, fallback URL and revalidation. For a streaming upload, use SmartRequest and its .stream() method.
fetchWithMetadata() and the …WithMetadata JSON helpers return { response, metadata: { fromCache, revalidated } } (frozen), so a caller learns whether the cache answered without trusting response headers.
new SmartFetch({ fetch }) dispatches through another fetch, for example a public-only one:
import { createPublicOnlyFetch } from '@push.rocks/smartrequest';
import { SmartFetch } from '@push.rocks/smartrequest/fetch';
const client =