@ttt-productions/rate-limit-core 0.8.1 → 0.8.3

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.
@@ -7,7 +7,7 @@
7
7
  export function getRateLimitErrorMessage(opts) {
8
8
  const { reset, context, copy } = opts;
9
9
  const minutes = Math.max(1, Math.ceil((reset - Date.now()) / 60_000));
10
- const timeString = minutes === 1 ? "1 minute" : `${minutes} minutes`;
10
+ const timeString = minutes === 1 ? '1 minute' : `${minutes} minutes`;
11
11
  if (copy?.format) {
12
12
  return copy.format({ timeString, context });
13
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"error-message.js","sourceRoot":"","sources":["../src/error-message.ts"],"names":[],"mappings":"AAcA;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CAAC,IAAkC;IACzE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;IACtC,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;IACtE,MAAM,UAAU,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,OAAO,UAAU,CAAC;IAErE,IAAI,IAAI,EAAE,MAAM,EAAE,CAAC;QACjB,OAAO,IAAI,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;IAC9C,CAAC;IAED,MAAM,IAAI,GAAG,OAAO;QAClB,CAAC,CAAC,GAAG,OAAO,sCAAsC,UAAU,GAAG;QAC/D,CAAC,CAAC,qCAAqC,UAAU,GAAG,CAAC;IAEvD,OAAO,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACxD,CAAC","sourcesContent":["export interface RateLimitErrorMessageOptions {\n /** Epoch ms when the limit resets (returned by `checkRateLimit`). */\n reset: number;\n /** Optional context shown in the message (e.g. \"Upload\"). */\n context?: string;\n /** Optional copy overrides — generic defaults are used when omitted. */\n copy?: {\n /** Suffix appended to every message. Default: \"\" (none). */\n suffix?: string;\n /** Template builder. Receives the formatted time string and context. */\n format?: (args: { timeString: string; context?: string }) => string;\n };\n}\n\n/**\n * Generate a user-friendly rate-limit error message with relative time.\n * Copy is fully consumer-controlled — the consuming app supplies any\n * additional suffix (e.g. an \"Early-launch rate limits in place\" notice)\n * at the call site.\n */\nexport function getRateLimitErrorMessage(opts: RateLimitErrorMessageOptions): string {\n const { reset, context, copy } = opts;\n const minutes = Math.max(1, Math.ceil((reset - Date.now()) / 60_000));\n const timeString = minutes === 1 ? \"1 minute\" : `${minutes} minutes`;\n\n if (copy?.format) {\n return copy.format({ timeString, context });\n }\n\n const base = context\n ? `${context} rate limit exceeded. Try again in ${timeString}.`\n : `Rate limit exceeded. Try again in ${timeString}.`;\n\n return copy?.suffix ? `${base} ${copy.suffix}` : base;\n}\n"]}
1
+ {"version":3,"file":"error-message.js","sourceRoot":"","sources":["../src/error-message.ts"],"names":[],"mappings":"AAcA;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CAAC,IAAkC;IACzE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;IACtC,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;IACtE,MAAM,UAAU,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,OAAO,UAAU,CAAC;IAErE,IAAI,IAAI,EAAE,MAAM,EAAE,CAAC;QACjB,OAAO,IAAI,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;IAC9C,CAAC;IAED,MAAM,IAAI,GAAG,OAAO;QAClB,CAAC,CAAC,GAAG,OAAO,sCAAsC,UAAU,GAAG;QAC/D,CAAC,CAAC,qCAAqC,UAAU,GAAG,CAAC;IAEvD,OAAO,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACxD,CAAC","sourcesContent":["export interface RateLimitErrorMessageOptions {\n /** Epoch ms when the limit resets (returned by `checkRateLimit`). */\n reset: number;\n /** Optional context shown in the message (e.g. \"Upload\"). */\n context?: string;\n /** Optional copy overrides — generic defaults are used when omitted. */\n copy?: {\n /** Suffix appended to every message. Default: \"\" (none). */\n suffix?: string;\n /** Template builder. Receives the formatted time string and context. */\n format?: (args: { timeString: string; context?: string }) => string;\n };\n}\n\n/**\n * Generate a user-friendly rate-limit error message with relative time.\n * Copy is fully consumer-controlled — the consuming app supplies any\n * additional suffix (e.g. an \"Early-launch rate limits in place\" notice)\n * at the call site.\n */\nexport function getRateLimitErrorMessage(opts: RateLimitErrorMessageOptions): string {\n const { reset, context, copy } = opts;\n const minutes = Math.max(1, Math.ceil((reset - Date.now()) / 60_000));\n const timeString = minutes === 1 ? '1 minute' : `${minutes} minutes`;\n\n if (copy?.format) {\n return copy.format({ timeString, context });\n }\n\n const base = context\n ? `${context} rate limit exceeded. Try again in ${timeString}.`\n : `Rate limit exceeded. Try again in ${timeString}.`;\n\n return copy?.suffix ? `${base} ${copy.suffix}` : base;\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- export { createRedisClientFactory } from "./redis-client.js";
2
- export type { RedisCredentialsProvider, RedisClientFactoryOptions, } from "./redis-client.js";
3
- export { createRateLimiterFactory } from "./rate-limiter.js";
4
- export type { RateLimitConfig, RateLimiterFactoryOptions, RateLimiterDegradation, } from "./rate-limiter.js";
5
- export { getRateLimitErrorMessage } from "./error-message.js";
6
- export type { RateLimitErrorMessageOptions } from "./error-message.js";
1
+ export { createRedisClientFactory } from './redis-client.js';
2
+ export type { RedisCredentialsProvider, RedisClientFactoryOptions } from './redis-client.js';
3
+ export { createRateLimiterFactory } from './rate-limiter.js';
4
+ export type { RateLimitConfig, RateLimiterFactoryOptions, RateLimiterDegradation, } from './rate-limiter.js';
5
+ export { getRateLimitErrorMessage } from './error-message.js';
6
+ export type { RateLimitErrorMessageOptions } from './error-message.js';
7
7
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,YAAY,EACV,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,YAAY,EACV,eAAe,EACf,yBAAyB,EACzB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAC9D,YAAY,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,YAAY,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAE7F,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,YAAY,EACV,eAAe,EACf,yBAAyB,EACzB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAC9D,YAAY,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { createRedisClientFactory } from "./redis-client.js";
2
- export { createRateLimiterFactory } from "./rate-limiter.js";
3
- export { getRateLimitErrorMessage } from "./error-message.js";
1
+ export { createRedisClientFactory } from './redis-client.js';
2
+ export { createRateLimiterFactory } from './rate-limiter.js';
3
+ export { getRateLimitErrorMessage } from './error-message.js';
4
4
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAM7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAO7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["export { createRedisClientFactory } from \"./redis-client.js\";\nexport type {\n RedisCredentialsProvider,\n RedisClientFactoryOptions,\n} from \"./redis-client.js\";\n\nexport { createRateLimiterFactory } from \"./rate-limiter.js\";\nexport type {\n RateLimitConfig,\n RateLimiterFactoryOptions,\n RateLimiterDegradation,\n} from \"./rate-limiter.js\";\n\nexport { getRateLimitErrorMessage } from \"./error-message.js\";\nexport type { RateLimitErrorMessageOptions } from \"./error-message.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAG7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAO7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["export { createRedisClientFactory } from './redis-client.js';\nexport type { RedisCredentialsProvider, RedisClientFactoryOptions } from './redis-client.js';\n\nexport { createRateLimiterFactory } from './rate-limiter.js';\nexport type {\n RateLimitConfig,\n RateLimiterFactoryOptions,\n RateLimiterDegradation,\n} from './rate-limiter.js';\n\nexport { getRateLimitErrorMessage } from './error-message.js';\nexport type { RateLimitErrorMessageOptions } from './error-message.js';\n"]}
@@ -1,5 +1,5 @@
1
- import { Ratelimit } from "@upstash/ratelimit";
2
- import type { Redis } from "@upstash/redis";
1
+ import { Ratelimit } from '@upstash/ratelimit';
2
+ import type { Redis } from '@upstash/redis';
3
3
  export interface RateLimitConfig {
4
4
  /** Unique prefix for this limiter (e.g. "ratelimit:upload"). */
5
5
  prefix: string;
@@ -43,8 +43,10 @@ export interface RateLimiterFactoryOptions {
43
43
  onDegraded?: (info: RateLimiterDegradation) => void;
44
44
  }
45
45
  /**
46
- * Create a memoized Ratelimit factory. Limiters are cached by their `prefix`
47
- * so repeated calls with the same config return the same instance.
46
+ * Create a memoized Ratelimit factory. One limiter is kept per `prefix`, and it is
47
+ * reused only while `maxRequests` and `window` still match: a caller that varies
48
+ * the capacity at runtime (a live incident multiplier) gets a limiter built for the
49
+ * new values, counting in the same Redis prefix, instead of the one built first.
48
50
  */
49
51
  export declare function createRateLimiterFactory(options: RateLimiterFactoryOptions): {
50
52
  getRateLimiter: (config: RateLimitConfig) => Ratelimit | null;
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limiter.d.ts","sourceRoot":"","sources":["../src/rate-limiter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAE5C,MAAM,WAAW,eAAe;IAC9B,gEAAgE;IAChE,MAAM,EAAE,MAAM,CAAC;IACf,0CAA0C;IAC1C,WAAW,EAAE,MAAM,CAAC;IACpB,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,sBAAsB;IACrC,MAAM,EAAE,aAAa,GAAG,aAAa,CAAC;IACtC,8CAA8C;IAC9C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wDAAwD;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AAC;IACpB;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,sBAAsB,KAAK,IAAI,CAAC;CACrD;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB;6BAczC,eAAe,KAAG,SAAS,GAAG,IAAI;0BA0C3D,MAAM,UACH,eAAe,KACtB,OAAO,CAAC;QAAE,OAAO,EAAE,IAAI,CAAA;KAAE,GAAG;QAAE,OAAO,EAAE,KAAK,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;EAqBlE"}
@@ -1,7 +1,9 @@
1
- import { Ratelimit } from "@upstash/ratelimit";
1
+ import { Ratelimit } from '@upstash/ratelimit';
2
2
  /**
3
- * Create a memoized Ratelimit factory. Limiters are cached by their `prefix`
4
- * so repeated calls with the same config return the same instance.
3
+ * Create a memoized Ratelimit factory. One limiter is kept per `prefix`, and it is
4
+ * reused only while `maxRequests` and `window` still match: a caller that varies
5
+ * the capacity at runtime (a live incident multiplier) gets a limiter built for the
6
+ * new values, counting in the same Redis prefix, instead of the one built first.
5
7
  */
6
8
  export function createRateLimiterFactory(options) {
7
9
  const limiters = new Map();
@@ -21,15 +23,22 @@ export function createRateLimiterFactory(options) {
21
23
  if (!redis)
22
24
  return null;
23
25
  const existing = limiters.get(config.prefix);
24
- if (existing)
25
- return existing;
26
+ if (existing &&
27
+ existing.maxRequests === config.maxRequests &&
28
+ existing.window === config.window) {
29
+ return existing.limiter;
30
+ }
26
31
  const limiter = new Ratelimit({
27
32
  redis,
28
33
  limiter: Ratelimit.slidingWindow(config.maxRequests, config.window),
29
34
  analytics,
30
35
  prefix: config.prefix,
31
36
  });
32
- limiters.set(config.prefix, limiter);
37
+ limiters.set(config.prefix, {
38
+ maxRequests: config.maxRequests,
39
+ window: config.window,
40
+ limiter,
41
+ });
33
42
  return limiter;
34
43
  }
35
44
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limiter.js","sourceRoot":"","sources":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AC,mBAAmB,EAAE,CAAC;gBACzB,mBAAmB,GAAG,IAAI,CAAC;gBAC3B,MAAM,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;YAC3D,CAAC;YACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC3B,CAAC;QACD,IAAI,CAAC;YACH,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACpD,IAAI,CAAC,OAAO;gBAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;YAC/C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC3B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,oEAAoE;YACpE,MAAM,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;YAChE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC3B,CAAC;IACH,CAAC;IAED,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["import { Ratelimit } from \"@upstash/ratelimit\";\nimport type { Redis } from \"@upstash/redis\";\n\nexport interface RateLimitConfig {\n /** Unique prefix for this limiter (e.g. \"ratelimit:upload\"). */\n prefix: string;\n /** Max requests allowed in the window. */\n maxRequests: number;\n /** Window duration (e.g. \"1 h\", \"10 m\", \"1 d\"). */\n window: string;\n}\n\n/**\n * Structured report of a rate-limiter degradation. Passed to the injected\n * `onDegraded` hook so the consuming app can decide the alerting posture\n * (e.g. Sentry `captureMessage` in prod, a warn line in the emulator) WITHOUT\n * this generic package importing a monitoring provider directly.\n *\n * - `reason: 'unavailable'` — a limiter could not be built (Redis is null:\n * missing credentials or the disable hook). Fired at most once per factory\n * instance, on the FIRST `checkRateLimit` call, so an unconfigured prod deploy\n * pages within minutes of traffic instead of silently allowing everything.\n * - `reason: 'limit-error'` — `limiter.limit()` rejected at runtime (e.g. an\n * Upstash outage). The call fails OPEN (`allowed: true`) after reporting.\n */\nexport interface RateLimiterDegradation {\n reason: 'unavailable' | 'limit-error';\n /** The limiter prefix in play, when known. */\n prefix?: string;\n /** The underlying error for `reason: 'limit-error'`. */\n error?: unknown;\n}\n\nexport interface RateLimiterFactoryOptions {\n /** Returns the Redis client or null when disabled. */\n getRedis: () => Redis | null;\n /** When true, includes Upstash analytics. Default true. */\n analytics?: boolean;\n /**\n * Optional degradation hook. The consuming app injects its own alerting\n * (Sentry capture in prod, warn in local/emulator) — this package stays\n * provider-agnostic. `unavailable` fires at most once per factory instance;\n * `limit-error` fires per failed `limit()` call. The hook must never throw\n * (it is invoked inside the fail-open path).\n */\n onDegraded?: (info: RateLimiterDegradation) => void;\n}\n\n/**\n * Create a memoized Ratelimit factory. Limiters are cached by their `prefix`\n * so repeated calls with the same config return the same instance.\n */\nexport function createRateLimiterFactory(options: RateLimiterFactoryOptions) {\n const limiters = new Map<string, Ratelimit>();\n const analytics = options.analytics ?? true;\n // Fire the `unavailable` degradation at most once per factory instance.\n let reportedUnavailable = false;\n\n function report(info: RateLimiterDegradation): void {\n try {\n options.onDegraded?.(info);\n } catch {\n // The alerting hook must never break the fail-open path.\n }\n }\n\n function getRateLimiter(config: RateLimitConfig): Ratelimit | null {\n const redis = options.getRedis();\n if (!redis) return null;\n\n const existing = limiters.get(config.prefix);\n if (existing) return existing;\n\n const limiter = new Ratelimit({\n redis,\n limiter: Ratelimit.slidingWindow(config.maxRequests, config.window as Parameters<typeof Ratelimit.slidingWindow>[1]),\n analytics,\n prefix: config.prefix,\n });\n limiters.set(config.prefix, limiter);\n return limiter;\n }\n\n /**\n * Check rate limit for a key (e.g. userId). Returns `{ allowed: true }`\n * when Redis is unavailable OR the limit isn't exceeded.\n *\n * FAIL-OPEN POSTURE (decided 2026-07-03): both failure modes degrade to\n * \"allow, but observed\" rather than blocking every write. When the limiter is\n * unavailable (Redis null — missing credentials / disabled), the first call\n * reports `unavailable` so an unconfigured prod deploy is loud. When a built\n * limiter's `limit()` rejects (Upstash outage), the error is reported and the\n * call still allows — an outage must not take down every rate-limited callable.\n */\n async function checkRateLimit(\n key: string,\n config: RateLimitConfig,\n ): Promise<{ allowed: true } | { allowed: false; reset: number }> {\n const limiter = getRateLimiter(config);\n if (!limiter) {\n if (!reportedUnavailable) {\n reportedUnavailable = true;\n report({ reason: 'unavailable', prefix: config.prefix });\n }\n return { allowed: true };\n }\n try {\n const { success, reset } = await limiter.limit(key);\n if (!success) return { allowed: false, reset };\n return { allowed: true };\n } catch (error) {\n // Runtime Redis error (e.g. Upstash outage). Fail OPEN, but report.\n report({ reason: 'limit-error', prefix: config.prefix, error });\n return { allowed: true };\n }\n }\n\n return { getRateLimiter, checkRateLimit };\n}\n"]}
1
+ {"version":3,"file":"rate-limiter.js","sourceRoot":"","sources":["../src/rate-limiter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAgD/C;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CAAC,OAAkC;IACzE,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAuE,CAAC;IAChG,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC;IAC5C,wEAAwE;IACxE,IAAI,mBAAmB,GAAG,KAAK,CAAC;IAEhC,SAAS,MAAM,CAAC,IAA4B;QAC1C,IAAI,CAAC;YACH,OAAO,CAAC,UAAU,EAAE,CAAC,IAAI,CAAC,CAAC;QAC7B,CAAC;QAAC,MAAM,CAAC;YACP,yDAAyD;QAC3D,CAAC;IACH,CAAC;IAED,SAAS,cAAc,CAAC,MAAuB;QAC7C,MAAM,KAAK,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;QACjC,IAAI,CAAC,KAAK;YAAE,OAAO,IAAI,CAAC;QAExB,MAAM,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E,KAAK,EAAE,CAAC;YAC/C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC3B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,oEAAoE;YACpE,MAAM,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;YAChE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC3B,CAAC;IACH,CAAC;IAED,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["import { Ratelimit } from '@upstash/ratelimit';\nimport type { Redis } from '@upstash/redis';\n\nexport interface RateLimitConfig {\n /** Unique prefix for this limiter (e.g. \"ratelimit:upload\"). */\n prefix: string;\n /** Max requests allowed in the window. */\n maxRequests: number;\n /** Window duration (e.g. \"1 h\", \"10 m\", \"1 d\"). */\n window: string;\n}\n\n/**\n * Structured report of a rate-limiter degradation. Passed to the injected\n * `onDegraded` hook so the consuming app can decide the alerting posture\n * (e.g. Sentry `captureMessage` in prod, a warn line in the emulator) WITHOUT\n * this generic package importing a monitoring provider directly.\n *\n * - `reason: 'unavailable'` — a limiter could not be built (Redis is null:\n * missing credentials or the disable hook). Fired at most once per factory\n * instance, on the FIRST `checkRateLimit` call, so an unconfigured prod deploy\n * pages within minutes of traffic instead of silently allowing everything.\n * - `reason: 'limit-error'` — `limiter.limit()` rejected at runtime (e.g. an\n * Upstash outage). The call fails OPEN (`allowed: true`) after reporting.\n */\nexport interface RateLimiterDegradation {\n reason: 'unavailable' | 'limit-error';\n /** The limiter prefix in play, when known. */\n prefix?: string;\n /** The underlying error for `reason: 'limit-error'`. */\n error?: unknown;\n}\n\nexport interface RateLimiterFactoryOptions {\n /** Returns the Redis client or null when disabled. */\n getRedis: () => Redis | null;\n /** When true, includes Upstash analytics. Default true. */\n analytics?: boolean;\n /**\n * Optional degradation hook. The consuming app injects its own alerting\n * (Sentry capture in prod, warn in local/emulator) — this package stays\n * provider-agnostic. `unavailable` fires at most once per factory instance;\n * `limit-error` fires per failed `limit()` call. The hook must never throw\n * (it is invoked inside the fail-open path).\n */\n onDegraded?: (info: RateLimiterDegradation) => void;\n}\n\n/**\n * Create a memoized Ratelimit factory. One limiter is kept per `prefix`, and it is\n * reused only while `maxRequests` and `window` still match: a caller that varies\n * the capacity at runtime (a live incident multiplier) gets a limiter built for the\n * new values, counting in the same Redis prefix, instead of the one built first.\n */\nexport function createRateLimiterFactory(options: RateLimiterFactoryOptions) {\n const limiters = new Map<string, { maxRequests: number; window: string; limiter: Ratelimit }>();\n const analytics = options.analytics ?? true;\n // Fire the `unavailable` degradation at most once per factory instance.\n let reportedUnavailable = false;\n\n function report(info: RateLimiterDegradation): void {\n try {\n options.onDegraded?.(info);\n } catch {\n // The alerting hook must never break the fail-open path.\n }\n }\n\n function getRateLimiter(config: RateLimitConfig): Ratelimit | null {\n const redis = options.getRedis();\n if (!redis) return null;\n\n const existing = limiters.get(config.prefix);\n if (\n existing &&\n existing.maxRequests === config.maxRequests &&\n existing.window === config.window\n ) {\n return existing.limiter;\n }\n\n const limiter = new Ratelimit({\n redis,\n limiter: Ratelimit.slidingWindow(\n config.maxRequests,\n config.window as Parameters<typeof Ratelimit.slidingWindow>[1],\n ),\n analytics,\n prefix: config.prefix,\n });\n limiters.set(config.prefix, {\n maxRequests: config.maxRequests,\n window: config.window,\n limiter,\n });\n return limiter;\n }\n\n /**\n * Check rate limit for a key (e.g. userId). Returns `{ allowed: true }`\n * when Redis is unavailable OR the limit isn't exceeded.\n *\n * FAIL-OPEN POSTURE (decided 2026-07-03): both failure modes degrade to\n * \"allow, but observed\" rather than blocking every write. When the limiter is\n * unavailable (Redis null — missing credentials / disabled), the first call\n * reports `unavailable` so an unconfigured prod deploy is loud. When a built\n * limiter's `limit()` rejects (Upstash outage), the error is reported and the\n * call still allows — an outage must not take down every rate-limited callable.\n */\n async function checkRateLimit(\n key: string,\n config: RateLimitConfig,\n ): Promise<{ allowed: true } | { allowed: false; reset: number }> {\n const limiter = getRateLimiter(config);\n if (!limiter) {\n if (!reportedUnavailable) {\n reportedUnavailable = true;\n report({ reason: 'unavailable', prefix: config.prefix });\n }\n return { allowed: true };\n }\n try {\n const { success, reset } = await limiter.limit(key);\n if (!success) return { allowed: false, reset };\n return { allowed: true };\n } catch (error) {\n // Runtime Redis error (e.g. Upstash outage). Fail OPEN, but report.\n report({ reason: 'limit-error', prefix: config.prefix, error });\n return { allowed: true };\n }\n }\n\n return { getRateLimiter, checkRateLimit };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { Redis } from "@upstash/redis";
1
+ import { Redis } from '@upstash/redis';
2
2
  export interface RedisCredentialsProvider {
3
3
  /** Lazy URL resolver — invoked only when Redis is first needed. */
4
4
  url: () => string | undefined;
@@ -1,4 +1,4 @@
1
- import { Redis } from "@upstash/redis";
1
+ import { Redis } from '@upstash/redis';
2
2
  /**
3
3
  * Build a lazy, singleton Redis client. The client is constructed on first
4
4
  * `get()` and reused thereafter. Returns null when credentials are missing
@@ -13,14 +13,14 @@ export function createRedisClientFactory(options) {
13
13
  return cached;
14
14
  resolved = true;
15
15
  if (options.disabledWhen?.()) {
16
- options.logger?.info?.("[rate-limit-core] Redis disabled by disabledWhen hook.");
16
+ options.logger?.info?.('[rate-limit-core] Redis disabled by disabledWhen hook.');
17
17
  disabled = true;
18
18
  return null;
19
19
  }
20
20
  const url = options.credentials.url();
21
21
  const token = options.credentials.token();
22
22
  if (!url || !token) {
23
- options.logger?.warn?.("[rate-limit-core] Redis credentials not configured.");
23
+ options.logger?.warn?.('[rate-limit-core] Redis credentials not configured.');
24
24
  disabled = true;
25
25
  return null;
26
26
  }
@@ -1 +1 @@
1
- {"version":3,"file":"redis-client.js","sourceRoot":"","sources":["../src/redis-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAoBvC;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CAAC,OAAkC;IAKzE,IAAI,MAAM,GAAiB,IAAI,CAAC;IAChC,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,IAAI,QAAQ,GAAG,KAAK,CAAC;IAErB,SAAS,OAAO;QACd,IAAI,QAAQ;YAAE,OAAO,MAAM,CAAC;QAC5B,QAAQ,GAAG,IAAI,CAAC;QAEhB,IAAI,OAAO,CAAC,YAAY,EAAE,EAAE,EAAE,CAAC;YAC7B,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,wDAAwD,CAAC,CAAC;YACjF,QAAQ,GAAG,IAAI,CAAC;YAChB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,GAAG,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;QACtC,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QAC1C,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;YACnB,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,qDAAqD,CAAC,CAAC;YAC9E,QAAQ,GAAG,IAAI,CAAC;YAChB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,GAAG,IAAI,KAAK,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC;QACnC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,OAAO;QACL,GAAG;YACD,IAAI,QAAQ;gBAAE,OAAO,IAAI,CAAC;YAC1B,OAAO,OAAO,EAAE,CAAC;QACnB,CAAC;QACD,OAAO;YACL,MAAM,GAAG,IAAI,CAAC;YACd,QAAQ,GAAG,KAAK,CAAC;YACjB,QAAQ,GAAG,KAAK,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { Redis } from \"@upstash/redis\";\n\nexport interface RedisCredentialsProvider {\n /** Lazy URL resolver — invoked only when Redis is first needed. */\n url: () => string | undefined;\n /** Lazy token resolver — invoked only when Redis is first needed. */\n token: () => string | undefined;\n}\n\nexport interface RedisClientFactoryOptions {\n credentials: RedisCredentialsProvider;\n /** Optional disable hook (e.g. emulator/local-dev detection). When this returns true on first call, Redis is permanently disabled for this factory instance. */\n disabledWhen?: () => boolean;\n /** Optional logger for \"Redis not configured\" / \"disabled\" diagnostics. */\n logger?: {\n info?: (message: string) => void;\n warn?: (message: string) => void;\n };\n}\n\n/**\n * Build a lazy, singleton Redis client. The client is constructed on first\n * `get()` and reused thereafter. Returns null when credentials are missing\n * or the disable hook returned true at first access.\n */\nexport function createRedisClientFactory(options: RedisClientFactoryOptions): {\n get(): Redis | null;\n /** Test-only: reset cached state. Do not call in production. */\n __reset(): void;\n} {\n let cached: Redis | null = null;\n let disabled = false;\n let resolved = false;\n\n function resolve(): Redis | null {\n if (resolved) return cached;\n resolved = true;\n\n if (options.disabledWhen?.()) {\n options.logger?.info?.(\"[rate-limit-core] Redis disabled by disabledWhen hook.\");\n disabled = true;\n return null;\n }\n const url = options.credentials.url();\n const token = options.credentials.token();\n if (!url || !token) {\n options.logger?.warn?.(\"[rate-limit-core] Redis credentials not configured.\");\n disabled = true;\n return null;\n }\n cached = new Redis({ url, token });\n return cached;\n }\n\n return {\n get() {\n if (disabled) return null;\n return resolve();\n },\n __reset() {\n cached = null;\n disabled = false;\n resolved = false;\n },\n };\n}\n"]}
1
+ {"version":3,"file":"redis-client.js","sourceRoot":"","sources":["../src/redis-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAoBvC;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CAAC,OAAkC;IAKzE,IAAI,MAAM,GAAiB,IAAI,CAAC;IAChC,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,IAAI,QAAQ,GAAG,KAAK,CAAC;IAErB,SAAS,OAAO;QACd,IAAI,QAAQ;YAAE,OAAO,MAAM,CAAC;QAC5B,QAAQ,GAAG,IAAI,CAAC;QAEhB,IAAI,OAAO,CAAC,YAAY,EAAE,EAAE,EAAE,CAAC;YAC7B,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,wDAAwD,CAAC,CAAC;YACjF,QAAQ,GAAG,IAAI,CAAC;YAChB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,GAAG,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;QACtC,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QAC1C,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;YACnB,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,qDAAqD,CAAC,CAAC;YAC9E,QAAQ,GAAG,IAAI,CAAC;YAChB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,GAAG,IAAI,KAAK,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC;QACnC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,OAAO;QACL,GAAG;YACD,IAAI,QAAQ;gBAAE,OAAO,IAAI,CAAC;YAC1B,OAAO,OAAO,EAAE,CAAC;QACnB,CAAC;QACD,OAAO;YACL,MAAM,GAAG,IAAI,CAAC;YACd,QAAQ,GAAG,KAAK,CAAC;YACjB,QAAQ,GAAG,KAAK,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { Redis } from '@upstash/redis';\n\nexport interface RedisCredentialsProvider {\n /** Lazy URL resolver — invoked only when Redis is first needed. */\n url: () => string | undefined;\n /** Lazy token resolver — invoked only when Redis is first needed. */\n token: () => string | undefined;\n}\n\nexport interface RedisClientFactoryOptions {\n credentials: RedisCredentialsProvider;\n /** Optional disable hook (e.g. emulator/local-dev detection). When this returns true on first call, Redis is permanently disabled for this factory instance. */\n disabledWhen?: () => boolean;\n /** Optional logger for \"Redis not configured\" / \"disabled\" diagnostics. */\n logger?: {\n info?: (message: string) => void;\n warn?: (message: string) => void;\n };\n}\n\n/**\n * Build a lazy, singleton Redis client. The client is constructed on first\n * `get()` and reused thereafter. Returns null when credentials are missing\n * or the disable hook returned true at first access.\n */\nexport function createRedisClientFactory(options: RedisClientFactoryOptions): {\n get(): Redis | null;\n /** Test-only: reset cached state. Do not call in production. */\n __reset(): void;\n} {\n let cached: Redis | null = null;\n let disabled = false;\n let resolved = false;\n\n function resolve(): Redis | null {\n if (resolved) return cached;\n resolved = true;\n\n if (options.disabledWhen?.()) {\n options.logger?.info?.('[rate-limit-core] Redis disabled by disabledWhen hook.');\n disabled = true;\n return null;\n }\n const url = options.credentials.url();\n const token = options.credentials.token();\n if (!url || !token) {\n options.logger?.warn?.('[rate-limit-core] Redis credentials not configured.');\n disabled = true;\n return null;\n }\n cached = new Redis({ url, token });\n return cached;\n }\n\n return {\n get() {\n if (disabled) return null;\n return resolve();\n },\n __reset() {\n cached = null;\n disabled = false;\n resolved = false;\n },\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ttt-productions/rate-limit-core",
3
- "version": "0.8.1",
3
+ "version": "0.8.3",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/ttt-productions/ttt-packages.git",
@@ -32,8 +32,7 @@
32
32
  },
33
33
  "devDependencies": {
34
34
  "@upstash/ratelimit": "^2.0.0",
35
- "@upstash/redis": "^1.34.0",
36
- "typescript": "^5.8.3"
35
+ "@upstash/redis": "^1.34.0"
37
36
  },
38
37
  "engines": {
39
38
  "node": ">=22",