### Try Consume Tokens with Specific Cost Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Attempts to consume a specified number of tokens from the bucket. New keys start with a full bucket. ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 10, refillPerSecond: 5 }); // Multiple-token cost (e.g., expensive endpoints cost 3 tokens) const allowed = limiter.tryConsume("user:42", 3); // true (10 → 7) const again = limiter.tryConsume("user:42", 3); // true (7 → 4) const blocked = limiter.tryConsume("user:42", 5); // false (4 < 5) ``` -------------------------------- ### Expose Remaining Tokens in Response Headers Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Example of exposing rate limit information in response headers within a Bun HTTP server. ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 10, refillPerSecond: 5 }); Bun.serve({ port: 3000, fetch(req) { const ip = req.headers.get("x-forwarded-for") ?? "unknown"; const allowed = limiter.tryConsume(ip); const headers = new Headers({ "X-RateLimit-Remaining": String(limiter.remaining(ip)), "X-RateLimit-Limit": "10", }); if (!allowed) { return new Response("Too Many Requests", { status: 429, headers }); } return new Response("OK", { headers }); }, }); ``` -------------------------------- ### resetAll(): void Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Clears all tracked buckets at once. Every key will start fresh on its next access. Suitable for test teardown, server restarts, or administrative "unblock all" actions. ```APIDOC ## `resetAll(): void` ### Description Clears all tracked buckets at once. Every key will start fresh on its next access. Suitable for test teardown, server restarts, or administrative "unblock all" actions. ### Method `void` ### Example ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 3, refillPerSecond: 5 }); limiter.tryConsume("a", 3); limiter.tryConsume("b", 3); limiter.tryConsume("c", 3); console.log(limiter.size); // 3 limiter.resetAll(); console.log(limiter.size); // 0 console.log(limiter.tryConsume("a", 3)); // true — full bucket again console.log(limiter.tryConsume("b", 3)); // true ``` ``` -------------------------------- ### tryConsume(key: string, cost?: number): boolean Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Attempts to consume `cost` tokens (default `1`) from the bucket identified by `key`. Returns `true` if the tokens were available and deducted, or `false` if the bucket did not have enough tokens. New keys start with a full bucket. ```APIDOC ## tryConsume(key: string, cost?: number): boolean ### Description Attempts to consume `cost` tokens (default `1`) from the bucket identified by `key`. Returns `true` if the tokens were available and deducted, or `false` if the bucket did not have enough tokens. New keys start with a full bucket. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters - **key** (string) - Required - The identifier for the token bucket. - **cost** (number) - Optional - The number of tokens to consume. Defaults to 1. ### Request Example ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 10, refillPerSecond: 5 }); // Use inside a Bun HTTP server to gate requests by IP Bun.serve({ port: 3000, fetch(req) { const ip = req.headers.get("x-forwarded-for") ?? "unknown"; if (!limiter.tryConsume(ip)) { return new Response("Too Many Requests", { status: 429 }); } return new Response("OK"); }, }); // Multiple-token cost (e.g., expensive endpoints cost 3 tokens) const allowed = limiter.tryConsume("user:42", 3); // true (10 → 7) const again = limiter.tryConsume("user:42", 3); // true (7 → 4) const blocked = limiter.tryConsume("user:42", 5); // false (4 < 5) ``` ### Response #### Success Response (boolean) - **true**: If tokens were successfully consumed. - **false**: If not enough tokens were available. #### Response Example ```json true ``` ``` -------------------------------- ### Get Remaining Tokens Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Returns the estimated number of tokens currently available for a key, accounting for time-based refill. Returns capacity for unseen keys. ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 10, refillPerSecond: 5 }); limiter.tryConsume("user:1", 4); console.log(limiter.remaining("user:1")); // 6 console.log(limiter.remaining("user:99")); // 10 — unknown key → full capacity ``` -------------------------------- ### Reset all tracked buckets Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Clears all tracked buckets at once. Suitable for test teardown, server restarts, or administrative "unblock all" actions. After calling `resetAll()`, all keys will start fresh on their next access. ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 3, refillPerSecond: 5 }); limiter.tryConsume("a", 3); limiter.tryConsume("b", 3); limiter.tryConsume("c", 3); console.log(limiter.size); // 3 limiter.resetAll(); console.log(limiter.size); // 0 console.log(limiter.tryConsume("a", 3)); // true — full bucket again console.log(limiter.tryConsume("b", 3)); // true ``` -------------------------------- ### Get the number of tracked keys Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Returns the number of keys currently tracked by the limiter. Only keys accessed via `tryConsume` or `remaining` are counted. Useful for monitoring memory growth in long-running servers. ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 5, refillPerSecond: 5 }); limiter.tryConsume("user:1"); limiter.tryConsume("user:2"); limiter.tryConsume("user:3"); console.log(limiter.size); // 3 limiter.reset("user:2"); console.log(limiter.size); // 2 limiter.resetAll(); console.log(limiter.size); // 0 ``` -------------------------------- ### TokenBucket Constructor Source: https://github.com/nds-stack/bun-rate-limit/blob/main/README.md Initializes a new TokenBucket instance with specified capacity and refill rate. ```APIDOC ## TokenBucket Constructor ### Description Initializes a new TokenBucket instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **capacity** (number) - Required - The maximum number of tokens the bucket can hold. * **refillPerSecond** (number) - Required - The rate at which tokens are refilled per second. ``` -------------------------------- ### new TokenBucket(options) Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Constructs a new rate limiter instance. Throws BunRateLimitError if either option is <= 0. ```APIDOC ## new TokenBucket(options) ### Description Constructs a new rate limiter instance. Throws `BunRateLimitError` if either option is `<= 0`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Constructor ### Endpoint N/A ### Request Example ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; // Allow up to 10 requests, refilling 5 tokens per second per key const limiter = new TokenBucket({ capacity: 10, refillPerSecond: 5 }); // Invalid options throw BunRateLimitError try { new TokenBucket({ capacity: 0, refillPerSecond: 5 }); } catch (err) { console.error(err.name); // "BunRateLimitError" console.error(err.message); // "capacity must be > 0" } ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Initialize TokenBucket Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Constructs a new rate limiter instance. Throws BunRateLimitError if capacity or refillPerSecond are not positive. ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; // Allow up to 10 requests, refilling 5 tokens per second per key const limiter = new TokenBucket({ capacity: 10, refillPerSecond: 5 }); // Invalid options throw BunRateLimitError try { new TokenBucket({ capacity: 0, refillPerSecond: 5 }); } catch (err) { console.error(err.name); // "BunRateLimitError" console.error(err.message); // "capacity must be > 0" } ``` -------------------------------- ### tryConsume(key, cost?) Source: https://github.com/nds-stack/bun-rate-limit/blob/main/README.md Attempts to consume a specified number of tokens from the bucket associated with a given key. Returns false if there are insufficient tokens. ```APIDOC ## tryConsume(key, cost?) ### Description Try to consume `cost` tokens (default 1) from the bucket associated with the `key`. Returns `false` if insufficient tokens are available. ### Method N/A (Method of TokenBucket class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **key** (string) - Required - The identifier for the token bucket. * **cost** (number) - Optional - The number of tokens to consume. Defaults to 1. ``` -------------------------------- ### Initialize and Use TokenBucket Source: https://github.com/nds-stack/bun-rate-limit/blob/main/README.md Instantiate a TokenBucket with capacity and refill rate, then use it in an HTTP handler to check for rate limits before processing a request. Returns a 429 status code if the request is rate-limited. ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 10, refillPerSecond: 5 }); // HTTP handler if (!limiter.tryConsume(ip)) { return new Response("rate limited", { status: 429 }); } ``` -------------------------------- ### Try Consume Tokens in Bun HTTP Server Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Use inside a Bun HTTP server to gate requests by IP address. Returns false if the bucket does not have enough tokens. ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 10, refillPerSecond: 5 }); Bun.serve({ port: 3000, fetch(req) { const ip = req.headers.get("x-forwarded-for") ?? "unknown"; if (!limiter.tryConsume(ip)) { return new Response("Too Many Requests", { status: 429 }); } return new Response("OK"); }, }); ``` -------------------------------- ### TokenBucket Constructor Source: https://github.com/nds-stack/bun-rate-limit/blob/main/README.md The TokenBucket constructor requires 'capacity' and 'refillPerSecond' options to configure the rate limiter. ```typescript new TokenBucket({ capacity: number, refillPerSecond: number }) ``` -------------------------------- ### Handle invalid TokenBucket configuration Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Catches `BunRateLimitError` thrown when `TokenBucket` is constructed with invalid options. This allows for specific error handling and differentiation in catch blocks. ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; // BunRateLimitError can also be imported directly if needed: // import { BunRateLimitError } from "@nds-stack/bun-rate-limit/errors"; function createLimiter(capacity: number, refillPerSecond: number) { try { return new TokenBucket({ capacity, refillPerSecond }); } catch (err) { if (err instanceof Error && err.name === "BunRateLimitError") { console.error(`[config error] ${err.message}`); // "capacity must be > 0" OR "refillPerSecond must be > 0" } throw err; } } const limiter = createLimiter(10, 5); // OK createLimiter(0, 5); // logs "[config error] capacity must be > 0" ``` -------------------------------- ### reset(key: string): void Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Removes the bucket for a specific key, effectively restoring it to a full token balance on the next access. Useful for manually unblocking a specific user or resetting state after an operation completes. ```APIDOC ## reset(key: string): void ### Description Removes the bucket for a specific key, effectively restoring it to a full token balance on the next access. Useful for manually unblocking a specific user or resetting state after an operation completes. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters - **key** (string) - Required - The identifier for the token bucket to reset. ### Request Example ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 5, refillPerSecond: 5 }); limiter.tryConsume("user:7", 5); console.log(limiter.tryConsume("user:7", 1)); // false — exhausted limiter.reset("user:7"); // clear the bucket console.log(limiter.tryConsume("user:7", 5)); // true — fresh bucket console.log(limiter.size); // 1 ``` ### Response #### Success Response (void) N/A #### Response Example N/A ``` -------------------------------- ### size Source: https://github.com/nds-stack/bun-rate-limit/blob/main/README.md Returns the total number of keys currently being tracked by the rate limiter. ```APIDOC ## size ### Description Returns the number of tracked keys. ### Method N/A (Property of TokenBucket class) ``` -------------------------------- ### size (getter) Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Returns the number of keys currently tracked by the limiter. Only keys that have been accessed at least once via `tryConsume` or `remaining` (for an existing key) are counted. Useful for monitoring memory growth in long-running servers. ```APIDOC ## `size` (getter) ### Description Returns the number of keys currently tracked by the limiter. Only keys that have been accessed at least once via `tryConsume` or `remaining` (for an existing key) are counted. Useful for monitoring memory growth in long-running servers. ### Method `getter` ### Example ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 5, refillPerSecond: 5 }); limiter.tryConsume("user:1"); limiter.tryConsume("user:2"); limiter.tryConsume("user:3"); console.log(limiter.size); // 3 limiter.reset("user:2"); console.log(limiter.size); // 2 limiter.resetAll(); console.log(limiter.size); // 0 ``` ``` -------------------------------- ### remaining(key) Source: https://github.com/nds-stack/bun-rate-limit/blob/main/README.md Returns the estimated number of tokens currently available in the bucket for a given key. ```APIDOC ## remaining(key) ### Description Returns the estimated number of tokens available for a given `key`. ### Method N/A (Method of TokenBucket class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **key** (string) - Required - The identifier for the token bucket. ``` -------------------------------- ### remaining(key: string): number Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Returns the estimated number of tokens currently available for `key`, accounting for time-based refill since the last access. Returns `capacity` for keys that have never been seen. The value is floored to an integer. ```APIDOC ## remaining(key: string): number ### Description Returns the estimated number of tokens currently available for `key`, accounting for time-based refill since the last access. Returns `capacity` for keys that have never been seen. The value is floored to an integer. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters - **key** (string) - Required - The identifier for the token bucket. ### Request Example ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 10, refillPerSecond: 5 }); limiter.tryConsume("user:1", 4); console.log(limiter.remaining("user:1")); // 6 console.log(limiter.remaining("user:99")); // 10 — unknown key → full capacity // Expose remaining tokens in response headers Bun.serve({ port: 3000, fetch(req) { const ip = req.headers.get("x-forwarded-for") ?? "unknown"; const allowed = limiter.tryConsume(ip); const headers = new Headers({ "X-RateLimit-Remaining": String(limiter.remaining(ip)), "X-RateLimit-Limit": "10", }); if (!allowed) { return new Response("Too Many Requests", { status: 429, headers }); } return new Response("OK", { headers }); }, }); ``` ### Response #### Success Response (number) - The estimated number of remaining tokens for the given key. #### Response Example ```json 6 ``` ``` -------------------------------- ### Reset Bucket for a Key Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt Removes the bucket for a specific key, restoring it to a full token balance on the next access. Useful for manually unblocking users. ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; const limiter = new TokenBucket({ capacity: 5, refillPerSecond: 5 }); limiter.tryConsume("user:7", 5); console.log(limiter.tryConsume("user:7", 1)); // false — exhausted limiter.reset("user:7"); // clear the bucket console.log(limiter.tryConsume("user:7", 5)); // true — fresh bucket console.log(limiter.size); // 1 ``` -------------------------------- ### reset(key) Source: https://github.com/nds-stack/bun-rate-limit/blob/main/README.md Removes the token bucket associated with the specified key, effectively resetting its state. ```APIDOC ## reset(key) ### Description Removes the bucket associated with the `key`. ### Method N/A (Method of TokenBucket class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **key** (string) - Required - The identifier for the token bucket to reset. ``` -------------------------------- ### resetAll() Source: https://github.com/nds-stack/bun-rate-limit/blob/main/README.md Removes all token buckets currently being tracked by the limiter. ```APIDOC ## resetAll() ### Description Removes all tracked buckets. ### Method N/A (Method of TokenBucket class) ### Parameters None ``` -------------------------------- ### BunRateLimitError Source: https://context7.com/nds-stack/bun-rate-limit/llms.txt A named error subclass thrown when `TokenBucket` is constructed with invalid options. Extends the native `Error` class and sets `name` to `"BunRateLimitError"` for reliable `instanceof` checks and error differentiation in catch blocks. ```APIDOC ## `BunRateLimitError` ### Description A named error subclass thrown when `TokenBucket` is constructed with invalid options. Extends the native `Error` class and sets `name` to `"BunRateLimitError"` for reliable `instanceof` checks and error differentiation in catch blocks. ### Example ```typescript import { TokenBucket } from "@nds-stack/bun-rate-limit"; // BunRateLimitError can also be imported directly if needed: // import { BunRateLimitError } from "@nds-stack/bun-rate-limit/errors"; function createLimiter(capacity: number, refillPerSecond: number) { try { return new TokenBucket({ capacity, refillPerSecond }); } catch (err) { if (err instanceof Error && err.name === "BunRateLimitError") { console.error(`[config error] ${err.message}`); // "capacity must be > 0" OR "refillPerSecond must be > 0" } throw err; } } const limiter = createLimiter(10, 5); // OK createLimiter(0, 5); // logs "[config error] capacity must be > 0" ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.