UNPKG

locatai-ts

Version:

Enterprise-grade AI-powered element locator for Selenium WebDriver - TypeScript implementation

108 lines 3.53 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.JsonFileLocatorCache = void 0; const path_1 = __importDefault(require("path")); const JsonFileHelpers_1 = require("./JsonFileHelpers"); /** * File-based implementation of ILocatorCache that stores locators in a JSON file */ class JsonFileLocatorCache { /** * Creates a new JSON file locator cache * @param root Optional root directory path */ constructor(root = process.cwd()) { this._gate = Promise.resolve(); this._cache = { version: 1, entries: [] }; this._cacheDir = path_1.default.join(root, 'LocatAICache'); this._filePath = path_1.default.join(this._cacheDir, 'locatai_cache.json'); this._init(); } /** * Initialize the cache by loading from disk */ async _init() { await (0, JsonFileHelpers_1.ensureDir)(this._cacheDir); this._cache = await (0, JsonFileHelpers_1.readJson)(this._filePath, { version: 1, entries: [] }); } /** * Execute a function with lock to prevent concurrent file access * @param work Function to execute * @returns Result of the function */ async _lock(work) { const prev = this._gate; let release; this._gate = new Promise(r => (release = r)); await prev; try { const result = await work(); await (0, JsonFileHelpers_1.writeJson)(this._filePath, this._cache); return result; } finally { release(); } } /** * @inheritdoc */ async tryGet(url, query, domHash) { await this._gate; const entry = this._cache.entries.find(e => e.url === url && e.query === query && e.dom === domHash); if (!entry) return []; return entry.locators .sort((a, b) => b.conf - a.conf) .map(l => ({ strategy: l.by, value: l.value, confidence: l.conf, successRate: l.sr })); } /** * @inheritdoc */ async save(url, query, domHash, locators) { await this._lock(async () => { this._cache.entries = this._cache.entries.filter(e => !(e.url === url && e.query === query && e.dom === domHash)); this._cache.entries.push({ url, query, dom: domHash, ts: new Date().toISOString(), locators: locators.map(l => ({ by: l.strategy, value: l.value, conf: l.confidence, sr: l.successRate || 0 })) }); }); } /** * @inheritdoc */ async removeLocator(url, query, domHash, strategy, value) { await this._lock(async () => { const entry = this._cache.entries.find(e => e.url === url && e.query === query && e.dom === domHash); if (entry) { entry.locators = entry.locators.filter(l => !(l.by === strategy && l.value === value)); } }); } /** * @inheritdoc */ async clear() { await this._lock(async () => { this._cache.entries = []; }); } } exports.JsonFileLocatorCache = JsonFileLocatorCache; //# sourceMappingURL=JsonFileLocatorCache.js.map