Askr documentation
Generated API snapshot

@askrjs/fetch

Exports from the declarations published in @askrjs/fetch. Signatures reflect the published artifact.

Exports

This entrypoint publishes 47 exports. Use the anchored symbol rows for direct links. Type-only exports are labeled separately from runtime values.

AdHocCalltype

AdHocCall: any

A one-off, untyped request description accepted by {@link createFetch}'s returned function.

url
url: string;
method
method?: string;
headers
headers?: HeadersInit;
query
query?: Record<string, unknown>;
querySpec
querySpec?: ParameterMap;
body
body?: unknown;
bodyCodec
bodyCodec?: Codec;
bodyMediaType
Explicit media type used to encode a request body with a multi-variant `content()` codec.
response
response?: Codec;
responses
responses?: Readonly<Record<number, Codec>>;
errors
errors?: Partial<Record<number | "default", Codec>>;
signal
signal?: AbortSignal;
timeout
timeout?: number;
endpoint
endpoint?: EndpointDescriptor;
operationId
operationId?: string;

AnyEndpointDescriptortype

AnyEndpointDescriptor: EndpointDescriptor<any, any, any, any, any, any>

An {@link EndpointDescriptor} with its type parameters erased, for use in generic contexts.

ApiClienttype

ApiClient: Readonly<{ [K in keyof A["endpoints"]]: ClientMethod<A["endpoints"][K]>; }>

A fully-typed client for an {@link ApiDefinition}, with one method per endpoint.

ApiDefinitiontype

ApiDefinition: any

A named collection of endpoints plus optional API metadata, as produced by {@link defineApi }.

endpoints
readonly endpoints: E;
metadata
readonly metadata?: ApiMetadata;

ApiMetadatatype

ApiMetadata: any

API-level (rather than per-endpoint) metadata, such as servers and security schemes.

servers
readonly servers?: readonly (string | { readonly url: string; })[];
tags
readonly tags?: readonly unknown[];
securitySchemes
readonly securitySchemes?: Readonly<Record<string, unknown>>;

arrayBuffertype

arrayBuffer: () => Codec<ArrayBuffer>

Creates a codec that decodes any response body as an `ArrayBuffer`.

blobtype

blob: () => Codec<Blob>

Creates a codec that decodes any response body as a `Blob`.

ClientOptionstype

ClientOptions: any

Options controlling how a {@link createClient } or {@link createFetch } client makes requests.

baseUrl
baseUrl?: string;
fetch
Custom transport, defaulting to the global `fetch`.
headers
headers?: HeadersInit;
credentials
credentials?: RequestCredentials;
timeout
Request timeout in milliseconds.
middleware
Middleware chain applied to every request, in order.

ClientResulttype

ClientResult: Successes<D> | Errors<D> | FailureResult

The possible results of calling a typed client method for endpoint descriptor `D`.

Codectype

Codec: any

Describes how a request or response body is serialized/deserialized: which wire format (`kind`), which media types it matches, and optionally a {@link Validator} to parse/validate the decoded value.

kind
readonly kind: "json" | "text" | "urlEncoded" | "multipart" | "blob" | "arrayBuffer" | "stream" | "empty" | "content";
mediaTypes
readonly mediaTypes: readonly string[];
validator
readonly validator?: Validator<T>;
variants
For `kind: "content"`, the per-media-type codec variants.

contenttype

content: <T extends Record<string, Codec>>(variants: T) => Codec<{ [K in keyof T]: T[K] extends Codec<infer V> ? V : never; }[keyof T]>

Creates a content-negotiated codec that selects among `variants` by the response's media type, decoding with whichever variant matches.

createClienttype

createClient: <A extends ApiDefinition>(api: A, options?: ClientOptions) => ApiClient<A>

Builds a typed {@link ApiClient} from an {@link ApiDefinition}. Each endpoint becomes a method that fills in the path, query, header, and body parameters, executes the request via {@link createFetch}, and returns a {@link ClientResult}.

createFetchtype

createFetch: (options?: ClientOptions) => (call: AdHocCall) => Promise<FetchResult>

Creates a low-level fetch function that builds a `Request` from an {@link AdHocCall}, runs it through the configured middleware chain, and decodes the response with the matching codec. Used internally by {@link createClient}, and usable directly for requests without a full {@link EndpointDescriptor}.

defineApitype

defineApi: <E extends Record<string, AnyEndpointDescriptor | EndpointBuilder>>(endpoints: E, metadata?: ApiMetadata) => ApiDefinition<Defined<E>>

Finalizes a map of {@link EndpointBuilder}s and/or raw {@link EndpointDescriptor}s into a frozen {@link ApiDefinition}, stamping each endpoint's `operationId` from its key and deep-freezing its parameters, security, responses, and errors.

const api = defineApi({
  getUser: get("/users/{id}").returns(json()),
});

deltype

del: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>

Starts building a DELETE endpoint at the given path.

emptytype

empty: () => Codec<undefined>

Creates a codec for bodies expected to be empty (e.g. 204 No Content), decoded as `undefined`.

EndpointBuildertype

EndpointBuilder: any

Fluent, immutable builder for describing a single endpoint's params, query, headers, body, responses, errors, and security requirements. Each method returns a new builder reflecting the added configuration; the accumulated state is finalized into an {@link EndpointDescriptor} by {@link defineApi}.

params
Declares path parameter types and optional runtime validators. Generic types are erased; runtime validation occurs only for entries whose specification includes a validator.
query
query<T extends Record<string, unknown>>(spec?: ParameterMap): EndpointBuilder<P, T, H, B, R, E>;
headers
headers<T extends Record<string, unknown>>(spec?: ParameterMap): EndpointBuilder<P, Q, T, B, R, E>;
body
body<C extends Codec>(codec: C): EndpointBuilder<P, Q, H, C extends Codec<infer T> ? T : never, R, E>;
returns
returns<C extends Codec>(codec: C): EndpointBuilder<P, Q, H, B, R & Record<200, C>, E>;
returns
returns<S extends number, C extends Codec>(status: S, codec: C): EndpointBuilder<P, Q, H, B, R & Record<S, C>, E>;
errors
errors<T extends Errors>(spec: T): EndpointBuilder<P, Q, H, B, R, E & T>;
security
security(requirements: readonly Readonly<Record<string, readonly string[]>>[]): EndpointBuilder<P, Q, H, B, R, E>;

EndpointDescriptortype

EndpointDescriptor: any

Describes a single API endpoint: its method, path, parameters, body, and possible responses.

method
readonly method: HttpMethod;
path
readonly path: string;
params
readonly params?: ParameterMap;
query
readonly query?: ParameterMap;
headers
readonly headers?: ParameterMap;
body
readonly body?: Codec;
responses
readonly responses: Readonly<R>;
errors
readonly errors: Readonly<E>;
security
readonly security?: readonly Readonly<Record<string, readonly string[]>>[];
operationId
readonly operationId?: string;
__input
readonly __input?: { params: P; query: Q; headers: H; body: B; };

FailureKindtype

FailureKind: "request" | "network" | "timeout" | "abort" | "decode" | "middleware"

Categorizes why a fetch could not produce an {@link HttpResult} or {@link SuccessResult}.

FailureResulttype

FailureResult: {
  ok: false;
  kind: FailureKind;
  status: number;
  error: unknown;
  headers: Headers;
  url: string;
  response?: Response;
}

A fetch outcome that failed before or independently of receiving a decodable HTTP response.

FetchErrortype

FetchError: typeof FetchError

An `Error` thrown by {@link unwrap} that wraps a failed (non-`ok`) {@link FetchResult}.

result
readonly result: Exclude<FetchResult, { ok: true; }>;

FetchResulttype

FetchResult: SuccessResult<T> | HttpResult<T> | FailureResult

The outcome of a fetch call: success, an HTTP-level error, or another kind of failure.

gettype

get: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>

Starts building a GET endpoint at the given path.

HttpMethodtype

HttpMethod: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"

The set of HTTP methods supported by endpoint descriptors.

HttpResulttype

HttpResult: {
  ok: false;
  kind: "http";
  status: S;
  error: T;
  mediaType: string | null;
  headers: Headers;
  url: string;
  response: Response;
}

A non-2xx fetch outcome where the server responded with a decodable error body.

InferCodectype

InferCodec: C extends Codec<infer T> ? T : never

Infers the decoded value type `T` from a {@link Codec}.

InferValidatortype

InferValidator: V extends Validator<infer T> ? T : never

Infers the parsed output type `T` from a {@link Validator}.

jsontype

json: { <T = unknown>(): Codec<T>; <V extends Validator>(schema: V): Codec<V extends Validator<infer T> ? T : never>; }

Creates a JSON codec, matching `application/json` and `+json` suffixed media types. Creates a JSON codec that validates/parses the decoded value with the given schema.

Middlewaretype

Middleware: (context: RequestContext, next: Next) => Promise<FetchResult>

A function that can inspect/replace the request context and/or the result of calling `next`.

multiparttype

multipart: () => Codec<FormData>

Creates a codec for `multipart/form-data` bodies, decoded as `FormData`.

Nexttype

Next: (context?: RequestContext) => Promise<FetchResult>

Invokes the next middleware in the chain, optionally passing a replacement context.

optionstype

options: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>

Starts building an OPTIONS endpoint at the given path.

ParameterMaptype

ParameterMap: Readonly<Record<string, Validator<unknown> | ParameterSpec | undefined>>

Maps parameter names to either a bare {@link Validator} or a full {@link ParameterSpec} describing serialization and validation.

ParameterSpectype

ParameterSpec: any

Serialization and validation settings for a single path, query, or header parameter.

validator
readonly validator?: Validator<T>;
style
readonly style?: ParameterStyle;
explode
readonly explode?: boolean;

ParameterStyletype

ParameterStyle: "simple" | "label" | "matrix" | "form" | "spaceDelimited" | "pipeDelimited" | "deepObject"

OpenAPI-style serialization styles for path, query, and header parameters.

patchtype

patch: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>

Starts building a PATCH endpoint at the given path.

pathNamestype

pathNames: (path: string) => string[]

Extracts the ordered list of `{param}` placeholder names from an endpoint path.

posttype

post: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>

Starts building a POST endpoint at the given path.

puttype

put: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>

Starts building a PUT endpoint at the given path.

RequestContexttype

RequestContext: any

The mutable-by-replacement state threaded through the middleware chain for a single request.

request
readonly request: Request;
endpoint
readonly endpoint?: AnyEndpointDescriptor;
operationId
readonly operationId?: string;
security
readonly security?: AnyEndpointDescriptor["security"];
attempt
1 on the first attempt, incremented by middleware (e.g. {@link retry }) on subsequent attempts.
replayableBody
Whether a body was encoded from a replayable value; streaming bodies set this to `false`.
deadline
Absolute timestamp (ms since epoch) by which the request must complete, if a timeout is set.

streamtype

stream: () => Codec<ReadableStream<Uint8Array>>

Creates a codec that exposes the raw response body as a `ReadableStream`, without buffering it.

SuccessResulttype

SuccessResult: {
  ok: true;
  kind: "success";
  status: S;
  data: T;
  mediaType: string | null;
  headers: Headers;
  url: string;
  response: Response;
}

A successful (2xx) fetch outcome, carrying the decoded response data.

texttype

text: () => Codec<string>

Creates a codec for plain text bodies (`text/*`), decoded as a string.

unwraptype

unwrap: <T>(result: FetchResult<T>) => T

Returns the data of a successful {@link FetchResult}, or throws a {@link FetchError} wrapping the result if it was not `ok`.

urlEncodedtype

urlEncoded: () => Codec<URLSearchParams>

Creates a codec for `application/x-www-form-urlencoded` bodies, decoded as `URLSearchParams`.

Validatortype

Validator: any

A minimal schema-validation contract, compatible with libraries such as Zod that expose a `safeParse` method (e.g. via a thin adapter).

safeParse
safeParse(value: unknown): { success: true; data: T; } | { success: false; error: unknown; };