/* eslint-disable max-len */ /* eslint-disable no-plusplus */ import type { // eslint-disable-next-line max-len JSONTextComponent, NBTObject, REGISTRIES, RootNBT, SOUND_TYPES, TEXTURE_TYPES, TimeArgument, OBJECTIVE_CRITERIA, } from 'sandstone/arguments' import type { StoreType } from 'sandstone/commands' import { SandstoneCommands } from 'sandstone/commands' import { getSandstoneContext, hasContext } from 'sandstone/context' import type { DatapackConfig, ResourcePackConfig } from 'sandstone/config' import type { _RawMCFunctionClass, // eslint-disable-next-line max-len AdvancementClassArguments, AtlasClassArguments, BannerPatternClassArguments, BlockStateDefinitionArguments, BlockStateDefinitionJSON, BlockTransformerClassArguments, ChatTypeClassArguments, DamageTypeClassArguments, DataPointPickClass, DecoratedPotPatternClassArguments, DialogClassArguments, EnchantmentClassArguments, EnchantmentProviderClassArguments, EquipmentClassArguments, FontArguments, InstrumentClassArguments, ItemModelDefinitionClassArguments, ItemModelDefinitionInput, ItemModifierClassArguments, JukeboxSongClassArguments, LanguageArguments, LootTableClassArguments, MacroArgument, MCFunctionClassArguments, ModelClassArguments, Node, FloatNumberProviderClassArguments, ParticleClassArguments, PlainTextArguments, PostEffectClassArguments, PredicateClassArguments, RecipeClassArguments, ShaderClassArguments, SlotSourceClassArguments, SoundEventArguments, SoundsIndexArguments, SulfurCubeArchetypeClassArguments, TagClassArguments, TagValuesJSON, TestEnvironmentClassArguments, TestInstanceClassArguments, TextureArguments, TimelineClassArguments, TradeSetClassArguments, TrialSpawnerClassArguments, TrimMaterialClassArguments, TrimPatternClassArguments, VariantClassArguments, VariantType, VillagerTradeClassArguments, WaypointStyleClassArguments, WorldClockClassArguments, IntegerNumberProviderClassArguments, } from 'sandstone/core' import { AdvancementClass, AtlasClass, BannerPatternClass, BlockStateDefinitionClass, BlockTransformerClass, ChatTypeClass, DamageTypeClass, DecoratedPotPatternClass, DialogClass, EnchantmentClass, EnchantmentProviderClass, EquipmentClass, FontClass, InstrumentClass, isMacroArgument, ItemModelDefinitionClass, ItemModifierClass, JukeboxSongClass, LanguageClass, LootTableClass, MacroLiteral, MCFunctionClass, ModelClass, FloatNumberProviderClass, ParticleClass, PlainTextClass, PostEffectClass, PredicateClass, RecipeClass, SandstoneCore, ShaderClass, SlotSourceClass, SoundEventClass, SoundsIndexClass, SulfurCubeArchetypeClass, TagClass, TestEnvironmentClass, TestInstanceClass, TextureClass, TimelineClass, TradeSetClass, TrialSpawnerClass, TrimMaterialClass, TrimPatternClass, VariantClass, VillagerTradeClass, WaypointStyleClass, WorldClockClass, IntegerNumberProviderClass, } from 'sandstone/core' import { CustomResourceClass } from 'sandstone/core/resources/custom' import { Flow, SandstoneConditions } from 'sandstone/flow' import type { LiteralUnion, NamespacedString, NonEmptyString } from 'sandstone/utils' import { makeCallable, randomUUID } from 'sandstone/utils' import type { DATA_PATH, DATA_TARGET, DATA_TYPES, SelectorEntityType, ItemPredicateItemType, SelectorProperties, TargetFor, TriggerHandler, UUIDinNumber, UUIDinScore, UUIDOptions, UUIDSource, } from 'sandstone/variables' import { coordinatesParser, DataArrayType, DataArrayInternal, DataClass, DataIndexMapType, DataIndexMapInternal, DataPointClass, ItemPredicateClass, LabelClass, LoopArgument, ObjectiveClass, Score, SelectorClass, type SelectorPickClass, TargetlessDataClass, TargetlessDataPointClass, TriggerClass, UUIDClass, VectorClass, } from 'sandstone/variables' import { ResolveNBTClass } from 'sandstone/variables/ResolveNBT' import type { handlerReadFile, handlerWriteFile } from './packType' import { PackType } from './packType' import { AwaitBodyVisitor } from './visitors/addAwaitBodyToMCFunctions' import { ContainerCommandsToMCFunctionVisitor, GenerateLazyMCFunction, IfElseTransformationVisitor, InitConstantsVisitor, InitObjectivesVisitor, InlineFunctionCallVisitor, LoopTransformationVisitor, OrTransformationVisitor, OptimizeMacroTemporariesVisitor, SimplifyExecuteFunctionVisitor, SimplifyReturnRunFunctionVisitor, SwitchTransformationVisitor, ThrowInlineVisitor, ThrowPropagationVisitor, UnifyChainedExecutesVisitor, WithNodeVisitor, } from './visitors' import type { RecipeJSON } from 'sandstone/arguments/shapedCrafting' import { JsonSymbolResource } from 'sandstone/arguments/generated/_json/dispatcher' export type ResourcePath = string[] const conflictDefaults = (resourceType: string) => { if (!hasContext()) return undefined const strategies = getSandstoneContext().conflictStrategies return (strategies?.[resourceType] || strategies?.default) as string | undefined } let tempStorage: DataClass<'storage'> type MCFunctionArgs = Exclude, MCFunctionClassArguments['callback']> const _foo: MCFunctionArgs = { addToSandstoneCore: false, } export class DataPack extends PackType { // TODO: typing. low priority readonly packMcmeta: any constructor( archiveOutput: boolean, options: DatapackConfig, ) { super( 'datapack', 'saves/$worldName$/datapacks/$packName$', 'world/datapacks/$packName$', 'datapacks/$packName$', 'server', archiveOutput, 'data', true, ) this.packMcmeta = { pack: { min_format: options.minFormat ?? options.packFormat, max_format: options.maxFormat ?? options.packFormat, description: options.description, }, } if (options.features) { this.packMcmeta.features = { enabled: options.features } } if (options.filter) { // Config uses `{ filter: { block: [...] } }`; mcmeta stores the // block array directly under `filter`. this.packMcmeta.filter = { block: options.filter.block } } } handleOutput = async ( type: 'output' | 'client' | 'server', readFile: handlerReadFile, writeFile: handlerWriteFile, ) => { if (type === 'output') { await writeFile('pack.mcmeta', JSON.stringify(this.packMcmeta, null, 2)) } } } export class ResourcePack extends PackType { // TODO: typing. low priority readonly packMcmeta: any constructor(options: ResourcePackConfig) { super( 'resourcepack', 'saves/$worldName$/resources', 'resource_pack', 'resourcepacks/$packName$', 'client', true, 'assets', true, ) this.packMcmeta = { pack: { min_format: options.minFormat ?? options.packFormat, max_format: options.maxFormat ?? options.packFormat, description: options.description, }, } if (options.filter) { this.packMcmeta.filter = { block: options.filter.block } } } handleOutput = async ( type: 'output' | 'client' | 'server', readFile: handlerReadFile, writeFile: handlerWriteFile, ) => { if (type === 'output') { await writeFile('pack.mcmeta', JSON.stringify(this.packMcmeta, null, 2)) } /* * TODO: language * * language: Contains additional languages to add to the language menu * Language code for a language, corresponding to a .json file with the same name in the folder assets//lang. * name: The full name of the language * region: The country or region name * bidirectional: If true, the language reads right to left. */ } } export class SandstonePack { readonly core: SandstoneCore = new SandstoneCore(this) packTypes: Map get packOptions() { if (hasContext()) { return getSandstoneContext().packOptions } return { datapack: { packFormat: 112, description: 'A Sandstone datapack', }, resourcepack: { packFormat: 93, description: 'A Sandstone resource pack', }, } } __initMCFunction?: MCFunctionClass // Smithed Pack IDs dependencies: Map readonly flow: Flow readonly commands: SandstoneCommands /** * Macro-enabled SandstoneCommands instance, WITHOUT the callable template * wrapper that `Macro` adds. Used by `ExecuteCommand.run` (and any other * proxy) so that commands chained inside a macro execute node (e.g. * `Macro.returnCmd.run.functionCmd(...)`) propagate `isMacro: true` through * to the resulting CommandNode. Without this, `.run` falls back to * `this.sandstonePack.commands` which is always `SandstoneCommands`, * silently stripping the macro flag at the proxy boundary. */ readonly macroCommands: SandstoneCommands readonly Macro: SandstoneCommands & ((strings: TemplateStringsArray, ...macros: (string | number | MacroArgument)[]) => MacroLiteral) readonly conditions = SandstoneConditions objectives: Set namedVariableIds: Record anonymousScoreId = 0 anonymousDataId = 0 constants: Set ticked: Record> startAllTicked: MCFunctionClass | undefined tickedCommands: Record> loadTags: { preLoad: TagClass<'function'>; load: TagClass<'function'>; postLoad: TagClass<'function'> } __rootObjective?: ObjectiveClass constructor( public defaultNamespace: string, public packUid: string, ) { this.packTypes = new Map() this.commands = new SandstoneCommands(this) this.macroCommands = new SandstoneCommands(this, true as const) this.Macro = makeCallable( this.macroCommands, (strings: TemplateStringsArray, ...macros: (string | number | MacroArgument)[]) => new MacroLiteral(this.core, strings, macros), true, ) as unknown as this['Macro'] this.flow = new Flow(this.core) this.objectives = new Set() this.namedVariableIds = {} this.constants = new Set() this.ticked = {} this.tickedCommands = {} // Override namespace from context if available if (hasContext()) { this.defaultNamespace = getSandstoneContext().namespace } this.loadTags = { preLoad: this.Tag('function', 'load:pre_load', []), load: this.Tag('function', 'load:load', []), postLoad: this.Tag('function', 'load:post_load', []), } this.setupLantern() this.dependencies = new Map() // ESM is funny for (const method of Object.getOwnPropertyNames(Object.getPrototypeOf(this))) { /* @ts-ignore */ if (method !== 'constructor' && typeof this[method] === 'function' && typeof this[method].bind === 'function') { /* @ts-ignore */ this[method] = this[method].bind(this) } } } /** * Performs a full reset of the pack. */ reset = () => { this.core.reset() this.packTypes.clear() this.__rootObjective = undefined this.__initMCFunction = undefined this.objectives.clear() this.anonymousDataId = 0 this.anonymousScoreId = 0 this.constants.clear() this.ticked = {} this.startAllTicked = undefined this.tickedCommands = {} this.dependencies.clear() this.loadTags = { preLoad: this.Tag('function', 'load:pre_load', []), load: this.Tag('function', 'load:load', []), postLoad: this.Tag('function', 'load:post_load', []), } this.setupLantern() // Override namespace from context if available if (hasContext()) { this.defaultNamespace = getSandstoneContext().namespace } // Initialize getters // oxlint-disable-next-line this.rootObjective // oxlint-disable-next-line this.initMCFunction } dataPack() { let pack = this.packTypes.get('datapack') as DataPack if (!pack) { const options = this.packOptions.datapack ?? { packFormat: 112, description: 'A Sandstone datapack' } pack = this.packTypes.set('datapack', new DataPack(false, options)).get('datapack') as DataPack } return pack } resourcePack() { let pack = this.packTypes.get('resourcepack') as ResourcePack if (!pack) { const options = this.packOptions.resourcepack ?? { packFormat: 93, description: 'A Sandstone resource pack' } pack = this.packTypes .set('resourcepack', new ResourcePack(options)) .get('resourcepack') as ResourcePack } return pack } setupLantern = () => { const loadStatus = this.Objective.create('load.status', 'dummy', undefined, { useDefaultNamespace: false, alreadyExists: true }) const privateInit = this.Tag('function', 'load:_private/init', [ this.MCFunction('load:_private/init', () => { this.commands.comment('Reset scoreboards so packs can set values accurate for current load.') this.commands.scoreboard.objectives.add(loadStatus.name, 'dummy') loadStatus.reset() }), ]) const privateLoad = this.Tag('function', 'load:_private/load', [ privateInit, { id: this.loadTags.preLoad, required: false }, { id: this.loadTags.load, required: false }, { id: this.loadTags.postLoad, required: false }, ]) this.Tag('function', 'minecraft:load', [privateLoad]) const loadVersion = hasContext() ? (getSandstoneContext().loadVersion ?? 1) : 1 this.initMCFunction.push(() => loadStatus(this.defaultNamespace).set(loadVersion)) } resourceToPath = (name: string, resourceFolders?: readonly string[]): ResourcePath => { if (name === '') { throw new Error('A resource name must not be empty!') } let namespace = this.defaultNamespace let fullName = name if (name.includes(':')) { ;[namespace, fullName] = name.split(':') } const fullPath = fullName.split('/') if (!resourceFolders) { return fullPath } return [namespace, ...resourceFolders, ...fullPath] } /** UTILS */ get _() { return this.flow } registerNewObjective = (objective: ObjectiveClass) => { for (const obj of this.objectives) { if (obj.name === objective.name) { return } } this.objectives.add(objective) } /** * Register a new numeric constant. */ registerNewConstant(amount: number) { this.constants.add(amount) } Objective = { /** * Create a new objective. Defaults to `dummy` if unspecified. * @param name The name of the objective * @param criteria The criteria for the objective * @param display The display information for the objective * @param options Optional. Options for the objective. * @param options.alreadyExists If true, the objective will not be registered as a new one. Defaults to false. * @param options.useDefaultNamespace If true (the default), the objective will be created in the default namespace. \ * For example, if the default namespace is `sandstone`, then the objective will be created as `sandstone.objective_name`. \ * If false, the objective will be created without a namespace. */ create: ( name: string, criteria: LiteralUnion = 'dummy', display?: JSONTextComponent, options: { alreadyExists?: boolean useDefaultNamespace?: boolean } = {}, ): ObjectiveClass => { let { alreadyExists = false, useDefaultNamespace = true } = options if (useDefaultNamespace) { name = `${this.defaultNamespace}.${name}` } const objective = new ObjectiveClass(this, name, criteria, display, { creator: 'user' }) if (!alreadyExists) { this.registerNewObjective(objective) } return objective }, /** * Get an existing objective. Sandstone will not check if the objective really exists. * @param name The name of the objective */ get: (name: string): ObjectiveClass => new ObjectiveClass(this, name, 'dummy', undefined, { creator: 'user' }), } get rootObjective() { if (this.__rootObjective) { return this.__rootObjective } this.__rootObjective = this.Objective.create('__sandstone', 'dummy', [ { text: 'Sandstone', color: 'gold' }, ' internals', ], { useDefaultNamespace: false }) return this.__rootObjective } private variableName(name?: string) { if (name === undefined) { return `anon_${this.packUid}_${this.anonymousScoreId++}` } else { this.namedVariableIds[name] ??= 0 return `${name}_${this.namedVariableIds[name]++}_${this.packUid}` } } /** * Creates a dynamic numeric variable, represented by an anonymous & unique score. * * @param initialValue The initial value of the variable. If left unspecified, * or if `undefined`, then the score will not be initialized. * * @param name A name that can be useful for debugging & consistent fake player naming. */ Variable(initialValue?: number | Score | undefined, name?: string): Score /** * Creates a dynamic numeric variable, represented by an anonymous & unique score. * * @param nbt The NBT value to set the Variable to. * * @param scale The scale to multiply the value by. Defaults to 1. * * @param name A name that can be useful for debugging & consistent fake player naming. */ Variable(nbt: DataPointClass, scale?: number, name?: string): Score Variable( ...args: | [initialValue?: number | Score | undefined, name?: string] | [nbt: DataPointClass, scale?: number, name?: string] ): Score { // Get the objective const score = this.rootObjective if (args[0] instanceof DataPointClass) { const [nbt, scale, name] = args // If the value is a data point, leverage the .set method return this.Variable(undefined, name).set(nbt, scale as number) } const [initialValue, name] = args // Get the specific anonymous score const anonymousScore = score(this.variableName(name as string | undefined)) // No initial value => we can directly return the score if (initialValue === undefined) { return anonymousScore } // We currently are in a MCFunction => that's where the initialization should take place if (this.core.currentMCFunction) { return anonymousScore.set(initialValue) } // Else, we should run it in the init MCFunction this.initMCFunction.push(() => anonymousScore.set(initialValue)) return anonymousScore } get flowVariable() { return this.rootObjective('if_result') } Trigger = (name: string, callback: TriggerHandler, pollingEvery = 1) => new TriggerClass(this.core, name, callback, pollingEvery) /** * Creates a new label * @param label Label/tag name * @param description Label description (optional) */ Label = (label: NonEmptyString | NamespacedString, description?: NonEmptyString) => new LabelClass(this, label, description) /** * Creates an item predicate for use in commands like `clear` and `execute if items`. * * @param itemType The item to match: an item ID, item tag (prefixed with #), or '*' for any item. * * @example * ```ts * // Match specific item * ItemPredicate('minecraft:diamond_sword') * * // Match item tag * ItemPredicate('#minecraft:swords') * * // Match any item with conditions * ItemPredicate('*').count({ max: 16 }) * * // Complex predicate * ItemPredicate('minecraft:diamond_sword') * .match('minecraft:enchantments', [{ enchantment: 'minecraft:sharpness', levels: { min: 3 } }]) * .has('minecraft:custom_name') * .without('minecraft:damage') * ``` */ ItemPredicate = (itemType: ItemPredicateItemType) => new ItemPredicateClass(this, itemType) /** * Creates a new Data Class Instance * @param type Source type * @param target Optional. Target for data * @param path Optional. Path for data */ Data(type: T): TargetlessDataClass Data(type: T, target: TargetFor): DataClass Data(type: T, target: MacroArgument | TargetFor): DataClass Data(type: T, target: TargetFor): DataClass Data( type: T, target: undefined, path: MacroArgument | DATA_PATH | DATA_PATH[], ): TargetlessDataPointClass Data( type: T, target: TargetFor, path: MacroArgument | DATA_PATH | DATA_PATH[], ): DataPointClass Data( type: T, target: MacroArgument | TargetFor, path: MacroArgument | DATA_PATH | DATA_PATH[], ): DataPointClass Data( type: T, target: TargetFor, path: MacroArgument | DATA_PATH | DATA_PATH[], ): DataPointClass Data( type: T, target?: TargetFor | MacroArgument, path?: MacroArgument | DATA_PATH | DATA_PATH[], ) { const dataPath = (path ?? typeof path === 'string') ? [path] : path // Since Macros technically don't need to be used with `Macro.`, this is fine. Its hacky. But whatever. if (!path && !target) { return new TargetlessDataClass(this, type) } if (!target) { return new TargetlessDataPointClass(this, type, dataPath as DATA_PATH[]) } if (!path) { return new DataClass( this, type, (isMacroArgument(this.core, target) || (type === 'block' ? coordinatesParser(target) : target)) as DATA_TARGET[T], ) } return new DataPointClass( this, type, (target instanceof VectorClass ? coordinatesParser(target) : target) as DATA_TARGET[T], dataPath as DATA_PATH[], ) } __rootStorage?: DataPointClass rootStorage() { if (!this.__rootStorage) { this.__rootStorage = new DataPointClass(this, 'storage', '__sandstone:variable', []) return this.__rootStorage } return this.__rootStorage } /** * Creates a dynamic data variable, represented by an anonymous & unique Data Point. * * @param initialValue Optional. The initial value of the variable. If left unspecified, * or if `undefined`, then the Data Point will not be initialized. * * @param name Optional. A name that can be useful for debugging & consistent pathing. */ DataVariable(initialValue?: NBTObject | DataPointClass | DataPointPickClass, name?: string): DataPointClass<'storage'> /** * Creates a dynamic data variable, represented by an anonymous & unique Data Point. * * @param score The Score to set the data variable to. * * @param storeType Optional. The number type you want to store. Defaults to int. * * @param scale Optional. The scale to multiply the value by. Defaults to 1. * * @param name Optional. A name that can be useful for debugging & consistent pathing. */ DataVariable(score: Score, storeType?: StoreType, scale?: number, name?: string): DataPointClass<'storage'> DataVariable( ...args: | [initialValue?: NBTObject | DataPointClass | DataPointPickClass, name?: string] | [score: Score, storeType?: StoreType, scale?: number, name?: string] ): DataPointClass<'storage'> { // Get the objective const data = this.rootStorage() if (args[0] instanceof Score) { const [score, storeType, scale, name] = args // If the value is a score, leverage the .set method return this.DataVariable(undefined, name).set(score, (storeType || 'int') as StoreType, scale || 1) } const [initialValue, name] = args // Get the specific anonymous data point const anonymousData = data.select(`${name ?? 'anon'}_${this.packUid}${name === undefined ? `_${this.anonymousDataId++}` : ''}`) // No initial value => we can directly return the data point if (initialValue === undefined) { return anonymousData } // We currently are in a MCFunction => that's where the initialization should take place if (this.core.currentMCFunction) { return anonymousData.set(initialValue as never) } // Else, we should run it in the init MCFunction this.initMCFunction.push(() => anonymousData.set(initialValue as never)) return anonymousData } DataIndexMap>( initialize: INITIAL, dataPoint?: DataPointClass<'storage'>, ) { return DataIndexMapInternal(this, initialize, dataPoint) as DataIndexMapType } DataArray( initialize: INITIAL, dataPoint?: DataPointClass<'storage'>, ) { return DataArrayInternal(this, initialize, dataPoint) as DataArrayType } getTempStorage = (name: string) => { if (tempStorage) { return tempStorage.select(name) } tempStorage = this.Data('storage', '__sandstone:temp') return tempStorage.select(name) } /** * Resolve NBT containing Data Points & Score's. * @param nbt NBT with Data Points & Scores initialized with ResolveNBTPart. * @param dataPoint Optional. Data Point to resolve to. * @param skipReset Optional. Skip the leading `data modify ... set value {}` * reset. Auto-skipped when ResolveNBT creates its own internal dataPoint * (the temp storage is known empty); pass `true` here for an external * dataPoint that's known to be empty (e.g. dedicated macro storage). */ ResolveNBT(nbt: Resolving, dataPoint?: DataPointClass<'storage'>, skipReset?: boolean) { return new ResolveNBTClass(this, nbt, dataPoint, skipReset) } Selector(target: '@e'): SelectorClass Selector(target: '@a'): SelectorClass Selector(target: '@s' | '@n'): SelectorClass Selector(target: '@p' | '@r', selectorArguments?: Omit, 'type'>, 'limit'>): SelectorClass Selector, 'limit'>>(target: '@s' | '@n', selectorArguments: PROPERTIES): SelectorClass Selector, 'type'>>(target: '@a', selectorArguments: PROPERTIES): SelectorClass Selector>(target: '@e', selectorArguments: PROPERTIES): SelectorClass Selector(target: '@s' | '@p' | '@a' | '@e' | '@n' | '@r', selectorArguments?: SelectorProperties): SelectorClass { return new SelectorClass(this, target, selectorArguments) as SelectorClass } UUID(): UUIDClass<'known'> /** Initializes with a static UUID. (you can use `import { randomUUID } from 'sandstone/utils'` to generate one) */ UUID(source: string | UUIDinNumber, options?: UUIDOptions): UUIDClass<'known'> /** Initializes with `Score`'s. */ UUID(source: UUIDinScore, options?: UUIDOptions): UUIDClass<'scores'> /** Initializes with a Data Point (to a UUID int array). */ UUID(source: DataPointClass, options?: UUIDOptions): UUIDClass<'data'> /** Initializes with a Selector. */ UUID(source: SelectorPickClass, options?: UUIDOptions): UUIDClass<'selector'> UUID(source: UUIDSource = randomUUID(), options?: UUIDOptions) { return new UUIDClass(this.core, source, options) } MCFunction(name: string, options?: MCFunctionArgs): MCFunctionClass MCFunction( name: string, callback: (loop: MCFunctionClass) => void, options?: MCFunctionArgs, ): MCFunctionClass MCFunction( name: string, callback: (loop: MCFunctionClass, ...params: PARAMS) => void, options?: MCFunctionArgs, ): MCFunctionClass MCFunction( name: string, environmentVariables: ENV, callback: (loop: MCFunctionClass) => void, options?: MCFunctionArgs, ): MCFunctionClass MCFunction( name: string, environmentVariables: ENV, callback: (loop: MCFunctionClass, ...params: PARAMS) => void, options?: MCFunctionArgs, ): MCFunctionClass MCFunction( ...args: | [name: string, options?: MCFunctionArgs] | [ name: string, callback: ( this: MCFunctionClass, ...params: PARAMS extends readonly MacroArgument[] ? PARAMS : [] ) => void, options?: MCFunctionArgs, ] | [ name: string, environmentVariables: ENV, callback: ( this: MCFunctionClass, ...params: PARAMS extends readonly MacroArgument[] ? PARAMS : [] ) => void, options?: MCFunctionArgs, ] ) { return new MCFunctionClass( this.core, args[0], { callback: (typeof args[1] === 'function' ? args[1] : args[2]) as () => void, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('function') as MCFunctionClassArguments['onConflict'], ...(Array.isArray(args[1]) ? args[3] : args[2] || args[1]), }, Array.isArray(args[1]) ? args[1] : undefined, ) as unknown as MCFunctionClass } appendNode = (node: Node) => this.core.getCurrentMCFunctionOrThrow().appendNode(node) get initMCFunction() { if (!this.__initMCFunction) { this.__initMCFunction = new MCFunctionClass(this.core, `${this.defaultNamespace}:__init__`, { addToSandstoneCore: true, creator: 'sandstone', }) as MCFunctionClass this.loadTags.load.push(this.__initMCFunction) return this.__initMCFunction } return this.__initMCFunction } /** * Register mcfunction that will be ticked at the rate you specify */ registerTicked(runEvery: TimeArgument, func: MCFunctionClass) { if (typeof runEvery === 'number') { runEvery = `${runEvery}t` // Normalize map key } const tag = this.ticked[runEvery] ?? (() => { const name = `__sandstone:ticked/${runEvery}` this.ticked[runEvery] = this.Tag('function', name, []) const looped = this.MCFunction(name, (self) => { this.commands.functionCmd(this.ticked[runEvery]) self.schedule.function(runEvery, 'replace') }) if (this.startAllTicked === undefined) { this.startAllTicked = this.MCFunction(`__sandstone:ticked/start/${this.packUid.toLowerCase()}`) this.loadTags.load.push(this.startAllTicked) } this.startAllTicked.push(() => looped()) return this.ticked[runEvery] })() if (func.env === undefined) { tag.push(func) } else { this.registerTickedCommands(runEvery, () => func()) } } /** * Register commands that will be ticked at the rate you specify */ registerTickedCommands(runEvery: TimeArgument, callback: () => void) { if (typeof runEvery === 'number') { runEvery = `${runEvery}t` // Normalize map key } if (this.tickedCommands[runEvery] === undefined) { this.tickedCommands[runEvery] = this.MCFunction(`__sandstone:ticked/${runEvery}/${this.packUid.toLowerCase()}_commands`) this.registerTicked(runEvery, this.tickedCommands[runEvery]) } this.tickedCommands[runEvery].push(callback) } Loop = () => new LoopArgument(this) __customResourceTypes: string[] = [] registerCustomResource(type: string) { if (this.__customResourceTypes.includes(type)) { throw new Error(`A custom resource of the type '${type}' has already been created!`) } this.__customResourceTypes.push(type) } get makeCustomResource(): [SandstoneCore, typeof CustomResourceClass] { return [this.core, CustomResourceClass] } /** Creates a resource in the datapack, path must include file extension. */ RawResource(path: string, contents: string | ArrayBuffer | Buffer | Promise): CustomResourceClass /** Creates a resource in the given pack, path must include file extension. */ RawResource(pack: PackType, path: string, contents: string | ArrayBuffer | Buffer | Promise): CustomResourceClass RawResource( ...args: | [path: string, contents: string | ArrayBuffer | Buffer | Promise] | [pack: PackType, path: string, contents: string | ArrayBuffer | Buffer | Promise] ) { const [core, CustomResource] = this.makeCustomResource if (args[0] instanceof PackType) { const _path = args[1] as string const path = _path.includes('/') ? _path.split('/') : [_path] const extension = path[path.length - 1].split('.')[1] path[path.length - 1] = path[path.length - 1].replace(`.${extension}`, '') class RawResource extends CustomResource { constructor() { super(core, path.join('/'), { type: `${Math.random()}`, packType: args[0] as PackType, extension, addToSandstoneCore: true, creator: 'user', }) } getValue = () => args[2] as string | ArrayBuffer | Buffer | Promise } return new RawResource() } const _path = args[0] as string const path = _path.includes('/') ? _path.split('/') : [_path] const extension = path[path.length - 1].split('.')[1] path[path.length - 1] = path[path.length - 1].replace(`.${extension}`, '') class RawResource extends CustomResource { constructor() { super(core, path.join('/'), { type: `${Math.random()}`, extension, addToSandstoneCore: true, creator: 'user', }) } getValue = () => args[1] } return new RawResource() } Advancement( name: string, json: AdvancementJSON, options?: Omit, 'json'>, ) { return new AdvancementClass(this.core, name, { json, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('advancement') as AdvancementClassArguments['onConflict'], ...options, }) } DamageType = (name: string, damageType: DamageTypeClassArguments['json'], options?: Omit, 'json'>) => new DamageTypeClass(this.core, name, { json: damageType, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('damage_type') as DamageTypeClassArguments['onConflict'], ...options, }) DecoratedPotPattern = (name: string, decoratedPotPattern: DecoratedPotPatternClassArguments['json'], options?: Omit, 'json'>) => new DecoratedPotPatternClass(this.core, name, { json: decoratedPotPattern, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('decorated_pot_pattern') as DecoratedPotPatternClassArguments['onConflict'], ...options, }) ItemModifier = (name: string, itemModifier: ItemModifierClassArguments['json'], options?: Omit, 'json'>) => new ItemModifierClass(this.core, name, { json: itemModifier, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('item_modifier') as ItemModifierClassArguments['onConflict'], ...options, }) NumberProvider( type: 'float', name: string, numberProvider: FloatNumberProviderClassArguments['json'], options?: Omit, 'json'> ): FloatNumberProviderClass NumberProvider( type: 'integer', name: string, numberProvider: IntegerNumberProviderClassArguments['json'], options?: Omit, 'json'> ): IntegerNumberProviderClass NumberProvider(type: 'float' | 'integer', name: string, numberProvider: any, options?: any) { if (type === 'float') { return new FloatNumberProviderClass(this.core, name, { json: numberProvider, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('float_number_provider') as FloatNumberProviderClassArguments['onConflict'], ...options, }) } return new IntegerNumberProviderClass(this.core, name, { json: numberProvider, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('integer_number_provider') as IntegerNumberProviderClassArguments['onConflict'], ...options, }) } LootTable = (name: string, lootTable: LootTableClassArguments['json'], options?: Omit, 'json'>) => new LootTableClass(this.core, name, { json: lootTable, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('loot_table') as LootTableClassArguments['onConflict'], ...options, }) Predicate = (name: string, predicate: PredicateClassArguments['json'], options?: Omit, 'json'>) => new PredicateClass(this.core, name, { json: predicate, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('predicate') as PredicateClassArguments['onConflict'], ...options, }) Recipe = ( name: string, recipe: RecipeJSON, options?: Omit, 'json'>, ) => new RecipeClass(this.core, name, { json: recipe as RecipeClassArguments['json'], creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('recipe') as RecipeClassArguments['onConflict'], ...options, }) SlotSource = (name: string, slotSource: SlotSourceClassArguments['json'], options?: Omit, 'json'>) => new SlotSourceClass(this.core, name, { json: slotSource, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('slot_source') as SlotSourceClassArguments['onConflict'], ...options, }) SulfurCubeArchetype = (name: string, sulfurCubeArchetype: SulfurCubeArchetypeClassArguments['json'], options?: Omit, 'json'>) => new SulfurCubeArchetypeClass(this.core, name, { json: sulfurCubeArchetype, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('sulfur_cube_archetype') as SulfurCubeArchetypeClassArguments['onConflict'], ...options, }) Tag = >( type: T, name: string, values: TagValuesJSON, options?: Partial>, ) => new TagClass(this.core, type, name, { values, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('tag') as TagClassArguments['onConflict'], ...options, }) TrimMaterial = (name: string, trimMaterial: TrimMaterialClassArguments['json'], options?: Omit, 'json'>) => new TrimMaterialClass(this.core, name, { json: trimMaterial, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('trim_material') as TrimMaterialClassArguments['onConflict'], ...options, }) TrimPattern = (name: string, trimPattern: TrimPatternClassArguments['json'], options?: Omit, 'json'>) => new TrimPatternClass(this.core, name, { json: trimPattern, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('trim_pattern') as TrimPatternClassArguments['onConflict'], ...options, }) BannerPattern = (name: string, bannerPattern: BannerPatternClassArguments['json'], options?: Omit, 'json'>) => new BannerPatternClass(this.core, name, { json: bannerPattern, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('banner_pattern') as BannerPatternClassArguments['onConflict'], ...options, }) BlockTransformer = (name: string, block_transformer: BlockTransformerClassArguments['json'], options?: Omit, 'json'>) => new BlockTransformerClass(this.core, name, { json: block_transformer, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('block_transformer') as BlockTransformerClassArguments['onConflict'], ...options, }) ChatType = (name: string, chatType: ChatTypeClassArguments['json'], options?: Omit, 'json'>) => new ChatTypeClass(this.core, name, { json: chatType, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('chat_type') as ChatTypeClassArguments['onConflict'], ...options, }) Dialog = (name: string, dialog: DialogClassArguments['json'], options?: Omit, 'json'>) => new DialogClass(this.core, name, { json: dialog, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('dialog') as DialogClassArguments['onConflict'], ...options, }) Enchantment = (name: string, enchantment: EnchantmentClassArguments['json'], options?: Omit, 'json'>) => new EnchantmentClass(this.core, name, { json: enchantment, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('enchantment') as EnchantmentClassArguments['onConflict'], ...options, }) EnchantmentProvider = (name: string, enchantmentProvider: EnchantmentProviderClassArguments['json'], options?: Omit, 'json'>) => new EnchantmentProviderClass(this.core, name, { json: enchantmentProvider, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('enchantment_provider') as EnchantmentProviderClassArguments['onConflict'], ...options, }) Instrument = (name: string, instrument: InstrumentClassArguments['json'], options?: Omit, 'json'>) => new InstrumentClass(this.core, name, { json: instrument, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('instrument') as InstrumentClassArguments['onConflict'], ...options, }) JukeboxSong = (name: string, jukeboxSong: JukeboxSongClassArguments['json'], options?: Omit, 'json'>) => new JukeboxSongClass(this.core, name, { json: jukeboxSong, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('jukebox_song') as JukeboxSongClassArguments['onConflict'], ...options, }) TestEnvironment = (name: string, testEnvironment: TestEnvironmentClassArguments['json'], options?: Omit, 'json'>) => new TestEnvironmentClass(this.core, name, { json: testEnvironment, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('test_environment') as TestEnvironmentClassArguments['onConflict'], ...options, }) TestInstance = (name: string, testInstance: TestInstanceClassArguments['json'], options?: Omit, 'json'>) => new TestInstanceClass(this.core, name, { json: testInstance, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('test_instance') as TestInstanceClassArguments['onConflict'], ...options, }) Timeline = (name: string, timeline: TimelineClassArguments['json'], options?: Omit, 'json'>) => new TimelineClass(this.core, name, { json: timeline, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('timeline') as TimelineClassArguments['onConflict'], ...options, }) WorldClock = (name: string, worldClock: WorldClockClassArguments['json'], options?: Omit, 'json'>) => new WorldClockClass(this.core, name, { json: worldClock, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('world_clock') as WorldClockClassArguments['onConflict'], ...options, }) TradeSet = (name: string, tradeSet: TradeSetClassArguments['json'], options?: Omit, 'json'>) => new TradeSetClass(this.core, name, { json: tradeSet, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('trade_set') as TradeSetClassArguments['onConflict'], ...options, }) TrialSpawner = (name: string, trialSpawner: TrialSpawnerClassArguments['json'], options?: Omit, 'json'>) => new TrialSpawnerClass(this.core, name, { json: trialSpawner, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('trial_spawner') as TrialSpawnerClassArguments['onConflict'], ...options, }) VillagerTrade = (name: string, villagerTrade: VillagerTradeClassArguments['json'], options?: Omit, 'json'>) => new VillagerTradeClass(this.core, name, { json: villagerTrade, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('villager_trade') as VillagerTradeClassArguments['onConflict'], ...options, }) Variant = (type: T, name: string, variant: VariantClassArguments['variant'], options?: Omit>, 'variant'>) => new VariantClass(this.core, type, name, { variant, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults(`${type}_variant`) as VariantClassArguments['onConflict'], ...options, }) Atlas = (name: string, json: AtlasClassArguments['json'], options?: Omit, 'json'>) => new AtlasClass(this.core, name, { json, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('atlas') as AtlasClassArguments['onConflict'], ...options, }) BlockStateDefinition( name: string, json: JSON, options?: Omit>, 'json'>, ) { return new BlockStateDefinitionClass(this.core, name, { json, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('blockstate') as BlockStateDefinitionArguments['onConflict'], ...options, }) } Font = (name: string, providers: FontArguments['providers'], options?: Omit, 'providers'>) => new FontClass(this.core, name, { providers, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('font') as FontArguments['onConflict'], ...options, }) Language = (name: string, language: LanguageArguments['language'], options?: Omit, 'language'>) => new LanguageClass(this.core, name, { language, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('language') as LanguageArguments['onConflict'], ...options, }) Model>( type: Type, name: string, json: ModelClassArguments['json'], options?: Omit, 'json'>, ) { return new ModelClass(this.core, type, name, { json, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('model') as ModelClassArguments['onConflict'], ...options, }) } /** * Creates an item definition resource for controlling how items are rendered. * * @param name The resource name (e.g., 'mypack:diamond_sword') * @param definition The item definition - can be: * - Raw ItemModelDefinition JSON * - Raw ItemModel JSON (will be wrapped) * - An ItemModelBuilder instance * - A callback receiving an ItemModelBuilder * @param options Optional resource options * * @example * ```ts * // Raw JSON * pack.ItemModelDefinition('mypack:custom_item', { * type: 'model', * model: 'minecraft:item/diamond_sword' * }) * * // Callback with predicate-style builder * pack.ItemModelDefinition('mypack:named_sword', (model) => * model * .has('minecraft:custom_name') * .onTrue('custom:named_sword') * .onFalse('minecraft:item/diamond_sword') * ) * * // From ItemPredicate via model() method * pack.ItemModelDefinition('mypack:diamond_sword', * pack.ItemPredicate('minecraft:diamond_sword') * .has('minecraft:enchantments') * .model() * .onTrue('custom:enchanted') * .onFalse('minecraft:item/diamond_sword') * ) * ``` */ ItemModelDefinition = ( name: string, definition: ItemModelDefinitionInput, options?: Omit, 'definition'>, ) => new ItemModelDefinitionClass(this.core, name, { definition, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('item_definition') as ItemModelDefinitionClassArguments['onConflict'], ...options, }) SoundEvent( type: Type, name: string, sound: SoundEventArguments['sound'], options?: Omit, 'sound'>, ) { return new SoundEventClass(this.core, type, name, { sound, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('sound_event') as SoundEventArguments['onConflict'], ...options, }) } SoundsIndex = (definitions: SoundsIndexArguments['definitions'], namespace?: string, options?: Omit, 'definitions'>) => new SoundsIndexClass(this.core, namespace ?? this.defaultNamespace, { definitions, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('sounds') as SoundsIndexArguments['onConflict'], ...options, }) PlainText = (name: string, text: PlainTextArguments['text'], options?: Partial) => new PlainTextClass(this.core, name, { text, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('atlas') as PlainTextArguments['onConflict'], ...options, }) Texture>( type: Type, name: string, texture: TextureArguments['texture'], options?: Partial>, ) { return new TextureClass(this.core, type, name, { texture, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('sound_event') as TextureArguments['onConflict'], ...options, }) } Equipment = (name: string, json: EquipmentClassArguments['json'], options?: Omit, 'json'>) => new EquipmentClass(this.core, name, { json, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('equipment') as EquipmentClassArguments['onConflict'], ...options, }) Particle = (name: string, json: ParticleClassArguments['json'], options?: Omit, 'json'>) => new ParticleClass(this.core, name, { json, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('particle') as ParticleClassArguments['onConflict'], ...options, }) PostEffect = (name: string, json: PostEffectClassArguments['json'], options?: Omit, 'json'>) => new PostEffectClass(this.core, name, { json, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('post_effect') as PostEffectClassArguments['onConflict'], ...options, }) Shader = (name: string, json: ShaderClassArguments['json'], options?: Omit, 'json'>) => new ShaderClass(this.core, name, { json, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('shader') as ShaderClassArguments['onConflict'], ...options, }) WaypointStyle = (name: string, json: WaypointStyleClassArguments['json'], options?: Omit, 'json'>) => new WaypointStyleClass(this.core, name, { json, creator: 'user', addToSandstoneCore: true, onConflict: conflictDefaults('waypoint_style') as WaypointStyleClassArguments['onConflict'], ...options, }) async save(cliOptions: { fileHandler: (relativePath: string, content: any) => Promise dry: boolean verbose: boolean }) { await this.core.save(cliOptions, { visitors: defaultVisitors(this), }) return this.packTypes } /** * Create an MCFunction from a body callback and run the full default * visitor pipeline, returning every compiled resource as a * `Map`. * * Acts exactly like `MCFunction(name, callback)` for context purposes * — the callback runs inside the new MCFunction's context, with * `currentMCFunction` set and command emissions going to its body. * * Unlike `save()`, this does NOT touch the filesystem and does NOT * load Smithed dependencies. It runs the visitor pipeline * synchronously. Intended for tests, REPL tooling, and downstream * inspection of Sandstone's output — including the auto-created * child MCFunctions that visitors spawn (e.g. `__if`, `__loop`, * `__switch`, `__sleep`, etc.). * * Binary resources and non-string outputs are skipped — for full * output capture use `save({ dry: true, fileHandler })` instead. * * @example * ```ts * const out = pack.compile('foo', () => say('hi')) * out.get('datapack/data/test/function/foo.mcfunction') // 'say hi' * ``` */ compile(name: string, callback: () => void): Map { this.MCFunction(name, callback) const visitors = defaultVisitors(this) const resources = this.core.generateResources({ visitors }) const out = new Map() for (const node of resources) { const { packType, fileExtension } = node.resource const _path = [packType.type, ...node.resource.path] if (packType.resourceSubFolder) { _path.splice(1, 0, packType.resourceSubFolder) } const resourcePath = `${_path.join('/')}.${fileExtension}` const value = node.getValue() if (typeof value === 'string') { out.set(resourcePath, value) } } return out } } /** * The full default visitor pipeline Sandstone runs on every pack during * `save()`. Exposed so tests, tooling, and downstream pack implementations * can run the same compilation steps without re-deriving the order. * * Order matters — see `pack.ts#save` for the rationale of each group. */ export function defaultVisitors(pack: SandstonePack) { return [ // Initialization visitors new InitObjectivesVisitor(pack), new InitConstantsVisitor(pack), new GenerateLazyMCFunction(pack), // Transformation visitors new LoopTransformationVisitor(pack), new SwitchTransformationVisitor(pack), new OrTransformationVisitor(pack), new IfElseTransformationVisitor(pack), new ThrowInlineVisitor(pack), new ContainerCommandsToMCFunctionVisitor(pack), // Special visitors new AwaitBodyVisitor(pack), new ThrowPropagationVisitor(pack), new WithNodeVisitor(pack), // Optimization new OptimizeMacroTemporariesVisitor(pack), new InlineFunctionCallVisitor(pack), new UnifyChainedExecutesVisitor(pack), new SimplifyExecuteFunctionVisitor(pack), new SimplifyReturnRunFunctionVisitor(pack), ] }