# @rcompat/http

This module provides HTTP servers built around WHATWG `Request` and `Response`,
with WebSocket, TLS, MIME, status, and timeout support.

## Installation

```bash
npm install @rcompat/http
```

```bash
pnpm add @rcompat/http
```

```bash
yarn add @rcompat/http
```

```bash
bun add @rcompat/http
```

## Usage

### Basic server

```js
import http from "@rcompat/http";

const server = await http.serve(request => {
  return new Response("Hello, world!");
}, { host: "localhost", port: 3000 });

// stop the server
server.stop();
```

### Routing

```js
import http from "@rcompat/http";

await http.serve(request => {
  const { pathname } = new URL(request.url);

  if (pathname === "/") {
    return new Response("Home");
  }

  if (pathname === "/api/users") {
    return Response.json([{ id: 1, name: "John" }]);
  }

  return new Response("Not Found", { status: 404 });
}, { host: "localhost", port: 3000 });
```

### HTTP methods

```js
import http from "@rcompat/http";

await http.serve(async request => {
  const { pathname } = new URL(request.url);
  const { method } = request;

  if (pathname === "/api/data") {
    if (method === "GET") {
      return Response.json({ data: "value" });
    }

    if (method === "POST") {
      const body = await request.json();
      return Response.json({ received: body }, { status: 201 });
    }

    return new Response("Method Not Allowed", { status: 405 });
  }

  return new Response("Not Found", { status: 404 });
}, { host: "localhost", port: 3000 });
```

### Request cancellation

`request.signal` is a stable `AbortSignal`. Pass it to downstream work so a
client disconnect can cancel work even after the request body has been read:

```js
import http from "@rcompat/http";

await http.serve(async request => {
  const body = await request.text();
  return fetch("https://api.example.com/relay", {
    method: "POST",
    body,
    signal: request.signal,
  });
}, { host: "localhost", port: 3000 });
```

On Node, premature client disconnection aborts the signal once with an
`AbortError`. Finishing the request body does **not** abort it: cancellation
remains observable while the handler waits and while the response streams.
Normal response completion removes the transport listeners without aborting
the signal. Later closure or reuse of that connection does not change a
completed request's signal. A signal is a cancellation notification, not proof
that response bytes were processed by the client.

Pending Node WebSocket handshakes are observed until rejection completes or a
successful upgrade transfers ownership. After upgrade, use WebSocket lifecycle
events rather than the HTTP request signal.

Bun and Deno use their native request signals. Bun supports the disconnect
cases above. Deno detects an interrupted upload through rejection of the body
read, but may defer its signal's cancellation until the handler returns; do not
rely solely on that signal to detect an incomplete body. Deno's legacy request
behavior may also abort a signal after a successful response. Across runtimes,
do not treat the signal as a success/failure record after the response lifetime
ends, and handle body-reading errors separately from downstream cancellation.

HTTP servers remain unavailable in browsers.

### Streaming multipart forms

`http.multipart(content_type, source, options?)` reads a Web
`ReadableStream<Uint8Array>` in wire order on Node, Bun, Deno, and in browsers.
Each part has a field `name`, an optional `filename` and `content_type`, and a
`body` byte stream. The content type includes any parameters from the part
header. Filenames have path components stripped.

```js
import http from "@rcompat/http";

async function upload(request, open_file_sink) {
  const content_type = request.headers.get("content-type");
  if (content_type === null || request.body === null) {
    return new Response("Expected a multipart body", { status: 400 });
  }

  for await (const part of http.multipart(content_type, request.body, {
    max_parts: 32,
    max_part_bytes: 8 * 1024 * 1024,
    signal: request.signal,
  })) {
    if (part.filename !== undefined) {
      const sink = await open_file_sink(part);
      await part.body.pipeTo(sink);
    }
  }

  return new Response(null, { status: 204 });
}
```

- Read each body before advancing the iterator. The parser reads on demand,
  retaining framing lookbehind and any unconsumed bytes from the current
  source chunk. Advancing completes any in-flight read, closes the old body,
  and discards its unread content. Canceling a part stops its body reads.
  The next iterator step discards its unread content.
- Breaking the loop or calling the iterator's `return()` cancels the input
  and releases its reader. Normal iteration through the end consumes the
  epilogue and releases the reader.
- `max_parts` defaults to 128 and `max_part_bytes` defaults to 16 MiB.
  Both accept nonnegative safe integers and apply to skipped parts. The parser
  also bounds preamble and part headers at 64 KiB each and bounds individual
  lines and delimiter suffix lookbehind at approximately 16 KiB. Enforce any
  total upload limit on the source stream.
- Malformed input raises `http.MultipartError`. Parser limits raise
  `http.MultipartLimitError`. Errors reject the body read or iterator step
  that encounters them. Source failures and the supplied signal's abort
  reason propagate unchanged.

The package exports the TypeScript types `MultipartPart` and `MultipartOptions`.
The existing `request.formData()` API continues to buffer fields and files.

### Status codes

```js
import http from "@rcompat/http";

const { Status } = http;

await http.serve(request => {
  return new Response("Created", { status: Status.CREATED });
}, { host: "localhost", port: 3000 });

// available status codes
Status.OK;                    // 200
Status.CREATED;               // 201
Status.NO_CONTENT;            // 204
Status.MOVED_PERMANENTLY;     // 301
Status.NOT_MODIFIED;          // 304
Status.BAD_REQUEST;           // 400
Status.UNAUTHORIZED;          // 401
Status.FORBIDDEN;             // 403
Status.NOT_FOUND;             // 404
Status.INTERNAL_SERVER_ERROR; // 500
// ... and many more
```

### WebSockets

```js
import http from "@rcompat/http";

const server = await http.serve(request => {
  // check if it's a WebSocket upgrade request
  if (request.headers.get("upgrade") === "websocket") {
    return server.upgrade(request, {
      open(socket) {
        console.log("Client connected");
        socket.send("Welcome!");
      },
      message(socket, message) {
        console.log("Received:", message);
        socket.send(`Echo: ${message}`);
      },
      close(socket) {
        console.log("Client disconnected");
      },
    });
  }

  return new Response("Hello!");
}, { host: "localhost", port: 3000 });
```

### SSL/HTTPS

```js
import http from "@rcompat/http";
import fs from "@rcompat/fs";

await http.serve(request => {
  return new Response("Secure!");
}, {
  host: "localhost",
  port: 443,
  ssl: {
    cert: fs.ref("./certs/cert.pem"),
    key: fs.ref("./certs/key.pem"),
  },
});
```

### MIME types

Get MIME types by extension or use predefined constants.

```js
import http from "@rcompat/http";

http.toMIME("index.html"); // "text/html"
http.toMIME("app.js");     // "text/javascript"
http.toMIME("data.json");  // "application/json"
http.toMIME("image.png");  // "image/png"

http.MIME.APPLICATION_JSON;                   // "application/json"
http.MIME.APPLICATION_X_WWW_FORM_URLENCODED; // "application/x-www-form-urlencoded"
http.MIME.TEXT_EVENT_STREAM;                  // "text/event-stream"
http.MIME.TEXT_HTML;                          // "text/html"
```

### Serving static files

```js
import http from "@rcompat/http";
import fs from "@rcompat/fs";

const publicFiles = fs.ref("./public");
const files = new Map([
  ["/", publicFiles.join("index.html")],
  ["/app.js", publicFiles.join("app.js")],
]);

await http.serve(async request => {
  const { pathname } = new URL(request.url);
  const file = files.get(pathname);

  if (file !== undefined && await file.exists()) {
    return new Response(file.stream(), {
      headers: { "content-type": http.toMIME(file.name) },
    });
  }

  return new Response("Not Found", { status: 404 });
}, { host: "localhost", port: 3000 });
```

## Timeout configuration

Timeout members are configured as whole milliseconds:

- `inactivity` is the maximum consecutive network inactivity during an
  in-flight request or response. Traffic resets it. It is not the keep-alive
  timeout after an exchange.
- `request` is the maximum total time to receive the complete incoming request,
  including headers and body. Traffic does not reset it. Handler and response
  time are excluded.
- `headers` is the maximum total time to receive complete request headers.

| Member | Node | Bun | Deno |
|--------|------|-----|------|
| `inactivity` | Supported | Supported; rounded up to seconds | Unsupported |
| `request` | Supported | Unsupported | Unsupported |
| `headers` | Supported | Unsupported | Unsupported |

Omitting `timeout`, or using an empty object, preserves the runtime defaults.
Individual omitted members also preserve native defaults. Bun's current native
inactivity default is 10 seconds. Node currently defaults to no inactivity
timeout, a 300-second request timeout, and the lesser of 60 seconds or its
request timeout for headers. In particular, Node derives an omitted header
timeout as `0` when `request: 0` is configured.

`0` disables a supported clock. Configuring any timeout member on Deno, or
configuring `request` or `headers` on Bun, throws before the server binds—even
when the value is `0`. Unsupported clocks are not silently ignored or emulated
as handler deadlines.

`inactivity` accepts values through `255000`, Bun's portable maximum. Node-only
request and header clocks accept values through `2147483647`. When both are
enabled, `headers` cannot exceed `request`; an explicit header timeout is also
validated against Node's effective request default.

The object is strict: unknown members and non-integer values are rejected. The
previous numeric form is breaking and must be migrated:

```js
// before
timeout: 30_000

// now
timeout: { inactivity: 30_000 }
```

## WebSocket portability

Text messages are strings and binary messages are `Uint8Array` values on every
runtime. The portable socket supports `send()`, `close()`, and `readyState`.
Node limits each assembled incoming or outgoing message to 16 MiB and does not
negotiate WebSocket extensions. When clients offer subprotocols, Node selects
the first offered protocol. Node caps queued outgoing data at 32 MiB;
`bufferedAmount` reports the bytes currently waiting to be written.

## Examples

### REST API

```js
import http from "@rcompat/http";

const { Status } = http;

const users = new Map();

await http.serve(async request => {
  const { pathname } = new URL(request.url);
  const { method } = request;

  // GET /users
  if (method === "GET" && pathname === "/users") {
    return Response.json([...users.values()]);
  }

  // POST /users
  if (method === "POST" && pathname === "/users") {
    const user = await request.json();
    user.id = crypto.randomUUID();
    users.set(user.id, user);
    return Response.json(user, { status: Status.CREATED });
  }

  // GET /users/:id
  const match = pathname.match(/^\/users\/(.+)$/);
  if (method === "GET" && match) {
    const user = users.get(match[1]);
    if (user) return Response.json(user);
    return Response.json({ error: "Not found" }, { status: Status.NOT_FOUND });
  }

  return new Response("Not Found", { status: Status.NOT_FOUND });
}, { host: "localhost", port: 3000 });
```

### Chat server with WebSockets

```js
import http from "@rcompat/http";

const clients = new Set();

const server = await http.serve(request => {
  if (request.headers.get("upgrade") === "websocket") {
    return server.upgrade(request, {
      open(socket) {
        clients.add(socket);
        broadcast(`User joined (${clients.size} online)`);
      },
      message(socket, message) {
        broadcast(`User: ${message}`);
      },
      close(socket) {
        clients.delete(socket);
        broadcast(`User left (${clients.size} online)`);
      },
    });
  }

  return new Response("WebSocket server");
}, { host: "localhost", port: 3000 });

function broadcast(message) {
  for (const client of clients) {
    client.send(message);
  }
}
```

## Cross-Runtime Compatibility

| Runtime | Support                                           |
| ------- | ------------------------------------------------- |
| Node.js | ✓                                                 |
| Deno    | ✓                                                 |
| Bun     | ✓                                                 |
| Browser | Constants, MIME resolution, and multipart parsing |

Browser bundles can safely import the package. [`http.MIME`](/api/http#http-mime),
[`http.Status`](/api/http#http-status), [`http.methods`](/api/http#http-methods),
[`http.toMIME`](/api/http#http-tomime), and `http.multipart()` work in browsers.
[`http.serve`](/api/http#http-serve) throws because browsers cannot listen for
incoming HTTP connections.

## License

MIT

## Contributing

See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root.
