@zardoy/flying-squid 0.0.82 → 0.0.84

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.
@@ -1,6 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = (obj) => {
4
+ const handleError = (err, eventName) => {
5
+ // Log the error but don't crash
6
+ if (err.name === 'UserError') {
7
+ obj.emit('error', err, 'behavior');
8
+ }
9
+ else {
10
+ const error = new Error(`Error in ${eventName} handler: ${err.message}`);
11
+ error.stack = err.stack;
12
+ obj.emit('error', error, 'behavior');
13
+ }
14
+ return false; // Return false to indicate error occurred
15
+ };
4
16
  return async (eventName, data, func, cancelFunc) => {
5
17
  let hiddenCancelled = false;
6
18
  let cancelled = false;
@@ -17,23 +29,53 @@ exports.default = (obj) => {
17
29
  };
18
30
  let resp;
19
31
  func = func || (() => { });
20
- await obj.emitThen(eventName + '_cancel', data, cancel).catch((err) => setTimeout(() => { throw err; }, 0));
21
- await obj.emitThen(eventName, data, cancelled, cancelCount).catch((err) => setTimeout(() => { throw err; }, 0));
32
+ // Handle each event emission separately to allow pipeline to continue
33
+ try {
34
+ await obj.emitThen(eventName + '_cancel', data, cancel);
35
+ }
36
+ catch (err) {
37
+ handleError(err, eventName + '_cancel');
38
+ }
39
+ try {
40
+ await obj.emitThen(eventName, data, cancelled, cancelCount);
41
+ }
42
+ catch (err) {
43
+ handleError(err, eventName);
44
+ }
22
45
  if (!hiddenCancelled && !cancelled) {
23
- resp = func(data);
24
- if (resp instanceof Promise)
25
- resp = await resp.catch((err) => setTimeout(() => { throw err; }, 0));
26
- if (typeof resp === 'undefined')
27
- resp = true;
46
+ try {
47
+ resp = func(data);
48
+ if (resp instanceof Promise) {
49
+ resp = await resp;
50
+ }
51
+ if (typeof resp === 'undefined')
52
+ resp = true;
53
+ }
54
+ catch (err) {
55
+ handleError(err, `${eventName} function`);
56
+ resp = false;
57
+ }
28
58
  }
29
59
  else if (cancelFunc && defaultCancel) {
30
- resp = cancelFunc(data);
31
- if (resp instanceof Promise)
32
- resp = await resp.catch((err) => setTimeout(() => { throw err; }, 0));
33
- if (typeof resp === 'undefined')
60
+ try {
61
+ resp = cancelFunc(data);
62
+ if (resp instanceof Promise) {
63
+ resp = await resp;
64
+ }
65
+ if (typeof resp === 'undefined')
66
+ resp = false;
67
+ }
68
+ catch (err) {
69
+ handleError(err, `${eventName} cancel function`);
34
70
  resp = false;
71
+ }
72
+ }
73
+ try {
74
+ await obj.emitThen(eventName + '_done', data, cancelled);
75
+ }
76
+ catch (err) {
77
+ handleError(err, eventName + '_done');
35
78
  }
36
- await obj.emitThen(eventName + '_done', data, cancelled).catch((err) => setTimeout(() => { throw err; }, 0));
37
79
  return resp;
38
80
  };
39
81
  };
@@ -58,7 +58,12 @@ const player = function (player, serv) {
58
58
  player.writePacket = (packetName, data) => {
59
59
  if (!serv.mcData.protocol.play.toClient.types[`packet_${packetName}`])
60
60
  return;
61
- player._client.write(packetName, data);
61
+ try {
62
+ player._client.write(packetName, data);
63
+ }
64
+ catch (err) {
65
+ serv.emit('error', err, { type: 'toPlayerPacket', name: packetName, data, player: player });
66
+ }
62
67
  };
63
68
  player.bridge = new mc_bridge_1.ServerPacketBridger(serv.mcData.version.minecraftVersion, (packetName, data) => {
64
69
  player.writePacket(packetName, data);
@@ -0,0 +1,18 @@
1
+ export declare const server: (serv: Server, options: Options) => {
2
+ lastSyncRequests: Map<string, {
3
+ time: number;
4
+ requestId: number;
5
+ }>;
6
+ nextRequestId: number;
7
+ /** @internal */
8
+ requestSync: (player: Player) => void;
9
+ handleSyncResponse: (player: Player, data: {
10
+ data: string;
11
+ }) => void;
12
+ };
13
+ export declare const player: (player: Player, serv: Server) => void;
14
+ declare global {
15
+ interface Server {
16
+ customSync: ReturnType<typeof server>;
17
+ }
18
+ }
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.player = exports.server = void 0;
4
+ const SYNC_REQUEST_CHANNEL = 'minecraft-web-client:sync-request';
5
+ const SYNC_RESPONSE_CHANNEL = 'minecraft-web-client:sync-response';
6
+ const CHECK_INTERVAL = 1000; // 1 second
7
+ const server = (serv, options) => {
8
+ const module = {
9
+ // Track when we last requested sync from each player
10
+ lastSyncRequests: new Map(),
11
+ nextRequestId: 0,
12
+ // Request entity list from a player
13
+ /** @internal */
14
+ requestSync: (player) => {
15
+ const requestId = module.nextRequestId++;
16
+ const request = {
17
+ requestId,
18
+ time: Date.now()
19
+ };
20
+ player._client.writeChannel(SYNC_REQUEST_CHANNEL, {
21
+ data: JSON.stringify({ requestId })
22
+ });
23
+ module.lastSyncRequests.set(player.uuid, request);
24
+ },
25
+ // Handle sync response from client
26
+ handleSyncResponse: (player, data) => {
27
+ try {
28
+ const parsed = JSON.parse(data.data);
29
+ // Type guard to validate response shape
30
+ const isValidResponse = (obj) => {
31
+ return typeof obj === 'object' && obj !== null &&
32
+ typeof obj.requestId === 'number' &&
33
+ Array.isArray(obj.entityIds) &&
34
+ obj.entityIds.every(id => typeof id === 'number');
35
+ };
36
+ if (!isValidResponse(parsed)) {
37
+ throw new Error('Invalid response format');
38
+ }
39
+ const { requestId, entityIds } = parsed;
40
+ // Verify this is a response to our last request
41
+ const lastRequest = module.lastSyncRequests.get(player.uuid);
42
+ if (!lastRequest || lastRequest.requestId !== requestId) {
43
+ return; // Ignore out of order responses
44
+ }
45
+ // Calculate and update latency
46
+ const latency = Date.now() - lastRequest.time;
47
+ player._client.latency = latency;
48
+ // Clean up the request
49
+ module.lastSyncRequests.delete(player.uuid);
50
+ const trackedIds = new Set(entityIds);
51
+ const expectedIds = new Set();
52
+ // Find entities that should be visible to the player
53
+ for (const entity of Object.values(serv.entities)) {
54
+ if (entity.id === player.id)
55
+ continue; // Skip self
56
+ // Check if entity is within view distance
57
+ const dx = entity.position.x - player.position.x;
58
+ const dy = entity.position.y - player.position.y;
59
+ const dz = entity.position.z - player.position.z;
60
+ const distanceSquared = dx * dx + dy * dy + dz * dz;
61
+ const viewDistance = entity.viewDistance ?? 150;
62
+ if (distanceSquared <= viewDistance * viewDistance) {
63
+ expectedIds.add(entity.id);
64
+ }
65
+ }
66
+ // Find missing entities
67
+ for (const entityId of expectedIds) {
68
+ if (!trackedIds.has(entityId)) {
69
+ const entity = serv.entities[entityId];
70
+ if (!entity)
71
+ continue;
72
+ serv.warn(`Player ${player.username} missing entity ${entityId} (${entity.name ?? entity.type}), respawning... (ping: ${latency}ms)`);
73
+ // Respawn the entity for this player
74
+ player.writePacket(entity.spawnPacketName, entity.getSpawnPacket());
75
+ // Send metadata if needed
76
+ if (serv.supportFeature('entityMetadataSentSeparately')) {
77
+ entity.sendMetadata(entity.metadata);
78
+ }
79
+ }
80
+ }
81
+ // Log extra entities (debugging)
82
+ for (const entityId of trackedIds) {
83
+ if (!expectedIds.has(entityId) && !serv.entities[entityId]) {
84
+ serv.warn(`Player ${player.username} tracking non-existent entity ${entityId}`);
85
+ }
86
+ }
87
+ }
88
+ catch (err) {
89
+ serv.err(`Error handling sync response from ${player.username}: ${err}`);
90
+ }
91
+ }
92
+ };
93
+ serv.customSync = module;
94
+ return module;
95
+ };
96
+ exports.server = server;
97
+ const player = (player, serv) => {
98
+ // Register sync channels with simplified string format
99
+ player._client.registerChannel(SYNC_REQUEST_CHANNEL, ['container', [
100
+ {
101
+ name: 'data',
102
+ type: ['pstring', { countType: 'i16' }]
103
+ }
104
+ ]]);
105
+ player._client.registerChannel(SYNC_RESPONSE_CHANNEL, ['container', [
106
+ {
107
+ name: 'data',
108
+ type: ['pstring', { countType: 'i16' }]
109
+ }
110
+ ]]);
111
+ // Handle sync responses from client
112
+ player._client.on(SYNC_RESPONSE_CHANNEL, (data) => {
113
+ serv.customSync.handleSyncResponse(player, data);
114
+ });
115
+ // Start periodic sync checks
116
+ player.on('spawned', () => {
117
+ player.setInterval(() => {
118
+ serv.customSync.requestSync(player);
119
+ }, CHECK_INTERVAL);
120
+ });
121
+ };
122
+ exports.player = player;
@@ -1,7 +1,7 @@
1
1
  export declare const server: (serv: Server) => {
2
- customWaypoints: Record<string, Waypoint>;
3
- customAddWaypoint: (id: string, waypoint: Waypoint) => void;
4
- customRemoveWaypoint: (id: string) => void;
2
+ waypoints: Record<string, Waypoint>;
3
+ addWaypoint: (id: string, waypoint: Waypoint, players?: Player[]) => void;
4
+ removeWaypoint: (id: string) => void;
5
5
  };
6
6
  export declare const player: (player: Player, serv: Server) => Promise<void>;
7
7
  export type Waypoint = {
@@ -11,6 +11,7 @@ export type Waypoint = {
11
11
  minDistance?: number;
12
12
  label?: string;
13
13
  color?: number;
14
+ _players?: string[];
14
15
  };
15
16
  declare global {
16
17
  interface Server {
@@ -5,16 +5,16 @@ const ADD_CHANNEL = 'minecraft-web-client:waypoint-add';
5
5
  const DELETE_CHANNEL = 'minecraft-web-client:waypoint-delete';
6
6
  const server = (serv) => {
7
7
  const module = {
8
- customWaypoints: {},
9
- customAddWaypoint: (id, waypoint) => {
10
- serv.customWaypoints.customWaypoints[id] = waypoint;
8
+ waypoints: {},
9
+ addWaypoint: (id, waypoint, players) => {
10
+ module.waypoints[id] = { ...waypoint, _players: players ? players.map(p => p.uuid) : undefined };
11
11
  // Broadcast add/update to all online players
12
- for (const player of serv.players ?? []) {
12
+ for (const player of (players ?? serv.players ?? [])) {
13
13
  sendAddWaypoint(player, id, waypoint);
14
14
  }
15
15
  },
16
- customRemoveWaypoint: (id) => {
17
- delete serv.customWaypoints.customWaypoints[id];
16
+ removeWaypoint: (id) => {
17
+ delete module.waypoints[id];
18
18
  // Broadcast delete to all online players
19
19
  for (const player of serv.players ?? []) {
20
20
  sendDeleteWaypoint(player, id);
@@ -40,9 +40,11 @@ function sendDeleteWaypoint(player, id) {
40
40
  player._client.writeChannel(DELETE_CHANNEL, { id });
41
41
  }
42
42
  function sendAllWaypoints(player, serv) {
43
- const entries = Object.entries(serv.customWaypoints.customWaypoints ?? {});
43
+ const entries = Object.entries(serv.customWaypoints.waypoints ?? {});
44
44
  for (const [id, waypoint] of entries) {
45
- sendAddWaypoint(player, id, waypoint);
45
+ if (!waypoint._players || waypoint._players.includes(player.uuid)) {
46
+ sendAddWaypoint(player, id, waypoint);
47
+ }
46
48
  }
47
49
  }
48
50
  const player = async (player, serv) => {
@@ -18,10 +18,10 @@ declare global {
18
18
  totalJoinsOnStart: number;
19
19
  getPlayerData: (uuid: string) => PlayerStatsStore;
20
20
  updatePlayerData: (uuid: string, updater: Partial<PlayerStatsStore> | ((data: PlayerStatsStore) => void)) => void;
21
- getAllPlayerData: () => Array<{
21
+ getAllPlayerData: () => Promise<Array<{
22
22
  uuid: string;
23
23
  data: PlayerStatsStore;
24
- }>;
24
+ }>>;
25
25
  loadPlayerDataFromDisk: (uuid: string) => Promise<boolean>;
26
26
  savePlayerDataToDisk: (uuid: string) => Promise<void>;
27
27
  saveAllPlayerDataToDisk: () => Promise<void>;
@@ -32,4 +32,6 @@ declare global {
32
32
  isFresh: boolean;
33
33
  _sessionStartMs: number;
34
34
  }
35
+ interface ServerDatabase {
36
+ }
35
37
  }
@@ -17,18 +17,11 @@ const server = function (serv, options) {
17
17
  // In-memory stores for player data and a flag for dirty tracking
18
18
  serv.playerStores ??= new Map();
19
19
  const dirtyStores = new Set();
20
- // Compute total joins from .dat files at startup
20
+ // Track loaded state
21
+ let initialLoadComplete = false;
22
+ const loadedPlayers = new Set();
23
+ let totalJoinsComputed = false;
21
24
  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
25
  // API: get player store
33
26
  serv.getPlayerData = (uuid) => {
34
27
  let store = serv.playerStores.get(uuid);
@@ -37,6 +30,7 @@ const server = function (serv, options) {
37
30
  serv.playerStores.set(uuid, newStore);
38
31
  store = newStore;
39
32
  dirtyStores.add(uuid);
33
+ loadedPlayers.add(uuid); // Track new players
40
34
  }
41
35
  return store;
42
36
  };
@@ -51,8 +45,53 @@ const server = function (serv, options) {
51
45
  }
52
46
  dirtyStores.add(uuid);
53
47
  };
54
- serv.getAllPlayerData = () => {
55
- return Array.from(serv.playerStores.entries()).map(([uuid, data]) => ({ uuid, data }));
48
+ serv.getAllPlayerData = async () => {
49
+ // Get all known players from both stores and playerdata directory
50
+ const allUuids = new Set();
51
+ // Add all in-memory players
52
+ for (const uuid of serv.playerStores.keys()) {
53
+ allUuids.add(uuid);
54
+ }
55
+ // Add any players from disk that haven't been loaded yet
56
+ if (options.worldFolder && !initialLoadComplete) {
57
+ const dir = path_1.default.resolve(String(options.worldFolder), 'playerdata');
58
+ try {
59
+ const entries = await fs_1.promises.readdir(dir);
60
+ // Compute total joins lazily if not done yet
61
+ if (!totalJoinsComputed) {
62
+ serv.totalJoinsOnStart = entries.filter((f) => f.toLowerCase().endsWith('.dat')).length;
63
+ totalJoinsComputed = true;
64
+ }
65
+ for (const file of entries) {
66
+ if (file.toLowerCase().endsWith('.json')) {
67
+ const uuid = path_1.default.basename(file, '.json');
68
+ allUuids.add(uuid);
69
+ }
70
+ }
71
+ }
72
+ catch (e) {
73
+ serv.warn(`Failed to load player data from disk: ${String(e)}`);
74
+ }
75
+ initialLoadComplete = true;
76
+ }
77
+ // Load any unloaded players
78
+ const loadPromises = [];
79
+ for (const uuid of allUuids) {
80
+ if (!loadedPlayers.has(uuid)) {
81
+ loadPromises.push(serv.loadPlayerDataFromDisk(uuid)
82
+ .then(() => { loadedPlayers.add(uuid); })
83
+ .catch((e) => { serv.warn(`Failed to load player data ${uuid} from disk: ${String(e)}`); }));
84
+ }
85
+ }
86
+ // Wait for all loads to complete
87
+ if (loadPromises.length > 0) {
88
+ await Promise.all(loadPromises);
89
+ }
90
+ // Return all player data
91
+ return Array.from(allUuids).map(uuid => ({
92
+ uuid,
93
+ data: serv.getPlayerData(uuid)
94
+ }));
56
95
  };
57
96
  // Load and save helpers
58
97
  const getJsonPath = (uuid) => options.worldFolder
@@ -142,6 +142,7 @@ const player = function (player, serv, { version }) {
142
142
  });
143
143
  }
144
144
  }
145
+ const blockDropVelocity = new vec3_1.Vec3(Math.random() * 4 - 2, Math.random() * 2 + 2, Math.random() * 4 - 2);
145
146
  async function completeDigging(location) {
146
147
  clearInterval(animationInterval);
147
148
  const diggingTime = Date.now() - startDiggingTime;
@@ -168,18 +169,24 @@ const player = function (player, serv, { version }) {
168
169
  if (typeof mcData.blockLoot === 'undefined') {
169
170
  drops.push({
170
171
  ...dropBase,
171
- blockDropVelocity: new vec3_1.Vec3(Math.random() * 4 - 2, Math.random() * 2 + 2, Math.random() * 4 - 2),
172
+ blockDropVelocity: blockDropVelocity,
172
173
  blockDropId: serv.supportFeature('theFlattening') ? currentlyDugBlock.drops?.[0] : currentlyDugBlock.type
173
174
  });
174
175
  }
175
176
  else {
176
177
  const heldItem = player.inventory.slots[36 + player.heldItemSlot];
177
- const silkTouch = heldItem?.enchants.map(enchant => enchant.name).includes('silk_touch');
178
+ let enchants;
179
+ try {
180
+ enchants = heldItem?.enchants;
181
+ }
182
+ catch (e) {
183
+ }
184
+ const silkTouch = enchants?.map(enchant => enchant.name).includes('silk_touch');
178
185
  const blockDrops = mcData.blockLoot[currentlyDugBlock.name].drops.filter(drop => !(drop[`${silkTouch ? 'noS' : 's'}ilkTouch`] ?? false));
179
186
  for (const drop of blockDrops) {
180
187
  drops.push({
181
188
  ...dropBase,
182
- blockDropVelocity: new vec3_1.Vec3(Math.random() * 4 - 2, Math.random() * 2 + 2, Math.random() * 4 - 2),
189
+ blockDropVelocity: blockDropVelocity,
183
190
  blockDropId: mcData.itemsByName[drop.item].id
184
191
  });
185
192
  }
@@ -214,7 +221,7 @@ const player = function (player, serv, { version }) {
214
221
  type: currentlyDugBlock.type << 4
215
222
  });
216
223
  if (serv.supportFeature('acknowledgePlayerDigging')) {
217
- player._client.write('acknowledge_player_digging', {
224
+ player.writePacket('acknowledge_player_digging', {
218
225
  location,
219
226
  block: currentlyDugBlock.stateId,
220
227
  status: 2,
@@ -240,7 +247,7 @@ const player = function (player, serv, { version }) {
240
247
  dropBlock: false,
241
248
  blockDropPosition: location.offset(0.5, 0.5, 0.5),
242
249
  blockDropWorld: player.world,
243
- blockDropVelocity: new vec3_1.Vec3(Math.random() * 4 - 2, Math.random() * 2 + 2, Math.random() * 4 - 2),
250
+ blockDropVelocity: blockDropVelocity,
244
251
  blockDropId: currentlyDugBlock.type,
245
252
  blockDropDamage: currentlyDugBlock.metadata,
246
253
  blockDropPickup: 500,
@@ -20,7 +20,6 @@ const player = async function (player, serv) {
20
20
  serv.err('-------------------------------');
21
21
  serv.emit('crash');
22
22
  serv.quit(`Internal server error. ${err}`);
23
- process.exit();
24
23
  }
25
24
  process.on('unhandledRejection', (promise) => { unhandledRejection(promise); });
26
25
  process.on('uncaughtException', err => { uncaughtException(err); });
@@ -15,6 +15,7 @@ module.exports = {
15
15
  'communication': require('./communication'),
16
16
  'crafting': require('./crafting'),
17
17
  'customBlockBreakTime': require('./customBlockBreakTime'),
18
+ 'customSync': require('./customSync'),
18
19
  'customWaypoints': require('./customWaypoints'),
19
20
  'database': require('./database'),
20
21
  'daycycle': require('./daycycle'),
@@ -33,13 +34,13 @@ module.exports = {
33
34
  'index': require('./index'),
34
35
  'inventory': require('./inventory'),
35
36
  'log': require('./log'),
36
- 'login': require('./login'),
37
37
  'logout': require('./logout'),
38
38
  'maps': require('./maps'),
39
39
  'moderation': require('./moderation'),
40
40
  'particle': require('./particle'),
41
41
  'physics': require('./physics'),
42
42
  'placeBlock': require('./placeBlock'),
43
+ 'playerLogin': require('./playerLogin'),
43
44
  'players': require('./players'),
44
45
  'pluginsFolder': require('./pluginsFolder'),
45
46
  'portal': require('./portal'),
@@ -73,8 +73,13 @@ const server = function (serv, settings) {
73
73
  serv._logBuffer ??= [];
74
74
  serv._errorBuffer ??= [];
75
75
  const MAX_BUFFER_LINES = 1500;
76
- serv.on('error', (error, pluginName) => {
77
- serv.err('Server: ' + error.stack + (pluginName ? ' (plugin: ' + pluginName + ')' : ''));
76
+ serv.on('error', (error, { type, pluginName, name } = {}) => {
77
+ let msg = 'Server';
78
+ if (type === 'fromPlayerPacket')
79
+ msg = `Player packet ${name ?? ''}`;
80
+ if (type === 'toPlayerPacket')
81
+ msg = `Server packet ${name ?? ''}`;
82
+ serv.err(msg + ': ' + error.stack + (pluginName ? ' (plugin: ' + pluginName + ')' : ''));
78
83
  });
79
84
  serv.on('clientError', (client, error) => {
80
85
  if (error.message.includes('ECONNABORTED') || error.message.includes('ECONNRESET'))
@@ -67,10 +67,33 @@ const server = function (serv, options) {
67
67
  serv.emit('clientError', client, error);
68
68
  });
69
69
  });
70
- const patchClient = (client) => {
70
+ const patchClient = (client, player) => {
71
71
  client.oldAddListener ??= client.on.bind(client);
72
72
  client.patchedAddListener = (name, ...args) => {
73
- client.oldAddListener(name, ...args);
73
+ if (name !== 'packet') {
74
+ const listener = args[0];
75
+ client.oldAddListener(name, (...args) => {
76
+ if (args.length !== 1) {
77
+ listener(...args);
78
+ }
79
+ else {
80
+ // PATCHED PACKET EMIT
81
+ const data = args[0];
82
+ const catchErr = (err) => {
83
+ serv.emit('error', err, { type: 'fromPlayerPacket', name, data, player: player });
84
+ };
85
+ try {
86
+ listener(data)?.catch(catchErr);
87
+ }
88
+ catch (err) {
89
+ catchErr(err);
90
+ }
91
+ }
92
+ });
93
+ }
94
+ else {
95
+ client.oldAddListener(name, ...args);
96
+ }
74
97
  serv.cleanupFunctions.push(() => client.removeListener(name, ...args));
75
98
  };
76
99
  client.on = client.patchedAddListener;
@@ -78,7 +101,7 @@ const server = function (serv, options) {
78
101
  };
79
102
  const addPlayerShared = async (player) => {
80
103
  player.serv = serv;
81
- patchClient(player._client);
104
+ patchClient(player._client, player);
82
105
  for (const plugin of Object.values({ ...serv.modules, ...serv.plugins }))
83
106
  plugin.player?.(player, serv, options);
84
107
  serv.emit('newPlayer', player);
@@ -3,6 +3,8 @@ export declare const entity: (entity: Entity, serv: Server) => void;
3
3
  export declare const server: (serv: Server) => void;
4
4
  declare global {
5
5
  interface Entity {
6
+ /** Whether the entity is invincible to all damage */
7
+ invincible: boolean;
6
8
  /** How many half-hearts an entity has of health (e.g. Player has 20). Not really used for objects, only players and mobs. */
7
9
  health: number;
8
10
  /** * sound: Sound to play (default is game.player.hurt)
@@ -7,15 +7,35 @@ exports.server = exports.entity = exports.player = void 0;
7
7
  const vec3_1 = require("vec3");
8
8
  const chalk_1 = __importDefault(require("chalk"));
9
9
  const user_error_1 = __importDefault(require("../user_error"));
10
+ const MAX_ATTACK_DISTANCE = 4; // Maximum reach in blocks
11
+ const ATTACK_COOLDOWN_MS = 250; // Minimum time between attacks
12
+ const DEFAULT_KNOCKBACK = new vec3_1.Vec3(0, 0.4, 0); // Base vertical knockback
13
+ const KNOCKBACK_MULTIPLIER = 0.4; // Horizontal knockback scaling
10
14
  const player = function (player, serv) {
15
+ let lastAttackTime = 0;
11
16
  function attackEntity(entityId) {
12
17
  const attackedEntity = serv.entities[entityId];
13
18
  const attackedPlayer = attackedEntity.type === 'player' ? attackedEntity : undefined;
14
- if (!attackedEntity || (attackedPlayer && attackedPlayer.gameMode !== 0))
19
+ if (!attackedEntity)
15
20
  return;
21
+ if (attackedPlayer && (attackedPlayer.gameMode === 1 || attackedPlayer.gameMode === 3 || attackedPlayer.invincible))
22
+ return;
23
+ // Anti-cheat: Distance check
24
+ const distance = player.position.distanceTo(attackedEntity.position);
25
+ if (distance > MAX_ATTACK_DISTANCE) {
26
+ return; // Silently fail suspicious attacks
27
+ }
28
+ // Rate limiting
29
+ const now = Date.now();
30
+ if (now - lastAttackTime < ATTACK_COOLDOWN_MS)
31
+ return;
32
+ lastAttackTime = now;
33
+ // Calculate knockback direction and strength
34
+ const knockbackDir = attackedEntity.position.minus(player.position).normalize();
35
+ const velocity = DEFAULT_KNOCKBACK.plus(knockbackDir.scaled(KNOCKBACK_MULTIPLIER));
16
36
  player.behavior('attack', {
17
37
  attackedEntity,
18
- velocity: attackedEntity.position.minus(player.position).plus(new vec3_1.Vec3(0, 0.5, 0)).scaled(5)
38
+ velocity
19
39
  }, (o) => o.attackedEntity.takeDamage(o));
20
40
  }
21
41
  player._client.on('use_entity', ({ mouse, target } = {}) => {
@@ -35,7 +55,10 @@ const player = function (player, serv) {
35
55
  };
36
56
  exports.player = player;
37
57
  const entity = function (entity, serv) {
58
+ entity.invincible = false;
38
59
  entity.takeDamage = ({ sound = 'game.player.hurt', damage = 1, velocity = new vec3_1.Vec3(0, 0, 0), maxVelocity = new vec3_1.Vec3(4, 4, 4), animation = true }) => {
60
+ if (entity.invincible)
61
+ return;
39
62
  entity.updateHealth(entity.health - damage);
40
63
  serv.playSound(sound, entity.world, entity.position);
41
64
  entity.sendVelocity(velocity, maxVelocity);
@@ -73,6 +96,7 @@ const server = function (serv) {
73
96
  info: 'Kill entities',
74
97
  usage: '/kill <selector>|<player>',
75
98
  tab: ['player'],
99
+ op: true,
76
100
  parse(str) {
77
101
  return str || false;
78
102
  },
@@ -105,6 +129,7 @@ const server = function (serv) {
105
129
  info: 'Applies damage to the specified entities',
106
130
  usage: '/damage',
107
131
  tab: ['player', 'number'],
132
+ op: true,
108
133
  parse(string, ctx) {
109
134
  return string.split(' '); // todo validate
110
135
  },
@@ -28,6 +28,7 @@ declare global {
28
28
  /** Alias to serv.overworld.seed */
29
29
  seed: number;
30
30
  writeLevelDat: () => Promise<void>;
31
+ broadcastSaved?: boolean;
31
32
  "overworldOriginalGenerator": (chunkX: number, chunkZ: number) => any;
32
33
  "overworldGeneratorOverride"?: (chunkX: number, chunkZ: number, generationOptions: any) => any;
33
34
  }
@@ -344,7 +344,7 @@ const server = async function (serv, options) {
344
344
  console.log('worlds init done');
345
345
  // Periodic autosave: world and all players
346
346
  const autosaveMs = options.savingInterval === false ? 0 : (typeof options.savingInterval === 'number' ? options.savingInterval : 60_000);
347
- if (autosaveMs > 0) {
347
+ if (autosaveMs > 0 && options.worldFolder) {
348
348
  let lastBroadcastTs = 0;
349
349
  const doAutosave = async () => {
350
350
  try {
@@ -358,7 +358,7 @@ const server = async function (serv, options) {
358
358
  await serv.saveAllPlayerDataToDisk?.();
359
359
  // Broadcast a single "Server saved" message (no spam more than once per interval)
360
360
  const now = Date.now();
361
- if (now - lastBroadcastTs > autosaveMs - 100) {
361
+ if (now - lastBroadcastTs > autosaveMs - 10_000 && serv.broadcastSaved !== false) {
362
362
  serv.broadcast('§7[autosave] Server saved');
363
363
  lastBroadcastTs = now;
364
364
  }
package/dist/modules.d.ts CHANGED
@@ -20,7 +20,13 @@ declare global {
20
20
  login: () => void;
21
21
  }
22
22
  interface ServerEvents {
23
- error: (error: Error, pluginName?: string) => void;
23
+ error: (error: Error, data?: {
24
+ type?: string;
25
+ name?: string;
26
+ data?: any;
27
+ player?: Player;
28
+ pluginName?: string;
29
+ }) => void;
24
30
  listening: (port: number) => void;
25
31
  pluginsReady: () => void;
26
32
  /** This event is emitted once all plugins are initialized. Use this event for working with properties / methods of other plugins. */
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/customSync.d.ts"
15
16
  import "./lib/modules/customWaypoints.d.ts"
16
17
  import "./lib/modules/database.d.ts"
17
18
  import "./lib/modules/daycycle.d.ts"
@@ -30,13 +31,13 @@ import "./lib/modules/http.d.ts"
30
31
  import "./lib/modules/index.d.ts"
31
32
  import "./lib/modules/inventory.d.ts"
32
33
  import "./lib/modules/log.d.ts"
33
- import "./lib/modules/login.d.ts"
34
34
  import "./lib/modules/logout.d.ts"
35
35
  import "./lib/modules/maps.d.ts"
36
36
  import "./lib/modules/moderation.d.ts"
37
37
  import "./lib/modules/particle.d.ts"
38
38
  import "./lib/modules/physics.d.ts"
39
39
  import "./lib/modules/placeBlock.d.ts"
40
+ import "./lib/modules/playerLogin.d.ts"
40
41
  import "./lib/modules/players.d.ts"
41
42
  import "./lib/modules/pluginsFolder.d.ts"
42
43
  import "./lib/modules/portal.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.82",
4
+ "version": "0.0.84",
5
5
  "main": "dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "bin": "dist/app.js",