UNPKG

lfs-akairo

Version:

LFS Akairo is a framework designed to simplify the creation of InSim applications.

284 lines (283 loc) 10.2 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; var module_exports = {}; __export(module_exports, { Module: () => Module }); module.exports = __toCommonJS(module_exports); var import_logger = require("#utils/logger"); var import_packets = require("node-insim/packets"); class Module { constructor(akairo) { this.akairo = akairo; this.intervals = /* @__PURE__ */ new Set(); this.events = /* @__PURE__ */ new Map(); this.commandHandlers = []; this.registeredCommands = /* @__PURE__ */ new Set(); this.unknownCommandHandlers = []; } /** * Registers a packet handler for a specific packet type. * @param type The type of packet to handle * @param callback Function to be called when packet is received */ onPacket(type, callback) { if (!Object.values(import_packets.PacketType).includes(type)) { throw new Error(`Invalid packet type: ${type}`); } const handlers = this.events.get(type) || []; const fallback = (packet) => __async(this, null, function* () { const player = this.getPlayerFromPacket(packet, type); callback(player, packet); }); handlers.push({ type, callback: fallback }); this.events.set(type, handlers); } /** * Registers a periodic task to be executed at specified intervals. * @param interval Time in milliseconds between executions * @param callback Function to be executed periodically */ onTick(interval, callback) { if (interval <= 0) { throw new Error("Interval must be greater than 0"); } const handler = () => __async(this, null, function* () { try { yield callback(this.akairo.players); } catch (error) { import_logger.logger.error(`Error in tick handler: "${error}"`); } }); const intervalId = setInterval(handler, interval); this.intervals.add(intervalId); } /** * Registers a command handler for one or more commands. * @param commands Command or array of commands to handle * @param callback Function to be called when command is received */ onCommand(commands, callback) { const commandList = Array.isArray(commands) ? commands : [commands]; if (commandList.length === 0) { throw new Error("At least one command must be provided"); } const normalizedCommands = new Set( commandList.map((cmd) => { const normalized = cmd.toLowerCase().trim(); if (normalized.length === 0) { throw new Error("Empty command is not allowed"); } if (this.registeredCommands.has(normalized)) { throw new Error(`Command "${normalized}" is already registered`); } return normalized; }) ); normalizedCommands.forEach((cmd) => this.registeredCommands.add(cmd)); this.commandHandlers.push({ commands: normalizedCommands, callback }); } /** * Registers a handler for unknown commands. * @param callback Function to be called when an unknown command is received */ onUnknownCommand(callback) { this.unknownCommandHandlers.push(callback); } /** * Bind all packets inside this module through InSim */ bind() { this.unbind(); for (const [type, handlers] of this.events) { for (const handler of handlers) { this.akairo.insim.addListener(type, handler.callback); } } this.akairo.insim.addListener( import_packets.PacketType.ISP_MSO, this.handleMessage.bind(this) ); } /** * Unbind all packets insidee this module through InSim */ unbind() { for (const [type, handlers] of this.events) { for (const handler of handlers) { this.akairo.insim.removeListener(type, handler.callback); } } this.akairo.insim.removeListener( import_packets.PacketType.ISP_MSO, this.handleMessage.bind(this) ); } handleMessage(packet) { return __async(this, null, function* () { if (packet.UserType !== import_packets.UserType.MSO_PREFIX) return; const parsed = this.parseMessage(packet); if (!parsed) return; const { command, args } = parsed; const player = this.getPlayerFromPacket(packet, import_packets.PacketType.ISP_MSO); if (!player) return; const commandExists = this.registeredCommands.has(command.toLowerCase()); if (commandExists) { yield this.handleKnownCommand(command, args, player); } else { yield this.handleUnknownCommand(command, args, player); } }); } parseMessage(packet) { var _a; const prefix = String((_a = this.akairo.settings) == null ? void 0 : _a.prefix).slice(0, 1) || "!"; const message = packet.Msg.substring(packet.TextStart).replace(/\s+/g, " ").trim(); if (!message.startsWith(prefix)) return null; const [rawCommand, ...args] = message.slice(prefix.length).split(" "); return { command: rawCommand.toLowerCase(), args: args.filter(Boolean) }; } handleKnownCommand(command, args, player) { return __async(this, null, function* () { const promises = this.commandHandlers.filter((handler) => handler.commands.has(command.toLowerCase())).map( (handler) => { var _a; return (_a = handler.callback(player, args)) == null ? void 0 : _a.catch( (error) => import_logger.logger.error(`Error handling command "${command}": "${error}"`) ); } ); yield Promise.all(promises); }); } handleUnknownCommand(command, args, player) { return __async(this, null, function* () { const promises = this.unknownCommandHandlers.map( (handler) => { var _a; return (_a = handler(player, command, args)) == null ? void 0 : _a.catch( (error) => import_logger.logger.error(`Error handling unknown command "${command}": "${error}"`) ); } ); yield Promise.all(promises); }); } getPlayerFromPacket(packet, type) { const player = () => { var _a, _b, _c; switch (type) { case import_packets.PacketType.ISP_NCN: { const parsed = packet; const found = (_a = this.akairo.players.getByUserName(parsed.UName)) != null ? _a : this.akairo.players.getByUniqueId(parsed.UCID); return found; } case import_packets.PacketType.ISP_NCI: { const parsed = packet; const found = this.akairo.players.getByUniqueId(parsed.UCID); return found; } case import_packets.PacketType.ISP_CNL: { const parsed = packet; const found = this.akairo.players.getByUniqueId(parsed.UCID); return found; } case import_packets.PacketType.ISP_NPL: { const parsed = packet; const found = (_c = (_b = this.akairo.players.getByUniqueId(parsed.UCID)) != null ? _b : this.akairo.players.getByPlayerId(parsed.PLID)) != null ? _c : this.akairo.players.getByPlayerName(parsed.PName); return found; } case import_packets.PacketType.ISP_PLP: { const parsed = packet; const found = this.akairo.players.getByPlayerId(parsed.PLID); return found; } case import_packets.PacketType.ISP_PLL: { const parsed = packet; const found = this.akairo.players.getByPlayerId(parsed.PLID); return found; } case import_packets.PacketType.ISP_TOC: { const parsed = packet; const byOldUniqueId = this.akairo.players.getByUniqueId( parsed.OldUCID ); if (byOldUniqueId) return byOldUniqueId; const byNewUniqueId = this.akairo.players.getByUniqueId( parsed.NewUCID ); if (byNewUniqueId) return byNewUniqueId; const byPlayerId = this.akairo.players.getByPlayerId(parsed.PLID); if (byPlayerId) return byPlayerId; return null; } case import_packets.PacketType.ISP_CPR: { const parsed = packet; const found = this.akairo.players.getByUniqueId(parsed.UCID); return found; } case import_packets.PacketType.ISP_MCI: { const list = []; const parsed = packet; for (const info of parsed.Info) { const byPlayerId = this.akairo.players.getByPlayerId(info.PLID); if (byPlayerId) { list.push(byPlayerId); } } return list; } default: return null; } }; const find = player(); if (find) return find; return this.akairo.players.array().find( (player2) => typeof player2.uniqueId === "number" && player2.uniqueId === packet.UCID || typeof player2.playerId === "number" && player2.playerId === packet.PLID ); } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { Module });