UNPKG

serverquery

Version:

Low level TeamSpeak™ 3 ServerQuery protocol implementation

137 lines (100 loc) 3.03 kB
const DEBUG = !!process.env.DEBUG; import { format } from 'util'; /** * Optionally import colors, if in DEBUG mode. */ let colors; // HACK: lazy optional import try { colors = require('colors/safe'); } catch (error) { colors = false; } /** * Colors proxy. */ export function color(style, str) { return colors ? colors[style](str) : str; } const SERVER_QUERY = color('green', 'ServerQuery:'); const LENGTH = color('bold', 'length:') const SERIALIZED = color('bold', 'serialized:') const CMD = color('bold', 'cmd:'); const FLAGS = color('bold', 'flags:'); const PARAMS = color('bold', 'params:'); const RESPONSE = color('bold', 'response:'); /** * Get current time. */ export function now() { let date = new Date(); return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; } /** * Print a log message heading. * @param {String} msg */ function heading(msg) { console.log(`\n${color('cyan', now())} - ${SERVER_QUERY} ${color('yellow', msg)}`); } /** * Print a debug message. * @param {String|Error} msg * @param {String|Error} ...lines */ export default function debug(msg, ...lines) { if (DEBUG) { if (msg instanceof Error) { heading('Encountered an error'); console.log(color('red', msg)); return; } heading(msg); if (lines[0] instanceof Error) { return console.log(color('red', lines[0])); } lines.forEach(line => console.log(` ${line}`)); } } /** * Print a formatted command debug message. * @param {String} msg * @param {Object} command * @param {String} ...rest */ export function debugCommand(msg, command, ...rest) { if (DEBUG) { heading(msg); if (command.serialized) { console.log(` ${LENGTH} ${color('magenta', command.serialized.length)} chars (includring \\r\\n)`); console.log(` ${SERIALIZED} ${color('cyan', command.serialized.slice(0, -2))}`); // trim off \r\n } console.log(` ${CMD} ${color('cyan', command.cmd)} | ${FLAGS} ${stringify(command.flags)} | ${PARAMS} ${stringify(command.params)}`); if (command.response) { console.log(` ${RESPONSE} ${stringify(command.response)}`); } rest.forEach(line => console.log(` ${line}`)); } } /** * Print a formatted error debug message. * @param {String} msg * @param {Error} error * @param {String} ...rest */ export function debugError(msg, error, ...rest) { heading(msg || 'An error occured'); console.log(' ' + color('red', String(error).replace(/\n/g, '\n '))); rest.forEach(line => console.log(` ${line}`)); } /** * Stringify an object and optionally trim the output. * @param {Object} objs * @param {Number} limit */ export function stringify(obj, limit = 50) { let str = format('%j', obj); if (limit && str.length > limit) { return str.substring(0, limit) + ' ...'; } return str; }