import type { JsonNBTObject, NBTObject, RootNBT } from 'sandstone/arguments' import type { MacroArgument } from 'sandstone/core' import { makeCallable } from 'sandstone/utils' import * as util from 'util' import { parseNBT } from './parser' import { _RawLabelClass } from '../Label' export abstract class NBTClass { abstract [util.inspect.custom]: () => string } export class NBTPrimitive extends NBTClass { value: number unit: Unit constructor(value: number, unit: Unit) { super() this.value = value this.unit = unit } /** * @internal */ toJSON() { return this.value } [util.inspect.custom] = () => `${this.value}${this.unit}` } export type NBTRange = { min?: number, max?: number, leftExclusive?: boolean, rightExclusive?: boolean } /* oxlint-disable no-unused-vars */ export class NBTLong extends NBTPrimitive<'l'> { constructor(value: number) { super(value, 'l') } } export class NBTByte extends NBTPrimitive<'b'> { constructor(value: number) { super(value, 'b') } } export class NBTShort extends NBTPrimitive<'s'> { constructor(value: number) { super(value, 's') } } export class NBTFloat extends NBTPrimitive<'f'> { constructor(value: number) { super(value, 'f') } } export class NBTInt extends NBTPrimitive<'i'> { constructor(value: number) { super(value, 'i') } } export class NBTDouble extends NBTPrimitive<'d'> { constructor(value: number) { super(value, 'd') } } export class NBTTypedArray extends NBTClass { values: number[] unit: string constructor(values: number[], unit: string) { super() this.values = values this.unit = unit } /** * @internal */ toJSON() { return this.values } [util.inspect.custom] = () => `[${this.unit};${this.values.length === 0 ? '' : this.values.join(',')}]` } export class NBTLongArray extends NBTTypedArray { constructor(values: number[]) { super(values, 'L') } } export class NBTByteArray extends NBTTypedArray { constructor(values: number[]) { super(values, 'B') } } export class NBTIntArray extends NBTTypedArray { constructor(values: number[]) { super(values, 'I') } } // TODO export type NBTList = Range['min'] extends 1 ? Range['leftExclusive'] extends false ? (Type[] & { 0: Type }) : Type[] : Type[] /** * `NBTList` for the generated JSON surface (`arguments/generated/_json`). * * Identical to `NBTList`, but constrained to `JsonNBTObject` so the element * type stays within that surface. */ export type JsonNBTList = Range['min'] extends 1 ? Range['leftExclusive'] extends false ? (Type[] & { 0: Type }) : Type[] : Type[] export class NotNBT extends NBTClass { nbt constructor(nbt: VALUE) { super() this.nbt = nbt } [util.inspect.custom] = () => `!${nbtResolver(this.nbt)}` } export type NBTAllNumberClasses = NBTLong | NBTShort | NBTByte | NBTFloat | NBTDouble | NBTInt export type NBTSimpleClasses = typeof NBTLong | typeof NBTShort | typeof NBTByte | typeof NBTFloat | typeof NBTDouble | typeof NBTInt export type NBTAllNumbers = NBTSimpleClasses export type NBTAllArrays = typeof NBTTypedArray | typeof NBTLongArray | typeof NBTByteArray | typeof NBTIntArray export class NBTString extends NBTPrimitive<'"'> {} export type NBTAllPrimitives = NBTAllNumbers | NBTAllArrays | typeof NBTString // Type Hack, not actually a primitive export class NBTAnyValue extends NBTPrimitive<'any'> {} export type NBTAllValues = NBTAllPrimitives | NBTAnyValue // TODO: Implement length generics and a wrapper class like Vector class with `subtracted`, `added`, `multiplied`, and `divided` function customNumber( num: T, _class: C, ): T extends number ? C : C[] { if (Array.isArray(num)) { return num.map((n) => new _class(n)) as any } return new _class(num) as any } function dynamicNBT(template: TemplateStringsArray, ...args: unknown[]): NBTObject { const mixedArgs = template.flatMap((s, i) => [s, args[i]]).slice(0, -1) // Remove the last argument, which will always be undefined const result = mixedArgs .map((element: any) => (element instanceof NBTClass ? nbtResolver(element).toString() : element.toString())) .join('') return parseNBT(NBT, result) } interface NBTInterface { /** * Transform a number into a Minecraft NBT int number. This may seem redundant, but it is necessary for strict typing. * * @param intNumber The number to transform. * * @example * summon(..., { Age: -5 }) // => { Age: -5 } * * summon(..., { Age: NBT.int(-5) }) // => { Age: -5i } */ int(intNumber: number): NBTInt /** * Transform several numbers into a an array of Minecraft NBT int numbers. This may seem redundant, but it is necessary for strict typing. * * @param intNumbers The numbers to transform. * * @example * summon(..., { Test: [0, 1, 2] }) // => { Test: [0, 1, 2] } * * summon(..., { Test: NBT.int([0, 1, 2]) }) // => { Test: [0i, 1i, 2i] } */ int(intNumbers: number[]): NBTInt[] /** * Transform a number into a Minecraft NBT float number. * * @param floatNumber The number to transform. * * @example * summon(..., { Health: 20 }) // => { Health: 20 } * * summon(..., { Health: NBT.float(20) }) // => { Health: 20f } */ float(floatNumber: number): NBTFloat /** * Transform several numbers into a an array of Minecraft NBT float numbers. * * @param floatNumbers The numbers to transform. * * @example * summon(..., { Test: [0, 1, 2] }) // => { Test: [0, 1, 2] } * * summon(..., { Test: NBT.float([0, 1, 2]) }) // => { Test: [0f, 1f, 2f] } */ float(floatNumbers: number[]): NBTFloat[] /** * Transform a number into a Minecraft NBT double number. Using this is optional. * * @param doubleNumber The number to transform. * * @example * summon(..., { Health: 20 }) // => { Health: 20 } * * summon(..., { Health: NBT.double(20) }) // => { Health: 20d } */ double(doubleNumber: number): NBTDouble /** * Transform several numbers into a an array of Minecraft NBT double numbers. Using this is optional. * * @param doubleNumbers The numbers to transform. * * @example * summon(..., { Test: [0, 1, 2] }) // => { Test: [0, 1, 2] } * * summon(..., { Test: NBT.double([0, 1, 2]) }) // => { Test: [0d, 1d, 2d] } */ double(doubleNumbers: number[]): NBTDouble[] /** * Transform a number into a Minecraft NBT byte number. * * @param byteNumber The number to transform. * * @example * summon(..., { Health: 20 }) // => { Health: 20 } * * summon(..., { Health: NBT.byte(20) }) // => { Health: 20b } */ byte(byteNumber: number): NBTByte /** * Transform several numbers into a an array of Minecraft NBT byte numbers. * * @param byteNumbers The numbers to transform. * * @example * summon(..., { Test: [0, 1, 2] }) // => { Test: [0, 1, 2] } * * summon(..., { Test: NBT.byte([0, 1, 2]) }) // => { Test: [0b, 1b, 2b] } */ byte(byteNumbers: number[]): NBTByte[] /** * Transform a number into a Minecraft NBT short number. * * @param shortNumber The number to transform. * * @example * summon(..., { Health: 20 }) // => { Health: 20 } * * summon(..., { Health: NBT.short(20) }) // => { Health: 20b } */ short(shortNumber: number): NBTShort /** * Transform several numbers into a an array of Minecraft NBT short numbers. * * @param shortNumbers The numbers to transform. * * @example * summon(..., { Test: [0, 1, 2] }) // => { Test: [0, 1, 2] } * * summon(..., { Test: NBT.short([0, 1, 2]) }) // => { Test: [0s, 1s, 2s] } */ short(shortNumbers: number[]): NBTShort[] /** * Transform a number into a Minecraft NBT long number. * * @param longNumber The number to transform. * * @example * summon(..., { Health: 20 }) // => { Health: 20 } * * summon(..., { Health: NBT.long(20) }) // => { Health: 20l } */ long(longNumber: number): NBTLong /** * Transform several numbers into a an array of Minecraft NBT long numbers. * * @param longNumbers The numbers to transform. * * @example * summon(..., { Test: [0, 1, 2] }) // => { Test: [0, 1, 2] } * * summon(..., { Test: NBT.long([0, 1, 2]) }) // => { Test: [0l, 1l, 2l] } */ long(longNumbers: number[]): NBTLong[] /** * Transforms an array into an Integer array. * * @param intNumbers The numbers to transform. * * @example * summon(..., { Test: [0, 1, 2] }) // => { Test: [0, 1, 2] } * * summon(..., { Test: NBT.intArray([0, 1, 2]) }) // => { Test: [I; 0, 1, 2] } */ intArray(intNumbers: number[]): NBTIntArray /** * Transforms an array into a Byte array. * * @param intNumbers The numbers to transform. * * @example * summon(..., { Test: [0, 1, 2] }) // => { Test: [0, 1, 2] } * * summon(..., { Test: NBT.byteArray([0, 1, 2]) }) // => { Test: [B; 0, 1, 2] } */ byteArray(intNumbers: number[]): NBTByteArray /** * Transforms an array into a Long array. * * @param longNumbers The numbers to transform. * * @example * summon(..., { Test: [0, 1, 2] }) // => { Test: [0, 1, 2] } * * summon(..., { Test: NBT.longArray([0, 1, 2]) }) // => { Test: [L; 0, 1, 2] } */ longArray(longNumbers: number[]): NBTLongArray /** * Used to check for the absence of a NBT in a selector. * * @param nbt The NBT to check the absence of. * * @example * * // Check for entities that are NOT new babies. * >>> Selector('@e', { nbt: NBT.not({ Age: -32768 }) }).toString() * @e[nbt=!{ Age: -32768 }] */ not: (nbt: RootNBT) => NotNBT /** * Return a stringified version of a NBT. * * @param nbt The NBT to stringify. * * @example * * >>> NBT.stringify({ Invisible: true }) * '{ Invisible: true }' * * >>> NBT.stringify({ Rotation: NBT.float([ 90, 0 ]) }) * '{ Rotation: [90f, 0f] }' * * >>> NBT.stringify({ Test: NBT.longArray([0, 1, 2]) }) * '{ Test: [L; 0, 1, 2] }' */ stringify: (nbt: NBTObject) => string /** * Parses the given NBT. * * @param nbt The NBT to parse. * * @example * * >>> NBT.parse(`{ Invisible: true }`) * { Invisible: true } * * >>> const inv = NBT.parse(`[{ Slot: 1b, Count: 1, id: 'minecraft:dirt' }]`) * [{ Slot: 1b, Count: 1, id: 'minecraft:dirt' }] * >>> inv.length * 1 * * >>> NBT.parse('{ Test: [L; 0, 1, 2] }') * { Test: [L; 0, 1, 2] } */ parse: (nbt: string) => NBTObject /** * Parses the given NBT. * * * @example * * >>> NBT`{ Invisible: true }` * { Invisible: true } * * >>> const inv = NBT`[{ Slot: 1b, Count: 1, id: 'minecraft:dirt' }]` * [{ Slot: 1b, Count: 1, id: 'minecraft:dirt' }] * >>> inv.length * 1 * * >>> NBT`{ Test: [L; 0, 1, 2] }` * { Test: [L; 0, 1, 2] } */ (nbts: TemplateStringsArray, ...args: unknown[]): NBTObject } export const NBT: NBTInterface = makeCallable( { int: (num: number | number[]): any => customNumber(num, NBTInt), float: (num: number | number[]): any => customNumber(num, NBTFloat), double: (num: number | number[]): any => customNumber(num, NBTDouble), byte: (num: number | number[]): any => customNumber(num, NBTByte), short: (num: number | number[]): any => customNumber(num, NBTShort), long: (num: number | number[]): any => customNumber(num, NBTLong), intArray: (numbers: number[]): any => new NBTIntArray(numbers), longArray: (numbers: number[]): any => new NBTLongArray(numbers), byteArray: (numbers: number[]): any => new NBTByteArray(numbers), not: (nbt: RootNBT) => new NotNBT(nbt), stringify: (nbt: NBTObject) => nbtResolver(nbt).toString(), parse: (nbt: string) => parseNBT(NBT, nbt), }, dynamicNBT, ) /** * The resolved result of converting a Sandstone NBT value (which may contain * live `MacroArgument` references) into the final Minecraft SNBT string. * * Carries macro information up to `CommandNode.getValue()` so commands with * `$(...)` substitutions can be flagged as macro commands (prefixed with `$`) * even when the macro originated from inside a nested value rather than as * a top-level arg object. */ export class ResolvedNBT { constructor( public readonly value: string, public readonly containsMacro: boolean, ) {} toString(): string { return this.value } } const resolve = (nbt: NBTObject | MacroArgument): ResolvedNBT => { if (nbt === null || nbt === undefined) { throw new Error('Nullish nbt values are not allowed') } if (typeof nbt === 'number') { // We have a double, integers are now required to be defined with NBT.int return new ResolvedNBT(`${nbt}d`, false) } if (typeof nbt === 'boolean') { // We have a boolean return new ResolvedNBT(nbt.toString(), false) } if (typeof nbt === 'string') { // We have a string /* * Sometimes, when we have both a " and a ' in a string, * util.inspect will end up creating a template string, invalid for Minecraft. */ const inspectedStr = util.inspect(nbt, { breakLength: Number.POSITIVE_INFINITY, compact: true, maxStringLength: Number.POSITIVE_INFINITY, depth: Number.POSITIVE_INFINITY, }) if (inspectedStr[0] === '`') { return new ResolvedNBT(JSON.stringify(nbt), false) } return new ResolvedNBT(inspectedStr, false) } if (Array.isArray(nbt)) { // We have an array let containsMacro = false const itemsStr = nbt .map((item) => { const resolved = resolve(item) if (resolved.containsMacro) containsMacro = true return resolved.value }) .join(',') return new ResolvedNBT(`[${itemsStr}]`, containsMacro) } // We have an object if (nbt instanceof NBTClass) { // It's actually a "Minecraft Primitive", like 3b, and not an object return new ResolvedNBT(nbt[util.inspect.custom](), false) } if (typeof nbt === 'object' || typeof nbt === 'function') { let failedMacro = false if ('toMacro' in nbt) { // @ts-ignore const macro = nbt.toMacro() if (macro === '$()') { failedMacro = true } else { return new ResolvedNBT(macro, true) } } if ('toNBT' in nbt) { // toNBT itself may recurse through nbtResolver, so reuse its result. // @ts-ignore const toNbtResult = nbt.toNBT() if (toNbtResult instanceof ResolvedNBT) { return toNbtResult } return new ResolvedNBT(String(toNbtResult), false) } else if (failedMacro) { throw new Error('[nbtResolver] A macro variable NBT insertion was attempted in an mcfunction without macros defined.') } if (typeof nbt === 'function') { /* @ts-ignore */ throw new Error(`[nbtResolver] This should never happen. A function or callable instance (${nbt.constructor?.name}) without toNBT was passed in as an NBT value.`) } if (nbt.constructor.name !== 'Object') { if ('toString' in nbt) { return new ResolvedNBT(`'${nbt}'`, false) } else { /* @ts-ignore */ throw new Error(`[nbtResolver] A ${nbt.constructor?.name} was passed in as an NBT value. Hint: define toNBT or toString if this was intentional`) } } } // It's a real object. let containsMacro = false const objectStr = Object.entries(nbt) .map(([key, value]) => { const resolved = resolve(value as NBTObject) if (resolved.containsMacro) containsMacro = true return `${formatKey(key)}:${resolved.value}` }) .join(',') return new ResolvedNBT(`{${objectStr}}`, containsMacro) } // SNBT unquoted keys allow many chars, but `,`, `:`, `;`, `.`, `[`, `]`, `{`, `}` collide with the syntax. Quote any key containing those. const SNBT_KEY_REQUIRED_QUOTE_CHARS = /[:,;.\[\]{}'"]/ const formatKey = (key: string): string => { // If the user already wrapped the key in matching quotes, trust them and leave it alone. if ( (key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'")) ) { return key } if (!SNBT_KEY_REQUIRED_QUOTE_CHARS.test(key)) { return key } // Prefer single quotes. Switch to double if key only contains a `'`; if both, escape the `'` inside single. if (key.includes("'")) { if (key.includes('"')) { return `'${key.replace(/'/g, "\\'")}'` } return `"${key}"` } return `'${key}'` } /** * Resolves a Sandstone NBT value into its Minecraft SNBT string form. * * Unlike the previous `nbtStringifier`, the result is a `ResolvedNBT` object * that preserves whether the value contained `$(...)` macro substitutions. * `CommandNode.getValue()` uses `containsMacro` to decide whether to emit the * command as a macro command (prefixed with `$`). * * Callers that need a plain string (template literals, string concatenation) * can rely on `ResolvedNBT`'s `toString()`, which is called automatically by * JS coercion. To be explicit, call `.toString()` on the result. */ export const nbtResolver = (nbt: NBTObject | MacroArgument): ResolvedNBT => resolve(nbt)