WRITE UNIT TESTS!!!

first async command working, no unit tests done AGAING
This commit is contained in:
2026-08-23 06:39:37 +02:00
parent e313aa5b9d
commit 268729bb62
18 changed files with 331 additions and 93 deletions
-17
View File
@@ -1,17 +0,0 @@
/*
Create an interface for the rest of the library to use to fetch nessesary data.
To do that, implement a termos config that will contain the table and db names, aswell as other relevant information -
maybe a flag for headless mode (uses the built-in console frontend module - need to evaluate this idea more)
*/
export async fetchFileSystem(): Promise<JSON> {
}
export async fetchUserGroups(): Promise<JSON> {
}
export async fetchUsers(): Promise<JSON> {
}
+10 -8
View File
@@ -1,14 +1,16 @@
type Listener = (payload: unknown) => void;
export class EventEmitter<TEvents> {
private Handlers: Map<keyof TEvents, Set<Function>> = new Map();
private Handlers: Map<keyof TEvents, Set<Listener>> = new Map();
public on<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
const listeners = this.Handlers.get(type);
if (listeners) {
listeners.add(handler);
listeners.add(handler as Listener);
} else {
const set: Set<Function> = new Set();
set.add(handler);
const set: Set<Listener> = new Set();
set.add(handler as Listener);
this.Handlers.set(type, set);
}
@@ -16,7 +18,7 @@ export class EventEmitter<TEvents> {
}
public off<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): void {
this.Handlers.get(type)?.delete(handler);
this.Handlers.get(type)?.delete(handler as Listener);
}
public once<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
@@ -28,10 +30,10 @@ export class EventEmitter<TEvents> {
};
if (listeners) {
listeners.add(wrapper);
listeners.add(wrapper as Listener);
} else {
const set: Set<Function> = new Set();
set.add(wrapper);
const set: Set<Listener> = new Set();
set.add(wrapper as Listener);
this.Handlers.set(type, set);
}
+19 -7
View File
@@ -14,6 +14,7 @@ export class Process {
private _StdoutChunks: Uint8Array[] = [];
private _StderrChunks: Uint8Array[] = [];
private _Settled: boolean = false;
private _EventEmitter: EventEmitter<ShellEventMap>;
private readonly _MaxChunkByteSize: number;
readonly PID: number;
@@ -21,7 +22,6 @@ export class Process {
readonly State: ShellState;
readonly Args: string[];
readonly Flags: string[];
EventEmitter: EventEmitter<ShellEventMap>;
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) {
this.PID = pid;
@@ -31,7 +31,7 @@ export class Process {
this.Args = args;
// Check if positive later and throw an error if so
this._MaxChunkByteSize = 1024;
this.EventEmitter = new EventEmitter<ShellEventMap>();
this._EventEmitter = new EventEmitter<ShellEventMap>();
}
private concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
@@ -67,13 +67,13 @@ export class Process {
if (data.length <= this._MaxChunkByteSize) {
chunks.push(data);
this.EventEmitter.emit(eventType, { pid: this.PID, data });
this._EventEmitter.emit(eventType, { pid: this.PID, data });
return;
} else {
const arr = this.divideToChunks(data);
for (const ent of arr) {
chunks.push(ent);
this.EventEmitter.emit(eventType, { pid: this.PID, data: ent });
this._EventEmitter.emit(eventType, { pid: this.PID, data: ent });
}
}
}
@@ -118,7 +118,7 @@ export class Process {
};
}
this.EventEmitter.emit("result", { pid: this.PID, result, state: output.state });
this._EventEmitter.emit("result", { pid: this.PID, result, state: output.state });
this._Settled = true;
})
.catch(error => {
@@ -137,7 +137,7 @@ export class Process {
},
);
this.EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
});
}
@@ -161,7 +161,7 @@ export class Process {
this.CommandDescriptor.name,
);
this.EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
return;
} else {
if (this._SignalHandler !== null) {
@@ -172,4 +172,16 @@ export class Process {
}
}
}
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
return this._EventEmitter.on(type, handler);
}
public once<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
return this._EventEmitter.once(type, handler);
}
public off<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): void {
this._EventEmitter.off(type, handler);
}
}
+21 -7
View File
@@ -9,22 +9,24 @@ export class ProcessManager {
private _Processes: Map<number, Process> = new Map();
private _PIDIndex: number = 0;
EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
public createProcess(state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]): void {
public createProcess(state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]): number {
const pid = ++this._PIDIndex;
const process = new Process(pid, state, descriptor, flags, args);
this._Processes.set(pid, process);
process.EventEmitter.on("stdout", payload => this.EventEmitter.emit("stdout", payload));
process.EventEmitter.on("stderr", payload => this.EventEmitter.emit("stderr", payload));
process.EventEmitter.on("result", payload => {
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
process.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
process.on("result", payload => {
this._Processes.delete(payload.pid);
this.EventEmitter.emit("result", payload);
this._EventEmitter.emit("result", payload);
});
this.EventEmitter.emit("process", { pid, name: descriptor.name });
this._EventEmitter.emit("process", { pid, name: descriptor.name });
process.execute();
return pid;
}
public sendSignal(pid: number, signal: Signal): void {
@@ -51,4 +53,16 @@ export class ProcessManager {
//Make global signals an enum later
process.sendSignal({ type: "SIGKILL" } satisfies Signal);
}
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
return this._EventEmitter.on(type, handler);
}
public once<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
return this._EventEmitter.once(type, handler);
}
public off<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): void {
this._EventEmitter.off(type, handler);
}
}
+5 -3
View File
@@ -27,7 +27,8 @@ const DirectoryNodeSchema = z.object({
ctime: z.number(),
atime: z.number(),
type: z.literal("directory"),
children: z.array(z.lazy((): any => TreeNodeSchema)),
//eslint-ignore
children: z.array(z.lazy((): any => TreeNodeSchema)), // eslint-disable-line @typescript-eslint/no-explicit-any
});
const TreeNodeSchema = z.union([FileNodeSchema, DirectoryNodeSchema]);
@@ -40,7 +41,8 @@ export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNod
const map = new Map<number, TreeNode>();
function parseNode(tree: any, parent: number): void {
// prettier-ignore
function parseNode(tree: any, parent: number): void { // eslint-disable-line @typescript-eslint/no-explicit-any
if (tree.type === "directory") {
const children: Record<string, number> = {};
@@ -75,7 +77,7 @@ export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNod
mtime: tree.mtime,
ctime: tree.ctime,
atime: tree.atime,
content: createImmutableBuffer(new Uint8Array()),
content: createImmutableBuffer(Uint8Array.from(tree.content)),
};
map.set(tree.inode, Object.freeze(fileNode));
}
+71 -25
View File
@@ -1,18 +1,40 @@
import { COMMAND_REGISTRY } from "@core/command_registry";
import { createErrorResult, createSuccessResult, type Result, type ResultError } from "@core/result";
import { createErrorResult, type Result } from "@core/result";
import { getCurrentSession } from "@core/session_manager";
import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
import type { CommandNotFoundError, ParseError, PermissionDeniedError, ShellError } from "@core/util/errors";
import type { ShellError } from "@core/util/errors";
import { createImmutableBuffer } from "@core/util/immutable_buffer";
import { parseCommand } from "@core/util/parser";
import { EventEmitter } from "./event_emitter";
import { ProcessManager } from "./process_manager";
export class Shell {
static #Instance: Shell;
static #Promise: Promise<Shell> | null = null;
private _State: Readonly<ShellState>;
private _ProcessManager: ProcessManager = new ProcessManager();
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
private _GlobalKeyMap: ReadonlyMap<string, string>;
public BoundPID: number | null = null;
private constructor(state: ShellState) {
this._State = Object.freeze(state);
this._GlobalKeyMap = new Map();
this._ProcessManager.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
this._ProcessManager.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
this._ProcessManager.on("process", payload => this._EventEmitter.emit("process", payload));
this._ProcessManager.on("result", payload => {
this._State = payload.state;
this._State = withExitCode(
this._State,
payload.result.type === "success" ? payload.result.exitCode : payload.result.error.exitCode,
);
if (this.BoundPID === payload.pid) this.BoundPID = null;
this._EventEmitter.emit("result", payload);
});
}
static async init(initialState: ShellState): Promise<Shell> {
@@ -35,64 +57,76 @@ export class Shell {
return Shell.#Promise;
}
public async Execute(input: string): Promise<Result<ShellError>> {
public async execute(input: string): Promise<void> {
let parsed;
try {
parsed = parseCommand(input);
} catch {
return createErrorResult(
const result = createErrorResult(
"ParseError",
`Parsing error - ${input}`,
{},
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
"",
) satisfies ResultError<ParseError>;
);
this._State = withExitCode(this._State, result.error.exitCode);
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
return;
}
if (parsed.command === "") {
return createSuccessResult(
"",
0,
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
);
}
if (parsed.command === "") return;
this._State = withHistory(this._State, input);
const command = COMMAND_REGISTRY.get(parsed.command);
if (!command)
return createErrorResult(
if (!command) {
const result = createErrorResult(
"CommandNotFound",
`Command ${parsed.command} not found`,
{ command: parsed.command },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
parsed.command,
) satisfies ResultError<CommandNotFoundError>;
);
this._State = withExitCode(this._State, result.error.exitCode);
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
return;
}
if (command.requiresRoot && getCurrentSession(this._State).user.uid != 0) {
return createErrorResult(
const result = createErrorResult(
"PermissionDenied",
`Permission Denied`,
{ resource: `Execution of the ${command.name} command` },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
parsed.command,
) satisfies ResultError<PermissionDeniedError>;
);
this._State = withExitCode(this._State, result.error.exitCode);
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
return;
}
const out = command.fn(this._State, parsed.flags, parsed.args);
this._State = out.state;
const pid = this._ProcessManager.createProcess(this._State, command, parsed.flags, parsed.args);
this.BoundPID = pid;
}
if (out.result.type === "error") {
this._State = withExitCode(this._State, out.result.error.exitCode);
public sendInput(input: string): void {
const signal = this._GlobalKeyMap.get(input);
if (signal !== undefined) {
if (this.BoundPID !== null) {
this._ProcessManager.sendSignal(this.BoundPID, { type: signal });
}
} else {
this._State = withExitCode(this._State, out.result.exitCode);
if (this.BoundPID !== null) {
this._ProcessManager.sendSignal(this.BoundPID, { type: "INPUT", payload: input });
}
}
return out.result;
}
public get State(): Readonly<ShellState> {
@@ -106,6 +140,18 @@ export class Shell {
}
return Shell.#Instance;
}
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
return this._EventEmitter.on(type, handler);
}
public once<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
return this._EventEmitter.once(type, handler);
}
public off<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): void {
this._EventEmitter.off(type, handler);
}
}
export interface ShellEventMap {