This site counts visits with analytics cookies only if you accept. Read the consent

Skip to content

API ReferenceTypes

Types

Complete reference for all TypeScript types exported by @noverax/courier.

6 min readUpdated both modes

Overview

All TypeScript types used across the Courier library, organized by category.

Client Types

TypedClient

The main typed client returned by createCaller and createProxyCaller. Provides dot-notation access to groups, .raw for full response, and .with() for per-request options.

ts
type TypedClient<T extends DefinedApi<any>, Raw extends boolean = false> = {
  [K in keyof ApiGroups<T>]: GroupClient<ApiGroups<T>[K], Raw>
} & {
  raw: TypedClient<T, true>
  with(options: WithOptions): TypedClient<T, Raw>
}

GroupClient

A group with typed endpoint methods, .raw accessor, and .with(): one method per endpoint of the group, typed from its variables and response, beside these two.

ts
type GroupClient<G, Raw extends boolean = false> = {
  // …one method per endpoint of G…
  raw: GroupClient<G, true>
  with(options: WithOptions): GroupClient<G, Raw>
}

WithOptions

Options for .with() — all CallOptions except rawData (controlled via .raw).

ts
type WithOptions = Omit<CallOptions, "rawData">

CallerDefaults

Options for createCaller.

ts
type CallerDefaults = {
  timeout?: number
  cancelPrevious?: boolean
  headers?: Record<string, string>
  context?: Context
  onError?: (error: RequestFailure) => void | Promise<void>
  onSuccess?: (data: unknown) => void | Promise<void>
}

ProxyCallerOptions

Options for createProxyCaller and createProxyQueryCaller, which take them after the routes of an API.

ts
type ProxyPath = {
  http?: string  // default: "/api/request"
  sse?: string   // default: "/api/sse"
  ws?: string    // no default — throws if WS endpoint invoked without it
}

type ProxyCallerOptions = {
  proxyPath?: ProxyPath
  timeout?: number
  cancelPrevious?: boolean
  coalesce?: boolean
  credentials?: RequestCredentials
  headers?: Record<string, string>
  onError?: (error: RequestFailure) => void | Promise<void>
  onSuccess?: (data: unknown) => void | Promise<void>
  ws?: CallerWSOptions
}

CourierRoutes

The routes of one API that a page's proxy client takes: the source the server registered it as, and each endpoint a page may call, by its path, with how the page reaches it. Courier's plugin for your build gives them to the page, as routes from @noverax/courier/routes, from the endpoints marked .expose() — or Courier writes them into courier.routes.ts; see Exposing Endpoints.

ts
import type { CourierRoutes, RouteMap, RouteShape } from "@noverax/courier/define"

// RouteShape: { type: "query"; get?: true; cancelPrevious?: boolean } | { type: "mutation" }
//           | { transport: "sse" } | { transport: "ws"; bidirectional?: true }
// RouteMap<TApi>: the paths of TApi, each in the shape the API declares it
// CourierRoutes<TApi, TEndpoints>: { source, endpoints, cancelPrevious?, coalesce? }

Endpoint Definition Types

Endpoint Types

An endpoint is an inert descriptor, not a callable. One of three types names it, according to the head it was built from:

ts
import type {
  AnyEndpoint,      // any of the three, when the kind does not matter
  ChannelEndpoint,  // ChannelEndpoint<Response, Variables, Send, VariablesOut?, Expose?>
  HttpEndpoint,     // HttpEndpoint<Response, Variables, Kind extends "query" | "mutation", VariablesOut?, Expose?>
  StreamEndpoint,   // StreamEndpoint<Response, Variables, VariablesOut?, Expose?>
} from "@noverax/courier/define"

VariablesOut is what the variables are once their schema has parsed them: the variables themselves, where it is left out. Expose is the endpoint's own .expose() mark — true, false, or undefined where the group or the API above decides; left out, it may be any of them, so a type written without it reads as an endpoint a page may call, and the routes Courier's plugin builds offer it.

Inference Helpers

Read the types back off an endpoint. This is how a caller knows what a method takes and returns:

ts
import type { InferClient } from "@noverax/courier/client" // InferClient<TApi>: the client createCaller(api) returns
import type {
  InferKind,          // InferKind<E>: "query" | "mutation" | "stream" | "channel"
  InferResponse,      // InferResponse<E>: what the endpoint resolves to
  InferSend,          // InferSend<E>: what a channel accepts from the client
  InferVariables,     // InferVariables<E>: what the caller must pass
  InferVariablesOut,  // InferVariablesOut<E>: what its closure receives, once a schema has validated the call
} from "@noverax/courier/define"

The clients infer all of this themselves; name a type with these helpers where one is needed elsewhere — a component's props, a test's fixture.

Wire Surfaces

The object .via() hands the closure. Name these to lift a closure out of the chain into a function of its own. The closure runs as the endpoint is defined, against a recorder, and again on every call and every retried attempt — a stream's or a channel's for each subscription — so it describes the request and does nothing else:

ts
interface HttpWire {
  get(path?: string, variables?: unknown, options?: MethodOptions<"get">): WireCall<"query">
  post(path?: string, body?: unknown, options?: MethodOptions<"post">): WireCall<"mutation">
  put(path?: string, body?: unknown, options?: MethodOptions<"put">): WireCall<"mutation">
  patch(path?: string, body?: unknown, options?: MethodOptions<"patch">): WireCall<"mutation">
  del(path?: string, variables?: unknown, options?: MethodOptions<"del">): WireCall<"mutation">
  head(path?: string, options?: MethodOptions<"head">): WireCall<"query">
  options(path?: string, variables?: unknown, options?: MethodOptions<"options">): WireCall<"query">
  query(path?: string, body?: unknown, options?: MethodOptions<"query">): WireCall<"query">
  /** A path with values put into it, each sent as text: http.path`reports/${year}` */
  path(strings: TemplateStringsArray, ...values: unknown[]): string
}

interface StreamWire {
  get(path?: string, variables?: unknown, options?: MethodOptions<"get">): WireCall<"query">
  path(strings: TemplateStringsArray, ...values: unknown[]): string
}

interface ChannelWire {
  connect(path?: string, variables?: unknown, options?: MethodOptions<"get">): WireCall<"query">
  path(strings: TemplateStringsArray, ...values: unknown[]): string
}

type WireKind = "query" | "mutation"
/** What a verb hands back — opaque, marked with whether it reads ("query") or writes ("mutation"). */
interface WireCall<Kind extends WireKind = WireKind> {}

type HttpProbe<Variables, Call extends WireCall = WireCall> = (http: HttpWire, variables: Variables) => Call
type StreamProbe<Variables> = (sse: StreamWire, variables: Variables) => WireCall
type ChannelProbe<Variables> = (ws: ChannelWire, variables: Variables) => WireCall

The mark is how .via() knows whether its endpoint reads or writes. A closure lifted out of the chain keeps it when its return type is left to be inferred:

ts
import type { HttpProbe, HttpWire } from "@noverax/courier/define"

const byId = (http: HttpWire, vars: { id: string }) => http.get(":id", vars)
const getById = endpoint.variables<{ id: string }>().via(byId).response<User>() // a read

// Typed HttpProbe<Variables>, a closure no longer says which verb it calls, so its endpoint does
const byIdTyped: HttpProbe<{ id: string }> = (http, vars) => http.get(":id", vars)
const getByIdTyped = endpoint.variables<{ id: string }>().via(byIdTyped).reads().response<User>()

ViaAddressed<Call, …> is what .via() gives for a closure returning Call. For a closure that calls a reading verb on one path and a writing verb on another, or one whose type does not say, it is an HttpKindUnnamed — no endpoint until .reads() or .writes() names its kind, and refused by a group with that reason.

Answer Stages

What .map() takes. Name these to write a stage once and map the answers of several endpoints with it — see Mapping the answer:

ts
/** What a stage is told of the answer besides its data */
interface AnswerHead {
  readonly status: number
  readonly headers: Headers
}

/** A stage: the data the schema checked, or the stage before gave, mapped to what the next one gets */
type AnswerMap<Data, Out> = (data: Data, answer: AnswerHead) => Out | Promise<Out>

Response Types

HttpResponse

ts
type HttpResponse<T = unknown> = {
  status: number    // HTTP status code
  headers: Headers  // Response headers
  data: T           // Parsed response body
}

Proxied

What a page receives of a value through the proxy, which sends it on as JSON: what each call of a proxy client resolves to, and each event it is told. A type JSON keeps whole is itself; any other is what JSON gives back of it — see Mapping the answer.

ts
import type { Proxied } from "@noverax/courier/define"

type Row = Proxied<{ id: string; at: Date; tags: Set<string> }>
// { id: string; at: string; tags: Record<string, never> }
type Same = Proxied<{ id: string; name?: string }> // { id: string; name?: string }
type Json = string | number | boolean | null | Json[] | { [key: string]: Json }
type Settings = Proxied<Json> // Json, a recursive type JSON keeps whole
type Bytes = Proxied<Uint8Array> // ArrayBuffer: bytes travel as themselves

Options Types

CallOptions

Per-request options passed when calling an endpoint.

ts
type CallOptions<R extends boolean = false> = Omit<RequestInit, "method" | "body"> & {
  timeout?: number
  responseType?: "json" | "text" | "blob" | "arrayBuffer" | "formData"
  onDownloadProgress?: (progress: { percent: number; transferredBytes: number; totalBytes: number }) => void
  onUploadProgress?: (progress: UploadProgress) => void
  rawData?: R
  forwardVariables?: boolean
  stream?: boolean
  method?: "GET" | "POST"
  coalesce?: boolean
  cancelPrevious?: boolean
}

headers, signal, credentials and the rest of RequestInit are passed to fetch; method is the verb a call goes to the proxy with, not the endpoint's own. coalesce and cancelPrevious say for this call alone whether it joins an identical read in flight, and whether it cancels the older call of its read in flight and may be cancelled by a newer one — see Deduplication & Abort.

UploadProgress

ts
type UploadProgress = {
  percent: number           // 0 to 1
  transferredBytes: number
  totalBytes: number
}

MethodParameters

ts
type MethodParameters<T extends HttpMethod> = T extends "head"
  ? [url?: string, options?: MethodOptions<T>]
  : [url?: string, variables?: Record<string, unknown>, options?: MethodOptions<T>]

Source & Config Types

BaseOptions

Core configuration for defineApi().

ts
type BaseOptions = MergeOptions & FetchOptions & {
  baseURL?: string
  responseType?: ResponseType
  responseParser?: ResponseParser
  defaultBody?: Record<string, unknown>
  defaultQueryParams?: Record<string, unknown>
  allowedHeaders?: string[]
  bodySerializer?: (data: Record<string, unknown>) => BodyInit
  searchParamsSerializer?: SearchParamsSerializer
  cancelPrevious?: boolean
  middleware?: Middleware[]
  expose?: boolean
  proxyPath?: ProxyPath
}

GroupOptions

ts
type GroupOptions = MergeOptions & {
  prefix?: string
  expose?: boolean
  cancelPrevious?: boolean
}

ResponseType

ts
type ResponseType = "json" | "text" | "blob" | "arrayBuffer" | "formData"

ResponseParser

ts
type ResponseParser = (
  body: unknown,
  answer: { readonly status: number; readonly headers: Headers },
) => unknown

A source's responseParser: handed the body as the source's responseType reads it — JSON already parsed, null for an empty body, the text of an error answer that is no JSON — and the answer's status and headers, it returns what the call resolves to, or a promise of it.

SearchParamsSerializer

ts
type SearchParamsSerializer = {
  stringify: (obj: Record<string, unknown>) => string
  parse: (str: string) => Record<string, unknown>
}

Context

ts
type Context = {
  req?: Request
  res?: Response
  headers?: Headers
  proxyMethod?: "GET" | "POST"
}

PathOptions

ts
type PathOptions = (request?: Request) =>
  Record<string, boolean | number | string | null | undefined> | undefined
  | Promise<Record<string, boolean | number | string | null | undefined> | undefined>

Middleware Types

Middleware

ts
type Middleware =
  | { name: string; phase: "before"; handler: BeforeHandler }
  | { name: string; phase: "after"; handler: AfterHandler }
  | { name: string; phase: "wrap"; handler: WrapHandler }

defineMiddleware(name, phase, handler) builds one — see Middleware.

MiddlewareContext

ts
type MiddlewareContext = {
  source: string
  group?: string
  method: string
  variables?: unknown
  headers: Headers
  transport?: "http" | "sse" | "ws"
  request?: Request
  kind?: "query" | "mutation"
  carriesSession?: boolean
  sessionPartition?: string
  signal?: AbortSignal
  purpose?: CallPurpose
}

type CallPurpose = "csrf-token"

purpose is set on a request the session makes rather than an endpoint's call — "csrf-token" for the double-submit token a write asks for — whose method names no endpoint. See Middleware for each field.

MiddlewareResponse

ts
type MiddlewareResponse = {
  status: number
  data: unknown
  headers: Headers
}

NextFn

ts
type NextFn = () => Promise<MiddlewareResponse>

React Query Types

ts
type QueryOptions<R, V> = WithVariables<V> &
  Omit<UseQueryOptions<R, Error, R, QueryKey>, "queryKey" | "queryFn"> & {
    requestOptions?: CallOptions
  }

type MutationOptions<R, V> = Omit<
  UseMutationOptions<R, Error, MutationVariables<V>>,
  "mutationFn"
> & {
  requestOptions?: CallOptions
}

type MutationVariables<V> = [V] extends [undefined]
  ? void
  : {} extends V ? void | V : V

type WithVariables<V> = [V] extends [undefined]
  ? { variables?: undefined }
  : {} extends V
    ? { variables?: V }
    : { variables: V }