bucketflow 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Davies
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,147 @@
1
+ # bucketflow
2
+
3
+ Lightweight in-memory rate limiting utilities for Node.js and TypeScript.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install bucketflow
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Token bucket
14
+
15
+ ```ts
16
+ import { TokenBucket } from "bucketflow";
17
+
18
+ const limiter = new TokenBucket(10, 1000);
19
+ const result = limiter.checkLimit("user-123");
20
+
21
+ if (!result.allowed) {
22
+ console.log(result.message);
23
+ }
24
+ ```
25
+
26
+ The constructor accepts `capacity`, `refillRate` in milliseconds, and an
27
+ optional rejection message.
28
+
29
+ ### Fixed window
30
+
31
+ ```ts
32
+ import { FixedWindow } from "bucketflow";
33
+
34
+ const limiter = new FixedWindow("api", "Too many requests", 100, 60_000);
35
+ const result = limiter.checkLimit("user-123");
36
+ ```
37
+
38
+ The constructor accepts a limiter key, optional rejection message, maximum
39
+ requests, and window duration in milliseconds.
40
+
41
+ ### Sliding window
42
+
43
+ ```ts
44
+ import { SlidingWindow } from "bucketflow";
45
+
46
+ const limiter = new SlidingWindow(60_000, 1_000, 100);
47
+ const result = limiter.checkLimit("user-123");
48
+ ```
49
+
50
+ The constructor accepts the window duration, refresh rate, maximum requests,
51
+ and an optional rejection message. Durations are in milliseconds.
52
+
53
+ ## Framework integrations
54
+
55
+ Bucketflow does not depend on a web framework. You can call a limiter from
56
+ middleware, hooks, guards, or any other request boundary.
57
+
58
+ ### Express
59
+
60
+ ```ts
61
+ import express from "express";
62
+ import { TokenBucket } from "bucketflow";
63
+
64
+ const app = express();
65
+ const limiter = new TokenBucket(100, 1_000);
66
+
67
+ app.use((req, res, next) => {
68
+ const key = req.ip ?? "unknown";
69
+ const result = limiter.checkLimit(key);
70
+
71
+ if (!result.allowed) {
72
+ res.status(429).json(result);
73
+ return;
74
+ }
75
+
76
+ next();
77
+ });
78
+ ```
79
+
80
+ ### Fastify
81
+
82
+ Fastify can use a limiter in a `preHandler` hook:
83
+
84
+ ```ts
85
+ import Fastify from "fastify";
86
+ import { TokenBucket } from "bucketflow";
87
+
88
+ const app = Fastify();
89
+ const limiter = new TokenBucket(100, 1_000);
90
+
91
+ app.addHook("preHandler", async (request, reply) => {
92
+ const key = request.ip;
93
+ const result = limiter.checkLimit(key);
94
+
95
+ if (!result.allowed) {
96
+ return reply.code(429).send(result);
97
+ }
98
+ });
99
+ ```
100
+
101
+ This works with Fastify because the package has no Express-specific or
102
+ NestJS-specific dependencies; the limiter can be called from Fastify hooks.
103
+
104
+ ### NestJS
105
+
106
+ In NestJS, the limiter can be used from middleware:
107
+
108
+ ```ts
109
+ import { Injectable, NestMiddleware } from "@nestjs/common";
110
+ import { Request, Response, NextFunction } from "express";
111
+ import { TokenBucket } from "bucketflow";
112
+
113
+ @Injectable()
114
+ export class RateLimitMiddleware implements NestMiddleware {
115
+ private readonly limiter = new TokenBucket(100, 1_000);
116
+
117
+ use(req: Request, res: Response, next: NextFunction) {
118
+ const key = req.ip ?? "unknown";
119
+ const result = this.limiter.checkLimit(key);
120
+
121
+ if (!result.allowed) {
122
+ res.status(429).json(result);
123
+ return;
124
+ }
125
+
126
+ next();
127
+ }
128
+ }
129
+ ```
130
+
131
+ Register the middleware in a module with `MiddlewareConsumer`, or adapt the
132
+ same pattern into a NestJS guard when route-level control is preferred.
133
+
134
+ ## API
135
+
136
+ The package currently exports:
137
+
138
+ - `TokenBucket`
139
+ - `FixedWindow`
140
+ - `SlidingWindow`
141
+
142
+ All limiters are in-memory and local to the running process. They are not
143
+ intended to coordinate limits across multiple Node.js processes or servers.
144
+
145
+ ## License
146
+
147
+ MIT
@@ -0,0 +1,11 @@
1
+ import { FixedWindowProps, FixedWindowResponse } from "../types";
2
+ export declare class FixedWindow implements FixedWindowProps {
3
+ key: string;
4
+ private store;
5
+ message: string;
6
+ maxNum: number;
7
+ window: number;
8
+ constructor(key: string, message: string | undefined, maxNum: number, window: number);
9
+ checkLimit(key: string): FixedWindowResponse;
10
+ }
11
+ //# sourceMappingURL=fixed-window.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fixed-window.d.ts","sourceRoot":"","sources":["../src/fixed-window.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAS,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAExE,qBAAa,WAAY,YAAW,gBAAgB;IAClD,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,KAAK,CAAiC;IAC9C,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IAEf,YACE,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,YAAsB,EACrC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EAMf;IAED,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,mBAAmB,CA0C3C;CACF"}
@@ -0,0 +1,4 @@
1
+ export * from "./fixed-window";
2
+ export * from "./token-bucket";
3
+ export * from "./sliding-window";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ FixedWindow: () => FixedWindow,
24
+ SlidingWindow: () => SlidingWindow,
25
+ TokenBucket: () => TokenBucket
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/fixed-window.ts
30
+ var FixedWindow = class {
31
+ constructor(key, message = "Too many requests", maxNum, window) {
32
+ this.store = /* @__PURE__ */ new Map();
33
+ this.key = key;
34
+ this.message = message;
35
+ this.maxNum = maxNum;
36
+ this.window = window;
37
+ }
38
+ checkLimit(key) {
39
+ if (!this.store.has(key)) {
40
+ this.store.set(key, {
41
+ count: 1,
42
+ windowEnd: Date.now() + this.window,
43
+ windowStart: Date.now()
44
+ });
45
+ return {
46
+ allowed: true,
47
+ reqRemaining: this.maxNum - 1,
48
+ message: this.message
49
+ };
50
+ }
51
+ const entry = this.store.get(key);
52
+ if (Date.now() > entry.windowEnd) {
53
+ entry.count = 0;
54
+ entry.windowEnd = Date.now() + this.window;
55
+ entry.windowStart = Date.now();
56
+ return {
57
+ allowed: true,
58
+ reqRemaining: this.maxNum,
59
+ message: this.message
60
+ };
61
+ }
62
+ if (entry.count >= this.maxNum) {
63
+ return {
64
+ allowed: false,
65
+ reqRemaining: 0,
66
+ message: this.message
67
+ };
68
+ }
69
+ entry.count += 1;
70
+ return {
71
+ allowed: true,
72
+ reqRemaining: this.maxNum - 1,
73
+ message: this.message
74
+ };
75
+ }
76
+ };
77
+
78
+ // src/token-bucket.ts
79
+ var TokenBucket = class {
80
+ constructor(capacity, refillRate, message = "Too many requests") {
81
+ this.store = /* @__PURE__ */ new Map();
82
+ this.capacity = capacity;
83
+ this.message = message;
84
+ this.refillRate = refillRate;
85
+ }
86
+ checkLimit(key) {
87
+ if (!this.store.has(key)) {
88
+ this.store.set(key, {
89
+ tokens: this.capacity,
90
+ tokenWindow: Date.now()
91
+ });
92
+ }
93
+ const entry = this.store.get(key);
94
+ const timeRemaining = Date.now() - entry.tokenWindow;
95
+ const tokensToAdd = Math.floor(timeRemaining / this.refillRate);
96
+ if (timeRemaining >= this.refillRate && entry.tokens < this.capacity) {
97
+ entry.tokens += Math.min(tokensToAdd, this.capacity);
98
+ entry.tokenWindow += this.refillRate;
99
+ }
100
+ if (entry.tokens > 0) {
101
+ entry.tokens -= 1;
102
+ entry.tokenWindow = Date.now();
103
+ return {
104
+ allowed: true,
105
+ message: this.message,
106
+ tokens: entry.tokens
107
+ };
108
+ }
109
+ return {
110
+ allowed: false,
111
+ message: this.message,
112
+ tokens: entry.tokens
113
+ };
114
+ }
115
+ };
116
+
117
+ // src/sliding-window.ts
118
+ var SlidingWindow = class {
119
+ constructor(window, refreshRate, maxRequests, message = "Too many requests") {
120
+ this.store = /* @__PURE__ */ new Map();
121
+ this.window = window;
122
+ this.message = message;
123
+ this.refreshRate = refreshRate;
124
+ this.maxRequests = maxRequests;
125
+ }
126
+ checkLimit(key) {
127
+ if (!this.store.has(key)) {
128
+ this.store.set(key, {
129
+ counter: 1,
130
+ startTime: Date.now()
131
+ });
132
+ }
133
+ const entry = this.store.get(key);
134
+ const timeElapsed = Date.now() - entry.startTime;
135
+ const requestOffload = Math.floor(timeElapsed / this.refreshRate);
136
+ if (timeElapsed >= this.refreshRate && entry.counter > 0) {
137
+ entry.counter = Math.max(
138
+ 0,
139
+ Math.min(entry.counter - requestOffload, this.maxRequests)
140
+ );
141
+ entry.startTime = Date.now();
142
+ return {
143
+ allowed: true,
144
+ counter: entry.counter,
145
+ message: this.message
146
+ };
147
+ }
148
+ if (entry.counter < this.maxRequests) {
149
+ entry.counter += 1;
150
+ return {
151
+ allowed: true,
152
+ counter: entry.counter,
153
+ message: this.message
154
+ };
155
+ }
156
+ return {
157
+ allowed: false,
158
+ counter: entry.counter,
159
+ message: this.message
160
+ };
161
+ }
162
+ };
163
+ // Annotate the CommonJS export names for ESM import in node:
164
+ 0 && (module.exports = {
165
+ FixedWindow,
166
+ SlidingWindow,
167
+ TokenBucket
168
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,139 @@
1
+ // src/fixed-window.ts
2
+ var FixedWindow = class {
3
+ constructor(key, message = "Too many requests", maxNum, window) {
4
+ this.store = /* @__PURE__ */ new Map();
5
+ this.key = key;
6
+ this.message = message;
7
+ this.maxNum = maxNum;
8
+ this.window = window;
9
+ }
10
+ checkLimit(key) {
11
+ if (!this.store.has(key)) {
12
+ this.store.set(key, {
13
+ count: 1,
14
+ windowEnd: Date.now() + this.window,
15
+ windowStart: Date.now()
16
+ });
17
+ return {
18
+ allowed: true,
19
+ reqRemaining: this.maxNum - 1,
20
+ message: this.message
21
+ };
22
+ }
23
+ const entry = this.store.get(key);
24
+ if (Date.now() > entry.windowEnd) {
25
+ entry.count = 0;
26
+ entry.windowEnd = Date.now() + this.window;
27
+ entry.windowStart = Date.now();
28
+ return {
29
+ allowed: true,
30
+ reqRemaining: this.maxNum,
31
+ message: this.message
32
+ };
33
+ }
34
+ if (entry.count >= this.maxNum) {
35
+ return {
36
+ allowed: false,
37
+ reqRemaining: 0,
38
+ message: this.message
39
+ };
40
+ }
41
+ entry.count += 1;
42
+ return {
43
+ allowed: true,
44
+ reqRemaining: this.maxNum - 1,
45
+ message: this.message
46
+ };
47
+ }
48
+ };
49
+
50
+ // src/token-bucket.ts
51
+ var TokenBucket = class {
52
+ constructor(capacity, refillRate, message = "Too many requests") {
53
+ this.store = /* @__PURE__ */ new Map();
54
+ this.capacity = capacity;
55
+ this.message = message;
56
+ this.refillRate = refillRate;
57
+ }
58
+ checkLimit(key) {
59
+ if (!this.store.has(key)) {
60
+ this.store.set(key, {
61
+ tokens: this.capacity,
62
+ tokenWindow: Date.now()
63
+ });
64
+ }
65
+ const entry = this.store.get(key);
66
+ const timeRemaining = Date.now() - entry.tokenWindow;
67
+ const tokensToAdd = Math.floor(timeRemaining / this.refillRate);
68
+ if (timeRemaining >= this.refillRate && entry.tokens < this.capacity) {
69
+ entry.tokens += Math.min(tokensToAdd, this.capacity);
70
+ entry.tokenWindow += this.refillRate;
71
+ }
72
+ if (entry.tokens > 0) {
73
+ entry.tokens -= 1;
74
+ entry.tokenWindow = Date.now();
75
+ return {
76
+ allowed: true,
77
+ message: this.message,
78
+ tokens: entry.tokens
79
+ };
80
+ }
81
+ return {
82
+ allowed: false,
83
+ message: this.message,
84
+ tokens: entry.tokens
85
+ };
86
+ }
87
+ };
88
+
89
+ // src/sliding-window.ts
90
+ var SlidingWindow = class {
91
+ constructor(window, refreshRate, maxRequests, message = "Too many requests") {
92
+ this.store = /* @__PURE__ */ new Map();
93
+ this.window = window;
94
+ this.message = message;
95
+ this.refreshRate = refreshRate;
96
+ this.maxRequests = maxRequests;
97
+ }
98
+ checkLimit(key) {
99
+ if (!this.store.has(key)) {
100
+ this.store.set(key, {
101
+ counter: 1,
102
+ startTime: Date.now()
103
+ });
104
+ }
105
+ const entry = this.store.get(key);
106
+ const timeElapsed = Date.now() - entry.startTime;
107
+ const requestOffload = Math.floor(timeElapsed / this.refreshRate);
108
+ if (timeElapsed >= this.refreshRate && entry.counter > 0) {
109
+ entry.counter = Math.max(
110
+ 0,
111
+ Math.min(entry.counter - requestOffload, this.maxRequests)
112
+ );
113
+ entry.startTime = Date.now();
114
+ return {
115
+ allowed: true,
116
+ counter: entry.counter,
117
+ message: this.message
118
+ };
119
+ }
120
+ if (entry.counter < this.maxRequests) {
121
+ entry.counter += 1;
122
+ return {
123
+ allowed: true,
124
+ counter: entry.counter,
125
+ message: this.message
126
+ };
127
+ }
128
+ return {
129
+ allowed: false,
130
+ counter: entry.counter,
131
+ message: this.message
132
+ };
133
+ }
134
+ };
135
+ export {
136
+ FixedWindow,
137
+ SlidingWindow,
138
+ TokenBucket
139
+ };
@@ -0,0 +1,10 @@
1
+ import type { LeakyBucketProps } from "../types";
2
+ export declare class LeakyBucket implements LeakyBucketProps {
3
+ capacity: number;
4
+ queue: Array<any>;
5
+ leakRate: number;
6
+ constructor(capacity: number, leakRate: number);
7
+ addRequest(req: any): boolean;
8
+ leak(): void;
9
+ }
10
+ //# sourceMappingURL=leaky-bucket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leaky-bucket.d.ts","sourceRoot":"","sources":["../src/leaky-bucket.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAEjD,qBAAa,WAAY,YAAW,gBAAgB;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IAEjB,YAAY,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAI7C;IAED,UAAU,CAAC,GAAG,EAAE,GAAG,WAMlB;IAED,IAAI,SAIH;CACF"}
@@ -0,0 +1,11 @@
1
+ import type { SlidingWindowProps, SlidingWindowResponse } from "../types";
2
+ export declare class SlidingWindow implements SlidingWindowProps {
3
+ window: number;
4
+ refreshRate: number;
5
+ maxRequests: number;
6
+ message: string;
7
+ private store;
8
+ constructor(window: number, refreshRate: number, maxRequests: number, message?: string);
9
+ checkLimit(key: string): SlidingWindowResponse;
10
+ }
11
+ //# sourceMappingURL=sliding-window.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sliding-window.d.ts","sourceRoot":"","sources":["../src/sliding-window.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,qBAAqB,EACtB,MAAM,UAAU,CAAC;AAElB,qBAAa,aAAc,YAAW,kBAAkB;IACtD,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAEhB,OAAO,CAAC,KAAK,CAA8C;IAE3D,YACE,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,MAAM,EACnB,OAAO,GAAE,MAA4B,EAMtC;IAED,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,qBAAqB,CAwC7C;CACF"}
@@ -0,0 +1,10 @@
1
+ import type { TokenBucketProps, TokenEntryResponse } from "../types";
2
+ export declare class TokenBucket implements TokenBucketProps {
3
+ capacity: number;
4
+ refillRate: number;
5
+ private store;
6
+ message: string;
7
+ constructor(capacity: number, refillRate: number, message?: string);
8
+ checkLimit(key: string): TokenEntryResponse;
9
+ }
10
+ //# sourceMappingURL=token-bucket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-bucket.d.ts","sourceRoot":"","sources":["../src/token-bucket.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,kBAAkB,EACnB,MAAM,UAAU,CAAC;AAElB,qBAAa,WAAY,YAAW,gBAAgB;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,KAAK,CAAsC;IACnD,OAAO,EAAE,MAAM,CAAC;IAEhB,YACE,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,OAAO,GAAE,MAA4B,EAKtC;IAED,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,kBAAkB,CAiC1C;CACF"}
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "bucketflow",
3
+ "version": "1.0.0",
4
+ "description": "Rate limiting for Node.js with token bucket, fixed window, and leaky bucket algorithms",
5
+ "main": "dist/index.js",
6
+ "keywords": [
7
+ "rate-limiting",
8
+ "token-bucket",
9
+ "fixed-window",
10
+ "leaky-bucket"
11
+ ],
12
+ "author": "Davies",
13
+ "license": "MIT",
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": ["dist"],
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.mjs",
22
+ "require": "./dist/index.js"
23
+ }
24
+ },
25
+ "types": "./dist/index.d.ts",
26
+ "scripts": {
27
+ "test": "echo \"Error: no test specified\" && exit 1",
28
+ "build": "tsup && tsc --emitDeclarationOnly",
29
+ "prepublishOnly": "npm run build"
30
+ },
31
+ "type": "commonjs",
32
+ "devDependencies": {
33
+ "tsup": "^8.5.1",
34
+ "typescript": "5.7.3"
35
+ }
36
+ }