ShtukbaseStandard
package file→ .shtukbase/packages/lenses/actions/kit.mjs

actions/kit.mjs

44 lines, 2.3 KB.

  1. // Finds the lens kit and runs it on the project in the working directory. The kit (kit.js, kit.css, the
  2. // templates, the build and the server) lives in this package, in kit/: an install puts it at
  3. // .shtukbase/packages/lenses/kit/. SHTUK_KIT, when set, points to another copy of the kit (an override for kit work).
  4. import { spawn, spawnSync } from "node:child_process";
  5. import { existsSync } from "node:fs";
  6. import { dirname, join, resolve } from "node:path";
  7. import { fileURLToPath } from "node:url";
  8. /** The package's own copy of the kit: kit/ next to actions/. */
  9. export const OWN_KIT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "kit");
  10. const runner = process.versions.bun ? process.execPath : "bun";
  11. /** The kit folder (SHTUK_KIT, else the package's own copy), or null after saying what is wrong. */
  12. export function kitDir() {
  13. const dir = process.env.SHTUK_KIT ? resolve(process.env.SHTUK_KIT) : OWN_KIT;
  14. if (!existsSync(join(dir, "bin", "shtukbase-lenses.js"))) {
  15. const why = process.env.SHTUK_KIT ? "SHTUK_KIT does not point to a kit" : "the lenses package is not fully installed, reinstall it";
  16. console.log(`kit not found in ${dir}: ${why}`);
  17. return null;
  18. }
  19. return dir;
  20. }
  21. /** Runs the kit's lens command line (`build` or `check`) on the project; returns its exit code. */
  22. export function lenses(cmd) {
  23. const dir = kitDir();
  24. if (!dir) return 2;
  25. const r = spawnSync(runner, [join(dir, "bin", "shtukbase-lenses.js"), cmd, "--root", process.cwd()], { encoding: "utf8" });
  26. // Findings go to stdout, one per line; the kit writes its complaint to stderr.
  27. for (const line of `${r.stdout ?? ""}${r.stderr ?? ""}`.split("\n")) if (line.trim()) console.log(line);
  28. return r.status ?? 1;
  29. }
  30. /** Runs the kit's server on the project until it stops; a signal is passed on, so no server is left behind. */
  31. export function serve(port) {
  32. const dir = kitDir();
  33. if (!dir) return Promise.resolve(2);
  34. console.log(`project ${process.cwd()} is open at http://127.0.0.1:${port}/ (Ctrl-C to stop)`);
  35. return new Promise((done) => {
  36. const child = spawn(runner, [join(dir, "server", "serve.ts"), process.cwd(), String(port)], { stdio: "inherit" });
  37. for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => child.kill(sig));
  38. child.on("exit", (code, sig) => done(code ?? (sig ? 0 : 1)));
  39. });
  40. }