2 Transports
ulyxie edited this page 2026-10-16 15:15:13 +00:00

Transports

A Session builds each request - URL, query, multipart body, ticket - and hands it to a transport to send. None of them adds a dependency.

The defaults

Runtime Default Why
Node Node's own http / https Node's fetch holds an upload's whole body in memory before sending it: +529 MB for a 512 MB file. http streams it: +0 MB
Bun fetch Bun's fetch streams a body the library encodes itself (+0 MB)
Browsers fetch Adds nothing to the bundle; the browser streams a File from disk

Uploads and downloads stream in every runtime. On Node and Bun, multipart bodies are encoded by the library as a stream with an exact Content-Length, because both runtimes' own FormData encoding reads every file part into memory. Browsers keep their native FormData.

Certificates, proxies and DNS in Node

Pass an agent; every request uses it.

import { readFileSync } from "node:fs";
import https from "node:https";
import tls from "node:tls";

// Trusting a private CA, as well as the usual ones
const ca = [...tls.rootCertificates, readFileSync("corp-ca.pem", "utf8")];
new Session({ baseUrl, otcsticket, agent: new https.Agent({ ca }) });

// Reaching a server whose name DNS does not resolve here
const lookup = (host, options, cb) => (options?.all ? cb(null, [{ address: "10.0.0.5", family: 4 }]) : cb(null, "10.0.0.5", 4));
new Session({ baseUrl, otcsticket, agent: new https.Agent({ lookup }) });
  • NODE_EXTRA_CA_CERTS=corp-ca.pem in the environment also trusts a CA, with no code.
  • A proxy needs a proxy agent: https-proxy-agent gives one (agent: new HttpsProxyAgent(process.env.HTTPS_PROXY)).
  • TLS stays fully verified against the URL's hostname in all of these.

The live tests (npm run test:live) reach the dev server exactly this way: an https.Agent with the private CA and a lookup to its address.

Your own fetch

Pass fetch to send everything through a fetch of your own, in any runtime:

import { Agent } from "undici";
const dispatcher = new Agent({ connect: { ca } });
new Session({ baseUrl, otcsticket, fetch: (url, init) => fetch(url, { ...init, dispatcher }) });

In Node, uploads sent this way sit in memory until sent - that is Node's fetch, whatever the dispatcher. Prefer agent for large files.

axios

For axios's proxy handling, an https.Agent, interceptors or progress events, send requests through it instead. axios is an optional peer dependency: install it yourself.

import axios from "axios";
import https from "node:https";
import { axiosTransport } from "@ulyxie/cs-rest/axios";

const session = new Session({
  baseUrl,
  otcsticket,
  transport: axiosTransport(axios.create({ httpsAgent: new https.Agent({ ca }) })),
});

axiosTransport takes your instance and never imports axios itself, so apps that do not use it never load axios. Uploads through it stream too: the transport sends them with redirects off, because axios's redirect support (follow-redirects) otherwise keeps a copy of the whole body.

Responses and errors

Whichever transport sends them:

  • Every request resolves with TResponse: { data, status, statusText, headers }, with lower-case header names.
  • data is parsed JSON by default, or text if the body is not JSON. responseType asks for "text", "arraybuffer" (an ArrayBuffer), "blob" or "stream" (a web ReadableStream, from every transport).
  • A status outside 2xx rejects with an HTTPError. error.response holds the decoded response - the same error.response.status / error.response.data an axios error had - and error.message includes Content Server's own error text when it sent one.
import { isHTTPError } from "@ulyxie/cs-rest";

try {
  await session.nodes.node(12345);
} catch (e) {
  if (isHTTPError(e) && e.status === 404) {
    // e.response.data.error: "..."
  }
}

Writing one

A transport is a function from TTransportRequest to TTransportResponse:

import { fetchTransport, type TTransport } from "@ulyxie/cs-rest";

const logging = (inner: TTransport): TTransport => async (request) => {
  console.log(request.method, request.url);
  return inner(request);
};

new Session({ baseUrl, otcsticket, transport: logging(fetchTransport()) });

The request arrives complete: absolute url with the query string, headers including OTCSTicket, and body already encoded (FormData, a string, or binary). Return the status, headers, and the body undecoded: a string for "json" and "text", otherwise whatever responseType asked for. Do not throw on an error status; the Session does that, so errors look the same everywhere.

Testing

fetch is also the easiest seam for tests: pass a fake one and inspect what it receives. The package's own test/requests.test.mjs and test/http.test.mjs work this way. In Node a form body then arrives as the library's streamed encoding; new Response(init.body, { headers: { "content-type": init.headers["content-type"] } }).formData() reads it back.

const fetch = async (url, init) => Response.json({ results: [] });
const session = new Session({ baseUrl: "http://cs.test/otcs/cs.exe", otcsticket: "t", fetch });