ShtukbaseStandard
файл пакета→ .shtukbase/packages/live/server/run.ts

server/run.ts

94 строки, 4.5 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // Running package actions for a page: only those the project allowed in `run:` of /base/live.md. An action runs
  2. // the way `shtuk run` runs it: its file from .shtukbase/packages/<id>/, with the project root as the working folder.
  3. // `shtuk check` runs every check of the project, the way `shtuk check` does.
  4. import { existsSync, readFileSync } from 'node:fs';
  5. import { extname, join } from 'node:path';
  6. import { parseYaml, pystr, splitFrontMatter } from '../../collections/checks/lib/pages.ts';
  7. import { Refused } from './records.ts';
  8. import { CHECK_ALL, PAGE } from './settings.ts';
  9. export const TIMEOUT_MS = 120_000;
  10. const BUN = process.versions.bun ? process.execPath : 'bun';
  11. type Action = { name: string; run: string; check?: boolean };
  12. /** Ids of the installed packages (the lock), in name order. */
  13. function installed(root: string): string[] {
  14. const f = join(root, '.shtukbase', 'packages.lock');
  15. if (!existsSync(f)) return [];
  16. const lock = parseYaml(readFileSync(f, 'utf8'));
  17. return Object.keys((lock.packages as object) ?? {}).sort();
  18. }
  19. export function actionsOf(root: string, pkg: string): Action[] {
  20. const f = join(root, '.shtukbase', 'packages', pkg, 'package.md');
  21. if (!existsSync(f)) return [];
  22. const fm = parseYaml(splitFrontMatter(readFileSync(f, 'utf8'))[0]);
  23. return (Array.isArray(fm.actions) ? fm.actions : []).filter((a: any) => a && a.name && a.run)
  24. .map((a: any) => ({ name: pystr(a.name), run: pystr(a.run), check: a.check === true }));
  25. }
  26. function command(file: string, args: string[]): string[] {
  27. const ext = extname(file);
  28. if (ext === '.py') return ['python3', file, ...args];
  29. if (['.ts', '.js', '.mjs'].includes(ext)) return [BUN, file, ...args];
  30. return [file, ...args];
  31. }
  32. export type Step = { title: string; cmd: string[] };
  33. /** What a request runs, after the allow list; throws Refused with the reason. */
  34. export function plan(root: string, allow: string[], pkg: unknown, action: unknown, args: unknown): Step[] {
  35. const p = pystr(pkg ?? '').trim(), a = pystr(action ?? '').trim();
  36. const key = `${p} ${a}`;
  37. if (!allow.includes(key))
  38. throw new Refused(`action "${key}" is not allowed: the project allows actions by the run: list on the page ${PAGE}${allow.length ? ` (now: ${allow.join(', ')})` : ' (it is empty now)'}`);
  39. const list = Array.isArray(args) ? args.map((x) => pystr(x)) : args == null ? [] : null;
  40. if (!list) throw new Refused('args must be a list of strings');
  41. if (key === CHECK_ALL) {
  42. const steps: Step[] = [];
  43. for (const id of installed(root))
  44. for (const x of actionsOf(root, id).filter((x) => x.check))
  45. steps.push({ title: `${id}/${x.name}`, cmd: command(join(root, '.shtukbase', 'packages', id, x.run), []) });
  46. return steps;
  47. }
  48. if (!installed(root).includes(p)) throw new Refused(`package ${p} is not installed in the project`);
  49. const found = actionsOf(root, p).find((x) => x.name === a);
  50. if (!found) throw new Refused(`package ${p} has no action ${a}`);
  51. return [{ title: `${p}/${a}`, cmd: command(join(root, '.shtukbase', 'packages', p, found.run), list) }];
  52. }
  53. export type Event = { type: 'start'; step: string } | { type: 'out'; text: string } | { type: 'end'; step: string; code: number } | { type: 'exit'; code: number };
  54. /** Runs the steps one after another; every line of output and every end is an event. The exit code is that of
  55. * the last failed step, else 0. `signal` stops the running step. */
  56. export async function execute(root: string, steps: Step[], emit: (e: Event) => void, signal?: AbortSignal): Promise<number> {
  57. let worst = 0;
  58. for (const s of steps) {
  59. if (signal?.aborted) break;
  60. emit({ type: 'start', step: s.title });
  61. const child = Bun.spawn(s.cmd, { cwd: root, stdout: 'pipe', stderr: 'pipe', stdin: 'ignore' });
  62. const kill = () => child.kill();
  63. signal?.addEventListener('abort', kill);
  64. const timer = setTimeout(kill, TIMEOUT_MS);
  65. const pump = async (stream: ReadableStream<Uint8Array>) => {
  66. const dec = new TextDecoder();
  67. let rest = '';
  68. for await (const chunk of stream) {
  69. rest += dec.decode(chunk, { stream: true });
  70. const lines = rest.split('\n');
  71. rest = lines.pop()!;
  72. for (const l of lines) emit({ type: 'out', text: l });
  73. }
  74. if (rest) emit({ type: 'out', text: rest });
  75. };
  76. await Promise.all([pump(child.stdout), pump(child.stderr)]);
  77. const code = await child.exited;
  78. clearTimeout(timer);
  79. signal?.removeEventListener('abort', kill);
  80. emit({ type: 'end', step: s.title, code });
  81. if (code !== 0) worst = code;
  82. }
  83. emit({ type: 'exit', code: worst });
  84. return worst;
  85. }