AgentSkillsCN

pubsubjs

指导开发者使用 PubSubJS 进行应用开发(包括事件、传输、属性、过滤规则,以及 React Hooks)。适用于将 PubSubJS 集成至服务或应用中,定义事件模式,或调试发布/订阅流程时使用。

SKILL.md
--- frontmatter
name: pubsubjs
description: Guidance for building with PubSubJS (events, transports, attributes, filtering, and React hooks). Apply when integrating PubSubJS into services or apps, defining event schemas, or debugging publish/subscribe flow.
license: MIT
metadata:
  author: pubsubjs
  version: "1.0.0"

PubSubJS

Use this skill when implementing or reviewing code that uses PubSubJS. Prefer the documented APIs and patterns below, and keep examples aligned with the current library behavior.

When to Apply

  • Defining event schemas and types
  • Publishing or subscribing to events
  • Adding attributes for filtering
  • Setting up transports (WebSocket, Redis, SSE)
  • Using the React hooks package

Core Patterns

Define Events

typescript
import { z } from "zod";
import { defineEvent } from "@pubsubjs/core";

export const events = defineEvent([
  {
    name: "user.created",
    schema: z.object({
      userId: z.string(),
      email: z.string().email(),
    }),
    attributesSchema: z.object({
      userId: z.string(),
      region: z.string(),
    }),
  },
]);

Publish

typescript
const publisher = new Publisher({ events, transport });

await publisher.publish("user.created", payload, {
  attributes: { userId: "u1", region: "eu" },
});

Subscribe (with filter)

typescript
const subscriber = new Subscriber({ events, transport });

subscriber.on(
  "user.created",
  (payload) => {
    console.log(payload.email);
  },
  {
    filter: {
      region: "eu",
    },
  }
);

await subscriber.subscribe();

Attributes & Filtering

Filters accept operators: $in, $exists, $prefix, $ne, $gt, $gte, $lt, $lte, $between.

  • Multiple keys are AND
  • Multiple conditions on the same key are OR
  • Dot notation is supported for nested attributes ("user.id")

Transports

WebSocket

  • WebSocketServerTransport for servers (Bun.serve)
  • WebSocketClientTransport for browsers/clients

Redis

  • RedisTransport for distributed systems (URL + optional channel prefix)

SSE

  • SSEClientTransport is client-only
  • SSE servers can be implemented outside PubSubJS

React Hooks

createPubSub returns hooks, no provider required.

typescript
const { useSubscribe, usePublish } = createPubSub({ events, transport });

useSubscribe("user.created", handler, []);

const { publish } = usePublish();

Notes