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

lavaflow

v1.0.5

Published

Professional-grade Lavalink v4 client library for Node.js with TypeScript-first design

Readme

lavaflow

A professional-grade, TypeScript-first Lavalink v4 client library for Node.js

npm version License

Features

Core Features

  • 🎯 Full Lavalink v4 Support - Complete implementation of the latest REST API and WebSocket protocol
  • 🏗️ TypeScript-First - Strongly typed APIs with full autocomplete support
  • Smart Load Balancing - Advanced penalty system for optimal node selection
  • 🌍 Voice Region Optimization - Auto-select nodes based on Discord voice region
  • 🔄 Automatic Reconnection - Exponential backoff with jitter for fault tolerance
  • ⏱️ Rate Limiting Handler - Built-in retry strategies (exponential/linear/none)
  • 🎨 Fluent Filter API - Chainable filter configuration for elegant code
  • 🎭 Event-Driven - Comprehensive event system for reactive programming
  • 🔌 Plugin Support - Extend functionality with custom plugins
  • 🛡️ Production-Ready - Battle-tested design patterns and error handling

Player Features

  • ▶️ Full Playback Control - Play, pause, resume, stop, seek
  • ⏭️ Queue Management - Add, remove, clear, shuffle queue
  • ⏮️ Previous Track - Play previous tracks (last 10 stored)
  • Shuffle - Randomize queue order
  • �🔁 Loop Modes - Track loop, queue loop, or off
  • 📜 Playback History - Track last 50 played songs
  • Favorites/Bookmarks - Save favorite tracks per user/guild
  • 💾 Queue Persistence - Save and restore queue state
  • 🔊 Volume Control - 0-100% volume adjustment with normalization
  • 🎛️ Speed/Pitch Control - Independent speed and pitch adjustment (0.25x-3.0x)
  • 🌊 Crossfade - Smooth transitions between tracks
  • 🎵 Gapless Playback - Seamless track transitions
  • 🔍 Multi-Platform Search - YouTube, YouTube Music, SoundCloud support
  • 📊 Position Tracking - Real-time playback position updates
  • 🤖 Intelligent AutoPlay - Automatically plays related tracks when queue ends (YouTube, SoundCloud, Spotify)
  • 💿 Metadata Cache - Cache track info to reduce API calls

Audio Filters

  • 🎚️ 10 Filter Types - Volume, Equalizer, Karaoke, Timescale, Tremolo, Vibrato, Rotation, Distortion, ChannelMix, LowPass
  • 🎵 8 Equalizer Presets - Bass, Treble, Soft, Flat, Electronic, Rock, Classical, Pop
  • 5 Effect Presets - Nightcore, Vaporwave, 8D Audio, Bassboost (4 levels), Soft
  • 🔗 Chainable API - Fluent filter configuration with filters().effect1().effect2().apply()

Installation

npm install lavaflow

Quick Start

import { Manager } from 'lavaflow';
import { Client } from 'discord.js';

const client = new Client({ intents: ['Guilds', 'GuildVoiceStates'] });

const manager = new Manager({
  nodes: [
    {
      name: 'Node 1',
      host: 'localhost',
      port: 2333,
      password: 'youshallnotpass',
      secure: false
    }
  ],
  send: (guildId, payload) => {
    const guild = client.guilds.cache.get(guildId);
    if (guild) guild.shard.send(payload);
  },
  autoPlay: true, // Enable intelligent AutoPlay
  debug: false // Disable debug logging
});

// Initialize manager after client is ready
client.on('ready', () => {
  manager.init(client.user!.id);
});

// Forward voice state updates
client.on('raw', (packet) => {
  if (manager.isInitialized()) {
    manager.updateVoiceState(packet);
  }
});

// Listen to events
manager.on('trackStart', (player, track) => {
  console.log(`Now playing: ${track.info.title}`);
});

manager.on('trackEnd', (player, track, reason) => {
  console.log(`Track ended: ${reason}`);
});

// Create and use a player
const player = manager.create({
  guildId: 'guild-id',
  voiceChannelId: 'voice-channel-id',
  textChannelId: 'text-channel-id'
});

await player.connect();

const result = await player.search('Never Gonna Give You Up');
if (result.loadType === 'track') {
  await player.play(result.data);
}

// Use filters with fluent API
await player.filters()
  .timescale({ speed: 1.2, pitch: 1.0, rate: 1.0 })
  .tremolo({ frequency: 4.0, depth: 0.5 })
  .karaoke()
  .apply();

// Advanced player features
player.setLoopMode('track'); // Loop current track
player.setLoopMode('queue'); // Loop entire queue
player.setLoopMode('off');   // Disable loop

await player.setSpeed(1.5);  // 1.5x speed (independent)
await player.setPitch(1.2);  // Higher pitch (independent)
await player.setSpeedAndPitch(1.3, 1.3); // Both together

player.setCrossfade(3000);   // 3 second crossfade
player.setVolumeNormalization(true); // Enable normalization

// Favorites
import { FavoritesManager } from 'lavaflow';
const favorites = new FavoritesManager();
favorites.addUserFavorite('userId', track);
favorites.addGuildFavorite('guildId', track, 'userId');
const userFavs = favorites.getUserFavorites('userId');

// Queue persistence
const saved = player.saveQueue(); // Returns JSON string
// Later...
await player.restoreQueue(saved); // Restore queue state

// Playback history
const history = player.getHistory(); // Last 50 tracks
player.clearHistory();

// Metadata cache
import { MetadataCache } from 'lavaflow';
const cache = new MetadataCache(1000, 3600000); // 1000 items, 1 hour TTL
const cachedTrack = cache.get('identifier');
if (!cachedTrack) {
  const track = await player.search('query');
  cache.set('identifier', track);
}

Architecture

Node Manager

Manages multiple Lavalink nodes with intelligent load balancing based on:

  • Player count (active and playing players)
  • CPU load (normalized by core count)
  • Memory usage
  • Custom penalty calculations

Player

Feature-rich player with:

  • Play, pause, stop, seek controls
  • Volume management
  • Filter support (v4 filters: Timescale, Tremolo, Karaoke, Distortion, Rotation, etc.)
  • Queue management
  • Voice state handling

Filter Builder

Chainable API for audio filters:

player.filters()
  .volume(0.8)
  .equalizer([{ band: 0, gain: 0.2 }])
  .timescale({ speed: 1.1 })
  .tremolo({ frequency: 2.0, depth: 0.5 })
  .vibrato({ frequency: 2.0, depth: 0.5 })
  .rotation({ rotationHz: 0.2 })
  .distortion({ sinOffset: 0, sinScale: 1, cosOffset: 0, cosScale: 1, tanOffset: 0, tanScale: 1, offset: 0, scale: 1 })
  .channelMix({ leftToLeft: 1, leftToRight: 0, rightToLeft: 0, rightToRight: 1 })
  .lowPass({ smoothing: 20 })
  .apply();

Events

  • nodeConnect - Node connected successfully
  • nodeDisconnect - Node disconnected
  • nodeError - Node encountered an error
  • nodeReconnect - Node attempting reconnection
  • trackStart - Track started playing
  • trackEnd - Track finished playing
  • trackStuck - Track got stuck
  • trackException - Track encountered an error
  • playerCreate - Player created
  • playerDestroy - Player destroyed
  • queueEnd - Queue finished playing
  • debug - Debug messages (only if debug: true)

AutoPlay Feature

lavaflow includes intelligent AutoPlay that automatically finds and plays related tracks when your queue ends:

  • YouTube: Uses YouTube's recommendation system (RD playlists)
  • SoundCloud: Searches for similar tracks by artist/title
  • Spotify: Converts to YouTube, gets recommendations, finds related tracks

AutoPlay keeps track of the last 50 played tracks to avoid repetition.

const manager = new Manager({
  autoPlay: true, // Enable AutoPlay (default: true)
  debug: true     // Show debug logs (default: false)
});

Plugin System

lavaflow supports custom plugins to extend functionality:

import { Manager, LavaPlugin } from 'lavaflow';

const myPlugin: LavaPlugin = {
  name: 'MyPlugin',
  onLoad(manager) {
    console.log('Plugin loaded!');
  },
  onEvent(event, ...args) {
    if (event === 'trackStart') {
      console.log('Track started:', args);
    }
  }
};

manager.use(myPlugin);

Check out lava-plugin-voice-status for a voice channel status plugin example.

API Documentation

Manager Options

interface ManagerOptions {
  nodes: NodeOptions[];
  send: (guildId: string, payload: any) => void;
  clientId?: string;
  shards?: number;
  autoPlay?: boolean;
  defaultSearchPlatform?: 'ytsearch' | 'ytmsearch' | 'scsearch';
  debug?: boolean;
}

Node Options

interface NodeOptions {
  name: string;
  host: string;
  port: number;
  password: string;
  secure?: boolean;
  resumeKey?: string;
  resumeTimeout?: number;
  maxReconnectAttempts?: number;
  reconnectDelay?: number;
  region?: string; // Geographic region for voice optimization
  retryStrategy?: 'exponential' | 'linear' | 'none'; // Rate limiting strategy
}

Player Options

interface PlayerOptions {
  guildId: string;
  voiceChannelId: string;
  textChannelId?: string;
  selfDeafen?: boolean;
  selfMute?: boolean;
  volume?: number;
}

Design Patterns

  • Singleton: NodeManager for centralized node management
  • Factory: Player creation through Manager
  • Builder: Fluent API for filter configuration
  • Event-Driven: Comprehensive event system for reactive patterns

Fault Tolerance

  • Automatic reconnection with exponential backoff
  • Jitter to prevent thundering herd
  • Node health monitoring
  • Graceful degradation

License

MIT © ryxu-xo

Contributing

Contributions are welcome! Please read our contributing guidelines and code of conduct.

Support