Browser/Tauri-compatible NATS client factory built on `nats.ws`, providing typed publish, subscribe, request-reply, and JetStream ordered consumer support with connection lifecycle management. ## Key Components ### Interfaces & Types | Export | Description | |---|---| | `NatsClient` | Core client interface with connect/close/publish/subscribe/request methods | | `NatsClientOptions` | Connection config including servers, auth, reconnect, and exponential backoff | | `NatsSubscribeOptions` | Per-subscription options: queue group, max messages, abort signal | | `NatsPublishOptions` / `NatsRequestOptions` | Optional headers and timeout for publish/request operations | | `JetStreamOrderedSubscribeOptions` | JetStream ephemeral consumer config: deliver policy, idle threshold (milliseconds — nats.ws converts to nanos itself), and `onRecovered`, which fires when the ordered consumer had to be rebuilt and the tail may have skipped messages | | `NatsStatus` / `NatsStatusEvent` | Union type and event shape for connection lifecycle events | | `JetStreamDeliverPolicy` | `'new'` or `'byStartSequence'` for ordered consumer replay | ### Functions | Export | Description | |---|---| | `createNatsClient(options)` | Factory function — returns a fully-implemented `NatsClient` instance | ### Internal Helpers - `createExponentialBackoffHandler` — configurable backoff with optional jitter using `crypto.getRandomValues` - `mapOptionsToConnectionOptions` — maps `NatsClientOptions` to `nats.ws` `ConnectionOptions` - `toNatsHeaders` — converts `Record` or existing `NatsHeaders` into a `nats.ws` headers object - `assertClientSide` — throws if called outside a browser/WebSocket-capable runtime ## Usage Example ```typescript import { createNatsClient } from './nats' const client = createNatsClient({ servers: 'wss://nats.example.com:443', token: 'my-token', exponentialBackoff: { initialDelayMs: 500, maxDelayMs: 15_000, jitter: true, }, }) client.onStatus(({ status }) => console.log('NATS status:', status)) await client.connect() // Publish JSON client.publishJson('events.user.created', { id: '123', name: 'Alice' }) // Request-reply const response = await client.requestJson<{ ok: boolean }>( 'rpc.user.create', { name: 'Bob' }, { timeoutMs: 3000 }, ) // Core subscribe client.subscribeJson<{ id: string }>('events.user.*', (payload, msg) => { console.log('Received:', payload) }) // JetStream ordered (live-tail) const handle = await client.subscribeJetStreamOrdered( (msg) => console.log('JetStream:', msg.subject), { streamName: 'EVENTS', filterSubject: 'events.>', deliverPolicy: 'new', }, ) // Cleanup handle.unsubscribe() await client.close() ``` ## Source [`nats.ts`](https://github.com/flamingo-stack/openframe-oss-lib/blob/main/nats.ts)