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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@feizk/gateway

v1.0.0

Published

TypeScript WebSocket client for the Discord Gateway API

Downloads

7

Readme

@feizk/gateway

A TypeScript WebSocket client for the Discord Gateway API with full lifecycle management, intelligent reconnection, and comprehensive error handling.

npm version License: MIT TypeScript

Part of the Feizk Discord ecosystem - a collection of powerful, type-safe packages for Discord bot development.

✨ Features

  • 🚀 Full Gateway Support: Complete Discord Gateway API v10 implementation
  • 🔄 Smart Reconnection: Exponential backoff with resume capability
  • 💓 Heartbeat Management: Automatic heartbeat with timeout detection
  • 🎯 Type-Safe Events: Strongly typed event system for all Gateway events
  • 🛠️ Rich Error Context: Detailed error information with recovery suggestions
  • 🔧 Sharding Support: Basic shard configuration (manager coming soon)
  • 📦 Modern TypeScript: Built with strict TypeScript for excellent DX
  • 🧪 Well Tested: Comprehensive test suite with high coverage

📦 Installation

npm install @feizk/gateway
# or
yarn add @feizk/gateway
# or
pnpm add @feizk/gateway

🚀 Quick Start

import { GatewayClient, GatewayIntent } from '@feizk/gateway';

const client = new GatewayClient({
  token: 'your-bot-token',
  intents: GatewayIntent.Guilds | GatewayIntent.GuildMessages,
});

// Listen for when the bot is ready
client.on('ready', data => {
  console.log(`🤖 Connected as ${data.user.username}!`);
  console.log(`📊 Serving ${data.guilds.length} guilds`);
});

// Handle errors gracefully
client.on('error', error => {
  console.error('❌ Gateway error:', error.getDetailedMessage());
  console.log('💡 Suggestions:', error.getRecoverySuggestions());
});

// Listen for connection state changes
client.on('stateChange', (newState, oldState) => {
  console.log(`🔄 Connection state: ${oldState} → ${newState}`);
});

// Connect to Discord
await client.connect();

📚 Advanced Usage

Event Handling

// Listen to specific Discord events
client.on('dispatch', (eventName, data) => {
  switch (eventName) {
    case 'GUILD_CREATE':
      console.log('Joined guild:', data.name);
      break;
    case 'MESSAGE_CREATE':
      console.log('New message:', data.content);
      break;
  }
});

// Listen to Gateway lifecycle events
client.on('hello', data => {
  console.log(`Heartbeat interval: ${data.heartbeat_interval}ms`);
});

client.on('resumed', () => {
  console.log('Session resumed successfully');
});

client.on('reconnect', () => {
  console.log('Discord requested reconnection');
});

Sharding Configuration

const client = new GatewayClient({
  token: 'your-bot-token',
  intents: GatewayIntent.Guilds,
  shard: [0, 2], // Shard 0 of 2 total shards
});

console.log('Shard info:', client.shard); // [0, 2]

Custom Configuration

const client = new GatewayClient({
  token: 'your-bot-token',
  intents: GatewayIntent.Guilds | GatewayIntent.GuildMessages,

  // Custom Gateway URL (usually not needed)
  gatewayUrl: 'wss://gateway.discord.gg/?v=10&encoding=json',

  // Reconnection settings
  maxReconnectAttempts: 10,
  reconnectDelay: 2000,
  maxReconnectDelay: 60000,

  // Large guild optimization
  largeThreshold: 100,

  // Initial presence
  presence: {
    status: 'online',
    since: null,
    activities: [],
    afk: false,
  },
});

Session Management

// Access session information
console.log('Session ID:', client.session.id);
console.log('Last sequence:', client.session.sequence);

// Check connection state
console.log('Connected:', client.connected);
console.log('State:', client.state);

Error Handling

client.on('error', error => {
  // Rich error context
  console.log('Error code:', error.code);
  console.log('Operation:', error.context.operation);
  console.log('Connection state:', error.context.connectionState);
  console.log('Last sequence:', error.context.lastSequence);

  // Get detailed information
  console.log(error.getDetailedMessage());

  // Get recovery suggestions
  error.getRecoverySuggestions().forEach(suggestion => {
    console.log('💡', suggestion);
  });

  // JSON serialization for logging
  console.log(JSON.stringify(error.toJSON(), null, 2));
});

Presence Updates

// Update bot presence
client.updatePresence({
  status: 'dnd',
  since: null,
  activities: [
    {
      name: 'with Discord API',
      type: 0, // Playing
    },
  ],
  afk: false,
});

Graceful Shutdown

process.on('SIGINT', async () => {
  console.log('Shutting down...');
  await client.disconnect();
  process.exit(0);
});

🎯 Gateway Intents

The package re-exports all Discord Gateway intents for convenience:

import { GatewayIntent } from '@feizk/gateway';

// Common combinations
const basicIntents = GatewayIntent.Guilds | GatewayIntent.GuildMessages;

const allIntents =
  GatewayIntent.Guilds |
  GatewayIntent.GuildMembers |
  GatewayIntent.GuildMessages |
  GatewayIntent.GuildMessageReactions |
  GatewayIntent.DirectMessages;

// Privileged intents (require enabling in Discord Developer Portal)
const privilegedIntents =
  GatewayIntent.GuildMembers | GatewayIntent.GuildPresences | GatewayIntent.MessageContent;

🔧 Connection States

The client goes through various connection states:

  • disconnected: Not connected to Discord
  • connecting: Establishing WebSocket connection
  • connected: Successfully connected and ready
  • resuming: Attempting to resume previous session
  • reconnecting: Reconnecting after connection loss

🛠️ Utility Functions

import {
  validateToken,
  getGatewayUrl,
  calculateIntents,
  hasIntent,
  exponentialBackoff,
} from '@feizk/gateway';

// Validate token format
const isValid = validateToken('your-token');

// Get Gateway URL for specific API version
const url = getGatewayUrl(10);

// Work with intents
const totalIntents = calculateIntents([GatewayIntent.Guilds, GatewayIntent.GuildMessages]);

const hasGuildIntent = hasIntent(totalIntents, GatewayIntent.Guilds);

// Calculate backoff delay
const delay = exponentialBackoff(attemptNumber);

🧪 Testing

The package includes comprehensive tests:

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

🏗️ Building

# Build the package
npm run build

# Build in development mode with watch
npm run dev

# Type check
npm run typecheck

📋 API Reference

GatewayClient

Constructor Options

| Option | Type | Default | Description | | ---------------------- | ------------------ | ------- | ----------------------------------- | | token | string | - | Discord bot token (required) | | intents | number | - | Gateway intents bitfield (required) | | gatewayUrl | string | Auto | Discord Gateway URL | | shard | [number, number] | - | Shard info [id, count] | | largeThreshold | number | 50 | Large guild member threshold | | presence | object | - | Initial presence data | | maxReconnectAttempts | number | 5 | Max reconnection attempts | | reconnectDelay | number | 1000 | Base reconnection delay (ms) | | maxReconnectDelay | number | 30000 | Max reconnection delay (ms) |

Methods

  • connect(): Promise<void> - Connect to Discord Gateway
  • disconnect(code?, reason?): Promise<void> - Disconnect from Gateway
  • send(payload): void - Send raw payload to Gateway
  • updatePresence(presence): void - Update bot presence

Properties

  • state: ConnectionState - Current connection state
  • connected: boolean - Whether client is connected
  • session: object - Session ID and sequence number
  • shard?: [number, number] - Shard information

Events

  • ready - Bot is ready (receives ready data)
  • resumed - Session resumed successfully
  • hello - Received hello from Discord
  • heartbeat - Heartbeat sent (receives sequence number)
  • heartbeatAck - Heartbeat acknowledged
  • invalidSession - Session invalidated (receives resumable boolean)
  • reconnect - Discord requested reconnection
  • dispatch - Gateway event received (receives event name and data)
  • raw - Raw Gateway payload (receives full payload)
  • error - Error occurred (receives GatewayError)
  • close - WebSocket closed (receives code and reason)
  • stateChange - Connection state changed (receives new and old state)

🤝 Contributing

We welcome contributions! Please see our contributing guidelines for details.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🔗 Related Packages

  • @feizk/rest - Discord REST API client (coming soon)
  • @feizk/core - High-level Discord bot framework (coming soon)
  • @feizk/voice - Discord voice connections (coming soon)

🆘 Support


Made with ❤️ by the Feizk team. Happy bot building! 🤖