fastv0
Version:
Fast File System Operations and AI Integration for Node.js - Like Cursor's token management
239 lines • 9.47 kB
JavaScript
/**
* File Manager - Core file operations for AI assistants
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileManager = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const glob_1 = require("glob");
class FileManager {
constructor(basePath, maxFileSize = 10 * 1024 * 1024) {
this.basePath = basePath || process.cwd();
this.maxFileSize = maxFileSize;
this.supportedExtensions = new Set([
'.py', '.js', '.ts', '.tsx', '.jsx', '.html', '.css', '.scss',
'.json', '.yaml', '.yml', '.md', '.txt', '.csv', '.xml', '.sql',
'.sh', '.bat', '.ps1', '.dockerfile', '.gitignore'
]);
}
async readFile(filePath, encoding = 'utf8') {
try {
const fullPath = path.resolve(filePath);
// Security check
if (!this.isSafePath(fullPath)) {
return { success: false, error: 'Unsafe file path' };
}
// Check if file exists
if (!await fs.pathExists(fullPath)) {
return { success: false, error: 'File does not exist' };
}
// Check file size
const stats = await fs.stat(fullPath);
if (stats.size > this.maxFileSize) {
return { success: false, error: `File too large: ${stats.size} bytes` };
}
// Read file content
const content = await fs.readFile(fullPath, encoding);
const fileInfo = await this.getFileInfo(fullPath);
return {
success: true,
content: content.toString(),
filePath: fullPath,
fileInfo: fileInfo.success ? fileInfo.fileInfo : undefined
};
}
catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
}
async writeFile(filePath, content, encoding = 'utf8', createDirs = true) {
try {
const fullPath = path.resolve(filePath);
// Security check
if (!this.isSafePath(fullPath)) {
return { success: false, error: 'Unsafe file path' };
}
// Create directories if needed
if (createDirs) {
await fs.ensureDir(path.dirname(fullPath));
}
// Write file content
await fs.writeFile(fullPath, content, encoding);
return {
success: true,
filePath: fullPath,
content: content
};
}
catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
}
async listFiles(directory, recursive = false, extensions) {
try {
const fullPath = path.resolve(directory);
if (!await fs.pathExists(fullPath)) {
return { success: false, error: 'Directory does not exist' };
}
const stats = await fs.stat(fullPath);
if (!stats.isDirectory()) {
return { success: false, error: 'Path is not a directory' };
}
const pattern = recursive ? '**/*' : '*';
const files = await (0, glob_1.glob)(pattern, { cwd: fullPath, nodir: true });
const fileInfos = [];
for (const file of files) {
const filePath = path.join(fullPath, file);
// Filter by extensions if specified
if (extensions && !extensions.includes(path.extname(filePath))) {
continue;
}
const fileInfo = await this.getFileInfo(filePath);
if (fileInfo.success && fileInfo.fileInfo) {
fileInfos.push(fileInfo.fileInfo);
}
}
return {
success: true,
files: fileInfos,
count: fileInfos.length
};
}
catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
}
async searchFiles(directory, query, fileTypes) {
try {
const fullPath = path.resolve(directory);
const results = [];
// Search by filename
const allFiles = await (0, glob_1.glob)('**/*', { cwd: fullPath, nodir: true });
for (const file of allFiles) {
const filePath = path.join(fullPath, file);
// Filter by file types if specified
if (fileTypes && !fileTypes.includes(path.extname(filePath))) {
continue;
}
// Search in filename
if (file.toLowerCase().includes(query.toLowerCase())) {
results.push({
type: 'filename',
filePath: filePath,
match: file
});
}
// Search in content for text files
const ext = path.extname(filePath);
if (['.py', '.js', '.ts', '.tsx', '.jsx', '.html', '.css', '.md', '.txt'].includes(ext)) {
try {
const content = await fs.readFile(filePath, 'utf8');
if (content.toLowerCase().includes(query.toLowerCase())) {
results.push({
type: 'content',
filePath: filePath,
match: query
});
}
}
catch {
// Skip files that can't be read
continue;
}
}
}
return {
success: true,
results: results,
count: results.length,
query: query
};
}
catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
results: [],
count: 0,
query: query
};
}
}
async getFileInfo(filePath) {
try {
const fullPath = path.resolve(filePath);
if (!await fs.pathExists(fullPath)) {
return { success: false, error: 'File does not exist' };
}
const stats = await fs.stat(fullPath);
const ext = path.extname(fullPath);
const fileInfo = {
name: path.basename(fullPath),
path: fullPath,
size: stats.size,
sizeMB: Math.round((stats.size / (1024 * 1024)) * 100) / 100,
extension: ext,
modifiedTime: stats.mtime.toISOString(),
createdTime: stats.birthtime.toISOString(),
isCode: this.supportedExtensions.has(ext),
isDocument: ['.txt', '.doc', '.docx', '.pdf', '.md'].includes(ext),
isImage: ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'].includes(ext),
isVideo: ['.mp4', '.avi', '.mov', '.wmv', '.flv'].includes(ext),
isArchive: ['.zip', '.rar', '.7z', '.tar', '.gz'].includes(ext)
};
return {
success: true,
fileInfo: fileInfo
};
}
catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
}
isSafePath(filePath) {
try {
const resolved = path.resolve(filePath);
const baseResolved = path.resolve(this.basePath);
return resolved.startsWith(baseResolved);
}
catch {
return false;
}
}
}
exports.FileManager = FileManager;
//# sourceMappingURL=file-manager.js.map
;