# ts-ws-machine

> TypeScript WebSocket Client modelled as an FSM. Comes with reconnect and heartbeat support.

Latest version **1.0.2** (published 2021-01-24) · MIT license · 0 weekly downloads

## Install

```sh
npm install ts-ws-machine
pnpm add ts-ws-machine
yarn add ts-ws-machine
bun add ts-ws-machine
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.2 |
| Published | 2021-01-24 |
| First published | 2021-01-24 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 75.5 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Author | Magnus Rundberget |
| Maintainers | rundis |
| Keywords | TypeScript, WebSocket, Reconnect, HeartBeat, FSM |

## Links

- npm: https://www.npmjs.com/package/ts-ws-machine
- Repository: https://github.com/rundis/ts-ws-machine
- Homepage: https://github.com/rundis/ts-ws-machine#readme
- Issues: https://github.com/rundis/ts-ws-machine/issues
- npm.io page: https://npm.io/package/ts-ws-machine

## Dependencies (2)

- [unionize](https://npm.io/package/unionize.md) ^3.1.0
- [@libre/atom](https://npm.io/package/@libre/atom.md) ^1.3.3

## Alternatives

- [@opentelemetry/exporter-zipkin](https://npm.io/package/@opentelemetry/exporter-zipkin.md) — 14.8M weekly downloads
- [pusher-js](https://npm.io/package/pusher-js.md) — 2.0M weekly downloads
- [browserify](https://npm.io/package/browserify.md) — 1.7M weekly downloads
- [sqs-consumer](https://npm.io/package/sqs-consumer.md) — 1.7M weekly downloads
- [@sanity/eventsource](https://npm.io/package/@sanity/eventsource.md) — 930.8K weekly downloads

## Recent versions

- 1.0.2 (latest) — 2021-01-24
- 1.0.1 — 2021-01-24
- 1.0.0 — 2021-01-24

## README

# ts-ws-machine
TypeScript WebSocket Client modelled as an FSM. Comes with reconnect and heartbeat support


## Installation

```bash
npm install ts-ws-machine
```

```bash
yarn add ts-ws-machine
```




## Usage
```typescript
import { wsMachine, calcBackoff } from "ts-ws-machine";

const ws = wsMachine({
  url: "ws://localhost:3000/ws",
  pingTimeoutMillis: 10000,
  pongTimeoutMillis: 10000,
  backoffFn: calcBackoff,
  onMessage: (msg) => {
    console.log("Some websocket message", msg.data);
  }, 
  // Optional
  pingMsg: "MyPingMessage",
  // Optional
  pongMsg: "MyPongMessage",
  // Optional
  onStateChange: ({ previous, current }) => {
    console.log(`State changed: ${previous.tag} -> ${current.tag}`);
  },  
});

ws.connect();
ws.send("Msg to server");
// do other stuff
ws.disconnect();
```

### Heartbeats
WSMachine will regularly send a ping message `pingTimeoutMillis` after it last received a response from the ws endpoint.
After a ping message is sent it will wait up-to `pongTimeoutMillis`, if no response is received from the server within that time period, the underlying websocket will be closed
and WSMachine will attempt to reconnect. If indeed a message is received (either a "pong" message or any other message really), a new ping will be scheduled.

### Reconnect
WSMachine will automatically try to reconnect if the underlying websocket is closed or a heartbeat is missed.
This lib comes with a default backoff implementation (`calcBackoff`) using an exponential backoff with some "jitter".
  
```typescript
// attempt is current number of reconnects attempted
// randSeed is a random number between 0 and 1, initialized when you call then `wsMachine` function.
export type BackoffFn = (attempt: number, randSeed: number) => number

// constant backoff
const constantBackoff = (attempt: number, randSeed: number) => 1000;

// linear backoff
const linearBackoff = (attempt: number, randSeed: number) => 1000 * attempt;

// sort of random backoff :)
const randomBackoff = (attempt: number, randSeed: number) => 1000 * attempt * randSeed;

```


### Config
- **url**: A valid websocket url
- **pingTimeoutmillis**: Number of milliseconds to wait since last hearing from the server before sending a ping message
- **pongTimeoutmillis**: Number of milliseconds to wait for server to send a message response after a ping message has been sent
- **pingMessage**: (optional) Custom ping message. Default is `ping`
- **pongMessage**: (optional) Custom pong message. Default is `pong`
- **onMessage**: Callback for messages from the server. Messages matching `pongMessage` are filtered out.
- **onStateChange**: (optional) Callback for listening to state changes from the statemachine. Handy for debugging, or for displaying the health of your websocket connection.

---
_Source: https://npm.io/package/ts-ws-machine · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
