UNPKG

@synet/patterns

Version:

Robust, battle-tested collection of stable patterns used in Synet packages

113 lines (112 loc) 3.54 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FileIndexer = void 0; const promises_1 = __importDefault(require("node:fs/promises")); const node_path_1 = __importDefault(require("node:path")); class FileIndexer { constructor(directory) { this.directory = directory; this.indexCache = null; this.indexPath = node_path_1.default.join(directory, "index.json"); promises_1.default.mkdir(directory, { recursive: true }).catch((err) => { console.error(`Error creating directory: ${err}`); }); } async exists() { try { await promises_1.default.access(this.indexPath); return true; } catch { return false; } } async create(entry) { const index = await this.loadIndex(); index[entry.alias] = entry; await this.saveIndex(index); } async get(idOrAlias) { const index = await this.loadIndex(); // First try as alias if (index[idOrAlias]) return index[idOrAlias]; // Then try as ID for (const alias in index) { if (index[alias].id === idOrAlias) { return index[alias]; } } return null; } async find(keyword) { const index = await this.loadIndex(); return (Object.values(index).find((entry) => entry.alias === keyword || entry.id === keyword) || null); } async delete(idOrAlias) { const index = await this.loadIndex(); // Try as alias first if (index[idOrAlias]) { delete index[idOrAlias]; await this.saveIndex(index); return true; } // Try as ID for (const alias in index) { if (index[alias].id === idOrAlias) { delete index[alias]; await this.saveIndex(index); return true; } } return false; } async list() { const index = await this.loadIndex(); return Object.values(index); } async rebuild(entries) { const newIndex = {}; for (const entry of entries) { if (entry.id && entry.alias) { newIndex[entry.alias] = entry; } } await this.saveIndex(newIndex); } async loadIndex() { if (this.indexCache) return this.indexCache; try { const exists = await this.exists(); if (!exists) return {}; const content = await promises_1.default.readFile(this.indexPath, "utf8"); const parsed = JSON.parse(content); // Handle format variations if (parsed.entries) { this.indexCache = parsed.entries; } else { this.indexCache = parsed; } return this.indexCache || {}; } catch (error) { console.error(`Error loading index: ${error}`); return {}; } } async saveIndex(index) { const withVersion = { entries: index, version: "1.0.0", }; await promises_1.default.writeFile(this.indexPath, JSON.stringify(withVersion, null, 2)); this.indexCache = index; } } exports.FileIndexer = FileIndexer;