commit abac587d144a6a962b6dad2782f2c5f358321d71 Author: nightshade Date: Thu Jul 24 12:46:01 2025 -0500 nerack repo diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..12db3dc --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +examples/** linguist-documentation=false linguist-vendored=false +*.sql linguist-detectable=true +*.sql linguist-language=SQL +*.c linguist-detectable=true +*.c linguist-language=C +*.html linguist-detectable=true +*.html linguist-language=HTML +*.mu linguist-language=Markdown +*.micron linguist-language=Markdown diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/COPYING @@ -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 +. diff --git a/COPYING.LESSER b/COPYING.LESSER new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER 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. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/GUIDE.md b/GUIDE.md new file mode 100644 index 0000000..f5fd658 --- /dev/null +++ b/GUIDE.md @@ -0,0 +1,772 @@ +[← Back to README](./README.md) + +# Guide + +This guide builds a todo app one concept at a time. See the [Reference](./REFERENCE.md) for full options on each step, helper, and field. Nerack discovers assets by file location and seeds each one into the context of the module that owns it (see [Assets](./REFERENCE.md#assets)). + +* [1. Pages and Templates](#1-pages-and-templates) +* [2. Show Data](#2-show-data) +* [3. Accept Input](#3-accept-input) +* [4. Nested Data](#4-nested-data) +* [5. Calling APIs](#5-calling-apis) +* [6. Tasks](#6-tasks) +* [7. Modules and Events](#7-modules-and-events) + +### 1. Pages and Templates + +Each `http(...)` declares a named resource and URL, and each verb pipeline is a list of steps. `html("home", "home_s")` renders the template asset `home` into context key `home_s`, and `http_response("home_s")` sends it. `{{url:verb:name}}` builds a link to a resource: the verb first, then the resource name. Any `:params` in the pattern are filled from the current scope by matching key names. + +Both pages share a layout, so `home` doubles as the layout: it declares the nav and a `{{$body}}` block whose default is the welcome page. The `todos` page extends it with `{{< home}}...{{/home}}`, overriding that block. Any template that declares a `{{$block}}` can be a parent; there is no special layout type. + +**`home.mustache.html`** +```html + + + +
+ {{$body}} +

Welcome

+ {{/body}} +
+ + +``` + +**`todos.mustache.html`** +```html +{{< home}} + {{$body}} +

My Todos

+

Nothing yet.

+ {{/body}} +{{/home}} +``` + +**`todo.c`** +```c +#include +#include + +module(todo){ + http("home", "/", + .get = { + html("home", "home_s"), + http_response("home_s") + } + ); + http("todos", "/todos", + .get = { + html("todos", "todos_s"), + http_response("todos_s") + } + ); +} +``` + +See [HTTP Pipelines](./REFERENCE.md#http-pipelines) and [Templates](./REFERENCE.md#templates). + +### 2. Show Data + +Bring in SQLite with `#include `, declare a database with `sqlite(...)`, and read with `sqlite_query()`. SQL files are assets like templates: `get_todos.sql` becomes the asset `get_todos`. + +Three new SQL files: + +**`create_todos_table.sql`** +```sql +CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL +); +``` + +**`seed_todos.sql`** +```sql +INSERT INTO todos(title) VALUES('Learn Nerack'); +``` + +**`get_todos.sql`** +```sql +select id, title from todos; +``` + +Render the rows Nerack stores under `todos_data`: + +**`todos.mustache.html`** +```diff + {{< home}} + {{$body}} +

My Todos

+-

Nothing yet.

++
    ++ {{#todos_data}} ++
  • {{title}}
  • ++ {{/todos_data}} ++
+ {{/body}} + {{/home}} +``` + +Wire up the module, database, and query: + +**`todo.c`** +```diff + #include + #include ++#include + + module(todo){ ++ sqlite( ++ "todos_db", ++ "file:todos.db?mode=rwc", ++ {"create_todos_table"}, ++ {"seed_todos"} ++ ); ++ + http("home", "/", + .get = { + html("home", "home_s"), + http_response("home_s") + } + ); + http("todos", "/todos", + .get = { ++ sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + } + ); + } +``` + +The three positional arguments are the database name, the SQL asset, and the context key for the result table (`todos_data`). The template walks the result with `{{#todos_data}}...{{/todos_data}}`. Migrations and seeds run on first connection. See [Databases](./REFERENCE.md#databases) and [query](./REFERENCE.md#query). + +### 3. Accept Input + +Add a `.post` verb that validates, inserts, and redirects (POST-redirect-GET). A resource-scoped `.errors` handler re-renders the form on validation failure. + +**`create_todo.sql`** +```sql +insert into todos(title) values({{title}}); +``` + +Add the form, repopulating the field and showing the error after a failed submit: + +**`todos.mustache.html`** +```diff + {{< home}} + {{$body}} +

My Todos

++
++ ++ {{#error:title}} ++ {{error_message:title}} ++ {{/error:title}} ++ ++
+
    + {{#todos_data}} +
  • {{title}}
  • + {{/todos_data}} +
+ {{/body}} + {{/home}} +``` + +Add a `.post` verb and an `.errors` handler: + +**`todo.c`** +```diff + #include + #include + #include + + module(todo){ + sqlite( + "todos_db", + "file:todos.db?mode=rwc", + {"create_todos_table"}, + {"seed_todos"} + ); + + http("home", "/", + .get = { + html("home", "home_s"), + http_response("home_s") + } + ); + + http("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") +- } ++ }, ++ .post = { ++ input({"title", not_empty_input}), ++ sqlite_query({"todos_db", "create_todo"}), ++ http_redirect("todos") ++ }, ++ .errors = { ++ {http_bad_request, {http_reroute("todos")}} ++ } + ); + } +``` + +The form posts to `{{url:post:todos}}`. Because `post` is a state-changing verb, the helper appends both `http_method=post` and a fresh CSRF token to the action URL, so the form needs no hidden fields of its own. + +`input()` validates and promotes `title` to app scope; the `{{title}}` in `create_todo.sql` binds as a prepared-statement parameter. On failure, `http_bad_request` triggers the handler, which `reroute`s back into the GET pipeline in-process. The `input:` and `error:` scopes survive the reroute, so the form repopulates with `{{input:title}}` and shows `{{error_message:title}}`. See [input](./REFERENCE.md#input), [Error and Repair Pipelines](./REFERENCE.md#error-and-repair-pipelines), and [redirect and reroute](./REFERENCE.md#redirect-and-reroute). + +### 4. Nested Data + +A `/todos/:id` page fetches a todo and its comments concurrently, then nests the comments inside the todo with `join()`. + +Three new SQL files and one new template: + +**`create_comments_table.sql`** +```sql +CREATE TABLE IF NOT EXISTS comments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + todo_id INTEGER NOT NULL REFERENCES todos(id), + body TEXT NOT NULL +); +``` + +**`get_todo.sql`** +```sql +select id, title from todos where id = {{id}}; +``` + +**`get_comments.sql`** +```sql +select id, todo_id, body from comments where todo_id = {{id}}; +``` + +Enter `{{#todo_data}}` first; after the join, `comments` lives inside each todo record: + +**`todo.mustache.html`** +```html +{{< home}} + {{$body}} + {{#todo_data}} +

{{title}}

+

Comments

+
    + {{#comments}} +
  • {{body}}
  • + {{/comments}} +
+ {{/todo_data}} + {{/body}} +{{/home}} +``` + +Link each list item to its detail page. `{{url:get:todo}}` resolves the `todo` resource's pattern (`/todos/:id`) and fills `:id` from the current scope, which inside `{{#todos_data}}` is the current row: + +**`todos.mustache.html`** +```diff + {{#todos_data}} +-
  • {{title}}
  • ++
  • {{title}}
  • + {{/todos_data}} +``` + +Register the migration and add a `todo` resource: + +**`todo.c`** +```diff + #include + #include + #include + + module(todo){ + sqlite( + "todos_db", + "file:todos.db?mode=rwc", +- {"create_todos_table"}, ++ {"create_todos_table", "create_comments_table"}, + {"seed_todos"} + ); + + http("home", "/", + .get = { + html("home", "home_s"), + http_response("home_s") + } + ); + + http("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "create_todo"}), + http_redirect("todos") + }, + .errors = { + {http_bad_request, {http_reroute("todos")}} + } + ); ++ ++ http("todo", "/todos/:id", ++ .get = { ++ input({"id", positive_integer_input}), ++ sqlite_query( ++ {"todos_db", "get_todo", "todo_data", .error_on_empty = true}, ++ {"todos_db", "get_comments", "comments"} ++ ), ++ join("todo_data", "id", "comments", "todo_id"), ++ html("todo", "todo_s"), ++ http_response("todo_s") ++ } ++ ); + } +``` + +Both queries in one `sqlite_query()` call run concurrently. `join()` lifts `comments` inside each `todo_data` record, so the template reaches `{{#comments}}` from within `{{#todo_data}}`. `.error_on_empty = true` returns 404 when the id matches nothing. See [join](./REFERENCE.md#join) and [query](./REFERENCE.md#query). + +### 5. Calling APIs + +`http_fetch()` calls external HTTP services like a query calls a database. JSON parses into context tables; multiple items in one `http_fetch()` run concurrently. + +Show the responses on the home page: + +**`home.mustache.html`** +```diff + + + +
    +- {{$body}} +-

    Welcome

    +- {{/body}} ++ {{$body}} ++

    Welcome

    ++ {{#weather}} ++

    {{city}}: {{precision:temp_c:0}}°C, {{conditions}}

    ++ {{/weather}} ++ {{#quote}} ++
    {{content}}, {{author}}
    ++ {{/quote}} ++ {{/body}} +
    + + +``` + +Fetch both services concurrently before rendering: + +**`todo.c`** +```diff + #include + #include + #include + + module(todo){ + sqlite( + "todos_db", + "file:todos.db?mode=rwc", + {"create_todos_table", "create_comments_table"}, + {"seed_todos"} + ); + + http("home", "/", + .get = { ++ http_fetch( ++ {http_get, "https://api.quotes.dev/random", "quote"}, ++ {http_get, "https://api.weather.dev/now", "weather"} ++ ), + html("home", "home_s"), + http_response("home_s") + } + ); + + http("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "create_todo"}), + http_redirect("todos") + }, + .errors = { + {http_bad_request, {http_reroute("todos")}} + } + ); + + http("todo", "/todos/:id", + .get = { + input({"id", positive_integer_input}), + sqlite_query( + {"todos_db", "get_todo", "todo_data", .error_on_empty = true}, + {"todos_db", "get_comments", "comments"} + ), + join("todo_data", "id", "comments", "todo_id"), + html("todo", "todo_s"), + http_response("todo_s") + } + ); + } +``` + +Both requests run concurrently under one `http_fetch()` call. The JSON parses into context tables the template walks with `{{#quote}}` and `{{#weather}}`. `http_fetch()` also supports other verbs, headers, request bodies, and interpolated URLs. See [fetch](./REFERENCE.md#fetch). + +### 6. Tasks + +A task is a named, reusable pipeline. Define it once with optional `.cron`; dispatch durable background runs with `dispatch("name")` (from `dispatch.h`). + +Two new SQL files: + +**`create_daily_stats_table.sql`** +```sql +CREATE TABLE IF NOT EXISTS daily_stats ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + todo_count INTEGER NOT NULL +); +``` + +**`record_daily_stats.sql`** +```sql +insert into daily_stats(todo_count) select count(*) from todos; +``` + +Register the migration, define the tasks, dispatch them from the POST: + +**`todo.c`** +```diff + #include + #include + #include ++#include + + module(todo){ + sqlite( + "todos_db", + "file:todos.db?mode=rwc", +- {"create_todos_table", "create_comments_table"}, ++ {"create_todos_table", "create_comments_table", "create_daily_stats_table"}, + {"seed_todos"} + ); + ++ task("record_daily_stats", { ++ sqlite_query({"todos_db", "record_daily_stats"}) ++ }, .cron = "0 0 * * *"); ++ ++ task("notify_new_todo", { ++ http_fetch({ ++ http_post, ++ "https://api.push.dev/notify", ++ .json = "{\"text\":\"New todo: {{title}}\"}" ++ }) ++ }, .accepts = {"title"}); ++ + http("home", "/", + .get = { + http_fetch( + {http_get, "https://api.quotes.dev/random", "quote"}, + {http_get, "https://api.weather.dev/now", "weather"} + ), + html("home", "home_s"), + http_response("home_s") + } + ); + + http("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "create_todo"}), ++ dispatch("notify_new_todo"), + http_redirect("todos") + }, + .errors = { + {http_bad_request, {http_reroute("todos")}} + } + ); + + http("todo", "/todos/:id", + .get = { + input({"id", positive_integer_input}), + sqlite_query( + {"todos_db", "get_todo", "todo_data", .error_on_empty = true}, + {"todos_db", "get_comments", "comments"} + ), + join("todo_data", "id", "comments", "todo_id"), + html("todo", "todo_s"), + http_response("todo_s") + } + ); + } +``` + +`.cron` and `dispatch(...)` both run the task on a task reactor, off the request reactors, so the POST returns immediately. Dispatched tasks are durable: a crash mid-task resumes on the next boot. To hand values to a task, list them under `.accepts`; `notify_new_todo` pulls in `title` that way. `dispatch()` comes from `dispatch.h`. See [Task Pipelines](./REFERENCE.md#task-pipelines). + +### 7. Modules and Events + +Split features into modules that talk through pub/sub events. A module is any `.c` file declaring `module(name){ ... }`, registering that module's resources, databases, tasks, and subscribers. Nerack discovers every `module(...)` on disk. A module's assets live in its `name/` folder and are private to it; assets at the project root are shared across modules (see [Assets](./REFERENCE.md#assets)). + +This step moves todos into its own module and adds an `activity` module that records an entry whenever a todo is created. The top-level file becomes `main.c` and keeps just the `home` resource; `home.mustache.html` stays at the project root, shared across modules: + +``` +. +├── main.c +├── todos/ +│ ├── todos.c +│ ├── todos.mustache.html +│ ├── todo.mustache.html +│ ├── create_todos_table.sql +│ ├── create_comments_table.sql +│ ├── create_daily_stats_table.sql +│ ├── seed_todos.sql +│ ├── record_daily_stats.sql +│ ├── get_todos.sql +│ ├── get_todo.sql +│ ├── get_comments.sql +│ └── create_todo.sql +├── activity/ +│ ├── activity.c +│ ├── activity.mustache.html +│ ├── create_activity_table.sql +│ ├── get_activities.sql +│ └── insert_activity.sql +└── home.mustache.html +``` + +**`main.c`** +```diff + #include + #include +-#include +-#include + +-module(todo){ ++module(main){ +- sqlite( +- "todos_db", +- "file:todos.db?mode=rwc", +- {"create_todos_table", "create_comments_table", "create_daily_stats_table"}, +- {"seed_todos"} +- ); +- +- task("record_daily_stats", { +- sqlite_query({"todos_db", "record_daily_stats"}) +- }, .cron = "0 0 * * *"); +- +- task("notify_new_todo", { +- http_fetch({ +- http_post, +- "https://api.push.dev/notify", +- .json = "{\"text\":\"New todo: {{title}}\"}" +- }) +- }, .accepts = {"title"}); +- + http("home", "/", + .get = { + http_fetch( + {http_get, "https://api.quotes.dev/random", "quote"}, + {http_get, "https://api.weather.dev/now", "weather"} + ), + html("home", "home_s"), + http_response("home_s") + } + ); +- +- http("todos", "/todos", +- .get = { +- sqlite_query({"todos_db", "get_todos", "todos_data"}), +- html("todos", "todos_s"), +- http_response("todos_s") +- }, +- .post = { +- input({"title", not_empty_input}), +- sqlite_query({"todos_db", "create_todo"}), +- dispatch("notify_new_todo"), +- http_redirect("todos") +- }, +- .errors = { +- {http_bad_request, {http_reroute("todos")}} +- } +- ); +- +- http("todo", "/todos/:id", +- .get = { +- input({"id", positive_integer_input}), +- sqlite_query( +- {"todos_db", "get_todo", "todo_data", .error_on_empty = true}, +- {"todos_db", "get_comments", "comments"} +- ), +- join("todo_data", "id", "comments", "todo_id"), +- html("todo", "todo_s"), +- http_response("todo_s") +- } +- ); + } +``` + +Add an Activity link to the shared nav: + +**`home.mustache.html`** +```diff + + +- ++ +
    + {{$body}} +

    Welcome

    + {{#weather}} +

    {{city}}: {{precision:temp_c:0}}°C, {{conditions}}

    + {{/weather}} + {{#quote}} +
    {{content}}, {{author}}
    + {{/quote}} + {{/body}} +
    + + +``` + +The todos logic moves into the module unchanged, with a `publish()` declaration and an `emit()` step added. Both todo resources move with it: + +**`todos/todos.c`** +```c +#include +#include +#include +#include +#include + +module(todos){ + sqlite( + "todos_db", + "file:todos.db?mode=rwc", + {"create_todos_table", "create_comments_table", "create_daily_stats_table"}, + {"seed_todos"} + ); + + publish("todo_created", + .with = {"title"} + ); + + task("record_daily_stats", { + sqlite_query({"todos_db", "record_daily_stats"}) + }, .cron = "0 0 * * *"); + + task("notify_new_todo", { + http_fetch({ + http_post, + "https://api.push.dev/notify", + .json = "{\"text\":\"New todo: {{title}}\"}" + }) + }, .accepts = {"title"}); + + http("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "create_todo"}), + dispatch("notify_new_todo"), + emit("todo_created"), + http_redirect("todos") + }, + .errors = { + {http_bad_request, {http_reroute("todos")}} + } + ); + + http("todo", "/todos/:id", + .get = { + input({"id", positive_integer_input}), + sqlite_query( + {"todos_db", "get_todo", "todo_data", .error_on_empty = true}, + {"todos_db", "get_comments", "comments"} + ), + join("todo_data", "id", "comments", "todo_id"), + html("todo", "todo_s"), + http_response("todo_s") + } + ); +} +``` + +The `activity` module owns its own table, query, template, and subscriber. Nothing in it references the todos module: + +**`activity/create_activity_table.sql`** +```sql +CREATE TABLE IF NOT EXISTS activities ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, + ref TEXT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +**`activity/insert_activity.sql`** +```sql +insert into activities(kind, ref) values('created', {{title}}); +``` + +**`activity/get_activities.sql`** +```sql +select kind, ref, created_at from activities order by created_at desc; +``` + +**`activity/activity.mustache.html`** +```html +{{< home}} + {{$body}} +

    Activity

    +
      + {{#activities}} +
    • {{kind}}: {{ref}} ({{created_at}})
    • + {{/activities}} +
    + {{/body}} +{{/home}} +``` + +**`activity/activity.c`** +```c +#include +#include +#include +#include + +module(activity){ + sqlite( + "activity_db", + "file:activity.db?mode=rwc", + {"create_activity_table"} + ); + + subscribe("todo_created", { + sqlite_query({"activity_db", "insert_activity"}) + }); + + http("activity", "/activity", + .get = { + sqlite_query({"activity_db", "get_activities", "activities"}), + html("activity", "activity_s"), + http_response("activity_s") + } + ); +} +``` + +When the POST calls `emit("todo_created")`, Nerack propagates the keys named in `publish(...).with` (`title`) to every subscriber. The `activity` module writes its row with no direct link to the publisher. Events are durable: undelivered ones replay after a crash. A third subscriber is another module with its own `subscribe(...)`, and the publisher still does not change. See [Modules and Composition](./REFERENCE.md#modules-and-composition) and [Event Pipelines](./REFERENCE.md#event-pipelines). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER 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. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/README.md b/README.md new file mode 100644 index 0000000..05d46ac --- /dev/null +++ b/README.md @@ -0,0 +1,167 @@ +![Nerack C](./images/nerack_scene.png) + +## Why Nerack + +Nerack is a declarative, protocol-agnostic framework for asynchronous networking applications in C, built around self-contained systems. + +* **Self-contained systems:** an app is a set of self-contained modules whose boundaries the compiler enforces. +* **Durable tasks and events:** both are persisted. After a crash, incomplete tasks resume at the step where they stopped and undelivered events replay. +* **Developer experience:** compilation, hot code reloading, and an HMR feedback loop, with no build scripts. Write code and save. The only dependency is Docker. +* **Memory, concurrency, and I/O managed by the framework:** application code does not call malloc/free or manage threads, mutexes, or locks. +* **Observability:** pipeline steps emit OpenTelemetry spans, logs, and errors automatically. +* **Protocols:** HTTP, RNS, LXMF, NomadNet, Gemini, Finger, SMTP, or any other; one app can serve several at once. +* **Databases:** SQLite, Postgres, MySQL, Redis, DuckDB, or any other; multi-tenancy is built in, and one app can use several at once. +* **Authentication:** cookie and session auth are bundled; WebAuthn, OTP, or any other. +* **Bundled modules:** HTML, Markdown, and Micron templates; Datastar, HTMX, Tailwind, DaisyUI; HTTP, RNS, SQLite; pub/sub; background and cron tasks. + +--- + +## Table of Contents +* [Quick Start](#quick-start) +* [Philosophy](#philosophy) +* [Tooling](#tooling) +* [Built With](#built-with) +* [License](#license) +* **Documentation** + * [Guide](./GUIDE.md): build a todo app one concept at a time + * [Reference](./REFERENCE.md): full options for every step, helper, and field + +--- + +## Quick Start + +Everything runs in Docker. + +```bash +mkdir myapp && cd myapp +wget https://docker.nightshadecoder.dev/nerack/compose.yml + +# Dev server on :3000, telemetry on :4000 +# Includes file watching, auto compilation, hot code reloading, HMR +docker compose up +``` + +Create `hello_world.c` with the example below. Nerack watches for changes and hot-reloads on save. Edit it with your own editor, the built-in TUI, or the web editor; see [Development Environment](#development-environment) for all three. + +```c +#include +#include + +module(hello_world){ + context("hello", "Hello, world"); + http("home", "/", .mime = mime_text, .get = {http_response("hello")}); +} +``` + +A module is any `.c` file declaring `module(name){...}`; `hello_world.c` declares the `hello_world` module. `context()` seeds the context key `hello` from a string literal instead of a file; `http()` declares the `home` resource mapping `/` to a GET pipeline that sends that value with `http_response()`, as `text/plain` because of `.mime`. `http()` comes from `http.h`; the core itself has no notion of HTTP. See the [Guide](./GUIDE.md) for a step-by-step walkthrough. + +--- + +## Philosophy + +An application is a data transformation: input arrives, is transformed, and leaves as output. Nerack arranges the work into pipelines: ordered lists of steps that turn a request into a response. + +### Steps + +Steps are the primitive; a pipeline is an ordered list of them. A step is declarative: it describes what should happen, not how. Each step is self-contained: it may run synchronously or asynchronously, but the pipeline treats it as a single synchronization point, and the next step starts only once it resolves. A step guarantees that when it finishes, context holds the values it promised; if it cannot, it raises an error instead, handled by an error or repair pipeline. Each step is its own OpenTelemetry span, logs itself, and counts its own performance. + +### Built on Standards + +The assets are standard formats: SQL, JSON, Markdown, HTML, CSS, JS, Micron. Business logic is plain C. The tooling is standard too: LLDB for debugging, Playwright and Criterion for testing, OpenTelemetry for observability. + +### Everything is a String + +The web is text: HTTP, RNS, Micron, HTML, Markdown, JSON, SQL. The pipeline context stores and passes data as strings. Strings are interpolated into SQL, templates, and URLs with `{{context_key}}`. + +### CLAD + +Four principles: + +* **(C)omposable:** small, independent steps chain into feature pipelines. +* **(L)ocality of Behavior:** behavior is apparent from reading the code. SQL, templates, and logic for a feature live together, not spread across model, view, and controller trees. +* **(A)utonomous:** each module owns its schemas, migrations, seeds, resources, UI, and logic, and the compiler enforces the boundaries. +* **(D)omain Based:** each module owns one slice of the app. A `todos` module defines everything related to todos and nothing else. + +Inspired by: + +* [Data Oriented Design](https://youtu.be/rX0ItVEVjHc) +* [A Philosophy of Software Design](https://youtu.be/bmSAYlu0NcY) +* [CUPID](https://youtu.be/cyZDLjLuQ9g) +* [Self-Contained Systems](https://youtu.be/Jjrencq8sUQ) +* [Locality of Behavior](https://htmx.org/essays/locality-of-behaviour) + +--- + +## Tooling + +### Development Environment + +Nerack apps can be built three ways: the web editor, the built-in TUI, or your own editor. The folder holding `compose.yml` is the project root; module `.c` files and assets (SQL, HTML, and so on) live there, as shown in the [Guide](./GUIDE.md) and [Reference](./REFERENCE.md). The three are not exclusive: mix and match freely. + +#### Web Editor +The built-in web editor represents modules, resources, pipelines, and databases as graphical widgets instead of raw text, with a code editor for step bodies. It generates module `.c` files and assets into the project root; saving a change compiles and hot-reloads it like any other edit. A module/asset viewer shows what was generated, and a server console shows requests and errors. +``` +http://localhost:3000/___dev___ +``` + +#### TUI +The built-in TUI is a terminal editor with auto-compilation, hot reloading, an LSP, and a server console for requests and errors. +```bash +docker compose attach nerack +``` + +#### Bring Your Own +Nerack watches the project root regardless of editor. Edit `.c` files and assets with any tool; Nerack compiles and hot-reloads on save. +```bash +docker compose attach server # server console: requests and errors +``` + +### Testing +Built-in runners for unit and end-to-end testing; no external framework setup required. +```bash +unit_tests # fast, criterion-based tests +e2e_tests # playwright-powered browser tests +``` + +### Debugging +The debug commands are pipeline-aware: halt on a step, step through execution, and inspect the full context, including nested tables and records. +```bash +app_debug # interactive debugger in the TUI +``` + +### Deployment +Nerack deploys as a standard Docker container. It does not terminate TLS; production deployments place Nerack behind a reverse proxy or load balancer (Nginx, Caddy, AWS ALB) to handle HTTPS. +```bash +app_build # outputs a minimal production Docker image +``` + +`app_build` runs each module's asset scan once (see [Assets](./REFERENCE.md#assets)) and compiles the results into that module's binary. The production image excludes the file watcher and `/__dev__`. + +### Observability +Each pipeline step emits OpenTelemetry spans. Logs, traces, errors, and auto-profiling are visualized on the telemetry server at port 4000. No manual instrumentation required. + +## Built With + +| | | +|---|---| +| [C](https://en.cppreference.com/w/c/23) | Language standard | +| [Docker](https://www.docker.com/) | Development environment, production images, stack orchestration | +| [libuv](https://libuv.org/) | Event loops, async I/O, file watching, shared thread pool | +| [libmicrohttpd](https://www.gnu.org/software/libmicrohttpd/) | HTTP server, used by the `http` protocol module | +| [Mustach](https://gitlab.com/jobol/mustach) | Templating and string interpolation, used by `html()`/`markdown()` | +| [Jansson](https://github.com/akheron/jansson) | JSON parsing and generation, used by `json()` and `http_fetch()` | +| [curl](https://curl.se/) | HTTP client, used by `http_fetch()` | +| [Reticulum](https://reticulum.network/) | Mesh networking stack, used by the `rns` protocol module | +| [LXMF](https://github.com/markqvist/LXMF) | Message transfer protocol over Reticulum, used by the `lxmf` protocol module | +| [Fresh](https://getfresh.dev/) | TUI editor | +| [clangd](https://clangd.llvm.org/) | Language server | +| [LLDB](https://lldb.llvm.org/) | Debugger | +| [Criterion](https://github.com/Snaipe/Criterion) | Unit testing | +| [Playwright](https://playwright.dev/) | End-to-end testing | +| [SigNoz](https://signoz.io/) + [OpenTelemetry](https://opentelemetry.io/) | APM, traces, logs, errors, dashboards | + +--- + +## License + +Nerack is licensed under the [LGPL](./LICENSE). Your application code can use any license; it is a Nerack plugin. diff --git a/REFERENCE.md b/REFERENCE.md new file mode 100644 index 0000000..4ea71e4 --- /dev/null +++ b/REFERENCE.md @@ -0,0 +1,1579 @@ +[← Back to README](./README.md) + +# Reference + +* [Context](#context) +* [Assets](#assets) +* [Databases](#databases) +* [Error and Repair Pipelines](#error-and-repair-pipelines) +* [Event Pipelines](#event-pipelines) +* [Task Pipelines](#task-pipelines) +* [Pipeline Steps](#pipeline-steps) +* [Imperative API](#imperative-api) +* [Conditionals](#conditionals) +* [Iteration](#iteration) +* [Modules and Composition](#modules-and-composition) +* [Additional Modules](#additional-modules) +* [Static Files](#static-files) +* [External Dependencies](#external-dependencies) + +### Context + +Pipelines read from and write to a shared, scoped key-value store that lives for one request. Every step draws inputs from context and writes outputs back. + +Three scopes: `input:xxx` for raw request parameters, `error:xxx` for validation/error data, and unprefixed names for app scope (query results, validated inputs, computed values). `input()` promotes values from `input:` to app scope. + +Keys are global to the request. A step that writes a key already in use replaces its value, so take care not to overwrite a value another step still needs. + +### Assets + +Every non-`.c` file is an asset, available by key to each module that seeds it (see below). The common types are Mustache templates (`*.mustache.html`), Micron templates (`*.mustache.mu`), Markdown (`*.mustache.md`), and SQL (`*.sql`), but any file type works. + +An asset's key is the filename's basename, the part before the first dot. `get_todos.sql` seeds `get_todos`, `todos.mustache.html` seeds `todos`. For templates the middle segment names the engine: `html()` reads `.mustache.html`, `micron()` reads `.mustache.mu`, `markdown()` reads `.mustache.md`, and a module can add its own (`html_erb()` reads `.erb.html`). One key can back several engines: `html("todo")` renders `todo.mustache.html`, `micron("todo")` renders `todo.mustache.mu`. A `{{> partial}}` or `{{< parent}}` reference resolves against the engine that rendered the enclosing template, so `todo.mustache.html` with `{{> layout}}` pulls in `layout.mustache.html` and `todo.mustache.mu` pulls in `layout.mustache.mu`. + +`html()`, `markdown()`, `micron()`, and the engine `*_query()` steps read a string from context by key and interpret it as a template or SQL. The step interprets whatever is under the key when it runs. + +`context(name, value)` does the same seeding from a string instead of a file. Useful for content too small to warrant its own file: +```c +context("hello", "

    Hello, world!

    "); // then html("hello", "hello_s") +context("ping", "select 1"); // then sqlite_query({"db", "ping"}) +``` + +A module is seeded with every asset from its own folder up to the project root. Assets at the root are shared by all modules; assets inside a module's folder are seen only by that module. The scan runs up the tree, not sideways, so a module never sees another module's folder: + +``` +. +├── layout.mustache.html # → every module +├── 404.mustache.html # → every module +├── partials/ +│ └── footer.mustache.html # → every module (partials/ has no module()) +└── todos/ + ├── todos.c # the "todos" module + ├── todos.mustache.html # → todos + └── detail/ + └── todo.mustache.html # → todos (detail/ has no module()) +``` + +In dev, the scan is live: editing an asset reloads that file into every module holding it, and saving a `.c` file recompiles and reloads that module alone. A production build runs the scan once and compiles each module's assets into its binary; see [Deployment](./README.md#deployment). + +### Databases + +Each database engine is a module: `#include` its header (e.g. `#include `) to activate it, then register one or more databases with `(...)`. Migrations and seeds are forward-only and index-based: they run in array order, each applied once, with new ones appended to the end. Both are tracked in a `nerack_meta` table. + +Multi-tenant databases use `{{interpolation}}` in `.connection`. Connections are pooled with LRU eviction. + +**`.database_key`**: identifier referenced by the first value of `query()` steps. +```c +.database_key = "todos_db" +``` + +**`.connection`**: engine-specific connection string. Supports `{{interpolation}}` for multi-tenancy. +```c +.connection = "file:{{user_id}}_todo.db?mode=rwc" +``` + +**`.migrations`**: array of SQL migration entries, applied once each in order. Each entry is a context key holding the SQL. +```c +.migrations = {"create_todos_table", "create_comments_table"} +``` + +**`.seeds`**: array of SQL seed entries, applied once each in order. Each entry is a context key holding the SQL. +```c +.seeds = {"seed_todos"} +``` + +Combined: +```c +#include + +sqlite( + .database_key = "blog_db", + .connection = "file:{{user_id}}_blog.db?mode=rwc", + .migrations = {"create_blogs_table", "create_comments_table"}, + .seeds = {"seed_blogs"} +); +``` + +**Engine include / query / register:** `#include ` + `sqlite_query()` + `sqlite()`. SQLite is the bundled engine; another engine added as a module follows the same three-name pattern (`postgres_*`, `redis_*`, and so on). + +### Error and Repair Pipelines + +When a step fails, execution halts and Nerack looks for a handler matching the error code. It checks the resource's own `.errors`/`.repairs` first, then the `error()`/`repair()` handlers in that resource's module, and uses the first match. A resource handler overrides the module's for the same code. + +Errors are terminal: the handler sends a response and ends the request. Repairs are resumable: they fix the context and resume the original pipeline at the step after the failure. Repairs resolve first; if no matching repair is found, resolution falls through to errors. Unhandled errors fall through to Nerack's internal handler, which renders a context template named after the error code, or the error message as `text/plain` with that code as the HTTP status when there is no such template. Every unhandled error also surfaces in the TUI console and telemetry. + +The `error` scope is shared across `input()` failures and `error_set()` calls: `{{error:name}}`, `{{error_code:name}}`, `{{error_message:name}}`. The raw input value remains in `input:name` for re-rendering forms. + +**Resource-scoped (`.errors` / `.repairs` fields):** +```c +http("todos", "/todos", + .post = { ... }, + .errors = { + {http_not_found, { + html("404", "not_found_s"), + http_response("not_found_s") + }}, + {http_bad_request, { + html("form", "form_s"), + http_response("form_s") + }} + }, + .repairs = { + {http_not_authorized, {run(.call = refresh_session_token)}} + } +); +``` + +**Module-scoped (`error()` / `repair()` calls):** +```c +module(todos){ + error(http_error, { + html("500", "error_s"), + http_response("error_s") + }); + error(http_not_found, { + html("404", "not_found_s"), + http_response("not_found_s") + }); + repair(http_not_authorized, {run(.call = refresh_session_token)}); + // ... resources ... +} +``` + +Error codes are plain integers; nothing in the core assigns them meaning. Protocol modules supply convenience names for their own status codes. `http.h` defines `http_bad_request` (400), `http_not_authorized` (401), `http_not_found` (404), `http_error` (500). Define your own for domain-specific errors, e.g. `#define err_quota_exceeded 723`. + +### Event Pipelines + +Internal pub/sub for cross-module communication. The publisher does not know who listens; the subscriber does not know who emits. Adding a subscriber means adding a new module with a `subscribe(...)` call; the publisher does not change. Activate with `#include ` in any module that publishes or subscribes. + +Events are durable. When a publisher is declared, Nerack creates a `nerack_events` database to track delivery. If the process crashes, undelivered events replay on the next boot. + +**`publish(event, .with = {...})`**: declares an outbound event contract. First value is the event name; `.with` lists context keys to pass along. +```c +publish("todo_created", + .with = {"user_id", "title"} +); +``` + +**`subscribe(event, { steps })`**: registers a subscriber pipeline keyed by event name. +```c +subscribe("todo_created", { + sqlite_query({"activity_db", "insert_activity"}) +}); +``` + +**`emit(event)`**: a pipeline step that fires the event (see [emit](#emit)). +```c +emit("todo_created") +``` + +**`.errors` / `.repairs`** *(per subscriber)*: each `subscribe(...)` can declare its own handlers, resolved the same way as resource pipelines (the subscriber's own handlers, then its module's). See [Error and Repair Pipelines](#error-and-repair-pipelines). +```c +subscribe("todo_created", { + sqlite_query({"activity_db", "insert_activity"}) +}, .errors = {{http_error, {run(.call = log_subscriber_failure)}}}); +``` + +Combined: +```c +// todos/todos.c: publisher +module(todos){ + publish("todo_created", + .with = {"user_id", "title"} + ); + publish("todo_deleted", + .with = {"user_id", "todo_id"} + ); + + http("todos", "/todos", + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "insert_todo"}), + emit("todo_created"), + http_redirect("todos") + } + ); +} + +// activity/activity.c: subscriber +module(activity){ + subscribe("todo_created", { + sqlite_query({"activity_db", "insert_created_activity"}) + }); + subscribe("todo_deleted", { + sqlite_query({"activity_db", "insert_deleted_activity"}) + }); +} +``` + +### Task Pipelines + +A task is a named, reusable pipeline, defined inside a module with `task(name, { pipeline }, ...)`. Registration and invocation are separate. `run_task("name")` runs a task inline as a step in the calling pipeline, for reusable pipelines composed into workflows. `dispatch("name")` runs it as a durable background job and returns immediately; requires `#include `. `.cron` runs it in the background on a schedule, no caller. + +Dispatched tasks are durable: the dispatch module creates the persistent task tables and checkpoints context after each step, so a crash mid-task resumes at the step where it stopped on the next boot. + +Any pipeline or task can call `run()`, `run_worker()`, `run_task()`, and `dispatch()` (the last requires `dispatch.h`). + +**`.task_key` — task name *(by order)***: task identifier, invoked via `run_task("name")` or `dispatch("name")`. +```c +task("recount", { + sqlite_query({"db", "recount_todos"}) +}); +``` + +**Pipeline *(by order)***: the task's pipeline body, a brace block. +```c +task("name", { + sqlite_query({...}), + emit("done"), + dispatch("followup") +}); +``` + +**`.accepts`**: context keys to pull from the caller into the task. +```c +task("recount_todos", { + sqlite_query({"db", "recount"}) +}, .accepts = {"user_id"}); +``` + +**`.cron`**: standard cron schedule for recurring tasks (no caller required). +```c +task("daily_digest", { + sqlite_query({"db", "digest"}) +}, .cron = "0 8 * * *"); +``` + +**`.errors` / `.repairs`** *(per task)*: each task can declare its own handlers, resolved the same way as resource pipelines (the task's own handlers, then its module's). See [Error and Repair Pipelines](#error-and-repair-pipelines). +```c +task("send_invoice", { + http_fetch({http_get, "https://api.billing.dev/invoices/{{invoice_id}}", "inv"}) +}, .repairs = {{http_not_authorized, {run(.call = refresh_billing_token)}}}); +``` + +Combined: +```c +// on-demand: dispatched via dispatch("recount_todos") +task("recount_todos", { + sqlite_query({"todos_db", "recount"}) +}, .accepts = {"user_id"}); + +// recurring: runs on schedule, no caller +task("daily_digest", { + sqlite_query({"todos_db", "digest"}), + emit("digest_ready") +}, .cron = "0 8 * * *"); +``` + +### Pipeline Steps + +Steps are the units of work in a pipeline. Each one receives the current context, acts on it, and passes control to the next. All steps accept `.if_context_key`/`.unless_context_key` for [conditional execution](#conditionals), and `.map`/`.map_context_key` for concurrent fan-out across rows of a context table (see [Iteration](#iteration)). + +* [input](#input) +* [query](#query) +* [join](#join) +* [run](#run) +* [run_worker](#run_worker) +* [emit](#emit) +* [run_task](#run_task) +* [dispatch](#dispatch) +* [nest](#nest) + +These core steps come from `nerack.h` and behave identically under every protocol. The remaining steps ship with a module and are documented alongside it. Any step works anywhere a step is accepted, as long as its module is `#include`d. A step's module need not match the protocol handling the request; `datastar()` called from an `rns()` pipeline patches an `http()` resource's `.sse` channel the same as it does from an `http()` pipeline. + +#### input + +Checks request parameters (query string, form body, URL params) against regex patterns. On success, each value is promoted from `input:name` to app scope. On failure, errors land in `error:name` and a `400 Bad Request` triggers the nearest [error/repair pipeline](#error-and-repair-pipelines). All validations in one call complete before the error fires, so all errors are available together for form re-rendering. + +Built-in regex macros are defined in `nerack.h`, with `url_input`, `ipv4_input`, `no_html_input`, and `hex_color_input` added by `http.h`. Define your own the same way: `#define zipcode_input "^\\d{5}$"`. + +**`.context_key` *(by order)***: name of the parameter to validate. +```c +input({.context_key = "title", .regex = "^\\S+$", .error_message = "required"}) +``` + +**`.regex` *(by order)***: regex pattern, or a built-in validator macro. +```c +input({.context_key = "email", .regex = email_input, .error_message = "bad email"}) +``` + +**`.error_message` *(by order)***: human-readable error shown via `{{error_message:name}}`. +```c +input({.context_key = "age", .regex = integer_input, .error_message = "must be a number"}) +``` + +**`.optional`**: skip validation when the parameter is absent. +```c +input({.context_key = "filter", .regex = "^(active|done)$", .optional = true}) +``` + +**`.default_value`**: default value injected when the parameter is absent. +```c +input({.context_key = "page", .regex = integer_input, .default_value = "1"}) +``` + +Combined: +```c +input( + {.context_key = "email", .regex = email_input, .error_message = "must be a valid email"}, + {.context_key = "title", .regex = not_empty_input, .error_message = "cannot be empty"}, + {.context_key = "page", .regex = integer_input, .error_message = "must be a number", .default_value = "1"}, + {.context_key = "filter", .regex = "^(active|done)$", .error_message = "must be 'active' or 'done'", .optional = true}, + {.context_key = "username", .regex = user_input, .error_message = "must be alphanumeric"} +) +``` + +For checks beyond regex (uniqueness, cross-field rules, lookups), pair `input()` with a query and `run()`: +```c +input({.context_key = "username", .regex = user_input, .error_message = "must be alphanumeric"}), +sqlite_query({"users_db", "find_username", "existing"}), +run(^(){ + auto rows = get("existing"); + if (rows && table_length(rows) > 0) + error_set("username", (error){http_bad_request, "already taken"}); +}) +``` + +**Built-in validators:** +- Strings: `not_empty_input`, `alpha_input`, `alphanumeric_input`, `slug_input`, `no_html_input` *(http.h)* +- Numbers: `integer_input`, `positive_integer_input`, `float_input`, `percent_input` +- Identity: `email_input`, `uuid_input`, `user_input` +- Dates & times: `date_input`, `time_input`, `datetime_input` +- Web *(http.h)*: `url_input`, `ipv4_input`, `hex_color_input` +- Codes: `zip_input`, `phone_input`, `cron_input` +- Security: `token_input`, `base64_input` +- Boolean: `bool_input`, `yes_no_input`, `on_off_input` + +#### query + +The bundled SQLite engine provides `sqlite_query()`; an engine added as its own module provides `_query()` (`postgres_query()`, `redis_query()`, and so on) of the same shape. All share the same `database_query_config`. By order: first value is the database `.database_key`, second is the `.query` context key holding the SQL, third is the `.context_key` for the result table (even single-row results are tables). Multiple items in one step run **concurrently**. Queries use prepared statements; interpolated `{{values}}` are bound, not spliced. An interpolated value absent from the current scope binds as SQL `NULL`, not an empty string. For transactions, put `BEGIN`/`COMMIT`/`ROLLBACK` in the SQL. + +**`.database_key` *(by order)***: database name, matching the name a `(...)` was registered with. +```c +sqlite_query({.database_key = "todos_db", .query = "get_todos", .context_key = "todos_data"}) +``` + +**`.query` *(by order)***: context key holding the SQL to run. +```c +sqlite_query({.database_key = "todos_db", .query = "get_todos", .context_key = "todos_data"}) +``` + +**`.context_key` *(by order)***: context key for the result table. Optional; omit when the result isn't needed (e.g. an insert without `RETURNING`). +```c +sqlite_query({.database_key = "todos_db", .query = "create_todo"}) // no result captured +sqlite_query({.database_key = "todos_db", .query = "get_todos", .context_key = "todos_data"}) // result under "todos_data" +``` + +**`.error_on_empty`**: when true, raise `404 Not Found` if the query affects/returns zero rows. Default false. +```c +sqlite_query({.database_key = "todos_db", .query = "get_todo", .context_key = "todo", .error_on_empty = true}) +``` + +**`.if_context_key` / `.unless_context_key`** *(per item)*: conditionally include or skip individual queries while running the others concurrently. +```c +sqlite_query( + {.database_key = "db", .query = "get_todos", .context_key = "todos_data"}, + {.database_key = "db", .query = "get_urgent", .context_key = "urgent", .if_context_key = "show_urgent"} +) +``` + +Combined: +```c +sqlite_query( + {.database_key = "todos_db", .query = "get_todos", .context_key = "todos_data"}, + {.database_key = "todos_db", .query = "get_todo", .context_key = "todo", .error_on_empty = true}, + {.database_key = "todos_db", .query = "get_urgent", .context_key = "urgent", .if_context_key = "show_urgent"} +) +``` + +#### join + +Nests records from one context table into each matching record of another, like a SQL JOIN in memory. Useful when records come from separate databases or queries. After the step, each outer record gains a new field holding its matched inner records. + +**`.parent_context_key`**: outer table whose records receive nested children. +```c +.parent_context_key = "projects" +``` + +**`.parent_field_key`**: field on the outer table to match against. +```c +.parent_field_key = "id" +``` + +**`.child_context_key`**: inner table whose records get nested. +```c +.child_context_key = "todos" +``` + +**`.child_field_key`**: field on the inner table that points at the outer. +```c +.child_field_key = "project_id" +``` + +**`.parent_child_join_key`**: new field on outer records holding the matched inner records. (defaults to the child table name) +```c +.parent_child_join_key = "todos" +``` + +Combined: +```c +join(.parent_context_key = "projects", .parent_field_key = "id", .child_context_key = "todos", .child_field_key = "project_id") +``` + +**Full context example.** Concurrent query → `join()` → `html()`: fetch parent and children from separate queries, render as one nested structure. Blog + comments, single database: + +**`blog.mustache.html`** +```html +
    + {{#blog}} +

    {{title}}

    +
    {{content}}
    +

    Comments

    +
      + {{#comments}} +
    • {{body}}
    • + {{/comments}} +
    + {{/blog}} +
    +``` + +```c +http("blog", "/blogs/:id", + .get = { + input({"id", positive_integer_input}), + + // Fetch both concurrently: one query() call, two items + sqlite_query( + {"blog_db", "get_blog", "blog"}, + {"blog_db", "get_comments", "comments"} + ), + + // Nest each comment into its matching blog record + join(.parent_context_key = "blog", .parent_field_key = "id", .child_context_key = "comments", .child_field_key = "blog_id"), + + // Enter {{#blog}} first; after join(), comments lives INSIDE each blog record + html("blog", "blog_s"), + http_response("blog_s") + } +); +``` + +Context shape at each step: + +``` +after query(): { blog: [{id, title, content}], + comments: [{id, blog_id, body}, ...] } // two sibling tables + +after join(): { blog: [{id, title, content, + comments: [{id, blog_id, body}, ...]}] } // nested inside blog +``` + +#### run + +`run()` calls a C function or block inline on the reactor, with access to context through the [Imperative API](#imperative-api). It is where business logic and data shaping live: enriching query results, aggregating, transforming data between steps, and setting flags for [conditional](#conditionals) downstream steps. Use it for short, non-blocking work, and call `error_set()` to trigger an error/repair pipeline. Use `run_worker()` instead when the body would stall the reactor. + +**`.icall` — block *(by order)***: inline block, for short logic specific to this pipeline. Here, attaching each challenger's opponent id so the template can render two voting forms with the right winner/loser pairing: +```c +run(^(){ + auto const t = get("challengers"); + auto const p0 = table_get(t, 0); + auto const p1 = table_get(t, 1); + record_set(p0, "opponent_id", record_get(p1, "id")); + record_set(p1, "opponent_id", record_get(p0, "id")); +}) +``` + +**`.call`**: reference to a named C function, for logic reuse across pipelines. +```c +run(.call = assign_opponents) +``` + +Inside blocks and `.call` functions, context, memory, errors, tables, and records are manipulated through the [Imperative API](#imperative-api). + +#### run_worker + +`run_worker()` takes the same block or `.call` as `run()` but is for blocking or CPU-bound work: external C libraries, blocking I/O, heavy computation. The work is dispatched to the shared thread pool, releasing the reactor; the pipeline resumes on the original reactor when the call returns. Use it when the body would stall a request reactor. + +**`.icall` — block *(by order)***: inline block, run on the shared thread pool. Here, rendering Markdown through an external C library and freeing its buffer when the request completes: +```c +run_worker(^(){ + auto const raw = third_party_render_md(get("markdown")); + defer_free(raw); + set("html", raw); +}) +``` + +**`.call`**: reference to a named C function, run on the shared thread pool. +```c +run_worker(.call = resize_image) +``` + +#### emit + +Triggers an internal pub/sub event. Subscribers in other modules react in their `subscribe()` pipelines, with no direct dependency on the emitter. See [Event Pipelines](#event-pipelines). + +**Event name *(by order)***: name of the event to publish. +```c +emit("todo_created") +``` + +#### run_task + +Runs a named task inline as a step in the calling pipeline; control returns to the next step when it finishes. For reusable pipelines composed into workflows. The task must be defined with `task(name, { ... })`. See [Task Pipelines](#task-pipelines). + +**Task name *(by order)***: name of a defined task. +```c +run_task("recount_todos") +``` + +#### dispatch + +Enqueues a named task as a durable background job; the calling pipeline continues immediately. Task reactors pick up queued jobs and execute their pipelines. The task is checkpointed after each step, so a crash mid-task resumes where it stopped. Requires `#include `, which provides the persistent task tables. The task must be defined with `task(name, { ... })`. See [Task Pipelines](#task-pipelines). + +**Task name *(by order)***: name of a defined task. +```c +dispatch("record_daily_stats") +``` + +#### nest + +Groups multiple steps into a single composite step. Useful when applying one `.if_context_key`/`.unless_context_key` to several steps without repeating it. + +**`.steps` *(by order)***: array of steps that run as a unit. +```c +nest({sqlite_query({...}), emit("urgent_todo"), html("urgent", "urgent_s"), http_response("urgent_s")}) +``` + +**`.if_context_key` / `.unless_context_key`**: condition applied to the whole group. +```c +nest({sqlite_query({...}), emit("urgent_todo"), html("urgent", "urgent_s"), http_response("urgent_s")}, + .if_context_key = "is_urgent") +``` + +--- + +### Imperative API + +Functions called from `run()`/`run_worker()` blocks and `.call` functions to read and write context, alloc memory, raise errors, and manipulate tables and records. + +* [context](#context-1) +* [memory](#memory) +* [errors](#errors) +* [tables](#tables) +* [records](#records) + +#### context + +Read, write, and test context keys, and resolve `{{interpolation}}` against the current scope. + +**`get(name)`**: returns the value stored under `name`, or `nullptr` if absent. The returned pointer is whatever was stored: a `string` for scalars, a `table` for query and fetch results. +```c +auto todos = get("todos"); +``` + +**`set(name, value)`**: writes `value` to `name`, exposing it to downstream steps and templates. +```c +set("is_urgent", "1"); +``` + +**`has(name)`**: returns true when `name` exists in the current scope. +```c +if (has("user_id")) { ... } +``` + +**`format(context_key, template)`**: resolves `{{name}}` interpolations in `template` against the current context and writes the result into `context_key`. Same scopes and helpers as templates. +```c +format("greeting", "Hello, {{user_name}}"); +auto greeting = get("greeting"); +``` + +Combined: +```c +run(^(){ + auto rows = get("todos"); + if (table_length(rows) > 5) { + set("is_urgent", "1"); + format("banner", "{{user_name}} has more than 5 open todos"); + } +}) +``` + +#### memory + +Pipeline-arena allocation and deferred cleanup of foreign pointers. Both clear when the request completes. + +**`alloc(bytes)`**: returns a buffer from the pipeline arena. Reclaimed automatically on request completion. +```c +auto buf = alloc(256); +``` + +**`defer_free(ptr)`**: schedules `free()` for a pointer returned by an external library. Runs when the arena is released. +```c +auto out = third_party_alloc(256); +defer_free(out); +``` + +Combined: +```c +run_worker(^(){ + auto url = alloc(512); + build_signed_url(url, 512, get("path")); + set("signed_url", url); + + auto raw = third_party_render_md(get("markdown")); + defer_free(raw); + set("html", raw); +}) +``` + +#### errors + +Raise field-scoped errors from `run()` to trigger error/repair pipelines. Keys land in the `error:name` scope, visible to templates as `{{error:name}}`, `{{error_code:name}}`, and `{{error_message:name}}`. + +**`error_set(name, err)`**: associates an error with `name` and triggers the nearest [error or repair pipeline](#error-and-repair-pipelines). +```c +error_set("token", (error){ http_bad_request, "token has expired" }); +``` + +**`error_get(name)`**: returns the `error` previously set on `name`. +```c +auto e = error_get("token"); +``` + +**`error_has(name)`**: returns true when `name` has an error. +```c +if (error_has("token")) { ... } +``` + +Combined: +```c +run(^(){ + auto token = get("token"); + if (!token || strlen(token) < 16) { + error_set("token", (error){ + http_bad_request, + "token must be at least 16 characters" + }); + } +}) +``` + +#### tables + +Tables are ordered collections of records, the shape `query()` produces and `http_fetch()` parses JSON into. Use these to build derived results. + +**`table_new()`**: returns an empty table in the pipeline arena. +```c +auto t = table_new(); +``` + +**`table_length(t)`**: number of records in `t`. +```c +auto n = table_length(get("todos")); +``` + +**`table_get(t, i)`**: record at index `i`, or `nullptr` if out of range. +```c +auto first = table_get(get("todos"), 0); +``` + +**`table_add(t, r)`**: appends `r` to `t`. +```c +table_add(t, record_new()); +``` + +**`table_remove(t, r)`**: removes record `r` from `t`. +```c +table_remove(t, r); +``` + +**`table_remove_at(t, i)`**: removes the record at index `i`. +```c +table_remove_at(t, 0); +``` + +Combined: +```c +run(^(){ + auto source = get("raw_users"); + auto active = table_new(); + for (size_t i = 0; i < table_length(source); i++) { + auto u = table_get(source, i); + auto status = record_get(u, "status"); + if (status && strcmp(status, "active") == 0) { + table_add(active, u); + } + } + set("active_users", active); +}) +``` + +#### records + +Records are name-value bags, the shape of one row from `query()` or one object from `http_fetch()`. All values are strings; see [Everything is a String](./README.md#everything-is-a-string). + +**`record_new()`**: returns an empty record in the pipeline arena. +```c +auto r = record_new(); +``` + +**`record_get(r, name)`**: string value of `name`, or `nullptr` if absent. +```c +auto title = record_get(r, "title"); +``` + +**`record_set(r, name, value)`**: writes `value` to `name` on `r`. +```c +record_set(r, "title", "New title"); +``` + +**`record_remove(r, name)`**: removes `name` from `r`. +```c +record_remove(r, "draft"); +``` + +Combined: +```c +run(^(){ + auto todos = get("todos"); + for (size_t i = 0; i < table_length(todos); i++) { + auto t = table_get(todos, i); + auto title = record_get(t, "title"); + if (title && strlen(title) > 40) { + record_set(t, "is_long", "1"); + } + } +}) +``` + +### Conditionals + +Every step accepts `.if_context_key` and `.unless_context_key`, naming a context variable. They work for any context value: validated inputs, query results, framework flags like `is_htmx`, or flags set from `run()`. + +**`.if_context_key`**: context key. Step runs only when the value is present. +```c +html("fragment", "frag_s", .if_context_key = "is_htmx") +``` + +**`.unless_context_key`**: context key. Step runs only when the value is absent. +```c +html("full_page", "page_s", .unless_context_key = "is_htmx") +``` + +For multi-state branching, set context flags from `run()`, then key downstream steps off them: + +```c +run(.call = classify_todo), +html("urgent_confirmation", "urgent_s", .if_context_key = "is_urgent"), +http_response("urgent_s", .if_context_key = "is_urgent"), +html("standard_confirmation", "standard_s", .unless_context_key = "is_urgent"), +http_response("standard_s", .unless_context_key = "is_urgent") +``` + +### Iteration + +`.map` and `.map_context_key` run a step once per row of a context table, all rows **concurrently**, like multiple items in `query()` or `http_fetch()`. With a `.context_key`, results are collected into a table aligned with the input, one entry per row. They differ in how each row reaches the step body: `.map` puts the row's fields in scope as bare `{{interpolations}}`; `.map_context_key` binds the row as a single-row table under a named key. + +**`.map`**: name of a context table to iterate over. The row's fields land in scope as bare interpolations. +```c +// One request per row in `users`, all concurrent. +// Each row's `id` fills the URL; responses collected into `profiles`, aligned with `users`. +http_fetch({http_get, "https://api.users.dev/{{id}}", "profiles", .map = "users"}) +``` + +**`.map_context_key`**: context key under which the current row is exposed as a single-row table. Pairs with `.map`. +```c +// Render the `todo` template once per row of `todos`. +// `.map_context_key = "todo_d"` presents the current row as the single-row table `todo_d` +// Rendered fragments are collected into `todo_s`, aligned with `todos`. +html("todo", "todo_s", .map = "todos", .map_context_key = "todo_d") +``` + +### Modules and Composition + +A module is declared with `module(name)` in a `name.c` file, usually inside a matching `name/` folder that holds its assets. A module owns its own resources, databases, migrations, tasks, and event contracts. Nerack scans the project for `module(...)` declarations and loads every module it finds. + +A module is seeded with the assets in its folder and every asset up to the project root, at startup. See [Assets](#assets) and [Context](#context). + +**`module(name)`**: declares a module. +```c +// todos/todos.c +module(todos){ + // resources, databases, tasks, subscribers ... +} +``` + +**`error(...)` / `repair(...)`**: module-scoped error and repair handlers (see [Error and Repair Pipelines](#error-and-repair-pipelines)). They cover resources in the same module; a resource's own `.errors`/`.repairs` override them for the same code. + +**Pipeline composition.** A request runs the resource's `.all` steps first, then the verb pipeline. Cross-cutting setup such as session loading, tenant resolution, and access checks goes in `.all`, where it runs ahead of every verb on that resource. + +```c +// todos/todos.c: session loads, resources require login +#include +#include +#include +#include + +module(todos){ + http("todos", "/todos", + .all = {cookie_logged_in(), cookie_session()}, + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "create_todo"}), + http_redirect("todos") + } + ); + + http("todo", "/todos/:id", + .all = {cookie_logged_in(), cookie_session(), input({"id", positive_integer_input})}, + .delete = { + sqlite_query({"todos_db", "delete_todo", .error_on_empty = true}), + http_redirect("todos") + } + ); +} +``` + +For `DELETE /todos/5` the steps run in this order: the resource `.all` steps (`cookie_logged_in()`, `cookie_session()`, `input({"id", ...})`), then the verb pipeline (`sqlite_query({"todos_db", "delete_todo", .error_on_empty = true})`, `http_redirect("todos")`). + +**Complete module file.** A `blogs/blogs.c`: + +```c +#include +#include +#include + +module(blogs){ + sqlite( + "blog_db", + "file:blogs.db?mode=rwc", + {"create_blogs_table", "create_comments_table"} + ); + + http("blog", "/blogs/:id", + .get = {...} + ); +} +``` + +Place the folder in the project; Nerack loads it on the next scan. + +A typical project layout: +``` +├── app.c # app module (module(app){ ... }) +├── todos/ # todos module +│ ├── todos.c # module(todos){ ... } +│ ├── todos.mustache.html # → todos +│ ├── create_todos_table.sql # → todos +│ └── get_todos.sql # → todos +├── activity/ # activity module +│ └── activity.c # module(activity){ ... } +├── public/ # static files, served directly +│ └── favicon.png +├── layout.mustache.html # → every module +├── 404.mustache.html # → every module +└── 500.mustache.html # → every module +``` + +--- + +### Additional Modules + +These modules are bundled. Activate each one by `#include`ing its header. + +* [Protocols](#protocols) + * [http](#http) + * [rns](#rns) +* [htmx](#htmx) +* [datastar](#datastar) +* [tailwind](#tailwind) +* [daisyui](#daisyui) +* [cookie_auth](#cookie_auth) +* [database engines](#database-engines) + +#### Protocols + +A protocol module registers itself with Nerack and runs its own reactor type: a dedicated pool of cores handling that protocol's traffic, alongside the task reactors and shared thread pool. `http` is the reference implementation and the one most apps include; `rns` serves Reticulum destinations from the same pipeline model. A new protocol defines its own pipelines, request/response handling, and serialization format, then registers with `module(name)`. An app can run several protocols at once, sharing databases, tasks, and events between them. + +##### http + +Activate with `#include `. It provides the resource/pipeline model (`http()`), HTTP verbs, fetch, response, headers and cookies, redirect and reroute, SSE, and HTML/Markdown/JSON rendering. `html()` renders Mustache and `markdown()` renders MDM (Mustache with Markdown); see [Templates](#templates). + +###### HTTP Pipelines + +Nerack is resource-based, not route-based. Each `http(...)` defines a named resource and URL with HTTP verb pipelines. `{{url:verb:name}}`, `http_redirect()`, and `http_reroute()` all identify the target by resource name; `:params` are read from the current scope by matching key names. Path specificity is automatic: exact matches (`/todos/active`) take priority over parameterized matches (`/todos/:id`) regardless of definition order. + +Clients select a verb via the request method, or by passing `http_method` as a query/form parameter. This lets HTML forms (limited to GET/POST) reach any verb, and gives SSE a connection path: `/todos?http_method=events`. Templates never write that parameter by hand: `{{url:verb:name}}` emits it, along with a CSRF token for state-changing verbs (see [Templates](#templates)). + +**Resource name *(by order)***: identifier used by `{{url:verb:name}}`, `http_redirect()`, and `http_reroute()`. +```c +http("todos", "/todos", .get = { ... }); +``` + +**URL pattern *(by order)***: URL pattern. Supports `:params`. +```c +http("todo", "/todos/:id", .get = { ... }); +``` + +**`.all`**: shared steps that run before every verb pipeline on the resource. +```c +http("todo", "/todos/:id", + .all = { input({"id", positive_integer_input, "must be a number"}) }, + .get = { ... }, + .delete = { ... } +); +``` + +**`.mime`**: default response content type. Values: `mime_html`, `mime_text`, `mime_event_stream`, `mime_json`, `mime_javascript` (default `mime_html`). +```c +http("feed", "/feed.json", .mime = mime_json, .get = { ... }); +``` + +**`.get` `.post` `.put` `.patch` `.delete`**: verb pipelines: ordered arrays of steps that transform a request into a response. +```c +http("todos", "/todos", + .get = { + sqlite_query({"db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"db", "create_todo"}), + http_redirect("todos") + } +); +``` + +**`.sse`**: persistent SSE channel. The first value is the channel name (supports `{{interpolation}}`); the connect steps follow in their own brace group. Clients reach this pipeline with the `events` verb, which `{{url:events:name}}` emits as `?http_method=events`; `.all` runs before the connect steps, as it does for any verb. +```c +http("todos", "/todos", + .sse = {"todos:{{user_id}}", { + sqlite_query({"db", "get_todos", "todos_data"}), + http_sse(.event = "initial"), + http_sse(.data = {"{{id}} {{title}}"}, .map = "todos_data") + }} +); +``` +`http_sse()` writes the components you pass straight to the connection, so a record can be built across calls: the `event:` line here, then one `data:` line per row from the `.map`ped call. + +**`.errors` / `.repairs`**: resource-scoped error and repair pipelines. See [Error and Repair Pipelines](#error-and-repair-pipelines). +```c +http("todos", "/todos", + .post = { ... }, + .errors = {{http_bad_request, { + html("form", "form_s"), + http_response("form_s") + }}} +); +``` + +Combined: +```c +http("todo", "/todos/:id", + .all = {input({"id", positive_integer_input, "must be a number"})}, + .get = { + sqlite_query({"todos_db", "get_todo", "todo", .error_on_empty = true}), + html("todo", "todo_s"), + http_response("todo_s") + }, + .patch = { + input({"title", not_empty_input, "required"}), + sqlite_query({"todos_db", "update_todo"}), + http_redirect("todo") + }, + .delete = { + sqlite_query({"todos_db", "delete_todo"}), + http_redirect("todos") + }, + .sse = {"todo:{{id}}", {http_sse(.event = "ready")}}, + .errors = {{http_not_found, { + html("404", "not_found_s"), + http_response("not_found_s") + }}} +); +``` + +###### Templates + +Nerack uses Mustache and MDM (Mustache + Markdown) templates, rendered by the `html()` and `markdown()` steps respectively. The full Mustache base spec is supported except dot notation: `{{a.b}}` does not work; use `{{#a}}{{b}}{{/a}}`. + +Base-spec features: +- **Interpolation**: `{{name}}` (HTML-escaped), `{{{name}}}` or `{{&name}}` (unescaped). +- **Sections**: `{{#name}}...{{/name}}` renders when truthy and iterates over arrays. +- **Inverted sections**: `{{^name}}...{{/name}}` renders when falsy or empty. +- **Comments**: `{{! ignored }}`. +- **Set delimiters**: `{{=<% %>=}}`. +- **Partials**: `{{> name }}` inlines the asset `name`, rendered against the current scope. +- **Layout inheritance**: `{{< parent}}{{$block}}override{{/block}}{{/parent}}` renders `parent` with each `{{$block}}default{{/block}}` block replaced by the override. Any asset declaring blocks can be a parent. + +Built-in helpers use `{{helper:args}}` syntax. Arguments are colon-separated, in order; each can be a literal or a context key. + +**`{{precision:field:N}}`**: format a numeric value with N decimal places. +```html +

    Total: ${{precision:total:2}}

    +``` + +**`{{input:field}}`**: raw, unvalidated request parameter from the `input` scope. Used to repopulate form fields after a validation error. +```html + +``` + +**`{{error:field}}`**: truthy when `field` has an error. Used as a Mustache section to conditionally render markup. +```html +{{#error:title}} + invalid +{{/error:title}} +``` + +**`{{error_message:field}}`**: human-readable message for a field error, from `input()`'s message or from `error_set()`. +```html +{{error_message:title}} +``` + +**`{{error_code:field}}`**: HTTP status code associated with a field error (e.g. `400`, `404`). +```html +

    Code: {{error_code:title}}

    +``` + +**`{{url:verb:name}}`**: resolve a resource to its URL for a given verb. The verb comes first and is always required, then the resource name; verbs are `get`, `post`, `put`, `patch`, `delete`, `events`. `:params` in the URL pattern are read from the current scope by matching key names, so the same helper works per-row inside a section. Extra `:key=value` segments become query parameters; a bare `:key` is read from the current scope. + +For a non-GET verb the helper appends the query string the router needs: `http_method=`, plus a CSRF token when the verb is state-changing (`post`, `put`, `patch`, `delete`, but not `events`). The token is a random hash, also set on an httponly/secure/samesite cookie; state-changing requests are verified against it. Nothing else is required to reach a non-GET verb: no hidden inputs, no separate CSRF helper. + +```html +All + +{{#todos_data}} + {{title}} +{{/todos_data}} + + +{{#todo}} + Delete +{{/todo}} + + + +Done + + +
    + + +
    + + + +Open + +``` + +**`{{asset:filename}}`**: resolve a file in `public/` to a cache-busted URL (content checksum + immutable cache headers). See [Static Files](#static-files). +```html + +``` + +--- + +###### fetch + +Makes one or more HTTP requests and stores responses in context. JSON parses into tables and records (nested tables for nested JSON); plain-text responses are stored as strings. Like `query()`, multiple items in one step run **concurrently**. + +By order: first value is the `.method`, second the `.url`, third the `.context_key` for the response. `http_fetch({http_get, "https://api.dev/now", "weather"})` is the same as spelling all three fields out. + +**`.method` *(by order)***: HTTP method. Defaults to `http_get`. Values: `http_get`, `http_post`, `http_put`, `http_patch`, `http_delete`. +```c +http_fetch({.url = "https://api.dev/charge", .context_key = "r", .method = http_post}) +``` + +**`.url` *(by order)***: request URL; supports `{{interpolation}}`. +```c +http_fetch({.url = "https://api.weather.dev/forecast?city={{city}}", .context_key = "w"}) +``` + +**`.context_key` *(by order)***: context key for the response. +```c +http_fetch({.url = "https://api.weather.dev/now", .context_key = "weather"}) +``` + +**`.headers`**: array of name/value pairs. +```c +http_fetch({.url = "https://api.dev/me", .context_key = "r", .headers = {{"Authorization", "Bearer {{token}}"}}}) +``` + +**`.json_table_key`** / **`.json`**: JSON request body. `.json_table_key` names a context key whose value is serialized; `.json` is a literal JSON string (supports `{{interpolation}}`). +```c +http_fetch({.url = "https://api.dev/charge", .context_key = "receipt", .method = http_post, .json_table_key = "order"}) +``` + +**`.text`**: context key sent as the plain-text request body. +```c +http_fetch({.url = "https://api.dev/log", .context_key = "r", .method = http_post, .text = "raw_body"}) +``` + +**`.if_context_key` / `.unless_context_key`** *(per item)*: conditionally include or skip individual requests while running others concurrently. +```c +http_fetch( + {.url = "https://api.weather.dev/now", .context_key = "weather"}, + {.url = "https://api.quotes.dev/random", .context_key = "quote", .if_context_key = "show_quote"} +) +``` + +Combined, single request: +```c +http_fetch({.url = "https://api.payments.dev/charge", + .context_key = "receipt", + .method = http_post, + .json_table_key = "order", + .headers = { + {"Authorization", "Bearer {{api_key}}"}, + {"Idempotency-Key", "{{order_id}}"} + } +}) +``` + +Combined, concurrent fan-out: +```c +http_fetch( + {.url = "https://api.weather.dev/now?city={{city}}", .context_key = "weather"}, + {.url = "https://api.news.dev/headlines?topic={{topic}}", .context_key = "news"}, + {.url = "https://api.quotes.dev/random", .context_key = "quote"} +) +``` + +###### sse + +Pushes a Server-Sent Event. With `.channel`, the event broadcasts to all clients on that channel. Without it, the event returns to the requesting client. Each call writes the components it is given straight to the connection, so consecutive calls build one record: `.event` on one, `.data` on the next. See [HTTP Pipelines](#http-pipelines). + +**`.channel` *(by order)***: channel to broadcast on; supports `{{interpolation}}`. +```c +http_sse(.channel = "todos:{{user_id}}", .event = "new_todo", .data = {"{{todo}}"}) +``` + +**`.event`**: SSE `event:` line value. +```c +http_sse(.event = "ping") +``` + +**`.data`**: array of strings, one per SSE `data:` line (multi-line data). +```c +http_sse(.event = "msg", .data = {"line one", "line two"}) +``` + +**`.comment`**: SSE `:` comment line value, useful for keep-alives. +```c +http_sse(.comment = "keep-alive") +``` + +Combined: +```c +http_sse(.channel = "todos:{{user_id}}", + .event = "todo_updated", + .data = {"id: {{todo_id}}", "title: {{title}}"}, + .comment = "broadcast at {{timestamp}}" +) +``` + +###### render + +Renders content into the pipeline context. `html()` renders Mustache; `markdown()` renders Markdown-with-Mustache; `json()` serializes the context table or record named by its first key to JSON. All take a `render_config`. + +**`.template_key` *(by order)***: context key holding the template string to render; for `json()` it names the context table or record to serialize. +```c +html(.template_key = "todos", .context_key = "todos_s") +``` + +**`.context_key` *(by order)***: context key to write the rendered output to. +```c +html(.template_key = "todos", .context_key = "todos_s") +``` + +Markdown-with-Mustache: +```c +context("welcome", "# Welcome, {{user_name}}"); // then markdown("welcome", "welcome_s") +``` + +JSON: +```c +sqlite_query({"todos_db", "get_todos", "todos_data"}), +json("todos_data", "todos_j") +``` + +###### respond + +Sends a pipeline context value as the HTTP response. + +**`.context_key` *(by order)***: key of the rendered content to send. +```c +http_response(.context_key = "todos_s") +``` + +**`.status`**: HTTP response status (default `http_ok`). Values: `http_ok` (200), `http_created` (201), `http_redirected` (302), `http_bad_request` (400), `http_not_authorized` (401), `http_not_found` (404), `http_error` (500). +```c +http_response(.context_key = "not_found_s", .status = http_not_found) +``` + +**`.mime`**: override the response content type. Values: `mime_html`, `mime_text`, `mime_event_stream`, `mime_json`, `mime_javascript`. +```c +http_response(.context_key = "plain_s", .mime = mime_text) +``` + +Combined: +```c +html("not_found", "not_found_s"), +http_response(.context_key = "not_found_s", .status = http_not_found) +``` + +###### headers and cookies + +Set HTTP response headers and cookies declaratively; values support `{{interpolation}}`. + +**`.key` / `.value` *(by order)***: name and value of a header, or of a cookie and its attributes. + +`http_headers()` sets one response header per pair: +```c +http_headers({"X-Request-Id", "{{request_id}}"}, {"Cache-Control", "no-store"}) +``` + +`http_cookies()` takes the cookie as the first pair and its attributes as the rest: +```c +http_cookies({"session", "{{sid}}"}, {"HttpOnly"}, {"SameSite", "Lax"}, {"Max-Age", "3600"}) +``` + +###### redirect and reroute + +`http_redirect()` returns a 302 to the client, causing the browser to navigate. `http_reroute()` re-enters the router server-side and runs the target resource's GET pipeline within the same request. Both take only the target resource name. `:params` in the target's URL pattern are read from the current context by matching key names. + +**Resource name *(by order)***: target resource name. Required `:params` are read from context by name. +```c +http_redirect("todos") // 302 to /todos +http_redirect("todo") // 302 to /todos/{{id}}, id read from context +http_redirect("org_todo") // 302 to /orgs/{{org}}/todos/{{id}}, org and id read from context +http_reroute("todo") // run the todo GET pipeline in-process, id read from context +``` + +##### rns + +Activate with `#include `. It provides the resource/pipeline model for [Reticulum](https://reticulum.network/) destinations: `rns()` declares a resource the same way `http()` does, with the same verb pipelines and the same `.all`/`.errors`/`.repairs` fields. There is no `.mime` and no `.sse`; Reticulum has no MIME negotiation, and delivery is message-based. + +Pages are written in Micron, Reticulum's markup, rendered by `micron()`. + +**Resource name *(by order)***: identifier used by `rns_reroute()`. +```c +rns("todos", "/todos", .get = { ... }); +``` + +**URL pattern *(by order)***: destination path. Supports `:params`. +```c +rns("todo", "/todos/:id", .get = { ... }); +``` + +**`.all`**: shared steps that run before every verb pipeline on the resource. +```c +rns("todo", "/todos/:id", + .all = {rns_identity(), input({"id", positive_integer_input, "must be a number"})}, + .get = { ... } +); +``` + +**`.get` `.post` `.put` `.patch` `.delete`**: verb pipelines, identical in shape to their `http()` counterparts. + +**`.errors` / `.repairs`**: resource-scoped error and repair pipelines. See [Error and Repair Pipelines](#error-and-repair-pipelines). + +**`rns_identity()`**: resolves the requesting peer's Reticulum identity, puts `user_id` in context, and loads that user's record as `user`, all in one step. It is the RNS equivalent of `cookie_logged_in()` and `cookie_session()` together. Put it in `.all` on resources that need to know who is calling; templates can then use `{{#user}}…{{/user}}` and steps can key channels off `{{user_id}}`. + +**`micron(template_key, context_key)`**: renders a Micron template from context into context, the way `html()` renders Mustache. Micron assets are ordinary files (`todos.mustache.mu` seeds `todos`), so Mustache interpolation and sections work inside them. + +**`rns_response(context_key)`**: sends a context value back to the requesting peer. + +**`{{url:verb:name}}`**: resolves an `rns()` resource the same way it resolves an `http()` one. GET resolves to the bare path; a non-GET verb is appended as an `action=` Micron link field, `|`-separated from any others, where `http()` appends an `http_method=` query parameter. Extra `:key=value` segments become link fields, not query parameters. + +**`rns_reroute(name)`**: re-enters the router in-process and runs the target resource's GET pipeline, like `http_reroute()`. `:params` are read from context by matching key names. + +Combined: +```c +#include +#include +#include + +module(todos_rns){ + rns("todos", "/todos", + .all = {rns_identity()}, + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data", .error_on_empty = true}), + micron("todos", "todos_s"), + rns_response("todos_s") + }, + .post = { + input({"title", not_empty_input, "cannot be empty"}), + sqlite_query({"todos_db", "create_todo"}), + rns_reroute("todos") + }, + .errors = { + {404, {micron("no_todos", "no_todos_s"), rns_response("no_todos_s")}} + } + ); +} +``` + +The same module can serve both protocols: declare `http(...)` and `rns(...)` resources side by side, sharing queries, tasks, and event subscriptions, and render Mustache for one and Micron for the other. Resource names form one protocol-agnostic namespace. When a module serves the same path over both protocols, give the two resources distinct names, prefixed with the protocol (`http_home`, `rns_home`); otherwise `{{url:verb:name}}`, `http_reroute()`, and `rns_reroute()` cannot tell them apart. `examples/08_todo_sse_datastar_rns` follows this convention. + +#### htmx + +Activate with `#include `. It serves the htmx runtime as the `{{> htmx }}` partial and sets the `is_htmx` context flag on requests carrying the `HX-Request` header. Pair the flag with `.if_context_key`/`.unless_context_key` to return a fragment to htmx and a full page to a direct visit, or use `hx-boost` to upgrade ordinary links and forms into AJAX swaps. + +```c +#include +#include +#include + +module(todos){ + http("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos_fragment", "frag_s", .if_context_key = "is_htmx"), + http_response("frag_s", .if_context_key = "is_htmx"), + html("todos_page", "page_s", .unless_context_key = "is_htmx"), + http_response("page_s", .unless_context_key = "is_htmx") + } + ); +} +``` + +Include the runtime once in the page ``: +```html +{{> htmx }} +... +``` + +#### datastar + +Activate with `#include `. It serves the Datastar runtime as the `{{> datastar }}` partial and provides `datastar()` for pushing reactive fragment and signal patches over an SSE channel. A page opens an SSE connection (a resource `.sse` channel); pipelines push patches to that channel, and Datastar applies them in the DOM. + +`datastar()` patches a context value into the page by target (element id or CSS selector). The first value is the channel (supports `{{interpolation}}`). + +**`.channel` *(by order)***: channel to push to. +```c +html("todo_row", "todo_row_s"), +datastar(.channel = "todos:{{user_id}}", .target = "#todo-list", .mode = append_mode, .elements = "todo_row_s") +``` + +**`.target`**: element id or CSS selector for the element to patch; supports `{{interpolation}}`. +```c +.target = "#todo-{{id}}" +``` + +**`.mode`**: how the rendered fragment is applied to the target (a `datastar_mode`). Default `outer_mode`. +```c +.mode = replace_mode +``` + +**`.elements`**: context key holding the rendered HTML fragment to patch in. Not required for `remove_mode`. +```c +.elements = "todo_row_s" +``` + +**`.signals`**: context key holding signal state to merge into the client store. +```c +.signals = "ui_state" +``` + +**`.javascript`**: JavaScript to execute on the client. +```c +.javascript = "window.scrollTo(0, document.body.scrollHeight)" +``` + +**Patch modes (`datastar_mode`):** `outer_mode`, `inner_mode`, `replace_mode`, `prepend_mode`, `append_mode`, `before_mode`, `after_mode`, `remove_mode`. + +Worked example: a POST inserts a row, returns it with `RETURNING`, appends it to every connected client's list. + +```c +http("todos", "/todos", + // Each browser opens this channel and listens for patches. + .sse = {"todos:{{user_id}}"}, + + .post = { + input({"title", not_empty_input}), + // RETURNING gives the new row back; capture it under "todo". + sqlite_query({"todos_db", "insert_todo", "todo", .error_on_empty = true}), + // Render the new row, then patch it into the list for everyone on the channel. + html("todo_row", "todo_row_s"), + datastar(.channel = "todos:{{user_id}}", + .target = "#todo-list", + .mode = append_mode, + .elements = "todo_row_s" + ) + } +); +``` + +Removing an element needs only a selector: +```c +datastar(.channel = "todos:{{user_id}}", .target = "#todo-{{id}}", .mode = remove_mode) +``` + +Datastar sets the `is_datastar` context flag on requests it originates, usable with `.if_context_key`/`.unless_context_key`. + +Include the runtime once in the page ``: +```html +{{> datastar }} +``` + +#### tailwind + +Activate with `#include `. It compiles the Tailwind utility classes used across the project's templates and serves the stylesheet as the `{{> tailwind }}` partial. Use Tailwind classes directly in templates; there is no build step or config file. + +```html +{{> tailwind }} + +

    Vote for which is roundest

    + +``` + +#### daisyui + +Activate with `#include `. It compiles the DaisyUI classes used across the project's templates and serves the stylesheet as the `{{> daisyui }}` partial. Use DaisyUI classes directly in templates; there is no build step or config file. + +```html +{{> daisyui }} + + + +``` + +#### cookie_auth + +Activate with `#include `. It provides cookie-based authentication as pipeline steps. The module is self-contained (per [SCS](./README.md#philosophy)): including the header mounts the `/login`, `/logout`, and `/signup` resources and ships the login page, so `{{url:get:login}}` and `{{url:post:logout}}` resolve with no app code. `cookie_logged_in()` and `cookie_session()` are ordinary steps, independent of each other; place them in `.all` or a verb pipeline, alone or together, as the resource needs. + +**`cookie_logged_in()`**: checks the request for the `user_id` cookie. If it is missing, redirects to the login page, which authenticates the visitor, sets the `user_id` cookie, and redirects back. When present, it promotes `user_id` into context, so later steps can interpolate `{{user_id}}` in SQL and connection strings. It does not load the user record; add `cookie_session()` when the pipeline also needs `user`. +```c +http("todos", "/todos", .all = {cookie_logged_in(), cookie_session()}, .get = { ... }); +``` + +**`cookie_session()`**: reads the `user_id` cookie and loads that user's record into context as `user`. Use it wherever pipelines or templates read the current user. On a public page such as an about or landing page, use it alone with no gate: the header can then show the user when signed in, a sign-in link otherwise. +```c +http("about", "/about", .all = {cookie_session()}, .get = { ... }); +``` +```html +{{#user}}Signed in as {{short_name}} · log out{{/user}} +{{^user}}sign in{{/user}} +``` + +**`cookie_login()` / `cookie_logout()` / `cookie_signup()`**: the actions behind the module's built-in resources. Use them directly only to mount your own auth resources (a custom URL, template, or extra steps) in place of the defaults. +```c +http("login", "/login", + .get = { + html("login", "login_s"), + http_response("login_s") + }, + .post = {cookie_login()} +); +http("logout", "/logout", .post = {cookie_logout()}); +http("signup", "/signup", + .get = { + html("signup", "signup_s"), + http_response("signup_s") + }, + .post = {cookie_signup()} +); +``` + +Combined: gate the resources that need auth, then read user fields in that module's templates. +```c +// todos/todos.c +#include +#include +#include + +module(todos){ + http("todos", "/todos", + .all = {cookie_logged_in(), cookie_session()}, + .get = { + html("todos", "todos_s"), + http_response("todos_s") + } + ); +} +``` +```html + +{{#user}} + Hi, {{short_name}} +{{/user}} + + +Log out +``` + +#### database engines + +SQLite is the bundled engine: `#include `, then `sqlite(...)` to register and `sqlite_query({...})` as a pipeline step. + +```c +#include // sqlite("...", "file:app.db?mode=rwc", ...); sqlite_query({...}); +``` + +Any other engine is added as its own module the same way, registering `(...)` and providing `_query({...})`. They share `database_config` and `database_query_config` from [Databases](#databases) and [query](#query); only `.connection` is engine-specific. The shape an added engine takes: + +```c +#include // postgres("...", "postgres://...", ...); postgres_query({...}); +#include // mysql("...", "mysql://...", ...); mysql_query({...}); +#include // redis("...", "redis://...", ...); redis_query({...}); +#include // duckdb("...", "duckdb:analytics.db", ...); duckdb_query({...}); +``` + +### Static Files + +Files in `public/` are served directly. Reference them in templates with `{{asset:filename}}`, which resolves to a content-checksummed, cache-busted URL with immutable cache headers. Updates invalidate caches automatically; unchanged files cache forever. + +``` +public/ +├── favicon.png +├── styles.css +└── logo.svg +``` + +```html + + +Logo +``` + +This differs from assets like SQL and HTML templates, which are embedded from files anywhere in the project and seeded into context for steps to read by key (see [Assets](#assets) and [Context](#context)). `public/` holds opaque files served to the browser. + +### External Dependencies + +Drop third-party C libraries into `/vendor`; Nerack compiles and links them with the app. Call into them from `run()`/`run_worker()` steps. Memory returned by a library that must be freed manually is registered with `defer_free()` so it is reclaimed when the request completes (see [memory](#memory)). + +``` +vendor/ +└── cmark/ + ├── cmark.c + └── cmark.h +``` + +```c +#include +#include "vendor/cmark/cmark.h" + +// plain C, called as a step with run_worker(.call = render_markdown) +void render_markdown(){ + auto md = get("markdown"); + auto out = cmark_markdown_to_html(md, strlen(md), 0); + defer_free(out); // library-owned pointer + set("html_content", out); +} +``` + +Wire it into a pipeline as a `run_worker()` step, off the request reactor: +```c +run_worker(.call = render_markdown) +``` + +For dependencies that aren't plain source (system packages, build tooling), provide a custom `Dockerfile`. Nerack builds from it instead of the default image. diff --git a/examples/00_hello_text/hello.c b/examples/00_hello_text/hello.c new file mode 100644 index 0000000..00c2b14 --- /dev/null +++ b/examples/00_hello_text/hello.c @@ -0,0 +1,11 @@ +#include +#include + +module(hello){ + context("greeting", "hello world"); + http("home", "/", .mime = mime_text, + .get = { + http_response("greeting") + } + ); +} diff --git a/examples/01_hello_world_text/hello_world.c b/examples/01_hello_world_text/hello_world.c new file mode 100644 index 0000000..73389a8 --- /dev/null +++ b/examples/01_hello_world_text/hello_world.c @@ -0,0 +1,13 @@ +#include +#include + +module(hello_world){ + context("greeting", "hello {{name}}"); + http("home", "/", .mime = mime_text, + .get = { + input({"name", not_empty_input, .default_value = "world"}), + html("greeting", "hello"), + http_response("hello") + } + ); +} diff --git a/examples/02_hello_world_html/hello_world.c b/examples/02_hello_world_html/hello_world.c new file mode 100644 index 0000000..3c29f7d --- /dev/null +++ b/examples/02_hello_world_html/hello_world.c @@ -0,0 +1,20 @@ +#include +#include + +module(hello_world){ + context("greeting", + "" + "" + "" + "

    Hello {{name}}

    " + "" + "" + ); + http("home", "/", + .get = { + input({"name", not_empty_input, .default_value = "world"}), + html("greeting", "hello"), + http_response("hello") + } + ); +} diff --git a/examples/03_hello_world_html_db/create_hello_world_table.sql b/examples/03_hello_world_html_db/create_hello_world_table.sql new file mode 100644 index 0000000..2b3b5be --- /dev/null +++ b/examples/03_hello_world_html_db/create_hello_world_table.sql @@ -0,0 +1,4 @@ +CREATE TABLE IF NOT EXISTS greetings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL +); diff --git a/examples/03_hello_world_html_db/get_hello_world.sql b/examples/03_hello_world_html_db/get_hello_world.sql new file mode 100644 index 0000000..4295826 --- /dev/null +++ b/examples/03_hello_world_html_db/get_hello_world.sql @@ -0,0 +1,3 @@ +select name +from greetings +limit 1; diff --git a/examples/03_hello_world_html_db/hello_world.c b/examples/03_hello_world_html_db/hello_world.c new file mode 100644 index 0000000..14ac6b8 --- /dev/null +++ b/examples/03_hello_world_html_db/hello_world.c @@ -0,0 +1,20 @@ +#include +#include +#include + +module(hello_world){ + sqlite( + "hello_db", + "file:hello.db?mode=rwc", + {"create_hello_world_table"}, + {"seed_hello_world"} + ); + + http("home", "/", + .get = { + sqlite_query({"hello_db", "get_hello_world", "hello_world_data"}), + html("hello_world", "hello"), + http_response("hello") + } + ); +} diff --git a/examples/03_hello_world_html_db/hello_world.mustache.html b/examples/03_hello_world_html_db/hello_world.mustache.html new file mode 100644 index 0000000..07ba98c --- /dev/null +++ b/examples/03_hello_world_html_db/hello_world.mustache.html @@ -0,0 +1,7 @@ + + + {{#hello_world_data}} +

    Hello {{name}}

    + {{/hello_world_data}} + + diff --git a/examples/03_hello_world_html_db/seed_hello_world.sql b/examples/03_hello_world_html_db/seed_hello_world.sql new file mode 100644 index 0000000..d6886f2 --- /dev/null +++ b/examples/03_hello_world_html_db/seed_hello_world.sql @@ -0,0 +1,2 @@ +INSERT INTO greetings(name) +VALUES('World'); diff --git a/examples/04_todo/404.mustache.html b/examples/04_todo/404.mustache.html new file mode 100644 index 0000000..f9fef41 --- /dev/null +++ b/examples/04_todo/404.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    not found

    + {{/body}} +{{/layout}} diff --git a/examples/04_todo/500.mustache.html b/examples/04_todo/500.mustache.html new file mode 100644 index 0000000..75a79b4 --- /dev/null +++ b/examples/04_todo/500.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    error

    + {{/body}} +{{/layout}} diff --git a/examples/04_todo/about.mustache.html b/examples/04_todo/about.mustache.html new file mode 100644 index 0000000..3b8b864 --- /dev/null +++ b/examples/04_todo/about.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    about us

    + {{/body}} +{{/layout}} diff --git a/examples/04_todo/contact.mustache.html b/examples/04_todo/contact.mustache.html new file mode 100644 index 0000000..6ef1152 --- /dev/null +++ b/examples/04_todo/contact.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    contact us

    + {{/body}} +{{/layout}} diff --git a/examples/04_todo/create_todo.sql b/examples/04_todo/create_todo.sql new file mode 100644 index 0000000..1eb79de --- /dev/null +++ b/examples/04_todo/create_todo.sql @@ -0,0 +1,2 @@ +insert into todos(title) +values({{title}}); diff --git a/examples/04_todo/create_todos_table.sql b/examples/04_todo/create_todos_table.sql new file mode 100644 index 0000000..5f41f95 --- /dev/null +++ b/examples/04_todo/create_todos_table.sql @@ -0,0 +1,5 @@ +CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + finished INTEGER CHECK(finished IN (1)) +); diff --git a/examples/04_todo/delete_todo.sql b/examples/04_todo/delete_todo.sql new file mode 100644 index 0000000..96c573c --- /dev/null +++ b/examples/04_todo/delete_todo.sql @@ -0,0 +1,2 @@ +delete from todos +where id = {{id}}; diff --git a/examples/04_todo/get_todos.sql b/examples/04_todo/get_todos.sql new file mode 100644 index 0000000..e4c76d9 --- /dev/null +++ b/examples/04_todo/get_todos.sql @@ -0,0 +1,2 @@ +select id, title, finished +from todos; diff --git a/examples/04_todo/home.mustache.html b/examples/04_todo/home.mustache.html new file mode 100644 index 0000000..eb8e808 --- /dev/null +++ b/examples/04_todo/home.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    home

    + {{/body}} +{{/layout}} diff --git a/examples/04_todo/layout.mustache.html b/examples/04_todo/layout.mustache.html new file mode 100644 index 0000000..313d2b8 --- /dev/null +++ b/examples/04_todo/layout.mustache.html @@ -0,0 +1,23 @@ + + + + + +

    + {{^user}} + sign in + {{/user}} + {{#user}} + welcome, {{short_name}} + {{/user}} +

    + + {{$body}} + {{/body}} + + diff --git a/examples/04_todo/public/favicon.png b/examples/04_todo/public/favicon.png new file mode 100644 index 0000000..e69de29 diff --git a/examples/04_todo/todo.c b/examples/04_todo/todo.c new file mode 100644 index 0000000..ec467c0 --- /dev/null +++ b/examples/04_todo/todo.c @@ -0,0 +1,70 @@ +#include +#include +#include +#include + +module(todo){ + sqlite( + "todos_db", + "file:{{user_id}}_todo.db?mode=rwc", + {"create_todos_table"} + ); + + http("home", "/", + .get = { + cookie_session(), + html("home", "home_s"), + http_response("home_s") + } + ); + + http("about", "/about", + .get = { + cookie_session(), + html("about", "about_s"), + http_response("about_s") + } + ); + + http("contact", "/contact", + .get = { + cookie_session(), + html("contact", "contact_s"), + http_response("contact_s") + } + ); + + http("todos", "/todos", + .all = { + cookie_logged_in(), + cookie_session() + }, + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "create_todo"}), + http_redirect("todos") + } + ); + + http("todo", "/todos/:id", + .all = { + cookie_logged_in(), + cookie_session(), + input({"id", positive_integer_input}) + }, + .patch = { + input({"finished", "^1$", "must be 1", .optional = true}), + sqlite_query({"todos_db", "update_todo"}), + http_redirect("todos") + }, + .delete = { + sqlite_query({"todos_db", "delete_todo"}), + http_redirect("todos") + } + ); +} diff --git a/examples/04_todo/todos.mustache.html b/examples/04_todo/todos.mustache.html new file mode 100644 index 0000000..736fe4a --- /dev/null +++ b/examples/04_todo/todos.mustache.html @@ -0,0 +1,28 @@ +{{< layout}} + {{$body}} +
    + + +
    + {{^todos_data}} +

    no todos

    + {{/todos_data}} + {{#todos_data}} +
    +
    + {{^finished}} + + {{/finished}} + {{#finished}} + + {{/finished}} + {{title}} + +
    +
    + +
    +
    + {{/todos_data}} + {{/body}} +{{/layout}} diff --git a/examples/04_todo/update_todo.sql b/examples/04_todo/update_todo.sql new file mode 100644 index 0000000..24bbcf6 --- /dev/null +++ b/examples/04_todo/update_todo.sql @@ -0,0 +1,3 @@ +update todos +set finished = {{finished}} +where id = {{id}}; diff --git a/examples/05_todo_sse_datastar/404.mustache.html b/examples/05_todo_sse_datastar/404.mustache.html new file mode 100644 index 0000000..f9fef41 --- /dev/null +++ b/examples/05_todo_sse_datastar/404.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    not found

    + {{/body}} +{{/layout}} diff --git a/examples/05_todo_sse_datastar/500.mustache.html b/examples/05_todo_sse_datastar/500.mustache.html new file mode 100644 index 0000000..75a79b4 --- /dev/null +++ b/examples/05_todo_sse_datastar/500.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    error

    + {{/body}} +{{/layout}} diff --git a/examples/05_todo_sse_datastar/about.mustache.html b/examples/05_todo_sse_datastar/about.mustache.html new file mode 100644 index 0000000..3b8b864 --- /dev/null +++ b/examples/05_todo_sse_datastar/about.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    about us

    + {{/body}} +{{/layout}} diff --git a/examples/05_todo_sse_datastar/contact.mustache.html b/examples/05_todo_sse_datastar/contact.mustache.html new file mode 100644 index 0000000..6ef1152 --- /dev/null +++ b/examples/05_todo_sse_datastar/contact.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    contact us

    + {{/body}} +{{/layout}} diff --git a/examples/05_todo_sse_datastar/create_todo.sql b/examples/05_todo_sse_datastar/create_todo.sql new file mode 100644 index 0000000..5193f91 --- /dev/null +++ b/examples/05_todo_sse_datastar/create_todo.sql @@ -0,0 +1,3 @@ +insert into todos(user_id, title) +values({{user_id}}, {{title}}) +returning id, title, finished; diff --git a/examples/05_todo_sse_datastar/create_todos_table.sql b/examples/05_todo_sse_datastar/create_todos_table.sql new file mode 100644 index 0000000..d7c962f --- /dev/null +++ b/examples/05_todo_sse_datastar/create_todos_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + title TEXT NOT NULL, + finished INTEGER CHECK(finished IN (1)) +); +CREATE INDEX IF NOT EXISTS idx_todos_user_id ON todos(user_id); diff --git a/examples/05_todo_sse_datastar/delete_todo.sql b/examples/05_todo_sse_datastar/delete_todo.sql new file mode 100644 index 0000000..44fda1f --- /dev/null +++ b/examples/05_todo_sse_datastar/delete_todo.sql @@ -0,0 +1,4 @@ +delete from todos +where user_id = {{user_id}} + and id = {{id}} +returning id; diff --git a/examples/05_todo_sse_datastar/get_todos.sql b/examples/05_todo_sse_datastar/get_todos.sql new file mode 100644 index 0000000..ec59e5d --- /dev/null +++ b/examples/05_todo_sse_datastar/get_todos.sql @@ -0,0 +1,3 @@ +select id, title, finished +from todos +where user_id = {{user_id}}; diff --git a/examples/05_todo_sse_datastar/home.mustache.html b/examples/05_todo_sse_datastar/home.mustache.html new file mode 100644 index 0000000..eb8e808 --- /dev/null +++ b/examples/05_todo_sse_datastar/home.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    home

    + {{/body}} +{{/layout}} diff --git a/examples/05_todo_sse_datastar/layout.mustache.html b/examples/05_todo_sse_datastar/layout.mustache.html new file mode 100644 index 0000000..f31f5e3 --- /dev/null +++ b/examples/05_todo_sse_datastar/layout.mustache.html @@ -0,0 +1,25 @@ + + + + {{$head}} + {{/head}} + + +

    + {{^user}} + sign in + {{/user}} + {{#user}} + welcome, {{short_name}} + {{/user}} +

    + + {{$body}} + {{/body}} + + diff --git a/examples/05_todo_sse_datastar/public/favicon.png b/examples/05_todo_sse_datastar/public/favicon.png new file mode 100644 index 0000000..e69de29 diff --git a/examples/05_todo_sse_datastar/todo.c b/examples/05_todo_sse_datastar/todo.c new file mode 100644 index 0000000..af301b2 --- /dev/null +++ b/examples/05_todo_sse_datastar/todo.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#include + +module(todo){ + sqlite( + "todos_db", + "file:todo.db?mode=rwc", + {"create_todos_table"} + ); + + http("home", "/", + .get = { + cookie_session(), + html("home", "home_s"), + http_response("home_s") + } + ); + + http("about", "/about", + .get = { + cookie_session(), + html("about", "about_s"), + http_response("about_s") + } + ); + + http("contact", "/contact", + .get = { + cookie_session(), + html("contact", "contact_s"), + http_response("contact_s") + } + ); + + http("todos", "/todos", + .all = { + cookie_logged_in(), + cookie_session() + }, + .sse = {"todos:{{user_id}}"}, + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "create_todo", "todo_data", .error_on_empty = true}), + html("todo", "todo_s"), + datastar("todos:{{user_id}}", .target = "#todos", .mode = prepend_mode, .elements = "todo_s") + } + ); + + http("todo", "/todos/:id", + .all = { + cookie_logged_in(), + cookie_session(), + input({"id", positive_integer_input}) + }, + .patch = { + input({"finished", "^1$", "must be 1", .optional = true}), + sqlite_query({"todos_db", "update_todo", "todo_data", .error_on_empty = true}), + html("todo", "todo_s"), + datastar("todos:{{user_id}}", .target = "#todo_{{id}}", .mode = replace_mode, .elements = "todo_s") + }, + .delete = { + sqlite_query({"todos_db", "delete_todo", .error_on_empty = true}), + datastar("todos:{{user_id}}", .target = "#todo_{{id}}", .mode = remove_mode) + } + ); +} diff --git a/examples/05_todo_sse_datastar/todo.mustache.html b/examples/05_todo_sse_datastar/todo.mustache.html new file mode 100644 index 0000000..a0bc20c --- /dev/null +++ b/examples/05_todo_sse_datastar/todo.mustache.html @@ -0,0 +1,3 @@ +{{#todo_data}} + {{> todo_item}} +{{/todo_data}} diff --git a/examples/05_todo_sse_datastar/todo_item.mustache.html b/examples/05_todo_sse_datastar/todo_item.mustache.html new file mode 100644 index 0000000..52dd32d --- /dev/null +++ b/examples/05_todo_sse_datastar/todo_item.mustache.html @@ -0,0 +1,10 @@ +
    + {{^finished}} + + {{/finished}} + {{#finished}} + + {{/finished}} + {{title}} + +
    diff --git a/examples/05_todo_sse_datastar/todos.mustache.html b/examples/05_todo_sse_datastar/todos.mustache.html new file mode 100644 index 0000000..e2d5359 --- /dev/null +++ b/examples/05_todo_sse_datastar/todos.mustache.html @@ -0,0 +1,16 @@ +{{< layout}} + {{$head}} + {{> datastar }} + {{/head}} + {{$body}} + + +
    + {{#todos_data}} + {{> todo_item}} + {{/todos_data}} +
    + {{/body}} +{{/layout}} diff --git a/examples/05_todo_sse_datastar/update_todo.sql b/examples/05_todo_sse_datastar/update_todo.sql new file mode 100644 index 0000000..1c67e44 --- /dev/null +++ b/examples/05_todo_sse_datastar/update_todo.sql @@ -0,0 +1,5 @@ +update todos +set finished = {{finished}} +where user_id = {{user_id}} + and id = {{id}} +returning id, title, finished; diff --git a/examples/06_todo_events/404.mustache.html b/examples/06_todo_events/404.mustache.html new file mode 100644 index 0000000..f9fef41 --- /dev/null +++ b/examples/06_todo_events/404.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    not found

    + {{/body}} +{{/layout}} diff --git a/examples/06_todo_events/500.mustache.html b/examples/06_todo_events/500.mustache.html new file mode 100644 index 0000000..75a79b4 --- /dev/null +++ b/examples/06_todo_events/500.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    error

    + {{/body}} +{{/layout}} diff --git a/examples/06_todo_events/activity/activity.c b/examples/06_todo_events/activity/activity.c new file mode 100644 index 0000000..8d6dd23 --- /dev/null +++ b/examples/06_todo_events/activity/activity.c @@ -0,0 +1,27 @@ +#include +#include +#include +#include +#include + +module(activity){ + sqlite( + "activity_db", + "file:activity.db?mode=rwc", + {"create_activity_table"} + ); + + subscribe("todo_created", { + sqlite_query({"activity_db", "insert_activity"}) + }); + + http("activity", "/activity", + .get = { + cookie_logged_in(), + cookie_session(), + sqlite_query({"activity_db", "get_activities", "activities"}), + html("activity", "activity_s"), + http_response("activity_s") + } + ); +} diff --git a/examples/06_todo_events/activity/activity.mustache.html b/examples/06_todo_events/activity/activity.mustache.html new file mode 100644 index 0000000..72d4cbd --- /dev/null +++ b/examples/06_todo_events/activity/activity.mustache.html @@ -0,0 +1,10 @@ +{{< layout}} + {{$body}} + {{^activities}} +

    no activity

    + {{/activities}} + {{#activities}} +

    {{action}}: {{title}} ({{created_at}})

    + {{/activities}} + {{/body}} +{{/layout}} diff --git a/examples/06_todo_events/activity/create_activity_table.sql b/examples/06_todo_events/activity/create_activity_table.sql new file mode 100644 index 0000000..51d198a --- /dev/null +++ b/examples/06_todo_events/activity/create_activity_table.sql @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS activity ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + action TEXT NOT NULL, + title TEXT NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_activity_user_id ON activity(user_id); diff --git a/examples/06_todo_events/activity/get_activities.sql b/examples/06_todo_events/activity/get_activities.sql new file mode 100644 index 0000000..b4a272d --- /dev/null +++ b/examples/06_todo_events/activity/get_activities.sql @@ -0,0 +1,5 @@ +select action, title, created_at +from activity +where user_id = {{user_id}} +order by created_at desc +limit 50; diff --git a/examples/06_todo_events/activity/insert_activity.sql b/examples/06_todo_events/activity/insert_activity.sql new file mode 100644 index 0000000..70703c3 --- /dev/null +++ b/examples/06_todo_events/activity/insert_activity.sql @@ -0,0 +1,2 @@ +insert into activity(user_id, action, title) +values({{user_id}}, 'created', {{title}}); diff --git a/examples/06_todo_events/home/home.c b/examples/06_todo_events/home/home.c new file mode 100644 index 0000000..7cf9636 --- /dev/null +++ b/examples/06_todo_events/home/home.c @@ -0,0 +1,13 @@ +#include +#include +#include + +module(home){ + http("home", "/", + .get = { + cookie_session(), + html("home", "home_s"), + http_response("home_s") + } + ); +} diff --git a/examples/06_todo_events/home/home.mustache.html b/examples/06_todo_events/home/home.mustache.html new file mode 100644 index 0000000..eb8e808 --- /dev/null +++ b/examples/06_todo_events/home/home.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    home

    + {{/body}} +{{/layout}} diff --git a/examples/06_todo_events/layout.mustache.html b/examples/06_todo_events/layout.mustache.html new file mode 100644 index 0000000..86af7c0 --- /dev/null +++ b/examples/06_todo_events/layout.mustache.html @@ -0,0 +1,22 @@ + + + + + +

    + {{^user}} + sign in + {{/user}} + {{#user}} + welcome, {{short_name}} + {{/user}} +

    + + {{$body}} + {{/body}} + + diff --git a/examples/06_todo_events/public/favicon.png b/examples/06_todo_events/public/favicon.png new file mode 100644 index 0000000..e69de29 diff --git a/examples/06_todo_events/todos/create_todo.sql b/examples/06_todo_events/todos/create_todo.sql new file mode 100644 index 0000000..a0602fc --- /dev/null +++ b/examples/06_todo_events/todos/create_todo.sql @@ -0,0 +1,2 @@ +insert into todos(user_id, title) +values({{user_id}}, {{title}}); diff --git a/examples/06_todo_events/todos/create_todos_table.sql b/examples/06_todo_events/todos/create_todos_table.sql new file mode 100644 index 0000000..d7c962f --- /dev/null +++ b/examples/06_todo_events/todos/create_todos_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + title TEXT NOT NULL, + finished INTEGER CHECK(finished IN (1)) +); +CREATE INDEX IF NOT EXISTS idx_todos_user_id ON todos(user_id); diff --git a/examples/06_todo_events/todos/delete_todo.sql b/examples/06_todo_events/todos/delete_todo.sql new file mode 100644 index 0000000..4c7b296 --- /dev/null +++ b/examples/06_todo_events/todos/delete_todo.sql @@ -0,0 +1,3 @@ +delete from todos +where user_id = {{user_id}} + and id = {{id}}; diff --git a/examples/06_todo_events/todos/get_todos.sql b/examples/06_todo_events/todos/get_todos.sql new file mode 100644 index 0000000..ec59e5d --- /dev/null +++ b/examples/06_todo_events/todos/get_todos.sql @@ -0,0 +1,3 @@ +select id, title, finished +from todos +where user_id = {{user_id}}; diff --git a/examples/06_todo_events/todos/todos.c b/examples/06_todo_events/todos/todos.c new file mode 100644 index 0000000..200f3db --- /dev/null +++ b/examples/06_todo_events/todos/todos.c @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include + +module(todos){ + sqlite( + "todos_db", + "file:todo.db?mode=rwc", + {"create_todos_table"} + ); + + publish("todo_created", + .with = {"user_id", "title"} + ); + + http("todos", "/todos", + .all = { + cookie_logged_in(), + cookie_session() + }, + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "create_todo"}), + emit("todo_created"), + http_redirect("todos") + } + ); + + http("todo", "/todos/:id", + .all = { + cookie_logged_in(), + cookie_session(), + input({"id", positive_integer_input}) + }, + .patch = { + input({"finished", "^1$", "must be 1", .optional = true}), + sqlite_query({"todos_db", "update_todo"}), + http_redirect("todos") + }, + .delete = { + sqlite_query({"todos_db", "delete_todo"}), + http_redirect("todos") + } + ); +} diff --git a/examples/06_todo_events/todos/todos.mustache.html b/examples/06_todo_events/todos/todos.mustache.html new file mode 100644 index 0000000..736fe4a --- /dev/null +++ b/examples/06_todo_events/todos/todos.mustache.html @@ -0,0 +1,28 @@ +{{< layout}} + {{$body}} +
    + + +
    + {{^todos_data}} +

    no todos

    + {{/todos_data}} + {{#todos_data}} +
    +
    + {{^finished}} + + {{/finished}} + {{#finished}} + + {{/finished}} + {{title}} + +
    +
    + +
    +
    + {{/todos_data}} + {{/body}} +{{/layout}} diff --git a/examples/06_todo_events/todos/update_todo.sql b/examples/06_todo_events/todos/update_todo.sql new file mode 100644 index 0000000..e1d2850 --- /dev/null +++ b/examples/06_todo_events/todos/update_todo.sql @@ -0,0 +1,4 @@ +update todos +set finished = {{finished}} +where user_id = {{user_id}} + and id = {{id}}; diff --git a/examples/07_roundest_pokemon_htmx/README.md b/examples/07_roundest_pokemon_htmx/README.md new file mode 100644 index 0000000..e958b0f --- /dev/null +++ b/examples/07_roundest_pokemon_htmx/README.md @@ -0,0 +1 @@ +compare to https://github.com/t3dotgg/1app5stacks diff --git a/examples/07_roundest_pokemon_htmx/create_pokemons_table.sql b/examples/07_roundest_pokemon_htmx/create_pokemons_table.sql new file mode 100644 index 0000000..b54579f --- /dev/null +++ b/examples/07_roundest_pokemon_htmx/create_pokemons_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS pokemons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + sprite TEXT NOT NULL, + wins INTEGER NOT NULL DEFAULT 0, + losses INTEGER NOT NULL DEFAULT 0 +); diff --git a/examples/07_roundest_pokemon_htmx/get_challengers.sql b/examples/07_roundest_pokemon_htmx/get_challengers.sql new file mode 100644 index 0000000..57f2514 --- /dev/null +++ b/examples/07_roundest_pokemon_htmx/get_challengers.sql @@ -0,0 +1,4 @@ +select id, name, sprite +from pokemons +order by random() +limit 2; diff --git a/examples/07_roundest_pokemon_htmx/get_results.sql b/examples/07_roundest_pokemon_htmx/get_results.sql new file mode 100644 index 0000000..c832b80 --- /dev/null +++ b/examples/07_roundest_pokemon_htmx/get_results.sql @@ -0,0 +1,9 @@ +select id, name, sprite, wins, losses, + round(100.0 * wins / nullif(wins + losses, 0), 1) as win_pct, + row_number() over ( + order by 1.0 * wins / nullif(wins + losses, 0) desc nulls last, + wins + losses desc, + name + ) as rank +from pokemons +order by rank; diff --git a/examples/07_roundest_pokemon_htmx/home.mustache.html b/examples/07_roundest_pokemon_htmx/home.mustache.html new file mode 100644 index 0000000..0f8fac1 --- /dev/null +++ b/examples/07_roundest_pokemon_htmx/home.mustache.html @@ -0,0 +1,53 @@ + + + + Roundest (Nerack Version) + {{> htmx }} + {{> tailwind }} + + +
    + +
    + {{$body}} +
    +

    Vote for which is roundest

    +
    + {{#challengers}} +
    +
    + {{name}} +
    + #{{id}} +

    {{name}}

    + + + +
    +
    +
    + {{/challengers}} +
    +
    + {{/body}} +
    + +
    + + diff --git a/examples/07_roundest_pokemon_htmx/results.mustache.html b/examples/07_roundest_pokemon_htmx/results.mustache.html new file mode 100644 index 0000000..1e3cc32 --- /dev/null +++ b/examples/07_roundest_pokemon_htmx/results.mustache.html @@ -0,0 +1,28 @@ +{{< home}} + {{$body}} +
    +
    + {{#results_data}} +
    +
    + {{rank}} +
    + {{name}} +
    +
    #{{id}}
    +

    {{name}}

    +
    +
    +
    + {{#win_pct}}{{win_pct}}%{{/win_pct}}{{^win_pct}}n/a{{/win_pct}} +
    +
    + {{wins}}W - {{losses}}L +
    +
    +
    + {{/results_data}} +
    +
    + {{/body}} +{{/home}} diff --git a/examples/07_roundest_pokemon_htmx/roundest.c b/examples/07_roundest_pokemon_htmx/roundest.c new file mode 100644 index 0000000..614a105 --- /dev/null +++ b/examples/07_roundest_pokemon_htmx/roundest.c @@ -0,0 +1,45 @@ +#include +#include +#include +#include +#include + +module(roundest){ + sqlite( + "pokemon_db", + "file::memory:?cache=shared", + {"create_pokemons_table"}, + {"seed_pokemons"} + ); + + http("home", "/", + .get = { + sqlite_query({"pokemon_db", "get_challengers", "challengers"}), + run(^(){ + auto const t = get("challengers"); + auto const p0 = table_get(t, 0); + auto const p1 = table_get(t, 1); + record_set(p0, "opponent_id", record_get(p1, "id")); + record_set(p1, "opponent_id", record_get(p0, "id")); + }), + html("home", "home_s"), + http_response("home_s") + }, + .post = { + input( + {"winner", positive_integer_input}, + {"loser", positive_integer_input} + ), + sqlite_query({"pokemon_db", "vote"}), + http_redirect("home") + } + ); + + http("results", "/results", + .get = { + sqlite_query({"pokemon_db", "get_results", "results_data"}), + html("results", "results_s"), + http_response("results_s") + } + ); +} diff --git a/examples/07_roundest_pokemon_htmx/seed_pokemons.sql b/examples/07_roundest_pokemon_htmx/seed_pokemons.sql new file mode 100644 index 0000000..88960ee --- /dev/null +++ b/examples/07_roundest_pokemon_htmx/seed_pokemons.sql @@ -0,0 +1,17 @@ +INSERT INTO pokemons(name, sprite) VALUES + ('bulbasaur', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png'), + ('charmander', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/4.png'), + ('squirtle', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/7.png'), + ('caterpie', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/10.png'), + ('pidgey', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/16.png'), + ('pikachu', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/25.png'), + ('jigglypuff', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/39.png'), + ('meowth', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/52.png'), + ('psyduck', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/54.png'), + ('machop', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/66.png'), + ('magnemite', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/81.png'), + ('gastly', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/92.png'), + ('onix', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/95.png'), + ('voltorb', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/100.png'), + ('eevee', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/133.png'), + ('snorlax', 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/143.png'); diff --git a/examples/07_roundest_pokemon_htmx/vote.sql b/examples/07_roundest_pokemon_htmx/vote.sql new file mode 100644 index 0000000..0d4081b --- /dev/null +++ b/examples/07_roundest_pokemon_htmx/vote.sql @@ -0,0 +1,8 @@ +begin transaction; +update pokemons + set wins = wins + 1 + where id = {{winner}}; +update pokemons + set losses = losses + 1 + where id = {{loser}}; +commit; diff --git a/examples/08_todo_sse_datastar_rns/404.mustache.html b/examples/08_todo_sse_datastar_rns/404.mustache.html new file mode 100644 index 0000000..f9fef41 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/404.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    not found

    + {{/body}} +{{/layout}} diff --git a/examples/08_todo_sse_datastar_rns/500.mustache.html b/examples/08_todo_sse_datastar_rns/500.mustache.html new file mode 100644 index 0000000..75a79b4 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/500.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    error

    + {{/body}} +{{/layout}} diff --git a/examples/08_todo_sse_datastar_rns/about.mustache.html b/examples/08_todo_sse_datastar_rns/about.mustache.html new file mode 100644 index 0000000..3b8b864 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/about.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    about us

    + {{/body}} +{{/layout}} diff --git a/examples/08_todo_sse_datastar_rns/about.mustache.mu b/examples/08_todo_sse_datastar_rns/about.mustache.mu new file mode 100644 index 0000000..43473d6 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/about.mustache.mu @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} + about us + {{/body}} +{{/layout}} diff --git a/examples/08_todo_sse_datastar_rns/contact.mustache.html b/examples/08_todo_sse_datastar_rns/contact.mustache.html new file mode 100644 index 0000000..6ef1152 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/contact.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    contact us

    + {{/body}} +{{/layout}} diff --git a/examples/08_todo_sse_datastar_rns/contact.mustache.mu b/examples/08_todo_sse_datastar_rns/contact.mustache.mu new file mode 100644 index 0000000..5840410 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/contact.mustache.mu @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} + contact us + {{/body}} +{{/layout}} diff --git a/examples/08_todo_sse_datastar_rns/create_todo.sql b/examples/08_todo_sse_datastar_rns/create_todo.sql new file mode 100644 index 0000000..5193f91 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/create_todo.sql @@ -0,0 +1,3 @@ +insert into todos(user_id, title) +values({{user_id}}, {{title}}) +returning id, title, finished; diff --git a/examples/08_todo_sse_datastar_rns/create_todos_table.sql b/examples/08_todo_sse_datastar_rns/create_todos_table.sql new file mode 100644 index 0000000..d7c962f --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/create_todos_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + title TEXT NOT NULL, + finished INTEGER CHECK(finished IN (1)) +); +CREATE INDEX IF NOT EXISTS idx_todos_user_id ON todos(user_id); diff --git a/examples/08_todo_sse_datastar_rns/delete_todo.sql b/examples/08_todo_sse_datastar_rns/delete_todo.sql new file mode 100644 index 0000000..44fda1f --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/delete_todo.sql @@ -0,0 +1,4 @@ +delete from todos +where user_id = {{user_id}} + and id = {{id}} +returning id; diff --git a/examples/08_todo_sse_datastar_rns/get_todos.sql b/examples/08_todo_sse_datastar_rns/get_todos.sql new file mode 100644 index 0000000..ec59e5d --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/get_todos.sql @@ -0,0 +1,3 @@ +select id, title, finished +from todos +where user_id = {{user_id}}; diff --git a/examples/08_todo_sse_datastar_rns/home.mustache.html b/examples/08_todo_sse_datastar_rns/home.mustache.html new file mode 100644 index 0000000..eb8e808 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/home.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

    home

    + {{/body}} +{{/layout}} diff --git a/examples/08_todo_sse_datastar_rns/home.mustache.mu b/examples/08_todo_sse_datastar_rns/home.mustache.mu new file mode 100644 index 0000000..492d119 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/home.mustache.mu @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} + home + {{/body}} +{{/layout}} diff --git a/examples/08_todo_sse_datastar_rns/layout.mustache.html b/examples/08_todo_sse_datastar_rns/layout.mustache.html new file mode 100644 index 0000000..330bf0f --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/layout.mustache.html @@ -0,0 +1,25 @@ + + + + {{$head}} + {{/head}} + + +

    + {{^user}} + sign in + {{/user}} + {{#user}} + welcome, {{short_name}} + {{/user}} +

    + + {{$body}} + {{/body}} + + diff --git a/examples/08_todo_sse_datastar_rns/layout.mustache.mu b/examples/08_todo_sse_datastar_rns/layout.mustache.mu new file mode 100644 index 0000000..feb19ec --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/layout.mustache.mu @@ -0,0 +1,10 @@ +>Nerack Todos + +{{#user}}welcome, {{short_name}}{{/user}}{{^user}}not identified{{/user}} + +`[home`{{url:get:rns_home}}] `[about us`{{url:get:rns_about}}] `[contact us`{{url:get:rns_contact}}] `[todos`{{url:get:rns_todos}}] + +- + +{{$body}} +{{/body}} diff --git a/examples/08_todo_sse_datastar_rns/public/favicon.png b/examples/08_todo_sse_datastar_rns/public/favicon.png new file mode 100644 index 0000000..e69de29 diff --git a/examples/08_todo_sse_datastar_rns/todo.c b/examples/08_todo_sse_datastar_rns/todo.c new file mode 100644 index 0000000..aaafc08 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/todo.c @@ -0,0 +1,134 @@ +#include +#include +#include +#include +#include +#include + +module(todo){ + sqlite( + "todos_db", + "file:todo.db?mode=rwc", + {"create_todos_table"} + ); + + http("http_home", "/", + .get = { + cookie_session(), + html("home", "home_s"), + http_response("home_s") + } + ); + + http("http_about", "/about", + .get = { + cookie_session(), + html("about", "about_s"), + http_response("about_s") + } + ); + + http("http_contact", "/contact", + .get = { + cookie_session(), + html("contact", "contact_s"), + http_response("contact_s") + } + ); + + http("http_todos", "/todos", + .all = { + cookie_logged_in(), + cookie_session() + }, + .sse = {"todos:{{user_id}}"}, + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "create_todo", "todo_data", .error_on_empty = true}), + html("todo", "todo_s"), + datastar("todos:{{user_id}}", .target = "#todos", .mode = prepend_mode, .elements = "todo_s") + } + ); + + http("http_todo", "/todos/:id", + .all = { + cookie_logged_in(), + cookie_session(), + input({"id", positive_integer_input}) + }, + .patch = { + input({"finished", "^1$", "must be 1", .optional = true}), + sqlite_query({"todos_db", "update_todo", "todo_data", .error_on_empty = true}), + html("todo", "todo_s"), + datastar("todos:{{user_id}}", .target = "#todo_{{id}}", .mode = replace_mode, .elements = "todo_s") + }, + .delete = { + sqlite_query({"todos_db", "delete_todo", .error_on_empty = true}), + datastar("todos:{{user_id}}", .target = "#todo_{{id}}", .mode = remove_mode) + } + ); + + rns("rns_home", "/", + .get = { + rns_identity(), + micron("home", "home_s"), + rns_response("home_s") + } + ); + + rns("rns_about", "/about", + .get = { + rns_identity(), + micron("about", "about_s"), + rns_response("about_s") + } + ); + + rns("rns_contact", "/contact", + .get = { + rns_identity(), + micron("contact", "contact_s"), + rns_response("contact_s") + } + ); + + rns("rns_todos", "/todos", + .all = {rns_identity()}, + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + micron("todos", "todos_s"), + rns_response("todos_s") + }, + .post = { + input({"title", not_empty_input}), + sqlite_query({"todos_db", "create_todo", "todo_data", .error_on_empty = true}), + html("todo", "todo_s"), + datastar("todos:{{user_id}}", .target = "#todos", .mode = prepend_mode, .elements = "todo_s"), + rns_reroute("rns_todos") + } + ); + + rns("rns_todo", "/todos/:id", + .all = { + rns_identity(), + input({"id", positive_integer_input}) + }, + .patch = { + input({"finished", "^1$", "must be 1", .optional = true}), + sqlite_query({"todos_db", "update_todo", "todo_data", .error_on_empty = true}), + html("todo", "todo_s"), + datastar("todos:{{user_id}}", .target = "#todo_{{id}}", .mode = replace_mode, .elements = "todo_s"), + rns_reroute("rns_todos") + }, + .delete = { + sqlite_query({"todos_db", "delete_todo", .error_on_empty = true}), + datastar("todos:{{user_id}}", .target = "#todo_{{id}}", .mode = remove_mode), + rns_reroute("rns_todos") + } + ); +} diff --git a/examples/08_todo_sse_datastar_rns/todo.mustache.html b/examples/08_todo_sse_datastar_rns/todo.mustache.html new file mode 100644 index 0000000..a0bc20c --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/todo.mustache.html @@ -0,0 +1,3 @@ +{{#todo_data}} + {{> todo_item}} +{{/todo_data}} diff --git a/examples/08_todo_sse_datastar_rns/todo_item.mustache.html b/examples/08_todo_sse_datastar_rns/todo_item.mustache.html new file mode 100644 index 0000000..b4d4615 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/todo_item.mustache.html @@ -0,0 +1,10 @@ +
    + {{^finished}} + + {{/finished}} + {{#finished}} + + {{/finished}} + {{title}} + +
    diff --git a/examples/08_todo_sse_datastar_rns/todo_item.mustache.mu b/examples/08_todo_sse_datastar_rns/todo_item.mustache.mu new file mode 100644 index 0000000..04a7761 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/todo_item.mustache.mu @@ -0,0 +1 @@ +{{^finished}}`[mark done`{{url:patch:rns_todo:finished=1}}]{{/finished}}{{#finished}}`[mark undone`{{url:patch:rns_todo}}]{{/finished}} {{title}} `[delete`{{url:delete:rns_todo}}] diff --git a/examples/08_todo_sse_datastar_rns/todos.mustache.html b/examples/08_todo_sse_datastar_rns/todos.mustache.html new file mode 100644 index 0000000..fd8c5a5 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/todos.mustache.html @@ -0,0 +1,16 @@ +{{< layout}} + {{$head}} + {{> datastar }} + {{/head}} + {{$body}} + + +
    + {{#todos_data}} + {{> todo_item}} + {{/todos_data}} +
    + {{/body}} +{{/layout}} diff --git a/examples/08_todo_sse_datastar_rns/todos.mustache.mu b/examples/08_todo_sse_datastar_rns/todos.mustache.mu new file mode 100644 index 0000000..187bd2c --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/todos.mustache.mu @@ -0,0 +1,16 @@ +{{< layout}} + {{$body}} + >todos + + ` `[add`{{url:post:rns_todos}}`title] + + - + + {{^todos_data}} + no todos + {{/todos_data}} + {{#todos_data}} + {{> todo_item}} + {{/todos_data}} + {{/body}} +{{/layout}} diff --git a/examples/08_todo_sse_datastar_rns/update_todo.sql b/examples/08_todo_sse_datastar_rns/update_todo.sql new file mode 100644 index 0000000..1c67e44 --- /dev/null +++ b/examples/08_todo_sse_datastar_rns/update_todo.sql @@ -0,0 +1,5 @@ +update todos +set finished = {{finished}} +where user_id = {{user_id}} + and id = {{id}} +returning id, title, finished; diff --git a/images/nerack.png b/images/nerack.png new file mode 100644 index 0000000..05f1ec4 Binary files /dev/null and b/images/nerack.png differ diff --git a/images/nerack_c.png b/images/nerack_c.png new file mode 100644 index 0000000..10695cf Binary files /dev/null and b/images/nerack_c.png differ diff --git a/images/nerack_scene.png b/images/nerack_scene.png new file mode 100644 index 0000000..13a0b1f Binary files /dev/null and b/images/nerack_scene.png differ diff --git a/images/nerack_sprites.png b/images/nerack_sprites.png new file mode 100644 index 0000000..aa7cb45 Binary files /dev/null and b/images/nerack_sprites.png differ diff --git a/llms-full.txt b/llms-full.txt new file mode 100644 index 0000000..651dbfb --- /dev/null +++ b/llms-full.txt @@ -0,0 +1,176 @@ +# Nerack LLM API Reference + +Nerack is a declarative, protocol-agnostic web framework written in C23. An app is a set of pipelines: ordered arrays of steps that turn a request into a response. + +## Model + +- `module(name){...}` declares a module. It expands to a `[[gnu::constructor]]` that runs once at boot. Any `.c` file with a `module()` declaration is a module (`todos/todos.c` declares `module(todos)`); Nerack finds them by scanning disk. +- A module body holds `http()`/`rns()` resources, `()` databases, `task()`, `publish()`/`subscribe()`, `context()`, and `error()`/`repair()` handlers. There is no module-level middleware; cross-cutting steps go in a resource's `.all`. +- A request runs the resource's `.all` steps, then the pipeline for the matched verb. +- Context is a per-request, scoped key/value store. The scopes are `input:x` (raw parameters), `error:x` (errors), and unprefixed names (app scope). `input()` validates an `input:x` value and promotes it to app scope. +- A value is a string or a table (query and fetch results). `{{key}}` interpolates a value into SQL, templates, URLs, and headers. +- The core has no notion of HTTP. `#include ` adds `http()` and the `http_*` steps; `#include ` provides the same model over Reticulum. One app can run several protocols, sharing databases, tasks, and events. +- Config arrays hold at most `array_max` (16) entries. +- The dialect is C23: `auto`, `nullptr`, designated initializers, clang blocks (`^(){...}`). App code does not call `malloc` or `free`. + +Argument convention: leading values are positional, in struct-field order; the rest are named (`.field = x`). `sqlite_query({"db","get_todos","todos_data"})` is the same as `sqlite_query({.database_key="db", .query="get_todos", .context_key="todos_data"})`. + +## Assets + +Every non-`.c` file is an asset, keyed by its basename up to the first dot: `get_todos.sql` seeds `get_todos`, `todos.mustache.html` seeds `todos`. For templates the middle segment names the engine: `html()` reads `.mustache.html`, `micron()` reads `.mustache.mu`, `markdown()` reads `.mustache.md`, and one key can back several engines. A `{{> partial}}` or `{{< parent}}` reference resolves against the engine that rendered the enclosing template, so `todo.mustache.mu` with `{{> layout}}` pulls in `layout.mustache.mu`. `context("name","value")` seeds a key from a string instead of a file. A module sees every asset from its own folder up to the project root: root assets are shared, a module folder's assets are private to it, and the scan runs up the tree, never sideways. `public/` files are served directly and referenced with `{{asset:file}}`. + +## Templates + +Templates are rendered by `html()` (Mustache), `markdown()` (Markdown with Mustache), and `micron()` (Micron, from `rns.h`). Output is auto-escaped. `json()` serializes a context table or record to JSON; it is not a template step. +The full Mustache base spec is supported except dot notation: write `{{#a}}{{b}}{{/a}}`, never `{{a.b}}`. +`{{x}}` escaped · `{{{x}}}`/`{{&x}}` raw · `{{#x}}..{{/x}}` section/loop · `{{^x}}..{{/x}}` inverted · `{{! c }}` comment · `{{=<% %>=}}` delimiters · `{{> name}}` partial · `{{< parent}}{{$block}}override{{/block}}{{/parent}}` inheritance (any asset with a `{{$block}}default{{/block}}` block can be a parent; layouts are built this way). + +Helpers use `{{helper:args}}`, colon-separated: +- `{{url:verb:name}}` resolves a resource to its URL. The verb is always required, GET included (`{{url:get:todos}}`). `:params` in the pattern fill from the current scope by matching key names, which also works per row inside a section. Extra `:key=value` segments become query parameters; a bare `:key` fills from scope. For a non-GET verb the helper appends `?http_method=`, plus `&csrf=` for state-changing verbs, verified server-side. The verbs are `get`, `post`, `put`, `patch`, `delete`, `events`. There is no `{{csrf:...}}` helper; forms and links need no hidden fields. + `{{url:get:todo}}`→`/todos/5` · `{{url:delete:todo}}`→`/todos/5?http_method=delete&csrf=…` · `{{url:patch:todo:finished=1}}`→`/todos/5?http_method=patch&csrf=…&finished=1` · `{{url:events:todos}}`→`/todos?http_method=events` +- `{{input:field}}` is a raw, unvalidated parameter, used to repopulate forms. `{{error:field}}` is a section that is truthy on an error. `{{error_message:field}}` and `{{error_code:field}}` give the message and status code. `{{precision:field:N}}` formats a number to N decimals. `{{asset:file}}` is a cache-busted `public/` URL. + +## Resources + +`http("name", "/url/:param", ...fields)` declares a resource, not a route. The name is used by `{{url:verb:name}}`, `http_redirect()`, and `http_reroute()`. An exact path beats a parameterized one regardless of declaration order. The verb is chosen by the HTTP method, or by an `http_method` parameter. +Fields: `.all = {steps}`; the verb arrays `.get`, `.post`, `.put`, `.patch`, `.delete`; `.mime` (default `mime_html`); `.sse = {"channel:{{interp}}", {...steps}}`, where the first value is the channel and the connect steps follow in their own brace group, reached with the `events` verb; and `.errors`/`.repairs`. + +`rns("name", "/path", ...)`, from `rns.h`, declares a resource with the same fields as `http()` apart from `.mime` and `.sse`. It adds `rns_identity()` (resolves the peer identity, sets `user_id`, and loads `user`; use it in `.all`), `micron(tmpl_key, ctx_key)`, `rns_response(ctx_key)`, and `rns_reroute("name")`. `{{url:verb:name}}` resolves rns resources as well: GET gives the bare path, and a non-GET verb appends `action=` as a `|`-separated Micron link field where `http()` would append `?http_method=`. Resource names share one namespace across protocols, so a module serving one path over both `http()` and `rns()` must name the resources distinctly, such as `http_home` and `rns_home`. + +## Steps + +Every step accepts `.if_context_key`/`.unless_context_key` and `.map`/`.map_context_key`. A step works in any pipeline whose module is `#include`d, including a pipeline run by another protocol: `datastar()` called from an `rns()` pipeline patches an `http()` `.sse` channel. The core steps come from `nerack.h`; `http_*`, `html`, `markdown`, and `json` come from `http.h`. + +- `input({ctx_key, regex, error_message, .optional=, .default_value=}, {...})` validates query, form, and URL parameters. On success it promotes each value to app scope; on failure it writes `error:name` and raises a 400. Every item validates before the error fires, so all field errors surface together. For checks beyond regex, such as uniqueness or cross-field rules, pair it with a query and a `run()` that calls `error_set()`. +- `_query({db_key, query_ctx_key, result_ctx_key, .error_on_empty=})` runs SQL. `sqlite_query` is bundled; `postgres_query`, `mysql_query`, `redis_query`, and `duckdb_query` have the same shape once that engine is added as a module. Multiple items in one call run concurrently. A `{{x}}` in SQL is bound, never spliced, and an absent `{{x}}` binds SQL NULL. A result is always a table, even for one row; omit the result key when it is unused. `.error_on_empty=true` returns a 404 on zero rows. For a transaction, put `BEGIN`/`COMMIT` in the SQL. +- `join(.parent_context_key=, .parent_field_key=, .child_context_key=, .child_field_key=, .parent_child_join_key=)` nests records in memory: each parent record gains a field, named after the child table by default, holding its matched children. `{blog:[{id}], comments:[{blog_id}]}` becomes `{blog:[{id, comments:[…]}]}`. +- `run(^(){...})` or `run(.call=fn)` runs a short piece of non-blocking C between steps. +- `run_worker(...)` takes the same forms but runs on the shared thread pool, for blocking or CPU-bound work. +- `nest({step, step}, .if_context_key=)` applies one condition to several steps. +- `emit("event")` fires an event. `run_task("name")` runs a task inline; `dispatch("name")` runs it as a durable background job and needs dispatch.h. +- `http_fetch({method, url, ctx_key, .headers=, .json=, .json_table_key=, .text=})` makes an outbound HTTP request; JSON responses parse into tables and records, and multiple items run concurrently. `.method` defaults to `http_get`. `.json` is a literal body and interpolates; `.json_table_key` names a context key serialized as the body; `.text` names a context key sent as a plain body; `.headers` is an array of `{name, value}` pairs. +- `html(tmpl_key, out_key)` and `markdown(tmpl_key, out_key)` render a template into context. `json(data_key, out_key)` serializes the table or record at `data_key`. +- `http_response(ctx_key, .status=, .mime=)` sends the response. `.status` defaults to `http_ok`. +- `http_headers({"K","V"}, ...)` sets one response header per pair. `http_cookies({"name","val"}, {"HttpOnly"}, {"Max-Age","3600"}, ...)` takes the cookie as the first pair and its attributes as the rest. Values interpolate. +- `http_redirect("name")` returns a 302. `http_reroute("name")` re-enters the router in process and runs the target's GET pipeline, not the current verb. Both take only the resource name and read `:params` from context by matching key names. +- `http_sse(.channel=, .event=, .data={"line","line"}, .comment=)` broadcasts to every client on `.channel`, or returns to the requester when `.channel` is omitted. It writes the given components straight to the connection, so consecutive calls build one record. + +## Conditionals & iteration + +`.if_context_key="k"` runs the step only when the key is present; `.unless_context_key="k"` only when it is absent. Both work on any context value, including framework flags like `is_htmx` and flags set in `run()`. +`.map="table"` runs the step once per row, all rows concurrently. Row fields land in scope as bare `{{interpolations}}`, and with a result key the outputs collect into a table aligned to the input. `.map_context_key="k"` exposes the current row as a single-row table named `k`, which `html` requires. +```c +http_fetch({http_get, "https://api.dev/{{id}}", "profiles", .map = "users"}) +html("todo","todo_s", .map = "todos", .map_context_key = "todo_d") +``` + +## Imperative API (inside run/run_worker/.call) + +`get(k)`→value or nullptr · `set(k,v)` · `has(k)`→bool · `format(out_key, "…{{k}}…")` resolves interpolation and writes into `out_key`. +`alloc(n)`→arena buffer (auto-freed at request end) · `defer_free(ptr)` for library-owned pointers. +`error_set(k,(error){code,"msg"})` triggers the nearest error/repair pipeline · `error_get(k)` · `error_has(k)`. +`table_new() table_length(t) table_get(t,i) table_add(t,r) table_remove(t,r) table_remove_at(t,i)`. +`record_new() record_get(r,k) record_set(r,k,v) record_remove(r,k)`. All record values are strings; a missing key or out-of-range index returns nullptr. + +## Errors & repairs + +Handlers are looked up by code: the resource's `.errors`/`.repairs` first, then the module's `error()`/`repair()`, and the first match wins. An error is terminal: it responds and ends the request. A repair is resumable: it fixes the context and resumes at the step after the failure. Repairs resolve first, then fall through to errors, then to Nerack's own handler, which renders a context template named after the code if one exists, otherwise the message as text/plain with that status. Codes are plain integers: `#define err_quota 723`. +```c +.errors = {{http_not_found, {html("404","nf_s"), http_response("nf_s")}}}, +.repairs = {{http_not_authorized, {run(.call = refresh_token)}}} +error(http_error, {html("500","e_s"), http_response("e_s")}); // module-scoped, inside module() +``` + +## Events (pubsub.h) + +Events are durable: undelivered ones replay after a crash. `publish("event", .with={"k1","k2"})` declares the outbound contract, `subscribe("event", {steps}, .errors=, .repairs=)` registers a subscriber in any other module, and `emit("event")` fires it as a step, carrying the `.with` keys. Adding a subscriber does not change the publisher. + +## Tasks + +`task("name", {steps}, .accepts={"keys"}, .cron="0 8 * * *", .errors=, .repairs=)` declares a named, reusable pipeline in a module. `run_task("name")` invokes it inline. `dispatch("name")` runs it as a durable background job that returns immediately, checkpoints after each step, and resumes after a crash; it needs dispatch.h. `.cron` runs it on a schedule with no caller. `.accepts` lists caller context keys to pull in. + +## Bundled modules + +- `htmx.h` provides the `{{> htmx}}` partial and sets `is_htmx` on an `HX-Request`. Pair it with `.if_context_key` to serve a fragment or a full page. +- `datastar.h` provides the `{{> datastar}}` partial. `datastar(channel, .target=, .mode=, .elements=, .signals=, .javascript=)` pushes reactive patches over a resource's `.sse` channel. `.target` is an id or CSS selector and interpolates; `.elements` is a context key holding rendered HTML, omitted for `remove_mode`; `.signals` is a context key merged into the client store. The modes, default `outer_mode`, are `outer_mode`, `inner_mode`, `replace_mode`, `prepend_mode`, `append_mode`, `before_mode`, `after_mode`, and `remove_mode`. It sets `is_datastar` on requests it originates. +- `tailwind.h` and `daisyui.h` provide `{{> tailwind}}` and `{{> daisyui}}` for the ``. Classes used in templates are compiled automatically, with no build step or config. +- `cookie_auth.h`, once included, mounts the `/login`, `/logout`, and `/signup` resources and the login page, with no app code. `cookie_logged_in()` is the gate: it checks the `user_id` cookie, redirects through login and back if it is missing, and promotes `user_id` into context so `{{user_id}}` interpolates in SQL and connection strings; it does not load the user. `cookie_session()` reads the cookie and loads `user` into context. Both are plain steps, used in `.all` or a verb pipeline, alone or together. In templates, `{{#user}}{{short_name}}{{/user}}` reads the user and `{{url:post:logout}}` is the logout link. `cookie_login()`, `cookie_logout()`, and `cookie_signup()` are the actions, for mounting custom resources. +- Engines: `sqlite` is bundled. `postgres`, `mysql`, `redis`, `duckdb`, or any other engine is added as a module of the same shape: `(db_key, connection, {migrations}, {seeds})` plus `_query()`. Migrations and seeds are forward-only and index-based, run once each in array order and tracked in `nerack_meta`; append new ones to the end. An interpolation in the connection string makes the database multi-tenant. + +## Constants + +Verbs: `http_get http_post http_put http_patch http_delete http_events`. +Status: `http_ok`200 `http_created`201 `http_redirected`302 `http_bad_request`400 `http_not_authorized`401 `http_not_found`404 `http_error`500. +Mime: `mime_html mime_text mime_event_stream mime_json mime_javascript`. +Validators (from `nerack.h`, plus `no_html_input url_input ipv4_input hex_color_input` from http.h): `not_empty_input alpha_input alphanumeric_input slug_input integer_input positive_integer_input float_input percent_input email_input uuid_input user_input date_input time_input datetime_input zip_input phone_input cron_input token_input base64_input bool_input yes_no_input on_off_input`. Define a custom one the same way: `#define zipcode_input "^\\d{5}$"`. + +## Framework-handled (do not reimplement) + +Nerack handles these; do not reimplement them: per-request arena memory and bounds-checked structures, where a missing key returns nullptr; SQL injection through bound parameters, XSS through auto-escaping, and CSRF through a token from `{{url:verb:name}}` verified on every state-changing request; concurrency, threads, locks, and connection pooling; compilation, hot reload, and HMR. + +## Example + +```c +// todos/get_todos.sql select id, title from todos; +// todos/get_todo.sql select id, title from todos where id = {{id}}; +// todos/get_comments.sql select id, todo_id, body from comments where todo_id = {{id}}; +// todos/create_todo.sql insert into todos(title) values({{title}}); +// todos/todos.mustache.html +// {{< layout}}{{$body}} +//
    +// +// {{#error:title}}{{error_message:title}}{{/error:title}} +//
    +// +// {{/body}}{{/layout}} + +// todos/todos.c +#include +#include +#include +#include + +module(todos){ + sqlite("db", "file:todos.db?mode=rwc", {"create_todos_table"}, {"seed_todos"}); + publish("todo_created", .with = {"title"}); + + http("todos", "/todos", + .get = { + sqlite_query({"db", "get_todos", "todos_data"}), + html("todos", "todos_s"), + http_response("todos_s") + }, + .post = { + input({"title", not_empty_input, "cannot be empty"}), + sqlite_query({"db", "create_todo"}), + emit("todo_created"), + http_redirect("todos") // POST-redirect-GET + }, + .errors = {{http_bad_request, {http_reroute("todos")}}} // re-render GET; form repopulates from input:/error: + ); + + http("todo", "/todos/:id", + .all = {input({"id", positive_integer_input})}, + .get = { + sqlite_query( // both run concurrently + {"db", "get_todo", "todo_data", .error_on_empty = true}, + {"db", "get_comments", "comments"} + ), + join(.parent_context_key = "todo_data", .parent_field_key = "id", + .child_context_key = "comments", .child_field_key = "todo_id"), + run(^(){ + auto d = get("todo_data"); + if (!record_get(table_get(d, 0), "title")) set("untitled", "1"); + }), + html("todo", "todo_s"), + http_response("todo_s") + } + ); +} + +// activity/activity.c: subscriber, no dependency on todos +module(activity){ + sqlite("activity_db", "file:activity.db?mode=rwc", {"create_activity_table"}); + subscribe("todo_created", {sqlite_query({"activity_db", "insert_activity"})}); +} +```