npm package: @sansavision/pulse-node
Description: Framework-agnostic native Node.js bindings for the Pulse protocol engine (QUIC relay, SFU, RPC, message queue).
Author: SansaVision
Latest version: 0.1.0

# @sansavision/pulse-node

> **Framework-agnostic** native Node.js bindings for the Pulse protocol engine.

Embeds the full Rust Tokio runtime as a native C-ABI addon (`.node`), allowing **any** Node.js process to run a high-performance Pulse relay, RPC server, SFU, or message queue — directly inside the same OS process, without Docker or Kubernetes.

## Supported Frameworks

This is **not** tied to any specific framework. It works with:

- **Next.js** (custom server mode via `node server.js`)
- **Remix** (Express/Fastify adapter)
- **SvelteKit** (Node adapter)
- **NestJS**, **Fastify**, **Express**, **Hono**, **Koa**
- **TanStack Start** (Vinxi adapter)
- Plain `node app.js`

## Installation

```bash
npm install @sansavision/pulse-node
```

## Quick Start

```javascript
const { PulseRelay, PulseRoom, PulseCodec, pulseVersion } = require('@sansavision/pulse-node');

// Start an embedded relay on port 4001
const relay = new PulseRelay({ bind: '0.0.0.0:4001', region: 'us-east-1' });
await relay.start();

// Create an SFU room for real-time media routing
const room = new PulseRoom('my-room');
await room.addParticipant('alice');
await room.addParticipant('bob');
await room.subscribe('bob', 'audio');

console.log(`Pulse v${pulseVersion()} relay running with ${await room.participantCount()} participants`);
```

## API Reference

### `PulseRelay`

Embedded QUIC + WebSocket relay server.

```typescript
const relay = new PulseRelay({
  bind: '0.0.0.0:4001',      // TCP/UDP bind address
  region: 'eu-west-1',        // Region for service discovery
  controlUrl: 'http://...',   // Control plane URL (optional)
  capacity: 100000,           // Max concurrent connections
  maxPayloadBytes: 1048576,   // Max PLP packet size (1 MiB)
  enableWebsocket: true,      // WebSocket gateway for browsers
});

const info = await relay.start();   // Start listening (non-blocking)
await relay.isRunning();            // Check status
await relay.stop();                 // Graceful shutdown
```

### `PulseRoom`

In-process Selective Forwarding Unit (SFU) for media routing.

```typescript
const room = new PulseRoom('call-123');
await room.addParticipant('alice');
await room.subscribe('alice', 'video-stream');
await room.participantCount();       // => 1
await room.removeParticipant('alice');
```

### `PulseRpc`

In-process RPC server using the Pulse RPC protocol.

```typescript
const rpc = new PulseRpc();
await rpc.register('user.getProfile');
await rpc.register('billing.createInvoice');
const methods = await rpc.methods(); // => ['user.getProfile', 'billing.createInvoice']
```

### `PulseQueue`

In-process durable message queue with at-least-once delivery.

```typescript
const queue = new PulseQueue('notifications');
const seq = await queue.enqueue(Buffer.from('Hello'));
const msg = await queue.dequeue();   // => Buffer('Hello')
const depth = await queue.depth();   // => 0
```

### `PulseCodec`

Low-level PLP binary packet encoder/decoder.

```typescript
const codec = new PulseCodec();

// Encode: packetType (0x05=StreamData), streamId, sequence, payload
const encoded = codec.encode(0x05, 42, 100, Buffer.from('data'));

// Decode
const { packetType, streamId, sequence, payload } = codec.decode(encoded);
```

### Utility Functions

```typescript
pulseVersion(); // => '0.1.0'
plpVersion();   // => 1
```

## Architecture

```
┌─────────────────────────────────────────────────┐
│              Node.js Process                     │
│                                                  │
│  ┌──────────────┐    ┌───────────────────────┐  │
│  │   V8 Engine   │    │  Rust Tokio Runtime   │  │
│  │  (Your App)   │    │  (Pulse Engine)       │  │
│  │               │    │                       │  │
│  │  Express/     │◄──►│  QUIC Server          │  │
│  │  Next.js/     │    │  WebSocket Gateway    │  │
│  │  Remix/       │    │  SFU Packet Router    │  │
│  │  SvelteKit    │    │  RPC Dispatcher       │  │
│  │  etc.         │    │  Message Queue        │  │
│  │               │    │  PLP Codec            │  │
│  └──────────────┘    └───────────────────────┘  │
│        libuv              tokio threads          │
└─────────────────────────────────────────────────┘
```

The Rust Tokio runtime runs on dedicated OS threads, completely independent of Node's single-threaded `libuv` event loop. This means:

- **Zero event-loop blocking** — `setTimeout`, `setInterval`, and async I/O work exactly as expected
- **Native performance** — compiled Rust, not interpreted JavaScript
- **Shared memory** — no IPC overhead between your app and the relay engine

## PLP Packet Types

| Value | Name | Description |
|-------|------|-------------|
| `0x01` | Connect | Client connection request |
| `0x02` | Accept | Server connection acceptance |
| `0x03` | Reject | Server connection rejection |
| `0x04` | StreamOpen | Open a new stream |
| `0x05` | StreamData | Stream data payload |
| `0x06` | StreamClose | Graceful stream close |
| `0x07` | StreamReset | Abrupt stream reset |
| `0x08` | Ping | Keepalive ping |
| `0x09` | Pong | Keepalive pong |
| `0x0A` | Metrics | Telemetry metrics |
| `0x0B` | Migrate | Connection migration |
| `0x0C` | MigrateAck | Migration acknowledgment |
| `0x0D` | RelayForward | Relay-to-relay forwarding |
| `0x0E` | Priority | Stream priority update |
| `0x0F` | GoAway | Graceful shutdown signal |

## License

MIT