From 9f582b99d2a9671b95ce212ea0d4a894dae6b8f7 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 02:47:42 +0100 Subject: [PATCH 01/14] chore: bun workspace scaffold Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 + CLAUDE.md | 123 +++++ LICENSE | 661 ++++++++++++++++++++++++++ README.md | 14 + apps/server/package.json | 7 + apps/web/package.json | 7 + bun.lock | 95 ++++ package.json | 16 + packages/contracts/package.json | 7 + packages/contracts/test/smoke.test.ts | 2 + packages/core/package.json | 7 + packages/course-format/package.json | 7 + packages/db/package.json | 7 + packages/feature-ai/package.json | 7 + packages/feature-import/package.json | 7 + packages/feature-learner/package.json | 7 + packages/feature-studio/package.json | 7 + packages/ui/package.json | 7 + tsconfig.json | 16 + 19 files changed, 1006 insertions(+) create mode 100644 CLAUDE.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 apps/server/package.json create mode 100644 apps/web/package.json create mode 100644 bun.lock create mode 100644 package.json create mode 100644 packages/contracts/package.json create mode 100644 packages/contracts/test/smoke.test.ts create mode 100644 packages/core/package.json create mode 100644 packages/course-format/package.json create mode 100644 packages/db/package.json create mode 100644 packages/feature-ai/package.json create mode 100644 packages/feature-import/package.json create mode 100644 packages/feature-learner/package.json create mode 100644 packages/feature-studio/package.json create mode 100644 packages/ui/package.json create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore index 95299e2..bc52024 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ node_modules/ *.log .env .worktrees/ +data/ +.cache/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..075473f --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,123 @@ + +Default to using Bun instead of Node.js. + +- Use `bun ` instead of `node ` or `ts-node ` +- Use `bun test` instead of `jest` or `vitest` +- Use `bun build ` instead of `webpack` or `esbuild` +- Use `bun install` instead of `npm install` or `yarn install` or `pnpm install` +- Use `bun run + + +``` + +With the following `frontend.tsx`: + +```tsx#frontend.tsx +import React from "react"; +import { createRoot } from "react-dom/client"; + +// import .css files directly and it works +import './index.css'; + +const root = createRoot(document.body); + +export default function Frontend() { + return

Hello, world!

; +} + +root.render(); +``` + +Then, run index.ts + +```sh +bun --hot ./index.ts +``` + +For more information, read the Bun API docs in `node_modules/bun-types/docs/**.mdx`. + +## Project rules + +Full design: `docs/superpowers/specs/2026-10-30-stcourses-design.md`. Plan: `docs/superpowers/plans/2026-10-30-stcourses.md`. + +- Bun only: `Bun.serve` routes and WebSockets, `bun:sqlite` or `Bun.sql`, `Bun.file`, `Bun.$`, `bun test`, `bun install`, `bunx`. Never express, vite, dotenv, pg, postgres.js, better-sqlite3, jest or vitest. +- Frontend: a React SPA served via HTML imports. No Next.js. Plain CSS with custom properties; no Tailwind. +- Course content is never stored in the database. Deleting the DB loses user data only. +- Database URL is `STC_DATABASE_URL`: `sqlite://` (default `sqlite://./data/stcourses.db`) or `postgres://...`. Every migration and query must run on both. +- Idle memory: at most 2 GB for the deployment. +- License: AGPL-3.0-only. Every package's `package.json` has `"license": "AGPL-3.0-only"`. +- Never write into `/home/user/functional-programming-course` or `/home/user/systemic-design-course`; their manifests are overlays in `overlays/`. +- Never commit anything from `/home/user/example_course_content` (licensed material, local test runs only). +- Design tokens (spec 4.1): ground `#12141a`, side `#181b22`, raised `#232733`, line `#262a33`, line2 `#343947`; text `#d9dce3`, reading text `#d9d4c8`, heading `#f2efe8`, muted `#a4abb8`, faint `#8c93a0`; accent `#f1b44c`, accent-dim `#8c7440`. Fonts: IBM Plex Sans (UI), Literata (lesson titles and reading text, 19px / 1.75 in a 660px column), IBM Plex Mono (code). Dark theme only in v1. +- Keyboard: arrow keys in the slide viewer, Escape closes overlays, normal Tab focus. No other shortcuts. +- Commits: use the machine's git identity; every message ends with `Co-Authored-By: Claude Opus 5.5 `. +- Paths with spaces and non-ASCII characters must load, serve and download correctly. A broken overlay or manifest yields diagnostics, never a crash. Media serving supports Range (206/416) and returns 404 for paths escaping the course root. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..8a91f53 --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +# STCourses + +STCourses is a self-hosted course platform. Homelabbers, universities and companies host their own courses, plus material they already own such as Packt video packages or Pluralsight slide PDFs, in one place that tracks progress. Authors write in Markdown in a git repo or in a browser studio; both edit the same files. Each install has one owner and is not multi-tenant. + +## Development + +``` +bun install # install workspace dependencies +bun test # run all tests +bun run typecheck # tsc --noEmit +bun run dev # start the server with hot reload +``` + +License: AGPL-3.0-only. diff --git a/apps/server/package.json b/apps/server/package.json new file mode 100644 index 0000000..7c86da9 --- /dev/null +++ b/apps/server/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/server", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..797fba0 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/web", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/bun.lock b/bun.lock new file mode 100644 index 0000000..d461254 --- /dev/null +++ b/bun.lock @@ -0,0 +1,95 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "stcourses", + "devDependencies": { + "@types/react": "^19", + "bun-types": "^1.3.14", + "typescript": "^5", + }, + }, + "apps/server": { + "name": "@stc/server", + "version": "0.0.0", + }, + "apps/web": { + "name": "@stc/web", + "version": "0.0.0", + }, + "packages/contracts": { + "name": "@stc/contracts", + "version": "0.0.0", + }, + "packages/core": { + "name": "@stc/core", + "version": "0.0.0", + }, + "packages/course-format": { + "name": "@stc/course-format", + "version": "0.0.0", + }, + "packages/db": { + "name": "@stc/db", + "version": "0.0.0", + }, + "packages/feature-ai": { + "name": "@stc/feature-ai", + "version": "0.0.0", + }, + "packages/feature-import": { + "name": "@stc/feature-import", + "version": "0.0.0", + }, + "packages/feature-learner": { + "name": "@stc/feature-learner", + "version": "0.0.0", + }, + "packages/feature-studio": { + "name": "@stc/feature-studio", + "version": "0.0.0", + }, + "packages/ui": { + "name": "@stc/ui", + "version": "0.0.0", + }, + }, + "packages": { + "@stc/contracts": ["@stc/contracts@workspace:packages/contracts"], + + "@stc/core": ["@stc/core@workspace:packages/core"], + + "@stc/course-format": ["@stc/course-format@workspace:packages/course-format"], + + "@stc/db": ["@stc/db@workspace:packages/db"], + + "@stc/feature-ai": ["@stc/feature-ai@workspace:packages/feature-ai"], + + "@stc/feature-import": ["@stc/feature-import@workspace:packages/feature-import"], + + "@stc/feature-learner": ["@stc/feature-learner@workspace:packages/feature-learner"], + + "@stc/feature-studio": ["@stc/feature-studio@workspace:packages/feature-studio"], + + "@stc/server": ["@stc/server@workspace:apps/server"], + + "@stc/ui": ["@stc/ui@workspace:packages/ui"], + + "@stc/web": ["@stc/web@workspace:apps/web"], + + "@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], + + "@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="], + + "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], + + "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "undici-types": ["undici-types@8.12.3", "", {}, "sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA=="], + + "@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..341e6f2 --- /dev/null +++ b/package.json @@ -0,0 +1,16 @@ +{ + "name": "stcourses", + "private": true, + "license": "AGPL-3.0-only", + "workspaces": ["packages/*", "apps/*"], + "scripts": { + "test": "bun test", + "typecheck": "bunx tsc --noEmit -p .", + "dev": "bun --hot apps/server/src/main.ts" + }, + "devDependencies": { + "@types/react": "^19", + "bun-types": "^1.3.14", + "typescript": "^5" + } +} diff --git a/packages/contracts/package.json b/packages/contracts/package.json new file mode 100644 index 0000000..0f09342 --- /dev/null +++ b/packages/contracts/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/contracts", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/packages/contracts/test/smoke.test.ts b/packages/contracts/test/smoke.test.ts new file mode 100644 index 0000000..8def1af --- /dev/null +++ b/packages/contracts/test/smoke.test.ts @@ -0,0 +1,2 @@ +import { expect, test } from "bun:test"; +test("smoke", () => { expect(1).toBe(1); }); diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 0000000..dcd395b --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/core", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/packages/course-format/package.json b/packages/course-format/package.json new file mode 100644 index 0000000..bbe81b8 --- /dev/null +++ b/packages/course-format/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/course-format", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/packages/db/package.json b/packages/db/package.json new file mode 100644 index 0000000..60f3f7b --- /dev/null +++ b/packages/db/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/db", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/packages/feature-ai/package.json b/packages/feature-ai/package.json new file mode 100644 index 0000000..689f090 --- /dev/null +++ b/packages/feature-ai/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/feature-ai", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/packages/feature-import/package.json b/packages/feature-import/package.json new file mode 100644 index 0000000..cab5a10 --- /dev/null +++ b/packages/feature-import/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/feature-import", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/packages/feature-learner/package.json b/packages/feature-learner/package.json new file mode 100644 index 0000000..ae4cba9 --- /dev/null +++ b/packages/feature-learner/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/feature-learner", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/packages/feature-studio/package.json b/packages/feature-studio/package.json new file mode 100644 index 0000000..0e7914e --- /dev/null +++ b/packages/feature-studio/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/feature-studio", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/packages/ui/package.json b/packages/ui/package.json new file mode 100644 index 0000000..ddb275b --- /dev/null +++ b/packages/ui/package.json @@ -0,0 +1,7 @@ +{ + "name": "@stc/ui", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-only" +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..c65f708 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "jsx": "react-jsx", + "types": ["bun-types"], + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "baseUrl": ".", + "paths": { "@stc/*": ["packages/*/src"] } + }, + "include": ["packages/*/src", "packages/*/test", "apps/*/src"] +} From 3b15d87a5f0055584089b94791dc17598080f47d Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 02:48:10 +0100 Subject: [PATCH 02/14] feat(contracts): shared server, exercise, ai, import and web interfaces Co-Authored-By: Claude Opus 5.5 --- packages/contracts/src/ai.ts | 3 ++ packages/contracts/src/exercise.ts | 7 ++++ packages/contracts/src/import.ts | 2 + packages/contracts/src/index.ts | 5 +++ packages/contracts/src/server.ts | 28 ++++++++++++++ packages/contracts/src/web.ts | 4 ++ packages/contracts/test/types.test.ts | 54 +++++++++++++++++++++++++++ 7 files changed, 103 insertions(+) create mode 100644 packages/contracts/src/ai.ts create mode 100644 packages/contracts/src/exercise.ts create mode 100644 packages/contracts/src/import.ts create mode 100644 packages/contracts/src/index.ts create mode 100644 packages/contracts/src/server.ts create mode 100644 packages/contracts/src/web.ts create mode 100644 packages/contracts/test/types.test.ts diff --git a/packages/contracts/src/ai.ts b/packages/contracts/src/ai.ts new file mode 100644 index 0000000..e0815c1 --- /dev/null +++ b/packages/contracts/src/ai.ts @@ -0,0 +1,3 @@ +export interface ChatMessage { role: "system" | "user" | "assistant" | "tool"; content: string; toolCallId?: string; name?: string } +export interface ToolSpec { name: string; description: string; inputSchema: Record } +export interface AiProvider { id: string; chat(messages: ChatMessage[], opts: { tools?: ToolSpec[]; signal?: AbortSignal }): AsyncIterable<{ text?: string; toolCall?: { id: string; name: string; input: unknown } }> } diff --git a/packages/contracts/src/exercise.ts b/packages/contracts/src/exercise.ts new file mode 100644 index 0000000..54723c5 --- /dev/null +++ b/packages/contracts/src/exercise.ts @@ -0,0 +1,7 @@ +// Browser-runnable exercises (spec 4.3 type 6) +export type ExerciseLanguage = "js" | "ts"; +export interface Assert { equal(actual: unknown, expected: unknown, message?: string): void; deepEqual(actual: unknown, expected: unknown, message?: string): void; ok(value: unknown, message?: string): void } +export interface ExerciseTest { name: string; run(mod: Record, assert: Assert): void | Promise } +// A tests file is an ES module: `export const tests: ExerciseTest[]`. Learner code is an ES module. +export interface TestResult { name: string; passed: boolean; message?: string; expected?: string; actual?: string } +export interface ExerciseRunner { language: ExerciseLanguage; run(learnerCode: string, testsModule: string, timeoutMs: number): Promise } diff --git a/packages/contracts/src/import.ts b/packages/contracts/src/import.ts new file mode 100644 index 0000000..dc75989 --- /dev/null +++ b/packages/contracts/src/import.ts @@ -0,0 +1,2 @@ +export interface ImportSource { kind: "packt-video" | "pdf-deck" | "code-repo" | "video-folder"; path: string; options?: Record } +export interface ImportResult { courseId: string; manifestPath: string; warnings: string[] } diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts new file mode 100644 index 0000000..859b47a --- /dev/null +++ b/packages/contracts/src/index.ts @@ -0,0 +1,5 @@ +export * from "./server"; +export * from "./exercise"; +export * from "./ai"; +export * from "./import"; +export * from "./web"; diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts new file mode 100644 index 0000000..dbfca4a --- /dev/null +++ b/packages/contracts/src/server.ts @@ -0,0 +1,28 @@ +export type Role = "owner" | "author" | "learner"; +export interface AuthUser { id: string; email: string; name: string; roles: Role[]; groups: string[] } +export interface RequestContext { user: AuthUser | null; params: Record; url: URL } +export type RouteHandler = (req: Request, rc: RequestContext) => Response | Promise; +export interface Feature { + name: string; // "learner" | "import" | "studio" | "ai" | "core" + routes: Record>>; // paths start with /api/ + jobs?: Record; // job kind -> handler +} +export interface JobContext { reportProgress(fraction: number, message?: string): Promise; signal: AbortSignal } +export type JobHandler = (payload: unknown, jc: JobContext) => Promise; +export type JobStatus = "queued" | "running" | "done" | "failed"; +export interface JobRecord { id: string; kind: string; status: JobStatus; progress: number; message: string | null; payload: unknown; result: unknown; error: string | null; createdAt: string; updatedAt: string } +export interface JobQueue { enqueue(kind: string, payload: unknown): Promise; get(id: string): Promise; list(kind?: string): Promise } +export interface AuthService { userFromRequest(req: Request): Promise } +// Placeholders until Task 4 (@stc/db) and Task 7 (@stc/course-format) exist; switch to the real imports in Task 7. +type Db = unknown; +type CourseRepository = unknown; +export interface ServerContext { + config: AppConfig; db: Db; courses: CourseRepository; + jobs: JobQueue; auth: AuthService; +} +export interface AppConfig { + port: number; databaseUrl: string; dataDir: string; // dataDir holds cache/, media/, worktrees/ + courseDirs: string[]; // folders scanned for stcourse.yaml (course repos and overlays/) + secret: string; // STC_SECRET, used to encrypt BYOK keys + publicUrl: string; +} diff --git a/packages/contracts/src/web.ts b/packages/contracts/src/web.ts new file mode 100644 index 0000000..2b7717c --- /dev/null +++ b/packages/contracts/src/web.ts @@ -0,0 +1,4 @@ +import type React from "react"; + +export interface WebRoute { path: string; element: () => Promise<{ default: React.ComponentType }>; nav?: { label: string; area: "header" | "admin" } } +export interface WebFeature { name: string; routes: WebRoute[] } diff --git a/packages/contracts/test/types.test.ts b/packages/contracts/test/types.test.ts new file mode 100644 index 0000000..ebf1370 --- /dev/null +++ b/packages/contracts/test/types.test.ts @@ -0,0 +1,54 @@ +import { expect, test } from "bun:test"; +import type { + AiProvider, AppConfig, AuthService, AuthUser, Assert, ChatMessage, ExerciseRunner, ExerciseTest, + Feature, ImportResult, ImportSource, JobContext, JobHandler, JobQueue, JobRecord, RequestContext, + RouteHandler, ServerContext, TestResult, ToolSpec, WebFeature, WebRoute, +} from "../src/index"; + +test("contract interfaces accept well-formed literals", async () => { + const user: AuthUser = { id: "u1", email: "a@b.c", name: "A", roles: ["owner", "learner"], groups: ["g"] }; + const rc: RequestContext = { user, params: { id: "1" }, url: new URL("http://localhost/api/x") }; + const handler: RouteHandler = async () => new Response("ok"); + const jobHandler: JobHandler = async (_p, jc) => { await jc.reportProgress(0.5, "half"); return null; }; + const feature: Feature = { + name: "core", + routes: { "/api/health": { GET: handler, POST: handler } }, + jobs: { noop: jobHandler }, + }; + const jc: JobContext = { reportProgress: async () => {}, signal: new AbortController().signal }; + const record: JobRecord = { + id: "j1", kind: "noop", status: "queued", progress: 0, message: null, payload: {}, result: null, + error: null, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", + }; + const queue: JobQueue = { enqueue: async () => "j1", get: async () => record, list: async () => [record] }; + const auth: AuthService = { userFromRequest: async () => user }; + const config: AppConfig = { + port: 3000, databaseUrl: "sqlite://./data/stcourses.db", dataDir: "./data", courseDirs: ["./overlays"], + secret: "s", publicUrl: "http://localhost:3000", + }; + const ctx: Pick = { config, jobs: queue, auth }; + + const assert: Assert = { equal() {}, deepEqual() {}, ok() {} }; + const t: ExerciseTest = { name: "t", run: (_mod, a) => a.ok(true) }; + const runner: ExerciseRunner = { + language: "ts", + run: async () => [{ name: "t", passed: true } satisfies TestResult], + }; + const msg: ChatMessage = { role: "user", content: "hi" }; + const tool: ToolSpec = { name: "x", description: "d", inputSchema: {} }; + const provider: AiProvider = { + id: "p", + async *chat() { yield { text: "hi" }; yield { toolCall: { id: "1", name: "x", input: {} } }; }, + }; + const source: ImportSource = { kind: "pdf-deck", path: "/tmp/a.pdf", options: {} }; + const result: ImportResult = { courseId: "c", manifestPath: "/tmp/stcourse.yaml", warnings: [] }; + const route: WebRoute = { + path: "/", element: async () => ({ default: () => null }), nav: { label: "Home", area: "header" }, + }; + const web: WebFeature = { name: "learner", routes: [route] }; + + expect(typeof feature.routes).toBe("object"); + expect(await queue.enqueue("noop", {})).toBe("j1"); + expect((await runner.run("", "", 1000))[0]!.passed).toBe(true); + void [rc, jc, ctx, assert, t, msg, tool, provider, source, result, web]; +}); From 7e7ce3053513e6775fb235d1495657274cf35421 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 02:49:42 +0100 Subject: [PATCH 03/14] feat(course-format): stcourse.yaml schema Co-Authored-By: Claude Opus 5.5 --- bun.lock | 5 + packages/course-format/package.json | 5 +- packages/course-format/src/schema.ts | 111 +++++++++++++++++++++ packages/course-format/test/schema.test.ts | 51 ++++++++++ 4 files changed, 171 insertions(+), 1 deletion(-) create mode 100644 packages/course-format/src/schema.ts create mode 100644 packages/course-format/test/schema.test.ts diff --git a/bun.lock b/bun.lock index d461254..736e0ae 100644 --- a/bun.lock +++ b/bun.lock @@ -29,6 +29,9 @@ "packages/course-format": { "name": "@stc/course-format", "version": "0.0.0", + "dependencies": { + "zod": "^4.6.7", + }, }, "packages/db": { "name": "@stc/db", @@ -90,6 +93,8 @@ "undici-types": ["undici-types@8.12.3", "", {}, "sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA=="], + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + "@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], } } diff --git a/packages/course-format/package.json b/packages/course-format/package.json index bbe81b8..935c4e7 100644 --- a/packages/course-format/package.json +++ b/packages/course-format/package.json @@ -3,5 +3,8 @@ "version": "0.0.0", "private": true, "type": "module", - "license": "AGPL-3.0-only" + "license": "AGPL-3.0-only", + "dependencies": { + "zod": "^4.6.7" + } } diff --git a/packages/course-format/src/schema.ts b/packages/course-format/src/schema.ts new file mode 100644 index 0000000..b488cd7 --- /dev/null +++ b/packages/course-format/src/schema.ts @@ -0,0 +1,111 @@ +import { z } from "zod"; + +const Track = z.object({ id: z.string(), label: z.string() }); +const Deck = z.object({ + id: z.string(), + file: z.string(), + title: z.string().optional(), + attachTo: z.string(), // a lesson id or module id +}); +const Attachment = z.object({ file: z.string(), title: z.string().optional(), module: z.string().optional() }); + +const Lesson = z.object({ + id: z.string(), + title: z.string(), + type: z.enum(["text", "video", "exercise"]), + file: z.string().optional(), + anchor: z.string().optional(), + duration: z.number().optional(), // seconds + transcript: z.string().optional(), + tracks: z.record(z.string(), z.object({ file: z.string().optional(), command: z.string().optional() })).optional(), + hints: z.object({ file: z.string(), match: z.string() }).optional(), + browser: z + .object({ + language: z.enum(["js", "ts"]), + starter: z.string(), + tests: z.string(), + solution: z.string().optional(), + }) + .optional(), + localCommand: z.union([z.string(), z.record(z.string(), z.string())]).optional(), +}); + +const Module = z.object({ + id: z.string(), + title: z.string(), + code: z.object({ dir: z.string(), command: z.string().optional() }).optional(), + lessons: z.array(Lesson), +}); + +export const ManifestSchema = z + .object({ + schema: z.literal(1), + id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/), + title: z.string(), + pitch: z.string().optional(), + authors: z.array(z.string()).optional(), + root: z.string().optional(), + cover: z.string().optional(), + accent: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(), + collections: z.array(z.string()).optional(), + visibility: z.enum(["public", "signed-in", "restricted"]).default("restricted"), + gating: z.enum(["none", "sequential"]).default("none"), + tracks: z.array(Track).optional(), + mentor: z.string().optional(), + source: z + .object({ + kind: z.enum(["authored", "packt-video", "pdf-deck", "code-repo", "video-folder"]), + origin: z.string().optional(), + importedAt: z.string().optional(), + }) + .optional(), + decks: z.array(Deck).optional(), + attachments: z.array(Attachment).optional(), + modules: z.array(Module), + }) + .superRefine((m, ctx) => { + const lessonIds = new Set(); + const moduleIds = new Set(m.modules.map((x) => x.id)); + m.modules.forEach((mod, mi) => { + mod.lessons.forEach((l, li) => { + const path = ["modules", mi, "lessons", li]; + if (lessonIds.has(l.id)) { + ctx.addIssue({ code: "custom", path: [...path, "id"], message: `duplicate lesson id "${l.id}"` }); + } + lessonIds.add(l.id); + if ((l.type === "text" || l.type === "video") && !l.file) { + ctx.addIssue({ code: "custom", path: [...path, "file"], message: `file is required for ${l.type} lessons` }); + } + }); + }); + m.decks?.forEach((d, i) => { + if (!lessonIds.has(d.attachTo) && !moduleIds.has(d.attachTo)) { + ctx.addIssue({ + code: "custom", + path: ["decks", i, "attachTo"], + message: `attachTo "${d.attachTo}" is not a lesson or module id`, + }); + } + }); + }); + +export type Manifest = z.infer; +export type Module = z.infer; +export type Lesson = z.infer; +export type Deck = z.infer; +export type Attachment = z.infer; +export type Track = z.infer; + +export function parseManifest( + yamlText: string, +): { ok: true; manifest: Manifest } | { ok: false; errors: string[] } { + let raw: unknown; + try { + raw = Bun.YAML.parse(yamlText); + } catch (e) { + return { ok: false, errors: [`yaml: ${e instanceof Error ? e.message : String(e)}`] }; + } + const r = ManifestSchema.safeParse(raw); + if (r.success) return { ok: true, manifest: r.data }; + return { ok: false, errors: r.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`) }; +} diff --git a/packages/course-format/test/schema.test.ts b/packages/course-format/test/schema.test.ts new file mode 100644 index 0000000..16a64fa --- /dev/null +++ b/packages/course-format/test/schema.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, test } from "bun:test"; +import { parseManifest } from "../src/schema"; + +const base = (extra = "", lessons = " - { id: l1, title: One, type: text, file: a.md }") => + `schema: 1\nid: x\ntitle: X\n${extra}modules:\n - id: m1\n title: M\n lessons:\n${lessons}\n`; + +describe("parseManifest", () => { + test("parses a minimal manifest", () => { + const r = parseManifest(base()); + expect(r.ok).toBe(true); + if (r.ok) { + expect(r.manifest.visibility).toBe("restricted"); + expect(r.manifest.gating).toBe("none"); + } + }); + + test("rejects a bad accent", () => { + const r = parseManifest(base('accent: "orange"\n')); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.errors.some((e) => e.includes("accent"))).toBe(true); + }); + + test("rejects duplicate lesson ids across modules", () => { + const text = base() + " - id: m2\n title: M2\n lessons:\n - { id: l1, title: Dup, type: text, file: b.md }\n"; + const r = parseManifest(text); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.errors.some((e) => e.includes("l1"))).toBe(true); + }); + + test("requires file for text and video lessons", () => { + for (const type of ["text", "video"]) { + const r = parseManifest(base("", ` - { id: l1, title: One, type: ${type} }`)); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.errors.some((e) => e.includes("file"))).toBe(true); + } + expect(parseManifest(base("", " - { id: l1, title: One, type: exercise }")).ok).toBe(true); + }); + + test("rejects a deck whose attachTo is not a lesson or module id", () => { + const r = parseManifest(base("decks:\n - { id: d1, file: d.pdf, attachTo: nope }\n")); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.errors.some((e) => e.includes("nope"))).toBe(true); + expect(parseManifest(base("decks:\n - { id: d1, file: d.pdf, attachTo: m1 }\n")).ok).toBe(true); + }); + + test("rejects schema: 2", () => { + const r = parseManifest(base().replace("schema: 1", "schema: 2")); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.errors.some((e) => e.startsWith("schema"))).toBe(true); + }); +}); From 7a68800f6faaea08caa1bbc16ab0ae7ff79d4ebf Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 02:50:00 +0100 Subject: [PATCH 04/14] test: sample fixture course Co-Authored-By: Claude Opus 5.5 --- fixtures/courses/sample/MENTOR.md | 1 + .../sample/code/S01 - First steps/hello.sh | 1 + .../courses/sample/exercises/add/solution.js | 3 ++ .../courses/sample/exercises/add/starter.js | 3 ++ .../courses/sample/exercises/add/tests.js | 4 ++ fixtures/courses/sample/lessons/01-intro.md | 3 ++ fixtures/courses/sample/lessons/02-video.md | 3 ++ fixtures/courses/sample/lessons/03-code.md | 7 ++++ .../courses/sample/lessons/04-exercise.md | 23 ++++++++++++ fixtures/courses/sample/media/clip.mp4 | Bin 0 -> 3934 bytes fixtures/courses/sample/media/deck.pdf | Bin 0 -> 1454 bytes fixtures/courses/sample/stcourse.yaml | 35 ++++++++++++++++++ scripts/make-fixtures.sh | 14 +++++++ 13 files changed, 97 insertions(+) create mode 100644 fixtures/courses/sample/MENTOR.md create mode 100644 fixtures/courses/sample/code/S01 - First steps/hello.sh create mode 100644 fixtures/courses/sample/exercises/add/solution.js create mode 100644 fixtures/courses/sample/exercises/add/starter.js create mode 100644 fixtures/courses/sample/exercises/add/tests.js create mode 100644 fixtures/courses/sample/lessons/01-intro.md create mode 100644 fixtures/courses/sample/lessons/02-video.md create mode 100644 fixtures/courses/sample/lessons/03-code.md create mode 100644 fixtures/courses/sample/lessons/04-exercise.md create mode 100644 fixtures/courses/sample/media/clip.mp4 create mode 100644 fixtures/courses/sample/media/deck.pdf create mode 100644 fixtures/courses/sample/stcourse.yaml create mode 100755 scripts/make-fixtures.sh diff --git a/fixtures/courses/sample/MENTOR.md b/fixtures/courses/sample/MENTOR.md new file mode 100644 index 0000000..696e9f0 --- /dev/null +++ b/fixtures/courses/sample/MENTOR.md @@ -0,0 +1 @@ +You are the mentor for the sample course. Give hints, never full solutions. diff --git a/fixtures/courses/sample/code/S01 - First steps/hello.sh b/fixtures/courses/sample/code/S01 - First steps/hello.sh new file mode 100644 index 0000000..6c02b52 --- /dev/null +++ b/fixtures/courses/sample/code/S01 - First steps/hello.sh @@ -0,0 +1 @@ +echo "hello from the sample course" diff --git a/fixtures/courses/sample/exercises/add/solution.js b/fixtures/courses/sample/exercises/add/solution.js new file mode 100644 index 0000000..7d65831 --- /dev/null +++ b/fixtures/courses/sample/exercises/add/solution.js @@ -0,0 +1,3 @@ +export function add(a, b) { + return a + b; +} diff --git a/fixtures/courses/sample/exercises/add/starter.js b/fixtures/courses/sample/exercises/add/starter.js new file mode 100644 index 0000000..29b3851 --- /dev/null +++ b/fixtures/courses/sample/exercises/add/starter.js @@ -0,0 +1,3 @@ +export function add(a, b) { + return a - b; +} diff --git a/fixtures/courses/sample/exercises/add/tests.js b/fixtures/courses/sample/exercises/add/tests.js new file mode 100644 index 0000000..4d5843b --- /dev/null +++ b/fixtures/courses/sample/exercises/add/tests.js @@ -0,0 +1,4 @@ +export const tests = [ + { name: "adds 2 and 3", run: (mod, assert) => assert.equal(mod.add(2, 3), 5) }, + { name: "adds -1 and 1", run: (mod, assert) => assert.equal(mod.add(-1, 1), 0) }, +]; diff --git a/fixtures/courses/sample/lessons/01-intro.md b/fixtures/courses/sample/lessons/01-intro.md new file mode 100644 index 0000000..4e844ff --- /dev/null +++ b/fixtures/courses/sample/lessons/01-intro.md @@ -0,0 +1,3 @@ +# Introduction + +Welcome to the sample course. It exists so tests have something small to load. diff --git a/fixtures/courses/sample/lessons/02-video.md b/fixtures/courses/sample/lessons/02-video.md new file mode 100644 index 0000000..52c1d4b --- /dev/null +++ b/fixtures/courses/sample/lessons/02-video.md @@ -0,0 +1,3 @@ +# Transcript + +A two-second test pattern plays. Nothing is said. diff --git a/fixtures/courses/sample/lessons/03-code.md b/fixtures/courses/sample/lessons/03-code.md new file mode 100644 index 0000000..0a29890 --- /dev/null +++ b/fixtures/courses/sample/lessons/03-code.md @@ -0,0 +1,7 @@ +# Code along + +Run the script in the section files: + +```sh +sh hello.sh +``` diff --git a/fixtures/courses/sample/lessons/04-exercise.md b/fixtures/courses/sample/lessons/04-exercise.md new file mode 100644 index 0000000..4e78add --- /dev/null +++ b/fixtures/courses/sample/lessons/04-exercise.md @@ -0,0 +1,23 @@ +# Adding numbers + +Functions take values and return values. + +## Exercises + +### Exercise 2.1 — `add` + +Implement `add(a, b)` so that it returns the sum of its arguments. + +## Hints + +
Exercise 2.1 (add) — nudge + +Which operator combines two numbers? + +
+ +
Exercise 2.1 (add) — near-solution + +Return `a + b`. + +
diff --git a/fixtures/courses/sample/media/clip.mp4 b/fixtures/courses/sample/media/clip.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..2e316e002b531e9b380e2a857d7020918b66f570 GIT binary patch literal 3934 zcmai03p`X?7e6x!~V5#+jKjW}2rtClNx=t8NdH=rQz^ zlBl@3H4!OE5hbLXQlY0*N@Bi!hHl+{_xJnu&pvDI|9b4T*IIiU2!dcf9xWGQG6@8c zA%cQQMf893=7_HD4+Mzrg1DrJ~#&8XyiIniGI}|fH zUBVM0Kn6>AKcC$Jz>A?}S2dOt0Z*(L@&QE(dFVHupg~|Q^FgFMF-qu=XGw%oK445E zB^swchHb|ilv(o>D4|0PLax7BA%+KevKEGO#DFiyaO_(_2%U38(EugJk3I*HEO2Ze zz!H-fBr|`Y?@Du`xjWIQG*~R;MA2QDgF?;MT&)Jw9caxW@gRNmW5_BT&|Jl^U$*yB zjX{}+ZL}cMQKpkOhLIp0LC381ODgmGKYu3djpPU>2b2hfn5GZFld4^e%Bg8tDAKsCOA{r{80gaOd|hdt;y zjlDI9g{$%SJr>hJeTWBSYlmb60l0Pypj}`Rsk8#q0?aXBS^{$-5X#Vc><~2v^e&i0 zVF-+vW?&L_z=p^LR|Y6CK#are0Yz5xa0Jj`396xl%=X6~1bwSO>V@g$82}XExZK0pdCi(NPQ(?Gi4m!jOcCx(?BXQAC1Ri>ljA~}6!U<& z2nXS^XfU`YESf9KLpfp@SHz-uP(7$HB1Oc}7|NnXF+8YIGzJ5fpsdvr0gSEY0FFk5 zrkiwa^ucxz=+U_f)E(O^D;;cPi363PjUK?f0Xwv5lmP@F}f!?-{JEHD-W z7RzKJL;x1-Zx{{6#6m8JV z7bFS1p+YHe0TdMop~F`o5)@;(!5p?c8t_6MI0T1{@DMq!;W$DBBQ_B#P;f2=yapA9 z3vdqDOeROA>~NVJNC!bVFc6{9z&DHTLLFk+;AJDSi*ZpY%3Y1Km{cN61wy1$fnow+ zuHdr&J}%3ZShKhaJ}d#R14ixBT zWl7D;%%jT5mvz?o9(mEIf9t}&x^>FYb-@({dUYRRQ6v=8@}E)&=alQ7w0hApwi=64 z`AvCH=wwELH>_@ypP~A+8%A#vA6TMen8w#m-?UbBn^mg3NwN6Ud3cX};iyCE%d5!2 z$2&09u?e+*ru4a|78&kFJXtT38|JgKwpmcy^!xNEcc<%gMJMkt@Lj)b=bo=|Om1q& zH2R9H1PhZgKg{$*JfySa$gA`I6*C7d+S<2g zrtfa!5ZQ~l`)o&y=s6VowT~Hh7+%_78-KT`xAkSv`#);VMxF}M{Z#xkIJAplF!ya| zN$m1>(dreMx7(5|DSI7`y)tGoui3V_ibFlRnYHf5n+{Cz5)attnWud{S7g*!J!!@G zd+5%Y1>xlu|q^Q2;Zsn8BH#f&-OfMy)w%)~g&Ti%QT~{I-rhAZuBw@hVgSO%d#q`X- zviH{UKd~GRgj60Rry=A08@%7GYQC_7(YhnU)cM!Uz3f!$su4@gWl&3jp-%4clOOZs zq5Ympn*$CjO}MkR&C9BvU3alm9_HAwaL0}rmv`rG-J$TmUf))@q#$1R*8P^>lNTR> zN4|f&!uhBNhqjWsa8YH6-#u*1FelnNHgD$?8*H)t8t7WnUb6E?ZI(JKfY^T5`kn>@>Kl)#MiyrX6;^t-R}M zy%mSDqwnratXrwNSDcwNHYzi+q zT;6ANH)@IeeP|aZNNX1Dnf#Z*l~AjmEh`O=IovO9w~ndE9Fy1ereE?AeH-AOCYQ-^| zNEdINf@h>`kJ5GLy^Diyl&c=L(r1;G>|S~h8rHZujhr{P&S!g$^2jU- zx7quiMKrsWmAjPalm(72S|1pD#%+Uzs`!@We?(U7tSc_AW`4T=V57^P|K7-2 zA8H~THo^D^qnfdhR=~_H5>*!2bUm(b${PrurMvTTakZ2`E_UmIktvVU=U|ZwPXBuH z%vBq3UaGg!DBMVG+0-PjOxitCc*jqzPJm7iuU43dgsLgOk1O@}6d$VST4J|HS}!1tBvan)^-kZus&`?yBJF#BZz7K(O6M zrZ(-Sn6SsSJ1vXp2k01pp8f${S|ecY*?$cD^f33{XOZMWCf}i_8_iRHSw4lo^Oq9y z@|+?`?#J}C!xQZs_3gb#)efRShF5Wm>uV;(O)q472|B(-R9hU-`Ic8E-rf}Vyt|$? zaP^wi(buu6PkN!Hwz^5Z&NG(2T6ew1_#%^eJ)U%-SKmmvw^^%@rU1 z@Ov9l9(~*+wH^xE-`D0*6g~RXuHN8x`AEwt{`?2v^n5YiUG_8uv~ZOuWPE z!&aKahuJ?=o;BYHP!p1JvcY%s;DbjaCJ!o4_D``=j|uD%2Q7Uk*ffv@P*b2R{sG-= zq8vy3)~@y5H$_-TCO3m3kqp!jDf^)PMgecveu~;iE9`zpw(9u?KhNQw&MCOYO@wB|rby;qM}P_kV7P z?zZ$4^q0m2``S-xKl`LAd{gEXc5Z9-hWOT*^FNeqeOJC$`>#iBD|-{#`hAjv+G{g-gdhA@+(|tFmU3-Gz>Fcg8r!5)N%lz-@wp$rm?cl`mP8HhBZPtztYCAbG z$e{Ly?r4j+`$TWg_Eyqf6^v4k%9#Df?{xmzn_pgyI=OtV#zqWkI4+7UdHD;7l%)a2|o?|fCRhep4hBOJ5q99S5)J9Oj3I2*IB7Y2YT5#JTtjgodrN}mpmK+NL-n)YTNO&xqM?4xEsW+ P@$mnLAnH_Es`>u_Pp5c< literal 0 HcmV?d00001 diff --git a/fixtures/courses/sample/media/deck.pdf b/fixtures/courses/sample/media/deck.pdf new file mode 100644 index 0000000000000000000000000000000000000000..5f8fde26d5e3e7b37915f96ca69796302cd95561 GIT binary patch literal 1454 zcmcgs&ubGw6plin?mq+ z;L#q6)`B3kf(LI3;zf!*`3Kmm=s)1mn{Q%Ux7!}A13T=zH}Cu2`)1}97Hak#TGXY& z{=5D6QUNW+KIbe%opm%n1Sg_J*(hp~L=izzXCPH7cyWD|Vawr85cTka(_;ye!P~(1 zLN5aULL9lnE{kub5pK=EkXYyn5J~J$qm5Cp6%9j<6nx)zla?wVkv^WwVqQ+gD}Uqd zDC9ueXTc++iG8Pt1WJ|&&okF|%xKgi;8hKRWSuPIM#LS?5Wx+WM8miXWeJ)Flo&I} z>ragq(7`Hcm4q*ylORu1iNtVo*x^Dhp&7-dld!S*E@aEN-*s?3>_)C1_VAJ)R>Q?TEbQ?2at1(0S1GJgvZQTkw!b;Z~us;Z}K9^nbyQKa)LMc z%`dwzpKdqz+U~3T=3aiKI|#h~Rwrz41>V4IdmV4!1zYY;-))B-@5<-dwU38+T>P4U zJ6p_M{WSGc9NrPZ@iB_iNtY~+@!zOxWYrah|0lwv`}*0#%fD`*>nRb8x#=h8h#)TK z#fU(~{XBKY#+Hl>>c!oKN%zI}?)LM;gN@PJhmF;V_)_k`o4R(62&0&J5Xd4knqB}zWtFDYtFGxvNhM{aTGMAlQ%SfJ^RcLul%YKr>JMz`H|ayOfdBvi literal 0 HcmV?d00001 diff --git a/fixtures/courses/sample/stcourse.yaml b/fixtures/courses/sample/stcourse.yaml new file mode 100644 index 0000000..7d25ac2 --- /dev/null +++ b/fixtures/courses/sample/stcourse.yaml @@ -0,0 +1,35 @@ +schema: 1 +id: sample +title: Sample course +pitch: A tiny self-contained course used by the test suite. +visibility: public +tracks: + - { id: js, label: JavaScript } +mentor: MENTOR.md +source: { kind: authored } +decks: + - { id: d1, file: media/deck.pdf, attachTo: m1-video } +modules: + - id: m1 + title: First steps + code: { dir: "code/S01 - First steps", command: "sh hello.sh" } + lessons: + - { id: m1-intro, title: Introduction, type: text, file: lessons/01-intro.md } + - { id: m1-video, title: Watch the clip, type: video, file: media/clip.mp4, duration: 2, transcript: lessons/02-video.md } + - { id: m1-code, title: Code along, type: text, file: lessons/03-code.md } + - id: m2 + title: Exercises + lessons: + - { id: m2-text, title: Adding numbers, type: text, file: lessons/04-exercise.md } + - id: m2-ex-add + title: "Exercise 2.1: add" + type: exercise + file: lessons/04-exercise.md + anchor: exercise-21--add + hints: { file: lessons/04-exercise.md, match: "Exercise 2.1 (add)" } + browser: + language: js + starter: exercises/add/starter.js + tests: exercises/add/tests.js + solution: exercises/add/solution.js + localCommand: "node --test" diff --git a/scripts/make-fixtures.sh b/scripts/make-fixtures.sh new file mode 100755 index 0000000..a9112ef --- /dev/null +++ b/scripts/make-fixtures.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Regenerates the binary fixtures under fixtures/courses/sample/media. +set -eu +cd "$(dirname "$0")/../fixtures/courses/sample/media" +/usr/bin/ffmpeg -y -loglevel error -f lavfi -i "testsrc=duration=2:size=160x90:rate=10" \ + -pix_fmt yuv420p -c:v libx264 -crf 35 -preset veryslow -movflags +faststart clip.mp4 +/home/user/.venvs/pdf/bin/python -I - <<'PY' +import pymupdf +doc = pymupdf.open() +for i, text in enumerate(["Sample deck: title", "Sample deck: middle", "Sample deck: end"], 1): + page = doc.new_page(width=480, height=270) + page.insert_text((40, 135), text, fontsize=24) +doc.save("deck.pdf", garbage=4, deflate=True) +PY From c78c7ec8d81577426d39a4904b918e8aa7cd0d24 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 02:51:26 +0100 Subject: [PATCH 05/14] feat(course-format): markdown extraction, discovery, loading, repository Co-Authored-By: Claude Opus 5.5 --- packages/contracts/src/server.ts | 4 +- packages/course-format/src/index.ts | 4 + packages/course-format/src/load.ts | 208 +++++++++++++++++++ packages/course-format/src/markdown.ts | 66 ++++++ packages/course-format/src/repository.ts | 42 ++++ packages/course-format/test/load.test.ts | 147 +++++++++++++ packages/course-format/test/markdown.test.ts | 89 ++++++++ 7 files changed, 558 insertions(+), 2 deletions(-) create mode 100644 packages/course-format/src/index.ts create mode 100644 packages/course-format/src/load.ts create mode 100644 packages/course-format/src/markdown.ts create mode 100644 packages/course-format/src/repository.ts create mode 100644 packages/course-format/test/load.test.ts create mode 100644 packages/course-format/test/markdown.test.ts diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index dbfca4a..4dfd75f 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -1,3 +1,4 @@ +import type { CourseRepository } from "@stc/course-format"; export type Role = "owner" | "author" | "learner"; export interface AuthUser { id: string; email: string; name: string; roles: Role[]; groups: string[] } export interface RequestContext { user: AuthUser | null; params: Record; url: URL } @@ -13,9 +14,8 @@ export type JobStatus = "queued" | "running" | "done" | "failed"; export interface JobRecord { id: string; kind: string; status: JobStatus; progress: number; message: string | null; payload: unknown; result: unknown; error: string | null; createdAt: string; updatedAt: string } export interface JobQueue { enqueue(kind: string, payload: unknown): Promise; get(id: string): Promise; list(kind?: string): Promise } export interface AuthService { userFromRequest(req: Request): Promise } -// Placeholders until Task 4 (@stc/db) and Task 7 (@stc/course-format) exist; switch to the real imports in Task 7. +// Placeholder until Task 7 (@stc/db) exists. type Db = unknown; -type CourseRepository = unknown; export interface ServerContext { config: AppConfig; db: Db; courses: CourseRepository; jobs: JobQueue; auth: AuthService; diff --git a/packages/course-format/src/index.ts b/packages/course-format/src/index.ts new file mode 100644 index 0000000..6424cba --- /dev/null +++ b/packages/course-format/src/index.ts @@ -0,0 +1,4 @@ +export * from "./schema"; +export * from "./markdown"; +export * from "./load"; +export * from "./repository"; diff --git a/packages/course-format/src/load.ts b/packages/course-format/src/load.ts new file mode 100644 index 0000000..b0e3c57 --- /dev/null +++ b/packages/course-format/src/load.ts @@ -0,0 +1,208 @@ +import { readdir, readFile, realpath } from "node:fs/promises"; +import { realpathSync } from "node:fs"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { extractHints, extractSection } from "./markdown"; +import { parseManifest, type Lesson, type Manifest } from "./schema"; + +export type Diagnostic = { + level: "error" | "warning"; + courseId?: string; + lessonId?: string; + path?: string; + message: string; +}; + +export interface LoadedCourse { + id: string; + manifestPath: string; + root: string; + manifest: Manifest | null; + status: "ok" | "error"; + diagnostics: Diagnostic[]; + lessonIndex: Map; +} + +const MANIFEST_NAME = "stcourse.yaml"; +const SKIP_DIRS = new Set(["node_modules", ".git"]); + +/** + * Absolute path of `rel` under `root` if its real path (symlinks followed) is inside the real root, + * else null. A nonexistent target is also null. + */ +export function resolveInside(root: string, rel: string): string | null { + try { + const realRoot = realpathSync(root); + const real = realpathSync(resolve(realRoot, rel)); + return real === realRoot || real.startsWith(realRoot + sep) ? real : null; + } catch { + return null; + } +} + +/** Finds stcourse.yaml at depth 0-2 under each dir. */ +export async function discoverManifests(courseDirs: string[]): Promise { + const found: string[] = []; + const seen = new Set(); + async function walk(dir: string, depth: number) { + const candidate = join(dir, MANIFEST_NAME); + if (await Bun.file(candidate).exists()) { + if (!seen.has(candidate)) { + seen.add(candidate); + found.push(candidate); + } + } + if (depth >= 2) return; + let entries; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + return; + } + entries.sort((a, b) => a.name.localeCompare(b.name)); + for (const e of entries) { + if (e.isDirectory() && !SKIP_DIRS.has(e.name)) await walk(join(dir, e.name), depth + 1); + } + } + for (const d of courseDirs) await walk(resolve(d), 0); + return found; +} + +export async function loadCourse(manifestPath: string): Promise { + manifestPath = resolve(manifestPath); + const dir = dirname(manifestPath); + const diagnostics: Diagnostic[] = []; + const course: LoadedCourse = { + id: basename(dir), + manifestPath, + root: dir, + manifest: null, + status: "error", + diagnostics, + lessonIndex: new Map(), + }; + const err = (message: string, extra: Partial = {}) => + diagnostics.push({ level: "error", courseId: course.id, message, ...extra }); + + let text: string; + try { + text = await readFile(manifestPath, "utf8"); + } catch (e) { + err(`cannot read manifest ${manifestPath}: ${(e as Error).message}`, { path: manifestPath }); + return course; + } + const parsed = parseManifest(text); + if (!parsed.ok) { + for (const m of parsed.errors) err(`invalid manifest: ${m}`, { path: manifestPath }); + return course; + } + const manifest = parsed.manifest; + course.manifest = manifest; + course.id = manifest.id; + course.root = resolve(dir, manifest.root ?? "."); + for (const mod of manifest.modules) { + for (const lesson of mod.lessons) course.lessonIndex.set(lesson.id, { moduleId: mod.id, lesson }); + } + + try { + course.root = await realpath(course.root); + } catch { + err(`course root does not exist or is unreadable: ${course.root}`, { path: course.root }); + return course; + } + const root = course.root; + + const mdCache = new Map(); + const readMd = async (rel: string): Promise => { + const abs = resolveInside(root, rel); + if (!abs) return null; + if (!mdCache.has(abs)) mdCache.set(abs, await Bun.file(abs).text()); + return mdCache.get(abs)!; + }; + /** Reports an error and returns false when `rel` does not exist inside the root. */ + const requireFile = (rel: string, what: string, lessonId?: string): boolean => { + if (resolveInside(root, rel)) return true; + err(`${what} not found: ${rel}`, { lessonId, path: rel }); + return false; + }; + + if (manifest.cover) requireFile(manifest.cover, "cover", undefined); + if (manifest.mentor) requireFile(manifest.mentor, "mentor file", undefined); + for (const d of manifest.decks ?? []) requireFile(d.file, `deck "${d.id}" file`); + for (const a of manifest.attachments ?? []) requireFile(a.file, "attachment"); + + for (const mod of manifest.modules) { + if (mod.code) requireFile(mod.code.dir, `module "${mod.id}" code dir`); + for (const l of mod.lessons) { + const id = l.id; + let fileOk = true; + if (l.file) fileOk = requireFile(l.file, "lesson file", id); + if (l.transcript) requireFile(l.transcript, "transcript", id); + for (const [track, t] of Object.entries(l.tracks ?? {})) { + if (t.file) requireFile(t.file, `track "${track}" file`, id); + } + if (l.browser) { + requireFile(l.browser.starter, "browser starter", id); + requireFile(l.browser.tests, "browser tests", id); + if (l.browser.solution) requireFile(l.browser.solution, "browser solution", id); + } + if (l.anchor) { + const file = l.file ?? l.hints?.file; + if (!file) { + err(`anchor "${l.anchor}" given but the lesson has no file`, { lessonId: id }); + } else if (fileOk) { + const md = await readMd(file); + if (md !== null && extractSection(md, l.anchor) === null) { + err(`anchor "${l.anchor}" not found in ${file}`, { lessonId: id, path: file }); + } + } + } + if (l.hints) { + if (requireFile(l.hints.file, "hints file", id)) { + const md = await readMd(l.hints.file); + if (md !== null && extractHints(md, l.hints.match).length === 0) { + err(`no hint blocks matching "${l.hints.match}" in ${l.hints.file}`, { lessonId: id, path: l.hints.file }); + } + } + } + } + } + + course.status = diagnostics.some((d) => d.level === "error") ? "error" : "ok"; + return course; +} + +function isOverlay(c: LoadedCourse): boolean { + if (!c.manifest?.root) return false; + const rel = relative(dirname(c.manifestPath), resolve(dirname(c.manifestPath), c.manifest.root)); + return rel === ".." || rel.startsWith(".." + sep) || isAbsolute(rel); +} + +/** Loads every manifest found under courseDirs. Duplicate ids: the overlay wins (spec section 13). */ +export async function loadAll(courseDirs: string[]): Promise { + const paths = await discoverManifests(courseDirs); + const loaded = await Promise.all(paths.map((p) => loadCourse(p))); + const winners = new Map(); + const result: LoadedCourse[] = []; + const dropped = new Set(); + for (const c of loaded) { + if (!c.manifest) { + result.push(c); + continue; + } + const prev = winners.get(c.id); + if (!prev) { + winners.set(c.id, c); + continue; + } + const [win, lose] = isOverlay(c) && !isOverlay(prev) ? [c, prev] : [prev, c]; + win.diagnostics.push({ + level: "warning", + courseId: win.id, + path: lose.manifestPath, + message: `shadows another manifest with the same id "${win.id}": ${lose.manifestPath}`, + }); + dropped.add(lose); + winners.set(c.id, win); + } + return loaded.filter((c) => !dropped.has(c)); +} diff --git a/packages/course-format/src/markdown.ts b/packages/course-format/src/markdown.ts new file mode 100644 index 0000000..512e636 --- /dev/null +++ b/packages/course-format/src/markdown.ts @@ -0,0 +1,66 @@ +/** GitHub-style heading slug: lowercase, markdown stripped, punctuation dropped, spaces to hyphens. */ +export function slugify(heading: string): string { + return heading + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") // links and images keep their text + .replace(/[`*~]/g, "") // code spans and emphasis markers + .replace(/<[^>]+>/g, "") // inline html + .trim() + .toLowerCase() + .replace(/[^\p{L}\p{N}\p{M}\s_-]/gu, "") + .replace(/\s/g, "-"); +} + +interface Heading { + line: number; + level: number; + text: string; +} + +function headings(lines: string[]): Heading[] { + const out: Heading[] = []; + let fence: string | null = null; + lines.forEach((line, i) => { + const f = /^ {0,3}(`{3,}|~{3,})/.exec(line); + if (f) { + const marker = f[1]![0]!; + if (fence === null) fence = marker; + else if (fence === marker) fence = null; + return; + } + if (fence !== null) return; + const h = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line); + if (h) out.push({ line: i, level: h[1]!.length, text: h[2]! }); + }); + return out; +} + +/** Heading line plus everything up to the next heading of the same or a higher level. */ +export function extractSection(markdown: string, anchor: string): string | null { + const lines = markdown.split(/\r?\n/); + const hs = headings(lines); + const seen = new Map(); + for (let i = 0; i < hs.length; i++) { + const h = hs[i]!; + const base = slugify(h.text); + const n = seen.get(base) ?? 0; + seen.set(base, n + 1); + const slug = n === 0 ? base : `${base}-${n}`; // GitHub numbers duplicates + if (slug !== anchor) continue; + const next = hs.slice(i + 1).find((x) => x.level <= h.level); + return lines.slice(h.line, next ? next.line : lines.length).join("\n").trimEnd(); + } + return null; +} + +/** `
……
` blocks whose summary starts with `match`, in document order. */ +export function extractHints(markdown: string, match: string): { label: string; body: string }[] { + const out: { label: string; body: string }[] = []; + const re = /
\s*([\s\S]*?)<\/summary>([\s\S]*?)<\/details>/g; + for (const m of markdown.matchAll(re)) { + const summary = m[1]!.trim(); + if (!summary.startsWith(match)) continue; + const label = summary.slice(match.length).replace(/^\s*(?:—|-|\()\s*/, "").trim(); + out.push({ label, body: m[2]!.trim() }); + } + return out; +} diff --git a/packages/course-format/src/repository.ts b/packages/course-format/src/repository.ts new file mode 100644 index 0000000..72060b5 --- /dev/null +++ b/packages/course-format/src/repository.ts @@ -0,0 +1,42 @@ +import { extname } from "node:path"; +import { loadAll, resolveInside, type LoadedCourse } from "./load"; +import { extractSection } from "./markdown"; + +export interface CourseRepository { + list(): LoadedCourse[]; + get(id: string): LoadedCourse | null; + /** Re-scans the course dirs. `id` is accepted for API symmetry; a rescan is cheap and keeps overlay shadowing correct. */ + reload(id?: string): Promise; + readLessonMarkdown(courseId: string, lessonId: string): Promise; + /** Absolute real path if inside the course root (symlinks followed), else null. */ + resolvePath(courseId: string, relPath: string): string | null; +} + +const MD = new Set([".md", ".markdown"]); + +export async function createCourseRepository(courseDirs: string[]): Promise { + let courses = await loadAll(courseDirs); + const repo: CourseRepository = { + list: () => courses, + get: (id) => courses.find((c) => c.id === id) ?? null, + async reload() { + courses = await loadAll(courseDirs); + }, + async readLessonMarkdown(courseId, lessonId) { + const entry = repo.get(courseId)?.lessonIndex.get(lessonId); + if (!entry) return null; + const { lesson } = entry; + const rel = lesson.type === "video" ? lesson.transcript : lesson.file; + if (!rel || !MD.has(extname(rel).toLowerCase())) return null; + const abs = repo.resolvePath(courseId, rel); + if (!abs) return null; + const text = await Bun.file(abs).text(); + return lesson.anchor ? extractSection(text, lesson.anchor) : text; + }, + resolvePath(courseId, relPath) { + const c = repo.get(courseId); + return c ? resolveInside(c.root, relPath) : null; + }, + }; + return repo; +} diff --git a/packages/course-format/test/load.test.ts b/packages/course-format/test/load.test.ts new file mode 100644 index 0000000..a93f3d3 --- /dev/null +++ b/packages/course-format/test/load.test.ts @@ -0,0 +1,147 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdtemp, rm, symlink } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { createCourseRepository, discoverManifests, loadAll, loadCourse } from "../src/index"; + +const sampleDir = resolve(import.meta.dir, "../../../fixtures/courses/sample"); +const tmps: string[] = []; +async function tmp(): Promise { + const d = await mkdtemp(join(tmpdir(), "stc-")); + tmps.push(d); + return d; +} +afterAll(() => Promise.all(tmps.map((d) => rm(d, { recursive: true, force: true })))); + +const manifest = (id: string, extra: string, lessons: string) => + `schema: 1\nid: ${id}\ntitle: T\n${extra}modules:\n - id: m\n title: M\n lessons:\n${lessons}\n`; + +describe("sample fixture", () => { + test("loads the sample fixture with no errors", async () => { + const c = await loadCourse(join(sampleDir, "stcourse.yaml")); + expect(c.diagnostics).toEqual([]); + expect(c.status).toBe("ok"); + expect(c.id).toBe("sample"); + expect([...c.lessonIndex.keys()]).toEqual(["m1-intro", "m1-video", "m1-code", "m2-text", "m2-ex-add"]); + }); + + test("repository reads lesson markdown and sections", async () => { + const repo = await createCourseRepository([sampleDir]); + expect(repo.list().map((c) => c.id)).toEqual(["sample"]); + expect(await repo.readLessonMarkdown("sample", "m1-intro")).toContain("# Introduction"); + const ex = await repo.readLessonMarkdown("sample", "m2-ex-add"); + expect(ex!.startsWith("### Exercise 2.1")).toBe(true); + expect(await repo.readLessonMarkdown("sample", "nope")).toBeNull(); + expect(repo.get("nope")).toBeNull(); + }); +}); + +describe("discovery", () => { + test("finds manifests at depth 0 to 2 only", async () => { + const d = await tmp(); + for (const p of ["stcourse.yaml", "a/stcourse.yaml", "a/b/stcourse.yaml", "a/b/c/stcourse.yaml"]) { + await Bun.write(join(d, p), "x"); + } + const found = (await discoverManifests([d])).map((p) => p.slice(d.length + 1)); + expect(found.sort()).toEqual(["a/b/stcourse.yaml", "a/stcourse.yaml", "stcourse.yaml"]); + }); +}); + +describe("overlays and errors", () => { + test("overlay with missing root gives status error", async () => { + const d = await tmp(); + const missing = join(d, "gone-repo"); + await Bun.write(join(d, "overlay/stcourse.yaml"), manifest("broken", `root: ${missing}\n`, " - { id: l, title: L, type: text, file: a.md }")); + await Bun.write(join(d, "ok/a.md"), "# A\n"); + await Bun.write(join(d, "ok/stcourse.yaml"), manifest("fine", "", " - { id: l, title: L, type: text, file: a.md }")); + const all = await loadAll([d]); + expect(all.map((c) => c.id).sort()).toEqual(["broken", "fine"]); + const broken = all.find((c) => c.id === "broken")!; + expect(broken.status).toBe("error"); + expect(broken.diagnostics.some((x) => x.level === "error" && x.message.includes(missing))).toBe(true); + expect(all.find((c) => c.id === "fine")!.status).toBe("ok"); + }); + + test("missing lesson file, anchor and hints each produce one error diagnostic naming lessonId", async () => { + const d = await tmp(); + await Bun.write(join(d, "a.md"), "# A\n\n## Real\n\ntext\n"); + const lessons = [ + " - { id: no-file, title: L, type: text, file: missing.md }", + " - { id: no-anchor, title: L, type: text, file: a.md, anchor: ghost }", + " - { id: no-hints, title: L, type: exercise, file: a.md, anchor: real, hints: { file: a.md, match: 'Exercise 1' } }", + ].join("\n"); + await Bun.write(join(d, "stcourse.yaml"), manifest("bad", "", lessons)); + const c = await loadCourse(join(d, "stcourse.yaml")); + expect(c.status).toBe("error"); + const errs = c.diagnostics.filter((x) => x.level === "error"); + expect(errs.map((e) => e.lessonId)).toEqual(["no-file", "no-anchor", "no-hints"]); + expect(errs[0]!.path).toBe("missing.md"); + expect(errs[1]!.message).toContain("ghost"); + expect(errs[2]!.message).toContain("Exercise 1"); + }); + + test("invalid manifest gives an error course and does not throw", async () => { + const d = await tmp(); + await Bun.write(join(d, "stcourse.yaml"), "schema: 2\nid: x\n"); + const c = await loadCourse(join(d, "stcourse.yaml")); + expect(c.status).toBe("error"); + expect(c.manifest).toBeNull(); + expect(c.diagnostics.length).toBeGreaterThan(0); + }); + + test("handles spaces and unicode in paths", async () => { + const d = await tmp(); + const rel = "S08 - Containerizing Applications/Æble notes.md"; + await Bun.write(join(d, rel), "# Æble\n"); + await Bun.write(join(d, "stcourse.yaml"), manifest("uni", "", ` - { id: l, title: L, type: text, file: "${rel}" }`)); + const repo = await createCourseRepository([d]); + expect(repo.get("uni")!.status).toBe("ok"); + expect(await repo.readLessonMarkdown("uni", "l")).toBe("# Æble\n"); + expect(repo.resolvePath("uni", rel)).toContain("Æble notes.md"); + }); + + test("overlay wins over in-repo manifest with same id", async () => { + const d = await tmp(); + const lesson = " - { id: l, title: L, type: text, file: a.md }"; + await Bun.write(join(d, "repo/a.md"), "# A\n"); + await Bun.write(join(d, "repo/stcourse.yaml"), manifest("dup", "", lesson.replace("L,", "InRepo,"))); + await Bun.write(join(d, "overlays/dup/stcourse.yaml"), manifest("dup", `root: ${join(d, "repo")}\n`, lesson.replace("L,", "Overlay,"))); + const all = await loadAll([d]); + const dup = all.filter((c) => c.id === "dup"); + expect(dup).toHaveLength(1); + expect(dup[0]!.manifestPath).toBe(join(d, "overlays/dup/stcourse.yaml")); + const warn = dup[0]!.diagnostics.find((x) => x.level === "warning"); + expect(warn!.path).toBe(join(d, "repo/stcourse.yaml")); + }); + + test("overlay wins regardless of discovery order", async () => { + const d = await tmp(); + const lesson = " - { id: l, title: L, type: text, file: a.md }"; + await Bun.write(join(d, "a-repo/a.md"), "# A\n"); + await Bun.write(join(d, "a-repo/stcourse.yaml"), manifest("dup", "", lesson)); + await Bun.write(join(d, "z-overlay/stcourse.yaml"), manifest("dup", `root: ${join(d, "a-repo")}\n`, lesson)); + const all = await loadAll([d]); + expect(all).toHaveLength(1); + expect(all[0]!.manifestPath).toBe(join(d, "z-overlay/stcourse.yaml")); + }); +}); + +describe("resolvePath", () => { + test("rejects ../, absolute paths and symlink escape", async () => { + const d = await tmp(); + await Bun.write(join(d, "root/a.md"), "# A\n"); + await Bun.write(join(d, "outside.txt"), "secret"); + await symlink("/etc", join(d, "root/etc-link")); + await symlink(join(d, "outside.txt"), join(d, "root/out-link.txt")); + await Bun.write(join(d, "root/stcourse.yaml"), manifest("r", "", " - { id: l, title: L, type: text, file: a.md }")); + const repo = await createCourseRepository([join(d, "root")]); + expect(repo.resolvePath("r", "a.md")).not.toBeNull(); + expect(repo.resolvePath("r", "../outside.txt")).toBeNull(); + expect(repo.resolvePath("r", join(d, "outside.txt"))).toBeNull(); + expect(repo.resolvePath("r", "etc-link/passwd")).toBeNull(); + expect(repo.resolvePath("r", "etc-link")).toBeNull(); + expect(repo.resolvePath("r", "out-link.txt")).toBeNull(); + expect(repo.resolvePath("r", "missing.md")).toBeNull(); + expect(repo.resolvePath("nope", "a.md")).toBeNull(); + }); +}); diff --git a/packages/course-format/test/markdown.test.ts b/packages/course-format/test/markdown.test.ts new file mode 100644 index 0000000..888d53d --- /dev/null +++ b/packages/course-format/test/markdown.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, test } from "bun:test"; +import { extractHints, extractSection, slugify } from "../src/markdown"; + +describe("slugify", () => { + test("follows GitHub's algorithm", () => { + expect(slugify("Exercise 3.1 — `move`")).toBe("exercise-31--move"); + expect(slugify("Why this module")).toBe("why-this-module"); + expect(slugify("Rules as functions `State → State`")).toBe("rules-as-functions-state--state"); + expect(slugify("**Bold** and [a link](http://x.y)")).toBe("bold-and-a-link"); + }); +}); + +const sample = `# Top + +intro + +## First + +one + +### Middle + +middle body + +\`\`\`sh +# not a heading +\`\`\` + +#### Deeper + +deep body + +### Sibling + +sibling body + +## Last + +end +`; + +describe("extractSection", () => { + test("returns only the middle section, including deeper headings", () => { + const s = extractSection(sample, "middle"); + expect(s).not.toBeNull(); + expect(s!.startsWith("### Middle")).toBe(true); + expect(s).toContain("# not a heading"); + expect(s).toContain("deep body"); + expect(s).not.toContain("sibling body"); + expect(s).not.toContain("one"); + }); + test("returns null for an unknown anchor", () => { + expect(extractSection(sample, "nope")).toBeNull(); + }); + test("a section runs to the end of file when nothing follows", () => { + expect(extractSection(sample, "last")).toBe("## Last\n\nend"); + }); +}); + +describe("extractHints", () => { + const md = `## Hints + +
Exercise 3.1 (move) — nudge + +Think about direction. + +
+ +
Exercise 3.1 (move) — stronger hint + +Add the delta. + +
+ +
Exercise 3.2 (inBounds) — nudge + +Other. + +
+`; + test("returns matching blocks in order with trimmed labels", () => { + const h = extractHints(md, "Exercise 3.1 (move)"); + expect(h.map((x) => x.label)).toEqual(["nudge", "stronger hint"]); + expect(h[0]!.body).toBe("Think about direction."); + }); + test("returns [] when nothing matches", () => { + expect(extractHints(md, "Exercise 9.9")).toEqual([]); + }); +}); From b8c65626f9096ccc6e04327d84f91ba5a83a52c7 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 02:52:24 +0100 Subject: [PATCH 06/14] feat: overlay manifests for the two reference courses Co-Authored-By: Claude Opus 5.5 --- overlays/pure-snake/stcourse.yaml | 558 ++++++++++++++++++ overlays/systemic-design/stcourse.yaml | 110 ++++ packages/course-format/test/reference.test.ts | 32 + 3 files changed, 700 insertions(+) create mode 100644 overlays/pure-snake/stcourse.yaml create mode 100644 overlays/systemic-design/stcourse.yaml create mode 100644 packages/course-format/test/reference.test.ts diff --git a/overlays/pure-snake/stcourse.yaml b/overlays/pure-snake/stcourse.yaml new file mode 100644 index 0000000..9f22b99 --- /dev/null +++ b/overlays/pure-snake/stcourse.yaml @@ -0,0 +1,558 @@ +schema: 1 +id: pure-snake +title: Pure Snake +pitch: Build Snake as pure functions, then wire it to the world with IO and event streams, in JavaScript, Scala 3 or F#. +visibility: public +root: /home/user/functional-programming-course +tracks: + - { id: js, label: JavaScript } + - { id: scala, label: Scala 3 } + - { id: fsharp, label: F# } +mentor: MENTOR.md +source: { kind: authored } +modules: + - id: m00 + title: "Setup and how to use this course" + lessons: + - { id: m00-text, title: "Setup and how to use this course", type: text, file: "course/00-setup.md" } + - id: m00-ex-green-lights + title: "Exercise 0.1 — Green lights" + type: exercise + file: "course/00-setup.md" + anchor: exercise-01--green-lights + hints: { file: "course/00-setup.md", match: "Exercise 0.1" } + localCommand: + js: "cd js && node --test \"test/m00-*.test.js\"" + scala: "cd scala && ./test.sh M00" + fsharp: "cd fsharp && ./test.sh M00" + - id: m00-ex-read-a-red-test + title: "Exercise 0.2 — Read a red test" + type: exercise + file: "course/00-setup.md" + anchor: exercise-02--read-a-red-test + hints: { file: "course/00-setup.md", match: "Exercise 0.2" } + localCommand: + js: "cd js && node --test \"test/m00-*.test.js\"" + scala: "cd scala && ./test.sh M00" + fsharp: "cd fsharp && ./test.sh M00" + - id: m00-ex-break-the-purity-audit-on-purpose + title: "Exercise 0.3 — Break the purity audit on purpose" + type: exercise + file: "course/00-setup.md" + anchor: exercise-03--break-the-purity-audit-on-purpose + localCommand: + js: "cd js && node --test \"test/m00-*.test.js\"" + scala: "cd scala && ./test.sh M00" + fsharp: "cd fsharp && ./test.sh M00" + - id: m01 + title: "Purity and immutability" + lessons: + - { id: m01-text, title: "Purity and immutability", type: text, file: "course/01-purity-and-immutability.md" } + - id: m01-ex-range + title: "Exercise 1.1 — `range`" + type: exercise + file: "course/01-purity-and-immutability.md" + anchor: exercise-11--range + hints: { file: "course/01-purity-and-immutability.md", match: "Exercise 1.1 (range)" } + localCommand: + js: "cd js && node --test \"test/m01-*.test.js\"" + scala: "cd scala && ./test.sh M01" + fsharp: "cd fsharp && ./test.sh M01" + - id: m01-ex-droplast + title: "Exercise 1.2 — `dropLast`" + type: exercise + file: "course/01-purity-and-immutability.md" + anchor: exercise-12--droplast + hints: { file: "course/01-purity-and-immutability.md", match: "Exercise 1.2 (dropLast)" } + localCommand: + js: "cd js && node --test \"test/m01-*.test.js\"" + scala: "cd scala && ./test.sh M01" + fsharp: "cd fsharp && ./test.sh M01" + - id: m01-ex-contains + title: "Exercise 1.3 — `contains`" + type: exercise + file: "course/01-purity-and-immutability.md" + anchor: exercise-13--contains + hints: { file: "course/01-purity-and-immutability.md", match: "Exercise 1.3 (contains)" } + localCommand: + js: "cd js && node --test \"test/m01-*.test.js\"" + scala: "cd scala && ./test.sh M01" + fsharp: "cd fsharp && ./test.sh M01" + - id: m01-ex-pipe + title: "Exercise 1.4 — `pipe` (JS only)" + type: exercise + file: "course/01-purity-and-immutability.md" + anchor: exercise-14--pipe-js-only + hints: { file: "course/01-purity-and-immutability.md", match: "Exercise 1.4 (pipe)" } + localCommand: + js: "cd js && node --test \"test/m01-*.test.js\"" + scala: "cd scala && ./test.sh M01" + fsharp: "cd fsharp && ./test.sh M01" + - id: m01-ex-compose + title: "Exercise 1.5 — `compose` (JS only)" + type: exercise + file: "course/01-purity-and-immutability.md" + anchor: exercise-15--compose-js-only + hints: { file: "course/01-purity-and-immutability.md", match: "Exercise 1.5 (compose)" } + localCommand: + js: "cd js && node --test \"test/m01-*.test.js\"" + scala: "cd scala && ./test.sh M01" + fsharp: "cd fsharp && ./test.sh M01" + - id: m01-ex-deepfreeze + title: "Exercise 1.6 — `deepFreeze` (JS only)" + type: exercise + file: "course/01-purity-and-immutability.md" + anchor: exercise-16--deepfreeze-js-only + hints: { file: "course/01-purity-and-immutability.md", match: "Exercise 1.6 (deepFreeze)" } + localCommand: + js: "cd js && node --test \"test/m01-*.test.js\"" + scala: "cd scala && ./test.sh M01" + fsharp: "cd fsharp && ./test.sh M01" + - id: m02 + title: "The game as data" + lessons: + - { id: m02-text, title: "The game as data", type: text, file: "course/02-the-game-as-data.md" } + - id: m02-ex-your-own-design + title: "Exercise 2.0 — Your own design (paper)" + type: exercise + file: "course/02-the-game-as-data.md" + anchor: exercise-20--your-own-design-paper + localCommand: + js: "cd js && node --test \"test/m02-*.test.js\"" + scala: "cd scala && ./test.sh M02" + fsharp: "cd fsharp && ./test.sh M02" + - id: m02-ex-point + title: "Exercise 2.1 — `point` and `pointEquals` (JS)" + type: exercise + file: "course/02-the-game-as-data.md" + anchor: exercise-21--point-and-pointequals-js + hints: { file: "course/02-the-game-as-data.md", match: "Exercise 2.1 (pointEquals)" } + localCommand: + js: "cd js && node --test \"test/m02-*.test.js\"" + scala: "cd scala && ./test.sh M02" + fsharp: "cd fsharp && ./test.sh M02" + - id: m02-ex-delta + title: "Exercise 2.2 — `delta`" + type: exercise + file: "course/02-the-game-as-data.md" + anchor: exercise-22--delta + hints: { file: "course/02-the-game-as-data.md", match: "Exercises 2.2 and 2.3 (delta, opposite)" } + localCommand: + js: "cd js && node --test \"test/m02-*.test.js\"" + scala: "cd scala && ./test.sh M02" + fsharp: "cd fsharp && ./test.sh M02" + - id: m02-ex-opposite + title: "Exercise 2.3 — `opposite`" + type: exercise + file: "course/02-the-game-as-data.md" + anchor: exercise-23--opposite + hints: { file: "course/02-the-game-as-data.md", match: "Exercises 2.2 and 2.3 (delta, opposite)" } + localCommand: + js: "cd js && node --test \"test/m02-*.test.js\"" + scala: "cd scala && ./test.sh M02" + fsharp: "cd fsharp && ./test.sh M02" + - id: m02-ex-action + title: "Exercise 2.4 — `Action` (JS)" + type: exercise + file: "course/02-the-game-as-data.md" + anchor: exercise-24--action-js + hints: { file: "course/02-the-game-as-data.md", match: "Exercise 2.4 (Action)" } + localCommand: + js: "cd js && node --test \"test/m02-*.test.js\"" + scala: "cd scala && ./test.sh M02" + fsharp: "cd fsharp && ./test.sh M02" + - id: m02-ex-initialstate + title: "Exercise 2.5 — `initialState`" + type: exercise + file: "course/02-the-game-as-data.md" + anchor: exercise-25--initialstate + hints: { file: "course/02-the-game-as-data.md", match: "Exercise 2.5 (initialState)" } + localCommand: + js: "cd js && node --test \"test/m02-*.test.js\"" + scala: "cd scala && ./test.sh M02" + fsharp: "cd fsharp && ./test.sh M02" + - id: m03 + title: "Pure game rules" + lessons: + - { id: m03-text, title: "Pure game rules", type: text, file: "course/03-pure-game-rules.md" } + - id: m03-ex-move + title: "Exercise 3.1 — `move`" + type: exercise + file: "course/03-pure-game-rules.md" + anchor: exercise-31--move + hints: { file: "course/03-pure-game-rules.md", match: "Exercise 3.1 (move)" } + localCommand: + js: "cd js && node --test \"test/m03-*.test.js\"" + scala: "cd scala && ./test.sh M03" + fsharp: "cd fsharp && ./test.sh M03" + - id: m03-ex-inbounds + title: "Exercise 3.2 — `inBounds`" + type: exercise + file: "course/03-pure-game-rules.md" + anchor: exercise-32--inbounds + hints: { file: "course/03-pure-game-rules.md", match: "Exercise 3.2 (inBounds)" } + localCommand: + js: "cd js && node --test \"test/m03-*.test.js\"" + scala: "cd scala && ./test.sh M03" + fsharp: "cd fsharp && ./test.sh M03" + - id: m03-ex-turn + title: "Exercise 3.3 — `turn`" + type: exercise + file: "course/03-pure-game-rules.md" + anchor: exercise-33--turn + hints: { file: "course/03-pure-game-rules.md", match: "Exercise 3.3 (turn)" } + localCommand: + js: "cd js && node --test \"test/m03-*.test.js\"" + scala: "cd scala && ./test.sh M03" + fsharp: "cd fsharp && ./test.sh M03" + - id: m03-ex-advance + title: "Exercise 3.4 — `advance`" + type: exercise + file: "course/03-pure-game-rules.md" + anchor: exercise-34--advance + hints: { file: "course/03-pure-game-rules.md", match: "Exercise 3.4 (advance)" } + localCommand: + js: "cd js && node --test \"test/m03-*.test.js\"" + scala: "cd scala && ./test.sh M03" + fsharp: "cd fsharp && ./test.sh M03" + - id: m04 + title: "Randomness without side effects" + lessons: + - { id: m04-text, title: "Randomness without side effects", type: text, file: "course/04-randomness-without-side-effects.md" } + - id: m04-ex-nextuint32 + title: "Exercise 4.1 — `nextUint32`" + type: exercise + file: "course/04-randomness-without-side-effects.md" + anchor: exercise-41--nextuint32 + hints: { file: "course/04-randomness-without-side-effects.md", match: "Exercise 4.1 (nextUint32)" } + localCommand: + js: "cd js && node --test \"test/m04-*.test.js\"" + scala: "cd scala && ./test.sh M04" + fsharp: "cd fsharp && ./test.sh M04" + - id: m04-ex-pure + title: "Exercise 4.2 — `pure`, `map`, `flatMap`, `run`" + type: exercise + file: "course/04-randomness-without-side-effects.md" + anchor: exercise-42--pure-map-flatmap-run + hints: { file: "course/04-randomness-without-side-effects.md", match: "Exercise 4.2 (pure, map, flatMap, run)" } + localCommand: + js: "cd js && node --test \"test/m04-*.test.js\"" + scala: "cd scala && ./test.sh M04" + fsharp: "cd fsharp && ./test.sh M04" + - id: m04-ex-intbelow + title: "Exercise 4.3 — `intBelow`" + type: exercise + file: "course/04-randomness-without-side-effects.md" + anchor: exercise-43--intbelow + hints: { file: "course/04-randomness-without-side-effects.md", match: "Exercise 4.3 (intBelow)" } + localCommand: + js: "cd js && node --test \"test/m04-*.test.js\"" + scala: "cd scala && ./test.sh M04" + fsharp: "cd fsharp && ./test.sh M04" + - id: m04-ex-freecells + title: "Exercise 4.4 — `freeCells`" + type: exercise + file: "course/04-randomness-without-side-effects.md" + anchor: exercise-44--freecells + hints: { file: "course/04-randomness-without-side-effects.md", match: "Exercise 4.4 (freeCells)" } + localCommand: + js: "cd js && node --test \"test/m04-*.test.js\"" + scala: "cd scala && ./test.sh M04" + fsharp: "cd fsharp && ./test.sh M04" + - id: m04-ex-spawnapple + title: "Exercise 4.5 — `spawnApple`" + type: exercise + file: "course/04-randomness-without-side-effects.md" + anchor: exercise-45--spawnapple + hints: { file: "course/04-randomness-without-side-effects.md", match: "Exercise 4.5 (spawnApple)" } + localCommand: + js: "cd js && node --test \"test/m04-*.test.js\"" + scala: "cd scala && ./test.sh M04" + fsharp: "cd fsharp && ./test.sh M04" + - id: m04-ex-tick + title: "Exercise 4.6 — `tick` and `newGame`" + type: exercise + file: "course/04-randomness-without-side-effects.md" + anchor: exercise-46--tick-and-newgame + hints: { file: "course/04-randomness-without-side-effects.md", match: "Exercise 4.6 (tick, newGame)" } + localCommand: + js: "cd js && node --test \"test/m04-*.test.js\"" + scala: "cd scala && ./test.sh M04" + fsharp: "cd fsharp && ./test.sh M04" + - id: m05 + title: "Folding time" + lessons: + - { id: m05-text, title: "Folding time", type: text, file: "course/05-folding-time.md" } + - id: m05-ex-update + title: "Exercise 5.1 — `update`" + type: exercise + file: "course/05-folding-time.md" + anchor: exercise-51--update + hints: { file: "course/05-folding-time.md", match: "Exercise 5.1 (update)" } + localCommand: + js: "cd js && node --test \"test/m05-*.test.js\"" + scala: "cd scala && ./test.sh M05" + fsharp: "cd fsharp && ./test.sh M05" + - id: m05-ex-replay + title: "Exercise 5.2 — `replay`" + type: exercise + file: "course/05-folding-time.md" + anchor: exercise-52--replay + hints: { file: "course/05-folding-time.md", match: "Exercise 5.2 (replay)" } + localCommand: + js: "cd js && node --test \"test/m05-*.test.js\"" + scala: "cd scala && ./test.sh M05" + fsharp: "cd fsharp && ./test.sh M05" + - id: m05-ex-history + title: "Exercise 5.3 — `history`" + type: exercise + file: "course/05-folding-time.md" + anchor: exercise-53--history + hints: { file: "course/05-folding-time.md", match: "Exercise 5.3 (history)" } + localCommand: + js: "cd js && node --test \"test/m05-*.test.js\"" + scala: "cd scala && ./test.sh M05" + fsharp: "cd fsharp && ./test.sh M05" + - id: m06 + title: "Rendering as data" + lessons: + - { id: m06-text, title: "Rendering as data", type: text, file: "course/06-rendering-as-data.md" } + - id: m06-ex-view + title: "Exercise 6.1 — `view`" + type: exercise + file: "course/06-rendering-as-data.md" + anchor: exercise-61--view + hints: { file: "course/06-rendering-as-data.md", match: "Exercise 6.1" } + localCommand: + js: "cd js && node --test \"test/m06-*.test.js\"" + scala: "cd scala && ./test.sh M06" + fsharp: "cd fsharp && ./test.sh M06" + - id: m06-ex-a-second-interpreter + title: "Exercise 6.2 (optional, untested) — a second interpreter" + type: exercise + file: "course/06-rendering-as-data.md" + anchor: exercise-62-optional-untested--a-second-interpreter + localCommand: + js: "cd js && node --test \"test/m06-*.test.js\"" + scala: "cd scala && ./test.sh M06" + fsharp: "cd fsharp && ./test.sh M06" + - id: m07 + title: "The IO type" + lessons: + - { id: m07-text, title: "The IO type", type: text, file: "course/07-the-io-type.md" } + - id: m07-ex-pure + title: "Exercise 7.1 — `pure` and `effect`" + type: exercise + file: "course/07-the-io-type.md" + anchor: exercise-71--pure-and-effect + hints: { file: "course/07-the-io-type.md", match: "Exercise 7.1" } + localCommand: + js: "cd js && node --test \"test/m07-*.test.js\"" + scala: "cd scala && ./test.sh M07" + fsharp: "cd fsharp && ./test.sh M07" + - id: m07-ex-map + title: "Exercise 7.2 — `map` and `flatMap`" + type: exercise + file: "course/07-the-io-type.md" + anchor: exercise-72--map-and-flatmap + hints: { file: "course/07-the-io-type.md", match: "Exercise 7.2" } + localCommand: + js: "cd js && node --test \"test/m07-*.test.js\"" + scala: "cd scala && ./test.sh M07" + fsharp: "cd fsharp && ./test.sh M07" + - id: m07-ex-sequence + title: "Exercise 7.3 — `sequence`, `draw`, `randomSeed`, `drawScene`" + type: exercise + file: "course/07-the-io-type.md" + anchor: exercise-73--sequence-draw-randomseed-drawscene + hints: { file: "course/07-the-io-type.md", match: "Exercise 7.3" } + localCommand: + js: "cd js && node --test \"test/m07-*.test.js\"" + scala: "cd scala && ./test.sh M07" + fsharp: "cd fsharp && ./test.sh M07" + - id: m07-ex-trace + title: "Exercise 7.4 — `trace`, the pure interpreter" + type: exercise + file: "course/07-the-io-type.md" + anchor: exercise-74--trace-the-pure-interpreter + hints: { file: "course/07-the-io-type.md", match: "Exercise 7.4" } + localCommand: + js: "cd js && node --test \"test/m07-*.test.js\"" + scala: "cd scala && ./test.sh M07" + fsharp: "cd fsharp && ./test.sh M07" + - id: m08 + title: "Event streams" + lessons: + - { id: m08-text, title: "Event streams", type: text, file: "course/08-event-streams.md" } + - id: m08-ex-run + title: "Exercise 8.1 — `run`" + type: exercise + file: "course/08-event-streams.md" + anchor: exercise-81--run + hints: { file: "course/08-event-streams.md", match: "Exercise 8.1" } + localCommand: + js: "cd js && node --test \"test/m08-*.test.js\"" + scala: "cd scala && ./test.sh M08" + fsharp: "cd fsharp && ./test.sh M08" + - id: m08-ex-keydowns + title: "Exercise 8.2 — sources: `keyDowns`, `keyUps`, `interval`" + type: exercise + file: "course/08-event-streams.md" + anchor: exercise-82--sources-keydowns-keyups-interval + hints: { file: "course/08-event-streams.md", match: "Exercise 8.2" } + localCommand: + js: "cd js && node --test \"test/m08-*.test.js\"" + scala: "cd scala && ./test.sh M08" + fsharp: "cd fsharp && ./test.sh M08" + - id: m08-ex-map + title: "Exercise 8.3 — `map`, `filter`, `filterMap`" + type: exercise + file: "course/08-event-streams.md" + anchor: exercise-83--map-filter-filtermap + hints: { file: "course/08-event-streams.md", match: "Exercise 8.3 / 8.4" } + localCommand: + js: "cd js && node --test \"test/m08-*.test.js\"" + scala: "cd scala && ./test.sh M08" + fsharp: "cd fsharp && ./test.sh M08" + - id: m08-ex-merge + title: "Exercise 8.4 — `merge`, `scan`, `startWith`" + type: exercise + file: "course/08-event-streams.md" + anchor: exercise-84--merge-scan-startwith + hints: { file: "course/08-event-streams.md", match: "Exercise 8.4" } + localCommand: + js: "cd js && node --test \"test/m08-*.test.js\"" + scala: "cd scala && ./test.sh M08" + fsharp: "cd fsharp && ./test.sh M08" + - id: m09 + title: "Wiring it together" + lessons: + - { id: m09-text, title: "Wiring it together", type: text, file: "course/09-wiring-it-together.md" } + - id: m09-ex-keytoaction + title: "Exercise 9.1 — `keyToAction`" + type: exercise + file: "course/09-wiring-it-together.md" + anchor: exercise-91--keytoaction + hints: { file: "course/09-wiring-it-together.md", match: "Exercise 9.1" } + localCommand: + js: "cd js && node --test \"test/m09-*.test.js\"" + scala: "cd scala && ./test.sh M09" + fsharp: "cd fsharp && ./test.sh M09" + - id: m09-ex-classicactions + title: "Exercise 9.2 — the app: `classicActions`, `states`, `render`, `main`" + type: exercise + file: "course/09-wiring-it-together.md" + anchor: exercise-92--the-app-classicactions-states-render-main + hints: { file: "course/09-wiring-it-together.md", match: "Exercise 9.2" } + localCommand: + js: "cd js && node --test \"test/m09-*.test.js\"" + scala: "cd scala && ./test.sh M09" + fsharp: "cd fsharp && ./test.sh M09" + - id: m09-ex-runio + title: "Exercise 9.3 — the runtime: `runIO` and `runApp`" + type: exercise + file: "course/09-wiring-it-together.md" + anchor: exercise-93--the-runtime-runio-and-runapp + hints: { file: "course/09-wiring-it-together.md", match: "Exercise 9.3" } + localCommand: + js: "cd js && node --test \"test/m09-*.test.js\"" + scala: "cd scala && ./test.sh M09" + fsharp: "cd fsharp && ./test.sh M09" + - id: m09-ex-browserplatform + title: "Exercise 9.4 (JS only) — `browserPlatform`" + type: exercise + file: "course/09-wiring-it-together.md" + anchor: exercise-94-js-only--browserplatform + localCommand: + js: "cd js && node --test \"test/m09-*.test.js\"" + scala: "cd scala && ./test.sh M09" + fsharp: "cd fsharp && ./test.sh M09" + - id: m10 + title: "Extensions, all pure" + lessons: + - { id: m10-text, title: "Extensions, all pure", type: text, file: "course/10-extensions.md" } + - id: m10-ex-movesevery + title: "Exercise 10.1 — `movesEvery`" + type: exercise + file: "course/10-extensions.md" + anchor: exercise-101--movesevery + localCommand: + js: "cd js && node --test \"test/m10-*.test.js\"" + scala: "cd scala && ./test.sh M10" + fsharp: "cd fsharp && ./test.sh M10" + - id: m10-ex-update + title: "Exercise 10.2 — `update`: `TogglePause`, `Restart`, `Frame`" + type: exercise + file: "course/10-extensions.md" + anchor: exercise-102--update-togglepause-restart-frame + hints: { file: "course/10-extensions.md", match: "Exercise 10.2" } + localCommand: + js: "cd js && node --test \"test/m10-*.test.js\"" + scala: "cd scala && ./test.sh M10" + fsharp: "cd fsharp && ./test.sh M10" + - id: m10-ex-two-more-keys + title: "Exercise 10.3 — two more keys" + type: exercise + file: "course/10-extensions.md" + anchor: exercise-103--two-more-keys + localCommand: + js: "cd js && node --test \"test/m10-*.test.js\"" + scala: "cd scala && ./test.sh M10" + fsharp: "cd fsharp && ./test.sh M10" + - id: m10-ex-the-frame-clock + title: "Exercise 10.4 — the frame clock" + type: exercise + file: "course/10-extensions.md" + anchor: exercise-104--the-frame-clock + hints: { file: "course/10-extensions.md", match: "Exercise 10.4" } + localCommand: + js: "cd js && node --test \"test/m10-*.test.js\"" + scala: "cd scala && ./test.sh M10" + fsharp: "cd fsharp && ./test.sh M10" + - id: m11 + title: "Capstone: Pong, by the method" + lessons: + - { id: m11-text, title: "Capstone: Pong, by the method", type: text, file: "course/11-capstone-pong.md" } + - id: m11-ex-model + title: "Exercise 11.1 — model" + type: exercise + file: "course/11-capstone-pong.md" + anchor: exercise-111--model + localCommand: + js: "cd js && node --test \"test/m11-*.test.js\"" + scala: "cd scala && ./test.sh M11" + fsharp: "cd fsharp && ./test.sh M11" + - id: m11-ex-rules + title: "Exercise 11.2 — rules" + type: exercise + file: "course/11-capstone-pong.md" + anchor: exercise-112--rules + hints: { file: "course/11-capstone-pong.md", match: "Exercise 11.2" } + localCommand: + js: "cd js && node --test \"test/m11-*.test.js\"" + scala: "cd scala && ./test.sh M11" + fsharp: "cd fsharp && ./test.sh M11" + - id: m11-ex-view + title: "Exercise 11.3 — view" + type: exercise + file: "course/11-capstone-pong.md" + anchor: exercise-113--view + localCommand: + js: "cd js && node --test \"test/m11-*.test.js\"" + scala: "cd scala && ./test.sh M11" + fsharp: "cd fsharp && ./test.sh M11" + - id: m11-ex-keys-and-wiring + title: "Exercise 11.4 — keys and wiring" + type: exercise + file: "course/11-capstone-pong.md" + anchor: exercise-114--keys-and-wiring + hints: { file: "course/11-capstone-pong.md", match: "Exercise 11.4" } + localCommand: + js: "cd js && node --test \"test/m11-*.test.js\"" + scala: "cd scala && ./test.sh M11" + fsharp: "cd fsharp && ./test.sh M11" + - id: ref + title: "Method and reference" + lessons: + - { id: ref-method, title: "The method", type: text, file: course/method.md } + - { id: ref-reference, title: "Reference", type: text, file: course/reference.md } diff --git a/overlays/systemic-design/stcourse.yaml b/overlays/systemic-design/stcourse.yaml new file mode 100644 index 0000000..8b88222 --- /dev/null +++ b/overlays/systemic-design/stcourse.yaml @@ -0,0 +1,110 @@ +schema: 1 +id: systemic-design +title: Systemic Design +pitch: Learn to build a rule-driven game engine by writing the systems that make its rules compose. +visibility: public +gating: sequential +root: /home/user/systemic-design-course +tracks: + - { id: rust, label: Rust } + - { id: ts, label: TypeScript } +mentor: mentor/SKILL.md +source: { kind: authored } +modules: + - id: m00 + title: "The Rewrite Trap" + lessons: + - id: m00-lesson + title: "The Rewrite Trap" + type: text + file: "course/00-rewrite-trap/lesson.md" + - id: m01 + title: "Handles and order of play" + lessons: + - id: m01-lesson + title: "Handles and order of play" + type: text + file: "course/01-handles/lesson.md" + localCommand: "node tools/start-module.mjs 01 " + - { id: m01-scenarios, title: Scenarios, type: text, file: "course/01-handles/scenarios.md" } + - id: m02 + title: "The action queue, depth-first" + lessons: + - id: m02-lesson + title: "The action queue, depth-first" + type: text + file: "course/02-action-queue/lesson.md" + localCommand: "node tools/start-module.mjs 02 " + - { id: m02-scenarios, title: Scenarios, type: text, file: "course/02-action-queue/scenarios.md" } + - id: m03 + title: "Deferred death" + lessons: + - id: m03-lesson + title: "Deferred death" + type: text + file: "course/03-death-step/lesson.md" + localCommand: "node tools/start-module.mjs 03 " + - { id: m03-scenarios, title: Scenarios, type: text, file: "course/03-death-step/scenarios.md" } + - id: m04 + title: "Interceptors and \"trigger twice\"" + lessons: + - id: m04-lesson + title: "Interceptors and \"trigger twice\"" + type: text + file: "course/04-interceptors/lesson.md" + localCommand: "node tools/start-module.mjs 04 " + - { id: m04-scenarios, title: Scenarios, type: text, file: "course/04-interceptors/scenarios.md" } + - id: m05 + title: "Behavior as data and Assemble" + lessons: + - id: m05-lesson + title: "Behavior as data and Assemble" + type: text + file: "course/05-assemble/lesson.md" + localCommand: "node tools/start-module.mjs 05 " + - { id: m05-scenarios, title: Scenarios, type: text, file: "course/05-assemble/scenarios.md" } + - id: m06 + title: "Grid, lexer and parser" + lessons: + - id: m06-lesson + title: "Grid, lexer and parser" + type: text + file: "course/06-parser/lesson.md" + localCommand: "node tools/start-module.mjs 06 " + - { id: m06-scenarios, title: Scenarios, type: text, file: "course/06-parser/scenarios.md" } + - id: m07 + title: "Resolving rules: NOT, identity, meta-nouns" + lessons: + - id: m07-lesson + title: "Resolving rules: NOT, identity, meta-nouns" + type: text + file: "course/07-rule-resolution/lesson.md" + localCommand: "node tools/start-module.mjs 07 " + - { id: m07-scenarios, title: Scenarios, type: text, file: "course/07-rule-resolution/scenarios.md" } + - id: m08 + title: "Push chains: validate, then commit" + lessons: + - id: m08-lesson + title: "Push chains: validate, then commit" + type: text + file: "course/08-push-chains/lesson.md" + localCommand: "node tools/start-module.mjs 08 " + - { id: m08-scenarios, title: Scenarios, type: text, file: "course/08-push-chains/scenarios.md" } + - id: m09 + title: "The turn pipeline" + lessons: + - id: m09-lesson + title: "The turn pipeline" + type: text + file: "course/09-turn-pipeline/lesson.md" + localCommand: "node tools/start-module.mjs 09 " + - { id: m09-scenarios, title: Scenarios, type: text, file: "course/09-turn-pipeline/scenarios.md" } + - id: m10 + title: "SpellGrid" + lessons: + - id: m10-lesson + title: "SpellGrid" + type: text + file: "course/10-spellgrid/lesson.md" + localCommand: "node tools/start-module.mjs 10 " + - { id: m10-scenarios, title: Scenarios, type: text, file: "course/10-spellgrid/scenarios.md" } diff --git a/packages/course-format/test/reference.test.ts b/packages/course-format/test/reference.test.ts new file mode 100644 index 0000000..61d9f33 --- /dev/null +++ b/packages/course-format/test/reference.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, test } from "bun:test"; +import { existsSync } from "node:fs"; +import { resolve } from "node:path"; +import { createCourseRepository, extractHints } from "../src/index"; + +const overlays = resolve(import.meta.dir, "../../../overlays"); +const snakeRoot = "/home/user/functional-programming-course"; +const systemicRoot = "/home/user/systemic-design-course"; + +describe("reference courses", () => { + test.skipIf(!existsSync(snakeRoot))("pure-snake loads cleanly", async () => { + const repo = await createCourseRepository([overlays]); + const c = repo.get("pure-snake")!; + expect(c.diagnostics.filter((d) => d.level === "error")).toEqual([]); + expect(c.status).toBe("ok"); + expect(c.manifest!.modules).toHaveLength(13); + expect(c.lessonIndex.has("m03-ex-move")).toBe(true); + const hints = c.lessonIndex.get("m03-ex-move")!.lesson.hints!; + const md = await Bun.file(repo.resolvePath("pure-snake", hints.file)!).text(); + expect(extractHints(md, hints.match)).toHaveLength(3); + expect(await repo.readLessonMarkdown("pure-snake", "m03-ex-move")).toStartWith("### Exercise 3.1"); + }); + + test.skipIf(!existsSync(systemicRoot))("systemic-design loads cleanly", async () => { + const repo = await createCourseRepository([overlays]); + const c = repo.get("systemic-design")!; + expect(c.diagnostics.filter((d) => d.level === "error")).toEqual([]); + expect(c.status).toBe("ok"); + expect(c.manifest!.modules).toHaveLength(11); + expect(c.manifest!.gating).toBe("sequential"); + }); +}); From a82ab18bee76eb381135ba4879e8733646cd3390 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 02:54:23 +0100 Subject: [PATCH 07/14] fix(course-format): directories are not lesson files; a failing course never rejects loadAll Co-Authored-By: Claude Opus 5.5 --- packages/course-format/src/load.ts | 37 ++++++++++++++++++++---- packages/course-format/test/load.test.ts | 28 ++++++++++++++++++ 2 files changed, 59 insertions(+), 6 deletions(-) diff --git a/packages/course-format/src/load.ts b/packages/course-format/src/load.ts index b0e3c57..32065f6 100644 --- a/packages/course-format/src/load.ts +++ b/packages/course-format/src/load.ts @@ -1,5 +1,5 @@ import { readdir, readFile, realpath } from "node:fs/promises"; -import { realpathSync } from "node:fs"; +import { realpathSync, statSync } from "node:fs"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { extractHints, extractSection } from "./markdown"; import { parseManifest, type Lesson, type Manifest } from "./schema"; @@ -67,8 +67,27 @@ export async function discoverManifests(courseDirs: string[]): Promise return found; } +/** Never throws: an unexpected failure becomes an error diagnostic on that course only. */ export async function loadCourse(manifestPath: string): Promise { manifestPath = resolve(manifestPath); + const dir = dirname(manifestPath); + try { + return await loadCourseUnsafe(manifestPath); + } catch (e) { + const id = basename(dir); + return { + id, + manifestPath, + root: dir, + manifest: null, + status: "error", + diagnostics: [{ level: "error", courseId: id, path: manifestPath, message: `unexpected error loading course: ${(e as Error).message}` }], + lessonIndex: new Map(), + }; + } +} + +async function loadCourseUnsafe(manifestPath: string): Promise { const dir = dirname(manifestPath); const diagnostics: Diagnostic[] = []; const course: LoadedCourse = { @@ -118,10 +137,16 @@ export async function loadCourse(manifestPath: string): Promise { if (!mdCache.has(abs)) mdCache.set(abs, await Bun.file(abs).text()); return mdCache.get(abs)!; }; - /** Reports an error and returns false when `rel` does not exist inside the root. */ - const requireFile = (rel: string, what: string, lessonId?: string): boolean => { - if (resolveInside(root, rel)) return true; - err(`${what} not found: ${rel}`, { lessonId, path: rel }); + /** Reports an error and returns false when `rel` is not a regular file (or directory, if asked) inside the root. */ + const requireFile = (rel: string, what: string, lessonId?: string, dir = false): boolean => { + const abs = resolveInside(root, rel); + if (!abs) { + err(`${what} not found: ${rel}`, { lessonId, path: rel }); + return false; + } + const st = statSync(abs); + if (dir ? st.isDirectory() : st.isFile()) return true; + err(`${what} is not a ${dir ? "directory" : "regular file"}: ${rel}`, { lessonId, path: rel }); return false; }; @@ -131,7 +156,7 @@ export async function loadCourse(manifestPath: string): Promise { for (const a of manifest.attachments ?? []) requireFile(a.file, "attachment"); for (const mod of manifest.modules) { - if (mod.code) requireFile(mod.code.dir, `module "${mod.id}" code dir`); + if (mod.code) requireFile(mod.code.dir, `module "${mod.id}" code dir`, undefined, true); for (const l of mod.lessons) { const id = l.id; let fileOk = true; diff --git a/packages/course-format/test/load.test.ts b/packages/course-format/test/load.test.ts index a93f3d3..ad14892 100644 --- a/packages/course-format/test/load.test.ts +++ b/packages/course-format/test/load.test.ts @@ -80,6 +80,34 @@ describe("overlays and errors", () => { expect(errs[2]!.message).toContain("Exercise 1"); }); + test("lesson file that is a directory gives a diagnostic", async () => { + const d = await tmp(); + await Bun.write(join(d, "adir/x.md"), "# X\n"); + await Bun.write(join(d, "stcourse.yaml"), manifest("dirs", "", " - { id: as-file, title: L, type: text, file: adir }")); + const c = await loadCourse(join(d, "stcourse.yaml")); + expect(c.status).toBe("error"); + const e = c.diagnostics.filter((x) => x.level === "error"); + expect(e).toHaveLength(1); + expect(e[0]!.lessonId).toBe("as-file"); + expect(e[0]!.path).toBe("adir"); + }); + + test("one throwing course does not break loadAll", async () => { + const d = await tmp(); + await Bun.write(join(d, "bad/adir/x.md"), "# X\n"); + await Bun.write(join(d, "bad/a.md"), "# A\n## Sec\n"); + await Bun.write( + join(d, "bad/stcourse.yaml"), + manifest("bad", "", " - { id: h, title: L, type: exercise, file: a.md, hints: { file: adir, match: 'E' } }"), + ); + await Bun.write(join(d, "good/a.md"), "# A\n"); + await Bun.write(join(d, "good/stcourse.yaml"), manifest("good", "", " - { id: l, title: L, type: text, file: a.md }")); + const all = await loadAll([d]); + expect(all.map((c) => c.id).sort()).toEqual(["bad", "good"]); + expect(all.find((c) => c.id === "bad")!.status).toBe("error"); + expect(all.find((c) => c.id === "good")!.status).toBe("ok"); + }); + test("invalid manifest gives an error course and does not throw", async () => { const d = await tmp(); await Bun.write(join(d, "stcourse.yaml"), "schema: 2\nid: x\n"); From f71a31a5f157d13403138793997e8c9a277040b2 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 02:55:38 +0100 Subject: [PATCH 08/14] fix(course-format): validate anchor file via requireFile; real throw test for loadCourse catch Co-Authored-By: Claude Opus 5.5 --- packages/course-format/src/load.ts | 11 ++++++- packages/course-format/test/load.test.ts | 40 +++++++++++++++++------- 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/packages/course-format/src/load.ts b/packages/course-format/src/load.ts index 32065f6..579d6ee 100644 --- a/packages/course-format/src/load.ts +++ b/packages/course-format/src/load.ts @@ -138,7 +138,16 @@ async function loadCourseUnsafe(manifestPath: string): Promise { return mdCache.get(abs)!; }; /** Reports an error and returns false when `rel` is not a regular file (or directory, if asked) inside the root. */ + const checked = new Map(); // one diagnostic per (lesson, path) const requireFile = (rel: string, what: string, lessonId?: string, dir = false): boolean => { + const key = `${lessonId ?? ""}\0${rel}\0${dir}`; + const prior = checked.get(key); + if (prior !== undefined) return prior; + const ok = checkFile(rel, what, lessonId, dir); + checked.set(key, ok); + return ok; + }; + const checkFile = (rel: string, what: string, lessonId: string | undefined, dir: boolean): boolean => { const abs = resolveInside(root, rel); if (!abs) { err(`${what} not found: ${rel}`, { lessonId, path: rel }); @@ -174,7 +183,7 @@ async function loadCourseUnsafe(manifestPath: string): Promise { const file = l.file ?? l.hints?.file; if (!file) { err(`anchor "${l.anchor}" given but the lesson has no file`, { lessonId: id }); - } else if (fileOk) { + } else if (fileOk && requireFile(file, l.file ? "lesson file" : "hints file", id)) { const md = await readMd(file); if (md !== null && extractSection(md, l.anchor) === null) { err(`anchor "${l.anchor}" not found in ${file}`, { lessonId: id, path: file }); diff --git a/packages/course-format/test/load.test.ts b/packages/course-format/test/load.test.ts index ad14892..2a8c0d6 100644 --- a/packages/course-format/test/load.test.ts +++ b/packages/course-format/test/load.test.ts @@ -1,5 +1,5 @@ import { afterAll, describe, expect, test } from "bun:test"; -import { mkdtemp, rm, symlink } from "node:fs/promises"; +import { chmod, mkdtemp, rm, symlink } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { createCourseRepository, discoverManifests, loadAll, loadCourse } from "../src/index"; @@ -92,20 +92,38 @@ describe("overlays and errors", () => { expect(e[0]!.path).toBe("adir"); }); - test("one throwing course does not break loadAll", async () => { + test("anchor resolved through a hints.file directory (no lesson file) gives one lesson diagnostic and loading continues", async () => { + const d = await tmp(); + await Bun.write(join(d, "adir/x.md"), "# X\n"); + const lessons = [ + " - { id: via-hints, title: L, type: exercise, anchor: sec, hints: { file: adir, match: 'E' } }", + " - { id: after, title: L, type: text, file: missing.md }", + ].join("\n"); + await Bun.write(join(d, "stcourse.yaml"), manifest("dirs2", "", lessons)); + const c = await loadCourse(join(d, "stcourse.yaml")); + const e = c.diagnostics.filter((x) => x.level === "error"); + expect(e.map((x) => x.lessonId)).toEqual(["via-hints", "after"]); + expect(e[0]!.path).toBe("adir"); + }); + + // An unreadable file passes requireFile (it is a regular file) but Bun.file().text() rejects. + test.skipIf(process.getuid?.() === 0)("one throwing course does not break loadAll", async () => { const d = await tmp(); - await Bun.write(join(d, "bad/adir/x.md"), "# X\n"); await Bun.write(join(d, "bad/a.md"), "# A\n## Sec\n"); - await Bun.write( - join(d, "bad/stcourse.yaml"), - manifest("bad", "", " - { id: h, title: L, type: exercise, file: a.md, hints: { file: adir, match: 'E' } }"), - ); + await chmod(join(d, "bad/a.md"), 0o000); + await Bun.write(join(d, "bad/stcourse.yaml"), manifest("bad", "", " - { id: l, title: L, type: text, file: a.md, anchor: sec }")); await Bun.write(join(d, "good/a.md"), "# A\n"); await Bun.write(join(d, "good/stcourse.yaml"), manifest("good", "", " - { id: l, title: L, type: text, file: a.md }")); - const all = await loadAll([d]); - expect(all.map((c) => c.id).sort()).toEqual(["bad", "good"]); - expect(all.find((c) => c.id === "bad")!.status).toBe("error"); - expect(all.find((c) => c.id === "good")!.status).toBe("ok"); + try { + const all = await loadAll([d]); + expect(all.map((c) => c.id).sort()).toEqual(["bad", "good"]); + const bad = all.find((c) => c.id === "bad")!; + expect(bad.status).toBe("error"); + expect(bad.diagnostics[0]!.message).toContain("unexpected error"); + expect(all.find((c) => c.id === "good")!.status).toBe("ok"); + } finally { + await chmod(join(d, "bad/a.md"), 0o644); + } }); test("invalid manifest gives an error course and does not throw", async () => { From 738d813fb8ccea4973e65f6eb5c85af86a0ac48f Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 02:57:34 +0100 Subject: [PATCH 09/14] feat(db): Bun.SQL connection and portable migrations Co-Authored-By: Claude Opus 5.5 --- packages/contracts/src/server.ts | 3 +- packages/db/migrations/0001_init.sql | 68 ++++++++++++++++++++++++++++ packages/db/src/connect.ts | 21 +++++++++ packages/db/src/index.ts | 2 + packages/db/src/migrate.ts | 27 +++++++++++ packages/db/test/helpers.ts | 28 ++++++++++++ packages/db/test/migrate.test.ts | 32 +++++++++++++ scripts/test-pg.sh | 14 ++++++ 8 files changed, 193 insertions(+), 2 deletions(-) create mode 100644 packages/db/migrations/0001_init.sql create mode 100644 packages/db/src/connect.ts create mode 100644 packages/db/src/index.ts create mode 100644 packages/db/src/migrate.ts create mode 100644 packages/db/test/helpers.ts create mode 100644 packages/db/test/migrate.test.ts create mode 100755 scripts/test-pg.sh diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 4dfd75f..1ac169e 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -14,8 +14,7 @@ export type JobStatus = "queued" | "running" | "done" | "failed"; export interface JobRecord { id: string; kind: string; status: JobStatus; progress: number; message: string | null; payload: unknown; result: unknown; error: string | null; createdAt: string; updatedAt: string } export interface JobQueue { enqueue(kind: string, payload: unknown): Promise; get(id: string): Promise; list(kind?: string): Promise } export interface AuthService { userFromRequest(req: Request): Promise } -// Placeholder until Task 7 (@stc/db) exists. -type Db = unknown; +import type { Db } from "@stc/db"; export interface ServerContext { config: AppConfig; db: Db; courses: CourseRepository; jobs: JobQueue; auth: AuthService; diff --git a/packages/db/migrations/0001_init.sql b/packages/db/migrations/0001_init.sql new file mode 100644 index 0000000..ade4751 --- /dev/null +++ b/packages/db/migrations/0001_init.sql @@ -0,0 +1,68 @@ +-- Portable SQL: TEXT ids and ISO-8601 timestamps, INTEGER booleans, TEXT JSON. +CREATE TABLE user_roles ( + user_id TEXT NOT NULL, role TEXT NOT NULL, + PRIMARY KEY (user_id, role) +); +CREATE TABLE groups (id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE); +CREATE TABLE group_members ( + group_id TEXT NOT NULL, user_id TEXT NOT NULL, + PRIMARY KEY (group_id, user_id) +); +CREATE TABLE course_authors ( + course_id TEXT NOT NULL, user_id TEXT NOT NULL, + PRIMARY KEY (course_id, user_id) +); +CREATE TABLE course_acl ( + course_id TEXT NOT NULL, + principal_type TEXT NOT NULL CHECK (principal_type IN ('user', 'group')), + principal_id TEXT NOT NULL, + PRIMARY KEY (course_id, principal_type, principal_id) +); +CREATE TABLE progress ( + user_id TEXT NOT NULL, course_id TEXT NOT NULL, lesson_id TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('not-started', 'in-progress', 'done')), + position_seconds REAL, + updated_at TEXT NOT NULL, + PRIMARY KEY (user_id, course_id, lesson_id) +); +CREATE TABLE notes ( + id TEXT PRIMARY KEY, user_id TEXT NOT NULL, course_id TEXT NOT NULL, lesson_id TEXT NOT NULL, + anchor_kind TEXT NOT NULL CHECK (anchor_kind IN ('none', 'video', 'slide')), + anchor_value TEXT, deck_id TEXT, + body TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL +); +CREATE INDEX notes_by_lesson ON notes (user_id, course_id, lesson_id); +CREATE TABLE exercise_attempts ( + user_id TEXT NOT NULL, course_id TEXT NOT NULL, lesson_id TEXT NOT NULL, track TEXT NOT NULL, + code TEXT NOT NULL, result_json TEXT, passed INTEGER NOT NULL, updated_at TEXT NOT NULL, + PRIMARY KEY (user_id, course_id, lesson_id, track) +); +CREATE TABLE user_api_keys ( + user_id TEXT NOT NULL, provider TEXT NOT NULL, ciphertext TEXT NOT NULL, created_at TEXT NOT NULL, + PRIMARY KEY (user_id, provider) +); +CREATE TABLE ai_settings ( + scope TEXT NOT NULL CHECK (scope IN ('server', 'user')), + owner_id TEXT NOT NULL, -- '' for server scope + mentor_off INTEGER NOT NULL, config_json TEXT NOT NULL, updated_at TEXT NOT NULL, + PRIMARY KEY (scope, owner_id) +); +CREATE TABLE ai_conversations ( + id TEXT PRIMARY KEY, user_id TEXT NOT NULL, course_id TEXT NOT NULL, title TEXT, created_at TEXT NOT NULL +); +CREATE TABLE ai_messages ( + id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, created_at TEXT NOT NULL +); +CREATE INDEX ai_messages_by_conversation ON ai_messages (conversation_id); +CREATE TABLE library_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL); +CREATE TABLE collections (id TEXT PRIMARY KEY, title TEXT NOT NULL, sort INTEGER NOT NULL); +CREATE TABLE collection_courses ( + collection_id TEXT NOT NULL, course_id TEXT NOT NULL, sort INTEGER NOT NULL, + PRIMARY KEY (collection_id, course_id) +); +CREATE TABLE jobs ( + id TEXT PRIMARY KEY, kind TEXT NOT NULL, status TEXT NOT NULL, progress REAL NOT NULL, + message TEXT, payload_json TEXT NOT NULL, result_json TEXT, error TEXT, + created_at TEXT NOT NULL, updated_at TEXT NOT NULL +); +CREATE INDEX jobs_by_status ON jobs (status); diff --git a/packages/db/src/connect.ts b/packages/db/src/connect.ts new file mode 100644 index 0000000..f30818a --- /dev/null +++ b/packages/db/src/connect.ts @@ -0,0 +1,21 @@ +import { mkdirSync } from "node:fs"; +import { dirname } from "node:path"; + +export type Db = { sql: Bun.SQL; dialect: "sqlite" | "postgres"; close(): Promise }; + +export async function connect(url: string): Promise { + if (url.startsWith("sqlite:")) { + const path = url.replace(/^sqlite:(\/\/)?/, ""); + if (path !== ":memory:" && path !== "") mkdirSync(dirname(path), { recursive: true }); + // A single connection keeps in-memory databases coherent and serialises writers. + const sql = new Bun.SQL(url, { max: 1 }); + await sql.unsafe("PRAGMA foreign_keys = ON"); + if (path !== ":memory:") await sql.unsafe("PRAGMA journal_mode = WAL"); + return { sql, dialect: "sqlite", close: () => sql.close() }; + } + if (url.startsWith("postgres:") || url.startsWith("postgresql:")) { + const sql = new Bun.SQL(url); + return { sql, dialect: "postgres", close: () => sql.close() }; + } + throw new Error(`Unsupported database URL (expected sqlite:// or postgres://): ${url}`); +} diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts new file mode 100644 index 0000000..3aaa0f0 --- /dev/null +++ b/packages/db/src/index.ts @@ -0,0 +1,2 @@ +export { connect, type Db } from "./connect"; +export { migrate } from "./migrate"; diff --git a/packages/db/src/migrate.ts b/packages/db/src/migrate.ts new file mode 100644 index 0000000..be5f38f --- /dev/null +++ b/packages/db/src/migrate.ts @@ -0,0 +1,27 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { Db } from "./connect"; + +const MIGRATIONS_DIR = join(import.meta.dir, "..", "migrations"); + +function statements(text: string): string[] { + const noComments = text.split("\n").filter((l) => !l.trim().startsWith("--")).join("\n"); + return noComments.split(";").map((s) => s.trim()).filter(Boolean); +} + +export async function migrate(db: Db): Promise { + await db.sql.unsafe("CREATE TABLE IF NOT EXISTS schema_migrations (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)"); + const done = new Set((await db.sql`SELECT name FROM schema_migrations`).map((r: { name: string }) => r.name)); + const files = readdirSync(MIGRATIONS_DIR).filter((f) => f.endsWith(".sql")).sort(); + const applied: string[] = []; + for (const name of files) { + if (done.has(name)) continue; + const stmts = statements(readFileSync(join(MIGRATIONS_DIR, name), "utf8")); + await db.sql.begin(async (tx) => { + for (const s of stmts) await tx.unsafe(s); + await tx`INSERT INTO schema_migrations (name, applied_at) VALUES (${name}, ${new Date().toISOString()})`; + }); + applied.push(name); + } + return applied; +} diff --git a/packages/db/test/helpers.ts b/packages/db/test/helpers.ts new file mode 100644 index 0000000..b162836 --- /dev/null +++ b/packages/db/test/helpers.ts @@ -0,0 +1,28 @@ +import { test } from "bun:test"; +import { connect, type Db } from "../src/connect"; +import { migrate } from "../src/migrate"; + +const PG = process.env.STC_TEST_PG_URL; + +/** Runs `fn` against a fresh migrated in-memory SQLite, and a fresh Postgres schema when STC_TEST_PG_URL is set. */ +export function forEachDb(name: string, fn: (db: Db) => Promise): void { + test(`${name} [sqlite]`, async () => { + const db = await connect("sqlite://:memory:"); + try { await migrate(db); await fn(db); } finally { await db.close(); } + }); + if (!PG) return; + test(`${name} [postgres]`, async () => { + const schema = `t_${Bun.randomUUIDv7().replaceAll("-", "")}`; + const admin = await connect(PG); + await admin.sql.unsafe(`CREATE SCHEMA ${schema}`); + const u = new URL(PG); + u.searchParams.set("options", `-c search_path=${schema}`); + const db = await connect(u.toString()); + try { await migrate(db); await fn(db); } + finally { + await db.close(); + await admin.sql.unsafe(`DROP SCHEMA ${schema} CASCADE`); + await admin.close(); + } + }); +} diff --git a/packages/db/test/migrate.test.ts b/packages/db/test/migrate.test.ts new file mode 100644 index 0000000..8619728 --- /dev/null +++ b/packages/db/test/migrate.test.ts @@ -0,0 +1,32 @@ +import { expect } from "bun:test"; +import { forEachDb } from "./helpers"; +import { migrate } from "../src/migrate"; + +forEachDb("applies 0001 once", async (db) => { + // helpers already migrated once; a second run applies nothing + expect(await migrate(db)).toEqual([]); + const rows = await db.sql`SELECT name FROM schema_migrations`; + expect(rows.map((r: { name: string }) => r.name)).toEqual(["0001_init.sql"]); +}); + +forEachDb("all tables exist", async (db) => { + const s = db.sql; + const t = "2026-01-01T00:00:00.000Z"; + const one = async (table: string, rows: Promise) => { await rows; expect((await s.unsafe(`SELECT COUNT(*) AS n FROM ${table}`))[0].n.toString()).toBe("1"); }; + await one("user_roles", s`INSERT INTO user_roles VALUES ('u','owner')`); + await one("groups", s`INSERT INTO groups VALUES ('g','G')`); + await one("group_members", s`INSERT INTO group_members VALUES ('g','u')`); + await one("course_authors", s`INSERT INTO course_authors VALUES ('c','u')`); + await one("course_acl", s`INSERT INTO course_acl VALUES ('c','user','u')`); + await one("progress", s`INSERT INTO progress VALUES ('u','c','l','done',1.5,${t})`); + await one("notes", s`INSERT INTO notes VALUES ('n','u','c','l','none',NULL,NULL,'b',${t},${t})`); + await one("exercise_attempts", s`INSERT INTO exercise_attempts VALUES ('u','c','l','py','x',NULL,1,${t})`); + await one("user_api_keys", s`INSERT INTO user_api_keys VALUES ('u','p','ct',${t})`); + await one("ai_settings", s`INSERT INTO ai_settings VALUES ('server','',0,'{}',${t})`); + await one("ai_conversations", s`INSERT INTO ai_conversations VALUES ('a','u','c',NULL,${t})`); + await one("ai_messages", s`INSERT INTO ai_messages VALUES ('m','a','user','hi',${t})`); + await one("library_settings", s`INSERT INTO library_settings VALUES ('k','v')`); + await one("collections", s`INSERT INTO collections VALUES ('co','T',0)`); + await one("collection_courses", s`INSERT INTO collection_courses VALUES ('co','c',0)`); + await one("jobs", s`INSERT INTO jobs VALUES ('j','k','queued',0,NULL,'{}',NULL,NULL,${t},${t})`); +}); diff --git a/scripts/test-pg.sh b/scripts/test-pg.sh new file mode 100755 index 0000000..45ba055 --- /dev/null +++ b/scripts/test-pg.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Runs the package tests against SQLite and a throwaway postgres:17 container. +set -euo pipefail +PORT="${STC_PG_PORT:-55432}" +cd "$(dirname "$0")/.." +trap 'docker stop stc-pg >/dev/null 2>&1 || true' EXIT +docker rm -f stc-pg >/dev/null 2>&1 || true +docker run -d --rm --name stc-pg -e POSTGRES_PASSWORD=stc -p 127.0.0.1:${PORT}:5432 postgres:17 >/dev/null +for _ in $(seq 1 60); do + docker exec stc-pg pg_isready -U postgres -h 127.0.0.1 >/dev/null 2>&1 && break + sleep 1 +done +sleep 1 +STC_TEST_PG_URL="postgres://postgres:stc@127.0.0.1:${PORT}/postgres" bun test packages From 4636273d5572327aef3a5fc52327f2ddd19842f5 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 02:59:09 +0100 Subject: [PATCH 10/14] feat(db): progress, notes, attempts, library, jobs repositories Co-Authored-By: Claude Opus 5.5 --- packages/db/src/index.ts | 5 ++ packages/db/src/repos/attempts.ts | 36 +++++++++ packages/db/src/repos/jobs.ts | 63 +++++++++++++++ packages/db/src/repos/library.ts | 49 ++++++++++++ packages/db/src/repos/notes.ts | 66 ++++++++++++++++ packages/db/src/repos/progress.ts | 34 ++++++++ packages/db/test/repos.test.ts | 125 ++++++++++++++++++++++++++++++ 7 files changed, 378 insertions(+) create mode 100644 packages/db/src/repos/attempts.ts create mode 100644 packages/db/src/repos/jobs.ts create mode 100644 packages/db/src/repos/library.ts create mode 100644 packages/db/src/repos/notes.ts create mode 100644 packages/db/src/repos/progress.ts create mode 100644 packages/db/test/repos.test.ts diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 3aaa0f0..7dba514 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -1,2 +1,7 @@ export { connect, type Db } from "./connect"; export { migrate } from "./migrate"; +export { progressRepo, type LessonProgress, type ProgressState } from "./repos/progress"; +export { notesRepo, type Note, type NoteInput } from "./repos/notes"; +export { attemptsRepo, type Attempt } from "./repos/attempts"; +export { libraryRepo, type Collection } from "./repos/library"; +export { jobsRepo, type JobPatch } from "./repos/jobs"; diff --git a/packages/db/src/repos/attempts.ts b/packages/db/src/repos/attempts.ts new file mode 100644 index 0000000..843e1c2 --- /dev/null +++ b/packages/db/src/repos/attempts.ts @@ -0,0 +1,36 @@ +import type { Db } from "../connect"; + +export type Attempt = { + userId: string; courseId: string; lessonId: string; track: string; + code: string; result: unknown; passed: boolean; updatedAt: string; +}; + +export function attemptsRepo(db: Db) { + return { + async get(userId: string, courseId: string, lessonId: string, track: string): Promise { + const rows = await db.sql`SELECT * FROM exercise_attempts WHERE user_id = ${userId} AND course_id = ${courseId} AND lesson_id = ${lessonId} AND track = ${track}`; + if (rows.length === 0) return null; + const r = rows[0]; + return { + userId: r.user_id, courseId: r.course_id, lessonId: r.lesson_id, track: r.track, + code: r.code, result: r.result_json === null ? null : JSON.parse(r.result_json), + passed: Number(r.passed) === 1, updatedAt: r.updated_at, + }; + }, + + async save(a: Attempt): Promise { + const resultJson = a.result === null || a.result === undefined ? null : JSON.stringify(a.result); + const passed = a.passed ? 1 : 0; + await db.sql.begin(async (tx) => { + const existing = await tx`SELECT 1 AS x FROM exercise_attempts WHERE user_id = ${a.userId} AND course_id = ${a.courseId} AND lesson_id = ${a.lessonId} AND track = ${a.track}`; + if (existing.length > 0) { + await tx`UPDATE exercise_attempts SET code = ${a.code}, result_json = ${resultJson}, passed = ${passed}, updated_at = ${a.updatedAt} + WHERE user_id = ${a.userId} AND course_id = ${a.courseId} AND lesson_id = ${a.lessonId} AND track = ${a.track}`; + } else { + await tx`INSERT INTO exercise_attempts (user_id, course_id, lesson_id, track, code, result_json, passed, updated_at) + VALUES (${a.userId}, ${a.courseId}, ${a.lessonId}, ${a.track}, ${a.code}, ${resultJson}, ${passed}, ${a.updatedAt})`; + } + }); + }, + }; +} diff --git a/packages/db/src/repos/jobs.ts b/packages/db/src/repos/jobs.ts new file mode 100644 index 0000000..0713e72 --- /dev/null +++ b/packages/db/src/repos/jobs.ts @@ -0,0 +1,63 @@ +import type { JobRecord } from "@stc/contracts"; +import type { Db } from "../connect"; + +// biome-ignore lint/suspicious/noExplicitAny: raw driver row +const toJob = (r: any): JobRecord => ({ + id: r.id, kind: r.kind, status: r.status, progress: Number(r.progress), message: r.message, + payload: JSON.parse(r.payload_json), result: r.result_json === null ? null : JSON.parse(r.result_json), + error: r.error, createdAt: r.created_at, updatedAt: r.updated_at, +}); + +export type JobPatch = Partial>; + +export function jobsRepo(db: Db) { + const get = async (id: string): Promise => { + const rows = await db.sql`SELECT * FROM jobs WHERE id = ${id}`; + return rows.length ? toJob(rows[0]) : null; + }; + + return { + get, + + async insert(kind: string, payload: unknown): Promise { + const id = Bun.randomUUIDv7(); + const now = new Date().toISOString(); + await db.sql`INSERT INTO jobs (id, kind, status, progress, message, payload_json, result_json, error, created_at, updated_at) + VALUES (${id}, ${kind}, 'queued', 0, NULL, ${JSON.stringify(payload ?? null)}, NULL, NULL, ${now}, ${now})`; + return id; + }, + + /** + * Picks the oldest queued job of one of `kinds` and flips it to running with a guarded + * `UPDATE ... WHERE id = ? AND status = 'queued'`. Of any concurrent claimers of the same + * row exactly one sees an affected count of 1 (Postgres re-checks the predicate after + * waiting on the row lock); losers pick the next candidate. + */ + async claimNext(kinds: string[]): Promise { + if (kinds.length === 0) return null; + for (;;) { + const next = await db.sql`SELECT id FROM jobs WHERE status = 'queued' AND kind IN ${db.sql(kinds)} ORDER BY created_at, id LIMIT 1`; + if (next.length === 0) return null; + const id: string = next[0].id; + const res = await db.sql`UPDATE jobs SET status = 'running', updated_at = ${new Date().toISOString()} WHERE id = ${id} AND status = 'queued'`; + if (Number(res.count) > 0) return get(id); + } + }, + + async update(id: string, patch: JobPatch): Promise { + const cur = await get(id); + if (!cur) return; + const next = { ...cur, ...patch }; + await db.sql`UPDATE jobs SET status = ${next.status}, progress = ${next.progress}, message = ${next.message ?? null}, + result_json = ${next.result === null || next.result === undefined ? null : JSON.stringify(next.result)}, + error = ${next.error ?? null}, updated_at = ${new Date().toISOString()} WHERE id = ${id}`; + }, + + async list(kind?: string): Promise { + const rows = kind === undefined + ? await db.sql`SELECT * FROM jobs ORDER BY created_at, id` + : await db.sql`SELECT * FROM jobs WHERE kind = ${kind} ORDER BY created_at, id`; + return rows.map(toJob); + }, + }; +} diff --git a/packages/db/src/repos/library.ts b/packages/db/src/repos/library.ts new file mode 100644 index 0000000..30134b1 --- /dev/null +++ b/packages/db/src/repos/library.ts @@ -0,0 +1,49 @@ +import type { Db } from "../connect"; + +export type Collection = { id: string; title: string; sort: number; courseIds: string[] }; +const FEATURED = "featured_course_id"; + +export function libraryRepo(db: Db) { + return { + async getFeatured(): Promise { + const rows = await db.sql`SELECT value FROM library_settings WHERE key = ${FEATURED}`; + return rows.length ? rows[0].value : null; + }, + + async setFeatured(courseId: string | null): Promise { + await db.sql.begin(async (tx) => { + await tx`DELETE FROM library_settings WHERE key = ${FEATURED}`; + if (courseId !== null) await tx`INSERT INTO library_settings (key, value) VALUES (${FEATURED}, ${courseId})`; + }); + }, + + async listCollections(): Promise { + const cols = await db.sql`SELECT id, title, sort FROM collections ORDER BY sort, title, id`; + const links = await db.sql`SELECT collection_id, course_id FROM collection_courses ORDER BY sort, course_id`; + return cols.map((c: { id: string; title: string; sort: number }) => ({ + id: c.id, title: c.title, sort: Number(c.sort), + courseIds: links.filter((l: { collection_id: string }) => l.collection_id === c.id).map((l: { course_id: string }) => l.course_id), + })); + }, + + async saveCollection(c: Collection): Promise { + await db.sql.begin(async (tx) => { + const existing = await tx`SELECT 1 AS x FROM collections WHERE id = ${c.id}`; + if (existing.length > 0) await tx`UPDATE collections SET title = ${c.title}, sort = ${c.sort} WHERE id = ${c.id}`; + else await tx`INSERT INTO collections (id, title, sort) VALUES (${c.id}, ${c.title}, ${c.sort})`; + await tx`DELETE FROM collection_courses WHERE collection_id = ${c.id}`; + let i = 0; + for (const courseId of new Set(c.courseIds)) { + await tx`INSERT INTO collection_courses (collection_id, course_id, sort) VALUES (${c.id}, ${courseId}, ${i++})`; + } + }); + }, + + async deleteCollection(id: string): Promise { + await db.sql.begin(async (tx) => { + await tx`DELETE FROM collection_courses WHERE collection_id = ${id}`; + await tx`DELETE FROM collections WHERE id = ${id}`; + }); + }, + }; +} diff --git a/packages/db/src/repos/notes.ts b/packages/db/src/repos/notes.ts new file mode 100644 index 0000000..875a2b7 --- /dev/null +++ b/packages/db/src/repos/notes.ts @@ -0,0 +1,66 @@ +import type { Db } from "../connect"; + +export type Note = { + id: string; userId: string; courseId: string; lessonId: string; + anchorKind: "none" | "video" | "slide"; anchorValue: string | null; deckId: string | null; + body: string; createdAt: string; updatedAt: string; +}; +export type NoteInput = { + userId: string; courseId: string; lessonId: string; + anchorKind: Note["anchorKind"]; anchorValue?: string | null; deckId?: string | null; body: string; +}; + +// biome-ignore lint/suspicious/noExplicitAny: raw driver row +const toNote = (r: any): Note => ({ + id: r.id, userId: r.user_id, courseId: r.course_id, lessonId: r.lesson_id, + anchorKind: r.anchor_kind, anchorValue: r.anchor_value, deckId: r.deck_id, + body: r.body, createdAt: r.created_at, updatedAt: r.updated_at, +}); + +const numeric = (v: string | null): number => { + const n = v === null ? NaN : Number(v); + return Number.isNaN(n) ? Number.POSITIVE_INFINITY : n; +}; + +export function notesRepo(db: Db) { + const getOne = async (id: string): Promise => { + const rows = await db.sql`SELECT * FROM notes WHERE id = ${id}`; + return rows.length ? toNote(rows[0]) : null; + }; + + return { + /** Ordered by anchor_kind, then anchor_value read numerically (so page 2 precedes page 10), then created_at. */ + async list(userId: string, courseId: string, lessonId?: string): Promise { + const rows = lessonId === undefined + ? await db.sql`SELECT * FROM notes WHERE user_id = ${userId} AND course_id = ${courseId}` + : await db.sql`SELECT * FROM notes WHERE user_id = ${userId} AND course_id = ${courseId} AND lesson_id = ${lessonId}`; + // Numeric ordering is done here: CAST of non-numeric text errors on Postgres but not SQLite. + return (rows.map(toNote) as Note[]).sort((a, b) => + (a.anchorKind < b.anchorKind ? -1 : a.anchorKind > b.anchorKind ? 1 : 0) || + numeric(a.anchorValue) - numeric(b.anchorValue) || + (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0) || + (a.id < b.id ? -1 : 1)); + }, + + async create(input: NoteInput): Promise { + const id = Bun.randomUUIDv7(); + const now = new Date().toISOString(); + await db.sql`INSERT INTO notes (id, user_id, course_id, lesson_id, anchor_kind, anchor_value, deck_id, body, created_at, updated_at) + VALUES (${id}, ${input.userId}, ${input.courseId}, ${input.lessonId}, ${input.anchorKind}, ${input.anchorValue ?? null}, ${input.deckId ?? null}, ${input.body}, ${now}, ${now})`; + return (await getOne(id))!; + }, + + async update(id: string, userId: string, body: string): Promise { + await db.sql`UPDATE notes SET body = ${body}, updated_at = ${new Date().toISOString()} WHERE id = ${id} AND user_id = ${userId}`; + const n = await getOne(id); + return n && n.userId === userId ? n : null; + }, + + async remove(id: string, userId: string): Promise { + const owned = await db.sql`SELECT 1 AS x FROM notes WHERE id = ${id} AND user_id = ${userId}`; + if (owned.length === 0) return false; + await db.sql`DELETE FROM notes WHERE id = ${id} AND user_id = ${userId}`; + return true; + }, + }; +} diff --git a/packages/db/src/repos/progress.ts b/packages/db/src/repos/progress.ts new file mode 100644 index 0000000..9472e30 --- /dev/null +++ b/packages/db/src/repos/progress.ts @@ -0,0 +1,34 @@ +import type { Db } from "../connect"; + +export type ProgressState = "not-started" | "in-progress" | "done"; +export type LessonProgress = { state: ProgressState; positionSeconds: number | null; updatedAt: string }; + +export function progressRepo(db: Db) { + return { + async get(userId: string, courseId: string): Promise> { + const rows = await db.sql`SELECT lesson_id, state, position_seconds, updated_at FROM progress WHERE user_id = ${userId} AND course_id = ${courseId}`; + const out: Record = {}; + for (const r of rows) { + out[r.lesson_id] = { + state: r.state, + positionSeconds: r.position_seconds === null ? null : Number(r.position_seconds), + updatedAt: r.updated_at, + }; + } + return out; + }, + + async set(userId: string, courseId: string, lessonId: string, state: ProgressState, positionSeconds?: number): Promise { + const now = new Date().toISOString(); + const pos = positionSeconds ?? null; + await db.sql.begin(async (tx) => { + const existing = await tx`SELECT 1 AS x FROM progress WHERE user_id = ${userId} AND course_id = ${courseId} AND lesson_id = ${lessonId}`; + if (existing.length > 0) { + await tx`UPDATE progress SET state = ${state}, position_seconds = ${pos}, updated_at = ${now} WHERE user_id = ${userId} AND course_id = ${courseId} AND lesson_id = ${lessonId}`; + } else { + await tx`INSERT INTO progress (user_id, course_id, lesson_id, state, position_seconds, updated_at) VALUES (${userId}, ${courseId}, ${lessonId}, ${state}, ${pos}, ${now})`; + } + }); + }, + }; +} diff --git a/packages/db/test/repos.test.ts b/packages/db/test/repos.test.ts new file mode 100644 index 0000000..8169fb9 --- /dev/null +++ b/packages/db/test/repos.test.ts @@ -0,0 +1,125 @@ +import { expect } from "bun:test"; +import { forEachDb } from "./helpers"; +import { attemptsRepo, jobsRepo, libraryRepo, notesRepo, progressRepo } from "../src"; + +forEachDb("progress upsert keeps one row", async (db) => { + const p = progressRepo(db); + await p.set("u", "c", "l1", "in-progress", 12.5); + await p.set("u", "c", "l1", "done"); + await p.set("u", "c", "l2", "in-progress", 3); + await p.set("other", "c", "l1", "done"); + const got = await p.get("u", "c"); + expect(Object.keys(got).sort()).toEqual(["l1", "l2"]); + expect(got.l1.state).toBe("done"); + expect(got.l1.positionSeconds).toBeNull(); + expect(got.l2.positionSeconds).toBe(3); + expect(typeof got.l1.updatedAt).toBe("string"); + expect((await db.sql`SELECT COUNT(*) AS n FROM progress WHERE user_id = 'u'`)[0].n.toString()).toBe("2"); +}); + +forEachDb("notes order puts slide page 2 before page 10", async (db) => { + const n = notesRepo(db); + const base = { userId: "u", courseId: "c", lessonId: "l" }; + await n.create({ ...base, anchorKind: "slide", anchorValue: "10", deckId: "d", body: "ten" }); + await n.create({ ...base, anchorKind: "slide", anchorValue: "2", deckId: "d", body: "two" }); + await n.create({ ...base, anchorKind: "none", body: "plain" }); + await n.create({ ...base, anchorKind: "video", anchorValue: "90.5", body: "video" }); + await n.create({ ...base, lessonId: "other", anchorKind: "none", body: "elsewhere" }); + const all = await n.list("u", "c", "l"); + expect(all.map((x) => x.body)).toEqual(["plain", "two", "ten", "video"]); + expect(all[1].deckId).toBe("d"); + expect((await n.list("u", "c")).length).toBe(5); +}); + +forEachDb("another user cannot update or delete a note", async (db) => { + const n = notesRepo(db); + const note = await n.create({ userId: "u", courseId: "c", lessonId: "l", anchorKind: "none", body: "mine" }); + expect(await n.update(note.id, "intruder", "hacked")).toBeNull(); + expect(await n.remove(note.id, "intruder")).toBe(false); + expect((await n.list("u", "c", "l"))[0].body).toBe("mine"); + expect((await n.update(note.id, "u", "edited"))?.body).toBe("edited"); + expect(await n.remove(note.id, "u")).toBe(true); + expect(await n.list("u", "c", "l")).toEqual([]); +}); + +forEachDb("attempts round-trip", async (db) => { + const a = attemptsRepo(db); + expect(await a.get("u", "c", "l", "py")).toBeNull(); + const att = { userId: "u", courseId: "c", lessonId: "l", track: "py", code: "print(1)", result: { out: "1", tests: [true] }, passed: true, updatedAt: "2026-01-01T00:00:00.000Z" }; + await a.save(att); + expect(await a.get("u", "c", "l", "py")).toEqual(att); + await a.save({ ...att, code: "x", result: null, passed: false }); + const again = await a.get("u", "c", "l", "py"); + expect(again).toMatchObject({ code: "x", result: null, passed: false }); +}); + +forEachDb("featured course and collections keep their order", async (db) => { + const l = libraryRepo(db); + expect(await l.getFeatured()).toBeNull(); + await l.setFeatured("a"); + await l.setFeatured("b"); + expect(await l.getFeatured()).toBe("b"); + await l.setFeatured(null); + expect(await l.getFeatured()).toBeNull(); + + await l.saveCollection({ id: "c2", title: "Second", sort: 2, courseIds: ["z", "y"] }); + await l.saveCollection({ id: "c1", title: "First", sort: 1, courseIds: ["b", "a", "c"] }); + expect(await l.listCollections()).toEqual([ + { id: "c1", title: "First", sort: 1, courseIds: ["b", "a", "c"] }, + { id: "c2", title: "Second", sort: 2, courseIds: ["z", "y"] }, + ]); + await l.saveCollection({ id: "c1", title: "First!", sort: 3, courseIds: ["c", "a"] }); + expect((await l.listCollections()).map((c) => [c.id, c.courseIds])).toEqual([["c2", ["z", "y"]], ["c1", ["c", "a"]]]); + await l.deleteCollection("c2"); + expect((await l.listCollections()).map((c) => c.id)).toEqual(["c1"]); + expect((await db.sql`SELECT COUNT(*) AS n FROM collection_courses`)[0].n.toString()).toBe("2"); +}); + +forEachDb("jobs lifecycle", async (db) => { + const j = jobsRepo(db); + const id = await j.insert("import", { url: "x" }); + const got = await j.get(id); + expect(got).toMatchObject({ kind: "import", status: "queued", progress: 0, payload: { url: "x" }, result: null, error: null, message: null }); + await j.update(id, { progress: 0.5, message: "half" }); + await j.update(id, { status: "done", result: { ok: 1 } }); + expect(await j.get(id)).toMatchObject({ status: "done", progress: 0.5, message: "half", result: { ok: 1 } }); + await j.insert("other", {}); + expect((await j.list()).length).toBe(2); + expect((await j.list("import")).map((x) => x.id)).toEqual([id]); + expect(await j.get("missing")).toBeNull(); +}); + +forEachDb("claimNext returns null when nothing is queued", async (db) => { + const j = jobsRepo(db); + expect(await j.claimNext(["import"])).toBeNull(); + await j.insert("other", {}); + expect(await j.claimNext(["import"])).toBeNull(); + expect(await j.claimNext([])).toBeNull(); +}); + +forEachDb("claimNext claims oldest first and marks running", async (db) => { + const j = jobsRepo(db); + const a = await j.insert("import", 1); + await Bun.sleep(2); + const b = await j.insert("import", 2); + expect((await j.claimNext(["import"]))).toMatchObject({ id: a, status: "running" }); + expect((await j.claimNext(["import"]))?.id).toBe(b); + expect(await j.claimNext(["import"])).toBeNull(); +}); + +forEachDb("two concurrent claimNext calls never claim the same job", async (db) => { + const j = jobsRepo(db); + const ids = [await j.insert("k", 1), await j.insert("k", 2)]; + for (let round = 0; round < 1; round++) { + const got = await Promise.all([j.claimNext(["k"]), j.claimNext(["k"])]); + expect(got.every((x) => x !== null)).toBe(true); + expect(new Set(got.map((x) => x!.id)).size).toBe(2); + expect([...got.map((x) => x!.id)].sort()).toEqual([...ids].sort()); + } + // single job, two claimers: exactly one wins + const solo = jobsRepo(db); + await db.sql`DELETE FROM jobs`; + const only = await solo.insert("k", 3); + const res = await Promise.all([solo.claimNext(["k"]), solo.claimNext(["k"])]); + expect(res.filter((x) => x !== null).map((x) => x!.id)).toEqual([only]); +}); From f061e360928c453b9a3664340bafc1e9930d2da2 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 03:01:05 +0100 Subject: [PATCH 11/14] fix(db): jobs.update writes only patched columns; late progress cannot resurrect a finished job Co-Authored-By: Claude Opus 5.5 --- packages/db/src/repos/jobs.ts | 20 ++++++++++++++------ packages/db/test/repos.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/packages/db/src/repos/jobs.ts b/packages/db/src/repos/jobs.ts index 0713e72..3850ef6 100644 --- a/packages/db/src/repos/jobs.ts +++ b/packages/db/src/repos/jobs.ts @@ -44,13 +44,21 @@ export function jobsRepo(db: Db) { } }, + /** + * Single UPDATE writing only the patched columns (plus updated_at). A progress-only patch + * (progress and/or message) is guarded by status = 'running', so a late report on a + * finished job is a no-op. + */ async update(id: string, patch: JobPatch): Promise { - const cur = await get(id); - if (!cur) return; - const next = { ...cur, ...patch }; - await db.sql`UPDATE jobs SET status = ${next.status}, progress = ${next.progress}, message = ${next.message ?? null}, - result_json = ${next.result === null || next.result === undefined ? null : JSON.stringify(next.result)}, - error = ${next.error ?? null}, updated_at = ${new Date().toISOString()} WHERE id = ${id}`; + const set: Record = { updated_at: new Date().toISOString() }; + if (patch.status !== undefined) set.status = patch.status; + if (patch.progress !== undefined) set.progress = patch.progress; + if (patch.message !== undefined) set.message = patch.message; + if (patch.result !== undefined) set.result_json = patch.result === null ? null : JSON.stringify(patch.result); + if (patch.error !== undefined) set.error = patch.error; + const progressOnly = patch.status === undefined && patch.result === undefined && patch.error === undefined; + if (progressOnly) await db.sql`UPDATE jobs SET ${db.sql(set)} WHERE id = ${id} AND status = 'running'`; + else await db.sql`UPDATE jobs SET ${db.sql(set)} WHERE id = ${id}`; }, async list(kind?: string): Promise { diff --git a/packages/db/test/repos.test.ts b/packages/db/test/repos.test.ts index 8169fb9..684b455 100644 --- a/packages/db/test/repos.test.ts +++ b/packages/db/test/repos.test.ts @@ -80,6 +80,7 @@ forEachDb("jobs lifecycle", async (db) => { const id = await j.insert("import", { url: "x" }); const got = await j.get(id); expect(got).toMatchObject({ kind: "import", status: "queued", progress: 0, payload: { url: "x" }, result: null, error: null, message: null }); + await j.claimNext(["import"]); await j.update(id, { progress: 0.5, message: "half" }); await j.update(id, { status: "done", result: { ok: 1 } }); expect(await j.get(id)).toMatchObject({ status: "done", progress: 0.5, message: "half", result: { ok: 1 } }); @@ -123,3 +124,27 @@ forEachDb("two concurrent claimNext calls never claim the same job", async (db) const res = await Promise.all([solo.claimNext(["k"]), solo.claimNext(["k"])]); expect(res.filter((x) => x !== null).map((x) => x!.id)).toEqual([only]); }); + +forEachDb("late progress update does not resurrect a done job", async (db) => { + const j = jobsRepo(db); + const id = await j.insert("k", {}); + await j.claimNext(["k"]); + await j.update(id, { status: "done", progress: 1, result: { ok: true } }); + await j.update(id, { progress: 0.4, message: "stale" }); + expect(await j.get(id)).toMatchObject({ status: "done", progress: 1, message: null, result: { ok: true } }); + const f = await j.insert("k", {}); + await j.update(f, { status: "failed", error: "boom" }); + await j.update(f, { progress: 0.9 }); + expect(await j.get(f)).toMatchObject({ status: "failed", error: "boom", progress: 0 }); +}); + +forEachDb("update only touches patched columns", async (db) => { + const j = jobsRepo(db); + const id = await j.insert("k", { a: 1 }); + await j.claimNext(["k"]); + await j.update(id, { progress: 0.5, message: "working" }); + await j.update(id, { message: "still" }); + expect(await j.get(id)).toMatchObject({ status: "running", progress: 0.5, message: "still", result: null, error: null, payload: { a: 1 } }); + await j.update(id, { result: { r: 1 } }); + expect(await j.get(id)).toMatchObject({ status: "running", progress: 0.5, message: "still", result: { r: 1 } }); +}); From ea18f18b4fdf1e8dfd4e50d23ab6f29a25bcb0ff Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 03:01:31 +0100 Subject: [PATCH 12/14] fix(db): use DOUBLE PRECISION for position and progress columns Co-Authored-By: Claude Opus 5.5 --- packages/db/migrations/0001_init.sql | 4 ++-- packages/db/test/repos.test.ts | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/db/migrations/0001_init.sql b/packages/db/migrations/0001_init.sql index ade4751..56ec758 100644 --- a/packages/db/migrations/0001_init.sql +++ b/packages/db/migrations/0001_init.sql @@ -21,7 +21,7 @@ CREATE TABLE course_acl ( CREATE TABLE progress ( user_id TEXT NOT NULL, course_id TEXT NOT NULL, lesson_id TEXT NOT NULL, state TEXT NOT NULL CHECK (state IN ('not-started', 'in-progress', 'done')), - position_seconds REAL, + position_seconds DOUBLE PRECISION, updated_at TEXT NOT NULL, PRIMARY KEY (user_id, course_id, lesson_id) ); @@ -61,7 +61,7 @@ CREATE TABLE collection_courses ( PRIMARY KEY (collection_id, course_id) ); CREATE TABLE jobs ( - id TEXT PRIMARY KEY, kind TEXT NOT NULL, status TEXT NOT NULL, progress REAL NOT NULL, + id TEXT PRIMARY KEY, kind TEXT NOT NULL, status TEXT NOT NULL, progress DOUBLE PRECISION NOT NULL, message TEXT, payload_json TEXT NOT NULL, result_json TEXT, error TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); diff --git a/packages/db/test/repos.test.ts b/packages/db/test/repos.test.ts index 684b455..f84821c 100644 --- a/packages/db/test/repos.test.ts +++ b/packages/db/test/repos.test.ts @@ -14,7 +14,9 @@ forEachDb("progress upsert keeps one row", async (db) => { expect(got.l1.positionSeconds).toBeNull(); expect(got.l2.positionSeconds).toBe(3); expect(typeof got.l1.updatedAt).toBe("string"); - expect((await db.sql`SELECT COUNT(*) AS n FROM progress WHERE user_id = 'u'`)[0].n.toString()).toBe("2"); + await p.set("u", "c", "l3", "in-progress", 1234.567); + expect((await p.get("u", "c")).l3.positionSeconds).toBe(1234.567); + expect((await db.sql`SELECT COUNT(*) AS n FROM progress WHERE user_id = 'u'`)[0].n.toString()).toBe("3"); }); forEachDb("notes order puts slide page 2 before page 10", async (db) => { From 7f33169487432a1deae0310e77b950ac1f1d6d8d Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 03:04:46 +0100 Subject: [PATCH 13/14] feat(core): config, job queue, range media serving, feature composition Adds aclRepo to @stc/db for canView. Co-Authored-By: Claude Opus 5.5 --- packages/core/src/app.ts | 99 +++++++++++++++++++++++++++++ packages/core/src/config.ts | 22 +++++++ packages/core/src/index.ts | 4 ++ packages/core/src/jobs.ts | 69 ++++++++++++++++++++ packages/core/src/media.ts | 57 +++++++++++++++++ packages/core/test/app.test.ts | 101 ++++++++++++++++++++++++++++++ packages/core/test/config.test.ts | 27 ++++++++ packages/core/test/jobs.test.ts | 61 ++++++++++++++++++ packages/core/test/media.test.ts | 59 +++++++++++++++++ packages/db/src/index.ts | 1 + packages/db/src/repos/acl.ts | 16 +++++ packages/db/test/acl.test.ts | 17 +++++ 12 files changed, 533 insertions(+) create mode 100644 packages/core/src/app.ts create mode 100644 packages/core/src/config.ts create mode 100644 packages/core/src/index.ts create mode 100644 packages/core/src/jobs.ts create mode 100644 packages/core/src/media.ts create mode 100644 packages/core/test/app.test.ts create mode 100644 packages/core/test/config.test.ts create mode 100644 packages/core/test/jobs.test.ts create mode 100644 packages/core/test/media.test.ts create mode 100644 packages/db/src/repos/acl.ts create mode 100644 packages/db/test/acl.test.ts diff --git a/packages/core/src/app.ts b/packages/core/src/app.ts new file mode 100644 index 0000000..fc7554f --- /dev/null +++ b/packages/core/src/app.ts @@ -0,0 +1,99 @@ +import type { AuthUser, Feature, RequestContext, RouteHandler, ServerContext } from "@stc/contracts"; +import type { LoadedCourse } from "@stc/course-format"; +import { aclRepo } from "@stc/db"; +import { serveMedia } from "./media"; + +type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; +export type Routes = Record Response | Promise>>>; + +export function canView(user: AuthUser | null, course: LoadedCourse, acl: { principal_type: string; principal_id: string }[], isAuthor = false): boolean { + const vis = course.manifest?.visibility ?? "restricted"; + if (vis === "public") return true; + if (!user) return false; + if (vis === "signed-in") return true; + if (user.roles.includes("owner") || isAuthor) return true; + return acl.some((a) => (a.principal_type === "user" && a.principal_id === user.id) || (a.principal_type === "group" && user.groups.includes(a.principal_id))); +} + +const json = (body: unknown, status = 200) => Response.json(body, { status }); + +export function createApp(ctx: ServerContext, features: Feature[]): { routes: Routes; fetch(req: Request): Promise } { + const acl = aclRepo(ctx.db); + + const core: Feature = { + name: "core", + routes: { + "/api/health": { GET: () => json({ ok: true, courses: ctx.courses.list().length, db: ctx.db.dialect }) }, + "/api/media/:courseId/*": { + GET: async (req, rc) => { + // Parse from the pathname so we do not depend on how the server fills params for "*". + const m = /^\/api\/media\/([^/]+)\/(.*)$/s.exec(rc.url.pathname); + if (!m) return new Response("Not found", { status: 404 }); + let courseId: string, rel: string; + try { courseId = decodeURIComponent(m[1]!); rel = decodeURIComponent(m[2]!); } catch { return new Response("Not found", { status: 404 }); } + const course = ctx.courses.get(courseId); + if (!course) return new Response("Not found", { status: 404 }); + const visible = canView(rc.user, course, await acl.listForCourse(course.id), rc.user ? await acl.isAuthor(course.id, rc.user.id) : false); + if (!visible) return new Response("Not found", { status: 404 }); + const abs = ctx.courses.resolvePath(course.id, rel); + if (!abs) return new Response("Not found", { status: 404 }); + return serveMedia(req, abs, { download: rc.url.searchParams.has("download") }); + }, + }, + }, + }; + + const wrap = (h: RouteHandler) => async (req: Request & { params?: Record }): Promise => { + const url = new URL(req.url); + const rc: RequestContext = { user: await ctx.auth.userFromRequest(req), params: req.params ?? {}, url }; + return h(req, rc); + }; + + const routes: Routes = {}; + for (const f of [core, ...features]) { + for (const [path, methods] of Object.entries(f.routes)) { + const slot = (routes[path] ??= {}); + for (const [m, h] of Object.entries(methods) as [Method, RouteHandler][]) { + if (slot[m]) throw new Error(`Duplicate route ${m} ${path} (feature "${f.name}")`); + slot[m] = wrap(h); + } + } + } + + // Matcher for fetch(): same semantics as Bun routes (":name" segment, trailing "*" wildcard). + const compiled = Object.entries(routes).map(([path, methods]) => { + const parts = path.split("/"); + return { parts, methods }; + }); + const match = (pathname: string) => { + const segs = pathname.split("/"); + for (const { parts, methods } of compiled) { + const params: Record = {}; + let ok = true; + for (let i = 0; i < parts.length && ok; i++) { + const p = parts[i]!; + if (p === "*") { params["*"] = segs.slice(i).join("/"); if (i >= segs.length) params["*"] = ""; return { methods, params }; } + if (segs[i] === undefined) ok = false; + else if (p.startsWith(":")) params[p.slice(1)] = decodeURIComponent(segs[i]!); + else if (p !== segs[i]) ok = false; + } + if (ok && parts.length === segs.length) return { methods, params }; + } + return null; + }; + + return { + routes, + async fetch(req) { + const url = new URL(req.url); + let m: ReturnType; + try { m = match(url.pathname); } catch { return new Response("Bad request", { status: 400 }); } + if (!m) return new Response("Not found", { status: 404 }); + const h = m.methods[req.method as Method]; + if (!h) return new Response("Method not allowed", { status: 405 }); + const r = req as Request & { params?: Record }; + r.params = m.params; + return h(r); + }, + }; +} diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts new file mode 100644 index 0000000..0359442 --- /dev/null +++ b/packages/core/src/config.ts @@ -0,0 +1,22 @@ +import type { AppConfig } from "@stc/contracts"; + +const DEV_SECRET = "stc-dev-secret-change-me"; + +export function loadConfig(env: Record = process.env): AppConfig { + const port = env.STC_PORT !== undefined && env.STC_PORT !== "" ? Number(env.STC_PORT) : 3000; + if (!Number.isInteger(port) || port < 0) throw new Error(`Invalid STC_PORT: ${env.STC_PORT}`); + let secret = env.STC_SECRET; + if (!secret) { + if (env.NODE_ENV === "production") throw new Error("STC_SECRET is required when NODE_ENV=production"); + console.warn("[stc] STC_SECRET is not set; using an insecure development default"); + secret = DEV_SECRET; + } + return { + port, + databaseUrl: env.STC_DATABASE_URL || "sqlite://./data/stcourses.db", + dataDir: env.STC_DATA_DIR || "./data", + courseDirs: (env.STC_COURSE_DIRS || "./overlays:./courses").split(":").filter(Boolean), + secret, + publicUrl: env.STC_PUBLIC_URL || `http://localhost:${port}`, + }; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 0000000..d955c36 --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,4 @@ +export { loadConfig } from "./config"; +export { createJobQueue } from "./jobs"; +export { serveMedia, contentType, contentDisposition } from "./media"; +export { createApp, canView, type Routes } from "./app"; diff --git a/packages/core/src/jobs.ts b/packages/core/src/jobs.ts new file mode 100644 index 0000000..21f365d --- /dev/null +++ b/packages/core/src/jobs.ts @@ -0,0 +1,69 @@ +import type { JobHandler, JobQueue } from "@stc/contracts"; +import { jobsRepo, type Db } from "@stc/db"; + +export function createJobQueue(db: Db, handlers: Record, opts: { pollMs?: number } = {}): JobQueue & { start(): void; stop(): Promise } { + const repo = jobsRepo(db); + const pollMs = opts.pollMs ?? 500; + const kinds = Object.keys(handlers); + let running = false; + let loop: Promise | null = null; + let wake: (() => void) | null = null; + let abort = new AbortController(); + + const runOne = async (): Promise => { + const job = await repo.claimNext(kinds); + if (!job) return false; + const jc = { + signal: abort.signal, + reportProgress: (fraction: number, message?: string) => + repo.update(job.id, message === undefined ? { progress: fraction } : { progress: fraction, message }), + }; + try { + const result = await handlers[job.kind]!(job.payload, jc); + await repo.update(job.id, { status: "done", progress: 1, result: result ?? null }); + } catch (e) { + await repo.update(job.id, { status: "failed", error: e instanceof Error ? e.message : String(e) }); + } + return true; + }; + + const sleep = () => new Promise((res) => { + const t = setTimeout(res, pollMs); + wake = () => { clearTimeout(t); res(); }; + }); + + const run = async () => { + while (running) { + let did = false; + try { did = await runOne(); } catch (e) { console.error("[stc] job worker error", e); } + if (!did && running) await sleep(); + } + }; + + return { + async enqueue(kind, payload) { + const id = await repo.insert(kind, payload); + wake?.(); + return id; + }, + get: (id) => repo.get(id), + list: (kind) => repo.list(kind), + start() { + if (running) return; + running = true; + abort = new AbortController(); + loop = (async () => { + // jobs left running by a previous process go back to the queue + await db.sql`UPDATE jobs SET status = 'queued', updated_at = ${new Date().toISOString()} WHERE status = 'running'`; + await run(); + })(); + }, + async stop() { + running = false; + abort.abort(); + wake?.(); + await loop; + loop = null; + }, + }; +} diff --git a/packages/core/src/media.ts b/packages/core/src/media.ts new file mode 100644 index 0000000..941c1ed --- /dev/null +++ b/packages/core/src/media.ts @@ -0,0 +1,57 @@ +const TYPES: Record = { + mp4: "video/mp4", webm: "video/webm", pdf: "application/pdf", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", + svg: "image/svg+xml", md: "text/markdown; charset=utf-8", txt: "text/plain; charset=utf-8", zip: "application/zip", + js: "text/javascript; charset=utf-8", ts: "text/plain; charset=utf-8", +}; + +export function contentType(path: string): string { + const ext = path.slice(path.lastIndexOf(".") + 1).toLowerCase(); + return TYPES[ext] ?? "application/octet-stream"; +} + +/** RFC 6266 / 5987 header value: ASCII fallback plus UTF-8 filename*. */ +export function contentDisposition(name: string, kind: "inline" | "attachment" = "attachment"): string { + const fallback = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_"); + const star = encodeURIComponent(name).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); + return `${kind}; filename="${fallback}"; filename*=UTF-8''${star}`; +} + +function parseRange(header: string, size: number): { start: number; end: number } | "invalid" | null { + const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); + if (!m) return null; // malformed or multi-range: ignore, serve whole file + const [, a, b] = m; + if (a === "" && b === "") return null; + let start: number, end: number; + if (a === "") { + const n = Number(b); + if (n === 0) return "invalid"; + start = Math.max(0, size - n); end = size - 1; + } else { + start = Number(a); + end = b === "" ? size - 1 : Math.min(Number(b), size - 1); + if (start >= size || start > end) return "invalid"; + } + return { start, end }; +} + +export async function serveMedia(req: Request, absPath: string, opts: { download?: boolean } = {}): Promise { + const file = Bun.file(absPath); + if (!(await file.exists())) return new Response("Not found", { status: 404 }); + const size = file.size; + const name = absPath.split("/").pop() ?? "file"; + const headers: Record = { + "Content-Type": contentType(absPath), + "Accept-Ranges": "bytes", + }; + if (opts.download) headers["Content-Disposition"] = contentDisposition(name); + const range = req.headers.get("range"); + const parsed = range ? parseRange(range, size) : null; + if (parsed === "invalid") return new Response(null, { status: 416, headers: { "Content-Range": `bytes */${size}`, "Accept-Ranges": "bytes" } }); + if (!parsed) { + headers["Content-Length"] = String(size); + return new Response(req.method === "HEAD" ? null : file, { status: 200, headers }); + } + headers["Content-Range"] = `bytes ${parsed.start}-${parsed.end}/${size}`; + headers["Content-Length"] = String(parsed.end - parsed.start + 1); + return new Response(req.method === "HEAD" ? null : file.slice(parsed.start, parsed.end + 1), { status: 206, headers }); +} diff --git a/packages/core/test/app.test.ts b/packages/core/test/app.test.ts new file mode 100644 index 0000000..6a8545c --- /dev/null +++ b/packages/core/test/app.test.ts @@ -0,0 +1,101 @@ +import { expect, test } from "bun:test"; +import { cpSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import type { AuthUser, Feature, ServerContext } from "@stc/contracts"; +import { createCourseRepository } from "@stc/course-format"; +import { connect, migrate } from "@stc/db"; +import { canView, createApp } from "../src"; + +const SAMPLE = resolve(import.meta.dir, "../../../fixtures/courses/sample"); + +async function setup(user: AuthUser | null = null) { + const dir = mkdtempSync(join(tmpdir(), "stc-app-")); + cpSync(SAMPLE, join(dir, "pub"), { recursive: true }); + const manifest = await Bun.file(join(SAMPLE, "stcourse.yaml")).text(); + mkdirSync(join(dir, "priv")); + cpSync(SAMPLE, join(dir, "priv"), { recursive: true }); + writeFileSync(join(dir, "priv/stcourse.yaml"), manifest.replace("id: sample", "id: secret").replace("visibility: public", "visibility: restricted")); + mkdirSync(join(dir, "broken")); + writeFileSync(join(dir, "broken/stcourse.yaml"), "schema: 1\nid: broken\ntitle: Broken\nroot: /does/not/exist\nmodules: []\n"); + symlinkSync("/etc", join(dir, "pub/escape")); + const db = await connect("sqlite://:memory:"); + await migrate(db); + const courses = await createCourseRepository([dir]); + const ctx = { db, courses, auth: { userFromRequest: async () => user } } as unknown as ServerContext; + return { ctx, db, dir }; +} +const feat = (name: string): Feature => ({ name, routes: { "/api/x": { GET: () => new Response(name) } } }); +const user = (over: Partial = {}): AuthUser => ({ id: "u1", email: "u@x", name: "U", roles: ["learner"], groups: [], ...over }); + +test("health ok, and an error course does not break it", async () => { + const { ctx, db } = await setup(); + expect(ctx.courses.get("broken")?.status).toBe("error"); + const app = createApp(ctx, []); + const r = await app.fetch(new Request("http://x/api/health")); + expect(r.status).toBe(200); + expect(await r.json()).toEqual({ ok: true, courses: ctx.courses.list().length, db: "sqlite" }); + expect(ctx.courses.list().length).toBe(3); + await db.close(); +}); + +test("media serves a file with Range, and a missing/broken course is 404", async () => { + const { ctx, db } = await setup(); + const app = createApp(ctx, []); + const r = await app.fetch(new Request("http://x/api/media/sample/media/clip.mp4", { headers: { Range: "bytes=0-9" } })); + expect(r.status).toBe(206); + expect((await app.fetch(new Request("http://x/api/media/broken/anything"))).status).toBe(404); + expect((await app.fetch(new Request("http://x/api/media/nope/a"))).status).toBe(404); + await db.close(); +}); + +test("traversal, absolute and symlink escapes are 404", async () => { + const { ctx, db } = await setup(); + const app = createApp(ctx, []); + for (const p of ["..%2F..%2Fetc%2Fpasswd", "%2Fetc%2Fpasswd", "escape/passwd", "../priv/stcourse.yaml", "%E0%A4%A"]) { + const r = await app.fetch(new Request(`http://x/api/media/sample/${p}`)); + expect(r.status).toBe(404); + } + await db.close(); +}); + +test("restricted course: 404 anonymous, visible to owner, author, ACL user and group", async () => { + const url = "http://x/api/media/secret/media/clip.mp4"; + const run = async (u: AuthUser | null, seed?: (db: Awaited>["db"]) => Promise) => { + const { ctx, db } = await setup(u); + await seed?.(db); + const s = (await createApp(ctx, []).fetch(new Request(url))).status; + await db.close(); + return s; + }; + expect(await run(null)).toBe(404); + expect(await run(user())).toBe(404); + expect(await run(user({ roles: ["owner"] }))).toBe(200); + expect(await run(user(), (db) => db.sql`INSERT INTO course_authors (course_id, user_id) VALUES ('secret', 'u1')`)).toBe(200); + expect(await run(user(), (db) => db.sql`INSERT INTO course_acl VALUES ('secret', 'user', 'u1')`)).toBe(200); + expect(await run(user({ groups: ["g"] }), (db) => db.sql`INSERT INTO course_acl VALUES ('secret', 'group', 'g')`)).toBe(200); + expect(await run(user({ groups: ["h"] }), (db) => db.sql`INSERT INTO course_acl VALUES ('secret', 'group', 'g')`)).toBe(404); +}); + +test("duplicate method+path across features throws", async () => { + const { ctx, db } = await setup(); + expect(() => createApp(ctx, [feat("a"), feat("b")])).toThrow(/Duplicate route GET \/api\/x/); + await db.close(); +}); + +test("feature routes receive RequestContext with the user", async () => { + const u = user(); + const { ctx, db } = await setup(u); + const f: Feature = { name: "a", routes: { "/api/who/:id": { GET: (_r, rc) => Response.json({ u: rc.user?.id, id: rc.params.id }) } } }; + const app = createApp(ctx, [f]); + expect(await (await app.fetch(new Request("http://x/api/who/42"))).json()).toEqual({ u: "u1", id: "42" }); + await db.close(); +}); + +test("canView matrix", async () => { + const { ctx, db } = await setup(); + const pub = ctx.courses.get("sample")!, priv = ctx.courses.get("secret")!; + expect(canView(null, pub, [])).toBe(true); + expect(canView(null, priv, [])).toBe(false); + await db.close(); +}); diff --git a/packages/core/test/config.test.ts b/packages/core/test/config.test.ts new file mode 100644 index 0000000..3305ea7 --- /dev/null +++ b/packages/core/test/config.test.ts @@ -0,0 +1,27 @@ +import { expect, test, spyOn } from "bun:test"; +import { loadConfig } from "../src"; + +test("defaults", () => { + const warn = spyOn(console, "warn").mockImplementation(() => {}); + const c = loadConfig({}); + expect(c.port).toBe(3000); + expect(c.databaseUrl).toBe("sqlite://./data/stcourses.db"); + expect(c.dataDir).toBe("./data"); + expect(c.courseDirs).toEqual(["./overlays", "./courses"]); + expect(c.publicUrl).toBe("http://localhost:3000"); + expect(warn).toHaveBeenCalledTimes(1); + warn.mockRestore(); +}); + +test("colon splitting and overrides", () => { + const c = loadConfig({ STC_PORT: "8080", STC_COURSE_DIRS: "/a b:/c", STC_SECRET: "s", STC_PUBLIC_URL: "https://x.test" }); + expect(c.port).toBe(8080); + expect(c.courseDirs).toEqual(["/a b", "/c"]); + expect(c.secret).toBe("s"); + expect(c.publicUrl).toBe("https://x.test"); +}); + +test("production without a secret throws", () => { + expect(() => loadConfig({ NODE_ENV: "production" })).toThrow(/STC_SECRET/); + expect(loadConfig({ NODE_ENV: "production", STC_SECRET: "x" }).secret).toBe("x"); +}); diff --git a/packages/core/test/jobs.test.ts b/packages/core/test/jobs.test.ts new file mode 100644 index 0000000..d65a5ad --- /dev/null +++ b/packages/core/test/jobs.test.ts @@ -0,0 +1,61 @@ +import { expect } from "bun:test"; +import { forEachDb } from "../../db/test/helpers"; +import { jobsRepo } from "@stc/db"; +import { createJobQueue } from "../src"; + +const until = async (f: () => Promise) => { + for (let i = 0; i < 200; i++) { if (await f()) return; await Bun.sleep(10); } + throw new Error("timeout"); +}; + +forEachDb("job runs to done with result and persisted progress", async (db) => { + const q = createJobQueue(db, { + ok: async (p, jc) => { await jc.reportProgress(0.5, "half"); return { echoed: p }; }, + }, { pollMs: 10 }); + q.start(); + try { + const id = await q.enqueue("ok", { a: 1 }); + await until(async () => (await q.get(id))?.status === "done"); + const j = (await q.get(id))!; + expect(j.result).toEqual({ echoed: { a: 1 } }); + expect(j.message).toBe("half"); + expect(j.progress).toBe(1); + } finally { await q.stop(); } +}); + +forEachDb("throwing handler gives failed with message", async (db) => { + const q = createJobQueue(db, { bad: async () => { throw new Error("boom"); } }, { pollMs: 10 }); + q.start(); + try { + const id = await q.enqueue("bad", null); + await until(async () => (await q.get(id))?.status === "failed"); + expect((await q.get(id))!.error).toBe("boom"); + } finally { await q.stop(); } +}); + +forEachDb("progress updates persist while running", async (db) => { + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const q = createJobQueue(db, { slow: async (_p, jc) => { await jc.reportProgress(0.3, "working"); await gate; return 1; } }, { pollMs: 10 }); + q.start(); + try { + const id = await q.enqueue("slow", null); + await until(async () => (await q.get(id))?.progress === 0.3); + expect((await q.get(id))!.status).toBe("running"); + expect((await q.get(id))!.message).toBe("working"); + release(); + await until(async () => (await q.get(id))?.status === "done"); + } finally { release(); await q.stop(); } +}); + +forEachDb("stale running job is requeued at start", async (db) => { + const id = await jobsRepo(db).insert("ok", { z: 1 }); + await jobsRepo(db).claimNext(["ok"]); + expect((await jobsRepo(db).get(id))!.status).toBe("running"); + const q = createJobQueue(db, { ok: async () => "again" }, { pollMs: 10 }); + q.start(); + try { + await until(async () => (await q.get(id))?.status === "done"); + expect((await q.get(id))!.result).toBe("again"); + } finally { await q.stop(); } +}); diff --git a/packages/core/test/media.test.ts b/packages/core/test/media.test.ts new file mode 100644 index 0000000..10fdb74 --- /dev/null +++ b/packages/core/test/media.test.ts @@ -0,0 +1,59 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { serveMedia } from "../src"; + +const dir = mkdtempSync(join(tmpdir(), "stc-media-")); +const file = join(dir, "clip.mp4"); +const bytes = new Uint8Array(1000).map((_, i) => i % 251); +writeFileSync(file, bytes); +const req = (range?: string) => new Request("http://x/m", { headers: range ? { Range: range } : {} }); + +test("full file gives 200", async () => { + const r = await serveMedia(req(), file); + expect(r.status).toBe(200); + expect(r.headers.get("content-type")).toBe("video/mp4"); + expect(r.headers.get("accept-ranges")).toBe("bytes"); + expect(r.headers.get("content-length")).toBe("1000"); + expect((await r.arrayBuffer()).byteLength).toBe(1000); +}); + +test("bytes=0-99 gives 206 with Content-Range", async () => { + const r = await serveMedia(req("bytes=0-99"), file); + expect(r.status).toBe(206); + expect(r.headers.get("content-range")).toBe("bytes 0-99/1000"); + expect(r.headers.get("content-length")).toBe("100"); + expect(new Uint8Array(await r.arrayBuffer())).toEqual(bytes.slice(0, 100)); +}); + +test("open-ended, suffix and clamped ranges", async () => { + let r = await serveMedia(req("bytes=900-"), file); + expect(r.status).toBe(206); + expect(r.headers.get("content-range")).toBe("bytes 900-999/1000"); + r = await serveMedia(req("bytes=-10"), file); + expect(r.headers.get("content-range")).toBe("bytes 990-999/1000"); + expect(new Uint8Array(await r.arrayBuffer())).toEqual(bytes.slice(990)); + r = await serveMedia(req("bytes=990-5000"), file); + expect(r.headers.get("content-range")).toBe("bytes 990-999/1000"); +}); + +test("unsatisfiable range gives 416", async () => { + const r = await serveMedia(req("bytes=999999999-"), file); + expect(r.status).toBe(416); + expect(r.headers.get("content-range")).toBe("bytes */1000"); +}); + +test("non-ASCII filename gets a valid filename*", async () => { + const f = join(dir, "Æble notes.pdf"); + writeFileSync(f, "pdf"); + const r = await serveMedia(req(), f, { download: true }); + expect(r.headers.get("content-type")).toBe("application/pdf"); + const cd = r.headers.get("content-disposition")!; + expect(cd).toContain("filename*=UTF-8''%C3%86ble%20notes.pdf"); + expect(cd).toContain('filename="_ble notes.pdf"'); +}); + +test("missing file is 404", async () => { + expect((await serveMedia(req(), join(dir, "nope.mp4"))).status).toBe(404); +}); diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 7dba514..ec4d4e5 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -5,3 +5,4 @@ export { notesRepo, type Note, type NoteInput } from "./repos/notes"; export { attemptsRepo, type Attempt } from "./repos/attempts"; export { libraryRepo, type Collection } from "./repos/library"; export { jobsRepo, type JobPatch } from "./repos/jobs"; +export { aclRepo, type AclEntry } from "./repos/acl"; diff --git a/packages/db/src/repos/acl.ts b/packages/db/src/repos/acl.ts new file mode 100644 index 0000000..d5ccd50 --- /dev/null +++ b/packages/db/src/repos/acl.ts @@ -0,0 +1,16 @@ +import type { Db } from "../connect"; + +export interface AclEntry { principal_type: "user" | "group"; principal_id: string } + +export function aclRepo(db: Db) { + return { + async listForCourse(courseId: string): Promise { + const rows = await db.sql`SELECT principal_type, principal_id FROM course_acl WHERE course_id = ${courseId} ORDER BY principal_type, principal_id`; + return rows.map((r: AclEntry) => ({ principal_type: r.principal_type, principal_id: r.principal_id })); + }, + async isAuthor(courseId: string, userId: string): Promise { + const rows = await db.sql`SELECT 1 AS x FROM course_authors WHERE course_id = ${courseId} AND user_id = ${userId}`; + return rows.length > 0; + }, + }; +} diff --git a/packages/db/test/acl.test.ts b/packages/db/test/acl.test.ts new file mode 100644 index 0000000..ad0c6fc --- /dev/null +++ b/packages/db/test/acl.test.ts @@ -0,0 +1,17 @@ +import { expect } from "bun:test"; +import { forEachDb } from "./helpers"; +import { aclRepo } from "../src"; + +forEachDb("aclRepo lists ACL rows and detects authors", async (db) => { + await db.sql`INSERT INTO course_acl (course_id, principal_type, principal_id) VALUES ('c', 'user', 'u1'), ('c', 'group', 'g1'), ('d', 'user', 'u2')`; + await db.sql`INSERT INTO course_authors (course_id, user_id) VALUES ('c', 'a1')`; + const r = aclRepo(db); + expect(await r.listForCourse("c")).toEqual([ + { principal_type: "group", principal_id: "g1" }, + { principal_type: "user", principal_id: "u1" }, + ]); + expect(await r.listForCourse("none")).toEqual([]); + expect(await r.isAuthor("c", "a1")).toBe(true); + expect(await r.isAuthor("c", "u1")).toBe(false); + expect(await r.isAuthor("d", "a1")).toBe(false); +}); From 05eee4cd4086aacf02b3718621b2ba5d42491fb3 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Fri, 30 Oct 2026 03:05:49 +0100 Subject: [PATCH 14/14] feat: server entry and web shell with design tokens Co-Authored-By: Claude Opus 5.5 --- apps/server/src/main.ts | 44 +++++++++++++++++++++ apps/server/test/server.test.ts | 36 +++++++++++++++++ apps/web/index.html | 14 +++++++ apps/web/src/features.ts | 4 ++ apps/web/src/main.tsx | 39 ++++++++++++++++++ bun.lock | 29 ++++++++++++++ package.json | 9 +++++ packages/ui/src/AppShell.tsx | 13 ++++++ packages/ui/src/fonts.css | 7 ++++ packages/ui/src/index.ts | 2 + packages/ui/src/primitives.tsx | 46 ++++++++++++++++++++++ packages/ui/src/tokens.css | 59 ++++++++++++++++++++++++++++ packages/ui/test/primitives.test.tsx | 19 +++++++++ 13 files changed, 321 insertions(+) create mode 100644 apps/server/src/main.ts create mode 100644 apps/server/test/server.test.ts create mode 100644 apps/web/index.html create mode 100644 apps/web/src/features.ts create mode 100644 apps/web/src/main.tsx create mode 100644 packages/ui/src/AppShell.tsx create mode 100644 packages/ui/src/fonts.css create mode 100644 packages/ui/src/index.ts create mode 100644 packages/ui/src/primitives.tsx create mode 100644 packages/ui/src/tokens.css create mode 100644 packages/ui/test/primitives.test.tsx diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts new file mode 100644 index 0000000..9b43b71 --- /dev/null +++ b/apps/server/src/main.ts @@ -0,0 +1,44 @@ +import type { AppConfig, AuthService, Feature, JobHandler, ServerContext } from "@stc/contracts"; +import { createApp, createJobQueue, loadConfig } from "@stc/core"; +import { createCourseRepository } from "@stc/course-format"; +import { connect, migrate } from "@stc/db"; +import indexHtml from "../../web/index.html"; + +// Temporary: the learner package replaces this with real sessions. +const anonymousAuth: AuthService = { userFromRequest: async () => null }; + +export async function startServer( + config: AppConfig, + features: Feature[], + _webFeatures?: unknown, +): Promise<{ server: Bun.Server; stop(): Promise }> { + const db = await connect(config.databaseUrl); + await migrate(db); + const courses = await createCourseRepository(config.courseDirs); + const handlers: Record = {}; + for (const f of features) Object.assign(handlers, f.jobs); + const jobs = createJobQueue(db, handlers); + const ctx: ServerContext = { config, db, courses, jobs, auth: anonymousAuth }; + const app = createApp(ctx, features); + jobs.start(); + const server = Bun.serve({ + port: config.port, + // Bun routes win over fetch; "/api/*" falls through to the composed app (404 for unknown API paths). + routes: { ...app.routes, "/api/*": (req) => app.fetch(req), "/*": indexHtml }, + fetch: (req) => app.fetch(req), + }); + return { + server, + async stop() { + await server.stop(true); + await jobs.stop(); + await db.close(); + }, + }; +} + +if (import.meta.main) { + const config = loadConfig(); + const { server } = await startServer(config, []); + console.log(`STCourses listening on ${server.url}`); +} diff --git a/apps/server/test/server.test.ts b/apps/server/test/server.test.ts new file mode 100644 index 0000000..8f17abb --- /dev/null +++ b/apps/server/test/server.test.ts @@ -0,0 +1,36 @@ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { resolve } from "node:path"; +import { loadConfig } from "@stc/core"; +import { startServer } from "../src/main"; + +let s: Awaited>; +let base: string; +beforeAll(async () => { + const config = loadConfig({ + STC_PORT: "0", STC_DATABASE_URL: "sqlite://:memory:", STC_SECRET: "t", + STC_COURSE_DIRS: resolve(import.meta.dir, "../../../fixtures/courses"), + }); + s = await startServer(config, []); + base = s.server.url.toString().replace(/\/$/, ""); +}); +afterAll(() => s.stop()); + +test("health reports the fixture course", async () => { + expect(await (await fetch(`${base}/api/health`)).json()).toEqual({ ok: true, courses: 1, db: "sqlite" }); +}); + +test("SPA paths return the HTML shell", async () => { + const r = await fetch(`${base}/some/spa/path`); + expect(r.status).toBe(200); + expect(await r.text()).toContain('
'); +}); + +test("unknown API paths are 404, not the SPA", async () => { + expect((await fetch(`${base}/api/nope`)).status).toBe(404); +}); + +test("media honours Range", async () => { + const r = await fetch(`${base}/api/media/sample/media/clip.mp4`, { headers: { Range: "bytes=0-9" } }); + expect(r.status).toBe(206); + expect((await r.arrayBuffer()).byteLength).toBe(10); +}); diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..2d79c9a --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,14 @@ + + + + + + STCourses + + + + +
+ + + diff --git a/apps/web/src/features.ts b/apps/web/src/features.ts new file mode 100644 index 0000000..8b077c9 --- /dev/null +++ b/apps/web/src/features.ts @@ -0,0 +1,4 @@ +import type { WebFeature } from "@stc/contracts"; + +// Phase 1 packages append one import line each and push into this list. +export const webFeatures: WebFeature[] = []; diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx new file mode 100644 index 0000000..a9afe98 --- /dev/null +++ b/apps/web/src/main.tsx @@ -0,0 +1,39 @@ +import { createRoot } from "react-dom/client"; +import { lazy, Suspense } from "react"; +import { createBrowserRouter, Link, Outlet, RouterProvider, type RouteObject } from "react-router-dom"; +import { AppShell } from "@stc/ui"; +import { webFeatures } from "./features"; + +function Home() { + return

No features installed yet

; +} + +function Layout() { + const nav = webFeatures.flatMap((f) => f.routes.filter((r) => r.nav?.area === "header")); + const header = ( + <> + STCourses + + + ); + return ( + + + + ); +} + +const featureRoutes: RouteObject[] = webFeatures.flatMap((f) => + f.routes.map((r) => { + const Element = lazy(r.element); + return { path: r.path, element: }; + }), +); + +const router = createBrowserRouter([ + { element: , children: [...featureRoutes, ...(featureRoutes.some((r) => r.path === "/") ? [] : [{ path: "*", element: }])] }, +]); + +createRoot(document.getElementById("root")!).render(); diff --git a/bun.lock b/bun.lock index 736e0ae..15e30fe 100644 --- a/bun.lock +++ b/bun.lock @@ -4,8 +4,17 @@ "workspaces": { "": { "name": "stcourses", + "dependencies": { + "@fontsource/ibm-plex-mono": "^5.3.0", + "@fontsource/ibm-plex-sans": "^5.3.0", + "@fontsource/literata": "^5.3.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router-dom": "6", + }, "devDependencies": { "@types/react": "^19", + "@types/react-dom": "^19.3.0", "bun-types": "^1.3.14", "typescript": "^5", }, @@ -59,6 +68,14 @@ }, }, "packages": { + "@fontsource/ibm-plex-mono": ["@fontsource/ibm-plex-mono@5.3.0", "", {}, "sha512-eTgnZjZEGk1QtD3ZstF+Vclo2HLAni8YMy34/DxllwZvyz1lR/1RF/xTiAquOBO7MvqBx8D2Ig2WCPMVfdZu7Q=="], + + "@fontsource/ibm-plex-sans": ["@fontsource/ibm-plex-sans@5.3.0", "", {}, "sha512-CbE4CbbEEZJX860XyUiRpsksXIQR8Rp2XDva2VO53NJox9tVNtusrysd2x5YkUEY3ErQ66W1IiiQL8/wihhw5w=="], + + "@fontsource/literata": ["@fontsource/literata@5.3.0", "", {}, "sha512-9JGMT5+YfBK49thoMq9ASaMRJErHT4V4QuMhAEwKHRLreOsIMP2xP6ZRLhPJ0e6YlET+kjWTJuN7LAxt9/gWGQ=="], + + "@remix-run/router": ["@remix-run/router@1.23.4", "", {}, "sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q=="], + "@stc/contracts": ["@stc/contracts@workspace:packages/contracts"], "@stc/core": ["@stc/core@workspace:packages/core"], @@ -85,10 +102,22 @@ "@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="], + "@types/react-dom": ["@types/react-dom@19.3.0", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="], + "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], + + "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], + + "react-router": ["react-router@6.30.6", "", { "dependencies": { "@remix-run/router": "1.23.4" }, "peerDependencies": { "react": ">=16.8" } }, "sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg=="], + + "react-router-dom": ["react-router-dom@6.30.6", "", { "dependencies": { "@remix-run/router": "1.23.4", "react-router": "6.30.6" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-0RHKZz7wwffvkU+2MFVT2NnjK44ssLEV+m0CAJaS2Ksmorrwj7WxH00jO0SOCW26/tINUnJHToXblDs33I38YQ=="], + + "scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="], + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], "undici-types": ["undici-types@8.12.3", "", {}, "sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA=="], diff --git a/package.json b/package.json index 341e6f2..87fe586 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,16 @@ }, "devDependencies": { "@types/react": "^19", + "@types/react-dom": "^19.3.0", "bun-types": "^1.3.14", "typescript": "^5" + }, + "dependencies": { + "@fontsource/ibm-plex-mono": "^5.3.0", + "@fontsource/ibm-plex-sans": "^5.3.0", + "@fontsource/literata": "^5.3.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router-dom": "6" } } diff --git a/packages/ui/src/AppShell.tsx b/packages/ui/src/AppShell.tsx new file mode 100644 index 0000000..31e23d6 --- /dev/null +++ b/packages/ui/src/AppShell.tsx @@ -0,0 +1,13 @@ +import type { ReactNode } from "react"; + +export function AppShell({ header, sidebar, children }: { header?: ReactNode; sidebar?: ReactNode; children: ReactNode }) { + return ( + <> + {header ?
{header}
: null} +
+ {sidebar ? : null} +
{children}
+
+ + ); +} diff --git a/packages/ui/src/fonts.css b/packages/ui/src/fonts.css new file mode 100644 index 0000000..0bd8525 --- /dev/null +++ b/packages/ui/src/fonts.css @@ -0,0 +1,7 @@ +@import "@fontsource/ibm-plex-sans/400.css"; +@import "@fontsource/ibm-plex-sans/500.css"; +@import "@fontsource/ibm-plex-sans/600.css"; +@import "@fontsource/ibm-plex-mono/400.css"; +@import "@fontsource/literata/400.css"; +@import "@fontsource/literata/600.css"; +@import "@fontsource/literata/400-italic.css"; diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts new file mode 100644 index 0000000..11877ed --- /dev/null +++ b/packages/ui/src/index.ts @@ -0,0 +1,2 @@ +export { AppShell } from "./AppShell"; +export { Pill, SegmentedToggle, ProgressBar, FloatingActionBar, CourseCover, monogram } from "./primitives"; diff --git a/packages/ui/src/primitives.tsx b/packages/ui/src/primitives.tsx new file mode 100644 index 0000000..efa08a4 --- /dev/null +++ b/packages/ui/src/primitives.tsx @@ -0,0 +1,46 @@ +import type { ButtonHTMLAttributes, CSSProperties, ReactNode } from "react"; + +export function Pill({ variant = "default", className, ...rest }: { variant?: "default" | "primary" | "ghost" } & ButtonHTMLAttributes) { + const cls = ["stc-pill", variant !== "default" && `stc-pill--${variant}`, className].filter(Boolean).join(" "); + return + ))} +
+ ); +} + +export function ProgressBar({ value, dim, label }: { value: number; dim?: boolean; label: string }) { + const pct = Math.round(Math.min(1, Math.max(0, value)) * 100); + return ( + + + + ); +} + +export function FloatingActionBar({ children }: { children: ReactNode }) { + return
{children}
; +} + +export function monogram(title: string): string { + const words = title.trim().split(/\s+/).filter(Boolean); + const letters = words.length >= 2 ? [words[0]![0], words[1]![0]] : Array.from(words[0] ?? "?").slice(0, 2); + return letters.join("").toUpperCase(); +} + +export function CourseCover({ title, image, accent }: { title: string; image?: string; accent?: string }) { + const style = accent ? ({ "--cfg": accent } as CSSProperties) : undefined; + return ( +
+ {image ? : } +
+ ); +} diff --git a/packages/ui/src/tokens.css b/packages/ui/src/tokens.css new file mode 100644 index 0000000..b0beebb --- /dev/null +++ b/packages/ui/src/tokens.css @@ -0,0 +1,59 @@ +:root { + --ground: #12141a; --side: #181b22; --raised: #232733; --line: #262a33; --line2: #343947; + --text: #d9dce3; --read: #d9d4c8; --head: #f2efe8; --muted: #a4abb8; --faint: #8c93a0; + --accent: #f1b44c; --accent-dim: #8c7440; --on-accent: #12141a; + --ok: #86c79f; --bad: #ee8f8f; + --sans: "IBM Plex Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; + --serif: "Literata", Georgia, "Times New Roman", serif; + --mono: "IBM Plex Mono", ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace; + --top: 52px; --sidew: 296px; --fast: 140ms; + color-scheme: dark; +} +*, *::before, *::after { box-sizing: border-box; } +body { margin: 0; background: var(--ground); color: var(--text); font: 400 14px/1.5 var(--sans); -webkit-font-smoothing: antialiased; } +a { color: inherit; } +button, input, textarea { font: inherit; color: inherit; } +button { cursor: pointer; } +code, pre { font-family: var(--mono); } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +::selection { background: color-mix(in srgb, var(--accent) 35%, transparent); } +.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } + +.reading { font-family: var(--serif); font-size: 19px; line-height: 1.75; color: var(--read); max-width: 660px; } +.work { font-family: var(--sans); font-size: 15.5px; line-height: 1.6; color: var(--text); max-width: 760px; } + +/* shell */ +.stc-top { position: sticky; top: 0; z-index: 30; height: var(--top); display: flex; align-items: center; gap: 14px; padding: 0 16px; background: var(--ground); border-bottom: 1px solid var(--line); } +.stc-shell { display: flex; align-items: flex-start; } +.stc-side { position: sticky; top: var(--top); flex: none; width: var(--sidew); height: calc(100vh - var(--top)); overflow-y: auto; background: var(--side); border-right: 1px solid var(--line); } +.stc-main { flex: 1; min-width: 0; padding: 44px 40px 0; } + +/* pill */ +.stc-pill { display: inline-flex; align-items: center; gap: 8px; height: 34px; padding: 0 15px; border: 1px solid var(--line2); border-radius: 18px; background: none; font-size: 13px; font-weight: 500; text-decoration: none; white-space: nowrap; transition: background var(--fast), color var(--fast), border-color var(--fast); } +.stc-pill:hover { background: var(--raised); } +.stc-pill--primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); } +.stc-pill--primary:hover { background: color-mix(in srgb, var(--accent) 86%, #fff); } +.stc-pill--ghost { border-color: transparent; color: var(--muted); } +.stc-pill--ghost:hover { color: var(--text); } +.stc-pill:disabled { opacity: .45; cursor: default; } + +/* segmented toggle */ +.stc-seg { display: inline-flex; padding: 2px; border: 1px solid var(--line2); border-radius: 20px; flex: none; } +.stc-seg button { border: 0; background: none; height: 28px; padding: 0 13px; border-radius: 16px; font-size: 12.5px; font-weight: 500; color: var(--faint); transition: background var(--fast), color var(--fast); } +.stc-seg button:hover { color: var(--text); } +.stc-seg button[aria-pressed="true"] { background: var(--raised); color: var(--head); } + +/* progress */ +.stc-bar { display: block; flex: 1; height: 4px; border-radius: 2px; background: var(--line); overflow: hidden; } +.stc-bar > i { display: block; height: 100%; background: var(--accent); border-radius: 2px; } +.stc-bar--dim > i { background: var(--accent-dim); } + +/* floating action bar */ +.stc-dock { position: sticky; bottom: 18px; z-index: 10; display: flex; width: max-content; max-width: 100%; margin: 56px auto 18px; gap: 4px; padding: 5px; background: var(--raised); border: 1px solid var(--line2); border-radius: 24px; box-shadow: 0 0 0 10px var(--ground); } +.stc-dock .stc-pill { height: 36px; border-color: transparent; } +.stc-dock .stc-pill:hover { background: var(--line2); } +.stc-dock .stc-pill--primary:hover { background: color-mix(in srgb, var(--accent) 86%, #fff); } + +/* cover */ +.stc-cover { flex: none; position: relative; width: var(--cw, 44px); aspect-ratio: 3 / 4; border-radius: 6px; background: var(--cbg, var(--raised)); color: var(--cfg, var(--accent)); border: 1px solid color-mix(in srgb, var(--cfg, var(--accent)) 18%, transparent); overflow: hidden; font: 600 calc(var(--cw, 44px) * .34) / 1 var(--sans); letter-spacing: -.03em; display: flex; align-items: flex-end; padding: calc(var(--cw, 44px) * .12); } +.stc-cover img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; } diff --git a/packages/ui/test/primitives.test.tsx b/packages/ui/test/primitives.test.tsx new file mode 100644 index 0000000..775fbf1 --- /dev/null +++ b/packages/ui/test/primitives.test.tsx @@ -0,0 +1,19 @@ +import { expect, test } from "bun:test"; +import { renderToString } from "react-dom/server"; +import { CourseCover, ProgressBar, SegmentedToggle } from "../src"; + +test("ProgressBar exposes aria-valuenow as a percentage", () => { + const html = renderToString(); + expect(html).toContain('role="progressbar"'); + expect(html).toContain('aria-valuenow="40"'); +}); + +test("CourseCover without an image shows a two-letter monogram", () => { + expect(renderToString()).toContain(">PS<"); + expect(renderToString()).toContain(">DO<"); +}); + +test("SegmentedToggle marks the active option", () => { + const html = renderToString( {}} options={[{ value: "a", label: "A" }, { value: "b", label: "B" }]} />); + expect(html).toMatch(/aria-pressed="true"[^>]*>B