4 Commits
Author SHA1 Message Date
ChaosMaker 41739d7cf9 - Reworked internal signals
- Separated input passing from signal calling
- Exposed command registry to the broader codebase
- Moved command execution call to internal shell logic
- TTY is now expected to watch for stdout escape sequences to perform tasks
2026-11-23 13:31:22 +01:00
ChaosMaker dbffe5375e - Fixed default inode sorting order from being highest to lowes to lowest to highest (bug) 2026-11-22 12:55:41 +01:00
ChaosMaker 57773fc2ef - Fixed a bug where the current session stored in the shell instance wasnt getting updated after each state change 2026-11-20 15:14:47 +01:00
ChaosMaker 9a31a5985b - Updated package.json to contain the new version tag 2026-11-20 12:28:04 +01:00
18 changed files with 214 additions and 136 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "termos", "name": "termos",
"version": "0.1.0", "version": "0.1.1",
"description": "Emulation library for a unix-like operating-system written in pure typescript", "description": "Emulation library for a unix-like operating-system written in pure typescript",
"files": [ "files": [
"dist" "dist"
+2 -2
View File
@@ -1,7 +1,7 @@
import type { Signal } from "./signal"; import type { Input } from "@shell/shell";
export interface CommandIO { export interface CommandIO {
writeStdout(data: Uint8Array): void; writeStdout(data: Uint8Array): void;
writeStderr(data: Uint8Array): void; writeStderr(data: Uint8Array): void;
getSignal(): Promise<Signal>; onInput(): Promise<Input>;
} }
+4
View File
@@ -3,11 +3,14 @@ import { descriptor as cat } from "./commands/cat";
import { descriptor as cd } from "./commands/cd"; import { descriptor as cd } from "./commands/cd";
import { descriptor as clear } from "./commands/clear"; import { descriptor as clear } from "./commands/clear";
import { descriptor as echo } from "./commands/echo"; import { descriptor as echo } from "./commands/echo";
import { descriptor as help } from "./commands/help";
import { descriptor as ls } from "./commands/ls"; import { descriptor as ls } from "./commands/ls";
import { descriptor as pwd } from "./commands/pwd"; import { descriptor as pwd } from "./commands/pwd";
import { descriptor as testasync } from "./commands/testasync"; import { descriptor as testasync } from "./commands/testasync";
import { descriptor as touch } from "./commands/touch"; import { descriptor as touch } from "./commands/touch";
export type CommandRegistry = ReadonlyMap<string, CommandDescriptor>;
const reg = new Map<string, CommandDescriptor>(); const reg = new Map<string, CommandDescriptor>();
//reg.set(descriptor.name, descriptor <- imported const from command implementation file); //reg.set(descriptor.name, descriptor <- imported const from command implementation file);
reg.set(echo.name, echo); reg.set(echo.name, echo);
@@ -18,6 +21,7 @@ reg.set(cat.name, cat);
reg.set(pwd.name, pwd); reg.set(pwd.name, pwd);
reg.set(clear.name, clear); reg.set(clear.name, clear);
reg.set(touch.name, touch); reg.set(touch.name, touch);
reg.set(help.name, help);
Object.freeze(reg); Object.freeze(reg);
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg; export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
+2 -1
View File
@@ -7,7 +7,8 @@ import type { ShellError } from "@core/util/errors";
export const COMMAND_NAME = "clear"; export const COMMAND_NAME = "clear";
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> { async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
io.writeStdout(new TextEncoder().encode("\x1b[2J\x1b[0;0H")); const encoded = new TextEncoder().encode("\x1b[2J\x1b[0;0H");
io.writeStdout(encoded);
const result: ResultSuccess = createSuccessResult(COMMAND_NAME); const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
+27
View File
@@ -0,0 +1,27 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { COMMAND_REGISTRY } from "@core/command_registry";
import { createSuccessResult, type ResultSuccess } from "@core/result";
import type { ShellState } from "@core/shell_state";
import type { ShellError } from "@core/util/errors";
export const COMMAND_NAME = "help";
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const e = new TextEncoder();
for (const entry of COMMAND_REGISTRY.keys()) {
io.writeStdout(e.encode(` ${entry}\n`));
}
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
state: state,
result,
};
}
export const descriptor: CommandDescriptor = {
fn: main,
name: COMMAND_NAME,
};
+8 -12
View File
@@ -237,16 +237,9 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
} }
} }
if (options.long) {
for (const entry of entries) { for (const entry of entries) {
listDirEntries(entry); listDirEntries(entry);
} }
} else {
for (const entry of entries) {
//shortDirEntries(entry);
}
io.writeStdout(e.encode(`No support for short format yet\n`));
}
return { return {
state, state,
@@ -257,7 +250,7 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
const node = state.filesystem.getNode(entry.ptr) as DirectoryNode; const node = state.filesystem.getNode(entry.ptr) as DirectoryNode;
if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\n`)); if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\n`));
io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`)); if (options.long) io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`));
let children: DirEntry[] = Array.from(node.children.entries()).map(([name, inode]) => ({ let children: DirEntry[] = Array.from(node.children.entries()).map(([name, inode]) => ({
name, name,
@@ -271,11 +264,15 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
if (options.long) { if (options.long) {
longMode(io, state, children); longMode(io, state, children);
if (options.recursive) io.writeStdout(e.encode("\n")); } else {
//shortMode(io, state, children);
} }
if (options.recursive) { if (options.recursive) {
io.writeStdout(e.encode("\n"));
for (const c of children) { for (const c of children) {
// Skip if names match . or ..
if (c.name.match(/^[.]{1,2}$/)) continue; if (c.name.match(/^[.]{1,2}$/)) continue;
const child = state.filesystem.getNode(c.ptr)!; const child = state.filesystem.getNode(c.ptr)!;
if (child.type === NodeType.Directory) { if (child.type === NodeType.Directory) {
@@ -291,8 +288,9 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
} }
} }
function shortMode(io: CommandIO, state: ShellState, children: DirEntry[]): void {}
function longMode(io: CommandIO, state: ShellState, children: DirEntry[]): void { function longMode(io: CommandIO, state: ShellState, children: DirEntry[]): void {
const e = new TextEncoder();
const buff: Uint8Array[] = []; const buff: Uint8Array[] = [];
const nodes: DirEntry[] = [...children]; const nodes: DirEntry[] = [...children];
@@ -440,8 +438,6 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
} }
} }
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
export const descriptor: CommandDescriptor = { export const descriptor: CommandDescriptor = {
fn: main, fn: main,
flags: [ flags: [
+3 -6
View File
@@ -2,7 +2,6 @@ import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io"; import type { CommandIO } from "@core/command_io";
import type { ResultSuccess } from "@core/result"; import type { ResultSuccess } from "@core/result";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
import { SIGNAL_MAP } from "@core/signal";
import type { ShellError } from "@core/util/errors"; import type { ShellError } from "@core/util/errors";
import { createImmutableBuffer } from "@core/util/immutable_buffer"; import { createImmutableBuffer } from "@core/util/immutable_buffer";
@@ -10,13 +9,12 @@ const COMMAND_NAME = "async";
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> { async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
while (true) { while (true) {
const out = await io.getSignal(); const sig = await io.onInput();
if (out.type === SIGNAL_MAP.INPUT) { const encoded = new TextEncoder().encode(("user pressed: " + sig.sequence + "\n") as string);
const encoded = new TextEncoder().encode(("user pressed: " + out.payload + "\n") as string);
io.writeStdout(encoded); io.writeStdout(encoded);
if (out.payload === "x") { if (sig.sequence === "\x03") {
const result: ResultSuccess = { const result: ResultSuccess = {
type: "success", type: "success",
exitCode: 0, exitCode: 0,
@@ -31,7 +29,6 @@ async function main(io: CommandIO, state: ShellState, __args: string[]): Promise
}; };
} }
} }
}
} }
export const descriptor = { export const descriptor = {
+5 -5
View File
@@ -1,9 +1,9 @@
const HISTORY_MAX_CAPACITY = 255; const HISTORY_MAX_CAPACITY = 255;
export type HistoryState = readonly string[]; export type HistoryState = readonly Uint8Array[];
export function addHistoryEntry(state: HistoryState, input: string): HistoryState { export function addHistoryEntry(state: HistoryState, input: Uint8Array): HistoryState {
const entries: string[] = [...state]; const entries: Uint8Array[] = [...state];
if (entries.length === HISTORY_MAX_CAPACITY) { if (entries.length === HISTORY_MAX_CAPACITY) {
entries.shift(); entries.shift();
@@ -12,11 +12,11 @@ export function addHistoryEntry(state: HistoryState, input: string): HistoryStat
entries.push(input); entries.push(input);
} }
const result: readonly string[] = entries; const result: readonly Uint8Array[] = entries;
return Object.freeze(result); return Object.freeze(result);
} }
export function getHistoryEntry(state: HistoryState, index: number): string { export function getHistoryEntry(state: HistoryState, index: number): Uint8Array {
const entry = state[index]; const entry = state[index];
if (entry === undefined) { if (entry === undefined) {
// Add a custom error object later // Add a custom error object later
+4 -1
View File
@@ -9,6 +9,7 @@ export interface ShellState {
readonly users: ReadonlyMap<number, UserInfo>; readonly users: ReadonlyMap<number, UserInfo>;
readonly groups: ReadonlyMap<number, GroupInfo>; readonly groups: ReadonlyMap<number, GroupInfo>;
readonly sessionStack: ReadonlyArray<SessionState>; readonly sessionStack: ReadonlyArray<SessionState>;
//readonly commmandRegistry: CommandRegistry;
} }
export function createInitialShellState( export function createInitialShellState(
@@ -16,12 +17,14 @@ export function createInitialShellState(
users: ReadonlyMap<number, UserInfo>, users: ReadonlyMap<number, UserInfo>,
groups: ReadonlyMap<number, GroupInfo>, groups: ReadonlyMap<number, GroupInfo>,
user: UserInfo, user: UserInfo,
//commandRegistry: CommandRegistry,
): ShellState { ): ShellState {
return Object.freeze({ return Object.freeze({
filesystem, filesystem,
users, users,
groups, groups,
sessionStack: Object.freeze([createInitialSessionState(user)]), sessionStack: Object.freeze([createInitialSessionState(user)]),
//commandRegistry,
}); });
} }
@@ -63,7 +66,7 @@ export function withCwd(state: ShellState, ptr: NodePointer): ShellState {
} satisfies ShellState); } satisfies ShellState);
} }
export function withHistory(state: ShellState, input: string): ShellState { export function withHistory(state: ShellState, input: Uint8Array): ShellState {
const session = getCurrentSession(state); const session = getCurrentSession(state);
const newSession = Object.freeze({ const newSession = Object.freeze({
-13
View File
@@ -1,13 +0,0 @@
//Payload optional because command that handles that signal
// is going to know what shape it is, therefore also able to cast it;
export type Signal = {
type: SIGNAL_MAP;
payload?: unknown;
};
export enum SIGNAL_MAP {
SIGINT = 2,
SIGTERM = 3,
SIGKILL = 9,
INPUT = 10,
}
+3 -2
View File
@@ -1,3 +1,5 @@
import type { SIGNAL_MAP } from "@shell/shell";
export interface ShellError { export interface ShellError {
readonly errorType: string; readonly errorType: string;
readonly message: string; readonly message: string;
@@ -219,6 +221,5 @@ export interface ProtocolError extends ShellError {
/** Process was killed by a signal (Exit = 128 + signalNumber) */ /** Process was killed by a signal (Exit = 128 + signalNumber) */
export interface SignalTerminationError extends ShellError { export interface SignalTerminationError extends ShellError {
errorType: "SignalTermination"; errorType: "SignalTermination";
signalNumber: number; // e.g., 9 (SIGKILL), 15 (SIGTERM), 2 (SIGINT) signal: SIGNAL_MAP;
signalName: string; // e.g., "SIGTERM", "SIGKILL"
} }
+2 -1
View File
@@ -6,13 +6,14 @@ interface UnclosedQuoteError {
timestamp: number; timestamp: number;
} }
export function tokenize(input: string): string[] { export function tokenize(buff: Uint8Array): string[] {
enum State { enum State {
Normal, Normal,
SingleQuote, SingleQuote,
DoubleQuote, DoubleQuote,
Escape, Escape,
} }
const input = new TextDecoder().decode(buff);
const tokens: string[] = []; const tokens: string[] = [];
const buffer: string[] = []; const buffer: string[] = [];
+1 -1
View File
@@ -131,7 +131,7 @@ function compareNode(
} }
case SortNodeBy.INODE: { case SortNodeBy.INODE: {
return r ? a.ptr.inode - b.ptr.inode : b.ptr.inode - a.ptr.inode; return r ? b.ptr.inode - a.ptr.inode : a.ptr.inode - b.ptr.inode;
} }
case SortNodeBy.TYPE: { case SortNodeBy.TYPE: {
+21 -11
View File
@@ -1,7 +1,13 @@
import { getCurrentSession } from "@core/session_manager"; import { getCurrentSession } from "@core/session_manager";
import { resolvePointerToHome } from "@core/util/path_resolver"; import { resolvePointerToHome } from "@core/util/path_resolver";
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline";
import { Termos } from "./entry"; import { Termos } from "./entry";
process.stdin.setRawMode(true);
readline.emitKeypressEvents(process.stdin);
const rl = readline.createInterface({ input, output });
//import { deserializeFileSystem } from "@shell/serializer"; //import { deserializeFileSystem } from "@shell/serializer";
//import { Shell } from "@shell/shell"; //import { Shell } from "@shell/shell";
@@ -36,19 +42,23 @@ shell.on("result", payload => {
shell.on("stdout", payload => { shell.on("stdout", payload => {
const decoded = new TextDecoder().decode(payload.data); const decoded = new TextDecoder().decode(payload.data);
process.stdout.write(decoded); if (decoded === "\x1b[2J\x1b[0;0H") {
}); console.clear();
console.clear();
process.stdout.write(resolvePointerToHome(shell.State, getCurrentSession(shell.State).cwd) + "\n> ");
process.stdin.on("data", async data => {
if (shell.BoundPID !== null) {
shell.sendInput(data.toString().trim());
return; return;
} }
const input = data.toString().trim(); process.stdout.write(decoded);
await shell.execute(input);
}); });
//export { Termos }; let buff = "";
console.clear();
process.stdout.write(resolvePointerToHome(shell.State, getCurrentSession(shell.State).cwd) + "\n> ");
process.stdin.on("keypress", async (str, key) => {
if (key.sequence === "\f") console.clear();
if (buff.length > 3) buff = "";
buff = buff + key.name;
await shell.input(key);
});
+23 -41
View File
@@ -2,16 +2,15 @@ import type { CommandDescriptor } from "@core/command";
import type { CommandIO } from "@core/command_io"; import type { CommandIO } from "@core/command_io";
import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result"; import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
import { SIGNAL_MAP, type Signal } from "@core/signal";
import type { ShellError, SignalTerminationError } from "@core/util/errors"; import type { ShellError, SignalTerminationError } from "@core/util/errors";
import { createImmutableBuffer } from "@core/util/immutable_buffer"; import { createImmutableBuffer } from "@core/util/immutable_buffer";
import { concatUint8Arrays, splitUint8Array } from "@termos/util/concat"; import { concatUint8Arrays, splitUint8Array } from "@termos/util/concat";
import { EventEmitter } from "./event_emitter"; import { EventEmitter } from "./event_emitter";
import type { ShellEventMap } from "./shell"; import { ShellEventMap, SIGNAL_MAP, type Input } from "./shell";
export class Process { export class Process {
private _SignalQueue: Signal[] = []; private _InputQueue: Input[] = [];
private _SignalHandler: ((signal: Signal) => void) | null = null; private _InputHandler: ((signal: Input) => void) | null = null;
private _StdoutChunks: Uint8Array[] = []; private _StdoutChunks: Uint8Array[] = [];
private _StderrChunks: Uint8Array[] = []; private _StderrChunks: Uint8Array[] = [];
private _Settled: boolean = false; private _Settled: boolean = false;
@@ -56,12 +55,12 @@ export class Process {
const io: CommandIO = { const io: CommandIO = {
writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data), writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data),
writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data), writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data),
getSignal: () => { onInput: () => {
const signal: Signal | undefined = this._SignalQueue.shift(); const signal: Input | undefined = this._InputQueue.shift();
if (signal !== undefined) return Promise.resolve(signal); if (signal !== undefined) return Promise.resolve(signal);
const promise = new Promise<Signal>(resolve => { const promise = new Promise<Input>(resolve => {
this._SignalHandler = resolve; this._InputHandler = resolve;
}); });
return promise; return promise;
}, },
@@ -115,51 +114,34 @@ export class Process {
}); });
} }
public sendSignal(signal: Signal): void { public sendInput(input: Input): void {
if (this._Settled) return;
if (this._InputHandler !== null) {
this._InputHandler(input);
this._InputHandler = null;
} else {
this._InputQueue.push(input);
}
}
public sendSignal(signal: SIGNAL_MAP): void {
if (this._Settled) return; if (this._Settled) return;
const result: ResultError<SignalTerminationError> = createErrorResult( const result: ResultError<SignalTerminationError> = createErrorResult(
"SignalTermination", "SignalTermination",
`Process ${this.Name}(${this.PID}) killed by a ${SIGNAL_MAP[signal.type]}(${signal.type})`, `Process ${this.Name} PID: ${this.PID} killed by a ${SIGNAL_MAP[signal]}`,
{ signalNumber: signal.type, signalName: SIGNAL_MAP[signal.type] }, { signal },
this.CommandDescriptor.name, this.CommandDescriptor.name,
); );
switch (signal.type) { switch (signal) {
case SIGNAL_MAP.SIGKILL:
this._SignalHandler = null;
this._Settled = true;
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
return;
case SIGNAL_MAP.SIGTERM:
if (this._SignalHandler !== null) {
this._SignalHandler(signal);
this._SignalHandler = null;
}
this._Settled = true;
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
return;
case SIGNAL_MAP.SIGINT: case SIGNAL_MAP.SIGINT:
if (this._SignalHandler !== null) {
this._SignalHandler(signal);
this._SignalHandler = null;
}
this._Settled = true; this._Settled = true;
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State }); this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
return; return;
default: default:
if (this._SignalHandler !== null) { break;
this._SignalHandler(signal);
this._SignalHandler = null;
} else {
this._SignalQueue.push(signal);
}
} }
} }
+14 -4
View File
@@ -1,9 +1,8 @@
import type { CommandDescriptor } from "@core/command"; import type { CommandDescriptor } from "@core/command";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
import { SIGNAL_MAP, type Signal } from "@core/signal";
import { EventEmitter } from "./event_emitter"; import { EventEmitter } from "./event_emitter";
import { Process } from "./process"; import { Process } from "./process";
import type { ShellEventMap } from "./shell"; import { Input, ShellEventMap, SIGNAL_MAP } from "./shell";
export class ProcessManager { export class ProcessManager {
private _Processes: Map<number, Process> = new Map(); private _Processes: Map<number, Process> = new Map();
@@ -16,6 +15,7 @@ export class ProcessManager {
const process = new Process(pid, state, descriptor, args); const process = new Process(pid, state, descriptor, args);
this._Processes.set(pid, process); this._Processes.set(pid, process);
process.on("signal", payload => this._EventEmitter.emit("signal", payload));
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload)); process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
process.on("stderr", payload => this._EventEmitter.emit("stderr", payload)); process.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
process.on("result", payload => { process.on("result", payload => {
@@ -29,7 +29,7 @@ export class ProcessManager {
return pid; return pid;
} }
public sendSignal(pid: number, signal: Signal): void { public sendSignal(pid: number, signal: SIGNAL_MAP): void {
const process = this._Processes.get(pid); const process = this._Processes.get(pid);
if (!process) { if (!process) {
@@ -41,6 +41,16 @@ export class ProcessManager {
process.sendSignal(signal); process.sendSignal(signal);
} }
public sendInput(pid: number, input: Input): void {
const process = this._Processes.get(pid);
if (!process) {
//Implement a proper error object later to return to shell
console.error("PID not found");
return;
}
process.sendInput(input);
}
public kill(pid: number): void { public kill(pid: number): void {
const process = this._Processes.get(pid); const process = this._Processes.get(pid);
@@ -51,7 +61,7 @@ export class ProcessManager {
} }
//Make global signals an enum later //Make global signals an enum later
process.sendSignal({ type: SIGNAL_MAP.SIGKILL } satisfies Signal); process.sendSignal(SIGNAL_MAP.SIGINT);
} }
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
+62 -21
View File
@@ -2,19 +2,44 @@ import { COMMAND_REGISTRY } from "@core/command_registry";
import { createErrorResult, type Result } from "@core/result"; import { createErrorResult, type Result } from "@core/result";
import { getCurrentSession, type SessionState } from "@core/session_manager"; import { getCurrentSession, type SessionState } from "@core/session_manager";
import { withExitCode, withHistory, type ShellState } from "@core/shell_state"; import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
import { SIGNAL_MAP } from "@core/signal";
import type { ShellError } from "@core/util/errors"; import type { ShellError } from "@core/util/errors";
import { createImmutableBuffer } from "@core/util/immutable_buffer"; import { createImmutableBuffer } from "@core/util/immutable_buffer";
import { tokenize } from "@core/util/parser"; import { tokenize } from "@core/util/parser";
import { concatUint8Arrays } from "@termos/util/concat";
import { EventEmitter } from "./event_emitter"; import { EventEmitter } from "./event_emitter";
import { ProcessManager } from "./process_manager"; import { ProcessManager } from "./process_manager";
export interface TTYState {
width: number;
height: number;
}
export enum SIGNAL_MAP {
CLR = 0,
SIGINT = 1,
}
export interface Input {
sequence: string;
name: string;
ctrl: boolean;
meta: boolean;
shift: boolean;
}
export class Shell { export class Shell {
private _State: Readonly<ShellState>; private _State: Readonly<ShellState>;
private _Session: SessionState; private _Session: SessionState;
private _ProcessManager: ProcessManager = new ProcessManager(); private _ProcessManager: ProcessManager = new ProcessManager();
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter(); private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
private _GlobalKeyMap: ReadonlyMap<string, SIGNAL_MAP>; private _SignalMap: ReadonlyMap<string, SIGNAL_MAP> = new Map([
["\f", SIGNAL_MAP.CLR],
["\x03", SIGNAL_MAP.SIGINT],
]);
private readonly E: TextEncoder = new TextEncoder();
private readonly D: TextDecoder = new TextDecoder();
private _Stdin: Uint8Array = new Uint8Array();
public BoundPID: number | null = null; public BoundPID: number | null = null;
@@ -22,17 +47,12 @@ export class Shell {
this._State = Object.freeze(state); this._State = Object.freeze(state);
this._Session = state.sessionStack[state.sessionStack.length - 1]!; this._Session = state.sessionStack[state.sessionStack.length - 1]!;
//Temporary solution for sigint keybind
const map = new Map();
map.set("ctrl+c", SIGNAL_MAP.SIGINT);
this._GlobalKeyMap = map;
this._ProcessManager.on("stdout", payload => this._EventEmitter.emit("stdout", payload)); this._ProcessManager.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
this._ProcessManager.on("stderr", payload => this._EventEmitter.emit("stderr", payload)); this._ProcessManager.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
this._ProcessManager.on("process", payload => this._EventEmitter.emit("process", payload)); this._ProcessManager.on("process", payload => this._EventEmitter.emit("process", payload));
this._ProcessManager.on("result", payload => { this._ProcessManager.on("result", payload => {
this._State = payload.state; this._State = payload.state;
this._Session = this._State.sessionStack[this._State.sessionStack.length - 1]!;
this._State = withExitCode( this._State = withExitCode(
this._State, this._State,
payload.result.type === "success" ? payload.result.exitCode : payload.result.error.exitCode, payload.result.type === "success" ? payload.result.exitCode : payload.result.error.exitCode,
@@ -41,9 +61,37 @@ export class Shell {
if (this.BoundPID === payload.pid) this.BoundPID = null; if (this.BoundPID === payload.pid) this.BoundPID = null;
this._EventEmitter.emit("result", payload); this._EventEmitter.emit("result", payload);
}); });
this._ProcessManager.on("signal", payload => this._EventEmitter.emit("signal", payload));
} }
public async execute(input: string): Promise<void> { public async input(key: {
sequence: string;
name: string;
ctrl: boolean;
meta: boolean;
shift: boolean;
}): Promise<void> {
const stdin = Uint8Array.from(this._Stdin);
switch (key.sequence) {
case "\x03":
if (!this.BoundPID) break;
const sig = this._SignalMap.get(key.sequence)!;
this._ProcessManager.sendSignal(this.BoundPID, sig);
break;
case "\r":
if (this.BoundPID) this._ProcessManager.sendInput(this.BoundPID, key);
this._Stdin = new Uint8Array();
this._execute(stdin);
break;
default:
if (this.BoundPID) this._ProcessManager.sendInput(this.BoundPID, key);
const buffer = this.E.encode(key.sequence);
this._Stdin = concatUint8Arrays([stdin, buffer]);
break;
}
}
private async _execute(input: Uint8Array): Promise<void> {
const parsed = tokenize(input); const parsed = tokenize(input);
if (!parsed[0]) return; if (!parsed[0]) return;
@@ -64,6 +112,7 @@ export class Shell {
); );
this._State = withExitCode(this._State, result.error.exitCode); this._State = withExitCode(this._State, result.error.exitCode);
this._Session = this._State.sessionStack[this._State.sessionStack.length - 1]!;
this._EventEmitter.emit("result", { pid: 0, result, state: this._State }); this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
return; return;
} }
@@ -77,6 +126,7 @@ export class Shell {
); );
this._State = withExitCode(this._State, result.error.exitCode); this._State = withExitCode(this._State, result.error.exitCode);
this._Session = this._State.sessionStack[this._State.sessionStack.length - 1]!;
this._EventEmitter.emit("result", { pid: 0, result, state: this._State }); this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
return; return;
} }
@@ -87,18 +137,8 @@ export class Shell {
this.BoundPID = pid; this.BoundPID = pid;
} }
public sendInput(input: string): void { public getHistoryIndex(i: number): Uint8Array | undefined {
const signal = this._GlobalKeyMap.get(input); return this._Session.history[i];
if (signal !== undefined) {
if (this.BoundPID !== null) {
this._ProcessManager.sendSignal(this.BoundPID, { type: signal });
}
} else {
if (this.BoundPID !== null) {
this._ProcessManager.sendSignal(this.BoundPID, { type: SIGNAL_MAP.INPUT, payload: input });
}
}
} }
public get State(): Readonly<ShellState> { public get State(): Readonly<ShellState> {
@@ -127,4 +167,5 @@ export interface ShellEventMap {
stdout: { pid: number; data: Uint8Array }; stdout: { pid: number; data: Uint8Array };
stderr: { pid: number; data: Uint8Array }; stderr: { pid: number; data: Uint8Array };
result: { pid: number; result: Result<ShellError>; state: ShellState }; result: { pid: number; result: Result<ShellError>; state: ShellState };
signal: { pid: number; sig: SIGNAL_MAP };
} }
+18
View File
@@ -0,0 +1,18 @@
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline";
process.stdin.setRawMode(true);
readline.emitKeypressEvents(process.stdin);
const rl = readline.createInterface({ input, output });
const d = new TextDecoder();
//@ts-ignore
rl.on("line", input => {
console.log(`Received: ${input}`);
});
process.stdin.on("keypress", async (str, key) => {
console.log(str, key);
});