import { sha256 } from "js-sha256";
const CACHE_NAME = "pkcjs_lrustorage_nameResolutions";
const CACHE_MAX_ITEMS = 5000;
// Wraps the existing LRUStorageInterface (Node SQLite + browser localforage + in-memory under noData)
// to provide typed name-resolution caching with HTTP-style max-age freshness control.
export class NameResolutionCache {
    constructor(pkc) {
        this._pkc = pkc;
    }
    async _store() {
        return this._pkc._createStorageLRU({ cacheName: CACHE_NAME, maxItems: CACHE_MAX_ITEMS });
    }
    static _key({ name, resolverKey, provider }) {
        return `${name}::${resolverKey}::${sha256(provider)}`;
    }
    // Returns the cached entry only if it satisfies cache.maxAge (seconds).
    //   cache.maxAge === 0     → always returns undefined (bypass)
    //   cache.maxAge === N     → returns entry if Date.now() - resolvedAtMs <= N * 1000
    //   cache.maxAge undefined → no freshness threshold, returns whatever is cached
    async get(args) {
        if (args.cache?.maxAge === 0)
            return undefined;
        const store = await this._store();
        const entry = (await store.getItem(NameResolutionCache._key(args)));
        if (!entry || typeof entry !== "object" || typeof entry.publicKey !== "string")
            return undefined;
        if (typeof args.cache?.maxAge === "number") {
            const ageMs = Date.now() - entry.resolvedAtMs;
            if (ageMs > args.cache.maxAge * 1000)
                return undefined;
        }
        return entry;
    }
    async set(args) {
        const store = await this._store();
        await store.setItem(NameResolutionCache._key({
            name: args.name,
            resolverKey: args.entry.resolverKey,
            provider: args.entry.provider
        }), args.entry);
    }
}
//# sourceMappingURL=name-resolution-cache.js.map