import { type DiagnosticLogEntry, DIAGNOSTIC_STORAGE_KEYS } from '../types/diagnostic'; import { type StorageManager, storage } from '../utils/storage'; const MAX_RECENT_LOGS = 300; type DiagnosticStoreStorage = Pick; export class DiagnosticLogStore { private appendChain: Promise = Promise.resolve(); constructor(private readonly storageManager: DiagnosticStoreStorage = storage) {} async append(entry: DiagnosticLogEntry): Promise { const runAppend = async () => { const recent = await this.getRecent(); const next = [...recent, entry]; if (next.length > MAX_RECENT_LOGS) { next.splice(0, next.length - MAX_RECENT_LOGS); } await this.storageManager.set(DIAGNOSTIC_STORAGE_KEYS.RECENT_LOGS, next); }; const appendPromise = this.appendChain.then(runAppend, runAppend); this.appendChain = appendPromise.catch(() => undefined); return appendPromise; } async getRecent(): Promise { const stored = await this.storageManager.get( DIAGNOSTIC_STORAGE_KEYS.RECENT_LOGS ); return Array.isArray(stored) ? stored : []; } async clear(): Promise { await this.storageManager.remove(DIAGNOSTIC_STORAGE_KEYS.RECENT_LOGS); } }