Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sisilicon
GitHub Repository: sisilicon/worldedit-be
Path: blob/master/src/library/classes/serverBuilder.ts
1784 views
1
import { world, Player, Entity, Dimension, CommandResult } from "@minecraft/server";
2
import { EventEmitter } from "./eventEmitter.js";
3
import { runCommandReturn } from "../@types/classes/ServerBuilder";
4
import { sleep } from "@notbeer-api";
5
import { EventList } from "library/@types/Events.js";
6
7
export class ServerBuilder extends EventEmitter<EventList> {
8
private commandQueue: Promise<runCommandReturn>[] = [];
9
private flushingCommands = false;
10
11
/**
12
* Force shuts down the server
13
* @example ServerBuilder.close()
14
*/
15
close(): void {
16
function crash() {
17
// eslint-disable-next-line no-constant-condition
18
while (true) {
19
crash();
20
}
21
}
22
crash();
23
}
24
25
/**
26
* Run a command in game
27
* @param command The command you want to run
28
* @returns {runCommandReturn}
29
* @example ServerBuilder.runCommand('say Hello World!');
30
*/
31
runCommand(command: string, target?: Dimension | Player | Entity): runCommandReturn {
32
try {
33
const successCount = (target ?? world.getDimension("overworld")).runCommand(command).successCount;
34
return { error: false, successCount };
35
} catch (e) {
36
return { error: true, successCount: 0 };
37
}
38
}
39
40
/**
41
* Queue a command in game
42
* @param command The command you want to run at some point
43
* @returns {Promise<runCommandReturn>}
44
* @example ServerBuilder.queueCommand('say Hello World!');
45
*/
46
queueCommand(command: string, target?: Dimension | Player | Entity): Promise<runCommandReturn> {
47
try {
48
if (this.flushingCommands || this.commandQueue.length > 128) throw "queue";
49
50
const promise = new Promise<CommandResult>((resolve) => {
51
resolve((target ?? world.getDimension("overworld")).runCommand(command));
52
})
53
.then((result) => {
54
return { error: false, ...result };
55
})
56
.catch((result) => {
57
return { error: true, successCount: 0, ...result };
58
})
59
.finally(() => this.commandQueue.splice(this.commandQueue.indexOf(promise), 1));
60
this.commandQueue.push(promise);
61
return promise;
62
} catch (e) {
63
if (typeof e == "string" && e.includes("queue")) {
64
return (async () => {
65
await sleep(1);
66
return await this.queueCommand(command, target);
67
})();
68
} else {
69
return Promise.resolve({ error: true, successCount: 0 });
70
}
71
}
72
}
73
74
/**
75
* Flushes all pending commands in the current tick.
76
* Any attempts at running commands while flushing will be queued.
77
*/
78
async flushCommands() {
79
if (this.commandQueue) return;
80
this.flushingCommands = true;
81
await Promise.all(this.commandQueue);
82
this.flushingCommands = false;
83
}
84
}
85
export const Server = new ServerBuilder();
86
87