/* eslint-disable operator-linebreak */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import fs from 'fs-extra' import * as util from 'util' import type { MultipleEntitiesArgument } from './arguments/selector' import type { Node } from './core/nodes' import type { UUIDinNumber } from './variables/UUID' export type NonEmptyString = (`${any}${string}` & { __brand?: never }) export type NamespacedString = (`${string}:${string}` & { __brand?: never }) /** * Allows to get autocompletion on string unions, while still allowing generic strings. * @see https://github.com/microsoft/TypeScript/issues/29729#issuecomment-700527227 */ export type LiteralUnion = T | (NonEmptyString & Record) export type NamespacedLiteralUnion = T | (NamespacedString & Record) export type AtLeastOne = [T, ...T[]] // biome-ignore lint/complexity/noBannedTypes: It can take any function, including constructors. export type HideFunctionProperties = T & { /** @deprecated */ call: T['call'] /** @deprecated */ apply: T['apply'] /** @deprecated */ bind: T['bind'] /** @deprecated */ prototype: T['prototype'] /** @deprecated */ length: T['length'] /** @deprecated */ arguments: T['arguments'] /** @deprecated */ caller: T['caller'] /** @deprecated */ readonly name: T['name'] /** @deprecated */ [Symbol.hasInstance]: (value: unknown) => boolean } export type BASIC_CONFLICT_STRATEGIES = 'throw' | 'replace' | 'warn' | 'rename' | 'ignore' export type OmitFirst = T extends [infer _, ...infer B] ? B : [] export function isAsyncFunction( func: ((...args: any[]) => void) | ((...args: any[]) => Promise), ): func is (...args: any[]) => Promise { if (util.types) { // We are in NodeJS, so we can use the builtin check return util.types.isAsyncFunction(func) } /* * We might be in a browser, or another weird environment * Try a native way first. */ if (func.constructor.name === 'AsyncFunction') { return true } // Okay, we need a stronger check. const string = func.toString().trim() return !!( // native ( string.match(/^async /) || // babel (this may change, but hey...) string.match(/return _ref[^.]*\.apply/) ) ) } export function isPromise(promise: any): promise is Promise { return promise && typeof promise.then === 'function' && promise[Symbol.toStringTag] === 'Promise' } /** * Create a brand checker for a class without importing it (avoiding circular deps). * Returns a type guard function that checks for the brand symbol. * * @example * import type { TagClass } from 'sandstone/core/resources/datapack/tag' * const isTagClass = createBrandChecker>('TagClass') * if (isTagClass(value)) { * // value is a TagClass instance * } */ export function createBrandChecker(className: string): (value: unknown) => value is T { const brand = Symbol.for(`sandstone.${className}`) return (value: unknown): value is T => { return typeof value === 'object' && value !== null && brand in value } } export type Either, B extends Record> = ( | { [K in keyof A | keyof B]?: K extends keyof A ? A[K] : never } | { [K in keyof A | keyof B]?: K extends keyof B ? B[K] : never } ) export type WithMCNamespace = `minecraft:${T}` | T export interface CreateLazyProxyOptions { /** * Function to fetch the source object/method for a given key. Called * lazily on each property access so the source can be swapped at * runtime (e.g. when the active `SandstonePack` changes). */ getSource: (key: TKey) => TSource /** Label used in error messages, e.g. `'Command'` or `'Pack method'`. */ label: string /** * Whether to bind sub-methods to the source they were accessed from. * * Set `true` for sources where sub-methods are regular class methods * that depend on `this` (e.g. `SandstonePack` methods). Set `false` * (default) when the source is already responsible for its own * binding — `SandstoneCommands` returns either arrow-function * methods (which capture `this` lexically) or methods pre-bound by * its own `bind()` helper, so an extra `.bind()` here would be a * no-op or even allocate a new function per access. */ bind?: boolean } /** * Build a `Proxy` that lazily resolves each top-level key to a source * value via `getSource(key)`. The resolved value can be invoked as a * function (delegated to the source) and probed for sub-properties * (forwarded to the source). Mirrors the two-stage `Proxy(fn, handler)` * shape used by the `commandsProxy` and `packMethodsProxy` in * `sandstone.ts`. * * @param options.getSource Returns the source for a key. The source can * be a function, a class instance, or any object with sub-properties. * @param options.label Used in the "X is not callable" error message. * @param options.bind When `true`, sub-methods are bound to their parent * source to preserve `this` context (needed for class methods). When * omitted/`false`, sub-methods are returned as-is (the source has * already bound them or uses arrow functions). */ export function createLazyProxy< TKey extends string, TSource, TShape extends { [K in TKey]?: any }, >(options: CreateLazyProxyOptions): TShape { const { getSource, label, bind: shouldBind = false } = options return new Proxy({} as TShape, { get(_target: object, prop: K): TShape[K] { // Create a function that delegates to the actual source when called. const fn = (...args: unknown[]): unknown => { const source = getSource(prop) if (typeof source === 'function') { return (source as (...args: unknown[]) => unknown)(...args) } throw new Error(`${label} '${prop}' is not callable`) } // Return a proxy that intercepts both function calls and sub-property // access. Sub-properties are read off the source on each access so // mutations to the source (e.g. `sandstonePack.commands.foo = // newCommand`) take effect immediately. return new Proxy(fn, { get(_target: object, subProp: string | symbol): unknown { const source = getSource(prop) as unknown as Record const value = source[subProp] if ( shouldBind && typeof value === 'function' && typeof (value as (...args: unknown[]) => unknown).bind === 'function' ) { return (value as (...args: unknown[]) => unknown).bind(source) } return value }, apply(_target: object, _thisArg: unknown, args: unknown[]): unknown { const source = getSource(prop) if (typeof source === 'function') { return (source as (...args: unknown[]) => unknown)(...args) } throw new Error(`${label} '${prop}' is not callable`) }, }) as TShape[K] }, }) } export function makeCallableProxy(func: any, object: any) { return new Proxy(func, { apply: (_t, _thisArg, args) => Reflect.apply(func, object, args), get: (_t, p, _r) => object[p], set: (_t, p, value, _r) => { object[p] = value return value }, getPrototypeOf: (_t) => Object.getPrototypeOf(object), ownKeys: (_t) => { return Reflect.ownKeys(object); }, getOwnPropertyDescriptor: (_t, prop) => { return Reflect.getOwnPropertyDescriptor(object, prop); }, has: (_t, prop) => { return Reflect.has(object, prop); } }) as any } export interface CallableInstance { __call__: (...args: any[]) => any } type CallableClass = new (...args: any[]) => CallableInstance export function makeClassCallable(Class_: C): MakeClassCallable { return new Proxy(Class_, { construct: (_t, argArray, _nt) => { const obj = new Class_(...argArray) const result = makeCallableProxy(obj.__call__, obj) // TODO: Figure this out // result.makeCallable(result) return result }, }) as any } export type MakeInstanceCallable = T & T['__call__'] export type MakeClassCallable = new ( ...args: ConstructorParameters ) => MakeInstanceCallable> export function makeCallable any>(object: T, func: F, useProxy = false): T & F { if (useProxy) { return makeCallableProxy(func, object) } const { name, ...objectExceptName } = object as T & { name?: unknown } // Everything can be assigned except the name const result = Object.assign(func, objectExceptName as unknown as T) if (name !== undefined) { const descriptor = Object.getOwnPropertyDescriptor(func, 'name')! descriptor.value = name Object.defineProperty(func, 'name', descriptor) } return result } type TupleSplit = O['length'] extends N ? [O, T] : T extends readonly [infer F, ...infer R] ? TupleSplit : [O, T] type TakeFirst = TupleSplit[0] type SkipFirst = TupleSplit[1] type TupleSlice = SkipFirst, S> export type SlicedArguments< T extends (...args: any[]) => any, FROM extends number | undefined = undefined, TO extends number | undefined = undefined, > = TupleSlice, FROM extends undefined ? 0 : FROM, TO extends undefined ? Parameters['length'] : TO> export type PartialFunction< T extends (...args: any[]) => any, FROM extends number | undefined = undefined, TO extends number | undefined = undefined, > = (...args: SlicedArguments) => ReturnType export 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 /* Ported from https://github.com/AjaxGb/mc-uuid-converter/blob/master/convert.js */ const uuidBytes = new Uint8Array(16) const uuid = new DataView(uuidBytes.buffer) export function randomUUID() { crypto.getRandomValues(uuidBytes) // Set version to 4 (random) // eslint-disable-next-line no-bitwise uuidBytes[6] = (uuidBytes[6] & 0x0f) | (4 << 4) // Set variant to 1 (Leach–Salz) // eslint-disable-next-line no-bitwise uuidBytes[8] = (uuidBytes[8] & 0x3f) | 0x80 const array: number[] = [] // eslint-disable-next-line no-plusplus for (let i = 0; i < 4; i++) { array.push(uuid.getInt32(i * 4, false)) } return array as UUIDinNumber } export const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1) export type UnionToIntersection = ( (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never ) export type LastOf = ( UnionToIntersection T : never> extends () => (infer R) ? R : never ) export type Push = [...T, V] export type UnionToTuple, N = [T] extends [never] ? true : false> = ( true extends N ? [] : Push>, L> ) export type PowerSet> = ( Keys extends [infer Head, ...infer Rest] ? PowerSet | ( Head extends keyof T ? { [K in Head]: NonNullable } & PowerSet : never ) : Record ) export type Prettify = ({ [K in keyof T]: T[K] } & {}) /** * Helper to add key-value pairs to an object if the values are not undefined. * * @returns An object with the key-value pairs if the values are not undefined, otherwise an empty object. */ export function add>(obj: O): Prettify> { const filtered = {} for (const key of Object.keys(obj)) { const value = obj[key] if (value !== undefined) { // @ts-ignore filtered[key] = value } } // @ts-ignore return filtered } export type RemoveArrayRepeats = { [K in keyof T]: T[number] extends { [P in keyof T]: P extends K ? never : T[P] }[number] ? never : T[K] } export function iterateEntries(node: Map, fn: (val: any) => any) { const newNode: Record = {} node.forEach(([key, val]) => { newNode[key] = fn(val) }) return newNode } export interface PackEntry { added: number downloads: { [key: string]: number } updated: number owner: string } export interface UserData { displayName: string } // eslint-disable-next-line no-shadow export enum HTTPResponses { OK = 200, CREATED = 201, BAD_REQUEST = 400, UNAUTHORIZED = 401, FORBIDDEN = 403, NOT_FOUND = 404, CONFLICT = 409, SERVER_ERROR = 500, } export type ReviewState = 'verified' | 'pending' | 'unsubmitted' | 'rejected' export async function safeWrite(...args: Partial>) { if (typeof args[0] !== 'string') throw new Error('unimplemented') await fs.ensureDir(args[0].replace(/(?:\/|\\)(?:.(?!(?:\/|\\)))+$/, '')) return fs.writeFile(...(args as Parameters<(typeof fs)['writeFile']>)) } export function sanitizeTarget(target: MultipleEntitiesArgument) { return `${target}`.toLowerCase().replaceAll(/-|=|\[|\]|\{|\}|:|"|'|,|@/g, '_') } /** * Formats a debug string for a class instance, including its arguments and body. * Must be called from the [util.inspect.custom] method. * * @param className The name of the class. * @param args The arguments passed to the class instance. It can be an array or an object. * @param body The body of the class instance, typically an array of nodes. * @param currentIndent The current indentation level. */ export function formatDebugString( className: string, args: undefined | any[] | Record | string, body: Node[] | undefined, currentIndent: string | undefined, ) { const FIXED_INDENT = ' ' const indent = currentIndent || '' const nextIndent = indent + FIXED_INDENT const options = { indent: nextIndent } as any let argsString if (typeof args === 'string') { argsString = args } else if (Array.isArray(args)) { argsString = args.map((arg) => util.inspect(arg, options)).join(', ') if (argsString.includes('\n')) { argsString = `\n${nextIndent}${args.map((arg) => util.inspect(arg, options).replaceAll('\n', `\n${nextIndent}`)).join(`,\n${nextIndent}`)}` } } else if (args && typeof args === 'object') { argsString = Object.entries(args) .map(([key, value]) => `${key}: ${util.inspect(value, options)}`) .join(', ') } else { argsString = '' } const bodyString = typeof body === 'undefined' ? '' : body .map((node) => { return util.inspect(node, options) }) .join(`\n${nextIndent}`) const rainbowBracketColors = [ 'yellow', 'green', 'cyan', 'blue', 'magenta', 'redBright', 'yellowBright', 'greenBright', 'cyanBright', 'blueBright', 'magentaBright', ] as const const bracketColor = rainbowBracketColors[(indent.length / FIXED_INDENT.length) % rainbowBracketColors.length] const realArgsString = argsString.length === 0 ? '' : `(${argsString})` const realBodyString = bodyString.length === 0 ? '' : ` ${util.styleText(bracketColor, '{')}\n${nextIndent}${bodyString}\n${indent}${util.styleText(bracketColor, '}')}` const classNameString = (util as any).styleText('green', className) return `${classNameString}${realArgsString}${realBodyString}` } export type AllKeys = T extends T ? keyof T : never type GetConstructorArgs = T extends new (...args: infer U) => any ? U : never export class Set extends global.Set { // oxlint-disable-next-line constructor(...args: GetConstructorArgs>) { super(...args) } has(value: unknown) { return super.has(value as any) } } export type SetType = T extends Set ? U : never type TestMembers = { [K in keyof T]: TestDispatcher[K extends keyof TestDispatcher ? K : never] } type NegatedMembers = { [K in keyof T as `!${Extract}`]?: Record } export type MemberModifiers = Partial & NegatedMembers type UnknownKey = { [K in NamespacedString]?: UnknownValue } type UnknownNegatableKey = ({ [K in `!${string}:${string}`]?: Record } & { [K in NamespacedString]?: UnknownValue | Record }) type McdocIDMapBase = Dispatcher & UnknownKey /** * A mapping of dispatcher IDs to their corresponding value types. * * Also supports unknown namespaced IDs. * * Must specify at least one key. * * ---- * * Disclaimers: * - Do not reference an ID multiple times. Multiple keys for the same ID (e.g. `acacia_button` and `minecraft:acacia_button`) will not cause a Typescript error due to limitations, but will cause an error in-game. * - Unknown IDs will not satisfy the Typed requirement of specifying at least one key, so either a known key must be also specified or `as any` must be placed at the end of the object. */ export type McdocIDMap = Partial> & { [K in keyof Dispatcher]-?: Record[K]> }[keyof Dispatcher] type McdocIDTestMapBase = TestMembers & UnknownKey /** * A mapping of dispatcher IDs to their corresponding value types. * * Also supports unknown namespaced IDs. * * Must specify at least one key. * * ---- * * Disclaimers: * - Do not reference an ID multiple times. Multiple keys for the same ID (e.g. `acacia_button` and `minecraft:acacia_button`) will not cause a Typescript error due to limitations, but will cause an error in-game. * - Unknown IDs will not satisfy the Typed requirement of specifying at least one key, so either a known key must be also specified or `as any` must be placed at the end of the object. */ export type McdocIDTestMap = Partial> & { [K in keyof TestMembers]-?: Record[K]> }[keyof TestMembers] type McdocNegatableIDMapBase = MemberModifiers & UnknownNegatableKey /** * A mapping of dispatcher IDs to their corresponding value types, with support for negated keys that equal an empty object. * * Also supports unknown namespaced IDs and negated unknown namespaced IDs. * * Must specify at least one key. * * ---- * * Disclaimers: * - Do not reference an ID multiple times. Multiple keys for the same ID (e.g. `acacia_button` and `minecraft:acacia_button` and `!acacia_button`) will not cause a Typescript error due to limitations, but will cause an error in-game. * - Unknown IDs will not satisfy the Typed requirement of specifying at least one key, so either a known key must be also specified or `as any` must be placed at the end of the object. * - The object type will allow non-negated Unknown IDs specified to an empty object, this is due to a types limitation, but will cause an error in-game. */ export type McdocNegatableIDMap = Partial> & { [K in keyof MemberModifiers]-?: Record[K]> }[keyof MemberModifiers] export type Enumerate< N extends number, Acc extends number[] = [], > = ( number extends N ? number // Guard against wide 'number' : Acc["length"] extends N ? Acc[number] : Enumerate ) export type BuildNeverTuple = ( number extends N ? never[] // Guard against wide 'number' : T['length'] extends N ? T : BuildNeverTuple ) export type Increment = ( number extends N ? number // Guard against wide 'number' : [...BuildNeverTuple, never]['length'] & number ) /** * `0..` * * Can be made exclusive of zero via `Exclude, 0>` */ export type PositiveNumber = ( number extends T ? never : `${T}` extends `-${string}` ? never : T ) /** * `..<0`; Cannot be zero nor above zero. * * Can be made inclusive via `NegativeNumber | 0` */ export type NegativeNumber = ( number extends T ? never : `${T}` extends `-${string}` ? T : never ) /** * No decimal allowed. */ export type WholeNumber = ( number extends T ? never : `${T}` extends `${string}.${string}` ? never : T ) /** * `0..` & no decimal allowed. * * Can be made exclusive of zero via `Exclude, 0>` */ export type PositiveWholeNumber = ( PositiveNumber extends never ? never : WholeNumber extends never ? never : N ) /** * `..-1` & no decimal allowed. * * Can include zero via `NegativeWholeNumber | 0` */ export type NegativeWholeNumber = ( number extends T ? never : `${T}` extends `${string}.${string}` ? never : `${T}` extends `-${string}` ? T : never ) /** * `0<..<1`; Cannot be zero nor one, below zero, nor above one. * * Can be made inclusive by adding unioned `0`/`1` literals. (eg. `PositiveFraction | 0 | 1`) */ export type PositiveFraction = ( number extends T ? never : `${T}` extends `0.${string}` ? T : never ) /** * `-1<..<0`; Cannot be negative one nor zero, below negative one, nor above zero. * * Can be made inclusive by adding unioned `-1`/`0` literals. (eg. `NegativeFraction | -1 | 0`) */ export type NegativeFraction = ( number extends T ? never : `${T}` extends `-0.${string}` ? T : never ) /** * Converts a positive numeric literal to its negative counterpart. * Example: ToNegative<5> -> -5 */ export type ToNegative = ( T extends 0 ? 0 : `-${T}` extends `${infer N extends number}` ? N : never ) /** * Checks if a number literal is negative by checking its string representation. */ export type IsNegative = `${N}` extends `-${string}` ? true : false /** * Gets the absolute value of a number. */ export type Abs = `${N}` extends `-${infer U extends number}` ? U : N /** * Creates a union of numbers from 0 to N-1. */ export type RangeTo = Enumerate /** * Generates a union of numbers between two positive integers (inclusive). */ export type PositiveRange = Exclude>, Enumerate> /** * The core logic for NBTInt<{ min: -5, max: 2 }> */ export type SmartRange = ( IsNegative extends true ? IsNegative extends true ? ToNegative, Abs>> : ToNegative>> | 0 | PositiveRange<1, Max> : PositiveRange ) export type AllowConst = T | Readonly export type RemoveFirst = T extends [any, ...infer Rest] ? Rest : [] export type BuildTuple = ( Accumulator['length'] extends Length ? Accumulator : BuildTuple )