organ-ai-zer
Version:
AI-powered file organizer CLI tool
277 lines • 10 kB
JavaScript
"use strict";
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.BaseCache = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const crypto = __importStar(require("crypto"));
const os = __importStar(require("os"));
/**
* Base cache class providing common caching functionality
* All specific cache implementations should extend this class
*/
class BaseCache {
constructor(config) {
this.memoryCache = new Map();
this.config = config;
this.cacheDir = path.join(os.homedir(), '.organ-ai-zer', 'cache', config.subDirectory);
}
/**
* Get cached data for a directory
*/
async getCached(directory, files, configHash) {
const cacheKey = this.getCacheKey(directory);
const directoryHash = this.calculateDirectoryHash(files);
// Check memory cache first
const memoryCache = this.memoryCache.get(cacheKey);
if (memoryCache && this.isValidCache(memoryCache, directoryHash, configHash)) {
console.log(`💾 Using cached ${this.config.subDirectory} from memory`);
return memoryCache.data;
}
// Check disk cache
try {
const diskCache = await this.loadFromDisk(cacheKey);
if (diskCache && this.isValidCache(diskCache, directoryHash, configHash)) {
console.log(`💿 Using cached ${this.config.subDirectory} from disk`);
// Refresh memory cache
this.memoryCache.set(cacheKey, diskCache);
return diskCache.data;
}
}
catch (error) {
console.log(`📁 No valid ${this.config.subDirectory} cache found`);
}
return null;
}
/**
* Cache data for a directory
*/
async cache(directory, files, data, configHash) {
const cacheKey = this.getCacheKey(directory);
const directoryHash = this.calculateDirectoryHash(files);
const cachedData = {
data,
directoryHash,
timestamp: Date.now(),
fileCount: files.length,
...(configHash && { configHash })
};
// Store in memory
this.memoryCache.set(cacheKey, cachedData);
console.log(`💾 Cached ${this.config.subDirectory} for ${files.length} files in memory`);
// Store on disk
try {
await this.saveToDisk(cacheKey, cachedData);
console.log(`💿 Cached ${this.config.subDirectory} to disk`);
}
catch (error) {
console.warn(`⚠️ Failed to save ${this.config.subDirectory} cache to disk:`, error);
}
}
/**
* Clear cache for specific directory or all
*/
async clearCache(directory) {
if (directory) {
const cacheKey = this.getCacheKey(directory);
this.memoryCache.delete(cacheKey);
try {
const diskPath = this.getDiskCachePath(cacheKey);
await fs.remove(diskPath);
console.log(`🗑️ Cleared ${this.config.subDirectory} cache for directory`);
}
catch (error) {
// Ignore if file doesn't exist
}
}
else {
this.memoryCache.clear();
try {
await fs.remove(this.cacheDir);
console.log(`🗑️ Cleared all ${this.config.subDirectory} caches`);
}
catch (error) {
// Ignore if directory doesn't exist
}
}
}
/**
* Get cache statistics
*/
getCacheStats() {
return {
memoryEntries: this.memoryCache.size,
diskCacheDir: this.cacheDir,
ttlMs: this.config.ttlMs,
subDirectory: this.config.subDirectory
};
}
/**
* Clean expired cache entries
*/
async cleanExpiredCache() {
const now = Date.now();
// Clean memory cache
for (const [key, cache] of this.memoryCache.entries()) {
if ((now - cache.timestamp) >= this.config.ttlMs) {
this.memoryCache.delete(key);
}
}
// Clean disk cache
try {
if (await fs.pathExists(this.cacheDir)) {
const files = await fs.readdir(this.cacheDir);
for (const file of files) {
if (file.endsWith('.json')) {
const filePath = path.join(this.cacheDir, file);
try {
const data = await fs.readJson(filePath);
if ((now - data.timestamp) >= this.config.ttlMs) {
await fs.remove(filePath);
}
}
catch (error) {
// Remove corrupted cache files
await fs.remove(filePath);
}
}
}
}
}
catch (error) {
console.warn(`⚠️ Failed to clean ${this.config.subDirectory} disk cache:`, error);
}
}
/**
* Get all cached directories
*/
async getCachedDirectories() {
const directories = [];
try {
if (await fs.pathExists(this.cacheDir)) {
const files = await fs.readdir(this.cacheDir);
for (const file of files) {
if (file.endsWith('.json')) {
const cacheKey = file.replace('.json', '');
if (this.config.filePrefix) {
if (file.startsWith(this.config.filePrefix)) {
directories.push(cacheKey.replace(this.config.filePrefix, ''));
}
}
else {
directories.push(cacheKey);
}
}
}
}
}
catch (error) {
// Ignore errors, return empty array
}
return directories;
}
/**
* Generate cache key for directory
*/
getCacheKey(directory) {
return crypto.createHash('md5').update(path.resolve(directory)).digest('hex');
}
/**
* Calculate hash of directory contents for change detection
*/
calculateDirectoryHash(files) {
const state = {
files: files.map(f => ({
name: f.name,
size: f.size,
modified: f.modified.getTime()
})).sort((a, b) => a.name.localeCompare(b.name))
};
return crypto.createHash('md5').update(JSON.stringify(state)).digest('hex');
}
/**
* Check if cached data is still valid
*/
isValidCache(cache, currentDirectoryHash, currentConfigHash) {
const now = Date.now();
const isNotExpired = (now - cache.timestamp) < this.config.ttlMs;
const directoryUnchanged = cache.directoryHash === currentDirectoryHash;
const configUnchanged = this.config.useConfigHash ?
(cache.configHash === currentConfigHash) : true;
if (!isNotExpired) {
console.log(`⏰ ${this.config.subDirectory} cache expired`);
return false;
}
if (!directoryUnchanged) {
console.log(`📁 Directory contents changed, ${this.config.subDirectory} cache invalid`);
return false;
}
if (!configUnchanged) {
console.log(`⚙️ Configuration changed, ${this.config.subDirectory} cache invalid`);
return false;
}
return true;
}
/**
* Get disk cache file path
*/
getDiskCachePath(cacheKey) {
const filename = this.config.filePrefix ?
`${this.config.filePrefix}${cacheKey}.json` :
`${cacheKey}.json`;
return path.join(this.cacheDir, filename);
}
/**
* Load cached data from disk
*/
async loadFromDisk(cacheKey) {
const cachePath = this.getDiskCachePath(cacheKey);
if (!(await fs.pathExists(cachePath))) {
return null;
}
const data = await fs.readJson(cachePath);
return data;
}
/**
* Save cached data to disk
*/
async saveToDisk(cacheKey, data) {
await fs.ensureDir(this.cacheDir);
const cachePath = this.getDiskCachePath(cacheKey);
await fs.writeJson(cachePath, data, { spaces: 2 });
}
}
exports.BaseCache = BaseCache;
//# sourceMappingURL=base-cache.js.map