import type { ANCHORS, AXES, Registry, COMPARISON_OPERATORS, Coordinates, MultipleEntitiesArgument, NBTObject, ObjectiveArgument, Range, Rotation, SingleEntityArgumentOf, SymbolBlock, SymbolMcdocBlockStates, RootNBT, } from 'sandstone/arguments' import type { ItemSlotSource } from '../world/item' import { blockStateStringifier } from '../block/setblock' import type { SandstoneCommands } from 'sandstone/commands' import { isMacroArgument, type MacroArgument, type Macroable, type MCFunctionNode, type PredicateClass, } from 'sandstone/core' import type { Node } from 'sandstone/core/nodes' import { ContainerCommandNode } from 'sandstone/core/nodes' import type { _RawMCFunctionClass } from 'sandstone/core/resources/datapack/mcfunction' import type { SandstonePack } from 'sandstone/pack' import { type AllowConst, makeCallable, type NamespacedLiteralUnion, type NonEmptyString } from 'sandstone/utils' import type { DataPointClass } from 'sandstone/variables/Data' import type { ObjectiveClass } from 'sandstone/variables/Objective' import type { ItemPredicateClass } from 'sandstone/variables/ItemPredicate' import { coordinatesParser, rangeParser, rotationParser, targetParser } from 'sandstone/variables/parsers' import { nbtResolver } from 'sandstone/variables' import type { Score } from 'sandstone/variables/Score' import { CommandArguments, FinalCommandOutput } from '../../helpers' import { FunctionCommandNode } from '../server/function' // Execute command export type SubCommand = [subcommand: string, ...args: unknown[]] type ParseLiteral = ( T extends 'true' | 'false' ? boolean : T extends `${infer N extends number}` ? N : T ) type ParseBlockState = { [K in keyof T]: ParseLiteral } type BlockEntity = NamespacedLiteralUnion type BlockStatic = NamespacedLiteralUnion> // Yes these suck const isObjective = (arg: any): arg is ObjectiveClass => typeof arg === 'object' && Object.hasOwn(arg, 'reset') const isScore = (arg: any): arg is Score => typeof arg === 'object' && Object.hasOwn(arg, 'setDisplay') export class ExecuteCommandPart extends CommandArguments { protected NodeType = ExecuteCommandNode /** * @internal */ nestedExecute = (args: SubCommand, executable = true) => this.subCommand([args], ExecuteCommand, executable) } export type StoreType = 'byte' | 'short' | 'int' | 'long' | 'float' | 'double' export type RelationType = | 'attacker' | 'controller' | 'leasher' | 'origin' | 'owner' | 'passengers' | 'target' | 'vehicle' export class ExecuteCommandNode extends ContainerCommandNode { command = 'execute' as const /** * Is being used by internals to generate a function call. (eg. Flow visitor) */ isFake: boolean /** * By default, the execute is treated as single (execute.run.stuff). * This is set to `false` if the execute is used as a function (execute.run(() => { stuff })). */ isSingleExecute: boolean /** * In case of a multiple execute, this specifies the base name of the MCFunction. */ givenCallbackName: string | undefined /** * If set, the child function created by createMCFunction will be called with * `function with storage `. This enables macro variables * from the storage to be used in the execute command. */ macroStorage: DataPointClass | undefined /** * If true, this execute node should be committed to its parent context after its body receives a command. * This is set when .run is accessed and the execute hasn't been committed yet. */ pendingCommit: boolean /** * The MCFunction created by createMCFunction, if any. * Used by LoopArgument to reference the loop function. */ createdMCFunction: _RawMCFunctionClass | null = null constructor( sandstonePack: SandstonePack, isMacro: boolean = false, args: SubCommand[] = [], { isFake = false, isSingleExecute = true, givenCallbackName = undefined as string | undefined, body = [] as Node[], macroStorage = undefined as DataPointClass | undefined, pendingCommit = false, } = {}, ) { super(sandstonePack, ...args) this.givenCallbackName = givenCallbackName this.isSingleExecute = isSingleExecute this.isFake = isFake this.macroStorage = macroStorage this.pendingCommit = pendingCommit this.isMacro = isMacro this.append(...body) } get callbackName() { return this.givenCallbackName ?? `execute_${this.args[0][0].split(' ')[0]}` } append = (...nodes: Node[]) => { for (const node of nodes) { this.body.push(node) if (this.isSingleExecute) { // Exit context first so the parent context becomes current this.sandstoneCore.getCurrentMCFunctionOrThrow().exitContext() // If this execute was pending commit (from .run access), commit it now to the parent context if (this.pendingCommit && !this.commited) { this.commit() } } } return (nodes.length === 1 ? nodes[0] : nodes) as any } getValue = () => { if (this.body.length > 1) { throw new Error('Execute nodes can only have one child node when toString is called.') } if (this.sandstoneCore.commandSerializationDepth === 0) { this.sandstoneCore.macroAlreadyUsed = false } this.sandstoneCore.commandSerializationDepth++ // This will be the execute string without "run" const flattenedArgs = this.args.flat(1) const args = [] for (const arg of flattenedArgs) { if (arg !== undefined && arg !== null) { // Yes these are cursed, unfortunately, there's not really a better way to do this as visitors only visit the root nodes. if (typeof arg === 'object') { if (isMacroArgument(this.sandstoneCore, arg)) { this.isMacro = true this.sandstoneCore.macroAlreadyUsed = true args.push((arg as MacroArgument).toMacro()) } else { args.push(arg) } } else { args.push(arg) } } } const executeString = `${this.command} ${args.join(' ')}` if (this.body.length === 0) { this.sandstoneCore.commandSerializationDepth-- return executeString } let command = this.body[0].getValue() // Yes this is cursed if (this.isFake) { this.sandstoneCore.commandSerializationDepth-- return command } if (command.startsWith('$')) { this.isMacro = true command = command.slice(1) } this.sandstoneCore.commandSerializationDepth-- return `${this.isMacro ? '$' : ''}${executeString} run ${command}` } createMCFunction = (currentMCFunction: MCFunctionNode | null) => { if (this.createdMCFunction) { // This is sus, but was needed. Ideally createMCFunction wouldn't be called multiple times at all. return { node: this as ExecuteCommandNode, mcFunction: this.createdMCFunction.node } } if (this.isSingleExecute || !currentMCFunction) { return { node: this as ExecuteCommandNode } } // Create a new MCFunctionNode with the body of the ExecuteNode. const mcFunction = this.sandstonePack.MCFunction(`${currentMCFunction.resource.name}/${this.callbackName}`, { creator: 'sandstone', onConflict: 'rename', }) const mcFunctionNode = mcFunction.node mcFunctionNode.body = this.body // Update each WithClass' containing MCFunction — the original caller // captured at construction time is stale now that the nodes live in // the new wrapper. for (const node of this.body) { if (node && typeof node === 'object' && 'containingMCFunction' in node) { ;(node as { containingMCFunction: MCFunctionNode | null }).containingMCFunction = mcFunctionNode } } // Store reference to the created MCFunction (used by LoopArgument) this.createdMCFunction = mcFunction // Return an execute calling this MCFunction. const mcFunctionCall = new FunctionCommandNode(this.sandstonePack, mcFunction) // If macroStorage is set, call the function with `with storage ` if (this.macroStorage) { mcFunctionCall.args.push('with', 'storage', this.macroStorage.currentTarget, this.macroStorage.path as NonEmptyString) } this.body = [mcFunctionCall] return { node: this as ExecuteCommandNode, mcFunction: mcFunctionNode } } } export class ExecuteStoreArgsCommand extends ExecuteCommandPart { /** * Saves the final command's return value as tag data within a block entity. * * Store as a byte, short, int, long, float, or double. If the return value is a decimal, it is rounded first and then multiplied by `scale`. * * @param targetPos Position of target block * * @param path Location of the desired tag to hold the value in. * * @param type Desired data size/type. * * @param scale Multiplier to apply before storing value. Defaults to 1. */ block = ( targetPos: Macroable, MACRO>, path: Macroable, type: Macroable, scale?: Macroable, ) => this.nestedExecute(['block', coordinatesParser(targetPos), path, type, scale]) /** * Saves the final command's return value in either a bossbar's current value or its maximum value. * * @param id ID of the bossbar to target for saving. * * @param type Whether to overwrite the bossbar's current value or its max value. */ bossbar = (id: Macroable, type: Macroable<'max' | 'value', MACRO>) => this.nestedExecute(['bossbar', id, type]) /** * Save the final command's return value in one of an entity's data tags. * * Store as a byte, short, int, long, float, or double. If the return value is a decimal, it is rounded first and then multiplied by `scale`. * * Like the `/data` command, `/execute store ` cannot modify player NBT. * * @param target A single entity to store under. * * @param path Location of the desired tag to hold the value in. * * @param type Desired data size/type. * * @param scale Multiplier to apply before storing value. Defaults to 1. */ entity = ( target: Macroable, MACRO>, path: Macroable, type: Macroable, scale?: Macroable, ) => this.nestedExecute(['entity', targetParser(target), path, type, scale]) /** * Overrides the given scores with the final command's return value. * * @param targets Specifies score holder(s) whose score is to be overridden. * * @param objective A scoreboard objective. */ score( targets: Macroable, MACRO>, objective: Macroable, ): ExecuteCommand /** * Overrides the given score with the final command's return value. * * @param score The score to override. */ score(score: Score): ExecuteCommand score(...args: any[]) { const finalArgs: SubCommand = ['score'] if (isScore(args[0])) { finalArgs.push(args[0].target, args[0].objective.name) } else { finalArgs.push(targetParser(args[0]), args[1]) } return this.nestedExecute(finalArgs) } /** * Uses the `path` within storage `target` to store the return value in. * * Store as a byte, short, int, long, float, or double. If the return value is a decimal, it is rounded first and then multiplied by `scale`. * * If the storage does not yet exist, it gets created. * * @param target Target storage container, as a namespaced ID. * * @param path Location of the desired tag to hold the value in. * * @param type Desired data size/type. * * @param scale Multiplier to apply before storing value. Defaults to 1. */ storage = ( target: Macroable, path: Macroable, type: Macroable, scale: Macroable = 1, ) => this.nestedExecute(['storage', target, path, type, scale]) } type DropFirstArg = ( T extends { (first: any, ...args: infer A1): infer R1 (first: any, ...args: infer A2): infer R2 } ? { (...args: A1): R1 (...args: A2): R2 } : never ) export class ExecuteStoreCommand extends ExecuteCommandPart { _storeCallable(cmd: ExecuteStoreArgsCommand, score: Score): ExecuteCommand _storeCallable(cmd: ExecuteStoreArgsCommand, dataPoint: DataPointClass<'entity'> | DataPointClass<'block'> | DataPointClass<'storage'>, type?: Macroable, scale?: Macroable): ExecuteCommand _storeCallable( cmd: ExecuteStoreArgsCommand, target: DataPointClass<'entity'> | DataPointClass<'block'> | DataPointClass<'storage'> | Score, type?: Macroable, scale?: Macroable, ): ExecuteCommand { if (isScore(target)) { return cmd.score(target.target, target.objective) } const resolvedType = type ?? 'int' if (target.type === 'block') { return cmd.block(coordinatesParser(target.currentTarget) as Macroable, MACRO>, target.path, resolvedType, scale) } if (target.type === 'entity') { /* @ts-ignore */ return cmd.entity(target.currentTarget as Macroable, target.path, resolvedType, scale) as unknown as ExecuteCommand } return cmd.storage(target.currentTarget as Macroable, target.path, resolvedType, scale) } /** Store the final command's result value. */ get result() { const cmd = this.subCommand([['result']], ExecuteStoreArgsCommand, false) return makeCallable(cmd, ( target: DataPointClass<'entity'> | DataPointClass<'block'> | DataPointClass<'storage'> | Score, type?: Macroable, scale?: Macroable, ) => this._storeCallable(cmd, target as any, type, scale), true) as ExecuteStoreArgsCommand & DropFirstArg['_storeCallable']> } /** Store the final command's success value. */ get success() { const cmd = this.subCommand([['success']], ExecuteStoreArgsCommand, false) return makeCallable(cmd, ( target: DataPointClass<'entity'> | DataPointClass<'block'> | DataPointClass<'storage'> | Score, type?: Macroable, scale?: Macroable, ) => this._storeCallable(cmd, target as any, type, scale), true) as ExecuteStoreArgsCommand & DropFirstArg['_storeCallable']> } } export class ExecuteDataArgsCommand extends ExecuteCommandPart { /** * Checks whether the targeted block has any data for a given tag * @param pos Position of the block to be tested. * @param path Data tag to check for. */ block = (pos: Macroable, MACRO>, path: Macroable) => this.nestedExecute(['data', 'block', coordinatesParser(pos), path], true) /** * Checks whether the targeted entity has any data for a given tag * @param target One single entity to be tested. * @param path Data tag to check for. */ entity = (target: Macroable, MACRO>, path: Macroable) => this.nestedExecute(['data', 'entity', targetParser(target), path], true) /** * Checks whether the targeted storage has any data for a given tag * @param source The storage to check in. * @param path Data tag to check for. */ storage = (source: Macroable, path: Macroable) => this.nestedExecute(['data', 'storage', source, path], true) } /** * Item predicate for matching items in inventory slots. * * Can be a string (item ID, item tag, or item ID with component predicates) * or an ItemPredicateClass built using the `items()` function. * * @example * ```ts * // String format * 'minecraft:diamond' * '#minecraft:logs' * 'minecraft:diamond_sword[minecraft:enchantments~{sharpness:5}]' * * // Builder format * ItemPredicate('minecraft:diamond_sword').match('minecraft:enchantments', [...]) * ``` */ export type ItemPredicate = string | ItemPredicateClass export class ExecuteItemsCommand extends ExecuteCommandPart { /** * Test for items in a block entity's inventory slots. * * @param sourcePos Position of the block entity to test. * * @param slotSource Slot source (e.g., `'container.*'`, `'container.0'`, inline slot source, or a slot source reference). * * @param itemPredicate Item predicate to match against. * * @example * ```ts * // Check if chest has any diamonds * execute.if.items.block(abs(0, 64, 0), 'container.*', 'minecraft:diamond') * * // Check for specific slot * execute.if.items.block(abs(0, 64, 0), 'container.0', '#minecraft:logs') * * // Using builder for complex predicates * execute.if.items.block(abs(0, 64, 0), 'container.*', * ItemPredicate('minecraft:diamond_sword').match('minecraft:enchantments', [...]) * ) * ``` */ block = ( sourcePos: Macroable, MACRO>, slotSource: Macroable, itemPredicate: Macroable, ) => this.nestedExecute(['items', 'block', coordinatesParser(sourcePos), slotSource, `${itemPredicate}`], true) /** * Test for items in an entity's inventory slots. * * @param source Entity to test. * * @param slotSource Slot source (e.g., `'inventory.*'`, `'hotbar.0'`, inline slot source, or a slot source reference). * * @param itemPredicate Item predicate to match against. * * @example * ```ts * // Check if player has any diamonds * execute.if.items.entity('@p', 'inventory.*', 'minecraft:diamond') * * // Check hotbar for tools * execute.if.items.entity('@s', 'hotbar.*', '#minecraft:tools') * * // Check for enchanted sword with builder * execute.if.items.entity('@p', 'weapon.mainhand', * ItemPredicate('minecraft:diamond_sword').has('minecraft:enchantments') * ) * * // Count items using store * execute.store.result(score).if.items.entity('@p', 'inventory.*', * ItemPredicate('*').match('minecraft:damage', { durability: { max: 10 } }) * ) * ``` */ entity = ( source: Macroable, MACRO>, slotSource: Macroable, itemPredicate: Macroable, ) => this.nestedExecute(['items', 'entity', targetParser(source), slotSource, `${itemPredicate}`], true) } /** * Command for the `execute if|unless slots` condition sub-command. * * Counts the number of slots from the slot source that are present on the targeted block or entity. * Slot sources are evaluated with the `minecraft:command_slot_source` loot type. */ export class ExecuteSlotsCommand extends ExecuteCommandPart { /** * Count slots from a slot source that are present in a block entity. * * @param sourcePos Position of the block entity to test. * * @param slotSource Slot source (e.g., `'container.*'`, inline slot source, or a slot source reference). * * @example * ```ts * // Count slots in a chest matching a slot source * execute.if.slots.block(abs(0, 64, 0), 'container.*') * execute.if.slots.block(abs(0, 64, 0), { type: 'minecraft:slot_range', slots: 'armor.chest' }) * ``` */ block = ( sourcePos: Macroable, MACRO>, slotSource: Macroable, ) => this.nestedExecute(['slots', 'block', coordinatesParser(sourcePos), slotSource], true) /** * Count slots from a slot source that are present in an entity. * * @param source Entity to test. * * @param slotSource Slot source (e.g., `'inventory.*'`, inline slot source, or a slot source reference). * * @example * ```ts * // Count slots on a player matching a slot source * execute.if.slots.entity('@p', 'inventory.*') * execute.if.slots.entity('@p', { type: 'minecraft:slot_range', slots: 'weapon.mainhand' }) * ``` */ entity = ( source: Macroable, MACRO>, slotSource: Macroable, ) => this.nestedExecute(['slots', 'entity', targetParser(source), slotSource], true) } export class ExecuteIfUnlessCommand extends ExecuteCommandPart { /** * Compares the block at a given position to a given block. * * @param pos Position of a target block to test. * @param block Block to test for (can be a tag). * @param state Optional block state properties to match. * * @example * ```ts * // Simple block check * execute.if.block(abs(0, 64, 0), 'minecraft:stone') * * // Check block with specific state * execute.if.block(abs(0, 64, 0), 'minecraft:oak_log', { axis: 'y' }) * ``` */ block>( pos: Macroable, MACRO>, block: BLOCK, state?: Macroable]>> : Record, MACRO>, ): ExecuteCommand /** * Compares the block at a given position to a given block with NBT data. * * @param pos Position of a target block to test. * @param block Block to test for (must be a block entity). * @param state Optional block state properties to match. * @param nbt NBT data to match against the block entity. * * @example * ```ts * // Check chest with specific NBT * execute.if.block(abs(0, 64, 0), 'minecraft:chest', { facing: 'north' }, { Items: [] }) * * // Check command block * execute.if.block(['~', '~', '~1'], 'minecraft:command_block', {}, { Command: 'say Hello' }) * ``` */ block>( pos: Macroable, MACRO>, block: BLOCK, state: Macroable]>> : Record | undefined, MACRO>, nbt: Macroable]>> : AllowConst, MACRO>, ): ExecuteCommand block( pos: Macroable, MACRO>, block: Macroable, state?: Macroable, MACRO>, nbt?: Macroable, MACRO>, ) { const stateStr = state && typeof state === 'object' && Object.keys(state).length > 0 ? blockStateStringifier(state as Record) : '' const nbtStr = nbt ? nbtResolver(nbt as NBTObject).toString() : '' return this.nestedExecute(['block', coordinatesParser(pos), `${block}${stateStr}${nbtStr}`], true) } /** * Compares the blocks in two equally sized volumes. * @param start Start position of the first volume. * @param end End position of the first volume. * @param destination Start position of the second volume. * @param scan_mode Specifies whether all blocks in the source volume should be compared, or if air blocks should be masked/ignored */ blocks = ( start: Macroable, MACRO>, end: Macroable, MACRO>, destination: Macroable, MACRO>, scan_mode: Macroable<'all' | 'masked', MACRO>, ) => this.nestedExecute( ['blocks', coordinatesParser(start), coordinatesParser(end), coordinatesParser(destination), scan_mode], true, ) /** * Checks whether one or more entities exist. * * @param targets The target entities to check. */ entity = (targets: Macroable, MACRO>) => this.nestedExecute(['entity', targetParser(targets)], true) /** * Checks whether the `predicate` evaluates to a positive result. * * @param predicate The predicate to test. */ predicate(predicate: Macroable) { if (typeof predicate === 'string') { return this.nestedExecute(['predicate', predicate], true) } if (Object.hasOwn(predicate, 'toMacro')) { return this.nestedExecute(['predicate', predicate], true) } /* @ts-ignore */ return this.nestedExecute(['predicate', predicate.name], true) } /** * Check a score against either another score or a given range. */ // eslint-disable-next-line max-len score( firstTarget: Macroable, MACRO>, firstObjective: Macroable, comparison: 'matches', value: Macroable, MACRO>, ): ExecuteCommand // eslint-disable-next-line max-len score( firstTarget: Macroable, MACRO>, firstObjective: Macroable, comparison: Macroable, otherTarget: Macroable, MACRO>, otherObjective: Macroable, ): ExecuteCommand score(firstScore: Score, comparison: 'matches', value: Macroable, MACRO>): ExecuteCommand score( firstScore: Score, comparison: Macroable, otherScore: Macroable, ): ExecuteCommand score(...args: any[]) { const finalArgs: string[] = [] if (isScore(args[0])) { finalArgs.push(args[0].target.toString(), args[0].objective.name, args[1]) if (isScore(args[2])) { finalArgs.push(args[2].target.toString(), args[2].objective.name) } else { finalArgs.push(rangeParser(this.sandstoneCore, args[2])) } } else { finalArgs.push(targetParser(args[0]), isObjective(args[1]) ? args[1].name : args[1], args[2]) if (args[4]) { finalArgs.push(targetParser(args[3]), isObjective(args[4]) ? args[4].name : args[4]) } else { finalArgs.push(rangeParser(this.sandstoneCore, args[3])) } } return this.nestedExecute(['score', ...finalArgs], true) } /** * Checks whether the current dimension matches the given one. * @param dimension Dimension to check against. */ dimension = (dimension: Macroable) => this.nestedExecute(['dimension', dimension]) /** * Checks whether the targeted block is in a chunk that is fully loaded (entity-processing chunk). * @param pos Position of target block to test. */ loaded = (pos: Macroable, MACRO>) => this.nestedExecute(['loaded', coordinatesParser(pos)]) /** Checks whether the data point exists or the targeted block, entity or storage has any data for a given tag. */ get data(): ExecuteDataArgsCommand & ((data: DataPointClass) => ExecuteCommand) { return makeCallable( new ExecuteDataArgsCommand(this.sandstonePack, this.isMacro, this.previousNode), (dataPoint: DataPointClass) => this.nestedExecute(dataPoint._toMinecraftCondition().getCondition() as ['']), ) } /** Tests for items in block entity or entity inventory slots. */ get items() { return new ExecuteItemsCommand(this.sandstonePack, this.isMacro, this.previousNode) } /** * Counts slots from a slot source that are present in a block entity or entity. * * @example * ```ts * execute.if.slots.entity('@p', 'inventory.*') * ``` */ get slots() { return new ExecuteSlotsCommand(this.sandstonePack, this.isMacro, this.previousNode) } function(func: Macroable<_RawMCFunctionClass<[], []> | (() => any) | string, MACRO>) { if (typeof func === 'object' && Object.hasOwn(func, 'addToTag')) { return this.nestedExecute(['function', (func as _RawMCFunctionClass<[], []>).name]) } /* @ts-ignore */ if (typeof func === 'string' || Object.hasOwn(func, 'toMacro')) { return this.nestedExecute(['function', func]) } const name = `${this.sandstoneCore.getCurrentMCFunctionOrThrow().resource.path.slice(2).join('/')}/execute_if_function` const _func = this.sandstonePack.MCFunction(name, { addToSandstoneCore: false, creator: 'sandstone', onConflict: 'rename', callback: func as () => void, }) return this.nestedExecute(['function', name]) } } export class ExecuteFacingEntityCommand extends ExecuteCommandPart { /** * Sets the command rotation to face a given point, as viewed from its anchor (either the eyes or the feet). * * @param targets The target(s) to rotate towards. (if you target multiple entities subcommands will run for each entity) * * @param anchor Whether to point at the target's eyes or feet. */ entity = (targets: Macroable, MACRO>, anchor: Macroable = 'feet') => this.nestedExecute(['facing', 'entity', targetParser(targets), anchor]) } export class ExecutePositionedCommand extends ExecuteCommandPart { /** * Sets the command position, without changing rotation or dimension, by matching an entity's position. * * @param targets Target entity/entities to match position with. */ as = (targets: Macroable, MACRO>) => this.nestedExecute(['positioned', 'as', targetParser(targets)]) /** * Sets the command position matching the height map (highest position in a column of blocks according to criteria) for the current position. * * - `world_surface` Any non-air block. * - `motion_blocking` Any motion blocking material (eg. ignores flowers and grass). * - `motion_blocking_no_leaves` Any non-leaf motion blocking material. * - `ocean_floor` Any non-fluid motion blocking material. */ over = ( heightMap: Macroable<'world_surface' | 'motion_blocking' | 'motion_blocking_no_leaves' | 'ocean_floor', MACRO>, ) => this.nestedExecute(['positioned', 'over', heightMap]) } export class ExecuteRotatedAsCommand extends ExecuteCommandPart { /** * Sets the command rotation, by matching an entity's rotation. * * @param targets Target entity/entities to match rotation with. */ as = (targets: Macroable, MACRO>) => this.nestedExecute(['rotated', 'as', targetParser(targets)]) } export class ExecuteCommand extends ExecuteCommandPart { protected NodeType = ExecuteCommandNode /** * Align execution position to block coordinates. * * @param axes Coordinate axes to align ('x', 'y', 'z', or combinations like 'xy'). * Floors coordinates on specified axes. * * @example * ```ts * execute.align('xyz').run.teleport('@s', rel(0, 1, 0)) // Align to block grid * execute.as('@a').align('y').run.setblock(rel(0, 0, 0), 'minecraft:stone') * ``` */ align = (axes: Macroable) => this.nestedExecute(['align', axes]) /** * Set execution anchor point. * * @param anchor Anchor position: 'eyes' or 'feet'. * Changes the reference point for `^ ^ ^` coordinates. * * @example * ```ts * execute.anchored('eyes').run.particle('minecraft:heart', abs(0, 0, 0)) * execute.as('@p').anchored('feet').run.summon('minecraft:armor_stand') * ``` */ anchored = (anchor: Macroable) => this.nestedExecute(['anchored', anchor]) /** * Change command executor. * * @param targets Entity selector to execute as. * Changes @s reference without affecting position/rotation. * * @example * ```ts * execute.as('@a').run.say('Hello from everyone!') * execute.as('@e[type=zombie]').run.damage('@s', 10) * ``` */ as = (targets: Macroable, MACRO>) => this.nestedExecute(['as', targetParser(targets)]) /** * Change execution position and rotation to match entity. * * @param targets Entity selector to copy position/rotation from. * Does not change command executor (@s). * * @example * ```ts * execute.at('@p').run.summon('minecraft:lightning_bolt') * execute.as('@a').at('@e[type=villager, limit=1]').run.teleport('@s', rel(0, 5, 0)) * ``` */ at = (targets: Macroable, MACRO>) => this.nestedExecute(['at', targetParser(targets)]) /** * Sets the command rotation to face a given point, as viewed from its anchor (either the eyes or the feet). * * @param pos Coordinate to rotate towards. */ get facing(): ExecuteFacingEntityCommand & ((pos: Macroable, MACRO>) => ExecuteCommand) { return makeCallable( new ExecuteFacingEntityCommand(this.sandstonePack, this.isMacro, this.previousNode), (pos: Macroable, MACRO>) => this.nestedExecute(['facing', coordinatesParser(pos)]), ) } /** * Sets the command dimension. * * @param dimension Name of the new execution dimension. */ in = (dimension: Macroable) => this.nestedExecute(['in', dimension]) /** * Sets the command executor to a related entity. * @param relation Relation with the current executor. */ on = (relation: Macroable) => this.nestedExecute(['on', relation]) /** * Sets the command position, without changing rotation or dimension. * * @param pos The new position. */ get positioned(): ExecutePositionedCommand & ((pos: Macroable, MACRO>) => ExecuteCommand) { return makeCallable( new ExecutePositionedCommand(this.sandstonePack, this.isMacro, this.previousNode), (pos: Macroable, MACRO>) => this.nestedExecute(['positioned', coordinatesParser(pos)]), ) } /** * Sets the command rotation. * * @param rotation The desired rotation. * * First value is measured clockwise in degrees from due south (the +Z Axis), ranging [–180 to +180) * Second value is measured as declination from the horizon in degrees, ranging [–90 to +90] (straight up to straight down) * * Relative values can be used to specify a rotation relative to the current execution rotation. */ get rotated(): ExecuteRotatedAsCommand & ((rotation: Macroable, MACRO>) => ExecuteCommand) { return makeCallable( new ExecuteRotatedAsCommand(this.sandstonePack, this.isMacro, this.previousNode), (rotation: Macroable, MACRO>) => this.nestedExecute(['rotated', rotationParser(rotation)]), ) } /** * Summons an entity at the command position and sets the command executor to said newly summoned entity. * @param entityType Entity to summon. */ summon(entityType: Macroable) { return this.nestedExecute(['summon', entityType]) } get if() { return this.subCommand([['if']], ExecuteIfUnlessCommand, false) } get unless() { return this.subCommand([['unless']], ExecuteIfUnlessCommand, false) } get store() { return this.subCommand([['store']], ExecuteStoreCommand, false) } get run() { const node = this.getNode() // Macro propagate: route command access through macroCommands when // this execute is part of a macro chain so that commands chained inside // (e.g. `Macro.returnCmd.run.functionCmd(...)`) keep `isMacro: true`. // Falling back to `this.sandstonePack.commands` (always ) silently // strips the macro flag at the proxy boundary. const commandsSource: SandstoneCommands = ((this.sandstonePack as any)[ this.isMacro ? 'macroCommands' : 'commands' ]) as SandstoneCommands const commands = new Proxy(commandsSource, { get: (_t, p, _r) => { // Mark as pending commit if not already committed // The node will be committed to its parent context when append() is called if (!node.commited) { node.pendingCommit = true } // The context will automatically be exited by the node itself this.sandstoneCore.getCurrentMCFunctionOrThrow().enterContext(node, false) return (commandsSource as any)[p] }, }) return makeCallable( commands, (...args: [callback: () => any] | [name: string, callback: () => any]) => { const callback = args.length === 1 ? args[0] : args[1] if (args.length === 2) { node.givenCallbackName = args[0] } node.isSingleExecute = false // Add node to parent context if not already committed. // Use `balanceContext`: the callback may contain // `_.await.sleep/until(...)` which calls `enterContext(this)` // and never pops itself. A single `exitContext()` here would // leave the await's wrapper on the stack, so subsequent // commands commit to the wrong body. this.sandstoneCore.balanceContext(node, callback, !node.commited) return new FinalCommandOutput(node) }, true, ) } } /** * Options for creating a deferred execute with macro storage. */ export type DeferredMacroExecuteOptions = { /** Name suffix for the child function (e.g., '__guuid_execute') */ childFunctionName: string /** * A function that receives the environment variable macro names and returns * the subcommands to prepend to the execute chain. * The envNames array contains the macro variable names in order (e.g., ['env_0', 'env_1']). */ prependArgs: (envNames: string[]) => SubCommand[] } & ( | { /** Environment variables to pass to the child function (scores, data points, etc.) */ env: MacroArgument[] macroStorage?: never } | { /** Explicit storage to use for the macro function call (e.g., '__sandstone:temp') */ macroStorage: DataPointClass env?: never } ) /** * Creates a deferred execute proxy that wraps commands in a macro-enabled child function. * * This utility allows building an execute chain without requiring MCFunction context, * then when `.run` is accessed, creates a child function called with environment variables * that are automatically converted to macro storage. * * @param pack The sandstone pack * @param executeChain An ExecuteCommand chain with autoCommit=false * @param options Configuration for the macro execute * @returns A proxy that intercepts .run and creates the macro structure * * @example * ```ts * const score = Variable() * const deferredExecute = new ExecuteCommand(pack, undefined, false) * return createDeferredMacroExecute(pack, deferredExecute, { * childFunctionName: '__my_macro', * prependArgs: (envNames) => [['as', `$(${envNames[0]})`]], * env: [score], * }) * ``` */ // Return type uses 'any' to avoid TS2859 complexity limit at call sites export function createDeferredMacroExecute( pack: SandstonePack, executeChain: ExecuteCommand, options: DeferredMacroExecuteOptions, ): any { const { childFunctionName, prependArgs } = options const createProxy = (chain: ExecuteCommand): any => { const handler: ProxyHandler = { get(_target, prop) { if (prop === 'run') { // Get the accumulated args from the deferred chain const node = (chain as any).previousNode ?? (chain as any).getNode?.() const accumulatedArgs: SubCommand[] = node?.args ?? [] const currentFunction = pack.core.getCurrentMCFunctionOrThrow() // Determine env names based on mode const envNames = 'env' in options && options.env ? options.env.map((_, i) => `env_${i}`) : [] // Create the execute node with prepended args (macro-enabled) const macroNode = new ExecuteCommandNode(pack, true, [...prependArgs(envNames), ...accumulatedArgs], { isSingleExecute: true, }) macroNode.isMacro = true // Create and call the child function based on mode let childFunctionNode: MCFunctionNode if ('env' in options && options.env) { // Mode 1: Use environment variables (auto-managed storage) const childFunction = pack.MCFunction( `${currentFunction.resource.name}/${childFunctionName}`, options.env, () => { /* Body will be added manually */ }, { creator: 'sandstone', onConflict: 'rename' }, ) // Call the child function (MCFunction with env handles the `with storage` automatically) // This also registers the env variables in the local map for macro resolution childFunction() childFunctionNode = childFunction.node } else { // Mode 2: Use explicit macro storage const childFunction = pack.MCFunction( `${currentFunction.resource.name}/${childFunctionName}`, () => { /* Body will be added manually */ }, { creator: 'sandstone', onConflict: 'rename' }, ) // Call the function with explicit storage pack.commands.functionCmd(childFunction.name, 'with', 'storage', options.macroStorage.currentTarget, options.macroStorage.path) childFunctionNode = childFunction.node } // Add the execute node directly to the function body childFunctionNode.body.push(macroNode as any) // Switch to child function context so commands go there pack.core.enterMCFunction(childFunctionNode.resource) // Enter the execute node's context so the user's command goes into its body childFunctionNode.enterContext(macroNode, false) // Track whether we've exited contexts (only do it once) let hasExited = false const exitContexts = () => { if (hasExited) return hasExited = true // Only exit if we're still in the child function context if (pack.core.currentMCFunction === childFunctionNode) { if (childFunctionNode.contextStack.length > 1) { childFunctionNode.exitContext() } pack.core.exitMCFunction() } } // Recursively wrap commands to handle multi-stage commands const wrapCommands = (target: any): any => { return new Proxy(target, { get(t, cmdProp) { const value = t[cmdProp] if (typeof value === 'function') { return (...args: any[]) => { const result = value.apply(t, args) // If result is an object with methods (command chain continues), wrap it if (result && typeof result === 'object' && typeof result.then !== 'function') { const proto = Object.getPrototypeOf(result) if (proto && proto.constructor?.name !== 'FinalCommandOutput') { return wrapCommands(result) } } // Final command reached, exit contexts exitContexts() return result } } // For getter properties that return objects, wrap them if (value && typeof value === 'object') { return wrapCommands(value) } return value }, }) } return wrapCommands(pack.commands) } // For all other properties, delegate to the underlying execute chain const result = (chain as any)[prop] if (typeof result === 'function') { return (...args: any[]) => { const nextChain = result.apply(chain, args) // If it returns an execute-like object, wrap it in a new proxy if (nextChain && typeof nextChain === 'object') { return createProxy(nextChain) } return nextChain } } // For getter properties (like .if, .store, .unless), wrap the result if (result && typeof result === 'object') { return createProxy(result) } return result }, } return new Proxy({}, handler) } return createProxy(executeChain) }