@hardlydifficult/throttle 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/README.md ADDED
@@ -0,0 +1,42 @@
1
+ # @hardlydifficult/throttle
2
+
3
+ Rate limiting utilities with optional state persistence.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @hardlydifficult/throttle
9
+ ```
10
+
11
+ ## Throttle
12
+
13
+ Delay-based rate limiting with human-readable durations.
14
+
15
+ ```typescript
16
+ import { Throttle } from '@hardlydifficult/throttle';
17
+
18
+ const throttle = new Throttle({
19
+ minimumDelay: { value: 1.5, unit: 'minutes' },
20
+ onSleep: (ms) => console.log(`Sleeping ${ms}ms`),
21
+ });
22
+
23
+ await throttle.wait(); // resolves immediately
24
+ await throttle.wait(); // sleeps 90s before resolving
25
+ ```
26
+
27
+ ## WeightedThrottle
28
+
29
+ Per-operation weight support with optional state persistence across restarts.
30
+
31
+ ```typescript
32
+ import { WeightedThrottle } from '@hardlydifficult/throttle';
33
+
34
+ const throttle = new WeightedThrottle({
35
+ unitsPerSecond: 10,
36
+ persistKey: 'api-throttle', // optional: survives restarts
37
+ onSleep: (ms, info) => console.log(`Sleeping ${ms}ms (weight: ${info.weight})`),
38
+ });
39
+
40
+ await throttle.wait(5); // consumes 5 units
41
+ await throttle.wait(10); // consumes 10 units, sleeps if needed
42
+ ```
@@ -0,0 +1,13 @@
1
+ import { type TimeSpan } from "@hardlydifficult/date-time";
2
+ export interface ThrottleOptions {
3
+ minimumDelay: TimeSpan;
4
+ onSleep?: (ms: number) => void;
5
+ }
6
+ export declare class Throttle {
7
+ private lastTimestamp;
8
+ private readonly minimumDelayMs;
9
+ private readonly onSleep?;
10
+ constructor(options: ThrottleOptions);
11
+ wait(): Promise<void>;
12
+ }
13
+ //# sourceMappingURL=Throttle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Throttle.d.ts","sourceRoot":"","sources":["../src/Throttle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAkB,MAAM,4BAA4B,CAAC;AAO3E,MAAM,WAAW,eAAe;IAC9B,YAAY,EAAE,QAAQ,CAAC;IACvB,OAAO,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;CAChC;AAED,qBAAa,QAAQ;IACnB,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAuB;gBAEpC,OAAO,EAAE,eAAe;IAQ9B,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAY5B"}
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Throttle = void 0;
4
+ const date_time_1 = require("@hardlydifficult/date-time");
5
+ const sleep = (ms) => new Promise((resolve) => {
6
+ setTimeout(resolve, ms);
7
+ });
8
+ class Throttle {
9
+ lastTimestamp = 0;
10
+ minimumDelayMs;
11
+ onSleep;
12
+ constructor(options) {
13
+ this.minimumDelayMs = (0, date_time_1.toMilliseconds)(options.minimumDelay);
14
+ if (this.minimumDelayMs <= 0) {
15
+ throw new Error("Throttle minimumDelay must be a positive duration");
16
+ }
17
+ this.onSleep = options.onSleep;
18
+ }
19
+ async wait() {
20
+ const now = Date.now();
21
+ const target = Math.max(now, this.lastTimestamp + this.minimumDelayMs);
22
+ const delay = target - now;
23
+ this.lastTimestamp = target;
24
+ if (delay > 0) {
25
+ this.onSleep?.(delay);
26
+ await sleep(delay);
27
+ }
28
+ }
29
+ }
30
+ exports.Throttle = Throttle;
31
+ //# sourceMappingURL=Throttle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Throttle.js","sourceRoot":"","sources":["../src/Throttle.ts"],"names":[],"mappings":";;;AAAA,0DAA2E;AAE3E,MAAM,KAAK,GAAG,CAAC,EAAU,EAAiB,EAAE,CAC1C,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;IACtB,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAC1B,CAAC,CAAC,CAAC;AAOL,MAAa,QAAQ;IACX,aAAa,GAAG,CAAC,CAAC;IACT,cAAc,CAAS;IACvB,OAAO,CAAwB;IAEhD,YAAY,OAAwB;QAClC,IAAI,CAAC,cAAc,GAAG,IAAA,0BAAc,EAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC3D,IAAI,IAAI,CAAC,cAAc,IAAI,CAAC,EAAE,CAAC;YAC7B,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;QACvE,CAAC;QACD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IACjC,CAAC;IAED,KAAK,CAAC,IAAI;QACR,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,CAAC;QACvE,MAAM,KAAK,GAAG,MAAM,GAAG,GAAG,CAAC;QAE3B,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC;QAE5B,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;YACd,IAAI,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC;YACtB,MAAM,KAAK,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC;IACH,CAAC;CACF;AAzBD,4BAyBC"}
@@ -0,0 +1,20 @@
1
+ export interface WeightedThrottleSleepInfo {
2
+ weight: number;
3
+ limitPerSecond: number;
4
+ scheduledStart: number;
5
+ }
6
+ export interface WeightedThrottleOptions {
7
+ unitsPerSecond: number;
8
+ persistKey?: string;
9
+ stateDirectory?: string;
10
+ onSleep?: (delayMs: number, info: WeightedThrottleSleepInfo) => void;
11
+ }
12
+ export declare class WeightedThrottle {
13
+ private nextAvailableAt;
14
+ private readonly unitsPerSecond;
15
+ private readonly stateTracker?;
16
+ private readonly onSleep?;
17
+ constructor(options: WeightedThrottleOptions);
18
+ wait(weight: number): Promise<void>;
19
+ }
20
+ //# sourceMappingURL=WeightedThrottle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WeightedThrottle.d.ts","sourceRoot":"","sources":["../src/WeightedThrottle.ts"],"names":[],"mappings":"AAOA,MAAM,WAAW,yBAAyB;IACxC,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,uBAAuB;IACtC,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,yBAAyB,KAAK,IAAI,CAAC;CACtE;AAED,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAuB;IACrD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAGf;gBAEE,OAAO,EAAE,uBAAuB;IAsBtC,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAuB1C"}
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WeightedThrottle = void 0;
4
+ const state_tracker_1 = require("@hardlydifficult/state-tracker");
5
+ const sleep = (ms) => new Promise((resolve) => {
6
+ setTimeout(resolve, ms);
7
+ });
8
+ class WeightedThrottle {
9
+ nextAvailableAt;
10
+ unitsPerSecond;
11
+ stateTracker;
12
+ onSleep;
13
+ constructor(options) {
14
+ this.unitsPerSecond = options.unitsPerSecond;
15
+ this.onSleep = options.onSleep;
16
+ if (!Number.isFinite(this.unitsPerSecond) || this.unitsPerSecond <= 0) {
17
+ throw new Error("WeightedThrottle requires a positive unitsPerSecond value");
18
+ }
19
+ if (options.persistKey !== undefined) {
20
+ this.stateTracker = new state_tracker_1.StateTracker({
21
+ key: options.persistKey,
22
+ default: Date.now(),
23
+ stateDirectory: options.stateDirectory,
24
+ });
25
+ this.nextAvailableAt = this.stateTracker.load();
26
+ }
27
+ else {
28
+ this.nextAvailableAt = 0;
29
+ }
30
+ }
31
+ async wait(weight) {
32
+ if (!Number.isFinite(weight) || weight <= 0) {
33
+ return;
34
+ }
35
+ const now = Date.now();
36
+ const startAt = Math.max(now, this.nextAvailableAt);
37
+ const processingWindowMs = (weight / this.unitsPerSecond) * 1000;
38
+ const delayMs = startAt - now;
39
+ const newNextAvailableAt = startAt + processingWindowMs;
40
+ this.stateTracker?.save(newNextAvailableAt);
41
+ this.nextAvailableAt = newNextAvailableAt;
42
+ if (delayMs > 0) {
43
+ this.onSleep?.(delayMs, {
44
+ weight,
45
+ limitPerSecond: this.unitsPerSecond,
46
+ scheduledStart: startAt,
47
+ });
48
+ await sleep(delayMs);
49
+ }
50
+ }
51
+ }
52
+ exports.WeightedThrottle = WeightedThrottle;
53
+ //# sourceMappingURL=WeightedThrottle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WeightedThrottle.js","sourceRoot":"","sources":["../src/WeightedThrottle.ts"],"names":[],"mappings":";;;AAAA,kEAA8D;AAE9D,MAAM,KAAK,GAAG,CAAC,EAAU,EAAiB,EAAE,CAC1C,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;IACtB,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAC1B,CAAC,CAAC,CAAC;AAeL,MAAa,gBAAgB;IACnB,eAAe,CAAS;IACf,cAAc,CAAS;IACvB,YAAY,CAAwB;IACpC,OAAO,CAGd;IAEV,YAAY,OAAgC;QAC1C,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,CAA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,IAAI,OAAO,GAAG,CAAC,EAAE,CAAC;YAChB,IAAI,CAAC,OAAO,EAAE,CAAC,OAAO,EAAE;gBACtB,MAAM;gBACN,cAAc,EAAE,IAAI,CAAC,cAAc;gBACnC,cAAc,EAAE,OAAO;aACxB,CAAC,CAAC;YACH,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;CACF;AAtDD,4CAsDC"}
@@ -0,0 +1,3 @@
1
+ export { Throttle, type ThrottleOptions } from "./Throttle";
2
+ export { WeightedThrottle, type WeightedThrottleOptions, type WeightedThrottleSleepInfo, } from "./WeightedThrottle";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,EACL,gBAAgB,EAChB,KAAK,uBAAuB,EAC5B,KAAK,yBAAyB,GAC/B,MAAM,oBAAoB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WeightedThrottle = exports.Throttle = void 0;
4
+ var Throttle_1 = require("./Throttle");
5
+ Object.defineProperty(exports, "Throttle", { enumerable: true, get: function () { return Throttle_1.Throttle; } });
6
+ var WeightedThrottle_1 = require("./WeightedThrottle");
7
+ Object.defineProperty(exports, "WeightedThrottle", { enumerable: true, get: function () { return WeightedThrottle_1.WeightedThrottle; } });
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uCAA4D;AAAnD,oGAAA,QAAQ,OAAA;AACjB,uDAI4B;AAH1B,oHAAA,gBAAgB,OAAA"}
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@hardlydifficult/throttle",
3
+ "version": "1.0.0",
4
+ "main": "./dist/index.js",
5
+ "types": "./dist/index.d.ts",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "scripts": {
10
+ "build": "tsc",
11
+ "test": "vitest run",
12
+ "test:watch": "vitest",
13
+ "test:coverage": "vitest run --coverage",
14
+ "lint": "tsc --noEmit",
15
+ "clean": "rm -rf dist"
16
+ },
17
+ "dependencies": {
18
+ "@hardlydifficult/state-tracker": "1.0.0",
19
+ "@hardlydifficult/date-time": "1.0.0"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "20.19.31",
23
+ "typescript": "5.8.3",
24
+ "vitest": "1.6.1"
25
+ },
26
+ "peerDependencies": {
27
+ "@hardlydifficult/state-tracker": "1.0.0",
28
+ "@hardlydifficult/date-time": "1.0.0"
29
+ },
30
+ "engines": {
31
+ "node": ">=18.0.0"
32
+ }
33
+ }