@lunora/ratelimit 1.0.0-alpha.21 → 1.0.0-alpha.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -440,5 +440,50 @@ interface RatelimitApiContext<Context> {
440
440
  * `@lunora/server` a type-only dependency of `@lunora/ratelimit`.
441
441
  */
442
442
  declare const ratelimitPlugin: <Context = unknown>(limiter: LimiterResolver<Context>) => Plugin<Record<never, never>, Context, Context & RatelimitApiContext<Context>>;
443
+ /** A budget bound to one named limit — check before the call, record after it. */
444
+ interface TokenBudget {
445
+ /**
446
+ * Peek at the budget before spending. `ok: false` means it is exhausted:
447
+ * refuse the call, and `retryAfter` says when it refills. Consumes nothing.
448
+ */
449
+ check: (key: string) => Promise<RateLimitStatus>;
450
+ /**
451
+ * Charge the tokens a call actually used. Always call it, including when the
452
+ * call THREW — a failed generation that consumed input tokens still has to be
453
+ * paid for. `tokens` of `0` is a no-op, so a call that spent nothing costs
454
+ * nothing.
455
+ *
456
+ * The charge is a reservation, so it may take the bucket negative: the tokens
457
+ * are already spent, and refusing to record them would let a single oversized
458
+ * call escape the budget entirely.
459
+ */
460
+ record: (key: string, tokens: number) => Promise<RateLimitStatus>;
461
+ }
462
+ /**
463
+ * Bind a {@link TokenBudget} to one of a limiter's named limits.
464
+ *
465
+ * ```ts
466
+ * const budget = tokenBudget(limiter, "tokens");
467
+ * const allowed = await budget.check(userId);
468
+ *
469
+ * if (!allowed.ok) {
470
+ * throw new LunoraError("RATE_LIMITED", `token budget exhausted; retry in ${String(allowed.retryAfter)}ms`);
471
+ * }
472
+ *
473
+ * try {
474
+ * const { text, usage } = await generateText({ model: ctx.ai.model(), prompt });
475
+ *
476
+ * await budget.record(userId, usage?.totalTokens ?? 0);
477
+ *
478
+ * return text;
479
+ * } catch (error) {
480
+ * // The prompt was still sent — charge what is known, then rethrow.
481
+ * await budget.record(userId, estimatedInputTokens);
482
+ *
483
+ * throw error;
484
+ * }
485
+ * ```
486
+ */
487
+ declare const tokenBudget: <Names extends string>(limiter: RateLimiter<Names>, name: Names) => TokenBudget;
443
488
  declare const VERSION = "0.0.0";
444
- export { type DatabaseStoreOptions as DbStoreOptions, type EvaluateOptions, type EvaluateResult, type LimiterResolver, type RateLimitArgs, type RateLimitConfig, type RateLimitConfigMap, type RateLimitDatabase as RateLimitDb, type RateLimitDatabaseIndexRange as RateLimitDbIndexRange, type RateLimitDatabaseQuery as RateLimitDbQuery, type RateLimitDatabaseReader as RateLimitDbReader, RateLimitError, type RateLimitKind, type RateLimitMiddlewareOptions, type RateLimitReason, type RateLimitStatus, type RateLimitStore, type RateLimitValue, RateLimiter, type RateLimiterOptions, type RatelimitApiContext, type ReadOnlyDatabaseStoreOptions as ReadOnlyDbStoreOptions, type SqlLike, type SqlStoreOptions, VERSION, availableAt, createDatabaseStore as createDbStore, createMemoryStore, createReadOnlyDatabaseStore as createReadOnlyDbStore, createSqlStore, databaseRateLimit as dbRateLimit, evaluate, rateLimit, ratelimitPlugin };
489
+ export { type DatabaseStoreOptions as DbStoreOptions, type EvaluateOptions, type EvaluateResult, type LimiterResolver, type RateLimitArgs, type RateLimitConfig, type RateLimitConfigMap, type RateLimitDatabase as RateLimitDb, type RateLimitDatabaseIndexRange as RateLimitDbIndexRange, type RateLimitDatabaseQuery as RateLimitDbQuery, type RateLimitDatabaseReader as RateLimitDbReader, RateLimitError, type RateLimitKind, type RateLimitMiddlewareOptions, type RateLimitReason, type RateLimitStatus, type RateLimitStore, type RateLimitValue, RateLimiter, type RateLimiterOptions, type RatelimitApiContext, type ReadOnlyDatabaseStoreOptions as ReadOnlyDbStoreOptions, type SqlLike, type SqlStoreOptions, type TokenBudget, VERSION, availableAt, createDatabaseStore as createDbStore, createMemoryStore, createReadOnlyDatabaseStore as createReadOnlyDbStore, createSqlStore, databaseRateLimit as dbRateLimit, evaluate, rateLimit, ratelimitPlugin, tokenBudget };
package/dist/index.d.ts CHANGED
@@ -440,5 +440,50 @@ interface RatelimitApiContext<Context> {
440
440
  * `@lunora/server` a type-only dependency of `@lunora/ratelimit`.
441
441
  */
442
442
  declare const ratelimitPlugin: <Context = unknown>(limiter: LimiterResolver<Context>) => Plugin<Record<never, never>, Context, Context & RatelimitApiContext<Context>>;
443
+ /** A budget bound to one named limit — check before the call, record after it. */
444
+ interface TokenBudget {
445
+ /**
446
+ * Peek at the budget before spending. `ok: false` means it is exhausted:
447
+ * refuse the call, and `retryAfter` says when it refills. Consumes nothing.
448
+ */
449
+ check: (key: string) => Promise<RateLimitStatus>;
450
+ /**
451
+ * Charge the tokens a call actually used. Always call it, including when the
452
+ * call THREW — a failed generation that consumed input tokens still has to be
453
+ * paid for. `tokens` of `0` is a no-op, so a call that spent nothing costs
454
+ * nothing.
455
+ *
456
+ * The charge is a reservation, so it may take the bucket negative: the tokens
457
+ * are already spent, and refusing to record them would let a single oversized
458
+ * call escape the budget entirely.
459
+ */
460
+ record: (key: string, tokens: number) => Promise<RateLimitStatus>;
461
+ }
462
+ /**
463
+ * Bind a {@link TokenBudget} to one of a limiter's named limits.
464
+ *
465
+ * ```ts
466
+ * const budget = tokenBudget(limiter, "tokens");
467
+ * const allowed = await budget.check(userId);
468
+ *
469
+ * if (!allowed.ok) {
470
+ * throw new LunoraError("RATE_LIMITED", `token budget exhausted; retry in ${String(allowed.retryAfter)}ms`);
471
+ * }
472
+ *
473
+ * try {
474
+ * const { text, usage } = await generateText({ model: ctx.ai.model(), prompt });
475
+ *
476
+ * await budget.record(userId, usage?.totalTokens ?? 0);
477
+ *
478
+ * return text;
479
+ * } catch (error) {
480
+ * // The prompt was still sent — charge what is known, then rethrow.
481
+ * await budget.record(userId, estimatedInputTokens);
482
+ *
483
+ * throw error;
484
+ * }
485
+ * ```
486
+ */
487
+ declare const tokenBudget: <Names extends string>(limiter: RateLimiter<Names>, name: Names) => TokenBudget;
443
488
  declare const VERSION = "0.0.0";
444
- export { type DatabaseStoreOptions as DbStoreOptions, type EvaluateOptions, type EvaluateResult, type LimiterResolver, type RateLimitArgs, type RateLimitConfig, type RateLimitConfigMap, type RateLimitDatabase as RateLimitDb, type RateLimitDatabaseIndexRange as RateLimitDbIndexRange, type RateLimitDatabaseQuery as RateLimitDbQuery, type RateLimitDatabaseReader as RateLimitDbReader, RateLimitError, type RateLimitKind, type RateLimitMiddlewareOptions, type RateLimitReason, type RateLimitStatus, type RateLimitStore, type RateLimitValue, RateLimiter, type RateLimiterOptions, type RatelimitApiContext, type ReadOnlyDatabaseStoreOptions as ReadOnlyDbStoreOptions, type SqlLike, type SqlStoreOptions, VERSION, availableAt, createDatabaseStore as createDbStore, createMemoryStore, createReadOnlyDatabaseStore as createReadOnlyDbStore, createSqlStore, databaseRateLimit as dbRateLimit, evaluate, rateLimit, ratelimitPlugin };
489
+ export { type DatabaseStoreOptions as DbStoreOptions, type EvaluateOptions, type EvaluateResult, type LimiterResolver, type RateLimitArgs, type RateLimitConfig, type RateLimitConfigMap, type RateLimitDatabase as RateLimitDb, type RateLimitDatabaseIndexRange as RateLimitDbIndexRange, type RateLimitDatabaseQuery as RateLimitDbQuery, type RateLimitDatabaseReader as RateLimitDbReader, RateLimitError, type RateLimitKind, type RateLimitMiddlewareOptions, type RateLimitReason, type RateLimitStatus, type RateLimitStore, type RateLimitValue, RateLimiter, type RateLimiterOptions, type RatelimitApiContext, type ReadOnlyDatabaseStoreOptions as ReadOnlyDbStoreOptions, type SqlLike, type SqlStoreOptions, type TokenBudget, VERSION, availableAt, createDatabaseStore as createDbStore, createMemoryStore, createReadOnlyDatabaseStore as createReadOnlyDbStore, createSqlStore, databaseRateLimit as dbRateLimit, evaluate, rateLimit, ratelimitPlugin, tokenBudget };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{availableAt as o,evaluate as a}from"./packem_shared/availableAt-BMlAt2U2.mjs";import{default as i}from"./packem_shared/dbRateLimit-e95-suu-.mjs";import{default as l}from"./packem_shared/RateLimitError-xJ2Iv-i7.mjs";import{rateLimit as x}from"./packem_shared/rateLimit-DLcwK-84.mjs";import{ratelimitPlugin as c}from"./packem_shared/ratelimitPlugin-D1QHZF9b.mjs";import{RateLimiter as b}from"./packem_shared/RateLimiter-CitqoGTI.mjs";import{createDbStore as u,createMemoryStore as L,createReadOnlyDbStore as n,createSqlStore as s}from"./packem_shared/createDbStore-CwJBMxDQ.mjs";const e="0.0.0";export{l as RateLimitError,b as RateLimiter,e as VERSION,o as availableAt,u as createDbStore,L as createMemoryStore,n as createReadOnlyDbStore,s as createSqlStore,i as dbRateLimit,a as evaluate,x as rateLimit,c as ratelimitPlugin};
1
+ import{availableAt as o,evaluate as a}from"./packem_shared/availableAt-BMlAt2U2.mjs";import{default as i}from"./packem_shared/dbRateLimit-e95-suu-.mjs";import{default as l}from"./packem_shared/RateLimitError-xJ2Iv-i7.mjs";import{rateLimit as x}from"./packem_shared/rateLimit-DLcwK-84.mjs";import{ratelimitPlugin as c}from"./packem_shared/ratelimitPlugin-D1QHZF9b.mjs";import{RateLimiter as u}from"./packem_shared/RateLimiter-CitqoGTI.mjs";import{createDbStore as b,createMemoryStore as n,createReadOnlyDbStore as L,createSqlStore as s}from"./packem_shared/createDbStore-CwJBMxDQ.mjs";import{tokenBudget as v}from"./packem_shared/tokenBudget-BRZSEqNB.mjs";const e="0.0.0";export{l as RateLimitError,u as RateLimiter,e as VERSION,o as availableAt,b as createDbStore,n as createMemoryStore,L as createReadOnlyDbStore,s as createSqlStore,i as dbRateLimit,a as evaluate,x as rateLimit,c as ratelimitPlugin,v as tokenBudget};
@@ -0,0 +1 @@
1
+ const r=(c,t)=>({check:async e=>c.check(t,{key:e}),record:async(e,a)=>{if(!Number.isFinite(a)||a<=0)return c.check(t,{key:e});const{config:i}=await c.getValue(t,{key:e}),n=Math.max(1,Math.floor((i.capacity??i.rate)/(i.shards??1)));return c.limit(t,{count:Math.min(Math.ceil(a),n),key:e,reserve:!0})}});export{r as tokenBudget};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/ratelimit",
3
- "version": "1.0.0-alpha.21",
3
+ "version": "1.0.0-alpha.22",
4
4
  "description": "Rate limiting: token-bucket / fixed-window / sliding-window algorithms, deny list, sharding, pluggable stores, and procedure middleware",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,7 +46,7 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/errors": "1.0.0-alpha.18"
49
+ "@lunora/errors": "1.0.0-alpha.21"
50
50
  },
51
51
  "engines": {
52
52
  "node": "^22.15.0 || >=24.11.0"