@zardoy/flying-squid 0.0.139 → 0.0.140

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.
Files changed (37) hide show
  1. package/dist/lib/blockArgument.d.ts +46 -0
  2. package/dist/lib/blockArgument.js +126 -0
  3. package/dist/lib/blockArgument.test.d.ts +1 -0
  4. package/dist/lib/blockArgument.test.js +65 -0
  5. package/dist/lib/command.js +3 -0
  6. package/dist/lib/commandArgs.d.ts +5 -0
  7. package/dist/lib/commandArgs.js +28 -0
  8. package/dist/lib/containers/gameData.d.ts +2 -0
  9. package/dist/lib/containers/gameData.js +18 -0
  10. package/dist/lib/modules/blocks.js +114 -49
  11. package/dist/lib/modules/blocks.test.d.ts +1 -0
  12. package/dist/lib/modules/blocks.test.js +91 -0
  13. package/dist/lib/modules/commands.js +8 -0
  14. package/dist/lib/modules/containers.js +1 -0
  15. package/dist/lib/modules/daycycle.js +1 -1
  16. package/dist/lib/modules/endFight.js +1 -0
  17. package/dist/lib/modules/experience.js +1 -0
  18. package/dist/lib/modules/gamerules.js +1 -0
  19. package/dist/lib/modules/moderation.js +8 -0
  20. package/dist/lib/modules/particle.js +1 -0
  21. package/dist/lib/modules/physics.js +1 -0
  22. package/dist/lib/modules/players.js +4 -1
  23. package/dist/lib/modules/portal.js +1 -0
  24. package/dist/lib/modules/pvp.js +1 -1
  25. package/dist/lib/modules/recipes.js +1 -0
  26. package/dist/lib/modules/sound.js +2 -0
  27. package/dist/lib/modules/spawn.js +2 -0
  28. package/dist/lib/modules/tabComplete.d.ts +26 -6
  29. package/dist/lib/modules/tabComplete.js +123 -110
  30. package/dist/lib/modules/tabComplete.test.d.ts +1 -0
  31. package/dist/lib/modules/tabComplete.test.js +76 -0
  32. package/dist/lib/modules/tp.js +1 -0
  33. package/dist/lib/modules/warps.js +2 -0
  34. package/dist/lib/modules/weather.js +1 -0
  35. package/dist/lib/modules/world.js +2 -0
  36. package/dist/lib/modules/worldManager.js +2 -0
  37. package/package.json +1 -1
@@ -0,0 +1,46 @@
1
+ /** A block state property as minecraft-data describes it (`blocks[id].states`). */
2
+ type BlockStateProperty = {
3
+ name: string;
4
+ type: 'enum' | 'bool' | 'int' | string;
5
+ num_values: number;
6
+ values?: string[];
7
+ };
8
+ type RegistryBlock = {
9
+ id: number;
10
+ name: string;
11
+ minStateId?: number;
12
+ maxStateId?: number;
13
+ defaultState?: number;
14
+ states?: BlockStateProperty[];
15
+ };
16
+ type BlockRegistry = {
17
+ blocksByName: Record<string, RegistryBlock | undefined>;
18
+ blocks: Record<number, RegistryBlock | undefined>;
19
+ blocksArray: RegistryBlock[];
20
+ };
21
+ export type ParsedBlockArgument = {
22
+ block: RegistryBlock;
23
+ stateId: number;
24
+ /** only the properties written in the argument (`stone[]` and `stone` give {}), used to compare blocks like /testforblock */
25
+ properties: Record<string, string>;
26
+ };
27
+ /** Values of a property in state index order (bool: index 0 is true, like the game's state ids). */
28
+ export declare function propertyValues(property: BlockStateProperty): string[];
29
+ /** Property values of a state id, e.g. ladder 4659 -> { facing: 'west', waterlogged: 'false' }. */
30
+ export declare function blockStateProperties(block: RegistryBlock, stateId: number): Record<string, string>;
31
+ /** State id of a block with the given property values (the others from the default state). */
32
+ export declare function blockStateIdFromProperties(block: RegistryBlock, properties: Record<string, string>): number;
33
+ /**
34
+ * Parses a vanilla block argument: `stone`, `minecraft:ladder[facing=west]`, `redstone_wire[power=15,east=side]`.
35
+ * Unknown blocks, properties and values are a UserError that names what is wrong and what is allowed.
36
+ * Pre-flattening versions (no block states) also take a numeric id; the data value is up to the command.
37
+ */
38
+ export declare function parseBlockArgument(registry: BlockRegistry, input: string): ParsedBlockArgument;
39
+ /** True when the state id is the block and has every property written in the argument (vanilla /testforblock, /execute if block). */
40
+ export declare function blockMatchesArgument(registry: BlockRegistry, parsed: ParsedBlockArgument, stateId: number): boolean;
41
+ /**
42
+ * Tab completion for a block argument being typed: block names, then `name[` with the property names, then the values
43
+ * of the property being typed, `,` / `]` after a complete pair. Returns full tokens (the client replaces the last word).
44
+ */
45
+ export declare function completeBlockArgument(registry: BlockRegistry, typed: string): string[];
46
+ export {};
@@ -0,0 +1,126 @@
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.propertyValues = propertyValues;
7
+ exports.blockStateProperties = blockStateProperties;
8
+ exports.blockStateIdFromProperties = blockStateIdFromProperties;
9
+ exports.parseBlockArgument = parseBlockArgument;
10
+ exports.blockMatchesArgument = blockMatchesArgument;
11
+ exports.completeBlockArgument = completeBlockArgument;
12
+ const user_error_1 = __importDefault(require("./user_error"));
13
+ /** Values of a property in state index order (bool: index 0 is true, like the game's state ids). */
14
+ function propertyValues(property) {
15
+ if (property.values?.length)
16
+ return property.values;
17
+ if (property.type === 'bool')
18
+ return ['true', 'false'];
19
+ return Array.from({ length: property.num_values }, (_, i) => String(i));
20
+ }
21
+ /** Property values of a state id, e.g. ladder 4659 -> { facing: 'west', waterlogged: 'false' }. */
22
+ function blockStateProperties(block, stateId) {
23
+ const states = block.states ?? [];
24
+ const out = {};
25
+ let rest = stateId - (block.minStateId ?? 0);
26
+ for (let i = states.length - 1; i >= 0; i--) {
27
+ const property = states[i];
28
+ out[property.name] = propertyValues(property)[rest % property.num_values];
29
+ rest = Math.floor(rest / property.num_values);
30
+ }
31
+ return out;
32
+ }
33
+ /** State id of a block with the given property values (the others from the default state). */
34
+ function blockStateIdFromProperties(block, properties) {
35
+ const states = block.states ?? [];
36
+ const values = { ...blockStateProperties(block, block.defaultState ?? block.minStateId ?? 0), ...properties };
37
+ let index = 0;
38
+ for (const property of states) {
39
+ const valueIndex = propertyValues(property).indexOf(values[property.name]);
40
+ index = index * property.num_values + Math.max(0, valueIndex);
41
+ }
42
+ return (block.minStateId ?? 0) + index;
43
+ }
44
+ /**
45
+ * Parses a vanilla block argument: `stone`, `minecraft:ladder[facing=west]`, `redstone_wire[power=15,east=side]`.
46
+ * Unknown blocks, properties and values are a UserError that names what is wrong and what is allowed.
47
+ * Pre-flattening versions (no block states) also take a numeric id; the data value is up to the command.
48
+ */
49
+ function parseBlockArgument(registry, input) {
50
+ const match = /^(?:minecraft:)?([a-z0-9_.\-/]+)(?:\[(.*)\])?$/i.exec(input.trim());
51
+ if (!match)
52
+ throw new user_error_1.default(`Invalid block "${input}", expected name or name[property=value,...]`);
53
+ const [, rawName, rawProperties] = match;
54
+ const block = /^\d+$/.test(rawName) ? registry.blocks[+rawName] : registry.blocksByName[rawName.toLowerCase()];
55
+ if (!block)
56
+ throw new user_error_1.default(`Unknown block "${rawName}"`);
57
+ const properties = {};
58
+ const states = block.states ?? [];
59
+ if (rawProperties?.trim()) {
60
+ for (const pair of rawProperties.split(',')) {
61
+ const [rawKey, rawValue, ...extra] = pair.split('=').map(s => s.trim());
62
+ if (!rawKey || rawValue === undefined || rawValue === '' || extra.length)
63
+ throw new user_error_1.default(`Invalid block property "${pair.trim()}", expected property=value`);
64
+ const property = states.find(s => s.name === rawKey);
65
+ if (!property) {
66
+ const known = states.map(s => s.name);
67
+ throw new user_error_1.default(`${block.name} has no property "${rawKey}"${known.length ? ` (it has ${known.join(', ')})` : ''}`);
68
+ }
69
+ const allowed = propertyValues(property);
70
+ const value = rawValue.toLowerCase();
71
+ if (!allowed.includes(value))
72
+ throw new user_error_1.default(`Invalid value "${rawValue}" for ${block.name} ${rawKey} (allowed: ${allowed.join(', ')})`);
73
+ if (properties[rawKey] !== undefined)
74
+ throw new user_error_1.default(`Property "${rawKey}" is given twice`);
75
+ properties[rawKey] = value;
76
+ }
77
+ }
78
+ return { block, stateId: blockStateIdFromProperties(block, properties), properties };
79
+ }
80
+ /** True when the state id is the block and has every property written in the argument (vanilla /testforblock, /execute if block). */
81
+ function blockMatchesArgument(registry, parsed, stateId) {
82
+ const block = registry.blocksArray.find(b => stateId >= (b.minStateId ?? 0) && stateId <= (b.maxStateId ?? b.minStateId ?? 0));
83
+ if (!block || block.id !== parsed.block.id)
84
+ return false;
85
+ const actual = blockStateProperties(block, stateId);
86
+ return Object.entries(parsed.properties).every(([key, value]) => actual[key] === value);
87
+ }
88
+ /**
89
+ * Tab completion for a block argument being typed: block names, then `name[` with the property names, then the values
90
+ * of the property being typed, `,` / `]` after a complete pair. Returns full tokens (the client replaces the last word).
91
+ */
92
+ function completeBlockArgument(registry, typed) {
93
+ const bracket = typed.indexOf('[');
94
+ if (bracket === -1) {
95
+ const names = registry.blocksArray.map(b => b.name);
96
+ const block = registry.blocksByName[typed.replace(/^minecraft:/, '')];
97
+ // the exact name typed: offer to open the state list too
98
+ if (block?.states?.length)
99
+ return [...names, `${typed}[`];
100
+ return names;
101
+ }
102
+ const prefix = typed.slice(0, bracket);
103
+ const block = registry.blocksByName[prefix.replace(/^minecraft:/, '')];
104
+ if (!block?.states?.length)
105
+ return [];
106
+ const inner = typed.slice(bracket + 1);
107
+ if (inner.includes(']'))
108
+ return [];
109
+ const pairs = inner.split(',');
110
+ const current = pairs.pop();
111
+ const done = pairs.map(p => p.split('=')[0].trim());
112
+ const head = `${prefix}[${pairs.length ? pairs.join(',') + ',' : ''}`;
113
+ const eq = current.indexOf('=');
114
+ if (eq === -1) {
115
+ return block.states.filter(s => !done.includes(s.name)).map(s => `${head}${s.name}=`);
116
+ }
117
+ const key = current.slice(0, eq).trim();
118
+ const property = block.states.find(s => s.name === key);
119
+ if (!property)
120
+ return [];
121
+ const remaining = block.states.some(s => s.name !== key && !done.includes(s.name));
122
+ return propertyValues(property).flatMap(value => {
123
+ const pair = `${head}${key}=${value}`;
124
+ return remaining ? [`${pair},`, `${pair}]`] : [`${pair}]`];
125
+ });
126
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,65 @@
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
+ const vitest_1 = require("vitest");
7
+ const minecraft_data_1 = __importDefault(require("minecraft-data"));
8
+ const prismarine_block_1 = __importDefault(require("prismarine-block"));
9
+ const user_error_1 = __importDefault(require("./user_error"));
10
+ const blockArgument_1 = require("./blockArgument");
11
+ const VERSION = '1.20.1';
12
+ const registry = (0, minecraft_data_1.default)(VERSION);
13
+ const Block = prismarine_block_1.default(VERSION);
14
+ (0, vitest_1.test)('a bare name gives the default state', () => {
15
+ (0, vitest_1.expect)((0, blockArgument_1.parseBlockArgument)(registry, 'stone').stateId).toBe(registry.blocksByName.stone.defaultState);
16
+ (0, vitest_1.expect)((0, blockArgument_1.parseBlockArgument)(registry, 'minecraft:ladder').stateId).toBe(registry.blocksByName.ladder.defaultState);
17
+ (0, vitest_1.expect)((0, blockArgument_1.parseBlockArgument)(registry, 'ladder[]').stateId).toBe(registry.blocksByName.ladder.defaultState);
18
+ });
19
+ (0, vitest_1.test)('properties give the same state id as prismarine-block', () => {
20
+ const cases = [
21
+ ['ladder[facing=west]', { facing: 'west', waterlogged: false }],
22
+ ['ladder[facing=east,waterlogged=true]', { facing: 'east', waterlogged: true }],
23
+ ['redstone_wire[power=15,east=side]', { power: 15, east: 'side', north: 'none', south: 'none', west: 'none' }],
24
+ ['oak_log[axis=x]', { axis: 'x' }],
25
+ ['candle[lit=true,candles=3]', { lit: true, candles: 3, waterlogged: false }],
26
+ ['minecraft:furnace[ lit = true , facing = south ]', { lit: true, facing: 'south' }]
27
+ ];
28
+ for (const [arg, props] of cases) {
29
+ const name = arg.replace(/^minecraft:/, '').split('[')[0];
30
+ (0, vitest_1.expect)((0, blockArgument_1.parseBlockArgument)(registry, arg).stateId, arg).toBe(Block.fromProperties(registry.blocksByName[name].id, props, 0).stateId);
31
+ }
32
+ });
33
+ (0, vitest_1.test)('state ids decode back to their properties', () => {
34
+ const { stateId } = (0, blockArgument_1.parseBlockArgument)(registry, 'ladder[facing=west]');
35
+ (0, vitest_1.expect)((0, blockArgument_1.blockStateProperties)(registry.blocksByName.ladder, stateId)).toEqual({ facing: 'west', waterlogged: 'false' });
36
+ });
37
+ (0, vitest_1.test)('wrong blocks, properties and values are user errors naming what is allowed', () => {
38
+ (0, vitest_1.expect)(() => (0, blockArgument_1.parseBlockArgument)(registry, 'not_a_block')).toThrow(user_error_1.default);
39
+ (0, vitest_1.expect)(() => (0, blockArgument_1.parseBlockArgument)(registry, 'ladder[color=red]')).toThrow(/has no property "color" \(it has facing, waterlogged\)/);
40
+ (0, vitest_1.expect)(() => (0, blockArgument_1.parseBlockArgument)(registry, 'ladder[facing=up]')).toThrow(/allowed: north, south, west, east/);
41
+ (0, vitest_1.expect)(() => (0, blockArgument_1.parseBlockArgument)(registry, 'ladder[facing]')).toThrow(user_error_1.default);
42
+ (0, vitest_1.expect)(() => (0, blockArgument_1.parseBlockArgument)(registry, 'ladder[facing=west,facing=east]')).toThrow(/twice/);
43
+ (0, vitest_1.expect)(() => (0, blockArgument_1.parseBlockArgument)(registry, 'stone[axis=x]')).toThrow(/stone has no property "axis"$/);
44
+ });
45
+ (0, vitest_1.test)('blockMatchesArgument compares the block and only the written properties', () => {
46
+ const westLadder = (0, blockArgument_1.parseBlockArgument)(registry, 'ladder[facing=west]').stateId;
47
+ (0, vitest_1.expect)((0, blockArgument_1.blockMatchesArgument)(registry, (0, blockArgument_1.parseBlockArgument)(registry, 'ladder'), westLadder)).toBe(true);
48
+ (0, vitest_1.expect)((0, blockArgument_1.blockMatchesArgument)(registry, (0, blockArgument_1.parseBlockArgument)(registry, 'ladder[facing=west]'), westLadder)).toBe(true);
49
+ (0, vitest_1.expect)((0, blockArgument_1.blockMatchesArgument)(registry, (0, blockArgument_1.parseBlockArgument)(registry, 'ladder[facing=east]'), westLadder)).toBe(false);
50
+ (0, vitest_1.expect)((0, blockArgument_1.blockMatchesArgument)(registry, (0, blockArgument_1.parseBlockArgument)(registry, 'stone'), westLadder)).toBe(false);
51
+ });
52
+ (0, vitest_1.test)('completion walks name -> [ -> property= -> value , or ]', () => {
53
+ (0, vitest_1.expect)((0, blockArgument_1.completeBlockArgument)(registry, 'lad')).toContain('ladder');
54
+ (0, vitest_1.expect)((0, blockArgument_1.completeBlockArgument)(registry, 'ladder')).toContain('ladder[');
55
+ (0, vitest_1.expect)((0, blockArgument_1.completeBlockArgument)(registry, 'stone')).not.toContain('stone[');
56
+ (0, vitest_1.expect)((0, blockArgument_1.completeBlockArgument)(registry, 'ladder[')).toEqual(['ladder[facing=', 'ladder[waterlogged=']);
57
+ (0, vitest_1.expect)((0, blockArgument_1.completeBlockArgument)(registry, 'ladder[facing=')).toEqual([
58
+ 'ladder[facing=north,', 'ladder[facing=north]',
59
+ 'ladder[facing=south,', 'ladder[facing=south]',
60
+ 'ladder[facing=west,', 'ladder[facing=west]',
61
+ 'ladder[facing=east,', 'ladder[facing=east]'
62
+ ]);
63
+ (0, vitest_1.expect)((0, blockArgument_1.completeBlockArgument)(registry, 'ladder[facing=west,')).toEqual(['ladder[facing=west,waterlogged=']);
64
+ (0, vitest_1.expect)((0, blockArgument_1.completeBlockArgument)(registry, 'ladder[facing=west,waterlogged=')).toEqual(['ladder[facing=west,waterlogged=true]', 'ladder[facing=west,waterlogged=false]']);
65
+ });
@@ -72,6 +72,9 @@ class Command {
72
72
  };
73
73
  }
74
74
  catch (err) {
75
+ // a UserError is the command's answer (bad block, bad mode, ...): the caller shows it as "Error: ..."
76
+ if (err?.userError)
77
+ throw err;
75
78
  console.error(`Error in command from ${ctx.player?.username || 'server'} "${command}":`);
76
79
  console.error(err);
77
80
  return {
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Splits command arguments on whitespace, keeping `[...]` and `{...}` groups (block states, NBT) in one argument:
3
+ * `~ ~1 ~ furnace[ lit = true ] keep` -> ['~', '~1', '~', 'furnace[ lit = true ]', 'keep'].
4
+ */
5
+ export declare function splitCommandArgs(str: string): string[];
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.splitCommandArgs = splitCommandArgs;
4
+ /**
5
+ * Splits command arguments on whitespace, keeping `[...]` and `{...}` groups (block states, NBT) in one argument:
6
+ * `~ ~1 ~ furnace[ lit = true ] keep` -> ['~', '~1', '~', 'furnace[ lit = true ]', 'keep'].
7
+ */
8
+ function splitCommandArgs(str) {
9
+ const args = [];
10
+ let current = '';
11
+ let depth = 0;
12
+ for (const ch of str.trim()) {
13
+ if (ch === '[' || ch === '{')
14
+ depth++;
15
+ else if ((ch === ']' || ch === '}') && depth > 0)
16
+ depth--;
17
+ if (/\s/.test(ch) && depth === 0) {
18
+ if (current)
19
+ args.push(current);
20
+ current = '';
21
+ continue;
22
+ }
23
+ current += ch;
24
+ }
25
+ if (current)
26
+ args.push(current);
27
+ return args;
28
+ }
@@ -37,6 +37,8 @@ export declare class GameData {
37
37
  private load;
38
38
  /** parsed loot table (`minecraft:chests/simple_dungeon`), undefined when unknown */
39
39
  lootTable(id: string): any | undefined;
40
+ /** ids of every known loot table (options, jars, datapacks, __MC_GAMEDATA_URL), for /loot completion */
41
+ lootTableIds(): string[];
40
42
  itemTag(id: string): string[];
41
43
  /** all cooking recipes (datapack ones, else the built-in vanilla list) */
42
44
  recipes(): CookingRecipe[];
@@ -93,6 +93,24 @@ class GameData {
93
93
  }
94
94
  return undefined;
95
95
  }
96
+ /** ids of every known loot table (options, jars, datapacks, __MC_GAMEDATA_URL), for /loot completion */
97
+ lootTableIds() {
98
+ const ids = new Set();
99
+ const { lootTables } = this.options;
100
+ if (lootTables && typeof lootTables === 'object')
101
+ for (const id of Object.keys(lootTables))
102
+ ids.add(strip(id));
103
+ if (this.loaded) {
104
+ for (const dir of ['loot_table', 'loot_tables']) {
105
+ try {
106
+ for (const id of this.registry.list(dir))
107
+ ids.add(strip(id));
108
+ }
109
+ catch { }
110
+ }
111
+ }
112
+ return [...ids].sort();
113
+ }
96
114
  itemTag(id) {
97
115
  try {
98
116
  return this.registry.tag('item', id.replace(/^#/, '')).map(strip);
@@ -1,7 +1,12 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.server = exports.player = void 0;
4
- const utils_1 = require("../utils");
7
+ const user_error_1 = __importDefault(require("../user_error"));
8
+ const blockArgument_1 = require("../blockArgument");
9
+ const commandArgs_1 = require("../commandArgs");
5
10
  const vec3_1 = require("vec3");
6
11
  const player = function (player, serv) {
7
12
  player.changeBlock = async (position, stateId, blockData, notify = true) => {
@@ -75,37 +80,67 @@ const server = function (serv, { version }) {
75
80
  const mcData = require('prismarine-registry')(version);
76
81
  const blocks = mcData.blocks;
77
82
  const postFlatenning = serv.supportFeature('theFlattening');
78
- // todo implement!
79
- const usage = postFlatenning ? '/setblock <x> <y> <z> <id> [data]' : '/setblock <x> <y> <z> <block> |replace|keep|destroy|';
83
+ /** world and origin for relative (~) coordinates: the player's, or the overworld at 0 128 0 from the console */
84
+ const commandWorld = (ctx) => ({
85
+ world: ctx.player ? ctx.player.world : serv.overworld,
86
+ origin: ctx.player ? ctx.player.position : new vec3_1.Vec3(0, 128, 0)
87
+ });
88
+ const parsePosition = (args, origin) => {
89
+ const axes = ['x', 'y', 'z'];
90
+ const coords = args.map((value, i) => serv.posFromString(value, origin[axes[i]]));
91
+ if (coords.some(c => !Number.isFinite(c)))
92
+ throw new user_error_1.default(`Invalid position "${args.join(' ')}"`);
93
+ return new vec3_1.Vec3(coords[0], coords[1], coords[2]).floored();
94
+ };
95
+ /** block argument -> state id; pre-flattening versions take a numeric data value after the block */
96
+ const parseBlock = (arg, data) => {
97
+ if (postFlatenning)
98
+ return (0, blockArgument_1.parseBlockArgument)(mcData, arg);
99
+ const parsed = (0, blockArgument_1.parseBlockArgument)(mcData, arg.replace(/\[.*$/, ''));
100
+ const meta = data && /^\d+$/.test(data) ? +data : 0;
101
+ return { ...parsed, stateId: parsed.block.id << 4 | meta };
102
+ };
103
+ const placeBlock = async (world, position, stateId, mode) => {
104
+ const old = await world.getBlockStateId(position);
105
+ if (mode === 'keep' && old !== 0)
106
+ return false;
107
+ if (old === stateId)
108
+ return false;
109
+ if (mode === 'destroy' && old !== 0) {
110
+ const oldBlock = postFlatenning ? mcData.blocksArray.find(b => old >= b.minStateId && old <= b.maxStateId) : blocks[old >> 4];
111
+ if (oldBlock)
112
+ serv.dropItem?.(world, position.offset(0.5, 0.5, 0.5), oldBlock.name);
113
+ }
114
+ await serv.setBlock(world, position, stateId);
115
+ return true;
116
+ };
80
117
  serv.commands.add({
81
118
  base: 'setblock',
82
119
  info: 'set a block at a position',
83
- usage: usage,
120
+ usage: postFlatenning
121
+ ? '/setblock <x> <y> <z> <block>[property=value,...] [replace|keep|destroy]'
122
+ : '/setblock <x> <y> <z> <block> [data] [replace|keep|destroy]',
84
123
  op: true,
85
- tab: ['blockX', 'blockY', 'blockZ', 'block', 'number'],
124
+ tab: postFlatenning
125
+ ? ['blockX', 'blockY', 'blockZ', 'block', 'setblockMode']
126
+ : ['blockX', 'blockY', 'blockZ', 'block', 'number', 'setblockMode'],
86
127
  parse(str) {
87
- const results = str.match(/^(~|~?-?[0-9]+) (~|~?-?[0-9]+) (~|~?-?[0-9]+) ([\w_:0-9]+)(?: ([0-9]{1,3}))?/);
88
- // todo parse properties & nbt!
89
- if (!results)
128
+ const args = (0, commandArgs_1.splitCommandArgs)(str);
129
+ if (args.length < 4)
90
130
  return false;
91
- return results;
131
+ return args;
92
132
  },
93
- action(params, ctx) {
94
- let res = params.slice(1, 4);
95
- if (ctx.player)
96
- res = res.map((val, i) => serv.posFromString(val, ctx.player.position[['x', 'y', 'z'][i]]));
97
- else
98
- res = res.map((val, i) => serv.posFromString(val, new vec3_1.Vec3(0, 128, 0)[['x', 'y', 'z'][i]]));
99
- const blockParam = params[4];
100
- const id = isNaN(+blockParam) ? mcData.blocksByName[(0, utils_1.skipMcPrefix)(blockParam)]?.id : +blockParam;
101
- const data = parseInt(params[5] || '0', 10);
102
- const stateId = postFlatenning
103
- ? data ? (blocks[id].minStateId + data) : blocks[id].defaultState
104
- : (id << 4 | data);
105
- if (ctx.player)
106
- ctx.player.setBlock(new vec3_1.Vec3(+res[0], +res[1], +res[2]).floored(), stateId);
107
- else
108
- serv.setBlock(serv.overworld, new vec3_1.Vec3(+res[0], +res[1], +res[2]).floored(), stateId);
133
+ async action(args, ctx) {
134
+ const { world, origin } = commandWorld(ctx);
135
+ const position = parsePosition(args.slice(0, 3), origin);
136
+ const rest = args.slice(4);
137
+ const data = !postFlatenning && rest[0] && /^\d+$/.test(rest[0]) ? rest.shift() : undefined;
138
+ const mode = rest[0] ?? 'replace';
139
+ if (!['replace', 'keep', 'destroy'].includes(mode))
140
+ throw new user_error_1.default(`Unknown mode "${mode}" (replace, keep, destroy)`);
141
+ const { stateId } = parseBlock(args[3], data);
142
+ const changed = await placeBlock(world, position, stateId, mode);
143
+ return changed ? `Changed the block at ${position.x}, ${position.y}, ${position.z}` : 'Could not set the block';
109
144
  }
110
145
  });
111
146
  serv.commands.add({
@@ -113,6 +148,7 @@ const server = function (serv, { version }) {
113
148
  info: 'set a block action',
114
149
  usage: '/setblockaction <x> <y> <z> <actionId> <actionParam>',
115
150
  op: true,
151
+ tab: ['blockX', 'blockY', 'blockZ', 'number', 'number'],
116
152
  parse(str) {
117
153
  const results = str.match(/^(-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)?/);
118
154
  if (!results)
@@ -126,31 +162,53 @@ const server = function (serv, { version }) {
126
162
  serv.setBlockAction(serv.overworld, new vec3_1.Vec3(+params[1], +params[2], +params[3]).floored(), +params[4], Number(params[5]));
127
163
  }
128
164
  });
165
+ const FILL_LIMIT = 32768;
129
166
  serv.commands.add({
130
167
  base: 'fill',
131
168
  op: true,
132
169
  info: 'Fills a region with a specific block',
133
- usage: '/fill <from> <to> <block>', // todo impl destroy|hollow|keep|outline|replace filter
134
- parse(string, ctx) {
135
- return string.split(' ');
170
+ usage: '/fill <x1> <y1> <z1> <x2> <y2> <z2> <block>[property=value,...] [replace [<filter>]|keep|hollow|outline|destroy]',
171
+ tab: ['blockX', 'blockY', 'blockZ', 'blockX', 'blockY', 'blockZ', 'block', 'fillMode', 'fillFilter'],
172
+ parse(str) {
173
+ const args = (0, commandArgs_1.splitCommandArgs)(str);
174
+ if (args.length < 7)
175
+ return false;
176
+ return args;
136
177
  },
137
- action([_sX, _sY, _sZ, _tX, _tY, _tZ, blockArg], ctx) {
138
- const [sX, sY, sZ, tX, tY, tZ] = [_sX, _sY, _sZ, _tX, _tY, _tZ].map(x => +x);
139
- const block = []; // todo resolve block
178
+ async action(args, ctx) {
179
+ const { world, origin } = commandWorld(ctx);
180
+ const from = parsePosition(args.slice(0, 3), origin);
181
+ const to = parsePosition(args.slice(3, 6), origin);
182
+ const { stateId } = parseBlock(args[6]);
183
+ const mode = args[7] ?? 'replace';
184
+ if (!['replace', 'keep', 'hollow', 'outline', 'destroy'].includes(mode))
185
+ throw new user_error_1.default(`Unknown mode "${mode}" (replace, keep, hollow, outline, destroy)`);
186
+ const filter = mode === 'replace' && args[8] ? parseBlock(args[8]) : undefined;
187
+ const min = new vec3_1.Vec3(Math.min(from.x, to.x), Math.min(from.y, to.y), Math.min(from.z, to.z));
188
+ const max = new vec3_1.Vec3(Math.max(from.x, to.x), Math.max(from.y, to.y), Math.max(from.z, to.z));
189
+ const volume = (max.x - min.x + 1) * (max.y - min.y + 1) * (max.z - min.z + 1);
190
+ if (volume > FILL_LIMIT)
191
+ throw new user_error_1.default(`Too many blocks in the specified area (maximum ${FILL_LIMIT}, specified ${volume})`);
140
192
  let changes = 0;
141
- for (let x = Math.min(sX, tX); x <= Math.max(sX, tX); x++) {
142
- for (let y = Math.min(sY, tY); y <= Math.max(sY, tY); y++) {
143
- for (let z = Math.min(sZ, tZ); z <= Math.max(sZ, tZ); z++) {
144
- ctx.player.setBlock(new vec3_1.Vec3(x, y, z), 0);
145
- changes++;
146
- if (changes > 1000) {
147
- ctx.player.chat(`[Fill] Made ${changes} changes`);
148
- break;
149
- }
193
+ for (let x = min.x; x <= max.x; x++) {
194
+ for (let y = min.y; y <= max.y; y++) {
195
+ for (let z = min.z; z <= max.z; z++) {
196
+ const position = new vec3_1.Vec3(x, y, z);
197
+ const edge = x === min.x || x === max.x || y === min.y || y === max.y || z === min.z || z === max.z;
198
+ let target = stateId;
199
+ if (!edge && mode === 'hollow')
200
+ target = 0;
201
+ if (!edge && mode === 'outline')
202
+ continue;
203
+ if (filter && !(0, blockArgument_1.blockMatchesArgument)(mcData, filter, await world.getBlockStateId(position)))
204
+ continue;
205
+ if (await placeBlock(world, position, target, mode === 'keep' ? 'keep' : mode === 'destroy' ? 'destroy' : 'replace'))
206
+ changes++;
150
207
  }
151
208
  }
152
209
  }
153
- },
210
+ return changes ? `Successfully filled ${changes} block(s)` : 'No blocks were filled';
211
+ }
154
212
  });
155
213
  // serv.commands.add({
156
214
  // base: 'clone',
@@ -165,17 +223,24 @@ const server = function (serv, { version }) {
165
223
  // })
166
224
  serv.commands.add({
167
225
  base: 'testforblock',
168
- info: '',
226
+ info: 'test whether a block (and the properties given) is at a position',
169
227
  op: true,
170
- usage: '/testforblock',
228
+ usage: '/testforblock <x> <y> <z> <block>[property=value,...]',
171
229
  tab: ['blockX', 'blockY', 'blockZ', 'block'],
172
- parse(string, ctx) {
173
- return string.split(' ');
230
+ parse(str) {
231
+ const args = (0, commandArgs_1.splitCommandArgs)(str);
232
+ if (args.length < 4)
233
+ return false;
234
+ return args;
174
235
  },
175
- action([blockX, blockY, blockZ, block, blockStates], ctx) {
176
- const pos = new vec3_1.Vec3(+blockX, +blockY, +blockZ); // todo relative eg testforblock ~ ~-1 ~ jukebox
177
- const worldBlock = ctx.player.world.getBlock(pos);
178
- return !!worldBlock;
236
+ async action(args, ctx) {
237
+ const { world, origin } = commandWorld(ctx);
238
+ const position = parsePosition(args.slice(0, 3), origin);
239
+ const expected = parseBlock(args[3]);
240
+ const actual = await world.getBlockStateId(position);
241
+ if (postFlatenning ? (0, blockArgument_1.blockMatchesArgument)(mcData, expected, actual) : actual >> 4 === expected.block.id)
242
+ return 'Successfully found the block';
243
+ throw new user_error_1.default(`The block at ${position.x}, ${position.y}, ${position.z} is not ${args[3]}`);
179
244
  }
180
245
  });
181
246
  };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,91 @@
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
+ const vitest_1 = require("vitest");
7
+ const vec3_1 = require("vec3");
8
+ const minecraft_data_1 = __importDefault(require("minecraft-data"));
9
+ const command_1 = __importDefault(require("../command"));
10
+ const blocks_1 = require("./blocks");
11
+ const VERSION = '1.20.1';
12
+ const mc = (0, minecraft_data_1.default)(VERSION);
13
+ /** the block commands on a fake server: an in-memory overworld, a player at 0 64 0 */
14
+ function setup() {
15
+ const blocks = new Map();
16
+ const key = (p) => `${p.x},${p.y},${p.z}`;
17
+ const world = {
18
+ getBlockStateId: async (p) => blocks.get(key(p)) ?? 0,
19
+ setBlockStateId: async (p, s) => { blocks.set(key(p), s); }
20
+ };
21
+ const drops = [];
22
+ const commands = new command_1.default({});
23
+ const serv = {
24
+ commands,
25
+ overworld: world,
26
+ supportFeature: (f) => f === 'theFlattening',
27
+ posFromString: (str, pos) => {
28
+ if (str.indexOf('~') === -1)
29
+ return parseFloat(str);
30
+ if (str === '~')
31
+ return pos;
32
+ return parseFloat(str.slice(1)) + pos;
33
+ },
34
+ setBlock: async (w, p, s) => w.setBlockStateId(p, s),
35
+ dropItem: (_w, _p, name) => { drops.push(name); }
36
+ };
37
+ (0, blocks_1.server)(serv, { version: VERSION });
38
+ const player = { world, position: new vec3_1.Vec3(0.5, 64, 0.5), op: true };
39
+ const run = async (cmd) => commands.use(cmd, { player });
40
+ const at = (x, y, z) => blocks.get(`${x},${y},${z}`) ?? 0;
41
+ const state = (name, props = {}) => {
42
+ const block = mc.blocksByName[name];
43
+ const PrismarineBlock = require('prismarine-block')(VERSION);
44
+ return Object.keys(props).length ? PrismarineBlock.fromProperties(block.id, props, 0).stateId : block.defaultState;
45
+ };
46
+ return { run, at, state, drops, blocks };
47
+ }
48
+ (0, vitest_1.test)('/setblock takes block states, relative coordinates and the minecraft: prefix', async () => {
49
+ const { run, at, state } = setup();
50
+ await run('setblock 1 2 3 ladder[facing=west]');
51
+ (0, vitest_1.expect)(at(1, 2, 3)).toBe(state('ladder', { facing: 'west', waterlogged: false }));
52
+ await run('setblock ~1 ~ ~-2 minecraft:redstone_wire[power=15,east=side]');
53
+ (0, vitest_1.expect)(at(1, 64, -2)).toBe(state('redstone_wire', { power: 15, east: 'side', north: 'none', south: 'none', west: 'none' }));
54
+ await run('setblock 0 0 0 furnace[ lit = true , facing = south ]');
55
+ (0, vitest_1.expect)(at(0, 0, 0)).toBe(state('furnace', { lit: true, facing: 'south' }));
56
+ });
57
+ (0, vitest_1.test)('/setblock keep, destroy, and errors that say what is wrong', async () => {
58
+ const { run, at, state, drops } = setup();
59
+ await run('setblock 1 2 3 stone');
60
+ (0, vitest_1.expect)(await run('setblock 1 2 3 dirt keep')).toEqual({ success: 'Could not set the block' });
61
+ (0, vitest_1.expect)(at(1, 2, 3)).toBe(state('stone'));
62
+ await run('setblock 1 2 3 dirt destroy');
63
+ (0, vitest_1.expect)(at(1, 2, 3)).toBe(state('dirt'));
64
+ (0, vitest_1.expect)(drops).toEqual(['stone']);
65
+ await (0, vitest_1.expect)(run('setblock 1 2 3 ladder[facing=up]')).rejects.toThrow(/allowed: north, south, west, east/);
66
+ await (0, vitest_1.expect)(run('setblock 1 2 3 nope')).rejects.toThrow(/Unknown block "nope"/);
67
+ await (0, vitest_1.expect)(run('setblock 1 2 3 stone sideways')).rejects.toThrow(/Unknown mode/);
68
+ (0, vitest_1.expect)(await run('setblock 1 2')).toMatch(/^Usage: \/setblock/);
69
+ });
70
+ (0, vitest_1.test)('/fill places the block (not air), hollow / outline / replace filter, volume limit', async () => {
71
+ const { run, at, state } = setup();
72
+ (0, vitest_1.expect)(await run('fill 0 0 0 2 2 2 glass')).toEqual({ success: 'Successfully filled 27 block(s)' });
73
+ (0, vitest_1.expect)(at(1, 1, 1)).toBe(state('glass'));
74
+ await run('fill 0 0 0 2 2 2 stone hollow');
75
+ (0, vitest_1.expect)(at(0, 0, 0)).toBe(state('stone'));
76
+ (0, vitest_1.expect)(at(1, 1, 1)).toBe(0);
77
+ await run('fill 0 0 0 2 2 2 oak_log[axis=x] replace stone');
78
+ (0, vitest_1.expect)(at(2, 2, 2)).toBe(state('oak_log', { axis: 'x' }));
79
+ (0, vitest_1.expect)(at(1, 1, 1)).toBe(0); // air was not stone, the filter skipped it
80
+ await run('fill 5 0 0 7 2 2 dirt outline');
81
+ (0, vitest_1.expect)(at(6, 1, 1)).toBe(0);
82
+ (0, vitest_1.expect)(at(5, 1, 1)).toBe(state('dirt'));
83
+ await (0, vitest_1.expect)(run('fill 0 0 0 100 100 100 stone')).rejects.toThrow(/Too many blocks/);
84
+ });
85
+ (0, vitest_1.test)('/testforblock compares the block and the written properties', async () => {
86
+ const { run } = setup();
87
+ await run('setblock 1 2 3 ladder[facing=west]');
88
+ (0, vitest_1.expect)(await run('testforblock 1 2 3 ladder')).toEqual({ success: 'Successfully found the block' });
89
+ (0, vitest_1.expect)(await run('testforblock 1 2 3 ladder[facing=west]')).toEqual({ success: 'Successfully found the block' });
90
+ await (0, vitest_1.expect)(run('testforblock 1 2 3 ladder[facing=east]')).rejects.toThrow(/is not ladder\[facing=east\]/);
91
+ });