HTTP Requests & File Downloads (vael:fetch)
vael:fetch provides an outbound HTTP/HTTPS client (fetch, fetchSync) and a streaming atomic file downloader (download, downloadSync). Neither fetch nor any Web global is installed on globalThis — import explicitly from "vael:fetch".
1. JSON API Requests (fetch / fetchSync)
Section titled “1. JSON API Requests (fetch / fetchSync)”FetchOptions includes built-in ergonomics for JSON payloads (json), URL-encoded query parameters (query), bearer authentication (bearerToken), timeouts (timeoutMs), and response size bounds (maxResponseBytes):
import { fetch, FetchError } from "vael:fetch";
interface ReleaseAsset { readonly id: number; readonly tag_name: string;}
const res = await fetch("https://api.example.com/v1/releases", { method: "GET", query: { per_page: "10", target: "linux-amd64" }, bearerToken: "tok_example_from_env", timeoutMs: 10_000, maxResponseBytes: 4 * 1024 * 1024, // 4 MiB (default 16 MiB, max 256 MiB)});
if (!res.ok) { throw new Error(`API returned HTTP ${res.status} ${res.statusText}`);}
const releases = res.json<ReleaseAsset[]>();console.log("Latest tag:", releases[0]?.tag_name);console.log("Rate limit remaining:", res.header("x-ratelimit-remaining"));For POST / PUT / PATCH JSON requests, pass json: vael:fetch serializes the payload and sets Content-Type: application/json; charset=utf-8 automatically when no explicit Content-Type header is provided. Specifying both body and json throws FetchError with code === "VAEL_FETCH_INVALID_OPTION".
import { fetchSync } from "vael:fetch";
// Runs identically in both vjs and vjs-liteconst created = fetchSync("https://api.example.com/v1/events", { method: "POST", json: { event: "deploy", revision: "a1b2c3d" }, headers: { "x-idempotency-key": "deploy-001" }, timeoutMs: 5_000,});
console.log(created.status, created.redirected, created.url);Handling FetchResponse Safely
Section titled “Handling FetchResponse Safely”res.okistruefor200..=299. Note thatfetch()andfetchSync()return non-2xx responses rather than throwing (unlikedownload(), which rejects on non-2xx).res.text()decodes strict UTF-8 and throwsFetchError("VAEL_FETCH_INVALID_UTF8") on invalid byte sequences.res.json<T>()throwsFetchError("VAEL_FETCH_INVALID_JSON") on malformed JSON.res.header(name)performs a case-insensitive lookup for the first header value;res.headerValues(name)returns all values (useful for multi-value headers likeset-cookie).res.bytes()returns a defensive copy ofres.body.
2. SSRF Protection & Redirect Credential Hygiene
Section titled “2. SSRF Protection & Redirect Credential Hygiene”vael:fetch is hardened by default against Server-Side Request Forgery (SSRF) and credential leaks:
- Private IP blocking by default (
allowPrivateIps: false): Loopback (127.0.0.0/8,::1), RFC 1918 private ranges (10.0.0.0/8,172.16.0.0/12,192.168.0.0/16), link-local (169.254.0.0/16,fe80::/10), cloud-metadata endpoints (169.254.169.254), and IPv4-mapped IPv6 equivalents are rejected withFetchError("VAEL_FETCH_SSRF_BLOCKED"). This check applies to the initial URL and every redirect target.- Opt in explicitly via
allowPrivateIps: trueonly when intentionally calling an internal or local service (such ashttp://127.0.0.1:8080).
- Opt in explicitly via
- No embedded URL credentials: URLs containing
user:pass@hostare rejected with"VAEL_FETCH_INVALID_URL". - Cross-origin redirect stripping: If a request follows a
301/302/303/307/308redirect to a different(scheme, host, port)origin,Authorization(includingbearerToken) andCookieheaders are automatically stripped before contacting the new origin. - Redacted errors:
FetchError.messageandFetchError.urlstrip query strings, embedded credentials, bearer tokens, and sensitive header values.
FetchErrorCode Reference
Section titled “FetchErrorCode Reference”| Error Code | Trigger |
|---|---|
VAEL_FETCH_INVALID_URL |
Non-http:/https: URL, malformed URL, or embedded userinfo. |
VAEL_FETCH_INVALID_OPTION |
Invalid timeoutMs, maxRedirects, maxBytes, body+json conflict, or body on GET/HEAD. |
VAEL_FETCH_SSRF_BLOCKED |
Target or redirect resolved to a private/loopback/link-local/metadata IP while allowPrivateIps is false. |
VAEL_FETCH_DNS_TIMEOUT |
DNS resolution exceeded timeout. |
VAEL_FETCH_TIMEOUT |
Overall request or download deadline (timeoutMs) expired. |
VAEL_FETCH_TOO_MANY_REDIRECTS |
Redirect chain exceeded maxRedirects (default 10, max 20). |
VAEL_FETCH_BODY_TOO_LARGE |
Response exceeded maxResponseBytes or download exceeded maxBytes. |
VAEL_FETCH_HTTP_STATUS |
Non-2xx status code during download() / downloadSync() (err.status is set). |
VAEL_FETCH_CHECKSUM_MISMATCH |
Downloaded bytes did not match expectedSha256 (temp file is deleted, destPath untouched). |
VAEL_FETCH_ALREADY_EXISTS |
destPath already exists and overwrite is false (default). |
VAEL_FETCH_NETWORK / VAEL_FETCH_IO |
Transport/TLS failure or destination directory / atomic rename failure. |
VAEL_FETCH_INVALID_UTF8 / VAEL_FETCH_INVALID_JSON |
Strict UTF-8 or JSON decode failure in res.text() / res.json(). |
import { fetch, FetchError } from "vael:fetch";
try { await fetch("http://169.254.169.254/latest/meta-data/");} catch (err) { if (err instanceof FetchError && err.code === "VAEL_FETCH_SSRF_BLOCKED") { console.error("Blocked private target:", err.url); } else { throw err; }}3. Streaming Atomic SHA-256 Downloads (download / downloadSync)
Section titled “3. Streaming Atomic SHA-256 Downloads (download / downloadSync)”Use download() (vjs) or downloadSync() (vjs & vjs-lite) instead of buffering large files in memory:
- Streams directly to a sibling temporary file in the destination directory (so
destPathnever sees partial bytes). - Rejects non-2xx HTTP statuses with
VAEL_FETCH_HTTP_STATUSwithout creating or modifyingdestPath. - Enforces
maxBytes(default256 MiB, max4 GiB) while streaming. - Computes SHA-256 incrementally and checks
expectedSha256(64-char ASCII hex) in constant time before atomically renaming the temporary file intodestPath. - Reports incremental progress via
onProgress({ bytesWritten, totalBytes }). - Fails closed with
VAEL_FETCH_ALREADY_EXISTSunlessoverwrite: trueis set.
import { download } from "vael:fetch";
const result = await download( "https://github.com/neotales/vaeljs/releases/download/v0.0.0-alpha.3/vjs-v0.0.0-alpha.3-linux-amd64.tar.gz", "./artifacts/vjs-v0.0.0-alpha.3-linux-amd64.tar.gz", { expectedSha256: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", maxBytes: 128 * 1024 * 1024, // 128 MiB cap timeoutMs: 120_000, overwrite: true, onProgress({ bytesWritten, totalBytes }) { const pct = totalBytes ? `${Math.round((bytesWritten / totalBytes) * 100)}%` : `${bytesWritten} B`; console.log(`Downloading: ${pct}`); }, },);
console.log(`Saved ${result.bytesWritten} bytes to ${result.path} (sha256: ${result.sha256})`);4. Portable Scripts Across vjs and vjs-lite
Section titled “4. Portable Scripts Across vjs and vjs-lite”If a script must run under both vjs and vjs-lite, import fetchSync and downloadSync:
import { downloadSync, fetchSync } from "vael:fetch";
const meta = fetchSync("https://example.com/manifest.json", { timeoutMs: 5_000 }).json<{ url: string; sha256: string;}>();
const dl = downloadSync(meta.url, "./bundle.tar.gz", { expectedSha256: meta.sha256, overwrite: true,});
console.log("Verified:", dl.path, dl.sha256);See the full vael:fetch API Reference for every interface and option.
