do you see errors with this code. if so can you fix them. I want it to be a fluid simulation that visualized water with scaling parts.

Script:
-- DepthWorker Script
-- DepthWorker Script (placed under the MainSimulation Script)

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local actor = script:GetActor()
if actor == nil then
	print("DepthWorker script not running within an Actor.")
	return
end

local ComputeLua = require(ReplicatedStorage:WaitForChild("ComputeLua"))

print("DepthWorker is running.")

-- Get buffer keys
local DEPTH_BUFFER_KEY = ComputeLua.GetBufferDataKey("DepthBuffer")
local FLUX_LD_LEFT_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_LD_LeftBuffer")
local FLUX_LD_DOWN_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_LD_DownBuffer")
local FLUX_RU_RIGHT_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_RU_RightBuffer")
local FLUX_RU_UP_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_RU_UpBuffer")
local TEX_SIZE_BUFFER_KEY = ComputeLua.GetBufferDataKey("TexSize")

ComputeLua.CreateThread(actor, "StepDepth", function(id, bufferData)
	-- Worker code
	print("DepthWorker is processing id:", id)

	-- [Existing worker code for depth computations]

	-- Copy the worker code provided earlier, ensuring that computations are correct.
	-- For brevity, please refer to the previous DepthWorker script for the detailed code.
	local depths = bufferData[DEPTH_BUFFER_KEY]
	local flux_LD_Left = bufferData[FLUX_LD_LEFT_BUFFER_KEY]
	local flux_LD_Down = bufferData[FLUX_LD_DOWN_BUFFER_KEY]
	local flux_RU_Right = bufferData[FLUX_RU_RIGHT_BUFFER_KEY]
	local flux_RU_Up = bufferData[FLUX_RU_UP_BUFFER_KEY]
	local texSize = bufferData[TEX_SIZE_BUFFER_KEY][1]

	local depth = depths[id]

	local fluxOut = flux_LD_Left[id] + flux_LD_Down[id] + flux_RU_Right[id] + flux_RU_Up[id]
	local fluxIn = 0

	-- Compute x and y from id
	local x = math.floor((id - 1) / texSize) + 1
	local y = ((id - 1) % texSize) + 1

	-- Helper function to get neighbor id
	local function getNeighborId(nx, ny)
		if nx >= 1 and nx <= texSize and ny >= 1 and ny <= texSize then
			return (nx - 1) * texSize + ny
		else
			return nil
		end
	end

	-- Flux in from neighbors
	local leftId = getNeighborId(x - 1, y)
	if leftId then
		fluxIn = fluxIn + flux_RU_Right[leftId] -- Neighbor's flux_RU_Right
	end
	local rightId = getNeighborId(x + 1, y)
	if rightId then
		fluxIn = fluxIn + flux_LD_Left[rightId] -- Neighbor's flux_LD_Left
	end
	local downId = getNeighborId(x, y - 1)
	if downId then
		fluxIn = fluxIn + flux_RU_Up[downId] -- Neighbor's flux_RU_Up
	end
	local upId = getNeighborId(x, y + 1)
	if upId then
		fluxIn = fluxIn + flux_LD_Down[upId] -- Neighbor's flux_LD_Down
	end

	-- Update depth
	local newDepth = depth - fluxOut + fluxIn
	newDepth = math.max(newDepth, 0)
	depths[id] = newDepth

	-- Return updated depths
	return {
		[DEPTH_BUFFER_KEY] = depths
	}
end)


module:
-- GMFluxContainer ModuleScript

local GMFluxContainer = {}
GMFluxContainer.__index = GMFluxContainer

-- FluxCell constants (indices start from 1)
GMFluxContainer.FluxCell = {
	Height = 1,          -- cell[1]
	Depth = 2,           -- cell[2]
	Flux_LD_Left = 3,    -- cell[3] corresponds to cell[Flux_LD_Left]
	Flux_LD_Down = 4,    -- cell[4] corresponds to cell[Flux_LD_Down]
	Flux_RU_Right = 5,   -- cell[5]
	Flux_RU_Up = 6,      -- cell[6]
}

-- Constructor
function GMFluxContainer.new(texSize, position, cellSize, parameters)
	local self = setmetatable({}, GMFluxContainer)

	-- Simulation parameters
	self.fluxStrength = parameters.fluxStrength or 0.250
	self.fluxAtten = parameters.fluxAtten or 0.975
	self.fluxSpill = parameters.fluxSpill or 0.0

	self.texSize = texSize or 64
	self.cellSize = cellSize or 2

	-- Position of the fluid grid in the world
	self.position = position or Vector3.new(0, 0, 0)

	-- Initialize data structures
	self.cells = {}
	for x = 1, self.texSize do
		self.cells[x] = {}
		for y = 1, self.texSize do
			self.cells[x][y] = {
				[GMFluxContainer.FluxCell.Height] = 0,
				[GMFluxContainer.FluxCell.Depth] = 0,
				[GMFluxContainer.FluxCell.Flux_LD_Left] = 0,
				[GMFluxContainer.FluxCell.Flux_LD_Down] = 0,
				[GMFluxContainer.FluxCell.Flux_RU_Right] = 0,
				[GMFluxContainer.FluxCell.Flux_RU_Up] = 0,
			}
		end
	end

	return self
end

-- Encode terrain heightmap
function GMFluxContainer:cellEncodeHeightmap(heightmap, factor)
	for x = 1, self.texSize do
		for y = 1, self.texSize do
			local height = heightmap[x][y] * factor
			self.cells[x][y][GMFluxContainer.FluxCell.Height] = height
		end
	end
end

-- Add fluid at a specific position
function GMFluxContainer:addFluid(x, y, amount)
	if x >= 1 and x <= self.texSize and y >= 1 and y <= self.texSize then
		self.cells[x][y][GMFluxContainer.FluxCell.Depth] = self.cells[x][y][GMFluxContainer.FluxCell.Depth] + amount
	else
		warn("Attempted to add fluid outside of simulation bounds at (" .. x .. ", " .. y .. ")")
	end
end

-- Get fluid depth at a position
function GMFluxContainer:getFluidDepthAt(x, y)
	if x >= 1 and x <= self.texSize and y >= 1 and y <= self.texSize then
		return self.cells[x][y][GMFluxContainer.FluxCell.Depth]
	else
		return 0
	end
end

-- Handle collisions (Advanced collisions)
function GMFluxContainer:handleCollisions(collidableObjects)
	-- Implement collision handling if necessary
	-- For now, this is left empty
end

return GMFluxContainer
script:
-- MainSimulation Script

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ComputeLua = require(ReplicatedStorage:WaitForChild("ComputeLua"))
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")

-- Simulation parameters
local texSize = 128 -- Adjust as needed
local cellSize = 2 -- Size of each cell in world units
local simPosition = Vector3.new(-100, 0, -200) -- Adjust to move the fluid grid

-- Controllable simulation parameters
local simulationParameters = {
	fluxStrength = 0.25,       -- Controls the fluid flow strength
	fluxAtten = 0.975,         -- Fluid attenuation
	fluxSpill = 0.0,           -- Fluid spill threshold
	simulationSpeed = 0.03,    -- Controls the simulation step interval
	fluidGenerationRate = 500, -- Controls the rate at which fluid is added per source per step
	heightmapUpdateInterval = 1 -- Interval in seconds to update the heightmap
}

-- Create an instance of the simulation container
local GMFluxContainer = require(script.Parent:WaitForChild("GMFluxContainer"))
local sim = GMFluxContainer.new(texSize, simPosition, cellSize, simulationParameters)

-- Function to generate the terrain heightmap using raycasts
local function generateTerrainHeightmap(sim)
	local heightmap = {}
	local basePosition = sim.position
	local cellSize = sim.cellSize

	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Exclude
	raycastParams.FilterDescendantsInstances = {} -- Ensure no instances are excluded
	raycastParams.IgnoreWater = false

	local maxTerrainHeight = 1000 -- Adjust based on your terrain
	local direction = Vector3.new(0, -maxTerrainHeight - 100, 0)

	for x = 1, sim.texSize do
		heightmap[x] = {}
		local worldX = basePosition.X + (x - 0.5) * cellSize
		for y = 1, sim.texSize do
			local worldZ = basePosition.Z + (y - 0.5) * cellSize
			local origin = Vector3.new(worldX, maxTerrainHeight, worldZ)
			local raycastResult = Workspace:Raycast(origin, direction, raycastParams)
			local height = 0

			if raycastResult then
				height = raycastResult.Position.Y
			else
				-- No hit, set to base level
				height = 0
			end

			heightmap[x][y] = height

			-- Uncomment to debug heightmap
			-- print(string.format("Heightmap[%d][%d]: %f", x, y, height))
		end
	end

	return heightmap
end

-- Generate the initial terrain heightmap
local heightmap = generateTerrainHeightmap(sim)

-- Set the terrain heightmap in the simulation
sim:cellEncodeHeightmap(heightmap, 1) -- Height factor is 1

-- Visualization parts parent
local visualizationFolder = Instance.new("Folder")
visualizationFolder.Name = "VisualizationParts"
visualizationFolder.Parent = Workspace

-- Create parts to visualize the simulation
local partsGrid = {}
local basePosition = sim.position

for x = 1, sim.texSize do
	partsGrid[x] = {}
	local worldX = basePosition.X + (x - 1) * sim.cellSize
	for y = 1, sim.texSize do
		local part = Instance.new("Part")
		part.Size = Vector3.new(sim.cellSize, 0.1, sim.cellSize) -- Initial minimal size
		local height = sim.cells[x][y][GMFluxContainer.FluxCell.Height]
		part.Position = Vector3.new(worldX, height + 0.05, basePosition.Z + (y - 1) * sim.cellSize)
		part.Anchored = true
		part.Material = Enum.Material.Slate -- Terrain material
		part.Color = Color3.fromRGB(139, 69, 19) -- Brown color for terrain
		part.Transparency = 0
		part.CastShadow = false
		part.Parent = visualizationFolder -- Parent to visualization folder

		-- Add attribute to track particle emitter
		part:SetAttribute("HasParticleEmitter", false)
		partsGrid[x][y] = part
	end
end

-- List of collidable objects (Advanced collisions)
local collidableObjectsFolder = Workspace:FindFirstChild("CollidableObjects")
local collidableObjects = {}
if collidableObjectsFolder then
	collidableObjects = collidableObjectsFolder:GetChildren()
end

-- List of water sources
local waterSources = {
	{x = math.floor(sim.texSize / 2), y = math.floor(sim.texSize / 2)},
	-- Add more sources as needed
}

-- Get worker scripts
local fluxWorker = script:WaitForChild("FluxWorker") -- The Worker script for flux computations
local depthWorker = script:WaitForChild("DepthWorker") -- The Worker script for depth computations

-- Create Dispatchers and Workers for ComputeLua
local numWorkers = 10 -- Adjust as needed

local fluxDispatcher = ComputeLua.CreateDispatcher(numWorkers, fluxWorker)
local depthDispatcher = ComputeLua.CreateDispatcher(numWorkers, depthWorker)

-- Move cloned actors to ServerScriptService to ensure they can run
for _, actor in ipairs(fluxDispatcher.workers) do
	actor.Parent = game.ServerScriptService
end

for _, actor in ipairs(depthDispatcher.workers) do
	actor.Parent = game.ServerScriptService
end

print("Workers are set up and moved to ServerScriptService.")

-- Create buffer keys for easy access
local HEIGHT_BUFFER_KEY = ComputeLua.GetBufferDataKey("HeightBuffer")
local DEPTH_BUFFER_KEY = ComputeLua.GetBufferDataKey("DepthBuffer")
local FLUX_LD_LEFT_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_LD_LeftBuffer")
local FLUX_LD_DOWN_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_LD_DownBuffer")
local FLUX_RU_RIGHT_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_RU_RightBuffer")
local FLUX_RU_UP_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_RU_UpBuffer")
local TEX_SIZE_BUFFER_KEY = ComputeLua.GetBufferDataKey("TexSize")
local FLUX_ATTEN_KEY = ComputeLua.GetBufferDataKey("FluxAtten")
local FLUX_STRENGTH_KEY = ComputeLua.GetBufferDataKey("FluxStrength")
local FLUX_SPILL_KEY = ComputeLua.GetBufferDataKey("FluxSpill")

-- Simulation loop control
local lastHeightmapUpdate = 0
local simulationTimer = 0
local isProcessing = false

RunService.Heartbeat:Connect(function(deltaTime)
	-- Skip if processing is ongoing
	if isProcessing then
		return
	end

	simulationTimer = simulationTimer + deltaTime

	-- Add fluid at specified water sources
	for _, source in ipairs(waterSources) do
		sim:addFluid(source.x, source.y, simulationParameters.fluidGenerationRate)
		-- Uncomment to debug depth values
		local depth = sim.cells[source.x][source.y][GMFluxContainer.FluxCell.Depth]
		 print(string.format("Added fluid at (%d,%d), new depth: %f", source.x, source.y, depth))
	end

	-- Perform simulation steps at the specified interval
	if simulationTimer >= simulationParameters.simulationSpeed then
		simulationTimer = 0
		isProcessing = true

		local numCells = sim.texSize * sim.texSize

		-- Prepare individual buffers for ComputeLua
		local heightData = table.create(numCells)
		local depthData = table.create(numCells)
		local flux_LD_LeftData = table.create(numCells)
		local flux_LD_DownData = table.create(numCells)
		local flux_RU_RightData = table.create(numCells)
		local flux_RU_UpData = table.create(numCells)

		local index = 1
		for x = 1, sim.texSize do
			for y = 1, sim.texSize do
				local cell = sim.cells[x][y]
				heightData[index] = cell[1]  -- Height
				depthData[index] = cell[2]   -- Depth
				flux_LD_LeftData[index] = cell[3] or 0    -- Flux_LD_Left
				flux_LD_DownData[index] = cell[4] or 0    -- Flux_LD_Down
				flux_RU_RightData[index] = cell[5] or 0   -- Flux_RU_Right
				flux_RU_UpData[index] = cell[6] or 0      -- Flux_RU_Up
				index = index + 1
			end
		end

		-- Set ComputeBuffers
		fluxDispatcher:SetComputeBuffer("HeightBuffer", heightData)
		fluxDispatcher:SetComputeBuffer("DepthBuffer", depthData)
		fluxDispatcher:SetComputeBuffer("Flux_LD_LeftBuffer", flux_LD_LeftData)
		fluxDispatcher:SetComputeBuffer("Flux_LD_DownBuffer", flux_LD_DownData)
		fluxDispatcher:SetComputeBuffer("Flux_RU_RightBuffer", flux_RU_RightData)
		fluxDispatcher:SetComputeBuffer("Flux_RU_UpBuffer", flux_RU_UpData)
		fluxDispatcher:SetComputeBuffer("TexSize", {sim.texSize})
		fluxDispatcher:SetComputeBuffer("FluxAtten", {simulationParameters.fluxAtten})
		fluxDispatcher:SetComputeBuffer("FluxStrength", {simulationParameters.fluxStrength})
		fluxDispatcher:SetComputeBuffer("FluxSpill", {simulationParameters.fluxSpill})

		local numThreads = numCells

		-- Dispatch StepFlux computations
		print("Dispatching StepFlux computations")
		fluxDispatcher:Dispatch("StepFlux", numThreads):andThen(function(data)
			print("StepFlux computations completed")

			-- Retrieve updated buffers
			local updatedFlux_LD_LeftData = data[FLUX_LD_LEFT_BUFFER_KEY]
			local updatedFlux_LD_DownData = data[FLUX_LD_DOWN_BUFFER_KEY]
			local updatedFlux_RU_RightData = data[FLUX_RU_RIGHT_BUFFER_KEY]
			local updatedFlux_RU_UpData = data[FLUX_RU_UP_BUFFER_KEY]

			-- Prepare buffers for StepDepth
			depthDispatcher:SetComputeBuffer("HeightBuffer", heightData)
			depthDispatcher:SetComputeBuffer("DepthBuffer", depthData)
			depthDispatcher:SetComputeBuffer("Flux_LD_LeftBuffer", updatedFlux_LD_LeftData)
			depthDispatcher:SetComputeBuffer("Flux_LD_DownBuffer", updatedFlux_LD_DownData)
			depthDispatcher:SetComputeBuffer("Flux_RU_RightBuffer", updatedFlux_RU_RightData)
			depthDispatcher:SetComputeBuffer("Flux_RU_UpBuffer", updatedFlux_RU_UpData)
			depthDispatcher:SetComputeBuffer("TexSize", {sim.texSize})

			-- Dispatch StepDepth computations
			print("Dispatching StepDepth computations")
			depthDispatcher:Dispatch("StepDepth", numThreads):andThen(function(data)
				print("StepDepth computations completed")

				local updatedDepthData = data[DEPTH_BUFFER_KEY]

				-- Update sim.cells with computed data
				local index = 1
				for x = 1, sim.texSize do
					for y = 1, sim.texSize do
						local cell = sim.cells[x][y]
						cell[2] = updatedDepthData[index] -- Update Depth
						cell[3] = updatedFlux_LD_LeftData[index]
						cell[4] = updatedFlux_LD_DownData[index]
						cell[5] = updatedFlux_RU_RightData[index]
						cell[6] = updatedFlux_RU_UpData[index]
						index = index + 1
					end
				end

				-- Handle collisions (cannot be parallelized due to Roblox API access)
				sim:handleCollisions(collidableObjects)

				-- Update visualization parts based on sim.cells
				for x = 1, sim.texSize do
					local partsColumn = partsGrid[x]
					local simCellsColumn = sim.cells[x]
					local worldX = basePosition.X + (x - 1) * sim.cellSize
					for y = 1, sim.texSize do
						local part = partsColumn[y]
						local cell = simCellsColumn[y]
						local depth = cell[GMFluxContainer.FluxCell.Depth]
						local height = cell[GMFluxContainer.FluxCell.Height]
						local worldZ = basePosition.Z + (y - 1) * sim.cellSize

						if depth > 0 then
							-- Scale the part to represent the fluid depth
							part.Size = Vector3.new(sim.cellSize, depth, sim.cellSize)
							part.Position = Vector3.new(worldX, height + depth / 2, worldZ)
							-- Set material and color for water
							part.Material = Enum.Material.Water
							-- Color intensity based on depth
							local colorIntensity = math.clamp(depth / 10, 0, 1)
							part.Color = Color3.new(0, 0, colorIntensity)
							part.Transparency = 0.3 -- Less transparent with more depth
						else
							-- Minimal size for empty cells
							part.Size = Vector3.new(sim.cellSize, 0.1, sim.cellSize)
							part.Position = Vector3.new(worldX, height + 0.05, worldZ)
							-- Set material and color for terrain
							part.Material = Enum.Material.Slate -- Terrain material
							part.Color = Color3.fromRGB(139, 69, 19) -- Brown color for terrain
							part.Transparency = 0
						end

						-- Uncomment to debug depth values
						-- print(string.format("Cell[%d][%d] - Depth: %f", x, y, depth))
					end
				end

				-- Reset processing flag
				isProcessing = false
			end, function(errorMessage)
				warn("StepDepth error:", errorMessage)
				isProcessing = false
			end)
		end, function(errorMessage)
			warn("StepFlux error:", errorMessage)
			isProcessing = false
		end)
	end

	-- Periodically update the heightmap
	lastHeightmapUpdate = lastHeightmapUpdate + deltaTime
	if lastHeightmapUpdate >= simulationParameters.heightmapUpdateInterval then
		lastHeightmapUpdate = 0

		-- Update the heightmap
		heightmap = generateTerrainHeightmap(sim)
		sim:cellEncodeHeightmap(heightmap, 1)
	end
end)



script:-- FluxWorker Script (placed under the MainSimulation Script)

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local actor = script:GetActor()
if actor == nil then
	print("FluxWorker script not running within an Actor.")
	return
end

local ComputeLua = require(ReplicatedStorage:WaitForChild("ComputeLua"))

print("FluxWorker is running.")

-- Get buffer keys
local HEIGHT_BUFFER_KEY = ComputeLua.GetBufferDataKey("HeightBuffer")
local DEPTH_BUFFER_KEY = ComputeLua.GetBufferDataKey("DepthBuffer")
local FLUX_LD_LEFT_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_LD_LeftBuffer")
local FLUX_LD_DOWN_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_LD_DownBuffer")
local FLUX_RU_RIGHT_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_RU_RightBuffer")
local FLUX_RU_UP_BUFFER_KEY = ComputeLua.GetBufferDataKey("Flux_RU_UpBuffer")
local TEX_SIZE_BUFFER_KEY = ComputeLua.GetBufferDataKey("TexSize")
local FLUX_ATTEN_KEY = ComputeLua.GetBufferDataKey("FluxAtten")
local FLUX_STRENGTH_KEY = ComputeLua.GetBufferDataKey("FluxStrength")
local FLUX_SPILL_KEY = ComputeLua.GetBufferDataKey("FluxSpill")

ComputeLua.CreateThread(actor, "StepFlux", function(id, bufferData)
	-- Worker code
	print("FluxWorker is processing id:", id)

	-- [Existing worker code for flux computations]

	-- Copy the worker code provided earlier, ensuring that computations are correct.
	-- For brevity, please refer to the previous FluxWorker script for the detailed code.
	local heights = bufferData[HEIGHT_BUFFER_KEY]
	local depths = bufferData[DEPTH_BUFFER_KEY]
	local flux_LD_Left = bufferData[FLUX_LD_LEFT_BUFFER_KEY]
	local flux_LD_Down = bufferData[FLUX_LD_DOWN_BUFFER_KEY]
	local flux_RU_Right = bufferData[FLUX_RU_RIGHT_BUFFER_KEY]
	local flux_RU_Up = bufferData[FLUX_RU_UP_BUFFER_KEY]
	local texSize = bufferData[TEX_SIZE_BUFFER_KEY][1]
	local fluxAtten = bufferData[FLUX_ATTEN_KEY][1]
	local fluxStrength = bufferData[FLUX_STRENGTH_KEY][1]
	local fluxSpill = bufferData[FLUX_SPILL_KEY][1]

	local height = heights[id]
	local depth = depths[id]
	local totalHeight = height + depth

	-- Compute x and y from id
	local x = math.floor((id - 1) / texSize) + 1
	local y = ((id - 1) % texSize) + 1

	-- Neighbor positions
	local function getNeighborId(nx, ny)
		if nx >= 1 and nx <= texSize and ny >= 1 and ny <= texSize then
			return (nx - 1) * texSize + ny
		else
			return nil
		end
	end

	local neighbors = {
		left = getNeighborId(x - 1, y),
		right = getNeighborId(x + 1, y),
		down = getNeighborId(x, y - 1),
		up = getNeighborId(x, y + 1),
	}

	-- Initialize fluxes
	local fluxes = {left = 0, right = 0, down = 0, up = 0}
	local totalFluxOut = 0

	-- Compute fluxes to neighbors
	for dir, neighborId in pairs(neighbors) do
		if neighborId then
			local neighborHeight = heights[neighborId]
			local neighborDepth = depths[neighborId]
			local neighborTotalHeight = neighborHeight + neighborDepth

			-- Get the appropriate flux component
			local fluxComponent
			if dir == 'left' then
				fluxComponent = flux_LD_Left[id]
			elseif dir == 'down' then
				fluxComponent = flux_LD_Down[id]
			elseif dir == 'right' then
				fluxComponent = flux_RU_Right[id]
			elseif dir == 'up' then
				fluxComponent = flux_RU_Up[id]
			end

			local deltaHeight = totalHeight - neighborTotalHeight
			local flux = fluxAtten * fluxComponent + fluxStrength * math.max(0, deltaHeight)
			fluxes[dir] = flux
			totalFluxOut = totalFluxOut + flux
		end
	end

	-- Limit total flux to available depth
	local maxFlux = math.max(0, depth - fluxSpill)
	if totalFluxOut > maxFlux and totalFluxOut > 0 then
		local scale = maxFlux / totalFluxOut
		for dir in pairs(fluxes) do
			fluxes[dir] = fluxes[dir] * scale
		end
	end

	-- Update fluxes in cell
	flux_LD_Left[id] = fluxes.left or 0
	flux_LD_Down[id] = fluxes.down or 0
	flux_RU_Right[id] = fluxes.right or 0
	flux_RU_Up[id] = fluxes.up or 0

	-- Return updated fluxes
	return {
		[FLUX_LD_LEFT_BUFFER_KEY] = flux_LD_Left,
		[FLUX_LD_DOWN_BUFFER_KEY] = flux_LD_Down,
		[FLUX_RU_RIGHT_BUFFER_KEY] = flux_RU_Right,
		[FLUX_RU_UP_BUFFER_KEY] = flux_RU_Up,
	}	
end)




module:

-- ComputeLua
-- blorbee
-- Stable Release (1.3.0) - 9/24/2024

local RunService = game:GetService("RunService")
local Promise = require(script.promise)

type Promise<T...> = {
	andThen: (self: Promise<T...>, successHandler: (...any) -> ...any, failureHandler: (...any) -> ...any) -> Promise<...any>,
	catch: (self: Promise<T...>, failureHandler: (...any) -> ...any) -> Promise<...any>,
	cancel: (self: Promise<T...>) -> (),
	finally: (self: Promise<T...>, finallyHandler: (...any) -> ...any) -> Promise<...any>,
	await: (self: Promise<T...>) -> (boolean, T...),
}

--[=[
	@class Dispatcher

	Responsible for handling and dispatching workers. 
	This should never be created by a worker or in parallel.

	```lua
	local ReplicatedStorage = game:GetService("ReplicatedStorage")

	local ComputeLua = require(ReplicatedStorage.ComputeLua)

	local worker = script.Worker
	local numWorkers = 256

	local Dispatcher = ComputeLua.CreateDispatcher(numWorkers, worker)
	```
]=]
local Dispatcher = {}
Dispatcher.__index = Dispatcher

--[=[
	@type BufferDataType Vector2 | Vector3 | CFrame | Color3 | UDim | UDim2 | number | boolean | string
	@within Dispatcher
	The only data types allowed in buffers
]=]
--[=[
	@type BufferDataType Vector2 | Vector3 | CFrame | Color3 | UDim | UDim2 | number | boolean | string
	@within ComputeLua
	The only data types allowed in buffers
]=]

--[=[
	@type ComputeBufferDataType { [number]: BufferDataType | ComputeBufferDataType }
	@within Dispatcher
	Type for the data of a ComputeBuffer
]=]
--[=[
	@type ComputeBufferDataType { [number]: BufferDataType | ComputeBufferDataType }
	@within ComputeLua
	Type for the data of a ComputeBuffer
]=]

export type BufferDataType = Vector2 | Vector3 | CFrame | Color3 | UDim | UDim2 | number | boolean | string
export type ComputeBufferDataType = {[number]: BufferDataType | ComputeBufferDataType}

export type Dispatcher = typeof(setmetatable({} :: DispatcherSelf, Dispatcher))

type DispatcherSelf = {
	numWorkers: number,
	worker: Script | LocalScript,
	workerFolder: Folder,
	workers: {Actor},
	workerRemote: BindableEvent,
	computeBuffers: {[number]: ComputeBufferDataType},

	Dispatch: (self: Dispatcher, thread: string, numThreads: number, overrideBatchSize: number?) -> Promise<{[number]: {ComputeBufferDataType}}>,
	SetComputeBuffer: (self: Dispatcher, bufferName: string, bufferData: ComputeBufferDataType) -> (),
	DestroyComputeBuffer: (self: Dispatcher, bufferName: string) -> (),
	Destroy: (self: Dispatcher) -> ()
}
--[=[
	@prop numWorkers number
	@within Dispatcher
	@readonly
	@private
]=]
--[=[
	@prop computeBuffers { [number]: ComputeBufferDataType }
	@within Dispatcher
	@readonly
	@private
]=]
--[=[
	@prop worker Script | LocalScript
	@within Dispatcher
	@readonly
	@private
]=]
--[=[
	@prop workerFolder Folder
	@within Dispatcher
	@readonly
	@private
]=]
--[=[
	@prop workers {Actor}
	@within Dispatcher
	@readonly
	@private
]=]
--[=[
	@prop workerRemote BindableEvent
	@within Dispatcher
	@readonly
	@private
]=]

export type ComputeLua = {
	CreateDispatcher: (numWorkers: number, worker: Script | LocalScript) -> Dispatcher,
	CreateThread: (actor: Actor, threadName: string, callback: (id: number, bufferData: SharedTable) -> {[number]: any}) -> (),
	GetBufferDataKey: (bufferName: string) -> number
}

local function doesBufferElementHaveCorrectDataType(element: BufferDataType): boolean
	if typeof(element) ~= "table" 
		and typeof(element) ~= "Vector2"
		and typeof(element) ~= "Vector3"
		and typeof(element) ~= "CFrame"
		and typeof(element) ~= "Color3"
		and typeof(element) ~= "UDim"
		and typeof(element) ~= "UDim2"
		and typeof(element) ~= "number"
		and typeof(element) ~= "boolean"
		and typeof(element) ~= "string"
	then
		return false
	end
	return true
end

local function doesComputeBufferDataHaveCorrectTyping(bufferData: ComputeBufferDataType): boolean
	local function checkTable(t: {BufferDataType})
		for key, value in pairs(t) do
			if typeof(key) ~= "number" then
				return false
			end
			if typeof(value) == "table" and not checkTable(value) then
				return false
			end
			if not doesBufferElementHaveCorrectDataType(value) then
				return false
			end
		end
		return true
	end
	return checkTable(bufferData)
end

local function convertStringToNumber(str: string): number
	local hash = 0
	local prime = 31
	local mod = math.pow(2, 32) - 1
	for i = 1, #str do
		local char = string.byte(str, i)
		hash = (hash * prime + char) % mod
	end
	return math.abs(hash)
end

--[=[
	Create a Dispatcher
	@since v1.0.0
	@tag Parallel Unsafe
	@private

	@param numWorkers number -- How many workers to create
	@param worker Script | LocalScript -- The worker template to use
	@return Dispatcher
]=]
function Dispatcher._new(numWorkers: number, worker: Script | LocalScript)
	assert(type(numWorkers) == "number", "numWorkers must be a number")
	assert(typeof(worker) == "Instance", "worker must be an Instance")
	assert(worker:IsA("Script") or worker:IsA("LocalScript"), "worker must be a Script or LocalScript")
	assert(numWorkers > 0, "numWorkers must be greater than 0")

	local self = setmetatable({} :: Dispatcher, Dispatcher)

	self.numWorkers = math.round(numWorkers)
	self.worker = worker
	self.workers = table.create(numWorkers, 0)
	self.constantBuffer = {}
	self.computeBuffers = {}

	local folder = Instance.new("Folder")
	folder.Name = "Workers"
	folder.Parent = self.worker
	self.workerFolder = folder

	self.workerRemote = Instance.new("BindableEvent")

	for i = 1, numWorkers do
		local actor = Instance.new("Actor")
		local w = self.worker:Clone()
		w.Parent = actor
		w.Enabled = true
		self.workers[i] = actor
	end

	for _, actor in self.workers do
		actor.Parent = self.workerFolder
	end

	return self
end

--[=[
	Dispatch a number of threads to the workers
	@since v1.3.0
	@tag Parallel Unsafe

	@param thread string -- The name of the thread to dispatch, this is the same name as the one in the workers
	@param numThreads number -- How many times of this thread should be calling
	@param overrideBatchSize number? -- (NOT RECOMMENDED) override the default batch size
	@return Promise
]=]
function Dispatcher.Dispatch(self: Dispatcher, thread: string, numThreads: number, overrideBatchSize: number?)
	assert(type(numThreads) == "number", "numThreads must be a number")
	if numThreads <= 0 then
		warn("numThreads must be greater than 0")
		return Promise.reject()
	end
	assert(type(thread) == "string", "thread must be a string")
	if overrideBatchSize ~= nil then
		assert(type(overrideBatchSize) == "number", "overrideBatchSize must be a number")
		assert(overrideBatchSize > 0, "overrideBatchSize must be greater than 0")
		overrideBatchSize = math.ceil(overrideBatchSize)	
	end

	local batchSize = overrideBatchSize or math.floor(numThreads / #self.workers)
	local data = {}
	for key, bufferData in pairs(self.computeBuffers) do
		data[key] = bufferData
	end
	data = SharedTable.new(data)

	return Promise.defer(function(res)
		local result = data
		local workersDone = 0
		local connection = self.workerRemote.Event:Connect(function(id: number, bufferKey: number, data: any, calls: number)
			result[bufferKey][id] = data
			workersDone += calls
		end)

		local workerCount = #self.workers
		local index = 1
		for i = 1, numThreads, batchSize do
			self.workers[index]:SendMessage(thread, i, batchSize, numThreads, data, self.workerRemote)
			index = (index % workerCount) + 1
		end

		repeat
			RunService.Stepped:Wait()
		until workersDone >= numThreads

		if connection ~= nil then
			connection:Disconnect()
		end
		connection = nil

		res(result)
	end)
end

--[=[
	Set/Create ComputeBuffer data
	@since v1.3.0
	@tag Parallel Unsafe

	@param bufferName string -- The name of the buffer
	@param bufferData ComputeBufferDataType -- The data to set
]=]
function Dispatcher.SetComputeBuffer(self: Dispatcher, bufferName: string, bufferData: ComputeBufferDataType)
	assert(doesComputeBufferDataHaveCorrectTyping(bufferData), "bufferData must have only elements that are acceptable ComputeBuffer types")
	assert(typeof(bufferName) == "string", "bufferName must be a string")
	local key = convertStringToNumber(bufferName)
	self.computeBuffers[key] = bufferData
end

--[=[
	Delete a ComputeBuffer's data
	@since v1.3.0
	@tag Parallel Unsafe
	
	@param bufferName string -- The name of the buffer
]=]
function Dispatcher.DestroyComputeBuffer(self: Dispatcher, bufferName: string)
	assert(typeof(bufferName) == "string", "bufferName must be a string")
	local key = convertStringToNumber(bufferName)
	self.computeBuffers[key] = nil
end

--[=[
	The cleanup function for a Dispatcher. This is important to call to free up memory
	@since v1.0.0
	@tag Parallel Unsafe
]=]
function Dispatcher.Destroy(self: Dispatcher)
	for i = 1, self.numWorkers do
		self.workers[i]:Destroy()
	end
	self.workerRemote:Destroy()
	self.workerFolder:Destroy()
	table.clear(self.computeBuffers)
	table.clear(self)
	table.freeze(self)
end


--[=[
	@class ComputeLua

	The handler for the Dispatcher, threads, and data keys

	```lua
	local ReplicatedStorage = game:GetService("ReplicatedStorage")
	local ComputeLua = require(ReplicatedStorage.ComputeLua)
	```
]=]
local ComputeLua: ComputeLua = {}

--[=[
	Create a Dispatcher to run a bunch of workers in parallel
	@since v1.0.0
	@tag Parallel Unsafe

	@param numWorkers number -- How many workers to use, balanced this with performance and speed
	@param worker Script | LocalScript -- The template script to clone as the worker
	@return Dispatcher
]=]
function ComputeLua.CreateDispatcher(numWorkers: number, worker: Script | LocalScript): Dispatcher
	return Dispatcher._new(numWorkers, worker)
end

--[=[
	Create a thread for the Dispatcher to execute
	@since v1.3.0
	@tag Serial Unsafe

	@param actor Actor -- The Actor to bind the thread to, this should be the same actor as the parent of the worker.
	@param threadName string -- The unique name of the thread.
	@param callback (id: number, bufferData: SharedTable) -> {any} -- The function that will be executed when the thread is called and what returns the data
]=]
function ComputeLua.CreateThread(actor: Actor, threadName: string, callback: (id: number, bufferData: SharedTable) -> {any})
	assert(typeof(actor) == "Instance", "actor must be an Actor")
	assert(type(threadName) == "string", "threadName must be a string")
	assert(type(callback) == "function", "callback must be a function")
	assert(actor:IsA("Actor"), "actor must be an Actor instance")

	actor:BindToMessageParallel(threadName, function(
		startDispatchId: number, 
		batchSize: number,
		numThreads: number,
		bufferData: SharedTable,
		resultRemote: BindableEvent
	)
		for i = startDispatchId, math.min(startDispatchId + (batchSize - 1), numThreads) do
			local result = callback(i, bufferData)
			if result ~= nil then
				local amount = #result
				for i = 1, amount, 2 do
					resultRemote:Fire(i, result[i], result[i + 1], 2 / amount)
				end
			else
				error(`Thread {threadName}'s workers is not returning a value!`)
			end
		end
	end)
end

--[=[
	Get a ComputeBuffer's data key through its name
	@since v1.3.0

	@param bufferName string -- The name of the buffer
	@return number
]=]
function ComputeLua.GetBufferDataKey(bufferName: string): number
	return convertStringToNumber(bufferName)
end

return ComputeLua

Module:
--[[
	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<T>}
	@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<T>}
	@param reducer (accumulator: U, value: T, index: number) -> U | Promise<U>
	@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<T>}
	@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<T>}
	@return Promise<T>
]=]
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<T>}
	@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<T>}
	@return Promise<T>
]=]
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<T>}
	@param predicate (value: T, index: number) -> U | Promise<U>
	@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<number>
]=]
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<T>
	@param times number
	@param ...? P
	@return Promise<T>
]=]
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<T>
	@param times number
	@param seconds number
	@param ...? P
	@return Promise<T>
]=]
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<P>
]=]
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