npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@ribcage/expo

v1.0.0

Published

React Native SDK for Ribcage with WebSocket and other client functionality

Readme

@ribcage/react-native-sdk

A comprehensive React Native SDK for Ribcage with WebSocket communication, automatic registration, health monitoring, and more.

Features

  • 🚀 Simple SDK Pattern: Initialize with RibcageSDK.start()
  • 🔌 Automatic Registration: Handles WebSocket handshake and client registration
  • 💓 Health Monitoring: Built-in ping/pong mechanism with connection health tracking
  • 🔄 Auto-Reconnection: Exponential backoff reconnection with message queuing
  • 📱 React Native Ready: Designed specifically for React Native environments
  • 🎯 Type-Safe: Full TypeScript support with exact Rust message type matching
  • ⚛️ React Hooks: Easy-to-use hooks for React components
  • 🏗️ Modular Architecture: Organized client structure for future expansion

Installation

bun add @ribcage/react-native-sdk

Quick Start

SDK Initialization

import { RibcageSDK, ClientType } from '@ribcage/react-native-sdk';

// Initialize the SDK
const sdk = await RibcageSDK.start({
  websocket: {
    enabled: true,
    clientType: ClientType.MOBILE,
    config: {
      host: '10.0.2.2', // Android emulator localhost
      port: 9001,
    },
    events: {
      onConnected: () => console.log('Connected!'),
      onMessage: (message) => console.log('Received:', message),
      onError: (error) => console.error('Error:', error),
    },
  },
});

// Send events to dashboard
await sdk.sendEvent('user_action', {
  type: 'button_click',
  data: { buttonId: 'submit' }
});

// Cleanup when done
await sdk.shutdown();

React Component Example

import React, { useEffect, useState } from 'react';
import { RibcageSDK, ClientType, type WebSocketMessage } from '@ribcage/react-native-sdk';

function MyComponent() {
  const [sdk, setSdk] = useState<RibcageSDK | null>(null);
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    const initSDK = async () => {
      const sdkInstance = await RibcageSDK.start({
        websocket: {
          clientType: ClientType.MOBILE,
          config: { host: '10.0.2.2', port: 9001 },
          events: {
            onConnected: () => setIsConnected(true),
            onDisconnected: () => setIsConnected(false),
            onMessage: (message) => console.log('Message:', message),
          },
        },
      });
      setSdk(sdkInstance);
    };

    initSDK().catch(console.error);

    return () => {
      if (sdk) {
        sdk.shutdown();
      }
    };
  }, []);

  const handleSendMessage = async () => {
    if (sdk && isConnected) {
      await sdk.sendEvent('test_event', {
        message: 'Hello from React Native!',
        timestamp: Date.now(),
      });
    }
  };

  return (
    <View>
      <Text>Status: {isConnected ? 'Connected' : 'Disconnected'}</Text>
      <Button title="Send Message" onPress={handleSendMessage} />
    </View>
  );
}

Using React Hooks (Alternative)

import { useWebSocket, ClientType } from '@ribcage/react-native-sdk';

function MyComponent() {
  const {
    isConnected,
    connectionState,
    messages,
    sendEvent,
  } = useWebSocket({
    config: { host: '10.0.2.2', port: 9001 },
    clientType: ClientType.MOBILE,
    events: {
      onConnected: () => console.log('WebSocket connected'),
      onMessage: (message) => console.log('New message:', message),
    },
  });

  return (
    <View>
      <Text>Status: {isConnected ? 'Connected' : 'Disconnected'}</Text>
      <Text>Client ID: {connectionState.clientId}</Text>
      <Text>Messages: {messages.length}</Text>
    </View>
  );
}

API Reference

RibcageSDK

The main SDK class providing initialization and client management.

Static Methods

  • RibcageSDK.start(config): Promise<RibcageSDK> - Initialize and start the SDK
  • RibcageSDK.init(config): Promise<RibcageSDK> - Alias for start()
  • RibcageSDK.getInstance(config): RibcageSDK - Get singleton instance

Instance Methods

  • initialize(): Promise<void> - Initialize all enabled clients
  • shutdown(): Promise<void> - Cleanup and shutdown all clients
  • isInitialized(): boolean - Check if SDK is ready
  • getWebSocketClient(): WebSocketClient | null - Get WebSocket client instance
  • connectWebSocket(): Promise<void> - Connect WebSocket if not connected
  • disconnectWebSocket(): void - Disconnect WebSocket
  • sendEvent(eventType, data): Promise<void> - Send event to dashboard
  • sendToClient(clientId, payload): Promise<void> - Send to specific client
  • broadcast(payload): Promise<void> - Broadcast to all clients

Configuration

interface RibcageSDKConfig {
  websocket?: {
    enabled?: boolean;                    // Default: true
    config?: Partial<WebSocketConfig>;    // Connection config
    events?: WebSocketEvents;             // Event callbacks
    clientType?: ClientType;              // MOBILE or DASHBOARD
    metadata?: Record<string, unknown>;   // Additional client data
  };
  // Future clients can be added here
}

interface WebSocketConfig {
  host: string;                    // Server host
  port: number;                    // Server port
  reconnectInterval?: number;      // Reconnection delay (default: 5000ms)
  pingInterval?: number;           // Ping interval (default: 30000ms)
  pongTimeout?: number;            // Pong timeout (default: 5000ms)
}

Message Types

All message types exactly match the Rust WebSocket server implementation:

// Auto-registration on connection
interface RegisterMessage {
  type: "register";
  data: {
    client_type: ClientType;
    client_id: string;
    metadata?: Record<string, unknown>;
  };
}

// Event messages (mobile → dashboard)
interface DirectMessage {
  type: "message"; 
  data: {
    from: string;
    payload: unknown;
    message_id: string;
    timestamp: number;
  };
}

// Health checks
interface PingMessage {
  type: "ping";
  data: { timestamp: number };
}

Architecture

SDK Structure

@ribcage/react-native-sdk/
├── src/
│   ├── sdk.ts                  # Main RibcageSDK class
│   ├── clients/
│   │   └── websocket/         # WebSocket client module
│   │       ├── client.ts      # WebSocket client
│   │       ├── connection.ts  # Connection management
│   │       ├── health.ts      # Health monitoring
│   │       ├── messages.ts    # Message handling
│   │       ├── types.ts       # TypeScript types
│   │       └── hooks/         # React hooks
│   └── index.ts               # Package exports

Communication Flow

  1. SDK Initialization: RibcageSDK.start() initializes all clients
  2. Auto-Registration: WebSocket client registers with server automatically
  3. Health Monitoring: Continuous ping/pong health checks
  4. Message Routing:
    • Mobile → Dashboard: All events forwarded to dashboards
    • Dashboard → Mobile: Targeted messages by client ID
  5. Error Handling: Automatic reconnection and message queuing

Future Expansion

The SDK is designed to support additional clients:

// Future clients can be easily added
const sdk = await RibcageSDK.start({
  websocket: { enabled: true },
  analytics: { enabled: true },  // Future
  push: { enabled: true },       // Future
  auth: { enabled: true },       // Future
});

React Native Setup

For Android emulator, use 10.0.2.2 as the host to connect to localhost. For physical devices, use your computer's IP address.

const config = {
  host: __DEV__ ? '10.0.2.2' : 'your-production-host.com',
  port: 9001,
};

License

MIT