# Fetch (https://effetch.pages.dev/docs/reference/fetch)

`@monarcode/effetch` exports one name, the `Fetch` namespace. Its members, grouped by the guide that covers them:

```ts
import { Fetch } from "@monarcode/effetch";
```

## Clients

Guide: [Declare a client](https://effetch.pages.dev/docs/clients).

### Fetch.isService

Returns `true` if `u` is a class made by [`Service`](https://effetch.pages.dev/docs/reference/fetch#service), or a class that extends one. `false` for anything else, including a key made with `Context.Service` and a [`Client`](https://effetch.pages.dev/docs/reference/fetch#client).

### Fetch.make

Makes a [`Client`](https://effetch.pages.dev/docs/reference/fetch#client).

### Fetch.Service

Declares a client as a service class: one class that is the client's service key, its layer and its config.

### Fetch.Client

A client made by [`make`](https://effetch.pages.dev/docs/reference/fetch#make). Every call returns an Effect that needs no services, apart from those its schemas require (the call's or endpoint's own, and the client's `defaultError` and `statusErrors`), and that can fail with the plugins' errors and the `statusErrors` that apply, on top of Effetch's own.

| Prop           | Type       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| -------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `httpClient`   | `object`   | The configured `HttpClient` underneath. It adds the base URL and the default headers to the requests you give it and runs every plugin with its defaults, but does no status check, no decoding, no `statusErrors` and no `onError` hooks. Transport failures are `NetworkError`s, next to the plugins' own errors. Use it for what the methods don't cover, such as a response you read yourself. For a streamed body, use Client.sse or Client.ndjson.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `statusErrors` | `SE`       | The `statusErrors` the client was made with, as a frozen copy, or `undefined` without any. They apply to every call, after the call's or the endpoint's own.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `request`      | `function` | Sends a request with any HTTP method, for a method only known at runtime. The other methods are shorthand for this one. A `GET` or `HEAD` request can't have a body: passing one dies.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `get`          | `function` | Sends a `GET` request. Takes no body.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `head`         | `function` | Sends a `HEAD` request. Takes no body.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `options`      | `function` | Sends an `OPTIONS` request. Takes no body.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `post`         | `function` | Sends a `POST` request. `body` is sent according to its type, or encoded with `input` when given.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `put`          | `function` | Sends a `PUT` request. `body` is sent according to its type, or encoded with `input` when given.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `patch`        | `function` | Sends a `PATCH` request. `body` is sent according to its type, or encoded with `input` when given.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `del`          | `function` | Sends a `DELETE` request. Named `del` because `delete` is a reserved word.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `sse`          | `function` | Sends a request and gives its Server-Sent Events (`text/event-stream`) as a `Stream`, one `SseEvent` per event, as they arrive. Use it for progress feeds, notifications and the streamed answers of language models. - `output` decodes each event's `data` as JSON. `Fetch.text()` gives the data as text, which is also the default without `output`. - `method` defaults to `"GET"`. Pass `"POST"`, with a `body`, for APIs that stream the answer to a request. - The request sends `Accept: text/event-stream`, unless an `accept` header is set on the call or the client. The request runs as any call does, up to the response's headers: plugins run once, `retry` and `timeout` apply to getting the response, and an error status fails the stream with an `HttpError` or a `statusErrors` error, before it gives anything, and a `204` or `205` gives an empty stream. Then the body is read as it arrives. An event whose data doesn't match `output`, a body that can't be read to the end, or a `Content-Type` other than `text/event-stream` fails the stream with a `DecodeError`, after the events before it. For plugins, the call ends when the headers arrive: their `onExit` hooks don't see the body being read. Interrupting the stream, or taking only part of it, aborts the request. The stream doesn't reconnect, and ignores `retry:` lines. |
| `ndjson`       | `function` | Sends a request and gives its newline-delimited JSON body (`application/x-ndjson`, JSON Lines) as a `Stream`, one value per line, as they arrive. Use it for exports and other long lists that a server streams. - `output` decodes each line's JSON. Without it, each value is the parsed JSON, as `unknown`. `Fetch.text()` gives each line's text. - Blank lines are skipped, and the last line needs no line end. - `method` defaults to `"GET"`. - The request sends `Accept: application/x-ndjson`, unless an `accept` header is set on the call or the client. Errors, plugins, retries, timeouts and interruption work as for Client.sse. A line that isn't valid JSON or doesn't match `output` fails the stream with a `DecodeError` that gives its line number.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `endpoint`     | `function` | Defines an endpoint: a route like `"GET /users/:id"` and the schemas, headers and plugin overrides to call it with. You get back a function that takes one call's `params`, `query`, `body`, `headers` and `plugins`, and returns the same Effect as the equivalent method: `getUser({ params: { id } })` sends what `api.get("/users/:id", { output: User, params: { id } })` does. - The route is checked as you type: an uppercase method, one space, then a path starting with `/` or an absolute `http(s)://` URL. - `params` are required, with exactly the path's names, when the path has any. - With an `input` schema, `body` is required and typed by it. `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints take no body. - A call's `headers` and `plugins` are merged over the endpoint's, and win. The schemas can't be changed per call. - With `stream: "sse"` or `stream: "ndjson"`, each call returns a `Stream` of the body's values, as Client.sse and Client.ndjson do. Defining an endpoint does nothing on its own: each call sends a request. A route that isn't valid (which the types prevent) throws.                                                                                                                                                                                                                                              |
| `bind`         | `function` | Binds an endpoint defined with `Fetch.endpoint` to this client. You get back the same endpoint `client.endpoint` makes from the same route and definition: `api.bind(Fetch.endpoint("GET /users/:id", { output: User }))` is `api.endpoint("GET /users/:id", { output: User })`. - Without its own `error`, the endpoint uses this client's `defaultError`. This client's `statusErrors` are tried after the definition's. - `plugins` overrides are given here, checked against this client's plugins. A call's own override wins. - `headers` given here are sent over the definition's. A call's own header wins over both. Binding does nothing on its own, and one definition can be bound to several clients: each endpoint sends to its own client's `baseUrl`, with its plugins. To bind a record of definitions at once, use Client.bindAll. To share them as a service, use `Fetch.Endpoints`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `bindAll`      | `function` | Binds a record of endpoint definitions at once: each entry is bound as Client.bind binds it, and keeps its name. An entry is a definition made with `Fetch.endpoint`, or a `[definition, options]` pair, where `options` are the options (`BindOptions`) `client.bind` takes. Binding does nothing on its own: no request is sent until an endpoint is called. An entry that isn't a definition throws, since that's a bug in the calling code. To share the endpoints as a service, see `Fetch.Endpoints`, which calls this when its layer is built.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |

### Fetch.ClientConfig

Configuration for [`make`](https://effetch.pages.dev/docs/reference/fetch#make).

| Prop            | Type    | Description                                                               |
| --------------- | ------- | ------------------------------------------------------------------------- |
| `baseUrl?`      | `union` | Prepended to relative paths. A string, or an Effect run once by `make`.   |
| `headers?`      | `union` | Headers sent with every request.                                          |
| `defaultError?` | `EB`    | Schema for non-2xx response bodies, unless a call passes its own `error`. |
| `statusErrors?` | `SE`    | Your own errors for error responses, by status, for every call.           |
| `plugins?`      | `Ps`    | Plugins, outermost first. Names must be unique.                           |

### Fetch.ServiceClass

A client as a service class: what [`Service`](https://effetch.pages.dev/docs/reference/fetch#service) returns, to extend.

### Fetch.ServiceClass.Any

Any class made by [`Service`](https://effetch.pages.dev/docs/reference/fetch#service), whatever its config. What [`isService`](https://effetch.pages.dev/docs/reference/fetch#isservice) narrows to.

## Calls

Guide: [Methods](https://effetch.pages.dev/docs/calls).

### Fetch.AnySchema

Any Effect schema accepted by the `output`, `error` and `input` options.

### Fetch.Args

The rest arguments after the path: the options object `T` is required when path `P` has parameters, optional otherwise.

### Fetch.BaseOptions

Options shared by every method.

| Prop            | Type            | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| --------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `query?`        | `Q`             | Query parameters. Arrays repeat the key; `null`/`undefined` are dropped.                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `headers?`      | `union`         | Headers for this call, merged over the client's headers.                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `output?`       | `O`             | Decodes the 2xx body with this schema. Without it, the call succeeds with the raw `HttpClientResponse`. The body is read as JSON, or as text with `Fetch.text()` and as bytes with `Fetch.bytes()`. The request carries a matching `Accept` header, such as `application/json`, unless an `accept` header is set on the call or the client. An empty JSON body (204, HEAD, …) is decoded as `null`: use `Schema.Void` for endpoints that return nothing. Non-2xx responses, 3xx included, fail with an `HttpError` before this runs. |
| `responseMode?` | `M`             | `"decoded-and-response"` makes the call succeed with a pair of the decoded body and the response, for its status and headers. Defaults to `"decoded"`: the decoded body alone. See ResponseMode.                                                                                                                                                                                                                                                                                                                                     |
| `error?`        | `EB`            | Decodes non-2xx bodies into `HttpError.body`. Overrides the client's.                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `statusErrors?` | `SE`            | Turns error responses into your own errors, by status (see StatusErrorMap). Tried before the client's. A response none of them decodes fails with an `HttpError`, its body decoded with `error`.                                                                                                                                                                                                                                                                                                                                     |
| `plugins?`      | `Overrides<Ps>` | Per-request plugin overrides, by plugin name: `false` skips the plugin's hooks and `wrap` for this call, and a partial of its options is merged over its `defaults`.                                                                                                                                                                                                                                                                                                                                                                 |

### Fetch.BodyMethod

The signature of `post`, `put`, `patch` and `del`: `body` allowed, typed by `input` when given.

- `Ps`: the client's plugins.
- `DefaultEB`: the client's `defaultError` schema, used when a call has no `error`.
- `ClientSE`: the client's `statusErrors` map, or `undefined` without one.

### Fetch.BodyOptions

The `body` and `input` options of methods that send a body.

| Prop     | Type        | Description                                                                                                                          |
| -------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `input?` | `I`         | Encodes `body` with this schema, then sends it as JSON, or as `multipart/form-data` when the schema is wrapped in `Fetch.multipart`. |
| `body?`  | `I["Type"]` | The request body. Typed by `input` when given.                                                                                       |

### Fetch.CallEffect

The Effect a call returns: it succeeds with [`Success`](https://effetch.pages.dev/docs/reference/fetch#success), fails with [`CallError`](https://effetch.pages.dev/docs/reference/fetch#callerror) and requires [`CallServices`](https://effetch.pages.dev/docs/reference/fetch#callservices).

- `O`: the `output` schema, or `undefined` for the raw response.
- `EB`: the `error` schema for non-2xx bodies.
- `I`: the `input` schema (`Schema.Unknown` or `undefined` when the call has none).
- `Ps`: the client's plugins.
- `SE`: the `statusErrors` maps of the call, the endpoint and the client, as a union. `undefined` (the default) when there are none.
- `M`: the [`ResponseMode`](https://effetch.pages.dev/docs/reference/fetch#responsemode), or `undefined` (the default) for the decoded body alone.
- `QS`: an endpoint's `query` schema (see [`QuerySchema`](https://effetch.pages.dev/docs/reference/fetch#queryschema)), or `undefined` (the default) without one.

### Fetch.CallServices

The services a call requires: those needed to decode `output`, `error` and the `statusErrors` maps' errors, and to encode `input` and an endpoint's `query`.

- `SE`: the `statusErrors` maps of the call, the endpoint and the client, as a union. `undefined` (the default) when there are none.
- `QS`: the endpoint's `query` schema (see [`QuerySchema`](https://effetch.pages.dev/docs/reference/fetch#queryschema)), or `undefined` (the default) without one.

### Fetch.NoBodyMethod

The signature of `get`, `head` and `options`: no `body` or `input`.

- `Ps`: the client's plugins.
- `DefaultEB`: the client's `defaultError` schema, used when a call has no `error`.
- `ClientSE`: the client's `statusErrors` map, or `undefined` without one.

### Fetch.NoBodyRequestOptions

Options of methods that don't send a body: `get`, `head`, `options`. The type parameters are those of [`BaseOptions`](https://effetch.pages.dev/docs/reference/fetch#baseoptions).

### Fetch.ParamsOption

The `params` option for path `P`: required (with exactly the path's parameter names) when the path has `:params`, forbidden otherwise.

### Fetch.PathParamNames

The names of the path parameters in `P`, as a union of string literals.

### Fetch.PathParams

The `params` object for path `P`: one required key per parameter name.

### Fetch.PathParamValue

A value accepted for a path parameter. It's converted with `String()` and then `encodeURIComponent`.

### Fetch.QueryInput

The `query` option: an object whose entries become URL query parameters. Arrays repeat the key (`tags=a&tags=b`); `null` and `undefined` entries and array items are dropped.

### Fetch.QueryOf

The constraint on a `query` of type `Q`: each of `Q`'s own properties must be a [`QueryValue`](https://effetch.pages.dev/docs/reference/fetch#queryvalue) or an array of them.

### Fetch.QueryValue

A single query value. Effetch drops `null` and `undefined` (Effect's own `UrlParams` would send `null` as the string `"null"`); other values are converted with `String()`. With Effect 4.1 or later, a value can also be `Redacted`: it's sent as its value, and stays redacted in Effect's own logs and traces.

### Fetch.RequestMethod

The signature of `request`: any HTTP method, `body` allowed, typed by `input` when given.

- `Ps`: the client's plugins.
- `DefaultEB`: the client's `defaultError` schema, used when a call has no `error`.
- `ClientSE`: the client's `statusErrors` map, or `undefined` without one.

### Fetch.RequestOptions

Options of methods that send a body: `post`, `put`, `patch`, `del` and `request`. The type parameters are those of [`BaseOptions`](https://effetch.pages.dev/docs/reference/fetch#baseoptions), and `I` is the `input` schema.

## Responses

Guide: [Read the response](https://effetch.pages.dev/docs/calls/responses).

### Fetch.bytes

Reads a 2xx body as bytes, a `Uint8Array`, for `output`. Use it for images, PDFs and other binary bodies. The array is typed `Uint8Array<ArrayBuffer>`, so in browsers, Node, Bun and Deno it can go straight into a `Blob`. React Native's `Blob` doesn't take arrays.

### Fetch.text

Reads a 2xx body as text, for `output`. Use it for plain-text tokens, CSV and other bodies that aren't JSON.

- `Fetch.text()` gives the text as it was sent, as a `string`. An empty body is `""`.
- `Fetch.text(schema)` reads a single value, such as a count or a status: it trims the text, then decodes it with `schema`, whose encoded side is a string, such as `Schema.NumberFromString`. An empty body fails, as for JSON.

### Fetch.BytesSchema

The schema [`bytes`](https://effetch.pages.dev/docs/reference/fetch#bytes) returns: a `Uint8Array` over an `ArrayBuffer`, read from the body's bytes.

### Fetch.ResponseMode

What a call succeeds with, besides the decoded body:

- `"decoded"` (the default): the decoded body, or the raw response without an `output` schema.
- `"decoded-and-response"`: a pair of the decoded body and the response, to read its status and headers too. Without an `output` schema, the first item is the response as well.

### Fetch.Success

What a call succeeds with: the `output` schema's type, or the raw `HttpClientResponse` without one. A conditional `output` gives the union.

### Fetch.TextSchema

A schema whose encoded side is a string, as [`text`](https://effetch.pages.dev/docs/reference/fetch#text) takes: such as `Schema.String`, `Schema.NumberFromString` or a `Schema.Literals` of strings.

## Uploads

Guide: [Upload files](https://effetch.pages.dev/docs/calls/uploads).

### Fetch.multipart

Sends a body as `multipart/form-data`, for `input`: the body is typed and checked by `schema`, as for JSON, then sent as `FormData`. Use it for file uploads.

### Fetch.UploadFile

A file to upload, for a field of a [`multipart`](https://effetch.pages.dev/docs/reference/fetch#multipart) input schema. It takes the files each platform can send:

- in browsers, Node, Bun and Deno, a `Blob` or `File`;
- in React Native, a [`NativeFile`](https://effetch.pages.dev/docs/reference/fetch#nativefile), `{ uri, name, type }`, as its pickers give it. React Native's `FormData` reads the file from disk by `uri`, and can't send a `Blob`.

### Fetch.MultipartFields

What a [`multipart`](https://effetch.pages.dev/docs/reference/fetch#multipart) input schema encodes a body to: an object of fields, each a [`MultipartValue`](https://effetch.pages.dev/docs/reference/fetch#multipartvalue) or a list of them.

### Fetch.MultipartSchema

A schema [`multipart`](https://effetch.pages.dev/docs/reference/fetch#multipart) takes: one whose encoded side is [`MultipartFields`](https://effetch.pages.dev/docs/reference/fetch#multipartfields), such as a `Schema.Struct` of strings, numbers, booleans, dates, lists of them and [`UploadFile`](https://effetch.pages.dev/docs/reference/fetch#uploadfile)s.

### Fetch.MultipartValue

One value of a multipart field, as an `input` schema encodes it: a string, a number, a boolean, a bigint or a `Date` (sent as text), a file (`Blob`, `File` or [`NativeFile`](https://effetch.pages.dev/docs/reference/fetch#nativefile)), or `null` or `undefined` (left out).

### Fetch.NativeFile

A file picked in React Native: the object React Native's pickers give, and its `FormData` reads from disk by `uri`.

- `uri`: where the file is, such as `file:///…` or `content://…`.
- `name`: the file name sent with it. A server only treats a part as a file when it has one, so it's required.
- `type`: its media type, such as `"image/jpeg"`. Without it, the part is sent as `application/octet-stream`, since Android rejects a file part without a type.

### Fetch.UploadFileSchema

The schema [`UploadFile`](https://effetch.pages.dev/docs/reference/fetch#uploadfile) is: a `Blob` (a `File` is one) or a [`NativeFile`](https://effetch.pages.dev/docs/reference/fetch#nativefile), encoded as it is.

## Errors

Guide: [Call errors](https://effetch.pages.dev/docs/errors).

### Fetch.catchStatus

Handles an `HttpError` with one of the given statuses, for one call: `f` gets the error, and the call continues with what `f` returns. Errors with other statuses, and every other error, pass through.

- `status` is one status, such as `404`, or a list, such as `[401, 403]`. The handler's error has its `status` narrowed to them (see [`CaughtStatus`](https://effetch.pages.dev/docs/reference/fetch#caughtstatus)).
- `HttpError` stays in the error type, since other statuses can still fail. `f`'s own errors are added.
- It works on any Effect whose errors include `HttpError`: calls, endpoints, and Effects built on them.

### Fetch.DecodeError

A 2xx response body didn't match the call's `output` schema, wasn't valid JSON, or couldn't be read.

### Fetch.HttpError

The server answered with a non-2xx status.

### Fetch.HttpError.With

An [`HttpError`](https://effetch.pages.dev/docs/reference/fetch#httperror) whose `body` was decoded as `B`. `body` is `undefined` when the response didn't match the error schema.

### Fetch.isFetchError

Returns `true` if `u` is a [`NetworkError`](https://effetch.pages.dev/docs/reference/fetch#networkerror), [`HttpError`](https://effetch.pages.dev/docs/reference/fetch#httperror) or [`DecodeError`](https://effetch.pages.dev/docs/reference/fetch#decodeerror).

### Fetch.NetworkError

The request never produced a response: DNS failure, connection refused, CORS rejection, the device is offline, and so on.

### Fetch.optional

Turns a `404` into `Option.none()`, and a success into `Option.some`, for one call: the call succeeds with an `Option` of its value. Other errors, `HttpError`s with other statuses included, pass through.

### Fetch.CallError

What a call can fail with: `NetworkError`, `HttpError` (with `body` typed by the `error` schema), `DecodeError` when there's an `output` schema, the plugins' errors, and the errors of the `statusErrors` maps that apply (see [`StatusError`](https://effetch.pages.dev/docs/reference/fetch#statuserror)).

- `SE`: the `statusErrors` maps of the call, the endpoint and the client, as a union. `undefined` (the default) when there are none.

### Fetch.CaughtStatus

The error [`catchStatus`](https://effetch.pages.dev/docs/reference/fetch#catchstatus)'s handler gets: an `HttpError` whose `status` is narrowed to the statuses `S` it was given. Its `body` is `unknown`: to read it typed by the `error` schema, use `Effect.catchTag("HttpError", …)`.

### Fetch.FetchError

Every error the library itself can fail a call with. Plugins may add their own errors on top of these.

### Fetch.StatusError

The errors a [`StatusErrorMap`](https://effetch.pages.dev/docs/reference/fetch#statuserrormap) can fail a call with: the union of its schemas' types. `M` can be a union of maps (the call's, the endpoint's and the client's), and is `undefined` when there are none, which gives `never`.

### Fetch.StatusErrorMap

The `statusErrors` option: turns error responses into your own errors. Each key is an HTTP status, and its value is the schema of the error that status means, or a list of schemas tried in order. The first schema that decodes the response's JSON body is what the call fails with, in place of an `HttpError`.

### Fetch.StatusErrorSchema

The schemas a [`StatusErrorMap`](https://effetch.pages.dev/docs/reference/fetch#statuserrormap) lists, as a union, under its numeric keys only. `M` can be a union of maps, and `undefined` gives `never`.

### Fetch.StatusErrorServices

The services decoding a [`StatusErrorMap`](https://effetch.pages.dev/docs/reference/fetch#statuserrormap)'s errors requires: the union of its schemas' `DecodingServices`. Like [`StatusError`](https://effetch.pages.dev/docs/reference/fetch#statuserror), `M` can be a union of maps, and `undefined` gives `never`.

## Plugins

Guide: [Write a plugin](https://effetch.pages.dev/docs/plugins/writing).

### Fetch.plugin

Defines a plugin. Returns its argument unchanged; it exists to infer `Name`, the errors, the services and the options type from the hooks.

### Fetch.Plugin

A plugin hooks into every call a client makes.

| Prop          | Type                     | Description                                                        |
| ------------- | ------------------------ | ------------------------------------------------------------------ |
| `name`        | `Name`                   | Unique within a client. Used as the key for per-request overrides. |
| `defaults?`   | `Opts`                   | Default options. Enables per-request `Partial<Opts>` overrides.    |
| `onRequest?`  | `OnRequest<Opts, E, R>`  | Runs before the request is sent, in array order.                   |
| `onResponse?` | `OnResponse<Opts, E, R>` | Runs on every response, non-2xx included, in reverse array order.  |
| `onError?`    | `OnError<Opts, R>`       | Observes any failure of the call. Can't change the outcome.        |
| `onExit?`     | `OnExit<Opts, R>`        | Observes the end of every call. Can't change the outcome.          |
| `wrap?`       | `Wrap<Opts, E, R>`       | Wraps the rest of the chain.                                       |

### Fetch.Plugin.Any

Any plugin. Use it to constrain a generic plugin-list parameter (`Ps extends ReadonlyArray<Plugin.Any>`).

### Fetch.Plugin.Definition

What [`plugin`](https://effetch.pages.dev/docs/reference/fetch#plugin) accepts. Like [`Plugin`](https://effetch.pages.dev/docs/reference/fetch#plugin-type), but each hook has its own error and service type parameters, so hooks that fail with different errors infer their union instead of conflicting.

### Fetch.Plugin.Errors

The union of errors the plugins in `Ps` can add to a call. `unknown` if a plugin's types were erased (for example by [`Any`](https://effetch.pages.dev/docs/reference/fetch#plugin-any)).

### Fetch.Plugin.OnError

The `onError` hook. `error` is a `FetchError`, another plugin's error, one of the call's `statusErrors`, or a defect's cause. It can't fail or change the call's outcome: if it dies, the defect is logged at Debug level and ignored.

### Fetch.Plugin.OnExit

The `onExit` hook: runs once per call, when it's over, with the call's `Exit`. On success that holds the call's result: the decoded `output`, or the response for a call without one, or, with `responseMode: "decoded-and-response"`, a pair of that and the response. Otherwise it holds the cause of its failure, defect or interruption. To tell whether the body was read, compare the result, or its first item, with `ctx.response`: a call returns the response itself only when it didn't decode it. It sees the final outcome, `statusErrors` and decoding included, which suits logging and metrics.

### Fetch.Plugin.OnRequest

The `onRequest` hook: returns the request to send, possibly changed.

### Fetch.Plugin.OnResponse

The `onResponse` hook: returns the response, possibly changed, or fails. Sees non-2xx responses too.

### Fetch.Plugin.Options

The options type of plugin `P`.

### Fetch.Plugin.Override

What one plugin accepts as a per-request override: `false` to skip it, or a partial of its options. Plugins without options accept only `false`. Keys set to `undefined` keep their default.

### Fetch.Plugin.Overrides

The `plugins` option of a call: an override per plugin name in `Ps`. Unknown names are compile errors, including when the client has no plugins. Plugins whose `name` isn't a string literal can't be overridden (they'd make every name valid).

### Fetch.Plugin.Services

The union of services the plugins in `Ps` require. `make` requires them once; calls on the client don't. `unknown` if a plugin's types were erased.

### Fetch.Plugin.Upstream

The client a plugin's `wrap` receives: the rest of the chain.

### Fetch.Plugin.UpstreamError

Stands for the errors of everything inside a plugin's `wrap`: the network, the library's other errors and inner plugins' errors. It's opaque on purpose; a `wrap` can only pass it through.

### Fetch.Plugin.UpstreamServices

Stands for the services required by everything inside a plugin's `wrap`. Opaque, like [`UpstreamError`](https://effetch.pages.dev/docs/reference/fetch#plugin-upstreamerror).

### Fetch.Plugin.Wrap

The `wrap` hook: wraps the rest of the chain (`client`). Its error and service types are opaque placeholders, so a `wrap` can add errors and services but can't drop the ones from further in. `options` reads this call's merged options, and `route` this call's route (see [`PluginContext`](https://effetch.pages.dev/docs/reference/fetch#plugincontext)).

### Fetch.PluginContext

What a plugin hook receives besides the request or response.

| Prop      | Type     | Description                                                                                                                 |
| --------- | -------- | --------------------------------------------------------------------------------------------------------------------------- |
| `request` | `object` | The request this hook is about (see above for which one).                                                                   |
| `options` | `Opts`   | The plugin's `defaults` merged with this call's override.                                                                   |
| `route`   | `union`  | The call's method and unfilled path, such as `"GET /users/:id"`. `undefined` for requests sent through `client.httpClient`. |

### Fetch.PluginExitContext

What a plugin's `onExit` hook receives besides the call's `Exit`: the fields of [`PluginContext`](https://effetch.pages.dev/docs/reference/fetch#plugincontext), and

- `response`: the response the plugin chain returned, whose status was checked and whose body was decoded. When a plugin failed after a response arrived, the last response the network sent (its body may not have been read). `undefined` when no response arrived: a network failure, a timeout, or a plugin that failed first. Its `request` is the one that was sent, after every plugin's `onRequest`.
- `durationMs`: how long the call took, in whole milliseconds measured with Effect's `Clock`, from when its request entered the plugin chain until the status was checked and the body decoded. Retries made by a plugin's `wrap` are included.

| Prop         | Type     | Description                                                                                                   |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------- |
| `route`      | `string` | The call's method and unfilled path, such as `"GET /users/:id"`.                                              |
| `response`   | `union`  | The response the plugin chain returned, else the last one the network sent, or `undefined` when none arrived. |
| `durationMs` | `number` | How long the call took, in whole milliseconds.                                                                |
| `request`    | `object` | The request this hook is about (see above for which one).                                                     |
| `options`    | `Opts`   | The plugin's `defaults` merged with this call's override.                                                     |

## Endpoints and services

Guide: [Endpoints or methods](https://effetch.pages.dev/docs/endpoints).

### Fetch.endpoint

Defines an endpoint without a client: a route like `"GET /users/:id"` and the schemas and headers to call it with. You get back plain data, an [`UnboundEndpoint`](https://effetch.pages.dev/docs/reference/fetch#unboundendpoint), that you can export from module level next to its schemas. `client.bind(definition)` turns it into an [`Endpoint`](https://effetch.pages.dev/docs/reference/fetch#endpoint-type) of that client: the same one `client.endpoint(route, definition)` makes.

- The route is checked as you type, as with `client.endpoint`. A route that isn't valid (which the types prevent) throws here, when the module loads.
- With an `input` schema, `body` is required on every call and typed by it. `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints take no `input`.
- Without `error`, the endpoint uses the `defaultError` of the client it's bound to.
- `statusErrors` (see [`StatusErrorMap`](https://effetch.pages.dev/docs/reference/fetch#statuserrormap)) are tried before those of the client it's bound to.
- With a `query` schema (see [`QuerySchema`](https://effetch.pages.dev/docs/reference/fetch#queryschema)), each call's `query` is typed and encoded by it, and required when the schema has required fields.
- With `stream: "sse"` or `stream: "ndjson"`, each call of the bound endpoint returns a `Stream` of the body's values. A `stream` that isn't one of those, or that comes with `responseMode` or a `Fetch.bytes()` output, throws here.
- Plugin overrides are given when binding: a definition doesn't know which plugins a client has.
- `definition.url(options)` builds the URL a call would go to, without the client's `baseUrl`.

### Fetch.Endpoints

Declares a module's endpoints as a service class: one class that is the service key, its layer and its definitions.

### Fetch.AnyUnboundEndpoint

Any [`UnboundEndpoint`](https://effetch.pages.dev/docs/reference/fetch#unboundendpoint), whatever its route and schemas. Use it to constrain a parameter that takes definitions.

### Fetch.BindAllMethod

The signature of `client.bindAll`: binds a record of definitions at once, as `client.bind` binds each one. `Ps`, `DefaultEB` and `ClientSE` are the client's, as in [`BindMethod`](https://effetch.pages.dev/docs/reference/fetch#bindmethod).

### Fetch.BindMethod

The signature of `client.bind`: turns an [`UnboundEndpoint`](https://effetch.pages.dev/docs/reference/fetch#unboundendpoint) into an [`Endpoint`](https://effetch.pages.dev/docs/reference/fetch#endpoint-type) of the client, the same one `client.endpoint` makes from the same route and definition.

- `Ps`: the client's plugins.
- `DefaultEB`: the client's `defaultError` schema, used when the definition has no `error`.
- `ClientSE`: the client's `statusErrors` map, or `undefined` without one.

### Fetch.BindOptions

What `client.bind` takes besides the definition: headers and plugin overrides for every call of the bound endpoint.

| Prop       | Type            | Description                                                              |
| ---------- | --------------- | ------------------------------------------------------------------------ |
| `headers?` | `union`         | Headers for every call, over the definition's. A call's own header wins. |
| `plugins?` | `Overrides<Ps>` | Plugin overrides for every call. A call's own override wins.             |

### Fetch.BoundEndpoint

The endpoint a client makes from one entry of [`EndpointDefinitions`](https://effetch.pages.dev/docs/reference/fetch#endpointdefinitions): what `client.bind` returns for that definition. `Ps`, `DefaultEB` and `ClientSE` are the client's, as in [`BindMethod`](https://effetch.pages.dev/docs/reference/fetch#bindmethod).

### Fetch.BoundEndpoints

The endpoints `client.bindAll` makes from a record of [`EndpointDefinitions`](https://effetch.pages.dev/docs/reference/fetch#endpointdefinitions): one [`Endpoint`](https://effetch.pages.dev/docs/reference/fetch#endpoint-type) for each entry, under the same name.

### Fetch.Endpoint

An endpoint made by `client.endpoint` or `client.bind`: a function that sends its request with the options of one call, and returns the same Effect as the equivalent client method. With `stream`, it returns a `Stream` of the body's values instead, as `api.sse` and `api.ndjson` do. To page through a list endpoint, pass it to `Fetch.paginate`.

### Fetch.EndpointArgs

The arguments of an endpoint call: the options object `T` is required when route `R` has path params, the endpoint has an `input` schema, or its `query` schema `QS` has required fields, and optional otherwise.

### Fetch.EndpointBody

The `body` option of an endpoint call: not allowed on `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints, required and typed by the schema when the endpoint has an `input`, and optional otherwise (sent according to its runtime type, like a call's `body`).

### Fetch.EndpointDefinition

What an endpoint is defined with, besides its route. Everything is optional.

| Prop            | Type                                          | Description                                                                                                                                                                                                                                                                  |
| --------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `output?`       | `O`                                           | Decodes the 2xx body. Without it, calls return the raw response.                                                                                                                                                                                                             |
| `error?`        | `EB`                                          | Decodes non-2xx bodies into `HttpError.body`. Overrides the client's.                                                                                                                                                                                                        |
| `statusErrors?` | `SE`                                          | Your own errors for error responses, by status. Tried before the client's.                                                                                                                                                                                                   |
| `input?`        | `NoBodyRoute<R> extends true ? undefined : I` | Encodes `body` with this schema, and makes `body` required on every call. Sent as JSON, or as `multipart/form-data` when the schema is wrapped in `Fetch.multipart`.                                                                                                         |
| `headers?`      | `union`                                       | Headers for every call, over the client's. A call's own header wins.                                                                                                                                                                                                         |
| `plugins?`      | `Overrides<Ps>`                               | Plugin overrides for every call. A call's own override wins.                                                                                                                                                                                                                 |
| `responseMode?` | `M`                                           | What every call succeeds with. A call's own `responseMode` wins.                                                                                                                                                                                                             |
| `query?`        | `QS`                                          | Types and encodes each call's `query`, and makes it required when the schema has required fields. See QuerySchema.                                                                                                                                                           |
| `stream?`       | `St`                                          | Makes every call a `Stream` of the response body's values, as `api.sse` or `api.ndjson` gives them (see StreamFormat and StreamElement), with `output` decoding each value. Can't be used with `responseMode` or a `Fetch.bytes()` output: defining such an endpoint throws. |

### Fetch.EndpointDefinitions

What `client.bindAll` and `Fetch.Endpoints` take: a record of definitions made with [`endpoint`](https://effetch.pages.dev/docs/reference/fetch#endpoint), by the name each endpoint gets, each entry checked by [`EndpointEntry`](https://effetch.pages.dev/docs/reference/fetch#endpointentry). `D` is the record's own type, and `Ps` the client's plugins. Names are strings: symbol keys are left out.

### Fetch.EndpointEntry

How `client.bindAll` and `Fetch.Endpoints` check one entry of a record of definitions, given the entry's own type `E` and the client's plugins `Ps`. An entry is a definition made with [`endpoint`](https://effetch.pages.dev/docs/reference/fetch#endpoint), or a pair of a definition and the [`BindOptions`](https://effetch.pages.dev/docs/reference/fetch#bindoptions) to bind it with. A pair's options are checked as `client.bind` checks them, so a misspelt option or plugin name is an error.

### Fetch.EndpointMethod

The signature of `client.endpoint`: defines an [`Endpoint`](https://effetch.pages.dev/docs/reference/fetch#endpoint-type) from a route and an [`EndpointDefinition`](https://effetch.pages.dev/docs/reference/fetch#endpointdefinition).

- `Ps`: the client's plugins.
- `DefaultEB`: the client's `defaultError` schema, used when the endpoint has no `error`.
- `ClientSE`: the client's `statusErrors` map, or `undefined` without one.

### Fetch.EndpointOptions

The options of one endpoint call: `params` for the route's path (see [`ParamsOption`](https://effetch.pages.dev/docs/reference/fetch#paramsoption)), `body` (see [`EndpointBody`](https://effetch.pages.dev/docs/reference/fetch#endpointbody)), `query`, `headers`, `plugins` and `responseMode`. The schemas are fixed by the endpoint.

- `Q`: the type of `query` without a query schema, checked with [`QueryOf`](https://effetch.pages.dev/docs/reference/fetch#queryof). Defaults to [`QueryInput`](https://effetch.pages.dev/docs/reference/fetch#queryinput).
- `M`: the call's [`ResponseMode`](https://effetch.pages.dev/docs/reference/fetch#responsemode), which wins over the endpoint's, or `undefined` without one.
- `QS`: the endpoint's `query` schema, which types `query` (see [`EndpointQuery`](https://effetch.pages.dev/docs/reference/fetch#endpointquery)), or `undefined` without one.

### Fetch.EndpointQuery

The `query` option of an endpoint call. With a `query` schema (see [`QuerySchema`](https://effetch.pages.dev/docs/reference/fetch#queryschema)), it's typed by the schema's `Type`, and required when that has required fields. Without one, it's any [`QueryInput`](https://effetch.pages.dev/docs/reference/fetch#queryinput), typed as `Q`.

### Fetch.EndpointRoute

The routes `endpoint` accepts: an uppercase HTTP method, one space, then a path that starts with `/` or an absolute `http://` or `https://` URL.

### Fetch.EndpointsClass

A service class whose service is a record of endpoints: what [`Endpoints`](https://effetch.pages.dev/docs/reference/fetch#endpoints) returns, to extend.

### Fetch.EndpointUrlArgs

The arguments of `endpoint.url`: its [`EndpointUrlOptions`](https://effetch.pages.dev/docs/reference/fetch#endpointurloptions), which can be left out when nothing in them is required.

### Fetch.EndpointUrlOptions

What `endpoint.url` takes: `params` for the route's path (see [`ParamsOption`](https://effetch.pages.dev/docs/reference/fetch#paramsoption)) and `query` (see [`EndpointQuery`](https://effetch.pages.dev/docs/reference/fetch#endpointquery)), as a call takes them.

### Fetch.QuerySchema

A schema for an endpoint's `query`: an object schema, usually a `Schema.Struct`, whose fields are the query parameters. A call's `query` is then typed by the schema's `Type`, and encoded with it before it's sent. A `Schema.Class` works too, and its calls take an instance.

### Fetch.RouteMethod

The HTTP method of route `R` (`"GET /users/:id"` gives `"GET"`).

### Fetch.RoutePath

The path of route `R`, everything after the method and the space (`"GET /users/:id"` gives `"/users/:id"`).

### Fetch.UnboundDefinition

What [`endpoint`](https://effetch.pages.dev/docs/reference/fetch#endpoint) defines an endpoint with, besides its route: an [`EndpointDefinition`](https://effetch.pages.dev/docs/reference/fetch#endpointdefinition) without `plugins`. Everything is optional.

- `output`: decodes the 2xx body, read as JSON, or as text or bytes with `Fetch.text()` and `Fetch.bytes()`. Without it, the endpoint succeeds with the raw `HttpClientResponse`.
- `error`: decodes non-2xx bodies into `HttpError.body`. Without it, the endpoint uses the `defaultError` of the client it's bound to.
- `statusErrors`: turns error responses into your own errors, by status (see [`StatusErrorMap`](https://effetch.pages.dev/docs/reference/fetch#statuserrormap)). Tried before those of the client it's bound to.
- `input`: encodes `body` before it's sent as JSON, and makes `body` required on every call. Not allowed on `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints, which take no body.
- `headers`: sent with every call, over the client's headers. Headers given when binding, then a call's own, win over them. Unlike the client's headers, these can set `content-type`.
- `responseMode`: what every call succeeds with (see [`ResponseMode`](https://effetch.pages.dev/docs/reference/fetch#responsemode)). A call's own `responseMode` wins.
- `query`: a schema for the query parameters (see [`QuerySchema`](https://effetch.pages.dev/docs/reference/fetch#queryschema)). Each call's `query` is then typed by it, and encoded with it.
- `stream`: `"sse"` or `"ndjson"` makes every call return a `Stream` of the body's values (see [`StreamFormat`](https://effetch.pages.dev/docs/reference/fetch#streamformat)).

### Fetch.UnboundEndpoint

An endpoint defined without a client, by [`endpoint`](https://effetch.pages.dev/docs/reference/fetch#endpoint): its route, schemas and headers, as plain data. `client.bind` turns it into an [`Endpoint`](https://effetch.pages.dev/docs/reference/fetch#endpoint-type) of that client, the same one `client.endpoint` makes from the same route and definition.

### Fetch.ValidRoute

The type of `endpoint`'s route argument: `R` itself when it's an [`EndpointRoute`](https://effetch.pages.dev/docs/reference/fetch#endpointroute), otherwise the list of `"<METHOD> /"` starts.

## Streaming

Guide: [Streaming responses](https://effetch.pages.dev/docs/streaming).

### Fetch.SseEvent

One Server-Sent Event, as `api.sse` and SSE endpoints give it (see [`StreamElement`](https://effetch.pages.dev/docs/reference/fetch#streamelement)).

| Prop    | Type     | Description                                               |
| ------- | -------- | --------------------------------------------------------- |
| `event` | `string` | The event's name, `"message"` when the server sends none. |
| `id`    | `union`  | The last event ID the server sent, or `undefined`.        |
| `data`  | `A`      | The event's data, decoded with `output`.                  |

### Fetch.StreamElement

What a stream in format `St` gives for each value, with the `output` schema `O`:

- `"sse"`: an [`SseEvent`](https://effetch.pages.dev/docs/reference/fetch#sseevent) whose `data` has `O`'s type, or is a `string` without `output`;
- `"ndjson"`: `O`'s type, or `unknown` (the parsed JSON) without `output`.

### Fetch.StreamFormat

How a streamed response body is split into values:

- `"sse"`: Server-Sent Events (`text/event-stream`), one value per event (see [`SseEvent`](https://effetch.pages.dev/docs/reference/fetch#sseevent)).
- `"ndjson"`: newline-delimited JSON (`application/x-ndjson`), one value per line.

### Fetch.StreamMethod

The signature of `api.sse` and `api.ndjson`: sends a request, and gives its response body as a `Stream` of values in format `St`, each a [`StreamElement`](https://effetch.pages.dev/docs/reference/fetch#streamelement). It takes [`StreamOptions`](https://effetch.pages.dev/docs/reference/fetch#streamoptions).

- `St`: the [`StreamFormat`](https://effetch.pages.dev/docs/reference/fetch#streamformat).
- `Ps`: the client's plugins.
- `DefaultEB`: the client's `defaultError` schema.
- `ClientSE`: the client's `statusErrors` map, or `undefined`.

### Fetch.StreamOptions

The options of `api.sse` and `api.ndjson`: those of a call, without `responseMode`, and with `method`.

- `method`: the request's method. Defaults to `"GET"`. Streaming APIs that take a request body, such as those of language models, use `"POST"`. `GET`, `HEAD`, `OPTIONS` and `TRACE` take no `body` or `input`.
- `output`: decodes each value (see [`StreamElement`](https://effetch.pages.dev/docs/reference/fetch#streamelement)). `Fetch.text()` gives each value's text; `Fetch.bytes()` can't be used.
- `params`, `query`, `headers`, `body`, `input`, `error`, `statusErrors` and `plugins`: as for any call.

## Pagination

Guide: [Pagination](https://effetch.pages.dev/docs/pagination).

### Fetch.paginate

Pages through a list, as a `Stream` of pages: it calls `endpoint` (a [`PageEndpoint`](https://effetch.pages.dev/docs/reference/fetch#pageendpoint)) for the first page, then for the next one while `next` gives a state, and stops after the page for which it gives `Option.none()`. See [`PaginateOptions`](https://effetch.pages.dev/docs/reference/fetch#paginateoptions) for `start`, `request` and `next`. Each page is one value of the stream, so a page that is a list stays a list: `Stream.flattenIterable` gives its items instead.

### Fetch.PageEndpoint

An endpoint [`paginate`](https://effetch.pages.dev/docs/reference/fetch#paginate) can page through: one made by `client.endpoint` or `client.bind`, whose calls return an `Effect`. A definition made by `Fetch.endpoint` needs binding first, and a stream endpoint can't be paged.

### Fetch.PageOf

One page of endpoint `EP`: its `output`'s type, or the raw response without `output`. It's what [`paginate`](https://effetch.pages.dev/docs/reference/fetch#paginate)'s stream gives, and what [`PaginateOptions`](https://effetch.pages.dev/docs/reference/fetch#paginateoptions)' `next` gets.

### Fetch.PageRequest

The options of one page's call, as [`PaginateOptions`](https://effetch.pages.dev/docs/reference/fetch#paginateoptions)' `request` returns them for endpoint `EP`: `params`, `body`, `query` and `headers`, typed as for any call of the endpoint.

### Fetch.PageResponse

What `next` gets as the response of a page of endpoint `EP`: the response when the endpoint's `responseMode` is `"decoded-and-response"`, for cursors in headers, and `undefined` otherwise.

### Fetch.PaginateOptions

How [`paginate`](https://effetch.pages.dev/docs/reference/fetch#paginate) goes from page to page, with a state `S`, such as a page number or a cursor.

| Prop      | Type       | Description                                                        |
| --------- | ---------- | ------------------------------------------------------------------ |
| `start`   | `S`        | The state of the first page.                                       |
| `request` | `function` | The options of the call for the page with this state.              |
| `next`    | `function` | The state of the next page, or `Option.none()` after the last one. |