@zardoy/flying-squid 0.0.77 → 0.0.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -102,14 +102,22 @@ class MCServer extends events_1.EventEmitter {
102
102
  const oldServer = options.oldServerData;
103
103
  server._server = oldServer?._server ?? (0, minecraft_protocol_1.createServer)({
104
104
  ...options,
105
- beforeLogin(client) {
106
- const existingPlayer = Object.values(server._server.clients)
107
- .find(c => c.username.toLowerCase() === client.username.toLowerCase());
108
- if (existingPlayer) {
109
- client.end('A player with this username is already connected');
110
- return false;
111
- }
112
- },
105
+ });
106
+ server._server.on('connection', (client) => {
107
+ const loginOld = client['_events'].login_start;
108
+ if (typeof loginOld === 'function') {
109
+ client['_events'].login_start = (packet) => {
110
+ const username = packet.username.toLowerCase();
111
+ const existingPlayer = Object.values(server._server.clients)
112
+ .find(c => c.username?.toLowerCase?.() === username);
113
+ if (existingPlayer) {
114
+ client.end('A player with this username is already connected');
115
+ }
116
+ else {
117
+ loginOld(packet);
118
+ }
119
+ };
120
+ }
113
121
  });
114
122
  patchServerSocket(server._server['socketServer'], server);
115
123
  if (oldServer) {
@@ -220,31 +228,99 @@ const patchServerSocket = (socket, server) => {
220
228
  });
221
229
  };
222
230
  function handleHttp(clientSocket, buffer) {
223
- // Create server info response
224
- const response = {
225
- version: {
226
- name: server.mcData.version.minecraftVersion,
227
- protocol: server.mcData.version.version
228
- },
229
- players: {
230
- online: server.players?.length || 0
231
- },
232
- // description: {
233
- // text: server.motd || 'A Minecraft Server'
234
- // },
235
- // favicon: server.favicon || undefined
236
- };
237
- // Send HTTP response
238
- const httpResponse = [
239
- 'HTTP/1.1 200 OK',
240
- 'Content-Type: application/json; charset=utf-8',
241
- 'Connection: close',
242
- 'Access-Control-Allow-Origin: *',
243
- `Content-Length: ${Buffer.byteLength(JSON.stringify(response))}`,
244
- '',
245
- JSON.stringify(response)
246
- ].join('\r\n');
247
- clientSocket.end(httpResponse);
231
+ try {
232
+ const head = buffer.toString();
233
+ const requestLine = head.split('\r\n')[0] || '';
234
+ const [method = 'GET', rawPath = '/'] = requestLine.split(' ');
235
+ const pathOnly = rawPath.split('?')[0];
236
+ // If an endpoint handler exists, delegate
237
+ const handler = server.endpointsHandlers?.[pathOnly];
238
+ if (typeof handler === 'function') {
239
+ // Minimal req/res shims
240
+ const resHeaders = {
241
+ 'Connection': 'close',
242
+ 'Access-Control-Allow-Origin': '*'
243
+ };
244
+ let statusCode = 200;
245
+ const res = {
246
+ writeHead: (code, headers) => {
247
+ statusCode = code;
248
+ if (headers)
249
+ Object.assign(resHeaders, headers);
250
+ },
251
+ setHeader: (name, value) => {
252
+ resHeaders[name] = value;
253
+ },
254
+ end: (body) => {
255
+ const payload = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body ?? '');
256
+ if (resHeaders['Content-Length'] === undefined) {
257
+ resHeaders['Content-Length'] = String(Buffer.byteLength(payload));
258
+ }
259
+ const lines = [
260
+ `HTTP/1.1 ${statusCode} ${statusCode === 200 ? 'OK' : ''}`,
261
+ ...Object.entries(resHeaders).map(([k, v]) => `${k}: ${v}`),
262
+ '',
263
+ ''
264
+ ];
265
+ clientSocket.write(lines.join('\r\n'));
266
+ clientSocket.end(payload);
267
+ }
268
+ };
269
+ const req = { method, url: rawPath, headers: {} };
270
+ try {
271
+ handler(req, res);
272
+ }
273
+ catch (e) {
274
+ const payload = 'Internal Server Error\n';
275
+ const response = [
276
+ 'HTTP/1.1 500 Internal Server Error',
277
+ 'Content-Type: text/plain; charset=utf-8',
278
+ 'Connection: close',
279
+ 'Access-Control-Allow-Origin: *',
280
+ `Content-Length: ${Buffer.byteLength(payload)}`,
281
+ '',
282
+ payload
283
+ ].join('\r\n');
284
+ clientSocket.end(response);
285
+ }
286
+ return;
287
+ }
288
+ // Default JSON status response
289
+ const response = {
290
+ version: {
291
+ name: server.mcData.version.minecraftVersion,
292
+ protocol: server.mcData.version.version
293
+ },
294
+ players: {
295
+ online: server.players?.length || 0
296
+ },
297
+ description: server._server.motdMsg ?? { text: server._server.motd },
298
+ favicon: server._server.favicon ?? null,
299
+ };
300
+ const httpResponse = [
301
+ 'HTTP/1.1 200 OK',
302
+ 'Content-Type: application/json; charset=utf-8',
303
+ 'Connection: close',
304
+ 'Access-Control-Allow-Origin: *',
305
+ `Content-Length: ${Buffer.byteLength(JSON.stringify(response))}`,
306
+ '',
307
+ JSON.stringify(response)
308
+ ].join('\r\n');
309
+ clientSocket.end(httpResponse);
310
+ }
311
+ catch (e) {
312
+ const payload = 'Bad Request\n';
313
+ const httpResponse = [
314
+ 'HTTP/1.1 400 Bad Request',
315
+ 'Content-Type: text/plain; charset=utf-8',
316
+ 'Connection: close',
317
+ 'Access-Control-Allow-Origin: *',
318
+ `Content-Length: ${Buffer.byteLength(payload)}`,
319
+ '',
320
+ payload
321
+ ].join('\r\n');
322
+ clientSocket.end(httpResponse);
323
+ }
248
324
  }
249
325
  return socket;
250
326
  };
@@ -0,0 +1,34 @@
1
+ export interface PlayerStatsStore {
2
+ stats: {
3
+ totalPlayedMs: number;
4
+ totalPlacedBlocks: number;
5
+ longestSessionMs: number;
6
+ };
7
+ meta?: {
8
+ firstLoginMs?: number;
9
+ lastLoginMs?: number;
10
+ };
11
+ }
12
+ export declare const server: (serv: Server, options: Options) => void;
13
+ export declare const player: (player: Player, serv: Server, options: Options) => void;
14
+ declare global {
15
+ interface Server {
16
+ playerStores: Map<string, PlayerStatsStore>;
17
+ totalJoinsOnStart: number;
18
+ getPlayerData: (uuid: string) => PlayerStatsStore;
19
+ updatePlayerData: (uuid: string, updater: Partial<PlayerStatsStore> | ((data: PlayerStatsStore) => void)) => void;
20
+ getAllPlayerData: () => Array<{
21
+ uuid: string;
22
+ data: PlayerStatsStore;
23
+ }>;
24
+ loadPlayerDataFromDisk: (uuid: string) => Promise<boolean>;
25
+ savePlayerDataToDisk: (uuid: string) => Promise<void>;
26
+ saveAllPlayerDataToDisk: () => Promise<void>;
27
+ }
28
+ interface Player {
29
+ db: PlayerStatsStore;
30
+ dataLoaded: boolean;
31
+ isFresh: boolean;
32
+ _sessionStartMs: number;
33
+ }
34
+ }
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.player = exports.server = void 0;
7
+ const fs_1 = require("fs");
8
+ const path_1 = __importDefault(require("path"));
9
+ const DEFAULT_PLAYER_STORE = {
10
+ stats: {
11
+ totalPlayedMs: 0,
12
+ totalPlacedBlocks: 0,
13
+ longestSessionMs: 0,
14
+ }
15
+ };
16
+ const server = function (serv, options) {
17
+ // In-memory stores for player data and a flag for dirty tracking
18
+ serv.playerStores ??= new Map();
19
+ const dirtyStores = new Set();
20
+ // Compute total joins from .dat files at startup
21
+ serv.totalJoinsOnStart = 0;
22
+ (async () => {
23
+ try {
24
+ if (options.worldFolder) {
25
+ const dir = path_1.default.resolve(String(options.worldFolder), 'playerdata');
26
+ const entries = await fs_1.promises.readdir(dir).catch(() => []);
27
+ serv.totalJoinsOnStart = entries.filter((f) => f.toLowerCase().endsWith('.dat')).length;
28
+ }
29
+ }
30
+ catch { /* ignore */ }
31
+ })();
32
+ // API: get player store
33
+ serv.getPlayerData = (uuid) => {
34
+ let store = serv.playerStores.get(uuid);
35
+ if (!store) {
36
+ const newStore = JSON.parse(JSON.stringify(DEFAULT_PLAYER_STORE));
37
+ serv.playerStores.set(uuid, newStore);
38
+ store = newStore;
39
+ dirtyStores.add(uuid);
40
+ }
41
+ return store;
42
+ };
43
+ // API: update store via partial or updater function
44
+ serv.updatePlayerData = (uuid, updater) => {
45
+ const store = serv.getPlayerData(uuid);
46
+ if (typeof updater === 'function') {
47
+ updater(store);
48
+ }
49
+ else {
50
+ Object.assign(store, updater);
51
+ }
52
+ dirtyStores.add(uuid);
53
+ };
54
+ serv.getAllPlayerData = () => {
55
+ return Array.from(serv.playerStores.entries()).map(([uuid, data]) => ({ uuid, data }));
56
+ };
57
+ // Load and save helpers
58
+ const getJsonPath = (uuid) => options.worldFolder
59
+ ? path_1.default.resolve(String(options.worldFolder), 'playerdata', `${uuid}.json`)
60
+ : undefined;
61
+ serv.loadPlayerDataFromDisk = async (uuid) => {
62
+ const jsonPath = getJsonPath(uuid);
63
+ if (!jsonPath)
64
+ return false;
65
+ try {
66
+ const buf = await fs_1.promises.readFile(jsonPath);
67
+ const parsed = JSON.parse(buf.toString('utf8'));
68
+ // Ensure defaults
69
+ const safe = {
70
+ ...parsed,
71
+ stats: { ...DEFAULT_PLAYER_STORE.stats, ...(parsed?.stats ?? {}) },
72
+ };
73
+ serv.playerStores.set(uuid, safe);
74
+ return false;
75
+ }
76
+ catch (e) {
77
+ // initialize default if file does not exist or invalid
78
+ serv.playerStores.set(uuid, JSON.parse(JSON.stringify(DEFAULT_PLAYER_STORE)));
79
+ dirtyStores.add(uuid);
80
+ return true;
81
+ }
82
+ };
83
+ serv.savePlayerDataToDisk = async (uuid) => {
84
+ const jsonPath = getJsonPath(uuid);
85
+ if (!jsonPath)
86
+ return;
87
+ try {
88
+ await fs_1.promises.mkdir(path_1.default.dirname(jsonPath), { recursive: true });
89
+ const data = serv.getPlayerData(uuid);
90
+ await fs_1.promises.writeFile(jsonPath, JSON.stringify(data));
91
+ dirtyStores.delete(uuid);
92
+ }
93
+ catch {
94
+ // ignore write errors for now
95
+ }
96
+ };
97
+ serv.saveAllPlayerDataToDisk = async () => {
98
+ const uuids = Array.from(dirtyStores.values());
99
+ await Promise.all(uuids.map((uuid) => serv.savePlayerDataToDisk(uuid)));
100
+ };
101
+ // Flush periodically and on shutdown
102
+ const interval = serv.setInterval(async () => {
103
+ await serv.saveAllPlayerDataToDisk();
104
+ }, 30_000);
105
+ serv.cleanupFunctions.push(() => clearInterval(interval));
106
+ };
107
+ exports.server = server;
108
+ const player = function (player, serv, options) {
109
+ // Load the JSON store once base player data is ready
110
+ player.on('dataLoaded', async () => {
111
+ const isFresh = await serv.loadPlayerDataFromDisk(player.uuid);
112
+ player.isFresh = isFresh;
113
+ player.dataLoaded = true;
114
+ player.db = serv.getPlayerData(player.uuid);
115
+ player._sessionStartMs = Date.now();
116
+ player.emit('databaseLoaded');
117
+ // Track first and last login times and username
118
+ const now = Date.now();
119
+ player.db.meta ??= {};
120
+ if (!player.db.meta.firstLoginMs)
121
+ player.db.meta.firstLoginMs = now;
122
+ player.db.meta.lastLoginMs = now;
123
+ await serv.savePlayerDataToDisk(player.uuid);
124
+ });
125
+ // Count placed blocks attempts
126
+ let lastPlace = 0;
127
+ player.on('blockPlaced', () => {
128
+ if (Date.now() - lastPlace < 5)
129
+ return;
130
+ lastPlace = Date.now();
131
+ const store = serv.getPlayerData(player.uuid);
132
+ store.stats.totalPlacedBlocks += 1;
133
+ serv.updatePlayerData(player.uuid, store);
134
+ });
135
+ // On disconnect, update played time and longest session
136
+ player.on('disconnected', async () => {
137
+ try {
138
+ const start = player._sessionStartMs ?? Date.now();
139
+ const sessionMs = Math.max(0, Date.now() - start);
140
+ const store = serv.getPlayerData(player.uuid);
141
+ store.stats.totalPlayedMs += sessionMs;
142
+ if (sessionMs > store.stats.longestSessionMs)
143
+ store.stats.longestSessionMs = sessionMs;
144
+ await serv.savePlayerDataToDisk(player.uuid);
145
+ }
146
+ catch { /* ignore */ }
147
+ });
148
+ };
149
+ exports.player = player;
@@ -0,0 +1,13 @@
1
+ import { IncomingMessage, ServerResponse } from 'http';
2
+ export declare const server: (serv: Server, options: Options) => void;
3
+ declare global {
4
+ interface Options {
5
+ debugEndpoints?: boolean;
6
+ }
7
+ interface Server {
8
+ _globalHttpHandler: any;
9
+ endpointsHandlers: {
10
+ [path: string]: (req: IncomingMessage, res: ServerResponse) => void;
11
+ };
12
+ }
13
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.server = void 0;
4
+ const server = function (serv, options) {
5
+ serv.endpointsHandlers ??= {};
6
+ if (options.debugEndpoints) {
7
+ serv.endpointsHandlers['/log'] = (_req, res) => {
8
+ const lines = serv._logBuffer?.join('\n') ?? 'No logs yet\n';
9
+ res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
10
+ res.end(lines);
11
+ };
12
+ serv.endpointsHandlers['/errors'] = (_req, res) => {
13
+ const lines = serv._errorBuffer?.join('\n') ?? 'No errors yet\n';
14
+ res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
15
+ res.end(lines);
16
+ };
17
+ }
18
+ };
19
+ exports.server = server;
@@ -15,6 +15,7 @@ module.exports = {
15
15
  'communication': require('./communication'),
16
16
  'crafting': require('./crafting'),
17
17
  'customBlockBreakTime': require('./customBlockBreakTime'),
18
+ 'database': require('./database'),
18
19
  'daycycle': require('./daycycle'),
19
20
  'digging': require('./digging'),
20
21
  'dimensionCodec': require('./dimensionCodec'),
@@ -27,11 +28,13 @@ module.exports = {
27
28
  'gamerules': require('./gamerules'),
28
29
  'header': require('./header'),
29
30
  'health': require('./health'),
31
+ 'http': require('./http'),
30
32
  'index': require('./index'),
31
33
  'inventory': require('./inventory'),
32
34
  'log': require('./log'),
33
35
  'login': require('./login'),
34
36
  'logout': require('./logout'),
37
+ 'maps': require('./maps'),
35
38
  'moderation': require('./moderation'),
36
39
  'particle': require('./particle'),
37
40
  'physics': require('./physics'),
@@ -43,6 +46,7 @@ module.exports = {
43
46
  'redstone': require('./redstone'),
44
47
  'resourcePack': require('./resourcePack'),
45
48
  'respawn': require('./respawn'),
49
+ 'safeZones': require('./safeZones'),
46
50
  'scoreboard': require('./scoreboard'),
47
51
  'settings': require('./settings'),
48
52
  'signs': require('./signs'),
@@ -69,6 +69,10 @@ if (isInNode) {
69
69
  }
70
70
  const server = function (serv, settings) {
71
71
  _servers.push(serv);
72
+ // Keep a rolling buffer of recent logs and errors for debug HTTP endpoints
73
+ serv._logBuffer ??= [];
74
+ serv._errorBuffer ??= [];
75
+ const MAX_BUFFER_LINES = 1500;
72
76
  serv.on('error', (error, pluginName) => {
73
77
  serv.err('Server: ' + error.stack + (pluginName ? ' (plugin: ' + pluginName + ')' : ''));
74
78
  });
@@ -99,13 +103,29 @@ const server = function (serv, settings) {
99
103
  });
100
104
  };
101
105
  serv.info = message => {
102
- serv.log('[' + chalk_1.default.green('INFO') + ']: ' + message);
106
+ const line = '[' + chalk_1.default.green('INFO') + ']: ' + message;
107
+ serv._logBuffer.push(line.replace(/\x1B\[[0-9;]*m/g, ''));
108
+ if (serv._logBuffer.length > MAX_BUFFER_LINES)
109
+ serv._logBuffer.shift();
110
+ serv.log(line);
103
111
  };
104
112
  serv.err = message => {
105
- serv.log('[' + chalk_1.default.red('ERROR') + ']: ' + message);
113
+ const line = '[' + chalk_1.default.red('ERROR') + ']: ' + message;
114
+ const plain = line.replace(/\x1B\[[0-9;]*m/g, '');
115
+ serv._logBuffer.push(plain);
116
+ serv._errorBuffer.push(plain);
117
+ if (serv._logBuffer.length > MAX_BUFFER_LINES)
118
+ serv._logBuffer.shift();
119
+ if (serv._errorBuffer.length > MAX_BUFFER_LINES)
120
+ serv._errorBuffer.shift();
121
+ serv.log(line);
106
122
  };
107
123
  serv.warn = message => {
108
- serv.log('[' + chalk_1.default.yellow('WARN') + ']: ' + message);
124
+ const line = '[' + chalk_1.default.yellow('WARN') + ']: ' + message;
125
+ serv._logBuffer.push(line.replace(/\x1B\[[0-9;]*m/g, ''));
126
+ if (serv._logBuffer.length > MAX_BUFFER_LINES)
127
+ serv._logBuffer.shift();
128
+ serv.log(line);
109
129
  };
110
130
  if (isInNode) {
111
131
  console.log = (function () {
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Convert PNG image file to map buffer format
3
+ * @param {string} imagePath - Path to the PNG file
4
+ * @returns {Promise<Buffer>} - Buffer containing color indices for map data
5
+ */
6
+ export declare function imageToMap(imagePath: any): Promise<any>;
7
+ /**
8
+ * Clear the image cache
9
+ */
10
+ export declare function clearImageCache(): void;
11
+ /**
12
+ * Get cache statistics
13
+ * @returns {object}
14
+ */
15
+ export declare function getCacheStats(): {
16
+ size: number;
17
+ paths: any[];
18
+ };
@@ -0,0 +1,370 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.imageToMap = imageToMap;
4
+ exports.clearImageCache = clearImageCache;
5
+ exports.getCacheStats = getCacheStats;
6
+ const colorsData = getColors1_16();
7
+ // Create reverse lookup map from hex colors to indices and RGB values for distance calculation
8
+ const colorLookup = new Map();
9
+ const colorIndices = [];
10
+ for (const [index, hexColor] of Object.entries(colorsData)) {
11
+ if (hexColor === "#00000000")
12
+ continue; // Skip transparent colors
13
+ const r = parseInt(hexColor.slice(3, 5), 16);
14
+ const g = parseInt(hexColor.slice(5, 7), 16);
15
+ const b = parseInt(hexColor.slice(7, 9), 16);
16
+ colorLookup.set(hexColor, parseInt(index));
17
+ colorIndices.push({
18
+ index: parseInt(index),
19
+ r,
20
+ g,
21
+ b,
22
+ hex: hexColor
23
+ });
24
+ }
25
+ // Cache for processed images
26
+ const imageCache = new Map();
27
+ /**
28
+ * Calculate color distance using Euclidean distance in RGB space
29
+ * @param {number} r1
30
+ * @param {number} g1
31
+ * @param {number} b1
32
+ * @param {number} r2
33
+ * @param {number} g2
34
+ * @param {number} b2
35
+ * @returns {number}
36
+ */
37
+ function colorDistance(r1, g1, b1, r2, g2, b2) {
38
+ return Math.sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2);
39
+ }
40
+ /**
41
+ * Find the closest color index for given RGB values
42
+ * @param {number} r
43
+ * @param {number} g
44
+ * @param {number} b
45
+ * @returns {number}
46
+ */
47
+ function findClosestColorIndex(r, g, b) {
48
+ let minDistance = Infinity;
49
+ let closestIndex = 0;
50
+ for (const color of colorIndices) {
51
+ const distance = colorDistance(r, g, b, color.r, color.g, color.b);
52
+ if (distance < minDistance) {
53
+ minDistance = distance;
54
+ closestIndex = color.index;
55
+ }
56
+ }
57
+ return closestIndex;
58
+ }
59
+ /**
60
+ * Convert PNG image file to map buffer format
61
+ * @param {string} imagePath - Path to the PNG file
62
+ * @returns {Promise<Buffer>} - Buffer containing color indices for map data
63
+ */
64
+ async function imageToMap(imagePath) {
65
+ // Check cache first
66
+ if (imageCache.has(imagePath)) {
67
+ return imageCache.get(imagePath);
68
+ }
69
+ try {
70
+ // Read and process the image
71
+ const { data, info } = await sharp(imagePath)
72
+ .resize(128, 128, { fit: 'fill' }) // Ensure 128x128 size
73
+ .raw()
74
+ .toBuffer({ resolveWithObject: true });
75
+ // Ensure we have the expected format
76
+ if (info.width !== 128 || info.height !== 128) {
77
+ throw new Error(`Image must be 128x128 pixels, got ${info.width}x${info.height}`);
78
+ }
79
+ const channels = info.channels;
80
+ const mapData = Buffer.alloc(128 * 128);
81
+ // Process each pixel
82
+ for (let i = 0; i < 128 * 128; i++) {
83
+ const pixelOffset = i * channels;
84
+ const r = data[pixelOffset];
85
+ const g = data[pixelOffset + 1];
86
+ const b = data[pixelOffset + 2];
87
+ // Handle transparency - if alpha is low, use index 0 (transparent)
88
+ if (channels >= 4 && data[pixelOffset + 3] < 128) {
89
+ mapData[i] = 0;
90
+ }
91
+ else {
92
+ mapData[i] = findClosestColorIndex(r, g, b);
93
+ }
94
+ }
95
+ // Cache the result
96
+ imageCache.set(imagePath, mapData);
97
+ return mapData;
98
+ }
99
+ catch (error) {
100
+ throw new Error(`Failed to process image ${imagePath}: ${error.message}`);
101
+ }
102
+ }
103
+ /**
104
+ * Clear the image cache
105
+ */
106
+ function clearImageCache() {
107
+ imageCache.clear();
108
+ }
109
+ /**
110
+ * Get cache statistics
111
+ * @returns {object}
112
+ */
113
+ function getCacheStats() {
114
+ return {
115
+ size: imageCache.size,
116
+ paths: Array.from(imageCache.keys())
117
+ };
118
+ }
119
+ function getColors1_16() {
120
+ return {
121
+ "0": "#00000000",
122
+ "1": "#00000000",
123
+ "2": "#00000000",
124
+ "3": "#00000000",
125
+ "4": "#FF597d27",
126
+ "5": "#FF6d9930",
127
+ "6": "#FF7fb238",
128
+ "7": "#FF435e1d",
129
+ "8": "#FFaea473",
130
+ "9": "#FFd5c98c",
131
+ "10": "#FFf7e9a3",
132
+ "11": "#FF827b56",
133
+ "12": "#FF8c8c8c",
134
+ "13": "#FFababab",
135
+ "14": "#FFc7c7c7",
136
+ "15": "#FF696969",
137
+ "16": "#FFb40000",
138
+ "17": "#FFdc0000",
139
+ "18": "#FFff0000",
140
+ "19": "#FF870000",
141
+ "20": "#FF7070b4",
142
+ "21": "#FF8a8adc",
143
+ "22": "#FFa0a0ff",
144
+ "23": "#FF545487",
145
+ "24": "#FF757575",
146
+ "25": "#FF909090",
147
+ "26": "#FFa7a7a7",
148
+ "27": "#FF585858",
149
+ "28": "#FF005700",
150
+ "29": "#FF006a00",
151
+ "30": "#FF007c00",
152
+ "31": "#FF004100",
153
+ "32": "#FFb4b4b4",
154
+ "33": "#FFdcdcdc",
155
+ "34": "#FFffffff",
156
+ "35": "#FF878787",
157
+ "36": "#FF737681",
158
+ "37": "#FF8d909e",
159
+ "38": "#FFa4a8b8",
160
+ "39": "#FF565861",
161
+ "40": "#FF6a4c36",
162
+ "41": "#FF825e42",
163
+ "42": "#FF976d4d",
164
+ "43": "#FF4f3928",
165
+ "44": "#FF4f4f4f",
166
+ "45": "#FF606060",
167
+ "46": "#FF707070",
168
+ "47": "#FF3b3b3b",
169
+ "48": "#FF2d2db4",
170
+ "49": "#FF3737dc",
171
+ "50": "#FF4040ff",
172
+ "51": "#FF212187",
173
+ "52": "#FF645432",
174
+ "53": "#FF7b663e",
175
+ "54": "#FF8f7748",
176
+ "55": "#FF4b3f26",
177
+ "56": "#FFb4b1ac",
178
+ "57": "#FFdcd9d3",
179
+ "58": "#FFfffcf5",
180
+ "59": "#FF878581",
181
+ "60": "#FF985924",
182
+ "61": "#FFba6d2c",
183
+ "62": "#FFd87f33",
184
+ "63": "#FF72431b",
185
+ "64": "#FF7d3598",
186
+ "65": "#FF9941ba",
187
+ "66": "#FFb24cd8",
188
+ "67": "#FF5e2872",
189
+ "68": "#FF486c98",
190
+ "69": "#FF5884ba",
191
+ "70": "#FF6699d8",
192
+ "71": "#FF365172",
193
+ "72": "#FFa1a124",
194
+ "73": "#FFc5c52c",
195
+ "74": "#FFe5e533",
196
+ "75": "#FF79791b",
197
+ "76": "#FF599011",
198
+ "77": "#FF6db015",
199
+ "78": "#FF7fcc19",
200
+ "79": "#FF436c0d",
201
+ "80": "#FFaa5974",
202
+ "81": "#FFd06d8e",
203
+ "82": "#FFf27fa5",
204
+ "83": "#FF804357",
205
+ "84": "#FF353535",
206
+ "85": "#FF414141",
207
+ "86": "#FF4c4c4c",
208
+ "87": "#FF282828",
209
+ "88": "#FF6c6c6c",
210
+ "89": "#FF848484",
211
+ "90": "#FF999999",
212
+ "91": "#FF515151",
213
+ "92": "#FF35596c",
214
+ "93": "#FF416d84",
215
+ "94": "#FF4c7f99",
216
+ "95": "#FF284351",
217
+ "96": "#FF592c7d",
218
+ "97": "#FF6d3699",
219
+ "98": "#FF7f3fb2",
220
+ "99": "#FF43215e",
221
+ "100": "#FF24357d",
222
+ "101": "#FF2c4199",
223
+ "102": "#FF334cb2",
224
+ "103": "#FF1b285e",
225
+ "104": "#FF483524",
226
+ "105": "#FF58412c",
227
+ "106": "#FF664c33",
228
+ "107": "#FF36281b",
229
+ "108": "#FF485924",
230
+ "109": "#FF586d2c",
231
+ "110": "#FF667f33",
232
+ "111": "#FF36431b",
233
+ "112": "#FF6c2424",
234
+ "113": "#FF842c2c",
235
+ "114": "#FF993333",
236
+ "115": "#FF511b1b",
237
+ "116": "#FF111111",
238
+ "117": "#FF151515",
239
+ "118": "#FF191919",
240
+ "119": "#FF0d0d0d",
241
+ "120": "#FFb0a836",
242
+ "121": "#FFd7cd42",
243
+ "122": "#FFfaee4d",
244
+ "123": "#FF847e28",
245
+ "124": "#FF409a96",
246
+ "125": "#FF4fbcb7",
247
+ "126": "#FF5cdbd5",
248
+ "127": "#FF307370",
249
+ "128": "#FF345ab4",
250
+ "129": "#FF3f6edc",
251
+ "130": "#FF4a80ff",
252
+ "131": "#FF274387",
253
+ "132": "#FF009928",
254
+ "133": "#FF00bb32",
255
+ "134": "#FF00d93a",
256
+ "135": "#FF00721e",
257
+ "136": "#FF5b3c22",
258
+ "137": "#FF6f4a2a",
259
+ "138": "#FF815631",
260
+ "139": "#FF442d19",
261
+ "140": "#FF4f0100",
262
+ "141": "#FF600100",
263
+ "142": "#FF700200",
264
+ "143": "#FF3b0100",
265
+ "144": "#FF937c71",
266
+ "145": "#FFb4988a",
267
+ "146": "#FFd1b1a1",
268
+ "147": "#FF6e5d55",
269
+ "148": "#FF703919",
270
+ "149": "#FF89461f",
271
+ "150": "#FF9f5224",
272
+ "151": "#FF542b13",
273
+ "152": "#FF693d4c",
274
+ "153": "#FF804b5d",
275
+ "154": "#FF95576c",
276
+ "155": "#FF4e2e39",
277
+ "156": "#FF4f4c61",
278
+ "157": "#FF605d77",
279
+ "158": "#FF706c8a",
280
+ "159": "#FF3b3949",
281
+ "160": "#FF835d19",
282
+ "161": "#FFa0721f",
283
+ "162": "#FFba8524",
284
+ "163": "#FF624613",
285
+ "164": "#FF485225",
286
+ "165": "#FF58642d",
287
+ "166": "#FF677535",
288
+ "167": "#FF363d1c",
289
+ "168": "#FF703637",
290
+ "169": "#FF8a4243",
291
+ "170": "#FFa04d4e",
292
+ "171": "#FF542829",
293
+ "172": "#FF281c18",
294
+ "173": "#FF31231e",
295
+ "174": "#FF392923",
296
+ "175": "#FF1e1512",
297
+ "176": "#FF5f4b45",
298
+ "177": "#FF745c54",
299
+ "178": "#FF876b62",
300
+ "179": "#FF473833",
301
+ "180": "#FF3d4040",
302
+ "181": "#FF4b4f4f",
303
+ "182": "#FF575c5c",
304
+ "183": "#FF2e3030",
305
+ "184": "#FF56333e",
306
+ "185": "#FF693e4b",
307
+ "186": "#FF7a4958",
308
+ "187": "#FF40262e",
309
+ "188": "#FF352b40",
310
+ "189": "#FF41354f",
311
+ "190": "#FF4c3e5c",
312
+ "191": "#FF282030",
313
+ "192": "#FF352318",
314
+ "193": "#FF412b1e",
315
+ "194": "#FF4c3223",
316
+ "195": "#FF281a12",
317
+ "196": "#FF35391d",
318
+ "197": "#FF414624",
319
+ "198": "#FF4c522a",
320
+ "199": "#FF282b16",
321
+ "200": "#FF642a20",
322
+ "201": "#FF7a3327",
323
+ "202": "#FF8e3c2e",
324
+ "203": "#FF4b1f18",
325
+ "204": "#FF1a0f0b",
326
+ "205": "#FF1f120d",
327
+ "206": "#FF251610",
328
+ "207": "#FF130b08",
329
+ "208": "#FF852122",
330
+ "209": "#FFa3292a",
331
+ "210": "#FFbd3031",
332
+ "211": "#FF641919",
333
+ "212": "#FF682c44",
334
+ "213": "#FF7f3653",
335
+ "214": "#FF943f61",
336
+ "215": "#FF4e2133",
337
+ "216": "#FF401114",
338
+ "217": "#FF4f1519",
339
+ "218": "#FF5c191d",
340
+ "219": "#FF300d0f",
341
+ "220": "#FF0f585e",
342
+ "221": "#FF126c73",
343
+ "222": "#FF167e86",
344
+ "223": "#FF0b4246",
345
+ "224": "#FF286462",
346
+ "225": "#FF327a78",
347
+ "226": "#FF3a8e8c",
348
+ "227": "#FF1e4b4a",
349
+ "228": "#FF3c1f2b",
350
+ "229": "#FF4a2535",
351
+ "230": "#FF562c3e",
352
+ "231": "#FF2d1720",
353
+ "232": "#FF0e7f5d",
354
+ "233": "#FF119b72",
355
+ "234": "#FF14b485",
356
+ "235": "#FF0a5f46",
357
+ "236": "#FF464646",
358
+ "237": "#FF565656",
359
+ "238": "#FF646464",
360
+ "239": "#FF343434",
361
+ "240": "#FF987b67",
362
+ "241": "#FFba967e",
363
+ "242": "#FFd8af93",
364
+ "243": "#FF725c4d",
365
+ "244": "#FF597569",
366
+ "245": "#FF6d9081",
367
+ "246": "#FF7fa796",
368
+ "247": "#FF43584f"
369
+ };
370
+ }
@@ -195,6 +195,7 @@ const player = function (player, serv, { version }) {
195
195
  });
196
196
  if (!blocks[id])
197
197
  return;
198
+ player.emit('blockPlaced', blocks[id]);
198
199
  const sound = 'dig.' + (materialToSound[blocks[id].material ?? ''] || 'stone');
199
200
  serv.playSound(sound, player.world, placedPosition.offset(0.5, 0.5, 0.5), {
200
201
  pitch: 0.8
@@ -0,0 +1,14 @@
1
+ import { Vec3 } from 'vec3';
2
+ export declare const server: (serv: Server) => void;
3
+ export declare const player: (player: Player, serv: Server) => void;
4
+ export type AABB = {
5
+ min: Vec3;
6
+ max: Vec3;
7
+ };
8
+ declare global {
9
+ interface Server {
10
+ safeZones: AABB[];
11
+ resetSafeZones: () => void;
12
+ addSafeZones: (x1: number, y1: number, z1: number, x2: number, y2: number, z2: number) => void;
13
+ }
14
+ }
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.player = exports.server = void 0;
4
+ const vec3_1 = require("vec3");
5
+ // Module to make positions safe to move to.
6
+ // If a client sends a position outside by more than threshold, ignore and teleport back inside.
7
+ const THRESHOLD = 0.5;
8
+ const server = (serv) => {
9
+ serv.safeZones ??= [];
10
+ serv.resetSafeZones = () => {
11
+ serv.safeZones = [];
12
+ };
13
+ serv.addSafeZones = (x1, y1, z1, x2, y2, z2) => {
14
+ const min = new vec3_1.Vec3(Math.min(x1, x2), Math.min(y1, y2), Math.min(z1, z2));
15
+ const max = new vec3_1.Vec3(Math.max(x1, x2), Math.max(y1, y2), Math.max(z1, z2));
16
+ serv.safeZones.push({ min, max });
17
+ };
18
+ };
19
+ exports.server = server;
20
+ const player = (player, serv) => {
21
+ // Enforce safe areas on client-provided movement
22
+ player.on('move_cancel', ({ position, onGround, teleport }, cancel) => {
23
+ // Allow server teleports/moves to pass through
24
+ if (teleport)
25
+ return;
26
+ const zones = serv.safeZones ?? [];
27
+ if (zones.length === 0)
28
+ return;
29
+ // Determine the reference area: prefer the box containing the player's current position
30
+ let zone = zones.find(box => isInsideStrict(player.position, box));
31
+ if (!zone) {
32
+ // Fallback: choose closest box to current position
33
+ let best;
34
+ for (const box of zones) {
35
+ const d = distanceToAABB(player.position, box);
36
+ if (!best || d < best.dist)
37
+ best = { box, dist: d };
38
+ }
39
+ zone = best?.box;
40
+ if (!zone)
41
+ return;
42
+ }
43
+ // If new position is within expanded bounds (threshold), allow it
44
+ if (isInsideExpanded(position, zone, THRESHOLD))
45
+ return;
46
+ // Otherwise, clamp back inside from direction of attempted position
47
+ const corrected = clampToAABBFromDirection(position, zone);
48
+ // Prevent default cancel handling and perform corrective teleport ourselves
49
+ cancel(false);
50
+ player.teleport(corrected);
51
+ });
52
+ };
53
+ exports.player = player;
54
+ function isInsideStrict(pos, box) {
55
+ return pos.x >= box.min.x && pos.x <= box.max.x &&
56
+ pos.y >= box.min.y && pos.y <= box.max.y &&
57
+ pos.z >= box.min.z && pos.z <= box.max.z;
58
+ }
59
+ function isInsideExpanded(pos, box, threshold) {
60
+ return pos.x >= (box.min.x - threshold) && pos.x <= (box.max.x + threshold) &&
61
+ pos.y >= (box.min.y - threshold) && pos.y <= (box.max.y + threshold) &&
62
+ pos.z >= (box.min.z - threshold) && pos.z <= (box.max.z + threshold);
63
+ }
64
+ function clampToAABBFromDirection(pos, box) {
65
+ const epsilon = 0.01;
66
+ let x = pos.x;
67
+ let y = pos.y;
68
+ let z = pos.z;
69
+ if (pos.x < box.min.x - THRESHOLD)
70
+ x = box.min.x + epsilon;
71
+ else if (pos.x > box.max.x + THRESHOLD)
72
+ x = box.max.x - epsilon;
73
+ else
74
+ x = clamp(pos.x, box.min.x + epsilon, box.max.x - epsilon);
75
+ if (pos.y < box.min.y - THRESHOLD)
76
+ y = box.min.y + epsilon;
77
+ else if (pos.y > box.max.y + THRESHOLD)
78
+ y = box.max.y - epsilon;
79
+ else
80
+ y = clamp(pos.y, box.min.y + epsilon, box.max.y - epsilon);
81
+ if (pos.z < box.min.z - THRESHOLD)
82
+ z = box.min.z + epsilon;
83
+ else if (pos.z > box.max.z + THRESHOLD)
84
+ z = box.max.z - epsilon;
85
+ else
86
+ z = clamp(pos.z, box.min.z + epsilon, box.max.z - epsilon);
87
+ return new vec3_1.Vec3(x, y, z);
88
+ }
89
+ function clamp(v, min, max) {
90
+ if (min > max)
91
+ return v; // degenerate box; shouldn't happen
92
+ return Math.max(min, Math.min(max, v));
93
+ }
94
+ function distanceToAABB(p, box) {
95
+ // Squared distance from point to AABB
96
+ const dx = dist1D(p.x, box.min.x, box.max.x);
97
+ const dy = dist1D(p.y, box.min.y, box.max.y);
98
+ const dz = dist1D(p.z, box.min.z, box.max.z);
99
+ return dx * dx + dy * dy + dz * dz;
100
+ }
101
+ function dist1D(v, min, max) {
102
+ if (v < min)
103
+ return min - v;
104
+ if (v > max)
105
+ return v - max;
106
+ return 0;
107
+ }
@@ -14,7 +14,7 @@ declare global {
14
14
  objectives: Record<string, Objective>;
15
15
  sidebarObjectives: Record<string, boolean>;
16
16
  createSidebarScoreboard: (name: string, displayText: string) => Objective;
17
- updateScoreboard: (objective: Objective, lines: ScoreboardLine[]) => void;
17
+ updateScoreboard: (objective: Objective, lines: ScoreboardLine[] | string[]) => void;
18
18
  displayScoreboard: (objective: Objective) => void;
19
19
  removeScoreboard: (objective: Objective) => void;
20
20
  }
@@ -107,18 +107,26 @@ const server = function (serv, options) {
107
107
  sendDisplayPacket(SCOREBOARD_POSITIONS.SIDEBAR, name);
108
108
  return objective;
109
109
  };
110
+ /**
111
+ * Update a scoreboard objective. Accepts either an array of `{ name, value }` or an array of strings.
112
+ * When strings are provided, values are automatically assigned from -1 and decreasing.
113
+ */
110
114
  serv.updateScoreboard = (objective, newLines) => {
115
+ // Normalize lines: if strings are provided, convert them to ScoreboardLine with descending negative scores starting at -1
116
+ const normalizedLines = Array.isArray(newLines) && typeof newLines[0] === 'string'
117
+ ? newLines.map((name, index) => ({ name, value: -1 - index }))
118
+ : newLines;
111
119
  const oldLines = objective._oldLines || [];
112
120
  const oldLineMap = new Map(oldLines.map(line => [line.name, line.value]));
113
- const newLineMap = new Map(newLines.map(line => [line.name, line.value]));
121
+ const newLineMap = new Map(normalizedLines.map(line => [line.name, line.value]));
114
122
  // Remove lines that no longer exist
115
- oldLines.forEach(({ name, value }) => {
123
+ oldLines.forEach(({ name }) => {
116
124
  if (!newLineMap.has(name)) {
117
125
  sendScorePacket(name, 1, objective.name, 0); // Remove
118
126
  }
119
127
  });
120
128
  // Add or update lines
121
- newLines.forEach(({ name, value }) => {
129
+ normalizedLines.forEach(({ name, value }) => {
122
130
  const oldValue = oldLineMap.get(name);
123
131
  // Only send update if line is new or value changed
124
132
  if (oldValue === undefined || oldValue !== value) {
@@ -127,7 +135,7 @@ const server = function (serv, options) {
127
135
  });
128
136
  // Update the scores map and store old lines for next comparison
129
137
  objective.scores = newLineMap;
130
- objective._oldLines = [...newLines];
138
+ objective._oldLines = [...normalizedLines];
131
139
  };
132
140
  serv.displayScoreboard = (objective) => {
133
141
  sendDisplayPacket(SCOREBOARD_POSITIONS.SIDEBAR, objective.name);
@@ -109,7 +109,7 @@ const entity = function (entity, serv) {
109
109
  // of other players
110
110
  entity.knownPosition = entity.knownPosition === undefined ? entity.position : entity.knownPosition;
111
111
  const diff = position.minus(entity.knownPosition);
112
- let maxDelta;
112
+ let maxDelta = 0;
113
113
  if (serv.supportFeature('fixedPointDelta')) {
114
114
  maxDelta = 3;
115
115
  }
@@ -342,6 +342,33 @@ const server = async function (serv, options) {
342
342
  serv.writeLevelDat();
343
343
  }
344
344
  console.log('worlds init done');
345
+ // Periodic autosave: world and all players
346
+ const autosaveMs = options.savingInterval === false ? 0 : (typeof options.savingInterval === 'number' ? options.savingInterval : 60_000);
347
+ if (autosaveMs > 0) {
348
+ let lastBroadcastTs = 0;
349
+ const doAutosave = async () => {
350
+ try {
351
+ // Save level.dat if needed
352
+ await serv.writeLevelDat();
353
+ // Save worlds if backend supports it
354
+ // prismarine-world saves chunks automatically when constructed with anvil; here we ensure flush via stop/start
355
+ // Save players
356
+ await Promise.allSettled(serv.players.map(p => p.save()));
357
+ // Also flush JSON player stores if the database module is loaded
358
+ await serv.saveAllPlayerDataToDisk?.();
359
+ // Broadcast a single "Server saved" message (no spam more than once per interval)
360
+ const now = Date.now();
361
+ if (now - lastBroadcastTs > autosaveMs - 100) {
362
+ serv.broadcast('§7[autosave] Server saved');
363
+ lastBroadcastTs = now;
364
+ }
365
+ }
366
+ catch (e) {
367
+ serv.warn('Autosave failed: ' + e?.message);
368
+ }
369
+ };
370
+ serv.setInterval(doAutosave, autosaveMs);
371
+ }
345
372
  return () => {
346
373
  for (const world of Object.values(serv.worlds)) {
347
374
  // world.throwOnReadWrite = true
package/dist/modules.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import { Client } from 'minecraft-protocol';
2
2
  import TypedEmitter from 'typed-emitter';
3
3
  import EventEmitter from 'events';
4
- import { IndexedData } from 'minecraft-data';
4
+ import { IndexedData, Block as MinecraftDataBlock } from 'minecraft-data';
5
5
  declare global {
6
6
  interface PlayerEvents {
7
7
  asap: () => void;
8
8
  loadingStatus: (status: string) => void;
9
+ blockPlaced: (block: MinecraftDataBlock) => void;
9
10
  connected: () => void;
10
11
  spawned: () => void;
11
12
  disconnected: (reason?: string) => void;
@@ -15,6 +16,7 @@ declare global {
15
16
  modpe: (data: string) => void;
16
17
  /** Emitted when the player's data is loaded from playerdata folder and can be patched if needed (but will be saved back to playerdata folder if patched) */
17
18
  dataLoaded: () => void;
19
+ databaseLoaded: () => void;
18
20
  }
19
21
  interface ServerEvents {
20
22
  error: (error: Error, pluginName?: string) => void;
package/dist/types.d.ts CHANGED
@@ -12,6 +12,7 @@ import "./lib/modules/commands.d.ts"
12
12
  import "./lib/modules/communication.d.ts"
13
13
  import "./lib/modules/crafting.d.ts"
14
14
  import "./lib/modules/customBlockBreakTime.d.ts"
15
+ import "./lib/modules/database.d.ts"
15
16
  import "./lib/modules/daycycle.d.ts"
16
17
  import "./lib/modules/digging.d.ts"
17
18
  import "./lib/modules/dimensionCodec.d.ts"
@@ -24,11 +25,13 @@ import "./lib/modules/fallDamange.d.ts"
24
25
  import "./lib/modules/gamerules.d.ts"
25
26
  import "./lib/modules/header.d.ts"
26
27
  import "./lib/modules/health.d.ts"
28
+ import "./lib/modules/http.d.ts"
27
29
  import "./lib/modules/index.d.ts"
28
30
  import "./lib/modules/inventory.d.ts"
29
31
  import "./lib/modules/log.d.ts"
30
32
  import "./lib/modules/login.d.ts"
31
33
  import "./lib/modules/logout.d.ts"
34
+ import "./lib/modules/maps.d.ts"
32
35
  import "./lib/modules/moderation.d.ts"
33
36
  import "./lib/modules/particle.d.ts"
34
37
  import "./lib/modules/physics.d.ts"
@@ -40,6 +43,7 @@ import "./lib/modules/pvp.d.ts"
40
43
  import "./lib/modules/redstone.d.ts"
41
44
  import "./lib/modules/resourcePack.d.ts"
42
45
  import "./lib/modules/respawn.d.ts"
46
+ import "./lib/modules/safeZones.d.ts"
43
47
  import "./lib/modules/scoreboard.d.ts"
44
48
  import "./lib/modules/settings.d.ts"
45
49
  import "./lib/modules/signs.d.ts"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zardoy/flying-squid",
3
3
  "description": "A minecraft server written in TS",
4
- "version": "0.0.77",
4
+ "version": "0.0.79",
5
5
  "main": "dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "bin": "dist/app.js",