Star ✨ on GitHub

Utils

API reference for utilities in Moonlink.js

Utility Functions and Classes

Core utilities provided by Moonlink.js for extending and customizing functionality.

Utility Functions

validateProperty

validatePropertyfunction

Validate Property

Validates a property based on a validation function.

Parameters
propertyrequiredany
The property to validate
validatorrequiredFunction
Function that returns a boolean indicating if property is valid
errorMessagerequiredstring
Error message to throw if property is invalid

Returns & Example

Returnsvoid - Throws error if property is invalid

// Validate port number
validateProperty(
options.port,
value => value === undefined || (value >= 0 && value <= 65535),
"Invalid port value. Must be between 0 and 65535."
);

// Validate string
validateProperty(
options.identifier,
value => value === undefined || typeof value === "string",
"Invalid identifier. Must be a string."
);

delay

delayfunction

Delay

Creates a promise that resolves after specified milliseconds.

Parameters
msrequirednumber
Milliseconds to delay

Returns & Example

ReturnsPromise<void>

// Wait for 1 second
await delay(1000);

// Use in async function
async function reconnect() {
console.log('Reconnecting in 5 seconds...');
await delay(5000);
console.log('Reconnecting now');
}

decodeTrack

decodeTrackfunction

Decode Track

Decodes a base64-encoded track string.

Parameters
encodedTrackrequiredstring
Base64-encoded track string

Returns & Example

ReturnsITrack - Decoded track object

const track = decodeTrack('base64EncodedTrackString');
console.log(track.info.title);
console.log(track.info.author);
console.log(track.info.length);

encodeTrack

encodeTrackfunction

Encode Track

Encodes track information into a base64 string.

Parameters
trackrequiredITrackInfo
Track object to encode

Returns & Example

Returnsstring - Base64-encoded track string

const encodedTrack = encodeTrack({
title: 'Song Name',
author: 'Artist',
length: 180000,
identifier: 'trackId',
isStream: false,
uri: 'https://example.com/track',
sourceName: 'youtube'
});

generateUUID

generateUUIDfunction

Generate UUID

Generates a unique identifier (UUID) based on host and port using SHA256 hashing.

Parameters
hostrequiredstring
Host name or IP address
portrequirednumber
Port number

Returns & Example

Returnsstring - SHA256 hashed UUID

const uuid = generateUUID('localhost', 2333);
console.log(uuid); // e.g., 'a6a945ab2b79527275c7b01a25c5c465'

compareVersions

compareVersionsfunction

Compare Versions

Compares two version strings (e.g., "1.0.0", "1.2.3") and returns a number indicating their relative order.

Parameters
currentrequiredstring
The current version string.
requiredrequiredstring
The required version string.

Returns & Example

Returnsnumber - A negative number if current is less than required, a positive number if current is greater than required, or 0 if they are equal.

const result1 = compareVersions("1.0.0", "1.0.0"); // 0
const result2 = compareVersions("1.0.0", "1.1.0"); // -1 (current is less than required)
const result3 = compareVersions("1.2.0", "1.1.0"); // 1 (current is greater than required)

stringifyWithReplacer

stringifyWithReplacerfunction

Stringify with Replacer

Converts a JavaScript value to a JSON string, handling circular references by replacing them with "[Circular Refs]".

Parameters
objrequiredany
The value to convert to a JSON string.

Returns & Example

Returnsstring - A JSON string representation of the value.

const obj = {};
obj.a = obj;
const jsonString = stringifyWithReplacer(obj);
console.log(jsonString); // {"a":"[Circular Refs]"}

Log

Logfunction

Log

Logs a message to a specified file.

Parameters
messagerequiredstring
Message to log
LogPathrequiredstring
Path to log file

Returns & Example

Returnsvoid

Log('Player created', './logs/moonlink.log');

makeRequest

makeRequestfunction

Make Request

Makes an HTTP request and returns JSON response. Now supports retries and timeouts.

Parameters
urlrequiredstring
Request URL
optionsrequiredhttp.RequestOptions & { body?: any }
Request options, including optional body.
timeoutnumber
Optional: Request timeout in milliseconds. Defaults to 10000.
retriesnumber
Optional: Number of retry attempts. Defaults to 3.
retryDelaynumber
Optional: Delay between retries in milliseconds. Defaults to 1000.

Returns & Example

ReturnsPromise<T | undefined> - Generic type response or undefined if request fails after retries.

// GET request with custom timeout and retries
const data = await makeRequest('https://api.example.com/data', {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
}, 5000, 5);

// POST request
const response = await makeRequest('https://api.example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' })
});

isSourceBlacklisted

isSourceBlacklistedfunction

Is Source Blacklisted

Checks if a given source name is blacklisted in the Manager options.

Parameters
managerrequiredManager
The Manager instance.
sourceNamerequiredstring
The name of the source to check.

Returns & Example

Returnsboolean - true if the source is blacklisted, false otherwise.

const isBlacklisted = isSourceBlacklisted(manager, 'spotify');
if (isBlacklisted) {
console.log('Spotify is blacklisted.');
}

Utility Classes

Structure

Structureclass

Structure Class

Abstract class for extending and customizing Moonlink.js structures. Provides static methods for managing the Manager instance and extending core classes.

Static Methods
setManagermethod
Sets the global Manager instance for internal use.
getManagermethod
Retrieves the global Manager instance.
extendmethod
Extends a core Moonlink.js structure (e.g., Player, Node) with custom functionality.
getmethod
Retrieves an extended or default structure by name.

Example Usage

// Extend Player class
Structure.extend('Player', Player => {
return class CustomPlayer extends Player {
  constructor(manager, options) {
    super(manager, options);
    this.customProperty = 'custom value';
  }
  
  customMethod() {
    return this.customProperty;
  }
};
});

// Use custom player
const player = manager.players.create({
guildId: '123456789',
voiceChannelId: '123456789',
textChannelId: '123456789'
});

console.log(player.customProperty);
player.customMethod();

Plugin

Pluginclass

Plugin Class

Base class for creating Moonlink.js plugins. Plugins can extend core functionalities and integrate with the Manager.

Properties
PropertyTypeDescription
namestringThe name of the plugin.
versionstringThe version of the plugin.
descriptionstringA brief description of the plugin's purpose.
author`stringRecord<string, any>`
minVersionstringThe minimum Moonlink.js version required by this plugin.
Methods
MethodDescription
load(manager)Called when the plugin is loaded by the Manager.
unload(manager)Called when the plugin is unloaded from the Manager.

Example Usage

class CustomPlugin extends Plugin {
constructor() {
  super();
  this.name = 'CustomPlugin';
  this.version = '1.0.0';
  this.description = 'A custom plugin';
  this.author = 'Your Name';
  this.minVersion = '1.0.0'; // Specify minimum Moonlink.js version
}

load(manager) {
  console.log(`${this.name} loaded`);
  
  // Add custom functionality
  Structure.extend('Player', Player => {
    return class CustomPlayer extends Player {
      constructor(manager, options) {
        super(manager, options);
        this.pluginProperty = 'plugin value';
      }
    };
  });
}

unload(manager) {
  console.log(`${this.name} unloaded`);
}
}

// Register plugin
manager.plugins.register(new CustomPlugin());

Utils