import { LRUCache } from 'lru-cache';
import { epochTime } from './utils.js';
export class InMemoryAdapter {
    type;
    constructor(type) {
        this.type = type;
    }
    tokenStorage = new LRUCache({ max: 1000 });
    sessionStorage = new LRUCache({ max: 1000 });
    grantIdStorage = new LRUCache({ max: 1000 });
    key(id) {
        return `${this.type}:${id}`;
    }
    async upsert(id, payload, expiresIn) {
        const key = this.key(id);
        if (this.type === 'Session' && payload.uid) {
            this.sessionStorage.set(payload.uid, id, {
                ttl: expiresIn * 1000
            });
        }
        const { grantId, userCode } = payload;
        if (grantId) {
            this.grantIdStorage.set(grantId, [key]);
            const grant = this.grantIdStorage.get(grantId);
            if (!grant) {
                this.grantIdStorage.set(grantId, [key]);
            }
            else {
                grant.push(key);
            }
        }
        if (userCode) {
            throw 'UNSUPPORTED';
        }
        this.tokenStorage.set(key, payload, {
            ttl: expiresIn * 1000
        });
    }
    findByUserCode(userCode) {
        throw new Error('UNSUPPORTED');
    }
    async find(id) {
        return this.tokenStorage.get(this.key(id));
    }
    async findByUid(uid) {
        const id = await this.sessionStorage.get(uid);
        return id ? this.find(id) : undefined;
    }
    async consume(id) {
        const payload = this.tokenStorage.get(this.key(id));
        if (payload) {
            payload.consumed = epochTime();
        }
    }
    async destroy(id) {
        this.tokenStorage.delete(this.key(id));
    }
    async revokeByGrantId(grantId) {
        const grant = this.grantIdStorage.get(grantId);
        if (grant) {
            grant.forEach((token) => this.tokenStorage.delete(token));
            this.grantIdStorage.delete(grantId);
        }
    }
}
//# sourceMappingURL=in-memory-adapter.js.map