@ooneex/rate-limit 0.0.1 → 0.0.5

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.
@@ -0,0 +1,36 @@
1
+ import { Exception } from "@ooneex/exception";
2
+ declare class RateLimitException extends Exception {
3
+ constructor(message: string, data?: Record<string, unknown>);
4
+ }
5
+ type RateLimiterClassType = new (...args: any[]) => IRateLimiter;
6
+ type RedisRateLimiterOptionsType = {
7
+ connectionString?: string;
8
+ connectionTimeout?: number;
9
+ idleTimeout?: number;
10
+ autoReconnect?: boolean;
11
+ maxRetries?: number;
12
+ enableOfflineQueue?: boolean;
13
+ enableAutoPipelining?: boolean;
14
+ tls?: boolean | object;
15
+ };
16
+ type RateLimitResultType = {
17
+ limited: boolean;
18
+ remaining: number;
19
+ total: number;
20
+ resetAt: Date;
21
+ };
22
+ interface IRateLimiter {
23
+ check: (key: string, limit: number, windowSeconds: number) => Promise<RateLimitResultType>;
24
+ reset: (key: string) => Promise<boolean>;
25
+ getCount: (key: string) => Promise<number>;
26
+ }
27
+ declare class RedisRateLimiter implements IRateLimiter {
28
+ private client;
29
+ constructor(options?: RedisRateLimiterOptionsType);
30
+ private connect;
31
+ private getKey;
32
+ check(key: string, limit: number, windowSeconds: number): Promise<RateLimitResultType>;
33
+ reset(key: string): Promise<boolean>;
34
+ getCount(key: string): Promise<number>;
35
+ }
36
+ export { RedisRateLimiterOptionsType, RedisRateLimiter, RateLimiterClassType, RateLimitResultType, RateLimitException, IRateLimiter };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- var c=void 0;export{c as default};
2
+ import{Exception as b}from"@ooneex/exception";import{HttpStatus as p}from"@ooneex/http-status";class t extends b{constructor(n,e={}){super(n,{status:p.Code.TooManyRequests,data:e});this.name="RateLimitException"}}class u{client;constructor(n={}){let e=n.connectionString||Bun.env.RATE_LIMIT_REDIS_URL;if(!e)throw new t("Redis connection string is required. Please provide a connection string either through the constructor options or set the RATE_LIMIT_REDIS_URL environment variable.");let{connectionString:o,...r}=n,m={...{connectionTimeout:1e4,idleTimeout:30000,autoReconnect:!0,maxRetries:3,enableOfflineQueue:!0,enableAutoPipelining:!0},...r};this.client=new Bun.RedisClient(e,m)}async connect(){if(!this.client.connected)await this.client.connect()}getKey(n){return`ratelimit:${n}`}async check(n,e,o){try{await this.connect();let r=this.getKey(n),s=await this.client.incr(r);if(s===1)await this.client.expire(r,o);let m=await this.client.ttl(r),a=new Date(Date.now()+m*1000);return{limited:s>e,remaining:Math.max(0,e-s),total:e,resetAt:a}}catch(r){throw new t(`Failed to check rate limit for key "${n}": ${r}`)}}async reset(n){try{await this.connect();let e=this.getKey(n);return await this.client.del(e)>0}catch(e){throw new t(`Failed to reset rate limit for key "${n}": ${e}`)}}async getCount(n){try{await this.connect();let e=this.getKey(n),o=await this.client.get(e);if(o===null)return 0;return Number.parseInt(o,10)}catch(e){throw new t(`Failed to get count for key "${n}": ${e}`)}}}export{u as RedisRateLimiter,t as RateLimitException};
3
3
 
4
- //# debugId=739F3CA43E7B60FB64756E2164756E21
4
+ //# debugId=DD9E5A2DC9D13F5664756E2164756E21
package/dist/index.js.map CHANGED
@@ -1,9 +1,11 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": [],
3
+ "sources": ["src/RateLimitException.ts", "src/RedisRateLimiter.ts"],
4
4
  "sourcesContent": [
5
+ "import { Exception } from \"@ooneex/exception\";\nimport { HttpStatus } from \"@ooneex/http-status\";\n\nexport class RateLimitException extends Exception {\n constructor(message: string, data: Record<string, unknown> = {}) {\n super(message, {\n status: HttpStatus.Code.TooManyRequests,\n data,\n });\n this.name = \"RateLimitException\";\n }\n}\n",
6
+ "import { RateLimitException } from \"./RateLimitException\";\nimport type { IRateLimiter, RateLimitResultType, RedisRateLimiterOptionsType } from \"./types\";\n\nexport class RedisRateLimiter implements IRateLimiter {\n private client: Bun.RedisClient;\n\n constructor(options: RedisRateLimiterOptionsType = {}) {\n const connectionString = options.connectionString || Bun.env.RATE_LIMIT_REDIS_URL;\n\n if (!connectionString) {\n throw new RateLimitException(\n \"Redis connection string is required. Please provide a connection string either through the constructor options or set the RATE_LIMIT_REDIS_URL environment variable.\",\n );\n }\n\n const { connectionString: _, ...userOptions } = options;\n\n const defaultOptions = {\n connectionTimeout: 10_000,\n idleTimeout: 30_000,\n autoReconnect: true,\n maxRetries: 3,\n enableOfflineQueue: true,\n enableAutoPipelining: true,\n };\n\n const clientOptions = { ...defaultOptions, ...userOptions };\n\n this.client = new Bun.RedisClient(connectionString, clientOptions);\n }\n\n private async connect(): Promise<void> {\n if (!this.client.connected) {\n await this.client.connect();\n }\n }\n\n private getKey(key: string): string {\n return `ratelimit:${key}`;\n }\n\n public async check(key: string, limit: number, windowSeconds: number): Promise<RateLimitResultType> {\n try {\n await this.connect();\n\n const rateLimitKey = this.getKey(key);\n\n // Increment counter\n const count = await this.client.incr(rateLimitKey);\n\n // Set expiry if this is the first request in window\n if (count === 1) {\n await this.client.expire(rateLimitKey, windowSeconds);\n }\n\n // Get TTL for reset time calculation\n const ttl = await this.client.ttl(rateLimitKey);\n const resetAt = new Date(Date.now() + ttl * 1000);\n\n return {\n limited: count > limit,\n remaining: Math.max(0, limit - count),\n total: limit,\n resetAt,\n };\n } catch (error) {\n throw new RateLimitException(`Failed to check rate limit for key \"${key}\": ${error}`);\n }\n }\n\n public async reset(key: string): Promise<boolean> {\n try {\n await this.connect();\n\n const rateLimitKey = this.getKey(key);\n const result = await this.client.del(rateLimitKey);\n\n return result > 0;\n } catch (error) {\n throw new RateLimitException(`Failed to reset rate limit for key \"${key}\": ${error}`);\n }\n }\n\n public async getCount(key: string): Promise<number> {\n try {\n await this.connect();\n\n const rateLimitKey = this.getKey(key);\n const value = await this.client.get(rateLimitKey);\n\n if (value === null) {\n return 0;\n }\n\n return Number.parseInt(value, 10);\n } catch (error) {\n throw new RateLimitException(`Failed to get count for key \"${key}\": ${error}`);\n }\n }\n}\n"
5
7
  ],
6
- "mappings": "",
7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ACF,MAAM,KAAK,QAAQ,EAEnB,IAAM,EAAe,KAAK,OAAO,CAAG,EAGpC,OAFe,MAAM,KAAK,OAAO,IAAI,CAAY,EAEjC,EAChB,MAAO,EAAO,CACd,MAAM,IAAI,EAAmB,uCAAuC,OAAS,GAAO,QAI3E,SAAQ,CAAC,EAA8B,CAClD,GAAI,CACF,MAAM,KAAK,QAAQ,EAEnB,IAAM,EAAe,KAAK,OAAO,CAAG,EAC9B,EAAQ,MAAM,KAAK,OAAO,IAAI,CAAY,EAEhD,GAAI,IAAU,KACZ,MAAO,GAGT,OAAO,OAAO,SAAS,EAAO,EAAE,EAChC,MAAO,EAAO,CACd,MAAM,IAAI,EAAmB,gCAAgC,OAAS,GAAO,GAGnF",
9
+ "debugId": "DD9E5A2DC9D13F5664756E2164756E21",
8
10
  "names": []
9
11
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ooneex/rate-limit",
3
- "description": "",
4
- "version": "0.0.1",
3
+ "description": "Rate limiting middleware for API request throttling and abuse prevention",
4
+ "version": "0.0.5",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist",
@@ -10,9 +10,13 @@
10
10
  "package.json"
11
11
  ],
12
12
  "module": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
13
14
  "exports": {
14
15
  ".": {
15
- "import": "./dist/index.js"
16
+ "import": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ }
16
20
  },
17
21
  "./package.json": "./package.json"
18
22
  },
@@ -21,10 +25,23 @@
21
25
  "test": "bun test tests",
22
26
  "build": "bunup",
23
27
  "lint": "tsgo --noEmit && bunx biome lint",
24
- "publish:prod": "bun publish --tolerate-republish --access public",
25
- "publish:pack": "bun pm pack --destination ./dist",
26
- "publish:dry": "bun publish --dry-run"
28
+ "npm:publish": "bun publish --tolerate-republish --access public"
27
29
  },
28
- "devDependencies": {},
29
- "peerDependencies": {}
30
+ "peerDependencies": {
31
+ "@ooneex/exception": "0.0.1",
32
+ "@ooneex/http-status": "0.0.1"
33
+ },
34
+ "dependencies": {
35
+ "@ooneex/exception": "0.0.1",
36
+ "@ooneex/http-status": "0.0.1"
37
+ },
38
+ "keywords": [
39
+ "api",
40
+ "bun",
41
+ "ooneex",
42
+ "rate-limit",
43
+ "rate-limiting",
44
+ "throttle",
45
+ "typescript"
46
+ ]
30
47
  }
Binary file