axiodb
Version:
The Pure JavaScript Alternative to SQLite. Embedded NoSQL database for Node.js with MongoDB-style queries, zero native dependencies, built-in InMemoryCache, and web GUI. Perfect for desktop apps, CLI tools, and embedded systems. No compilation, no platfor
310 lines • 13.1 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/no-unused-vars */
const promises_1 = __importDefault(require("fs/promises"));
const fs_1 = __importDefault(require("fs"));
const worker_process_1 = __importDefault(require("../cli/worker_process"));
// Import Helpers
const response_helper_1 = __importDefault(require("../../Helper/response.helper"));
class FolderManager {
constructor() {
this.fileSystem = promises_1.default;
this.fileSystemSync = fs_1.default;
this.responseHelper = new response_helper_1.default();
this.WorkerProcess = new worker_process_1.default();
}
/**
* Creates a new directory at the specified path.
*/
CreateDirectory(path) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield this.fileSystem.mkdir(path, { recursive: true });
return this.responseHelper.Success(`Directory created at: ${path}`);
}
catch (error) {
return this.responseHelper.Error(`Failed to create directory: ${error}`);
}
});
}
/**
* Deletes a directory at the specified path.
*/
DeleteDirectory(path) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield this.fileSystem.rm(path, { recursive: true, force: true });
return this.responseHelper.Success(`Directory deleted: ${path}`);
}
catch (error) {
return this.responseHelper.Error(`Failed to delete directory: ${error}`);
}
});
}
/**
* Checks if a directory exists at the specified path.
*/
DirectoryExists(path) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield this.fileSystem.access(path);
return this.responseHelper.Success(false);
}
catch (_a) {
return this.responseHelper.Error(true);
}
});
}
/**
* Lists the contents of a directory at the specified path.
*/
ListDirectory(path) {
return __awaiter(this, void 0, void 0, function* () {
try {
const contents = yield this.fileSystem.readdir(path);
return this.responseHelper.Success(contents);
}
catch (error) {
return this.responseHelper.Error(`Failed to list directory: ${error}`);
}
});
}
/**
* Moves a directory from the old path to the new path.
*/
MoveDirectory(oldPath, newPath) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield this.fileSystem.rename(oldPath, newPath);
return this.responseHelper.Success(`Moved directory to: ${newPath}`);
}
catch (error) {
return this.responseHelper.Error(`Failed to move directory: ${error}`);
}
});
}
/**
* Locks a directory at the specified path.
*/
LockDirectory(path) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield this.fileSystem.chmod(path, 0o000);
return this.responseHelper.Success(`Directory locked: ${path}`);
}
catch (error) {
return this.responseHelper.Error(`Failed to lock directory: ${error}`);
}
});
}
/**
* Unlocks a directory at the specified path.
*/
UnlockDirectory(path) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield this.fileSystem.chmod(path, 0o777);
return this.responseHelper.Success(`Directory unlocked: ${path}`);
}
catch (error) {
return this.responseHelper.Error(`Failed to unlock directory: ${error}`);
}
});
}
/**
* Checks if a directory is locked at the specified path.
*/
IsDirectoryLocked(path) {
return __awaiter(this, void 0, void 0, function* () {
try {
const stats = yield this.fileSystem.stat(path);
const isLocked = (stats.mode & 0o200) === 0; // Check if the directory is locked (no write permission for owner)
return this.responseHelper.Success(isLocked);
}
catch (error) {
return this.responseHelper.Error(`Failed to check lock status: ${error}`);
}
});
}
/**
* get the size of a directory at the specified path.
* Handles permission issues by temporarily modifying permissions if needed.
*/
GetDirectorySize(path) {
return __awaiter(this, void 0, void 0, function* () {
// Store original permissions to restore later
const permissionsMap = new Map();
try {
// Check if directory exists
try {
yield this.fileSystem.access(path);
}
catch (error) {
return this.responseHelper.Error(`Directory does not exist or is inaccessible: ${error}`);
}
// Collect and store original permissions, unlock files/folders as needed
yield this.prepareDirectoryForSizeCalculation(path, permissionsMap);
// Now perform the size calculation
const osType = worker_process_1.default.getOS();
let size;
if (osType === "windows") {
try {
// More comprehensive PowerShell command that handles directories better
const stdout = yield this.WorkerProcess.execCommand(`powershell -command "(Get-ChildItem '${path}' -Recurse -Force | Measure-Object -Property Length -Sum).Sum"`);
size = parseInt(stdout, 10) || 0;
}
catch (cmdError) {
console.warn(`Windows command failed: ${cmdError}, using fallback method`);
size = yield this.calculateDirectorySizeRecursively(path);
}
}
else {
try {
// Try du with error redirection
const stdout = yield this.WorkerProcess.execCommand(`du -sb "${path}" 2>/dev/null`);
size = parseInt(stdout.split("\t")[0], 10) || 0;
}
catch (cmdError) {
console.warn(`Unix command failed: ${cmdError}, using fallback method`);
size = yield this.calculateDirectorySizeRecursively(path);
}
}
return this.responseHelper.Success(size);
}
catch (err) {
console.error(`Error getting directory size: ${err}`);
return this.responseHelper.Error(`Failed to get directory size: ${err}`);
}
finally {
// Restore original permissions
yield this.restoreDirectoryPermissions(permissionsMap);
}
});
}
/**
* Recursively prepares a directory and its contents for size calculation
* by temporarily modifying permissions if needed.
*/
prepareDirectoryForSizeCalculation(dirPath, permissionsMap) {
return __awaiter(this, void 0, void 0, function* () {
try {
// Store original directory permissions
try {
const stats = yield this.fileSystem.stat(dirPath);
permissionsMap.set(dirPath, stats.mode);
// If directory isn't readable, make it readable
if ((stats.mode & 0o444) !== 0o444) {
yield this.fileSystem.chmod(dirPath, 0o755);
}
}
catch (error) {
console.warn(`Could not check/modify permissions for ${dirPath}: ${error}`);
return;
}
// Process directory contents
let items;
try {
items = yield this.fileSystem.readdir(dirPath);
}
catch (error) {
console.warn(`Could not read directory ${dirPath}: ${error}`);
return;
}
// Process each item recursively
for (const item of items) {
const itemPath = `${dirPath}/${item}`;
try {
const stats = yield this.fileSystem.stat(itemPath);
// Store original permissions
permissionsMap.set(itemPath, stats.mode);
if (stats.isDirectory()) {
// If subdirectory isn't readable, make it readable
if ((stats.mode & 0o444) !== 0o444) {
yield this.fileSystem.chmod(itemPath, 0o755);
}
// Recursively process subdirectory
yield this.prepareDirectoryForSizeCalculation(itemPath, permissionsMap);
}
else if (stats.isFile()) {
// If file isn't readable, make it readable
if ((stats.mode & 0o444) !== 0o444) {
yield this.fileSystem.chmod(itemPath, 0o644);
}
}
}
catch (itemError) {
// Continue with other items
}
}
}
catch (error) {
console.warn(`Error preparing directory ${dirPath}: ${error}`);
}
});
}
/**
* Restores original permissions for all modified files and directories
*/
restoreDirectoryPermissions(permissionsMap) {
return __awaiter(this, void 0, void 0, function* () {
// Convert to array and reverse to handle deepest paths first
const paths = Array.from(permissionsMap.keys()).reverse();
for (const path of paths) {
const originalMode = permissionsMap.get(path);
if (originalMode !== undefined) {
try {
yield this.fileSystem.chmod(path, originalMode);
}
catch (error) {
console.warn(`Failed to restore permissions for ${path}: ${error}`);
}
}
}
});
}
/**
* Calculates directory size recursively using Node.js native functions.
* This is a fallback method for when command-line tools fail.
*/
calculateDirectorySizeRecursively(dirPath) {
return __awaiter(this, void 0, void 0, function* () {
let totalSize = 0;
try {
const items = yield this.fileSystem.readdir(dirPath);
for (const item of items) {
const itemPath = `${dirPath}/${item}`;
try {
const stats = yield this.fileSystem.stat(itemPath);
if (stats.isDirectory()) {
totalSize += yield this.calculateDirectorySizeRecursively(itemPath);
}
else if (stats.isFile()) {
totalSize += stats.size;
}
}
catch (itemError) {
console.warn(`Skipping item during size calculation: ${itemPath}: ${itemError}`);
}
}
}
catch (error) {
console.warn(`Error reading directory during size calculation: ${dirPath}: ${error}`);
}
return totalSize;
});
}
}
exports.default = FolderManager;
//# sourceMappingURL=FolderManager.js.map