### Install and Start NodeLink Source: https://github.com/performanc/nodelink/blob/v3/README.md Clone the repository, install dependencies, copy the configuration, and start the NodeLink server. ```bash git clone https://github.com/PerformanC/NodeLink.git cd NodeLink npm install cp config.default.js config.js npm run start ``` -------------------------------- ### Start NodeLink Server Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/00-START-HERE.txt Starts the NodeLink server using npm. This command assumes dependencies are installed and configuration is set up. ```bash npm run start ``` -------------------------------- ### Loading a NodeLink Plugin from npm Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Example configuration file demonstrating how to import and register a NodeLink plugin installed from npm. ```typescript // config.js import myPlugin from '@user/nodelink-plugin-example' export default { plugins: [myPlugin], // ... rest of config } ``` -------------------------------- ### Install NodeLink Dependencies Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/00-START-HERE.txt Installs the necessary Node.js packages for NodeLink. This is a prerequisite for starting the server. ```bash npm install ``` -------------------------------- ### Prometheus Metrics Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Example output for the GET /v4/metrics endpoint, showing player counts in Prometheus text format. ```text # HELP nodelink_players_total Total number of active players # TYPE nodelink_players_total gauge nodelink_players_total 5 # HELP nodelink_players_playing Number of playing players # TYPE nodelink_players_playing gauge nodelink_players_playing 3 ``` -------------------------------- ### Server Statistics Response Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Example JSON response for the GET /v4/stats endpoint, showing player activity, uptime, and resource utilization. ```json { "players": 5, "playingPlayers": 3, "uptime": 3600000, "memory": { "rss": 52428800, "heapUsed": 31457280, "heapTotal": 67108864, "external": 1048576 }, "cpu": { "cores": 8, "systemLoad": [0.5, 0.6, 0.4], "processLoad": 1.2 }, "frameStats": { "sent": 144000, "nulled": 100, "deficit": 50 } } ``` -------------------------------- ### Plugin with Environment Variable Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Example of a plugin that reads configuration values from environment variables. This allows for dynamic setup of plugin behavior. ```typescript const myPlugin: Plugin = { name: 'my-plugin', hooks: { onReady: async (server: NodelinkServer) => { const debugEnabled = process.env.MY_PLUGIN_DEBUG === 'true' const apiKey = process.env.MY_PLUGIN_API_KEY if (debugEnabled) { console.log('My plugin debug mode enabled') } if (apiKey) { // Initialize external API } } } } ``` -------------------------------- ### Example Event Logger Plugin Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md A complete plugin example that logs various player and server events. It demonstrates the use of multiple hooks like onReady, onTrackStart, onTrackEnd, onPlayerCreate, and onPlayerDestroy. ```typescript // plugins/event-logger/index.ts import type { NodelinkServer, Plugin } from '@performanc/nodelink' const eventLoggerPlugin: Plugin = { name: 'event-logger', version: '1.0.0', hooks: { onReady: async (server: NodelinkServer) => { console.log('Event logger plugin loaded') }, onTrackStart: async (server, player, track) => { console.log(`[TRACK START] Guild: ${player.guildId}`) console.log(` Title: ${track.info.title}`) console.log(` Author: ${track.info.author}`) console.log(` Duration: ${track.info.length}ms`) }, onTrackEnd: async (server, player, track, reason) => { console.log(`[TRACK END] Guild: ${player.guildId}`) console.log(` Title: ${track.info.title}`) console.log(` Reason: ${reason}`) }, onPlayerCreate: async (server, player) => { console.log(`[PLAYER CREATE] Guild: ${player.guildId}`) }, onPlayerDestroy: async (server, player) => { console.log(`[PLAYER DESTROY] Guild: ${player.guildId}`) } } } export default eventLoggerPlugin ``` -------------------------------- ### Registering a Custom Source Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Example of how to register a custom audio source instance with the NodeLink extensions. ```typescript nodelink.extensions.sources.set('custom', customSourceInstance) ``` -------------------------------- ### Cluster Configuration Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/README.md Configure the cluster settings for NodeLink, including the number of workers and scaling parameters. ```javascript cluster: { enabled: true, workers: 4, minWorkers: 1, specializedSourceWorker: { enabled: true, count: 1, microWorkers: 2 }, scaling: { maxPlayersPerWorker: 20, targetUtilization: 0.7 } } ``` -------------------------------- ### Server Configuration Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/03-configuration.md Configure basic server settings like host, port, password, and whether to use the Bun server. ```javascript server: { host: '0.0.0.0', port: 2333, password: 'my-secure-password', useBunServer: false } ``` -------------------------------- ### Example: Search With Specific Source using cURL Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Demonstrates how to perform a search using cURL with a specific source prefix. ```bash # Uses specific source curl 'http://localhost:2333/v4/loadtracks?identifier=spotify:lofi+hip+hop' ``` -------------------------------- ### onTrackStart Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onTrackStart hook to react when a track begins playing. It receives the server, player, and track data. ```typescript hooks: { onTrackStart: async ( server: NodelinkServer, player: Player, track: TrackData ) => { console.log(`Playing: ${track.info.title}`) } } ``` -------------------------------- ### Check Node.js Version Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/README.md Check the currently installed Node.js version. ```bash node --version ``` -------------------------------- ### onReady Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onReady hook to execute code when the server has fully initialized. This hook receives the NodelinkServer instance. ```typescript hooks: { onReady: async (server: NodelinkServer) => { console.log('Server is ready') } } ``` -------------------------------- ### API Authentication Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/README.md Authenticate API requests using the Authorization header. The default password is 'youshallnotpass'. ```bash curl -H "Authorization: your-password" \ http://localhost:2333/v4/stats ``` -------------------------------- ### Example: Search Without Prefix using cURL Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Demonstrates how to perform a search using cURL, which will utilize the 'defaultSearchSource' if no prefix is specified. ```bash # Uses defaultSearchSource curl 'http://localhost:2333/v4/loadtracks?identifier=lofi+hip+hop' ``` -------------------------------- ### Load Tracks using cURL Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Example using cURL to load tracks with an identifier and authorization header. ```bash curl 'http://localhost:2333/v4/loadtracks?identifier=youtube:lofi' \ -H "Authorization: youshallnotpass" ``` -------------------------------- ### GET /v4/profiler/ui Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Serves the profiler user interface, if available. ```APIDOC ## Special Endpoints ### GET /v4/profiler/ui ### Description Serves the profiler UI (if available). ### Method GET ### Endpoint /v4/profiler/ui ``` -------------------------------- ### Load Track via HTTP and WebSocket Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/00-START-HERE.txt Demonstrates loading a track using an HTTP GET request for search, followed by a WebSocket message to play the track. Requires a valid search query and track object. ```bash GET /v4/loadtracks?identifier=youtube:search_query Then send: {op: "play", guildId: "...", track: {...}} ``` -------------------------------- ### GET /v4/metrics Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Returns Prometheus-formatted metrics for server monitoring, if enabled. ```APIDOC ## GET /v4/metrics ### Description Returns Prometheus-formatted metrics (if enabled in config). ### Method GET ### Endpoint /v4/metrics ### Response #### Success Response (200) Plain text Prometheus format metrics. ### Response Example ``` # HELP nodelink_players_total Total number of active players # TYPE nodelink_players_total gauge nodelink_players_total 5 # HELP nodelink_players_playing Number of playing players # TYPE nodelink_players_playing gauge nodelink_players_playing 3 ``` ``` -------------------------------- ### Get Server Statistics Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Use GET /v4/stats to retrieve server statistics including player counts, uptime, and resource usage. ```http GET /v4/stats HTTP/1.1 Authorization: youshallnotpass ``` -------------------------------- ### WebSocket API: GET /v4/websocket Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Establishes a WebSocket connection for real-time event streaming and command execution. ```APIDOC ## WebSocket API ### Connection: GET /v4/websocket ### Description Upgrades to WebSocket connection for real-time events. ### Method GET ### Endpoint /v4/websocket ### Headers Required - **Authorization**: Server password - **Client-Name**: Client identifier - **User-Id**: Discord user ID ### Connection Lifecycle 1. Client sends WebSocket upgrade request 2. Server responds with `ready` opcode: ```json { "op": "ready", "resumed": false, "sessionId": "session-id-here" } ``` 3. Client sends commands (e.g., play, pause) 4. Server sends events (e.g., TrackStartEvent, PlayerUpdateEvent) 5. Server sends stats periodically (configurable) ### Common Operations #### Play Track ```json { "op": "play", "guildId": "123456789", "track": "encoded_track_string" } ``` #### Update Player ```json { "op": "update", "guildId": "123456789", "playerState": { "position": 5000, "paused": false, "volume": 100 } } ``` #### Destroy Player ```json { "op": "destroy", "guildId": "123456789" } ``` ### Events Received | Op | | Type | | Description | |----|----|----| | playerUpdate | PlayerUpdateEvent | Player state changed | | event | TrackStartEvent | Track started | | event | TrackEndEvent | Track finished | | event | TrackExceptionEvent | Playback error | | event | TrackStuckEvent | Track stuck (timeout) | | event | WebSocketClosedEvent | WebSocket closed | | stats | StatsEvent | Server statistics | ``` -------------------------------- ### Connect to Profiler WebSocket Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Example of connecting to the real-time profiler WebSocket endpoint for a specific worker. This allows for detailed performance monitoring of individual workers. ```bash ws://localhost:2333/v4/profiler/socket?scope=worker-1 ``` -------------------------------- ### GET /v4/connection Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Tests the connection quality and bandwidth to the NodeLink server. ```APIDOC ## GET /v4/connection ### Description Tests connection quality and bandwidth. ### Method GET ### Endpoint /v4/connection ### Response #### Success Response (200) - **address** (string) - Client IP address - **failingAddresses** (string[]) - IPs with connection issues - **ipBlocks** (array) - IP block information ``` -------------------------------- ### GET /v4/info Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Retrieves general information about the NodeLink server, including its version and build details. ```APIDOC ## GET /v4/info ### Description Gets NodeLink server information. ### Method GET ### Endpoint /v4/info ### Response #### Success Response (200) - **version** (string) - Server version - **buildLine** (number) - Build information - **versionMajor** (number) - Major version - **versionMinor** (number) - Minor version - **versionPatch** (number) - Patch version - **versionPreRelease** (string) - Pre-release identifier - **git** (object) - Git information ``` -------------------------------- ### Worker Log Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Illustrates typical log messages from worker processes, including startup, utilization warnings, idle status, and failure notifications. Worker IDs are included for easy identification. ```text [INFO] Worker-1 spawned [WARN] Worker-2 high utilization (0.85) [INFO] Worker-3 hibernated (idle) [ERROR] Worker-2 failed, affecting guilds: 123, 456, 789 ``` -------------------------------- ### NodelinkServer Methods Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/04-types.md Provides signatures and descriptions for key methods of the NodelinkServer class, including starting the server, handling voice frames, and managing voice sockets. ```typescript start: `start(options?: {isClusterPrimary?: boolean; isClusterWorker?: boolean}): Promise` ``` ```typescript handleVoiceFrame: `handleVoiceFrame(frame: Buffer): void` ``` ```typescript registerVoiceSocket: `registerVoiceSocket(guildId: string, socket: SessionSocket): void` ``` ```typescript getSourcesFromWorker: `getSourcesFromWorker(): Promise` ``` ```typescript handleIPCMessage: `handleIPCMessage(msg: IPCMessage): void` ``` -------------------------------- ### Load YouTube Track via curl Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Example of loading a YouTube track using a curl command with the track's identifier. ```bash curl 'http://localhost:2333/v4/loadtracks?identifier=https://youtube.com/watch?v=dQw4w9WgXcQ' ``` -------------------------------- ### onPlayerCreate Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onPlayerCreate hook to execute code when a new player instance is created. It receives the server and the player object. ```typescript hooks: { onPlayerCreate: async ( server: NodelinkServer, player: Player ) => { console.log(`Player created for guild ${player.guildId}`) } } ``` -------------------------------- ### onPlaylistLoad Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onPlaylistLoad hook to react when a playlist is loaded. It receives the server and the search result containing playlist information. ```typescript hooks: { onPlaylistLoad: async ( server: NodelinkServer, result: SourceSearchResult ) => { console.log(`Playlist loaded: ${result.info?.name}`) } } ``` -------------------------------- ### TrackStartEvent Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/06-websocket-protocol.md Sent when a track starts playing, containing guild ID and track information. ```APIDOC ## TrackStartEvent Sent when a track starts playing. ### Message Format ```json { "op": "event", "type": "TrackStartEvent", "guildId": "string", "track": { ... } } ``` ``` -------------------------------- ### onShutdown Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onShutdown hook to execute code during server shutdown. This hook receives the NodelinkServer instance. ```typescript hooks: { onShutdown: async (server: NodelinkServer) => { console.log('Server shutting down') } } ``` -------------------------------- ### Monitor Server Metrics (Prometheus) Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/00-START-HERE.txt Retrieves server metrics in Prometheus format via an HTTP GET request for monitoring systems. ```bash GET /v4/metrics (Prometheus) ``` -------------------------------- ### npm Package Configuration for NodeLink Plugin Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Example package.json for a NodeLink plugin distributed via npm. Ensure peerDependencies match the NodeLink version. ```json { "name": "@user/nodelink-plugin-example", "version": "1.0.0", "description": "Example plugin for NodeLink", "main": "dist/index.js", "types": "dist/index.d.ts", "peerDependencies": { "@performanc/nodelink": "^3.0.0" } } ``` -------------------------------- ### Basic Cluster Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Enables cluster mode with a default of 4 workers, recommended for typical production setups and balanced resource usage. ```javascript cluster: { enabled: true, workers: 4 } ``` -------------------------------- ### Memory Tuning Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Example of configuring memory limits for workers within the cluster runtime settings. This helps manage memory usage on servers with constraints. ```javascript runtime: { workerMaxOldSpaceMb: 1024 // 1GB per worker } ``` -------------------------------- ### Configure NodeLink via Environment Variables Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/00-START-HERE.txt Shows how to configure NodeLink using environment variables. This is an alternative to editing the config.js file. Example variable shown is for cluster mode. ```bash - Or use environment variables (CLUSTER_ENABLED, etc.) ``` -------------------------------- ### onWebSocketConnect Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onWebSocketConnect hook to react to new WebSocket client connections. It provides the socket, client info, and old session ID. ```typescript hooks: { onWebSocketConnect: ( socket: SessionSocket, clientInfo: ClientInfo, oldSessionId: string | undefined ) => { console.log(`Client ${clientInfo.name} connected`) } } ``` -------------------------------- ### WebSocket Upgrade Request Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/06-websocket-protocol.md Initiates a WebSocket connection by sending an HTTP GET request with specific headers like Upgrade, Connection, Authorization, Client-Name, User-Id, and Session-Id. ```http GET /v4/websocket HTTP/1.1 Host: localhost:2333 Upgrade: websocket Connection: Upgrade Authorization: youshallnotpass Client-Name: Moonlink.js/1.0.0 User-Id: 123456789 Session-Id: abc123def456 ``` -------------------------------- ### Kubernetes StatefulSet for NodeLink Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Example Kubernetes StatefulSet configuration for deploying NodeLink with cluster mode enabled. Specifies replica count, ports, environment variables, and resource requests/limits. ```yaml apiVersion: apps/v1 kind: StatefulSet metadata: name: nodelink spec: replicas: 3 serviceName: nodelink selector: matchLabels: app: nodelink template: metadata: labels: app: nodelink spec: containers: - name: nodelink image: nodelink:latest ports: - containerPort: 2333 env: - name: CLUSTER_ENABLED value: "true" - name: CLUSTER_WORKERS value: "4" resources: requests: memory: "512Mi" cpu: "500m" limits: memory: "2Gi" cpu: "2000m" ``` -------------------------------- ### Example Valid PATCH Payload for Sessions Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/10-error-handling.md Demonstrates a valid JSON payload for updating session properties, including optional 'resuming' and 'timeout' fields. ```json { "resuming": true, "timeout": 600 } ``` -------------------------------- ### Curl Request for Tracks Not Found Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/10-error-handling.md If tracks are not found with a specific identifier, try using a different source. This example attempts to load tracks using the 'spotify' source. ```bash # Try different source curl 'http://localhost:2333/v4/loadtracks?identifier=spotify:query' ``` -------------------------------- ### Enable NodeLink Memory Tracing Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/10-error-handling.md Environment variable setting to enable detailed memory usage tracing when starting the NodeLink server. This helps in debugging memory-related issues. ```bash NODELINK_MEMORY_TRACE=true npm run start ``` -------------------------------- ### onRESTRequest Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onRESTRequest hook to intercept and process all incoming HTTP requests. It receives the request and response objects. ```typescript hooks: { onRESTRequest: ( req: http.IncomingMessage, res: http.ServerResponse ) => { console.log(`${req.method} ${req.url}`) } } ``` -------------------------------- ### onPlayerDestroy Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onPlayerDestroy hook to execute code when a player instance is destroyed. It receives the server and the player object. ```typescript hooks: { onPlayerDestroy: async ( server: NodelinkServer, player: Player ) => { console.log(`Player destroyed for guild ${player.guildId}`) } } ``` -------------------------------- ### onWebSocketClose Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onWebSocketClose hook to handle WebSocket connection closures. It provides the socket, close code, and reason. ```typescript hooks: { onWebSocketClose: ( socket: SessionSocket, code: number, reason: string ) => { console.log(`Client disconnected (${code}): ${reason}`) } } ``` -------------------------------- ### onTrackEnd Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onTrackEnd hook to execute code when a track finishes playing. It receives the server, player, track data, and the reason for ending. ```typescript hooks: { onTrackEnd: async ( server: NodelinkServer, player: Player, track: TrackData, endReason: string ) => { console.log(`Track ended (${endReason})`) } } ``` -------------------------------- ### Configure Audio Sources Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/03-configuration.md Set up individual audio sources like YouTube and Spotify. Includes options for enabling sources and setting load limits. ```javascript sources: { youtube: { enabled: true, playlistLoadLimit: 20, albumLoadLimit: 20 }, spotify: { enabled: true, clientId: '', clientSecret: '', sp_dc: '', market: 'US', playlistLoadLimit: 50, albumLoadLimit: 50, allowLocalFiles: true } // ... more sources } ``` -------------------------------- ### Cluster Statistics Response Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Example JSON response from the cluster statistics endpoint, showing overall player counts, CPU information, and per-worker metrics. ```json { "players": 50, "playingPlayers": 35, "cpu": { "cores": 8 }, "frameStats": { "sent": 1440000 }, "workers": { "worker-1": { "players": 6, "playingPlayers": 5 }, "worker-2": { "players": 7, "playingPlayers": 5 }, "worker-3": { "players": 6, "playingPlayers": 5 } } } ``` -------------------------------- ### Example Valid Track Object for Play Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/10-error-handling.md Illustrates the structure of a valid track object required for the play endpoint, including essential information like title, author, length, and identifier. ```json { "encoded": "encoded_string...", "info": { "title": "...", "author": "...", "length": 180000, "identifier": "...", "isSeekable": true, "isStream": false, "uri": "...", "sourceName": "youtube" } } ``` -------------------------------- ### Configure HTTP Proxy for Audio Sources Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Use this configuration object to set up an HTTP proxy for supported audio sources. Specify the proxy URL, username, and password as needed. ```javascript proxy: { url: 'http://proxy-server:8080', username: 'user', password: 'pass' } ``` -------------------------------- ### Load a Track via API Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/INDEX.md To load a track, make a GET request to the /v4/loadtracks endpoint with an identifier. The response contains an encoded track string to be used in a WebSocket 'play' operation. ```bash GET /v4/loadtracks?identifier=SOURCE:QUERY ``` -------------------------------- ### GET /v4/routeplanner/status Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Gets the current status of the route planner, including any IP blocking information. ```APIDOC ## GET /v4/routeplanner/status ### Description Gets route planner status and IP blocking information. ### Method GET ### Endpoint /v4/routeplanner/status ### Response #### Success Response (200) - **class** (string) - Route planner class name - **details** (object) - Planner-specific details ``` -------------------------------- ### Get Route Planner Status Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Use GET /v4/routeplanner/status to check the status of the route planner and view IP blocking information. ```http GET /v4/routeplanner/status HTTP/1.1 Authorization: youshallnotpass ``` -------------------------------- ### Load Tracks by Identifier Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Use GET /v4/loadtracks to load tracks from various sources like URLs, search queries, or local paths. Requires an 'identifier' query parameter. ```http GET /v4/loadtracks?identifier=youtube:lofi%20hip%20hop HTTP/1.1 Authorization: youshallnotpass ``` -------------------------------- ### Get Prometheus Metrics Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Use GET /v4/metrics to retrieve server metrics in Prometheus format. This endpoint is enabled via configuration. ```http GET /v4/metrics HTTP/1.1 ``` -------------------------------- ### Configure SoundCloud Source Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Enable the SoundCloud source. An optional clientId can be provided for improved access. ```javascript soundcloud: { enabled: true, clientId: '' // Optional, for improved access } ``` -------------------------------- ### GET /v4/version Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Retrieves the current running version of the NodeLink service. ```APIDOC ## GET /v4/version ### Description Returns the running NodeLink version as plain text. ### Method GET ### Endpoint /v4/version ### Response #### Success Response (200) Plain text version string (e.g., "3.8.0") ### Request Example ```bash curl http://localhost:2333/v4/version ``` ### Response Example ``` 3.8.0 ``` ``` -------------------------------- ### WebSocket: GET /v4/profiler/socket Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Streams real-time profiler data via WebSocket. ```APIDOC ### WebSocket: GET /v4/profiler/socket ### Description Real-time profiler data streaming. ### Method GET ### Endpoint /v4/profiler/socket ### Query Parameters - **intervalMs** (number) - Poll interval (700-15000ms, default 2000) - **allocDurationMs** (number) - Allocation profile duration (1000-15000ms, default 3000) - **allocEveryMs** (number) - Allocation poll interval (5000-120000ms, default 0 = disabled) - **scope** (string) - Profile scope ('all' or specific filter, default 'all') - **code** (string) - Profiler access code (configurable, default 'CAPYBARA') ### Messages - `profilerReady`: Connection established with configuration - `profilerSnapshot`: Performance snapshot with warnings - `profilerBootstrap`: Historical snapshot data on connect - `profilerError`: Profile collection error ``` -------------------------------- ### Configure Spotify Source Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Enable the Spotify source and configure API credentials, market, and various load limits and concurrency settings. Supports explicit content and local files. ```javascript spotify: { enabled: true, clientId: '', // Official API credentials clientSecret: '', externalAuthUrl: '', // For anonymous token generation sp_dc: '', // Mobile token cookie market: 'US', // Search market code playlistLoadLimit: 50, albumLoadLimit: 50, playlistPageLoadConcurrency: 2, albumPageLoadConcurrency: 2, allowExplicit: true, allowLocalFiles: true } ``` -------------------------------- ### GET /v4/sessions/:sessionId/players Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Retrieves a list of all players currently associated with a given session. ```APIDOC ## GET /v4/sessions/:sessionId/players ### Description Lists all players in a session. ### Method GET ### Endpoint /v4/sessions/:sessionId/players ### Parameters #### Path Parameters - **sessionId** (string): Session identifier ### Response #### Success Response (200) Array of player objects with guild IDs, track info, and state. #### Error Response - **404 Not Found**: Session not found ``` -------------------------------- ### Local Files Source Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Configuration for the local filesystem audio source. Requires a 'basePath' to the music directory. ```javascript local: enabled: true basePath: './local-music/' // Base directory for music ``` -------------------------------- ### Get NodeLink Version Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Retrieve the running NodeLink version. This endpoint returns plain text. ```http GET /v4/version HTTP/1.1 ``` ```bash curl http://localhost:2333/v4/version # Response: 3.8.0 ``` -------------------------------- ### Get Real-time Statistics Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/README.md Retrieve real-time statistics from the NodeLink server via the /v4/stats endpoint. ```bash curl -H "Authorization: password" \ http://localhost:2333/v4/stats | jq ``` -------------------------------- ### Scale NodeLink for Production Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/00-START-HERE.txt Outlines the steps for scaling NodeLink for production environments, including enabling cluster mode, configuring workers, and monitoring. ```bash 1. Enable cluster mode 2. Configure worker count 3. Enable specialized source workers 4. Monitor via /v4/stats 5. Deploy to Kubernetes ``` -------------------------------- ### Configure VK Music Source Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Enable the VK Music source. Requires a userToken or userCookie for authentication, and supports proxy configuration. ```javascript vkmusic: { enabled: true, userToken: '', // User access token userCookie: '', // Browser cookie fallback proxy: { url: '', username: '', password: '' } } ``` -------------------------------- ### Get Prometheus Metrics Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/README.md Retrieve Prometheus metrics from the NodeLink server via the /v4/metrics endpoint, if enabled. ```bash curl -H "Authorization: password" \ http://localhost:2333/v4/metrics ``` -------------------------------- ### Configure Yandex Music Source Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Enable the Yandex Music source. Requires an accessToken and allows configuration for load limits, availability, explicit content, and proxy settings. ```javascript yandexmusic: { enabled: true, accessToken: '', // Required: API token playlistLoadLimit: 50, albumLoadLimit: 50, artistLoadLimit: 20, allowUnavailable: false, allowExplicit: true, proxy: { url: '', username: '', password: '' } } ``` -------------------------------- ### Configure Deezer Source Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Enable the Deezer source. Optional ARL cookie and decryption key can be provided for enhanced functionality. ```javascript deezer: { enabled: true, arl: '', // Optional: Deezer ARL cookie decryptionKey: '' // Optional: Decryption key } ``` -------------------------------- ### GET /v4/stats Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Retrieves server statistics, including player counts, uptime, and resource utilization (memory, CPU). ```APIDOC ## GET /v4/stats ### Description Retrieves server statistics. ### Method GET ### Endpoint /v4/stats ### Response #### Success Response (200) - **players** (number) - Total active players - **playingPlayers** (number) - Players currently playing - **uptime** (number) - Server uptime in milliseconds - **memory** (object) - Memory statistics - **cpu** (object) - CPU statistics - **frameStats** (object) - Audio frame statistics ### Response Example ```json { "players": 5, "playingPlayers": 3, "uptime": 3600000, "memory": { "rss": 52428800, "heapUsed": 31457280, "heapTotal": 67108864, "external": 1048576 }, "cpu": { "cores": 8, "systemLoad": [0.5, 0.6, 0.4], "processLoad": 1.2 }, "frameStats": { "sent": 144000, "nulled": 100, "deficit": 50 } } ``` ``` -------------------------------- ### Create or Resume Player Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Initiate a new player for a guild within a session or resume an existing one. Requires session and guild IDs. ```http POST /v4/sessions/abc123/players/guild-123 HTTP/1.1 Authorization: youshallnotpass ``` -------------------------------- ### Get NodeLink Server Info Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Use this endpoint to retrieve general information about the NodeLink server, such as its version and build details. ```http GET /v4/info HTTP/1.1 Authorization: youshallnotpass ``` -------------------------------- ### Configure Apple Music Source Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Enable the Apple Music source. No specific configuration options are detailed in this snippet. ```javascript applemusic: { enabled: true } ``` -------------------------------- ### TrackEndEvent Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/06-websocket-protocol.md Sent when a track stops playing, including track details, reason for stopping, and whether the next track can start. ```APIDOC ## TrackEndEvent Sent when a track stops. ### Message Format ```json { "op": "event", "type": "TrackEndEvent", "guildId": "string", "track": { ... }, "reason": "string", "mayStartNext": "boolean" } ``` ### Reasons - `FINISHED`: Track played to end - `LOAD_FAILED`: Track could not be loaded - `STOPPED`: Stopped by user command - `REPLACED`: Another track was queued - `CLEANUP`: Player was destroyed ``` -------------------------------- ### HTTP/Direct URLs Source Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Configuration for direct audio file URLs. Supports various formats and an optional custom user agent. ```javascript http: enabled: true userAgent: '' // Optional: Custom user agent ``` -------------------------------- ### Connection Establishment Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/06-websocket-protocol.md Details the HTTP Upgrade request to establish a WebSocket connection and the initial handshake response. ```APIDOC ## Connection Establishment ### Upgrade Request Establishes a WebSocket connection using an HTTP GET request with specific headers. #### Method GET #### Endpoint /v4/websocket #### Headers - **Host** (string) - Required - `localhost:2333` - **Upgrade** (string) - Required - `websocket` - **Connection** (string) - Required - `Upgrade` - **Authorization** (string) - Required - Server password - **Client-Name** (string) - Required - Client identifier (e.g., "Moonlink.js/1.0.0") - **User-Id** (string) - Required - Discord user ID (17-20 digits) - **Session-Id** (string) - Optional - Previous session ID to resume ### Response #### Success Response (101 Switching Protocols) Indicates a successful WebSocket connection upgrade. ```http HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Nodelink-Api-Version: 4 IamNodelink: true ``` Upon successful upgrade, the server sends a ready message: ```json { "op": "ready", "resumed": false, "sessionId": "abc123def456" } ``` ``` -------------------------------- ### Curl Request for Missing Parameter Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/10-error-handling.md Include required query parameters in your request. This example shows how to include the 'identifier' parameter. ```bash curl 'http://localhost:2333/v4/loadtracks?identifier=youtube:search+query' ``` -------------------------------- ### Copy Default Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/00-START-HERE.txt Copies the default configuration file to a user-editable file. This step is required before customizing NodeLink settings. ```bash cp config.default.js config.js ``` -------------------------------- ### GET /v4/loadtracks Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Loads tracks from an identifier, which can be a URL, a source-specific search query, a unified search query, or a local file path. ```APIDOC ## GET /v4/loadtracks ### Description Loads tracks from an identifier (URL, search query, or source prefix). ### Method GET ### Endpoint /v4/loadtracks ### Parameters #### Query Parameters - **identifier** (string) - Required - Track/playlist identifier (URL, source:query, or local path) ### Request Example ```bash curl 'http://localhost:2333/v4/loadtracks?identifier=youtube:lofi' -H "Authorization: youshallnotpass" ``` ### Response #### Success Response (200) Track data object(s) with metadata, source info, and encoded track string. #### Error Response - **400 Bad Request**: Missing or invalid identifier - **404 Not Found**: Tracks not found ``` -------------------------------- ### Environment Variables for Cluster Settings Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Demonstrates how to override cluster configuration settings using environment variables. This includes enabling cluster mode, setting the worker count, and adjusting Node.js memory limits. ```bash # Enable cluster mode CLUSTER_ENABLED=true # Set worker count CLUSTER_WORKERS=4 # Set memory limits NODE_OPTIONS="--max-old-space-size=2048" ``` -------------------------------- ### Eternalbox Source Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Configuration for the Eternalbox audio source, including base URL, Spotify enrichment, search result limits, and cache settings. ```javascript eternalbox: enabled: true baseUrl: 'https://eternalboxmirror.xyz' enrichSpotify: true searchResults: 30 cacheMaxBytes: 20 * 1024 * 1024 includeAnalysis: true includeAnalysisSummary: true // ... branching algorithm parameters ``` -------------------------------- ### Register a Custom Audio Source Extension Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Define and register a custom audio source by implementing the SourceExtension interface and using server.extensions.sources.set(). ```typescript interface MyCustomSource extends SourceExtension { name: 'mycustom' search(query: string): Promise load(identifier: string): Promise isURLSupported(url: string): boolean isQueryValid(query: string): boolean } // In plugin onReady hook: server.extensions.sources.set('mycustom', myCustomSourceInstance) ``` -------------------------------- ### TrackCacheManager Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/05-managers.md Manages the caching of track data. Provides methods to load, save, set, get, clear, and check the size of the track cache. ```APIDOC ## TrackCacheManager ### Description Manages the caching of track data. Provides methods to load, save, set, get, clear, and check the size of the track cache. ### Public Interface ```ts class TrackCacheManager { load(): Promise save(): Promise set(key: string, track: TrackData, ttlMs?: number): void get(key: string): TrackData | undefined clear(): void size(): number } ``` ``` -------------------------------- ### Deploy NodeLink with Docker Source: https://github.com/performanc/nodelink/blob/v3/README.md Deploy NodeLink using Docker Compose for a managed environment or build and run directly with Docker. ```bash # Using Docker Compose docker-compose up -d # Or using Docker directly docker build -t nodelink . docker run -p 2333:2333 nodelink ``` -------------------------------- ### Monitor Server Statistics (HTTP) Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/00-START-HERE.txt Retrieves JSON statistics about the NodeLink server's performance and status via an HTTP GET request. ```bash GET /v4/stats (JSON stats) ``` -------------------------------- ### Unified Search Sources Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Configures multiple sources to be searched simultaneously. ```javascript unifiedSearchSources: ['youtube', 'soundcloud'] ``` -------------------------------- ### Handle IPC Messages in Hooks Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onIPCMessage hook to process messages received from workers. This example logs a message when a 'playerEvent' is detected. ```typescript hooks: { onIPCMessage: ( message: IPCMessage ) => { if (message.type === 'playerEvent') { console.log('Player event from worker') } } } ``` -------------------------------- ### onWebSocketMessage Hook Example Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/08-plugins-extensions.md Implement the onWebSocketMessage hook to process incoming WebSocket messages. It provides the socket, parsed data, and guild ID. ```typescript hooks: { onWebSocketMessage: ( socket: SessionSocket, data: ParsedWebSocketData, guildId: string | undefined ) => { console.log(`Message: ${JSON.stringify(data)}`) } } ``` -------------------------------- ### Troubleshooting Worker Spawning Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Command to check logs for worker-related errors during cluster startup. Useful for diagnosing issues where workers fail to spawn. ```bash CLUSTER_ENABLED=true node start.js 2>&1 | grep -i worker ``` -------------------------------- ### WebSocket Connection Lifecycle Stages Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/06-websocket-protocol.md Outlines the typical sequence of events during a WebSocket connection, from the initial upgrade request to connection closure. ```text 1. Client: WebSocket upgrade request with headers 2. Server: 101 Switching Protocols response 3. Server: ready message (resumed: false, sessionId: xyz) 4. Client: play message with track 5. Server: playerUpdate messages (continuous) 6. Server: TrackStartEvent 7. [Client: update filters/volume/etc] 8. Server: playerUpdate + TrackEndEvent 9. Client: destroy message 10. Server: Connection closed ``` -------------------------------- ### TrackCacheManager Public Interface Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/05-managers.md Defines the methods for managing a cache of track data, including loading, saving, setting, getting, clearing, and checking the size of the cache. ```typescript class TrackCacheManager { load(): Promise save(): Promise set(key: string, track: TrackData, ttlMs?: number): void get(key: string): TrackData | undefined clear(): void size(): number } ``` -------------------------------- ### Configure YouTube Source Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Enable the YouTube source and set playlist and album load limits. This configuration is part of the main NodeLink config file. ```javascript youtube: { enabled: true, playlistLoadLimit: 20, // Tracks per playlist albumLoadLimit: 20 // Tracks per album } ``` -------------------------------- ### MeaningManager Public Interface Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/05-managers.md Defines the public interface for fetching song meanings and artist information. Use this to get song meanings or Wikipedia context for artists. ```typescript class MeaningManager { fetchMeaning(track: TrackData): Promise fetchArtistInfo(artist: string): Promise } ``` -------------------------------- ### TrackEndEvent Message Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/06-websocket-protocol.md Sent when a track stops playing. Includes guild ID, track information, the reason for stopping, and whether the next track may start. ```json { "op": "event", "type": "TrackEndEvent", "guildId": "123456789", "track": { ... }, "reason": "FINISHED", "mayStartNext": true } ``` -------------------------------- ### Configure Resumable Sessions via REST API Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/06-websocket-protocol.md This bash command demonstrates how to configure session resumption using the REST API, specifying the session ID and the desired settings. ```bash PATCH /v4/sessions/:sessionId Content-Type: application/json { "resuming": true, "timeout": 600 } ``` -------------------------------- ### Fetch Cluster Statistics Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Example of using curl to retrieve statistics from the cluster's statistics endpoint. This is useful for monitoring worker performance and player counts. ```bash curl -H "Authorization: password" \ http://localhost:2333/v4/stats ``` -------------------------------- ### Bilibili Source Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Configuration for the Bilibili audio source. The 'sessdata' cookie is optional and used for 4K content. ```javascript bilibili: enabled: true sessdata: '' // Optional: SESSDATA cookie for 4K ``` -------------------------------- ### Docker Deployment Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Dockerfile for building a NodeLink image with cluster mode enabled. Sets environment variables for cluster workers. ```dockerfile FROM node:22-alpine WORKDIR /app COPY . . RUN npm install ENV CLUSTER_ENABLED=true ENV CLUSTER_WORKERS=4 CMD ["npm", "run", "start"] ``` -------------------------------- ### Configure Auto-Scaling Parameters Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/09-cluster-deployment.md Define parameters for automatic scaling of workers based on load. This includes thresholds for scaling up/down, utilization targets, and lag/CPU limits. ```javascript scaling: { maxPlayersPerWorker: 20, targetUtilization: 0.7, scaleUpThreshold: 0.75, scaleDownThreshold: 0.3, checkIntervalMs: 5000, idleWorkerTimeoutMs: 60000, queueLengthScaleUpFactor: 5, lagPenaltyLimit: 60, cpuPenaltyLimit: 0.85 } ``` -------------------------------- ### JioSaavn Source Configuration Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/07-audio-sources.md Configuration for the JioSaavn audio source. Includes limits for loading playlists and artists, and an optional secret key and proxy settings. ```javascript jiosaavn: enabled: true playlistLoadLimit: 50 artistLoadLimit: 20 secretKey: '38346591', // Optional: Alternative secret key proxy: url: '' username: '' password: '' ``` -------------------------------- ### POST /v4/sessions/:sessionId/players/:guildId Source: https://github.com/performanc/nodelink/blob/v3/_autodocs/02-endpoints.md Creates a new player for a guild within a session or resumes an existing one. ```APIDOC ## POST /v4/sessions/:sessionId/players/:guildId ### Description Creates or resumes a player for a guild. ### Method POST ### Endpoint /v4/sessions/:sessionId/players/:guildId ### Parameters #### Path Parameters - **sessionId** (string): Session identifier - **guildId** (string): Guild identifier ### Response #### Success Response (201 Created) Player object with current state. #### Success Response (200 OK) Player object with current state. #### Error Response - **404 Not Found**: Session not found ```