Something went wrong. Try again.
A generic websocket connection with Zod schema validation and on message execution.
Something went wrong. Try again.
Files
- TypeScript 100%
README.md
# wah
Generic WebSocket action handler for TypeScript. Connect to any WebSocket, define message schemas with [Zod](https://zod.dev), and dispatch to typed handlers.
Works in both Node.js and browser environments with zero configuration — the runtime is detected automatically.
## Features
- **Cross-platform** — Runs in Node.js (using `ws`) and browsers (using native `WebSocket`) with the same API. Runtime detection is automatic.
- **Schema-matched handlers** — Register Zod schemas with handler functions. Incoming messages are validated at runtime, and all matching handlers are invoked with fully typed data.
- **Multi-service failover** — Provide multiple WebSocket URLs. On connection failure, wah cycles through them with exponential backoff.
- **Dynamic query parameters** — Update URL query parameters at runtime. The connection gracefully reconnects with the new URL.
- **Bidirectional communication** — Handlers receive a `send()` function to reply through the same WebSocket.
- **Error isolation** — Handler errors are emitted as events, never crash the connection.
- **Configurable logging** — Built-in logger with log levels, or bring your own.
## Installation
```bash
pnpm add @vinerima/wah
```
In Node.js, install `ws` as well:
```bash
pnpm add ws
```
`ws` is an optional peer dependency — browser environments use the native `WebSocket` and don't need it.
## Quick Start
```typescript
import { WebSocketClient, LogLevel } from "@vinerima/wah";
import { z } from "zod";
// Define message schemas
const tradeSchema = z.object({
type: z.literal("trade"),
symbol: z.string(),
price: z.number(),
volume: z.number(),
});
const systemSchema = z.object({
type: z.literal("system"),
code: z.number(),
message: z.string(),
});
// Create client
const client = new WebSocketClient({
service: "wss://stream.example.com/v1",
queryParams: { apiKey: "abc123", symbols: "BTC,ETH" },
logger: { enabled: true, level: LogLevel.DEBUG },
});
// Register handlers — data is fully typed via z.infer
client.handle(tradeS…