@ably/react-web-cli

中文文档
1.0.0发布于 2026/05/01Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 2532

React component for embedding the Ably CLI in a web terminal

原始使用文档
文档目录18 节
  1. Features
  2. Installation
  3. Prerequisites
  4. Usage
  5. Props
  6. Implementing a Signing Endpoint
  7. Breaking Changes & Migration
  8. HMAC-Signed Authentication (Breaking Change)
  9. Connection States
  10. Server-Initiated Disconnections
  11. Session Resumption
  12. Split-Screen Mode
  13. Setting Up a Terminal Server
  14. Notes
  15. Debugging & Verbose Logging
  16. Example Project
  17. Development
  18. License

@ably/react-web-cli

npm (scoped) License

A React component for embedding an interactive Ably CLI terminal in web applications.

Ably Web CLI demo screenshot

Features

  • Embed a fully-featured Ably CLI session (xterm.js) inside any React app.
  • Secure WebSocket connection to the Ably terminal-server using HMAC-signed authentication with signedConfig and signature.
  • First-class terminal UX:
    • Terminal-native status messages with ANSI colors
    • Animated spinner while (re)connecting
    • Live countdown and clear guidance (press Enter to cancel / retry)
    • ASCII modal boxes for important status messages
  • Robust connection handling:
    • Automatic exponential-back-off reconnects (0 s, 2 s, 4 s, 8 s …)
    • Configurable maximum reconnection attempts (default: 15) before switching to manual reconnect
    • Proper handling of server-initiated disconnections with specific error codes
  • Session resumption on page reload or transient network loss (resumeOnReload).
  • Split-screen mode with two independent terminal sessions at once.
  • Works in fullscreen or in a resizable drawer (see examples/web-cli).
  • Written in TypeScript & totally tree-shakable.

Installation

# Using npm
npm install @ably/react-web-cli

# Using yarn
yarn add @ably/react-web-cli

# Using pnpm
pnpm add @ably/react-web-cli

Prerequisites

  • React 17.0.0 or higher
  • A running instance of the Ably CLI terminal server (see @ably/cli-terminal-server)
  • A backend signing endpoint to generate HMAC-signed credentials (see implementation guide below)

Usage

import { useState, useEffect } from "react";
import { AblyCliTerminal } from "@ably/react-web-cli";

export default function MyTerminal() {
  const [status, setStatus] = useState("disconnected");
  const [signedConfig, setSignedConfig] = useState("");
  const [signature, setSignature] = useState("");

  // Sign credentials via your backend endpoint
  // See examples/web-cli/api/sign.ts for implementation reference
  async function signCredentials(apiKey: string) {
    const response = await fetch("/api/sign", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ apiKey }),
    });
    const { signedConfig, signature } = await response.json();
    setSignedConfig(signedConfig);
    setSignature(signature);
  }

  // Authenticate on mount (or when user provides credentials)
  useEffect(() => {
    const apiKey = "YOUR_ABLY_API_KEY"; // Get from user input or config
    signCredentials(apiKey);
  }, []);

  if (!signedConfig || !signature) {
    return <div>Loading...</div>;
  }

  return (
    <div style={{ height: 500 }}>
      <AblyCliTerminal
        websocketUrl="wss://web-cli.ably.com"
        signedConfig={signedConfig}
        signature={signature}
        initialCommand="ably --version"
        onConnectionStatusChange={setStatus}
        onSessionEnd={(reason) => console.log("session ended", reason)}
        onSessionId={(id) => console.log("session id", id)}
        resumeOnReload
        maxReconnectAttempts={15}
      />

      <p>Status: {status}</p>
    </div>
  );
}

Props

PropTypeRequiredDefaultDescription
websocketUrlstring✅-URL of the WebSocket terminal server
signedConfigstring✅-JSON-encoded signed config containing credentials and metadata (HMAC authenticated)
signaturestring✅-HMAC-SHA256 signature of the signedConfig for secure authentication
initialCommandstringNo-Command to run on startup
onConnectionStatusChangefunctionNo-Callback when connection status changes
onSessionIdfunctionNo-Callback when session ID is received
onSessionEndfunctionNo-Callback when session ends
maxReconnectAttemptsnumberNo15Maximum reconnection attempts before giving up
resumeOnReloadbooleanNofalseWhether to attempt to resume an existing session after page reload
enableSplitScreenbooleanNofalseEnable split-screen mode with a second independent terminal

Note: The signedConfig and signature must be generated by your backend using HMAC-SHA256 signing. Never sign credentials in the browser - this would expose your signing secret.

Reference implementations:

  • Vercel: See examples/web-cli/api/sign.ts for a serverless function example
  • Node.js: See examples/web-cli/server/sign-handler.ts for the shared signing logic
  • Vite Dev: See examples/web-cli/vite.config.ts for development middleware

Your signing secret must match the terminal server's SIGNING_SECRET configuration. Contact your platform team for the secret or refer to the terminal server documentation.

Implementing a Signing Endpoint

You must implement a backend endpoint to sign credentials. Here's a minimal example:

// Example: /api/sign endpoint (Node.js/Express/Vercel)
import crypto from "crypto";

export default function handler(req, res) {
  const { apiKey } = req.body;
  const secret = process.env.SIGNING_SECRET; // From environment variable

  // Build config object
  const config = {
    apiKey,
    timestamp: Date.now(),
  };

  // Sign it with HMAC-SHA256
  const configString = JSON.stringify(config);
  const hmac = crypto.createHmac("sha256", secret);
  hmac.update(configString);
  const signature = hmac.digest("hex");

  res.json({ signedConfig: configString, signature });
}

Security Requirements:

  • ⚠️ Never embed your signing secret in client-side code
  • ⚠️ Always sign on your secure backend server
  • ✅ Signing secret must match the terminal server's configuration
  • ✅ Use HTTPS in production to protect API keys in transit

Full implementation examples:

  • See examples/web-cli/ directory for complete working examples
  • Includes Vercel serverless function, Vite dev middleware, and React integration

Breaking Changes & Migration

HMAC-Signed Authentication (Breaking Change)

This is a breaking change. The authentication mechanism has been updated to use HMAC-signed credentials for improved security.

Old API (deprecated):

<AblyCliTerminal
  websocketUrl="wss://web-cli.ably.com"
  ablyApiKey="YOUR_ABLY_API_KEY"           // ❌ Removed
  ablyAccessToken="YOUR_ABLY_TOKEN"        // ❌ Removed
  ablyEndpoint="nonprod:sandbox"           // ❌ Removed
  ablyControlHost="staging-control..."     // ❌ Removed
/>

New API (required):

<AblyCliTerminal
  websocketUrl="wss://web-cli.ably.com"
  signedConfig={signedConfig}              // ✅ Required
  signature={signature}                    // ✅ Required
/>

Migration Steps:

  1. Implement backend signing: Create a /api/sign endpoint on your backend (see "Implementing a Signing Endpoint" section above)
  2. Get signing secret: Obtain the SIGNING_SECRET from your platform team (must match terminal server configuration)
  3. Update your React code:
    • Remove old props: ablyApiKey, ablyAccessToken, ablyEndpoint, ablyControlHost
    • Call your /api/sign endpoint to get signedConfig and signature
    • Pass the signed credentials to AblyCliTerminal

Why this change?

The new HMAC-signed authentication prevents credential tampering and ensures that configuration settings (like endpoint and control host) are authenticated by the server. This provides better security for embedded terminal sessions.

Connection States

The component manages several connection states that your application can respond to:

  • initial: Terminal is initializing
  • connecting: Attempting to connect to the server
  • connected: Successfully connected and ready
  • disconnected: Connection closed by server or manually by user
  • reconnecting: Attempting to reconnect after a connection drop
  • error: Connection error or other terminal error

Server-Initiated Disconnections

The terminal properly handles server-initiated disconnections with specific WebSocket close codes:

CodeDescriptionBehavior
1000Normal closureShows reason in terminal, requires manual reconnect
1001Server going awayShows service restart message, requires manual reconnect
1011Server errorShows unexpected condition message, requires manual reconnect
1013Service unavailableShows service unavailable message, requires manual reconnect
4000Generic server disconnectShows server-provided reason, requires manual reconnect
4001Authentication failedShows authentication error with instructions, requires manual reconnect
4008Policy violationShows auth timeout/format message, requires manual reconnect
4429Capacity limit reachedShows capacity message with CLI install instructions, requires manual reconnect

For other WebSocket close codes, the terminal will automatically attempt to reconnect using an exponential backoff strategy.

Session Resumption

When resumeOnReload is enabled, the terminal will store the session ID in sessionStorage and attempt to resume the session after a page reload. This allows for a seamless experience when navigating away and back to the page.

Split-Screen Mode

When enableSplitScreen is set to true, the component displays a split icon in the top-right corner of the terminal. Clicking this icon splits the view into two independent terminal sessions side by side.

Features of split-screen mode:

  • Two completely independent terminal sessions sharing the same credentials
  • Each terminal has its own tab with a close button
  • Both terminals resize automatically to maintain optimal layout
  • Status and connection management happens independently for each terminal
  • Close either terminal to return to single-pane mode

The feature is designed for developers who need to run multiple commands simultaneously, such as subscribing to a channel in one pane while publishing to it in another.

Setting Up a Terminal Server

The terminal server required for this component is provided in a separate repository. Please refer to the @ably/cli-terminal-server repository for:

  • Installation instructions
  • Configuration options
  • Running the server locally
  • Docker deployment instructions

For production use, the Ably Web CLI connects to wss://web-cli.ably.com by default, which is a hosted instance of the terminal server.

Notes

  • The terminal requires a container for sizing, so make sure the parent element has a defined height and width.
  • The component handles reconnection automatically with exponential backoff.
  • Only ably, clear, and exit commands are available in the terminal by default.
  • The terminal supports full xterm.js functionality including colors and Unicode.

Debugging & Verbose Logging

The component ships with a built-in verbose logger that is disabled by default. Enable it in any of the following ways before the component mounts:

  1. Query-string flag – simply add ?cliDebug=true to the page URL. Example: http://localhost:5173/?cliDebug=true (The flag may be combined with other query parameters.)

  2. Runtime global flag – from the browser DevTools console run:

window.ABLY_CLI_DEBUG = true;

The terminal will now emit detailed lifecycle logs prefixed with [AblyCLITerminal DEBUG]. Remove the flag or refresh without the query parameter to return to silent mode.

Example Project

For a complete example of using this component, see the web-cli example in the Ably CLI repository.

Development

# Install dependencies
pnpm install

# Build the package
pnpm build

# Run tests
pnpm test

License

Apache-2.0

版本与发布记录

@ably/react-web-cli 共发布 13 个版本,首次发布于 2025/04/11;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.0.0latest2026/05/016 个月前
0.17.02026/03/097 个月前
0.16.02026/01/209 个月前
0.15.02025/12/0411 个月前
0.14.02025/11/061 年前
0.13.12025/09/241.1 年前

关于 @ably/react-web-cli 的常见问题

@ably/react-web-cli 是什么?

React component for embedding the Ably CLI in a web terminal

如何安装 @ably/react-web-cli?

在项目目录运行 npm install @ably/react-web-cli,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=17.0.0)、react-dom(>=17.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ably/react-web-cli 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ably/react-web-cli 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@ably/react-web-cli 可以商用吗?

@ably/react-web-cli 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@ably/react-web-cli 的下载量有多少?

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

@ably/react-web-cli 还在维护吗?

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