Forked from bakit/terminal
Forked from bakit/terminal
src / cache.ts
import { logger } from "./logger";
interface CacheEntry<T> {
value: T;
expiresAt: number;
}
/**
* Simple in-memory TTL cache.
*/
export class Cache<T = any> {
private store = new Map<string, CacheEntry<T>>();
private defaultTtlMs: number;
constructor(defaultTtlMs = 60_000) {
this.defaultTtlMs = defaultTtlMs;
}
get(key: string): T | undefined {
const entry = this.store.get(key);
if (!entry) return undefined;
if (Date.now() > entry.expiresAt) {
this.store.delete(key);
return undefined;
}
return entry.value;
}
set(key: string, value: T, ttlMs?: number): void {
const expiresAt = Date.now() + (ttlMs ?? this.defaultTtlMs);
this.store.set(key, { value, expiresAt });
}
has(key: string): boolean {
return this.get(key) !== undefined;
}
delete(key: string): boolean {
return this.store.delete(key);
}
clear(): void {
this.store.clear();
}
size(): number {
return this.store.size;
}
/**
* Evict expired entries.
*/
evictExpired(): number {
const now = Date.now();
let evicted = 0;
for (const [key, entry] of this.store) {
if (now > entry.expiresAt) {
this.store.delete(key);
evicted++;
}
}
return evicted;
}
}
/**
* Command result cache — stores execCommand results keyed by command + cwd.
*/
export const commandCache = new Cache<string>(5 * 60 * 1000);
src / cache.ts
import { logger } from "./logger";
interface CacheEntry<T> {
value: T;
expiresAt: number;
}
/**
* Simple in-memory TTL cache.
*/
export class Cache<T = any> {
private store = new Map<string, CacheEntry<T>>();
private defaultTtlMs: number;
constructor(defaultTtlMs = 60_000) {
this.defaultTtlMs = defaultTtlMs;
}
get(key: string): T | undefined {
const entry = this.store.get(key);
if (!entry) return undefined;
if (Date.now() > entry.expiresAt) {
this.store.delete(key);
return undefined;
}
return entry.value;
}
set(key: string, value: T, ttlMs?: number): void {
const expiresAt = Date.now() + (ttlMs ?? this.defaultTtlMs);
this.store.set(key, { value, expiresAt });
}
has(key: string): boolean {
return this.get(key) !== undefined;
}
delete(key: string): boolean {
return this.store.delete(key);
}
clear(): void {
this.store.clear();
}
size(): number {
return this.store.size;
}
/**
* Evict expired entries.
*/
evictExpired(): number {
const now = Date.now();
let evicted = 0;
for (const [key, entry] of this.store) {
if (now > entry.expiresAt) {
this.store.delete(key);
evicted++;
}
}
return evicted;
}
}
/**
* Command result cache — stores execCommand results keyed by command + cwd.
*/
export const commandCache = new Cache<string>(5 * 60 * 1000);