From 619de5e1f836e1da85877a15d6b52a97ba39c594 Mon Sep 17 00:00:00 2001 From: gornodox Date: Wed, 13 May 2026 17:56:19 +0200 Subject: [PATCH] WIP: new abstraction layer, file system now a singleton, shell should be too --- src/app.d.ts | 1 + src/lib/stores/bash/bash.ts | 88 ++--- src/lib/stores/bash/commandRegistry.ts | 44 +-- src/lib/stores/bash/commands/cd.ts | 1 + src/lib/stores/bash/metadata.ts | 6 - src/lib/stores/bash/process.ts | 126 ++++--- src/lib/stores/terminal/init.svelte.ts | 13 +- src/lib/stores/terminal/stdio/io.ts | 4 +- src/lib/stores/terminal/terminal.ts | 2 + src/lib/termos/bin/cd.ts | 3 + src/lib/termos/filesystem/filesystem.ts | 322 ++++++++++++++++++ src/lib/termos/filesystem/virtualfs.d.ts | 1 - src/lib/termos/shell/bash.d.ts | 7 - src/lib/termos/shell/command.d.ts | 27 -- src/lib/termos/shell/command.ts | 23 ++ .../termos/shell/{process.d.ts => process.ts} | 28 +- src/lib/termos/shell/shell.ts | 44 +++ src/lib/termos/terminal/io.ts | 11 + src/lib/termos/terminal/keybind_inhibitor.ts | 0 src/lib/termos/termos.d.ts | 137 +++----- src/lib/termos/util/hash.ts | 0 src/lib/termos/util/sort.ts | 0 src/lib/termos/util/stack.ts | 0 src/modules/Terminal.svelte | 42 +-- 24 files changed, 628 insertions(+), 302 deletions(-) create mode 100644 src/lib/termos/bin/cd.ts create mode 100644 src/lib/termos/filesystem/filesystem.ts delete mode 100644 src/lib/termos/filesystem/virtualfs.d.ts delete mode 100644 src/lib/termos/shell/bash.d.ts delete mode 100644 src/lib/termos/shell/command.d.ts create mode 100644 src/lib/termos/shell/command.ts rename src/lib/termos/shell/{process.d.ts => process.ts} (67%) create mode 100644 src/lib/termos/shell/shell.ts create mode 100644 src/lib/termos/terminal/io.ts create mode 100644 src/lib/termos/terminal/keybind_inhibitor.ts create mode 100644 src/lib/termos/util/hash.ts create mode 100644 src/lib/termos/util/sort.ts create mode 100644 src/lib/termos/util/stack.ts diff --git a/src/app.d.ts b/src/app.d.ts index da08e6d..a449932 100755 --- a/src/app.d.ts +++ b/src/app.d.ts @@ -8,6 +8,7 @@ declare global { // interface PageState {} // interface Platform {} } + namespace TermOS {} } export {}; diff --git a/src/lib/stores/bash/bash.ts b/src/lib/stores/bash/bash.ts index aa586fd..dce8e01 100755 --- a/src/lib/stores/bash/bash.ts +++ b/src/lib/stores/bash/bash.ts @@ -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; - 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; - + private _userInstances: Stack; - + 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 { 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; } diff --git a/src/lib/stores/bash/commandRegistry.ts b/src/lib/stores/bash/commandRegistry.ts index 5970155..1ba34e8 100644 --- a/src/lib/stores/bash/commandRegistry.ts +++ b/src/lib/stores/bash/commandRegistry.ts @@ -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 any>; - flags: string[]; - help: string; - root: boolean; + method: (this: Bash, args: CommandArgs) => Result; + keybinds?: Map 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; + +WebG. /* //export const commands { return: { method: this.cmd_return, @@ -150,4 +150,4 @@ export const COMMANDS = { flags: [], help: "", } -} */ \ No newline at end of file +} */ diff --git a/src/lib/stores/bash/commands/cd.ts b/src/lib/stores/bash/commands/cd.ts index 712aed5..6fc173d 100755 --- a/src/lib/stores/bash/commands/cd.ts +++ b/src/lib/stores/bash/commands/cd.ts @@ -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; } diff --git a/src/lib/stores/bash/metadata.ts b/src/lib/stores/bash/metadata.ts index 32a0d10..3cc6406 100644 --- a/src/lib/stores/bash/metadata.ts +++ b/src/lib/stores/bash/metadata.ts @@ -9,9 +9,3 @@ export enum ExitCode { SUCCESS = 0, ERROR = 1 } - -export type Permission = { - r: boolean; - w: boolean; - x: boolean; -}; \ No newline at end of file diff --git a/src/lib/stores/bash/process.ts b/src/lib/stores/bash/process.ts index eb9b360..1a05227 100644 --- a/src/lib/stores/bash/process.ts +++ b/src/lib/stores/bash/process.ts @@ -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 { - return this._result; - } - - private async _Run(command: ICommand, bashInstance: Bash, args: CommandArgs) { - this._result = command.method.call( - bashInstance, args); - } - -} \ No newline at end of file + public getUid(): number { + return this._uid; + } + + public getInitTime(): Date { + return this._initTimestamp; + } + + public getName(): string { + return this._name; + } + + public async getResult(): Promise { + return this._result; + } + + private async _Run(command: ICommand, bashInstance: Bash, args: CommandArgs) { + this._result = command.method.call(bashInstance, args); + } +} diff --git a/src/lib/stores/terminal/init.svelte.ts b/src/lib/stores/terminal/init.svelte.ts index 444bbdf..42dbb8b 100755 --- a/src/lib/stores/terminal/init.svelte.ts +++ b/src/lib/stores/terminal/init.svelte.ts @@ -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 { +function jsonToNodeTable(data: JSON): Map { const FsTable: Map = new Map(); const entryList = Object.entries(data); @@ -24,7 +23,7 @@ function jsonToNodeTable(data: any): Map { 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 { return FsTable; } -async function fetchFsJson(sig: string): Promise { +async function fetchFsJson(sig: string): Promise { 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 { return data; } -TermOS.Shell.Bash; - export async function initTerminal( user: { username: string; password: string }, callbackInit: PageCallbacks, localeId: string -): Promise { +): Promise { try { const sig = await fetchFsSignature('/src/lib/assets/fs/signature'); - const fsJson = await fetchFsJson(sig); + const fsJson: JSON = await fetchFsJson(sig); const fs: Map = jsonToNodeTable(fsJson); /* const locale: ILocale = { id: localeId, diff --git a/src/lib/stores/terminal/stdio/io.ts b/src/lib/stores/terminal/stdio/io.ts index d0ad7c0..dc24c34 100755 --- a/src/lib/stores/terminal/stdio/io.ts +++ b/src/lib/stores/terminal/stdio/io.ts @@ -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, {}); } } diff --git a/src/lib/stores/terminal/terminal.ts b/src/lib/stores/terminal/terminal.ts index 286e4be..f120d82 100755 --- a/src/lib/stores/terminal/terminal.ts +++ b/src/lib/stores/terminal/terminal.ts @@ -33,6 +33,8 @@ export type PageCallbacks = { getFontSize: () => number; }; +TermOS.Shell; + export class Terminal { private _bash: Bash; private _callbacks: Partial = {}; diff --git a/src/lib/termos/bin/cd.ts b/src/lib/termos/bin/cd.ts new file mode 100644 index 0000000..2f1e9ba --- /dev/null +++ b/src/lib/termos/bin/cd.ts @@ -0,0 +1,3 @@ +import { Command } from '../shell/command'; + +export class cd extends Command {} diff --git a/src/lib/termos/filesystem/filesystem.ts b/src/lib/termos/filesystem/filesystem.ts new file mode 100644 index 0000000..8ccb572 --- /dev/null +++ b/src/lib/termos/filesystem/filesystem.ts @@ -0,0 +1,322 @@ +import type { User } from '../shell/shell'; + +export class FileSystem { + static #instance: FileSystem; + private _fs: Map; + 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 { + 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 { + 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 { + 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 { + const FsTable: Map = new Map(); + 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; +}; diff --git a/src/lib/termos/filesystem/virtualfs.d.ts b/src/lib/termos/filesystem/virtualfs.d.ts deleted file mode 100644 index 9b2afc7..0000000 --- a/src/lib/termos/filesystem/virtualfs.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare namespace FileSystem {} diff --git a/src/lib/termos/shell/bash.d.ts b/src/lib/termos/shell/bash.d.ts deleted file mode 100644 index 45d9763..0000000 --- a/src/lib/termos/shell/bash.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -namespace TermOS { - export namespace Shell { - export class Bash { - private readonly _fs: TermOS. - } - } -} diff --git a/src/lib/termos/shell/command.d.ts b/src/lib/termos/shell/command.d.ts deleted file mode 100644 index 42cdae2..0000000 --- a/src/lib/termos/shell/command.d.ts +++ /dev/null @@ -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 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; - }; - } -} diff --git a/src/lib/termos/shell/command.ts b/src/lib/termos/shell/command.ts new file mode 100644 index 0000000..c55af0f --- /dev/null +++ b/src/lib/termos/shell/command.ts @@ -0,0 +1,23 @@ +export abstract class Command { + public abstract readonly _flags: CommandFlag[]; + public abstract readonly _root: boolean; + //public abstract readonly _keybinds?: Map 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; +}; diff --git a/src/lib/termos/shell/process.d.ts b/src/lib/termos/shell/process.ts similarity index 67% rename from src/lib/termos/shell/process.d.ts rename to src/lib/termos/shell/process.ts index 35565f5..cf5c6ae 100644 --- a/src/lib/termos/shell/process.d.ts +++ b/src/lib/termos/shell/process.ts @@ -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 + public async get Result(): Promise { + return this._result; + } + + private async _Exec(command: Command, shell: Shell, flags: CommandFlag[], args: string[]) { + this._result = Command. + } } - } -} diff --git a/src/lib/termos/shell/shell.ts b/src/lib/termos/shell/shell.ts new file mode 100644 index 0000000..acea91c --- /dev/null +++ b/src/lib/termos/shell/shell.ts @@ -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; + + 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[]; +}; diff --git a/src/lib/termos/terminal/io.ts b/src/lib/termos/terminal/io.ts new file mode 100644 index 0000000..c07ba52 --- /dev/null +++ b/src/lib/termos/terminal/io.ts @@ -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 {}; diff --git a/src/lib/termos/terminal/keybind_inhibitor.ts b/src/lib/termos/terminal/keybind_inhibitor.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/lib/termos/termos.d.ts b/src/lib/termos/termos.d.ts index 9f9a277..792d4dd 100644 --- a/src/lib/termos/termos.d.ts +++ b/src/lib/termos/termos.d.ts @@ -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 = { + cd +} as const satisfies Record; - export enum ExitCode { - OK = 0, - ERR = 1, - INT = 2 +export declare namespace Terminal { + async function _init() {} + + export class KeybindInhibitor { + private readonly _keybinds: Map any>; + + constructor(keybinds: Map 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 any>; + type KeyStroke = { + key: string; + mods?: Modifier[]; + }; - constructor(keybinds: Map 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 { diff --git a/src/lib/termos/util/hash.ts b/src/lib/termos/util/hash.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/lib/termos/util/sort.ts b/src/lib/termos/util/sort.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/lib/termos/util/stack.ts b/src/lib/termos/util/stack.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/modules/Terminal.svelte b/src/modules/Terminal.svelte index 2118205..5235cf6 100755 --- a/src/modules/Terminal.svelte +++ b/src/modules/Terminal.svelte @@ -1,11 +1,9 @@