
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="999c8f6f-f4fe-5e70-ba9b-9141b3a263e7")}catch(e){}}();
import { createHash } from 'node:crypto';
import log from '@apify/log';
import { PRICING_TIERS } from './pricing_info.js';
import { TTLLRUCache } from './ttl_lru.js';
const USER_CACHE_MAX_SIZE = 200;
const USER_CACHE_TTL_SECS = 60 * 60; // 1 hour
const ANONYMOUS_USER_INFO = { userId: null, userPlanTier: 'FREE' };
// LRU cache with TTL for user info - keyed by hashed token
const userInfoCache = new TTLLRUCache(USER_CACHE_MAX_SIZE, USER_CACHE_TTL_SECS);
function normalizePlanTier(tier) {
    if (!tier)
        return 'FREE';
    const upper = tier.toUpperCase();
    const match = PRICING_TIERS.find((t) => t === upper);
    if (match)
        return match;
    // Enterprise / custom plan names fall through to FREE; log so we can spot them in the wild.
    log.info(`Unrecognized plan tier "${tier}", defaulting to FREE`);
    return 'FREE';
}
/**
 * Gets user info (id + plan tier) from token, using cache to avoid repeated API calls.
 * Token is hashed before caching to avoid storing raw tokens.
 *
 * Defensive defaults: returns `{ userId: null, userPlanTier: 'FREE' }` when the token is
 * missing/empty, the API call fails, or the plan is unrecognized. Failed lookups are NOT
 * cached so the next call retries.
 */
export async function getUserInfoCached(token, apifyClient) {
    var _a;
    if (!token)
        return ANONYMOUS_USER_INFO;
    const tokenHash = createHash('sha256').update(token).digest('hex');
    const cached = userInfoCache.get(tokenHash);
    if (cached)
        return cached;
    try {
        const user = await apifyClient.user('me').get();
        if (!(user === null || user === void 0 ? void 0 : user.id)) {
            return { ...ANONYMOUS_USER_INFO };
        }
        // `tier` is present on /v2/users/me `plan` response (FREE/BRONZE/SILVER/GOLD/PLATINUM/DIAMOND)
        // but missing from apify-client's type declaration — hence the cast.
        const planTier = (_a = user.plan) === null || _a === void 0 ? void 0 : _a.tier;
        const info = {
            userId: user.id,
            userPlanTier: normalizePlanTier(planTier),
        };
        userInfoCache.set(tokenHash, info);
        return info;
    }
    catch {
        return { ...ANONYMOUS_USER_INFO };
    }
}
//# sourceMappingURL=userid_cache.js.map
//# debugId=999c8f6f-f4fe-5e70-ba9b-9141b3a263e7
