/** * Persistor - Unified cache provider for Sandlot. * * This module provides a generic caching abstraction that can be used * by various components (typechecker, types resolver, etc.) with different * backend implementations (in-memory, IndexedDB, filesystem, etc.). */ import type { ResolvedTypes } from "./esm-types-resolver"; // ============================================================================= // Cache Interface // ============================================================================= /** * Generic async cache interface. * All cache operations are async to support both sync (Map) and async (IndexedDB) backends. */ export interface ICache { get(key: string): Promise; set(key: string, value: T): Promise; has(key: string): Promise; delete(key: string): Promise; clear(): Promise; } // ============================================================================= // Persistor Interface // ============================================================================= /** * Unified cache provider for Sandlot. * * Provides typed caches for different resource types. * All caches use the generic ICache interface. */ export interface IPersistor { /** * Cache for TypeScript lib files (lib.dom.d.ts, lib.es2020.d.ts, etc.) * * Key format: `ts:${version}:${libName}` * Example: `ts:5.9.3:dom` * * Value: The .d.ts file content as a string */ readonly tsLibs: ICache; /** * Cache for npm package type definitions. * * Key format: `types:${package}@${version}` * Example: `types:lodash@4.17.21` * * Value: ResolvedTypes object containing all .d.ts files for the package */ readonly packageTypes: ICache; } // ============================================================================= // In-Memory Implementation // ============================================================================= /** * Simple in-memory cache implementation using a Map. * Works on all platforms (browser, Node.js, Bun, Deno). */ export class InMemoryCache implements ICache { private cache = new Map(); async get(key: string): Promise { return this.cache.get(key) ?? null; } async set(key: string, value: T): Promise { this.cache.set(key, value); } async has(key: string): Promise { return this.cache.has(key); } async delete(key: string): Promise { this.cache.delete(key); } async clear(): Promise { this.cache.clear(); } } /** * In-memory persistor implementation. * Suitable for single-session usage where persistence across reloads is not needed. */ export class InMemoryPersistor implements IPersistor { readonly tsLibs = new InMemoryCache(); readonly packageTypes = new InMemoryCache(); } /** * Create an in-memory persistor instance. */ export function createInMemoryPersistor(): IPersistor { return new InMemoryPersistor(); }