@arkstack/realtime

中文文档
0.22.2发布于 2026/11/07ES Module零依赖近 30 天下载 2451

Client for consuming Arkstack realtime notifications (Pusher/Firebase), with framework-agnostic core plus React and Vue bindings.

原始使用文档
文档目录9 节
  1. Install
  2. Usage
  3. Client events
  4. React
  5. Vue
  6. Firebase
  7. Custom transport
  8. API
  9. License

@arkstack/realtime

@arkstack/realtime

The client for consuming Arkstack realtime notifications. A framework-agnostic core plus React and Vue bindings, backed by Pusher or Firebase Cloud Messaging.

Pairs with the realtime notification driver in @arkstack/notifications, which broadcasts a per-user channel (user.<id>) that this client subscribes to.

Install

pnpm add @arkstack/realtime

Then install the client SDK for your transport (both are optional peer dependencies — install only the one you use):

pnpm add pusher-js   # Pusher transport
pnpm add firebase    # Firebase transport

Usage

Create a client and subscribe to a user's channel. subscribe/forUser resolve to an unsubscribe function.

import { createRealtime } from '@arkstack/realtime'

const realtime = createRealtime({
  transport: 'pusher',
  pusher: {
    key: import.meta.env.VITE_PUSHER_KEY,
    cluster: 'mt1',
    authEndpoint: '/broadcasting/auth',
  },
})

const unsubscribe = await realtime.forUser(user.id, (notification) => {
  console.log(notification.title, notification.description)
})

// later
unsubscribe()
await realtime.disconnect()

Client events

Pusher private and presence channels can send ephemeral client events (often called whispers). Subscribe to the channel before sending an event:

const stopTyping = await realtime.listenForWhisper('private-room.7', 'typing', ({ userId }) =>
  console.log(`${userId} is typing`),
)

await realtime.whisper('private-room.7', 'typing', { userId: user.id })
stopTyping()

The client- prefix is added automatically. Pusher sends client events over its private/presence channel. Firebase uses Realtime Database to publish the same ephemeral events across connected clients. Use listen(channel, event, handler) and trigger(channel, event, payload) when you need the lower-level APIs with exact event names.

Each notification matches the payload broadcast by the server:

interface RealtimeNotification {
  id: string
  type: string | null
  title: string
  description: string
  actionText?: string | null
  actionLink?: string | null
  meta?: Record<string, unknown> | null
  read_at: string | null
  created_at: string
}

React

import { useNotifications } from '@arkstack/realtime/react'

function Bell({ realtime, userId }) {
  const { notifications, latest, clear } = useNotifications(realtime, realtime.channelFor(userId), { limit: 20 })

  return (
    <span onClick={clear}>
      {notifications.length} · {latest?.title}
    </span>
  )
}

The hook accumulates notifications (newest first), caps them at limit, and unsubscribes automatically on unmount or when client/channel change.

Vue

<script setup>
import { useNotifications } from "@arkstack/realtime/vue";

const props = defineProps(["realtime", "userId"]);
const { notifications, latest, clear } = useNotifications(
  props.realtime,
  props.realtime.channelFor(props.userId),
  { limit: 20 },
);
</script>

<template>
  <span @click="clear">{{ notifications.length }} · {{ latest?.title }}</span>
</template>

The composable unsubscribes automatically when the component's scope is disposed.

Firebase

Firebase Cloud Messaging delivers to the device (via onMessage), so notifications are matched by event name rather than channel:

const realtime = createRealtime({
  transport: 'firebase',
  firebase: {
    apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
    projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
    appId: import.meta.env.VITE_FIREBASE_APP_ID,
    messagingSenderId: import.meta.env.VITE_FIREBASE_SENDER_ID,
    databaseURL: import.meta.env.VITE_FIREBASE_DATABASE_URL,
  },
})

Firebase client events are written below arkstack/client-events in Realtime Database and removed immediately after publishing. Configure Firebase Security Rules for the channels your authenticated clients may read and write. Override the root with firebase.clientEventsPath when needed.

Custom transport

Provide transportFactory to bridge any backend (a raw WebSocket, SSE, a test double, …):

import { createRealtime, type RealtimeTransport } from '@arkstack/realtime'

const transport: RealtimeTransport = {
  subscribe(channel, event, handler) {
    const socket = new WebSocket(`wss://example.test/${channel}`)
    socket.addEventListener('message', (e) => {
      const { event: name, payload } = JSON.parse(e.data)
      if (name === event) handler(payload)
    })

    return { channel, unsubscribe: () => socket.close() }
  },
  disconnect() {},
}

const realtime = createRealtime({ transportFactory: () => transport })

API

  • createRealtime(config) — create a RealtimeClient. Config: transport ('pusher' | 'firebase'), event (default notification), channelPrefix (default user.), pusher/firebase credentials, or a custom transportFactory.
  • client.subscribe(channel, handler) / client.forUser(userId, handler) — subscribe; returns an unsubscribe function.
  • client.listen(channel, event, handler) — listen for an arbitrary event.
  • client.listenForWhisper(channel, event, handler) / client.whisper(channel, event, payload) — receive and send Pusher client events.
  • client.trigger(channel, event, payload) — emit an exact event name through a transport that supports it.
  • client.channelFor(userId) — the per-user channel name.
  • client.disconnect() — tear down the transport connection.
  • @arkstack/realtime/react — useNotifications(client, channel, { limit? }) → { notifications, latest, clear }.
  • @arkstack/realtime/vue — useNotifications(client, channel, { limit? }) → { notifications, latest, clear, stop }.

See the notifications guide for the server side.

License

MIT

版本与发布记录

@arkstack/realtime 共发布 62 个版本,首次发布于 2026/07/07;过去 12 个月发布了 62 个版本。

版本发布日期距今
0.22.2latest2026/11/07今天
0.22.12026/11/052 天前
0.22.02026/11/052 天前
0.21.12026/11/052 天前
0.21.02026/10/2810 天前
0.20.22026/10/2315 天前

关于 @arkstack/realtime 的常见问题

@arkstack/realtime 是什么?

Client for consuming Arkstack realtime notifications (Pusher/Firebase), with framework-agnostic core plus React and Vue bindings.

如何安装 @arkstack/realtime?

在项目目录运行 npm install @arkstack/realtime,或使用 pnpm add / yarn add / bun add。

@arkstack/realtime 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/arkstack__realtime 是否存在。

@arkstack/realtime 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@arkstack/realtime 可以商用吗?

@arkstack/realtime 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@arkstack/realtime 的下载量有多少?

根据 npm 官方下载统计,@arkstack/realtime 在 2026/10/07 – 2026/11/05 这 30 天内被下载 2,451 次,日均约 82 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@arkstack/realtime 还在维护吗?

最新版本 0.22.2 发布于 2026/11/07(今天);至今共发布 62 个版本,其中过去 12 个月发布了 62 个;首次发布于 2026/07/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。