carbon-http
v3.0.1
Published
Node.js Ultrasonic HTTP(s) request wrapper with no dependency
Maintainers
Readme
Carbon HTTP (v3.0.1)
Carbon HTTP is a zero-dependency, ultrasonic HTTP(S) client engineered specifically for enterprise Node.js microservices and financial infrastructure. Built with TypeScript targeting ES2022, it leverages native Node.js core modules (node:http, node:https, node:url, node:zlib) to deliver bulletproof resilience, low latency, and zero supply-chain risk.
🛡️ Key Enterprise Architectural Guarantees
| Architectural Dimension | Carbon HTTP Implementation | Risk Mitigated |
|---|---|---|
| Memory Protection | Bounded streaming payload limit (maxBodyLength, default 10MB) | Prevents Out-of-Memory (OOM) process crashes from malicious/large responses |
| Timeout Model | Absolute wall-clock timer with active socket destruction | Eliminates Slowloris idle socket deadline evasion attacks |
| Connection Pooling | Native HTTP/HTTPS Keep-Alive agents (defaultHttpAgent, defaultHttpsAgent) | Eliminates TCP/TLS handshake round-trip latency overhead |
| Compression | Automatic Accept-Encoding: gzip, deflate, br with native zlib stream piping | Minimizes network bandwidth utilization by up to 85% |
| Observability & Errors | Standard ES2022 Error.cause taxonomy (CarbonHttpError hierarchy) | Enables APMs (Datadog, New Relic, Sentry) and loggers (Pino, Winston) to trace origin causes |
| Supply Chain Security | 0 External Dependencies | Eliminates transitive dependency vulnerability vectors |
🚀 Quickstart
Installation
# NPM
npm install carbon-http
# Yarn
yarn add carbon-http
# pnpm
pnpm add carbon-http💡 API Reference & Examples
1. High-Throughput Service-to-Service Request (GET)
import {
Request,
CarbonHttpTimeoutError,
CarbonHttpMaxBodyLengthError,
CarbonHttpNetworkError,
} from 'carbon-http';
interface PaymentAccount {
accountId: string;
balance: number;
currency: string;
}
async function fetchAccount(accountId: string): Promise<PaymentAccount> {
try {
const res = await Request(`https://api.hsbc.internal/v1/accounts/${accountId}`, {
timeoutMs: 3000, // 3s absolute wall-clock deadline
maxBodyLength: 2 * 1024 * 1024, // 2MB max memory buffer threshold
decompress: true, // Transparent gzip/brotli decompression
});
// Safely parse JSON with explicit runtime validation callback
return res.json((raw: unknown) => {
const data = raw as PaymentAccount;
if (!data.accountId || typeof data.balance !== 'number') {
throw new Error('Invalid schema payload returned from upstream service');
}
return data;
});
} catch (err) {
if (err instanceof CarbonHttpTimeoutError) {
console.error(`[TIMEOUT] Request to ${err.url} exceeded ${err.timeoutMs}ms deadline`);
} else if (err instanceof CarbonHttpMaxBodyLengthError) {
console.error(`[OOM-GUARD] Payload exceeded ${err.maxBodyLength} bytes`);
} else if (err instanceof CarbonHttpNetworkError) {
console.error(`[NETWORK] Socket failure: ${err.cause.message}`);
}
throw err;
}
}2. Request Cancellation with AbortSignal (POST)
import { Request, HttpMethod, CarbonHttpAbortError } from 'carbon-http';
const controller = new AbortController();
// Cancel request if processing takes longer than expected externally
const timeoutId = setTimeout(() => controller.abort(), 2000);
try {
const res = await Request('https://api.syniol.com/v2/transactions', {
method: HttpMethod.POST,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: 500.0,
recipient: 'GB1234567890',
}),
signal: controller.signal,
});
clearTimeout(timeoutId);
console.log(`Status: ${res.status}`);
} catch (err) {
if (err instanceof CarbonHttpAbortError) {
console.warn(`[ABORTED] Request to ${err.url} was cancelled via AbortSignal`);
}
}🚨 Error Taxonomy
All exceptions thrown by carbon-http extend CarbonHttpError and propagate standard Error.cause objects:
CarbonHttpError (Base Error Class)
├── CarbonHttpNetworkError (DNS, TCP connection refused, socket drops)
├── CarbonHttpTimeoutError (Absolute wall-clock deadline exceeded)
├── CarbonHttpAbortError (Request cancelled via AbortSignal)
├── CarbonHttpJsonParseError (JSON syntax error with HTTP status & 200-char body preview)
└── CarbonHttpMaxBodyLengthError (Response payload exceeded maxBodyLength limit)⚙️ Public Configuration & Types
CarbonHttpRequestOption
headers?: Record<string, string>— Custom request header map.method?: HttpMethod— HTTP verb (HttpMethod.GET,HttpMethod.POST, etc.).body?: string | Uint8Array | Buffer— Payload content.port?: number— Override port.timeoutMs?: number— Absolute wall-clock timeout in milliseconds (default:30,000ms).signal?: AbortSignal— StandardAbortSignalinstance for cancellation.maxBodyLength?: number— Maximum response memory buffer threshold in bytes (default:10MB).decompress?: boolean— Enable automaticAccept-Encodingand nativezlibstream decompression (default:true).agent?: HttpAgent | HttpsAgent | boolean— Custom Node.js HTTP/HTTPS Agent orfalseto disable pooling.
CarbonHttpResponse
status: number— Numerical HTTP status code.headers: HttpHeaders— Normalized response header object.incomingMessage: IncomingMessage— Raw Node.js stream reference.text(): string— Returns body as UTF-8 string.json<T>(parser?: (raw: unknown) => T): T— Parses response body as JSON with optional runtime parser callback.
📜 Governance & License
Copyright © 2022-2026 Syniol Limited.
Distributed under the BSD 3-Clause License.
