WIP: new abstraction layer, file system now a singleton, shell should be too

This commit is contained in:
2026-05-13 17:56:19 +02:00
parent 106abd851a
commit 619de5e1f8
24 changed files with 628 additions and 302 deletions
+1
View File
@@ -8,6 +8,7 @@ declare global {
// interface PageState {}
// interface Platform {}
}
namespace TermOS {}
}
export {};
+45 -43
View File
@@ -1,12 +1,17 @@
import { VirtualFS, type TreeNode } from './fs';
import { Terminal, type PrintData } from '../terminal/terminal';
import { Stack } from '../stack';
import { PASSWD, type User } from './etc/userData';
import { ExitCode } from './metadata';
import { COMMANDS, type CommandArgs, type CommandResultData, type ICommand } from './commandRegistry';
import { Terminal, type PrintData } from '../terminal/terminal';
import {
COMMANDS,
type CommandArgs,
type CommandResultData,
type ICommand
} from './commandRegistry';
import { GROUP, type Group } from './etc/groupData';
import { Process } from './process';
import { PASSWD, type User } from './etc/userData';
import { VirtualFS, type TreeNode } from './fs';
import type { KeybindInhibitor } from './keybindInhibitor';
import { ExitCode } from './metadata';
import { Process } from './process';
export enum Signal {
SIGINT,
@@ -16,7 +21,7 @@ export enum Signal {
export type BashInitArgs = {
io?: Terminal;
fs: Map<number, TreeNode>;
user: {username: string, password: string};
user: { username: string; password: string };
};
export type Result = {
@@ -31,13 +36,12 @@ export class Bash {
private readonly _group: Group[];
private readonly _terminal!: Terminal;
private readonly _commands: Record<string, ICommand>;
private _userInstances: Stack<User>;
private user: User;
private _process?: Process;
constructor(args: BashInitArgs) {
this._commands = COMMANDS;
this._passwd = PASSWD;
@@ -46,33 +50,29 @@ export class Bash {
this._terminal = args.io!;
const loginResult = this.userLogin(args.user.username, args.user.password);
if(loginResult == ExitCode.ERROR)
if (loginResult == ExitCode.ERROR)
this._terminal.throwExeption(
`Failed to initialize bash instance - access denied for user ${args.user.username}`,
ExitCode.ERROR
)
`Failed to initialize bash instance - access denied for user ${args.user.username}`,
ExitCode.ERROR
);
this.user = this._userInstances.peek()!
this.vfs = new VirtualFS({ fs: args.fs, user: this.user});
this.user = this._userInstances.peek()!;
this.vfs = new VirtualFS({ fs: args.fs, user: this.user });
}
private _initNewUserSession(user: User): User {
if(!this._passwd.includes(user))
this._terminal.throwExeption(`user not found under the name ${user.username}`, ExitCode.ERROR)
if (!this._passwd.includes(user))
this._terminal.throwExeption(
`user not found under the name ${user.username}`,
ExitCode.ERROR
);
this._userInstances.push(user);
return user
return user;
}
private async _initNewProcess(command: ICommand, args: CommandArgs) {
this._process = new Process(
this,
this.user.uid,
'TEMP PROCESS NAME',
command,
args
);
private async _initNewProcess(command: ICommand, args: CommandArgs) {
this._process = new Process(this, this.user.uid, 'TEMP PROCESS NAME', command, args);
//this._terminal.isProcessActive = true;
}
@@ -83,7 +83,7 @@ export class Bash {
output: output,
cmd: cmd
};
console.log(this.vfs.formatPath(this.vfs.getPathByInode(inode)), "TEST TEST !@#");
console.log(this.vfs.formatPath(this.vfs.getPathByInode(inode)), 'TEST TEST !@#');
this._terminal.PrintOutput(data);
}
@@ -118,17 +118,16 @@ export class Bash {
}
getProcess(): Process | ExitCode.ERROR {
if(this._process) {
if (this._process) {
return this._process;
}
return ExitCode.ERROR;
}
getProcessKeybindInhibitor(): KeybindInhibitor | null {
if(this._process) {
if (this._process) {
return this._process.getKeybindInhibitor();
}
else return null;
} else return null;
}
getTerminalWidth(): number {
@@ -140,20 +139,20 @@ export class Bash {
}
hasSudoPerms(uid: number): boolean {
return this._group[1].members.includes(uid);
return this._group[0].members.includes(uid);
}
async executeCommand(commandName: string, args: CommandArgs): Promise<Result> {
let result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd() };
const command: ICommand = this._commands[commandName];
if (!command) this.throwError(result);
if (command.root) {
if (this.hasSudoPerms(this.user.uid)) {
await this._initNewProcess(command, args);
if(!this._process) throw new Error('failed to init new process');
if (!this._process) throw new Error('failed to init new process');
const out: Result = await this._process.getResult();
this._appendNewResult(this.getCwd(), out, this.user.history[0]);
}
@@ -161,7 +160,7 @@ export class Bash {
}
await this._initNewProcess(command, args);
if(!this._process) throw new Error('failed to init new process');
if (!this._process) throw new Error('failed to init new process');
const out: Result = await this._process.getResult();
console.log(out);
@@ -170,6 +169,10 @@ export class Bash {
return out;
}
static testMethod() {
//
}
throwError(result: Result): void {
switch (result.exitCode) {
default: {
@@ -188,13 +191,12 @@ export class Bash {
}
userLogin(username: string, passwd: string): ExitCode {
const user: User | undefined =
this._passwd.find((user) => user.username === username);
const user: User | undefined = this._passwd.find((user) => user.username === username);
if(user && user.passwd === passwd) {
if (user && user.passwd === passwd) {
this._initNewUserSession(user);
return ExitCode.SUCCESS;
}
}
return ExitCode.ERROR;
}
+22 -22
View File
@@ -1,39 +1,39 @@
import { isBuildCommand } from "typescript";
import type { KeyBind } from "../terminal/keybindRegistry";
import type { Bash, Result } from "./bash";
import { cd } from "./commands/cd";
import { clear } from "./commands/clear";
import { ls } from "./commands/ls";
import { testProcess } from "./commands/testAsync";
import { WebG } from '$lib/shimagic/renderer/web_g_engine';
import type { KeyBind } from '../terminal/keybindRegistry';
import type { Bash, Result } from './bash';
import { cd } from './commands/cd';
import { clear } from './commands/clear';
import { ls } from './commands/ls';
import { testProcess } from './commands/testAsync';
export type ICommand = {
method: (this: Bash, args: CommandArgs) => Result;
keybinds?: Map<KeyBind, () => any>;
flags: string[];
help: string;
root: boolean;
method: (this: Bash, args: CommandArgs) => Result;
keybinds?: Map<KeyBind, () => any>;
flags: string[];
help: string;
root: boolean;
};
export type CommandArgs = {
flags: string[];
args: string[];
flags: string[];
args: string[];
};
export type CommandResultData = {
cmd: string; //the string that contains the shorthand for the command that was executed - used in a switch statement in parseResult
data: any; //the data that the commmand may have returned like TreeNodes[] from ls
args?: CommandArgs;
cmd: string; //the string that contains the shorthand for the command that was executed - used in a switch statement in parseResult
data: any; //the data that the commmand may have returned like TreeNodes[] from ls
args?: CommandArgs;
};
TermOS.Shell.Command.
export const COMMANDS = {
cd,
ls,
clear,
testProcess
clear,
testProcess
} as const satisfies Record<string, ICommand>;
WebG.
/* //export const commands {
return: {
method: this.cmd_return,
@@ -150,4 +150,4 @@ export const COMMANDS = {
flags: [],
help: "",
}
} */
} */
+1
View File
@@ -22,6 +22,7 @@ export const cmd_cd = function (this: Bash, args: CommandArgs): Result {
if (args.args[0] === '-') {
[this.getFs().cwd, this.getFs().pwd] = [this.getFs().pwd, this.getFs().cwd];
result.exitCode = ExitCode.SUCCESS;
return result;
}
-6
View File
@@ -9,9 +9,3 @@ export enum ExitCode {
SUCCESS = 0,
ERROR = 1
}
export type Permission = {
r: boolean;
w: boolean;
x: boolean;
};
+61 -65
View File
@@ -1,74 +1,70 @@
import type { Bash, Result } from "./bash";
import type { CommandArgs, ICommand } from "./commandRegistry";
import { KeybindInhibitor } from "./keybindInhibitor";
import { ExitCode } from "./metadata";
import type { Bash, Result } from './bash';
import type { CommandArgs, ICommand } from './commandRegistry';
import { KeybindInhibitor } from './keybindInhibitor';
import { ExitCode } from './metadata';
export class Process {
private _bash: Bash;
private _result: Result;
private _uid: number;
private _name: string;
private _initTimestamp: Date;
private _keybindInhibitor?: KeybindInhibitor;
private _abortController: AbortController;
private _bash: Bash;
private _result: Result;
private _uid: number;
private _name: string;
private _initTimestamp: Date;
private _keybindInhibitor?: KeybindInhibitor;
private _abortController: AbortController;
constructor(
_bashInstance: Bash,
uid: number,
name: string,
command: ICommand,
args: CommandArgs
) {
this._bash = _bashInstance;
this._result = { exitCode: ExitCode.ERROR, path: this._bash.getCwd() }
this._uid = uid;
this._name = name;
this._initTimestamp = new Date();
this._abortController = new AbortController();
if(command.keybinds) {
this._keybindInhibitor = new KeybindInhibitor(command.keybinds);
}
this._Run(command, _bashInstance, args);
}
public getKeybindInhibitor(): KeybindInhibitor | null {
if(this._keybindInhibitor) {
return this._keybindInhibitor;
}
else {
return null;
}
}
constructor(
_bashInstance: Bash,
uid: number,
name: string,
command: ICommand,
args: CommandArgs
) {
this._bash = _bashInstance;
this._result = { exitCode: ExitCode.ERROR, path: this._bash.getCwd() };
this._uid = uid;
this._name = name;
this._initTimestamp = new Date();
this._abortController = new AbortController();
public sigKill(callback: () => void): ExitCode {
this._abortController.abort();
callback();
if (command.keybinds) {
this._keybindInhibitor = new KeybindInhibitor(command.keybinds);
}
return ExitCode.SUCCESS //Only temp, need to add ExitCode.INT
}
this._Run(command, _bashInstance, args);
}
public getUid(): number {
return this._uid;
}
public getKeybindInhibitor(): KeybindInhibitor | null {
if (this._keybindInhibitor) {
return this._keybindInhibitor;
} else {
return null;
}
}
public getInitTime(): Date {
return this._initTimestamp;
}
public sigKill(callback: () => void): ExitCode {
this._abortController.abort();
callback();
public getName(): string {
return this._name;
}
return ExitCode.SUCCESS; //Only temp, need to add ExitCode.INT
}
public async getResult(): Promise<Result> {
return this._result;
}
private async _Run(command: ICommand, bashInstance: Bash, args: CommandArgs) {
this._result = command.method.call(
bashInstance, args);
}
}
public getUid(): number {
return this._uid;
}
public getInitTime(): Date {
return this._initTimestamp;
}
public getName(): string {
return this._name;
}
public async getResult(): Promise<Result> {
return this._result;
}
private async _Run(command: ICommand, bashInstance: Bash, args: CommandArgs) {
this._result = command.method.call(bashInstance, args);
}
}
+5 -8
View File
@@ -1,4 +1,3 @@
import { TermOS } from '$lib/termos/termos';
import type { TreeNode } from '../bash/fs';
//import { type ILocale } from './localeRegistry';
import { Terminal, type PageCallbacks, type TermInitArgs } from './terminal';
@@ -9,7 +8,7 @@ export function isInitializing(): boolean {
return initializing;
}
function jsonToNodeTable(data: any): Map<number, TreeNode> {
function jsonToNodeTable(data: JSON): Map<number, TreeNode> {
const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
const entryList = Object.entries(data);
@@ -24,7 +23,7 @@ function jsonToNodeTable(data: any): Map<number, TreeNode> {
func: object.Func,
children: object.Children,
content: object.Content,
link: object.Link,
link: object.Target,
permission: {
user: {
r: object.Permission[0]?.Read,
@@ -57,7 +56,7 @@ function jsonToNodeTable(data: any): Map<number, TreeNode> {
return FsTable;
}
async function fetchFsJson(sig: string): Promise<any> {
async function fetchFsJson(sig: string): Promise<JSON> {
const signature: string | null = localStorage.getItem('signature');
if (signature !== sig || signature === null || localStorage.getItem('fs') === null) {
@@ -108,16 +107,14 @@ async function fetchLocale(id: string): Promise<any> {
return data;
}
TermOS.Shell.Bash;
export async function initTerminal(
user: { username: string; password: string },
callbackInit: PageCallbacks,
localeId: string
): Promise<Terminal> {
): Promise<Shell> {
try {
const sig = await fetchFsSignature('/src/lib/assets/fs/signature');
const fsJson = await fetchFsJson(sig);
const fsJson: JSON = await fetchFsJson(sig);
const fs: Map<number, TreeNode> = jsonToNodeTable(fsJson);
/* const locale: ILocale = {
id: localeId,
+2 -2
View File
@@ -23,7 +23,7 @@ function appendOutput(container: HTMLElement, props: OutputProps): Output | unde
}
export function print(e: HTMLElement, data: PrintData): void {
if(data.cmd == 'clear') return;
if (data.cmd == 'clear') return;
if (isInitializing()) {
console.error('Terminal is initializing! Skipping Print');
@@ -37,7 +37,7 @@ export function print(e: HTMLElement, data: PrintData): void {
}
export function clear(): void {
for(const instance of outputInstances) {
for (const instance of outputInstances) {
unmount(instance, {});
}
}
+2
View File
@@ -33,6 +33,8 @@ export type PageCallbacks = {
getFontSize: () => number;
};
TermOS.Shell;
export class Terminal {
private _bash: Bash;
private _callbacks: Partial<PageCallbacks> = {};
+3
View File
@@ -0,0 +1,3 @@
import { Command } from '../shell/command';
export class cd extends Command {}
+322
View File
@@ -0,0 +1,322 @@
import type { User } from '../shell/shell';
export class FileSystem {
static #instance: FileSystem;
private _fs: Map<number, TreeNode>;
private _root: number;
private constructor() {
const
this._fs = this._jsonToNodeTable();
this._root = this._fs.values().next().value!.inode;
if (!this._root) throw new Error('First entry in the filesystem map empty!');
}
private async _fetchFsSignature(path: string): Promise<any> {
try {
const response = await fetch(path);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.text();
return data.slice(0, 36); //32 characters of uuid + 4 dashes
} catch (error) {
console.error('Failed to fetch the file system signature', error);
}
}
private async _fetchFileSystem(path: string): Promise<any> {
const response = await fetch(path);
if (!response.ok) throw new Error('Failed to fetch the file system json');
const data = await response.json();
return data;
}
private async fetchFsJson(sig: string): Promise<JSON> {
const signature: string | null = localStorage.getItem('signature');
if (signature !== sig || signature === null || localStorage.getItem('fs') === null) {
const fs: JSON = await this._fetchFileSystem('/src/lib/assets/fs/fs.json');
localStorage.setItem('signature', sig);
localStorage.setItem('fs', JSON.stringify(fs));
console.info('FS fetched from file, new sinature:', sig);
return fs;
} else {
const fs: string | null = localStorage.getItem('fs');
if (fs === null) throw new Error('FS in LocalStorage is null!');
console.info('FS fetched from localStorage with signature:', sig);
return JSON.parse(fs);
}
}
private _jsonToNodeTable(data: JSON): Map<number, TreeNode> {
const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
const entryList = Object.entries(data);
for (let i = 0; i < entryList.length; i++) {
const object: any = entryList[i][1];
const node: TreeNode = {
inode: object.Inode,
name: object.Name,
type: object.Type,
size: object.Size,
interactible: object.Interactible,
func: object.Func,
children: object.Children,
content: object.Content,
link: object.Target,
permission: {
user: {
r: object.Permission[0]?.Read,
w: object.Permission[0]?.Write,
x: object.Permission[0]?.Exec
},
group: {
r: object.Permission[1]?.Read,
w: object.Permission[1]?.Write,
x: object.Permission[1]?.Exec
},
other: {
r: object.Permission[2]?.Read,
w: object.Permission[2]?.Write,
x: object.Permission[2]?.Exec
}
},
owner: object.Owner,
group: object.Group,
timestamps: {
modified: new Date(object.TimeStamps.MTime),
changed: new Date(object.TimeStamps.CTime),
accessed: new Date(object.TimeStamps.ATime)
},
parent: object.Parent
};
FsTable.set(object.Inode, node);
}
return FsTable;
}
private _createNode(name: string, type: Type, path: number, user: User): void {
const currTime: Date = new Date();
const node: TreeNode = {
parent: path,
inode: this._fs.size + 1,
name: name,
type: type,
size: 4096,
children: [],
content: '',
link: -1,
permission: {
user: {
r: true,
w: true,
x: false
},
group: {
r: true,
w: false,
x: false
},
other: {
r: true,
w: false,
x: false
}
},
owner: user.uid,
group: user.gid,
timestamps: {
modified: currTime,
changed: currTime,
accessed: currTime
},
interactible: false,
func: null
};
this._fs.set(this._fs.size + 1, node);
}
private _deleteNode(inode: number): void {
this._fs.delete(inode);
}
private _iNodeToPathString(inode: number): string | null {
const currentNode = this._fs.get(inode);
if (!currentNode) return null;
if (!currentNode.parent || currentNode.inode === this._root) return '/';
const parentPath: string | null = this._iNodeToPathString(currentNode.parent);
if (!parentPath) return null;
return parentPath === '/' ? `/${currentNode.name}` : `${parentPath}/${currentNode.name}`;
}
private _pathStringToNode(path: string): TreeNode | null {
// Truncates all slatshes at the start and end of the string
const normalizedPath: string = path.replace(/^\/+|\/+$/g, '');
// Splits the path to node names and filters them out from empty strings
const pathComponents: string[] = normalizedPath.split('/').filter((node) => node.length > 0);
let currentNode: TreeNode | undefined = this._fs.get(this._root);
if (!currentNode) return null;
if (pathComponents.length === 0) return currentNode;
for (const component of pathComponents) {
const childINode: number | undefined = this._getChildNodeByName(
currentNode!,
component
)?.inode;
if (!childINode) return null;
const nextNode = this._fs.get(childINode);
if (!nextNode) return null;
currentNode = nextNode;
}
return currentNode;
}
private _getChildNodeByName(node: TreeNode, name: string): TreeNode | null {
for (const inode of node.children) {
const child = this._fs.get(inode);
if (child && child.name === name) return child;
}
return null;
}
private _isAbsolutePath = (path: string): boolean => {
return typeof path === 'string' && path.startsWith('/');
};
public getPathByINode(inode: number): string | null {
return this._iNodeToPathString(inode);
}
public formatPath(path: string, user: User): string {
if (path.startsWith(user.home)) return path.replace(user.home, '~');
return path;
}
public resolvePath(path: string, user: User): TreeNode | null {
if (path === '/') return this._fs.get(this._root)!;
let parsedPath: string = path;
if (!this._isAbsolutePath(path)) {
const trail = this._iNodeToPathString(user.cwd!);
if (!trail)
throw new Error('Somehow the current user has his cwd set to a nonexistant directory', {
cause: 'iNodeToPathString returned null from user.cwd'
});
parsedPath = `${trail}/${path}`;
}
if (path.startsWith('~')) {
const trail = user.home;
if (!trail)
throw new Error('User has his home directory set to a nonexistant one or is undefined', {
cause: 'iNodeToPathString returned null from user.home'
});
parsedPath = `${trail}/${path.replace('~', '')}`;
}
return this._pathStringToNode(parsedPath);
}
public recursiveTraversalPre(
node: TreeNode,
callback: (param: TreeNode) => void,
childIndex?: number[],
depthIndex?: number
): void | null {
if (!depthIndex) depthIndex = 0;
if (!childIndex) childIndex = [0];
if (node.type != Type.File && node.children[childIndex[depthIndex]]) {
let unNode = this._fs.get(node.children[childIndex[depthIndex]]);
if (!unNode) return null;
node = unNode;
depthIndex++;
if (!childIndex[depthIndex]) childIndex[depthIndex] = 0;
callback(node);
} else {
let unNode = this._fs.get(node.parent);
if (!unNode) return null;
node = unNode;
childIndex[depthIndex] = 0;
depthIndex--;
childIndex[depthIndex]++;
}
if (depthIndex < 0) return;
this.recursiveTraversalPre(node, callback, childIndex, depthIndex);
}
public static get instance(): FileSystem {
if(!FileSystem.#instance) {
FileSystem.#instance = new FileSystem();
}
return FileSystem.instance;
}
}
export type TreeNode = {
inode: number;
parent: number;
name: string;
type: Type;
size: number; //Size in Bytes
children: number[];
content: string; // GUID of the cache file that contains the file contents.
link: number; // Links
permission: NodePermission;
owner: number;
group: number;
timestamps: TimeStamps;
interactible: boolean;
func: any;
};
export enum Type {
Directory = 16384,
File = 32768,
SymbolicLink = 40960
}
export type NodePermission = {
user: Permission;
group: Permission;
other: Permission;
};
export type Permission = {
r: boolean;
w: boolean;
x: boolean;
};
export type TimeStamps = {
modified: Date;
changed: Date;
accessed: Date;
};
-1
View File
@@ -1 +0,0 @@
declare namespace FileSystem {}
-7
View File
@@ -1,7 +0,0 @@
namespace TermOS {
export namespace Shell {
export class Bash {
private readonly _fs: TermOS.
}
}
}
-27
View File
@@ -1,27 +0,0 @@
namespace TermOS {
export namespace Shell {
export abstract class Command {
public abstract readonly _flags: CommandFlag[];
public abstract readonly _root: boolean;
public abstract readonly _keybinds?: Map<KeyBind, () => any>;
public abstract readonly _help: string; //TODO: Dont know where to pull the help text from yet
public abstract result: CommandResult = { bin: this.constructor.name };
public abstract Main(this: Bash, flags: CommandFlag[], args: string[]) {}
}
export type CommandFlag = {
flag: string;
values?: string[];
};
export type CommandResult = {
bin: string;
flags?: CommandFlag[];
args?: string[];
path: number;
exitcode: ExitCode;
data?: any;
};
}
}
+23
View File
@@ -0,0 +1,23 @@
export abstract class Command {
public abstract readonly _flags: CommandFlag[];
public abstract readonly _root: boolean;
//public abstract readonly _keybinds?: Map<KeyBind, () => any>;
public abstract readonly _help: string; //TODO: Dont know where to pull the help text from yet
public abstract result: CommandResult;
public abstract Main(this: Shell, flags: CommandFlag[], args: string[]): void;
}
export type CommandFlag = {
flag: string;
values?: string[];
};
export type CommandResult = {
bin: string;
flags?: CommandFlag[];
args?: string[];
path: number;
exitcode: ExitCode;
data?: any;
};
@@ -1,30 +1,30 @@
import type { CommandArgs } from "$lib/stores/bash/commandRegistry";
import type { KeybindInhibitor } from "$lib/stores/bash/keybindInhibitor";
import type { ExitCode } from "$lib/stores/bash/metadata";
import type { Command, CommandResult } from "./command";
namespace TermOS {
export namespace Shell {
export class Process {
private _bash: Bash;
private _shell: Shell;
private _uid: number;
private _name: string;
private _timestamp: Date;
private _keybindInhibitor?: KeybindInhibitor;
//private _keybindInhibitor?: KeybindInhibitor;
private _abortController: AbortController;
private _result: CommandResult;
constructor(
bash: Bash,
bash: Shell,
uid: number,
name: string,
command: Command,
args: CommandArgs
) {
this._bash = bash;
this._shell = shell;
this._uid = uid;
this._name = name;
this._timestamp = new Date();
this._abortController = new AbortController();
this._result: CommandResult = { exitCode: ExitCode.ERROR, path: this._bash.getCwd() }
if(command._keybinds) {
this._keybindInhibitor = new KeybindInhibitor(command.keybinds)
}
@@ -57,7 +57,11 @@ namespace TermOS {
return this._name
}
public async get Result(): Promise<CommandResult>
public async get Result(): Promise<CommandResult> {
return this._result;
}
private async _Exec(command: Command, shell: Shell, flags: CommandFlag[], args: string[]) {
this._result = Command.
}
}
}
}
+44
View File
@@ -0,0 +1,44 @@
import type { Stack } from '$lib/stores/stack';
import { FileSystem } from '../filesystem/filesystem';
export class Shell {
private readonly _fs: FileSystem;
private _passwd: User[];
private _group: Group[];
private _commands: Command[];
private _userSessions: Stack<User>;
private user: User;
private _process?: Process;
constructor() {
this._fs = new FileSystem();
}
}
export enum ExitCode {
OK = 0,
ERR = 1,
INT = 2
}
export type User = {
username: string;
password: string;
readonly uid: number;
readonly gid: number;
home: string;
accessible: boolean;
history: string;
cwd?: number;
pwd?: number;
};
export type Group = {
groupname: string;
gid: number;
members: number[];
};
+11
View File
@@ -0,0 +1,11 @@
export namespace IO {
//const _io: HTMLElement = document.getElementById('output-wrapper');
export function PrintOutput(): void {}
export function ClearOutput(): void {
console.log('clear');
}
}
export {};
+48 -89
View File
@@ -1,82 +1,60 @@
declare namespace TermOS {
export async function Initialize() {}
import { Shell } from "./shell/shell";
import FileSystem
export declare namespace Shell {
async function _init() {}
export type User = {
username: string;
password: string;
readonly uid: number;
readonly gid: number;
home: string;
accessible: boolean;
history: string;
cwd?: number;
pwd?: number;
};
export async function Initialize() {}
export type Group = {
groupname: string;
gid: number;
members: number[];
};
export const CommandRegistry: Record<string, Command> = {
cd
} as const satisfies Record<string, Command>;
export enum ExitCode {
OK = 0,
ERR = 1,
INT = 2
export declare namespace Terminal {
async function _init() {}
export class KeybindInhibitor {
private readonly _keybinds: Map<KeyBind, () => any>;
constructor(keybinds: Map<KeyBind, () => any>) {
this._keybinds = keybinds;
}
private parseModifierStates(event: KeyboardEvent): Modifier[] | undefined {
const mods: Modifier[] = [];
if (event.altKey) mods.push('Alt');
if (event.ctrlKey) mods.push('Ctrl');
if (event.shiftKey) mods.push('Ctrl');
if (mods.length == 0) return undefined;
return mods;
}
processKeystroke(event: KeyboardEvent) {
const keybind: KeyBind = [
{
key: event.key,
mods: this.parseModifierStates(event)
}
];
const out = this._keybinds.get(keybind);
if (out) out();
}
}
export declare namespace Terminal {
async function _init() {}
type Modifier = 'Ctrl' | 'Alt' | 'Shift';
export class KeybindInhibitor {
private readonly _keybinds: Map<KeyBind, () => any>;
type KeyStroke = {
key: string;
mods?: Modifier[];
};
constructor(keybinds: Map<KeyBind, () => any>) {
this._keybinds = keybinds;
}
private parseModifierStates(event: KeyboardEvent): Modifier[] | undefined {
const mods: Modifier[] = [];
if (event.altKey) mods.push('Alt');
if (event.ctrlKey) mods.push('Ctrl');
if (event.shiftKey) mods.push('Ctrl');
if (mods.length == 0) return undefined;
return mods;
}
processKeystroke(event: KeyboardEvent) {
const keybind: KeyBind = [
{
key: event.key,
mods: this.parseModifierStates(event)
}
];
const out = this._keybinds.get(keybind);
if (out) out();
}
}
type Modifier = 'Ctrl' | 'Alt' | 'Shift';
type KeyStroke = {
key: string;
mods?: Modifier[];
};
export type KeyBind = [KeyStroke] | [KeyStroke, KeyStroke];
}
export declare namespace FileSystem {}
export type KeyBind = [KeyStroke] | [KeyStroke, KeyStroke];
}
export declare namespace FileSystem {}
/*
namespace TermOS {
export async function Initialize() {}
@@ -230,22 +208,7 @@ namespace TermOS {
}
}
type TreeNode = {
inode: number;
parent: number;
name: string;
type: Type;
size: number; //Size in Bytes
children: number[];
content: string; // GUID of the cache file that contains the file contents.
link: number; // Links
permission: NodePermission;
owner: number;
group: number;
timestamps: TimeStamps;
interactible: boolean;
func: any;
}
enum Type {
Directory = 16384,
@@ -259,11 +222,7 @@ namespace TermOS {
other: Permission;
}
type TimeStamps = {
modified: Date;
changed: Date;
accessed: Date;
}
// TODO: Finish this
enum ExitCode {
View File
View File
View File
+22 -20
View File
@@ -1,11 +1,9 @@
<script lang="ts">
import { Terminal, type PrintData } from '$lib/stores/terminal/terminal';
import { onMount } from 'svelte';
import Input from './terminal/Input.svelte';
import { initTerminal, isInitializing } from '$lib/stores/terminal/init.svelte';
import { clear, print } from '$lib/stores/terminal/stdio/io';
import type { User } from '$lib/stores/bash/etc/userData';
import { ExitCode } from '$lib/stores/bash/metadata';
import { initTerminal } from '$lib/stores/terminal/init.svelte';
import { clear, print } from '$lib/stores/terminal/stdio/io';
import { Terminal, type PrintData } from '$lib/stores/terminal/terminal';
import Input from './terminal/Input.svelte';
const clearTerminal = (): void => clear();
@@ -13,7 +11,7 @@
export async function init(username: string, password: string) {
try {
terminal = await initTerminal({username, password}, callbackInit, 'en_US');
terminal = await initTerminal({ username, password }, callbackInit, 'en_US');
updateTerminal();
} catch (error) {
console.error('terminal init failed', error);
@@ -30,23 +28,25 @@
function getWidth() {
const e = document.getElementById('cout');
if(!e){
if (!e) {
throw new Error('cant get width of the teminal element. Its null');
}
//gets an int from padding property value (which is a string) by cutting last 2 letters "px" and parsing to int
const padding: number = parseInt(window.getComputedStyle(e, null).getPropertyValue('padding').slice(0, -2));
return e.clientWidth - (padding * 2);
const padding: number = parseInt(
window.getComputedStyle(e, null).getPropertyValue('padding').slice(0, -2)
);
return e.clientWidth - padding * 2;
}
function getFontSize() {
const e = document.getElementById('cout');
if(!e) {
if (!e) {
throw new Error('cant get font size of the terminal element. its null');
}
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d')!;
ctx.font = `${window.getComputedStyle(e, null).getPropertyValue('font-size')} 'JetBrains Mono', monospace;`;
const ctx = canvas.getContext('2d')!;
ctx.font = `${window.getComputedStyle(e, null).getPropertyValue('font-size')} 'JetBrains Mono', monospace;`;
return ctx.measureText('M').width;
}
@@ -55,7 +55,7 @@
terminalKeyInhibitor.processKeystroke(event);
const processKeyInhibitor = terminal.getProcessKeyInhibitor();
if(processKeyInhibitor != ExitCode.ERROR) {
if (processKeyInhibitor != ExitCode.ERROR) {
processKeyInhibitor.processKeystroke(event);
}
@@ -81,7 +81,7 @@
}
const elem = document.getElementById('cout');
if(!elem){
if (!elem) {
throw new Error('cant scroll to bottom, element is null');
}
@@ -111,11 +111,13 @@
//let isProcessActive = $state(false);
let inputValue = $state<string>('');
</script>
<label for="input" onkeydowncapture={(event) => inputHandler(event)} class="w-11/12">
<div id="terminal" class=" transition-discrete terminal-window shadow-() h-full w-full rounded-md shadow-bg">
<div
id="terminal"
class=" terminal-window shadow-() h-full w-full rounded-md shadow-bg transition-discrete"
>
<div
class="terminal-bar flex h-9 w-full flex-row items-center rounded-t-md bg-bg-dark text-center font-terminal text-sm font-bold text-primary-dark light:bg-bg-dark-light light:text-primary-light"
>
@@ -124,7 +126,7 @@
<button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button>
<button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button>
</div>
<div class=" flex mr-2 grow">
<div class=" mr-2 flex grow">
<h5>{username}</h5>
<!-- prettier-ignore -->
<h5 class=" mr-2">@terminal: </h5>
@@ -153,8 +155,8 @@
to {
opacity: 1;
display: block;
}
}
}
}
.dots-wrapper {
& > button {
border: none;