/** * vapor-chamber - HTTP client * * Written to the CDCC guideline of small, single-purpose functions * (docs/whitepaper.md 3.5). It is a guideline: no lint rule checks it. * * What it does beyond a bare `fetch`: * - `AbortSignal.any` with manual fallback for older environments * - The async bus's retry schedule (full jitter, docs/retry.md) for a re-send it decides itself * - A declared wait sets when to re-send, never whether: `Retry-After` (RFC 9110), else `RateLimit` `t`, else `X-RateLimit-Reset` * - 419 CSRF refresh coalesces concurrent requests (no duplicate refreshes) * - `session-expired` CustomEvent + configurable callback * - The caller's abort (`transport:aborted:request`) distinct from no reply in time (`transport:timeout:reply`) */ export type HttpConfig = { /** * Request timeout in ms. * * Two consumers, two defaults - this type is shared by `postCommand` and by * `createHttpClient` (via `HttpRequestConfig`), and they do not agree: * **10_000 through `postCommand`, 30_000 through a client** (a command POST * and a general-purpose GET have different patience). * * Bounds: a value that does not compare as a number (NaN, a non-numeric * string) takes that default; anything above * 2_147_483_647 ms (`setTimeout`'s ceiling, where it would fire at once) * is capped there, so `Infinity` means "as long as a timer can wait"; 0 or * a negative value times out immediately. */ timeout?: number; /** * Re-sends by the bus's rule (`retryClass`): a transient failure (408, 429, * 503) for any method; an uncertain one, or an answer with a declared wait, * only for an idempotent method or an `Idempotency-Key`. `maxAttempts` is * the bus's bound (`RetryOptions`): attempts in total, the first included, * default 3. `false` sends once. Default: **on for a GET through a client, * off for any other method and through `postCommand`**; `{}` turns it on. * While on, an unidentified request (no idempotent method, no key) that got * no reply, a 502 or a 504 is not re-sent and fails with * `context.outcome: 'unknown'`. A re-send waits the declared wait, else the * async bus's schedule: random under 200 ms x 2^n, capped at 20 s * (docs/retry.md). tests/one-client.test.ts. */ retry?: Pick | false; /** External abort signal (e.g. from component unmount) */ signal?: AbortSignal; /** Read the CSRF token from the DOM and attach it as a header. An app header of that name, in any spelling, goes out once with the token. Default: false */ csrf?: boolean; /** * URL to fetch when a CSRF-expiry response (HTTP 419) occurs, to obtain a * fresh token. The default targets the Laravel Sanctum SPA convention * because it's the most common backend issuing 419 - override for other * frameworks, or set to '' to disable the auto-refresh entirely (the lib * will then only re-read the token from the DOM on retry). * Default: '/sanctum/csrf-cookie'. */ csrfCookieUrl?: string; /** Additional headers merged into every request. A name matches in any case: its first spelling is kept and the last value wins (the Fetch Standard's "set"), so it goes out once. */ headers?: Record; /** Called when a 401 session-expired response is received */ onSessionExpired?: (status: number) => void; /** * Stamps `context.silent` on a thrown error so a caller-provided global error * handler can skip it - for fire-and-forget requests (best-effort * telemetry, background prefetch) that shouldn't surface UI noise. * Default: false. */ silent?: boolean; /** * Resolve a 304 Not Modified instead of throwing it. A 304 answers a * conditional request the app sent itself (`If-None-Match`, * `If-Modified-Since`): "what you hold is current", not a failure. Opted * in, the response resolves as it is (`status` 304, `ok` false as Fetch * says, `data` the empty body); off, it throws its `remote:` failure like * any non-2xx. Never cached. Default: false. * tests/http-not-modified.test.ts. */ resolveNotModified?: boolean; }; export type HttpResponse = { data: T; status: number; headers: Record; ok: boolean; /** * The final URL, after any redirect Fetch followed (Fetch's `Response.url`). * Always set by `createHttpClient` and `postCommand`; optional for an app's * own client. */ url?: string; /** True when Fetch followed a redirect to reach `url` (`Response.redirected`). */ redirected?: boolean; /** True when this response was served from a stale (past-fresh) cache entry. */ stale?: boolean; /** Present on a stale hit: resolves with the fresh response once the background revalidation lands. */ revalidation?: Promise>; /** True when this is a retained cache entry served in place of a transient failure (`cache.serveStaleOnError`). */ servedOnError?: boolean; /** The transient error `servedOnError` masked - surfaced alongside the stale data, never silently dropped. */ error?: unknown; }; type CsrfResult = { token: string; headerName: string; }; /** Read CSRF token from DOM: meta tag -> cookie -> hidden input. TTL-cached for 5 min. */ export declare function readCsrfToken(): CsrfResult | null; /** Invalidate the CSRF token cache (e.g. after logout). */ export declare function invalidateCsrfCache(): void; /** * @internal - Retry-After's grammar, for `_declaredWait`. * RFC 9110: `delay-seconds = 1*DIGIT`, else an HTTP-date; anything else is * ignored. `Number()` alone would read `-5`, `1.5`, `1e1`, `0x10` as waits. * No ceiling of its own (Retry-After is a minimum, RFC 9110): each caller * applies its policy. Only a wait no timer can hold is ignored. * tests/retry-after-long.test.ts, tests/retry-after-grammar.test.ts. */ export declare function _parseRetryAfter(header: string | null | undefined): number | undefined; export type CombinedSignal = { signal: AbortSignal; detach: () => void; }; /** * @internal - `AbortSignal.any([a, b])`, and the same result where a platform * lacks it (Chrome before 116, Firefox before 124, Safari before 17.4): an * input already aborted gives a result already aborted, else the first input * to abort aborts it, each with that input's `reason`. The client, the * transports, the bus's tickets and supersede combine through it * (tests/combine-signals.test.ts). * * The native result's listeners are the platform's: nothing to detach. The * fallback's sit on both inputs until one aborts; a caller whose result * outlives its use (one request on a transport's signal) calls `detach` when it * settles, or they accrete once per request. */ export declare function _combineSignals(a: AbortSignal, b: AbortSignal): CombinedSignal; /** @internal - a wait the signal cuts short with a rejection: the client's re-send and a transport's poll. */ export declare function _sleepMs(ms: Delay, signal?: AbortSignal): Promise; /** * @internal - a request body as JSON, or the failure that says it cannot be * one: `transport:invalid:json` (a BigInt, a cycle; the platform's TypeError * is its cause). Nothing was sent, and `invalid` is never re-sent. Returned, * not thrown, so each caller settles it its own way. The client, postCommand * and every bridge encode through it (tests/invalid-json.test.ts). */ export declare function _encodeJson(value: unknown, url: string, action?: string): string | BusError; /** * @internal - the failure a backend declared: `remote::`, the * condition from the problem's own `status` (else the response's), `detail` the * message, the rest `context`. `retryIn` is the response's `Retry-After` (RFC * 9110), never a body member: it is set after the spread, so a body cannot * supply it. A batched result or a frame has no response of its own: the * `headers` it carries stand for one (OData JSON batch; transports.ts, * answerOf). One reader for the client and every bridge (log s35.131). */ export declare function _remoteProblem(p: ProblemDetails, status?: number, retryIn?: number): BusError; /** @internal - a non-2xx: its problem, or, for a body that is not one, the status alone. */ export declare function _answered(status: number, data: unknown, headers?: Record): BusError; /** * @internal - the wait an answer declares, its `context.retryIn`: Retry-After * (RFC 9110 10.2.3), else the RateLimit field's `t` seconds for a policy with * no quota left (`r=0`), else `X-RateLimit-Reset` (docs/retry.md). * draft-ietf-httpapi-ratelimit-headers-11: a List of items, each * `"policy";r=;t=`. Retry-After "MUST take precedence". Names in lower * case. The one reader: the client and every bridge, through `_answered`, and * a batched result's own headers. tests/declared-wait.test.ts. */ export declare function _declaredWait(headers: Record): number | undefined; /** * @internal - headers an app's own client or a batched result carries, read * as a response's: names in lower case (RFC 9110 5.1), the first spelling * kept, string values only. The client's own are lower case already * (`headersToObject`). tests/declared-wait.test.ts, tests/batch-retry-after.test.ts. */ export declare function _headersOf(headers: unknown): Record | undefined; /** * @internal - one header of those `_headersOf` reads, by its lower-case name, * with no copy: `_headersOf`'s rule (any case, the first spelling, a string * value) for one name. A 202's answer reads only its `Location`: the copy cost * every 202 about 115 ns (log 36.49). tests/accepted.test.ts. */ export declare function _headerOf(headers: unknown, name: string): string | undefined; /** * @internal - the groups a `Cache-Groups` or `Cache-Group-Invalidation` field * names (RFC 9875): a Structured Field List of Strings (RFC 9651). Parameters * and a member that is not a String are skipped unread. A String that does not * parse, two members with no comma, a trailing comma or an inner list ignore * the field whole (RFC 9651 4.2: a failed parse ignores the field). * The one reader: the client, * the transports and fetchLoaders. tests/cache-groups.test.ts. */ export declare function _groupsOf(value: string | undefined): string[]; export declare function postCommand(url: string, body: unknown, config?: HttpConfig): Promise>; /** * @internal - postCommand with its body already JSON: a batching transport * joins its commands' parts. `retry` is the re-sends, already read: a * transport sends once (the bus re-sends), so it reads no `retry` option. * Not `async`: it returns runWithRetry's promise itself, and a throw in its * body is a rejection by its `try` (tests/post-json-turns.test.ts). */ export declare function _postJson(url: string, serialized: string, config?: HttpConfig, retry?: number): Promise>; /** * @internal - one GET outside a client: the client's headers (`X-Requested-With` * kept, log 36.47) and its 30 s, the command's fetch and JSON reader, so a body * that is not JSON (a sign-in page) fails as `remote:unexpected:json`, and the * one loop, with no re-send. A transport's poll of a status monitor (src/accepted.ts). */ export declare function _getJson(url: string, config: HttpConfig): Promise>; export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; export type ResponseType = 'json' | 'blob' | 'text'; export type HttpRequestConfig = HttpConfig & { /** HTTP method. Default: 'GET' */ method?: HttpMethod; /** Request body (auto-serialized if object, passthrough for FormData) */ data?: unknown; /** Query parameters - supports arrays and nested objects */ params?: Record; /** Base URL prepended to relative paths */ baseURL?: string; /** Response parsing mode. Default: 'json' */ responseType?: ResponseType; /** * Enable LRU caching for GET. `true` = default TTL, no stale window. * `{ ttl }` sets the fresh-window duration. `{ staleTtl }` opts into * stale-while-revalidate: a hit within `ttl + staleTtl` past `ttl` is * served instantly with `{ stale: true, revalidation: Promise }` attached, * while a background fetch refreshes the entry. `serveStaleOnError` is a * separate opt-in: a transient failure (timeout/network/5xx) with ANY * retained entry (even past its stale window) resolves to * `{ stale: true, servedOnError: true, error }` instead of rejecting. */ cache?: boolean | { ttl?: number; staleTtl?: number; serveStaleOnError?: boolean; }; /** * Enable request deduplication for GET. Default: true. A concurrent GET * of the same URL joins the one in flight and shares its outcome, but * keeps its own `signal`: aborting it rejects that caller's promise only. * The fetch is cancelled once every caller holding it has aborted; a * caller without a signal holds it until it lands. * (`tests/http-dedupe-signal.test.ts`) A `silent` read and one without * `silent` are two requests, even at the same moment: joined, they would * share one failure, and one caller's `silent` mark would reach the other * (`tests/silent-dedupe.test.ts`). */ dedupe?: boolean; /** * Fetch's cache mode for this request (`RequestInit.cache`), for the * browser's cache and the client's own store (`cache`) alike. `'no-cache'` * asks the server before a stored copy is used, sending its `ETag`: a router * refresh reads so. `'reload'` reads past a stored copy and stores the * answer. `'no-store'` neither reads nor stores. Absent: Fetch's default. A * read in one mode never joins a read in another. * tests/http-cache-mode.test.ts, tests/cache-groups.test.ts. */ cacheMode?: RequestCache; /** @internal marks a CSRF-retried request */ _csrfRetried?: boolean; }; /** * A `safe` helper's outcome: it never throws. `error` is the failure the call * would have thrown, the core's `BusError` (`conditionOf(error)`, and * `problemOf(error)` for the backend's RFC 9457 problem). One exception: an * app's interceptor that throws reaches it as it was thrown, as an app's own * throw does everywhere (docs/contract.md rule 8). `status` is 0 when there * was no response. */ export type SafeResult = { data: T | null; error: BusError | null; status: number; }; export type DownloadResult = { data: Blob; status: number; filename: string; }; export type Interceptor = { onFulfilled?: (value: T) => T | void; onRejected?: (error: unknown) => void; }; export type InterceptorManager = { use(onFulfilled?: (value: T) => T | void, onRejected?: (error: unknown) => void): number; eject(id: number): void; }; export type HttpClient = { get(url: string, config?: HttpRequestConfig): Promise>; post(url: string, data?: unknown, config?: HttpRequestConfig): Promise>; put(url: string, data?: unknown, config?: HttpRequestConfig): Promise>; patch(url: string, data?: unknown, config?: HttpRequestConfig): Promise>; delete(url: string, config?: HttpRequestConfig): Promise>; request(url: string, config?: HttpRequestConfig): Promise>; download(url: string, filename?: string, config?: HttpRequestConfig): Promise; safe: { get(url: string, config?: HttpRequestConfig): Promise>; post(url: string, data?: unknown, config?: HttpRequestConfig): Promise>; put(url: string, data?: unknown, config?: HttpRequestConfig): Promise>; patch(url: string, data?: unknown, config?: HttpRequestConfig): Promise>; delete(url: string, config?: HttpRequestConfig): Promise>; }; interceptors: { request: InterceptorManager; response: InterceptorManager; }; create(defaults?: Partial): HttpClient; clearCache(): void; /** * Drop the cached reads whose response named one of `groups` in its * `Cache-Groups` (RFC 9875), and tell each group to `onInvalidateGroup`'s * listeners. `groups`: the names, or a `Cache-Group-Invalidation` field * value as received. A write's answer runs it, and a transport runs it for a * batched result's or a frame's field, so the field reader stays in the * client. tests/cache-groups.test.ts. */ invalidateGroups(groups: readonly string[] | string): void; /** * Hear each group the client invalidates. A listener's throw is logged and * the rest still hear. Returns the unsubscribe. The router listens here. */ onInvalidateGroup(listener: (group: string) => void): () => void; }; import { type Delay } from './bounds'; import { type ProblemDetails } from './http-errors'; import { BusError } from './failure'; import type { RetryOptions } from './command-bus'; /** * createHttpClient - multi-method HTTP client with interceptors, caching, * deduplication, safe mode, and file download. * * Framework-agnostic - no Vue imports. * * @example * const http = createHttpClient({ baseURL: '/api', csrf: true }); * * // All methods * const users = await http.get('/users', { params: { page: 1 } }); * await http.post('/cart', { itemId: 1, qty: 2 }); * await http.put('/cart/1', { qty: 5 }); * await http.delete('/cart/1'); * * // Safe mode - never throws * const result = await http.safe.post('/login', credentials); * if (result.error) console.log(result.error.message); * * // File download * await http.download('/export/csv', 'products.csv'); * * // Interceptors * http.interceptors.request.use((config) => { config.headers = { ...config.headers, 'X-Custom': '1' }; return config; }); * * // Create scoped instance * const adminHttp = http.create({ baseURL: '/admin/api', headers: { 'X-Admin': 'true' } }); */ export declare function createHttpClient(instanceDefaults?: Partial): HttpClient; /** * @internal One group namespace's hub (RFC 9875): every source calls * `invalidateGroups`, every reader listens with `onInvalidateGroup`. A client * is one, and a bus's transport client is that bus's hub; a bus with no * client gets its own from its first reader (`cache()`). */ export type GroupHub = Pick; /** * @internal A hub: `drop` first, with the groups (a client's stored reads), * then each listener per group. A listener's throw is logged and the rest * still hear. No listener emits, so nothing loops. * tests/cache-groups.test.ts, tests/cache-groups-hub.test.ts. */ export declare function _groupHub(drop?: (groups: readonly string[]) => void): GroupHub; /** * @internal - `client` with `defaults` under every call, as `create` merges * them (the call wins, headers by name), but on `client`'s own state: its * cache, its in-flight reads and its interceptors. A write through either * invalidates a read cached through the other: one client. * `routerHttp({ http })` (router/remote.ts). tests/router/one-client.test.ts. */ export declare function _withDefaults(client: HttpClient, defaults: Partial): HttpClient; export {}; //# sourceMappingURL=http.d.ts.map