49 Commits
Author SHA1 Message Date
ChaosMaker d825299e26 - Cleaned up old tests
- Changed `node:buffer` and `node:streams` imports to native `WebWorkers` imports;
- Fixed tests that used old `toPtr` and `fromPtr` functions to use the new NodePointer class methods
- Exposed pointer resolution helper functions to the consumer
2026-11-20 12:22:23 +01:00
ChaosMaker 2cf84ccd2f Exported Shell as a type in the index 2026-11-20 11:00:14 +01:00
ChaosMaker 204d713f91 - Fixed a bug in serializer that didnt account for parsed inodes to the inode index on the vdisk
- Fixed the touch command (for now only creates files)
- Fixed a minor bug in ls where it wouldnt return the correct result when a path provided in the args wouldnt resolve
2026-11-20 10:35:44 +01:00
ChaosMaker af6a9c8bda Update README.md 2026-11-17 22:59:04 +01:00
ChaosMaker 7310ae9671 Update README.md 2026-11-17 22:56:31 +01:00
ChaosMaker 031f8f7726 Merge branch 'master' of ssh://git.gornodox.dev:2222/ChaosMaker/termos
Merge new filesystem to master
2026-11-17 20:49:09 +01:00
ChaosMaker ed8c27677c - package.json tweaks
- `README.md` edits
2026-11-17 20:40:58 +01:00
ChaosMaker f4a74f67cf - Prepare for build and release 2026-11-17 20:03:19 +01:00
ChaosMaker 2f25e44681 - Fixed output formatting error in ls.ts
- Added an exported `Termos` object entry point
- Defined a basic config for the entry point
- Wrote a self contained initialization function for parsin the config into a returned `Shell` instance
- Adjusted `dev.ts` to use the said entry point
2026-11-16 12:16:49 +01:00
ChaosMaker d4ec6b0c49 - Added a safety check in serializer.ts to look for fields containing undefined
- Updated the fs json to contain the new result from the fixed serializer that parses the link counts
- Updated ls to use proper link counts and sizes in the long format (apart from dir sizes which remain at arbitrary 4096)
2026-11-14 10:49:51 +01:00
ChaosMaker de1ce64226 - Fixed cat command
- Moved device config initialization to `serializer.ts`
- Minor bugfixes
- Added `read()` to `filesystem.ts`
2026-11-13 04:15:28 +01:00
ChaosMaker d5566aa494 - Fixed a buged while condition inside path_resolver.ts
- Fixed `NodePointer` class to work with by reference comparison (maps use that) so the reverse index can look up entries properly`. `NodePointer` now caches every pointer created so logic can use reference comparison
2026-11-11 05:21:03 +01:00
ChaosMaker cb9cd7a67a new tree json pasted 2026-11-10 17:15:18 +01:00
ChaosMaker b161e42b3f - Fixed ls (mostly)
- Fixed sorting
- Many minor changes

(need to fix the json serializer to include size in its results *the C++ one*)
2026-11-10 16:19:10 +01:00
ChaosMaker 492f1ba372 - Fixed sort.ts
- Fixed `cd`
2026-11-10 13:13:38 +01:00
ChaosMaker 00200b4c75 - Fixed all of path_resolver.ts functions
- `resolveInode` functions now `resolvePointer`
- Fixed all resolve pointer -> path functions
2026-11-10 12:02:21 +01:00
ChaosMaker 584e594726 - Downward tree traversal fixed (untested - might have bugs)
- Moved filesystem mockups to a separate file
- Tree visualizer now has support for symlinks and mountpoints
2026-11-10 09:08:15 +01:00
ChaosMaker 4fa284de13 - Fixed resolvePath
- Added symlink resolution
- Added mount resolution
- Fixed filesystem not awaiting for disks to be mounted
(now `FileSystem.init()` needs to be called with `await`)
- Removed old test fixture files
- Added a feature-full `resolvePath`test suite

*all tests passing green*
2026-11-10 08:04:57 +01:00
ChaosMaker dd804f6f14 Virtual FileSystem fixed - (Needs unit testing)! 2026-11-09 05:10:44 +01:00
ChaosMaker 832fc6c759 - filesystem move node method fixed
- upTraversalTree fixed

- who tf knows what else
2026-10-30 06:13:34 +01:00
ChaosMaker 2a6e6c57c3 - filesystem fixes
- tree traversal up fixes
2026-09-21 04:44:10 +02:00
ChaosMaker f2b5f86a6c Try initializing FileSystem now
- vdisk finished
- vdiskmanager finished
- devices can properly initialize and hold aswell as retireve data
- added mock synchronous store classes for testing
2026-09-20 12:40:38 +02:00
ChaosMaker 933b1fc5e8 - vdisk done?
- vdiskman done?
2026-09-19 06:27:12 +02:00
ChaosMaker 849e0e61f5 a lot of mess, keep working on VDisk for now. 2026-09-17 10:32:31 +02:00
ChaosMaker d642ee6258 Update README.md 2026-09-12 02:02:30 +02:00
ChaosMaker 9c5bd71a5c - moved index code to dev.ts
- some work i dont know about or dont remember ¯\_(ツ)_/¯
2026-09-11 22:50:08 +02:00
ChaosMaker ec13299e95 some bs work, not finished (reference notes board on email for info) 2026-09-09 10:43:37 +02:00
ChaosMaker e2ade5de29 Bugfixes
- chunking fixed
- bug with recursive ls looping fixed
- bug with empty directories on ls -a failing fixed
2026-09-06 02:48:11 +02:00
ChaosMaker b75e691a0b Bugfixes and improvements
- ls fixed
- fixed a bug where ~ wouldnt resolve properly
- temporarily increased the process chunking treshold, because chunking breaks formatting
- added clear
- added pwd
2026-09-06 00:26:09 +02:00
ChaosMaker 776a93e21b Revert "more things broken for now"
This reverts commit 6cc9727091.
2026-09-03 23:22:17 +02:00
ChaosMaker 6cc9727091 more things broken for now
- shell now uses the path env variable
- commands run based on permission of the bin file
2026-09-03 12:27:32 +02:00
ChaosMaker 2715e5e28e Shell update
- changed shell init code to synchronous with guaranteed returns
- Shell.Instance now a normal method not a getter
2026-09-03 11:45:19 +02:00
ChaosMaker 8a349330b0 - initial changes to data shapes
- ls command needs fixing
2026-09-03 11:15:05 +02:00
ChaosMaker 2e9227f6d8 - cat added
- touch beginnings
- path resolver now returns a -1 on error
- added a command template file for easier copy-pasting
2026-09-01 05:47:23 +02:00
ChaosMaker 8e054a220d - implemented the rest of long-format compatible ls flags
- split path_resolver functions to 3 separate functions that prioritize different points of relativity
- added a `convertToUnit`function to convert from bytes to higher units of messurement
- revert change: excluded inode 0 from tree traversal results
2026-08-30 17:35:20 +02:00
ChaosMaker 4776232377 - refactored resolvePath to have parity with resolveInode and take in ShellState instead of FileSystem and cwd
- reverted change "removed inode 0 from tree traversal results"
2026-08-30 09:58:23 +02:00
ChaosMaker d0f8376244 - moved uint8array concat and split functions to their own files
- fixed an error in the cd command as a result of a previous improvement
2026-08-30 08:38:05 +02:00
ChaosMaker f1b69bb282 Update README.md 2026-08-29 21:35:23 +02:00
ChaosMaker 1b3314ab87 readme edit 2026-08-29 21:20:11 +02:00
ChaosMaker 96e15a87f2 - readme update
- rid of AI generated task list (ts is so ass)
- added an npm script for running the project
2026-08-29 21:14:46 +02:00
ChaosMaker 55b5d3a873 - cleaned up old console logs that trashed the terminal
- adjusted the eslint config to include the `__` pattern for function arguments aswell
2026-08-28 17:03:12 +02:00
ChaosMaker 1ee2a2fe7a - Old tests fixed
- Added a static Fixuture class for test mockups
2026-08-28 16:52:59 +02:00
ChaosMaker 310218663d - fixed a bug in *sort.ts* where passed number arrays wouldnt get properly parsed into TreeNode arrays
- excluded inode 0 from tree traversal results
2026-08-25 06:54:42 +02:00
ChaosMaker 20718604e4 - fixed a bug in dnTaverseTree where children would get pushed into the result in reverse order
- added an inode display to the `printTree` algorithm

- removed a redundant type in *`signal.ts`*
- improved `resolveInode` to now take `ShellState` instead of `FileSystem` and added an optional `abs` *`boolean`* argument to determine if the retuned path should be normalized or absolute

- implemented a builtin `TreeNode` quicksort function
- changed the `TreeNodeType` to a numeric enum
- added a standalone `Posix` class that holds a const with character weights compliant with posix
2026-08-25 06:34:23 +02:00
ChaosMaker dad18cd4cc bigass changes
- ls beginnings,
- added groups to shellstate
- made buffers optional in result factory functions,
- made an enum signal map,
- fixed a minor bug in path resolver that didnt output the '/' if     the inode was at root (inode 0) from the moment it was called

- added code that attaches the shell to the built-in IDE terminal

--

tests need fixing, new code needs testing
2026-08-24 10:30:04 +02:00
ChaosMaker 48aac3c883 testing headless-mode user input 2026-08-23 10:19:54 +02:00
ChaosMaker 268729bb62 WRITE UNIT TESTS!!!
first async command working, no unit tests done AGAING
2026-08-23 06:39:37 +02:00
ChaosMaker e313aa5b9d . 2026-08-20 09:44:19 +02:00
ChaosMaker 16a1805f25 fixed naming convention and text casing to use CamelCase on class fields. Process manager implemented, not tested, needs integration with current shell implementation 2026-08-20 09:44:03 +02:00
75 changed files with 8425 additions and 5494 deletions
+1
View File
@@ -0,0 +1 @@
{}
+1
View File
@@ -0,0 +1 @@
{}
+33
View File
@@ -0,0 +1,33 @@
{
"file-explorer": true,
"global-search": true,
"switcher": true,
"graph": true,
"backlink": true,
"canvas": true,
"outgoing-link": true,
"tag-pane": true,
"footnotes": false,
"properties": true,
"page-preview": true,
"daily-notes": true,
"templates": true,
"note-composer": true,
"command-palette": true,
"slash-command": false,
"editor-status": true,
"bookmarks": true,
"markdown-importer": false,
"zk-prefixer": false,
"random-note": false,
"outline": true,
"word-count": true,
"slides": false,
"audio-recorder": false,
"workspaces": false,
"file-recovery": true,
"publish": false,
"sync": true,
"bases": true,
"webviewer": false
}
+196
View File
@@ -0,0 +1,196 @@
{
"main": {
"id": "89ee32072433406f",
"type": "split",
"children": [
{
"id": "21d78959e637e988",
"type": "tabs",
"children": [
{
"id": "1db1d6b317bc05ae",
"type": "leaf",
"state": {
"type": "markdown",
"state": {
"file": "README.md",
"mode": "source",
"source": false
},
"icon": "lucide-file",
"title": "README"
}
}
]
}
],
"direction": "vertical"
},
"left": {
"id": "6703a701fa3161c8",
"type": "split",
"children": [
{
"id": "59a1957ef4b6aa34",
"type": "tabs",
"children": [
{
"id": "af4cfba92021d1c8",
"type": "leaf",
"state": {
"type": "file-explorer",
"state": {
"sortOrder": "alphabetical",
"autoReveal": false,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-folder-closed",
"title": "Files"
}
},
{
"id": "195ed2a7004c5679",
"type": "leaf",
"state": {
"type": "search",
"state": {
"query": "",
"matchingCase": false,
"explainSearch": false,
"collapseAll": false,
"extraContext": false,
"sortOrder": "alphabetical"
},
"icon": "lucide-search",
"title": "Search"
}
},
{
"id": "e0b0a93bee04adf7",
"type": "leaf",
"state": {
"type": "bookmarks",
"state": {
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-bookmark",
"title": "Bookmarks"
}
}
]
}
],
"direction": "horizontal",
"width": 300
},
"right": {
"id": "cdb5787bc7b074a1",
"type": "split",
"children": [
{
"id": "4f7b084c90edcafa",
"type": "tabs",
"children": [
{
"id": "87c20e5388b56742",
"type": "leaf",
"state": {
"type": "backlink",
"state": {
"file": "todo.md",
"collapseAll": false,
"extraContext": false,
"sortOrder": "alphabetical",
"showSearch": false,
"searchQuery": "",
"backlinkCollapsed": false,
"unlinkedCollapsed": true
},
"icon": "links-coming-in",
"title": "Backlinks"
}
},
{
"id": "d06f3a18f218bb85",
"type": "leaf",
"state": {
"type": "outgoing-link",
"state": {
"file": "todo.md",
"linksCollapsed": false,
"unlinkedCollapsed": true
},
"icon": "links-going-out",
"title": "Outgoing links"
}
},
{
"id": "5e8256b0c8cb4527",
"type": "leaf",
"state": {
"type": "tag",
"state": {
"sortOrder": "frequency",
"useHierarchy": true,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-tags",
"title": "Tags"
}
},
{
"id": "c4c977be0ce05b9d",
"type": "leaf",
"state": {
"type": "all-properties",
"state": {
"sortOrder": "frequency",
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-archive",
"title": "All properties"
}
},
{
"id": "bf5df26d52eb2371",
"type": "leaf",
"state": {
"type": "outline",
"state": {
"file": "todo.md",
"followCursor": false,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-list",
"title": "Outline"
}
}
]
}
],
"direction": "horizontal",
"width": 300,
"collapsed": true
},
"left-ribbon": {
"hiddenItems": {
"switcher:Open quick switcher": false,
"graph:Open graph view": false,
"canvas:Create new canvas": false,
"daily-notes:Open today's daily note": false,
"templates:Insert template": false,
"command-palette:Open command palette": false,
"bases:Create new base": false
}
},
"active": "1db1d6b317bc05ae",
"lastOpenFiles": [
"src/util/posix.ts",
"src/core/util/sort.ts"
]
}
+1 -1
View File
@@ -19,7 +19,7 @@
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/tsx",
"runtimeArgs": ["src/index.ts"],
"runtimeArgs": ["src/dev.ts"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"skipFiles": ["<node_internals>/**"]
+4
View File
@@ -0,0 +1,4 @@
{
"typescript.validate.enable": true,
"typescript.tsserver.experimental.enableProjectDiagnostics": true
}
+63 -2
View File
@@ -1,3 +1,64 @@
# termos
# Termos
terminal emulation library that bases its functionality on the bash shell
This library allows running a fully contained unix-like operating system written in pure typescript.
It supports all the basic operations like saving and reading files, creating new files and folders.
It has support for users and permissions and can handle multiple user sessions at the same time.
It doesnt implement a website friendly interface on its own. Thats one of the desing choices in this project, to make it as versatile as possible. But it shares a easy to use interface that you can plug into your frontend code to interact with it properly.
> [!NOTE]
> Right now the project is still in alpha and this is just a small portion of whats to come that serves for demonstration purposes. The code and design will change in the future so most of this is not set in stone
## Prerequisites
- [Node.js](https://nodejs.org/) installed (version 22 or higher)
- [pnpm](https://pnpm.io/) installed (version 12 or higher)
## Installation
> [!NOTE]
> If youre using Windows or MacOS as your operating system then the installation process might be different.
> Refer to [this website][ref1] on how to install nodejs on your operating system
> and [this website][ref2] for pnpm accordingly.
[ref1]: https://nodejs.org/en/download
[ref2]: https://pnpm.io/installation
```bash
pnpm add "https://git.gornodox.dev/ChaosMaker/termos/releases/download/0.1.0/termos-0.1.0.tgz"
```
## Minimal usecase
```typescript
import { Termos } from "termos";
const shell = await Termos.getShell({
filesystem: {
// an example json representation of the filesystem
json: `{"dev": [{"id":0,"tree": {"atime": 1788458541,"children": [{"atime": 1794947961,"children": [],"content": [87,101,108,99,111,109,101,32,116,111,32,84,101,114,109,111,115,33,32,240,144,148,140,213,158,46,32,46,213,158,240,144,166,175,10],"ctime": 1794948078,"group": 0,"inode": 1,"link_count": 1,"mode": 420,"mtime": 1794948078,"name": "hello_world.txt","owner": 0,"parent": 0,"size": 35,"type": "regular"}],"content": null,"ctime": 1794947961,"group": 0,"inode": 0,"link_count": 2,"mode": 493,"mtime": 1794947961,"name": "root","owner": 0,"parent": 0,"size": 29,"type": "directory"}}]}`,
},
users: [{ username: "root", groups: ["root"], home: "/" }],
groups: ["root"],
general: { user: "root" },
});
// Subscribtion needed to recive command results and print out error messages
shell.on("result", payload => {
if (payload.result.type === "error") {
console.log(payload.result.error.message + "\n");
}
process.stdout.write("\n" + "Hello~\n> ");
});
// Subscribtion needed to recieve stdout buffer contents from shell
shell.on("stdout", payload => {
const decoded = new TextDecoder().decode(payload.data);
process.stdout.write(decoded);
});
// Takes in a string and executes it as a command
shell.execute("ls -l");
```
For more information, reference the [wiki]()
+1 -1
View File
@@ -11,7 +11,7 @@ export default [
...functional.configs.recommended,
rules: {
"functional/no-mixed-types": "off",
"@typescript-eslint/no-unused-vars": ["error", { varsIgnorePattern: "^__" }],
"@typescript-eslint/no-unused-vars": ["error", { varsIgnorePattern: "^__", argsIgnorePattern: "^__" }],
"@typescript-eslint/no-restricted-imports": [
"error",
{
-3287
View File
File diff suppressed because it is too large Load Diff
+32 -7
View File
@@ -1,22 +1,42 @@
{
"name": "termos",
"version": "1.0.0",
"description": "terminal emulation library that bases its functionality on the bash shell",
"main": "index.ts",
"version": "0.1.0",
"description": "Emulation library for a unix-like operating-system written in pure typescript",
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"default": "./dist/index.js"
}
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"test": "eslint . && vitest"
"test": "eslint . && vitest",
"dev": "pnpx tsx src/dev.ts",
"build": "tsup src/index.ts --format esm --dts --clean"
},
"repository": {
"type": "git",
"url": "ssh://git@git.gornodox.dev:2222/ChaosMaker/termos.git"
},
"devEngines": {
"packageManager": {
"name": "pnpm",
"version": "12^",
"onFail": "warn"
}
},
"keywords": [],
"author": "gornodox",
"license": "ISC",
"type": "module",
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/node": "^26.1.0",
"@types/node": "^26.2.0",
"eslint": "^10.6.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-functional": "^10.0.0",
@@ -27,10 +47,15 @@
"vite-tsconfig-paths": "^6.1.1",
"vitest": "^4.1.10"
},
"dependencies": {
"zod": "^4.4.3"
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
},
"allowScripts": {
"esbuild@0.28.1": true
},
"dependencies": {
"tsup": "^9.0.0"
}
}
+2699
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
allowBuilds:
esbuild: true
+18 -9
View File
@@ -1,11 +1,20 @@
export interface TermosConfig {
serverAddress: string;
dbName: string;
idbName: string;
}
export const defaultConfig: TermosConfig = {
serverAddress: "",
dbName: "termos",
idbName: "cache",
groups: string[];
users: {
username: string;
groups: string[];
home: string;
}[];
general: {
user: string;
serverAddress?: string;
dbName?: string;
idbName?: string;
};
filesystem: {
json: string;
maxNameLength?: number;
maxPathLength?: number;
maxSymlinkDepth?: number;
};
}
+1 -6
View File
@@ -3,12 +3,7 @@ import type { Result } from "./result";
import type { ShellState } from "./shell_state";
import type { ShellError } from "./util/errors";
export type CommandFn = (
io: CommandIO,
state: ShellState,
flags: string[],
args: string[],
) => Promise<CommandOutput<ShellError>>;
export type CommandFn = (io: CommandIO, state: ShellState, args: string[]) => Promise<CommandOutput<ShellError>>;
export interface CommandDescriptor {
fn: CommandFn;
+12
View File
@@ -1,11 +1,23 @@
import type { CommandDescriptor } from "./command";
import { descriptor as cat } from "./commands/cat";
import { descriptor as cd } from "./commands/cd";
import { descriptor as clear } from "./commands/clear";
import { descriptor as echo } from "./commands/echo";
import { descriptor as ls } from "./commands/ls";
import { descriptor as pwd } from "./commands/pwd";
import { descriptor as testasync } from "./commands/testasync";
import { descriptor as touch } from "./commands/touch";
const reg = new Map<string, CommandDescriptor>();
//reg.set(descriptor.name, descriptor <- imported const from command implementation file);
reg.set(echo.name, echo);
reg.set(cd.name, cd);
reg.set(testasync.name, testasync);
reg.set(ls.name, ls);
reg.set(cat.name, cat);
reg.set(pwd.name, pwd);
reg.set(clear.name, clear);
reg.set(touch.name, touch);
Object.freeze(reg);
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
+21
View File
@@ -0,0 +1,21 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
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 = "";
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
state: state,
result,
};
}
export const descriptor: CommandDescriptor = {
fn: main,
name: COMMAND_NAME,
};
+76
View File
@@ -0,0 +1,76 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import type { FileSystemCorruptionError } from "@core/filesystem/errors";
import { type NodePointer } from "@core/filesystem/node";
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state";
import type { PathResolutionError, PermissionDeniedError, ShellError } from "@core/util/errors";
import { resolvePath } from "@core/util/path_resolver";
export const COMMAND_NAME = "cat";
//Need to implement escape sequences
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
for (const arg of args) {
let ptr: NodePointer;
try {
ptr = resolvePath(state, arg);
} catch (e) {
return {
state,
result: createErrorResult(
"PathResolutionError",
"No such file or directory",
{ path: arg },
COMMAND_NAME,
),
} satisfies CommandOutput<PathResolutionError>;
}
if (!state.filesystem.isFile(ptr)) {
const entries = state.filesystem.getNodeEntries(ptr);
if (!entries) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing. FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
return {
state,
result: createErrorResult(
"PathResolutionError",
`${entries[0]!.name} is a directory`,
{ path: arg },
COMMAND_NAME,
),
} satisfies CommandOutput<PathResolutionError>;
}
const session = getCurrentSession(state);
if (!state.filesystem.canRead(ptr, session.user)) {
return {
state,
result: createErrorResult("PermissionDenied", "Permission denied", { resource: arg }, COMMAND_NAME),
} satisfies CommandOutput<PermissionDeniedError>;
}
const content = await state.filesystem.read(ptr);
io.writeStdout(content);
}
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
state: state,
result,
};
}
export const descriptor: CommandDescriptor = {
fn: main,
name: COMMAND_NAME,
};
+15 -45
View File
@@ -1,5 +1,6 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { FileSystem } from "@core/filesystem/filesystem";
import type { CommandIO } from "@core/command_io";
import type { NodePointer } from "@core/filesystem/node";
import { createErrorResult, createSuccessResult } from "@core/result";
import { getCurrentSession } from "@core/session_manager";
import { ShellState, withCwd } from "@core/shell_state";
@@ -9,12 +10,11 @@ import {
type PermissionDeniedError,
type ShellError,
} from "@core/util/errors";
import { createImmutableBuffer } from "@core/util/immutable_buffer";
import { resolveInode, resolvePath } from "@core/util/path_resolver";
import { resolvePath } from "@core/util/path_resolver";
export const COMMAND_NAME = "cd";
function main(state: ShellState, __flags: string[], args: string[]): CommandOutput<ShellError> {
async function main(__io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
if (args.length > 1) {
return {
state,
@@ -22,84 +22,54 @@ function main(state: ShellState, __flags: string[], args: string[]): CommandOutp
"InvalidArguments",
"The maximum ammount of arguments for this command is 1",
{ expected: "cd <path>", actual: `cd ${args.toString().replace(/[,]/g, " ")}` },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
COMMAND_NAME,
),
} satisfies CommandOutput<InvalidArgumentsError>;
}
let inode: number;
let ptr: NodePointer;
const session = getCurrentSession(state);
if (args[0] === undefined) {
inode = session.user.home;
ptr = session.user.home;
} else if (args[0] === "-") {
inode = session.pwd;
ptr = session.pwd;
} else {
const result = safeResolvePath(state.filesystem, session.cwd, args[0]);
if (result.type === "error") {
try {
ptr = resolvePath(state, args[0]);
} catch (e) {
return {
state,
result: createErrorResult(
"PathResolutionError",
"No such file or directory",
{ path: args[0]! },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
COMMAND_NAME,
),
} satisfies CommandOutput<PathResolutionError>;
}
inode = result.inode;
}
if (state.filesystem.isFile(inode)) {
if (state.filesystem.isFile(ptr)) {
return {
state,
result: createErrorResult(
"PathResolutionError",
"No such file or directory",
{ path: resolveInode(state.filesystem, inode) },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
COMMAND_NAME,
),
result: createErrorResult("PathResolutionError", "Not a directory", { path: args[0]! }, COMMAND_NAME),
} satisfies CommandOutput<PathResolutionError>;
}
if (!state.filesystem.canExecute(inode, session.user)) {
if (!state.filesystem.canExecute(ptr, session.user)) {
return {
state,
result: createErrorResult(
"PermissionDenied",
"Permission denied",
{ resource: args[0]! },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
COMMAND_NAME,
),
result: createErrorResult("PermissionDenied", "Permission denied", { resource: args[0]! }, COMMAND_NAME),
} satisfies CommandOutput<PermissionDeniedError>;
}
const returnState = withCwd(state, inode);
const returnState = withCwd(state, ptr);
return {
state: returnState,
result: createSuccessResult(COMMAND_NAME),
};
function safeResolvePath(
fs: FileSystem,
cwd: number,
path: string,
): { type: "success"; inode: number } | { type: "error" } {
try {
return { type: "success", inode: resolvePath(fs, cwd, path) };
} catch {
return { type: "error" };
}
}
}
export const descriptor: CommandDescriptor = {
+23
View File
@@ -0,0 +1,23 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
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 = "clear";
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
io.writeStdout(new TextEncoder().encode("\x1b[2J\x1b[0;0H"));
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
state: state,
result,
};
}
export const descriptor: CommandDescriptor = {
fn: main,
name: COMMAND_NAME,
};
+6 -12
View File
@@ -1,25 +1,19 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { ResultSuccess } from "@core/result";
import type { CommandIO } from "@core/command_io";
import { createSuccessResult, type ResultSuccess } from "@core/result";
import type { ShellState } from "@core/shell_state";
import type { ShellError } from "@core/util/errors";
import { createImmutableBuffer } from "@core/util/immutable_buffer";
export const COMMAND_NAME = "echo";
//Need to implement escape sequences
function main(state: ShellState, flags: string[], args: string[]): CommandOutput<ShellError> {
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const joined = args.join(" ");
const encoded = new TextEncoder().encode(joined);
const encoded = new TextEncoder().encode(joined + "\n");
const stdout = createImmutableBuffer(encoded);
io.writeStdout(encoded);
const result: ResultSuccess = {
type: "success",
exitCode: 0,
stdout,
stderr: createImmutableBuffer(new Uint8Array()),
commandName: COMMAND_NAME,
};
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
state: state,
+490
View File
@@ -0,0 +1,490 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { NodePointer, NodeType, type DirectoryNode, type FileNode, type Node } from "@core/filesystem/node";
import { createErrorResult, createSuccessResult } from "@core/result";
import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state";
import type { ShellError } from "@core/util/errors";
import { resolvePath } from "@core/util/path_resolver";
import { SortNodeBy, sortNodes } from "@core/util/sort";
import { concatUint8Arrays } from "@termos/util/concat";
import { convertToUnit } from "@termos/util/format_unit";
export const COMMAND_NAME = "ls";
interface DirEntry {
name: string;
ptr: NodePointer;
}
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const entries: { ptr: NodePointer; path: string }[] = [];
const paths: string[] = [];
const e = new TextEncoder();
let options = {
all: false,
almostAll: false,
long: false,
noSort: false,
noOwner: false,
noGroup: false,
sortBy: SortNodeBy.NAME,
humanReadable: false,
f: false,
x: false,
timestamp: "atime",
reverse: false,
recursive: false,
quoteName: false,
appendIndicator: false,
numericUidGid: false,
literal: false,
inode: false,
si: false,
dereference: false,
fullTime: false,
};
for (let arg of args) {
let val;
if (arg.startsWith("--")) {
arg = arg.slice(2);
if (arg.match(/\w+[=]{1}\w+/g)) {
const flag = arg.split("=")[0];
val = arg.split("=")[1] ?? "";
if (flag === "time" && isValidTimestamp(val)) {
options.timestamp = val;
continue;
}
if (flag === "sort" && isValidSortMethod(val)) {
options.sortBy = val as SortNodeBy;
continue;
}
return {
state,
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
};
}
switch (arg) {
case "all":
options.all = true;
break;
case "almost-all":
options.almostAll = true;
break;
case "no-group":
options.noGroup = true;
break;
case "human-readable":
options.humanReadable = true;
break;
case "reverse":
options.reverse = true;
break;
case "recursive":
options.recursive = true;
break;
case "quote-name":
options.quoteName = true;
break;
case "numeric-uid-gid":
options.numericUidGid = true;
break;
case "inode":
options.inode = true;
break;
case "dereference":
options.dereference = true;
break;
case "literal":
options.literal = true;
break;
case "si":
options.si = true;
options.humanReadable = true;
break;
case "full-time":
options.fullTime = true;
break;
case "help":
// handled separately
break;
default:
return {
state,
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
};
break;
}
} else if (arg.startsWith("-")) {
arg = arg.slice(1);
for (const c of arg) {
switch (c) {
case "l":
options.long = true;
break;
case "a":
options.all = true;
break;
case "A":
options.almostAll = true;
break;
case "c":
options.timestamp = "ctime";
break;
case "U":
options.noSort = true;
break;
case "g":
options.noOwner = true;
options.long = true;
break;
case "G":
options.noGroup = true;
break;
case "h":
options.humanReadable = true;
break;
case "f":
options.f = true;
options.noSort = true;
options.all = true;
break;
case "x":
options.x = true;
break;
case "X":
options.sortBy = SortNodeBy.EXTENSION;
break;
case "u":
options.timestamp = "atime";
break;
case "t":
options.sortBy = options.timestamp as SortNodeBy;
break;
case "S":
options.sortBy = SortNodeBy.SIZE;
break;
case "r":
options.reverse = true;
break;
case "R":
options.recursive = true;
break;
case "Q":
options.quoteName = true;
break;
case "p":
options.appendIndicator = true;
break;
case "o":
options.noGroup = true;
options.long = true;
break;
case "n":
options.numericUidGid = true;
break;
case "N":
options.literal = true;
break;
case "i":
options.inode = true;
break;
case "L":
options.dereference = true;
break;
case "m":
// -m: comma separated list (not in options yet)
break;
default:
return {
state,
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
};
}
}
} else {
paths.push(arg);
}
}
const session = getCurrentSession(state);
if (paths.length === 0) {
entries.push({ ptr: session.cwd, path: "." });
} else {
for (const path of paths) {
let ptr;
try {
ptr = resolvePath(state, path);
} catch {
return {
state,
result: createErrorResult(
"PathResolutionError",
`No such file or directory`,
{ path },
COMMAND_NAME,
),
};
}
entries.push({ ptr, path });
}
}
if (options.long) {
for (const entry of entries) {
listDirEntries(entry);
}
} else {
for (const entry of entries) {
//shortDirEntries(entry);
}
io.writeStdout(e.encode(`No support for short format yet\n`));
}
return {
state,
result: createSuccessResult(COMMAND_NAME),
};
function listDirEntries(entry: { ptr: NodePointer; path: string }): void {
const node = state.filesystem.getNode(entry.ptr) as DirectoryNode;
if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\n`));
io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`));
let children: DirEntry[] = Array.from(node.children.entries()).map(([name, inode]) => ({
name,
ptr: NodePointer.of(entry.ptr.device, inode),
}));
if (!options.noSort) children = sortNodes(state, children, options.reverse, options.sortBy);
if (!options.all && !options.almostAll) {
children = children.filter(c => !c.name.startsWith("."));
}
if (options.long) {
longMode(io, state, children);
if (options.recursive) io.writeStdout(e.encode("\n"));
}
if (options.recursive) {
for (const c of children) {
if (c.name.match(/^[.]{1,2}$/)) continue;
const child = state.filesystem.getNode(c.ptr)!;
if (child.type === NodeType.Directory) {
let path;
if (entry.path === "/") {
path = "/" + c.name;
} else if (entry.path.endsWith("/")) {
path = entry.path + c.name;
} else path = entry.path + "/" + c.name;
listDirEntries({ ptr: c.ptr, path });
}
}
}
}
function longMode(io: CommandIO, state: ShellState, children: DirEntry[]): void {
const e = new TextEncoder();
const buff: Uint8Array[] = [];
const nodes: DirEntry[] = [...children];
// Calculate the string size of the biggerst node in the array;
// Sets 4 length for directories because the arbitrary size is 4096 later in the code
const maxInodeWidth = Math.max(...nodes.map(c => c.ptr.inode.toString().length));
const maxSizeWidth = Math.max(
...nodes.map(c =>
state.filesystem.getNode(c.ptr)!.type === NodeType.File
? (state.filesystem.getNode(c.ptr) as FileNode).size.toString().length
: 4,
),
);
const maxLinksWidth = Math.max(
...nodes.map((c): number => {
const node = state.filesystem.getNode(c.ptr)!;
const o = node.link_count.toString().length;
return o;
}),
);
const namePadding = nodes.every(c => !c.name.includes(" "));
for (const n of nodes) {
const node = state.filesystem.getNode(n.ptr)!;
if (options.inode) {
const inode = node.inode.toString().padStart(maxInodeWidth, " ");
buff.push(e.encode(inode + " "));
}
// Mode
const mode: string = parseMode(node.mode);
switch (node.type) {
case NodeType.Directory:
buff.push(e.encode("d" + mode + " "));
break;
case NodeType.File:
buff.push(e.encode("-" + mode + " "));
break;
}
//Link count
const linkCount = node.link_count.toString().padStart(maxLinksWidth, " ") + " ";
buff.push(e.encode(linkCount));
// owner group
if (options.noGroup) {
buff.push(e.encode(`${state.users.get(node.owner)?.username} `));
} else if (options.noOwner) {
buff.push(e.encode(`${state.groups.get(node.group)?.groupname} `));
} else if (options.numericUidGid) {
buff.push(e.encode(`${node.owner} ${node.group} `));
} else {
buff.push(
e.encode(`${state.users.get(node.owner)?.username} ${state.groups.get(node.group)?.groupname} `),
);
}
//Size
// Holy abomination, pad the stringified bytesize number with whitespaces so the actual length of the string matches across all rows
// Sets the folder size to an arbitrary 4096, could change it later to smth else
let size;
if (options.humanReadable) {
const bytes = node.type === NodeType.File ? node.size : 4096;
size = convertToUnit(bytes, 1, options.si ? 1000 : 1024);
} else {
size =
node.type === NodeType.File
? `${node.size.toString().padStart(maxSizeWidth, " ")} `
: `${"4096".padStart(maxSizeWidth, " ")} `;
}
buff.push(e.encode(size));
//Timestamp
const date = getDateTimestamp(node, options.timestamp);
if (options.fullTime) {
buff.push(
// Month + 1 because January is 0
e.encode(
`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `,
),
);
} else {
buff.push(
// Month + 1 because January is 0
e.encode(`${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `),
);
}
//Name
if (options.quoteName) {
buff.push(
e.encode(
`"${node.type === NodeType.Directory ? n.name + '"' + (options.appendIndicator ? "/" : "") : n.name + '"'}\n`,
),
);
} else {
const unpadded = `${n.name.includes(" ") && !options.literal ? "'" + n.name + "'" : n.name}`;
const name = `${!namePadding ? (unpadded.includes(" ") ? unpadded : " " + unpadded) : unpadded}`;
buff.push(
e.encode(
`${node.type === NodeType.Directory ? name + (options.appendIndicator ? "/" : "") : name}\n`,
),
);
}
}
const out = concatUint8Arrays(buff);
io.writeStdout(out);
}
function getDateTimestamp(node: Node, ts: string): Date {
if (ts === "atime") return new Date(node.atime);
if (ts === "ctime") return new Date(node.ctime);
if (ts === "mtime") return new Date(node.mtime);
return new Date();
}
function parseMode(mode: number) {
const owner = (mode >> 6) & 7;
const group = (mode >> 3) & 7;
const other = mode & 7;
const map = (bits: number) => {
let s = "";
s += bits & 4 ? "r" : "-";
s += bits & 2 ? "w" : "-";
s += bits & 1 ? "x" : "-";
return s;
};
return map(owner) + map(group) + map(other);
}
function isValidSortMethod(value: string): value is SortNodeBy {
return Object.values(SortNodeBy).includes(value as SortNodeBy);
}
function isValidTimestamp(value: string): value is SortNodeBy.ATIME | SortNodeBy.MTIME | SortNodeBy.CTIME {
return Object.values(SortNodeBy).includes(value as SortNodeBy.ATIME | SortNodeBy.MTIME | SortNodeBy.CTIME);
}
}
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
export const descriptor: CommandDescriptor = {
fn: main,
flags: [
{ name: "l" }, // done
{ name: "a" }, // done
{ name: "A" }, // done
{ name: "c" },
{ name: "U" }, // done
{ name: "g" }, // done
{ name: "G" }, // done
{ name: "h" }, // done
{ name: "f" }, // done
{ name: "x" },
{ name: "X" }, // done
{ name: "u" },
{ name: "t" }, // done
{ name: "S" }, // done
{ name: "r" }, // done
{ name: "R" }, // done
{ name: "Q" }, // done
{ name: "p" }, // done
{ name: "o" }, // done
{ name: "n" }, // done
{ name: "N" }, // done
{ name: "L" },
{ name: "m" },
{ name: "i" }, // done
{ name: "sort", takesValue: true }, // done
{ name: "time", takesValue: true }, // done
{ name: "help" },
{ name: "all" }, // done
{ name: "almost-all" }, // done
{ name: "full-time" }, // done
{ name: "no-group" }, // done
{ name: "human-readable" }, // done
{ name: "reverse" }, // done
{ name: "recursive" }, // done
{ name: "quote-name" }, // done
{ name: "literal" }, // done
{ name: "numeric-uid-gid" }, // done
{ name: "inode" }, // done
{ name: "si" }, // done
{ name: "dereference" },
],
name: "ls",
};
+41
View File
@@ -0,0 +1,41 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state";
import type { InvalidArgumentsError, ShellError } from "@core/util/errors";
import { resolvePointer } from "@core/util/path_resolver";
export const COMMAND_NAME = "pwd";
//Need to implement escape sequences
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
if (args.length > 0) {
return {
state,
result: createErrorResult(
"InvalidArguments",
`Expected aruments 0, got ${args.length}.`,
{ expected: "pwd", actual: `pwd ${args.toString().replace(/[,]/g, " ")}` },
COMMAND_NAME,
),
} satisfies CommandOutput<InvalidArgumentsError>;
}
const session = getCurrentSession(state);
const path = resolvePointer(state, session.cwd);
io.writeStdout(new TextEncoder().encode(path));
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
state: state,
result,
};
}
export const descriptor: CommandDescriptor = {
fn: main,
name: COMMAND_NAME,
};
+40
View File
@@ -0,0 +1,40 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import type { ResultSuccess } from "@core/result";
import type { ShellState } from "@core/shell_state";
import { SIGNAL_MAP } from "@core/signal";
import type { ShellError } from "@core/util/errors";
import { createImmutableBuffer } from "@core/util/immutable_buffer";
const COMMAND_NAME = "async";
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
while (true) {
const out = await io.getSignal();
if (out.type === SIGNAL_MAP.INPUT) {
const encoded = new TextEncoder().encode(("user pressed: " + out.payload + "\n") as string);
io.writeStdout(encoded);
if (out.payload === "x") {
const result: ResultSuccess = {
type: "success",
exitCode: 0,
stdout: createImmutableBuffer(new Uint8Array()),
stderr: createImmutableBuffer(new Uint8Array()),
commandName: COMMAND_NAME,
};
return {
state: state,
result,
};
}
}
}
}
export const descriptor = {
fn: main,
name: COMMAND_NAME,
} satisfies CommandDescriptor;
+52
View File
@@ -0,0 +1,52 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { NodeType } from "@core/filesystem/node";
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state";
import type { ShellError } from "@core/util/errors";
import { resolvePath } from "@core/util/path_resolver";
export const COMMAND_NAME = "touch";
//Need to implement escape sequences
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const session = getCurrentSession(state);
for (const arg of args) {
try {
resolvePath(state, arg);
} catch {
const index = arg.lastIndexOf("/");
const fileName = arg.slice(index + 1);
const parentPath = index === -1 ? "./" : arg.slice(0, index + 1);
const pptr = resolvePath(state, parentPath);
state.filesystem.createNode(pptr, fileName, {
type: NodeType.File,
mode: 0o644,
owner: session.user.uid,
group: session.user.gid,
content: new Blob(),
size: 0,
});
continue;
}
return {
state,
result: createErrorResult("AlreadyExists", "The file already exists", {}),
} satisfies CommandOutput<ShellError>;
}
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
state: state,
result,
};
}
export const descriptor: CommandDescriptor = {
fn: main,
name: COMMAND_NAME,
};
+40 -3
View File
@@ -1,4 +1,4 @@
import type { TreeNodeType } from "./treenode";
import type { NodePointer, NodeType } from "./node";
export type FileSystemError =
NotADirectoryError | AlreadyExistsError | NodeNotFoundError | IllegalMutationError | FileSystemInitializationError;
@@ -14,7 +14,15 @@ export interface NotADirectoryError {
message: string;
timestamp: number;
type: "NotADirectory";
nodeType: TreeNodeType;
nodeType: NodeType;
}
export interface NotAFileError {
inode: number;
message: string;
timestamp: number;
type: "NotAFile";
nodeType: NodeType;
}
export interface AlreadyExistsError {
@@ -28,7 +36,21 @@ export interface AlreadyExistsError {
export interface NodeNotFoundError {
type: "NodeNotFound";
message: string;
inode: number;
pointer: NodePointer;
timestamp: number;
}
export interface DeviceNotFoundError {
type: "DeviceNotFound";
message: string;
device_id: number;
timestamp: number;
}
export interface MountPointNotFoundError {
type: "MountPointNotFound";
message: string;
pointer: NodePointer;
timestamp: number;
}
@@ -45,3 +67,18 @@ export interface DirectoryLoopError {
descendantInode: number;
ancestorInode: number;
}
export interface InvalidNodeNameError {
type: "InvalidNodeName";
message: string;
timestamp: number;
pointer: NodePointer;
attemptedName: string;
}
export interface FileSystemCorruptionError {
type: "FileSystemCorruption";
message: string;
timestamp: number;
override?: {};
}
File diff suppressed because it is too large Load Diff
+120
View File
@@ -0,0 +1,120 @@
export type Node = FileNode | DirectoryNode | SymlinkNode;
export type NodeHash = ReadonlyMap<number, Node>;
export type ShadowHash = ReadonlyMap<number, Node | null>;
export class NodePointer {
private static readonly _cache = new Map<string, NodePointer>();
private readonly _device_id: number;
private readonly _inode: number;
private constructor(device_id: number, inode: number) {
this._device_id = device_id;
this._inode = inode;
}
static of(device_id: number, inode: number): NodePointer {
const key = `${device_id}:${inode}`;
let p = NodePointer._cache.get(key);
if (!p) {
p = new NodePointer(device_id, inode);
NodePointer._cache.set(key, p);
}
return p;
}
static parse(s: string): NodePointer {
const m = /^(\d+):(\d+)$/.exec(s);
if (!m) throw new Error(`Invalid NodePointer: ${s}`);
let p = NodePointer._cache.get(s);
if (!p) {
p = new NodePointer(Number(m[1]), Number(m[2]));
NodePointer._cache.set(s, p);
}
return p;
}
get device(): number {
return this._device_id;
}
get inode(): number {
return this._inode;
}
toString(): string {
return `${this._device_id}:${this.inode}`;
}
equals(other: NodePointer): boolean {
return this._device_id === other._device_id && this.inode === other.inode;
}
}
//export type NodePointer = `${string}:${string}`;
export interface NodeEntry {
readonly pinode: number;
readonly pdevice_id: number;
readonly name: string;
}
export interface FileNode {
readonly type: NodeType.File;
readonly inode: number;
readonly link_count: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly content: string;
readonly size: number;
}
export interface DirectoryNode {
readonly type: NodeType.Directory;
readonly inode: number;
readonly link_count: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly children: Map<string, number>;
}
export interface SymlinkNode {
readonly type: NodeType.Symlink;
readonly inode: number;
readonly link_count: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly target: string;
}
export enum NodeType {
File = 0,
Directory = 1,
Symlink = 2,
}
/* export function toPtr({ device_id, inode }: { device_id: number; inode: number }): NodePointer {
return `${device_id}:${inode}`;
}
export function fromPtr(ptr: NodePointer): { device_id: number; inode: number } {
if (!ptr.match(/^\d+[:]\d+$/)) {
//TODO: Make typed
throw new Error("Invalid node pointer format");
}
const arr = ptr.split(":");
return {
device_id: Number(arr[0]),
inode: Number(arr[1]),
};
} */
-51
View File
@@ -1,51 +0,0 @@
import type { ImmutableBuffer } from "@core/util/immutable_buffer";
export type TreeNode = FileNode | DirectoryNode;
export interface FileNode {
readonly type: TreeNodeType.File;
readonly inode: number;
readonly name: string;
readonly parent: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly content: ImmutableBuffer;
}
export interface DirectoryNode {
readonly type: TreeNodeType.Directory;
readonly inode: number;
readonly name: string;
readonly parent: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly children: Readonly<Record<string, number>>;
}
/* export interface SymlinkNode {
readonly type: TreeNodeType.Symlink;
readonly inode: number;
readonly name: string;
readonly parent: number;
readonly mode: number;
readonly owner: number;
readonly group: number;
readonly mtime: number;
readonly ctime: number;
readonly atime: number;
readonly target: string;
} */
export enum TreeNodeType {
File = "0",
Directory = "1",
//Symlink = "2",
}
+447
View File
@@ -0,0 +1,447 @@
import { NodePointer, NodeType, type DirectoryNode, type Node, type NodeEntry, type NodeHash } from "./node";
export function DefaultVDiskConfig(id: number): VDiskConfig {
const base = new Map();
const root = {
type: NodeType.Directory,
inode: 0,
link_count: 2,
mode: 0o0555,
owner: 0,
group: 0,
mtime: 0,
ctime: 0,
atime: 0,
children: new Map(),
} satisfies DirectoryNode;
base.set(0, root);
return {
id,
label: `disk-${id}`,
readonly: false,
size: Infinity,
base,
index: 0,
dataC: {
chunkSize: 8096,
cacheSize: 64 * 1024 * 1024,
cacheTTL: 60_000,
},
};
}
export interface VDiskConfig {
id: number;
label: string;
index: number;
readonly: boolean;
size: number;
base: NodeHash;
dataC: DataConfig;
}
export interface DataConfig {
chunkSize: number;
cacheSize: number;
cacheTTL: number;
}
export interface IDataStore {
read(uuid: string): Promise<Uint8Array>;
stream(uuid: string): ReadableStream;
put(uuid: string, blob: Blob): Promise<void>;
delete(uuid: string): Promise<void>;
has(uuid: string): Promise<boolean>;
list(): Promise<string[]>;
}
export interface IMetaStore {
loadAll(): Promise<Map<number, Node | null>>;
write(entries: Array<[number, Node | null]>): Promise<void>;
delete(entries: Array<number>): Promise<void>;
}
export class VDisk {
private readonly _id: number;
private readonly _label: string;
private readonly _readonly: boolean;
private readonly _totalSize: number;
private readonly _base: NodeHash;
private readonly _dataStore: IDataStore;
private readonly _metaStore: IMetaStore;
private _iIndex: number;
private _rIndex: ReadonlyMap<NodePointer, ReadonlyArray<NodeEntry>>;
private _overlay: Map<number, Node | null>;
private _pending: Map<number, Node | null> | null;
private _rIndexInvalid: boolean;
private _flush: Promise<void>;
private constructor(config: VDiskConfig, data: IDataStore, meta: IMetaStore) {
this._id = config.id;
this._label = config.label;
this._readonly = config.readonly;
this._totalSize = config.size;
this._base = config.base;
this._iIndex = config.index;
this._dataStore = data;
this._metaStore = meta;
this._overlay = new Map();
this._rIndex = new Map();
this._rIndexInvalid = false;
this._pending = null;
this._flush = Promise.resolve();
}
private async _batch<T>(fn: () => T): Promise<T> {
if (this._pending) {
console.error("Nested batch not ok");
}
this._pending = new Map();
let result: T;
try {
result = fn();
} catch (err) {
this._pending = null;
throw err;
}
const pending = this._pending;
this._pending = null;
for (const [inode, node] of pending) {
this._overlay.set(inode, node);
}
const entries = Array.from(pending.entries());
const next = this._flush.then(() => this._metaStore.write(entries));
this._flush = next.catch(() => {});
await next;
return result;
}
private _isWritable(): void {
if (this._readonly) throw Error(`The ${this._label} device under id - ${this._id} is marked readonly`);
}
private _buildReverseIndex(): Map<NodePointer, NodeEntry[]> {
const index: Map<NodePointer, NodeEntry[]> = new Map();
const stack: [number, number, number, string][] = [];
const root = this.getNode(0) as DirectoryNode;
for (const [name, inode] of root.children) {
if (name === "." || name === "..") continue;
stack.push([inode, 0, this._id, name]);
}
while (stack.length > 0) {
const [inode, pinode, pdevice_id, name] = stack.pop()!;
const node = this.getNode(inode);
if (node === undefined) continue;
const key = NodePointer.of(this._id, inode);
const entry = {
pinode,
pdevice_id,
name,
};
const arr = index.get(key);
if (arr) arr.push(entry);
else index.set(key, [entry]);
if (node.type === NodeType.Directory) {
for (const [name, cinode] of node.children) {
if (name === "." || name === "..") continue;
stack.push([cinode, inode, pdevice_id, name]);
}
}
}
return index;
}
private _putNode(inode: number, node: Node | null): void {
if (!this._pending)
throw new Error(
"_putNode called outside of batch. This is not a BUG. Every mutation must be wrapped in a _batch call",
);
this._pending.set(inode, node);
}
public static async open(config: VDiskConfig, data: IDataStore, meta: IMetaStore): Promise<VDisk> {
const vdisk = new VDisk(config, data, meta);
await vdisk.loadOverlay();
vdisk._rIndex = vdisk._buildReverseIndex();
return vdisk;
}
public getNode(inode: number): Node | undefined {
if (this._pending && this._pending.has(inode)) {
return this._pending.get(inode) ?? undefined;
}
const node = this._overlay.get(inode);
if (node) return node;
if (node === null) return undefined;
return this._base.get(inode);
}
public async createNodeEntry(
pinode: number,
name: string,
data:
| {
type: NodeType.File;
mode: number;
owner: number;
group: number;
content: Blob | ReadableStream;
size: number;
}
| { type: NodeType.Directory; mode: number; owner: number; group: number }
| { type: NodeType.Symlink; mode: number; owner: number; group: number; target: string },
): Promise<number> {
return this._batch(async () => {
this._isWritable();
const index = ++this._iIndex;
const time = Date.now();
const link_count = data.type === NodeType.Directory ? 2 : 1;
const base = {
inode: index,
link_count,
type: data.type,
mode: data.mode,
owner: data.owner,
group: data.group,
mtime: time,
ctime: time,
atime: time,
};
const pnode = this.getNode(pinode) as DirectoryNode;
const uuid = crypto.randomUUID();
let node: Node;
switch (data.type) {
case NodeType.File:
node = { ...base, type: NodeType.File, content: uuid, size: data.size };
this.writeContent(
uuid,
data.content instanceof ReadableStream ? await new Response(data.content).blob() : data.content,
);
break;
case NodeType.Directory:
node = { ...base, type: NodeType.Directory, children: new Map() };
break;
case NodeType.Symlink:
node = { ...base, type: NodeType.Symlink, target: data.target };
break;
}
const children = new Map(pnode.children);
children.set(name, index);
const parent = {
...pnode,
children,
link_count: pnode.link_count + (data.type === NodeType.Directory ? 1 : 0),
mtime: time,
ctime: time,
};
this._putNode(index, node);
this._putNode(pinode, parent);
this.invalidateRIndex();
return index;
});
}
public linkNodeEntry(pinode: number, name: string, tinode: number): Promise<void> {
return this._batch(() => {
this._isWritable();
const pnode = this.getNode(pinode) as DirectoryNode;
const tnode = this.getNode(tinode) as Node;
const time = Date.now();
const children = new Map(pnode.children);
children.set(name, tnode.inode);
const parent = { ...pnode, children, mtime: time, ctime: time };
const target = { ...tnode, link_count: tnode.link_count + 1, ctime: time };
this._putNode(tinode, target);
this._putNode(pinode, parent);
this.invalidateRIndex();
});
}
public unlinkNodeEntry(inode: number, name: string): Promise<void> {
return this._batch(() => {
this._isWritable();
const pnode = this.getNode(inode) as DirectoryNode;
const tinode = pnode.children.get(name)!;
const tnode = this.getNode(tinode) as Node;
const time = Date.now();
const children = new Map(pnode.children);
children.delete(name);
const parent = { ...pnode, children, mtime: time, ctime: time };
const link_count = tnode.link_count - 1;
const wasLast = link_count === 0;
this._putNode(inode, parent);
this._putNode(tinode, wasLast ? null : { ...tnode, link_count, ctime: Date.now() });
this.invalidateRIndex();
});
}
public moveNodeEntry(pinode: number, dinode: number, tname: string, dname?: string): Promise<void> {
return this._batch(() => {
this._isWritable();
const pnode = this.getNode(pinode) as DirectoryNode;
const dnode = this.getNode(dinode) as DirectoryNode;
const tinode = pnode.children.get(tname)!;
const tnode = this.getNode(tinode)!;
const name = dname ?? tname;
const isDir = tnode.type === NodeType.Directory;
const time = Date.now();
if (pinode === dinode) {
const pchildren = new Map(pnode.children);
pchildren.delete(tname);
pchildren.set(name, tinode);
const parent = { ...pnode, children: pchildren, mtime: time, ctime: time };
const target = { ...tnode, ctime: time };
this._putNode(pinode, parent);
this._putNode(tinode, target);
this.invalidateRIndex();
return;
}
const pchildren = new Map(pnode.children);
pchildren.delete(tname);
const dchildren = new Map(dnode.children);
dchildren.set(name, tinode);
const parent = {
...pnode,
children: pchildren,
mtime: time,
ctime: time,
link_count: pnode.link_count - (isDir ? 1 : 0),
};
const target = { ...tnode, ctime: time };
const destination = {
...dnode,
children: dchildren,
mtime: time,
ctime: time,
link_count: dnode.link_count + (isDir ? 1 : 0),
};
this._putNode(pinode, parent);
this._putNode(tinode, target);
this._putNode(dinode, destination);
this.invalidateRIndex();
});
}
public writeNodeEntry(inode: number, data: { mode?: number; owner?: number; group?: number }): Promise<void> {
return this._batch(() => {
this._isWritable();
const node = this.getNode(inode)!;
const newNode: Node = {
...node,
mode: data.mode ?? node.mode,
owner: data.owner ?? node.owner,
group: data.group ?? node.group,
ctime: Date.now(),
};
this._putNode(inode, newNode);
});
}
public readContent(uuid: string): Promise<Uint8Array> {
return this._dataStore.read(uuid);
}
public streamContent(uuid: string): ReadableStream {
return this._dataStore.stream(uuid);
}
public async writeContent(uuid: string, blob: Blob): Promise<void> {
this._isWritable();
await this._dataStore.put(uuid, blob);
}
public async deleteContent(uuid: string): Promise<void> {
this._isWritable();
await this._dataStore.delete(uuid);
}
public hasContent(uuid: string): Promise<boolean> {
return this._dataStore.has(uuid);
}
public async loadOverlay(): Promise<void> {
const overlay = await this._metaStore.loadAll();
this._overlay = new Map(overlay);
}
// public sweepOrphans(): Promise<void> {}
// public sweepDangling(): Promise<void> {}
public invalidateRIndex(): void {
this._rIndexInvalid = true;
}
public getIndex(): ReadonlyMap<NodePointer, ReadonlyArray<NodeEntry>> {
if (this._rIndexInvalid) {
this._rIndex = this._buildReverseIndex();
this._rIndexInvalid = false;
}
return this._rIndex;
}
public get ID(): number {
return this._id;
}
public get Label(): string {
return this._label;
}
public get IsReadonly(): boolean {
return this._readonly;
}
public get ByteSize(): number {
return this._totalSize;
}
}
View File
+4 -4
View File
@@ -24,16 +24,16 @@ export function createErrorResult<E extends ShellError>(
message: string,
// Omit - includes all properties of E except the ones that are already inside ShellError - basically skipping duplicates and allowing this to be a one-liner
extraProps: Omit<E, keyof ShellError>,
stdout: ImmutableBuffer,
stderr: ImmutableBuffer,
commandName?: string,
stdout?: ImmutableBuffer,
stderr?: ImmutableBuffer,
cause?: { name: string; message: string },
): ResultError<E> {
const error = createShellError<E>(errorType, message, extraProps, cause);
return Object.freeze({
type: "error",
stdout,
stderr,
stdout: stdout ?? createImmutableBuffer(new Uint8Array()),
stderr: stderr ?? createImmutableBuffer(new Uint8Array()),
error,
// commandName is either undefined or string but when undefined - has to be ommited - we achieve that with a condition wrapped in a spread
...(commandName !== undefined && { commandName }),
+12 -5
View File
@@ -1,21 +1,28 @@
import type { NodePointer } from "./filesystem/node";
import { type HistoryState } from "./history_state";
import { createShellState, type ShellState } from "./shell_state";
import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors";
export interface GroupInfo {
readonly groupname: string;
readonly gid: number;
readonly members: number[];
}
export interface UserInfo {
readonly username: string;
readonly uid: number;
readonly gid: number;
readonly group: readonly number[];
readonly home: number;
readonly home: NodePointer;
}
export interface SessionState {
readonly user: UserInfo;
readonly envVars: ReadonlyMap<string, string>;
readonly history: HistoryState;
readonly cwd: number;
readonly pwd: number;
readonly cwd: NodePointer;
readonly pwd: NodePointer;
readonly exitCode: number;
}
@@ -59,7 +66,7 @@ export function login(
const stack = [...state.sessionStack];
stack.push(createInitialSessionState(user));
return createShellState(state.filesystem, state.users, stack);
return createShellState(state.filesystem, state.users, state.groups, stack);
}
export function logout(state: ShellState): ShellState {
@@ -67,7 +74,7 @@ export function logout(state: ShellState): ShellState {
const stack = [...state.sessionStack];
stack.pop();
return createShellState(state.filesystem, state.users, stack);
return createShellState(state.filesystem, state.users, state.groups, stack);
}
return state;
}
+13 -3
View File
@@ -1,22 +1,26 @@
import type { FileSystem } from "./filesystem/filesystem";
import type { NodePointer } from "./filesystem/node";
import { addHistoryEntry } from "./history_state";
import type { UserInfo } from "./session_manager";
import type { GroupInfo, UserInfo } from "./session_manager";
import { createInitialSessionState, getCurrentSession, type SessionState } from "./session_manager";
export interface ShellState {
readonly filesystem: FileSystem;
readonly users: ReadonlyMap<number, UserInfo>;
readonly groups: ReadonlyMap<number, GroupInfo>;
readonly sessionStack: ReadonlyArray<SessionState>;
}
export function createInitialShellState(
filesystem: FileSystem,
users: ReadonlyMap<number, UserInfo>,
groups: ReadonlyMap<number, GroupInfo>,
user: UserInfo,
): ShellState {
return Object.freeze({
filesystem,
users,
groups,
sessionStack: Object.freeze([createInitialSessionState(user)]),
});
}
@@ -24,23 +28,25 @@ export function createInitialShellState(
export function createShellState(
filesystem: FileSystem,
users: ReadonlyMap<number, UserInfo>,
groups: ReadonlyMap<number, GroupInfo>,
sessionStack: ReadonlyArray<SessionState>,
): ShellState {
return Object.freeze({
filesystem,
users,
groups,
sessionStack: Object.freeze(sessionStack),
});
}
export function withCwd(state: ShellState, inode: number): ShellState {
export function withCwd(state: ShellState, ptr: NodePointer): ShellState {
const session = getCurrentSession(state);
const newSession = Object.freeze({
user: session.user,
envVars: Object.freeze(session.envVars),
history: Object.freeze(session.history),
cwd: inode,
cwd: ptr,
pwd: session.cwd,
exitCode: session.exitCode,
} satisfies SessionState);
@@ -52,6 +58,7 @@ export function withCwd(state: ShellState, inode: number): ShellState {
return Object.freeze({
filesystem: state.filesystem,
users: state.users,
groups: state.groups,
sessionStack: Object.freeze(sessionStack),
} satisfies ShellState);
}
@@ -75,6 +82,7 @@ export function withHistory(state: ShellState, input: string): ShellState {
return Object.freeze({
filesystem: state.filesystem,
users: state.users,
groups: state.groups,
sessionStack: Object.freeze(sessionStack),
} satisfies ShellState);
}
@@ -101,6 +109,7 @@ export function withEnv(state: ShellState, key: string, value: string): ShellSta
return Object.freeze({
filesystem: state.filesystem,
users: state.users,
groups: state.groups,
sessionStack: Object.freeze(sessionStack),
} satisfies ShellState);
}
@@ -124,6 +133,7 @@ export function withExitCode(state: ShellState, exitCode: number): ShellState {
return Object.freeze({
filesystem: state.filesystem,
users: state.users,
groups: state.groups,
sessionStack: Object.freeze(sessionStack),
} satisfies ShellState);
}
+8 -3
View File
@@ -1,8 +1,13 @@
export type Input = string;
//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: string;
type: SIGNAL_MAP;
payload?: unknown;
};
export enum SIGNAL_MAP {
SIGINT = 2,
SIGTERM = 3,
SIGKILL = 9,
INPUT = 10,
}
+1
View File
@@ -38,6 +38,7 @@ const EXIT_CODE_MAP: Record<string, number> = {
GenericError: 1,
InvalidArguments: 2,
ParseError: 62,
UsageError: 63,
PathResolutionError: 64,
DataFormatError: 65,
+6
View File
@@ -2,6 +2,7 @@ export interface ImmutableBuffer {
readonly length: number;
get(index: number): number;
slice(start?: number, end?: number): ImmutableBuffer;
byteSize(): number;
toArray(): Uint8Array;
}
@@ -22,10 +23,15 @@ export function createImmutableBuffer(input: Uint8Array): ImmutableBuffer {
return Uint8Array.from(buffer);
};
const byteSize = (): number => {
return buffer.byteLength;
};
const result: ImmutableBuffer = {
length: buffer.length,
get,
slice,
byteSize,
toArray,
};
+1 -52
View File
@@ -6,13 +6,7 @@ interface UnclosedQuoteError {
timestamp: number;
}
interface ParsedCommand {
command: string;
flags: string[];
args: string[];
}
function tokenize(input: string): string[] {
export function tokenize(input: string): string[] {
enum State {
Normal,
SingleQuote,
@@ -98,48 +92,3 @@ function tokenize(input: string): string[] {
flushBuffer();
return tokens;
}
export function parseCommand(input: string): ParsedCommand {
const tokens = tokenize(input);
const command = tokens[0] ?? "";
const flags: string[] = [];
const args: string[] = [];
let pastEndOfOptions = false;
for (let i = 1; i < tokens.length; i++) {
const token = tokens[i]!;
if (pastEndOfOptions) {
args.push(token);
continue;
}
if (token === "--") {
pastEndOfOptions = true;
continue;
}
if (token.startsWith("--")) {
flags.push(token.slice(2));
continue;
} else if (token.startsWith("-")) {
if (token.includes("=")) {
flags.push(token.slice(1));
continue;
}
for (const char of token.slice(1)) {
flags.push(char);
}
continue;
} else {
args.push(token);
continue;
}
}
return {
command,
flags,
args,
};
}
+237 -41
View File
@@ -1,73 +1,269 @@
import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
import type { FileSystem } from "../filesystem/filesystem";
import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode";
import type { FileSystemCorruptionError, NodeNotFoundError, NotADirectoryError } from "@core/filesystem/errors";
import { NodePointer, NodeType, type Node } from "@core/filesystem/node";
import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state";
export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
export function resolvePath(state: ShellState, path: string): NodePointer {
let linkDepth = 0;
const maxDepth = state.filesystem.maxSymlinkDepth;
const session = getCurrentSession(state);
const isAbsolute = path.startsWith("/");
const normalizedPath: string = path.replace(/^\/+|\/+$/g, "");
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0);
const pathComponents: string[] = path.split("/").filter(c => c.length > 0);
if (pathComponents.length === 0 && isAbsolute) return 0;
if (pathComponents.length === 0) return cwd;
let currentDeviceId: number;
let currentNode: Node;
let currentNode = isAbsolute ? fs.getRoot() : (fs.getNode(cwd) as DirectoryNode);
if (isAbsolute) {
currentDeviceId = 0;
currentNode = state.filesystem.getRoot();
} else if (!isAbsolute && pathComponents[0] === "~") {
const home = session.user.home;
currentDeviceId = home.device;
currentNode = state.filesystem.getNode(session.user.home)!;
if (!currentNode) {
throw {
type: "NodeNotFound",
message: `CWD node under inode ${cwd} not found`,
message: `[Panic] ${session.user.username}'s home directory does not exist!`,
timestamp: Date.now(),
inode: cwd,
pointer: session.user.home,
} satisfies NodeNotFoundError;
}
pathComponents.shift();
if (currentNode.type === NodeType.Symlink) {
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
const target = currentNode.target;
if (target.startsWith("/")) {
currentDeviceId = 0;
currentNode = state.filesystem.getRoot();
} else {
const entries = state.filesystem.getNodeEntries(session.user.home);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
}
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
}
} else {
currentDeviceId = session.cwd.device;
currentNode = state.filesystem.getNode(session.cwd)!;
if (!currentNode) {
throw {
type: "NodeNotFound",
message: "[Panic] Current working directory does not exist!",
timestamp: Date.now(),
pointer: session.cwd,
} satisfies NodeNotFoundError;
}
}
while (pathComponents.length > 0) {
const name = pathComponents.shift()!;
for (const name of pathComponents) {
if (name === ".") continue;
if (name === "..") {
currentNode = fs.getNode(currentNode.parent) as DirectoryNode;
if (state.filesystem.isMountTarget(NodePointer.of(currentDeviceId, currentNode.inode))) {
const mount = state.filesystem.getMountPoint(NodePointer.of(currentDeviceId, currentNode.inode));
if (!mount) {
throw {
type: "FileSystemCorruption",
message: "Mount registry entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
const entries = state.filesystem.getNodeEntries(mount);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
continue;
}
if (currentNode.inode === 0) continue;
const entries = state.filesystem.getNodeEntries(NodePointer.of(currentDeviceId, currentNode.inode));
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
continue;
}
const inode = currentNode.children[name];
if (!inode)
throw {
type: "NodeNotFound",
message: `Child node in ${currentNode.name} under name ${name} not found`,
timestamp: Date.now(),
inode: currentNode.inode,
} satisfies NodeNotFoundError;
if (fs.isFile(inode))
if (currentNode.type !== NodeType.Directory) {
throw {
type: "NotADirectory",
message: `Child node ${name} is not a directory`,
message: "Not a directory",
timestamp: Date.now(),
inode: inode,
nodeType: TreeNodeType.File,
inode: currentNode.inode,
nodeType: currentNode.type,
} satisfies NotADirectoryError;
currentNode = fs.getNode(inode) as DirectoryNode;
}
return currentNode.inode;
const childInode = currentNode.children.get(name);
if (childInode === undefined) {
throw {
type: "NodeNotFound",
message: `${name} not found`,
timestamp: Date.now(),
pointer: NodePointer.of(currentDeviceId, currentNode.inode),
} satisfies NodeNotFoundError;
}
export function resolveInode(fs: FileSystem, inode: number): string {
const node = fs.getNode(inode);
let childPtr = NodePointer.of(currentDeviceId, childInode);
if (state.filesystem.isMountPoint(childPtr)) {
const mount = state.filesystem.getMountTarget(childPtr)!;
childPtr = mount;
currentDeviceId = mount.device;
}
let child = state.filesystem.getNode(childPtr);
if (!child) {
throw {
type: "NodeNotFound",
message: `Node under ${childPtr} not found (probable dangling orphan)`,
timestamp: Date.now(),
pointer: childPtr,
} satisfies NodeNotFoundError;
}
if (child.type === NodeType.Symlink) {
// Change to typed error later on
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
const target = child.target;
if (target.startsWith("/")) {
currentDeviceId = 0;
currentNode = state.filesystem.getRoot();
} else {
const entries = state.filesystem.getNodeEntries(childPtr);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
}
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
continue;
}
currentNode = child;
}
return NodePointer.of(currentDeviceId, currentNode.inode);
}
export function resolvePointer(state: ShellState, pointer: NodePointer): string {
const node = state.filesystem.getNode(pointer);
const components: string[] = [];
if (node === undefined) return "";
let currentInode = inode;
while (currentInode !== 0) {
const node = fs.getNode(currentInode) as TreeNode;
if (!node) break;
let ptr = pointer;
// TODO: Change while statements condition to not be hardcoded
while (!ptr.equals(NodePointer.of(0, 0))) {
if (state.filesystem.isMountTarget(ptr)) {
const mount = state.filesystem.getMountPoint(ptr);
if (!mount) {
throw {
type: "FileSystemCorruption",
message: "Mount registry entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
components.push(node.name);
currentInode = node.parent;
const entries = state.filesystem.getNodeEntries(mount);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
components.reverse();
components.unshift("");
return components.join("/");
components.push(entries[0].name);
ptr = NodePointer.of(entries[0].pdevice_id, entries[0].pinode);
continue;
}
const entries = state.filesystem.getNodeEntries(ptr);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
components.push(entries[0].name);
ptr = NodePointer.of(entries[0].pdevice_id, entries[0].pinode);
}
if (components.length === 0) {
components.push("/");
return components.join("");
}
components.reverse().unshift("");
let result = components.join("/");
return result;
}
export function resolvePointerToHome(state: ShellState, ptr: NodePointer): string {
const home = resolvePointer(state, getCurrentSession(state).user.home);
let result = resolvePointer(state, ptr);
if (result.startsWith(home)) {
result = `~${result.slice(home.length)}`;
}
return result;
}
export function resolvePointerToCwd(state: ShellState, ptr: NodePointer): string {
const cwd = resolvePointer(state, getCurrentSession(state).cwd);
let result = resolvePointer(state, ptr);
if (result.startsWith(cwd)) {
result = `.${result.slice(cwd.length)}`;
}
return result;
}
export function resolvePointerRelative(state: ShellState, ptr: NodePointer, relative: NodePointer): string {
const rel = resolvePointer(state, relative);
let result = resolvePointer(state, ptr);
if (result.startsWith(rel)) {
result = `.${result.slice(rel.length)}`;
}
return result;
}
+143
View File
@@ -0,0 +1,143 @@
import { FileNode, NodePointer } from "@core/filesystem/node";
import type { ShellState } from "@core/shell_state";
import { Posix } from "@termos/util/posix";
export enum SortNodeBy {
NAME = "name",
INODE = "inode",
SIZE = "size",
EXTENSION = "extension",
TYPE = "type",
MTIME = "mtime",
ATIME = "atime",
CTIME = "ctime",
}
export function sortNodes<T extends { name: string; ptr: NodePointer }>(
state: ShellState,
arr: T[],
r: boolean = false,
by: SortNodeBy = SortNodeBy.NAME,
): T[] {
if (arr.length === 0) return [];
nodeQS(arr, r, by, 0, arr.length - 1, state);
return arr;
}
function nodeQS(
arr: { name: string; ptr: NodePointer }[],
r: boolean,
by: SortNodeBy,
start: number,
end: number,
state: ShellState,
): void {
if (end <= start) return;
const pivot = partitionNodeArray(arr, r, by, start, end, state);
nodeQS(arr, r, by, start, pivot - 1, state);
nodeQS(arr, r, by, pivot + 1, end, state);
}
function partitionNodeArray(
part: { name: string; ptr: NodePointer }[],
r: boolean,
by: SortNodeBy,
start: number,
end: number,
state: ShellState,
): number {
const pivot = part[end];
let i = start - 1;
for (let j = start; j <= end; j++) {
if (compareNode(part[j]!, pivot!, by, r, state) < 0) {
i++;
const temp = part[i]!;
part[i] = part[j]!;
part[j] = temp;
}
}
i++;
const temp = part[i]!;
part[i] = part[end]!;
part[end] = temp;
return i;
}
function compareNode(
a: { name: string; ptr: NodePointer },
b: { name: string; ptr: NodePointer },
by: SortNodeBy,
r: boolean,
state: ShellState,
): number {
switch (by) {
case SortNodeBy.NAME: {
const A: string = a.name;
const B: string = b.name;
const min = Math.min(A.length, B.length);
for (let i = 0; i < min; i++) {
const charA = Posix.GetCharWeight(A.charAt(i));
const charB = Posix.GetCharWeight(B.charAt(i));
if (charA !== charB) {
return r ? charB - charA : charA - charB;
}
}
return r ? B.length - A.length : A.length - B.length;
}
case SortNodeBy.MTIME:
case SortNodeBy.ATIME:
case SortNodeBy.CTIME: {
const nodeA = state.filesystem.getNode(a.ptr)!;
const nodeB = state.filesystem.getNode(b.ptr)!;
const A: number = nodeA[by];
const B: number = nodeB[by];
return r ? A - B : B - A;
}
case SortNodeBy.SIZE: {
const nodeA = state.filesystem.getNode(a.ptr)!;
const nodeB = state.filesystem.getNode(b.ptr)!;
const A: number = (nodeA as FileNode).size;
const B: number = (nodeB as FileNode).size;
return r ? A - B : B - A;
}
case SortNodeBy.EXTENSION: {
const A: string = a.name.split(".").pop() ?? "";
const B: string = b.name.split(".").pop() ?? "";
const min = Math.min(A.length, B.length);
for (let i = 0; i < min; i++) {
const charA = Posix.GetCharWeight(A.charAt(i));
const charB = Posix.GetCharWeight(B.charAt(i));
if (charA !== charB) {
return r ? charB - charA : charA - charB;
}
}
return r ? B.length - A.length : A.length - B.length;
}
case SortNodeBy.INODE: {
return r ? a.ptr.inode - b.ptr.inode : b.ptr.inode - a.ptr.inode;
}
case SortNodeBy.TYPE: {
const nodeA = state.filesystem.getNode(a.ptr)!;
const nodeB = state.filesystem.getNode(a.ptr)!;
return r ? nodeB.type - nodeA.type : nodeA.type - nodeB.type;
}
}
}
+60
View File
@@ -0,0 +1,60 @@
import type { Node } from "@core/filesystem/node";
import type { IDataStore, IMetaStore } from "@core/filesystem/vdisk";
export class MemMetaStore implements IMetaStore {
private _data: Map<number, Node | null> = new Map();
public loadAll(): Promise<Map<number, Node | null>> {
return Promise.resolve(this._data);
}
public write(entries: Array<[number, Node | null]>): Promise<void> {
for (const [inode, node] of entries) {
this._data.set(inode, node);
}
return Promise.resolve();
}
public delete(entries: number[]): Promise<void> {
for (const inode of entries) {
this._data.delete(inode);
}
return Promise.resolve();
}
}
export class MemDataStore implements IDataStore {
private _data: Map<string, Blob> = new Map();
public async read(uuid: string): Promise<Uint8Array> {
const blob = this._data.get(uuid);
if (!blob) throw new Error("Content missing - " + uuid);
const buff = await blob.arrayBuffer();
return new Uint8Array(buff);
}
public stream(uuid: string): ReadableStream {
const blob = this._data.get(uuid);
if (!blob) throw new Error("Content missing - " + uuid);
return blob.stream();
}
public put(uuid: string, blob: Blob): Promise<void> {
this._data.set(uuid, blob);
return Promise.resolve();
}
public delete(uuid: string): Promise<void> {
this._data.delete(uuid);
return Promise.resolve();
}
public has(uuid: string): Promise<boolean> {
return Promise.resolve(this._data.has(uuid));
}
public list(): Promise<string[]> {
return Promise.resolve(Array.from(this._data.keys()));
}
}
+24 -21
View File
@@ -1,41 +1,44 @@
import type { FileSystem } from "@core/filesystem/filesystem";
import { TreeNodeType, type TreeNode } from "@core/filesystem/treenode";
import { NodePointer, NodeType, type NodeEntry } from "@core/filesystem/node";
export function dnTraverseTree(fs: FileSystem, root: number): number[] {
export function dnTraverseTree(fs: FileSystem, root: NodePointer): NodePointer[] {
if (fs.getNode(root) === undefined) return [];
const result: number[] = [];
const stack: number[] = [];
const result: NodePointer[] = [];
const stack: NodePointer[] = [];
stack.push(root);
while (stack.length > 0) {
const node = fs.getNode(stack.pop() as number);
if (node === undefined) continue;
const ptr = stack.pop()!;
const node = fs.getNode(ptr);
if (!node) continue;
result.push(node.inode);
result.push(ptr);
if (node.type === TreeNodeType.Directory) {
for (const value of Object.values(node.children)) {
stack.push(value);
if (node.type === NodeType.Directory) {
const children = Array.from(node.children.values());
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i]!;
const pointer = NodePointer.of(ptr.device, child);
stack.push(pointer);
}
}
}
return result;
}
export function upTraverseTree(fs: FileSystem, inode: number): number[] {
if (fs.getNode(inode) === undefined) return [];
export function upTraverseTree(fs: FileSystem, ptr: NodePointer): NodePointer[] {
if (fs.getNode(ptr) === undefined) return [];
const result: number[] = [];
result.push(inode);
const result: NodePointer[] = [ptr];
let currentPtr = ptr;
let currentInode = inode;
while (currentInode !== 0) {
const node = fs.getNode(currentInode) as TreeNode;
if (!node) break;
while (currentPtr.inode !== 0) {
const entries = fs.getNodeEntries(currentPtr);
if (!entries || entries.length === 0) throw new Error(`No reverse-index entry found for ${currentPtr}`);
result.push(node.parent);
currentInode = node.parent;
const parent = entries[0] as NodeEntry;
currentPtr = NodePointer.of(parent.pdevice_id, parent.pinode);
result.push(currentPtr);
}
return result;
+45
View File
@@ -0,0 +1,45 @@
import { IDataStore, IMetaStore, VDisk, VDiskConfig } from "@core/filesystem/vdisk";
export class VDiskManager {
private _disks: Map<number, VDisk>;
constructor() {
this._disks = new Map();
}
public async registerDisk(config: VDiskConfig, data: IDataStore, meta: IMetaStore): Promise<VDisk> {
if (this._disks.has(config.id)) {
throw new Error("Disk of this id already exists");
}
const vd = await VDisk.open(config, data, meta);
this._disks.set(config.id, vd);
return vd;
}
public getDisk(id: number): VDisk | undefined {
const vd = this._disks.get(id);
return vd;
}
public hasDisk(id: number): boolean {
return this._disks.has(id);
}
public listDisk(): VDisk[] {
return Array.from(this._disks.values());
}
public listID(): number[] {
return Array.from(this._disks.keys());
}
public unregisterDisk(id: number): void {
if (!this._disks.has(id)) {
throw new Error("Disk of this id doesnt exist");
}
this._disks.delete(id);
}
}
+54
View File
File diff suppressed because one or more lines are too long
+188
View File
@@ -0,0 +1,188 @@
import type { FileSystemCorruptionError, NodeNotFoundError, NotADirectoryError } from "@core/filesystem/errors";
import { FileSystem } from "@core/filesystem/filesystem";
import { NodePointer, NodeType, type Node } from "@core/filesystem/node";
import type { GroupInfo, UserInfo } from "@core/session_manager";
import { createInitialShellState, type ShellState } from "@core/shell_state";
import { deserializeFileSystem } from "@shell/serializer";
import { Shell } from "@shell/shell";
import type { TermosConfig } from "./config";
async function getShell(config: TermosConfig): Promise<Shell> {
// TODO: Validate json schema
const devices = deserializeFileSystem(config.filesystem.json);
const fs = await FileSystem.init(devices);
const users: Map<number, UserInfo> = new Map();
const groups: Map<number, GroupInfo> = new Map();
const reverseGroups: Map<string, number> = new Map();
const reverseUsers: Map<string, number> = new Map();
if (config.users.length === 0) throw new Error("System needs to have at least one user");
if (config.groups.length === 0) throw new Error("System needs to have at least one user group");
for (let i = 1000; i < config.groups.length + 1000; i++) {
const group = config.groups[i - 1000]!;
reverseGroups.set(group, i);
const members: number[] = [];
for (let i = 1000; i < config.users.length + 1000; i++) {
const user = config.users[i - 1000]!;
if (user.groups.some(g => g === group)) {
members.push(i);
}
}
groups.set(i, { groupname: group, gid: i, members });
}
for (let i = 1000; i < config.users.length + 1000; i++) {
const user = config.users[i - 1000]!;
if (user.groups.length === 0) throw new Error("User must belong to at least one user group");
const gid = reverseGroups.get(user.groups[0]!);
if (!gid) throw new Error("User is a member of an undefined group");
const groups: number[] = [];
for (const group of user.groups) {
if (group === "sudoers") continue;
const gid = reverseGroups.get(group);
if (!gid) throw new Error("User is a member of an undefined group");
groups.push(gid);
}
reverseUsers.set(user.username, i);
users.set(i, { username: user.username, uid: i, gid, group: groups, home: resPath(user.home) });
}
const uid = reverseUsers.get(config.general.user);
if (!uid) throw new Error("Tried to initialize termos with an undefined user");
const user = users.get(uid)!;
const state: ShellState = createInitialShellState(fs, users, groups, user);
return new Shell(state);
function resPath(path: string) {
let linkDepth = 0;
const maxDepth = fs.maxSymlinkDepth;
const pathComponents: string[] = path.split("/").filter(c => c.length > 0);
let currentDeviceId: number = 0;
let currentNode: Node = fs.getRoot();
while (pathComponents.length > 0) {
const name = pathComponents.shift()!;
if (name === ".") continue;
if (name === "..") {
if (fs.isMountTarget(NodePointer.of(currentDeviceId, currentNode.inode))) {
const mount = fs.getMountPoint(NodePointer.of(currentDeviceId, currentNode.inode));
if (!mount) {
throw {
type: "FileSystemCorruption",
message: "Mount registry entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
const entries = fs.getNodeEntries(mount);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
continue;
}
if (currentNode.inode === 0) continue;
const entries = fs.getNodeEntries(NodePointer.of(currentDeviceId, currentNode.inode));
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
continue;
}
if (currentNode.type !== NodeType.Directory) {
throw {
type: "NotADirectory",
message: "Not a directory",
timestamp: Date.now(),
inode: currentNode.inode,
nodeType: currentNode.type,
} satisfies NotADirectoryError;
}
const childInode = currentNode.children.get(name);
if (childInode === undefined) {
throw {
type: "NodeNotFound",
message: `${name} not found`,
timestamp: Date.now(),
pointer: NodePointer.of(currentDeviceId, currentNode.inode),
} satisfies NodeNotFoundError;
}
let childPtr = NodePointer.of(currentDeviceId, childInode);
if (fs.isMountPoint(childPtr)) {
const mount = fs.getMountTarget(childPtr)!;
childPtr = mount;
currentDeviceId = mount.device;
}
let child = fs.getNode(childPtr);
if (!child) {
throw {
type: "NodeNotFound",
message: `Node under ${childPtr} not found (probable dangling orphan)`,
timestamp: Date.now(),
pointer: childPtr,
} satisfies NodeNotFoundError;
}
if (child.type === NodeType.Symlink) {
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
const target = child.target;
if (target.startsWith("/")) {
currentDeviceId = 0;
currentNode = fs.getRoot();
} else {
const entries = fs.getNodeEntries(childPtr);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
}
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
continue;
}
currentNode = child;
}
return NodePointer.of(currentDeviceId, currentNode.inode);
}
}
export const Termos = {
getShell,
};
+8 -15
View File
@@ -1,15 +1,8 @@
import { defaultConfig, TermosConfig } from "./config";
let config: TermosConfig = { ...defaultConfig };
namespace Termos {
export function init(config: Partial<TermosConfig>) {
config = { ...defaultConfig, ...config};
console.log("termos initialized");
}
}
const message: string = "Hello, World!";
console.log(message);
export { Termos };
export {
resolvePointer,
resolvePointerRelative,
resolvePointerToCwd,
resolvePointerToHome,
} from "@core/util/path_resolver";
export { Termos } from "./entry";
export { type Shell } from "./shell/index";
-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> {
}
+15 -13
View File
@@ -1,26 +1,28 @@
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);
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);
this.handlers.set(type, set);
const set: Set<Listener> = new Set();
set.add(handler as Listener);
this.Handlers.set(type, set);
}
return (): void => this.off(type, handler);
}
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 {
const listeners = this.handlers.get(type);
const listeners = this.Handlers.get(type);
const wrapper = (payload: TEvents[K]) => {
handler(payload);
@@ -28,18 +30,18 @@ export class EventEmitter<TEvents> {
};
if (listeners) {
listeners.add(wrapper);
listeners.add(wrapper as Listener);
} else {
const set: Set<Function> = new Set();
set.add(wrapper);
this.handlers.set(type, set);
const set: Set<Listener> = new Set();
set.add(wrapper as Listener);
this.Handlers.set(type, set);
}
return (): void => this.off(type, wrapper);
}
public emit<K extends keyof TEvents>(type: K, payload: TEvents[K]): void {
const listeners = this.handlers.get(type);
const listeners = this.Handlers.get(type);
if (listeners) {
for (const listener of [...listeners]) {
+1
View File
@@ -0,0 +1 @@
export { type Shell } from "./shell";
+94 -91
View File
@@ -2,110 +2,84 @@ import type { CommandDescriptor } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result";
import type { ShellState } from "@core/shell_state";
import type { Signal } from "@core/signal";
import { SIGNAL_MAP, type Signal } from "@core/signal";
import type { ShellError, SignalTerminationError } from "@core/util/errors";
import { createImmutableBuffer } from "@core/util/immutable_buffer";
import { concatUint8Arrays, splitUint8Array } from "@termos/util/concat";
import { EventEmitter } from "./event_emitter";
import type { ShellEventMap } from "./shell";
export class Process {
private signalQueue: Signal[] = [];
private signalHandler: ((signal: Signal) => void) | null = null;
private stdoutChunks: Uint8Array[] = [];
private stderrChunks: Uint8Array[] = [];
private settled: boolean = false;
private readonly maxChunkByteSize: number;
private _SignalQueue: Signal[] = [];
private _SignalHandler: ((signal: Signal) => void) | null = null;
private _StdoutChunks: Uint8Array[] = [];
private _StderrChunks: Uint8Array[] = [];
private _Settled: boolean = false;
private _EventEmitter: EventEmitter<ShellEventMap>;
private readonly _MaxChunkByteSize: number;
readonly pid: number;
readonly commandDescriptor: CommandDescriptor;
readonly state: ShellState;
readonly args: string[];
readonly flags: string[];
events: EventEmitter<ShellEventMap>;
readonly PID: number;
readonly Name: string;
readonly CommandDescriptor: CommandDescriptor;
readonly State: ShellState;
readonly Args: string[];
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) {
this.pid = pid;
this.state = state;
this.commandDescriptor = descriptor;
this.flags = flags;
this.args = args;
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, args: string[]) {
this.PID = pid;
this.State = state;
this.Name = descriptor.name;
this.CommandDescriptor = descriptor;
this.Args = args;
// Check if positive later and throw an error if so
this.maxChunkByteSize = 1024;
this.events = new EventEmitter<ShellEventMap>();
}
private concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
const size = arrays.reduce((sum, arr) => sum + arr.length, 0);
const result = new Uint8Array(size);
let offset = 0;
for (const arr of arrays) {
result.set(arr, offset);
offset += arr.length;
}
return result;
}
// Tested
private divideToChunks(data: Uint8Array): Uint8Array[] {
const nChunks: number = Math.ceil(data.length / this.maxChunkByteSize);
const chunks: Uint8Array[] = [];
for (let i = 0; i < nChunks; i++) {
const start = this.maxChunkByteSize * i;
const end = this.maxChunkByteSize * (i + 1);
chunks.push(data.subarray(start, end));
}
return chunks;
this._MaxChunkByteSize = 1024;
this._EventEmitter = new EventEmitter<ShellEventMap>();
}
// WARNING, CHUNKING OUTPUT BREAKS FORMATING
private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void {
if (this.settled) return;
if (this._Settled) return;
if (data.length <= this.maxChunkByteSize) {
if (data.length <= this._MaxChunkByteSize) {
chunks.push(data);
this.events.emit(eventType, { pid: this.pid, data });
this._EventEmitter.emit(eventType, { pid: this.PID, data });
return;
} else {
const arr = this.divideToChunks(data);
const arr = splitUint8Array(data, this._MaxChunkByteSize);
for (const ent of arr) {
chunks.push(ent);
this.events.emit(eventType, { pid: this.pid, data: ent });
this._EventEmitter.emit(eventType, { pid: this.PID, data: ent });
}
}
}
start(): void {
public execute(): void {
const io: CommandIO = {
writeStdout: (data: Uint8Array) => this.writeToOutput(this.stdoutChunks, "stdout", data),
writeStderr: (data: Uint8Array) => this.writeToOutput(this.stderrChunks, "stderr", data),
writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data),
writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data),
getSignal: () => {
const signal: Signal | undefined = this.signalQueue.shift();
const signal: Signal | undefined = this._SignalQueue.shift();
if (signal !== undefined) return Promise.resolve(signal);
const promise = new Promise<Signal>(resolve => {
this.signalHandler = resolve;
this._SignalHandler = resolve;
});
return promise;
},
};
const promise = this.commandDescriptor.fn(io, this.state, this.flags, this.args);
const promise = this.CommandDescriptor.fn(io, this.State, this.Args);
promise
.then(output => {
if (this.settled) return;
if (this._Settled) return;
let result: ResultSuccess | ResultError<ShellError>;
const stdout: Uint8Array = this.concatUint8Arrays(this.stdoutChunks);
const stderr: Uint8Array = this.concatUint8Arrays(this.stderrChunks);
const stdout: Uint8Array = concatUint8Arrays(this._StdoutChunks);
const stderr: Uint8Array = concatUint8Arrays(this._StderrChunks);
if (output.result.type === "success") {
result = createSuccessResult(
this.commandDescriptor.name,
this.CommandDescriptor.name,
0,
createImmutableBuffer(stdout),
createImmutableBuffer(stderr),
@@ -118,57 +92,86 @@ export class Process {
};
}
this.events.emit("result", { pid: this.pid, result, state: output.state });
this.settled = true;
this._EventEmitter.emit("result", { pid: this.PID, result, state: output.state });
this._Settled = true;
})
.catch(error => {
if (this.settled) return;
if (this._Settled) return;
const result: ResultError<ShellError> = createErrorResult(
"GenericError",
"Promised output from command function rejected",
{},
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
this.commandDescriptor.name,
this.CommandDescriptor.name,
undefined,
undefined,
{
name: "Caught error",
message: String(error),
},
);
this.events.emit("result", { pid: this.pid, result, state: this.state });
this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
});
}
sendSignal(signal: Signal): void {
if (this.settled) return;
public sendSignal(signal: Signal): void {
if (this._Settled) return;
if (signal.type === "SIGKILL") {
if (this.signalHandler !== null) {
this.signalHandler(signal);
this.signalHandler = null;
}
this.settled = true;
const result: ResultError<SignalTerminationError> = createErrorResult(
"SignalTermination",
`Process ${this.pid} killed by signal sigkill`,
{ signalNumber: 9, signalName: signal.type },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
this.commandDescriptor.name,
`Process ${this.Name}(${this.PID}) killed by a ${SIGNAL_MAP[signal.type]}(${signal.type})`,
{ signalNumber: signal.type, signalName: SIGNAL_MAP[signal.type] },
this.CommandDescriptor.name,
);
this.events.emit("result", { pid: this.pid, result, state: this.state });
switch (signal.type) {
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:
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;
default:
if (this._SignalHandler !== null) {
this._SignalHandler(signal);
this._SignalHandler = null;
} else {
if (this.signalHandler !== null) {
this.signalHandler(signal);
this.signalHandler = null;
} else {
this.signalQueue.push(signal);
this._SignalQueue.push(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);
}
}
+68
View File
@@ -0,0 +1,68 @@
import type { CommandDescriptor } from "@core/command";
import type { ShellState } from "@core/shell_state";
import { SIGNAL_MAP, type Signal } from "@core/signal";
import { EventEmitter } from "./event_emitter";
import { Process } from "./process";
import type { ShellEventMap } from "./shell";
export class ProcessManager {
private _Processes: Map<number, Process> = new Map();
private _PIDIndex: number = 0;
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
public createProcess(state: ShellState, descriptor: CommandDescriptor, args: string[]): number {
const pid = ++this._PIDIndex;
const process = new Process(pid, state, descriptor, args);
this._Processes.set(pid, process);
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("process", { pid, name: descriptor.name });
process.execute();
return pid;
}
public sendSignal(pid: number, signal: Signal): 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.sendSignal(signal);
}
public kill(pid: number): 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;
}
//Make global signals an enum later
process.sendSignal({ type: SIGNAL_MAP.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);
}
}
+103 -52
View File
@@ -1,59 +1,50 @@
import { createImmutableBuffer } from "@core/util/immutable_buffer";
import { z } from "zod";
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "../core/filesystem/treenode";
import type { IDataStore, IMetaStore, VDiskConfig } from "@core/filesystem/vdisk";
import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
import { NodeType, type DirectoryNode, type FileNode, type Node, type SymlinkNode } from "../core/filesystem/node";
const FileNodeSchema = z.object({
inode: z.number(),
name: z.string(),
mode: z.number(),
parent: z.number(),
owner: z.number(),
group: z.number(),
mtime: z.number(),
ctime: z.number(),
atime: z.number(),
type: z.literal("regular"),
content: z.array(z.number()),
});
/* export function serializeFileSystem(map: ReadonlyMap<number, TreeNode | null>): string {
const DirectoryNodeSchema = z.object({
inode: z.number(),
name: z.string(),
mode: z.number(),
parent: z.number(),
owner: z.number(),
group: z.number(),
mtime: z.number(),
ctime: z.number(),
atime: z.number(),
type: z.literal("directory"),
children: z.array(z.lazy((): any => TreeNodeSchema)),
});
} */
const TreeNodeSchema = z.union([FileNodeSchema, DirectoryNodeSchema]);
export function serializeFileSystem() {}
export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNode> {
export function deserializeFileSystem(json: string): { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] {
const raw = JSON.parse(json);
const validated = TreeNodeSchema.parse(raw);
let index = 0;
const map = new Map<number, TreeNode>();
// prettier-ignore
function parseNode(tree: any, parent: number, store: MemDataStore, map: Map<number, Node>): void { // eslint-disable-line @typescript-eslint/no-explicit-any
if(tree === null || tree.type === undefined) {
const time = Date.now();
const defaultNode: DirectoryNode = {
type: NodeType.Directory,
inode: 0,
link_count: 2,
mode: 0o0555,
owner: 0,
group: 0,
mtime: time,
ctime: time,
atime: time,
children: new Map(),
};
map.set(0, Object.freeze(defaultNode));
return;
}
function parseNode(tree: any, parent: number): void {
if (tree.type === "directory") {
const children: Record<string, number> = {};
if(tree.inode > index) index = tree.inode;
switch(tree.type) {
case "directory": {
const children: Map<string, number> = new Map();
for (const child of tree.children) {
parseNode(child, tree.inode);
children[child.name] = child.inode;
parseNode(child, tree.inode, store, map);
children.set(child.name, child.inode);
}
const directoryNode: DirectoryNode = {
type: TreeNodeType.Directory,
type: NodeType.Directory,
inode: tree.inode,
name: tree.name,
parent,
link_count: tree.link_count,
mode: tree.mode,
owner: tree.owner,
group: tree.group,
@@ -62,27 +53,87 @@ export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNod
atime: tree.atime,
children,
};
if(Object.values(directoryNode).some(e => e === undefined))
throw new Error(`Serialization failed, object contains undefined fields - ${directoryNode}`);
children.set('..', parent);
children.set('.', tree.inode);
map.set(tree.inode, Object.freeze(directoryNode));
} else {
break;
}
case "regular": {
const uuid = crypto.randomUUID();
const fileNode: FileNode = {
type: TreeNodeType.File,
type: NodeType.File,
inode: tree.inode,
name: tree.name,
parent,
mode: tree.mode,
link_count: tree.link_count,
owner: tree.owner,
group: tree.group,
mtime: tree.mtime,
ctime: tree.ctime,
atime: tree.atime,
content: createImmutableBuffer(new Uint8Array()),
content: uuid,
size: tree.size,
};
if(Object.values(fileNode).some(e => e === undefined))
throw new Error(`Serialization failed, object contains undefined fields - ${fileNode}`);
const buff: Uint8Array<ArrayBuffer> = Uint8Array.from(tree.content);
store.put(uuid, new Blob([buff]));
map.set(tree.inode, Object.freeze(fileNode));
break;
}
case "symlink": {
const symlinkNode: SymlinkNode = {
type: NodeType.Symlink,
inode: tree.inode,
mode: tree.mode,
link_count: tree.link_count,
owner: tree.owner,
group: tree.group,
mtime: tree.mtime,
ctime: tree.ctime,
atime: tree.atime,
target: tree.target,
};
if(Object.values(symlinkNode).some(e => e === undefined))
throw new Error(`Serialization failed, object contains undefined fields - ${symlinkNode}`);
map.set(tree.inode, Object.freeze(symlinkNode));
break;
}
default:
throw new Error(`Unknown node type in JSON ${tree.type}`);
}
}
parseNode(validated, validated.inode);
const base: ReadonlyMap<number, TreeNode> = map;
const result: { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] = [];
for (const dev of raw.dev) {
const map = new Map();
const data = new MemDataStore();
const meta = new MemMetaStore();
parseNode(dev.tree, dev.tree.inode, data, map);
return base;
const config: VDiskConfig = {
id: dev.id,
label: `disk-${dev.id}`,
index,
readonly: false,
size: 1024 * 1024 * 1024 * 8, //8 GiB
base: map,
dataC: {
chunkSize: 1024 * 8, //8 KiB
cacheSize: 1024 * 1024 * 64, //64 MiB
cacheTTL: 1000 * 60, // 1 min
},
};
result.push({ dstore: data, mstore: meta, config });
}
return result;
}
+91 -77
View File
@@ -1,110 +1,124 @@
import { COMMAND_REGISTRY } from "@core/command_registry";
import { createErrorResult, createSuccessResult, type Result, type ResultError } from "@core/result";
import { getCurrentSession } from "@core/session_manager";
import { createErrorResult, type Result } from "@core/result";
import { getCurrentSession, type SessionState } from "@core/session_manager";
import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
import type { CommandNotFoundError, ParseError, PermissionDeniedError, ShellError } from "@core/util/errors";
import { SIGNAL_MAP } from "@core/signal";
import type { ShellError } from "@core/util/errors";
import { createImmutableBuffer } from "@core/util/immutable_buffer";
import { parseCommand } from "@core/util/parser";
import { tokenize } 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 _State: Readonly<ShellState>;
private _Session: SessionState;
private _ProcessManager: ProcessManager = new ProcessManager();
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
private _GlobalKeyMap: ReadonlyMap<string, SIGNAL_MAP>;
private constructor(state: ShellState) {
this._state = Object.freeze(state);
public BoundPID: number | null = null;
constructor(state: ShellState) {
this._State = Object.freeze(state);
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("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> {
if (Shell.#instance) {
console.warn("Shell already initialized");
return this.#instance;
}
public async execute(input: string): Promise<void> {
const parsed = tokenize(input);
if (Shell.#promise) return Shell.#promise;
if (!parsed[0]) return;
Shell.#promise = (async () => {
try {
Shell.#instance = new Shell(initialState);
return Shell.#instance;
} finally {
Shell.#promise = null;
}
})();
this._State = withHistory(this._State, input);
const command = COMMAND_REGISTRY.get(parsed[0]);
return Shell.#promise;
}
if (!command) {
const encoded = new TextEncoder().encode(`Command ${parsed[0]} not found`);
public async Execute(input: string): Promise<Result<ShellError>> {
let parsed;
try {
parsed = parseCommand(input);
} catch {
return createErrorResult(
"ParseError",
`Parsing error - ${input}`,
{},
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
"",
) satisfies ResultError<ParseError>;
}
if (parsed.command === "") {
return createSuccessResult(
"",
0,
createImmutableBuffer(new Uint8Array()),
const result = createErrorResult(
"CommandNotFound",
`Command ${parsed[0]} not found`,
{ command: parsed[0] },
parsed[0],
createImmutableBuffer(encoded),
createImmutableBuffer(new Uint8Array()),
);
this._State = withExitCode(this._State, result.error.exitCode);
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
return;
}
this._state = withHistory(this._state, input);
const command = COMMAND_REGISTRY.get(parsed.command);
if (!command)
return createErrorResult(
"CommandNotFound",
`Command ${parsed.command} not found`,
{ command: parsed.command },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
parsed.command,
) satisfies ResultError<CommandNotFoundError>;
if (command.requiresRoot && getCurrentSession(this._state).user.uid != 0) {
return createErrorResult(
if (command.requiresRoot && getCurrentSession(this._State).user.uid != 0) {
const result = createErrorResult(
"PermissionDenied",
`Permission Denied`,
{ resource: `Execution of the ${command.name} command` },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
parsed.command,
) satisfies ResultError<PermissionDeniedError>;
parsed[0],
);
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;
parsed.shift();
if (out.result.type === "error") {
this._state = withExitCode(this._state, out.result.error.exitCode);
const pid = this._ProcessManager.createProcess(this._State, command, parsed);
this.BoundPID = pid;
}
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: SIGNAL_MAP.INPUT, payload: input });
}
}
return out.result;
}
public get State(): Readonly<ShellState> {
return this._state;
return this._State;
}
public static get Instance(): Shell | undefined {
if (!Shell.#instance) {
console.error("Shell has not been initialised yet. Call `await Shell.init()` first.");
return;
public get Session(): Readonly<SessionState> {
return this._Session;
}
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);
}
}
-73
View File
@@ -1,73 +0,0 @@
import { MD5 } from "./hash";
//INDEXED DB IS SO FUCKING DOGSHIT ITS INSANE
//TODO: load IDB db name from config;
export async function initializeIDB() {
const request = indexedDB.open("cache");
request.onerror = e => {
throw new Error(`Failed to open the IDB during the init - ${request.error}`);
};
request.onsuccess = e => {
const DB = request.result;
const STORE = DB.createObjectStore("fs", { autoIncrement: true });
STORE.createIndex("json", "json");
STORE.createIndex("checksum", "checksum");
};
}
export async function writeFileSystemCache(cache: string, checksum: string) {
if (cache.length === 0 || checksum.length === 0) {
throw new Error(`Cache value or the checksum value cannot be empty!`);
}
if (!isChecksumMatching(cache, checksum))
throw new Error("The cache value checksum does not match the provided checksum");
const request = indexedDB.open("cache");
request.onerror = e => {
throw new Error(`Failed to open the IDB during the init - ${request.error}`);
};
request.onsuccess = e => {
const DB = request.result;
const T = DB.transaction(["cache"], "readwrite");
const STOREFS = T.objectStore("fs");
const STORECK = T.objectStore("fs");
const RFS = STOREFS.add(cache);
//const CFS =
};
}
export async function fetchFileSystemCache(): Promise<{ cache: string; checksum: string }> {
const request = indexedDB.open("cache");
request.onerror = e => {
throw new Error(`Failed to open the IDB - ${request.error}`);
};
request.onsuccess = e => {
const DB = request.result;
const T = DB.transaction(["cache"], "readonly");
const STORE = T.objectStore("fs");
const R = STORE.get("1");
R.onerror = e => {
throw new Error(`Some IDB error - ${R.error}`);
};
R.onsuccess = e => {
console.log(R.result.json, R.result.checksum);
};
};
}
function isChecksumMatching(json: string, checksum: string): boolean {
const resourceChksm = MD5.hash(json);
return resourceChksm === checksum;
}
+26
View File
@@ -0,0 +1,26 @@
export function concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
const size = arrays.reduce((sum, arr) => sum + arr.length, 0);
const array = new Uint8Array(size);
let offset = 0;
for (const arr of arrays) {
array.set(arr, offset);
offset += arr.length;
}
return array;
}
export function splitUint8Array(data: Uint8Array, size: number): Uint8Array[] {
const nChunks: number = Math.ceil(data.length / size);
const chunks: Uint8Array[] = [];
for (let i = 0; i < nChunks; i++) {
const start = size * i;
const end = size * (i + 1);
chunks.push(data.subarray(start, end));
}
return chunks;
}
+11
View File
@@ -0,0 +1,11 @@
export function convertToUnit(bytes: number, decimalPoint?: number, pow: 1024 | 1000 = 1024): string {
if (!+bytes) return "0";
const k: number = pow;
const dp: number = decimalPoint ? (decimalPoint < 0 ? 0 : decimalPoint) : 1;
const units: string[] = ["", "K", "M", "G", "T", "P"];
const i: number = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(dp)}${units[i]}`;
}
+3 -3
View File
@@ -52,7 +52,7 @@ export class MD5 {
return (b & d) | (c & ~d);
}
let AA = A,
const AA = A,
BB = B,
CC = C,
DD = D;
@@ -129,7 +129,7 @@ export class MD5 {
return new Uint8Array([...out, ...zeroArray, ...lengthBytes]);
}
private static sliceToBlocks(input: Uint8Array): number[][] {
/* private static sliceToBlocks(input: Uint8Array): number[][] {
const blocks: number[][] = [];
for (let i = 0; i < input.length; i += 64) {
@@ -138,7 +138,7 @@ export class MD5 {
}
return blocks;
}
} */
private static sliceToWords(block: Uint8Array): number[] {
const words: number[] = new Array<number>(16);
+112
View File
@@ -0,0 +1,112 @@
export class Posix {
private static readonly CharTable = {
// Space and punctuation (32-47)
" ": 32,
"!": 33,
'"': 34,
"#": 35,
$: 36,
"%": 37,
"&": 38,
"'": 39,
"(": 40,
")": 41,
"*": 42,
"+": 43,
",": 44,
"-": 45,
".": 46,
"/": 47,
// Numbers 0-9 (48-57)
"0": 48,
"1": 49,
"2": 50,
"3": 51,
"4": 52,
"5": 53,
"6": 54,
"7": 55,
"8": 56,
"9": 57,
// More punctuation (58-64)
":": 58,
";": 59,
"<": 60,
"=": 61,
">": 62,
"?": 63,
"@": 64,
// LETTERS - INTERLEAVED AaBbCc... (65-116)
A: 65,
a: 66,
B: 67,
b: 68,
C: 69,
c: 70,
D: 71,
d: 72,
E: 73,
e: 74,
F: 75,
f: 76,
G: 77,
g: 78,
H: 79,
h: 80,
I: 81,
i: 82,
J: 83,
j: 84,
K: 85,
k: 86,
L: 87,
l: 88,
M: 89,
m: 90,
N: 91,
n: 92,
O: 93,
o: 94,
P: 95,
p: 96,
Q: 97,
q: 98,
R: 99,
r: 100,
S: 101,
s: 102,
T: 103,
t: 104,
U: 105,
u: 106,
V: 107,
v: 108,
W: 109,
w: 110,
X: 111,
x: 112,
Y: 113,
y: 114,
Z: 115,
z: 116,
// Specials after letters (now 117-126)
"[": 117,
"\\": 118,
"]": 119,
"^": 120,
_: 121,
"`": 122,
"{": 123,
"|": 124,
"}": 125,
"~": 126,
} as const;
public static GetCharWeight(char: string): number {
return this.CharTable[char as keyof typeof this.CharTable];
}
}
+73 -30
View File
@@ -1,61 +1,104 @@
import type { FileSystem } from "@core/filesystem/filesystem";
import { TreeNodeType } from "@core/filesystem/treenode";
export function printTree(fs: FileSystem, root: number): string {
const rootNode = fs.getNode(root);
if (rootNode === undefined) return "";
const lines: string[] = [];
lines.push(rootNode.name);
import { NodePointer, NodeType, type SymlinkNode } from "@core/filesystem/node";
type Frame = {
inode: number;
ptr: NodePointer;
name: string;
prefix: string;
isLast: boolean;
};
const stack: Frame[] = [];
function getSortedChildren(fs: FileSystem, ptr: NodePointer): Array<{ name: string; ptr: NodePointer }> {
const node = fs.getNode(ptr);
if (!node || node.type !== NodeType.Directory) return [];
const getSorterChildren = (inode: number): number[] => {
const node = fs.getNode(inode);
if (!node || node.type !== TreeNodeType.Directory) return [];
const entries = Object.entries(node.children);
const entries = Array.from(node.children.entries());
entries.sort(([a], [b]) => a.localeCompare(b));
return entries.map(([, childInode]) => childInode) as number[];
};
const rootChildren = getSorterChildren(root);
return entries.map(([name, inode]) => ({
name,
ptr: NodePointer.of(ptr.device, inode),
}));
}
function mountSuffix(fs: FileSystem, ptr: NodePointer): string {
if (!fs.isMountPoint(ptr)) return "";
const target = fs.getMountPoint(ptr);
if (!target) return " -> [mount: target missing]";
return ` -> ${target.toString()}`;
}
function symlinkSuffix(node: { type: NodeType; target?: string }): string {
return node.type === NodeType.Symlink ? ` -> ${(node as SymlinkNode).target}` : "";
}
export function printTree(fs: FileSystem, root: NodePointer, rootLabel = "/"): string {
const rootNode = fs.getNode(root);
if (rootNode === undefined) return "";
const lines: string[] = [];
const rootSuffix = mountSuffix(fs, root) + symlinkSuffix(rootNode);
lines.push(`${rootLabel} ${root.toString()}${rootSuffix}`);
const stack: Frame[] = [];
const rootChildren = getSortedChildren(fs, root);
for (let i = rootChildren.length - 1; i >= 0; i--) {
const childInode: number = rootChildren[i] as number;
const child = rootChildren[i]!;
if (child.name.startsWith(".")) continue;
const isLast = i === rootChildren.length - 1;
stack.push({ inode: childInode, prefix: "", isLast });
stack.push({ ptr: child.ptr, name: child.name, prefix: "", isLast });
}
while (stack.length > 0) {
const frame = stack.pop()!;
const node = fs.getNode(frame.inode);
const node = fs.getNode(frame.ptr);
if (!node) continue;
const name = node.name;
const connector = frame.isLast ? "└── " : "├── ";
lines.push(frame.prefix + connector + name);
const suffix = mountSuffix(fs, frame.ptr) + symlinkSuffix(node);
lines.push(`${frame.prefix}${connector}${frame.name} ${frame.ptr.toString()}${suffix}`);
if (node.type === TreeNodeType.Directory) {
if (node.type === NodeType.Directory && !fs.isMountPoint(frame.ptr)) {
const childPrefix = frame.prefix + (frame.isLast ? " " : "│ ");
const children = getSorterChildren(frame.inode);
const children = getSortedChildren(fs, frame.ptr);
for (let i = children.length - 1; i >= 0; i--) {
const childInode = children[i] as number;
const child = children[i]!;
if (child.name.startsWith(".")) continue;
const childIsLast = i === children.length - 1;
stack.push({ inode: childInode, prefix: childPrefix, isLast: childIsLast });
stack.push({
ptr: child.ptr,
name: child.name,
prefix: childPrefix,
isLast: childIsLast,
});
}
}
}
return lines.join("\n");
}
export function printDeviceTree(fs: FileSystem, deviceId: number, rootLabel?: string): string {
return printTree(fs, NodePointer.of(deviceId, 0), rootLabel ?? `disk-${deviceId}:/`);
}
export function printAllDeviceTrees(fs: FileSystem, deviceIds?: number[]): string {
const ids =
deviceIds ??
(() => {
const mgr = (fs as unknown as { _VDiskManager?: { listID(): number[] } })._VDiskManager;
if (!mgr) {
throw new Error(
"printAllDeviceTrees: FileSystem has no public device list — pass deviceIds explicitly",
);
}
return mgr.listID();
})();
return ids
.slice()
.sort((a, b) => a - b)
.map(id => printDeviceTree(fs, id))
.join("\n\n");
}
-113
View File
@@ -1,113 +0,0 @@
import { descriptor as cd } from "@core/commands/cd";
import type { ResultError, ResultSuccess } from "@core/result";
import type { UserInfo } from "@core/session_manager";
import { getCurrentSession } from "@core/session_manager";
import { createInitialShellState, withCwd, type ShellState } from "@core/shell_state";
import type { PathResolutionError } from "@core/util/errors";
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
import { expect, test } from "vitest";
const testTree: FixtureNode = {
inode: 0,
name: "root",
type: "Dir",
children: [
{
inode: 1,
name: "hello.txt",
type: "File",
content: "Goodbye World!",
children: [],
},
{
inode: 2,
name: "sub",
type: "Dir",
children: [
{
inode: 3,
name: "world.txt",
type: "File",
content: "Goodbye!",
children: [],
},
{
inode: 4,
name: "bye",
type: "Dir",
children: [],
},
],
},
],
};
const fs = buildTestFS(testTree);
const users: Map<number, UserInfo> = new Map();
const user: UserInfo = {
username: "root",
uid: 0,
gid: 0,
group: [0],
home: 0,
};
users.set(0, user);
const state: ShellState = createInitialShellState(fs, users, user);
test("changes cwd to home", () => {
let newState = withCwd(state, 2);
const output = cd.fn(newState, [], []);
newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultSuccess).exitCode).toBe(0);
expect(session.cwd).toBe(0);
expect(session.pwd).toBe(2);
});
test("changes cwd to pwd", () => {
let newState = withCwd(state, 2);
const output = cd.fn(newState, [], ["-"]);
newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultSuccess).exitCode).toBe(0);
expect(session.cwd).toBe(0);
expect(session.pwd).toBe(2);
});
test("changes cwd to 4", () => {
const output = cd.fn(state, [], ["/sub/bye"]);
const newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultSuccess).exitCode).toBe(0);
expect(session.cwd).toBe(4);
expect(session.pwd).toBe(0);
});
test("returns an error result (tried to enter a non existent location)", () => {
const output = cd.fn(state, [], ["/not/real"]);
const newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultError<PathResolutionError>).error.exitCode).toBe(64);
expect(session.cwd).toBe(0);
expect(session.pwd).toBe(0);
});
test("returns an error result (tried to enter a file)", () => {
const output = cd.fn(state, [], ["/hello.txt"]);
const newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultError<PathResolutionError>).error.exitCode).toBe(64);
expect(session.cwd).toBe(0);
expect(session.pwd).toBe(0);
});
-64
View File
@@ -1,64 +0,0 @@
import { descriptor as echo } from "@core/commands/echo";
import type { ResultSuccess } from "@core/result";
import type { UserInfo } from "@core/session_manager";
import { createInitialShellState, type ShellState } from "@core/shell_state";
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
import { expect, test } from "vitest";
const testTree: FixtureNode = {
inode: 0,
name: "root",
type: "Dir",
children: [
{
inode: 1,
name: "hello.txt",
type: "File",
content: "Goodbye World!",
children: [],
},
{
inode: 2,
name: "sub",
type: "Dir",
children: [
{
inode: 3,
name: "world.txt",
type: "File",
content: "Goodbye!",
children: [],
},
{
inode: 4,
name: "bye",
type: "Dir",
children: [],
},
],
},
],
};
const fs = buildTestFS(testTree);
const users: Map<number, UserInfo> = new Map();
const user: UserInfo = {
username: "root",
uid: 0,
gid: 0,
group: [0],
home: 0,
};
users.set(0, user);
const state: ShellState = createInitialShellState(fs, users, user);
test("returns a Result of type success", () => {
const output = echo.fn(state, [], ["hello", "world"]);
const string = new TextDecoder().decode(output.result.stdout.toArray());
expect(output.result.type).toBe("success");
expect((output.result as ResultSuccess).exitCode).toBe(0);
expect(string).toBe("hello world");
});
File diff suppressed because it is too large Load Diff
+628 -59
View File
@@ -1,73 +1,642 @@
import { resolveInode, resolvePath } from "@core/util/path_resolver";
// @tests/core/util/path_resolver.test.ts (adjust)
import { NodePointer } from "@core/filesystem/node";
import { resolvePath } from "@core/util/path_resolver";
import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers";
import { buildTestFS } from "@tests/helpers/filesystems_fixture";
import { depth7Tree } from "@tests/helpers/tree_fixture";
import { describe, expect, test } from "vitest";
import { makeFS, makeShellState, makeTree, makeUser } from "@tests/helpers/filesystems_fixture";
import { describe, expect, it } from "vitest";
const fs = buildTestFS(depth7Tree);
// ============================================================================
// Path normalization
// ============================================================================
describe("resolvePath", () => {
test("returns an inode from an absolute path", () => {
const path = "/d1/d2/d3/d4/";
const result = resolvePath(fs, 1, path);
expect(result).toBeDefined();
expect(fs.getNode(result as number)!.name).toBe("d4");
describe("resolvePath — path normalization", () => {
/**
* `/` is the root of device 0; no traversal is needed.
*/
it("resolves '/' to the root of device 0", async () => {
const fs = await makeFS([makeTree().build()]);
expect(resolvePath(makeShellState(fs), "/")).toEqual({ device_id: 0, inode: 0 });
});
test("returns an inode from a relative path", () => {
const path = "./d2/d3/d4/";
const result = resolvePath(fs, 1, path);
expect(result).toBeDefined();
expect(fs.getNode(result as number)!.name).toBe("d4");
/**
* Redundant leading slashes are stripped by the normalizer.
*/
it("resolves '/', '//', and '///' identically", async () => {
const fs = await makeFS([makeTree().build()]);
const state = makeShellState(fs);
for (const p of ["/", "//", "///"]) {
expect(resolvePath(state, p)).toEqual({ device_id: 0, inode: 0 });
}
});
test("returns an inode from a relative parent path", () => {
const path = "../d1/d2/d3/d4/";
const result = resolvePath(fs, 1, path);
expect(result).toBeDefined();
expect(fs.getNode(result as number)!.name).toBe("d4");
});
test("returns inode 0", () => {
const path = "/";
const result = resolvePath(fs, 1, path);
expect(result).toBeDefined();
expect(result).toBe(0);
expect(fs.getNode(result as number)!.name).toBe("root");
});
test("returns inode 1 (cwd)", () => {
const path = "";
const result = resolvePath(fs, 1, path);
expect(result).toBeDefined();
expect(result).toBe(1);
expect(fs.getNode(result as number)!.name).toBe("d1");
});
test("throws because of a nonexistent path", () => {
expectNodeNotFoundError(() => resolvePath(fs, 1, "/d3"));
});
test("throws because of file path component", () => {
expectNotADirectoryError(() => resolvePath(fs, 6, "./deep_file.txt/d8"));
});
test("throws because of a nonexistent cwd inode (technicaly should never happen)", () => {
expectNodeNotFoundError(() => resolvePath(fs, 69, "/d3"));
/**
* Empty path returns the current working directory without traversal.
*/
it("resolves an empty string to the current working directory", async () => {
const t = makeTree();
const work = t.addDir(0, "work");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: NodePointer.of(0, work) });
expect(resolvePath(state, "")).toEqual({ device_id: 0, inode: work });
});
});
describe("resolveInode", () => {
test("returns an the path from the d4 node", () => {
expect(resolveInode(fs, 4)).toBe("/d1/d2/d3/d4");
// ============================================================================
// Absolute paths
// ============================================================================
describe("resolvePath — absolute paths", () => {
/**
* Single-component absolute path resolves to the child's pointer.
*/
it("resolves '/name' to the child node of root", async () => {
const t = makeTree();
const foo = t.addFile(0, "foo");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/foo")).toEqual({ device_id: 0, inode: foo });
});
test("returns an empty string from a non existent inode", () => {
expect(resolveInode(fs, 999)).toBe("");
/**
* Nested paths traverse each directory in turn.
*/
it("resolves a nested path '/a/b' to the final child", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
const b = t.addFile(a, "b");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 0, inode: b });
});
/**
* Deeper paths traverse more levels.
*/
it("resolves a deep path '/a/b/c/d' to the final child", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
const b = t.addDir(a, "b");
const c = t.addDir(b, "c");
const d = t.addFile(c, "d");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/a/b/c/d")).toEqual({ device_id: 0, inode: d });
});
/**
* Trailing slash is stripped and resolves the same as without it.
*/
it("resolves '/a/b/' to the same pointer as '/a/b'", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
t.addFile(a, "b");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs);
expect(resolvePath(state, "/a/b/")).toEqual(resolvePath(state, "/a/b"));
});
/**
* Missing top-level component raises a typed NodeNotFound.
*/
it("throws NodeNotFound when the first component does not exist", async () => {
const fs = await makeFS([makeTree().build()]);
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "/missing"));
});
/**
* Missing intermediate component raises a typed NodeNotFound.
*/
it("throws NodeNotFound when an intermediate component does not exist", async () => {
const t = makeTree();
t.addDir(0, "a");
const fs = await makeFS([t.build()]);
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "/a/missing/b"));
});
/**
* Descending through a file at a non-final position is rejected with
* NotADirectory (this one works — the isFile check fires because `a` is
* not the last component).
*/
it("throws NotADirectory when traversing through a file at a non-final position", async () => {
const t = makeTree();
t.addFile(0, "a");
const fs = await makeFS([t.build()]);
await expectNotADirectoryError(() => resolvePath(makeShellState(fs), "/a/b/c"));
});
/**
* EXPECTED-TO-FAIL: descending through a file at the final position should
* also throw NotADirectory. Current implementation skips the isFile check
* on the last iteration and then crashes on `(file as Directory).children`.
*/
it("should throw NotADirectory when descending through a file at the final position", async () => {
const t = makeTree();
t.addFile(0, "a");
const fs = await makeFS([t.build()]);
await expectNotADirectoryError(() => resolvePath(makeShellState(fs), "/a/b"));
});
});
// ============================================================================
// Relative paths
// ============================================================================
describe("resolvePath — relative paths", () => {
/**
* A single relative component resolves against cwd.
*/
it("resolves a relative path from a device-0 cwd", async () => {
const t = makeTree();
const work = t.addDir(0, "work");
const file = t.addFile(work, "file");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: NodePointer.of(0, work) });
expect(resolvePath(state, "file")).toEqual({ device_id: 0, inode: file });
});
/**
* Multi-component relative paths traverse from cwd.
*/
it("resolves a multi-component relative path from cwd", async () => {
const t = makeTree();
const work = t.addDir(0, "work");
const sub = t.addDir(work, "sub");
const leaf = t.addFile(sub, "leaf");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: NodePointer.of(0, work) });
expect(resolvePath(state, "sub/leaf")).toEqual({ device_id: 0, inode: leaf });
});
/**
* Missing relative component raises a typed NodeNotFound.
*/
it("throws NodeNotFound for a missing relative component", async () => {
const fs = await makeFS([makeTree().build()]);
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "nope"));
});
});
// ============================================================================
// ~ expansion
// ============================================================================
describe("resolvePath — '~' expansion", () => {
/**
* `~` expands to the user's home directory (home on device 0).
*/
it("expands '~' to the user's home directory", async () => {
const t = makeTree();
const home = t.addDir(0, "home");
const fs = await makeFS([t.build()]);
const user = makeUser(NodePointer.of(0, home));
const state = makeShellState(fs, { user });
expect(resolvePath(state, "~")).toEqual({ device_id: 0, inode: home });
});
/**
* `~/name` expands home first, then resolves `name` beneath it.
*/
it("expands '~/name' to a child of home", async () => {
const t = makeTree();
const home = t.addDir(0, "home");
const file = t.addFile(home, "file");
const fs = await makeFS([t.build()]);
const user = makeUser(NodePointer.of(0, home));
const state = makeShellState(fs, { user });
expect(resolvePath(state, "~/file")).toEqual({ device_id: 0, inode: file });
});
/**
* EXPECTED-TO-FAIL: `~` expansion never touches `currentVD`, so a home on
* device 1 resolves the first component but then reads subsequent children
* from device 0 — usually crashing on a missing inode.
*/
it("should resolve '~/file' when home lives on device 1", async () => {
const t0 = makeTree();
const t1 = makeTree();
const home = t1.addDir(0, "home");
const file = t1.addFile(home, "file");
const fs = await makeFS([t0.build(), t1.build()]);
const user = makeUser(NodePointer.of(1, home));
const state = makeShellState(fs, { user });
expect(resolvePath(state, "~/file")).toEqual({ device_id: 1, inode: file });
});
});
// ============================================================================
// Symlink resolution
// ============================================================================
describe("resolvePath — symlink resolution", () => {
/**
* Absolute symlink targets resolve from device 0's root.
*/
it("follows an absolute symlink target", async () => {
const t = makeTree();
const real = t.addDir(0, "real");
const leaf = t.addFile(real, "leaf");
t.addSymlink(0, "link", "/real/leaf");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 0, inode: leaf });
});
});
// ============================================================================
// Mount points
// ============================================================================
describe("resolvePath — mount points", () => {
/**
* EXPECTED-TO-FAIL: mount redirect must fire on the child before descent.
* `/mnt` alone should return the mounted device's root, not the mountpoint
* directory on the parent device.
*/
it("should resolve '/mnt' to the mounted device's root", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
expect(resolvePath(makeShellState(fs), "/mnt")).toEqual({ device_id: 1, inode: 0 });
});
/**
* EXPECTED-TO-FAIL: `/mnt/file` should descend through the mount and land
* on `/file` on device 1 — the trailing component must not be consumed by
* the redirect.
*/
it("should resolve '/mnt/file' to '/file' on the mounted device", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const file = t1.addFile(0, "file");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
expect(resolvePath(makeShellState(fs), "/mnt/file")).toEqual({ device_id: 1, inode: file });
});
/**
* EXPECTED-TO-FAIL: deep paths through a mount must traverse the mounted
* device for every subsequent component.
*/
it("should resolve '/mnt/sub/leaf' to '/sub/leaf' on the mounted device", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
});
/**
* A non-mountpoint directory resolves to itself on the parent device —
* `/a` is not a mount, so no redirect.
*/
it("resolves a non-mountpoint directory to itself on the parent device", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a"); // /a = device 0:1 (not a mountpoint)
const mnt = t0.addDir(0, "mnt"); // /mnt = device 0:2 (the mountpoint)
const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(
NodePointer.of(0, mnt), // "0:2" — the mountpoint
NodePointer.of(1, 0),
);
const state = makeShellState(fs);
// /a is not a mountpoint → resolves to itself on device 0
expect(resolvePath(state, "/a")).toEqual({ device_id: 0, inode: a });
// /mnt IS a mountpoint → redirects to device 1's root
// (this is already covered by the /mnt tests; include for contrast or drop)
expect(resolvePath(state, "/mnt")).toEqual({ device_id: 1, inode: 0 });
});
/**
* EXPECTED-TO-FAIL: nested mount at `/a/b` should redirect to dev1's sub.
*/
it("should resolve '/a/b' (nested mount) to the mounted device's sub", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a");
const b = t0.addDir(a, "b");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(NodePointer.of(0, b), NodePointer.of(1, sub));
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 1, inode: sub });
});
/**
* EXPECTED-TO-FAIL: continuation of the nested case — `/a/b/leaf` should
* land on dev1's leaf through the mounted sub.
*/
it("should resolve '/a/b/leaf' through a nested mount", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a");
const b = t0.addDir(a, "b");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(NodePointer.of(0, b), NodePointer.of(1, sub));
expect(resolvePath(makeShellState(fs), "/a/b/leaf")).toEqual({ device_id: 1, inode: leaf });
});
/**
* EXPECTED-TO-FAIL: two independent mounts must redirect independently.
*/
it("should resolve multiple independent mounts", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const other = t0.addDir(0, "other");
const t1 = makeTree();
const file = t1.addFile(0, "file");
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
fs.mount(NodePointer.of(0, other), NodePointer.of(1, sub));
const state = makeShellState(fs);
expect(resolvePath(state, "/mnt/file")).toEqual({ device_id: 1, inode: file });
expect(resolvePath(state, "/other/leaf")).toEqual({ device_id: 1, inode: leaf });
});
});
// ============================================================================
// Symlinks across mount points
// ============================================================================
describe("resolvePath — symlinks across mount points", () => {
/**
* EXPECTED-TO-FAIL: symlink whose target lands on another device must
* return the target's device id in the result. Without threading, the loop
* terminates with currentNode from dev1 but currentVD still 0.
*/
it("should thread the target's device into currentVD after a symlink→mount hop", async () => {
const t0 = makeTree();
t0.addSymlink(0, "link", "/mnt");
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 1, inode: 0 });
});
/**
* EXPECTED-TO-FAIL: full traversal through the symlink and across the
* mount. Verifies not only the final pointer is right, but that the loop
* can continue descending on the mounted device.
*/
it("should resolve through a symlink→mount hop and continue on the mounted device", async () => {
const t0 = makeTree();
t0.addSymlink(0, "link", "/mnt");
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const file = t1.addFile(0, "file");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
expect(resolvePath(makeShellState(fs), "/link/file")).toEqual({ device_id: 1, inode: file });
});
});
// ============================================================================
// Integration
// ============================================================================
describe("resolvePath — integration", () => {
/**
* Full traversal across multiple levels with a file terminus.
*/
it("resolves a multi-level path through directories to a file", async () => {
const t = makeTree();
const varInode = t.addDir(0, "var");
const logInode = t.addDir(varInode, "log");
const appLog = t.addFile(logInode, "app.log");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/var/log/app.log")).toEqual({ device_id: 0, inode: appLog });
});
});
// ============================================================================
// Known bugs — each test asserts *current* behavior and goes red on the fix.
// ============================================================================
describe("resolvePath — known bugs", () => {
/**
* BUG: symlink depth overflow throws a raw `Error`, not a typed error.
* Same setup as above; asserts the thrown object isn't a discriminated
* union member (no `type` field).
*
* Fix: throw a typed `SymlinkLoopError` (or similar) from `errors.ts`.
*/
it("BUG: symlink depth overflow throws a raw Error, not a typed one", async () => {
const t = makeTree();
const sNames = Array.from({ length: 41 }, (_, i) => `s${i + 1}`);
t.addFile(0, "target");
for (let i = 0; i < 40; i++) {
t.addSymlink(0, sNames[i]!, `/${sNames[i + 1]}`);
}
t.addSymlink(0, sNames[40]!, "/target");
const fs = await makeFS([t.build()]);
let thrown: unknown = undefined;
try {
resolvePath(makeShellState(fs), "/s1");
} catch (e) {
thrown = e;
}
expect(thrown).toBeInstanceOf(Error);
expect(thrown).not.toHaveProperty("type");
// ^ BUG: no `type` discriminant. Correct: typed (e.g. SymlinkLoop).
});
});
describe("resolvePath — '..' across mount boundaries", () => {
/**
* BASIC CASE. Mount `/mnt` (device 0) → device 1's root. From inside the
* mount (at `1:0`), `..` must exit through the reverse mount index to
* `/mnt`'s parent (`/`) — not stay put via the `inode === 0` shortcut.
*
* This is the direct fix target: the `..` branch must check
* `getMountSource(currentPtr)` *before* the `inode === 0` shortcut.
*/
it("'..' from a mount root returns to the mountpoint's parent", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
const atMountedRoot = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
});
/**
* NON-ROOT MOUNTPOINT. Mount `/home/user/mnt` → device 1's root. `..` from
* the mounted root must land on `/home/user` (device 0), *not* `/`.
* Catches a fix that hardcodes "go to root on mount exit".
*/
it("'..' from a non-root mount returns to the mountpoint's immediate parent", async () => {
const t0 = makeTree();
const home = t0.addDir(0, "home");
const user = t0.addDir(home, "user");
const mnt = t0.addDir(user, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
const atMountedRoot = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: user });
});
/**
* INSIDE-MOUNT `..`. A subdirectory of the mounted device is *not* the
* mount root, so `..` from `1:sub` must stay inside device 1 (regular
* reverse-index walk), not exit the mount. Catches a fix that exits the
* mount on every `..` inside the mounted device instead of only at its
* root.
*/
it("'..' from inside a mount (not at its root) stays inside the mount", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const fs = await makeFS([t0.build(), t1.build()]);
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
const atSub = makeShellState(fs, { cwd: NodePointer.of(1, sub) });
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
});
/**
* MULTI-STEP `..`. From `/mnt/sub/leaf`, three consecutive `..` should
* produce `/mnt/sub` → `/mnt` → `/`. Exercises both the in-mount walk and
* the final mount exit in one flow. Catches a fix that only handles the
* "already at mount root" case but breaks when coming from deeper.
*/
it("multi-step '..' walks from deep inside a mount out to the parent device", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
// Sanity: full descent lands at `1:leaf`
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
// One `..` up: /mnt/sub
const atLeaf = makeShellState(fs, { cwd: NodePointer.of(1, leaf) });
expect(resolvePath(atLeaf, "..")).toEqual({ device_id: 1, inode: sub });
// Another `..`: /mnt's content = dev1 root
const atSub = makeShellState(fs, { cwd: NodePointer.of(1, sub) });
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
// Final `..`: exit the mount → /
const atMountedRoot = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
});
/**
* INDEPENDENT MOUNTS AT DIFFERENT DEPTHS. Mount A at `/a` (dev0 → dev1)
* and Mount B at `/b/nested` (dev0 → dev2). `..` from dev1's root must go
* to `/` (parent of `/a`), while `..` from dev2's root must go to `/b`
* (parent of `/b/nested`).
*
* Catches a fix that collapses the reverse index to a single entry — e.g.,
* if `getMountSource` returns the *first* mount's mountpoint for any
* target, or if `mount()` overwrites the wrong entry.
*/
it("'..' from different mounts returns to each mountpoint's own parent", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a");
const b = t0.addDir(0, "b");
const nested = t0.addDir(b, "nested");
const fs = await makeFS([t0.build(), makeTree().build(), makeTree().build()]);
await fs.mount(NodePointer.of(0, a), NodePointer.of(1, 0)); // /a → dev1
await fs.mount(NodePointer.of(0, nested), NodePointer.of(2, 0)); // /b/nested → dev2
// `..` from dev1's root → parent of `/a` = `/`
const atDev1Root = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
// `..` from dev2's root → parent of `/b/nested` = `/b`
const atDev2Root = makeShellState(fs, { cwd: NodePointer.of(2, 0) });
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 0, inode: b });
});
/**
* MOUNT NESTED IN A MOUNTED DEVICE'S TREE. The most realistic cross-device
* scenario:
*
* dev0: /mnt (0:1)
* dev1: / (1:0)
* /b (1:2) ← mountpoint of B
* dev2: / (2:0)
*
* Mount A: 0:1 → 1:0 (/mnt shows dev1)
* Mount B: 1:2 → 2:0 (/mnt/b shows dev2)
*
* From `/mnt/b` (dev2 root), `..` must exit B's mount to `/mnt/b`'s parent
* in the *mounted* device 1 (`1:0`), not skip straight to device 0. A
* second `..` then exits A's mount to `/`.
*
* This is the true "chained mount exit" case. Each `..` handles exactly
* one mount; the reverse index for `1:2` (B's mountpoint) lands on `1:0`
* (dev1 root), which is itself a mount target of A. The second `..` then
* exits A. Both steps go through the same `getMountSource` branch.
*/
it("'..' walks out of a mount nested inside another mount's device tree", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const b = t1.addDir(0, "b");
const fs = await makeFS([t0.build(), t1.build(), makeTree().build()]);
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0)); // /mnt → dev1
await fs.mount(NodePointer.of(1, b), NodePointer.of(2, 0)); // /mnt/b → dev2
// Sanity: /mnt/b resolves to dev2 root
expect(resolvePath(makeShellState(fs), "/mnt/b")).toEqual({ device_id: 2, inode: 0 });
// `..` from dev2 root → exit B's mount → parent of `1:b` = `1:0` (dev1 root)
const atDev2Root = makeShellState(fs, { cwd: NodePointer.of(2, 0) });
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 1, inode: 0 });
// `..` from dev1 root → exit A's mount → parent of `0:mnt` = `/`
const atDev1Root = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
});
/**
* ROUND TRIP. `cd /mnt`, `cd ..`, `cd mnt` should land back at `{1:0}`.
* Catches a fix that mutates mount state (e.g., a stale `currentDeviceId`
* that leaks across calls) or that resolves `/mnt` differently after a
* `..` exit.
*/
it("entering and exiting a mount via resolvePath round-trips", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
// Start at /, enter /mnt
const fromRoot = makeShellState(fs);
expect(resolvePath(fromRoot, "/mnt")).toEqual({ device_id: 1, inode: 0 });
// `..` from mounted root → /
const atMnt = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atMnt, "..")).toEqual({ device_id: 0, inode: 0 });
// `mnt` again from / → back to mounted root
const atRoot = makeShellState(fs, { cwd: NodePointer.of(0, 0) });
expect(resolvePath(atRoot, "mnt")).toEqual({ device_id: 1, inode: 0 });
});
});
-90
View File
@@ -1,90 +0,0 @@
import type { UserInfo } from "@core/session_manager";
import { createInitialSessionState, getCurrentSession, login, logout } from "@core/session_manager";
import { createInitialShellState } from "@core/shell_state";
import { buildTestFS } from "@tests/helpers/filesystems_fixture";
import { depth7Tree } from "@tests/helpers/tree_fixture";
import { describe, expect, test } from "vitest";
const root: UserInfo = {
username: "root",
uid: 0,
gid: 0,
group: [0],
home: 0,
};
const testU: UserInfo = {
username: "test",
uid: 1,
gid: 1,
group: [1],
home: 1,
};
const fs = buildTestFS(depth7Tree);
const users = new Map();
users.set(0, root);
users.set(1, testU);
const state = createInitialShellState(fs, users, root);
const passMap = new Map();
passMap.set(0, "123");
passMap.set(1, "321");
test("createInitialSessionState - successfully creates a new session state", () => {
const state = createInitialSessionState(root);
expect(state.cwd).toEqual(root.home);
expect(state.pwd).toEqual(root.home);
expect(state.exitCode).toEqual(0);
expect(state.user).toBe(root);
expect(Object.isFrozen(state)).toBe(true);
});
describe("login", () => {
test("it successfully starts a new session under the user test", () => {
const newState = login(state, "test", "321", passMap);
const pop = getCurrentSession(newState);
expect(pop.user).toEqual(testU);
});
test("fails to start a new session. Cause: no password mapped to the uid", () => {
const nopass: UserInfo = {
username: "no pass",
uid: 2,
gid: 1,
group: [1],
home: 1,
};
users.set(2, nopass);
//TODO: Fix to expect the correct object;
expect(() => login(state, "no pass", "321", passMap)).toThrow();
});
test("fails to start a new session. Cause: Incorrect password", () => {
//TODO: Fix to expect the correct object;
expect(() => login(state, "no pass", "333", passMap)).toThrow();
});
test("fails to start a new session. Cause: Specified user does not exist", () => {
//TODO: Fix to expect the correct object;
expect(() => login(state, "no user", "321", passMap)).toThrow();
});
});
describe("logout", () => {
test("returns the state with the current user poped from the stack", () => {
const newState = login(state, "test", "321", passMap);
const newPop = getCurrentSession(newState);
expect(newPop.user).toEqual(testU);
const newNewState = logout(state);
const pop = getCurrentSession(newNewState);
expect(pop.user).toEqual(root);
});
});
-98
View File
@@ -1,98 +0,0 @@
import { FileSystem } from "@core/filesystem/filesystem";
import { TreeNodeType, type DirectoryNode, type TreeNode } from "@core/filesystem/treenode";
import type { UserInfo } from "@core/session_manager";
import { getCurrentSession } from "@core/session_manager";
import { createInitialShellState, withCwd, withEnv, withExitCode, withHistory } from "@core/shell_state";
import { expect, test } from "vitest";
const map: Map<number, TreeNode> = new Map();
const time = Date.now();
const root: DirectoryNode = {
type: TreeNodeType.Directory,
inode: 0,
name: "root",
parent: 0,
mode: 0o555,
owner: 0,
group: 0,
mtime: time,
atime: time,
ctime: time,
children: {},
};
map.set(0, root);
const base: ReadonlyMap<number, TreeNode> = map;
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
const fs = FileSystem.init(base, overlay, 0);
const users: Map<number, UserInfo> = new Map();
const user: UserInfo = {
username: "root",
uid: 0,
gid: 0,
group: [0],
home: 0,
};
users.set(0, user);
const state = createInitialShellState(fs, users, user);
test("createInitialShellState - initializes successfully", () => {
expect(state.sessionStack.at(0)).toBeDefined();
expect(state.users.get(user.uid)).toEqual(user);
expect(Object.isFrozen(state)).toBe(true);
});
test("fails - tries to mutate a frozen immutable object", () => {
expect(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(state as any).sessionStack = [];
}).toThrow();
});
test("getCurrentSession - successfully returns the current (top most) session from the stack", () => {
const session = getCurrentSession(state);
expect(session.cwd).toBe(0);
expect(session.pwd).toBe(0);
expect(session.exitCode).toBe(0);
expect(session.history).toEqual([]);
expect(session.envVars.size).toBe(0);
expect(session.user).toBe(user);
});
test("withCwd", () => {
const nstate = withCwd(state, 1);
const result = getCurrentSession(nstate);
expect(result.cwd).toBe(1);
expect(result.pwd).toBe(0);
expect(nstate.filesystem).toBe(state.filesystem);
expect(getCurrentSession(state).cwd).toBe(0);
});
test("withEnv", () => {
const nstate = withEnv(state, "foo", "Hello World!");
const result = getCurrentSession(nstate);
expect(result.envVars.get("foo")).toBe("Hello World!");
expect(nstate.filesystem).toBe(state.filesystem);
expect(getCurrentSession(state).envVars.get("foo")).toBeUndefined();
});
test("withHistory", () => {
const nstate = withHistory(state, 'echo "Hi!"');
const result = getCurrentSession(nstate);
expect(result.history).toContain('echo "Hi!"');
expect(nstate.filesystem).toBe(state.filesystem);
expect(getCurrentSession(state).history).not.toContain('echo "Hi!"');
});
test("withExitCode", () => {
const nstate = withExitCode(state, 10);
const result = getCurrentSession(nstate);
expect(result.exitCode).toEqual(10);
expect(nstate.filesystem).toBe(state.filesystem);
expect(getCurrentSession(state).exitCode).toEqual(0);
});
-86
View File
@@ -1,86 +0,0 @@
import { parseCommand } from "@core/util/parser";
import { describe, expect, test } from "vitest";
describe("parseCommand", () => {
test("returns an empty ParsedCommand object", () => {
expect(parseCommand("")).toEqual({ command: "", flags: [], args: [] });
});
test("returns an empty ParsedCommand object", () => {
expect(parseCommand("")).toEqual({ command: "", flags: [], args: [] });
});
test("returns an empty ParsedCommand object", () => {
expect(parseCommand("")).toEqual({ command: "", flags: [], args: [] });
});
test("returns a parsed ls command without any args", () => {
expect(parseCommand("ls")).toEqual({ command: "ls", flags: [], args: [] });
});
test("returns a parsed ls command with arg /tmp", () => {
expect(parseCommand("ls /tmp")).toEqual({ command: "ls", flags: [], args: ["/tmp"] });
});
test("returns a parsed ls command with flags l and no args", () => {
expect(parseCommand("ls -l")).toEqual({ command: "ls", flags: ["l"], args: [] });
});
test("returns a parsed command with flags l,a and no args", () => {
expect(parseCommand("ls -la")).toEqual({ command: "ls", flags: ["l", "a"], args: [] });
});
test("returns a parsed command with flags l,a and no args", () => {
expect(parseCommand("ls -l -a")).toEqual({ command: "ls", flags: ["l", "a"], args: [] });
});
test("returns a parsed command with flags l,a and a /tmp arg", () => {
expect(parseCommand("ls -la /tmp")).toEqual({ command: "ls", flags: ["l", "a"], args: ["/tmp"] });
});
test("returns a parsed grep command with a valued color flag", () => {
expect(parseCommand("grep --color=auto")).toEqual({ command: "grep", flags: ["color=auto"], args: [] });
});
test("returns a parsed grep command with a valued color and r flags", () => {
expect(parseCommand("grep --color=auto -r")).toEqual({
command: "grep",
flags: ["color=auto", "r"],
args: [],
});
});
test("returns a parsed grep command with a valued color in short form and r flags", () => {
expect(parseCommand("grep -color=auto -r")).toEqual({
command: "grep",
flags: ["color=auto", "r"],
args: [],
});
});
test("returns a parsed grep command with a valued w in short form and r flags", () => {
expect(parseCommand("grep -w=auto -r")).toEqual({
command: "grep",
flags: ["w=auto", "r"],
args: [],
});
});
test("returns a parsed echo command with a --version arg", () => {
expect(parseCommand("echo -- --version")).toEqual({ command: "echo", flags: [], args: ["--version"] });
});
test("returns a parsed echo command with a -f arg", () => {
expect(parseCommand("echo -- -f")).toEqual({ command: "echo", flags: [], args: ["-f"] });
});
test("returns a parsed echo command without any args", () => {
expect(parseCommand("echo --")).toEqual({ command: "echo", flags: [], args: [] });
});
test("returns a parsed ls command with flags l,a and a --tmp arg", () => {
expect(parseCommand("ls -la -- --tmp")).toEqual({ command: "ls", flags: ["l", "a"], args: ["--tmp"] });
});
test("returns a parsed rm command with flags r,f,no-preserve-root and a / arg", () => {
expect(parseCommand("rm -rf --no-preserve-root /")).toEqual({
command: "rm",
flags: ["r", "f", "no-preserve-root"],
args: ["/"],
});
});
test("throws an UnclosedQuote error", () => {
expect(() => parseCommand('echo "hello')).toThrow(expect.objectContaining({ type: "UnclosedQuote" }));
});
});
-60
View File
@@ -1,60 +0,0 @@
import { dnTraverseTree, upTraverseTree } from "@core/util/tree_traversal";
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
import { depth7Tree } from "@tests/helpers/tree_fixture";
import { describe, expect, test } from "vitest";
const testTree: FixtureNode = {
inode: 0,
name: "root",
type: "Dir",
children: [
{
inode: 1,
name: "hello.txt",
type: "File",
content: "Hello, world!",
children: [],
},
{
inode: 2,
name: "sub",
type: "Dir",
children: [
{
inode: 3,
name: "world.txt",
type: "File",
content: "Goodbye!",
children: [],
},
],
},
],
};
const fs = buildTestFS(testTree);
const fsTwo = buildTestFS(depth7Tree);
describe("dnTraverseTree", () => {
test("successfully traverses down the tree in depth-first pre-order", () => {
const result = dnTraverseTree(fs, 0);
expect(result, `Checking the result ${result} to be [0, 1, 2, 3]`).toEqual([0, 2, 3, 1]);
});
test("returns empty array for a non existent root inode", () => {
expect(dnTraverseTree(fs, 999)).toEqual([]);
});
});
describe("upTraverseTree", () => {
test("successfully traverses up the tree", () => {
const result = upTraverseTree(fsTwo, 7);
expect(result, `Checking the result ${result} to be [7, 6, 5, 4, 3, 2, 1, 0]`).toEqual([
7, 6, 5, 4, 3, 2, 1, 0,
]);
});
test("returns empty array for a non existent inode", () => {
expect(dnTraverseTree(fs, 999)).toEqual([]);
});
});
+84 -15
View File
@@ -1,17 +1,23 @@
// @core/filesystem/errors.test-util.ts (adjust path to match yours)
import type {
AlreadyExistsError,
DeviceNotFoundError,
DirectoryLoopError,
FileSystemCorruptionError,
FileSystemInitializationError,
IllegalMutationError,
InvalidNodeNameError,
NodeNotFoundError,
NotADirectoryError,
NotAFileError,
} from "@core/filesystem/errors";
import type { TreeNodeType } from "@core/filesystem/treenode";
import type { NodeType } from "@core/filesystem/node";
import { expect } from "vitest";
export function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) {
export async function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) {
let thrown: unknown;
try {
fn();
await fn();
} catch (e) {
thrown = e;
}
@@ -20,19 +26,19 @@ export function expectThrows(fn: () => unknown, expectedShape: Record<string, un
expect(thrown).toMatchObject(expectedShape);
}
export function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<NotADirectoryError>) {
expectThrows(fn, {
export async function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<NotADirectoryError>) {
return await expectThrows(fn, {
type: "NotADirectory",
inode: expect.any(Number) as number,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
nodeType: expect.any(String) as TreeNodeType,
nodeType: expect.any(Number) as NodeType,
...overrides,
});
}
export function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<AlreadyExistsError>) {
expectThrows(fn, {
export async function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<AlreadyExistsError>) {
return await expectThrows(fn, {
type: "AlreadyExists",
parentInode: expect.any(Number) as number,
name: expect.any(String) as string,
@@ -42,18 +48,23 @@ export function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<
});
}
export function expectNodeNotFoundError(fn: () => unknown, overrides?: Partial<NodeNotFoundError>) {
expectThrows(fn, {
/**
* FIXED: `NodeNotFoundError` has `pointer: NodePointer` (a string), not `inode: number`.
* The previous version asserted `inode: expect.any(Number)` and would have failed
* against every real thrown `NodeNotFoundError`.
*/
export async function expectNodeNotFoundError(fn: () => unknown, overrides?: Partial<NodeNotFoundError>) {
return await expectThrows(fn, {
type: "NodeNotFound",
inode: expect.any(Number) as number,
pointer: expect.any(String) as string,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
export function expectIllegalMutationError(fn: () => unknown, overrides?: Partial<IllegalMutationError>) {
expectThrows(fn, {
export async function expectIllegalMutationError(fn: () => unknown, overrides?: Partial<IllegalMutationError>) {
return await expectThrows(fn, {
type: "IllegalMutation",
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
@@ -61,8 +72,8 @@ export function expectIllegalMutationError(fn: () => unknown, overrides?: Partia
});
}
export function expectDirectoryLoopError(fn: () => void, overrides?: Partial<DirectoryLoopError>) {
expectThrows(fn, {
export async function expectDirectoryLoopError(fn: () => void, overrides?: Partial<DirectoryLoopError>) {
return await expectThrows(fn, {
type: "DirectoryLoop",
descendantInode: expect.any(Number) as number,
ancestorInode: expect.any(Number) as number,
@@ -71,3 +82,61 @@ export function expectDirectoryLoopError(fn: () => void, overrides?: Partial<Dir
...overrides,
});
}
// ---- NEW helpers below ----
export async function expectDeviceNotFoundError(fn: () => unknown, overrides?: Partial<DeviceNotFoundError>) {
return await expectThrows(fn, {
type: "DeviceNotFound",
device_id: expect.any(Number) as number,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
export async function expectNotAFileError(fn: () => unknown, overrides?: Partial<NotAFileError>) {
return await expectThrows(fn, {
type: "NotAFile",
inode: expect.any(Number) as number,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
nodeType: expect.any(Number) as NodeType,
...overrides,
});
}
export async function expectFileSystemInitializationError(
fn: () => unknown,
overrides?: Partial<FileSystemInitializationError>,
) {
return await expectThrows(fn, {
type: "FileSystemInitializationError",
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
export async function expectInvalidNodeNameError(fn: () => unknown, overrides?: Partial<InvalidNodeNameError>) {
return await expectThrows(fn, {
type: "InvalidNodeName",
pointer: expect.any(String) as string,
attemptedName: expect.any(String) as string,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
export async function expectFileSystemCorruptionError(
fn: () => unknown,
overrides?: Partial<FileSystemCorruptionError>,
) {
return await expectThrows(fn, {
type: "FileSystemCorruption",
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
+172 -62
View File
@@ -1,71 +1,181 @@
// ============================================================================
// Node fixtures
// ============================================================================
import { FileSystem } from "@core/filesystem/filesystem";
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "@core/filesystem/treenode";
import { createImmutableBuffer } from "@core/util/immutable_buffer";
import {
NodePointer,
NodeType,
type DirectoryNode,
type FileNode,
type Node,
type SymlinkNode,
} from "@core/filesystem/node";
import { DefaultVDiskConfig } from "@core/filesystem/vdisk";
import type { SessionState, UserInfo } from "@core/session_manager";
import type { ShellState } from "@core/shell_state";
import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
export interface FixtureNode {
inode: number;
name: string;
type: "File" | "Dir";
children: FixtureNode[];
content?: string;
mode?: number;
owner?: number;
group?: number;
mtime?: number;
ctime?: number;
atime?: number;
}
export function buildTestFS(tree: FixtureNode): FileSystem {
const map = new Map<number, TreeNode>();
function parse(node: FixtureNode, parent: number): void {
if (node.type === "Dir") {
for (const child of node.children) {
parse(child, node.inode);
}
const children: Record<string, number> = {};
for (const child of node.children) {
children[child.name] = child.inode;
}
const directoryNode: DirectoryNode = {
type: TreeNodeType.Directory,
inode: node.inode,
name: node.name,
parent: parent,
mode: node.mode ?? 0o777,
owner: node.owner ?? 0,
group: node.group ?? 0,
mtime: node.mtime ?? Date.now(),
ctime: node.ctime ?? Date.now(),
atime: node.atime ?? Date.now(),
children: children,
export function makeDir(inode: number, children: Record<string, number> = {}): DirectoryNode {
return {
type: NodeType.Directory,
inode,
link_count: 2,
mode: 0o755,
owner: 0,
group: 0,
mtime: 0,
ctime: 0,
atime: 0,
children: new Map(Object.entries(children)),
};
map.set(node.inode, Object.freeze(directoryNode));
} else {
const fileNode: FileNode = {
type: TreeNodeType.File,
inode: node.inode,
name: node.name,
parent: parent,
mode: node.mode ?? 0o777,
owner: node.owner ?? 0,
group: node.group ?? 0,
mtime: node.mtime ?? Date.now(),
ctime: node.ctime ?? Date.now(),
atime: node.atime ?? Date.now(),
content: createImmutableBuffer(new TextEncoder().encode(node.content)),
}
export function makeFile(inode: number): FileNode {
return {
type: NodeType.File,
inode,
link_count: 1,
mode: 0o644,
owner: 0,
group: 0,
mtime: 0,
ctime: 0,
atime: 0,
content: `uuid-${inode}`,
size: 0,
};
map.set(node.inode, Object.freeze(fileNode));
}
}
parse(tree, 0);
export function makeSymlink(inode: number, target: string): SymlinkNode {
return {
type: NodeType.Symlink,
inode,
link_count: 1,
mode: 0o777,
owner: 0,
group: 0,
mtime: 0,
ctime: 0,
atime: 0,
target,
};
}
const base: ReadonlyMap<number, TreeNode> = map;
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
export function makeUser(home: NodePointer = NodePointer.of(0, 0)): UserInfo {
return {
username: "test",
uid: 1000,
gid: 1000,
group: [],
home,
};
}
return FileSystem.init(base, overlay, base.size - 1);
// ============================================================================
// Tree builder — auto-assigns inodes, validates before use
// ============================================================================
export interface TreeBuilder {
addDir(parentInode: number, name: string): number;
addFile(parentInode: number, name: string): number;
addSymlink(parentInode: number, name: string, target: string): number;
build(): Map<number, Node>;
}
export function makeTree(): TreeBuilder {
const nodes = new Map<number, Node>([[0, makeDir(0)]]);
let nextInode = 1;
function attach(parentInode: number, name: string, childInode: number): void {
const parent = nodes.get(parentInode);
if (!parent || parent.type !== NodeType.Directory) {
throw new Error(`Parent inode ${parentInode} is not a directory`);
}
const children = new Map(parent.children);
children.set(name, childInode);
nodes.set(parentInode, { ...parent, children });
}
function add(node: Node, parentInode: number, name: string): number {
attach(parentInode, name, node.inode);
nodes.set(node.inode, node);
return node.inode;
}
return {
addDir(parentInode, name) {
return add(makeDir(nextInode++), parentInode, name);
},
addFile(parentInode, name) {
return add(makeFile(nextInode++), parentInode, name);
},
addSymlink(parentInode, name, target) {
return add(makeSymlink(nextInode++, target), parentInode, name);
},
build() {
for (const [key, node] of nodes) {
if (node.inode !== key) {
throw new Error(`inode mismatch: key=${key}, node.inode=${node.inode}`);
}
if (node.type === NodeType.Directory) {
for (const [cname, cinode] of node.children) {
if (!nodes.has(cinode)) {
throw new Error(`dangling child '${cname}' → inode ${cinode}`);
}
}
}
}
return nodes;
},
};
}
// ============================================================================
// FileSystem builder — real VDisk stack, one device per base map
// ============================================================================
export async function makeFS(bases: Map<number, Node>[]): Promise<FileSystem> {
const devices = bases.map((base, id) => ({
dstore: new MemDataStore(),
mstore: new MemMetaStore(),
config: {
...DefaultVDiskConfig(id),
base,
index: Math.max(0, ...base.keys()),
},
}));
const fs = FileSystem.init(devices);
// `FileSystem.init` does not await `registerDisk` (see the init suite BUG);
// flush a macrotask so every disk is registered before the first resolve.
await new Promise(r => setImmediate(r));
return fs;
}
// ============================================================================
// Shell state fixture
// ============================================================================
export function makeShellState(
fs: FileSystem,
opts: { cwd?: NodePointer; home?: NodePointer; user?: UserInfo } = {},
): ShellState {
const cwd = opts.cwd ?? NodePointer.of(0, 0);
const user = opts.user ?? makeUser(opts.home);
const session = {
user,
envVars: new Map<string, string>(),
history: [],
cwd,
pwd: cwd,
exitCode: 0,
} as unknown as SessionState;
return {
filesystem: fs,
users: new Map(),
groups: new Map(),
sessionStack: [session],
} as unknown as ShellState;
}
-58
View File
@@ -1,58 +0,0 @@
import type { FixtureNode } from "./filesystems_fixture";
export const depth7Tree: FixtureNode = {
inode: 0,
name: "root",
type: "Dir",
children: [
{
inode: 1,
name: "d1",
type: "Dir",
children: [
{
inode: 2,
name: "d2",
type: "Dir",
children: [
{
inode: 3,
name: "d3",
type: "Dir",
children: [
{
inode: 4,
name: "d4",
type: "Dir",
children: [
{
inode: 5,
name: "d5",
type: "Dir",
children: [
{
inode: 6,
name: "d6",
type: "Dir",
children: [
{
inode: 7,
name: "deep_file.txt",
type: "File",
content: "Deepest node at depth 7",
children: [],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
};
-29
View File
@@ -1,29 +0,0 @@
import { expect, test } from "vitest";
function divideToChunks(data: Uint8Array): Uint8Array[] {
const nChunks: number = Math.ceil(data.length / 1024);
const chunks: Uint8Array[] = [];
for (let i = 0; i < nChunks; i++) {
const start = 1024 * i;
const end = 1024 * (i + 1);
chunks.push(data.slice(start, end));
}
console.log(chunks.length);
return chunks;
}
test("divide to chunks", () => {
const data: Uint8Array = new Uint8Array(2048);
const result: Uint8Array[] = divideToChunks(data);
expect(result.length).toEqual(2);
});
test("divide to chunks", () => {
const data: Uint8Array = new Uint8Array(2049);
const result = divideToChunks(data);
expect(result.length).toEqual(3);
});
-9
View File
@@ -1,9 +0,0 @@
import { deserializeFileSystem } from "@shell/serializer";
import { test } from "vitest";
const rawJson = `{"atime": 1786341244,"children": [{"atime": 1786341264,"children": [{"atime": 1786341330,"children": [],"content": null,"ctime": 1786341330,"group": 1000,"inode": 2,"mode": 493,"mtime": 1786341330,"name": "subdir1","owner": 1000,"parent": 1,"type": "directory"}],"content": null,"ctime": 1786341330,"group": 1000,"inode": 1,"mode": 493,"mtime": 1786341330,"name": "folder1","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341269,"children": [{"atime": 1786341344,"children": [],"content": null,"ctime": 1786341344,"group": 1000,"inode": 4,"mode": 493,"mtime": 1786341344,"name": "subdir2","owner": 1000,"parent": 3,"type": "directory"},{"atime": 1786341345,"children": [{"atime": 1786341356,"children": [],"content": [],"ctime": 1786341356,"group": 1000,"inode": 6,"mode": 420,"mtime": 1786341356,"name": "empty-foo","owner": 1000,"parent": 5,"type": "regular"}],"content": null,"ctime": 1786341356,"group": 1000,"inode": 5,"mode": 493,"mtime": 1786341356,"name": "subdir3","owner": 1000,"parent": 3,"type": "directory"}],"content": null,"ctime": 1786341345,"group": 1000,"inode": 3,"mode": 493,"mtime": 1786341345,"name": "folder2","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341312,"children": [],"content": [72,101,108,108,111,44,32,87,111,114,108,100,33,10],"ctime": 1786341312,"group": 1000,"inode": 7,"mode": 420,"mtime": 1786341312,"name": "some-file","owner": 1000,"parent": 0,"type": "regular"}],"content": null,"ctime": 1786341312,"group": 1000,"inode": 0,"mode": 493,"mtime": 1786341312,"name": "root","owner": 1000,"parent": 0,"type": "directory"}`;
test("deserialize json into the correct tree structure", () => {
const base = deserializeFileSystem(rawJson);
console.log(base);
});
-70
View File
@@ -1,70 +0,0 @@
import { getCurrentSession, type UserInfo } from "@core/session_manager";
import { createInitialShellState, type ShellState } from "@core/shell_state";
import { Shell } from "@shell/shell";
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
import { describe, expect, test } from "vitest";
const testTree: FixtureNode = {
inode: 0,
name: "root",
type: "Dir",
children: [
{
inode: 1,
name: "hello.txt",
type: "File",
content: "Goodbye World!",
children: [],
},
{
inode: 2,
name: "sub",
type: "Dir",
children: [
{
inode: 3,
name: "world.txt",
type: "File",
content: "Goodbye!",
children: [],
},
{
inode: 4,
name: "bye",
type: "Dir",
children: [],
},
],
},
],
};
const fs = buildTestFS(testTree);
const users: Map<number, UserInfo> = new Map();
const user: UserInfo = {
username: "root",
uid: 0,
gid: 0,
group: [0],
home: 0,
};
users.set(0, user);
const state: ShellState = createInitialShellState(fs, users, user);
describe("Shell tests", () => {
test("Successfully executes the cd command", async () => {
await Shell.init(state);
const result = await Shell.Instance?.Execute("cd /sub");
const statee = Shell.Instance?.State;
expect(result?.type).toEqual("success");
expect(getCurrentSession(statee!).history.length).toBe(1);
expect(getCurrentSession(statee!).history[0]).toEqual("cd /sub");
expect(getCurrentSession(statee!).cwd).toBe(2);
expect(getCurrentSession(statee!).exitCode).toBe(0);
});
test("Returns a proper command error from cd", () => {});
test("Returns an empty success result as per parsing a whitespace character or inputing nothing", () => {});
});
+20
View File
@@ -0,0 +1,20 @@
import { splitUint8Array } from "@termos/util/concat";
import { expect, test } from "vitest";
test("divide to chunks", () => {
const data: Uint8Array = new Uint8Array(2048);
const result = splitUint8Array(data, 1024);
expect(result.length).toEqual(2);
});
test("divide to chunks", () => {
const data: Uint8Array = new Uint8Array(2049);
const result = splitUint8Array(data, 1024);
expect(result.length).toEqual(3);
});
test("divide to chunks", () => {
const data: Uint8Array = new Uint8Array(2048);
const result = splitUint8Array(data, 53);
expect(result.length).toEqual(Math.ceil(2048 / 53));
});
+1
View File
@@ -23,6 +23,7 @@
"sourceMap": true,
"ignoreDeprecations": "6.0",
"baseUrl": "./",
"types": ["node"],
"paths": {
"@tests/*": ["test/*"],
"@shell/*": ["src/shell/*"],
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts", "!src/dev.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"],
format: ["esm"],
dts: true,
clean: true,
sourcemap: true,
});