From 97dbf11a10835911694392dcad57e6e32c51899d Mon Sep 17 00:00:00 2001 From: crazyRBLX11 <165557662+crazyRBLX11@users.noreply.github.com> Date: Tue, 29 Oct 2024 12:19:22 +0000 Subject: [PATCH] Atom required packages added Added most of the packages Atom uses to the source. Fixed some of the issues flagged by Selene and Roblox LSP and moved the old update logs from the Atom modules to it's own .MD file. --- Pre-0.5-Update-Logs.md | 18 + src/Atom/Atom.lua | 6 +- .../AtomModuleContents/AtomClient_OOP.lua | 16 +- .../AtomModuleContents/AtomServer_OOP.lua | 79 +- .../AtomModuleContents/Core/Serializer.lua | 1 + .../AtomModuleContents/Utils/ModuleLoader.lua | 7 +- src/Atom/Components/RemoteEvent.lua | 7 +- src/Atom/Packages/GoodSignal.lua | 180 ++ src/Atom/Packages/Janitor.lua | 753 ++++++ src/Atom/Packages/Promise.lua | 2068 +++++++++++++++++ src/Atom/Packages/Sourceesque.lua | 269 +++ src/Atom/Packages/Switch.lua | 104 + src/Atom/Packages/TextLib.lua | 36 + 13 files changed, 3459 insertions(+), 85 deletions(-) create mode 100644 Pre-0.5-Update-Logs.md create mode 100644 src/Atom/Packages/GoodSignal.lua create mode 100644 src/Atom/Packages/Janitor.lua create mode 100644 src/Atom/Packages/Promise.lua create mode 100644 src/Atom/Packages/Sourceesque.lua create mode 100644 src/Atom/Packages/Switch.lua create mode 100644 src/Atom/Packages/TextLib.lua diff --git a/Pre-0.5-Update-Logs.md b/Pre-0.5-Update-Logs.md new file mode 100644 index 0000000..fe673a2 --- /dev/null +++ b/Pre-0.5-Update-Logs.md @@ -0,0 +1,18 @@ +V0.1 +Implemented a simple module loader. + +V0.2 +Moved some of the code in the main script into modular code for readability. +Added SubTicks. +Temporarily removed my ModuleLoader as it broke intellisense. +Added the serializer. + +V0.4 +Implemented the AtomMain.GetService() function, +Implemented the AtomMain.CreateRemoteEvent() function, +Implemented the AtomMain.CreateUnreliableEvent() function, +Implented the Atom.GetSignal() function, + +V0.5 +Moved the serializer to a seperate script for modularity and added a copy of it's requirements to it. +Fixed the cylical dependency bug in the Module Loader. \ No newline at end of file diff --git a/src/Atom/Atom.lua b/src/Atom/Atom.lua index 132b2aa..07e4ab8 100644 --- a/src/Atom/Atom.lua +++ b/src/Atom/Atom.lua @@ -1,12 +1,12 @@ local RunService = game:GetService("RunService") if RunService:IsServer() then - return require(script.AtomServer_OOP) + return require(script:FindFirstChild("AtomServer_OOP", true)) else - local AtomServer = script:FindFirstChild("AtomServer_OOP") + local AtomServer = script:FindFirstChild("AtomServer_OOP", true) if AtomServer and RunService:IsRunning() then AtomServer:Destroy() end - return require(script.AtomClient_OOP) + return require(script:FindFirstChild("AtomClient_OOP", true)) end \ No newline at end of file diff --git a/src/Atom/AtomModuleContents/AtomClient_OOP.lua b/src/Atom/AtomModuleContents/AtomClient_OOP.lua index 043219f..4ac12ee 100644 --- a/src/Atom/AtomModuleContents/AtomClient_OOP.lua +++ b/src/Atom/AtomModuleContents/AtomClient_OOP.lua @@ -14,7 +14,6 @@ local AtomMain = {} local AtomRoot = script.Parent.Parent local started = false -local startComplete = false -- Make Types for tables and arrays as they don't officially have types. type tab = { [string] : string | boolean | Instance } @@ -30,12 +29,7 @@ local Packages = AtomRoot:WaitForChild("Packages") --[[local function require(Directory:Instance, ScriptName:string) return ModuleLoader.new(Directory, ScriptName) end ]] -local function wait(seconds:number) - return task.wait(seconds) -end -local function Wait(duration:number) - return task.wait(duration) -end + local function SubTick() return tick() / 2 end @@ -154,7 +148,7 @@ function AtomMain.Start() controllerInitPromises, Promise.new(function(r) debug.setmemorycategory(Controller.Name) - local controllertouse = require(Controllers, Controller.Name) + local controllertouse = require(Controllers) controllertouse.new() controllertouse:Init() r() @@ -175,7 +169,7 @@ function AtomMain.Start() controllersStartPromises, Promise.new(function(r) debug.setmemorycategory(controller.Name) - local controllertouse = require(Controllers, controller.Name) + local controllertouse = require(Controllers) controllertouse.new() controllertouse:Start() r() @@ -184,7 +178,7 @@ function AtomMain.Start() end end - startComplete = true + started = true local EndTick = tick() local EndSubTick = SubTick() onCompletedSignal:Fire("Atom has started succesfully.") @@ -204,7 +198,7 @@ end end end ]] -local Core = script.Parent.Core.Client +local Core = script.Parent.Core return { versiondetails = { major = 0, minor = 1, isrelease = false }, diff --git a/src/Atom/AtomModuleContents/AtomServer_OOP.lua b/src/Atom/AtomModuleContents/AtomServer_OOP.lua index df44b89..c60fc88 100644 --- a/src/Atom/AtomModuleContents/AtomServer_OOP.lua +++ b/src/Atom/AtomModuleContents/AtomServer_OOP.lua @@ -5,26 +5,7 @@ Rewrite of my 2019-2021 framework. ~31/10/2023 crazyattaker1 -V0.1 -Started Development. - -V0.2 -Moved some of the code in the main script into modular code for readability. -Added SubTicks. -Temporarily removed my ModuleLoader as it broke intellisense. -Added the serializer. - -V0.4 -Implemented the AtomMain.GetService() function, -Implemented the AtomMain.CreateRemoteEvent() function, -Implemented the AtomMain.CreateUnreliableEvent() function, -Implented the Atom.GetSignal() function, - -V0.5 -Moved the serializer to a seperate script for modularity and added a copy of it's requirements to it. -Fixed the cylical dependency bug in the Module Loader. - -Tools Used in Atom Development: VSCode Insider Edition, Argon Code Sync. +Tools Used in Atom Development: VSCode Insider Edition, GitHub, GitHub Desktop, Git, Roblox Studio and Argon Code Sync. ]] @@ -35,45 +16,27 @@ local AtomRoot = script.Parent.Parent AtomRoot.Parent = game:GetService("ReplicatedStorage") local started: boolean = false -local startComplete: boolean = false -- Set Important Directories -local Services = AtomRoot.Services -- Needed for custom require and it will be needed further in the script. -local Controllers = AtomRoot.Controllers -local Components = AtomRoot.Components +local Services : Folder = AtomRoot.Services -- Needed for custom require and it will be needed further in the script. +local Controllers : Folder = AtomRoot.Controllers +local Components : Folder = AtomRoot.Components local Packages = AtomRoot:WaitForChild("Packages") -local Utility = Packages.Utility - -- Overwrite Functions local ModuleLoader = require(script.Parent.Utils.ModuleLoader) -- Needed for custom require. --[[local function require(Directory:Instance, ScriptName:string) return ModuleLoader:require(Directory, ScriptName) -end ]] +end ]] -- Removed while I try fix the Intellisense issues it causes. function SubTick() return tick() / 2 end ---[[ Currently unused as it broke intellisense. [[ -local BSON = require(Packages, "BSON") -local ByteNet = require(Packages, "ByteNet") -local GoodSignal = require(Packages, "GoodSignal") -local Janitor = require(Packages, "Janitor") -local Promise = require(Packages, "Promise") -local Proto = require(Packages, "proto") -local ProfileService = require(Packages, "ProfileService") -local Sourceesque = require(Packages, "Sourceesque") -local Warp = require(Packages, "Warp") -local RestrictRead = require(Utility, "restrictRead") -local Switch, case, default = unpack(require(Packages, "Switch")) ]] - -local BSON = require(Packages.BSON) local ByteNet = require(Packages.ByteNet) local GoodSignal = require(Packages.GoodSignal) local Janitor = require(Packages.Janitor) local Promise = require(Packages.Promise) -local Proto = require(Packages.proto) local ProfileService = require(Packages.ProfileService) local Sourceesque = require(Packages.Sourceesque) local Warp = require(Packages.Warp) @@ -115,6 +78,11 @@ function Clean(WorkingJanitor) return "Cleaned." end +function AtomMain.Clean(WorkingJanitor) + WorkingJanitor:Cleanup() + return "Cleaned." +end + --[[ Start the framework. @@ -130,13 +98,11 @@ Atom.Start() ]] function AtomMain.Start() if started then return Promise.reject("Atom has already started.") end - if _VERSION ~= "Luau" then ErrorSignal:Fire("Running on an External Lua Runtime.") return end + if _VERSION ~= "Luau" then ErrorSignal:Fire("Atom can't run on non Luau Runtimes.") return end local StartTick = tick() local StartSubTick = SubTick() - started = true - return Promise.new(function(resolve) -- Create a Janitor to clean unneeded files post setup. local InitJanitor = Janitor.new() @@ -161,10 +127,8 @@ function AtomMain.Start() if CurrentFolderItterations < MaxFolderItterations then CurrentFolderItterations = CurrentFolderItterations + 1 print("Currently on the " .. CurrentFolderItterations .. " itteration.") - if v:IsA("Folder") then -- If it's a Folder, continue. + if v:IsA("Folder") then if v:GetAttribute("Cleanable") ~= false then - -- Reads through the directory to find any files to be moved before - -- preparing it to be cleaned. for _, scriptObject in pairs(v:GetChildren()) do InitJanitor:Add(v) end @@ -196,24 +160,7 @@ function AtomMain.Start() print(Clean(InitJanitor)) resolve(Promise.all(servicesInitPromises)) end):andThen(function() - --[[local servicesStartPromises = {} - - for _, service in ipairs(Services:GetDescendants()) do - if service:IsA("ModuleScript") and service.Name:match("Service$") then - table.insert( - servicesStartPromises, - Promise.new(function(r) - debug.setmemorycategory(service.Name) - local servicetouse = require(Services:WaitForChild(service.Name)) - local serviceClass = servicetouse.new() - serviceClass:Start() - r() - end) - ) - end - end ]] - - startComplete = true + started = true local EndTick = tick() local EndSubTick = SubTick() onCompletedSignal:Fire("Atom has started succesfully.") diff --git a/src/Atom/AtomModuleContents/Core/Serializer.lua b/src/Atom/AtomModuleContents/Core/Serializer.lua index c66dd94..240e856 100644 --- a/src/Atom/AtomModuleContents/Core/Serializer.lua +++ b/src/Atom/AtomModuleContents/Core/Serializer.lua @@ -20,6 +20,7 @@ function Serializer.serialize(Buffer: buffer, offset: number, DataType: string, case("table")(function() for i, v in ipairs(Data) do + print("Atom Serializer "..i) Serializer.serialize(Buffer, offset, DataType, v) -- recursively serialize each element in the table end end), diff --git a/src/Atom/AtomModuleContents/Utils/ModuleLoader.lua b/src/Atom/AtomModuleContents/Utils/ModuleLoader.lua index c0b30bc..f2c5507 100644 --- a/src/Atom/AtomModuleContents/Utils/ModuleLoader.lua +++ b/src/Atom/AtomModuleContents/Utils/ModuleLoader.lua @@ -5,14 +5,15 @@ ModuleLoader.__index = ModuleLoader function ModuleLoader:require(Directory, ScriptName:string) local Modules = Directory:GetChildren() - + for i, v in ipairs(Modules) do if v:IsA("ModuleScript") and v.Name == ScriptName then print("Module Loader: "..i..". Requiring "..v:GetFullName()) - return require(v) + local mod : ModuleScript = require(v) + return mod end end - + return nil end diff --git a/src/Atom/Components/RemoteEvent.lua b/src/Atom/Components/RemoteEvent.lua index 684892e..3a6c63a 100644 --- a/src/Atom/Components/RemoteEvent.lua +++ b/src/Atom/Components/RemoteEvent.lua @@ -18,6 +18,7 @@ local function serialize(Buffer : buffer, offset : number, DataType:string , Dat end elseif dataType == "table" then for i, v in ipairs(Data) do + print("Atom Serializer "..i) serialize(Buffer, offset, DataType, v) -- recursively serialize each element in the table end else @@ -26,13 +27,15 @@ local function serialize(Buffer : buffer, offset : number, DataType:string , Dat end function ServerRemoteEvent.new(RemoteName:string, Parent:Instance) - local ServerRemoteEventInstance = Instance.new("RemoteEvent", Parent) + local ServerRemoteEventInstance = Instance.new("RemoteEvent") + ServerRemoteEventInstance.Parent = Parent ServerRemoteEventInstance.Name = RemoteName return ServerRemoteEventInstance end function ClientRemoteEvent.new(RemoteName:string, Parent:Instance) - local ClientRemoteEventInstance = Instance.new("RemoteEvent", Parent) + local ClientRemoteEventInstance = Instance.new("RemoteEvent") + ClientRemoteEventInstance.Parent = Parent ClientRemoteEventInstance.Name = RemoteName return ClientRemoteEventInstance end diff --git a/src/Atom/Packages/GoodSignal.lua b/src/Atom/Packages/GoodSignal.lua new file mode 100644 index 0000000..e3a1129 --- /dev/null +++ b/src/Atom/Packages/GoodSignal.lua @@ -0,0 +1,180 @@ +-------------------------------------------------------------------------------- +-- Batched Yield-Safe Signal Implementation -- +-- This is a Signal class which has effectively identical behavior to a -- +-- normal RBXScriptSignal, with the only difference being a couple extra -- +-- stack frames at the bottom of the stack trace when an error is thrown. -- +-- This implementation caches runner coroutines, so the ability to yield in -- +-- the signal handlers comes at minimal extra cost over a naive signal -- +-- implementation that either always or never spawns a thread. -- +-- -- +-- API: -- +-- local Signal = require(THIS MODULE) -- +-- local sig = Signal.new() -- +-- local connection = sig:Connect(function(arg1, arg2, ...) ... end) -- +-- sig:Fire(arg1, arg2, ...) -- +-- connection:Disconnect() -- +-- sig:DisconnectAll() -- +-- local arg1, arg2, ... = sig:Wait() -- +-- -- +-- Licence: -- +-- Licenced under the MIT licence. -- +-- -- +-- Authors: -- +-- stravant - July 31st, 2021 - Created the file. -- +-------------------------------------------------------------------------------- + +-- The currently idle thread to run the next handler on +local freeRunnerThread = nil + +-- Function which acquires the currently idle handler runner thread, runs the +-- function fn on it, and then releases the thread, returning it to being the +-- currently idle one. +-- If there was a currently idle runner thread already, that's okay, that old +-- one will just get thrown and eventually GCed. +local function acquireRunnerThreadAndCallEventHandler(fn, ...) + local acquiredRunnerThread = freeRunnerThread + freeRunnerThread = nil + fn(...) + -- The handler finished running, this runner thread is free again. + freeRunnerThread = acquiredRunnerThread +end + +-- Coroutine runner that we create coroutines of. The coroutine can be +-- repeatedly resumed with functions to run followed by the argument to run +-- them with. +local function runEventHandlerInFreeThread() + -- Note: We cannot use the initial set of arguments passed to + -- runEventHandlerInFreeThread for a call to the handler, because those + -- arguments would stay on the stack for the duration of the thread's + -- existence, temporarily leaking references. Without access to raw bytecode + -- there's no way for us to clear the "..." references from the stack. + while true do + acquireRunnerThreadAndCallEventHandler(coroutine.yield()) + end +end + +-- Connection class +local Connection = {} +Connection.__index = Connection + +function Connection.new(signal, fn) + return setmetatable({ + _connected = true, + _signal = signal, + _fn = fn, + _next = false, + }, Connection) +end + +function Connection:Disconnect() + self._connected = false + + -- Unhook the node, but DON'T clear it. That way any fire calls that are + -- currently sitting on this node will be able to iterate forwards off of + -- it, but any subsequent fire calls will not hit it, and it will be GCed + -- when no more fire calls are sitting on it. + if self._signal._handlerListHead == self then + self._signal._handlerListHead = self._next + else + local prev = self._signal._handlerListHead + while prev and prev._next ~= self do + prev = prev._next + end + if prev then + prev._next = self._next + end + end +end + +-- Make Connection strict +setmetatable(Connection, { + __index = function(tb, key) + error(("Attempt to get Connection::%s (not a valid member)"):format(tostring(key)), 2) + end, + __newindex = function(tb, key, value) + error(("Attempt to set Connection::%s (not a valid member)"):format(tostring(key)), 2) + end +}) + +-- Signal class +local Signal = {} +Signal.__index = Signal + +function Signal.new() + return setmetatable({ + _handlerListHead = false, + }, Signal) +end + +function Signal:Connect(fn) + local connection = Connection.new(self, fn) + if self._handlerListHead then + connection._next = self._handlerListHead + self._handlerListHead = connection + else + self._handlerListHead = connection + end + return connection +end + +-- Disconnect all handlers. Since we use a linked list it suffices to clear the +-- reference to the head handler. +function Signal:DisconnectAll() + self._handlerListHead = false +end + +-- Signal:Fire(...) implemented by running the handler functions on the +-- coRunnerThread, and any time the resulting thread yielded without returning +-- to us, that means that it yielded to the Roblox scheduler and has been taken +-- over by Roblox scheduling, meaning we have to make a new coroutine runner. +function Signal:Fire(...) + local item = self._handlerListHead + while item do + if item._connected then + if not freeRunnerThread then + freeRunnerThread = coroutine.create(runEventHandlerInFreeThread) + -- Get the freeRunnerThread to the first yield + coroutine.resume(freeRunnerThread) + end + task.spawn(freeRunnerThread, item._fn, ...) + end + item = item._next + end +end + +-- Implement Signal:Wait() in terms of a temporary connection using +-- a Signal:Connect() which disconnects itself. +function Signal:Wait() + local waitingCoroutine = coroutine.running() + local cn; + cn = self:Connect(function(...) + cn:Disconnect() + task.spawn(waitingCoroutine, ...) + end) + return coroutine.yield() +end + +-- Implement Signal:Once() in terms of a connection which disconnects +-- itself before running the handler. +function Signal:Once(fn) + local cn; + cn = self:Connect(function(...) + if cn._connected then + cn:Disconnect() + end + fn(...) + end) + return cn +end + +-- Make signal strict +setmetatable(Signal, { + __index = function(tb, key) + error(("Attempt to get Signal::%s (not a valid member)"):format(tostring(key)), 2) + end, + __newindex = function(tb, key, value) + error(("Attempt to set Signal::%s (not a valid member)"):format(tostring(key)), 2) + end +}) + +return Signal diff --git a/src/Atom/Packages/Janitor.lua b/src/Atom/Packages/Janitor.lua new file mode 100644 index 0000000..362887a --- /dev/null +++ b/src/Atom/Packages/Janitor.lua @@ -0,0 +1,753 @@ +--!strict +-- Compiled with L+ C Edition +-- Janitor +-- Original by Validark +-- Modifications by pobammer +-- roblox-ts support by OverHash and Validark +-- LinkToInstance fixed by Elttob. +-- Cleanup edge cases fixed by codesenseAye. + +local Promise = require(script.Parent.Promise) + +local IndicesReference = setmetatable({}, { + __tostring = function() + return "IndicesReference" + end; +}) + +local LinkToInstanceIndex = setmetatable({}, { + __tostring = function() + return "LinkToInstanceIndex" + end; +}) + +local INVALID_METHOD_NAME = + "Object is a %* and as such expected `true?` for the method name and instead got %*. Traceback: %*" +local METHOD_NOT_FOUND_ERROR = "Object %* doesn't have method %*, are you sure you want to add it? Traceback: %*" +local NOT_A_PROMISE = "Invalid argument #1 to 'Janitor:AddPromise' (Promise expected, got %* (%*)) Traceback: %*" + +--[=[ + Janitor is a light-weight, flexible object for cleaning up connections, instances, or anything. This implementation covers all use cases, + as it doesn't force you to rely on naive typechecking to guess how an instance should be cleaned up. + Instead, the developer may specify any behavior for any object. + + @class Janitor +]=] +local Janitor = {} +Janitor.ClassName = "Janitor" +Janitor.CurrentlyCleaning = true +Janitor.SuppressInstanceReDestroy = false +Janitor[IndicesReference] = nil +Janitor.__index = Janitor + +--[=[ + @prop CurrentlyCleaning boolean + @readonly + @within Janitor + + Whether or not the Janitor is currently cleaning up. +]=] + +--[=[ + @prop SuppressInstanceReDestroy boolean + @within Janitor + @since 1.15.4 + + Whether or not you want to suppress the re-destroying + of instances. Default is false, which is the original + behavior. +]=] + +local TypeDefaults = { + ["function"] = true; + thread = true; + RBXScriptConnection = "Disconnect"; +} + +--[=[ + Instantiates a new Janitor object. + @return Janitor +]=] +function Janitor.new(): Janitor + return setmetatable({ + CurrentlyCleaning = false; + [IndicesReference] = nil; + }, Janitor) :: any +end + +--[=[ + Determines if the passed object is a Janitor. This checks the metatable directly. + + @param Object any -- The object you are checking. + @return boolean -- `true` if `Object` is a Janitor. +]=] +function Janitor.Is(Object: any): boolean + return type(Object) == "table" and getmetatable(Object) == Janitor +end + +type BooleanOrString = boolean | string + +--[=[ + Adds an `Object` to Janitor for later cleanup, where `MethodName` is the key of the method within `Object` which should be called at cleanup time. + If the `MethodName` is `true` the `Object` itself will be called if it's a function or have `task.cancel` called on it if it is a thread. If passed + an index it will occupy a namespace which can be `Remove()`d or overwritten. Returns the `Object`. + + :::info + Objects not given an explicit `MethodName` will be passed into the `typeof` function for a very naive typecheck. + RBXConnections will be assigned to "Disconnect", functions and threads will be assigned to `true`, and everything else will default to "Destroy". + Not recommended, but hey, you do you. + ::: + + ### Luau: + + ```lua + local Workspace = game:GetService("Workspace") + local TweenService = game:GetService("TweenService") + + local Obliterator = Janitor.new() + local Part = Workspace.Part + + -- Queue the Part to be Destroyed at Cleanup time + Obliterator:Add(Part, "Destroy") + + -- Queue function to be called with `true` MethodName + Obliterator:Add(print, true) + + -- Close a thread. + Obliterator:Add(task.defer(function() + while true do + print("Running!") + task.wait(0.5) + end + end), true) + + -- This implementation allows you to specify behavior for any object + Obliterator:Add(TweenService:Create(Part, TweenInfo.new(1), {Size = Vector3.new(1, 1, 1)}), "Cancel") + + -- By passing an Index, the Object will occupy a namespace + -- If "CurrentTween" already exists, it will call :Remove("CurrentTween") before writing + Obliterator:Add(TweenService:Create(Part, TweenInfo.new(1), {Size = Vector3.new(1, 1, 1)}), "Destroy", "CurrentTween") + ``` + + ### TypeScript: + + ```ts + import { Workspace, TweenService } from "@rbxts/services"; + import { Janitor } from "@rbxts/janitor"; + + const Obliterator = new Janitor<{ CurrentTween: Tween }>(); + const Part = Workspace.FindFirstChild("Part") as Part; + + // Queue the Part to be Destroyed at Cleanup time + Obliterator.Add(Part, "Destroy"); + + // Queue function to be called with `true` MethodName + Obliterator.Add(print, true); + + // Close a thread. + Obliterator.Add(task.defer(() => { + while (true) { + print("Running!"); + task.wait(0.5); + } + }), true); + + // This implementation allows you to specify behavior for any object + Obliterator.Add(TweenService.Create(Part, new TweenInfo(1), {Size: new Vector3(1, 1, 1)}), "Cancel"); + + // By passing an Index, the Object will occupy a namespace + // If "CurrentTween" already exists, it will call :Remove("CurrentTween") before writing + Obliterator.Add(TweenService.Create(Part, new TweenInfo(1), {Size: new Vector3(1, 1, 1)}), "Destroy", "CurrentTween"); + ``` + + @param Object T -- The object you want to clean up. + @param MethodName? boolean | string -- The name of the method that will be used to clean up. If not passed, it will first check if the object's type exists in TypeDefaults, and if that doesn't exist, it assumes `Destroy`. + @param Index? any -- The index that can be used to clean up the object manually. + @return T -- The object that was passed as the first argument. +]=] +function Janitor:Add(Object: T, MethodName: BooleanOrString?, Index: any?): T + if Index then + self:Remove(Index) + + local This = self[IndicesReference] + if not This then + This = {} + self[IndicesReference] = This + end + + This[Index] = Object + end + + local TypeOf = typeof(Object) + local NewMethodName = MethodName or TypeDefaults[TypeOf] or "Destroy" + + if TypeOf == "function" or TypeOf == "thread" then + if NewMethodName ~= true then + warn(string.format(INVALID_METHOD_NAME, TypeOf, tostring(NewMethodName), debug.traceback(nil, 2))) + end + else + if not (Object :: any)[NewMethodName] then + warn( + string.format( + METHOD_NOT_FOUND_ERROR, + tostring(Object), + tostring(NewMethodName), + debug.traceback(nil, 2) + ) + ) + end + end + + self[Object] = NewMethodName + return Object +end + +--[=[ + Adds a [Promise](https://github.com/evaera/roblox-lua-promise) to the Janitor. If the Janitor is cleaned up and the Promise is not completed, the Promise will be cancelled. + + ### Luau: + + ```lua + local Obliterator = Janitor.new() + Obliterator:AddPromise(Promise.delay(3)):andThenCall(print, "Finished!"):catch(warn) + task.wait(1) + Obliterator:Cleanup() + ``` + + ### TypeScript: + + ```ts + import { Janitor } from "@rbxts/janitor"; + + const Obliterator = new Janitor(); + Obliterator.AddPromise(Promise.delay(3)).andThenCall(print, "Finished!").catch(warn); + task.wait(1); + Obliterator.Cleanup(); + ``` + + @param PromiseObject Promise -- The promise you want to add to the Janitor. + @return Promise +]=] +function Janitor:AddPromise(PromiseObject) + if not Promise.is(PromiseObject) then + error(string.format(NOT_A_PROMISE, typeof(PromiseObject), tostring(PromiseObject), debug.traceback(nil, 2))) + end + + if PromiseObject:getStatus() == Promise.Status.Started then + local Id = newproxy(false) + local NewPromise = self:Add(Promise.new(function(Resolve, _, OnCancel) + if OnCancel(function() + PromiseObject:cancel() + end) then + return + end + + Resolve(PromiseObject) + end), "cancel", Id) + + NewPromise:finallyCall(self.Remove, self, Id) + return NewPromise + else + return PromiseObject + end +end + +--[=[ + Cleans up whatever `Object` was set to this namespace by the 3rd parameter of [Janitor.Add](#Add). + + ### Luau: + + ```lua + local Obliterator = Janitor.new() + Obliterator:Add(workspace.Baseplate, "Destroy", "Baseplate") + Obliterator:Remove("Baseplate") + ``` + + ### TypeScript: + + ```ts + import { Workspace } from "@rbxts/services"; + import { Janitor } from "@rbxts/janitor"; + + const Obliterator = new Janitor<{ Baseplate: Part }>(); + Obliterator.Add(Workspace.FindFirstChild("Baseplate") as Part, "Destroy", "Baseplate"); + Obliterator.Remove("Baseplate"); + ``` + + @param Index any -- The index you want to remove. + @return Janitor +]=] +function Janitor:Remove(Index: any) + local This = self[IndicesReference] + + if This then + local Object = This[Index] + + if Object then + local MethodName = self[Object] + + if MethodName then + if MethodName == true then + if type(Object) == "function" then + Object() + else + local Cancelled + if coroutine.running() ~= Object then + Cancelled = pcall(function() + task.cancel(Object) + end) + end + + if not Cancelled then + task.defer(function() + if Object then + task.cancel(Object) + end + end) + end + end + else + local ObjectMethod = Object[MethodName] + if ObjectMethod then + if + self.SuppressInstanceReDestroy + and MethodName == "Destroy" + and typeof(Object) == "Instance" + then + pcall(ObjectMethod, Object) + else + ObjectMethod(Object) + end + end + end + + self[Object] = nil + end + + This[Index] = nil + end + end + + return self +end + +--[=[ + Removes an object from the Janitor without running a cleanup. + + ### Luau + + ```lua + local Obliterator = Janitor.new() + Obliterator:Add(function() + print("Removed!") + end, true, "Function") + + Obliterator:RemoveNoClean("Function") -- Does not print. + ``` + + ### TypeScript: + + ```ts + import { Janitor } from "@rbxts/janitor"; + + const Obliterator = new Janitor<{ Function: () => void }>(); + Obliterator.Add(() => print("Removed!"), true, "Function"); + + Obliterator.RemoveNoClean("Function"); // Does not print. + ``` + + @since v1.15 + @param Index any -- The index you are removing. + @return Janitor +]=] +function Janitor:RemoveNoClean(Index: any) + local This = self[IndicesReference] + + if This then + local Object = This[Index] + if Object then + self[Object] = nil + end + + This[Index] = nil + end + + return self +end + +--[=[ + Cleans up multiple objects at once. + + ### Luau: + + ```lua + local Obliterator = Janitor.new() + Obliterator:Add(function() + print("Removed One") + end, true, "One") + + Obliterator:Add(function() + print("Removed Two") + end, true, "Two") + + Obliterator:Add(function() + print("Removed Three") + end, true, "Three") + + Obliterator:RemoveList("One", "Two", "Three") -- Prints "Removed One", "Removed Two", and "Removed Three" + ``` + + ### TypeScript: + + ```ts + import { Janitor } from "@rbxts/janitor"; + + type NoOp = () => void + + const Obliterator = new Janitor<{ One: NoOp, Two: NoOp, Three: NoOp }>(); + Obliterator.Add(() => print("Removed One"), true, "One"); + Obliterator.Add(() => print("Removed Two"), true, "Two"); + Obliterator.Add(() => print("Removed Three"), true, "Three"); + + Obliterator.RemoveList("One", "Two", "Three"); // Prints "Removed One", "Removed Two", and "Removed Three" + ``` + + @since v1.14 + @param ... any -- The indices you want to remove. + @return Janitor +]=] +function Janitor:RemoveList(...: any) + local This = self[IndicesReference] + if This then + local Length = select("#", ...) + if Length == 1 then + return self:Remove(...) + else + for SelectIndex = 1, Length do + self:Remove(select(SelectIndex, ...)) + end + end + end + + return self +end + +--[=[ + Cleans up multiple objects at once without running their cleanup. + + ### Luau: + + ```lua + local Obliterator = Janitor.new() + Obliterator:Add(function() + print("Removed One") + end, true, "One") + + Obliterator:Add(function() + print("Removed Two") + end, true, "Two") + + Obliterator:Add(function() + print("Removed Three") + end, true, "Three") + + Obliterator:RemoveListNoClean("One", "Two", "Three") -- Nothing is printed. + ``` + + ### TypeScript: + + ```ts + import { Janitor } from "@rbxts/janitor"; + + type NoOp = () => void + + const Obliterator = new Janitor<{ One: NoOp, Two: NoOp, Three: NoOp }>(); + Obliterator.Add(() => print("Removed One"), true, "One"); + Obliterator.Add(() => print("Removed Two"), true, "Two"); + Obliterator.Add(() => print("Removed Three"), true, "Three"); + + Obliterator.RemoveListNoClean("One", "Two", "Three"); // Nothing is printed. + ``` + + @since v1.15 + @param ... any -- The indices you want to remove. + @return Janitor +]=] +function Janitor:RemoveListNoClean(...: any) + local This = self[IndicesReference] + if This then + local Length = select("#", ...) + if Length == 1 then + return self:RemoveNoClean(...) + else + for SelectIndex = 1, Length do + -- MACRO + local Index = select(SelectIndex, ...) + local Object = This[Index] + if Object then + self[Object] = nil + end + + This[Index] = nil + end + end + end + + return self +end + +--[=[ + Gets whatever object is stored with the given index, if it exists. This was added since Maid allows getting the task using `__index`. + + ### Luau: + + ```lua + local Obliterator = Janitor.new() + Obliterator:Add(workspace.Baseplate, "Destroy", "Baseplate") + print(Obliterator:Get("Baseplate")) -- Returns Baseplate. + ``` + + ### TypeScript: + + ```ts + import { Workspace } from "@rbxts/services"; + import { Janitor } from "@rbxts/janitor"; + + const Obliterator = new Janitor<{ Baseplate: Part }>(); + Obliterator.Add(Workspace.FindFirstChild("Baseplate") as Part, "Destroy", "Baseplate"); + print(Obliterator.Get("Baseplate")); // Returns Baseplate. + ``` + + @param Index any -- The index that the object is stored under. + @return any? -- This will return the object if it is found, but it won't return anything if it doesn't exist. +]=] +function Janitor:Get(Index: any): any? + local This = self[IndicesReference] + return if This then This[Index] else nil +end + +--[=[ + Returns a frozen copy of the Janitor's indices. + + ### Luau: + + ```lua + local Obliterator = Janitor.new() + Obliterator:Add(workspace.Baseplate, "Destroy", "Baseplate") + print(Obliterator:GetAll().Baseplate) -- Prints Baseplate. + ``` + + ### TypeScript: + + ```ts + import { Workspace } from "@rbxts/services"; + import { Janitor } from "@rbxts/janitor"; + + const Obliterator = new Janitor<{ Baseplate: Part }>(); + Obliterator.Add(Workspace.FindFirstChild("Baseplate") as Part, "Destroy", "Baseplate"); + print(Obliterator.GetAll().Baseplate); // Prints Baseplate. + ``` + + @since v1.15.1 + @return {[any]: any} +]=] +function Janitor:GetAll(): {[any]: any} + local This = self[IndicesReference] + return if This then table.freeze(table.clone(This)) else {} +end + +local function GetFenv(self) + return function() + for Object, MethodName in next, self do + if Object ~= IndicesReference and Object ~= "SuppressInstanceReDestroy" then + return Object, MethodName + end + end + end +end + +--[=[ + Calls each Object's `MethodName` (or calls the Object if `MethodName == true`) and removes them from the Janitor. Also clears the namespace. + This function is also called when you call a Janitor Object (so it can be used as a destructor callback). + + ### Luau: + + ```lua + Obliterator:Cleanup() -- Valid. + Obliterator() -- Also valid. + ``` + + ### TypeScript: + + ```ts + Obliterator.Cleanup() + ``` +]=] +function Janitor:Cleanup() + if not self.CurrentlyCleaning then + self.CurrentlyCleaning = nil + + local Get = GetFenv(self) + local Object, MethodName = Get() + + while Object and MethodName do -- changed to a while loop so that if you add to the janitor inside of a callback it doesn't get untracked (instead it will loop continuously which is a lot better than a hard to pindown edgecase) + if MethodName == true then + if type(Object) == "function" then + Object() + else + local Cancelled + if coroutine.running() ~= Object then + Cancelled = pcall(function() + task.cancel(Object) + end) + end + + if not Cancelled then + task.defer(function() + if Object then + task.cancel(Object) + end + end) + end + end + else + local ObjectMethod = Object[MethodName] + if ObjectMethod then + if self.SuppressInstanceReDestroy and MethodName == "Destroy" and typeof(Object) == "Instance" then + pcall(ObjectMethod, Object) + else + ObjectMethod(Object) + end + end + end + + self[Object] = nil + Object, MethodName = Get() + end + + local This = self[IndicesReference] + if This then + table.clear(This) + self[IndicesReference] = {} + end + + self.CurrentlyCleaning = false + end +end + +--[=[ + Calls [Janitor.Cleanup](#Cleanup) and renders the Janitor unusable. + + :::warning + Running this will make any further attempts to call a method of Janitor error. + ::: +]=] +function Janitor:Destroy() + self:Cleanup() + table.clear(self) + setmetatable(self, nil) +end + +Janitor.__call = Janitor.Cleanup + +--[=[ + "Links" this Janitor to an Instance, such that the Janitor will `Cleanup` when the Instance is `Destroyed()` and garbage collected. + A Janitor may only be linked to one instance at a time, unless `AllowMultiple` is true. When called with a truthy `AllowMultiple` parameter, + the Janitor will "link" the Instance without overwriting any previous links, and will also not be overwritable. + When called with a falsy `AllowMultiple` parameter, the Janitor will overwrite the previous link which was also called with a falsy `AllowMultiple` parameter, if applicable. + + ### Luau: + + ```lua + local Obliterator = Janitor.new() + + Obliterator:Add(function() + print("Cleaning up!") + end, true) + + do + local Folder = Instance.new("Folder") + Obliterator:LinkToInstance(Folder) + Folder:Destroy() + end + ``` + + ### TypeScript: + + ```ts + import { Janitor } from "@rbxts/janitor"; + + const Obliterator = new Janitor(); + Obliterator.Add(() => print("Cleaning up!"), true); + + { + const Folder = new Instance("Folder"); + Obliterator.LinkToInstance(Folder, false); + Folder.Destroy(); + } + ``` + + @param Object Instance -- The instance you want to link the Janitor to. + @param AllowMultiple? boolean -- Whether or not to allow multiple links on the same Janitor. + @return RBXScriptConnection -- A RBXScriptConnection that can be disconnected to prevent the cleanup of LinkToInstance. +]=] +function Janitor:LinkToInstance(Object: Instance, AllowMultiple: boolean?): RBXScriptConnection + local IndexToUse = if AllowMultiple then newproxy(false) else LinkToInstanceIndex + + return self:Add(Object.Destroying:Connect(function() + self:Cleanup() + end), "Disconnect", IndexToUse) +end + +Janitor.LegacyLinkToInstance = Janitor.LinkToInstance + +--[=[ + Links several instances to a new Janitor, which is then returned. + + @param ... Instance -- All the Instances you want linked. + @return Janitor -- A new Janitor that can be used to manually disconnect all LinkToInstances. +]=] +function Janitor:LinkToInstances(...: Instance) + local ManualCleanup = Janitor.new() + for Index = 1, select("#", ...) do + local Object = select(Index, ...) + if typeof(Object) ~= "Instance" then + continue + end + + ManualCleanup:Add(self:LinkToInstance(Object, true), "Disconnect") + end + + return ManualCleanup +end + +function Janitor:__tostring() + return "Janitor" +end + +export type Janitor = { + ClassName: "Janitor", + CurrentlyCleaning: boolean, + SuppressInstanceReDestroy: boolean, + + Add: (self: Janitor, Object: T, MethodName: BooleanOrString?, Index: any?) -> T, + AddPromise: (self: Janitor, PromiseObject: T) -> T, + + Remove: (self: Janitor, Index: any) -> Janitor, + RemoveNoClean: (self: Janitor, Index: any) -> Janitor, + + RemoveList: (self: Janitor, ...any) -> Janitor, + RemoveListNoClean: (self: Janitor, ...any) -> Janitor, + + Get: (self: Janitor, Index: any) -> any?, + GetAll: (self: Janitor) -> {[any]: any}, + + Cleanup: (self: Janitor) -> (), + Destroy: (self: Janitor) -> (), + + LinkToInstance: (self: Janitor, Object: Instance, AllowMultiple: boolean?) -> RBXScriptConnection, + LinkToInstances: (self: Janitor, ...Instance) -> Janitor, +} + +table.freeze(Janitor) +return Janitor diff --git a/src/Atom/Packages/Promise.lua b/src/Atom/Packages/Promise.lua new file mode 100644 index 0000000..97cdf37 --- /dev/null +++ b/src/Atom/Packages/Promise.lua @@ -0,0 +1,2068 @@ +--[[ + An implementation of Promises similar to Promise/A+. +]] + +local ERROR_NON_PROMISE_IN_LIST = "Non-promise value passed into %s at index %s" +local ERROR_NON_LIST = "Please pass a list of promises to %s" +local ERROR_NON_FUNCTION = "Please pass a handler function to %s!" +local MODE_KEY_METATABLE = { __mode = "k" } + +local function isCallable(value) + if type(value) == "function" then + return true + end + + if type(value) == "table" then + local metatable = getmetatable(value) + if metatable and type(rawget(metatable, "__call")) == "function" then + return true + end + end + + return false +end + +--[[ + Creates an enum dictionary with some metamethods to prevent common mistakes. +]] +local function makeEnum(enumName, members) + local enum = {} + + for _, memberName in ipairs(members) do + enum[memberName] = memberName + end + + return setmetatable(enum, { + __index = function(_, k) + error(string.format("%s is not in %s!", k, enumName), 2) + end, + __newindex = function() + error(string.format("Creating new members in %s is not allowed!", enumName), 2) + end, + }) +end + +--[=[ + An object to represent runtime errors that occur during execution. + Promises that experience an error like this will be rejected with + an instance of this object. + + @class Error +]=] +local Error +do + Error = { + Kind = makeEnum("Promise.Error.Kind", { + "ExecutionError", + "AlreadyCancelled", + "NotResolvedInTime", + "TimedOut", + }), + } + Error.__index = Error + + function Error.new(options, parent) + options = options or {} + return setmetatable({ + error = tostring(options.error) or "[This error has no error text.]", + trace = options.trace, + context = options.context, + kind = options.kind, + parent = parent, + createdTick = os.clock(), + createdTrace = debug.traceback(), + }, Error) + end + + function Error.is(anything) + if type(anything) == "table" then + local metatable = getmetatable(anything) + + if type(metatable) == "table" then + return rawget(anything, "error") ~= nil and type(rawget(metatable, "extend")) == "function" + end + end + + return false + end + + function Error.isKind(anything, kind) + assert(kind ~= nil, "Argument #2 to Promise.Error.isKind must not be nil") + + return Error.is(anything) and anything.kind == kind + end + + function Error:extend(options) + options = options or {} + + options.kind = options.kind or self.kind + + return Error.new(options, self) + end + + function Error:getErrorChain() + local runtimeErrors = { self } + + while runtimeErrors[#runtimeErrors].parent do + table.insert(runtimeErrors, runtimeErrors[#runtimeErrors].parent) + end + + return runtimeErrors + end + + function Error:__tostring() + local errorStrings = { + string.format("-- Promise.Error(%s) --", self.kind or "?"), + } + + for _, runtimeError in ipairs(self:getErrorChain()) do + table.insert( + errorStrings, + table.concat({ + runtimeError.trace or runtimeError.error, + runtimeError.context, + }, "\n") + ) + end + + return table.concat(errorStrings, "\n") + end +end + +--[[ + Packs a number of arguments into a table and returns its length. + + Used to cajole varargs without dropping sparse values. +]] +local function pack(...) + return select("#", ...), { ... } +end + +--[[ + Returns first value (success), and packs all following values. +]] +local function packResult(success, ...) + return success, select("#", ...), { ... } +end + +local function makeErrorHandler(traceback) + assert(traceback ~= nil, "traceback is nil") + + return function(err) + -- If the error object is already a table, forward it directly. + -- Should we extend the error here and add our own trace? + + if type(err) == "table" then + return err + end + + return Error.new({ + error = err, + kind = Error.Kind.ExecutionError, + trace = debug.traceback(tostring(err), 2), + context = "Promise created at:\n\n" .. traceback, + }) + end +end + +--[[ + Calls a Promise executor with error handling. +]] +local function runExecutor(traceback, callback, ...) + return packResult(xpcall(callback, makeErrorHandler(traceback), ...)) +end + +--[[ + Creates a function that invokes a callback with correct error handling and + resolution mechanisms. +]] +local function createAdvancer(traceback, callback, resolve, reject) + return function(...) + local ok, resultLength, result = runExecutor(traceback, callback, ...) + + if ok then + resolve(unpack(result, 1, resultLength)) + else + reject(result[1]) + end + end +end + +local function isEmpty(t) + return next(t) == nil +end + +--[=[ + An enum value used to represent the Promise's status. + @interface Status + @tag enum + @within Promise + .Started "Started" -- The Promise is executing, and not settled yet. + .Resolved "Resolved" -- The Promise finished successfully. + .Rejected "Rejected" -- The Promise was rejected. + .Cancelled "Cancelled" -- The Promise was cancelled before it finished. +]=] +--[=[ + @prop Status Status + @within Promise + @readonly + @tag enums + A table containing all members of the `Status` enum, e.g., `Promise.Status.Resolved`. +]=] +--[=[ + A Promise is an object that represents a value that will exist in the future, but doesn't right now. + Promises allow you to then attach callbacks that can run once the value becomes available (known as *resolving*), + or if an error has occurred (known as *rejecting*). + + @class Promise + @__index prototype +]=] +local Promise = { + Error = Error, + Status = makeEnum("Promise.Status", { "Started", "Resolved", "Rejected", "Cancelled" }), + _getTime = os.clock, + _timeEvent = game:GetService("RunService").Heartbeat, + _unhandledRejectionCallbacks = {}, +} +Promise.prototype = {} +Promise.__index = Promise.prototype + +function Promise._new(traceback, callback, parent) + if parent ~= nil and not Promise.is(parent) then + error("Argument #2 to Promise.new must be a promise or nil", 2) + end + + local self = { + -- The executor thread. + _thread = nil, + + -- Used to locate where a promise was created + _source = traceback, + + _status = Promise.Status.Started, + + -- A table containing a list of all results, whether success or failure. + -- Only valid if _status is set to something besides Started + _values = nil, + + -- Lua doesn't like sparse arrays very much, so we explicitly store the + -- length of _values to handle middle nils. + _valuesLength = -1, + + -- Tracks if this Promise has no error observers.. + _unhandledRejection = true, + + -- Queues representing functions we should invoke when we update! + _queuedResolve = {}, + _queuedReject = {}, + _queuedFinally = {}, + + -- The function to run when/if this promise is cancelled. + _cancellationHook = nil, + + -- The "parent" of this promise in a promise chain. Required for + -- cancellation propagation upstream. + _parent = parent, + + -- Consumers are Promises that have chained onto this one. + -- We track them for cancellation propagation downstream. + _consumers = setmetatable({}, MODE_KEY_METATABLE), + } + + if parent and parent._status == Promise.Status.Started then + parent._consumers[self] = true + end + + setmetatable(self, Promise) + + local function resolve(...) + self:_resolve(...) + end + + local function reject(...) + self:_reject(...) + end + + local function onCancel(cancellationHook) + if cancellationHook then + if self._status == Promise.Status.Cancelled then + cancellationHook() + else + self._cancellationHook = cancellationHook + end + end + + return self._status == Promise.Status.Cancelled + end + + self._thread = coroutine.create(function() + local ok, _, result = runExecutor(self._source, callback, resolve, reject, onCancel) + + if not ok then + reject(result[1]) + end + end) + + task.spawn(self._thread) + + return self +end + +--[=[ + Construct a new Promise that will be resolved or rejected with the given callbacks. + + If you `resolve` with a Promise, it will be chained onto. + + You can safely yield within the executor function and it will not block the creating thread. + + ```lua + local myFunction() + return Promise.new(function(resolve, reject, onCancel) + wait(1) + resolve("Hello world!") + end) + end + + myFunction():andThen(print) + ``` + + You do not need to use `pcall` within a Promise. Errors that occur during execution will be caught and turned into a rejection automatically. If `error()` is called with a table, that table will be the rejection value. Otherwise, string errors will be converted into `Promise.Error(Promise.Error.Kind.ExecutionError)` objects for tracking debug information. + + You may register an optional cancellation hook by using the `onCancel` argument: + + * This should be used to abort any ongoing operations leading up to the promise being settled. + * Call the `onCancel` function with a function callback as its only argument to set a hook which will in turn be called when/if the promise is cancelled. + * `onCancel` returns `true` if the Promise was already cancelled when you called `onCancel`. + * Calling `onCancel` with no argument will not override a previously set cancellation hook, but it will still return `true` if the Promise is currently cancelled. + * You can set the cancellation hook at any time before resolving. + * When a promise is cancelled, calls to `resolve` or `reject` will be ignored, regardless of if you set a cancellation hook or not. + + :::caution + If the Promise is cancelled, the `executor` thread is closed with `coroutine.close` after the cancellation hook is called. + + You must perform any cleanup code in the cancellation hook: any time your executor yields, it **may never resume**. + ::: + + @param executor (resolve: (...: any) -> (), reject: (...: any) -> (), onCancel: (abortHandler?: () -> ()) -> boolean) -> () + @return Promise +]=] +function Promise.new(executor) + return Promise._new(debug.traceback(nil, 2), executor) +end + +function Promise:__tostring() + return string.format("Promise(%s)", self._status) +end + +--[=[ + The same as [Promise.new](/api/Promise#new), except execution begins after the next `Heartbeat` event. + + This is a spiritual replacement for `spawn`, but it does not suffer from the same [issues](https://eryn.io/gist/3db84579866c099cdd5bb2ff37947cec) as `spawn`. + + ```lua + local function waitForChild(instance, childName, timeout) + return Promise.defer(function(resolve, reject) + local child = instance:WaitForChild(childName, timeout) + + ;(child and resolve or reject)(child) + end) + end + ``` + + @param executor (resolve: (...: any) -> (), reject: (...: any) -> (), onCancel: (abortHandler?: () -> ()) -> boolean) -> () + @return Promise +]=] +function Promise.defer(executor) + local traceback = debug.traceback(nil, 2) + local promise + promise = Promise._new(traceback, function(resolve, reject, onCancel) + local connection + connection = Promise._timeEvent:Connect(function() + connection:Disconnect() + local ok, _, result = runExecutor(traceback, executor, resolve, reject, onCancel) + + if not ok then + reject(result[1]) + end + end) + end) + + return promise +end + +-- Backwards compatibility +Promise.async = Promise.defer + +--[=[ + Creates an immediately resolved Promise with the given value. + + ```lua + -- Example using Promise.resolve to deliver cached values: + function getSomething(name) + if cache[name] then + return Promise.resolve(cache[name]) + else + return Promise.new(function(resolve, reject) + local thing = getTheThing() + cache[name] = thing + + resolve(thing) + end) + end + end + ``` + + @param ... any + @return Promise<...any> +]=] +function Promise.resolve(...) + local length, values = pack(...) + return Promise._new(debug.traceback(nil, 2), function(resolve) + resolve(unpack(values, 1, length)) + end) +end + +--[=[ + Creates an immediately rejected Promise with the given value. + + :::caution + Something needs to consume this rejection (i.e. `:catch()` it), otherwise it will emit an unhandled Promise rejection warning on the next frame. Thus, you should not create and store rejected Promises for later use. Only create them on-demand as needed. + ::: + + @param ... any + @return Promise<...any> +]=] +function Promise.reject(...) + local length, values = pack(...) + return Promise._new(debug.traceback(nil, 2), function(_, reject) + reject(unpack(values, 1, length)) + end) +end + +--[[ + Runs a non-promise-returning function as a Promise with the + given arguments. +]] +function Promise._try(traceback, callback, ...) + local valuesLength, values = pack(...) + + return Promise._new(traceback, function(resolve) + resolve(callback(unpack(values, 1, valuesLength))) + end) +end + +--[=[ + Begins a Promise chain, calling a function and returning a Promise resolving with its return value. If the function errors, the returned Promise will be rejected with the error. You can safely yield within the Promise.try callback. + + :::info + `Promise.try` is similar to [Promise.promisify](#promisify), except the callback is invoked immediately instead of returning a new function. + ::: + + ```lua + Promise.try(function() + return math.random(1, 2) == 1 and "ok" or error("Oh an error!") + end) + :andThen(function(text) + print(text) + end) + :catch(function(err) + warn("Something went wrong") + end) + ``` + + @param callback (...: T...) -> ...any + @param ... T... -- Additional arguments passed to `callback` + @return Promise +]=] +function Promise.try(callback, ...) + return Promise._try(debug.traceback(nil, 2), callback, ...) +end + +--[[ + Returns a new promise that: + * is resolved when all input promises resolve + * is rejected if ANY input promises reject +]] +function Promise._all(traceback, promises, amount) + if type(promises) ~= "table" then + error(string.format(ERROR_NON_LIST, "Promise.all"), 3) + end + + -- We need to check that each value is a promise here so that we can produce + -- a proper error rather than a rejected promise with our error. + for i, promise in pairs(promises) do + if not Promise.is(promise) then + error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.all", tostring(i)), 3) + end + end + + -- If there are no values then return an already resolved promise. + if #promises == 0 or amount == 0 then + return Promise.resolve({}) + end + + return Promise._new(traceback, function(resolve, reject, onCancel) + -- An array to contain our resolved values from the given promises. + local resolvedValues = {} + local newPromises = {} + + -- Keep a count of resolved promises because just checking the resolved + -- values length wouldn't account for promises that resolve with nil. + local resolvedCount = 0 + local rejectedCount = 0 + local done = false + + local function cancel() + for _, promise in ipairs(newPromises) do + promise:cancel() + end + end + + -- Called when a single value is resolved and resolves if all are done. + local function resolveOne(i, ...) + if done then + return + end + + resolvedCount = resolvedCount + 1 + + if amount == nil then + resolvedValues[i] = ... + else + resolvedValues[resolvedCount] = ... + end + + if resolvedCount >= (amount or #promises) then + done = true + resolve(resolvedValues) + cancel() + end + end + + onCancel(cancel) + + -- We can assume the values inside `promises` are all promises since we + -- checked above. + for i, promise in ipairs(promises) do + newPromises[i] = promise:andThen(function(...) + resolveOne(i, ...) + end, function(...) + rejectedCount = rejectedCount + 1 + + if amount == nil or #promises - rejectedCount < amount then + cancel() + done = true + + reject(...) + end + end) + end + + if done then + cancel() + end + end) +end + +--[=[ + Accepts an array of Promises and returns a new promise that: + * is resolved after all input promises resolve. + * is rejected if *any* input promises reject. + + :::info + Only the first return value from each promise will be present in the resulting array. + ::: + + After any input Promise rejects, all other input Promises that are still pending will be cancelled if they have no other consumers. + + ```lua + local promises = { + returnsAPromise("example 1"), + returnsAPromise("example 2"), + returnsAPromise("example 3"), + } + + return Promise.all(promises) + ``` + + @param promises {Promise} + @return Promise<{T}> +]=] +function Promise.all(promises) + return Promise._all(debug.traceback(nil, 2), promises) +end + +--[=[ + Folds an array of values or promises into a single value. The array is traversed sequentially. + + The reducer function can return a promise or value directly. Each iteration receives the resolved value from the previous, and the first receives your defined initial value. + + The folding will stop at the first rejection encountered. + ```lua + local basket = {"blueberry", "melon", "pear", "melon"} + Promise.fold(basket, function(cost, fruit) + if fruit == "blueberry" then + return cost -- blueberries are free! + else + -- call a function that returns a promise with the fruit price + return fetchPrice(fruit):andThen(function(fruitCost) + return cost + fruitCost + end) + end + end, 0) + ``` + + @since v3.1.0 + @param list {T | Promise} + @param reducer (accumulator: U, value: T, index: number) -> U | Promise + @param initialValue U +]=] +function Promise.fold(list, reducer, initialValue) + assert(type(list) == "table", "Bad argument #1 to Promise.fold: must be a table") + assert(isCallable(reducer), "Bad argument #2 to Promise.fold: must be a function") + + local accumulator = Promise.resolve(initialValue) + return Promise.each(list, function(resolvedElement, i) + accumulator = accumulator:andThen(function(previousValueResolved) + return reducer(previousValueResolved, resolvedElement, i) + end) + end):andThen(function() + return accumulator + end) +end + +--[=[ + Accepts an array of Promises and returns a Promise that is resolved as soon as `count` Promises are resolved from the input array. The resolved array values are in the order that the Promises resolved in. When this Promise resolves, all other pending Promises are cancelled if they have no other consumers. + + `count` 0 results in an empty array. The resultant array will never have more than `count` elements. + + ```lua + local promises = { + returnsAPromise("example 1"), + returnsAPromise("example 2"), + returnsAPromise("example 3"), + } + + return Promise.some(promises, 2) -- Only resolves with first 2 promises to resolve + ``` + + @param promises {Promise} + @param count number + @return Promise<{T}> +]=] +function Promise.some(promises, count) + assert(type(count) == "number", "Bad argument #2 to Promise.some: must be a number") + + return Promise._all(debug.traceback(nil, 2), promises, count) +end + +--[=[ + Accepts an array of Promises and returns a Promise that is resolved as soon as *any* of the input Promises resolves. It will reject only if *all* input Promises reject. As soon as one Promises resolves, all other pending Promises are cancelled if they have no other consumers. + + Resolves directly with the value of the first resolved Promise. This is essentially [[Promise.some]] with `1` count, except the Promise resolves with the value directly instead of an array with one element. + + ```lua + local promises = { + returnsAPromise("example 1"), + returnsAPromise("example 2"), + returnsAPromise("example 3"), + } + + return Promise.any(promises) -- Resolves with first value to resolve (only rejects if all 3 rejected) + ``` + + @param promises {Promise} + @return Promise +]=] +function Promise.any(promises) + return Promise._all(debug.traceback(nil, 2), promises, 1):andThen(function(values) + return values[1] + end) +end + +--[=[ + Accepts an array of Promises and returns a new Promise that resolves with an array of in-place Statuses when all input Promises have settled. This is equivalent to mapping `promise:finally` over the array of Promises. + + ```lua + local promises = { + returnsAPromise("example 1"), + returnsAPromise("example 2"), + returnsAPromise("example 3"), + } + + return Promise.allSettled(promises) + ``` + + @param promises {Promise} + @return Promise<{Status}> +]=] +function Promise.allSettled(promises) + if type(promises) ~= "table" then + error(string.format(ERROR_NON_LIST, "Promise.allSettled"), 2) + end + + -- We need to check that each value is a promise here so that we can produce + -- a proper error rather than a rejected promise with our error. + for i, promise in pairs(promises) do + if not Promise.is(promise) then + error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.allSettled", tostring(i)), 2) + end + end + + -- If there are no values then return an already resolved promise. + if #promises == 0 then + return Promise.resolve({}) + end + + return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel) + -- An array to contain our resolved values from the given promises. + local fates = {} + local newPromises = {} + + -- Keep a count of resolved promises because just checking the resolved + -- values length wouldn't account for promises that resolve with nil. + local finishedCount = 0 + + -- Called when a single value is resolved and resolves if all are done. + local function resolveOne(i, ...) + finishedCount = finishedCount + 1 + + fates[i] = ... + + if finishedCount >= #promises then + resolve(fates) + end + end + + onCancel(function() + for _, promise in ipairs(newPromises) do + promise:cancel() + end + end) + + -- We can assume the values inside `promises` are all promises since we + -- checked above. + for i, promise in ipairs(promises) do + newPromises[i] = promise:finally(function(...) + resolveOne(i, ...) + end) + end + end) +end + +--[=[ + Accepts an array of Promises and returns a new promise that is resolved or rejected as soon as any Promise in the array resolves or rejects. + + :::warning + If the first Promise to settle from the array settles with a rejection, the resulting Promise from `race` will reject. + + If you instead want to tolerate rejections, and only care about at least one Promise resolving, you should use [Promise.any](#any) or [Promise.some](#some) instead. + ::: + + All other Promises that don't win the race will be cancelled if they have no other consumers. + + ```lua + local promises = { + returnsAPromise("example 1"), + returnsAPromise("example 2"), + returnsAPromise("example 3"), + } + + return Promise.race(promises) -- Only returns 1st value to resolve or reject + ``` + + @param promises {Promise} + @return Promise +]=] +function Promise.race(promises) + assert(type(promises) == "table", string.format(ERROR_NON_LIST, "Promise.race")) + + for i, promise in pairs(promises) do + assert(Promise.is(promise), string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.race", tostring(i))) + end + + return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel) + local newPromises = {} + local finished = false + + local function cancel() + for _, promise in ipairs(newPromises) do + promise:cancel() + end + end + + local function finalize(callback) + return function(...) + cancel() + finished = true + return callback(...) + end + end + + if onCancel(finalize(reject)) then + return + end + + for i, promise in ipairs(promises) do + newPromises[i] = promise:andThen(finalize(resolve), finalize(reject)) + end + + if finished then + cancel() + end + end) +end + +--[=[ + Iterates serially over the given an array of values, calling the predicate callback on each value before continuing. + + If the predicate returns a Promise, we wait for that Promise to resolve before moving on to the next item + in the array. + + :::info + `Promise.each` is similar to `Promise.all`, except the Promises are ran in order instead of all at once. + + But because Promises are eager, by the time they are created, they're already running. Thus, we need a way to defer creation of each Promise until a later time. + + The predicate function exists as a way for us to operate on our data instead of creating a new closure for each Promise. If you would prefer, you can pass in an array of functions, and in the predicate, call the function and return its return value. + ::: + + ```lua + Promise.each({ + "foo", + "bar", + "baz", + "qux" + }, function(value, index) + return Promise.delay(1):andThen(function() + print(("%d) Got %s!"):format(index, value)) + end) + end) + + --[[ + (1 second passes) + > 1) Got foo! + (1 second passes) + > 2) Got bar! + (1 second passes) + > 3) Got baz! + (1 second passes) + > 4) Got qux! + ]] + ``` + + If the Promise a predicate returns rejects, the Promise from `Promise.each` is also rejected with the same value. + + If the array of values contains a Promise, when we get to that point in the list, we wait for the Promise to resolve before calling the predicate with the value. + + If a Promise in the array of values is already Rejected when `Promise.each` is called, `Promise.each` rejects with that value immediately (the predicate callback will never be called even once). If a Promise in the list is already Cancelled when `Promise.each` is called, `Promise.each` rejects with `Promise.Error(Promise.Error.Kind.AlreadyCancelled`). If a Promise in the array of values is Started at first, but later rejects, `Promise.each` will reject with that value and iteration will not continue once iteration encounters that value. + + Returns a Promise containing an array of the returned/resolved values from the predicate for each item in the array of values. + + If this Promise returned from `Promise.each` rejects or is cancelled for any reason, the following are true: + - Iteration will not continue. + - Any Promises within the array of values will now be cancelled if they have no other consumers. + - The Promise returned from the currently active predicate will be cancelled if it hasn't resolved yet. + + @since 3.0.0 + @param list {T | Promise} + @param predicate (value: T, index: number) -> U | Promise + @return Promise<{U}> +]=] +function Promise.each(list, predicate) + assert(type(list) == "table", string.format(ERROR_NON_LIST, "Promise.each")) + assert(isCallable(predicate), string.format(ERROR_NON_FUNCTION, "Promise.each")) + + return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel) + local results = {} + local promisesToCancel = {} + + local cancelled = false + + local function cancel() + for _, promiseToCancel in ipairs(promisesToCancel) do + promiseToCancel:cancel() + end + end + + onCancel(function() + cancelled = true + + cancel() + end) + + -- We need to preprocess the list of values and look for Promises. + -- If we find some, we must register our andThen calls now, so that those Promises have a consumer + -- from us registered. If we don't do this, those Promises might get cancelled by something else + -- before we get to them in the series because it's not possible to tell that we plan to use it + -- unless we indicate it here. + + local preprocessedList = {} + + for index, value in ipairs(list) do + if Promise.is(value) then + if value:getStatus() == Promise.Status.Cancelled then + cancel() + return reject(Error.new({ + error = "Promise is cancelled", + kind = Error.Kind.AlreadyCancelled, + context = string.format( + "The Promise that was part of the array at index %d passed into Promise.each was already cancelled when Promise.each began.\n\nThat Promise was created at:\n\n%s", + index, + value._source + ), + })) + elseif value:getStatus() == Promise.Status.Rejected then + cancel() + return reject(select(2, value:await())) + end + + -- Chain a new Promise from this one so we only cancel ours + local ourPromise = value:andThen(function(...) + return ... + end) + + table.insert(promisesToCancel, ourPromise) + preprocessedList[index] = ourPromise + else + preprocessedList[index] = value + end + end + + for index, value in ipairs(preprocessedList) do + if Promise.is(value) then + local success + success, value = value:await() + + if not success then + cancel() + return reject(value) + end + end + + if cancelled then + return + end + + local predicatePromise = Promise.resolve(predicate(value, index)) + + table.insert(promisesToCancel, predicatePromise) + + local success, result = predicatePromise:await() + + if not success then + cancel() + return reject(result) + end + + results[index] = result + end + + resolve(results) + end) +end + +--[=[ + Checks whether the given object is a Promise via duck typing. This only checks if the object is a table and has an `andThen` method. + + @param object any + @return boolean -- `true` if the given `object` is a Promise. +]=] +function Promise.is(object) + if type(object) ~= "table" then + return false + end + + local objectMetatable = getmetatable(object) + + if objectMetatable == Promise then + -- The Promise came from this library. + return true + elseif objectMetatable == nil then + -- No metatable, but we should still chain onto tables with andThen methods + return isCallable(object.andThen) + elseif + type(objectMetatable) == "table" + and type(rawget(objectMetatable, "__index")) == "table" + and isCallable(rawget(rawget(objectMetatable, "__index"), "andThen")) + then + -- Maybe this came from a different or older Promise library. + return true + end + + return false +end + +--[=[ + Wraps a function that yields into one that returns a Promise. + + Any errors that occur while executing the function will be turned into rejections. + + :::info + `Promise.promisify` is similar to [Promise.try](#try), except the callback is returned as a callable function instead of being invoked immediately. + ::: + + ```lua + local sleep = Promise.promisify(wait) + + sleep(1):andThen(print) + ``` + + ```lua + local isPlayerInGroup = Promise.promisify(function(player, groupId) + return player:IsInGroup(groupId) + end) + ``` + + @param callback (...: any) -> ...any + @return (...: any) -> Promise +]=] +function Promise.promisify(callback) + return function(...) + return Promise._try(debug.traceback(nil, 2), callback, ...) + end +end + +--[=[ + Returns a Promise that resolves after `seconds` seconds have passed. The Promise resolves with the actual amount of time that was waited. + + This function is **not** a wrapper around `wait`. `Promise.delay` uses a custom scheduler which provides more accurate timing. As an optimization, cancelling this Promise instantly removes the task from the scheduler. + + :::warning + Passing `NaN`, infinity, or a number less than 1/60 is equivalent to passing 1/60. + ::: + + ```lua + Promise.delay(5):andThenCall(print, "This prints after 5 seconds") + ``` + + @function delay + @within Promise + @param seconds number + @return Promise +]=] +do + -- uses a sorted doubly linked list (queue) to achieve O(1) remove operations and O(n) for insert + + -- the initial node in the linked list + local first + local connection + + function Promise.delay(seconds) + assert(type(seconds) == "number", "Bad argument #1 to Promise.delay, must be a number.") + -- If seconds is -INF, INF, NaN, or less than 1 / 60, assume seconds is 1 / 60. + -- This mirrors the behavior of wait() + if not (seconds >= 1 / 60) or seconds == math.huge then + seconds = 1 / 60 + end + + return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel) + local startTime = Promise._getTime() + local endTime = startTime + seconds + + local node = { + resolve = resolve, + startTime = startTime, + endTime = endTime, + } + + if connection == nil then -- first is nil when connection is nil + first = node + connection = Promise._timeEvent:Connect(function() + local threadStart = Promise._getTime() + + while first ~= nil and first.endTime < threadStart do + local current = first + first = current.next + + if first == nil then + connection:Disconnect() + connection = nil + else + first.previous = nil + end + + current.resolve(Promise._getTime() - current.startTime) + end + end) + else -- first is non-nil + if first.endTime < endTime then -- if `node` should be placed after `first` + -- we will insert `node` between `current` and `next` + -- (i.e. after `current` if `next` is nil) + local current = first + local next = current.next + + while next ~= nil and next.endTime < endTime do + current = next + next = current.next + end + + -- `current` must be non-nil, but `next` could be `nil` (i.e. last item in list) + current.next = node + node.previous = current + + if next ~= nil then + node.next = next + next.previous = node + end + else + -- set `node` to `first` + node.next = first + first.previous = node + first = node + end + end + + onCancel(function() + -- remove node from queue + local next = node.next + + if first == node then + if next == nil then -- if `node` is the first and last + connection:Disconnect() + connection = nil + else -- if `node` is `first` and not the last + next.previous = nil + end + first = next + else + local previous = node.previous + -- since `node` is not `first`, then we know `previous` is non-nil + previous.next = next + + if next ~= nil then + next.previous = previous + end + end + end) + end) + end +end + +--[=[ + Returns a new Promise that resolves if the chained Promise resolves within `seconds` seconds, or rejects if execution time exceeds `seconds`. The chained Promise will be cancelled if the timeout is reached. + + Rejects with `rejectionValue` if it is non-nil. If a `rejectionValue` is not given, it will reject with a `Promise.Error(Promise.Error.Kind.TimedOut)`. This can be checked with [[Error.isKind]]. + + ```lua + getSomething():timeout(5):andThen(function(something) + -- got something and it only took at max 5 seconds + end):catch(function(e) + -- Either getting something failed or the time was exceeded. + + if Promise.Error.isKind(e, Promise.Error.Kind.TimedOut) then + warn("Operation timed out!") + else + warn("Operation encountered an error!") + end + end) + ``` + + Sugar for: + + ```lua + Promise.race({ + Promise.delay(seconds):andThen(function() + return Promise.reject( + rejectionValue == nil + and Promise.Error.new({ kind = Promise.Error.Kind.TimedOut }) + or rejectionValue + ) + end), + promise + }) + ``` + + @param seconds number + @param rejectionValue? any -- The value to reject with if the timeout is reached + @return Promise +]=] +function Promise.prototype:timeout(seconds, rejectionValue) + local traceback = debug.traceback(nil, 2) + + return Promise.race({ + Promise.delay(seconds):andThen(function() + return Promise.reject(rejectionValue == nil and Error.new({ + kind = Error.Kind.TimedOut, + error = "Timed out", + context = string.format( + "Timeout of %d seconds exceeded.\n:timeout() called at:\n\n%s", + seconds, + traceback + ), + }) or rejectionValue) + end), + self, + }) +end + +--[=[ + Returns the current Promise status. + + @return Status +]=] +function Promise.prototype:getStatus() + return self._status +end + +--[[ + Creates a new promise that receives the result of this promise. + + The given callbacks are invoked depending on that result. +]] +function Promise.prototype:_andThen(traceback, successHandler, failureHandler) + self._unhandledRejection = false + + -- If we are already cancelled, we return a cancelled Promise + if self._status == Promise.Status.Cancelled then + local promise = Promise.new(function() end) + promise:cancel() + + return promise + end + + -- Create a new promise to follow this part of the chain + return Promise._new(traceback, function(resolve, reject, onCancel) + -- Our default callbacks just pass values onto the next promise. + -- This lets success and failure cascade correctly! + + local successCallback = resolve + if successHandler then + successCallback = createAdvancer(traceback, successHandler, resolve, reject) + end + + local failureCallback = reject + if failureHandler then + failureCallback = createAdvancer(traceback, failureHandler, resolve, reject) + end + + if self._status == Promise.Status.Started then + -- If we haven't resolved yet, put ourselves into the queue + table.insert(self._queuedResolve, successCallback) + table.insert(self._queuedReject, failureCallback) + + onCancel(function() + -- These are guaranteed to exist because the cancellation handler is guaranteed to only + -- be called at most once + if self._status == Promise.Status.Started then + table.remove(self._queuedResolve, table.find(self._queuedResolve, successCallback)) + table.remove(self._queuedReject, table.find(self._queuedReject, failureCallback)) + end + end) + elseif self._status == Promise.Status.Resolved then + -- This promise has already resolved! Trigger success immediately. + successCallback(unpack(self._values, 1, self._valuesLength)) + elseif self._status == Promise.Status.Rejected then + -- This promise died a terrible death! Trigger failure immediately. + failureCallback(unpack(self._values, 1, self._valuesLength)) + end + end, self) +end + +--[=[ + Chains onto an existing Promise and returns a new Promise. + + :::warning + Within the failure handler, you should never assume that the rejection value is a string. Some rejections within the Promise library are represented by [[Error]] objects. If you want to treat it as a string for debugging, you should call `tostring` on it first. + ::: + + You can return a Promise from the success or failure handler and it will be chained onto. + + Calling `andThen` on a cancelled Promise returns a cancelled Promise. + + :::tip + If the Promise returned by `andThen` is cancelled, `successHandler` and `failureHandler` will not run. + + To run code no matter what, use [Promise:finally]. + ::: + + @param successHandler (...: any) -> ...any + @param failureHandler? (...: any) -> ...any + @return Promise<...any> +]=] +function Promise.prototype:andThen(successHandler, failureHandler) + assert(successHandler == nil or isCallable(successHandler), string.format(ERROR_NON_FUNCTION, "Promise:andThen")) + assert(failureHandler == nil or isCallable(failureHandler), string.format(ERROR_NON_FUNCTION, "Promise:andThen")) + + return self:_andThen(debug.traceback(nil, 2), successHandler, failureHandler) +end + +--[=[ + Shorthand for `Promise:andThen(nil, failureHandler)`. + + Returns a Promise that resolves if the `failureHandler` worked without encountering an additional error. + + :::warning + Within the failure handler, you should never assume that the rejection value is a string. Some rejections within the Promise library are represented by [[Error]] objects. If you want to treat it as a string for debugging, you should call `tostring` on it first. + ::: + + Calling `catch` on a cancelled Promise returns a cancelled Promise. + + :::tip + If the Promise returned by `catch` is cancelled, `failureHandler` will not run. + + To run code no matter what, use [Promise:finally]. + ::: + + @param failureHandler (...: any) -> ...any + @return Promise<...any> +]=] +function Promise.prototype:catch(failureHandler) + assert(failureHandler == nil or isCallable(failureHandler), string.format(ERROR_NON_FUNCTION, "Promise:catch")) + return self:_andThen(debug.traceback(nil, 2), nil, failureHandler) +end + +--[=[ + Similar to [Promise.andThen](#andThen), except the return value is the same as the value passed to the handler. In other words, you can insert a `:tap` into a Promise chain without affecting the value that downstream Promises receive. + + ```lua + getTheValue() + :tap(print) + :andThen(function(theValue) + print("Got", theValue, "even though print returns nil!") + end) + ``` + + If you return a Promise from the tap handler callback, its value will be discarded but `tap` will still wait until it resolves before passing the original value through. + + @param tapHandler (...: any) -> ...any + @return Promise<...any> +]=] +function Promise.prototype:tap(tapHandler) + assert(isCallable(tapHandler), string.format(ERROR_NON_FUNCTION, "Promise:tap")) + return self:_andThen(debug.traceback(nil, 2), function(...) + local callbackReturn = tapHandler(...) + + if Promise.is(callbackReturn) then + local length, values = pack(...) + return callbackReturn:andThen(function() + return unpack(values, 1, length) + end) + end + + return ... + end) +end + +--[=[ + Attaches an `andThen` handler to this Promise that calls the given callback with the predefined arguments. The resolved value is discarded. + + ```lua + promise:andThenCall(someFunction, "some", "arguments") + ``` + + This is sugar for + + ```lua + promise:andThen(function() + return someFunction("some", "arguments") + end) + ``` + + @param callback (...: any) -> any + @param ...? any -- Additional arguments which will be passed to `callback` + @return Promise +]=] +function Promise.prototype:andThenCall(callback, ...) + assert(isCallable(callback), string.format(ERROR_NON_FUNCTION, "Promise:andThenCall")) + local length, values = pack(...) + return self:_andThen(debug.traceback(nil, 2), function() + return callback(unpack(values, 1, length)) + end) +end + +--[=[ + Attaches an `andThen` handler to this Promise that discards the resolved value and returns the given value from it. + + ```lua + promise:andThenReturn("some", "values") + ``` + + This is sugar for + + ```lua + promise:andThen(function() + return "some", "values" + end) + ``` + + :::caution + Promises are eager, so if you pass a Promise to `andThenReturn`, it will begin executing before `andThenReturn` is reached in the chain. Likewise, if you pass a Promise created from [[Promise.reject]] into `andThenReturn`, it's possible that this will trigger the unhandled rejection warning. If you need to return a Promise, it's usually best practice to use [[Promise.andThen]]. + ::: + + @param ... any -- Values to return from the function + @return Promise +]=] +function Promise.prototype:andThenReturn(...) + local length, values = pack(...) + return self:_andThen(debug.traceback(nil, 2), function() + return unpack(values, 1, length) + end) +end + +--[=[ + Cancels this promise, preventing the promise from resolving or rejecting. Does not do anything if the promise is already settled. + + Cancellations will propagate upwards and downwards through chained promises. + + Promises will only be cancelled if all of their consumers are also cancelled. This is to say that if you call `andThen` twice on the same promise, and you cancel only one of the child promises, it will not cancel the parent promise until the other child promise is also cancelled. + + ```lua + promise:cancel() + ``` +]=] +function Promise.prototype:cancel() + if self._status ~= Promise.Status.Started then + return + end + + self._status = Promise.Status.Cancelled + + if self._cancellationHook then + self._cancellationHook() + end + + coroutine.close(self._thread) + + if self._parent then + self._parent:_consumerCancelled(self) + end + + for child in pairs(self._consumers) do + child:cancel() + end + + self:_finalize() +end + +--[[ + Used to decrease the number of consumers by 1, and if there are no more, + cancel this promise. +]] +function Promise.prototype:_consumerCancelled(consumer) + if self._status ~= Promise.Status.Started then + return + end + + self._consumers[consumer] = nil + + if next(self._consumers) == nil then + self:cancel() + end +end + +--[[ + Used to set a handler for when the promise resolves, rejects, or is + cancelled. +]] +function Promise.prototype:_finally(traceback, finallyHandler) + self._unhandledRejection = false + + local promise = Promise._new(traceback, function(resolve, reject, onCancel) + local handlerPromise + + onCancel(function() + -- The finally Promise is not a proper consumer of self. We don't care about the resolved value. + -- All we care about is running at the end. Therefore, if self has no other consumers, it's safe to + -- cancel. We don't need to hold out cancelling just because there's a finally handler. + self:_consumerCancelled(self) + + if handlerPromise then + handlerPromise:cancel() + end + end) + + local finallyCallback = resolve + if finallyHandler then + finallyCallback = function(...) + local callbackReturn = finallyHandler(...) + + if Promise.is(callbackReturn) then + handlerPromise = callbackReturn + + callbackReturn + :finally(function(status) + if status ~= Promise.Status.Rejected then + resolve(self) + end + end) + :catch(function(...) + reject(...) + end) + else + resolve(self) + end + end + end + + if self._status == Promise.Status.Started then + -- The promise is not settled, so queue this. + table.insert(self._queuedFinally, finallyCallback) + else + -- The promise already settled or was cancelled, run the callback now. + finallyCallback(self._status) + end + end) + + return promise +end + +--[=[ + Set a handler that will be called regardless of the promise's fate. The handler is called when the promise is + resolved, rejected, *or* cancelled. + + Returns a new Promise that: + - resolves with the same values that this Promise resolves with. + - rejects with the same values that this Promise rejects with. + - is cancelled if this Promise is cancelled. + + If the value you return from the handler is a Promise: + - We wait for the Promise to resolve, but we ultimately discard the resolved value. + - If the returned Promise rejects, the Promise returned from `finally` will reject with the rejected value from the + *returned* promise. + - If the `finally` Promise is cancelled, and you returned a Promise from the handler, we cancel that Promise too. + + Otherwise, the return value from the `finally` handler is entirely discarded. + + :::note Cancellation + As of Promise v4, `Promise:finally` does not count as a consumer of the parent Promise for cancellation purposes. + This means that if all of a Promise's consumers are cancelled and the only remaining callbacks are finally handlers, + the Promise is cancelled and the finally callbacks run then and there. + + Cancellation still propagates through the `finally` Promise though: if you cancel the `finally` Promise, it can cancel + its parent Promise if it had no other consumers. Likewise, if the parent Promise is cancelled, the `finally` Promise + will also be cancelled. + ::: + + ```lua + local thing = createSomething() + + doSomethingWith(thing) + :andThen(function() + print("It worked!") + -- do something.. + end) + :catch(function() + warn("Oh no it failed!") + end) + :finally(function() + -- either way, destroy thing + + thing:Destroy() + end) + + ``` + + @param finallyHandler (status: Status) -> ...any + @return Promise<...any> +]=] +function Promise.prototype:finally(finallyHandler) + assert(finallyHandler == nil or isCallable(finallyHandler), string.format(ERROR_NON_FUNCTION, "Promise:finally")) + return self:_finally(debug.traceback(nil, 2), finallyHandler) +end + +--[=[ + Same as `andThenCall`, except for `finally`. + + Attaches a `finally` handler to this Promise that calls the given callback with the predefined arguments. + + @param callback (...: any) -> any + @param ...? any -- Additional arguments which will be passed to `callback` + @return Promise +]=] +function Promise.prototype:finallyCall(callback, ...) + assert(isCallable(callback), string.format(ERROR_NON_FUNCTION, "Promise:finallyCall")) + local length, values = pack(...) + return self:_finally(debug.traceback(nil, 2), function() + return callback(unpack(values, 1, length)) + end) +end + +--[=[ + Attaches a `finally` handler to this Promise that discards the resolved value and returns the given value from it. + + ```lua + promise:finallyReturn("some", "values") + ``` + + This is sugar for + + ```lua + promise:finally(function() + return "some", "values" + end) + ``` + + @param ... any -- Values to return from the function + @return Promise +]=] +function Promise.prototype:finallyReturn(...) + local length, values = pack(...) + return self:_finally(debug.traceback(nil, 2), function() + return unpack(values, 1, length) + end) +end + +--[=[ + Yields the current thread until the given Promise completes. Returns the Promise's status, followed by the values that the promise resolved or rejected with. + + @yields + @return Status -- The Status representing the fate of the Promise + @return ...any -- The values the Promise resolved or rejected with. +]=] +function Promise.prototype:awaitStatus() + self._unhandledRejection = false + + if self._status == Promise.Status.Started then + local thread = coroutine.running() + + self + :finally(function() + task.spawn(thread) + end) + -- The finally promise can propagate rejections, so we attach a catch handler to prevent the unhandled + -- rejection warning from appearing + :catch( + function() end + ) + + coroutine.yield() + end + + if self._status == Promise.Status.Resolved then + return self._status, unpack(self._values, 1, self._valuesLength) + elseif self._status == Promise.Status.Rejected then + return self._status, unpack(self._values, 1, self._valuesLength) + end + + return self._status +end + +local function awaitHelper(status, ...) + return status == Promise.Status.Resolved, ... +end + +--[=[ + Yields the current thread until the given Promise completes. Returns true if the Promise resolved, followed by the values that the promise resolved or rejected with. + + :::caution + If the Promise gets cancelled, this function will return `false`, which is indistinguishable from a rejection. If you need to differentiate, you should use [[Promise.awaitStatus]] instead. + ::: + + ```lua + local worked, value = getTheValue():await() + + if worked then + print("got", value) + else + warn("it failed") + end + ``` + + @yields + @return boolean -- `true` if the Promise successfully resolved + @return ...any -- The values the Promise resolved or rejected with. +]=] +function Promise.prototype:await() + return awaitHelper(self:awaitStatus()) +end + +local function expectHelper(status, ...) + if status ~= Promise.Status.Resolved then + error((...) == nil and "Expected Promise rejected with no value." or (...), 3) + end + + return ... +end + +--[=[ + Yields the current thread until the given Promise completes. Returns the values that the promise resolved with. + + ```lua + local worked = pcall(function() + print("got", getTheValue():expect()) + end) + + if not worked then + warn("it failed") + end + ``` + + This is essentially sugar for: + + ```lua + select(2, assert(promise:await())) + ``` + + **Errors** if the Promise rejects or gets cancelled. + + @error any -- Errors with the rejection value if this Promise rejects or gets cancelled. + @yields + @return ...any -- The values the Promise resolved with. +]=] +function Promise.prototype:expect() + return expectHelper(self:awaitStatus()) +end + +-- Backwards compatibility +Promise.prototype.awaitValue = Promise.prototype.expect + +--[[ + Intended for use in tests. + + Similar to await(), but instead of yielding if the promise is unresolved, + _unwrap will throw. This indicates an assumption that a promise has + resolved. +]] +function Promise.prototype:_unwrap() + if self._status == Promise.Status.Started then + error("Promise has not resolved or rejected.", 2) + end + + local success = self._status == Promise.Status.Resolved + + return success, unpack(self._values, 1, self._valuesLength) +end + +function Promise.prototype:_resolve(...) + if self._status ~= Promise.Status.Started then + if Promise.is((...)) then + (...):_consumerCancelled(self) + end + return + end + + -- If the resolved value was a Promise, we chain onto it! + if Promise.is((...)) then + -- Without this warning, arguments sometimes mysteriously disappear + if select("#", ...) > 1 then + local message = string.format( + "When returning a Promise from andThen, extra arguments are " .. "discarded! See:\n\n%s", + self._source + ) + warn(message) + end + + local chainedPromise = ... + + local promise = chainedPromise:andThen(function(...) + self:_resolve(...) + end, function(...) + local maybeRuntimeError = chainedPromise._values[1] + + -- Backwards compatibility < v2 + if chainedPromise._error then + maybeRuntimeError = Error.new({ + error = chainedPromise._error, + kind = Error.Kind.ExecutionError, + context = "[No stack trace available as this Promise originated from an older version of the Promise library (< v2)]", + }) + end + + if Error.isKind(maybeRuntimeError, Error.Kind.ExecutionError) then + return self:_reject(maybeRuntimeError:extend({ + error = "This Promise was chained to a Promise that errored.", + trace = "", + context = string.format( + "The Promise at:\n\n%s\n...Rejected because it was chained to the following Promise, which encountered an error:\n", + self._source + ), + })) + end + + self:_reject(...) + end) + + if promise._status == Promise.Status.Cancelled then + self:cancel() + elseif promise._status == Promise.Status.Started then + -- Adopt ourselves into promise for cancellation propagation. + self._parent = promise + promise._consumers[self] = true + end + + return + end + + self._status = Promise.Status.Resolved + self._valuesLength, self._values = pack(...) + + -- We assume that these callbacks will not throw errors. + for _, callback in ipairs(self._queuedResolve) do + coroutine.wrap(callback)(...) + end + + self:_finalize() +end + +function Promise.prototype:_reject(...) + if self._status ~= Promise.Status.Started then + return + end + + self._status = Promise.Status.Rejected + self._valuesLength, self._values = pack(...) + + -- If there are any rejection handlers, call those! + if not isEmpty(self._queuedReject) then + -- We assume that these callbacks will not throw errors. + for _, callback in ipairs(self._queuedReject) do + coroutine.wrap(callback)(...) + end + else + -- At this point, no one was able to observe the error. + -- An error handler might still be attached if the error occurred + -- synchronously. We'll wait one tick, and if there are still no + -- observers, then we should put a message in the console. + + local err = tostring((...)) + + coroutine.wrap(function() + Promise._timeEvent:Wait() + + -- Someone observed the error, hooray! + if not self._unhandledRejection then + return + end + + -- Build a reasonable message + local message = string.format("Unhandled Promise rejection:\n\n%s\n\n%s", err, self._source) + + for _, callback in ipairs(Promise._unhandledRejectionCallbacks) do + task.spawn(callback, self, unpack(self._values, 1, self._valuesLength)) + end + + if Promise.TEST then + -- Don't spam output when we're running tests. + return + end + + warn(message) + end)() + end + + self:_finalize() +end + +--[[ + Calls any :finally handlers. We need this to be a separate method and + queue because we must call all of the finally callbacks upon a success, + failure, *and* cancellation. +]] +function Promise.prototype:_finalize() + for _, callback in ipairs(self._queuedFinally) do + -- Purposefully not passing values to callbacks here, as it could be the + -- resolved values, or rejected errors. If the developer needs the values, + -- they should use :andThen or :catch explicitly. + coroutine.wrap(callback)(self._status) + end + + self._queuedFinally = nil + self._queuedReject = nil + self._queuedResolve = nil + + -- Clear references to other Promises to allow gc + if not Promise.TEST then + self._parent = nil + self._consumers = nil + end + + task.defer(coroutine.close, self._thread) +end + +--[=[ + Chains a Promise from this one that is resolved if this Promise is already resolved, and rejected if it is not resolved at the time of calling `:now()`. This can be used to ensure your `andThen` handler occurs on the same frame as the root Promise execution. + + ```lua + doSomething() + :now() + :andThen(function(value) + print("Got", value, "synchronously.") + end) + ``` + + If this Promise is still running, Rejected, or Cancelled, the Promise returned from `:now()` will reject with the `rejectionValue` if passed, otherwise with a `Promise.Error(Promise.Error.Kind.NotResolvedInTime)`. This can be checked with [[Error.isKind]]. + + @param rejectionValue? any -- The value to reject with if the Promise isn't resolved + @return Promise +]=] +function Promise.prototype:now(rejectionValue) + local traceback = debug.traceback(nil, 2) + if self._status == Promise.Status.Resolved then + return self:_andThen(traceback, function(...) + return ... + end) + else + return Promise.reject(rejectionValue == nil and Error.new({ + kind = Error.Kind.NotResolvedInTime, + error = "This Promise was not resolved in time for :now()", + context = ":now() was called at:\n\n" .. traceback, + }) or rejectionValue) + end +end + +--[=[ + Repeatedly calls a Promise-returning function up to `times` number of times, until the returned Promise resolves. + + If the amount of retries is exceeded, the function will return the latest rejected Promise. + + ```lua + local function canFail(a, b, c) + return Promise.new(function(resolve, reject) + -- do something that can fail + + local failed, thing = doSomethingThatCanFail(a, b, c) + + if failed then + reject("it failed") + else + resolve(thing) + end + end) + end + + local MAX_RETRIES = 10 + local value = Promise.retry(canFail, MAX_RETRIES, "foo", "bar", "baz") -- args to send to canFail + ``` + + @since 3.0.0 + @param callback (...: P) -> Promise + @param times number + @param ...? P + @return Promise +]=] +function Promise.retry(callback, times, ...) + assert(isCallable(callback), "Parameter #1 to Promise.retry must be a function") + assert(type(times) == "number", "Parameter #2 to Promise.retry must be a number") + + local args, length = { ... }, select("#", ...) + + return Promise.resolve(callback(...)):catch(function(...) + if times > 0 then + return Promise.retry(callback, times - 1, unpack(args, 1, length)) + else + return Promise.reject(...) + end + end) +end + +--[=[ + Repeatedly calls a Promise-returning function up to `times` number of times, waiting `seconds` seconds between each + retry, until the returned Promise resolves. + + If the amount of retries is exceeded, the function will return the latest rejected Promise. + + @since v3.2.0 + @param callback (...: P) -> Promise + @param times number + @param seconds number + @param ...? P + @return Promise +]=] +function Promise.retryWithDelay(callback, times, seconds, ...) + assert(isCallable(callback), "Parameter #1 to Promise.retry must be a function") + assert(type(times) == "number", "Parameter #2 (times) to Promise.retry must be a number") + assert(type(seconds) == "number", "Parameter #3 (seconds) to Promise.retry must be a number") + + local args, length = { ... }, select("#", ...) + + return Promise.resolve(callback(...)):catch(function(...) + if times > 0 then + Promise.delay(seconds):await() + + return Promise.retryWithDelay(callback, times - 1, seconds, unpack(args, 1, length)) + else + return Promise.reject(...) + end + end) +end + +--[=[ + Converts an event into a Promise which resolves the next time the event fires. + + The optional `predicate` callback, if passed, will receive the event arguments and should return `true` or `false`, based on if this fired event should resolve the Promise or not. If `true`, the Promise resolves. If `false`, nothing happens and the predicate will be rerun the next time the event fires. + + The Promise will resolve with the event arguments. + + :::tip + This function will work given any object with a `Connect` method. This includes all Roblox events. + ::: + + ```lua + -- Creates a Promise which only resolves when `somePart` is touched + -- by a part named `"Something specific"`. + return Promise.fromEvent(somePart.Touched, function(part) + return part.Name == "Something specific" + end) + ``` + + @since 3.0.0 + @param event Event -- Any object with a `Connect` method. This includes all Roblox events. + @param predicate? (...: P) -> boolean -- A function which determines if the Promise should resolve with the given value, or wait for the next event to check again. + @return Promise

+]=] +function Promise.fromEvent(event, predicate) + predicate = predicate or function() + return true + end + + return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel) + local connection + local shouldDisconnect = false + + local function disconnect() + connection:Disconnect() + connection = nil + end + + -- We use shouldDisconnect because if the callback given to Connect is called before + -- Connect returns, connection will still be nil. This happens with events that queue up + -- events when there's nothing connected, such as RemoteEvents + + connection = event:Connect(function(...) + local callbackValue = predicate(...) + + if callbackValue == true then + resolve(...) + + if connection then + disconnect() + else + shouldDisconnect = true + end + elseif type(callbackValue) ~= "boolean" then + error("Promise.fromEvent predicate should always return a boolean") + end + end) + + if shouldDisconnect and connection then + return disconnect() + end + + onCancel(disconnect) + end) +end + +--[=[ + Registers a callback that runs when an unhandled rejection happens. An unhandled rejection happens when a Promise + is rejected, and the rejection is not observed with `:catch`. + + The callback is called with the actual promise that rejected, followed by the rejection values. + + @since v3.2.0 + @param callback (promise: Promise, ...: any) -- A callback that runs when an unhandled rejection happens. + @return () -> () -- Function that unregisters the `callback` when called +]=] +function Promise.onUnhandledRejection(callback) + table.insert(Promise._unhandledRejectionCallbacks, callback) + + return function() + local index = table.find(Promise._unhandledRejectionCallbacks, callback) + + if index then + table.remove(Promise._unhandledRejectionCallbacks, index) + end + end +end + +return Promise diff --git a/src/Atom/Packages/Sourceesque.lua b/src/Atom/Packages/Sourceesque.lua new file mode 100644 index 0000000..7d49b17 --- /dev/null +++ b/src/Atom/Packages/Sourceesque.lua @@ -0,0 +1,269 @@ +--!strict + +-- ******************************* -- +-- AX3NX / AXEN -- +-- ******************************* -- + +---- Services ---- + +---- Imports ---- + +---- Settings ---- + +type BaseValues = number | Vector3 +export type ValueWrapper = () -> (BaseValues) +export type SupportedValues = BaseValues & ValueWrapper + +local TRUE = 0b1 +local FALSE = 0b0 +local NAN = 0/0 +local NAN_VECTOR = Vector3.new(NAN, NAN, NAN) + +local COMPRESSION_TYPES = { + Byte = "b", + Float = "f", + Short = "h", + Double = "d", + Number = "n", + Vector = "fff", + Integer = "j", + UnsignedByte = "B", + UnsignedShort = "H", + UnsignedInteger = "J" +} + +---- Constants ---- + +local Utility = { + CompressionTypes = COMPRESSION_TYPES +} + +---- Variables ---- + +---- Private Functions ---- + +local function GetSubstituteType(Value: BaseValues): BaseValues + return type(Value) == "number" and NAN or NAN_VECTOR +end + +local function GetDeltaFormat(Size: number): string + if Size <= 8 then + return COMPRESSION_TYPES.UnsignedByte + elseif Size <= 16 then + return COMPRESSION_TYPES.UnsignedShort + end + + return COMPRESSION_TYPES.UnsignedInteger +end + +---- Public Functions ---- + +function Utility.Always(Value: BaseValues): () -> (BaseValues) + return function() + return Value + end +end + +function Utility.ReconcileWithDeltaTable(DeltaTable: {BaseValues}, BaseTable: {BaseValues}) + for Index, BaseValue in BaseTable do + local DeltaValue = DeltaTable[Index] + if type(BaseValue) == "number" then + DeltaValue = DeltaValue ~= DeltaValue and BaseValue or DeltaValue + elseif type(DeltaValue) == "vector" then + if DeltaValue == BaseValue then + DeltaValue = BaseValue + elseif DeltaValue ~= DeltaValue then + DeltaValue = Vector3.new( + DeltaValue.X ~= DeltaValue.X and BaseValue.X or DeltaValue.X, + DeltaValue.Y ~= DeltaValue.Y and BaseValue.Y or DeltaValue.Y, + DeltaValue.Z ~= DeltaValue.Z and BaseValue.Z or DeltaValue.Z + ) + end + end + + BaseTable[Index] = DeltaValue + end +end + +function Utility.CreateCompressionTable(Types: {string}) + local Format = table.concat(Types) + local RawTypes = Types + local DeltaFormat = GetDeltaFormat(#Format) + local DeltaFormatOffset = (1 + string.packsize(DeltaFormat)) + Types = string.split(Format, "") + + return { + Size = string.packsize(DeltaFormat .. Format), + + Compress = function(Values: {SupportedValues}, PreviousValues: {BaseValues}): (string, number) + local Stream = "" + local StreamFormat = "" + local ChangedValues: {BaseValues} = table.create(#Values) + + --> Remove wrappers + for Index, Value in Values do + if type(Value) == "function" then + local Raw = Value() + Values[Index] = Raw + if PreviousValues then + PreviousValues[Index] = GetSubstituteType(Raw) + end + end + end + + --> Create fake delta values + if not PreviousValues then + PreviousValues = table.create(#Values) + for Index, Value in Values do + (PreviousValues :: any)[Index] = GetSubstituteType(Value) + end + end + + --> Delta compression + local DeltaBits = 0 + local TypeCursor = 0 + local DeltaCursor = 0 + + for Index, RawCurrent in Values do + local Current: BaseValues = RawCurrent + local Previous = PreviousValues[Index] + local HasValueChanged = (Current ~= Previous) + + if type(Current) == "vector" then + --> Move type cursor 3 places forward since a vector is 3 floats + TypeCursor += 3 + + --> Avoid checking all axes if the vector didn't change + if not HasValueChanged then + DeltaBits += bit32.lshift(0b000, DeltaCursor) + DeltaCursor += 3 + continue + end + + --> Bit pack vector axis delta + local VectorBits = 0 + local XBit = (Current.X ~= (Previous :: Vector3).X) and TRUE or FALSE + local YBit = (Current.Y ~= (Previous :: Vector3).Y) and TRUE or FALSE + local ZBit = (Current.Z ~= (Previous :: Vector3).Z) and TRUE or FALSE + + VectorBits += bit32.lshift(XBit, 0) + VectorBits += bit32.lshift(YBit, 1) + VectorBits += bit32.lshift(ZBit, 2) + + --> Insert changed axes + if XBit == TRUE then + table.insert(ChangedValues, Current.X) + end + + if YBit == TRUE then + table.insert(ChangedValues, Current.Y) + end + + if ZBit == TRUE then + table.insert(ChangedValues, Current.Z) + end + + --> Add to delta bits & update format + DeltaBits += bit32.lshift(VectorBits, DeltaCursor) + DeltaCursor += 3 + StreamFormat ..= string.rep(COMPRESSION_TYPES.Float, (XBit + YBit + ZBit)) + else + DeltaBits += bit32.lshift(HasValueChanged and TRUE or FALSE, DeltaCursor) + TypeCursor += 1 + DeltaCursor += 1 + + if HasValueChanged then + StreamFormat ..= Types[TypeCursor] + table.insert(ChangedValues, Current) + end + end + end + + --> Build stream + Stream = string.pack(DeltaFormat .. StreamFormat, DeltaBits, table.unpack(ChangedValues)) + + return Stream, string.packsize(DeltaFormat .. StreamFormat) + end, + + Decompress = function(Stream: string): ({BaseValues}, number) + local StreamFormat = "" + + local Values: {BaseValues} = table.create(#Types, NAN) + local ValueIndices: {number} = {} + local VectorIndices: {number} = {} + + --> Construct stream format from delta compressed portion + local Offset = 0 + local StreamIndex = 0 + + local DeltaBits = string.unpack(DeltaFormat, Stream) + local DeltaCursor = 0 + + for Index, Type in RawTypes do + --> Add vector offsets + local ValueIndex = Index + Offset + + if Type == COMPRESSION_TYPES.Vector then + local XBit = bit32.extract(DeltaBits, DeltaCursor, 1) + local YBit = bit32.extract(DeltaBits, DeltaCursor + 1, 1) + local ZBit = bit32.extract(DeltaBits, DeltaCursor + 2, 1) + local Size = (XBit + YBit + ZBit) + + --> Fill empty vector axes with null + if XBit == TRUE then + StreamIndex += 1 + ValueIndices[StreamIndex] = ValueIndex + end + + if YBit == TRUE then + StreamIndex += 1 + ValueIndices[StreamIndex] = ValueIndex + 1 + end + + if ZBit == TRUE then + StreamIndex += 1 + ValueIndices[StreamIndex] = ValueIndex + 2 + end + + Offset += 2 + table.insert(VectorIndices, ValueIndex) + StreamFormat ..= string.rep(COMPRESSION_TYPES.Float, Size) + elseif bit32.extract(DeltaBits, DeltaCursor, 1) == TRUE then + StreamIndex += 1 + StreamFormat ..= Type + ValueIndices[StreamIndex] = ValueIndex + end + + DeltaCursor += #Type + end + + --> Unpack the compressed stream, read with X bytes offset (first X bytes are used by the delta compression) + local UnpackedValues = {string.unpack(StreamFormat, Stream, DeltaFormatOffset)} + + --> Remove the extra value returned by string.unpack + UnpackedValues[#UnpackedValues] = nil + + for Index, Value in UnpackedValues do + Values[ValueIndices[Index]] = Value + end + + --> Reconstruct vectors + for Index = #VectorIndices, 1, -1 do + local ReadIndex = VectorIndices[Index] + Values[ReadIndex] = Vector3.new( + Values[ReadIndex] :: number, + table.remove(Values, ReadIndex + 1) :: number, + table.remove(Values, ReadIndex + 1) :: number + ) + end + + return Values, string.packsize(DeltaFormat .. StreamFormat) + end + } +end + +---- Initialization ---- + +---- Connections ---- + +return Utility \ No newline at end of file diff --git a/src/Atom/Packages/Switch.lua b/src/Atom/Packages/Switch.lua new file mode 100644 index 0000000..93e8dea --- /dev/null +++ b/src/Atom/Packages/Switch.lua @@ -0,0 +1,104 @@ +local bypassIndex = math.huge -- As a heads up, NEVER set your case value to this. It will break things! + +local self; self = { + [1] = function(condition) -- Switch + -- The first thing we want to do is get that condition, and NOT call the case function, so we will just + -- return another function with the functionality of a case + + return function(cases) + for index, case in ipairs(cases) do + local conditionResult, caseFunction = case(condition) + + if typeof(conditionResult) == "function" then + -- If conditionResult is a function, we can assume we just came across a default statement + + if index ~= #cases then + error("Attempted to use a default statement in an index that was not the last") + + else + conditionResult() + break + end + + elseif typeof(conditionResult) == "boolean" then + -- If conditionResult is a boolean, we can assume we just came across a case statement + + if conditionResult then + if caseFunction then + -- If the case has its own defined function, immediately call it + + caseFunction() + + else + -- Otherwise, let's look for the next case attached to a function + + while true do + index += 1 + + if cases[index] == self[3] then + warn("Case " .. condition .. " does not ever break, and ends in a default statement. Did you forget to include a function somewhere?") + break + end + + local _, newCaseFunction = cases[index](bypassIndex) + + if newCaseFunction then + newCaseFunction() + break + + elseif index > #cases then + warn("Case " .. condition .. " does not ever break. Did you forget to include a function somewhere?") + break + end + end + end + + break + end + + else + -- We should expect cases to return a boolean userdata value, and a function userdata value for default statements + -- Anything else is unacceptable because its not a compatible statement + + error("Attempted to use a non-valid statement in the switch statement") + end + + end + end + end, + + [2] = function(requiredValue) -- Case + -- The first thing we want is to get the checked comparison + -- Of course, we don't want to run the case function, so let's + -- return a parent function + + return function(caseFunction) + return function(conditionValue) + -- In here, we check if the condition meets the case required value + -- If so, the switch statement will recognize this by recieving a + -- true value, and this finding the first occuring attached function. + -- If not, the switch statement will recieve a false value and ignore + -- the case. + + if conditionValue == bypassIndex or conditionValue == requiredValue then + return true, caseFunction + else + return false, nil + end + end + end + end, + + [3] = function() -- Default + -- This works almost exactly like a case, except we do not check a condition + -- This is similar to an "else" statement in lua/luau + + return function(defaultFunction) + return function() + return defaultFunction + end + end + end, +} + +return self \ No newline at end of file diff --git a/src/Atom/Packages/TextLib.lua b/src/Atom/Packages/TextLib.lua new file mode 100644 index 0000000..0b050c0 --- /dev/null +++ b/src/Atom/Packages/TextLib.lua @@ -0,0 +1,36 @@ +--!strict +-- Written by crazyattaker1. 29/10/2024. Lightweight RichText Implementation. +local TextLib = {} + +type Properties = { Bold:boolean, StrikeThrough:boolean, Underline:boolean, Italics:boolean } + +function TextLib.Update(Text:string, PropertiesTable:Properties) + local BoldPrefix = "" + local BoldSuffix = "" + local StrikePrefix = "" + local StrikeSuffix = "" + local UnderlinePrefix = "" + local UnderlineSuffix = "" + local ItalicsPrefix = "" + local ItalicsSuffix = "" + if PropertiesTable.Bold == true then + BoldPrefix = "" + BoldSuffix = "" + end + if PropertiesTable.StrikeThrough == true then + StrikePrefix = "" + StrikeSuffix = "" + end + if PropertiesTable.Underline == true then + UnderlinePrefix = "" + UnderlineSuffix = "" + end + if PropertiesTable.Italics == true then + ItalicsPrefix = "" + ItalicsSuffix = "" + end + task.wait(1) + return BoldPrefix..StrikePrefix..UnderlinePrefix..ItalicsPrefix..Text..ItalicsSuffix..UnderlineSuffix..StrikeSuffix..BoldSuffix +end + +return TextLib