@intellectual-frontiers/terminal 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.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/args.d.ts +240 -0
- package/dist/args.js +328 -0
- package/dist/commands.d.ts +103 -0
- package/dist/commands.js +127 -0
- package/dist/mod.d.ts +19 -0
- package/dist/mod.js +20 -0
- package/dist/palette.d.ts +44 -0
- package/dist/palette.js +84 -0
- package/dist/vt.d.ts +78 -0
- package/dist/vt.js +486 -0
- package/dist/width.d.ts +63 -0
- package/dist/width.js +170 -0
- package/package.json +63 -4
- package/src/args.ts +547 -0
- package/src/commands.ts +182 -0
- package/src/mod.ts +20 -0
- package/src/palette.ts +104 -0
- package/src/vt.ts +497 -0
- package/src/width.ts +181 -0
package/src/commands.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Spec: 0001-terminal FR-002
|
|
2
|
+
/**
|
|
3
|
+
* A command tree declared once as data (commons 0005-typescript-runtime FR-072): a command of groups and verbs to any depth, each with a
|
|
4
|
+
* name and a summary, and each verb with its options (`./args.ts`'s declaration) and its arguments. From that declaration alone it
|
|
5
|
+
* resolves an argument vector to the verb it names, to the help asked for, or to a typed error that names the word not known, where, the
|
|
6
|
+
* words known there and the nearest of them; and it renders the help of every level, so that help never runs a verb.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* A group named with no verb asks for its help, as `git remote` with no verb would list; `--help` or `-h` anywhere before `--` asks for
|
|
10
|
+
* the help of the deepest group or verb named before it. Unknown options of a verb are its own parser's business (`parseArgs`), which the
|
|
11
|
+
* verb runs on the arguments left to it.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { group, resolveCommand, verb } from "./commands.ts";
|
|
16
|
+
* const tree = group({ name: "tool", summary: "A tool.", children: [group({ name: "work", summary: "Works.", children: [
|
|
17
|
+
* verb({ name: "build", summary: "Build.", options: {} }),
|
|
18
|
+
* ] })] });
|
|
19
|
+
* resolveCommand(tree, ["work", "build", "a"]); // ok: the verb build, with ["a"] left
|
|
20
|
+
* resolveCommand(tree, ["wrk"]); // err: wrk is not known at the top, did you mean work?
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* @module
|
|
24
|
+
*/
|
|
25
|
+
import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
|
|
26
|
+
import { helpOf, type Operand, type Spec, type SpecCheck, suggest } from "./args.ts";
|
|
27
|
+
|
|
28
|
+
/** An example of a verb: the words after the verb, and what it does. */
|
|
29
|
+
export type Example = { readonly args: readonly string[]; readonly says: string };
|
|
30
|
+
|
|
31
|
+
/** A verb: a leaf of the tree, with the options and arguments it takes. */
|
|
32
|
+
export type Verb<S extends Spec = Spec> = {
|
|
33
|
+
readonly kind: "verb";
|
|
34
|
+
readonly name: string;
|
|
35
|
+
readonly summary: string;
|
|
36
|
+
readonly options: S;
|
|
37
|
+
readonly operands: readonly Operand[];
|
|
38
|
+
readonly examples: readonly Example[];
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** A group: a word that names more words, groups or verbs. */
|
|
42
|
+
export type Group = {
|
|
43
|
+
readonly kind: "group";
|
|
44
|
+
readonly name: string;
|
|
45
|
+
readonly summary: string;
|
|
46
|
+
readonly children: readonly CommandNode[];
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** One node of a command tree. */
|
|
50
|
+
export type CommandNode = Group | Verb;
|
|
51
|
+
|
|
52
|
+
/** A verb, declared with its options checked as `parseArgs` checks them. */
|
|
53
|
+
export function verb<S extends Spec>(v: {
|
|
54
|
+
readonly name: string;
|
|
55
|
+
readonly summary: string;
|
|
56
|
+
readonly options: S & SpecCheck<S>;
|
|
57
|
+
readonly operands?: readonly Operand[];
|
|
58
|
+
readonly examples?: readonly Example[];
|
|
59
|
+
}): Verb<S> {
|
|
60
|
+
return { kind: "verb", name: v.name, summary: v.summary, options: v.options, operands: v.operands ?? [], examples: v.examples ?? [] };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A group of nodes. */
|
|
64
|
+
export function group(g: { readonly name: string; readonly summary: string; readonly children: readonly CommandNode[] }): Group {
|
|
65
|
+
return { kind: "group", name: g.name, summary: g.summary, children: g.children };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Whether a name is one a command may have: lower case letters, digits and dashes, beginning with a letter. */
|
|
69
|
+
export function validCommandName(name: string): boolean {
|
|
70
|
+
return /^[a-z][a-z0-9-]*$/.test(name);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** What is wrong with a declared tree: a name that may not be one, or two children of a group with the same name. */
|
|
74
|
+
export type TreeProblem =
|
|
75
|
+
| { readonly kind: "bad-name"; readonly path: readonly string[]; readonly name: string }
|
|
76
|
+
| { readonly kind: "duplicate"; readonly path: readonly string[]; readonly name: string };
|
|
77
|
+
|
|
78
|
+
/** Every problem of a tree, in the order of its nodes; none where it is well formed. */
|
|
79
|
+
export function treeProblems(root: CommandNode, path: readonly string[] = []): readonly TreeProblem[] {
|
|
80
|
+
const here = [...path, root.name];
|
|
81
|
+
const own: TreeProblem[] = validCommandName(root.name) ? [] : [{ kind: "bad-name", path, name: root.name }];
|
|
82
|
+
switch (root.kind) {
|
|
83
|
+
case "verb":
|
|
84
|
+
return own;
|
|
85
|
+
case "group": {
|
|
86
|
+
const seen = new Set<string>();
|
|
87
|
+
const dups: TreeProblem[] = [];
|
|
88
|
+
for (const c of root.children) {
|
|
89
|
+
if (seen.has(c.name)) dups.push({ kind: "duplicate", path: here, name: c.name });
|
|
90
|
+
seen.add(c.name);
|
|
91
|
+
}
|
|
92
|
+
return [...own, ...dups, ...root.children.flatMap((c) => treeProblems(c, here))];
|
|
93
|
+
}
|
|
94
|
+
default:
|
|
95
|
+
return absurd(root);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** What an argument vector names: a verb with the arguments left for it, or the help of a node. */
|
|
100
|
+
export type Resolved =
|
|
101
|
+
| { readonly kind: "verb"; readonly path: readonly string[]; readonly verb: Verb; readonly args: readonly string[] }
|
|
102
|
+
| { readonly kind: "help"; readonly path: readonly string[]; readonly node: CommandNode };
|
|
103
|
+
|
|
104
|
+
/** Why an argument vector names nothing: a word not known below `path`, the words known there, and the nearest. */
|
|
105
|
+
export type CommandError = {
|
|
106
|
+
readonly kind: "unknown-command";
|
|
107
|
+
readonly path: readonly string[];
|
|
108
|
+
readonly word: string;
|
|
109
|
+
readonly known: readonly string[];
|
|
110
|
+
readonly suggestion: string | undefined;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/** Whether a word asks for help. */
|
|
114
|
+
export function asksForHelp(word: string): boolean {
|
|
115
|
+
return word === "--help" || word === "-h";
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Resolves an argument vector (the words after the program's name) against a tree whose root is the program. */
|
|
119
|
+
export function resolveCommand(root: Group, argv: readonly string[]): Result<Resolved, CommandError> {
|
|
120
|
+
let node: CommandNode = root;
|
|
121
|
+
const path: string[] = [root.name];
|
|
122
|
+
let i = 0;
|
|
123
|
+
while (node.kind === "group") {
|
|
124
|
+
const word = argv[i];
|
|
125
|
+
if (word === undefined || asksForHelp(word)) return ok({ kind: "help", path, node });
|
|
126
|
+
const known: readonly string[] = node.children.map((c) => c.name);
|
|
127
|
+
const next: CommandNode | undefined = node.children.find((c) => c.name === word);
|
|
128
|
+
if (next === undefined) {
|
|
129
|
+
const candidates = word.startsWith("-") ? ["--help"] : known;
|
|
130
|
+
return err({ kind: "unknown-command", path: [...path], word, known, suggestion: suggest(word, candidates) });
|
|
131
|
+
}
|
|
132
|
+
node = next;
|
|
133
|
+
path.push(next.name);
|
|
134
|
+
i += 1;
|
|
135
|
+
}
|
|
136
|
+
const args = argv.slice(i);
|
|
137
|
+
const end = args.indexOf("--");
|
|
138
|
+
const before = end < 0 ? args : args.slice(0, end);
|
|
139
|
+
if (before.some(asksForHelp)) return ok({ kind: "help", path, node });
|
|
140
|
+
return ok({ kind: "verb", path, verb: node, args });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** A command error as one sentence, with the help to run next. */
|
|
144
|
+
export function formatCommandError(e: CommandError): string {
|
|
145
|
+
const at = e.path.join(" ");
|
|
146
|
+
const what = e.word.startsWith("-") ? "an option" : "a command";
|
|
147
|
+
const near = e.suggestion === undefined ? "" : `; did you mean ${e.suggestion}?`;
|
|
148
|
+
return `${e.word} is not ${what} of ${at}${near} Run ${at} --help to see what it takes.`;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Lines of two columns, the second aligned two spaces after the widest first. */
|
|
152
|
+
function columns(rows: readonly (readonly [string, string])[]): readonly string[] {
|
|
153
|
+
const width = Math.max(0, ...rows.map(([l]) => l.length));
|
|
154
|
+
return rows.map(([l, r]) => ` ${l.padEnd(width)} ${r}`.trimEnd());
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The help of a node at `path` (the words that name it, the program's first), from its declaration alone. */
|
|
158
|
+
export function commandHelp(path: readonly string[], node: CommandNode): string {
|
|
159
|
+
const at = path.join(" ");
|
|
160
|
+
switch (node.kind) {
|
|
161
|
+
case "group": {
|
|
162
|
+
const rows = node.children.map((c): readonly [string, string] => [c.name, c.summary]);
|
|
163
|
+
return [
|
|
164
|
+
`${at}: ${node.summary}`,
|
|
165
|
+
"",
|
|
166
|
+
`Usage: ${at} COMMAND [OPTIONS] [ARGUMENTS]`,
|
|
167
|
+
"",
|
|
168
|
+
"Commands:",
|
|
169
|
+
...columns(rows),
|
|
170
|
+
"",
|
|
171
|
+
`Run ${at} COMMAND --help for a command's help.`,
|
|
172
|
+
].join("\n");
|
|
173
|
+
}
|
|
174
|
+
case "verb": {
|
|
175
|
+
const body = helpOf(at, node.summary, node.options, node.operands);
|
|
176
|
+
const examples = node.examples.map((x): readonly [string, string] => [[at, ...x.args].join(" "), x.says]);
|
|
177
|
+
return examples.length === 0 ? body : [body, "", "Examples:", ...columns(examples)].join("\n");
|
|
178
|
+
}
|
|
179
|
+
default:
|
|
180
|
+
return absurd(node);
|
|
181
|
+
}
|
|
182
|
+
}
|
package/src/mod.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Spec: 0001-terminal FR-006
|
|
2
|
+
/**
|
|
3
|
+
* The terminal, as pure code (commons terminal 0001-terminal): a typed command-line parser (`args`) and command trees (`commands`), the one palette of colour roles and marks (`palette`), display width
|
|
4
|
+
* and the cutting of a text by columns (`width`), and a small terminal emulator for snapshot tests (`vt`). Each is a namespace of this entry and an entry of its own (`@intellectual-frontiers/terminal/args`,
|
|
5
|
+
* and so on), so that a program imports what it uses; nothing here touches the host.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { args } from "@intellectual-frontiers/terminal";
|
|
10
|
+
* const options = { verbose: args.flag({ help: "Say more." }) };
|
|
11
|
+
* args.parseArgs(["--verbose"], { options, operands: [] }); // an Args value with options.verbose true
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* @module
|
|
15
|
+
*/
|
|
16
|
+
export * as args from "./args.ts";
|
|
17
|
+
export * as commands from "./commands.ts";
|
|
18
|
+
export * as palette from "./palette.ts";
|
|
19
|
+
export * as vt from "./vt.ts";
|
|
20
|
+
export * as width from "./width.ts";
|
package/src/palette.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Spec: 0001-terminal FR-003
|
|
2
|
+
/**
|
|
3
|
+
* The console's one palette (commons 0006-signals FR-022): the colour roles as a union type, and the marks a person reads at a glance,
|
|
4
|
+
* each with an ASCII fallback for a terminal with no emoji. Whether colour and emoji may be used is the terminal's (commons
|
|
5
|
+
* 0005-typescript-runtime FR-023, `runtime/tty.ts`'s `lookOf`); this module only obeys it: `paint` writes SGR sequences only where colour is
|
|
6
|
+
* allowed, and `mark` an emoji only where emoji are.
|
|
7
|
+
*
|
|
8
|
+
* `Capabilities` has the fields of the runtime's `Look` that output depends on (`colour`, `emoji`, `columns`, the same names), so a `Look`
|
|
9
|
+
* is a `Capabilities` as it is.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { label, mark, paint } from "./palette.ts";
|
|
14
|
+
* mark("done", { emoji: true }); // "✅"
|
|
15
|
+
* mark("done", { emoji: false }); // "[ok]"
|
|
16
|
+
* paint("failure", "3 failed", { colour: true }); // "\u001b[31m3 failed\u001b[0m"
|
|
17
|
+
* label("warning", "slow", { colour: false, emoji: false }); // "[!] slow"
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @module
|
|
21
|
+
*/
|
|
22
|
+
import { absurd } from "@intellectual-frontiers/core";
|
|
23
|
+
|
|
24
|
+
/** What the terminal written to can show: colour, emoji, and its width in columns (the fields of the runtime's `Look`). */
|
|
25
|
+
export type Capabilities = { readonly colour: boolean; readonly emoji: boolean; readonly columns: number };
|
|
26
|
+
|
|
27
|
+
/** What a piece of output means, and so its colour. */
|
|
28
|
+
export type Role = "success" | "failure" | "skipped" | "cancelled" | "hint" | "warning" | "dim" | "accent" | "plain";
|
|
29
|
+
|
|
30
|
+
/** Every role, in a fixed order. */
|
|
31
|
+
export const ROLES: readonly Role[] = ["success", "failure", "skipped", "cancelled", "hint", "warning", "dim", "accent", "plain"];
|
|
32
|
+
|
|
33
|
+
/** A mark at the start of a line: how something ended, or what a line is. */
|
|
34
|
+
export type MarkKind = "done" | "failed" | "skipped" | "cancelled" | "hint" | "warning" | "pending" | "action";
|
|
35
|
+
|
|
36
|
+
/** Every mark, in a fixed order. */
|
|
37
|
+
export const MARK_KINDS: readonly MarkKind[] = ["done", "failed", "skipped", "cancelled", "hint", "warning", "pending", "action"];
|
|
38
|
+
|
|
39
|
+
/** A mark as an emoji, its ASCII fallback, and the role it is painted in. */
|
|
40
|
+
export type MarkStyle = { readonly emoji: string; readonly ascii: string; readonly role: Role };
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The marks: ✅ ❌ ⏭️ ⏹️ 👉 ⚠️ ⏳ ⚡, and `[ok]` `[x]` `[skip]` `[stop]` `->` `[!]` `[todo]` `[you]` where there are no emoji. ❌ and ⚠️ are
|
|
44
|
+
* problems; ⏳ (pending) is something not set up yet, expected until someone does it; ⚡ (action) is a step that is the person's to take
|
|
45
|
+
* (send a change, back up, approve): nothing is wrong, so it is neither a warning nor an error (FR-027).
|
|
46
|
+
*/
|
|
47
|
+
export const MARKS: Readonly<Record<MarkKind, MarkStyle>> = {
|
|
48
|
+
done: { emoji: "✅", ascii: "[ok]", role: "success" },
|
|
49
|
+
failed: { emoji: "❌", ascii: "[x]", role: "failure" },
|
|
50
|
+
skipped: { emoji: "\u{23ed}\u{fe0f}", ascii: "[skip]", role: "skipped" },
|
|
51
|
+
cancelled: { emoji: "\u{23f9}\u{fe0f}", ascii: "[stop]", role: "cancelled" },
|
|
52
|
+
hint: { emoji: "👉", ascii: "->", role: "hint" },
|
|
53
|
+
warning: { emoji: "\u{26a0}\u{fe0f}", ascii: "[!]", role: "warning" },
|
|
54
|
+
pending: { emoji: "\u{23f3}", ascii: "[todo]", role: "dim" },
|
|
55
|
+
action: { emoji: "\u{26a1}", ascii: "[you]", role: "accent" },
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** A mark: its emoji where the terminal shows emoji, else its ASCII fallback. */
|
|
59
|
+
export function mark(kind: MarkKind, caps: { readonly emoji: boolean }): string {
|
|
60
|
+
const m = MARKS[kind];
|
|
61
|
+
return caps.emoji ? m.emoji : m.ascii;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The SGR parameters of a role; empty for `plain`. */
|
|
65
|
+
export function sgrOf(role: Role): string {
|
|
66
|
+
switch (role) {
|
|
67
|
+
case "success":
|
|
68
|
+
return "32";
|
|
69
|
+
case "failure":
|
|
70
|
+
return "31";
|
|
71
|
+
case "skipped":
|
|
72
|
+
return "33";
|
|
73
|
+
case "cancelled":
|
|
74
|
+
return "35";
|
|
75
|
+
case "hint":
|
|
76
|
+
return "36";
|
|
77
|
+
case "warning":
|
|
78
|
+
return "33;1";
|
|
79
|
+
case "dim":
|
|
80
|
+
return "2";
|
|
81
|
+
case "accent":
|
|
82
|
+
return "1";
|
|
83
|
+
case "plain":
|
|
84
|
+
return "";
|
|
85
|
+
default:
|
|
86
|
+
return absurd(role);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const ESC = String.fromCharCode(0x1b);
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A text in a role's colour, followed by a reset, where colour is allowed; the text as it is where it is not, for the role `plain`, and for
|
|
94
|
+
* an empty text. Painted texts are put side by side, not inside one another: the inner reset would end the outer colour.
|
|
95
|
+
*/
|
|
96
|
+
export function paint(role: Role, text: string, caps: { readonly colour: boolean }): string {
|
|
97
|
+
const sgr = sgrOf(role);
|
|
98
|
+
return caps.colour && sgr !== "" && text !== "" ? `${ESC}[${sgr}m${text}${ESC}[0m` : text;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A line's beginning: the mark painted in its role, a space, and the text. */
|
|
102
|
+
export function label(kind: MarkKind, text: string, caps: { readonly colour: boolean; readonly emoji: boolean }): string {
|
|
103
|
+
return `${paint(MARKS[kind].role, mark(kind, caps), caps)} ${text}`;
|
|
104
|
+
}
|