-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
716 lines (702 loc) · 21.7 KB
/
cli.js
File metadata and controls
716 lines (702 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
// @ts-check
/**
* Command Line Interpreter – a console GUI element for text-based user interaction within web applications.
* @version 1.1.0
* @copyright (c) 2025 Christoph Zager
* @license MIT
* @link https://github.com/chzager/cli
*/
class CommandLineInterpreter
{
/**
* @typedef CommandLineInterpreterOptions
* @property {boolean} richtextEnabled Enable or disable formatting the output text on the CLI.
* @property {number} tabWidth Minimum whitespace string for tab-separated (`\t`) values in output. Default is two.
*/
/**
* The basic built-in commands for every CLI.
* @type {Record<string, CommandLineInterpreterCommandCallback>}
*/
static builtInCommands = {
/** Clear the entire output of the current session. */
"clear": (cli, ...args) =>
{
switch (args?.[0])
{
case "--?":
cli.writeLn("Usage: clear")
.writeLn("Clear all output.");
break;
case undefined:
cli.body.replaceChildren();
break;
default:
cli.writeLn(`clear: Invalid argument: ${args[0]}`);
}
},
/** Display a list of all available commands (including the built-in). */
"help": (cli, ...args) =>
{
switch (args?.[0])
{
case "--?":
cli.writeLn("Usage: help")
.writeLn("Display a list of all available commands.");
break;
case undefined:
cli.writeLn("These are the available commands:")
.writeLn(Array.from(cli.commands.keys())
.sort()
.map(s => `\t${s}`).join("\n")
)
.writeLn("\nTry `<command> --?` for more information on a specific command.");
break;
default:
cli.writeLn(`help: Invalid argument: ${args[0]}`);
}
},
/** Display or manage the input history. */
"history": (cli, ...args) =>
{
switch (args?.[0])
{
case "--?":
cli.writeLn("Usage: history [option]")
.writeLn("Display or manage the list of all that has been entered.")
.writeLn("Optional arguments to manage the history:")
.writeLn([
" \t--clean\tRemove duplicate entries and invalid commands",
" \t--clear\tClean the entire history",
" \t--limit [<n>]\tDisplay or set the limit of history items"
].join("\n"));
break;
case "--clear":
cli.history = [];
cli.history.position = -1;
cli.memorize("history", cli.history);
break;
case "--clean":
const builtInCommandNames = Object.keys(CommandLineInterpreter.builtInCommands);
const validCommands = Array.from(cli.commands.keys()).filter(s => !builtInCommandNames.includes(s));
cli.history = Array.from(new Set(cli.history)).filter(s => validCommands.includes(/^\S+/.exec(s)?.[0] ?? ""));
cli.history.position = cli.history.length;
cli.memorize("history", cli.history);
cli.writeLn("The history has been cleaned.");
break;
case "--limit":
const limitValue = cli.getNamedArgumentValue(args, "--limit") || cli.history.limit;
if ((typeof limitValue === "number") || (/[0-9]+/.test(limitValue)))
{
cli.history.limit = Number(limitValue);
cli.history.splice(0, cli.history.length - cli.history.limit);
cli.writeLn(`The history is limited to ${cli.history.limit} itmes.`);
cli.memorize("history", cli.history);
cli.memorize("history_limit", cli.history.limit);
}
else
{
cli.writeLn(`history: Not a number: ${limitValue}`);
}
break;
case undefined:
cli.writeLn(cli.history.map(s => s.replace(/([*_])/g, "\\$1")).join("\n"));
break;
default:
cli.writeLn(`history: Invalid argument: ${args[0]}`);
}
}
};
/**
* @param {Record<string, CommandLineInterpreterCommandCallback>} commands Custom commands to be available in this CLI.
* @param {HTMLElement} [target] HTML element on the document where the CLI element shall be displayed.
* @param {CommandLineInterpreterInitOptions} [options] Options for this CLI.
*/
constructor(commands, target, options)
{
const keyHandler = (/** @type {KeyboardEvent} */ event) =>
{
const inputEle = /** @type {HTMLElement} */(event.target);
switch (event.key)
{
case "PageUp":
this.body.scrollBy(0, 0 - (this.body.clientHeight - 10));
break;
case "PageDown":
this.body.scrollBy(0, (this.body.clientHeight - 10));
break;
case "ArrowUp":
if ((this.history.position > 0) && (this.history.length > 0))
{
event.preventDefault();
this.history.position -= 1;
inputEle.innerText = this.history[this.history.position];
const selection = window.getSelection();
if (!!selection)
{
selection.removeAllRanges();
const range = document.createRange();
range.setStartAfter(inputEle.childNodes[0]);
selection.addRange(range);
}
};
break;
case "ArrowDown":
if (this.history.position < this.history.length)
{
this.history.position += 1;
inputEle.innerText = (this.history.position === this.history.length) ? "" : this.history[this.history.position];
};
break;
case "Escape":
inputEle.innerText = "";
break;
case "Enter":
const inputString = inputEle.innerText;
inputEle.replaceWith(CommandLineInterpreter.createElement("span.input", inputString + "\n"));
if (/\w/.test(inputString))
{
if (this.history[this.history.length - 1] !== inputString)
{
this.history.push(inputString.trim());
}
this.history.splice(0, this.history.length - this.history.limit);
this.history.position = this.history.length;
this.memorize("history", this.history);
}
this.eval(inputString.trim())
.finally(() =>
{
this.receiveInput(this.prompt, keyHandler);
});
}
};
/**
* String to be used as command prompt.
*/
this.prompt = options?.prompt || "\nCLI> ";
/**
* Options of this CLI.
* @type {CommandLineInterpreterOptions}
*/
this.options = {
richtextEnabled: options?.richtextEnabled ?? true,
tabWidth: options?.tabWidth || 2
};
/**
* ID of the current CLI instance. This is used for appliance of CSS styles and storing
* data in the browser's local storage.
*/
this.id = options?.id || this.constructor.name;
if (options?.theme !== "custom")
{
const themeFileUrl = `link[rel="stylesheet"][href="https://cdn.jsdelivr.net/gh/chzager/cli/themes/${options?.theme || "default"}.css"]`;
if (!document.head.querySelector(themeFileUrl))
{
document.head.append(CommandLineInterpreter.createElement(themeFileUrl));
}
}
const storedData = JSON.parse(localStorage.getItem(this.id) || "{}");
/**
* The input history. This is also stored in the `localStorage`.
* @type {Array<string> & {position?: number, limit?: number}}
*/
this.history = storedData?.history ?? [];
this.history.limit = Number(storedData?.history_limit) || 50;
this.history.position = this.history.length;
/**
* Available commands in this CLI.
* @type {Map<string, CommandLineInterpreterCommandCallback>}
*/
this.commands = new Map();
for (const commandProvider of [CommandLineInterpreter.builtInCommands, commands])
{
for (const [command, func] of Object.entries(commandProvider))
{
if (typeof func === "function")
{
this.commands.set(command, func);
}
}
}
/**
* This CLI's HTML element.
*/
// @ts-ignore missing deprecated property 'align'.
this.body = (target instanceof HTMLElement) ? target : document.body.appendChild(CommandLineInterpreter.createElement("div"));
this.body.classList.add(CommandLineInterpreter.name.toLowerCase());
this.body.onclick = () =>
{
if (window.getSelection()?.toString() === "")
{
const inputEle = this.body.querySelector(`.input[contenteditable="true"]`);
if (inputEle instanceof HTMLElement)
{
inputEle.focus();
}
}
};
if (!!options?.motd)
{
this.writeLn(options.motd);
}
this.eval(options?.startup ?? "")
.then(() =>
{
this.receiveInput(this.prompt, keyHandler);
});
}
/**
* Evaluate a string expression of commands or variable assignments.
* Multiple commands/assignments are separated by semi-colon (`;`) or line break (`\n`).
* @param {string} expr Expression to evaluate.
* @returns A `Promise` that resolves once all commands have been fully processed.
*/
eval (expr)
{
return /** @type {Promise<void>} */(new Promise(resolve =>
{
const handleError = (/** @type {Error} */ error) =>
{
this.writeLn(`\x1b[31m${error}`);
console.error(error);
};
const evaluate = (/** @type {string} */ string) =>
{
return /** @type {Promise<void>} */(new Promise(resolve =>
{
let immediateContinue = true;
const inputValues = /(\S+)(.*)/.exec(string);
if (!!inputValues)
{
const cmd = inputValues[1];
const commandFunction = this.commands.get(cmd);
if (typeof commandFunction === "function")
{
const args = [];
for (const argMatch of (inputValues[2] ?? "").matchAll(/"([^"]*)"|\S+/g))
{
args.push(argMatch[1] || argMatch[0]);
}
try
{
const cmdResult = commandFunction(this, ...args);
if (cmdResult instanceof Promise)
{
immediateContinue = false;
cmdResult
.catch(handleError)
.finally(resolve);
}
}
catch (error)
{
handleError(error);
}
}
else
{
this.writeLn(`Unknown command: ${cmd}`);
}
}
if (immediateContinue)
{
resolve();
}
}));
};
const iterateChunk = () =>
{
const chunk = chunks.shift();
if (!!chunk)
{
evaluate(chunk).finally(iterateChunk);
}
else
{
resolve();
}
};
const chunks = expr.split(/\s*[;\n]+\s*/).filter(s => !!s.trim());
iterateChunk();
}));
}
/**
* Internal generic user input receiver.
*
* You should use either {@linkcode readLn()} or {@linkcode readKey()}.
* @param {string} prompt The prompt to be printed before the input.
* @param {(ev: KeyboardEvent) => any} keyHandler Event handler for keyboard events.
* @protected
*/
receiveInput (prompt, keyHandler)
{
this.body.normalize();
this.write(prompt);
const inputEle = CommandLineInterpreter.createElement(`span.input[contenteditable="true"][spellcheck="false"][autocorrect="off"][autocapitalize="none"]`);
inputEle.addEventListener("paste", (/** @type {ClipboardEvent} */ evt) =>
{
evt.preventDefault();
const clipboardText = evt.clipboardData.getData('text/plain');
const selection = window.getSelection();
if (selection)
{
const selectRange = selection.getRangeAt(0);
const oldRangeStart = selectRange.startOffset;
const inputText = inputEle.innerText;
inputEle.innerText = inputText.substring(0, oldRangeStart) + clipboardText + inputText.substring(selectRange.endOffset, inputText.length);
selection.removeAllRanges();
const newRange = document.createRange();
newRange.setStart(inputEle.childNodes[0], oldRangeStart + clipboardText.length);
selection.addRange(newRange);
}
});
inputEle.onkeydown = (/** @type {KeyboardEvent} */ event) =>
{
event.stopImmediatePropagation();
keyHandler(event);
};
setTimeout(() => // (To isolate from any event.)
{
this.body.appendChild(inputEle);
this.body.scrollTo(0, this.body.scrollHeight);
inputEle.focus();
}, 10);
}
/**
* Stores data in the browser's `localStorage`.
* @param {string} key Key (identifier) of the data to be stored.
* @param {any} data Data to be stored.
* @private
*/
memorize (key, data)
{
if (localStorage)
{
const storedData = JSON.parse(localStorage.getItem(this.id) || "{}");
storedData[key] = data;
localStorage.setItem(this.id, JSON.stringify(storedData));
}
};
/**
* Checks if a named argument is present in the arguments.
* @param {Array<string>} args Arguments.
* @param {...string} name Name of the argument to be checked. Named arguments always begin with one or two hyphens.
*/
namedArgumentExists (args, ...name)
{
for (const n of name)
{
if (args.includes(n))
{
return true;
}
}
return false;
}
/**
* Retrieves the value of a named argument, which is the item following the named argument in the arguments list.
* @param {Array<string>} args Arguments.
* @param {...string} name Name of the argument whose value is to be retrieved. Named arguments always begin with one or two hyphens.
* @returns {string | undefined} The named argument's value, or `undefined` if the named argument does not exists.
*/
getNamedArgumentValue (args, ...name)
{
for (const n of name)
{
const argIndex = args.indexOf(n);
if (argIndex > -1)
{
return ((args.length > argIndex + 1) && (/^--?/.test(args[argIndex + 1]) === false))
? args[argIndex + 1]
: "";
}
}
return undefined;
}
/**
* Writes the given text to the CLI on screen. Usually you should rather
* use {@linkcode writeLn()} which adds a new line at the end of the text.
* @param {string} text Text to be written.
*/
write (text)
{
const format = (/** @type {string} */ text) =>
{
/** @type {Array<string|HTMLElement>} */
const chunks = [];
/** @type {RegExpExecArray} */
let match;
while ((match = /((\\)([*_´]))|((\*{1,2}|_{1,2}|`)([^\s].*?)\5)|((http)s?:\/\/\S+\b)|((\x1b\[)(3[0-7]|0)m(.*))/g.exec(text)))
{
const token = match[2] ?? match[5] ?? match[8] ?? match[10]; // Escaped format tag OR format tag OR "http" OR color tag
const content = match[3] ?? match[6] ?? match[7] ?? match[12];
const index = text.indexOf(token);
if (token === "\\")
{
chunks.push(text.substring(0, index), content);
text = text.substring(index + 2); // 2 = token character + formatting character
}
else
{
/** @type {string} */
let tag = "span";
/** @type {Array<string|HTMLElement>} */
let innerNodes = [];
let contentLength = content.length;
if (token === "\x1b[")
{
contentLength += match[11].length + 3; // 3 = "\xb1" + "[" + "m";
let color = "--cli-color-foreground";
switch (match[11])
{
case "30":
color = "--cli-color-black";
break;
case "31":
color = "--cli-color-red";
break;
case "32":
color = "--cli-color-green";
break;
case "33":
color = "--cli-color-yellow";
break;
case "34":
color = "--cli-color-blue";
break;
case "35":
color = "--cli-color-magenta";
break;
case "36":
color = "--cli-color-cyan";
break;
case "37":
color = "--cli-color-white";
break;
}
tag = `span[style="color:var(${color})"]`;
innerNodes = format(content);
}
else if (token === "http")
{
tag = `a[href="${content}"][target="_blank"]`;
innerNodes = [content];
}
else
{
switch (token)
{
case "**":
case "__":
tag = "b";
innerNodes = format(content);
break;
case "*":
case "_":
tag = "i";
innerNodes = format(content);
break;
case "`":
tag = "code";
innerNodes = [content];
break;
}
contentLength += (token.length * 2);
}
chunks.push(text.substring(0, index), CommandLineInterpreter.createElement(tag, ...innerNodes));
text = text.substring(index + contentLength);
}
}
chunks.push(text);
return chunks;
};
const tabularize = (/** @type {string} */ text) =>
{
/** @type {Array<number>} */
const columnWidths = [];
const lines = text.split("\n").map(line =>
line.split("\t").map((cell, colIndex) =>
{
const ele = CommandLineInterpreter.createElement("p", ...format(cell));
columnWidths[colIndex] = Math.max(columnWidths[colIndex] || 0, ele.innerText.length);
return ele;
})
);
for (const line of lines)
{
const columnCount = line.length;
for (let columnIndex = 0; columnIndex < columnCount; columnIndex += 1)
{
const cell = line[columnIndex];
const cellText = cell.innerText;
const paddingSpaces = columnWidths[columnIndex] - cellText.length;
if (paddingSpaces > 0)
{
if (/^[\-\+]?\d+(\.\d*)?\s*$/.test(cellText))
{
cell.prepend(" ".repeat(paddingSpaces));
}
else if (columnIndex < columnCount - 1)
{
cell.append(" ".repeat(paddingSpaces));
}
}
cell.append((columnIndex < columnCount - 1) ? "\x20".repeat(this.options.tabWidth) : "\n");
}
}
return lines.map(l => l.map(c => Array.from(c.childNodes))).flat(2);
};
if (this.options.richtextEnabled)
{
if (/\t/.test(text))
{
this.body.append(...tabularize(text.replace(/[\s\n]*$/g, "")));
}
else
{
this.body.append(...format(text));
}
}
else
{
this.body.append(text.replace(/\x1b\[\d+m/g, ""));
}
this.body.scrollTo(0, this.body.scrollHeight);
return this;
};
/**
* Just like {@linkcode write()}, but adds a new line at the end of the text.
* You should prefer this over `write()`.
* @param {string} text Text to be written.
*/
writeLn (text)
{
return this.write(text + "\n");
}
/**
* Require the user to press a single key.
* @param {Array<string>} keys Set of acceptable keys. This may include special keys such as "Enter" or "Escape". See [MDN reference](https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values).
* @param {string} [prompt] The prompt to be printed before the input.
* @returns {Promise<string>} A `Promise` that resolves to the pressed key. Does not resolve for keys outside the defined set.
*/
readKey (keys, prompt)
{
return new Promise(resolve =>
{
const lKeys = [...keys.map(k => k.toLowerCase())];
this.receiveInput(prompt || keys.join("/").toUpperCase() + "? ",
(/** @type {KeyboardEvent} */ event) =>
{
if (/^f\d/i.test(event.key) === false)
{
event.preventDefault();
if (lKeys.includes(event.key.toLowerCase()))
{
const inputKey = event.key;
const inputEle = /** @type {HTMLElement} */(event.target);
inputEle.replaceWith(CommandLineInterpreter.createElement("span", inputKey + "\n"));
resolve(inputKey.toUpperCase());
}
}
});
});
}
/**
* Read any user input from the CLI. The user must commit his input with [Enter].
* @param {string} [prompt] The prompt to be printed before the input. Default is `"> "`.
* @returns {Promise<string>} A `Promise` that resolves to the entered text.
*/
readLn (prompt)
{
return new Promise(resolve =>
{
this.receiveInput(prompt || "> ",
(/** @type {KeyboardEvent} */ event) =>
{
const inputEle = /** @type {HTMLElement} */(event.target);
switch (event.key)
{
case "Escape":
inputEle.innerText = "";
break;
case "Enter":
inputEle.replaceWith(CommandLineInterpreter.createElement("span.input", inputEle.innerText + "\n"));
resolve(inputEle.innerText);
}
});
});
}
/**
* Read any user input from the CLI but does not show the input on screen.
* The user must commit his input with [Enter].
* @param {string} [prompt] The prompt to be printed before the input. Default is `"> "`.
* @returns {Promise<string>} A `Promise` that resolves to the entered secret as a plain string.
*/
readSecret (prompt)
{
return new Promise(resolve =>
{
let secret = "";
this.receiveInput(prompt || "> ",
(/** @type {KeyboardEvent} */event) =>
{
switch (event.key)
{
case "Enter":
const inputEle = /** @type {HTMLElement} */(event.target);
inputEle.replaceWith(CommandLineInterpreter.createElement("span", "\n"));
resolve(secret);
break;
case "Backspace":
secret = secret.substring(0, secret.length - 1);
break;
default:
if (event.key.length === 1)
{
event.preventDefault();
secret += event.key;
}
}
});
});
}
/**
* Create a new HTML elemement.
* @param {string} tag The tag of the desired HTML element. This may include CSS classes and attributes.
* @param {...string|HTMLElement} children Content (or child elements) to be created on/in the HTML element.
* @returns The newly created HTML element.
*/
static createElement (tag, ...children)
{
const element = document.createElement(/^[a-z0-1]+/.exec(tag)?.[0] || "div");
// Set attributes:
for (const attributeMatch of tag.matchAll(/\[(.+?)=["'](.+?)["']\]/g))
{
element.setAttribute(attributeMatch[1], attributeMatch[2]);
}
// Add CSS classes:
for (const cssClass of tag.replaceAll(/\[.+\]/g, "").matchAll(/\.([^.[\s]+)/g))
{
element.classList.add(cssClass[1]);
}
element.append(...children);
return element;
};
}
// Create <style> element with mandatory CSS rules for CLI child elements:
addEventListener("DOMContentLoaded", () =>
{
document.head.appendChild(CommandLineInterpreter.createElement(
"style",
`.${CommandLineInterpreter.name.toLowerCase()} * {${[
"background-color: transparent;",
"color: inherit;",
"font-family: inherit;",
"font-size: inherit;",
"padding: 0;",
"margin: 0;",
"border: none;",
"outline: none;",
"white-space: inherit;"].join("")}}`
));
});