From 33ccb7e3eb6219a3a64dc0b07888817127eaace0 Mon Sep 17 00:00:00 2001 From: cyclic Date: Sat, 9 Aug 2025 14:31:59 -0600 Subject: [PATCH] initialize --- .luaurc | 7 + .vscode/settings.json | 3 + aftman.toml | 6 + benchmark.luau | 62 +++ example.luau | 8 + pesde.lock | 44 ++ pesde.toml | 15 + rokit.toml | 7 + src/Enum/HTTPCodes.luau | 214 ++++++++ src/Lib/Duration.luau | 109 +++++ src/Lib/ErrorTypes/LICENSE | 674 ++++++++++++++++++++++++++ src/Lib/ErrorTypes/README.md | 4 + src/Lib/ErrorTypes/init.luau | 5 + src/Lib/ErrorTypes/rokit.toml | 7 + src/Lib/ErrorTypes/src/init.luau | 133 +++++ src/Lib/ErrorTypes/test.luau | 34 ++ src/Lib/Future.luau | 175 +++++++ src/Lib/Router.luau | 73 +++ src/Lib/Signal.luau | 74 +++ src/Lib/Spawn.luau | 27 ++ src/Middleware/CORS.luau | 9 + src/Middleware/Logging.luau | 11 + src/Middleware/RateLimit.luau | 3 + src/Middleware/init.luau | 14 + src/Server/Defaults/MoanaWorking.luau | 18 + src/Server/Endpoints/init.luau | 148 ++++++ src/Server/Folder/init.luau | 129 +++++ src/Server/Response/init.luau | 92 ++++ src/Server/init.luau | 218 +++++++++ src/init.luau | 46 ++ test.luau | 30 ++ 31 files changed, 2399 insertions(+) create mode 100644 .luaurc create mode 100644 .vscode/settings.json create mode 100644 aftman.toml create mode 100644 benchmark.luau create mode 100644 example.luau create mode 100644 pesde.lock create mode 100644 pesde.toml create mode 100644 rokit.toml create mode 100644 src/Enum/HTTPCodes.luau create mode 100644 src/Lib/Duration.luau create mode 100644 src/Lib/ErrorTypes/LICENSE create mode 100644 src/Lib/ErrorTypes/README.md create mode 100644 src/Lib/ErrorTypes/init.luau create mode 100644 src/Lib/ErrorTypes/rokit.toml create mode 100644 src/Lib/ErrorTypes/src/init.luau create mode 100644 src/Lib/ErrorTypes/test.luau create mode 100644 src/Lib/Future.luau create mode 100644 src/Lib/Router.luau create mode 100644 src/Lib/Signal.luau create mode 100644 src/Lib/Spawn.luau create mode 100644 src/Middleware/CORS.luau create mode 100644 src/Middleware/Logging.luau create mode 100644 src/Middleware/RateLimit.luau create mode 100644 src/Middleware/init.luau create mode 100644 src/Server/Defaults/MoanaWorking.luau create mode 100644 src/Server/Endpoints/init.luau create mode 100644 src/Server/Folder/init.luau create mode 100644 src/Server/Response/init.luau create mode 100644 src/Server/init.luau create mode 100644 src/init.luau create mode 100644 test.luau diff --git a/.luaurc b/.luaurc new file mode 100644 index 0000000..1429a45 --- /dev/null +++ b/.luaurc @@ -0,0 +1,7 @@ +{ + "aliases": { + "lib": "src/Lib", + "packages": "luau_packages", + "lune": "~/.lune/.typedefs/0.8.9/" + } +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..7787a6b --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "luau-lsp.require.mode": "relativeToFile" +} diff --git a/aftman.toml b/aftman.toml new file mode 100644 index 0000000..212064c --- /dev/null +++ b/aftman.toml @@ -0,0 +1,6 @@ +# This file lists tools managed by Aftman, a cross-platform toolchain manager. +# For more information, see https://github.com/LPGhatguy/aftman + +# To add a new tool, add an entry to this table. +[tools] +# rojo = "rojo-rbx/rojo@6.2.0" \ No newline at end of file diff --git a/benchmark.luau b/benchmark.luau new file mode 100644 index 0000000..c4a470b --- /dev/null +++ b/benchmark.luau @@ -0,0 +1,62 @@ +local NumRequests = 10000 +assert(NumRequests >= 10, "please set NumRequests to at least 10") + +local SizeInMiB = 1 -- response packet size + +local ResponseData = string.rep("a", SizeInMiB * 1000000) + +local Net = require("@lune/net") +local ServerLib = require("src/Server") +local Server = ServerLib.new(3000) + +local RootFolder = Server:registerFolder("root", "/") +Server:registerEndpoint(RootFolder, "wow", { + method = "GET", + path = "/wow", + callback = function(request, response) + response:setBody(ResponseData):setStatus(200):finish() + end +}) + +Server:start() + +local Completed = 0 +local Successful = 0 + +local Start = os.clock() + +for i = 1, NumRequests do + local Response = Net.request({ url = "http://localhost:3000/wow", Method = "GET" }) + Completed += 1 + + if Response.ok and Response.statusCode == 200 then + Successful += 1 + end + + if Completed % (NumRequests / 10) == 0 then + print(`Completed [{Completed}/{NumRequests}]`) + end +end + +local Finish = os.clock() +local TimeTook = Finish - Start + +local function Round(Ineger, DecimalPlace) + local Multiplier = 10 ^ DecimalPlace + return math.round(Ineger * Multiplier) / Multiplier +end + +local function MegabitToGigabit(Megabit: number): number + return Megabit / 1000 +end + +print(`-- FINISHED --`) +print(`Response packet size: {SizeInMiB} MiB`) +print(`Time elapsed: {Round(TimeTook, 3)}`) +print(`Number of unsuccessful requests: {NumRequests - Successful}`) +print(`Success %: {math.round((Successful / NumRequests) * 100)}%`) +print(`Requests/second: {math.round(NumRequests / TimeTook)}`) +print(`Bandwidth/second: {Round(MegabitToGigabit(NumRequests * SizeInMiB), 3)} GBit`) +print(`Average response time: {Round((TimeTook / NumRequests) * 1000, 3)}ms`) + +Server:disconnect() diff --git a/example.luau b/example.luau new file mode 100644 index 0000000..0bc8bfb --- /dev/null +++ b/example.luau @@ -0,0 +1,8 @@ +local Moana = require("src") +local Instance = Moana.init() + +local APIFolder = Instance:registerFolder("api", "/api") +APIFolder:registerEndpoint("thing", {}) +APIFolder:registerFolder("specific") + +APIFolder:unregisterEndpoint("thing") diff --git a/pesde.lock b/pesde.lock new file mode 100644 index 0000000..addaa5b --- /dev/null +++ b/pesde.lock @@ -0,0 +1,44 @@ +name = "moana/moana" +version = "0.1.0" +target = "luau" + +[graph."corecii/greentea"."0.4.11 lune"] +resolved_ty = "standard" + +[graph."corecii/greentea"."0.4.11 lune".target] +environment = "lune" +lib = "src/init.luau" + +[graph."corecii/greentea"."0.4.11 lune".pkg_ref] +ref_ty = "pesde" +name = "corecii/greentea" +version = "0.4.11" +index_url = "https://github.com/pesde-pkg/index" + +[graph."corecii/greentea"."0.4.11 lune".pkg_ref.target] +environment = "lune" +lib = "src/init.luau" + +[graph."kimpure/asciitable"."0.2.1 luau"] +direct = ["asciitable", { name = "kimpure/asciitable", version = "^0.2.1" }, "standard"] +resolved_ty = "standard" + +[graph."kimpure/asciitable"."0.2.1 luau".target] +environment = "luau" +lib = "src/init.luau" + +[graph."kimpure/asciitable"."0.2.1 luau".dependencies] +"corecii/greentea" = ["0.4.11 lune", "greentea"] + +[graph."kimpure/asciitable"."0.2.1 luau".pkg_ref] +ref_ty = "pesde" +name = "kimpure/asciitable" +version = "0.2.1" +index_url = "https://github.com/pesde-pkg/index" + +[graph."kimpure/asciitable"."0.2.1 luau".pkg_ref.dependencies] +greentea = [{ name = "corecii/greentea", version = "^0.4.11", index = "https://github.com/pesde-pkg/index", target = "lune" }, "standard"] + +[graph."kimpure/asciitable"."0.2.1 luau".pkg_ref.target] +environment = "luau" +lib = "src/init.luau" diff --git a/pesde.toml b/pesde.toml new file mode 100644 index 0000000..e7a509b --- /dev/null +++ b/pesde.toml @@ -0,0 +1,15 @@ +name = "moana/moana" +version = "0.1.0" +description = "network" +authors = ["me"] +repository = "https://codeberg.org/moana" +license = "MIT" + +[target] +environment = "luau" + +[indices] +default = "https://github.com/pesde-pkg/index" + +[dependencies] +asciitable = { name = "kimpure/asciitable", version = "^0.2.1" } diff --git a/rokit.toml b/rokit.toml new file mode 100644 index 0000000..2ee5e4a --- /dev/null +++ b/rokit.toml @@ -0,0 +1,7 @@ +# This file lists tools managed by Rokit, a toolchain manager for Roblox projects. +# For more information, see https://github.com/rojo-rbx/rokit + +# New tools can be added by running `rokit add ` in a terminal. + +[tools] +lune = "lune-org/lune@0.8.9" diff --git a/src/Enum/HTTPCodes.luau b/src/Enum/HTTPCodes.luau new file mode 100644 index 0000000..44c70f7 --- /dev/null +++ b/src/Enum/HTTPCodes.luau @@ -0,0 +1,214 @@ +type StatusCode = { + Message: string?, + Name: string, +} + +export type HTTPCodes = { + number: StatusCode, +} + +local HTTPCodes: HTTPCodes = { + [100] = { + Name = "Continue", + }, + [101] = { + Name = "Switching Protocols", + }, + [102] = { + Name = "Processing", + }, + [103] = { + Name = "Early Hints", + }, + [200] = { + Name = "OK", + Message = "The request was successful", + }, + [201] = { + Name = "Created" + }, + [202] = { + Name = "Accepted", + }, + [203] = { + Name = "Non-Authoritative Information", + }, + [204] = { + Name = 'No Content', + Message = "The request was successful but there is no content to return" + }, + [205] = { + Name = "Reset Content", + }, + [206] = { + Name = "Partial Content", + }, + [207] = { + Name = "Multi-Status", + }, + [208] = { + Name = "Already Reported", + }, + [226] = { + Name = "IM Used", + }, + [300] = { + Name = "Multiple Choices", + }, + [301] = { + Name = "Moved Permanently", + }, + [302] = { + Name = "Found", + }, + [303] = { + Name = "See Other", + }, + [304] = { + Name = "Not Modified", + }, + [305] = { + Name = "Use Proxy", + }, + [306] = { + Name = "Unused", + }, + [307] = { + Name = "Temporary Redirect", + }, + [308] = { + Name = "Permanent Redirect", + }, + [400] = { + Name = 'Bad Request', + Message = "The request could not be understood by the server" + }, + [401] = { + Name = 'Unauthorized', + Message = "Authentication is required and has failed or not been provided" + }, + [402] = { + Name = "Payment Required", + }, + [403] = { + Name = 'Forbidden', + Message = "You don't have permission to access this resource" + }, + [404] = { + Name = 'Not Found', + Message = "That content was not found" + }, + [405] = { + Name = "Method Not Allowed", + }, + [406] = { + Name = "Not Acceptable", + }, + [407] = { + Name = "Proxy Authentication Required", + }, + [408] = { + Name = 'Request Timeout', + Message = "The request took too long to process" + }, + [409] = { + Name = "Conflict", + }, + [410] = { + Name = "Gone", + }, + [411] = { + Name = "Length Required", + }, + [412] = { + Name = "Precondition Failed", + }, + [413] = { + Name = "Content Too Large", + }, + [414] = { + Name = "URI Too Long", + }, + [415] = { + Name = "Unsupported Media Type", + }, + [416] = { + Name = "Range Not Satisfiable", + }, + [417] = { + Name = "Expectation Failed", + }, + [418] = { + Name = "I'm a teapot", + }, + [421] = { + Name = "Misdirected Request", + }, + [422] = { + Name = "Unprocessable Content", + }, + [423] = { + Name = "Locked", + }, + [424] = { + Name = "Failed Dependency", + }, + [425] = { + Name = "Too Early", + }, + [426] = { + Name = "Upgrade Required", + }, + [428] = { + Name = "Precondition Required", + }, + [429] = { + Name = 'Too Many Requests', + Message = "Too many requests, try again in %d seconds" + }, + [431] = { + Name = "Request Header Fields Too Large", + }, + [451] = { + Name = "Unavailable For Legal Reasons", + }, + [500] = { + Name = 'Internal Server Error', + Message = "An unexpected error occurred on the server" + }, + [501] = { + Name = "Not Implemented", + }, + [502] = { + Name = 'Bad Gateway', + Message = "The server received an invalid response from the upstream server" + }, + [503] = { + Name = 'Service Unavailable', + Message = "The server is temporarily unavailable" + }, + [504] = { + Name = 'Gateway Timeout', + Message = "The server timed out waiting for a response from the upstream server" + }, + [505] = { + Name = "HTTP Version Not Supported", + }, + [506] = { + Name = "Variant Also Negotiates", + }, + [507] = { + Name = "Insufficient Storage", + }, + [508] = { + Name = "Loop Detected", + }, + [510] = { + Name = "Not Extended", + }, + [511] = { + Name = "Network Authentication Required", + }, +} + +return HTTPCodes \ No newline at end of file diff --git a/src/Lib/Duration.luau b/src/Lib/Duration.luau new file mode 100644 index 0000000..a8bb7a9 --- /dev/null +++ b/src/Lib/Duration.luau @@ -0,0 +1,109 @@ +--[=[ + @class Duration + @tag Lib + + A utility class for converting various time durations into seconds. +]=] + +--[=[ + @type DurationObj {seconds: number?, minutes: number?, hours: number?, days: number?} + @within Duration + Represents a time duration with optional time units. + + .seconds number? -- Number of seconds + .minutes number? -- Number of minutes + .hours number? -- Number of hours + .days number? -- Number of days +]=] + +--[=[ + @method minutesToSeconds + @within Duration + @param minutes number -- The number of minutes to convert + @return number -- The equivalent time in seconds + + Converts minutes to seconds. +]=] + +--[=[ + @method hoursToSeconds + @within Duration + @param hours number -- The number of hours to convert + @return number -- The equivalent time in seconds + + Converts hours to seconds. +]=] + +--[=[ + @method daysToSeconds + @within Duration + @param days number -- The number of days to convert + @return number -- The equivalent time in seconds + + Converts days to seconds. +]=] + +--[=[ + @method fullToSeconds + @within Duration + @param obj DurationObj -- A duration object containing any combination of time units + @return number -- The total time in seconds + + Converts a duration object into its total equivalent in seconds. + All time units in the object are summed together. + + ```lua + local duration = { + days = 1, + hours = 2, + minutes = 30 + } + local seconds = Duration:fullToSeconds(duration) + ``` +]=] + +export type DurationObj = { + seconds: number?, + minutes: number?, + hours: number?, + days: number?, +} + +export type Duration = { + minutesToSeconds: (self: Duration, minutes: number) -> number, + hoursToSeconds: (self: Duration, hours: number) -> number, + daysToSeconds: (self: Duration, days: number) -> number, + fullToSeconds: (self: Duration, obj: DurationObj) -> number, +} + +-- self explanatory enough that it doesn't warrant explanation +local Duration = {} +function Duration:minutesToSeconds(minutes: number): number + return minutes * 60 +end +function Duration:hoursToSeconds(hours: number): number + return self:minutesToSeconds(hours * 60) +end +function Duration:daysToSeconds(days: number): number + return self:hoursToSeconds(days * 24) +end + +function Duration:fullToSeconds(obj: DurationObj): number + local Result = 0 + + for Measurement, Value in pairs(obj) do + if Measurement == "seconds" then + Result += Value + elseif Measurement == "minutes" then + Result += self:minutesToSeconds(Value) + elseif Measurement == "hours" then + Result += self:hoursToSeconds(Value) + elseif Measurement == "days" then + Result += self:daysToSeconds(Value) + end + end + + return Result +end + +return Duration diff --git a/src/Lib/ErrorTypes/LICENSE b/src/Lib/ErrorTypes/LICENSE new file mode 100644 index 0000000..e72bfdd --- /dev/null +++ b/src/Lib/ErrorTypes/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/src/Lib/ErrorTypes/README.md b/src/Lib/ErrorTypes/README.md new file mode 100644 index 0000000..34a0acc --- /dev/null +++ b/src/Lib/ErrorTypes/README.md @@ -0,0 +1,4 @@ +# Luau Error Types +## Example +```lua +``` diff --git a/src/Lib/ErrorTypes/init.luau b/src/Lib/ErrorTypes/init.luau new file mode 100644 index 0000000..2507e27 --- /dev/null +++ b/src/Lib/ErrorTypes/init.luau @@ -0,0 +1,5 @@ +local ErrorTypes = require("src") +export type ErrorType = ErrorTypes.ErrorType +export type Error = ErrorTypes.Error + +return ErrorTypes \ No newline at end of file diff --git a/src/Lib/ErrorTypes/rokit.toml b/src/Lib/ErrorTypes/rokit.toml new file mode 100644 index 0000000..2ee5e4a --- /dev/null +++ b/src/Lib/ErrorTypes/rokit.toml @@ -0,0 +1,7 @@ +# This file lists tools managed by Rokit, a toolchain manager for Roblox projects. +# For more information, see https://github.com/rojo-rbx/rokit + +# New tools can be added by running `rokit add ` in a terminal. + +[tools] +lune = "lune-org/lune@0.8.9" diff --git a/src/Lib/ErrorTypes/src/init.luau b/src/Lib/ErrorTypes/src/init.luau new file mode 100644 index 0000000..aa6283b --- /dev/null +++ b/src/Lib/ErrorTypes/src/init.luau @@ -0,0 +1,133 @@ +local Stdio = require("@lune/stdio") +local Signal = require("@lib/Signal") +local Task = require("@lune/task") + +export type ErrorType = { + name: string, + types: { string }, + exitOnError: boolean | true, +} + +export type Error = ErrorType & { + parent: ErrorType, + stackTrace: any, + message: string, + errorType: string, + debugType: string, + errorSignal: Signal.Signal, + + new: (args: ErrorType) -> Error, + + raise: (self: Error, errorType: string, message: string, debugType: string? | "info") -> (), + assert: (self: Error, assertion: boolean, errorType: string, message: string, debugType: string? | "error") -> (), + output: (self: Error) -> (), + catch: (self: Error, errorType: string, callback: () -> (), handler: (error: Error) -> ()) -> (), + catchAll: (self: Error, callback: () -> (), handler: (error: Error) -> ()) -> (), + onError: (self: Error, (error: Error) -> ()) -> Signal.Connection, + onErrorOnce: (self: Error, (error: Error) -> ()) -> Signal.Connection, +} + +local ErrorClass = {} +ErrorClass.__index = ErrorClass + +function ErrorClass.new(Args: ErrorType): Error + local self = setmetatable({}, ErrorClass) + + self.name = Args.name + self.types = {} + self.exitOnError = (Args.exitOnError == nil and true) or Args.exitOnError + + self.stackTrace = nil + self.message = "" + self.errorType = "" + self.debugType = "" + self.errorSignal = Signal.new() + + for _, TypeValue in Args.types do + self.types[TypeValue] = TypeValue + end + + return self :: Error +end + +function ErrorClass:raise(errorType: string, message: string, debugType: string? | "info") + self.stackTrace = debug.traceback() + self.message = message + self.errorType = errorType + self.debugType = debugType or "info" + + self.errorSignal:fire(errorType, message, debugType) + + if self.exitOnError and debugType == "error" then + error(self:output()) + end +end + +function ErrorClass:assert(assertion: boolean, errorType: string, message: string, debugType: string? | "error") + if not assertion then + self:raise(errorType, message, debugType or "error") + end +end + +function ErrorClass:output() + local Color = self.debugType == "warn" and "yellow" or self.debugType == "error" and "red" or "reset" + + Stdio.write( + string.format( + "%s%s%s %s/%s: %s%s\n", + Stdio.style("bold"), + Stdio.color(Color :: Stdio.Color), + self.debugType == "warn" and "[WARNING]" or self.debugType == "error" and "[ERROR]" or "[INFO]", + self.name, + self.errorType, + Stdio.color("reset"), + self.message + ) + ) +end + +function ErrorClass:catch(errorType: string, callback: () -> (), handler: (error: Error) -> ()) + local Connection = self.errorSignal:connect(function(raisedErrorType: string, message: string, debugType: string) + if raisedErrorType == errorType then + Task.spawn(handler, self) + end + end) + + local Success, Result = pcall(callback) + if not Success then + self:raise(errorType, tostring(Result), "error") + end + + Connection:disconnect() +end + +function ErrorClass:catchAll(callback: () -> (), handler: (error: Error) -> ()) + local Connection = self.errorSignal:connect(function() + Task.spawn(handler, self) + end) + + local Success, Result = pcall(callback) + if not Success then + self:raise("unhandledError", tostring(Result), "error") + end + + Connection:disconnect() +end + +function ErrorClass:onError(handler: (error: Error) -> ()) + local Connection = self.errorSignal:connect(function() + Task.spawn(handler, self) + end) + + return Connection +end + +function ErrorClass:onErrorOnce(handler: (error: Error) -> ()) + local Connection = self.errorSignal:once(function() + Task.spawn(handler, self) + end) + + return Connection +end + +return ErrorClass diff --git a/src/Lib/ErrorTypes/test.luau b/src/Lib/ErrorTypes/test.luau new file mode 100644 index 0000000..7bd17c9 --- /dev/null +++ b/src/Lib/ErrorTypes/test.luau @@ -0,0 +1,34 @@ +local Error = require("src") + +local CatError = Error.new({ + name = "cat", + types = { + "meow", + "purr", + "chirp" + } +}) :: Error.Error + +local function DoThing() + CatError:assert(1 == 2, CatError.types.meow, "1 doesnt equal 2", "error") + CatError:raise(CatError.types.purr, ":3 adorable kitty") +end + +CatError:onErrorOnce(function(Error: Error.Error) + if Error.errorType == CatError.types.chirp then + Error:output() + end +end) + +CatError:raise(CatError.types.chirp, "ultra rare chirp error", "error") +CatError:raise(CatError.types.chirp, "this doesnt get outputted :3", "error") + +CatError:catchAll(DoThing, function(Error: Error.Error) + Error:output() +end) + +CatError:catch(CatError.types.purr, DoThing, function(Error: Error.Error) + if Error.message:match(":3") then + print('wow') + end +end) \ No newline at end of file diff --git a/src/Lib/Future.luau b/src/Lib/Future.luau new file mode 100644 index 0000000..ee4d5b4 --- /dev/null +++ b/src/Lib/Future.luau @@ -0,0 +1,175 @@ +--!nocheck +--# selene: allow(shadowing) + +local Spawn = require("Spawn") + +local Task = require("@lune/task") + +export type Future = { + valueList: { any }?, + afterList: { (T...) -> () }, + yieldList: { thread }, + resolver: ((T...) -> ())?, + rejecter: ((string) -> ())?, + + isComplete: (self: Future) -> boolean, + isPending: (self: Future) -> boolean, + + expect: (self: Future, Message: string) -> T..., + unwrap: (self: Future) -> T..., + unwrapOr: (self: Future, T...) -> T..., + unwrapOrElse: (self: Future, Else: () -> T...) -> T..., + + after: (self: Future, Callback: (T...) -> ()) -> (), + await: (self: Future) -> T..., + resolve: (self: Future, T...) -> (), + reject: (self: Future, message: string) -> (), +} + +local function isComplete(self: Future): boolean + return self.valueList ~= nil +end + +local function isPending(self: Future): boolean + return self.valueList == nil +end + +local function expect(self: Future, Message: string): T... + assert(self.valueList, Message) + + return table.unpack(self.valueList) +end + +local function unwrap(self: Future): T... + return self:expect("Attempt to unwrap pending future!") +end + +local function unwrapOr(self: Future, ...): T... + if self.valueList then + return table.unpack(self.valueList) + else + return ... + end +end + +local function unwrapOrElse(self: Future, Else: () -> T...): T... + if self.valueList then + return table.unpack(self.valueList) + else + return Else() + end +end + +local function after(self: Future, Callback: (T...) -> ()): T... + if self.valueList then + Spawn(Callback, table.unpack(self.valueList)) + else + table.insert(self.afterList, Callback) + end +end + +local function await(self: Future): T... + if self.valueList then + return table.unpack(self.valueList) + else + table.insert(self.yieldList, coroutine.running()) + + return coroutine.yield() + end +end + +local function Future(Callback: (A...) -> T..., ...: A...): Future + local self: Future = { + valueList = nil, + afterList = {}, + yieldList = {}, + + isComplete = isComplete, + isPending = isPending, + + expect = expect, + unwrap = unwrap, + unwrapOr = unwrapOr, + unwrapOrElse = unwrapOrElse, + + after = after, + await = await, + } :: any + + Spawn(function(self: Future, Callback: (A...) -> T..., ...: A...) + local valueList = { Callback(...) } + self.valueList = valueList + + for _, Thread in self.yieldList do + Task.spawn(Thread, table.unpack(valueList)) + end + + for _, Callback in self.afterList do + Spawn(Callback, table.unpack(valueList)) + end + end, self, Callback, ...) + + return self +end + +local function Try(Callback: (A...) -> T..., ...: A...): Future + return Future(function(...) + local data = { pcall(Callback, ...) } + + local success = table.remove(data, 1) + + if not success then + error(data[1]) + end + + return table.unpack(data) + end, ...) +end + +local function Defer(): Future + local self: Future = { + valueList = nil, + afterList = {}, + yieldList = {}, + + isComplete = isComplete, + isPending = isPending, + + expect = expect, + unwrap = unwrap, + unwrapOr = unwrapOr, + unwrapOrElse = unwrapOrElse, + + after = after, + await = await, + } :: any + + function self:resolve(...) + if self.valueList then + error("Future already resolved") + end + + local valueList = { ... } + self.valueList = valueList + + for _, Thread in self.yieldList do + Task.spawn(Thread, table.unpack(valueList)) + end + + for _, Callback in self.afterList do + Spawn(Callback, table.unpack(valueList)) + end + end + + function self:reject(message: string) + error(message) + end + + return self +end + +return { + new = Future, + try = Try, + defer = Defer +} \ No newline at end of file diff --git a/src/Lib/Router.luau b/src/Lib/Router.luau new file mode 100644 index 0000000..2919d2a --- /dev/null +++ b/src/Lib/Router.luau @@ -0,0 +1,73 @@ +local Router = {} + +export type RouteParams = {[string]: string} +export type QueryParams = {[string]: string | {string}} + +function Router.parseRouteParams(pattern: string, path: string): RouteParams? + local params: RouteParams = {} + + local escapedPattern = pattern:gsub("[%-%^%$%(%)%%%.%[%]%*%+%?]", "%%%1") + + local luaPattern = escapedPattern:gsub(":([%w_]+)", "([^/]+)") + + local paramNames = {} + for paramName in pattern:gmatch(":([%w_]+)") do + table.insert(paramNames, paramName) + end + + local matches = {string.match(path, "^" .. luaPattern .. "$")} + + if #matches ~= #paramNames then + return nil + end + + for i, paramName in ipairs(paramNames) do + params[paramName] = matches[i] + end + + return params +end + +function Router.parseQuery(queryString: string): QueryParams + local params: QueryParams = {} + + if not queryString or queryString == "" then + return params + end + + for pair in queryString:gmatch("[^&]+") do + local key, value = pair:match("([^=]+)=?(.*)") + if key then + key = Router.urlDecode(key) + value = Router.urlDecode(value) + + if params[key] then + if type(params[key]) == "string" then + params[key] = {params[key], value} + else + table.insert(params[key] :: {string}, value) + end + else + params[key] = value + end + end + end + + return params +end + +function Router.urlDecode(str: string): string + str = str:gsub("+", " ") + str = str:gsub("%%(%x%x)", function(hex) + return string.char(tonumber(hex, 16)) + end) + return str +end + +function Router.matchRoute(pattern: string, path: string): boolean + local escapedPattern = pattern:gsub("[%-%^%$%(%)%%%.%[%]%*%+%?]", "%%%1") + local luaPattern = escapedPattern:gsub(":([%w_]+)", "([^/]+)") + return string.match(path, "^" .. luaPattern .. "$") ~= nil +end + +return Router diff --git a/src/Lib/Signal.luau b/src/Lib/Signal.luau new file mode 100644 index 0000000..81df43c --- /dev/null +++ b/src/Lib/Signal.luau @@ -0,0 +1,74 @@ +local task = require("@lune/task") + +local Signal = {} +Signal.__index = Signal + +local Connection = {} +Connection.__index = Connection + +function Connection.new(Signal, Callback) + return setmetatable({ + Signal = Signal, + Callback = Callback, + }, Connection) +end + +function Connection.disconnect(self) + self.Signal[self] = nil +end + +function Signal.new() + return setmetatable({} :: any, Signal) +end + +function Signal.connect(self, Callback) + local CN = Connection.new(self, Callback) + self[CN] = true + return CN +end + +function Signal.once(self, Callback) + local CN + CN = Connection.new(self, function(...) + CN:disconnect() + Callback(...) + end) + self[CN] = true + return CN +end + +function Signal.wait(self) + local waitingCoroutine = coroutine.running() + local cn + cn = self:connect(function(...) + cn:disconnect() + task.spawn(waitingCoroutine, ...) + end) + return coroutine.yield() +end + +function Signal.disconnectAll(self) + table.clear(self) +end + +function Signal.fire(self, ...) + if next(self) then + for CN in pairs(self) do + CN.Callback(...) + end + end +end + +export type Connection = { + disconnect: (self: Connection) -> (), +} + +export type Signal = { + fire: (self: Signal, T...) -> (), + connect: (self: Signal, fn: (T...) -> ()) -> Connection, + once: (self: Signal, fn: (T...) -> ()) -> Connection, + wait: (self: Signal) -> T..., + disconnectAll: (self: Signal) -> (), +} + +return Signal :: { new: () -> Signal<...any> } \ No newline at end of file diff --git a/src/Lib/Spawn.luau b/src/Lib/Spawn.luau new file mode 100644 index 0000000..05f0cd3 --- /dev/null +++ b/src/Lib/Spawn.luau @@ -0,0 +1,27 @@ +local Task = require("@lune/task") + +local FreeThreads: { thread } = {} + +local function RunCallback(Callback, Thread, ...) + Callback(...) + table.insert(FreeThreads, Thread) +end + +local function Yielder() + while true do + RunCallback(coroutine.yield()) + end +end + +return function(Callback: (T...) -> (), ...: T...) + local Thread + if #FreeThreads > 0 then + Thread = FreeThreads[#FreeThreads] + FreeThreads[#FreeThreads] = nil + else + Thread = coroutine.create(Yielder) + coroutine.resume(Thread) + end + + Task.spawn(Thread, Callback, Thread, ...) +end \ No newline at end of file diff --git a/src/Middleware/CORS.luau b/src/Middleware/CORS.luau new file mode 100644 index 0000000..a496836 --- /dev/null +++ b/src/Middleware/CORS.luau @@ -0,0 +1,9 @@ +local Response = require("../Server/Response") + +return function(Request, Response: Response.Response) + Response:setHeaders({ + ["Access-Control-Allow-Origin"] = "*", + ["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS", + ["Access-Control-Allow-Headers"] = "Content-Type", + }) +end \ No newline at end of file diff --git a/src/Middleware/Logging.luau b/src/Middleware/Logging.luau new file mode 100644 index 0000000..25e7e78 --- /dev/null +++ b/src/Middleware/Logging.luau @@ -0,0 +1,11 @@ +local Net = require("@lune/net") +local Stdio = require("@lune/stdio") +local Response = require("../Server/Response") + +local function IsPositive(Status: number) + return Status >= 200 and Status < 300 +end + +return function(Request: Net.ServeRequest, Response: Response.Response) + print(`[{os.date()}] {Stdio.color("blue")}'{Request.path}'{Stdio.color("reset")} ({Request.method}): {IsPositive(Response.data.status :: number) and Stdio.color("green") or Stdio.color("red")}{Response.data.status}{Stdio.color("reset")}`) +end diff --git a/src/Middleware/RateLimit.luau b/src/Middleware/RateLimit.luau new file mode 100644 index 0000000..daad2aa --- /dev/null +++ b/src/Middleware/RateLimit.luau @@ -0,0 +1,3 @@ +return function() + +end \ No newline at end of file diff --git a/src/Middleware/init.luau b/src/Middleware/init.luau new file mode 100644 index 0000000..67a3380 --- /dev/null +++ b/src/Middleware/init.luau @@ -0,0 +1,14 @@ +local CORS = require("CORS") +local Logging = require("Logging") + +local Ratelimit = require("RateLimit") + +return { + pre = { + Ratelimit = Ratelimit + }, + post = { + CORS = CORS, + Logging = Logging + } +} \ No newline at end of file diff --git a/src/Server/Defaults/MoanaWorking.luau b/src/Server/Defaults/MoanaWorking.luau new file mode 100644 index 0000000..09bd508 --- /dev/null +++ b/src/Server/Defaults/MoanaWorking.luau @@ -0,0 +1,18 @@ +local Net = require("@lune/net") +local Response =require("../Response") +local Endpoints = require("../Endpoints") +local ErrorTypes = require("@lib/ErrorTypes") + +return function(Endpoints: Endpoints.Endpoints) + Endpoints:register("moanaStatus", { + path = "/moana/status", + output = ErrorTypes.new({ + name = "MoanaStatus", + types = {"error"}, + exitOnError = false + }), + callback = function(request: Net.ServeRequest, response: Response.Response) + response:setBody("working"):setStatus(200):finish() + end + }) +end diff --git a/src/Server/Endpoints/init.luau b/src/Server/Endpoints/init.luau new file mode 100644 index 0000000..12ec8e3 --- /dev/null +++ b/src/Server/Endpoints/init.luau @@ -0,0 +1,148 @@ +local ErrorTypes = require("@lib/ErrorTypes") +local Response = require("../Response") +local Net = require("@lune/net") + +export type Endpoint = { + name: string?, + output: ErrorTypes.Error, + path: string, + method: string?, + middleware: {pre: {}?, post: {}?}?, + contentTypes: {receive: string?, response: string?}?, + callback: (Net.ServeRequest, Response.Response) -> any, + ratelimitRules: unknown? +} + +export type Endpoints = { + endpoints: {Endpoint}, + pathIndex: {[string]: Endpoint}, + error: ErrorTypes.Error, + new: () -> Endpoints, + register: (self: Endpoints, name: string, object: Endpoint) -> Endpoint, + unregister: (self: Endpoints, name: string) -> Endpoints, + getByName: (self: Endpoints, name: string) -> Endpoint | nil, + getByPath: (self: Endpoints, path: string) -> Endpoint | nil +} + +local Endpoints: Endpoints = { + endpoints = {}, + pathIndex = {}, + error = ErrorTypes.new({ + name = 'Endpoints', + types = { + 'register', + 'unregister' + }, + exitOnError = true + }) +} :: Endpoints + +function Endpoints:register(name: string, object: Endpoint): Endpoint + self.error:assert(self.endpoints[name] == nil, self.error.types.register, `endpoint '{name}' already exists, overwriting`, "warn") + + object.name = name + object.output = ErrorTypes.new({ + name = `Endpoints/{object.name}`, + types = { + 'callError' + }, + exitOnError = false + }) + + if object.callback then + local OldCallback = object.callback + object.callback = function(Request: Net.ServeRequest, Response: Response.Response) + local Success, Message = pcall(OldCallback, Request, Response) + if not Success then + object.output:raise('callError', Message, "error") + + Response:setStatus(500) + Response:setBody("The endpoint has errored while responding to your request") + Response:finish() + end + + return Message + end + end + + self.endpoints[name] = object + + local normalizedPath = object.path:gsub("/+$", "") + if normalizedPath == "" then normalizedPath = "/" end + self.pathIndex[normalizedPath] = object + + if normalizedPath ~= "/" then + self.pathIndex[normalizedPath .. "/"] = object + end + + return self.endpoints[name] +end + +function Endpoints:unregister(name: string): Endpoints + self.error:assert(self.endpoints[name], self.error.types.unregister, `endpoint '{name}' does not exist, cannot unregister`, "warn") + + local endpoint = self.endpoints[name] + if endpoint then + local normalizedPath = endpoint.path:gsub("/+$", "") + if normalizedPath == "" then normalizedPath = "/" end + self.pathIndex[normalizedPath] = nil + if normalizedPath ~= "/" then + self.pathIndex[normalizedPath .. "/"] = nil + end + end + + self.endpoints[name] = nil + return Endpoints +end + +function Endpoints:getByName(name: string): Endpoint | nil + for Index, Endpoint in pairs(self.endpoints) do + if Endpoint.name == name then + return Endpoint + end + end + + return nil +end + +function Endpoints:getByPath(path: string): Endpoint | nil + local endpoint = self.pathIndex[path] + if endpoint then + return endpoint + end + + local normalizedPath = path:gsub("/+$", "") + if normalizedPath == "" then normalizedPath = "/" end + endpoint = self.pathIndex[normalizedPath] + if endpoint then + return endpoint + end + + if normalizedPath ~= "/" then + endpoint = self.pathIndex[normalizedPath .. "/"] + if endpoint then + return endpoint + end + end + + return nil +end + +function Endpoints.new(): Endpoints + local NewEndpoints = setmetatable({ + endpoints = {}, + pathIndex = {}, + error = ErrorTypes.new({ + name = 'Endpoints', + types = { + 'register', + 'unregister' + }, + exitOnError = true + }) + }, {__index = Endpoints}) + + return NewEndpoints +end + +return Endpoints diff --git a/src/Server/Folder/init.luau b/src/Server/Folder/init.luau new file mode 100644 index 0000000..d41efea --- /dev/null +++ b/src/Server/Folder/init.luau @@ -0,0 +1,129 @@ +local Endpoint = require("../Endpoints") +local ErrorTypes = require("@lib/ErrorTypes") + +export type Child = { + name: string, + object: Endpoint.Endpoint | Folder, + type: "folder" | "endpoint", + path: string? +} + +export type Folder = { + name: string, + path: string, + children: { [string]: Child }, + error: ErrorTypes.Error, + + addChild: (self: Folder, child: Child) -> Folder, + removeChild: (self: Folder, name: string) -> Folder, + getChild: (self: Folder, path: string) -> Child?, + new: (name: string, path: string) -> Folder +} + +local Folder = {} +Folder.__index = Folder + +function Folder.new(name: string, path: string): Folder + local self = setmetatable({}, Folder) + + self.name = name + self.path = path + self.children = {} + self.error = ErrorTypes.new({ + name = "Folder", + types = { + "addChild", + "removeChild", + "getChild" + }, + exitOnError = true + }) + + return self +end + +function Folder:addChild(child: Child): Folder + self.error:assert(self.children[child.name] == nil, "addChild", `Child '{child.name}' already exists`) + + child.path = self.path .. "/" .. child.name + self.children[child.name] = child + + return self +end + +function Folder:removeChild(name: string): Folder + self.error:assert(self.children[name] ~= nil, "removeChild", `Child '{name}' doesn't exist`) + + self.children[name] = nil + return self +end + +function Folder:registerEndpoint(name: string, endpointConfig: Endpoint.Endpoint): Endpoint.Endpoint + local Endpoint = table.clone(endpointConfig) + Endpoint.name = name + + self:addChild({ + name = name, + object = Endpoint, + type = "endpoint" + }) + + return Endpoint +end + +function Folder:registerFolder(name: string): Folder + local newFolder = Folder.new(name, self.path .. "/" .. name) + + self:addChild({ + name = name, + object = newFolder, + type = "folder", + path = newFolder.path + }) + + return newFolder +end + +function Folder:unregisterEndpoint(name: string): Folder + return self:removeChild(name) +end + +function Folder:unregisterFolder(name: string): Folder + local Child = self:getChild(name) + + if Child.type == 'folder' then + for Index, GrandChild in pairs(Child.children) do + if GrandChild.type == 'endpoint' then + Child:unregisterEndpoint(Index) + else + Child:unregisterFolder(Index) + end + end + + Folder:removeChild(Child.name) + end + + return self +end + +function Folder:getChild(path: string): Child? + local Parts = string.split(path, "/") + local Current = self + + for i = 1, #Parts do + local Part = Parts[i] + local Child = Current.children[Part] + + if not Child then + return nil + elseif Child.type == "endpoint" then + return Child + else + Current = Child.object + end + end + + return nil +end + +return Folder \ No newline at end of file diff --git a/src/Server/Response/init.luau b/src/Server/Response/init.luau new file mode 100644 index 0000000..4b39464 --- /dev/null +++ b/src/Server/Response/init.luau @@ -0,0 +1,92 @@ +local Future = require("@lib/Future") +local Net = require("@lune/net") +local Serde = require("@lune/serde") + +type headers = { + [string]: any +} + +type body = { + [any]: any +} + +export type Response = { + endpoint: any, + data: Net.ServeResponse, + hasFinished: boolean, + future: Future.Future, + setHeaders: (self: Response, headers: headers? | {}) -> Response, + getHeaders: (self: Response) -> headers, + setHeader: (self: Response, name: string, value: any) -> Response, + setBody: (self: Response, Data: any) -> Response, + json: (self: Response) -> Response, + setStatus: (self: Response, statusCode: number) -> Response, + finished: (self: Response) -> boolean, + finish: (self: Response) -> Response, + await: (self: Response) -> Net.ServeResponse, + new: (endpoint: any) -> Response +} + +local Response: Response = { + hasFinished = false +} :: Response + +function Response:setHeaders(headers: headers? | {}): Response + self.data.headers = headers or {} + return self +end + +function Response:getHeaders(): headers + return self.data.headers +end + +function Response:setHeader(name: string, value: any): Response + self:setHeaders(self:getHeaders()) -- init with an empty table if non-existent + self.data.headers[name] = value + + return self +end + +function Response:setBody(data: any): Response + self.data.body = data + return self +end + +function Response:json(data: any): Response + self:setHeader("Content-Type", "application/json") + self:setBody(Serde.encode("json", data)) + return self +end + +function Response:setStatus(statusCode: number): Response + self.data.status = statusCode + return self +end + +function Response:finish(): Response + self.hasFinished = true + self.future:resolve(self) + + return self +end + +function Response:finished(): boolean + return self.hasFinished +end + +function Response:await(): Net.ServeResponse + return self.future:await() +end + +function Response.new(endpoint: any): Response + local NewResponse = setmetatable({ + hasFinished = false, + data = {}, + future = Future.defer(), + endpoint = endpoint + }, {__index = Response}) + + return NewResponse +end + +return Response diff --git a/src/Server/init.luau b/src/Server/init.luau new file mode 100644 index 0000000..3ebe7d7 --- /dev/null +++ b/src/Server/init.luau @@ -0,0 +1,218 @@ +local Net = require("@lune/net") +local Task = require("@lune/task") + +local Signal = require("@lib/Signal") +local Future = require("@lib/Future") +local Router = require("@lib/Router") + +local Folder = require("Folder") +local Endpoints = require("Endpoints") +local Response = require("Response") + +export type Server = { + rootFolder: Folder.Folder, + endpoints: Endpoints.Endpoints, + + signal: Signal.Signal, + instance: Net.ServeHandle?, + loop: thread, + + createFolder: (self: Server, path: string) -> Folder.Folder, + getFolder: (self: Server, path: string) -> Folder.Folder?, + registerEndpoint: (self: Server, folderPath: string, endpoint: Endpoints.Endpoint) -> Server, + unregisterEndpoint: (self: Server, folderPath: string, endpointName: string) -> Server, + + get: (self: Server, path: string, callback: (Net.ServeRequest, Response.Response) -> ()) -> Endpoints.Endpoint, + post: (self: Server, path: string, callback: (Net.ServeRequest, Response.Response) -> ()) -> Endpoints.Endpoint, + put: (self: Server, path: string, callback: (Net.ServeRequest, Response.Response) -> ()) -> Endpoints.Endpoint, + delete: (self: Server, path: string, callback: (Net.ServeRequest, Response.Response) -> ()) -> Endpoints.Endpoint, + patch: (self: Server, path: string, callback: (Net.ServeRequest, Response.Response) -> ()) -> Endpoints.Endpoint, + + new: (port: number, verbose: boolean?) -> Server, + start: (self: Server) -> nil, + disconnect: (self: Server) -> nil, +} + +local Server = {} +Server.__index = Server + +function Server.new(port: number, verbose: boolean?): Server + local self = setmetatable({}, Server) + self.endpoints = Endpoints.new() + + self.signal = Signal.new() + + local function Callback(request: Net.ServeRequest) + local url = request.path + local path, queryString = url:match("([^%?]*)%??(.*)?") + path = path or url + + local Endpoint = self.endpoints:getByPath(path) + local routeParams = {} + + if not Endpoint then + for _, endpoint in pairs(self.endpoints.endpoints) do + if endpoint.path:find(":") then + local params = Router.parseRouteParams(endpoint.path, path) + if params then + Endpoint = endpoint + routeParams = params + break + end + end + end + end + + local Response = Response.new(Endpoint) + + if not Endpoint then + Response:setStatus(404):setBody("404 Not Found"):finish() + return Response:await() + end + + request.params = routeParams + + if Endpoint.middleware and Endpoint.middleware.pre then + for Index, Middleware in pairs(Endpoint.middleware.pre) do + Middleware(request, Response) + end + end + + local EndpointThread = Task.spawn(Endpoint.callback, request, Response) + local Timeout = Task.delay(30, function() + if not Response:finished() then + coroutine.close(EndpointThread) + Response = Response.new() + + Response:setStatus(500):setBody("The endpoint has timedout while waiting for completion"):finish() + end + end) + + local EndpointResult = Response:await() + coroutine.close(Timeout) + + if Endpoint.middleware and Endpoint.middleware.post then + for Index, Middleware in pairs(Endpoint.middleware.post or {}) do + Middleware(request, EndpointResult) + end + end + + return EndpointResult.data + end + + self.loop = Task.spawn(function() + coroutine.yield() + while self.instance do + local _reference = self.instance + Task.wait(0.1) + end + end) + + function self:registerEndpoint(folder: Folder.Folder, name: string, body: Endpoints.Endpoint): Endpoints.Endpoint + body.path = folder.path .. body.path + return self.endpoints:register(name, body) + end + + function self:get(path: string, callback: (Net.ServeRequest, Response.Response) -> ()): Endpoints.Endpoint + local rootFolder = self:registerFolder("root", "/") + return self:registerEndpoint(rootFolder, "GET_" .. path:gsub("/", "_"), { + method = "GET", + path = path, + callback = callback + }) + end + + function self:post(path: string, callback: (Net.ServeRequest, Response.Response) -> ()): Endpoints.Endpoint + local rootFolder = self:registerFolder("root", "/") + return self:registerEndpoint(rootFolder, "POST_" .. path:gsub("/", "_"), { + method = "POST", + path = path, + callback = callback + }) + end + + function self:put(path: string, callback: (Net.ServeRequest, Response.Response) -> ()): Endpoints.Endpoint + local rootFolder = self:registerFolder("root", "/") + return self:registerEndpoint(rootFolder, "PUT_" .. path:gsub("/", "_"), { + method = "PUT", + path = path, + callback = callback + }) + end + + function self:delete(path: string, callback: (Net.ServeRequest, Response.Response) -> ()): Endpoints.Endpoint + local rootFolder = self:registerFolder("root", "/") + return self:registerEndpoint(rootFolder, "DELETE_" .. path:gsub("/", "_"), { + method = "DELETE", + path = path, + callback = callback + }) + end + + function self:patch(path: string, callback: (Net.ServeRequest, Response.Response) -> ()): Endpoints.Endpoint + local rootFolder = self:registerFolder("root", "/") + return self:registerEndpoint(rootFolder, "PATCH_" .. path:gsub("/", "_"), { + method = "PATCH", + path = path, + callback = callback + }) + end + + function Server:registerFolder(name: string, path: string, parent: Folder.Folder?): Folder.Folder + if not parent then + if not self.rootFolder then + self.rootFolder = Folder.new("root", "") + end + + parent = self.rootFolder + end + + if path == "" or path == "/" then + return parent :: Folder.Folder + end + + local Parts = string.split(path, "/") + local Current = parent + + for i, Part in ipairs(Parts) do + if Part == "" then continue end + + if not Current.children[Part] then + local NewFolder = Folder.new(Part, Current.path .. "/" .. Part) + + Current:addChild({ + name = Part, + object = NewFolder, + type = "folder" + }) + end + + Current = Current.children[Part].object + end + + return Current + end + + function self:start() + if not self.instance then + self.instance = Net.serve(port, function(request: Net.ServeRequest) + self.signal:fire(request) + + local Response = Future.new(Callback, request):await() + return Response + end) + end + + coroutine.resume(self.loop) + end + + function self:disconnect() + self.instance.stop() + self.instance = nil + Task.cancel(self.loop) + end + + return self +end + +return Server diff --git a/src/init.luau b/src/init.luau new file mode 100644 index 0000000..115ad6d --- /dev/null +++ b/src/init.luau @@ -0,0 +1,46 @@ +-- Enums +local HTTPCodes = require("Enum/HTTPCodes") + +export type Enum = { + HTTPCodes: HTTPCodes.HTTPCodes, +} + +local Enum: Enum = { + HTTPCodes = HTTPCodes +} + +-- Libs +local Duration = require("lib/Duration") + +export type Lib = { + Duration: Duration.Duration, +} + +local Lib: Lib = { + Duration = Duration +} + +export type Moana = { + Lib: Lib, + Enum: Enum, + + Version: string, + + init: () -> Moana, + exit: (self: Moana) -> Moana, +} + +local Moana: Moana = { + Lib = Lib, + Enum = Enum, + + Version = '2.0.0', +} :: Moana + +function Moana.init() +end + +function Moana:exit() +end + +return Moana diff --git a/test.luau b/test.luau new file mode 100644 index 0000000..082732c --- /dev/null +++ b/test.luau @@ -0,0 +1,30 @@ +local Net = require("@lune/net") +local Middleware = require("src/Middleware") + +local Response = require("src/Server/Response") + +local ServerLib = require("src/Server") +local Server = ServerLib.new(3001) + +local RootFolder = Server:registerFolder("root", "/") +local wowEndpoint = Server:registerEndpoint(RootFolder, "wow", { + method = "GET", + path = "/wow", + callback = function(request: Net.ServeRequest, response: Response.Response) + response.endpoint.output:raise("funsies", "wow", "info") + response:setBody(string.len(request.body)):setStatus(200):finish() + end +}) + +print(wowEndpoint) + +wowEndpoint.output:onError(function(err) + err:output() +end) + +Server:start() +Net.request({url = 'http://localhost:3001/wow'}) + +Server:disconnect() + +local thing