@wrnexus/pubsub
In-process and Redis-backed publish/subscribe.
Install the package
After WorkRoot approves private registry access, install the release-aligned package:
bun add @wrnexus/pubsub@0.8.7Request preview access. Never put registry tokens in source control.
Topic-based publish/subscribe with a pluggable driver — in-process by default, Redis for cross-process messaging.
Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.
Overview
@wrnexus/pubsub is a small server-side pub/sub bus. You publish messages to a topic and subscribe with topic patterns; handlers fire for matching topics. The default driver keeps everything in-process, and you can swap in the Redis driver (@wrnexus/pubsub/redis) to fan messages out across processes or hosts. It also backs @wrnexus/core's realtime bridge for horizontal scaling.
bun add @wrnexus/pubsub
Private package — the machine must be authenticated to the wrnexus npm org
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
API
createPubSub(driver?): PubSub
Creates a bus over a driver. Defaults to memoryDriver() (in-process).
interface PubSub {
publish<T = unknown>(topic: string, message: T): Promise<void>;
subscribe<T = unknown>(pattern: string, handler: Handler<T>): () => void;
close(): Promise<void>;
}
type Handler<T = unknown> = (message: T, topic: string) => void | Promise<void>;
publish(topic, message)— resolves once the driver and in-memory async handlers finish.subscribe(pattern, handler)— returns an unsubscribe function.close()— idempotently rejects new work, clears local subscriptions, and closes the driver.
Pattern matching
Subscription patterns match in three ways:
- Exact —
"order:created"matches only that topic. - Prefix —
"order:*"matches any topic starting with"order:". - Everything —
"*"matches all topics.
memoryDriver(): PubSubDriver
The default in-process driver. Handlers are invoked synchronously (fire-and-forget for async handlers) whenever a published topic matches a registered pattern.
interface PubSubDriver {
publish(topic: string, message: unknown): void | Promise<void>;
subscribe(pattern: string, handler: Handler): () => void;
}
@wrnexus/pubsub/redis — redisDriver(url?)
A cross-process driver backed by Redis. It speaks RESP over a raw TCP socket via Bun.connect, so it adds no npm dependency. url defaults to $REDIS_URL, then redis://localhost:6379. The URL may carry a password and a database index (e.g. redis://:secret@host:6379/2).
function redisDriver(url?: string, options?: RedisDriverOptions): PubSubDriver & { close(): void };
- Exact topics use Redis
SUBSCRIBE; wildcard patterns (ns:*,*) use - Messages are JSON-stringified on publish and
JSON.parsed on receipt; a payload close()tears down both the subscriber and publisher connections.- Lost sockets reconnect with bounded exponential backoff and active subscriptions
PSUBSCRIBE, whose glob semantics line up with this library's matching.
that isn't valid JSON is delivered as the raw string.
are replayed. maxPending bounds unavailable-connection writes (default 1000); reconnectDelayMs and reconnectMaxDelayMs tune recovery (100ms/5000ms).
RESP codec (internal)
redis.ts uses a minimal RESP implementation exported from resp.ts (encodeCommand, parseReply, concat, and the RespValue type). These are implementation details of the Redis driver, not part of the public package entry.
Usage
In-process (default):
import { createPubSub } from "@wrnexus/pubsub";
const bus = createPubSub();
const off = bus.subscribe("order:*", (msg, topic) => {
console.log(topic, msg);
});
await bus.publish("order:created", { id: 7 });
off(); // unsubscribe
Cross-process with Redis:
import { createPubSub } from "@wrnexus/pubsub";
import { redisDriver } from "@wrnexus/pubsub/redis";
const driver = redisDriver("redis://localhost:6379");
const bus = createPubSub(driver);
bus.subscribe("order:*", (msg, topic) => {
// received on any app process subscribed to this pattern
});
await bus.publish("order:created", { id: 7 });
// on shutdown (also closes the driver)
await bus.close();
Requirements / Notes
- Bun-only. The Redis driver depends on
Bun.connect; it throws - The Redis driver reads
REDIS_URLfrom the environment when nourlis passed. - Backs [
@wrnexus/core](../core)'s realtime bridge for horizontal scaling. - No external npm dependencies — the Redis client is a self-contained RESP codec.
redisDriver requires the Bun runtime (Bun.connect). outside Bun. The default in-memory driver has no runtime dependencies.
Complete TypeScript API
Generated from the exact installed package declarations.
import { Context } from '@wrnexus/core';
import { SubjectContext } from '@wrnexus/rpc';
interface MessageEnvelope<T = unknown> {
id: string;
topic: string;
data: T;
timestamp: number;
attempts: number;
}
interface ResilientPubSubOptions {
retries?: number;
retryDelayMs?: number;
onError?: (error: unknown, envelope: MessageEnvelope) => void;
}
declare function createResilientPubSub(driver: PubSubDriver, options?: ResilientPubSubOptions): PubSub;
interface PresenceMember {
id: string;
metadata?: Record<string, unknown>;
joinedAt: number;
expiresAt: number;
}
declare class PresenceChannel {
#private;
private readonly ttlMs;
private readonly now;
constructor(ttlMs?: number, now?: () => number);
touch(id: string, metadata?: Record<string, unknown>): PresenceMember;
leave(id: string): boolean;
list(): PresenceMember[];
prune(): number;
}
interface SubjectPubSub {
publish<T>(ctx: Context, topic: string, message: T): Promise<void>;
subscribe<T>(pattern: string, handler: (message: T, topic: string, subject?: SubjectContext) => void | Promise<void>): () => void;
}
/**
* Authenticated pub/sub envelope. The token uses a fixed, purpose-specific
* audience; subscribers verify it before exposing the message to a handler.
*/
declare function subjectPubSub(bus: PubSub): SubjectPubSub;
/**
* @wrnexus/pubsub — topic-based publish/subscribe with a pluggable driver.
* The default is in-process; swap in a Redis/NATS driver for cross-instance
* messaging (it also backs @wrnexus/core's realtime bridge).
*
* const bus = createPubSub();
* const off = bus.subscribe("order:*", (msg, topic) => {...});
* await bus.publish("order:created", { id: 7 });
*
* Subscriptions match exact topics, "ns:*" prefixes, and "*" (everything).
*/
type Handler<T = unknown> = (message: T, topic: string) => void | Promise<void>;
interface PubSubDriver {
publish(topic: string, message: unknown): void | Promise<void>;
subscribe(pattern: string, handler: Handler): () => void;
close?(): void | Promise<void>;
}
interface PubSub {
publish<T = unknown>(topic: string, message: T): Promise<void>;
subscribe<T = unknown>(pattern: string, handler: Handler<T>): () => void;
/** Stop new work, remove subscriptions, and close the backing driver. */
close(): Promise<void>;
}
/** In-process pub/sub driver (default). */
declare function memoryDriver(): PubSubDriver;
/** Create a pub/sub bus over a driver (in-memory by default). */
declare function createPubSub(driver?: PubSubDriver): PubSub;
interface NatsClient {
publish(subject: string, data: Uint8Array): void | Promise<void>;
subscribe(subject: string, handler: (data: Uint8Array, subject: string) => void): () => void;
close?(): void | Promise<void>;
}
declare function natsDriver(client: NatsClient): PubSubDriver;
interface KafkaClient {
publish(topic: string, value: string): void | Promise<void>;
subscribe(pattern: string, handler: (value: string, topic: string) => void): () => void;
close?(): void | Promise<void>;
}
/** Kafka adapter contract; consumer-group/rebalance policy remains owned by the selected client. */
declare function kafkaDriver(client: KafkaClient): PubSubDriver;
export { type Handler, type KafkaClient, type MessageEnvelope, type NatsClient, PresenceChannel, type PresenceMember, type PubSub, type PubSubDriver, type ResilientPubSubOptions, type SubjectPubSub, createPubSub, createResilientPubSub, kafkaDriver, memoryDriver, natsDriver, subjectPubSub };
Examples
Copy-ready examples from the installed package documentation.
In-process (default)
import { createPubSub } from "@wrnexus/pubsub";
const bus = createPubSub();
const off = bus.subscribe("order:*", (msg, topic) => {
console.log(topic, msg);
});
await bus.publish("order:created", { id: 7 });
off(); // unsubscribeCross-process with Redis
import { createPubSub } from "@wrnexus/pubsub";
import { redisDriver } from "@wrnexus/pubsub/redis";
const driver = redisDriver("redis://localhost:6379");
const bus = createPubSub(driver);
bus.subscribe("order:*", (msg, topic) => {
// received on any app process subscribed to this pattern
});
await bus.publish("order:created", { id: 7 });
// on shutdown (also closes the driver)
await bus.close();