@operad-io/tui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/package.json +27 -4
  4. package/src/actions.ts +997 -0
  5. package/src/app.ts +1665 -0
  6. package/src/args.ts +198 -0
  7. package/src/autostart.ts +302 -0
  8. package/src/client.ts +478 -0
  9. package/src/discover.ts +90 -0
  10. package/src/events.ts +345 -0
  11. package/src/index.ts +11 -0
  12. package/src/layout.ts +260 -0
  13. package/src/live.ts +113 -0
  14. package/src/markdown.ts +85 -0
  15. package/src/recent.ts +40 -0
  16. package/src/sanitize.ts +18 -0
  17. package/src/state.ts +3200 -0
  18. package/src/theme.ts +525 -0
  19. package/src/themes.ts +60 -0
  20. package/src/view/index.ts +1204 -0
  21. package/src/wrap.ts +156 -0
  22. package/theme.schema.json +197 -0
  23. package/themes/LICENSE-catppuccin +21 -0
  24. package/themes/LICENSE-dracula +21 -0
  25. package/themes/LICENSE-github +21 -0
  26. package/themes/LICENSE-kanagawa +21 -0
  27. package/themes/LICENSE-nord +21 -0
  28. package/themes/LICENSE-one +20 -0
  29. package/themes/LICENSE-rose-pine +21 -0
  30. package/themes/LICENSE-solarized +20 -0
  31. package/themes/LICENSE-tokyo-night +22 -0
  32. package/themes/README.md +81 -0
  33. package/themes/catppuccin-frappe.json +19 -0
  34. package/themes/catppuccin-latte.json +19 -0
  35. package/themes/catppuccin-macchiato.json +19 -0
  36. package/themes/catppuccin-mocha.json +19 -0
  37. package/themes/dracula.json +19 -0
  38. package/themes/github-dark.json +19 -0
  39. package/themes/github-light.json +19 -0
  40. package/themes/kanagawa-dragon.json +19 -0
  41. package/themes/kanagawa-lotus.json +19 -0
  42. package/themes/kanagawa-wave.json +19 -0
  43. package/themes/nord.json +19 -0
  44. package/themes/one-dark.json +19 -0
  45. package/themes/one-light.json +19 -0
  46. package/themes/rose-pine-dawn.json +19 -0
  47. package/themes/rose-pine-main.json +19 -0
  48. package/themes/solarized-dark.json +19 -0
  49. package/themes/solarized-light.json +19 -0
  50. package/themes/tokyo-night-day.json +19 -0
  51. package/themes/tokyo-night-night.json +19 -0
  52. package/tui.schema.json +24 -0
package/src/args.ts ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * The arguments an action asks a person for, read from the action's `args`
3
+ * JSON Schema. Nothing here knows a plugin: an enum is a list to pick from, an
4
+ * integer is a number between its bounds, a boolean is yes or no, a string a text.
5
+ * The note argument (`role: "note"`) is not here; the note input keeps it.
6
+ */
7
+
8
+ import type { ViewAction, ViewRow } from "@operad-io/engine";
9
+ import { sanitize } from "./sanitize.ts";
10
+
11
+ /** One value a person can pick. */
12
+ export interface ArgOption {
13
+ readonly value: string | number | boolean;
14
+ readonly label: string;
15
+ }
16
+
17
+ /** One argument to ask for. */
18
+ export interface ArgField {
19
+ readonly name: string;
20
+ readonly kind: "pick" | "number" | "text";
21
+ readonly integer: boolean;
22
+ readonly options: readonly ArgOption[];
23
+ readonly min?: number | undefined;
24
+ readonly max?: number | undefined;
25
+ readonly description?: string | undefined;
26
+ /** The option that is the current value, when the row or a default gives one. */
27
+ readonly current?: number | undefined;
28
+ /** An optional choice starts unset, so Enter keeps the action's default. */
29
+ readonly optional?: boolean | undefined;
30
+ /** The text a number or text input starts with. */
31
+ readonly initial: string;
32
+ /**
33
+ * Conditionals from the schema's `allOf` (`if` an earlier field is a value,
34
+ * `then` this field's own choices): when `by` has been answered `is`, the
35
+ * field takes these choices instead of `options`.
36
+ */
37
+ readonly variants?: readonly ArgVariant[] | undefined;
38
+ /** Set by `narrowField`: the answered branch gives nothing to pick, so the field is not asked. */
39
+ readonly skipped?: boolean | undefined;
40
+ }
41
+
42
+ /** The choices of a field once an earlier field has been answered. */
43
+ export interface ArgVariant {
44
+ readonly by: string;
45
+ readonly is: unknown;
46
+ readonly options: readonly ArgOption[];
47
+ readonly current?: number | undefined;
48
+ /** The chosen branch lists no choice for this field: it is not asked. */
49
+ readonly skip?: boolean | undefined;
50
+ }
51
+
52
+ /** `field` as it is once `values` are answered: the variant that matches, else as it is. */
53
+ export function narrowField(field: ArgField, values: Readonly<Record<string, unknown>>): ArgField {
54
+ const variant = field.variants?.find((one) => values[one.by] === one.is);
55
+ if (variant === undefined) return field;
56
+ return { ...field, options: variant.options, current: variant.current, skipped: variant.skip === true };
57
+ }
58
+
59
+ function variantsOf(schema: NonNullable<ViewAction["args"]>, name: string, seen: readonly (string | undefined)[]): ArgVariant[] {
60
+ const found: ArgVariant[] = [];
61
+ for (const branch of schema.allOf ?? []) {
62
+ const condition = Object.entries(branch.if?.properties ?? {}).find(([, one]) => one.const !== undefined);
63
+ const prop = branch.then?.properties?.[name];
64
+ if (condition === undefined) continue;
65
+ if (prop?.enum === undefined || prop.enum.length === 0) {
66
+ found.push({ by: condition[0], is: condition[1].const, options: [], skip: true });
67
+ continue;
68
+ }
69
+ const options = prop.enum.map((value) => ({ value, label: sanitize(String(value)) }));
70
+ const texts = [...seen.slice(0, 2), prop.default === undefined ? undefined : String(prop.default)];
71
+ const at = texts.map((text) => (text === undefined ? -1 : options.findIndex((o) => o.label === text))).find((i) => i >= 0);
72
+ found.push({ by: condition[0], is: condition[1].const, options, current: at });
73
+ }
74
+ return found;
75
+ }
76
+
77
+ export type ArgParse =
78
+ | { readonly ok: true; readonly value: string | number | boolean }
79
+ | { readonly ok: false; readonly reason: string };
80
+
81
+ /**
82
+ * The arguments of `action` other than the note, in the order it asks them:
83
+ * the required ones, then any optional enum (a choice that starts unset).
84
+ */
85
+ export function argFields(action: ViewAction, row: ViewRow | undefined): readonly ArgField[] {
86
+ const schema = action.args;
87
+ if (schema?.properties === undefined) return [];
88
+ const names = [...(schema.required ?? [])];
89
+ for (const [name, prop] of Object.entries(schema.properties)) {
90
+ if (names.includes(name) || prop.role === "note") continue;
91
+ if (prop.enum !== undefined && prop.enum.length > 0) names.push(name);
92
+ }
93
+ const fields: ArgField[] = [];
94
+ for (const name of names) {
95
+ const prop = schema.properties[name];
96
+ if (prop === undefined || prop.role === "note") continue;
97
+ const description = prop.description === undefined ? undefined : sanitize(prop.description);
98
+ const given = prop.default;
99
+ const seen = [row?.state, row?.badge, given === undefined ? undefined : String(given)];
100
+ if (prop.enum !== undefined && prop.enum.length > 0) {
101
+ const options = prop.enum.map((value) => ({ value, label: sanitize(String(value)) }));
102
+ const found = seen
103
+ .map((text) => (text === undefined ? -1 : options.findIndex((o) => o.label === text)))
104
+ .find((at) => at >= 0);
105
+ const optional = !(schema.required ?? []).includes(name);
106
+ const variants = variantsOf(schema, name, seen);
107
+ fields.push({
108
+ ...(variants.length === 0 ? {} : { variants }),
109
+ name,
110
+ kind: "pick",
111
+ integer: false,
112
+ options,
113
+ description,
114
+ current: found,
115
+ ...(optional ? { optional: true } : {}),
116
+ initial: "",
117
+ });
118
+ } else if (prop.type === "boolean") {
119
+ const options = [
120
+ { value: true, label: "yes" },
121
+ { value: false, label: "no" },
122
+ ];
123
+ const current = given === true ? 0 : given === false ? 1 : undefined;
124
+ fields.push({ name, kind: "pick", integer: false, options, description, current, initial: "" });
125
+ } else if (prop.type === "integer" || prop.type === "number") {
126
+ fields.push({
127
+ name,
128
+ kind: "number",
129
+ integer: prop.type === "integer",
130
+ options: [],
131
+ min: prop.minimum,
132
+ max: prop.maximum,
133
+ description,
134
+ initial: typeof given === "number" ? String(given) : "",
135
+ });
136
+ } else if (prop.type === "string") {
137
+ fields.push({
138
+ name,
139
+ kind: "text",
140
+ integer: false,
141
+ options: [],
142
+ min: prop.minLength,
143
+ max: prop.maxLength,
144
+ description,
145
+ initial: typeof given === "string" ? sanitize(given) : "",
146
+ });
147
+ }
148
+ }
149
+ return fields;
150
+ }
151
+
152
+ /** What the field accepts, in one line: shown when a value does not fit. */
153
+ export function allowedText(field: ArgField): string {
154
+ if (field.kind === "pick") return `${field.name}: ${field.options.map((o) => o.label).join(", ")}`;
155
+ if (field.kind === "number") {
156
+ const kind = field.integer ? "a whole number" : "a number";
157
+ const range =
158
+ field.min !== undefined && field.max !== undefined
159
+ ? ` from ${field.min} to ${field.max}`
160
+ : field.min !== undefined
161
+ ? ` of at least ${field.min}`
162
+ : field.max !== undefined
163
+ ? ` of at most ${field.max}`
164
+ : "";
165
+ return `${field.name}: ${kind}${range}`;
166
+ }
167
+ const size =
168
+ field.min !== undefined || field.max !== undefined
169
+ ? ` (${field.min ?? 0} to ${field.max ?? "any"} characters)`
170
+ : "";
171
+ return `${field.name}: text${size}`;
172
+ }
173
+
174
+ /** Checks typed text against the field, the way the server will. */
175
+ export function parseArg(field: ArgField, text: string): ArgParse {
176
+ const trimmed = text.trim();
177
+ const refuse = (): ArgParse => ({ ok: false, reason: allowedText(field) });
178
+ if (field.kind === "pick") {
179
+ const wanted = trimmed.toLowerCase();
180
+ const aliases: Record<string, string> = { y: "yes", n: "no", true: "yes", false: "no" };
181
+ const option = field.options.find(
182
+ (o) => o.label.toLowerCase() === wanted || (o.label === "yes" || o.label === "no" ? o.label === aliases[wanted] : false),
183
+ );
184
+ return option === undefined ? refuse() : { ok: true, value: option.value };
185
+ }
186
+ if (field.kind === "number") {
187
+ if (!(field.integer ? /^-?\d+$/ : /^-?\d+(\.\d+)?$/).test(trimmed)) return refuse();
188
+ const value = Number(trimmed);
189
+ if (!Number.isFinite(value)) return refuse();
190
+ if (field.min !== undefined && value < field.min) return refuse();
191
+ if (field.max !== undefined && value > field.max) return refuse();
192
+ return { ok: true, value };
193
+ }
194
+ const length = [...text].length;
195
+ if (trimmed === "" || (field.min !== undefined && length < field.min)) return refuse();
196
+ if (field.max !== undefined && length > field.max) return refuse();
197
+ return { ok: true, value: text };
198
+ }
@@ -0,0 +1,302 @@
1
+ /**
2
+ * `operad tui` starts `operad serve` itself when none answers: it probes the
3
+ * address, refuses to start a second serve for a home that already has one,
4
+ * starts one detached when the home is free, and waits for it to answer. It
5
+ * never opens the store and never loads a plugin.
6
+ */
7
+
8
+ import { spawn } from "node:child_process";
9
+ import {
10
+ closeSync,
11
+ fstatSync,
12
+ openSync,
13
+ readSync,
14
+ statSync,
15
+ } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { lastLines } from "@operad-io/engine/platform";
18
+ import {
19
+ lockHeld,
20
+ readConfig,
21
+ serveLockPath,
22
+ } from "@operad-io/engine";
23
+ import { defaultFetch, TuiError, type FetchLike } from "./client.ts";
24
+ import { urlFromConfig } from "./discover.ts";
25
+
26
+ /** How long the first probe waits for an answer. */
27
+ export const PROBE_TIMEOUT_MS = 1_500;
28
+
29
+ /** How long a started serve has to answer. */
30
+ export const START_TIMEOUT_MS = 15_000;
31
+
32
+ /** How often a started serve is probed. */
33
+ export const START_POLL_MS = 100;
34
+
35
+ /** The server could not be reached or started; the message says why. */
36
+ export class TuiStartError extends TuiError {
37
+ constructor(message: string) {
38
+ super(message, { kind: "start" });
39
+ this.name = "TuiStartError";
40
+ }
41
+ }
42
+
43
+ /** What a probe of `GET /v1/types` found. */
44
+ export type Probe = "operad" | "silent" | "other";
45
+
46
+ /**
47
+ * Asks the address for `/v1/types` without a token. An operad server answers
48
+ * either the list (`200`) or its own error body (`401`); anything else that
49
+ * answers is not operad, and nothing answering is silent.
50
+ */
51
+ export async function probeServer(
52
+ url: string,
53
+ fetchImpl: FetchLike = defaultFetch,
54
+ timeoutMs = PROBE_TIMEOUT_MS,
55
+ ): Promise<Probe> {
56
+ let response: Response;
57
+ try {
58
+ response = await fetchImpl(`${url}/v1/types`, {
59
+ headers: { accept: "application/json" },
60
+ signal: AbortSignal.timeout(timeoutMs),
61
+ });
62
+ } catch {
63
+ return "silent";
64
+ }
65
+ let body: unknown;
66
+ try {
67
+ body = await response.json();
68
+ } catch {
69
+ return "other";
70
+ }
71
+ if (typeof body !== "object" || body === null) return "other";
72
+ if (response.status === 200 && "types" in body && Array.isArray(body.types)) {
73
+ return "operad";
74
+ }
75
+ if (
76
+ response.status === 401 &&
77
+ "error" in body &&
78
+ typeof body.error === "object" &&
79
+ body.error !== null &&
80
+ "message" in body.error &&
81
+ typeof body.error.message === "string"
82
+ ) {
83
+ return "operad";
84
+ }
85
+ return "other";
86
+ }
87
+
88
+ /** A serve that was started: it resolves when the process has exited. */
89
+ export interface StartedServe {
90
+ readonly exited: Promise<number | null>;
91
+ /** The process id, when the system gave one. */
92
+ readonly pid?: number | undefined;
93
+ }
94
+
95
+ /** Starts `operad serve` for a home, appending its output to `log`. */
96
+ export type ServeSpawner = (log: string) => StartedServe;
97
+
98
+ /**
99
+ * The real spawner: the runtime and entry of the current process, detached
100
+ * from it so the serve keeps running after the TUI quits.
101
+ */
102
+ export function spawnServe(home: string, entry: string): ServeSpawner {
103
+ return (log) => {
104
+ const fd = openSync(log, "a");
105
+ try {
106
+ const child = spawn(process.execPath, [entry, "serve"], {
107
+ cwd: home,
108
+ env: { ...process.env, OPERAD_HOME: home },
109
+ detached: true,
110
+ stdio: ["ignore", fd, fd],
111
+ });
112
+ const exited = new Promise<number | null>((resolve) => {
113
+ child.once("error", () => resolve(null));
114
+ child.once("exit", (code) => resolve(code));
115
+ });
116
+ child.unref();
117
+ return { exited, pid: child.pid };
118
+ } finally {
119
+ closeSync(fd);
120
+ }
121
+ };
122
+ }
123
+
124
+ /** The options of `ensureServer`. */
125
+ export interface EnsureServerOptions {
126
+ readonly home: string;
127
+ readonly fetch?: FetchLike | undefined;
128
+ /** Required to start anything; without it nothing is started. */
129
+ readonly spawn?: ServeSpawner | undefined;
130
+ /** Prints the one line before the full screen opens. */
131
+ readonly write?: ((line: string) => void) | undefined;
132
+ readonly probeTimeoutMs?: number | undefined;
133
+ readonly startTimeoutMs?: number | undefined;
134
+ readonly pollMs?: number | undefined;
135
+ /** Tests inject a wait instead of a timer. */
136
+ readonly wait?: ((ms: number) => Promise<void>) | undefined;
137
+ /** The clock the start deadline is read from; probe time counts. */
138
+ readonly now?: (() => number) | undefined;
139
+ /** Tests inject the home lock check. */
140
+ readonly lockHeld?: ((path: string) => boolean) | undefined;
141
+ }
142
+
143
+ /** True when a serve's log says it could not listen because the port is taken. */
144
+ export function portInUse(text: string): boolean {
145
+ return /Failed to start server|EADDRINUSE|address already in use|port \d+ in use/i.test(text);
146
+ }
147
+
148
+ /** How many bytes a log holds now; a log that cannot be read holds none. */
149
+ function logSize(log: string): number {
150
+ try {
151
+ return statSync(log).size;
152
+ } catch {
153
+ return 0;
154
+ }
155
+ }
156
+
157
+ /** Reads a log from `offset` on; a log that cannot be read holds nothing. */
158
+ function readSince(log: string, offset: number): string {
159
+ try {
160
+ const fd = openSync(log, "r");
161
+ try {
162
+ const size = fstatSync(fd).size;
163
+ if (size <= offset) return "";
164
+ const buffer = Buffer.allocUnsafe(size - offset);
165
+ let read = 0;
166
+ while (read < buffer.length) {
167
+ const count = readSync(fd, buffer, read, buffer.length - read, offset + read);
168
+ if (count === 0) break;
169
+ read += count;
170
+ }
171
+ return buffer.subarray(0, read).toString("utf8");
172
+ } finally {
173
+ closeSync(fd);
174
+ }
175
+ } catch {
176
+ return "";
177
+ }
178
+ }
179
+
180
+ /** The end of a log, including at least `lines` newlines when the file has them. */
181
+ function readTail(log: string, lines: number): string {
182
+ const fd = openSync(log, "r");
183
+ try {
184
+ const size = fstatSync(fd).size;
185
+ if (size === 0) return "";
186
+ const chunkSize = 8192;
187
+ const chunks: Buffer[] = [];
188
+ let start = size;
189
+ let found = 0;
190
+ while (start > 0 && found <= lines) {
191
+ const from = Math.max(0, start - chunkSize);
192
+ const length = start - from;
193
+ const buffer = Buffer.allocUnsafe(length);
194
+ let read = 0;
195
+ while (read < length) {
196
+ const count = readSync(fd, buffer, read, length - read, from + read);
197
+ if (count === 0) break;
198
+ read += count;
199
+ }
200
+ const part = buffer.subarray(0, read);
201
+ chunks.unshift(part);
202
+ for (let index = part.length - 1; index >= 0; index -= 1) {
203
+ if (part[index] === 0x0a) found += 1;
204
+ }
205
+ start = from;
206
+ }
207
+ return Buffer.concat(chunks).toString("utf8");
208
+ } finally {
209
+ closeSync(fd);
210
+ }
211
+ }
212
+
213
+ function tailOf(log: string): string {
214
+ try {
215
+ const lines = lastLines(readTail(log, 10), 10);
216
+ return lines.length === 0 ? "(the log is empty)" : lines.join("\n");
217
+ } catch {
218
+ return "(no log was written)";
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Makes sure a serve answers at the address `config.json` names, starting one
224
+ * when none runs and none holds the home. Returns the URL.
225
+ */
226
+ export async function ensureServer(options: EnsureServerOptions): Promise<string> {
227
+ const { home } = options;
228
+ const config = await readConfig(home);
229
+ const url = urlFromConfig(config.http.listen, config.http.port);
230
+ const fetchImpl = options.fetch ?? defaultFetch;
231
+ const wait =
232
+ options.wait ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
233
+
234
+ const first = await probeServer(url, fetchImpl, options.probeTimeoutMs);
235
+ if (first === "operad") return url;
236
+ if (first === "other") {
237
+ throw new TuiStartError(
238
+ `something answers at ${url} (port ${config.http.port}) but it is not operad; change http.port in config.json or pass --url`,
239
+ );
240
+ }
241
+ if (!config.http.enabled) {
242
+ throw new TuiStartError(
243
+ `http.enabled is false in config.json, so no serve listens at ${url}; set it to true or pass --url`,
244
+ );
245
+ }
246
+ if ((options.lockHeld ?? lockHeld)(serveLockPath(home))) {
247
+ throw new TuiStartError(
248
+ `an operad serve already runs for this home but does not answer on ${url}; check http.enabled, http.listen and http.port in config.json`,
249
+ );
250
+ }
251
+ if (options.spawn === undefined) {
252
+ throw new TuiStartError(`no operad serve answers at ${url}`);
253
+ }
254
+
255
+ const log = join(home, "serve.log");
256
+ // Only what the started serve writes counts, not what older ones left.
257
+ const logBefore = logSize(log);
258
+ options.write?.(`starting operad serve (log: ${log})`);
259
+ const started = options.spawn(log);
260
+ let exitCode: number | null | undefined;
261
+ void started.exited.then((code) => {
262
+ exitCode = code;
263
+ });
264
+
265
+ const now = options.now ?? Date.now;
266
+ const lockCheck = options.lockHeld ?? lockHeld;
267
+ const timeout = options.startTimeoutMs ?? START_TIMEOUT_MS;
268
+ const step = options.pollMs ?? START_POLL_MS;
269
+ const deadline = now() + timeout;
270
+ // Another `operad tui` may have started the serve first. Our child then
271
+ // lost the lock and exited, and the winner is the one to wait for.
272
+ let adopted = false;
273
+ for (;;) {
274
+ if (exitCode !== undefined && !adopted) {
275
+ if (!lockCheck(serveLockPath(home))) {
276
+ if (portInUse(readSince(log, logBefore))) {
277
+ throw new TuiStartError(
278
+ `operad serve could not start: port ${config.http.port} is in use and does not answer on ${url}; another program may hold the port; log ${log}:\n${tailOf(log)}`,
279
+ );
280
+ }
281
+ throw new TuiStartError(
282
+ `operad serve exited at once${exitCode === null ? "" : ` (code ${exitCode})`}; log ${log}:\n${tailOf(log)}`,
283
+ );
284
+ }
285
+ adopted = true;
286
+ }
287
+ if ((await probeServer(url, fetchImpl, options.probeTimeoutMs)) === "operad") {
288
+ return url;
289
+ }
290
+ if (now() >= deadline) break;
291
+ await wait(step);
292
+ }
293
+ if (adopted) {
294
+ // The serve that holds the home lock is not ours and did not answer.
295
+ throw new TuiStartError(
296
+ `an operad serve already runs for this home but does not answer on ${url} within ${Math.round(timeout / 1000)} seconds; check http.enabled, http.listen and http.port in config.json; log ${log}:\n${tailOf(log)}`,
297
+ );
298
+ }
299
+ throw new TuiStartError(
300
+ `operad serve did not answer on ${url} within ${Math.round(timeout / 1000)} seconds; log ${log}:\n${tailOf(log)}`,
301
+ );
302
+ }