-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
774 lines (631 loc) · 20.1 KB
/
index.js
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
const state = {
path: "~",
env: {},
date: new Date(),
dirs: ["/home/guest"],
hist: [],
histPtr: null,
};
const dirMap = {
home: {
guest: {
".secret.txt": "😊",
"about-me.txt": "I'm a software engineer",
"about-this-site.txt": `Ok, ok, yes. This isn't a real terminal.
You got me.
If you're trying to do some cool grep-pipe-xargs wizardry it won't work.
This was just a fun way to present some information in a way that shows what I enjoy.
I will come back and implement a vim emulator one day, I swear...`,
"links.txt": `[github](https://github.com/rdo34) | [linkedin](https://linkedin.com/in/ross-james-donohoe)`,
blog: {
"placeholder.txt": "Pfft, I don't have a blog",
},
},
},
};
addEventListener("keypress", function (e) {
if (e.key.length === 1) {
e.preventDefault();
inputChar(e.key);
}
});
addEventListener("keydown", function (e) {
if (e.key === "Enter") {
e.preventDefault();
handleCommand();
createNewLine();
}
if (e.key === "Backspace") {
e.preventDefault();
deletePrevChar();
}
if (e.key === "Delete") {
e.preventDefault();
deleteCurrentChar();
}
if (e.key === "ArrowLeft") {
e.preventDefault();
moveCaretBack();
}
if (e.key === "ArrowRight") {
e.preventDefault();
moveCaretForward();
}
if (e.key === "ArrowUp") {
e.preventDefault();
moveHistoryBack();
}
if (e.key === "ArrowDown") {
e.preventDefault();
moveHistoryForward();
}
// SIGINT
if (e.key === "c" && e.ctrlKey) {
e.preventDefault();
createNewLine();
}
});
function inputChar(char) {
const charElement = document.createElement("span");
charElement.innerHTML += encodeHtml(char);
const parentNode = caret().parentNode;
parentNode.insertBefore(charElement, caret());
}
function deletePrevChar() {
const parentNode = caret().parentNode;
const prev = caret().previousElementSibling;
if (prev) {
parentNode.removeChild(prev);
}
}
function deleteCurrentChar() {
const parentNode = caret().parentNode;
const next = caret().nextElementSibling;
const current = caret();
if (current) {
parentNode.removeChild(current);
next.classList.add("caret");
}
}
function moveCaretBack() {
const prev = caret().previousElementSibling;
if (prev) {
caret().classList.remove("caret");
prev.classList.add("caret");
}
}
function moveCaretForward() {
const next = caret().nextElementSibling;
if (next) {
caret().classList.remove("caret");
next.classList.add("caret");
}
}
function moveHistoryBack() {
if (state.histPtr === null) {
state.histPtr = state.hist.length - 1;
} else if (state.histPtr > 0) {
state.histPtr = Math.max(0, state.histPtr - 1);
}
createInputLine(state.hist[state.histPtr]);
}
function moveHistoryForward() {
if (state.histPtr === null) {
return;
}
if (state.histPtr === state.hist.length - 1) {
state.histPtr = null;
createInputLine("");
return;
}
state.histPtr = Math.min(state.hist.length - 1, state.histPtr + 1);
createInputLine(state.hist[state.histPtr]);
}
function createInputLine(text) {
const commands = document.querySelectorAll(".terminal-input");
const lastCommand = commands[commands.length - 1];
const children = text.split("").map((char) => {
const span = document.createElement("span");
span.innerHTML = encodeHtml(char);
return span;
});
const newCaret = document.createElement("span");
newCaret.classList.add("caret");
lastCommand.innerHTML = "";
lastCommand.append(...children);
lastCommand.appendChild(newCaret);
}
function createNewLine() {
state.histPtr = null;
const newLine = document.createElement("span");
newLine.classList.add("terminal-line");
const leader = document.createElement("span");
leader.innerHTML = makeLeaderText();
leader.classList.add("terminal-leader");
newLine.appendChild(leader);
const input = document.createElement("span");
input.classList.add("terminal-input");
newLine.appendChild(input);
const caret = document.createElement("span");
caret.classList.add("caret");
input.appendChild(caret);
const lastCaret = document.querySelector(".caret");
if (lastCaret) {
lastCaret.classList.remove("caret");
}
const terminal = document.querySelector(".terminal");
terminal.appendChild(newLine);
terminal.scrollTop = terminal.scrollHeight;
}
function caret() {
return document.querySelector(".caret");
}
const STRING_TO_HTML = {
"<": "<",
">": ">",
"&": "&",
'"': """,
"'": "'",
" ": " ",
};
function encodeHtml(text) {
return STRING_TO_HTML[text] || text;
}
function makeLeaderText() {
return `[email protected]:${state.path}$`;
}
function println(text, parseLinks = false) {
const newLine = document.createElement("span");
newLine.classList.add("terminal-line");
let innerHTML = text;
if (parseLinks) {
const elements = innerHTML.match(/\[.*?\)/g);
if (elements != null && elements.length > 0) {
for (const element of elements) {
const label = element.match(/\[(.*?)\]/)[1];
const url = element.match(/\((.*?)\)/)[1];
innerHTML = innerHTML.replace(
element,
`<a href="${url}" target="_blank">${label}</a>`
);
}
}
}
newLine.innerHTML = innerHTML;
document.querySelector(".terminal").appendChild(newLine);
}
const handlers = {
alias: alias,
bg: permissionDenied("bg"),
bind: permissionDenied("bind"),
builtin: permissionDenied("builtin"),
cat: concatenate,
caller: permissionDenied("caller"),
cd: changeDirectory,
chmod: permissionDenied("chmod"),
chown: permissionDenied("chown"),
chroot: permissionDenied("chroot"),
clear: clear,
compgen: permissionDenied("compgen"),
complete: permissionDenied("complete"),
compopt: permissionDenied("compopt"),
coproc: permissionDenied("coproc"),
cp: permissionDenied("cp"),
dirs: dirs,
disown: permissionDenied("disown"),
echo: echo,
enable: permissionDenied("enable"),
eval: permissionDenied("eval"),
exec: permissionDenied("exec"),
exit: permissionDenied("exit"),
export: exportFn,
false: permissionDenied("false"),
fc: fixCommand,
fg: permissionDenied("fg"),
for: permissionDenied("for"),
function: permissionDenied("function"),
getopts: noop,
hash: permissionDenied("hash"),
help: help,
history: history,
if: permissionDenied("if"),
jobs: permissionDenied("jobs"),
kill: permissionDenied("kill"),
let: permissionDenied("let"),
local: permissionDenied("local"),
logout: permissionDenied("logout"),
mapfile: permissionDenied("mapfile"),
popd: popd,
printf: echo,
pushd: pushd,
pwd: processWorkingDirectory,
read: permissionDenied("read"),
readarray: permissionDenied("readarray"),
readonly: permissionDenied("readonly"),
return: permissionDenied("return"),
select: permissionDenied("select"),
set: permissionDenied("set"),
shift: permissionDenied("shift"),
shopt: permissionDenied("shopt"),
source: permissionDenied("source"),
suspend: permissionDenied("suspend"),
test: permissionDenied("test"),
time: permissionDenied("time"),
times: permissionDenied("times"),
trap: permissionDenied("trap"),
true: permissionDenied("true"),
type: permissionDenied("type"),
typeset: permissionDenied("typeset"),
ulimit: permissionDenied("ulimit"),
umask: permissionDenied("umask"),
unalias: permissionDenied("unalias"),
unset: permissionDenied("unset"),
wait: permissionDenied("wait"),
while: permissionDenied("while"),
apt: permissionDenied("apt"),
"apt-get": permissionDenied("apt-get"),
curl: permissionDenied("curl"),
ls: list,
mkdir: makeDirectory,
mv: permissionDenied("mv"),
nano: permissionDenied("nano"),
rm: permissionDenied("rm"),
su: permissionDenied("su"),
sudo: permissionDenied("sudo"),
touch: makeFile,
vi: permissionDenied("vi"),
vim: permissionDenied("vim"),
wget: permissionDenied("wget"),
};
const HTML_SPACE_CHAR = " ";
function handleCommand() {
const commands = document.querySelectorAll(".terminal-input");
const command = commands[commands.length - 1].textContent.trim();
if (command.length > 0) {
cmd(command);
state.hist.push(command);
}
}
function cmd(command) {
const [baseCommand, ...args] = command.split(HTML_SPACE_CHAR);
if (handlers[baseCommand]) {
handlers[baseCommand](args);
} else {
insertCommandNotFound(baseCommand);
}
}
function insertCommandNotFound(command) {
println(`sh: command not found: ${command}`);
}
function permissionDenied(command) {
return function () {
println(`sh: ${command}: permission denied`);
};
}
function noop() {
println("");
}
function help() {
for (const line of CONSTANTS.HELP.split("\n")) {
println(line);
}
}
function clear() {
const terminal = document.querySelector(".terminal");
terminal.innerHTML = "";
}
function list(args) {
const pathArg = args.find((arg) => !arg.startsWith("-"));
if (Path.outOfBounds(pathArg)) {
permissionDenied("ls")([pathArg]);
return;
}
const dir = Path.resolve(pathArg);
if (!dir) {
println(`ls: cannot access '${pathArg}': No such file or directory`);
return;
}
let entries = [".", "..", ...Object.keys(dir)];
const includeHidden = args.some(
(arg) => arg.startsWith("-") && arg.includes("a")
);
if (!includeHidden) {
entries = entries.filter((entry) => !entry.startsWith("."));
}
if (typeof dir === "string") {
entries = [pathArg.split("/").pop()];
}
const longFormat = args.some(
(arg) => arg.startsWith("-") && arg.includes("l")
);
if (longFormat) {
const entryDetails = entries.map((entry) => {
const isDir = typeof dir[entry] === "object";
const typeAndPermissions = `${isDir ? "d" : "-"}r--r--r--`;
const links = 1;
const owner = "guest";
const group = "guest";
const size = isDir ? 4096 : 1024;
const month = state.date.toLocaleString("default", { month: "short" });
const day = state.date.getDate();
const time = state.date.toLocaleTimeString("en-GB", {
hour: "2-digit",
minute: "2-digit",
});
const date = `${month} ${day} ${time}`;
return [typeAndPermissions, links, owner, group, size, date, entry].join(
HTML_SPACE_CHAR
);
});
for (const entry of entryDetails) {
println(entry);
}
return;
}
const newLine = document.createElement("span");
newLine.classList.add("terminal-line");
for (const entry of entries) {
newLine.innerHTML += entry;
newLine.innerHTML += "	";
}
document.querySelector(".terminal").appendChild(newLine);
}
function changeDirectory(args) {
const newPath = args[0];
if (!newPath) {
state.path = "~";
return;
}
if (newPath === ".") {
return;
}
if (Path.outOfBounds(newPath)) {
permissionDenied("cd")([newPath]);
return;
}
const newFullPath = Path.absolute(newPath);
const target = Path.resolve(newFullPath);
if (typeof target !== "object") {
println(`cd: ${newPath}: Not a directory`);
return;
}
if (!target) {
println(`cd: ${newPath}: No such file or directory`);
return;
}
state.path = newFullPath.replace("/home/guest", "~");
state.dirs.push(Path.absolute(newFullPath));
}
function echo(args) {
println(args.join(HTML_SPACE_CHAR));
}
function alias(args) {
const [alias, command] = args[0].split("=");
if (!alias || !command) {
for (const arg of args.filter((arg) => !arg.startsWith("-"))) {
println(`sh: alias: ${arg}: not found`);
}
return;
}
handlers[alias] = function (args) {
cmd([command, ...args].join(HTML_SPACE_CHAR).trim());
};
}
// cat
function concatenate(args) {
const filePath = args[0];
const file = Path.resolve(filePath);
if (typeof file === "string") {
println(file, true);
return;
}
if (typeof file === "object") {
println(`cat: ${filePath}: Is a directory`);
return;
}
println(`cat: ${filePath}: No such file or directory`);
}
function makeDirectory(args) {
const dirPath = args[0];
if (!dirPath) {
println("mkdir: missing operand");
return;
}
const dir = Path.resolve(dirPath);
if (dir) {
println(`mkdir: cannot create directory '${dirPath}': File exists`);
return;
}
const pathParts = dirPath.split("/");
const dirName = pathParts.pop();
const parentDir = Path.resolve(pathParts.join("/"));
if (!parentDir) {
println(
`mkdir: cannot create directory '${dirPath}': No such file or directory`
);
return;
}
parentDir[dirName] = {};
}
function makeFile(args) {
const filePath = args[0];
if (!filePath) {
println("touch: missing file operand");
return;
}
const file = Path.resolve(filePath);
if (file) {
println(`touch: cannot create file '${filePath}': File exists`);
return;
}
const pathParts = filePath.split("/");
const fileName = pathParts.pop();
const parentDir = Path.resolve(pathParts.join("/"));
if (!parentDir) {
println(
`touch: cannot create file '${filePath}': No such file or directory`
);
return;
}
parentDir[fileName] = "";
}
function processWorkingDirectory() {
println(Path.absolute(state.path));
}
function dirs() {
println(state.dirs.join(" "));
}
function pushd(args) {
const dirPath = args[0];
if (!dirPath) {
println("pushd: missing operand");
return;
}
const dir = Path.resolve(dirPath);
if (!dir) {
println(`pushd: ${dirPath}: No such file or directory`);
return;
}
state.dirs.push(Path.absolute(dirPath));
}
function popd() {
state.dirs.pop();
}
function exportFn(args) {
const [envVar, value] = args[0].split("=");
state.env[envVar] = value;
}
function history(_args) {
for (const [idx, cmd] of state.hist.entries()) {
const newLine = document.createElement("span");
newLine.classList.add("terminal-line");
newLine.innerHTML += " ";
newLine.innerHTML += idx + 1;
newLine.innerHTML += "	";
newLine.innerHTML += cmd;
document.querySelector(".terminal").appendChild(newLine);
}
}
function fixCommand(args) {
return history(args);
}
class Path {
static traverse(_path) {
const basePath = ["home", "guest"];
if (["~", "~/"].includes(_path)) {
return basePath;
}
let targetPath = _path;
let currentRelativePath = state.path.slice(1).split("/").filter(Boolean);
if (targetPath.startsWith("/home/guest")) {
targetPath = targetPath.slice(11);
currentRelativePath = [];
}
if (targetPath.startsWith("~/")) {
targetPath = targetPath.slice(2);
currentRelativePath = [];
}
const resolvedPath = [...basePath, ...currentRelativePath];
const targetPathParts = targetPath.split("/").filter(Boolean);
for (const part of targetPathParts) {
if (part === ".") {
continue;
} else if (part === "..") {
resolvedPath.pop();
} else {
resolvedPath.push(part);
}
}
return resolvedPath;
}
static resolve(_path = "") {
const resolvedPath = Path.traverse(_path);
let resolved = dirMap;
for (const part of resolvedPath) {
resolved = resolved[part];
}
return resolved;
}
static absolute(_path) {
const path = Path.traverse(_path);
return `/${path.join("/")}`;
}
static outOfBounds(_path = "") {
const path = Path.absolute(_path);
return path.startsWith("/") && !path.startsWith("/home/guest");
}
}
async function simulateTyping(text) {
for (const char of text) {
inputChar(char);
await sleep();
}
}
async function sleep(_ms) {
let ms = _ms;
if (!ms) {
ms = Math.floor(Math.random() * 100) + 50;
}
return new Promise((res) => setTimeout(res, ms));
}
const scipts = {
welcome,
};
async function welcome() {
await simulateTyping("echo Welcome to rossdonohoe.dev!");
await sleep();
handleCommand();
createNewLine();
await sleep(400);
await simulateTyping("ls -l");
await sleep();
handleCommand();
createNewLine();
}
scipts.welcome();
const CONSTANTS = {
HELP: `GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
These shell commands are defined internally. Type \help' to see this list.
Type \help name' to find out more about the function \name'.
Use \info bash' to find out more about the shell in general.
Use \man -k' or \`info' to find out more about commands not in this list.
A star (*) next to a name means that the command is disabled.
job_spec [&] history [-c] [-d offset] [n] or history -anrw >
(( expression )) if COMMANDS; then COMMANDS; [ elif COMMANDS; t>
. filename [arguments] jobs [-lnprs] [jobspec ...] or jobs -x command>
: kill [-s sigspec | -n signum | -sigspec] pid |>
[ arg... ] let arg [arg ...]
[[ expression ]] local [option] name[=value] ...
alias [-p] [name[=value] ... ] logout [n]
bg [job_spec ...] mapfile [-d delim] [-n count] [-O origin] [-s >
bind [-lpsvPSVX] [-m keymap] [-f filename] [-q > popd [-n] [+N | -N]
break [n] printf [-v var] format [arguments]
builtin [shell-builtin [arg ...]] pushd [-n] [+N | -N | dir]
caller [expr] pwd [-LP]
case WORD in [PATTERN [| PATTERN]...) COMMANDS > read [-ers] [-a array] [-d delim] [-i text] [->
cd [-L|[-P [-e]] [-@]] [dir] readarray [-d delim] [-n count] [-O origin] [->
command [-pVv] command [arg ...] readonly [-aAf] [name[=value] ...] or readonly>
compgen [-abcdefgjksuv] [-o option] [-A action]> return [n]
complete [-abcdefgjksuv] [-pr] [-DEI] [-o optio> select NAME [in WORDS ... ;] do COMMANDS; done
compopt [-o|+o option] [-DEI] [name ...] set [-abefhkmnptuvxBCHP] [-o option-name] [--]>
continue [n] shift [n]
coproc [NAME] command [redirections] shopt [-pqsu] [-o] [optname ...]
declare [-aAfFgiIlnrtux] [-p] [name[=value] ...> source filename [arguments]
dirs [-clpv] [+N] [-N] suspend [-f]
disown [-h] [-ar] [jobspec ... | pid ...] test [expr]
echo [-neE] [arg ...] time [-p] pipeline
enable [-a] [-dnps] [-f filename] [name ...] times
eval [arg ...] trap [-lp] [[arg] signal_spec ...]
exec [-cl] [-a name] [command [argument ...]] [> true
exit [n] type [-afptP] name [name ...]
export [-fn] [name[=value] ...] or export -p typeset [-aAfFgiIlnrtux] [-p] name[=value] ...
false ulimit [-SHabcdefiklmnpqrstuvxPT] [limit]
fc [-e ename] [-lnr] [first] [last] or fc -s [p> umask [-p] [-S] [mode]
fg [job_spec] unalias [-a] name [name ...]
for NAME [in WORDS ... ] ; do COMMANDS; done unset [-f] [-v] [-n] [name ...]
for (( exp1; exp2; exp3 )); do COMMANDS; done until COMMANDS; do COMMANDS; done
function name { COMMANDS ; } or name () { COMMA> variables - Names and meanings of some shell v>
getopts optstring name [arg ...] wait [-fn] [-p var] [id ...]
hash [-lr] [-p pathname] [-dt] [name ...] while COMMANDS; do COMMANDS; done
help [-dms] [pattern ...] { COMMANDS ; }`,
};