refactoring and comments

fix(cli.js): refactor help and error handling logic for better readability and maintainability
feat(cli.js): add support for custom port and timeout options
fix(parallel.js): update list of hosts to ping
fix(bedrock.js): add comments and improve error handling in ping function
fix(java.js): add comments and improve error handling in ping function
fix(varint.js): add comments to functions and improve readability
fix(index.d.ts): export all functions from java.js and bedrock.js
fix(lib/bedrock.d.ts): update source link
fix(lib/java.d.ts): update source link
This commit is contained in:
2023-10-22 21:32:00 +03:00
parent 915edbec9c
commit 910184bf5f
8 changed files with 148 additions and 59 deletions

View File

@ -131,12 +131,15 @@ const UNCONNECTED_PONG = (buffer) => {
const ping = (host, port = 19132, cb, timeout = 5000) => {
const socket = dgram.createSocket('udp4');
// Set manual timeout interval.
// This ensures the connection will NEVER hang regardless of internal state
const timeoutTask = setTimeout(() => {
socket.emit('error', new Error('Socket timeout'));
}, timeout);
const closeSocket = () => {
socket.close(); clearTimeout(timeoutTask);
socket.close();
clearTimeout(timeoutTask);
};
// Generic error handler
@ -144,6 +147,10 @@ const ping = (host, port = 19132, cb, timeout = 5000) => {
// This is mostly dangerous since it can swallow errors
let didFireError = false;
/**
* Handle any error that occurs during the ping process.
* @param {Error} err The error that occurred.
*/
const handleError = (err) => {
closeSocket();
@ -191,15 +198,15 @@ const ping = (host, port = 19132, cb, timeout = 5000) => {
}
});
socket.on('error', (err) => handleError(err));
socket.on('error', handleError);
};
/**
* Asynchronously ping Minecraft Bedrock server.
* The optional `options` argument can be an object with a `ping` (default is `19132`) or/and `timeout` (default is `5000`) property.
* @param {string} host The Bedrock server address.
* @param {import('../types/lib/bedrock.js').PingOptions} options The configuration for pinging Minecraft Bedrock server.
* @returns {Promise<import('../types/lib/bedrock.js').BedrockPingResponse>}
* @param {import('../types/index.js').PingOptions} options The configuration for pinging Minecraft Bedrock server.
* @returns {Promise<import('../types/index.js').BedrockPingResponse>}
*/
export const pingBedrock = (host, options = {}) => {
if (!host) throw new Error('Host argument is not provided');