/* eslint-disable camelcase */ /* eslint-disable @typescript-eslint/ban-types */ import type { GAMEMODES, JSONTextComponent, NBTSerializable, Range, RootNBT, SymbolEntity } from 'sandstone/arguments' import type { PredicateClass, SandstoneCore, TagClass } from 'sandstone/core' import type { SandstonePack } from 'sandstone/pack' import { nbtResolver, ResolvedNBT } from 'sandstone/variables/nbt/NBTs' import { rangeParser } from 'sandstone/variables/parsers' import * as util from 'util' import type { Macroable } from '../core/Macro' import { formatDebugString, type LiteralUnion } from '../utils' import type { ConditionClass, ConditionTextComponentClass, SelectorPickClass } from './abstractClasses' import type { LabelClass } from './Label' import type { NotNBT } from './nbt/NBTs' type ScoreArgument = Record> type AdvancementsArgumentValue = boolean | [string, boolean] | [string, boolean][] type AdvancementsArgument = Record> // Basic Keys type EntityKey = keyof SymbolEntity type NegatedEntityKey = `!${EntityKey}` // Tag Strings (e.g., "#skeleton" or "!#skeleton") type TagString = `#${string}` type NegatedTagString = `!#${string}` type NonEmptyList = (readonly T[] & { readonly 0: T }) // The List Type: Can ONLY contain negated keys or negated tags type NegatedList = NonEmptyList // The Master Selector Type export type SelectorEntityType = ( | EntityKey | NegatedEntityKey | TagString | NegatedTagString | TagClass<'entity_type'> | NegatedList ) /** * Helper: Detects if T involves a Tag in any way. * This triggers if T is a Tag string, a TagClass, or a List containing a Tag string. */ type IsTagInvolved = T extends TagString | NegatedTagString | TagClass ? true : ( T extends readonly any[] ? Extract extends never ? false : true : false ) /** * Helper: Unwrap a Negation String to get the Key. * "!arrow" -> "arrow" */ type UnwrapNegation = T extends `!${infer K}` ? K : never /** * The Main Resolver: * 1. If a Tag is involved -> Return SymbolEntity<'%fallback'> * 2. If it's a List -> Exclude all keys found in the list from the total Map. * 3. If it's a Negated Key -> Exclude that key. * 4. If it's a Positive Key -> Return that specific type. */ export type ResolveEntityValues = IsTagInvolved extends true ? SymbolEntity<'%fallback'> : ( T extends NegatedList // It is a list of Negated Keys (we know no tags are here because of IsTagInvolved check) // We exclude the unwrapped keys from the full set. ? SymbolEntity[Exclude>] : T extends NegatedEntityKey // Single Negation ? SymbolEntity[Exclude>] : T extends EntityKey // Single Positive Key ? SymbolEntity[T] : never ) type TypeOrArray = T | T[] /** * If MustBeSingle is false, then anything is allowed. * If it is true, then you must provide limit=1 or limit=0. * * If MustBePlayer is false, any entity is allowed. * If it is true, then you must provide `type` of `minecraft:player`. */ export type SelectorProperties< MustBeSingle extends boolean, MustBePlayer extends boolean, EntityType extends SelectorEntityType = '#fallback', MACRO extends boolean = false, > = ( { /** * Filter target selection based on their Euclidean distances from some point, * searching for the target's feet (a point at the bottom of the center of their hitbox). * * If the positional arguments `x`, `y` and `z` are left undefined, * radius is calculated relative to the position of the command's execution. * * Only unsigned values are allowed. */ distance?: Macroable, MACRO> /** Filter target selection based on their scores in the specified objectives. */ scores?: Macroable, MACRO> /** * Filter target selection to those who are on a given team. * * Allowed values are: * - `teamName`, to filter those who are in the given team. * - `!teamName`, to filter those who are not in the given team. * - `false`, to filter those who are teamless (in no team). * - `true`, ot filter those who have at least one team. */ team?: Macroable /** * Filter target selection to those that have the given tag(s). * * Multiple values are allowed, when passed as an array. * * @example * * Selector(`@e`, { tag: 'alive' }) => `@e[tag=alive]` * * Selector(`@e`, { tag: ['alive', 'winner'] }) => `@e[tag=alive, tag=winner]` * */ tag?: Macroable, MACRO> /** Filter target selection to all those with a given name. This cannot be a JSON text compound. */ name?: Macroable /** * Specify the targets selection priority. * * - `nearest`: Sort by increasing distance. (Default for `@p`) * - `furthest`: Sort by decreasing distance. * - `random`: Sort randomly. (Default for `@r`) * - `arbitrary`: Do not sort. (Default for `@e`, `@a`) */ sort?: 'nearest' | 'furthest' | 'random' | 'arbitrary' /** Filter target selection based on their experience levels. This naturally filters out all non-player targets. */ level?: Macroable, MACRO> /** Filter target selection to those who are in the specified game mode. */ gamemode?: Macroable | `!${GAMEMODES}`[], MACRO> /** * Filter target selection based on their vertical rotation, measured in degrees. * * Values range from `-90` (straight up) to `0` (at the horizon) to `+90` (straight down). */ x_rotation?: Macroable, MACRO> /** * Filter target selection based on their rotation in the horizontal XZ-plane, * measured clockwise in degrees from due south (or the positive Z direction). * * Values vary: * - from `-180` (facing due north, the -Z direction) * - to `-90` (facing due east, the +X direction) * - to `0` (facing due south, the +Z direction) * - to `+90` (facing due west, the -X direction) * - to `+180` (facing due north again). */ y_rotation?: Macroable, MACRO> /** Select all targets that match the specified advancement and value. */ advancements?: Macroable /** Select all targets that match the specified predicate. */ predicate?: Macroable /** Select all targets that have the specified NBT. */ nbt?: Macroable ) ) >, MACRO> /** * Define a position on the X-axis in the world the selector starts at, * for use with the `distance` argument or the volume arguments, `dx`, `dy` and `dz`. */ x?: Macroable /** * Define a position on the Y-axis in the world the selector starts at, * for use with the `distance` argument or the volume arguments, `dx`, `dy` and `dz`. */ y?: Macroable /** * Define a position on the Z-axis in the world the selector starts at, * for use with the `distance` argument or the volume arguments, `dx`, `dy` and `dz`. */ z?: Macroable /** * Filter target selection based on their x-difference, from some point, * as measured from the closest corner of the entities' hitboxes */ dx?: Macroable /** * Filter target selection based on their y-difference, from some point, * as measured from the closest corner of the entities' hitboxes */ dy?: Macroable /** * Filter target selection based on their z-difference, from some point, * as measured from the closest corner of the entities' hitboxes */ dz?: Macroable } & ( MustBeSingle extends true ? { limit: Macroable<0 | 1, MACRO> } : { limit?: Macroable } ) & ( MustBePlayer extends true ? { /** * Filter target selection to those of a specific entity type. * * Multiple values are allowed, when passed as an array. * * @example * * Selector(`@e`, { type: 'minecraft:cow' }) => `@e[type=!minecraft:cow]` * * Selector(`@e`, { type: ['!minecraft:cow', '!minecraft:skeleton'] }) => `@e[type=!minecraft:cow, type=!minecraft:skeleton]` */ type: 'minecraft:player' | 'player' } : { /** * Filter target selection to those of a specific entity type. * * Multiple values are allowed, when passed as an array. * * @example * * Selector(`@e`, { type: 'minecraft:cow' }) => `@e[type=minecraft:cow]` * * Selector(`@e`, { type: ['!minecraft:cow', '!minecraft:skeleton'] }) => `@e[type=!minecraft:cow, type=!minecraft:skeleton]` */ type?: EntityType } ) ) // Returns the string representation of a score argument. `{ myScore: [0, null] } => {myScore=0..}`, `{ myScore: [-Infinity, 5] } => {myScore='..5'}`, 8 => '8' function parseScore(core: SandstoneCore, scores: ScoreArgument): string { return `{${Object.entries(scores) .map(([scoreName, value]) => [scoreName, rangeParser(core, value)].join('=')) .join(', ')}}` } // Returns the string representation of advancements function parseAdvancements(advancements: AdvancementsArgument): string { return `{${Object.entries(advancements) .map(([advancementName, value]) => { if (typeof value === 'boolean') { return [advancementName, value].join('=') } if (Array.isArray(value)) { if (Array.isArray(value[0])) { return [ advancementName, `{${value.map((_value) => (_value as [string, boolean]).join('=')).join(',')}}`, ].join('=') } return [advancementName, `{${value.join('=')}}`].join('=') } return [advancementName, parseAdvancements(value)].join('=') }) .join(', ')}}` } /** * The readonly phantom brands make these parameters covariant. Declaring that * explicitly avoids walking SelectorProperties' generated entity/NBT graph. */ export class SelectorClass< out MACRO extends boolean = false, out IsSingle extends boolean = false, out IsPlayer extends boolean = false, > implements ConditionTextComponentClass, SelectorPickClass, ConditionClass, NBTSerializable { declare readonly __textComponentClassBrand: true declare readonly __conditionClassBrand: true /** * Phantom brand property for TypeScript to distinguish between different * SelectorClass type parameter combinations. Does not exist at runtime. */ declare readonly __selectorBrand: { macro: MACRO; single: IsSingle; player: IsPlayer } /** * Phantom brand property required by SelectorPickClass interface. * Does not exist at runtime. */ declare readonly __selectorPickBrand: { single: IsSingle; player: IsPlayer } arguments: SelectorProperties /** * Whether the most recent `toString()` produced a selector string containing * any `$(...)` macro substitution. `CommandNode.getValue()` reads this so it * can flag the surrounding command as a macro command (prefixed with `$`), * even though `toString()` itself returns a plain string (the `$(...)` is * baked in via template literal coercion). * * @internal */ _hasMacro = false constructor( protected sandstonePack: SandstonePack, public target: '@s' | '@p' | '@a' | '@e' | '@n' | '@r', selectorArguments?: SelectorProperties, ) { this.arguments = selectorArguments ?? ({} as SelectorProperties) } // Custom actions // /** * List all scores of this entity. */ listScores = () => { this.sandstonePack.commands.scoreboard.players.list(this.toString()) } toString() { if (!this.arguments || !Object.keys(this.arguments).length) { this._hasMacro = false return this.target } const result: (readonly [string, string | ResolvedNBT])[] = [] const args = { ...this.arguments } const modifiers = { // Parse scores scores: (scores: ScoreArgument) => result.push(['scores', parseScore(this.sandstonePack.core, scores)]), // Parse potentially multiple nbt nbt: (nbt: RootNBT | RootNBT[]) => { const nbts = Array.isArray(nbt) ? nbt : [nbt] for (const nbt_ of nbts) { const resolved = nbtResolver(nbt_) if (resolved.containsMacro) { this._hasMacro = true } result.push(['nbt', resolved] as const) } }, // Parse advancements advancements: (advancements: AdvancementsArgument) => result.push(['advancements', parseAdvancements(advancements)]), // Parse potentially multiple tags tag: (tag: string | string[]) => { const tags = Array.isArray(tag) ? tag : [tag] result.push(...tags.map((tag_) => ['tag', tag_] as const)) }, // Parse potentially multiple gamemodes gamemode: (gamemode: string | string[]) => { const gamemodes = Array.isArray(gamemode) ? gamemode : [gamemode] result.push(...gamemodes.map((gamemode_) => ['gamemode', gamemode_] as const)) }, // Parse potentially multiple predicates predicate: (predicate: string | string[]) => { const predicates = Array.isArray(predicate) ? predicate : [predicate] result.push(...predicates.map((pred) => ['predicate', pred] as const)) }, // Handle boolean values for teams team: (team: string | boolean) => { let teamRepr: string if (team === true) { teamRepr = '!' } else if (team === false) { teamRepr = '' } else { teamRepr = team } result.push(['team', teamRepr]) }, distance: (range_: Range) => result.push(['distance', rangeParser(this.sandstonePack.core, range_)]), } as const Object.entries(args).forEach(([key_, value]) => { const key = key_ as Extract if (key in modifiers) { const modifierName = key as keyof typeof modifiers modifiers[modifierName](value as any) } else if (value !== undefined) { result.push([key, `${value}`]) } }) // TODO: This probably should do more than drag the type to the front const entityType = result.findIndex(([key]) => key === 'type') if (entityType !== -1) { result.unshift(...result.splice(entityType, 1)) } const predicate = result.findIndex(([key]) => key === 'predicate') if (predicate !== -1) { result.push(...result.splice(predicate, 1)) } return `${this.target}[${result.map(([key, value]) => `${key}=${value}`).join(', ')}]` } /** * @internal */ _toMinecraftCondition = () => new this.sandstonePack.conditions.Selector(this.sandstonePack.core, this.toString()) /** * @internal */ _toChatComponent(): JSONTextComponent { return { type: 'selector', selector: this.toString(), } } /** * @internal */ _toSelector(): SelectorClass { // Cast is safe - the MACRO type parameter only affects type checking, // not the runtime structure of the object return this as unknown as SelectorClass } protected toJSON() { return this.toString() } toNBT() { return `'${this.toString()}'` } [util.inspect.custom]() { return formatDebugString(this.constructor.name, this.toString(), undefined, undefined) } }