// http-rate-limiter.ts — Simple sliding window rate limiter for HTTP transport.
// In-memory, no external dependencies. Limits requests per session per minute.
const WINDOW_MS = 60_000; // 1 minute
const MAX_REQUESTS_PER_WINDOW = 100;
const windows = new Map();
/**
 * Check if a request from the given session key is allowed.
 * Uses a sliding window algorithm: keeps timestamps of requests
 * within the last WINDOW_MS and checks count against max.
 *
 * @param sessionKey - Session identifier (session ID or IP)
 * @param now - Current timestamp (injectable for testing)
 * @returns Object with `allowed` boolean and `retryAfterMs` if rejected
 */
export function checkHttpRateLimit(sessionKey, now) {
    const currentTime = now ?? Date.now();
    const cutoff = currentTime - WINDOW_MS;
    let entry = windows.get(sessionKey);
    if (!entry) {
        entry = { timestamps: [] };
        windows.set(sessionKey, entry);
    }
    // Prune timestamps outside the window
    entry.timestamps = entry.timestamps.filter((t) => t > cutoff);
    if (entry.timestamps.length >= MAX_REQUESTS_PER_WINDOW) {
        // Calculate when the oldest request in the window will expire
        const oldest = entry.timestamps[0] ?? currentTime;
        const retryAfterMs = oldest + WINDOW_MS - currentTime;
        return { allowed: false, retryAfterMs: Math.max(retryAfterMs, 1) };
    }
    entry.timestamps.push(currentTime);
    return { allowed: true };
}
/** Reset all rate limit state (for testing). */
export function resetHttpRateLimits() {
    windows.clear();
}
/** Exposed for testing — the configured max requests per window. */
export const HTTP_RATE_LIMIT_MAX = MAX_REQUESTS_PER_WINDOW;
/** Exposed for testing — the window duration in ms. */
export const HTTP_RATE_LIMIT_WINDOW_MS = WINDOW_MS;
//# sourceMappingURL=http-rate-limiter.js.map