包文件→ .shtukbase/packages/tui/lib/tui.ts
lib/tui.ts
314 行, 14.6 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // The shared part of the tui package: find the Shtukbase binary with the terminal front, reach a node that serves this
- // project, run one text command of the front and turn its terminal output into plain lines.
- // Bun only, no dependencies. The working directory is the project root.
- //
- // The terminal front reads every screen through the local node (`sb_space::reads` behind `sb-client`). The node serves
- // the projects listed in its home (`<home>/spaces.md` → space `index.md` → `projects:`). When the person's own node
- // (`$SHTUKBASE_HOME` or `~/.shtukbase`) does not serve this project, the package starts a node of its own in a
- // temporary home that lists only this project, and stops it after the command.
- import { spawn, spawnSync } from 'node:child_process';
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
- import { tmpdir } from 'node:os';
- import { basename, delimiter, dirname, join, resolve } from 'node:path';
- /** A binary that has the terminal front. `prefix` is put before the text command (`tui` for `shtukbase`). */
- export type Bin = { path: string; prefix: string[]; version: string; from: string; canServe: boolean };
- export const INSTALL_HINT =
- 'install Shtukbase: `curl -fsSL https://releases.shtukbase.com/install.sh | sh` or build from source ' +
- '(`cd engine && cargo build --release -p shtukbase`), or point SHTUK_TUI_BIN to the file';
- function isFile(p: string): boolean {
- return statSync(p, { throwIfNoEntry: false })?.isFile() ?? false;
- }
- /** `shtukbase --version` → the version line; null when the file does not run. */
- function versionOf(path: string): string | null {
- const r = spawnSync(path, ['--version'], { encoding: 'utf8', timeout: 10_000 });
- if (r.error || r.status !== 0) return null;
- return (r.stdout || '').trim().split('\n')[0] ?? '';
- }
- /** The binary at `path`, if it is a Shtukbase binary with the terminal front (or the front's own example binary). */
- function probe(path: string, from: string): Bin | null {
- if (!isFile(path)) return null;
- if (basename(path) === 'tui') {
- // engine/target/<profile>/examples/tui: the front alone, commands without the `tui` word, no node of its own.
- return { path, prefix: [], version: 'sb-tui (example)', from, canServe: false };
- }
- const v = versionOf(path);
- if (v === null || !v.startsWith('shtukbase')) return null;
- if (v.includes('tui: off')) return null; // built without the terminal front
- return { path, prefix: ['tui'], version: v, from, canServe: true };
- }
- /** Shtukbase checkouts this project knows of: $SHTUKBASE_REPO, the folders of locally installed packages, the
- * folders around the project. A checkout is a folder with `engine/Cargo.toml`. */
- export function checkouts(root: string): string[] {
- const out: string[] = [];
- const add = (p: string | undefined) => {
- if (p && existsSync(join(p, 'engine', 'Cargo.toml')) && !out.includes(resolve(p))) out.push(resolve(p));
- };
- add(process.env.SHTUKBASE_REPO);
- const lock = join(root, '.shtukbase', 'packages.lock');
- if (existsSync(lock)) {
- for (const m of readFileSync(lock, 'utf8').matchAll(/^\s+source:\s*"?([^"\n]+?)"?\s*$/gm)) {
- const at = m[1].indexOf('/apps/standard/packages/');
- if (at > 0) add(m[1].slice(0, at));
- }
- }
- for (let d = resolve(root); ; d = dirname(d)) {
- add(d);
- if (dirname(d) === d) break;
- }
- return out;
- }
- /** Finds the binary: $SHTUK_TUI_BIN (an explicit choice wins), then `shtukbase` on PATH, then
- * `engine/target/<profile>/shtukbase` and `engine/target/<profile>/examples/tui` in a known checkout. */
- export function findBin(root: string): { bin: Bin | null; tried: string[] } {
- const tried: string[] = [];
- const env = process.env.SHTUK_TUI_BIN;
- if (env) {
- tried.push(`SHTUK_TUI_BIN=${env}`);
- const b = probe(resolve(root, env), 'SHTUK_TUI_BIN');
- if (b) return { bin: b, tried };
- }
- for (const dir of (process.env.PATH || '').split(delimiter)) {
- if (!dir) continue;
- const p = join(dir, 'shtukbase');
- if (!isFile(p)) continue;
- tried.push(p);
- const b = probe(p, 'PATH');
- if (b) return { bin: b, tried };
- }
- for (const repo of checkouts(root)) {
- const target = join(repo, 'engine', 'target');
- const profiles = existsSync(target)
- ? readdirSync(target).filter((n) => statSync(join(target, n), { throwIfNoEntry: false })?.isDirectory())
- : [];
- const order = (n: string) => (n === 'release' ? 0 : n === 'hot' ? 1 : n === 'debug' ? 3 : 2);
- profiles.sort((a, b) => order(a) - order(b));
- for (const name of ['shtukbase', join('examples', 'tui')]) {
- for (const prof of profiles) {
- const p = join(target, prof, name);
- if (!isFile(p)) continue;
- tried.push(p);
- const b = probe(p, `build ${repo}`);
- if (b) return { bin: b, tried };
- }
- }
- tried.push(`${target}/*/shtukbase (none)`);
- }
- return { bin: null, tried };
- }
- /** A node that serves the project. `env` goes to every front command; `stop` ends a node the package started. */
- export type Node = { env: Record<string, string>; own: boolean; stop: () => void; note: string };
- function homeOf(): string {
- return process.env.SHTUKBASE_HOME || join(process.env.HOME || '', '.shtukbase');
- }
- /** Pages of `/automations` that a node could run. A temporary node is not started over them unless asked. */
- export function automationPages(root: string): number {
- const dir = join(root, 'automations');
- if (!existsSync(dir)) return 0;
- return readdirSync(dir).filter((n) => n.endsWith('.md')).length;
- }
- /** Runs a front command and returns its code, raw output (escape codes kept) and error text. */
- export function front(bin: Bin, node: Node, args: string[], root: string, extra: Record<string, string> = {}): { status: number; out: string; err: string } {
- const r = spawnSync(bin.path, [...bin.prefix, ...args], {
- cwd: root,
- encoding: 'utf8',
- timeout: 60_000,
- env: { ...process.env, ...node.env, ...extra, SHTUKBASE_COLOR: '1' },
- maxBuffer: 64 * 1024 * 1024,
- });
- return { status: r.status ?? 1, out: r.stdout || '', err: (r.stderr || '') + (r.error ? String(r.error) : '') };
- }
- /** Errors that mean "this node does not serve the project", so another node may. */
- export function notServed(err: string): boolean {
- return /UnknownSpace|LocalNodeUnavailable|not registered|node is not running|space\.ambiguous/.test(err);
- }
- /** Reaches a node for the project: the person's own node first; then a temporary one (only with a binary that can
- * serve; over `/automations` pages only with `ownNode`). Returns the node or the one line that says why not. */
- export async function reachNode(bin: Bin, root: string, opts: { ownNode?: boolean } = {}): Promise<Node | string> {
- const mine: Node = { env: {}, own: false, stop: () => {}, note: `the owner's node (${homeOf()})` };
- const probeRun = front(bin, mine, ['sidebar', '--space', root, '--width', '40'], root);
- if (probeRun.status === 0 && probeRun.out.trim()) return mine;
- if (!notServed(probeRun.err)) return `TUI cannot read the project: ${firstLine(probeRun.err) || 'empty output'}`;
- if (!bin.canServe) return 'no own node is running or it does not know the project, and this binary has no `serve`: ' + INSTALL_HINT;
- const autos = automationPages(root);
- if (autos > 0 && !opts.ownNode) {
- return `the owner's node does not serve the project; not starting a temporary node: /automations has ${autos} pages, it could run them. ` +
- 'Add the project to the app (or to ~/.shtukbase/spaces.md) and start it, or pass --own-node';
- }
- return await startNode(bin, root);
- }
- function firstLine(s: string): string {
- return s.trim().split('\n')[0] ?? '';
- }
- /** Starts `shtukbase serve` in a temporary home that lists only this project; waits until it answers. */
- async function startNode(bin: Bin, root: string): Promise<Node | string> {
- const tmp = mkdtempSync(join(tmpdir(), 'shtuk-tui-'));
- const home = join(tmp, 'home');
- const space = join(tmp, 'space');
- for (const d of [home, space]) mkdirSync(d, { recursive: true });
- const abs = resolve(root);
- writeFileSync(join(home, 'spaces.md'), `---\ntype: Spaces\nspaces:\n - path: ${space}\n---\n`);
- writeFileSync(join(space, 'index.md'), `---\ntitle: tui\nprojects:\n - name: ${JSON.stringify(basename(abs))}\n path: ${JSON.stringify(abs)}\n---\n`);
- const child = spawn(bin.path, ['serve', '--home', home], {
- cwd: tmp,
- env: { ...process.env, SHTUKBASE_HOME: home },
- stdio: ['ignore', 'ignore', 'ignore'],
- detached: false,
- });
- let stopped = false;
- const stop = () => {
- if (stopped) return;
- stopped = true;
- try { child.kill('SIGTERM'); } catch { /* already gone */ }
- rmSync(tmp, { recursive: true, force: true });
- };
- for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) process.once(sig, () => { stop(); process.exit(130); });
- process.once('exit', stop);
- const node: Node = { env: { SHTUKBASE_HOME: home }, own: true, stop, note: 'the package\'s temporary node' };
- for (let i = 0; i < 100; i++) {
- if (child.exitCode !== null) break;
- if (existsSync(join(home, 'node.json'))) {
- const r = front(bin, node, ['sidebar', '--space', root, '--width', '40'], root);
- if (r.status === 0 && r.out.trim()) return node;
- if (!/LocalNodeUnavailable|connect/i.test(r.err)) { stop(); return `TUI cannot read the project: ${firstLine(r.err) || 'empty output'}`; }
- }
- await Bun.sleep(100);
- }
- stop();
- return 'the temporary node did not come up in 10 seconds (`shtukbase serve`)';
- }
- // ---- terminal output → plain lines ------------------------------------------------------------------------------
- const WIDE: [number, number][] = [
- [0x1100, 0x115f], [0x231a, 0x231b], [0x2329, 0x232a], [0x23e9, 0x23ec], [0x23f0, 0x23f0], [0x23f3, 0x23f3],
- [0x25fd, 0x25fe], [0x2614, 0x2615], [0x2648, 0x2653], [0x267f, 0x267f], [0x2693, 0x2693], [0x26a1, 0x26a1],
- [0x26aa, 0x26ab], [0x26bd, 0x26be], [0x26c4, 0x26c5], [0x26ce, 0x26ce], [0x26d4, 0x26d4], [0x26ea, 0x26ea],
- [0x26f2, 0x26f3], [0x26f5, 0x26f5], [0x26fa, 0x26fa], [0x26fd, 0x26fd], [0x2705, 0x2705], [0x270a, 0x270b],
- [0x2728, 0x2728], [0x274c, 0x274c], [0x274e, 0x274e], [0x2753, 0x2755], [0x2757, 0x2757], [0x2795, 0x2797],
- [0x27b0, 0x27b0], [0x27bf, 0x27bf], [0x2b1b, 0x2b1c], [0x2b50, 0x2b50], [0x2b55, 0x2b55], [0x2e80, 0x303e],
- [0x3041, 0x33ff], [0x3400, 0x4dbf], [0x4e00, 0x9fff], [0xa000, 0xa4cf], [0xac00, 0xd7a3], [0xf900, 0xfaff],
- [0xfe30, 0xfe4f], [0xff00, 0xff60], [0xffe0, 0xffe6], [0x1f004, 0x1f004], [0x1f0cf, 0x1f0cf], [0x1f18e, 0x1f18e],
- [0x1f191, 0x1f19a], [0x1f200, 0x1f251], [0x1f300, 0x1f64f], [0x1f680, 0x1f6ff], [0x1f7e0, 0x1f7eb],
- [0x1f90c, 0x1f9ff], [0x1fa70, 0x1faff], [0x20000, 0x3fffd],
- ];
- function width(cp: number): number {
- if (cp === 0x200d || (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0x0300 && cp <= 0x036f) || (cp >= 0x1f3fb && cp <= 0x1f3ff)) return 0;
- for (const [a, b] of WIDE) if (cp >= a && cp <= b) return 2;
- return 1;
- }
- /** Plays terminal output on a grid (cursor moves, line clears) and returns its lines without colours, trimmed. */
- export function render(raw: string): string[] {
- const grid: string[][] = [];
- let row = 0;
- let col = 0;
- const line = (r: number) => (grid[r] ??= []);
- const put = (ch: string, w: number) => {
- const l = line(row);
- if (w === 0) {
- const at = col > 0 ? col - 1 : 0;
- let k = at;
- while (k > 0 && l[k] === '') k--;
- l[k] = (l[k] ?? ' ') + ch;
- if (ch === '️' && l[k + 1] === undefined && col === k + 1) { l[k + 1] = ''; col++; }
- return;
- }
- while (l.length < col) l.push(' ');
- l[col] = ch;
- if (w === 2) l[col + 1] = '';
- col += w;
- };
- const chars = Array.from(raw);
- for (let i = 0; i < chars.length; i++) {
- const c = chars[i];
- if (c === '\x1b') {
- const n = chars[i + 1];
- if (n === '[') {
- let j = i + 2;
- let params = '';
- while (j < chars.length && !/[@-~]/.test(chars[j])) params += chars[j++];
- const fin = chars[j];
- i = j;
- const nums = params.replace(/^[?>=]/, '').split(';').map((x) => parseInt(x, 10));
- if (params.startsWith('?')) continue;
- if (fin === 'H' || fin === 'f') { row = (nums[0] || 1) - 1; col = (nums[1] || 1) - 1; }
- else if (fin === 'G') col = (nums[0] || 1) - 1;
- else if (fin === 'C') col += nums[0] || 1;
- else if (fin === 'D') col = Math.max(0, col - (nums[0] || 1));
- else if (fin === 'A') row = Math.max(0, row - (nums[0] || 1));
- else if (fin === 'B') row += nums[0] || 1;
- else if (fin === 'K') {
- const l = line(row);
- const mode = nums[0] || 0;
- if (mode === 2) l.length = 0;
- else if (mode === 0) l.length = Math.min(l.length, col);
- else for (let k = 0; k <= col && k < l.length; k++) l[k] = ' ';
- } else if (fin === 'J') {
- if ((nums[0] || 0) >= 2) grid.length = 0;
- else { line(row).length = Math.min(line(row).length, col); grid.length = Math.min(grid.length, row + 1); }
- }
- continue;
- }
- if (n === ']' || n === '_' || n === 'P' || n === '^') {
- // OSC, APC (kitty pictures), DCS (sixel), PM: up to BEL or ESC \.
- let j = i + 2;
- while (j < chars.length && chars[j] !== '\x07' && !(chars[j] === '\x1b' && chars[j + 1] === '\\')) j++;
- i = chars[j] === '\x07' ? j : j + 1;
- continue;
- }
- i += 1; // a two-character escape
- continue;
- }
- if (c === '\n') { row++; col = 0; continue; }
- if (c === '\r') { col = 0; continue; }
- const cp = c.codePointAt(0) ?? 32;
- if (cp < 0x20 || cp === 0x7f) continue;
- put(c, width(cp));
- }
- const lines = Array.from(grid, (l) => (l ?? []).join('').replace(/\s+$/, ''));
- while (lines.length && !lines[lines.length - 1]) lines.pop();
- return lines;
- }
- /** Parses `[address] [--flag value]... [--switch]` after the action's own words. */
- export function splitArgs(argv: string[]): { free: string[]; flags: string[]; ownNode: boolean } {
- const free: string[] = [];
- const flags: string[] = [];
- let ownNode = false;
- for (let i = 0; i < argv.length; i++) {
- const a = argv[i];
- if (a === '--own-node') { ownNode = true; continue; }
- if (a.startsWith('--')) {
- flags.push(a);
- const v = argv[i + 1];
- if (v !== undefined && !v.startsWith('--') && !['--desc', '--preview', '--time', '--index'].includes(a)) { flags.push(v); i++; }
- continue;
- }
- free.push(a);
- }
- return { free, flags, ownNode };
- }
- /** The binary or the one line that says what to do, with exit code 2. */
- export function needBin(root: string): Bin {
- const { bin } = findBin(root);
- if (bin) return bin;
- console.log(`tui: the Shtukbase binary with the text interface was not found; ${INSTALL_HINT}`);
- process.exit(2);
- }