@commandkit/ratelimit 0.0.0-dev.20260317060555

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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +801 -0
  3. package/dist/api.d.ts +79 -0
  4. package/dist/api.js +266 -0
  5. package/dist/augmentation.d.ts +11 -0
  6. package/dist/augmentation.js +8 -0
  7. package/dist/configure.d.ts +28 -0
  8. package/dist/configure.js +85 -0
  9. package/dist/constants.d.ts +17 -0
  10. package/dist/constants.js +21 -0
  11. package/dist/directive/use-ratelimit-directive.d.ts +22 -0
  12. package/dist/directive/use-ratelimit-directive.js +38 -0
  13. package/dist/directive/use-ratelimit.d.ts +14 -0
  14. package/dist/directive/use-ratelimit.js +169 -0
  15. package/dist/engine/RateLimitEngine.d.ts +48 -0
  16. package/dist/engine/RateLimitEngine.js +137 -0
  17. package/dist/engine/algorithms/fixed-window.d.ts +44 -0
  18. package/dist/engine/algorithms/fixed-window.js +198 -0
  19. package/dist/engine/algorithms/leaky-bucket.d.ts +48 -0
  20. package/dist/engine/algorithms/leaky-bucket.js +119 -0
  21. package/dist/engine/algorithms/sliding-window.d.ts +45 -0
  22. package/dist/engine/algorithms/sliding-window.js +127 -0
  23. package/dist/engine/algorithms/token-bucket.d.ts +47 -0
  24. package/dist/engine/algorithms/token-bucket.js +118 -0
  25. package/dist/engine/violations.d.ts +55 -0
  26. package/dist/engine/violations.js +106 -0
  27. package/dist/errors.d.ts +21 -0
  28. package/dist/errors.js +28 -0
  29. package/dist/index.d.ts +31 -0
  30. package/dist/index.js +53 -0
  31. package/dist/plugin.d.ts +140 -0
  32. package/dist/plugin.js +796 -0
  33. package/dist/providers/fallback.d.ts +7 -0
  34. package/dist/providers/fallback.js +11 -0
  35. package/dist/providers/memory.d.ts +6 -0
  36. package/dist/providers/memory.js +11 -0
  37. package/dist/providers/redis.d.ts +7 -0
  38. package/dist/providers/redis.js +11 -0
  39. package/dist/runtime.d.ts +45 -0
  40. package/dist/runtime.js +67 -0
  41. package/dist/storage/fallback.d.ts +180 -0
  42. package/dist/storage/fallback.js +261 -0
  43. package/dist/storage/memory.d.ts +146 -0
  44. package/dist/storage/memory.js +304 -0
  45. package/dist/storage/redis.d.ts +130 -0
  46. package/dist/storage/redis.js +243 -0
  47. package/dist/types.d.ts +296 -0
  48. package/dist/types.js +40 -0
  49. package/dist/utils/config.d.ts +34 -0
  50. package/dist/utils/config.js +105 -0
  51. package/dist/utils/keys.d.ts +102 -0
  52. package/dist/utils/keys.js +304 -0
  53. package/dist/utils/locking.d.ts +17 -0
  54. package/dist/utils/locking.js +60 -0
  55. package/dist/utils/time.d.ts +23 -0
  56. package/dist/utils/time.js +72 -0
  57. package/package.json +65 -0
package/dist/errors.js ADDED
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ /**
3
+ * Rate limit error type.
4
+ *
5
+ * Lets callers distinguish rate-limit failures from other errors.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.RateLimitError = void 0;
9
+ /**
10
+ * Error thrown by the directive wrapper when a function is rate-limited.
11
+ *
12
+ * @extends Error
13
+ */
14
+ class RateLimitError extends Error {
15
+ /**
16
+ * Create a rate-limit error with the stored result payload.
17
+ *
18
+ * @param result - Aggregated rate-limit result.
19
+ * @param message - Optional error message override.
20
+ */
21
+ constructor(result, message) {
22
+ super(message ?? 'Rate limit exceeded');
23
+ this.name = 'RateLimitError';
24
+ this.result = result;
25
+ }
26
+ }
27
+ exports.RateLimitError = RateLimitError;
28
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3JzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2Vycm9ycy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7Ozs7R0FJRzs7O0FBSUg7Ozs7R0FJRztBQUNILE1BQWEsY0FBZSxTQUFRLEtBQUs7SUFHdkM7Ozs7O09BS0c7SUFDSCxZQUFtQixNQUEyQixFQUFFLE9BQWdCO1FBQzlELEtBQUssQ0FBQyxPQUFPLElBQUkscUJBQXFCLENBQUMsQ0FBQztRQUN4QyxJQUFJLENBQUMsSUFBSSxHQUFHLGdCQUFnQixDQUFDO1FBQzdCLElBQUksQ0FBQyxNQUFNLEdBQUcsTUFBTSxDQUFDO0lBQ3ZCLENBQUM7Q0FDRjtBQWRELHdDQWNDIn0=
@@ -0,0 +1,31 @@
1
+ import './augmentation';
2
+ import type { CommandKitPlugin } from 'commandkit';
3
+ /**
4
+ * Create compiler + runtime plugins for rate limiting.
5
+ *
6
+ * Runtime options are provided via configureRatelimit().
7
+ *
8
+ * @param options - Optional compiler plugin configuration.
9
+ * @returns Ordered array of compiler and runtime plugins.
10
+ */
11
+ export declare function ratelimit(options?: Partial<{
12
+ compiler: import('commandkit').CommonDirectiveTransformerOptions;
13
+ }>): CommandKitPlugin[];
14
+ export * from './types';
15
+ export * from './constants';
16
+ export * from './runtime';
17
+ export * from './configure';
18
+ export * from './errors';
19
+ export * from './api';
20
+ export * from './plugin';
21
+ export * from './directive/use-ratelimit';
22
+ export * from './directive/use-ratelimit-directive';
23
+ export * from './engine/RateLimitEngine';
24
+ export * from './engine/algorithms/fixed-window';
25
+ export * from './engine/algorithms/sliding-window';
26
+ export * from './engine/algorithms/token-bucket';
27
+ export * from './engine/algorithms/leaky-bucket';
28
+ export * from './engine/violations';
29
+ export * from './storage/memory';
30
+ export * from './storage/redis';
31
+ export * from './storage/fallback';
package/dist/index.js ADDED
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.ratelimit = ratelimit;
18
+ require("./augmentation");
19
+ const plugin_1 = require("./plugin");
20
+ const use_ratelimit_directive_1 = require("./directive/use-ratelimit-directive");
21
+ const configure_1 = require("./configure");
22
+ /**
23
+ * Create compiler + runtime plugins for rate limiting.
24
+ *
25
+ * Runtime options are provided via configureRatelimit().
26
+ *
27
+ * @param options - Optional compiler plugin configuration.
28
+ * @returns Ordered array of compiler and runtime plugins.
29
+ */
30
+ function ratelimit(options) {
31
+ const compiler = new use_ratelimit_directive_1.UseRateLimitDirectivePlugin(options?.compiler);
32
+ const runtime = new plugin_1.RateLimitPlugin((0, configure_1.getRateLimitConfig)());
33
+ return [compiler, runtime];
34
+ }
35
+ __exportStar(require("./types"), exports);
36
+ __exportStar(require("./constants"), exports);
37
+ __exportStar(require("./runtime"), exports);
38
+ __exportStar(require("./configure"), exports);
39
+ __exportStar(require("./errors"), exports);
40
+ __exportStar(require("./api"), exports);
41
+ __exportStar(require("./plugin"), exports);
42
+ __exportStar(require("./directive/use-ratelimit"), exports);
43
+ __exportStar(require("./directive/use-ratelimit-directive"), exports);
44
+ __exportStar(require("./engine/RateLimitEngine"), exports);
45
+ __exportStar(require("./engine/algorithms/fixed-window"), exports);
46
+ __exportStar(require("./engine/algorithms/sliding-window"), exports);
47
+ __exportStar(require("./engine/algorithms/token-bucket"), exports);
48
+ __exportStar(require("./engine/algorithms/leaky-bucket"), exports);
49
+ __exportStar(require("./engine/violations"), exports);
50
+ __exportStar(require("./storage/memory"), exports);
51
+ __exportStar(require("./storage/redis"), exports);
52
+ __exportStar(require("./storage/fallback"), exports);
53
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztBQWNBLDhCQVFDO0FBdEJELDBCQUF3QjtBQUN4QixxQ0FBMkM7QUFDM0MsaUZBQWtGO0FBRWxGLDJDQUFpRDtBQUVqRDs7Ozs7OztHQU9HO0FBQ0gsU0FBZ0IsU0FBUyxDQUN2QixPQUVFO0lBRUYsTUFBTSxRQUFRLEdBQUcsSUFBSSxxREFBMkIsQ0FBQyxPQUFPLEVBQUUsUUFBUSxDQUFDLENBQUM7SUFDcEUsTUFBTSxPQUFPLEdBQUcsSUFBSSx3QkFBZSxDQUFDLElBQUEsOEJBQWtCLEdBQUUsQ0FBQyxDQUFDO0lBQzFELE9BQU8sQ0FBQyxRQUFRLEVBQUUsT0FBTyxDQUFDLENBQUM7QUFDN0IsQ0FBQztBQUVELDBDQUF3QjtBQUN4Qiw4Q0FBNEI7QUFDNUIsNENBQTBCO0FBQzFCLDhDQUE0QjtBQUM1QiwyQ0FBeUI7QUFDekIsd0NBQXNCO0FBQ3RCLDJDQUF5QjtBQUN6Qiw0REFBMEM7QUFDMUMsc0VBQW9EO0FBQ3BELDJEQUF5QztBQUN6QyxtRUFBaUQ7QUFDakQscUVBQW1EO0FBQ25ELG1FQUFpRDtBQUNqRCxtRUFBaUQ7QUFDakQsc0RBQW9DO0FBQ3BDLG1EQUFpQztBQUNqQyxrREFBZ0M7QUFDaEMscURBQW1DIn0=
@@ -0,0 +1,140 @@
1
+ import { RuntimePlugin } from 'commandkit';
2
+ import type { CommandKitEnvironment, CommandKitPluginRuntime, CommandKitHMREvent, PreparedAppCommandExecution } from 'commandkit';
3
+ import { Message } from 'discord.js';
4
+ import type { Interaction } from 'discord.js';
5
+ import type { RateLimitPluginOptions } from './types';
6
+ /**
7
+ * Runtime plugin that enforces rate limits for CommandKit commands so handlers stay lean.
8
+ *
9
+ * @extends RuntimePlugin<RateLimitPluginOptions>
10
+ */
11
+ export declare class RateLimitPlugin extends RuntimePlugin<RateLimitPluginOptions> {
12
+ readonly name = "RateLimitPlugin";
13
+ private readonly engines;
14
+ private readonly memoryStorage;
15
+ private readonly queues;
16
+ private hasLoggedMissingStorage;
17
+ constructor(options: RateLimitPluginOptions);
18
+ /**
19
+ * Initialize runtime storage and defaults for this plugin instance.
20
+ *
21
+ * @param ctx - CommandKit runtime for the active application.
22
+ * @returns Resolves when runtime storage has been initialized.
23
+ * @throws Error when the plugin has not been configured.
24
+ */
25
+ activate(ctx: CommandKitPluginRuntime): Promise<void>;
26
+ /**
27
+ * Dispose queues and clear shared runtime state.
28
+ *
29
+ * @returns Resolves after queues are aborted and runtime state is cleared.
30
+ */
31
+ deactivate(): Promise<void>;
32
+ /**
33
+ * Evaluate rate limits and optionally queue execution to avoid dropping commands.
34
+ *
35
+ * @param ctx - CommandKit runtime for the active application.
36
+ * @param env - Command execution environment.
37
+ * @param source - Interaction or message triggering the command.
38
+ * @param prepared - Prepared command execution data.
39
+ * @param execute - Callback that executes the command handler.
40
+ * @returns True when execution is deferred or handled, otherwise false to continue.
41
+ */
42
+ executeCommand(ctx: CommandKitPluginRuntime, env: CommandKitEnvironment, source: Interaction | Message, prepared: PreparedAppCommandExecution, execute: () => Promise<any>): Promise<boolean>;
43
+ /**
44
+ * Clear matching keys when a command is hot-reloaded to avoid stale state.
45
+ *
46
+ * @param ctx - CommandKit runtime for the active application.
47
+ * @param event - HMR event describing the changed file.
48
+ * @returns Resolves after matching keys are cleared and the event is handled.
49
+ */
50
+ performHMR(ctx: CommandKitPluginRuntime, event: CommandKitHMREvent): Promise<void>;
51
+ /**
52
+ * Resolve a cached engine instance for a storage backend.
53
+ *
54
+ * @param storage - Storage backend to associate with the engine.
55
+ * @returns Cached engine instance for the storage.
56
+ */
57
+ private getEngine;
58
+ /**
59
+ * Normalize a storage config into a storage driver instance.
60
+ *
61
+ * @param config - Storage config or driver.
62
+ * @returns Storage driver instance or null when not configured.
63
+ */
64
+ private resolveStorage;
65
+ /**
66
+ * Resolve the default storage, falling back to memory when enabled.
67
+ *
68
+ * @returns Resolved storage instance or null when disabled.
69
+ */
70
+ private resolveDefaultStorage;
71
+ /**
72
+ * Log a one-time error when storage is missing.
73
+ *
74
+ * @returns Nothing; logs at most once per process.
75
+ */
76
+ private logMissingStorage;
77
+ /**
78
+ * Emit a ratelimited event through CommandKit's event bus.
79
+ *
80
+ * @param ctx - CommandKit runtime for the active application.
81
+ * @param payload - Rate-limit event payload to emit.
82
+ * @returns Nothing; emits the event when available.
83
+ */
84
+ private emitRateLimited;
85
+ /**
86
+ * Determine whether a source should bypass rate limits.
87
+ *
88
+ * @param source - Interaction or message to evaluate.
89
+ * @returns True when the source should bypass rate limiting.
90
+ */
91
+ private shouldBypass;
92
+ /**
93
+ * Check for temporary exemptions in storage for the source.
94
+ *
95
+ * @param source - Interaction or message to evaluate.
96
+ * @returns True when a temporary exemption is found.
97
+ */
98
+ private hasTemporaryBypass;
99
+ /**
100
+ * Send the default rate-limited response when no custom handler is set.
101
+ *
102
+ * @param env - Command execution environment.
103
+ * @param source - Interaction or message that was limited.
104
+ * @param info - Aggregated rate-limit info for the response.
105
+ * @returns Resolves after the response is sent.
106
+ */
107
+ private respondRateLimited;
108
+ /**
109
+ * Enqueue a command execution for later retry under queue rules.
110
+ *
111
+ * @param params - Queue execution parameters.
112
+ * @returns True when the execution was queued.
113
+ */
114
+ private enqueueExecution;
115
+ /**
116
+ * Get or create an async queue for the given key.
117
+ *
118
+ * @param key - Queue identifier.
119
+ * @param options - Normalized queue settings.
120
+ * @returns Async queue instance.
121
+ */
122
+ private getQueue;
123
+ /**
124
+ * Consume limits for queued execution to decide whether to run now.
125
+ *
126
+ * @param engine - Rate limit engine.
127
+ * @param limiter - Resolved limiter configuration.
128
+ * @param resolvedKeys - Scope keys to consume.
129
+ * @returns Aggregated rate-limit info for the queue check.
130
+ */
131
+ private consumeForQueue;
132
+ /**
133
+ * Defer interaction replies when queueing and the source is repliable.
134
+ *
135
+ * @param source - Interaction or message that may be deferred.
136
+ * @param queue - Normalized queue settings.
137
+ * @returns Resolves after attempting to defer the interaction.
138
+ */
139
+ private deferInteractionIfNeeded;
140
+ }