33 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
59 changed files with 7311 additions and 5631 deletions
+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
}
+37 -14
View File
@@ -11,31 +11,54 @@ It doesnt implement a website friendly interface on its own. Thats one of the de
## Prerequisites
- [Node.js](https://nodejs.org/) installed (version 26.2.0 or higher)
- [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.
> 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
wget https://git.gornodox.dev/ChaosMaker/termos/archive/unstable-async.zip
unzip -d termos unstable-async.zip
cd termos
npm install
pnpm add "https://git.gornodox.dev/ChaosMaker/termos/releases/download/0.1.0/termos-0.1.0.tgz"
```
## Running the project
## Minimal usecase
```bash
npm run dev
```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");
```
## Running the test suite
```bash
npm run test
```
For more information, reference the [wiki]()
-3287
View File
File diff suppressed because it is too large Load Diff
+29 -5
View File
@@ -1,16 +1,35 @@
{
"name": "termos",
"version": "0.0.1",
"version": "0.1.0",
"description": "Emulation library for a unix-like operating-system written in pure typescript",
"main": "index.ts",
"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",
"dev": "npx tsx src/index.ts"
"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",
@@ -28,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;
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;
};
}
export const defaultConfig: TermosConfig = {
serverAddress: "",
dbName: "termos",
idbName: "cache",
};
+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;
+6
View File
@@ -1,9 +1,12 @@
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);
@@ -12,6 +15,9 @@ 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;
+1 -7
View File
@@ -6,13 +6,7 @@ import type { ShellError } from "@core/util/errors";
export const COMMAND_NAME = "";
//Need to implement escape sequences
async function main(
io: CommandIO,
state: ShellState,
flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
+21 -17
View File
@@ -1,6 +1,7 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { TreeNodeType, type FileNode, type TreeNode } from "@core/filesystem/treenode";
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";
@@ -10,15 +11,12 @@ import { resolvePath } from "@core/util/path_resolver";
export const COMMAND_NAME = "cat";
//Need to implement escape sequences
async function main(
io: CommandIO,
state: ShellState,
flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
for (const arg of args) {
const inode = resolvePath(state, arg);
if (inode === -1) {
let ptr: NodePointer;
try {
ptr = resolvePath(state, arg);
} catch (e) {
return {
state,
result: createErrorResult(
@@ -30,15 +28,20 @@ async function main(
} satisfies CommandOutput<PathResolutionError>;
}
// Casting to TreeNode because the resolvePath already ensures the inode is correct;
const node = state.filesystem.getNode(inode) as TreeNode;
if (node.type != TreeNodeType.File) {
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",
`${node.name} is a directory`,
`${entries[0]!.name} is a directory`,
{ path: arg },
COMMAND_NAME,
),
@@ -47,15 +50,16 @@ async function main(
const session = getCurrentSession(state);
if (!state.filesystem.canRead(inode, session.user)) {
if (!state.filesystem.canRead(ptr, session.user)) {
return {
state,
result: createErrorResult("PermissionDenied", "Permission denied", { resource: arg }, COMMAND_NAME),
} satisfies CommandOutput<PermissionDeniedError>;
}
node as FileNode;
io.writeStdout(node.content.toArray());
const content = await state.filesystem.read(ptr);
io.writeStdout(content);
}
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
+11 -14
View File
@@ -1,5 +1,6 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
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";
@@ -13,12 +14,7 @@ import { resolvePath } from "@core/util/path_resolver";
export const COMMAND_NAME = "cd";
async function main(
__io: CommandIO,
state: ShellState,
__flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
async function main(__io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
if (args.length > 1) {
return {
state,
@@ -31,16 +27,17 @@ async function main(
} 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 {
inode = resolvePath(state, args[0]);
if (inode === -1) {
try {
ptr = resolvePath(state, args[0]);
} catch (e) {
return {
state,
result: createErrorResult(
@@ -53,21 +50,21 @@ async function main(
}
}
if (state.filesystem.isFile(inode)) {
if (state.filesystem.isFile(ptr)) {
return {
state,
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]! }, COMMAND_NAME),
} satisfies CommandOutput<PermissionDeniedError>;
}
const returnState = withCwd(state, inode);
const returnState = withCwd(state, ptr);
return {
state: returnState,
+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,
};
+1 -6
View File
@@ -7,12 +7,7 @@ import type { ShellError } from "@core/util/errors";
export const COMMAND_NAME = "echo";
//Need to implement escape sequences
async function main(
io: CommandIO,
state: ShellState,
__flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const joined = args.join(" ");
const encoded = new TextEncoder().encode(joined + "\n");
+313 -135
View File
@@ -1,70 +1,243 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { TreeNodeType, type DirectoryNode, type TreeNode } from "@core/filesystem/treenode";
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 { SortTreeNodeBy, sortTreeNodes } from "@core/util/sort";
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";
async function main(
io: CommandIO,
state: ShellState,
flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
const entries: { inode: number; path: string }[] = [];
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();
const vars = flags.filter(
// Match at least 1 character between each side of a singular = character
f =>
f.match(/\w+[=]{1}\w+/g) &&
// Check if descriptors flags array contains an object with the name as the flags key and has takesValue set to true
descriptor.flags?.some(flag => flag.name === f.split("=")[0] && flag.takesValue === true),
);
const fSet = new Set(flags.filter(f => descriptor.flags?.some(flag => flag.name === f) && !vars.includes(f)));
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,
};
if (fSet.size + vars.length < flags.length) {
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),
};
}
const session = getCurrentSession(state);
const timeVar = vars.find(f => f.startsWith("time"))?.split("=")[1];
const sortVar = vars.find(f => f.startsWith("sort"))?.split("=")[1];
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);
let sortBy: SortTreeNodeBy = sortVar && isValidSortMethod(sortVar) ? sortVar : SortTreeNodeBy.NAME;
let timestamp: SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME =
timeVar && isValidTimestamp(timeVar) ? timeVar : SortTreeNodeBy.ATIME;
if (args.length === 0) {
entries.push({ inode: session.cwd, path: "." });
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 {
for (const arg of args) {
const inode = resolvePath(state, arg);
if (inode === -1) {
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: arg },
{ path },
COMMAND_NAME,
),
};
}
entries.push({ inode: inode, path: arg });
entries.push({ ptr, path });
}
}
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
if (options.long) {
for (const entry of entries) {
listDirEntries(entry);
}
@@ -74,171 +247,175 @@ async function main(
}
io.writeStdout(e.encode(`No support for short format yet\n`));
}
io.writeStdout(e.encode("\n"));
return {
state,
result: createSuccessResult(COMMAND_NAME),
};
function listDirEntries(entry: { inode: number; path: string }): void {
const node = state.filesystem.getNode(entry.inode) as DirectoryNode;
function listDirEntries(entry: { ptr: NodePointer; path: string }): void {
const node = state.filesystem.getNode(entry.ptr) as DirectoryNode;
// This method of evaluating flags is faulty, it doesnt respect order;
if (fSet.has("t")) sortBy = timestamp;
if (fSet.has("S")) sortBy = SortTreeNodeBy.SIZE;
if (fSet.has("X")) sortBy = SortTreeNodeBy.EXTENSION;
if (fSet.has("R") || fSet.has("recursive")) io.writeStdout(e.encode(`${entry.path}:\n`));
if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\n`));
io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`));
let children: TreeNode[] = Object.entries(node.children).map(c => state.filesystem.getNode(c[1])!);
if (!fSet.has("f") || !fSet.has("U"))
children = sortTreeNodes(state, children, fSet.has("r") || fSet.has("reverse"), sortBy);
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 (fSet.has("a") || fSet.has("A") || fSet.has("all") || fSet.has("almost-all") || fSet.has("f"))
if (!options.all && !options.almostAll) {
children = children.filter(c => !c.name.startsWith("."));
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
longMode(io, state, children, fSet);
io.writeStdout(e.encode("\n"));
}
if (fSet.has("R") || fSet.has("recursive")) {
for (const child of children) {
if (child.type === TreeNodeType.Directory) {
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 = "/" + child.name;
path = "/" + c.name;
} else if (entry.path.endsWith("/")) {
path = entry.path + child.name;
} else path = entry.path + "/" + child.name;
listDirEntries({ inode: child.inode, path });
path = entry.path + c.name;
} else path = entry.path + "/" + c.name;
listDirEntries({ ptr: c.ptr, path });
}
}
}
}
}
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
function longMode(io: CommandIO, state: ShellState, nodes: TreeNode[], flags: Set<string>): void {
function longMode(io: CommandIO, state: ShellState, children: DirEntry[]): void {
const e = new TextEncoder();
if (flags.has("a") || flags.has("all") || flags.has("f")) {
const cwdNode = state.filesystem.getNode(nodes[0]!.parent)!;
const parentNode = state.filesystem.getNode(cwdNode.parent)!;
const parent: TreeNode = { ...parentNode, name: ".." };
nodes.unshift(parent);
const cwd: TreeNode = { ...cwdNode, name: "." };
nodes.unshift(cwd);
}
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.inode.toString().length));
const maxInodeWidth = Math.max(...nodes.map(c => c.ptr.inode.toString().length));
const maxSizeWidth = Math.max(
...nodes.map(c => (c.type === TreeNodeType.File ? c.content.byteSize().toString().length : 4)),
);
const maxChildrenWidth = Math.max(
...nodes.map(c =>
c.type === TreeNodeType.Directory ? Object.entries(c.children).length.toString().length : 2,
state.filesystem.getNode(c.ptr)!.type === NodeType.File
? (state.filesystem.getNode(c.ptr) as FileNode).size.toString().length
: 4,
),
);
for (const node of nodes) {
if (flags.has("i") || flags.has("inode")) {
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, " ");
io.writeStdout(e.encode(inode + " "));
buff.push(e.encode(inode + " "));
}
// Mode
const mode: string = parseMode(node.mode);
switch (node.type) {
case TreeNodeType.Directory:
io.writeStdout(e.encode("d" + mode + " "));
case NodeType.Directory:
buff.push(e.encode("d" + mode + " "));
break;
case TreeNodeType.File:
io.writeStdout(e.encode("-" + mode + " "));
case NodeType.File:
buff.push(e.encode("-" + mode + " "));
break;
}
const childAmnt =
node.type === TreeNodeType.Directory
? `${Object.entries(node.children).length.toString().padStart(maxChildrenWidth, " ")} `
: `${"10".padStart(maxChildrenWidth, " ")} `;
//Link count
const linkCount = node.link_count.toString().padStart(maxLinksWidth, " ") + " ";
buff.push(e.encode(linkCount));
io.writeStdout(e.encode(childAmnt));
if (flags.has("o") || flags.has("G") || flags.has("no-group")) {
io.writeStdout(e.encode(`${state.users.get(node.owner)?.username} `));
} else if (flags.has("g")) {
io.writeStdout(e.encode(`${state.groups.get(node.group)?.groupname} `));
} else if (flags.has("n") || flags.has("numeric-uid-gid")) {
io.writeStdout(e.encode(`${node.owner} ${node.group} `));
// 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 {
io.writeStdout(
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 (flags.has("h") || flags.has("human-readable")) {
const bytes = node.type === TreeNodeType.File ? node.content.byteSize() : 4096;
size = convertToUnit(bytes, 1, flags.has("si") ? 1000 : 1024);
if (options.humanReadable) {
const bytes = node.type === NodeType.File ? node.size : 4096;
size = convertToUnit(bytes, 1, options.si ? 1000 : 1024);
} else {
size =
node.type === TreeNodeType.File
? `${node.content.byteSize().toString().padStart(maxSizeWidth, " ")} `
node.type === NodeType.File
? `${node.size.toString().padStart(maxSizeWidth, " ")} `
: `${"4096".padStart(maxSizeWidth, " ")} `;
}
io.writeStdout(e.encode(size));
buff.push(e.encode(size));
// for now only mtime, need a helper function for all the formatting later on
const mtime = new Date(node.mtime);
if (flags.has("full-time")) {
io.writeStdout(
//Timestamp
const date = getDateTimestamp(node, options.timestamp);
if (options.fullTime) {
buff.push(
// Month + 1 because January is 0
e.encode(
`${mtime.getFullYear()}-${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}:${mtime.getMinutes()} `,
`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `,
),
);
} else {
io.writeStdout(
buff.push(
// Month + 1 because January is 0
e.encode(`${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}:${mtime.getMinutes()} `),
e.encode(`${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `),
);
}
const appendSlash = flags.has("p");
if (flags.has("Q") || flags.has("quote-name")) {
io.writeStdout(
//Name
if (options.quoteName) {
buff.push(
e.encode(
`"${node.type === TreeNodeType.Directory ? node.name + '"' + (appendSlash ? "/" : "") : node.name + '"'}\n`,
),
);
} else if (!flags.has("N") || !flags.has("literal")) {
io.writeStdout(
e.encode(
`${node.type === TreeNodeType.Directory ? node.name + (appendSlash ? "/" : "") : node.name}\n`,
`"${node.type === NodeType.Directory ? n.name + '"' + (options.appendIndicator ? "/" : "") : n.name + '"'}\n`,
),
);
} else {
const name = `${node.name.includes(" ") ? "'" + node.name + "'" : node.name}`;
io.writeStdout(
e.encode(`${node.type === TreeNodeType.Directory ? name + (appendSlash ? "/" : "") : name}\n`),
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`,
),
);
}
}
}
function parseMode(mode: number) {
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;
@@ -252,17 +429,18 @@ function parseMode(mode: number) {
};
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 isValidSortMethod(value: string): value is SortTreeNodeBy {
return Object.values(SortTreeNodeBy).includes(value as SortTreeNodeBy);
}
function isValidTimestamp(value: string): value is SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME {
return Object.values(SortTreeNodeBy).includes(
value as SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME,
);
}
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
export const descriptor: CommandDescriptor = {
fn: main,
+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,
};
+1 -6
View File
@@ -8,12 +8,7 @@ import { createImmutableBuffer } from "@core/util/immutable_buffer";
const COMMAND_NAME = "async";
async function main(
io: CommandIO,
state: ShellState,
__flags: string[],
__args: string[],
): Promise<CommandOutput<ShellError>> {
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
while (true) {
const out = await io.getSignal();
+24 -31
View File
@@ -1,7 +1,7 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { TreeNodeType } from "@core/filesystem/treenode";
import { createSuccessResult, type ResultSuccess } from "@core/result";
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";
@@ -10,41 +10,34 @@ import { resolvePath } from "@core/util/path_resolver";
export const COMMAND_NAME = "touch";
//Need to implement escape sequences
async function main(
io: CommandIO,
state: ShellState,
flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
for (const arg of args) {
const inode = resolvePath(state, arg);
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const session = getCurrentSession(state);
let newState;
if (inode === -1) {
for (const arg of args) {
try {
resolvePath(state, arg);
} catch {
const index = arg.lastIndexOf("/");
let parentPath;
if (index === -1) {
parentPath = "./";
} else {
parentPath = arg.slice(0, index);
}
const fileName = arg.slice(index + 1);
const parent = resolvePath(state, parentPath);
const parentPath = index === -1 ? "./" : arg.slice(0, index + 1);
const pptr = resolvePath(state, parentPath);
newState = state.filesystem.createNode(
parent,
fileName,
TreeNodeType.File,
0o644,
session.user.uid,
session.user.gid,
);
} else {
}
}
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 {
+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 -3
View File
@@ -1,3 +1,4 @@
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";
@@ -13,15 +14,15 @@ export interface UserInfo {
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;
}
+3 -2
View File
@@ -1,4 +1,5 @@
import type { FileSystem } from "./filesystem/filesystem";
import type { NodePointer } from "./filesystem/node";
import { addHistoryEntry } from "./history_state";
import type { GroupInfo, UserInfo } from "./session_manager";
import { createInitialSessionState, getCurrentSession, type SessionState } from "./session_manager";
@@ -38,14 +39,14 @@ export function createShellState(
});
}
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);
+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,
};
}
+206 -48
View File
@@ -1,70 +1,228 @@
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";
import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode";
export function resolvePath(state: ShellState, 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 session.cwd;
let currentDeviceId: number;
let currentNode: Node;
let currentNode = isAbsolute
? state.filesystem.getRoot()
: (state.filesystem.getNode(session.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: `[Panic] ${session.user.username}'s home directory does not exist!`,
timestamp: Date.now(),
pointer: session.user.home,
} satisfies NodeNotFoundError;
}
pathComponents.shift();
if (!currentNode) return -1;
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 (let i = 0; i < pathComponents.length; i++) {
const name = pathComponents[i]!;
if (name === ".") continue;
if (name === "..") {
currentNode = state.filesystem.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 (state.filesystem.isFile(inode) && !(i === pathComponents.length - 1))
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 = state.filesystem.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;
}
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 resolveInode(state: ShellState, inode: number): string {
const node = state.filesystem.getNode(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 = state.filesystem.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.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("/");
@@ -77,9 +235,9 @@ export function resolveInode(state: ShellState, inode: number): string {
return result;
}
export function resolveInodeToHome(state: ShellState, inode: number): string {
const home = resolveInode(state, getCurrentSession(state).user.home);
let result = resolveInode(state, inode);
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)}`;
@@ -88,9 +246,9 @@ export function resolveInodeToHome(state: ShellState, inode: number): string {
return result;
}
export function resolveInodeToCwd(state: ShellState, inode: number): string {
const cwd = resolveInode(state, getCurrentSession(state).cwd);
let result = resolveInode(state, inode);
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)}`;
@@ -99,9 +257,9 @@ export function resolveInodeToCwd(state: ShellState, inode: number): string {
return result;
}
export function resolveInodeRelative(state: ShellState, inode: number, relative: number): string {
const rel = resolveInode(state, relative);
let result = resolveInode(state, inode);
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)}`;
+55 -47
View File
@@ -1,8 +1,8 @@
import type { FileNode, TreeNode } from "@core/filesystem/treenode";
import { FileNode, NodePointer } from "@core/filesystem/node";
import type { ShellState } from "@core/shell_state";
import { Posix } from "@termos/util/posix";
export enum SortTreeNodeBy {
export enum SortNodeBy {
NAME = "name",
INODE = "inode",
SIZE = "size",
@@ -13,50 +13,46 @@ export enum SortTreeNodeBy {
CTIME = "ctime",
}
export function sortTreeNodes<T extends TreeNode | number>(
export function sortNodes<T extends { name: string; ptr: NodePointer }>(
state: ShellState,
arr: T[],
r: boolean = false,
by: SortTreeNodeBy = SortTreeNodeBy.NAME,
by: SortNodeBy = SortNodeBy.NAME,
): T[] {
if (arr.length === 0) return [];
const nodes: TreeNode[] = [];
if (typeof arr[0] === "number") {
for (const e of arr as number[]) {
const node = state.filesystem.getNode(e);
if (!node) continue;
nodes.push(node);
}
} else {
nodes.push(...(arr as TreeNode[]));
}
nodeQS(nodes, r, by, 0, nodes.length - 1);
if (typeof arr[0] === "number") {
return nodes.map(n => n.inode) as T[];
} else {
return nodes as T[];
}
nodeQS(arr, r, by, 0, arr.length - 1, state);
return arr;
}
function nodeQS(arr: TreeNode[], r: boolean, by: SortTreeNodeBy, start: number, end: number): void {
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);
nodeQS(arr, r, by, start, pivot - 1);
nodeQS(arr, r, by, pivot + 1, end);
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: TreeNode[], r: boolean, by: SortTreeNodeBy, start: number, end: number): number {
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 (compareTreeNode(part[j]!, pivot!, by, r) < 0) {
if (compareNode(part[j]!, pivot!, by, r, state) < 0) {
i++;
const temp = part[i]!;
part[i] = part[j]!;
@@ -72,11 +68,17 @@ function partitionNodeArray(part: TreeNode[], r: boolean, by: SortTreeNodeBy, st
return i;
}
function compareTreeNode(a: TreeNode, b: TreeNode, by: SortTreeNodeBy, r: boolean): number {
function compareNode(
a: { name: string; ptr: NodePointer },
b: { name: string; ptr: NodePointer },
by: SortNodeBy,
r: boolean,
state: ShellState,
): number {
switch (by) {
case SortTreeNodeBy.NAME: {
const A: string = a.name.startsWith(".") ? a.name.slice(1) : a.name;
const B: string = b.name.startsWith(".") ? b.name.slice(1) : b.name;
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++) {
@@ -91,23 +93,27 @@ function compareTreeNode(a: TreeNode, b: TreeNode, by: SortTreeNodeBy, r: boolea
return r ? B.length - A.length : A.length - B.length;
}
case SortTreeNodeBy.MTIME:
case SortTreeNodeBy.ATIME:
case SortTreeNodeBy.CTIME: {
const A: number = a[by];
const B: number = b[by];
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 SortTreeNodeBy.SIZE: {
const A: number = (a as FileNode).content.byteSize();
const B: number = (b as FileNode).content.byteSize();
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 SortTreeNodeBy.EXTENSION: {
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);
@@ -124,12 +130,14 @@ function compareTreeNode(a: TreeNode, b: TreeNode, by: SortTreeNodeBy, r: boolea
return r ? B.length - A.length : A.length - B.length;
}
case SortTreeNodeBy.INODE: {
return r ? a.inode - b.inode : b.inode - a.inode;
case SortNodeBy.INODE: {
return r ? a.ptr.inode - b.ptr.inode : b.ptr.inode - a.ptr.inode;
}
case SortTreeNodeBy.TYPE: {
return r ? b.type - a.type : a.type - b.type;
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()));
}
}
+23 -21
View File
@@ -1,42 +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) {
const children = Object.values(node.children);
if (node.type === NodeType.Directory) {
const children = Array.from(node.children.values());
for (let i = children.length - 1; i >= 0; i--) {
stack.push(children[i] as number);
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 -85
View File
@@ -1,85 +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");
}
}
*/
import { FileSystem } from "@core/filesystem/filesystem";
import type { TreeNode } from "@core/filesystem/treenode";
import { getCurrentSession, type GroupInfo, type UserInfo } from "@core/session_manager";
import { createInitialShellState, type ShellState } from "@core/shell_state";
import { resolveInodeToHome } from "@core/util/path_resolver";
import { deserializeFileSystem } from "@shell/serializer";
import { Shell } from "@shell/shell";
import { printTree } from "./util/tree_visualizer";
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"}`;
const base = deserializeFileSystem(rawJson);
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
const fs = FileSystem.init(base, overlay, base.size - 1);
console.log(printTree(fs, 0));
const users: Map<number, UserInfo> = new Map();
const groups: Map<number, GroupInfo> = new Map();
const user: UserInfo = {
username: "root",
uid: 1000,
gid: 1000, // <- PRIMARY GID
group: [1000], // <- GROUPS ARRAY
home: 3,
};
const group: GroupInfo = {
groupname: "root",
gid: 1000,
members: [1000], // <- UID
};
users.set(1000, user);
groups.set(1000, group);
const state: ShellState = createInitialShellState(fs, users, groups, user);
await Shell.init(state);
//console.log(resolveInode(Shell.Instance?.State!, 6));
//console.log(resolveInode(Shell.Instance?.State!, 6, true));
//console.log(sortTreeNodes(Shell.Instance?.State!, dnTraverseTree(Shell.Instance?.State.filesystem!, 0)));
Shell.Instance?.on("result", payload => {
const decoded = new TextDecoder().decode(payload.result.stdout.toArray());
process.stdout.write(decoded + "\n");
process.stdout.write(resolveInodeToHome(payload.state, getCurrentSession(payload.state).cwd) + "\n> ");
});
/*
Cant do it like this because commands also use the stdout event right before returning a result so e.g. echo will print twice
Need to use this only if a continuous process is running
*/
/* Shell.Instance?.on("stdout", payload => {
const decoded = new TextDecoder().decode(payload.data);
process.stdout.write(decoded + "\n");
}); */
//console.clear();
process.stdout.write(resolveInodeToHome(state, getCurrentSession(state).cwd) + "\n> ");
process.stdin.on("data", async data => {
if (Shell.Instance?.BoundPID !== null) {
Shell.Instance?.sendInput(data.toString().trim());
return;
}
const input = data.toString().trim();
await Shell.Instance?.execute(input);
});
//export { Termos };
export {
resolvePointer,
resolvePointerRelative,
resolvePointerToCwd,
resolvePointerToHome,
} from "@core/util/path_resolver";
export { Termos } from "./entry";
export { type Shell } from "./shell/index";
+1
View File
@@ -0,0 +1 @@
export { type Shell } from "./shell";
+3 -4
View File
@@ -23,20 +23,19 @@ export class Process {
readonly CommandDescriptor: CommandDescriptor;
readonly State: ShellState;
readonly Args: string[];
readonly Flags: string[];
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) {
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, args: string[]) {
this.PID = pid;
this.State = state;
this.Name = descriptor.name;
this.CommandDescriptor = descriptor;
this.Flags = flags;
this.Args = args;
// Check if positive later and throw an error if so
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;
@@ -68,7 +67,7 @@ export class Process {
},
};
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 => {
+4 -4
View File
@@ -1,6 +1,6 @@
import type { CommandDescriptor } from "@core/command";
import type { ShellState } from "@core/shell_state";
import type { Signal } from "@core/signal";
import { SIGNAL_MAP, type Signal } from "@core/signal";
import { EventEmitter } from "./event_emitter";
import { Process } from "./process";
import type { ShellEventMap } from "./shell";
@@ -11,9 +11,9 @@ export class ProcessManager {
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
public createProcess(state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]): number {
public createProcess(state: ShellState, descriptor: CommandDescriptor, args: string[]): number {
const pid = ++this._PIDIndex;
const process = new Process(pid, state, descriptor, flags, args);
const process = new Process(pid, state, descriptor, args);
this._Processes.set(pid, process);
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
@@ -51,7 +51,7 @@ export class ProcessManager {
}
//Make global signals an enum later
process.sendSignal({ type: "SIGKILL" } satisfies Signal);
process.sendSignal({ type: SIGNAL_MAP.SIGKILL } satisfies Signal);
}
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
+101 -54
View File
@@ -1,63 +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";
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()),
});
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"),
//eslint-ignore
children: z.array(z.lazy((): any => TreeNodeSchema)), // eslint-disable-line @typescript-eslint/no-explicit-any
});
const TreeNodeSchema = z.union([FileNodeSchema, DirectoryNodeSchema]);
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";
/* export function serializeFileSystem(map: ReadonlyMap<number, TreeNode | null>): string {
} */
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);
const map = new Map<number, TreeNode>();
let index = 0;
// prettier-ignore
function parseNode(tree: any, parent: number): void { // eslint-disable-line @typescript-eslint/no-explicit-any
if (tree.type === "directory") {
const children: Record<string, number> = {};
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;
}
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,
@@ -66,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(Uint8Array.from(tree.content)),
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;
}
+18 -49
View File
@@ -1,26 +1,26 @@
import { COMMAND_REGISTRY } from "@core/command_registry";
import { createErrorResult, type Result } from "@core/result";
import { getCurrentSession } from "@core/session_manager";
import { getCurrentSession, type SessionState } from "@core/session_manager";
import { withExitCode, withHistory, 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";
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 _Session: SessionState;
private _ProcessManager: ProcessManager = new ProcessManager();
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
private _GlobalKeyMap: ReadonlyMap<string, SIGNAL_MAP>;
public BoundPID: number | null = null;
private constructor(state: ShellState) {
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();
@@ -43,51 +43,22 @@ export class Shell {
});
}
static async init(initialState: ShellState): Promise<Shell> {
if (Shell.#Instance) {
console.warn("Shell already initialized");
return this.#Instance;
}
if (Shell.#Promise) return Shell.#Promise;
Shell.#Promise = (async () => {
try {
Shell.#Instance = new Shell(initialState);
return Shell.#Instance;
} finally {
Shell.#Promise = null;
}
})();
return Shell.#Promise;
}
public async execute(input: string): Promise<void> {
let parsed;
try {
parsed = parseCommand(input);
} catch {
const result = createErrorResult("ParseError", `Parsing error - ${input}`, {});
const parsed = tokenize(input);
this._State = withExitCode(this._State, result.error.exitCode);
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
return;
}
if (parsed.command === "") return;
if (!parsed[0]) return;
this._State = withHistory(this._State, input);
const command = COMMAND_REGISTRY.get(parsed.command);
const command = COMMAND_REGISTRY.get(parsed[0]);
if (!command) {
const encoded = new TextEncoder().encode(`Command ${parsed.command} not found`);
const encoded = new TextEncoder().encode(`Command ${parsed[0]} not found`);
const result = createErrorResult(
"CommandNotFound",
`Command ${parsed.command} not found`,
{ command: parsed.command },
parsed.command,
`Command ${parsed[0]} not found`,
{ command: parsed[0] },
parsed[0],
createImmutableBuffer(encoded),
createImmutableBuffer(new Uint8Array()),
);
@@ -102,7 +73,7 @@ export class Shell {
"PermissionDenied",
`Permission Denied`,
{ resource: `Execution of the ${command.name} command` },
parsed.command,
parsed[0],
);
this._State = withExitCode(this._State, result.error.exitCode);
@@ -110,7 +81,9 @@ export class Shell {
return;
}
const pid = this._ProcessManager.createProcess(this._State, command, parsed.flags, parsed.args);
parsed.shift();
const pid = this._ProcessManager.createProcess(this._State, command, parsed);
this.BoundPID = pid;
}
@@ -132,12 +105,8 @@ export class Shell {
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;
}
return Shell.#Instance;
public get Session(): Readonly<SessionState> {
return this._Session;
}
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
-74
View File
@@ -1,74 +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;
}
*/
+76 -33
View File
@@ -1,61 +1,104 @@
import type { FileSystem } from "@core/filesystem/filesystem";
import { TreeNodeType } from "@core/filesystem/treenode";
import { NodePointer, NodeType, type SymlinkNode } from "@core/filesystem/node";
export function printTree(fs: FileSystem, root: number): string {
type Frame = {
ptr: NodePointer;
name: string;
prefix: string;
isLast: boolean;
};
function getSortedChildren(fs: FileSystem, ptr: NodePointer): Array<{ name: string; ptr: NodePointer }> {
const node = fs.getNode(ptr);
if (!node || node.type !== NodeType.Directory) return [];
const entries = Array.from(node.children.entries());
entries.sort(([a], [b]) => a.localeCompare(b));
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[] = [];
lines.push(rootNode.name + ` (${rootNode.inode})`);
type Frame = {
inode: number;
prefix: string;
isLast: boolean;
};
const rootSuffix = mountSuffix(fs, root) + symlinkSuffix(rootNode);
lines.push(`${rootLabel} ${root.toString()}${rootSuffix}`);
const stack: Frame[] = [];
const getSorterChildren = (inode: number): number[] => {
const node = fs.getNode(inode);
if (!node || node.type !== TreeNodeType.Directory) return [];
const entries = Object.entries(node.children);
entries.sort(([a], [b]) => a.localeCompare(b));
return entries.map(([, childInode]) => childInode) as number[];
};
const rootChildren = getSorterChildren(root);
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 + ` (${node.inode})`);
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");
}
-92
View File
@@ -1,92 +0,0 @@
import type { CommandIO } from "@core/command_io";
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 { withCwd, type ShellState } from "@core/shell_state";
import type { PathResolutionError } from "@core/util/errors";
import { Fixture } from "@tests/helpers/state_fixture";
import { expect, test } from "vitest";
const stdout: Uint8Array[] = [];
const stderr: Uint8Array[] = [];
const io: CommandIO = {
writeStdout: (data: Uint8Array) => {
stdout.push(data);
},
writeStderr: (data: Uint8Array) => {
stderr.push(data);
},
getSignal: () => {
return new Promise(() => {});
},
};
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 = Fixture.State;
test("changes cwd to home", async () => {
let newState = withCwd(state, 2);
const output = await cd.fn(io, newState, [], []);
newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultSuccess).exitCode).toBe(0);
expect(session.cwd).toBe(Fixture.user.home);
expect(session.pwd).toBe(2);
});
test("changes cwd to pwd", async () => {
let newState = withCwd(state, 2);
const output = await cd.fn(io, 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", async () => {
const output = await cd.fn(io, state, [], ["/folder2/subdir2"]);
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)", async () => {
const output = await cd.fn(io, 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)", async () => {
const output = await cd.fn(io, state, [], ["/some-file"]);
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);
});
-33
View File
@@ -1,33 +0,0 @@
import type { CommandIO } from "@core/command_io";
import { descriptor as echo } from "@core/commands/echo";
import type { ResultSuccess } from "@core/result";
import { type ShellState } from "@core/shell_state";
import { Fixture } from "@tests/helpers/state_fixture";
import { expect, test } from "vitest";
const stdout: Uint8Array[] = [];
const stderr: Uint8Array[] = [];
const io: CommandIO = {
writeStdout: (data: Uint8Array) => {
stdout.push(data);
},
writeStderr: (data: Uint8Array) => {
stderr.push(data);
},
getSignal: () => {
return new Promise(() => {});
},
};
const state: ShellState = Fixture.State;
test("returns a Result of type success", async () => {
const output = await echo.fn(io, state, [], ["hello", "world"]);
const string = new TextDecoder().decode(stdout[0]);
expect(output.result.type).toBe("success");
expect((output.result as ResultSuccess).exitCode).toBe(0);
// Fix: added a newline character
expect(string).toEqual("hello world\n");
});
-36
View File
@@ -1,36 +0,0 @@
import type { ResultError } from "@core/result";
import { type ShellState } from "@core/shell_state";
import { SIGNAL_MAP } from "@core/signal";
import type { SignalTerminationError } from "@core/util/errors";
import { Shell } from "@shell/shell";
import { Fixture } from "@tests/helpers/state_fixture";
import { expect, test } from "vitest";
const state: ShellState = Fixture.State;
test("returns a Result of type success", async () => {
await Shell.init(state);
let result;
Shell.Instance?.on("result", payload => {
//const decoder = new TextDecoder();
//console.log(decoder.decode(payload.result.stdout.toArray()));
//console.log(payload);
result = payload.result;
expect(result.type).toBe("error");
expect((result as ResultError<SignalTerminationError>).error.exitCode).toEqual(130);
expect((result as ResultError<SignalTerminationError>).error.signalNumber).toEqual(SIGNAL_MAP.SIGINT);
});
await Shell.Instance?.execute("async");
Shell.Instance?.sendInput("a");
Shell.Instance?.sendInput("b");
Shell.Instance?.sendInput("c");
Shell.Instance?.sendInput("d");
Shell.Instance?.sendInput(
"right now technically anything goes because its just a plain string however i plan on improving this system a bit later on",
);
Shell.Instance?.sendInput("ctrl+c");
});
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 { Fixture7Depth } from "@tests/helpers/state_fixture";
import { describe, expect, test } from "vitest";
import { makeFS, makeShellState, makeTree, makeUser } from "@tests/helpers/filesystems_fixture";
import { describe, expect, it } from "vitest";
const state = Fixture7Depth.State;
const fs = state.filesystem;
// ============================================================================
// 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(state, 4, true)).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(state, 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 });
});
});
-57
View File
@@ -1,57 +0,0 @@
import { createInitialSessionState, getCurrentSession, login, logout } from "@core/session_manager";
import { Fixture } from "@tests/helpers/state_fixture";
import { describe, expect, test } from "vitest";
const state = Fixture.State;
const passMap = new Map();
passMap.set(0, "123");
passMap.set(1000, "321");
test("createInitialSessionState - successfully creates a new session state", () => {
const state = createInitialSessionState(Fixture.user);
expect(state.cwd).toEqual(Fixture.user.home);
expect(state.pwd).toEqual(Fixture.user.home);
expect(state.exitCode).toEqual(0);
expect(state.user).toBe(Fixture.user);
expect(Object.isFrozen(state)).toBe(true);
});
describe("login", () => {
test("it successfully starts a new session under the user test", () => {
const newState = login(state, "user", "321", passMap);
const pop = getCurrentSession(newState);
expect(pop.user).toEqual(Fixture.user2);
});
test("fails to start a new session. Cause: no password mapped to the uid", () => {
//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, "user", "321", passMap);
const newPop = getCurrentSession(newState);
expect(newPop.user).toEqual(Fixture.user2);
const newNewState = logout(state);
const pop = getCurrentSession(newNewState);
expect(pop.user).toEqual(Fixture.user);
});
});
-64
View File
@@ -1,64 +0,0 @@
import { getCurrentSession } from "@core/session_manager";
import { withCwd, withEnv, withExitCode, withHistory } from "@core/shell_state";
import { Fixture } from "@tests/helpers/state_fixture";
import { expect, test } from "vitest";
const state = Fixture.State;
test("createInitialShellState - initializes successfully", () => {
expect(state.sessionStack.at(0)).toBeDefined();
expect(state.users.get(Fixture.user.uid)).toEqual(Fixture.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(Fixture.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" }));
});
});
-63
View File
@@ -1,63 +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);
// This got changed from [0, 2, 3, 1] to [1, 2, 3]
// A bug in dnTraverseTree resulted in the tree traversal not respecting order of nodes, and including root.
// Including root in results caused further problems so it was decided that results wont include the passed root node;
expect(result, `Checking the result ${result} to be [1, 2, 3]`).toEqual([1, 2, 3]);
});
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(Number) 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,
});
}
+169 -59
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 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)),
};
}
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 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(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 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,
};
}
export function makeUser(home: NodePointer = NodePointer.of(0, 0)): UserInfo {
return {
username: "test",
uid: 1000,
gid: 1000,
group: [],
home,
};
map.set(node.inode, Object.freeze(fileNode));
}
// ============================================================================
// 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;
}
parse(tree, 0);
// ============================================================================
// Shell state fixture
// ============================================================================
const base: ReadonlyMap<number, TreeNode> = map;
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
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.init(base, overlay, base.size - 1);
return {
filesystem: fs,
users: new Map(),
groups: new Map(),
sessionStack: [session],
} as unknown as ShellState;
}
-91
View File
@@ -1,91 +0,0 @@
import { FileSystem } from "@core/filesystem/filesystem";
import type { TreeNode } from "@core/filesystem/treenode";
import type { GroupInfo, UserInfo } from "@core/session_manager";
import { createInitialShellState, type ShellState } from "@core/shell_state";
import { deserializeFileSystem } from "@shell/serializer";
import { buildTestFS } from "./filesystems_fixture";
import { depth7Tree } from "./tree_fixture";
export class Fixture {
/*
root (0)
├── folder1 (1)
│ └── subdir1 (2)
├── folder2 (3)
│ ├── subdir2 (4)
│ └── subdir3 (5)
│ └── empty-foo (6)
└── some-file (7)
*/
static 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"}`;
static user: UserInfo = {
username: "root",
uid: 0,
gid: 0, // <- PRIMARY GID
group: [0], // <- GROUPS ARRAY
home: 0,
};
static user2: UserInfo = {
username: "user",
uid: 1000,
gid: 1000,
group: [1000],
home: 1,
};
static nopass: UserInfo = {
username: "no pass",
uid: 1001,
gid: 1000,
group: [1000],
home: 2,
};
static group: GroupInfo = {
groupname: "root",
gid: 0,
members: [0], // <- UID
};
static group2: GroupInfo = {
groupname: "user",
gid: 1000,
members: [1000, 1001], // <- UID
};
public static get State(): ShellState {
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"}`;
const base = deserializeFileSystem(rawJson);
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
const fs = FileSystem.init(base, overlay, base.size - 1);
const users: Map<number, UserInfo> = new Map();
const groups: Map<number, GroupInfo> = new Map();
users.set(0, Fixture.user);
users.set(1000, Fixture.user2);
users.set(1001, Fixture.nopass);
groups.set(0, Fixture.group);
groups.set(1000, Fixture.group2);
return createInitialShellState(fs, users, groups, Fixture.user);
}
}
export class Fixture7Depth extends Fixture {
public static get State(): ShellState {
const fs = buildTestFS(depth7Tree);
const users: Map<number, UserInfo> = new Map();
const groups: Map<number, GroupInfo> = new Map();
users.set(0, Fixture7Depth.user);
users.set(1000, Fixture7Depth.user2);
groups.set(0, Fixture7Depth.group);
groups.set(1000, Fixture7Depth.group2);
return createInitialShellState(fs, users, groups, Fixture7Depth.user);
}
}
-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: [],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
};
-8
View File
@@ -1,8 +0,0 @@
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);
//expect(true).toEqual(false);
});
-29
View File
@@ -1,29 +0,0 @@
import { getCurrentSession } from "@core/session_manager";
import { Shell } from "@shell/shell";
import { Fixture } from "@tests/helpers/state_fixture";
import { describe, expect, test } from "vitest";
const state = Fixture.State;
describe("Shell tests", () => {
test("Successfully executes the cd command", async () => {
await Shell.init(state);
let result;
Shell.Instance?.on("result", payload => {
result = payload.result;
});
await Shell.Instance?.execute("cd /folder1");
const statee = Shell.Instance?.State;
expect(result!.type).toEqual("success");
expect(getCurrentSession(statee!).history.length).toBe(1);
expect(getCurrentSession(statee!).history[0]).toEqual("cd /folder1");
expect(getCurrentSession(statee!).cwd).toBe(1);
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", () => {});
});
+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,
});