### Install Client Engines with lip Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/index.md Install client-side engines for LegacyScriptEngine using the 'lip install' command with the '#client_' prefix. This allows for client-specific plugin execution. ```shell lip install github.com/LiteLDev/LegacyScriptEngine#client_lua lip install github.com/LiteLDev/LegacyScriptEngine#client_quickjs lip install github.com/LiteLDev/LegacyScriptEngine#client_nodejs lip install github.com/LiteLDev/LegacyScriptEngine#client_python ``` -------------------------------- ### JavaScript Code Example Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/DataBase.md A comprehensive example demonstrating database initialization, data loading using different iteration methods, and data writing with bound parameters. ```javascript let dat = {}; let modified = {}; let session = null; function initdb() { if (!file.exists("plugins/MyPlugin")) file.mkdir("plugins/MyPlugin"); session = new DBSession("sqlite", {path: "./plugins/MyPlugin/dat.db"}); session.exec(` CREATE TABLE IF NOT EXISTS \"test\" ( player CHAR(100) NOT NULL, coins INTEGER NOT NULL ); `); // SQLite automatically adds a hidden ROWID column. // insertId refers to this ROWID value. } // Using do...while loop function loadData() { let stmt = session.prepare("SELECT * FROM test"); // After prepare/execute, the cursor is already on the first row do { let row = stmt.fetch(); dat[row.player] = row.coins; } while (stmt.step()); } // Using callback function function loadData2() { session.prepare("SELECT * FROM test") .execute() .fetchAll((row) => { dat[row.player] = row.coins; }); } function writeData() { let keys = Object.keys(modified); let stmt = session.prepare("UPDATE test SET coins = ? WHERE player = ?"); for (let i = 0; i < keys.length; i++) { let v = modified[keys[i]]; // Automatically executes after binding if logic requires stmt.bind([v, keys[i]]).execute(); stmt.clear(); // Clear values for next iteration } } mc.regPlayerCmd("getcoin", "Get a coin!", (pl, args)=>{ dat[pl.realName]++; modified[pl.realName]++; }); ``` -------------------------------- ### Install Server Engines with lip Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/index.md Use the 'lip install' command to add specific LegacyScriptEngine versions for server-side use. Ensure you have Python installed if you choose the Python engine. ```shell lip install github.com/LiteLDev/LegacyScriptEngine#lua lip install github.com/LiteLDev/LegacyScriptEngine#quickjs lip install github.com/LiteLDev/LegacyScriptEngine#nodejs lip install github.com/LiteLDev/LegacyScriptEngine#python ``` -------------------------------- ### Install Specific Client Engine Version Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/index.md To install a particular version of a client engine, append '@version' to the installation command. This is useful for compatibility or testing specific releases. ```shell lip install github.com/LiteLDev/LegacyScriptEngine#client_lua@0.17.0-rc.2 lip install github.com/LiteLDev/LegacyScriptEngine#client_quickjs@0.17.0-rc.2 lip install github.com/LiteLDev/LegacyScriptEngine#client_nodejs@0.17.0-rc.2 lip install github.com/LiteLDev/LegacyScriptEngine#client_python@0.17.0-rc.2 ``` -------------------------------- ### Navigate To Block Return Value Example Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Example of the return value structure for simulateNavigateTo when navigating to a block. It indicates if a full path was found and the path coordinates. ```json { isFullPath: false, path: [ [ -8, 0, -3 ], [ -7, 0, -2 ], [ -6, 0, -2 ], [ -5, 0, -2 ], [ -4, 0, -1 ], [ -3, 0, -1 ], [ -2, 0, -1 ], [ -1, 0, 0 ] ] } ``` -------------------------------- ### Register GET Request Listeners with Priority Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.zh.md Demonstrates how multiple GET request listeners are handled based on definition order. More specific paths defined earlier take precedence over more general or later-defined paths. ```javascript svr.onGet('/test/123', (req, res) => { res.write('test'); }).onGet('/test/(.+)', (req, res) => { res.write('get /test/'); }).onGet('/test/foo', (req, res) => { res.write("bar"); }); ``` -------------------------------- ### Install PDM Package Manager Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/LanguageSupport.md Command to install the PDM tool, which is recommended for managing Python plugin dependencies and metadata. ```bash pip install --user pdm ``` -------------------------------- ### Database Session and Statement Implementation Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/DataBase.md Example demonstrating database initialization, row iteration using do-while and callbacks, and parameter binding. ```javascript let dat = {}; let modified = {}; let session = null; function initdb() { if (!file.exists("plugins/MyPlugin")) file.mkdir("plugins/MyPlugin"); session = new DBSession("sqlite", {path: "./plugins/MyPlugin/dat.db"}); session.exec(` CREATE TABLE IF NOT EXISTS "test" ( player CHAR(100) NOT NULL, coins INTEGER NOT NULL );`); // SQLite automatically adds a hidden ROWID column. // insertId refers to this ROWID value. } // Using do...while loop function loadData() { let stmt = session.prepare("SELECT * FROM test"); // After prepare/execute, the cursor is already on the first row do { let row = stmt.fetch(); dat[row.player] = row.coins; } while (stmt.step()); } // Using callback function function loadData2() { session.prepare("SELECT * FROM test") .execute() .fetchAll((row) => { dat[row.player] = row.coins; }); } function writeData() { let keys = Object.keys(modified); let stmt = session.prepare("UPDATE test SET coins = ? WHERE player = ?"); for (let i = 0; i < keys.length; i++) { let v = modified[keys[i]]; // Automatically executes after binding if logic requires stmt.bind([v, keys[i]]).execute(); stmt.clear(); // Clear values for next iteration } } mc.regPlayerCmd("getcoin", "Get a coin!", (pl, args)=>{ dat[pl.realName]++; modified[pl.realName]++; }); ``` -------------------------------- ### Listen on Address and Port Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.zh.md Starts the server by listening on the specified address and port. This is a primary method for initiating server operations. ```javascript svr.listen(addr, port) ``` -------------------------------- ### Start Server at Address and Port Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.zh.md An alternative method to svr.listen for specifying the address and port to listen on. It also returns the server object for chaining. ```javascript svr.startAt(addr, port) ``` -------------------------------- ### onServerStarted Event Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/EventAPI/OtherEvents.md Fires when the server has started. This event cannot be intercepted. ```APIDOC ## onServerStarted Event ### Description Fires when the server has started. ### Parameters #### Parameters - None ### Intercept Event Cannot be intercepted. ``` -------------------------------- ### QuickJS Entry Module Import Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/LanguageSupport.md Example of an entry module import that fails due to QuickJS path resolution behavior. ```javascript import { initCommand } from "./command/command.js" initCommand(); ``` -------------------------------- ### Listen for HTTP GET Requests Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.zh.md Register a callback function to handle incoming GET requests for a specific path using `svr.onGet`. The path can include regular expressions. The callback receives HttpRequest and HttpResponse objects. ```javascript svr.onGet(path, callback) ``` -------------------------------- ### Server Control Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.zh.md Methods for starting, stopping, and checking the status of the server. ```APIDOC ## Server Control ### Listen for Port and Start Server `svr.listen(addr, port)` `svr.startAt(addr, port)` - **Parameters**: - `addr` (String): Listening address, can be an IP address or domain name. - `port` (Number): Listening port. - **Returns**: The server object (for chaining operations). - **Return Type**: `HttpServer` ### Stop Server `svr.stop()` - **Returns**: None. ### Get Server Running Status `svr.isRunning()` - **Returns**: Whether the server is running. - **Return Type**: `Boolean` ``` -------------------------------- ### Plugin Management and Communication in JavaScript Source: https://context7.com/liteldev/legacyscriptengine/llms.txt Shows how to get version information, list plugins, manage exports/imports, and handle plugin unloading. ```javascript // Version information log(`LSE Version: ${ll.versionString()}`); log(`Version: ${ll.major}.${ll.minor}.${ll.revision}`); log(`Is Release: ${ll.isRelease}`); log(`Language: ${ll.language}`); ``` ```javascript // Plugin information let plugins = ll.listPlugins(); log(`Loaded plugins: ${plugins.join(", ")}`); let allPluginInfo = ll.getAllPluginInfo(); allPluginInfo.forEach(plugin => { log(`${plugin.name} v${plugin.versionStr}: ${plugin.desc}`); }); ``` ```javascript // Current plugin info let currentPlugin = ll.getCurrentPluginInfo(); log(`This plugin: ${currentPlugin.name}`); ``` ```javascript // Export function for other plugins function mySharedFunction(param1, param2) { return param1 + param2; } ll.exports(mySharedFunction, "MyPlugin", "addNumbers"); ``` ```javascript // Import function from another plugin if (ll.hasExported("OtherPlugin", "getData")) { let getData = ll.imports("OtherPlugin", "getData"); let result = getData("playerStats"); log(`Got data: ${JSON.stringify(result)}`); } ``` ```javascript // Cleanup on unload ll.onUnload(() => { log("Plugin unloading, saving data..."); // Save data, close connections, etc. }); ``` -------------------------------- ### Example Log Output Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/ScriptAPI/Logger.md The resulting format of an error log message. ```log [2021-05-21 19:41:03 Error] Fail to transport the player ``` -------------------------------- ### Bind Parameters to Statement Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/DataBase.md Example demonstrating how to bind various data types to a prepared statement using an object, array, and individual values. ```javascript let stmt = session.prepare("INSERT INTO table VALUES ($a, $b, $c, $d, $e, $f, $g, $h)"); let values = { c: "have you", d: "finished", e: "your", f: "homework?" }; stmt.bind(values); // Binds c, d, e, f stmt.bind("LLSE"); // Binds to a stmt.bind(["****", "mojang"]); // Binds to b and g stmt.bind(114514, 7); // Binds to h (index 7) ``` -------------------------------- ### Register Command with Overloads and Enums Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Command.md Example of registering a command with aliases, enumerated parameters, mandatory parameters, and multiple overloads. The callback handles different actions based on the 'action' parameter. ```javascript mc.listen("onServerStarted", () => { let cmd = mc.newCommand("manager", "Command Description", PermType.GameMasters); cmd.setAlias("mgr"); cmd.setEnum("ChangeAction", ["add", "remove"]); cmd.setEnum("ListAction", ["list"]); cmd.mandatory("action", ParamType.Enum, "ChangeAction", 1); cmd.mandatory("action", ParamType.Enum, "ListAction", 1); cmd.mandatory("name", ParamType.RawText); cmd.overload(["ChangeAction", "name"]); cmd.overload(["ListAction"]); cmd.setCallback((_cmd, _ori, out, res) => { switch (res.action) { case "add": return out.success(`add "${res.name}"`); case "remove": return out.success(`remove "${res.name}"`); case "list": return out.success(`Name List:`); } }); cmd.setup(); }); ``` -------------------------------- ### Get Configuration File Path (JavaScript) Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Retrieves the full path of the currently managed configuration file. ```javascript conf.getPath() ``` -------------------------------- ### Register Custom Commands with Overloads Source: https://context7.com/liteldev/legacyscriptengine/llms.txt Register a comprehensive command with multiple overloads, including enumerations for actions and parameters. Requires OP permission. Ensure the server has started before registration. ```javascript // Register a comprehensive command with multiple overloads mc.listen("onServerStarted", () => { // Create command with OP permission required let cmd = mc.newCommand("home", "Manage player homes", PermType.GameMasters); cmd.setAlias("h"); // Define enumerations for actions cmd.setEnum("HomeAction", ["set", "delete", "tp"]); cmd.setEnum("ListAction", ["list"]); // Define parameters cmd.mandatory("action", ParamType.Enum, "HomeAction", 1); cmd.mandatory("action", ParamType.Enum, "ListAction", 1); cmd.mandatory("name", ParamType.String); cmd.optional("player", ParamType.Player); // Register overloads cmd.overload(["HomeAction", "name"]); cmd.overload(["ListAction"]); cmd.overload(["HomeAction", "name", "player"]); // Set callback handler cmd.setCallback((cmd, origin, output, results) => { let player = origin.player; if (!player) { output.error("This command can only be used by players"); return; } switch (results.action) { case "set": let pos = player.pos; output.success(`Home "${results.name}" set at ${pos.x}, ${pos.y}, ${pos.z}`); break; case "delete": output.success(`Home "${results.name}" deleted`); break; case "tp": output.success(`Teleporting to home "${results.name}"`); break; case "list": output.success("Your homes: home1, home2, spawn"); break; } }); // Install the command cmd.setup(); }); // Execute background commands mc.runcmd("say Server starting..."); let result = mc.runcmdEx("list"); log(`Command success: ${result.success}, Output: ${result.output}`); ``` -------------------------------- ### Initialize Node.js Plugin Project Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/LanguageSupport.md Standard command to initialize a new Node.js project directory for plugin development. ```bash npm init ``` -------------------------------- ### Send an Asynchronous HTTP(s) Get Request Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.md Allows scripts to send asynchronous GET requests to specified URLs and handle responses via a callback function. ```APIDOC ## Send an Asynchronous HTTP(s) Get Request ### Description Sends an asynchronous HTTP(s) GET request to a specified URL and executes a callback function upon receiving the response. ### Method `network.httpGet(url, callback)` ### Parameters #### Path Parameters - **url** (String) - Required - The target address of the request (including parameters). - **callback** (Function) - Required - The callback function to execute when the request returns. ### Callback Function Prototype `function(status, result)` - **status** (Integer) - The HTTP(s) response code (e.g., 200 for success, -1 for failure). - **result** (String) - The returned data from the request. ### Return Value - Returns `Boolean` indicating whether the request was successfully sent. ``` -------------------------------- ### GET mc.getPlayer(info) Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Manually generate a player object using player information. The player must be online for the operation to succeed. ```APIDOC ## GET mc.getPlayer(info) ### Description Manually generate a player object using player information. Note that the player must be online. ### Parameters #### Path Parameters - **info** (String) - Required - Player's name, XUID, UniqueId, RuntimeId, or UUID. ### Response - **Return Value** (Player) - The generated player object or Null if the operation failed. ``` -------------------------------- ### Initialize Python Plugin Project Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/LanguageSupport.md Command to initialize a new Python project using PDM, which generates the necessary pyproject.toml file. ```bash pdm init ``` -------------------------------- ### Create or Open Ini Profile (JavaScript) Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Use this to create a new INI configuration file or open an existing one. LLSE will create the directory if it doesn't exist. Provide default content if the file is new. ```javascript new IniConfigFile(path[,default]) ``` -------------------------------- ### Send Asynchronous HTTP(s) GET Request Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.zh.md Use network.httpGet to send an asynchronous GET request. Provide the URL, optional headers, and a callback function to handle the response. The callback receives the status code and result data. ```javascript network.httpGet(url[,header],callback) ``` -------------------------------- ### Create or Open Ini Profile (Lua) Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Use this to create a new INI configuration file or open an existing one. LLSE will create the directory if it doesn't exist. Provide default content if the file is new. ```lua IniConfigFile(path[,default]) ``` -------------------------------- ### GET bl.hasContainer Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Block.md Checks if the block acts as a container. ```APIDOC ## GET bl.hasContainer ### Description Determines if the block has an associated container (e.g., chests, buckets). ### Response - **Boolean** - True if the block has a container, false otherwise. ``` -------------------------------- ### GET system.randomGuid Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/SystemInfo.md Generates a random unique identifier string. ```APIDOC ## GET system.randomGuid ### Description Generates and returns a randomly generated unique identifier (GUID) string. ### Endpoint system.randomGuid() ### Response - **Return Value** (String) - A randomly generated unique identifier GUID. ``` -------------------------------- ### GET bl.getBlockState Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Block.md Parses and returns the BlockState of the block as an object. ```APIDOC ## GET bl.getBlockState ### Description Convenience function to parse block BlockState and convert it to an object for easy reading. ### Response - **Object** - The parsed BlockState object. ``` -------------------------------- ### Create or Open a JSON Configuration File Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Initializes a JSON configuration file object. The path is relative to the BDS root directory. ```JavaScript new JsonConfigFile(path[,default]) ``` ```Lua JsonConfigFile(path[,default]) ``` -------------------------------- ### Initialize Configuration Items Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Ensures a configuration item exists with a default value if it is missing. ```JavaScript conf.init(name,default) ``` -------------------------------- ### Get Player Sprint Status Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Checks if the player is currently sprinting. ```javascript pl.isSprinting() ``` -------------------------------- ### JsonConfigFile Constructor Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Initializes or opens a JSON configuration file at the specified path. ```APIDOC ## Constructor: JsonConfigFile(path, default) ### Description Creates or opens a JSON configuration file. If the file does not exist, it creates it using the provided default content. ### Parameters #### Path Parameters - **path** (String) - Required - The file path relative to the BDS root directory. - **default** (String) - Optional - The default content to write if the file is newly created. ### Response - **JsonConfigFile** (Object) - The opened configuration file object. ``` -------------------------------- ### Command Registration and Parameter Handling Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Command.md Explains how to register a new command using mc.newCommand and how the 'result' object maps command parameters to data values. ```APIDOC ## Command Registration ### Description Registers a new command with the engine, defining its name, description, permissions, and parameter structure. ### Parameters - **name** (String) - The name of the command. - **description** (String) - A brief description of the command. - **permission** (PermType) - The permission level required to execute the command. ### Parameter Types The `result` object contains key-value pairs where the key is the parameter name and the value is the data provided by the executor. Supported types include: - **ParamType.Bool**: Boolean - **ParamType.Int**: Integer - **ParamType.Float**: Float - **ParamType.String**: String - **ParamType.Actor**: Array - **ParamType.Player**: Array - **ParamType.BlockPos**: IntPos - **ParamType.Vec3**: FloatPos - **ParamType.RawText**: String - **ParamType.Message**: String - **ParamType.JsonValue**: String - **ParamType.Item**: Item - **ParamType.Block**: Block - **ParamType.Effect**: String - **ParamType.Enum**: String - **ParamType.SoftEnum**: String - **ParamType.ActorType**: String - **ParamType.Command**: String ### Request Example ```js mc.listen("onServerStarted", () => { let cmd = mc.newCommand("manager", "Command Description", PermType.GameMasters); cmd.setAlias("mgr"); cmd.setEnum("ChangeAction", ["add", "remove"]); cmd.mandatory("action", ParamType.Enum, "ChangeAction", 1); cmd.mandatory("name", ParamType.RawText); cmd.overload(["ChangeAction", "name"]); cmd.setCallback((_cmd, _ori, out, res) => { // res contains the parsed parameters return out.success(`Action: ${res.action}, Name: ${res.name}`); }); cmd.setup(); }); ``` ``` -------------------------------- ### GET mc.getOnlinePlayers() Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Retrieve a list of all currently online player objects. ```APIDOC ## GET mc.getOnlinePlayers() ### Description Returns an array of player objects, each corresponding to a player currently on the server. ### Response - **Return Value** (Array) - A list of online Player objects. ``` -------------------------------- ### Get List Length Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/NbtAPI/NBTList.md Retrieve the total number of elements in the NbtList. ```JavaScript list.getSize() ``` -------------------------------- ### GET system.getTimeObj Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/SystemInfo.md Retrieves the current system time as a structured object. ```APIDOC ## GET system.getTimeObj ### Description Returns an object containing individual components of the current system time. ### Endpoint system.getTimeObj() ### Response - **tm.Y** (Integer) - Year value (4 digits) - **tm.M** (Integer) - Month value - **tm.D** (Integer) - Day value - **tm.h** (Integer) - Hour value (24-hour clock) - **tm.m** (Integer) - Minute value - **tm.s** (Integer) - Seconds value - **tm.ms** (Integer) - Millisecond value ``` -------------------------------- ### IniConfigFile Constructor Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Initializes or opens an INI configuration file at the specified path. ```APIDOC ## Constructor: IniConfigFile(path, default) ### Description Creates or opens an INI configuration file. If the file does not exist, it creates it using the provided default content. ### Parameters - **path** (String) - Required - The path to the configuration file relative to the BDS root directory. - **default** (String) - Optional - Default content to write if the file is created. ### Response - **Returns** (IniConfigFile) - The profile object for the configuration file. ``` -------------------------------- ### GET system.getTimeStr Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/SystemInfo.md Retrieves the current system time as a formatted string. ```APIDOC ## GET system.getTimeStr ### Description Returns the current time string using the local time zone and 24-hour clock format. ### Endpoint system.getTimeStr() ### Response - **Return Value** (String) - The current time string (e.g., 2021-04-03 19:15:01) ``` -------------------------------- ### Get All Items Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Container.md Retrieves all item objects currently stored in the container. ```APIDOC ## GET ct.getAllItems() ### Description Retrieves all item objects in all grids of the container. The returned objects are references, meaning modifications directly affect the items in the container. ### Response - **Return Type**: Array - A list of all item objects in the container. ``` -------------------------------- ### Read Entire Configuration File Content (JavaScript) Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Reads and returns the entire content of the configuration file as a string. ```javascript conf.read() ``` -------------------------------- ### NbtList Creation Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/NbtAPI/NBTList.md Demonstrates how to create a new NbtList object, optionally initializing it with an array of NBT objects. ```APIDOC ## NbtList Creation ### Description Creates a new NbtList object. This list can store NBT objects and supports operations unique to lists. ### Method `new NbtList([data])` (JavaScript) or `NbtList([data])` (Lua) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **data** (Array) - Optional - An array of NBT objects to initialize the list with. The array can contain nested structures, but all elements must be NBT objects. ### Request Example ```javascript // JavaScript Example const myList = new NbtList([{ type: 'string', value: 'hello' }, { type: 'int', value: 123 }]); ``` ```lua -- Lua Example local myList = NbtList({{ type = 'string', value = 'hello' }, { type = 'int', value = 123 }}) ``` ### Response #### Success Response (200) - **NbtList** - The newly created NbtList object. #### Response Example ```json { "type": "NbtList", "value": [ { "type": "string", "value": "hello" }, { "type": "int", "value": 123 } ] } ``` ### Error Handling - Throws an exception if the creation fails. ``` -------------------------------- ### JSON Configuration File Management Source: https://context7.com/liteldev/legacyscriptengine/llms.txt Handle plugin settings using JSON files. The `init` method provides default values if a setting is not found. ```javascript let config = new JsonConfigFile("plugins/MyPlugin/config.json", JSON.stringify({ serverName: "My Server", maxPlayers: 20, features: { pvp: true, economy: true } })); // Initialize with defaults (creates if not exists) let serverName = config.init("serverName", "Default Server"); let maxPlayers = config.init("maxPlayers", 20); // Read and write values config.set("lastRestart", Date.now()); let features = config.get("features"); log(`PVP enabled: ${features.pvp}`); // Reload from disk after manual edits config.reload(); config.close(); ``` -------------------------------- ### Manage Respawn Position Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Gets or modifies the player's respawn coordinates. ```text pl.getRespawnPosition() ``` ```text pl.setRespawnPosition(pos) pl.setRespawnPosition(x,y,z,dimid) ``` -------------------------------- ### Get Device Information Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Retrieves the device information object associated with the player. ```text pl.getDevice() ``` -------------------------------- ### Simulated Player Actions in JavaScript Source: https://context7.com/liteldev/legacyscriptengine/llms.txt Illustrates creating and controlling simulated players (bots) for testing and automation, including movement, interaction, and navigation. ```javascript // Create simulated player let bot = mc.spawnSimulatedPlayer("TestBot", 100, 65, 200, 0); if (bot) { // Basic actions bot.simulateJump(); bot.simulateAttack(); bot.simulateRespawn(); // Look at target bot.simulateLookAt(player.pos, 1); // Continuous look bot.simulateSetBodyRotation(90); // Movement bot.simulateLocalMove({ x: 0, y: 0, z: 1 }, 1.0); // Move forward bot.simulateMoveTo(110, 65, 210, 0); // Direct move // Navigation with pathfinding let navResult = bot.simulateNavigateTo(player.pos, 1.0); if (navResult.isFullPath) { log("Full path found!"); } log(`Path: ${JSON.stringify(navResult.path)}`); // Interact with world bot.simulateInteract(); // Interact with entity/block in view bot.simulateDestroy(); // Break block in view bot.simulateUseItem(); // Use held item // Stop actions bot.simulateStopMoving(); bot.simulateStopDestroyingBlock(); // Disconnect bot bot.simulateDisconnect(); } ``` -------------------------------- ### Get Standing Block Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Retrieves the block object the player is currently standing on. ```text pl.getBlockStandingOn() ``` -------------------------------- ### Get All Loaded Entities Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Entity.md Retrieves an array of all currently loaded entity objects. ```javascript mc.getAllEntities() ``` -------------------------------- ### Create a Simple Form with Buttons Source: https://context7.com/liteldev/legacyscriptengine/llms.txt Ideal for presenting a list of options to the player. Each button is associated with an ID handled in the callback. ```javascript player.sendSimpleForm( "Main Menu", "Select an option:", ["Teleport Home", "Shop", "Settings", "Exit"], ["textures/items/compass", "textures/items/emerald", "textures/items/redstone", ""], (pl, id, reason) => { if (id === null) return; switch (id) { case 0: pl.tell("Teleporting home..."); break; case 1: pl.tell("Opening shop..."); break; case 2: pl.tell("Opening settings..."); break; case 3: pl.tell("Goodbye!"); break; } } ); ``` -------------------------------- ### Get Player Biome Information Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Retrieves the current biome ID or name for the player. ```javascript pl.getBiomeId() ``` ```javascript pl.getBiomeName() ``` -------------------------------- ### Player Utility and UI Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.zh.md Methods for server transfer, client control, and sidebar management. ```APIDOC ## pl.transServer(server, port) ### Description Transfers the player to a specified server. ### Parameters - **server** (String) - Required - Target server IP or domain. - **port** (Integer) - Required - Target server port. ### Response - **Boolean** - Returns true if successful. ## pl.crash() ### Description Forces the player's client to crash. ### Response - **Boolean** - Returns true if successful. ## pl.setSidebar(title, data, sortOrder) ### Description Sets a custom sidebar for the player. ### Parameters - **title** (String) - Required - Sidebar title. - **data** (Object) - Required - Sidebar content key-value pairs. - **sortOrder** (Number) - Optional - 0 for ascending, 1 for descending. Default is 1. ### Response - **Boolean** - Returns true if successful. ## pl.removeSidebar() ### Description Removes the player's custom sidebar. ### Response - **Boolean** - Returns true if successful. ``` -------------------------------- ### Player Respawn Coordinates Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Methods for getting and setting the player's respawn coordinates. ```APIDOC ## GET /api/player/getRespawnPosition ### Description Retrieves the player's current respawn coordinates. ### Method GET ### Endpoint /api/player/getRespawnPosition ### Response #### Success Response (200) - **position** (IntPos) - The respawn coordinates of the player. #### Response Example ```json { "position": {"x": 0, "y": 64, "z": 0, "dimension": "overworld"} } ``` ``` ```APIDOC ## POST /api/player/setRespawnPosition ### Description Sets the player's respawn coordinates. ### Method POST ### Endpoint /api/player/setRespawnPosition ### Parameters #### Request Body - **pos** (IntPos or FloatPos) - Required - The new respawn coordinates. Can be provided as a single `IntPos` or `FloatPos` object, or as individual x, y, z, and dimid parameters. - **x** (Number) - Required if `pos` is not provided - The x-coordinate. - **y** (Number) - Required if `pos` is not provided - The y-coordinate. - **z** (Number) - Required if `pos` is not provided - The z-coordinate. - **dimid** (String) - Required if `pos` is not provided - The dimension ID. ### Request Example ```json { "pos": {"x": 10, "y": 70, "z": -30, "dimension": "overworld"} } ``` ### Response #### Success Response (200) - **success** (Boolean) - Indicates whether the respawn position was successfully modified. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### HTTP Client API Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.zh.md Methods for performing asynchronous HTTP(s) GET and POST requests. ```APIDOC ## network.httpGet(url[,header],callback) ### Description Sends an asynchronous HTTP(s) GET request. ### Parameters - **url** (String) - Required - Target URL including query parameters. - **header** (Object) - Optional - Request headers. - **callback** (Function) - Required - Callback function with signature `function(status, result)`. ### Response - **Returns** (Boolean) - Whether the request was successfully sent. - **Callback status** (Integer) - HTTP response code (or -1 on failure). - **Callback result** (String) - Response body. --- ## network.httpPost(url[,header],data,type,callback) ### Description Sends an asynchronous HTTP(s) POST request. ### Parameters - **url** (String) - Required - Target URL. - **header** (Object) - Optional - Request headers. - **data** (String) - Required - Data to send. - **type** (String) - Required - Content-Type (e.g., 'application/json'). - **callback** (Function) - Required - Callback function with signature `function(status, result)`. ``` -------------------------------- ### Write Entire Configuration File Content (JavaScript) Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Writes a given string content to the entire configuration file. Returns a boolean indicating success. ```javascript conf.write(content) ``` -------------------------------- ### HTTP Server API Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.zh.md Methods for creating a lightweight HTTP server and registering route handlers. ```APIDOC ## HttpServer ### Description Provides a simple HTTP server for small-scale data transmission. ### Methods - **onGet(path, callback)**: Register GET handler. - **onPut(path, callback)**: Register PUT handler. - **onPost(path, callback)**: Register POST handler. - **onPatch(path, callback)**: Register PATCH handler. - **onDelete(path, callback)**: Register DELETE handler. ### Parameters - **path** (String) - Required - URL path (supports regex). - **callback** (Function) - Required - Callback receiving (HttpRequest, HttpResponse). ``` -------------------------------- ### NbtList - Get List Size Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/NbtAPI/NBTList.md Retrieves the number of elements currently stored in the NbtList. ```APIDOC ## Get List Length ### Description Returns the total number of NBT objects contained within the NbtList. ### Method `list.getSize()` ### Endpoint This is a method called on an existing `NbtList` object. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const size = myList.getSize(); console.log(size); // Output: 2 (if myList has 2 elements) ``` ```lua local size = myList:getSize() print(size) -- Output: 2 (if myList has 2 elements) ``` ### Response #### Success Response (200) - **Integer** - The number of elements in the list. #### Response Example ```json { "size": 2 } ``` ``` -------------------------------- ### Get All Loaded Entities Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Entity.md Retrieves a list of all currently loaded entity objects in the game. ```APIDOC ## GET mc.getAllEntities() ### Description This function returns an array of entity objects, each of which corresponds to a loaded entity. ### Method GET ### Endpoint mc.getAllEntities() ### Response #### Success Response (200) - **Return value** (Array) - A list of all loaded entity objects. ``` -------------------------------- ### system.newProcess Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/SystemCall.md Runs a specified program from a given location. This function works asynchronously. ```APIDOC ## system.newProcess ### Description Runs the specified program located at a given path. This function works asynchronously. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **process** (String) - Required - The path of the program to run, including command line arguments. - **callback** (Function) - Required - The callback function to be invoked with the program's exit code and output. - **timeLimit** (Integer) - Optional - The maximum time limit for the program process to run, in milliseconds. Defaults to -1 (unlimited). ### Callback Function Signature `function(exitcode, output)` - **exitcode** (Integer) - The process exit code. - **output** (String) - The contents of the program's standard output and standard error. ### Return Value - **Return value** (Boolean) - Whether the process was successfully started. ### Request Example ```javascript system.newProcess("/usr/bin/myprogram --option value", function(exitcode, output) { console.log("Process Exit Code:", exitcode); console.log("Process Output:", output); }, 10000); ``` ### Response #### Success Response (Implicit) - **Return value** (Boolean) - Indicates if the process was successfully initiated. #### Response Example ```json true ``` ``` -------------------------------- ### Connect WebSocket Client Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.zh.md Establish a WebSocket connection using the `connect` method with a target URL. Returns a boolean indicating success. ```javascript wsc.connect(target) ``` -------------------------------- ### Get All Items and Clear Container Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Container.zh.md Methods to retrieve all items or clear the entire container. ```APIDOC ## Get All Items and Clear Container ### `ct.getAllItems()` - **Description**: Retrieves a list of all item objects currently in the container. The returned item objects are references. - **Returns**: `Array` - An array containing all item objects in the container. ### `ct.removeAllItems()` - **Description**: Removes all items from the container, effectively emptying it. - **Returns**: `Boolean` - Whether the container was successfully cleared. ``` -------------------------------- ### GET mc.getBlock Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Block.md Retrieves a block object from the game world based on provided coordinates. ```APIDOC ## GET mc.getBlock ### Description Retrieves a block object at the specified position. The block must be in a loaded chunk. ### Method GET ### Endpoint mc.getBlock(pos) or mc.getBlock(x, y, z, dimid) ### Parameters #### Path Parameters - **pos** (IntPos) - Required - The coordinates of the block. - **x** (Integer) - Required - X coordinate. - **y** (Integer) - Required - Y coordinate. - **z** (Integer) - Required - Z coordinate. - **dimid** (Integer) - Required - Dimension ID. ### Response #### Success Response (200) - **Block** (Object) - The generated Block object. Returns Null if acquisition fails. ``` -------------------------------- ### File System Operations in JavaScript Source: https://context7.com/liteldev/legacyscriptengine/llms.txt Demonstrates simple read/write operations, advanced file object handling, and asynchronous file access using the File API. ```javascript // Simple file operations let content = File.readFrom("plugins/MyPlugin/data.txt"); if (content) { log(`File content: ${content}`); } File.writeTo("plugins/MyPlugin/output.txt", "Hello, World!"); File.writeLine("plugins/MyPlugin/log.txt", `[${new Date()}] Server started`); ``` ```javascript // File object for advanced operations let file = new File("plugins/MyPlugin/binary.dat", File.WriteMode, true); file.writeSync("Binary data here"); file.seekTo(0, false); // Move to beginning let data = file.readSync(10); log(`Read: ${data}`); file.close(); ``` ```javascript // Async file operations let asyncFile = new File("plugins/MyPlugin/large.txt", File.ReadMode); asyncFile.readAll((result) => { if (result) { log(`Async read complete, length: ${result.length}`); } }); ``` ```javascript // File properties let f = new File("plugins/MyPlugin/test.txt", File.ReadMode); log(`Path: ${f.path}`); log(`Absolute: ${f.absolutePath}`); log(`Size: ${f.size} bytes`); f.close(); ``` -------------------------------- ### Get All Player Tags Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Retrieves an array containing all string tags currently assigned to the player. ```javascript pl.getAllTags() ``` -------------------------------- ### 创建/打开键值对数据库 Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/DataBase.zh.md 通过指定目录路径初始化 KVDatabase 对象。如果目录不存在,系统将尝试自动创建。 ```JavaScript new KVDatabase(dir) ``` ```Lua KVDatabase(dir) ``` -------------------------------- ### Get Element Data Type Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/NbtAPI/NBTList.md Query the NBT data type of an element at a specific index. ```JavaScript list.getTypeOf(index) ``` -------------------------------- ### Initialize Configuration Item (JavaScript) Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Initializes a configuration item if it doesn't exist, writing the default value. If it exists, it reads and returns the current value. Supports Integer, Float, String, and Boolean types. ```javascript conf.init(section,name,default) ``` -------------------------------- ### Get Entities in a Specified Area Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Entity.md Retrieves a list of entity objects within a specified area. ```APIDOC ## GET mc.getEntities(startPos[,range]) / mc.getEntities(startPos,endPos[,range]) ### Description Retrieves a list of entity objects within a specified area. ### Method GET ### Endpoint mc.getEntities(startPos[,range]) mc.getEntities(startPos,endPos[,range]) ### Parameters #### Path Parameters - **startPos** (IntPos / FloatPos) - Required - The starting position of the search. - **endPos** (IntPos / FloatPos) - Optional - The end position of the search. - **range** (Number) - Optional - The search radius. ### Response #### Success Response (200) - **Return value** (Array) - A list of entity objects within the specified area. ``` -------------------------------- ### JsonConfigFile Methods Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/DataAPI/ConfigFile.md Methods for reading, writing, initializing, and deleting configuration items within a JSON file. ```APIDOC ## Methods for JsonConfigFile ### init(name, default) Initializes a configuration item. If it doesn't exist, it creates it with the default value. - **name** (String) - Required - Configuration item name. - **default** (Any) - Required - The value to initialize with. ### set(name, data) Writes a configuration item to the file. - **name** (String) - Required - Configuration item name. - **data** (Any) - Required - Data to write (Integer, Float, String, Boolean, Array, Object). - **Returns** (Boolean) - Success status. ### get(name, default) Reads a configuration item. - **name** (String) - Required - Configuration item name. - **default** (Any) - Optional - Value to return if read fails. ### delete(name) Deletes a configuration item. - **name** (String) - Required - Configuration item name. - **Returns** (Boolean) - Success status. ``` -------------------------------- ### Get Entities in Area Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Entity.md Retrieves a list of entity objects within a specified coordinate range. ```javascript mc.getEntities(startPos[,range]) mc.getEntities(startPos,endPos[,range]) ``` -------------------------------- ### Create Simple Form Object Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GuiAPI/FormBuilder.md Initializes a blank simple form object. ```javascript mc.newSimpleForm() ``` -------------------------------- ### Get Player Attributes Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Retrieves an array of property objects representing the player's NBT attributes. ```javascript pl.getAttributes() ``` ```json { "Base": 0, "Current": 0, "DefaultMax": 1024, "DefaultMin": -1024, "Max": 1024, "Min": -1024, "Name": "minecraft:luck" } ``` -------------------------------- ### Get Player Abilities Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.md Retrieves an object containing all of the player's abilities, sourced from their NBT data. ```javascript pl.getAbilities() ``` -------------------------------- ### Asynchronously Connect WebSocket Client Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/SystemAPI/Network.zh.md Initiate an asynchronous WebSocket connection with `connectAsync`. Provide the target URL and a callback function that receives a boolean indicating connection success or failure. ```javascript wsc.connectAsync(target,callback) ``` -------------------------------- ### Player Experience Management Source: https://github.com/liteldev/legacyscriptengine/blob/develop/docs/apis/GameAPI/Player.zh.md Methods for getting, setting, adding, and reducing player experience levels and points. ```APIDOC ## pl.reduceLevel(count) ### Description Reduces the player's experience level. ### Parameters - **count** (Integer) - Required - The number of levels to reduce. ### Response - **Boolean** - Returns true if successful. ## pl.getLevel() ### Description Gets the player's current experience level. ### Response - **Integer** - The current experience level. ## pl.setLevel(count) ### Description Sets the player's experience level. ### Parameters - **count** (Integer) - Required - The level to set. ### Response - **Boolean** - Returns true if successful. ## pl.resetLevel() ### Description Resets the player's experience level. ### Response - **Boolean** - Returns true if successful. ## pl.getCurrentExperience() ### Description Gets the player's current experience points. ### Response - **Integer** - The current experience points. ## pl.setCurrentExperience(count) ### Description Sets the player's current experience points. ### Parameters - **count** (Integer) - Required - The experience points to set. ### Response - **Boolean** - Returns true if successful. ## pl.getTotalExperience() ### Description Gets the player's total experience points. ### Response - **Integer** - The total experience points. ## pl.setTotalExperience(count) ### Description Sets the player's total experience points. ### Parameters - **count** (Integer) - Required - The experience points to set. ### Response - **Boolean** - Returns true if successful. ## pl.addExperience(count) ### Description Increases the player's experience points. ### Parameters - **count** (Integer) - Required - The experience points to add. ### Response - **Boolean** - Returns true if successful. ## pl.reduceExperience(count) ### Description Reduces the player's experience points. ### Parameters - **count** (Integer) - Required - The experience points to reduce. ### Response - **Boolean** - Returns true if successful. ## pl.getXpNeededForNextLevel() ### Description Gets the experience points required for the next level, ignoring current experience. ### Response - **Integer** - The required experience points. ```