# apigenie-generator server ws

Source: https://apigenie.pl/docs/reference/generator/server-ws
Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md).
Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md).

[Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification)

Generate a TypeScript (Node.js) server of the WebSocket channels of an AsyncAPI document.

## Usage

```sh
apigenie-generator server ws [...OPTIONS] INPUT_FILE
```

## Description

The input must be an AsyncAPI 3.x document. Documents referencing other files are bundled first.

The server serves the WebSocket channels of the document (see
[`apigenie-generator client ws`](/docs/reference/generator/client-ws)) at their addresses, using the
[ws](https://github.com/websockets/ws) package. By default it implements the application the
document describes: it sends the messages of `send` operations and receives the messages of
`receive` operations. Set the `perspective` option to `counterpart` to swap them.

```ts
import { createServer } from "chat-api-server";

const server = createServer({
  room: {
    onConnect(session) {
      console.log(`joined ${session.params.roomId}`);
    },
    onJoin(session, payload) {
      session.sendRoomEvent({ kind: "joined", user: payload.user });
    },
  },
});
await server.listen(8080);
```

For every channel, the generated code has:

- a session class (`RoomSession`): a connection of a client, with the values of the address
  parameters (`params`), the query parameters converted to the types of the WebSocket binding
  (`query`), the handshake `headers`, the headers of the WebSocket binding typed by its schema
  (`bindingHeaders`), what the authenticator returned (`principal`, see below),
  `send<Message>(payload)` methods and `close()`. The
  reply messages of an operation whose `reply` is on the same channel get `send<Message>`
  methods too, and, when the request and reply messages have a correlation id in their payloads,
  `replyTo<Operation>(request, reply)` sends the reply with the request's correlation id copied
  into it (e.g. `session.replyToRequestPickup(request, confirmation)`).
- a handler interface (`RoomHandler`) with `onConnect`, `on<Message>` for every message the
  server receives (when the channel receives one message, or when its messages can be told apart
  by a property with a distinct constant value), `onMessage` for every message of a channel
  receiving several, `onUnknownMessage`, `onClose` and `onError`

The handlers of a session are called one at a time, in the order of the events; a handler
returning a promise delays the next one until it settles. Errors thrown by handlers are passed to
`onError`.

`createServer(handlers, options)` serves the channels with handlers. Connections to other addresses
are rejected with status 404, and handshakes without a header that the headers schema of the
channel's WebSocket binding requires with status 400. Options are an existing HTTP server to attach
to (`server`), a path prefix of all addresses (`basePath`), the authenticators of the security
schemes (`authenticate`) and `onAuthenticationError(error, request)`, called when an authenticator throws or an
authenticated connection can't be accepted (by default, `console.error`). The result has `listen(port, host)`, `close()`, `address()`
and `httpServer`.

### Security

A channel takes the security schemes of its operations, or of its servers for an operation
without any. When a channel has some, the `authenticate` option is required: an `Authenticators`
object with a function per scheme, called with the credential that the handshake carries and a
context with the scheme key, the scheme, its scopes, the HTTP request and the address
parameters. The connection is accepted when the authenticator of one of the channel's schemes
returns a value other than `false`, `null` or `undefined`; that value becomes `session.principal`.
Otherwise the handshake is refused with status 401. When the authenticator throws or rejects,
the handshake is refused with status 500 and the error goes to `onAuthenticationError`.

```ts
const server = createServer(handlers, {
  authenticate: {
    streamToken: (token) => tokens.verify(token), // the merchant, or undefined
    oauth2: async (token, { scopes }) => introspect(token, scopes),
  },
});
```

The credential is read from the handshake by the type of the scheme:

| Scheme | Credential |
| ------ | ---------- |
| `httpApiKey` | the query parameter, header or cookie named by `name` and `in` |
| `http` with scheme `basic` | `user:password` of the `Authorization` header |
| `http` with scheme `bearer`, `oauth2`, `openIdConnect` | the bearer token of the `Authorization` header, or of the `access_token` query parameter |

The authenticator checks the scopes; the server doesn't. Other scheme types, such as
`userPassword`, `X509` or the SASL schemes, can't be sent with a WebSocket handshake: they are
left out with a warning.

The generated package contains `src/types.ts`, `src/messages.ts`, `src/server.ts`,
`src/metadata.ts`, `src/runtime.ts` and `src/index.ts`, with `package.json` (depending on `ws`)
and `tsconfig.json`.

Not supported, and reported as warnings: replies on another channel or at a runtime-expression
address, channels without an address, and channels sharing an address with another channel (only
the first one is served), and security schemes that a WebSocket handshake can't carry.

## Extensions

| Extension | Effect |
| --------- | ------ |
| `x-apigenie.codegen.name` | on a channel: the base of its names (`LobbyHandler`); on a message: the base of its types (`PostPayload`); on a component schema: the name of its type |
| `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) |

The extensions can live in an overlay for this target instead of in the document, e.g.
`ws.overlay.yaml`:

```yaml
overlay: 1.0.0
info:
  title: WebSocket names
  version: 1.0.0
actions:
  - target: $.channels.room
    update:
      x-apigenie:
        codegen:
          name: Lobby
  - target: $.components.messages.ChatMessage
    update:
      x-apigenie:
        codegen:
          name: Post
```

```sh
apigenie-generator server ws asyncapi.yaml --overlay ws.overlay.yaml -o out
```

## Options

### -c, --config

Path to the configuration file to use. See the "Configuration" section for more information.

### --overlay OVERLAY

Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the
extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those
listed under `commands.generate.server_ws.overlay` in the configuration file (with paths relative to
it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to
the AsyncAPI document bundled with the files it references.

### --strict

Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated)
instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`).

### --check

Writes nothing: compares what the generator would write with the output directory, prints the
files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See
[Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date).

### -o, --output

Directory where the package is generated.

### --package-name

Name of the generated package. Defaults to the title of the API followed by `-server`.

### --package-version

Version of the generated package. Defaults to the version of the API.

## Configuration

```yaml
version: '1.0'
commands:
  generate:
    server_ws:
      layout: package
      import_extension: .js
      perspective: application
```

| Option | Description |
| ------ | ----------- |
| `layout` | `package` (default): an npm package with sources in `src/`; `sources`: the sources only |
| `import_extension` | Extension of relative imports: `.js` (default, Node.js) or an empty string (bundlers) |
| `perspective` | `application` (default): the described application; `counterpart`: its client |

## Verification

The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi).

This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives.

| Results | Level 1 | Level 2 | Level 3 |
| --- | --- | --- | --- |
| Release 0.12.0 | ✓ snapshots of 3.0; 30 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8) | ✓ 4 of 4 operations pass (node) |
| Development version | ✓ snapshots of 3.0; 30 supported, 0 not yet | runs before a release | runs before a release |
