@fluixi/api 1.0.0-alpha.107 → 1.0.0-alpha.109

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,4888 @@
1
+ import {
2
+ withHeaders
3
+ } from "./chunk-MI6ZXL3J.mjs";
4
+ import {
5
+ ApiError,
6
+ errorResponse
7
+ } from "./chunk-FIHRBQUV.mjs";
8
+ import {
9
+ __commonJS,
10
+ __publicField,
11
+ __toESM
12
+ } from "./chunk-GTIH4MXK.mjs";
13
+
14
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/BlockedKeys/BlockedKeys.js
15
+ var require_BlockedKeys = __commonJS({
16
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/BlockedKeys/BlockedKeys.js"(exports, module) {
17
+ "use strict";
18
+ module.exports = class BlockedKeys {
19
+ constructor() {
20
+ this._keys = /* @__PURE__ */ new Map();
21
+ }
22
+ collectExpired() {
23
+ const now = Date.now();
24
+ for (const [key, expire] of this._keys) {
25
+ if (expire <= now) {
26
+ this._keys.delete(key);
27
+ }
28
+ }
29
+ }
30
+ /**
31
+ * Add new blocked key
32
+ *
33
+ * @param key String
34
+ * @param sec Number
35
+ */
36
+ add(key, sec) {
37
+ this.addMs(key, sec * 1e3);
38
+ }
39
+ /**
40
+ * Add new blocked key for ms
41
+ *
42
+ * @param key String
43
+ * @param ms Number
44
+ */
45
+ addMs(key, ms) {
46
+ this._keys.set(key, Date.now() + ms);
47
+ if (this._keys.size > 999) {
48
+ this.collectExpired();
49
+ }
50
+ }
51
+ /**
52
+ * 0 means not blocked
53
+ *
54
+ * @param key
55
+ * @returns {number}
56
+ */
57
+ msBeforeExpire(key) {
58
+ const expire = this._keys.get(key);
59
+ const now = Date.now();
60
+ if (expire && expire >= now) {
61
+ return expire - now;
62
+ }
63
+ return 0;
64
+ }
65
+ /**
66
+ * If key is not given, delete all data in memory
67
+ *
68
+ * @param {string|undefined} key
69
+ */
70
+ delete(key) {
71
+ if (key) {
72
+ this._keys.delete(key);
73
+ } else {
74
+ this._keys.clear();
75
+ }
76
+ }
77
+ };
78
+ }
79
+ });
80
+
81
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/BlockedKeys/index.js
82
+ var require_BlockedKeys2 = __commonJS({
83
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/BlockedKeys/index.js"(exports, module) {
84
+ "use strict";
85
+ var BlockedKeys = require_BlockedKeys();
86
+ module.exports = BlockedKeys;
87
+ }
88
+ });
89
+
90
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterRes.js
91
+ var require_RateLimiterRes = __commonJS({
92
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterRes.js"(exports, module) {
93
+ "use strict";
94
+ module.exports = class RateLimiterRes {
95
+ constructor(remainingPoints, msBeforeNext, consumedPoints, isFirstInDuration) {
96
+ this.remainingPoints = typeof remainingPoints === "undefined" ? 0 : remainingPoints;
97
+ this.msBeforeNext = typeof msBeforeNext === "undefined" ? 0 : msBeforeNext;
98
+ this.consumedPoints = typeof consumedPoints === "undefined" ? 0 : consumedPoints;
99
+ this.isFirstInDuration = typeof isFirstInDuration === "undefined" ? false : isFirstInDuration;
100
+ }
101
+ get msBeforeNext() {
102
+ return this._msBeforeNext;
103
+ }
104
+ set msBeforeNext(ms) {
105
+ this._msBeforeNext = ms;
106
+ return this;
107
+ }
108
+ get remainingPoints() {
109
+ return this._remainingPoints;
110
+ }
111
+ set remainingPoints(p) {
112
+ this._remainingPoints = p;
113
+ return this;
114
+ }
115
+ get consumedPoints() {
116
+ return this._consumedPoints;
117
+ }
118
+ set consumedPoints(p) {
119
+ this._consumedPoints = p;
120
+ return this;
121
+ }
122
+ get isFirstInDuration() {
123
+ return this._isFirstInDuration;
124
+ }
125
+ set isFirstInDuration(value) {
126
+ this._isFirstInDuration = Boolean(value);
127
+ }
128
+ _getDecoratedProperties() {
129
+ return {
130
+ remainingPoints: this.remainingPoints,
131
+ msBeforeNext: this.msBeforeNext,
132
+ consumedPoints: this.consumedPoints,
133
+ isFirstInDuration: this.isFirstInDuration
134
+ };
135
+ }
136
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
137
+ return this._getDecoratedProperties();
138
+ }
139
+ toString() {
140
+ return JSON.stringify(this._getDecoratedProperties());
141
+ }
142
+ toJSON() {
143
+ return this._getDecoratedProperties();
144
+ }
145
+ };
146
+ }
147
+ });
148
+
149
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterAbstract.js
150
+ var require_RateLimiterAbstract = __commonJS({
151
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterAbstract.js"(exports, module) {
152
+ "use strict";
153
+ module.exports = class RateLimiterAbstract {
154
+ /**
155
+ *
156
+ * @param opts Object {
157
+ * points: <required>, // Number of points (must be a number, can be negative)
158
+ * duration: <required>, // Per seconds (must be a non-negative number, 0 = never expires)
159
+ * blockDuration: 0, // Block if consumed more than points in current duration for blockDuration seconds
160
+ * execEvenly: false, // Execute allowed actions evenly over duration
161
+ * execEvenlyMinDelayMs: duration * 1000 / points, // ms, works with execEvenly=true option
162
+ * keyPrefix: 'rlflx',
163
+ * }
164
+ */
165
+ constructor(opts = {}) {
166
+ this.points = opts.points;
167
+ this.duration = opts.duration;
168
+ this.blockDuration = opts.blockDuration;
169
+ this.execEvenly = opts.execEvenly;
170
+ this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs;
171
+ this.keyPrefix = opts.keyPrefix;
172
+ }
173
+ get points() {
174
+ return this._points;
175
+ }
176
+ set points(value) {
177
+ if (Number.isFinite(value)) {
178
+ this._points = value;
179
+ } else {
180
+ throw new Error("points must be set and must be a finite number");
181
+ }
182
+ }
183
+ get duration() {
184
+ return this._duration;
185
+ }
186
+ set duration(value) {
187
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
188
+ this._duration = value;
189
+ } else {
190
+ throw new Error("duration must be set and must be a finite, non-negative number");
191
+ }
192
+ }
193
+ get msDuration() {
194
+ return this.duration * 1e3;
195
+ }
196
+ get blockDuration() {
197
+ return this._blockDuration;
198
+ }
199
+ set blockDuration(value) {
200
+ this._blockDuration = typeof value === "undefined" ? 0 : value;
201
+ }
202
+ get msBlockDuration() {
203
+ return this.blockDuration * 1e3;
204
+ }
205
+ get execEvenly() {
206
+ return this._execEvenly;
207
+ }
208
+ set execEvenly(value) {
209
+ this._execEvenly = typeof value === "undefined" ? false : Boolean(value);
210
+ }
211
+ get execEvenlyMinDelayMs() {
212
+ return this._execEvenlyMinDelayMs === void 0 ? this._getExecEvenlyMinDelayMsDefault() : this._execEvenlyMinDelayMs;
213
+ }
214
+ set execEvenlyMinDelayMs(value) {
215
+ this._execEvenlyMinDelayMs = value;
216
+ }
217
+ _getExecEvenlyMinDelayMsDefault() {
218
+ return this.points > 0 ? Math.ceil(this.msDuration / this.points) : 0;
219
+ }
220
+ get keyPrefix() {
221
+ return this._keyPrefix;
222
+ }
223
+ set keyPrefix(value) {
224
+ if (typeof value === "undefined") {
225
+ value = "rlflx";
226
+ }
227
+ if (typeof value !== "string") {
228
+ throw new Error("keyPrefix must be string");
229
+ }
230
+ this._keyPrefix = value;
231
+ }
232
+ _getKeySecDuration(options = {}) {
233
+ return options && options.customDuration >= 0 ? options.customDuration : this.duration;
234
+ }
235
+ getKey(key) {
236
+ return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;
237
+ }
238
+ parseKey(rlKey) {
239
+ return this.keyPrefix.length > 0 ? rlKey.substring(this.keyPrefix.length + 1) : rlKey;
240
+ }
241
+ consume() {
242
+ throw new Error("You have to implement the method 'consume'!");
243
+ }
244
+ penalty() {
245
+ throw new Error("You have to implement the method 'penalty'!");
246
+ }
247
+ reward() {
248
+ throw new Error("You have to implement the method 'reward'!");
249
+ }
250
+ get() {
251
+ throw new Error("You have to implement the method 'get'!");
252
+ }
253
+ set() {
254
+ throw new Error("You have to implement the method 'set'!");
255
+ }
256
+ block() {
257
+ throw new Error("You have to implement the method 'block'!");
258
+ }
259
+ delete() {
260
+ throw new Error("You have to implement the method 'delete'!");
261
+ }
262
+ };
263
+ }
264
+ });
265
+
266
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterCompatibleAbstract.js
267
+ var require_RateLimiterCompatibleAbstract = __commonJS({
268
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterCompatibleAbstract.js"(exports, module) {
269
+ "use strict";
270
+ module.exports = class RateLimiterCompatibleAbstract {
271
+ get keyPrefix() {
272
+ throw new Error("You have to implement the getter 'keyPrefix'!");
273
+ }
274
+ get blockDuration() {
275
+ throw new Error("You have to implement the getter 'blockDuration'!");
276
+ }
277
+ set blockDuration(value) {
278
+ throw new Error("You have to implement the setter 'blockDuration'!");
279
+ }
280
+ get execEvenly() {
281
+ throw new Error("You have to implement the getter 'execEvenly'!");
282
+ }
283
+ set execEvenly(value) {
284
+ throw new Error("You have to implement the setter 'execEvenly'!");
285
+ }
286
+ consume() {
287
+ throw new Error("You have to implement the method 'consume'!");
288
+ }
289
+ penalty() {
290
+ throw new Error("You have to implement the method 'penalty'!");
291
+ }
292
+ reward() {
293
+ throw new Error("You have to implement the method 'reward'!");
294
+ }
295
+ get() {
296
+ throw new Error("You have to implement the method 'get'!");
297
+ }
298
+ set() {
299
+ throw new Error("You have to implement the method 'set'!");
300
+ }
301
+ block() {
302
+ throw new Error("You have to implement the method 'block'!");
303
+ }
304
+ delete() {
305
+ throw new Error("You have to implement the method 'delete'!");
306
+ }
307
+ };
308
+ }
309
+ });
310
+
311
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/helper/isRateLimiterCompatible.js
312
+ var require_isRateLimiterCompatible = __commonJS({
313
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/helper/isRateLimiterCompatible.js"(exports, module) {
314
+ "use strict";
315
+ var RateLimiterAbstract = require_RateLimiterAbstract();
316
+ var RateLimiterCompatibleAbstract = require_RateLimiterCompatibleAbstract();
317
+ module.exports = function isRateLimiterCompatible(obj) {
318
+ return obj instanceof RateLimiterAbstract || obj instanceof RateLimiterCompatibleAbstract;
319
+ };
320
+ }
321
+ });
322
+
323
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterInsuredAbstract.js
324
+ var require_RateLimiterInsuredAbstract = __commonJS({
325
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterInsuredAbstract.js"(exports, module) {
326
+ "use strict";
327
+ var RateLimiterAbstract = require_RateLimiterAbstract();
328
+ var RateLimiterRes2 = require_RateLimiterRes();
329
+ var isRateLimiterCompatible = require_isRateLimiterCompatible();
330
+ module.exports = class RateLimiterInsuredAbstract extends RateLimiterAbstract {
331
+ constructor(opts = {}) {
332
+ super(opts);
333
+ this.insuranceLimiter = opts.insuranceLimiter;
334
+ }
335
+ get insuranceLimiter() {
336
+ return this._insuranceLimiter;
337
+ }
338
+ set insuranceLimiter(value) {
339
+ if (typeof value !== "undefined" && !isRateLimiterCompatible(value)) {
340
+ throw new Error("insuranceLimiter must be instance of RateLimiterAbstract or RateLimiterCompatibleAbstract");
341
+ }
342
+ this._insuranceLimiter = value;
343
+ if (this._insuranceLimiter) {
344
+ this._insuranceLimiter.blockDuration = this.blockDuration;
345
+ this._insuranceLimiter.execEvenly = this.execEvenly;
346
+ }
347
+ }
348
+ _handleError(err, funcName, resolve, reject, params) {
349
+ if (err instanceof RateLimiterRes2) {
350
+ reject(err);
351
+ } else if (!isRateLimiterCompatible(this.insuranceLimiter)) {
352
+ reject(err);
353
+ } else {
354
+ this.insuranceLimiter[funcName](...params).then((res) => {
355
+ resolve(res);
356
+ }).catch((res) => {
357
+ reject(res);
358
+ });
359
+ }
360
+ }
361
+ _operation(funcName, params) {
362
+ const promise = this[funcName](...params);
363
+ return new Promise((resolve, reject) => {
364
+ return promise.then((res) => {
365
+ resolve(res);
366
+ }).catch((err) => {
367
+ if (funcName.startsWith("_")) {
368
+ funcName = funcName.slice(1);
369
+ }
370
+ this._handleError(err, funcName, resolve, reject, params);
371
+ });
372
+ });
373
+ }
374
+ consume(key, pointsToConsume = 1, options = {}) {
375
+ return this._operation("_consume", [key, pointsToConsume, options]);
376
+ }
377
+ penalty(key, points = 1, options = {}) {
378
+ return this._operation("_penalty", [key, points, options]);
379
+ }
380
+ reward(key, points = 1, options = {}) {
381
+ return this._operation("_reward", [key, points, options]);
382
+ }
383
+ get(key, options = {}) {
384
+ return this._operation("_get", [key, options]);
385
+ }
386
+ set(key, points, secDuration, options = {}) {
387
+ return this._operation("_set", [key, points, secDuration, options]);
388
+ }
389
+ block(key, secDuration, options = {}) {
390
+ return this._operation("_block", [key, secDuration, options]);
391
+ }
392
+ delete(key, options = {}) {
393
+ return this._operation("_delete", [key, options]);
394
+ }
395
+ _consume() {
396
+ throw new Error("You have to implement the method '_consume'!");
397
+ }
398
+ _penalty() {
399
+ throw new Error("You have to implement the method '_penalty'!");
400
+ }
401
+ _reward() {
402
+ throw new Error("You have to implement the method '_reward'!");
403
+ }
404
+ _get() {
405
+ throw new Error("You have to implement the method '_get'!");
406
+ }
407
+ _set() {
408
+ throw new Error("You have to implement the method '_set'!");
409
+ }
410
+ _block() {
411
+ throw new Error("You have to implement the method '_block'!");
412
+ }
413
+ _delete() {
414
+ throw new Error("You have to implement the method '_delete'!");
415
+ }
416
+ };
417
+ }
418
+ });
419
+
420
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterStoreAbstract.js
421
+ var require_RateLimiterStoreAbstract = __commonJS({
422
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterStoreAbstract.js"(exports, module) {
423
+ "use strict";
424
+ var BlockedKeys = require_BlockedKeys2();
425
+ var RateLimiterRes2 = require_RateLimiterRes();
426
+ var RateLimiterInsuredAbstract = require_RateLimiterInsuredAbstract();
427
+ module.exports = class RateLimiterStoreAbstract extends RateLimiterInsuredAbstract {
428
+ /**
429
+ *
430
+ * @param opts Object Defaults {
431
+ * ... see other in RateLimiterAbstract
432
+ *
433
+ * inMemoryBlockOnConsumed: 40, // Number of points when key is blocked
434
+ * inMemoryBlockDuration: 10, // Block duration in seconds
435
+ * insuranceLimiter: RateLimiterAbstract
436
+ * }
437
+ */
438
+ constructor(opts = {}) {
439
+ super(opts);
440
+ this.inMemoryBlockOnConsumed = opts.inMemoryBlockOnConsumed;
441
+ this.inMemoryBlockDuration = opts.inMemoryBlockDuration;
442
+ this._inMemoryBlockedKeys = new BlockedKeys();
443
+ }
444
+ get client() {
445
+ return this._client;
446
+ }
447
+ set client(value) {
448
+ if (typeof value === "undefined") {
449
+ throw new Error("storeClient is not set");
450
+ }
451
+ this._client = value;
452
+ }
453
+ /**
454
+ * Have to be launched after consume
455
+ * It blocks key and execute evenly depending on result from store
456
+ *
457
+ * It uses _getRateLimiterRes function to prepare RateLimiterRes from store result
458
+ *
459
+ * @param resolve
460
+ * @param reject
461
+ * @param rlKey
462
+ * @param changedPoints
463
+ * @param storeResult
464
+ * @param {Object} options
465
+ * @private
466
+ */
467
+ _afterConsume(resolve, reject, rlKey, changedPoints, storeResult, options = {}) {
468
+ const res = this._getRateLimiterRes(rlKey, changedPoints, storeResult);
469
+ if (this.inMemoryBlockOnConsumed > 0 && !(this.inMemoryBlockDuration > 0) && res.consumedPoints >= this.inMemoryBlockOnConsumed) {
470
+ this._inMemoryBlockedKeys.addMs(rlKey, res.msBeforeNext);
471
+ if (res.consumedPoints > this.points) {
472
+ return reject(res);
473
+ } else {
474
+ return resolve(res);
475
+ }
476
+ } else if (res.consumedPoints > this.points) {
477
+ let blockPromise = Promise.resolve();
478
+ if (this.blockDuration > 0 && res.consumedPoints <= this.points + changedPoints) {
479
+ res.msBeforeNext = this.msBlockDuration;
480
+ blockPromise = this._block(rlKey, res.consumedPoints, this.msBlockDuration, options);
481
+ }
482
+ if (this.inMemoryBlockOnConsumed > 0 && res.consumedPoints >= this.inMemoryBlockOnConsumed) {
483
+ this._inMemoryBlockedKeys.add(rlKey, this.inMemoryBlockDuration);
484
+ res.msBeforeNext = this.msInMemoryBlockDuration;
485
+ }
486
+ blockPromise.then(() => {
487
+ reject(res);
488
+ }).catch((err) => {
489
+ reject(err);
490
+ });
491
+ } else if (this.execEvenly && this.points > 0 && res.msBeforeNext > 0 && !res.isFirstInDuration) {
492
+ let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));
493
+ if (delay < this.execEvenlyMinDelayMs) {
494
+ delay = res.consumedPoints * this.execEvenlyMinDelayMs;
495
+ }
496
+ res.msBeforeNext = Math.max(res.msBeforeNext - delay, 0);
497
+ setTimeout(resolve, delay, res);
498
+ } else {
499
+ resolve(res);
500
+ }
501
+ }
502
+ getInMemoryBlockMsBeforeExpire(rlKey) {
503
+ if (this.inMemoryBlockOnConsumed > 0) {
504
+ return this._inMemoryBlockedKeys.msBeforeExpire(rlKey);
505
+ }
506
+ return 0;
507
+ }
508
+ get inMemoryBlockOnConsumed() {
509
+ return this._inMemoryBlockOnConsumed;
510
+ }
511
+ set inMemoryBlockOnConsumed(value) {
512
+ this._inMemoryBlockOnConsumed = value ? parseInt(value) : 0;
513
+ if (this.inMemoryBlockOnConsumed > 0 && this.points > this.inMemoryBlockOnConsumed) {
514
+ throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option');
515
+ }
516
+ }
517
+ get inMemoryBlockDuration() {
518
+ return this._inMemoryBlockDuration;
519
+ }
520
+ set inMemoryBlockDuration(value) {
521
+ this._inMemoryBlockDuration = value ? parseInt(value) : 0;
522
+ if (this.inMemoryBlockDuration > 0 && this.inMemoryBlockOnConsumed === 0) {
523
+ throw new Error("inMemoryBlockOnConsumed option must be set up");
524
+ }
525
+ }
526
+ get msInMemoryBlockDuration() {
527
+ return this._inMemoryBlockDuration * 1e3;
528
+ }
529
+ /**
530
+ * Block any key for secDuration seconds
531
+ *
532
+ * @param key
533
+ * @param secDuration
534
+ * @param {Object} options
535
+ *
536
+ * @return Promise<RateLimiterRes>
537
+ */
538
+ block(key, secDuration, options = {}) {
539
+ const msDuration = secDuration * 1e3;
540
+ return this._block(this.getKey(key), this.points + 1, msDuration, options);
541
+ }
542
+ /**
543
+ * Set points by key for any duration
544
+ *
545
+ * @param key
546
+ * @param points
547
+ * @param secDuration
548
+ * @param {Object} options
549
+ *
550
+ * @return Promise<RateLimiterRes>
551
+ */
552
+ set(key, points, secDuration, options = {}) {
553
+ const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1e3;
554
+ return this._set(this.getKey(key), points, msDuration, options);
555
+ }
556
+ /**
557
+ *
558
+ * @param key
559
+ * @param pointsToConsume
560
+ * @param {Object} options
561
+ * @returns Promise<RateLimiterRes>
562
+ */
563
+ _consume(key, pointsToConsume = 1, options = {}) {
564
+ return new Promise((resolve, reject) => {
565
+ const rlKey = this.getKey(key);
566
+ const inMemoryBlockMsBeforeExpire = this.getInMemoryBlockMsBeforeExpire(rlKey);
567
+ if (inMemoryBlockMsBeforeExpire > 0) {
568
+ return reject(new RateLimiterRes2(0, inMemoryBlockMsBeforeExpire));
569
+ }
570
+ this._upsert(rlKey, pointsToConsume, this._getKeySecDuration(options) * 1e3, false, options).then((res) => {
571
+ this._afterConsume(resolve, reject, rlKey, pointsToConsume, res);
572
+ }).catch((err) => reject(err));
573
+ });
574
+ }
575
+ /**
576
+ *
577
+ * @param key
578
+ * @param points
579
+ * @param {Object} options
580
+ * @returns Promise<RateLimiterRes>
581
+ */
582
+ _penalty(key, points = 1, options = {}) {
583
+ const rlKey = this.getKey(key);
584
+ return new Promise((resolve, reject) => {
585
+ this._upsert(rlKey, points, this._getKeySecDuration(options) * 1e3, false, options).then((res) => {
586
+ resolve(this._getRateLimiterRes(rlKey, points, res));
587
+ }).catch((res) => reject(res));
588
+ });
589
+ }
590
+ /**
591
+ *
592
+ * @param key
593
+ * @param points
594
+ * @param {Object} options
595
+ * @returns Promise<RateLimiterRes>
596
+ */
597
+ _reward(key, points = 1, options = {}) {
598
+ const rlKey = this.getKey(key);
599
+ return new Promise((resolve, reject) => {
600
+ this._upsert(rlKey, -points, this._getKeySecDuration(options) * 1e3, false, options).then((res) => {
601
+ resolve(this._getRateLimiterRes(rlKey, -points, res));
602
+ }).catch((res) => reject(res));
603
+ });
604
+ }
605
+ /**
606
+ *
607
+ * @param key
608
+ * @param {Object} options
609
+ * @returns Promise<RateLimiterRes>|null
610
+ */
611
+ get(key, options = {}) {
612
+ const rlKey = this.getKey(key);
613
+ return new Promise((resolve, reject) => {
614
+ this._get(rlKey, options).then((res) => {
615
+ if (res === null || typeof res === "undefined") {
616
+ resolve(null);
617
+ } else {
618
+ resolve(this._getRateLimiterRes(rlKey, 0, res));
619
+ }
620
+ }).catch((err) => {
621
+ this._handleError(err, "get", resolve, reject, [key, options]);
622
+ });
623
+ });
624
+ }
625
+ /**
626
+ *
627
+ * @param key
628
+ * @param {Object} options
629
+ * @returns Promise<boolean>
630
+ */
631
+ delete(key, options = {}) {
632
+ const rlKey = this.getKey(key);
633
+ return new Promise((resolve, reject) => {
634
+ this._delete(rlKey, options).then((res) => {
635
+ this._inMemoryBlockedKeys.delete(rlKey);
636
+ resolve(res);
637
+ }).catch((err) => {
638
+ this._handleError(err, "delete", resolve, reject, [key, options]);
639
+ });
640
+ });
641
+ }
642
+ /**
643
+ * Cleanup keys no-matter expired or not.
644
+ */
645
+ deleteInMemoryBlockedAll() {
646
+ this._inMemoryBlockedKeys.delete();
647
+ }
648
+ /**
649
+ * Get RateLimiterRes object filled depending on storeResult, which specific for exact store
650
+ *
651
+ * @param rlKey
652
+ * @param changedPoints
653
+ * @param storeResult
654
+ * @private
655
+ */
656
+ _getRateLimiterRes(rlKey, changedPoints, storeResult) {
657
+ throw new Error("You have to implement the method '_getRateLimiterRes'!");
658
+ }
659
+ /**
660
+ * Block key for this.msBlockDuration milliseconds
661
+ * Usually, it just prolongs lifetime of key
662
+ *
663
+ * @param rlKey
664
+ * @param initPoints
665
+ * @param msDuration
666
+ * @param {Object} options
667
+ *
668
+ * @return Promise<any>
669
+ */
670
+ _block(rlKey, initPoints, msDuration, options = {}) {
671
+ return new Promise((resolve, reject) => {
672
+ this._upsert(rlKey, initPoints, msDuration, true, options).then(() => {
673
+ resolve(new RateLimiterRes2(0, msDuration > 0 ? msDuration : -1, initPoints));
674
+ }).catch((err) => {
675
+ this._handleError(err, "block", resolve, reject, [this.parseKey(rlKey), msDuration / 1e3, options]);
676
+ });
677
+ });
678
+ }
679
+ /**
680
+ * @param rlKey
681
+ * @param points
682
+ * @param msDuration
683
+ * @param {Object} options
684
+ *
685
+ * @return Promise<any>
686
+ */
687
+ _set(rlKey, points, msDuration, options = {}) {
688
+ return new Promise((resolve, reject) => {
689
+ this._upsert(rlKey, points, msDuration, true, options).then(() => {
690
+ resolve(new RateLimiterRes2(0, msDuration > 0 ? msDuration : -1, points));
691
+ }).catch((err) => {
692
+ this._handleError(err, "set", resolve, reject, [this.parseKey(rlKey), points, msDuration / 1e3, options]);
693
+ });
694
+ });
695
+ }
696
+ /**
697
+ * Have to be implemented in every limiter
698
+ * Resolve with raw result from Store OR null if rlKey is not set
699
+ * or Reject with error
700
+ *
701
+ * @param rlKey
702
+ * @param {Object} options
703
+ * @private
704
+ *
705
+ * @return Promise<any>
706
+ */
707
+ _get(rlKey, options = {}) {
708
+ throw new Error("You have to implement the method '_get'!");
709
+ }
710
+ /**
711
+ * Have to be implemented
712
+ * Resolve with true OR false if rlKey doesn't exist
713
+ * or Reject with error
714
+ *
715
+ * @param rlKey
716
+ * @param {Object} options
717
+ * @private
718
+ *
719
+ * @return Promise<any>
720
+ */
721
+ _delete(rlKey, options = {}) {
722
+ throw new Error("You have to implement the method '_delete'!");
723
+ }
724
+ /**
725
+ * Have to be implemented
726
+ * Resolve with object used for {@link _getRateLimiterRes} to generate {@link RateLimiterRes}
727
+ *
728
+ * @param {string} rlKey
729
+ * @param {number} points
730
+ * @param {number} msDuration
731
+ * @param {boolean} forceExpire
732
+ * @param {Object} options
733
+ * @abstract
734
+ *
735
+ * @return Promise<Object>
736
+ */
737
+ _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {
738
+ throw new Error("You have to implement the method '_upsert'!");
739
+ }
740
+ };
741
+ }
742
+ });
743
+
744
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterRedis.js
745
+ var require_RateLimiterRedis = __commonJS({
746
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterRedis.js"(exports, module) {
747
+ "use strict";
748
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
749
+ var RateLimiterRes2 = require_RateLimiterRes();
750
+ var incrTtlLuaScript = `redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} `;
751
+ var RateLimiterRedis = class extends RateLimiterStoreAbstract {
752
+ /**
753
+ *
754
+ * @param {Object} opts
755
+ * Defaults {
756
+ * ... see other in RateLimiterStoreAbstract
757
+ *
758
+ * redis: RedisClient
759
+ * rejectIfRedisNotReady: boolean = false - reject / invoke insuranceLimiter immediately when redis connection is not "ready"
760
+ * }
761
+ */
762
+ constructor(opts) {
763
+ super(opts);
764
+ this.client = opts.storeClient;
765
+ this._rejectIfRedisNotReady = !!opts.rejectIfRedisNotReady;
766
+ this._incrTtlLuaScript = opts.customIncrTtlLuaScript || incrTtlLuaScript;
767
+ this.useRedisPackage = opts.useRedisPackage || this.client.constructor.name === "Commander" || false;
768
+ this.useRedis3AndLowerPackage = opts.useRedis3AndLowerPackage;
769
+ if (typeof this.client.defineCommand === "function") {
770
+ this.client.defineCommand("rlflxIncr", {
771
+ numberOfKeys: 1,
772
+ lua: this._incrTtlLuaScript
773
+ });
774
+ }
775
+ }
776
+ /**
777
+ * Prevent actual redis call if redis connection is not ready
778
+ * Because of different connection state checks for ioredis and node-redis, only this clients would be actually checked.
779
+ * For any other clients all the requests would be passed directly to redis client
780
+ * @param {String} rlKey
781
+ * @param {Boolean} isReadonly
782
+ * @return {boolean}
783
+ * @private
784
+ */
785
+ _isRedisReady(rlKey, isReadonly) {
786
+ if (!this._rejectIfRedisNotReady) {
787
+ return true;
788
+ }
789
+ if (this.client.status) {
790
+ return this.client.status === "ready";
791
+ }
792
+ if (typeof this.client.isReady === "function") {
793
+ return this.client.isReady();
794
+ }
795
+ if (typeof this.client.isReady === "boolean") {
796
+ return this.client.isReady === true;
797
+ }
798
+ if (this.client._slots && typeof this.client._slots.getClient === "function") {
799
+ if (typeof this.client.isOpen === "boolean" && this.client.isOpen !== true) {
800
+ return false;
801
+ }
802
+ try {
803
+ const slotClient = this.client._slots.getClient(rlKey, isReadonly);
804
+ return slotClient && slotClient.isReady === true;
805
+ } catch (error) {
806
+ return false;
807
+ }
808
+ }
809
+ return true;
810
+ }
811
+ _getRateLimiterRes(rlKey, changedPoints, result) {
812
+ let [consumed, resTtlMs] = result;
813
+ if (Array.isArray(consumed)) {
814
+ [, consumed] = consumed;
815
+ [, resTtlMs] = resTtlMs;
816
+ }
817
+ const res = new RateLimiterRes2();
818
+ res.consumedPoints = parseInt(consumed);
819
+ res.isFirstInDuration = res.consumedPoints === changedPoints;
820
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
821
+ res.msBeforeNext = resTtlMs;
822
+ return res;
823
+ }
824
+ async _upsert(rlKey, points, msDuration, forceExpire = false) {
825
+ if (typeof points == "string") {
826
+ if (!RegExp("^[1-9][0-9]*$").test(points)) {
827
+ throw new Error("Consuming string different than integer values is not supported by this package");
828
+ }
829
+ } else if (!Number.isInteger(points)) {
830
+ throw new Error("Consuming decimal number of points is not supported by this package");
831
+ }
832
+ if (!this._isRedisReady(rlKey, false)) {
833
+ throw new Error("Redis connection is not ready");
834
+ }
835
+ const secDuration = Math.floor(msDuration / 1e3);
836
+ const multi = this.client.multi();
837
+ if (forceExpire) {
838
+ if (secDuration > 0) {
839
+ if (!this.useRedisPackage && !this.useRedis3AndLowerPackage) {
840
+ multi.set(rlKey, points, "EX", secDuration);
841
+ } else {
842
+ multi.set(rlKey, points, { EX: secDuration });
843
+ }
844
+ } else {
845
+ multi.set(rlKey, points);
846
+ }
847
+ if (!this.useRedisPackage && !this.useRedis3AndLowerPackage) {
848
+ return multi.pttl(rlKey).exec(true);
849
+ }
850
+ return multi.pTTL(rlKey).exec(true);
851
+ }
852
+ if (secDuration > 0) {
853
+ if (!this.useRedisPackage && !this.useRedis3AndLowerPackage) {
854
+ return this.client.rlflxIncr(
855
+ [rlKey].concat([String(points), String(secDuration), String(this.points), String(this.duration)])
856
+ );
857
+ }
858
+ if (this.useRedis3AndLowerPackage) {
859
+ return new Promise((resolve, reject) => {
860
+ const incrCallback = function(err, result) {
861
+ if (err) {
862
+ return reject(err);
863
+ }
864
+ return resolve(result);
865
+ };
866
+ if (typeof this.client.rlflxIncr === "function") {
867
+ this.client.rlflxIncr(rlKey, points, secDuration, this.points, this.duration, incrCallback);
868
+ } else {
869
+ this.client.eval(this._incrTtlLuaScript, 1, rlKey, points, secDuration, this.points, this.duration, incrCallback);
870
+ }
871
+ });
872
+ } else {
873
+ return this.client.eval(this._incrTtlLuaScript, {
874
+ keys: [rlKey],
875
+ arguments: [String(points), String(secDuration), String(this.points), String(this.duration)]
876
+ });
877
+ }
878
+ } else {
879
+ if (!this.useRedisPackage && !this.useRedis3AndLowerPackage) {
880
+ return multi.incrby(rlKey, points).pttl(rlKey).exec(true);
881
+ }
882
+ return multi.incrBy(rlKey, points).pTTL(rlKey).exec(true);
883
+ }
884
+ }
885
+ async _get(rlKey) {
886
+ if (!this._isRedisReady(rlKey, true)) {
887
+ throw new Error("Redis connection is not ready");
888
+ }
889
+ if (!this.useRedisPackage && !this.useRedis3AndLowerPackage) {
890
+ return this.client.multi().get(rlKey).pttl(rlKey).exec().then((result) => {
891
+ const [[, points]] = result;
892
+ if (points === null) return null;
893
+ return result;
894
+ });
895
+ }
896
+ return this.client.multi().get(rlKey).pTTL(rlKey).exec(true).then((result) => {
897
+ const [points] = result;
898
+ if (points === null) return null;
899
+ return result;
900
+ });
901
+ }
902
+ _delete(rlKey) {
903
+ return this.client.del(rlKey).then((result) => result > 0);
904
+ }
905
+ };
906
+ module.exports = RateLimiterRedis;
907
+ }
908
+ });
909
+
910
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterRedisNonAtomic.js
911
+ var require_RateLimiterRedisNonAtomic = __commonJS({
912
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterRedisNonAtomic.js"(exports, module) {
913
+ "use strict";
914
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
915
+ var RateLimiterRes2 = require_RateLimiterRes();
916
+ var RateLimiterRedisNonAtomic = class extends RateLimiterStoreAbstract {
917
+ constructor(opts) {
918
+ super(opts);
919
+ this.client = opts.storeClient;
920
+ this._rejectIfRedisNotReady = !!opts.rejectIfRedisNotReady;
921
+ this.useRedisPackage = opts.useRedisPackage || this.client.constructor.name === "Commander" || false;
922
+ }
923
+ _isRedisReady(rlKey, isReadonly) {
924
+ if (!this._rejectIfRedisNotReady) {
925
+ return true;
926
+ }
927
+ if (this.client.status) {
928
+ return this.client.status === "ready";
929
+ }
930
+ if (typeof this.client.isReady === "function") {
931
+ return this.client.isReady();
932
+ }
933
+ if (typeof this.client.isReady === "boolean") {
934
+ return this.client.isReady === true;
935
+ }
936
+ if (this.client._slots && typeof this.client._slots.getClient === "function") {
937
+ if (typeof this.client.isOpen === "boolean" && this.client.isOpen !== true) {
938
+ return false;
939
+ }
940
+ try {
941
+ const slotClient = this.client._slots.getClient(rlKey, isReadonly);
942
+ return slotClient && slotClient.isReady === true;
943
+ } catch (error) {
944
+ return false;
945
+ }
946
+ }
947
+ return true;
948
+ }
949
+ _getRateLimiterRes(rlKey, changedPoints, result) {
950
+ let [consumed, resTtlMs] = result;
951
+ if (Array.isArray(consumed)) {
952
+ [, consumed] = consumed;
953
+ [, resTtlMs] = resTtlMs;
954
+ }
955
+ const res = new RateLimiterRes2();
956
+ res.consumedPoints = parseInt(consumed);
957
+ res.isFirstInDuration = res.consumedPoints === changedPoints;
958
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
959
+ res.msBeforeNext = resTtlMs;
960
+ return res;
961
+ }
962
+ _parseStoreResult(result) {
963
+ let points;
964
+ let ttlMs;
965
+ if (Array.isArray(result[0])) {
966
+ [, points] = result[0];
967
+ [, ttlMs] = result[1];
968
+ } else {
969
+ [points, ttlMs] = result;
970
+ }
971
+ return {
972
+ points: parseInt(points, 10),
973
+ ttlMs
974
+ };
975
+ }
976
+ _execMulti(multi) {
977
+ return multi.exec();
978
+ }
979
+ _setKey(rlKey, points, secDuration) {
980
+ const multi = this.client.multi();
981
+ if (secDuration > 0) {
982
+ if (!this.useRedisPackage) {
983
+ multi.set(rlKey, points, "EX", secDuration);
984
+ } else {
985
+ multi.set(rlKey, points, { EX: secDuration });
986
+ }
987
+ } else {
988
+ multi.set(rlKey, points);
989
+ }
990
+ return this._execMulti(multi);
991
+ }
992
+ _setKeyWithTtlMs(rlKey, points, ttlMs) {
993
+ const multi = this.client.multi();
994
+ multi.set(rlKey, points);
995
+ if (ttlMs > 0) {
996
+ if (!this.useRedisPackage) {
997
+ multi.pexpire(rlKey, ttlMs);
998
+ } else {
999
+ multi.pExpire(rlKey, ttlMs);
1000
+ }
1001
+ }
1002
+ return this._execMulti(multi);
1003
+ }
1004
+ async _upsert(rlKey, points, msDuration, forceExpire = false) {
1005
+ if (typeof points == "string") {
1006
+ if (!RegExp("^[1-9][0-9]*$").test(points)) {
1007
+ throw new Error("Consuming string different than integer values is not supported by this package");
1008
+ }
1009
+ } else if (!Number.isInteger(points)) {
1010
+ throw new Error("Consuming decimal number of points is not supported by this package");
1011
+ }
1012
+ if (!this._isRedisReady(rlKey, false)) {
1013
+ throw new Error("Redis connection is not ready");
1014
+ }
1015
+ const parsedPoints = typeof points === "string" ? parseInt(points, 10) : points;
1016
+ const secDuration = Math.floor(msDuration / 1e3);
1017
+ if (forceExpire) {
1018
+ await this._setKey(rlKey, parsedPoints, secDuration);
1019
+ return [parsedPoints, secDuration > 0 ? secDuration * 1e3 : -1];
1020
+ }
1021
+ const currentResult = await this._get(rlKey);
1022
+ const hasCurrent = currentResult !== null;
1023
+ const current = hasCurrent ? this._parseStoreResult(currentResult) : { points: 0, ttlMs: -1 };
1024
+ const newPoints = current.points + parsedPoints;
1025
+ if (secDuration > 0) {
1026
+ if (!hasCurrent) {
1027
+ await this._setKey(rlKey, newPoints, secDuration);
1028
+ return [newPoints, secDuration * 1e3];
1029
+ }
1030
+ if (current.ttlMs <= 0) {
1031
+ await this._setKey(rlKey, newPoints, secDuration);
1032
+ return [newPoints, secDuration * 1e3];
1033
+ }
1034
+ await this._setKeyWithTtlMs(rlKey, newPoints, current.ttlMs);
1035
+ return [newPoints, current.ttlMs];
1036
+ }
1037
+ await this._setKey(rlKey, newPoints, 0);
1038
+ return [newPoints, -1];
1039
+ }
1040
+ async _get(rlKey) {
1041
+ if (!this._isRedisReady(rlKey, true)) {
1042
+ throw new Error("Redis connection is not ready");
1043
+ }
1044
+ const multi = this.client.multi().get(rlKey);
1045
+ if (!this.useRedisPackage) {
1046
+ multi.pttl(rlKey);
1047
+ } else {
1048
+ multi.pTTL(rlKey);
1049
+ }
1050
+ return this._execMulti(multi).then((result) => {
1051
+ if (Array.isArray(result[0])) {
1052
+ const [, points2] = result[0];
1053
+ if (points2 === null) return null;
1054
+ return result;
1055
+ }
1056
+ const [points] = result;
1057
+ if (points === null) return null;
1058
+ return result;
1059
+ });
1060
+ }
1061
+ _delete(rlKey) {
1062
+ return this.client.del(rlKey).then((result) => result > 0);
1063
+ }
1064
+ };
1065
+ module.exports = RateLimiterRedisNonAtomic;
1066
+ }
1067
+ });
1068
+
1069
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterMongo.js
1070
+ var require_RateLimiterMongo = __commonJS({
1071
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterMongo.js"(exports, module) {
1072
+ "use strict";
1073
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
1074
+ var RateLimiterRes2 = require_RateLimiterRes();
1075
+ var RateLimiterMongo = class _RateLimiterMongo extends RateLimiterStoreAbstract {
1076
+ /**
1077
+ *
1078
+ * @param {Object} opts
1079
+ * Defaults {
1080
+ * indexKeyPrefix: {attr1: 1, attr2: 1}
1081
+ * ... see other in RateLimiterStoreAbstract
1082
+ *
1083
+ * mongo: MongoClient
1084
+ * }
1085
+ */
1086
+ constructor(opts) {
1087
+ super(opts);
1088
+ this.dbName = opts.dbName;
1089
+ this.tableName = opts.tableName;
1090
+ this.indexKeyPrefix = opts.indexKeyPrefix;
1091
+ this.disableIndexesCreation = opts.disableIndexesCreation;
1092
+ if (opts.mongo) {
1093
+ this.client = opts.mongo;
1094
+ } else {
1095
+ this.client = opts.storeClient;
1096
+ }
1097
+ if (typeof this.client.then === "function") {
1098
+ this.client.then((conn) => {
1099
+ this.client = conn;
1100
+ this._initCollection();
1101
+ });
1102
+ } else {
1103
+ this._initCollection();
1104
+ }
1105
+ }
1106
+ get dbName() {
1107
+ return this._dbName;
1108
+ }
1109
+ set dbName(value) {
1110
+ this._dbName = typeof value === "undefined" ? _RateLimiterMongo.getDbName() : value;
1111
+ }
1112
+ static getDbName() {
1113
+ return "node-rate-limiter-flexible";
1114
+ }
1115
+ get tableName() {
1116
+ return this._tableName;
1117
+ }
1118
+ set tableName(value) {
1119
+ this._tableName = typeof value === "undefined" ? this.keyPrefix : value;
1120
+ }
1121
+ get client() {
1122
+ return this._client;
1123
+ }
1124
+ set client(value) {
1125
+ if (typeof value === "undefined") {
1126
+ throw new Error("mongo is not set");
1127
+ }
1128
+ this._client = value;
1129
+ }
1130
+ get indexKeyPrefix() {
1131
+ return this._indexKeyPrefix;
1132
+ }
1133
+ set indexKeyPrefix(obj) {
1134
+ this._indexKeyPrefix = obj || {};
1135
+ }
1136
+ get disableIndexesCreation() {
1137
+ return this._disableIndexesCreation;
1138
+ }
1139
+ set disableIndexesCreation(value) {
1140
+ this._disableIndexesCreation = !!value;
1141
+ }
1142
+ async createIndexes() {
1143
+ const db = typeof this.client.db === "function" ? this.client.db(this.dbName) : this.client;
1144
+ const collection = db.collection(this.tableName);
1145
+ await collection.createIndex({ expire: -1 }, { expireAfterSeconds: 0 });
1146
+ await collection.createIndex(Object.assign({}, this.indexKeyPrefix, { key: 1 }), { unique: true });
1147
+ }
1148
+ _initCollection() {
1149
+ const db = typeof this.client.db === "function" ? this.client.db(this.dbName) : this.client;
1150
+ const collection = db.collection(this.tableName);
1151
+ if (!this.disableIndexesCreation) {
1152
+ this.createIndexes().catch((err) => {
1153
+ console.error(`Cannot create indexes for mongo collection ${this.tableName}`, err);
1154
+ });
1155
+ }
1156
+ this._collection = collection;
1157
+ }
1158
+ _getRateLimiterRes(rlKey, changedPoints, result) {
1159
+ const res = new RateLimiterRes2();
1160
+ let doc;
1161
+ if (typeof result.value === "undefined") {
1162
+ doc = result;
1163
+ } else {
1164
+ doc = result.value;
1165
+ }
1166
+ res.isFirstInDuration = doc.points === changedPoints;
1167
+ res.consumedPoints = doc.points;
1168
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
1169
+ res.msBeforeNext = doc.expire !== null ? Math.max(new Date(doc.expire).getTime() - Date.now(), 0) : -1;
1170
+ return res;
1171
+ }
1172
+ _upsert(key, points, msDuration, forceExpire = false, options = {}) {
1173
+ if (!this._collection) {
1174
+ return Promise.reject(Error("Mongo connection is not established"));
1175
+ }
1176
+ const docAttrs = options.attrs || {};
1177
+ let where;
1178
+ let upsertData;
1179
+ if (forceExpire) {
1180
+ where = { key };
1181
+ where = Object.assign(where, docAttrs);
1182
+ upsertData = {
1183
+ $set: {
1184
+ key,
1185
+ points,
1186
+ expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null
1187
+ }
1188
+ };
1189
+ upsertData.$set = Object.assign(upsertData.$set, docAttrs);
1190
+ } else {
1191
+ where = {
1192
+ $or: [
1193
+ { expire: { $gt: /* @__PURE__ */ new Date() } },
1194
+ { expire: { $eq: null } }
1195
+ ],
1196
+ key
1197
+ };
1198
+ where = Object.assign(where, docAttrs);
1199
+ upsertData = {
1200
+ $setOnInsert: {
1201
+ key,
1202
+ expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null
1203
+ },
1204
+ $inc: { points }
1205
+ };
1206
+ upsertData.$setOnInsert = Object.assign(upsertData.$setOnInsert, docAttrs);
1207
+ }
1208
+ const upsertOptions = {
1209
+ upsert: true,
1210
+ returnDocument: "after"
1211
+ };
1212
+ return new Promise((resolve, reject) => {
1213
+ this._collection.findOneAndUpdate(
1214
+ where,
1215
+ upsertData,
1216
+ upsertOptions
1217
+ ).then((res) => {
1218
+ resolve(res);
1219
+ }).catch((errUpsert) => {
1220
+ if (errUpsert && errUpsert.code === 11e3) {
1221
+ const replaceWhere = Object.assign({
1222
+ // try to replace OLD limit doc
1223
+ $or: [
1224
+ { expire: { $lte: /* @__PURE__ */ new Date() } },
1225
+ { expire: { $eq: null } }
1226
+ ],
1227
+ key
1228
+ }, docAttrs);
1229
+ const replaceTo = {
1230
+ $set: Object.assign({
1231
+ key,
1232
+ points,
1233
+ expire: msDuration > 0 ? new Date(Date.now() + msDuration) : null
1234
+ }, docAttrs)
1235
+ };
1236
+ this._collection.findOneAndUpdate(
1237
+ replaceWhere,
1238
+ replaceTo,
1239
+ upsertOptions
1240
+ ).then((res) => {
1241
+ resolve(res);
1242
+ }).catch((errReplace) => {
1243
+ if (errReplace && errReplace.code === 11e3) {
1244
+ this._upsert(key, points, msDuration, forceExpire).then((res) => resolve(res)).catch((err) => reject(err));
1245
+ } else {
1246
+ reject(errReplace);
1247
+ }
1248
+ });
1249
+ } else {
1250
+ reject(errUpsert);
1251
+ }
1252
+ });
1253
+ });
1254
+ }
1255
+ _get(rlKey, options = {}) {
1256
+ if (!this._collection) {
1257
+ return Promise.reject(Error("Mongo connection is not established"));
1258
+ }
1259
+ const docAttrs = options.attrs || {};
1260
+ const where = Object.assign({
1261
+ key: rlKey,
1262
+ $or: [
1263
+ { expire: { $gt: /* @__PURE__ */ new Date() } },
1264
+ { expire: { $eq: null } }
1265
+ ]
1266
+ }, docAttrs);
1267
+ return this._collection.findOne(where);
1268
+ }
1269
+ _delete(rlKey, options = {}) {
1270
+ if (!this._collection) {
1271
+ return Promise.reject(Error("Mongo connection is not established"));
1272
+ }
1273
+ const docAttrs = options.attrs || {};
1274
+ const where = Object.assign({ key: rlKey }, docAttrs);
1275
+ return this._collection.deleteOne(where).then((res) => res.deletedCount > 0);
1276
+ }
1277
+ };
1278
+ module.exports = RateLimiterMongo;
1279
+ }
1280
+ });
1281
+
1282
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterMySQL.js
1283
+ var require_RateLimiterMySQL = __commonJS({
1284
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterMySQL.js"(exports, module) {
1285
+ "use strict";
1286
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
1287
+ var RateLimiterRes2 = require_RateLimiterRes();
1288
+ var RateLimiterMySQL = class extends RateLimiterStoreAbstract {
1289
+ /**
1290
+ * @callback callback
1291
+ * @param {Object} err
1292
+ *
1293
+ * @param {Object} opts
1294
+ * @param {callback} cb
1295
+ * Defaults {
1296
+ * ... see other in RateLimiterStoreAbstract
1297
+ *
1298
+ * storeClient: anySqlClient,
1299
+ * storeType: 'knex', // required only for Knex instance
1300
+ * dbName: 'string',
1301
+ * tableName: 'string',
1302
+ * }
1303
+ */
1304
+ constructor(opts, cb = null) {
1305
+ super(opts);
1306
+ this.client = opts.storeClient;
1307
+ this.clientType = opts.storeType;
1308
+ this.dbName = opts.dbName;
1309
+ this.tableName = opts.tableName;
1310
+ this.clearExpiredByTimeout = opts.clearExpiredByTimeout;
1311
+ this.tableCreated = opts.tableCreated;
1312
+ if (!this.tableCreated) {
1313
+ this._createDbAndTable().then(() => {
1314
+ this.tableCreated = true;
1315
+ if (this.clearExpiredByTimeout) {
1316
+ this._clearExpiredHourAgo();
1317
+ }
1318
+ if (typeof cb === "function") {
1319
+ cb();
1320
+ }
1321
+ }).catch((err) => {
1322
+ if (typeof cb === "function") {
1323
+ cb(err);
1324
+ } else {
1325
+ throw err;
1326
+ }
1327
+ });
1328
+ } else {
1329
+ if (this.clearExpiredByTimeout) {
1330
+ this._clearExpiredHourAgo();
1331
+ }
1332
+ if (typeof cb === "function") {
1333
+ cb();
1334
+ }
1335
+ }
1336
+ }
1337
+ clearExpired(expire) {
1338
+ return new Promise((resolve) => {
1339
+ this._getConnection().then((conn) => {
1340
+ conn.query(`DELETE FROM ??.?? WHERE expire < ?`, [this.dbName, this.tableName, expire], () => {
1341
+ this._releaseConnection(conn);
1342
+ resolve();
1343
+ });
1344
+ }).catch(() => {
1345
+ resolve();
1346
+ });
1347
+ });
1348
+ }
1349
+ _clearExpiredHourAgo() {
1350
+ if (this._clearExpiredTimeoutId) {
1351
+ clearTimeout(this._clearExpiredTimeoutId);
1352
+ }
1353
+ this._clearExpiredTimeoutId = setTimeout(() => {
1354
+ this.clearExpired(Date.now() - 36e5).then(() => {
1355
+ this._clearExpiredHourAgo();
1356
+ });
1357
+ }, 3e5);
1358
+ this._clearExpiredTimeoutId.unref();
1359
+ }
1360
+ /**
1361
+ *
1362
+ * @return Promise<any>
1363
+ * @private
1364
+ */
1365
+ _getConnection() {
1366
+ switch (this.clientType) {
1367
+ case "pool":
1368
+ return new Promise((resolve, reject) => {
1369
+ this.client.getConnection((errConn, conn) => {
1370
+ if (errConn) {
1371
+ return reject(errConn);
1372
+ }
1373
+ resolve(conn);
1374
+ });
1375
+ });
1376
+ case "sequelize":
1377
+ return this._getSequelizeConnectionManager().getConnection();
1378
+ case "knex":
1379
+ return this.client.client.acquireConnection();
1380
+ default:
1381
+ return Promise.resolve(this.client);
1382
+ }
1383
+ }
1384
+ _releaseConnection(conn) {
1385
+ switch (this.clientType) {
1386
+ case "pool":
1387
+ return conn.release();
1388
+ case "sequelize":
1389
+ return this._getSequelizeConnectionManager().releaseConnection(conn);
1390
+ case "knex":
1391
+ return this.client.client.releaseConnection(conn);
1392
+ default:
1393
+ return true;
1394
+ }
1395
+ }
1396
+ _getSequelizeConnectionManager() {
1397
+ let connectionManager;
1398
+ let originalError;
1399
+ try {
1400
+ connectionManager = this.client.connectionManager;
1401
+ } catch (err) {
1402
+ originalError = err;
1403
+ }
1404
+ if (connectionManager) {
1405
+ return connectionManager;
1406
+ }
1407
+ if (this.client.dialect && this.client.dialect.connectionManager) {
1408
+ return this.client.dialect.connectionManager;
1409
+ }
1410
+ if (originalError) {
1411
+ throw originalError;
1412
+ }
1413
+ throw new Error("Sequelize connection manager is not available");
1414
+ }
1415
+ /**
1416
+ *
1417
+ * @returns {Promise<any>}
1418
+ * @private
1419
+ */
1420
+ _createDbAndTable() {
1421
+ return new Promise((resolve, reject) => {
1422
+ this._getConnection().then((conn) => {
1423
+ conn.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`, (errDb) => {
1424
+ if (errDb) {
1425
+ this._releaseConnection(conn);
1426
+ return reject(errDb);
1427
+ }
1428
+ conn.query(this._getCreateTableStmt(), (err) => {
1429
+ if (err) {
1430
+ this._releaseConnection(conn);
1431
+ return reject(err);
1432
+ }
1433
+ this._releaseConnection(conn);
1434
+ resolve();
1435
+ });
1436
+ });
1437
+ }).catch((err) => {
1438
+ reject(err);
1439
+ });
1440
+ });
1441
+ }
1442
+ _getCreateTableStmt() {
1443
+ return `CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`;
1444
+ }
1445
+ get clientType() {
1446
+ return this._clientType;
1447
+ }
1448
+ set clientType(value) {
1449
+ if (typeof value === "undefined") {
1450
+ if (this.client.constructor.name === "Connection") {
1451
+ value = "connection";
1452
+ } else if (this.client.constructor.name === "Pool") {
1453
+ value = "pool";
1454
+ } else if (this.client.constructor.name === "Sequelize") {
1455
+ value = "sequelize";
1456
+ } else {
1457
+ throw new Error("storeType is not defined");
1458
+ }
1459
+ }
1460
+ this._clientType = value.toLowerCase();
1461
+ }
1462
+ get dbName() {
1463
+ return this._dbName;
1464
+ }
1465
+ set dbName(value) {
1466
+ this._dbName = typeof value === "undefined" ? "rtlmtrflx" : value;
1467
+ }
1468
+ get tableName() {
1469
+ return this._tableName;
1470
+ }
1471
+ set tableName(value) {
1472
+ this._tableName = typeof value === "undefined" ? this.keyPrefix : value;
1473
+ }
1474
+ get tableCreated() {
1475
+ return this._tableCreated;
1476
+ }
1477
+ set tableCreated(value) {
1478
+ this._tableCreated = typeof value === "undefined" ? false : !!value;
1479
+ }
1480
+ get clearExpiredByTimeout() {
1481
+ return this._clearExpiredByTimeout;
1482
+ }
1483
+ set clearExpiredByTimeout(value) {
1484
+ this._clearExpiredByTimeout = typeof value === "undefined" ? true : Boolean(value);
1485
+ }
1486
+ _getRateLimiterRes(rlKey, changedPoints, result) {
1487
+ const res = new RateLimiterRes2();
1488
+ const [row] = result;
1489
+ res.isFirstInDuration = changedPoints === row.points;
1490
+ res.consumedPoints = res.isFirstInDuration ? changedPoints : row.points;
1491
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
1492
+ res.msBeforeNext = row.expire ? Math.max(row.expire - Date.now(), 0) : -1;
1493
+ return res;
1494
+ }
1495
+ _upsertTransaction(conn, key, points, msDuration, forceExpire) {
1496
+ return new Promise((resolve, reject) => {
1497
+ conn.query("BEGIN", (errBegin) => {
1498
+ if (errBegin) {
1499
+ conn.rollback();
1500
+ return reject(errBegin);
1501
+ }
1502
+ const dateNow = Date.now();
1503
+ const newExpire = msDuration > 0 ? dateNow + msDuration : null;
1504
+ let q;
1505
+ let values;
1506
+ if (forceExpire) {
1507
+ q = `INSERT INTO ??.?? VALUES (?, ?, ?)
1508
+ ON DUPLICATE KEY UPDATE
1509
+ points = ?,
1510
+ expire = ?;`;
1511
+ values = [
1512
+ this.dbName,
1513
+ this.tableName,
1514
+ key,
1515
+ points,
1516
+ newExpire,
1517
+ points,
1518
+ newExpire
1519
+ ];
1520
+ } else {
1521
+ q = `INSERT INTO ??.?? VALUES (?, ?, ?)
1522
+ ON DUPLICATE KEY UPDATE
1523
+ points = IF(expire <= ?, ?, points + (?)),
1524
+ expire = IF(expire <= ?, ?, expire);`;
1525
+ values = [
1526
+ this.dbName,
1527
+ this.tableName,
1528
+ key,
1529
+ points,
1530
+ newExpire,
1531
+ dateNow,
1532
+ points,
1533
+ points,
1534
+ dateNow,
1535
+ newExpire
1536
+ ];
1537
+ }
1538
+ conn.query(q, values, (errUpsert) => {
1539
+ if (errUpsert) {
1540
+ conn.rollback();
1541
+ return reject(errUpsert);
1542
+ }
1543
+ conn.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;", [this.dbName, this.tableName, key], (errSelect, res) => {
1544
+ if (errSelect) {
1545
+ conn.rollback();
1546
+ return reject(errSelect);
1547
+ }
1548
+ conn.query("COMMIT", (err) => {
1549
+ if (err) {
1550
+ conn.rollback();
1551
+ return reject(err);
1552
+ }
1553
+ resolve(res);
1554
+ });
1555
+ });
1556
+ });
1557
+ });
1558
+ });
1559
+ }
1560
+ _upsert(key, points, msDuration, forceExpire = false) {
1561
+ if (!this.tableCreated) {
1562
+ return Promise.reject(Error("Table is not created yet"));
1563
+ }
1564
+ return new Promise((resolve, reject) => {
1565
+ this._getConnection().then((conn) => {
1566
+ this._upsertTransaction(conn, key, points, msDuration, forceExpire).then((res) => {
1567
+ resolve(res);
1568
+ this._releaseConnection(conn);
1569
+ }).catch((err) => {
1570
+ reject(err);
1571
+ this._releaseConnection(conn);
1572
+ });
1573
+ }).catch((err) => {
1574
+ reject(err);
1575
+ });
1576
+ });
1577
+ }
1578
+ _get(rlKey) {
1579
+ if (!this.tableCreated) {
1580
+ return Promise.reject(Error("Table is not created yet"));
1581
+ }
1582
+ return new Promise((resolve, reject) => {
1583
+ this._getConnection().then((conn) => {
1584
+ conn.query(
1585
+ "SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",
1586
+ [this.dbName, this.tableName, rlKey, Date.now()],
1587
+ (err, res) => {
1588
+ if (err) {
1589
+ reject(err);
1590
+ } else if (res.length === 0) {
1591
+ resolve(null);
1592
+ } else {
1593
+ resolve(res);
1594
+ }
1595
+ this._releaseConnection(conn);
1596
+ }
1597
+ // eslint-disable-line
1598
+ );
1599
+ }).catch((err) => {
1600
+ reject(err);
1601
+ });
1602
+ });
1603
+ }
1604
+ _delete(rlKey) {
1605
+ if (!this.tableCreated) {
1606
+ return Promise.reject(Error("Table is not created yet"));
1607
+ }
1608
+ return new Promise((resolve, reject) => {
1609
+ this._getConnection().then((conn) => {
1610
+ conn.query(
1611
+ "DELETE FROM ??.?? WHERE `key` = ?",
1612
+ [this.dbName, this.tableName, rlKey],
1613
+ (err, res) => {
1614
+ if (err) {
1615
+ reject(err);
1616
+ } else {
1617
+ resolve(res.affectedRows > 0);
1618
+ }
1619
+ this._releaseConnection(conn);
1620
+ }
1621
+ // eslint-disable-line
1622
+ );
1623
+ }).catch((err) => {
1624
+ reject(err);
1625
+ });
1626
+ });
1627
+ }
1628
+ };
1629
+ module.exports = RateLimiterMySQL;
1630
+ }
1631
+ });
1632
+
1633
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterPostgres.js
1634
+ var require_RateLimiterPostgres = __commonJS({
1635
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterPostgres.js"(exports, module) {
1636
+ "use strict";
1637
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
1638
+ var RateLimiterRes2 = require_RateLimiterRes();
1639
+ var RateLimiterPostgres2 = class extends RateLimiterStoreAbstract {
1640
+ /**
1641
+ * @callback callback
1642
+ * @param {Object} err
1643
+ *
1644
+ * @param {Object} opts
1645
+ * @param {callback} cb
1646
+ * Defaults {
1647
+ * ... see other in RateLimiterStoreAbstract
1648
+ *
1649
+ * storeClient: postgresClient,
1650
+ * storeType: 'knex', // required only for Knex instance
1651
+ * tableName: 'string',
1652
+ * schemaName: 'string', // optional
1653
+ * }
1654
+ */
1655
+ constructor(opts, cb = null) {
1656
+ super(opts);
1657
+ this.client = opts.storeClient;
1658
+ this.clientType = opts.storeType;
1659
+ this.tableName = opts.tableName;
1660
+ this.schemaName = opts.schemaName;
1661
+ this.clearExpiredByTimeout = opts.clearExpiredByTimeout;
1662
+ this.tableCreated = opts.tableCreated;
1663
+ if (!this.tableCreated) {
1664
+ this._createTable().then(() => {
1665
+ this.tableCreated = true;
1666
+ if (this.clearExpiredByTimeout) {
1667
+ this._clearExpiredHourAgo();
1668
+ }
1669
+ if (typeof cb === "function") {
1670
+ cb();
1671
+ }
1672
+ }).catch((err) => {
1673
+ if (typeof cb === "function") {
1674
+ cb(err);
1675
+ } else {
1676
+ throw err;
1677
+ }
1678
+ });
1679
+ } else {
1680
+ if (this.clearExpiredByTimeout) {
1681
+ this._clearExpiredHourAgo();
1682
+ }
1683
+ if (typeof cb === "function") {
1684
+ cb();
1685
+ }
1686
+ }
1687
+ }
1688
+ _getTableIdentifier() {
1689
+ return this.schemaName ? `"${this.schemaName}"."${this.tableName}"` : `"${this.tableName}"`;
1690
+ }
1691
+ clearExpired(expire) {
1692
+ return new Promise((resolve) => {
1693
+ const q = {
1694
+ name: "rlflx-clear-expired",
1695
+ text: `DELETE FROM ${this._getTableIdentifier()} WHERE expire < $1`,
1696
+ values: [expire]
1697
+ };
1698
+ this._query(q).then(() => {
1699
+ resolve();
1700
+ }).catch(() => {
1701
+ resolve();
1702
+ });
1703
+ });
1704
+ }
1705
+ /**
1706
+ * Delete all rows expired 1 hour ago once per 5 minutes
1707
+ *
1708
+ * @private
1709
+ */
1710
+ _clearExpiredHourAgo() {
1711
+ if (this._clearExpiredTimeoutId) {
1712
+ clearTimeout(this._clearExpiredTimeoutId);
1713
+ }
1714
+ this._clearExpiredTimeoutId = setTimeout(() => {
1715
+ this.clearExpired(Date.now() - 36e5).then(() => {
1716
+ this._clearExpiredHourAgo();
1717
+ });
1718
+ }, 3e5);
1719
+ this._clearExpiredTimeoutId.unref();
1720
+ }
1721
+ /**
1722
+ *
1723
+ * @return Promise<any>
1724
+ * @private
1725
+ */
1726
+ _getConnection() {
1727
+ switch (this.clientType) {
1728
+ case "pool":
1729
+ return Promise.resolve(this.client);
1730
+ case "sequelize":
1731
+ return this._getSequelizeConnectionManager().getConnection();
1732
+ case "knex":
1733
+ return this.client.client.acquireConnection();
1734
+ case "typeorm":
1735
+ return Promise.resolve(this.client.driver.master);
1736
+ default:
1737
+ return Promise.resolve(this.client);
1738
+ }
1739
+ }
1740
+ _releaseConnection(conn) {
1741
+ switch (this.clientType) {
1742
+ case "pool":
1743
+ return true;
1744
+ case "sequelize":
1745
+ return this._getSequelizeConnectionManager().releaseConnection(conn);
1746
+ case "knex":
1747
+ return this.client.client.releaseConnection(conn);
1748
+ case "typeorm":
1749
+ return true;
1750
+ default:
1751
+ return true;
1752
+ }
1753
+ }
1754
+ _getSequelizeConnectionManager() {
1755
+ let connectionManager;
1756
+ let accessError;
1757
+ try {
1758
+ connectionManager = this.client.connectionManager;
1759
+ } catch (err) {
1760
+ accessError = err;
1761
+ }
1762
+ if (connectionManager) {
1763
+ return connectionManager;
1764
+ }
1765
+ if (this.client.dialect && this.client.dialect.connectionManager) {
1766
+ return this.client.dialect.connectionManager;
1767
+ }
1768
+ if (accessError) {
1769
+ throw accessError;
1770
+ }
1771
+ throw new Error("Sequelize connection manager is not available");
1772
+ }
1773
+ /**
1774
+ *
1775
+ * @returns {Promise<any>}
1776
+ * @private
1777
+ */
1778
+ _createTable() {
1779
+ return new Promise((resolve, reject) => {
1780
+ this._query({
1781
+ text: this._getCreateTableStmt()
1782
+ }).then(() => {
1783
+ resolve();
1784
+ }).catch((err) => {
1785
+ if (err.code === "23505") {
1786
+ resolve();
1787
+ } else {
1788
+ reject(err);
1789
+ }
1790
+ });
1791
+ });
1792
+ }
1793
+ _getCreateTableStmt() {
1794
+ return `CREATE TABLE IF NOT EXISTS ${this._getTableIdentifier()} (
1795
+ key varchar(255) PRIMARY KEY,
1796
+ points integer NOT NULL DEFAULT 0,
1797
+ expire bigint
1798
+ );`;
1799
+ }
1800
+ get clientType() {
1801
+ return this._clientType;
1802
+ }
1803
+ set clientType(value) {
1804
+ const constructorName = this.client.constructor.name;
1805
+ if (typeof value === "undefined") {
1806
+ if (constructorName === "Client") {
1807
+ value = "client";
1808
+ } else if (constructorName === "Pool" || constructorName === "BoundPool") {
1809
+ value = "pool";
1810
+ } else if (constructorName === "Sequelize") {
1811
+ value = "sequelize";
1812
+ } else {
1813
+ throw new Error("storeType is not defined");
1814
+ }
1815
+ }
1816
+ this._clientType = value.toLowerCase();
1817
+ }
1818
+ get tableName() {
1819
+ return this._tableName;
1820
+ }
1821
+ set tableName(value) {
1822
+ this._tableName = typeof value === "undefined" ? this.keyPrefix : value;
1823
+ }
1824
+ get schemaName() {
1825
+ return this._schemaName;
1826
+ }
1827
+ set schemaName(value) {
1828
+ this._schemaName = value;
1829
+ }
1830
+ get tableCreated() {
1831
+ return this._tableCreated;
1832
+ }
1833
+ set tableCreated(value) {
1834
+ this._tableCreated = typeof value === "undefined" ? false : !!value;
1835
+ }
1836
+ get clearExpiredByTimeout() {
1837
+ return this._clearExpiredByTimeout;
1838
+ }
1839
+ set clearExpiredByTimeout(value) {
1840
+ this._clearExpiredByTimeout = typeof value === "undefined" ? true : Boolean(value);
1841
+ }
1842
+ _getRateLimiterRes(rlKey, changedPoints, result) {
1843
+ const res = new RateLimiterRes2();
1844
+ const row = result.rows[0];
1845
+ res.isFirstInDuration = changedPoints === row.points;
1846
+ res.consumedPoints = res.isFirstInDuration ? changedPoints : row.points;
1847
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
1848
+ res.msBeforeNext = row.expire ? Math.max(row.expire - Date.now(), 0) : -1;
1849
+ return res;
1850
+ }
1851
+ _query(q) {
1852
+ const prefix = this.tableName.toLowerCase();
1853
+ const queryObj = { text: q.text, values: q.values };
1854
+ if (q.name) {
1855
+ queryObj.name = `${prefix}:${q.name}`;
1856
+ }
1857
+ return new Promise((resolve, reject) => {
1858
+ this._getConnection().then((conn) => {
1859
+ conn.query(queryObj).then((res) => {
1860
+ resolve(res);
1861
+ this._releaseConnection(conn);
1862
+ }).catch((err) => {
1863
+ reject(err);
1864
+ this._releaseConnection(conn);
1865
+ });
1866
+ }).catch((err) => {
1867
+ reject(err);
1868
+ });
1869
+ });
1870
+ }
1871
+ _upsert(key, points, msDuration, forceExpire = false) {
1872
+ if (!this.tableCreated) {
1873
+ return Promise.reject(Error("Table is not created yet"));
1874
+ }
1875
+ const newExpire = msDuration > 0 ? Date.now() + msDuration : null;
1876
+ const expireQ = forceExpire ? " $3 " : ` CASE
1877
+ WHEN ${this._getTableIdentifier()}.expire <= $4 THEN $3
1878
+ ELSE ${this._getTableIdentifier()}.expire
1879
+ END `;
1880
+ return this._query({
1881
+ name: forceExpire ? "rlflx-upsert-force" : "rlflx-upsert",
1882
+ text: `
1883
+ INSERT INTO ${this._getTableIdentifier()} VALUES ($1, $2, $3)
1884
+ ON CONFLICT(key) DO UPDATE SET
1885
+ points = CASE
1886
+ WHEN (${this._getTableIdentifier()}.expire <= $4 OR 1=${forceExpire ? 1 : 0}) THEN $2
1887
+ ELSE ${this._getTableIdentifier()}.points + ($2)
1888
+ END,
1889
+ expire = ${expireQ}
1890
+ RETURNING points, expire;`,
1891
+ values: [key, points, newExpire, Date.now()]
1892
+ });
1893
+ }
1894
+ _get(rlKey) {
1895
+ if (!this.tableCreated) {
1896
+ return Promise.reject(Error("Table is not created yet"));
1897
+ }
1898
+ return new Promise((resolve, reject) => {
1899
+ this._query({
1900
+ name: "rlflx-get",
1901
+ text: `
1902
+ SELECT points, expire FROM ${this._getTableIdentifier()} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,
1903
+ values: [rlKey, Date.now()]
1904
+ }).then((res) => {
1905
+ if (res.rowCount === 0) {
1906
+ res = null;
1907
+ }
1908
+ resolve(res);
1909
+ }).catch((err) => {
1910
+ reject(err);
1911
+ });
1912
+ });
1913
+ }
1914
+ _delete(rlKey) {
1915
+ if (!this.tableCreated) {
1916
+ return Promise.reject(Error("Table is not created yet"));
1917
+ }
1918
+ return this._query({
1919
+ name: "rlflx-delete",
1920
+ text: `DELETE FROM ${this._getTableIdentifier()} WHERE key = $1`,
1921
+ values: [rlKey]
1922
+ }).then((res) => res.rowCount > 0);
1923
+ }
1924
+ };
1925
+ module.exports = RateLimiterPostgres2;
1926
+ }
1927
+ });
1928
+
1929
+ // (disabled):cluster
1930
+ var require_cluster = __commonJS({
1931
+ "(disabled):cluster"() {
1932
+ "use strict";
1933
+ }
1934
+ });
1935
+
1936
+ // (disabled):crypto
1937
+ var require_crypto = __commonJS({
1938
+ "(disabled):crypto"() {
1939
+ "use strict";
1940
+ }
1941
+ });
1942
+
1943
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/MemoryStorage/Record.js
1944
+ var require_Record = __commonJS({
1945
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/MemoryStorage/Record.js"(exports, module) {
1946
+ "use strict";
1947
+ module.exports = class Record {
1948
+ /**
1949
+ *
1950
+ * @param value int
1951
+ * @param expiresAt Number|Date
1952
+ * @param timeoutId
1953
+ */
1954
+ constructor(value, expiresAt, timeoutId = null) {
1955
+ this.value = value;
1956
+ this.expiresAt = expiresAt;
1957
+ this.timeoutId = timeoutId;
1958
+ }
1959
+ get value() {
1960
+ return this._value;
1961
+ }
1962
+ set value(value) {
1963
+ this._value = parseInt(value, 10);
1964
+ }
1965
+ get expiresAt() {
1966
+ return this._expiresAt;
1967
+ }
1968
+ set expiresAt(value) {
1969
+ if (value instanceof Date) {
1970
+ this._expiresAt = value.getTime();
1971
+ } else {
1972
+ this._expiresAt = value;
1973
+ }
1974
+ }
1975
+ get timeoutId() {
1976
+ return this._timeoutId;
1977
+ }
1978
+ set timeoutId(value) {
1979
+ this._timeoutId = value;
1980
+ }
1981
+ };
1982
+ }
1983
+ });
1984
+
1985
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/MemoryStorage/MemoryStorage.js
1986
+ var require_MemoryStorage = __commonJS({
1987
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/MemoryStorage/MemoryStorage.js"(exports, module) {
1988
+ "use strict";
1989
+ var Record = require_Record();
1990
+ var RateLimiterRes2 = require_RateLimiterRes();
1991
+ module.exports = class MemoryStorage {
1992
+ constructor() {
1993
+ this._storage = /* @__PURE__ */ new Map();
1994
+ }
1995
+ incrby(key, value, durationSec) {
1996
+ const record = this._storage.get(key);
1997
+ if (record) {
1998
+ const msBeforeExpires = record.expiresAt ? record.expiresAt - Date.now() : -1;
1999
+ if (!record.expiresAt || msBeforeExpires > 0) {
2000
+ record.value = record.value + value;
2001
+ return new RateLimiterRes2(0, msBeforeExpires, record.value, false);
2002
+ }
2003
+ return this.set(key, value, durationSec);
2004
+ }
2005
+ return this.set(key, value, durationSec);
2006
+ }
2007
+ set(key, value, durationSec) {
2008
+ const durationMs = durationSec * 1e3;
2009
+ const existingRecord = this._storage.get(key);
2010
+ if (existingRecord && existingRecord.timeoutId) {
2011
+ clearTimeout(existingRecord.timeoutId);
2012
+ }
2013
+ const record = new Record(
2014
+ value,
2015
+ durationMs > 0 ? Date.now() + durationMs : null
2016
+ );
2017
+ this._storage.set(key, record);
2018
+ if (durationMs > 0) {
2019
+ record.timeoutId = setTimeout(() => {
2020
+ this._storage.delete(key);
2021
+ }, durationMs);
2022
+ if (record.timeoutId.unref) {
2023
+ record.timeoutId.unref();
2024
+ }
2025
+ }
2026
+ return new RateLimiterRes2(0, durationMs === 0 ? -1 : durationMs, record.value, true);
2027
+ }
2028
+ /**
2029
+ *
2030
+ * @param key
2031
+ * @returns {*}
2032
+ */
2033
+ get(key) {
2034
+ const record = this._storage.get(key);
2035
+ if (record) {
2036
+ const msBeforeExpires = record.expiresAt ? record.expiresAt - Date.now() : -1;
2037
+ return new RateLimiterRes2(0, msBeforeExpires, record.value, false);
2038
+ }
2039
+ return null;
2040
+ }
2041
+ /**
2042
+ *
2043
+ * @param key
2044
+ * @returns {boolean}
2045
+ */
2046
+ delete(key) {
2047
+ const record = this._storage.get(key);
2048
+ if (record) {
2049
+ if (record.timeoutId) {
2050
+ clearTimeout(record.timeoutId);
2051
+ }
2052
+ this._storage.delete(key);
2053
+ return true;
2054
+ }
2055
+ return false;
2056
+ }
2057
+ /**
2058
+ * @internal
2059
+ * @param key
2060
+ * @param value
2061
+ * @param expiresAt
2062
+ */
2063
+ _restoreRecord(key, value, expiresAt) {
2064
+ const now = Date.now();
2065
+ const hasExpiresAt = expiresAt !== null;
2066
+ if (hasExpiresAt && !Number.isFinite(expiresAt)) {
2067
+ return;
2068
+ }
2069
+ if (hasExpiresAt && expiresAt <= now) {
2070
+ return;
2071
+ }
2072
+ const durationMs = hasExpiresAt ? expiresAt - now : 0;
2073
+ const existingRecord = this._storage.get(key);
2074
+ if (existingRecord && existingRecord.timeoutId) {
2075
+ clearTimeout(existingRecord.timeoutId);
2076
+ }
2077
+ const record = new Record(
2078
+ value,
2079
+ expiresAt
2080
+ );
2081
+ this._storage.set(key, record);
2082
+ if (durationMs > 0) {
2083
+ record.timeoutId = setTimeout(() => {
2084
+ this._storage.delete(key);
2085
+ }, durationMs);
2086
+ if (record.timeoutId.unref) {
2087
+ record.timeoutId.unref();
2088
+ }
2089
+ }
2090
+ }
2091
+ };
2092
+ }
2093
+ });
2094
+
2095
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterMemory.js
2096
+ var require_RateLimiterMemory = __commonJS({
2097
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterMemory.js"(exports, module) {
2098
+ "use strict";
2099
+ var RateLimiterAbstract = require_RateLimiterAbstract();
2100
+ var MemoryStorage = require_MemoryStorage();
2101
+ var RateLimiterRes2 = require_RateLimiterRes();
2102
+ var RateLimiterMemory2 = class extends RateLimiterAbstract {
2103
+ constructor(opts = {}) {
2104
+ super(opts);
2105
+ this._memoryStorage = new MemoryStorage();
2106
+ }
2107
+ /**
2108
+ *
2109
+ * @param key
2110
+ * @param pointsToConsume
2111
+ * @param {Object} options
2112
+ * @returns {Promise<RateLimiterRes>}
2113
+ */
2114
+ consume(key, pointsToConsume = 1, options = {}) {
2115
+ return new Promise((resolve, reject) => {
2116
+ const rlKey = this.getKey(key);
2117
+ const secDuration = this._getKeySecDuration(options);
2118
+ let res = this._memoryStorage.incrby(rlKey, pointsToConsume, secDuration);
2119
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
2120
+ if (res.consumedPoints > this.points) {
2121
+ if (this.blockDuration > 0 && res.consumedPoints <= this.points + pointsToConsume) {
2122
+ res = this._memoryStorage.set(rlKey, res.consumedPoints, this.blockDuration);
2123
+ }
2124
+ reject(res);
2125
+ } else if (this.execEvenly && this.points > 0 && res.msBeforeNext > 0 && !res.isFirstInDuration) {
2126
+ let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));
2127
+ if (delay < this.execEvenlyMinDelayMs) {
2128
+ delay = res.consumedPoints * this.execEvenlyMinDelayMs;
2129
+ }
2130
+ res.msBeforeNext = Math.max(res.msBeforeNext - delay, 0);
2131
+ setTimeout(resolve, delay, res);
2132
+ } else {
2133
+ resolve(res);
2134
+ }
2135
+ });
2136
+ }
2137
+ penalty(key, points = 1, options = {}) {
2138
+ const rlKey = this.getKey(key);
2139
+ return new Promise((resolve) => {
2140
+ const secDuration = this._getKeySecDuration(options);
2141
+ const res = this._memoryStorage.incrby(rlKey, points, secDuration);
2142
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
2143
+ resolve(res);
2144
+ });
2145
+ }
2146
+ reward(key, points = 1, options = {}) {
2147
+ const rlKey = this.getKey(key);
2148
+ return new Promise((resolve) => {
2149
+ const secDuration = this._getKeySecDuration(options);
2150
+ const res = this._memoryStorage.incrby(rlKey, -points, secDuration);
2151
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
2152
+ resolve(res);
2153
+ });
2154
+ }
2155
+ /**
2156
+ * Block any key for secDuration seconds
2157
+ *
2158
+ * @param key
2159
+ * @param secDuration
2160
+ */
2161
+ block(key, secDuration) {
2162
+ const msDuration = secDuration * 1e3;
2163
+ const initPoints = this.points + 1;
2164
+ this._memoryStorage.set(this.getKey(key), initPoints, secDuration);
2165
+ return Promise.resolve(
2166
+ new RateLimiterRes2(0, msDuration === 0 ? -1 : msDuration, initPoints)
2167
+ );
2168
+ }
2169
+ set(key, points, secDuration) {
2170
+ const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1e3;
2171
+ this._memoryStorage.set(this.getKey(key), points, secDuration);
2172
+ return Promise.resolve(
2173
+ new RateLimiterRes2(0, msDuration === 0 ? -1 : msDuration, points)
2174
+ );
2175
+ }
2176
+ get(key) {
2177
+ const res = this._memoryStorage.get(this.getKey(key));
2178
+ if (res !== null) {
2179
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
2180
+ }
2181
+ return Promise.resolve(res);
2182
+ }
2183
+ delete(key) {
2184
+ return Promise.resolve(this._memoryStorage.delete(this.getKey(key)));
2185
+ }
2186
+ dump() {
2187
+ const storage = [];
2188
+ for (const [key, record] of this._memoryStorage._storage) {
2189
+ storage.push({
2190
+ key: this.parseKey(key),
2191
+ value: record.value,
2192
+ expiresAt: record.expiresAt
2193
+ });
2194
+ }
2195
+ return {
2196
+ version: 1,
2197
+ dumpedAt: Date.now(),
2198
+ storage
2199
+ };
2200
+ }
2201
+ /**
2202
+ * Restores rate-limiter state from a previously dumped snapshot.
2203
+ *
2204
+ * Each entry is classified into one of three buckets:
2205
+ * - **invalid** – the item is not an object or has a malformed schema (bad key, value or expiry type).
2206
+ * - **expired** – the item has logically expired based on current timestamp.
2207
+ * - **restored** – the item was valid and successfully loaded into storage.
2208
+ *
2209
+ * @param {Object} data - Snapshot produced by {@link dump}.
2210
+ * @param {boolean} [detailResponse=false] - When `true`, each bucket also
2211
+ * carries a `keys` array listing every affected key.
2212
+ * @returns {{ invalid, expired, restored } | undefined} Summary counts (and
2213
+ * optionally keys). Returns `undefined` when `data` fails schema checks.
2214
+ */
2215
+ restore(data, detailResponse = false) {
2216
+ if (!data || typeof data !== "object" || data.version !== 1) {
2217
+ return void 0;
2218
+ }
2219
+ const response = detailResponse ? {
2220
+ invalid: { count: 0, keys: [] },
2221
+ expired: { count: 0, keys: [] },
2222
+ restored: { count: 0, keys: [] }
2223
+ } : { invalid: 0, expired: 0, restored: 0 };
2224
+ const record = (bucket, key) => {
2225
+ if (detailResponse) {
2226
+ response[bucket].count += 1;
2227
+ response[bucket].keys.push(key);
2228
+ } else {
2229
+ response[bucket] += 1;
2230
+ }
2231
+ };
2232
+ if (!Array.isArray(data.storage)) {
2233
+ return response;
2234
+ }
2235
+ for (const item of data.storage) {
2236
+ if (!item || typeof item !== "object") {
2237
+ record("invalid", "N/A");
2238
+ continue;
2239
+ }
2240
+ const isValidKey = typeof item.key === "string" || typeof item.key === "number";
2241
+ const isValidValue = Number.isFinite(item.value);
2242
+ const isValidExpiry = item.expiresAt === null || Number.isFinite(item.expiresAt);
2243
+ if (!isValidKey || !isValidValue || !isValidExpiry) {
2244
+ record("invalid", item.key);
2245
+ continue;
2246
+ }
2247
+ if (item.expiresAt !== null && item.expiresAt <= Date.now()) {
2248
+ record("expired", item.key);
2249
+ continue;
2250
+ }
2251
+ this._memoryStorage._restoreRecord(this.getKey(item.key), item.value, item.expiresAt);
2252
+ record("restored", item.key);
2253
+ }
2254
+ return response;
2255
+ }
2256
+ };
2257
+ module.exports = RateLimiterMemory2;
2258
+ }
2259
+ });
2260
+
2261
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterCluster.js
2262
+ var require_RateLimiterCluster = __commonJS({
2263
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterCluster.js"(exports, module) {
2264
+ "use strict";
2265
+ var cluster = require_cluster();
2266
+ var crypto = require_crypto();
2267
+ var RateLimiterAbstract = require_RateLimiterAbstract();
2268
+ var RateLimiterMemory2 = require_RateLimiterMemory();
2269
+ var RateLimiterRes2 = require_RateLimiterRes();
2270
+ var channel = "rate_limiter_flexible";
2271
+ var masterInstance = null;
2272
+ var masterSendToWorker = function(worker, msg, type, res) {
2273
+ let data;
2274
+ if (res === null || res === true || res === false) {
2275
+ data = res;
2276
+ } else {
2277
+ data = {
2278
+ remainingPoints: res.remainingPoints,
2279
+ msBeforeNext: res.msBeforeNext,
2280
+ consumedPoints: res.consumedPoints,
2281
+ isFirstInDuration: res.isFirstInDuration
2282
+ };
2283
+ }
2284
+ worker.send({
2285
+ channel,
2286
+ keyPrefix: msg.keyPrefix,
2287
+ // which rate limiter exactly
2288
+ promiseId: msg.promiseId,
2289
+ type,
2290
+ data
2291
+ });
2292
+ };
2293
+ var workerWaitInit = function(payload) {
2294
+ setTimeout(() => {
2295
+ if (this._initiated) {
2296
+ process.send(payload);
2297
+ } else if (typeof this._promises[payload.promiseId] !== "undefined") {
2298
+ workerWaitInit.call(this, payload);
2299
+ }
2300
+ }, 30);
2301
+ };
2302
+ var workerSendToMaster = function(func, promiseId, key, arg, opts) {
2303
+ const payload = {
2304
+ channel,
2305
+ keyPrefix: this.keyPrefix,
2306
+ func,
2307
+ promiseId,
2308
+ data: {
2309
+ key,
2310
+ arg,
2311
+ opts
2312
+ }
2313
+ };
2314
+ if (!this._initiated) {
2315
+ workerWaitInit.call(this, payload);
2316
+ } else {
2317
+ process.send(payload);
2318
+ }
2319
+ };
2320
+ var masterProcessMsg = function(worker, msg) {
2321
+ if (!msg || msg.channel !== channel || typeof this._rateLimiters[msg.keyPrefix] === "undefined") {
2322
+ return false;
2323
+ }
2324
+ let promise;
2325
+ switch (msg.func) {
2326
+ case "consume":
2327
+ promise = this._rateLimiters[msg.keyPrefix].consume(msg.data.key, msg.data.arg, msg.data.opts);
2328
+ break;
2329
+ case "penalty":
2330
+ promise = this._rateLimiters[msg.keyPrefix].penalty(msg.data.key, msg.data.arg, msg.data.opts);
2331
+ break;
2332
+ case "reward":
2333
+ promise = this._rateLimiters[msg.keyPrefix].reward(msg.data.key, msg.data.arg, msg.data.opts);
2334
+ break;
2335
+ case "block":
2336
+ promise = this._rateLimiters[msg.keyPrefix].block(msg.data.key, msg.data.arg, msg.data.opts);
2337
+ break;
2338
+ case "get":
2339
+ promise = this._rateLimiters[msg.keyPrefix].get(msg.data.key, msg.data.opts);
2340
+ break;
2341
+ case "delete":
2342
+ promise = this._rateLimiters[msg.keyPrefix].delete(msg.data.key, msg.data.opts);
2343
+ break;
2344
+ default:
2345
+ return false;
2346
+ }
2347
+ if (promise) {
2348
+ promise.then((res) => {
2349
+ masterSendToWorker(worker, msg, "resolve", res);
2350
+ }).catch((rejRes) => {
2351
+ masterSendToWorker(worker, msg, "reject", rejRes);
2352
+ });
2353
+ }
2354
+ };
2355
+ var workerProcessMsg = function(msg) {
2356
+ if (!msg || msg.channel !== channel || msg.keyPrefix !== this.keyPrefix) {
2357
+ return false;
2358
+ }
2359
+ if (this._promises[msg.promiseId]) {
2360
+ clearTimeout(this._promises[msg.promiseId].timeoutId);
2361
+ let res;
2362
+ if (msg.data === null || msg.data === true || msg.data === false) {
2363
+ res = msg.data;
2364
+ } else {
2365
+ res = new RateLimiterRes2(
2366
+ msg.data.remainingPoints,
2367
+ msg.data.msBeforeNext,
2368
+ msg.data.consumedPoints,
2369
+ msg.data.isFirstInDuration
2370
+ // eslint-disable-line comma-dangle
2371
+ );
2372
+ }
2373
+ switch (msg.type) {
2374
+ case "resolve":
2375
+ this._promises[msg.promiseId].resolve(res);
2376
+ break;
2377
+ case "reject":
2378
+ this._promises[msg.promiseId].reject(res);
2379
+ break;
2380
+ default:
2381
+ throw new Error(`RateLimiterCluster: no such message type '${msg.type}'`);
2382
+ }
2383
+ delete this._promises[msg.promiseId];
2384
+ }
2385
+ };
2386
+ var getOpts = function() {
2387
+ return {
2388
+ points: this.points,
2389
+ duration: this.duration,
2390
+ blockDuration: this.blockDuration,
2391
+ execEvenly: this.execEvenly,
2392
+ execEvenlyMinDelayMs: this.execEvenlyMinDelayMs,
2393
+ keyPrefix: this.keyPrefix
2394
+ };
2395
+ };
2396
+ var savePromise = function(resolve, reject) {
2397
+ const hrtime = process.hrtime();
2398
+ let promiseId = hrtime[0].toString() + hrtime[1].toString();
2399
+ if (typeof this._promises[promiseId] !== "undefined") {
2400
+ promiseId += crypto.randomBytes(12).toString("base64");
2401
+ }
2402
+ this._promises[promiseId] = {
2403
+ resolve,
2404
+ reject,
2405
+ timeoutId: setTimeout(() => {
2406
+ delete this._promises[promiseId];
2407
+ reject(new Error("RateLimiterCluster timeout: no answer from master in time"));
2408
+ }, this.timeoutMs)
2409
+ };
2410
+ return promiseId;
2411
+ };
2412
+ var RateLimiterClusterMaster = class {
2413
+ constructor() {
2414
+ if (masterInstance) {
2415
+ return masterInstance;
2416
+ }
2417
+ this._rateLimiters = {};
2418
+ cluster.setMaxListeners(0);
2419
+ cluster.on("message", (worker, msg) => {
2420
+ if (msg && msg.channel === channel && msg.type === "init") {
2421
+ if (typeof this._rateLimiters[msg.opts.keyPrefix] === "undefined") {
2422
+ this._rateLimiters[msg.opts.keyPrefix] = new RateLimiterMemory2(msg.opts);
2423
+ }
2424
+ worker.send({
2425
+ channel,
2426
+ type: "init",
2427
+ keyPrefix: msg.opts.keyPrefix
2428
+ });
2429
+ } else {
2430
+ masterProcessMsg.call(this, worker, msg);
2431
+ }
2432
+ });
2433
+ masterInstance = this;
2434
+ }
2435
+ };
2436
+ var RateLimiterClusterMasterPM2 = class {
2437
+ constructor(pm2) {
2438
+ if (masterInstance) {
2439
+ return masterInstance;
2440
+ }
2441
+ this._rateLimiters = {};
2442
+ pm2.launchBus((err, pm2Bus) => {
2443
+ pm2Bus.on("process:msg", (packet) => {
2444
+ const msg = packet.raw;
2445
+ if (msg && msg.channel === channel && msg.type === "init") {
2446
+ if (typeof this._rateLimiters[msg.opts.keyPrefix] === "undefined") {
2447
+ this._rateLimiters[msg.opts.keyPrefix] = new RateLimiterMemory2(msg.opts);
2448
+ }
2449
+ pm2.sendDataToProcessId(packet.process.pm_id, {
2450
+ data: {},
2451
+ topic: channel,
2452
+ channel,
2453
+ type: "init",
2454
+ keyPrefix: msg.opts.keyPrefix
2455
+ }, (sendErr, res) => {
2456
+ if (sendErr) {
2457
+ console.log(sendErr, res);
2458
+ }
2459
+ });
2460
+ } else {
2461
+ const worker = {
2462
+ send: (msgData) => {
2463
+ const pm2Message = msgData;
2464
+ pm2Message.topic = channel;
2465
+ if (typeof pm2Message.data === "undefined") {
2466
+ pm2Message.data = {};
2467
+ }
2468
+ pm2.sendDataToProcessId(packet.process.pm_id, pm2Message, (sendErr, res) => {
2469
+ if (sendErr) {
2470
+ console.log(sendErr, res);
2471
+ }
2472
+ });
2473
+ }
2474
+ };
2475
+ masterProcessMsg.call(this, worker, msg);
2476
+ }
2477
+ });
2478
+ });
2479
+ masterInstance = this;
2480
+ }
2481
+ };
2482
+ var RateLimiterClusterWorker = class extends RateLimiterAbstract {
2483
+ get timeoutMs() {
2484
+ return this._timeoutMs;
2485
+ }
2486
+ set timeoutMs(value) {
2487
+ this._timeoutMs = typeof value === "undefined" ? 5e3 : Math.abs(parseInt(value));
2488
+ }
2489
+ constructor(opts = {}) {
2490
+ super(opts);
2491
+ process.setMaxListeners(0);
2492
+ this.timeoutMs = opts.timeoutMs;
2493
+ this._initiated = false;
2494
+ process.on("message", (msg) => {
2495
+ if (msg && msg.channel === channel && msg.type === "init" && msg.keyPrefix === this.keyPrefix) {
2496
+ this._initiated = true;
2497
+ } else {
2498
+ workerProcessMsg.call(this, msg);
2499
+ }
2500
+ });
2501
+ process.send({
2502
+ channel,
2503
+ type: "init",
2504
+ opts: getOpts.call(this)
2505
+ });
2506
+ this._promises = {};
2507
+ }
2508
+ consume(key, pointsToConsume = 1, options = {}) {
2509
+ return new Promise((resolve, reject) => {
2510
+ const promiseId = savePromise.call(this, resolve, reject);
2511
+ workerSendToMaster.call(this, "consume", promiseId, key, pointsToConsume, options);
2512
+ });
2513
+ }
2514
+ penalty(key, points = 1, options = {}) {
2515
+ return new Promise((resolve, reject) => {
2516
+ const promiseId = savePromise.call(this, resolve, reject);
2517
+ workerSendToMaster.call(this, "penalty", promiseId, key, points, options);
2518
+ });
2519
+ }
2520
+ reward(key, points = 1, options = {}) {
2521
+ return new Promise((resolve, reject) => {
2522
+ const promiseId = savePromise.call(this, resolve, reject);
2523
+ workerSendToMaster.call(this, "reward", promiseId, key, points, options);
2524
+ });
2525
+ }
2526
+ block(key, secDuration, options = {}) {
2527
+ return new Promise((resolve, reject) => {
2528
+ const promiseId = savePromise.call(this, resolve, reject);
2529
+ workerSendToMaster.call(this, "block", promiseId, key, secDuration, options);
2530
+ });
2531
+ }
2532
+ get(key, options = {}) {
2533
+ return new Promise((resolve, reject) => {
2534
+ const promiseId = savePromise.call(this, resolve, reject);
2535
+ workerSendToMaster.call(this, "get", promiseId, key, options);
2536
+ });
2537
+ }
2538
+ delete(key, options = {}) {
2539
+ return new Promise((resolve, reject) => {
2540
+ const promiseId = savePromise.call(this, resolve, reject);
2541
+ workerSendToMaster.call(this, "delete", promiseId, key, options);
2542
+ });
2543
+ }
2544
+ };
2545
+ module.exports = {
2546
+ RateLimiterClusterMaster,
2547
+ RateLimiterClusterMasterPM2,
2548
+ RateLimiterCluster: RateLimiterClusterWorker
2549
+ };
2550
+ }
2551
+ });
2552
+
2553
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterMemcache.js
2554
+ var require_RateLimiterMemcache = __commonJS({
2555
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterMemcache.js"(exports, module) {
2556
+ "use strict";
2557
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
2558
+ var RateLimiterRes2 = require_RateLimiterRes();
2559
+ var RateLimiterMemcache = class extends RateLimiterStoreAbstract {
2560
+ /**
2561
+ *
2562
+ * @param {Object} opts
2563
+ * Defaults {
2564
+ * ... see other in RateLimiterStoreAbstract
2565
+ *
2566
+ * storeClient: memcacheClient
2567
+ * }
2568
+ */
2569
+ constructor(opts) {
2570
+ super(opts);
2571
+ this.client = opts.storeClient;
2572
+ }
2573
+ _getRateLimiterRes(rlKey, changedPoints, result) {
2574
+ const res = new RateLimiterRes2();
2575
+ res.consumedPoints = parseInt(result.consumedPoints);
2576
+ res.isFirstInDuration = result.consumedPoints === changedPoints;
2577
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
2578
+ res.msBeforeNext = result.msBeforeNext;
2579
+ return res;
2580
+ }
2581
+ _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {
2582
+ return new Promise((resolve, reject) => {
2583
+ const nowMs = Date.now();
2584
+ const secDuration = Math.floor(msDuration / 1e3);
2585
+ if (forceExpire) {
2586
+ this.client.set(rlKey, points, secDuration, (err) => {
2587
+ if (!err) {
2588
+ this.client.set(
2589
+ `${rlKey}_expire`,
2590
+ secDuration > 0 ? nowMs + secDuration * 1e3 : -1,
2591
+ secDuration,
2592
+ () => {
2593
+ const res = {
2594
+ consumedPoints: points,
2595
+ msBeforeNext: secDuration > 0 ? secDuration * 1e3 : -1
2596
+ };
2597
+ resolve(res);
2598
+ }
2599
+ );
2600
+ } else {
2601
+ reject(err);
2602
+ }
2603
+ });
2604
+ } else {
2605
+ this.client.incr(rlKey, points, (err, consumedPoints) => {
2606
+ if (err || consumedPoints === false) {
2607
+ this.client.add(rlKey, points, secDuration, (errAddKey, createdNew) => {
2608
+ if (errAddKey || !createdNew) {
2609
+ if (typeof options.attemptNumber === "undefined" || options.attemptNumber < 3) {
2610
+ const nextOptions = Object.assign({}, options);
2611
+ nextOptions.attemptNumber = nextOptions.attemptNumber ? nextOptions.attemptNumber + 1 : 1;
2612
+ this._upsert(rlKey, points, msDuration, forceExpire, nextOptions).then((resUpsert) => resolve(resUpsert)).catch((errUpsert) => reject(errUpsert));
2613
+ } else {
2614
+ reject(new Error("Can not add key"));
2615
+ }
2616
+ } else {
2617
+ this.client.add(
2618
+ `${rlKey}_expire`,
2619
+ secDuration > 0 ? nowMs + secDuration * 1e3 : -1,
2620
+ secDuration,
2621
+ () => {
2622
+ const res = {
2623
+ consumedPoints: points,
2624
+ msBeforeNext: secDuration > 0 ? secDuration * 1e3 : -1
2625
+ };
2626
+ resolve(res);
2627
+ }
2628
+ );
2629
+ }
2630
+ });
2631
+ } else {
2632
+ this.client.get(`${rlKey}_expire`, (errGetExpire, resGetExpireMs) => {
2633
+ if (errGetExpire) {
2634
+ reject(errGetExpire);
2635
+ } else {
2636
+ const expireMs = resGetExpireMs === false ? 0 : resGetExpireMs;
2637
+ const res = {
2638
+ consumedPoints,
2639
+ msBeforeNext: expireMs >= 0 ? Math.max(expireMs - nowMs, 0) : -1
2640
+ };
2641
+ resolve(res);
2642
+ }
2643
+ });
2644
+ }
2645
+ });
2646
+ }
2647
+ });
2648
+ }
2649
+ _get(rlKey) {
2650
+ return new Promise((resolve, reject) => {
2651
+ const nowMs = Date.now();
2652
+ this.client.get(rlKey, (err, consumedPoints) => {
2653
+ if (!consumedPoints) {
2654
+ resolve(null);
2655
+ } else {
2656
+ this.client.get(`${rlKey}_expire`, (errGetExpire, resGetExpireMs) => {
2657
+ if (errGetExpire) {
2658
+ reject(errGetExpire);
2659
+ } else {
2660
+ const expireMs = resGetExpireMs === false ? 0 : resGetExpireMs;
2661
+ const res = {
2662
+ consumedPoints,
2663
+ msBeforeNext: expireMs >= 0 ? Math.max(expireMs - nowMs, 0) : -1
2664
+ };
2665
+ resolve(res);
2666
+ }
2667
+ });
2668
+ }
2669
+ });
2670
+ });
2671
+ }
2672
+ _delete(rlKey) {
2673
+ return new Promise((resolve, reject) => {
2674
+ this.client.del(rlKey, (err, res) => {
2675
+ if (err) {
2676
+ reject(err);
2677
+ } else if (res === false) {
2678
+ resolve(res);
2679
+ } else {
2680
+ this.client.del(`${rlKey}_expire`, (errDelExpire) => {
2681
+ if (errDelExpire) {
2682
+ reject(errDelExpire);
2683
+ } else {
2684
+ resolve(res);
2685
+ }
2686
+ });
2687
+ }
2688
+ });
2689
+ });
2690
+ }
2691
+ };
2692
+ module.exports = RateLimiterMemcache;
2693
+ }
2694
+ });
2695
+
2696
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RLWrapperBlackAndWhite.js
2697
+ var require_RLWrapperBlackAndWhite = __commonJS({
2698
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RLWrapperBlackAndWhite.js"(exports, module) {
2699
+ "use strict";
2700
+ var RateLimiterRes2 = require_RateLimiterRes();
2701
+ var RateLimiterCompatibleAbstract = require_RateLimiterCompatibleAbstract();
2702
+ module.exports = class RLWrapperBlackAndWhite extends RateLimiterCompatibleAbstract {
2703
+ constructor(opts = {}) {
2704
+ super();
2705
+ this.limiter = opts.limiter;
2706
+ this.blackList = opts.blackList;
2707
+ this.whiteList = opts.whiteList;
2708
+ this.isBlackListed = opts.isBlackListed;
2709
+ this.isWhiteListed = opts.isWhiteListed;
2710
+ this.runActionAnyway = opts.runActionAnyway;
2711
+ }
2712
+ get limiter() {
2713
+ return this._limiter;
2714
+ }
2715
+ set limiter(value) {
2716
+ if (typeof value === "undefined") {
2717
+ throw new Error("limiter is not set");
2718
+ }
2719
+ this._limiter = value;
2720
+ }
2721
+ get keyPrefix() {
2722
+ return this.limiter.keyPrefix;
2723
+ }
2724
+ get blockDuration() {
2725
+ return this.limiter.blockDuration;
2726
+ }
2727
+ set blockDuration(value) {
2728
+ this.limiter.blockDuration = value;
2729
+ }
2730
+ get execEvenly() {
2731
+ return this.limiter.execEvenly;
2732
+ }
2733
+ set execEvenly(value) {
2734
+ this.limiter.execEvenly = value;
2735
+ }
2736
+ get runActionAnyway() {
2737
+ return this._runActionAnyway;
2738
+ }
2739
+ set runActionAnyway(value) {
2740
+ this._runActionAnyway = typeof value === "undefined" ? false : value;
2741
+ }
2742
+ get blackList() {
2743
+ return this._blackList;
2744
+ }
2745
+ set blackList(value) {
2746
+ this._blackList = Array.isArray(value) ? value : [];
2747
+ }
2748
+ get isBlackListed() {
2749
+ return this._isBlackListed;
2750
+ }
2751
+ set isBlackListed(func) {
2752
+ if (typeof func === "undefined") {
2753
+ func = () => false;
2754
+ }
2755
+ if (typeof func !== "function") {
2756
+ throw new Error("isBlackListed must be function");
2757
+ }
2758
+ this._isBlackListed = func;
2759
+ }
2760
+ get whiteList() {
2761
+ return this._whiteList;
2762
+ }
2763
+ set whiteList(value) {
2764
+ this._whiteList = Array.isArray(value) ? value : [];
2765
+ }
2766
+ get isWhiteListed() {
2767
+ return this._isWhiteListed;
2768
+ }
2769
+ set isWhiteListed(func) {
2770
+ if (typeof func === "undefined") {
2771
+ func = () => false;
2772
+ }
2773
+ if (typeof func !== "function") {
2774
+ throw new Error("isWhiteListed must be function");
2775
+ }
2776
+ this._isWhiteListed = func;
2777
+ }
2778
+ isBlackListedSomewhere(key) {
2779
+ return this.blackList.indexOf(key) >= 0 || this.isBlackListed(key);
2780
+ }
2781
+ isWhiteListedSomewhere(key) {
2782
+ return this.whiteList.indexOf(key) >= 0 || this.isWhiteListed(key);
2783
+ }
2784
+ getBlackRes() {
2785
+ return new RateLimiterRes2(0, Number.MAX_SAFE_INTEGER, 0, false);
2786
+ }
2787
+ getWhiteRes() {
2788
+ return new RateLimiterRes2(Number.MAX_SAFE_INTEGER, 0, 0, false);
2789
+ }
2790
+ rejectBlack() {
2791
+ return Promise.reject(this.getBlackRes());
2792
+ }
2793
+ resolveBlack() {
2794
+ return Promise.resolve(this.getBlackRes());
2795
+ }
2796
+ resolveWhite() {
2797
+ return Promise.resolve(this.getWhiteRes());
2798
+ }
2799
+ _execAction(action, key, args, rejectOnBlack = false) {
2800
+ let res;
2801
+ if (this.isWhiteListedSomewhere(key)) {
2802
+ res = this.resolveWhite();
2803
+ } else if (this.isBlackListedSomewhere(key)) {
2804
+ res = rejectOnBlack ? this.rejectBlack() : this.resolveBlack();
2805
+ }
2806
+ if (typeof res === "undefined") {
2807
+ return this.limiter[action](key, ...args);
2808
+ }
2809
+ if (this.runActionAnyway) {
2810
+ this.limiter[action](key, ...args).catch(() => {
2811
+ });
2812
+ }
2813
+ return res;
2814
+ }
2815
+ consume(key, pointsToConsume = 1, options = {}) {
2816
+ return this._execAction("consume", key, [pointsToConsume, options], true);
2817
+ }
2818
+ block(key, secDuration, options = {}) {
2819
+ return this._execAction("block", key, [secDuration, options]);
2820
+ }
2821
+ penalty(key, points = 1, options = {}) {
2822
+ return this._execAction("penalty", key, [points, options]);
2823
+ }
2824
+ reward(key, points = 1, options = {}) {
2825
+ return this._execAction("reward", key, [points, options]);
2826
+ }
2827
+ get(key, options = {}) {
2828
+ if (this.runActionAnyway) {
2829
+ return this.limiter.get(key, options);
2830
+ }
2831
+ return this._execAction("get", key, [options]);
2832
+ }
2833
+ set(key, points, secDuration, options = {}) {
2834
+ return this._execAction("set", key, [points, secDuration, options]);
2835
+ }
2836
+ delete(key, options = {}) {
2837
+ return this.limiter.delete(key, options);
2838
+ }
2839
+ };
2840
+ }
2841
+ });
2842
+
2843
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RLWrapperTimeouts.js
2844
+ var require_RLWrapperTimeouts = __commonJS({
2845
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RLWrapperTimeouts.js"(exports, module) {
2846
+ "use strict";
2847
+ var RateLimiterInsuredAbstract = require_RateLimiterInsuredAbstract();
2848
+ var isRateLimiterCompatible = require_isRateLimiterCompatible();
2849
+ module.exports = class RLWrapperTimeouts extends RateLimiterInsuredAbstract {
2850
+ constructor(opts = {}) {
2851
+ super({
2852
+ ...opts,
2853
+ points: 0,
2854
+ duration: 0
2855
+ });
2856
+ this.limiter = opts.limiter;
2857
+ this.timeoutMs = opts.timeoutMs || 0;
2858
+ }
2859
+ get limiter() {
2860
+ return this._limiter;
2861
+ }
2862
+ set limiter(limiter) {
2863
+ if (!isRateLimiterCompatible(limiter)) {
2864
+ throw new TypeError("limiter must be an instance of RateLimiterAbstract or RateLimiterCompatibleAbstract");
2865
+ }
2866
+ this._limiter = limiter;
2867
+ if (!this.insuranceLimiter && limiter instanceof RateLimiterInsuredAbstract) {
2868
+ this.insuranceLimiter = limiter.insuranceLimiter;
2869
+ }
2870
+ }
2871
+ get timeoutMs() {
2872
+ return this._timeoutMs;
2873
+ }
2874
+ set timeoutMs(value) {
2875
+ if (typeof value !== "number" || value < 0) {
2876
+ throw new TypeError("timeoutMs must be a non-negative number");
2877
+ }
2878
+ this._timeoutMs = value;
2879
+ }
2880
+ _run(funcName, params) {
2881
+ return new Promise(async (resolve, reject) => {
2882
+ const timeout = setTimeout(() => {
2883
+ return reject(new Error("Operation timed out"));
2884
+ }, this.timeoutMs);
2885
+ await this.limiter[funcName](...params).then((result) => {
2886
+ clearTimeout(timeout);
2887
+ resolve(result);
2888
+ }).catch((err) => {
2889
+ clearTimeout(timeout);
2890
+ reject(err);
2891
+ });
2892
+ });
2893
+ }
2894
+ _consume(key, pointsToConsume = 1, options = {}) {
2895
+ return this._run("consume", [key, pointsToConsume, options]);
2896
+ }
2897
+ _penalty(key, points = 1, options = {}) {
2898
+ return this._run("penalty", [key, points, options]);
2899
+ }
2900
+ _reward(key, points = 1, options = {}) {
2901
+ return this._run("reward", [key, points, options]);
2902
+ }
2903
+ _get(key, options = {}) {
2904
+ return this._run("get", [key, options]);
2905
+ }
2906
+ _set(key, points, secDuration, options = {}) {
2907
+ return this._run("set", [key, points, secDuration, options]);
2908
+ }
2909
+ _block(key, secDuration, options = {}) {
2910
+ return this._run("block", [key, secDuration, options]);
2911
+ }
2912
+ _delete(key, options = {}) {
2913
+ return this._run("delete", [key, options]);
2914
+ }
2915
+ };
2916
+ }
2917
+ });
2918
+
2919
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterUnion.js
2920
+ var require_RateLimiterUnion = __commonJS({
2921
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterUnion.js"(exports, module) {
2922
+ "use strict";
2923
+ var isRateLimiterCompatible = require_isRateLimiterCompatible();
2924
+ module.exports = class RateLimiterUnion {
2925
+ constructor(...limiters) {
2926
+ if (limiters.length < 1) {
2927
+ throw new Error("RateLimiterUnion: at least one limiter have to be passed");
2928
+ }
2929
+ limiters.forEach((limiter) => {
2930
+ if (!isRateLimiterCompatible(limiter)) {
2931
+ throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract or RateLimiterCompatibleAbstract");
2932
+ }
2933
+ });
2934
+ this._limiters = limiters;
2935
+ }
2936
+ consume(key, points = 1) {
2937
+ return new Promise((resolve, reject) => {
2938
+ const promises = [];
2939
+ this._limiters.forEach((limiter) => {
2940
+ promises.push(limiter.consume(key, points).catch((rej) => ({ rejected: true, rej })));
2941
+ });
2942
+ Promise.all(promises).then((res) => {
2943
+ const resObj = {};
2944
+ let rejected = false;
2945
+ res.forEach((item) => {
2946
+ if (item.rejected === true) {
2947
+ rejected = true;
2948
+ }
2949
+ });
2950
+ for (let i = 0; i < res.length; i++) {
2951
+ if (rejected && res[i].rejected === true) {
2952
+ resObj[this._limiters[i].keyPrefix] = res[i].rej;
2953
+ } else if (!rejected) {
2954
+ resObj[this._limiters[i].keyPrefix] = res[i];
2955
+ }
2956
+ }
2957
+ if (rejected) {
2958
+ reject(resObj);
2959
+ } else {
2960
+ resolve(resObj);
2961
+ }
2962
+ });
2963
+ });
2964
+ }
2965
+ };
2966
+ }
2967
+ });
2968
+
2969
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/RateLimiterQueueError.js
2970
+ var require_RateLimiterQueueError = __commonJS({
2971
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/RateLimiterQueueError.js"(exports, module) {
2972
+ "use strict";
2973
+ module.exports = class RateLimiterQueueError extends Error {
2974
+ constructor(message, extra) {
2975
+ super();
2976
+ if (Error.captureStackTrace) {
2977
+ Error.captureStackTrace(this, this.constructor);
2978
+ }
2979
+ this.name = "CustomError";
2980
+ this.message = message;
2981
+ if (extra) {
2982
+ this.extra = extra;
2983
+ }
2984
+ }
2985
+ };
2986
+ }
2987
+ });
2988
+
2989
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterQueue.js
2990
+ var require_RateLimiterQueue = __commonJS({
2991
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterQueue.js"(exports, module) {
2992
+ "use strict";
2993
+ var RateLimiterQueueError = require_RateLimiterQueueError();
2994
+ var MAX_QUEUE_SIZE = 4294967295;
2995
+ var KEY_DEFAULT = "limiter";
2996
+ module.exports = class RateLimiterQueue {
2997
+ constructor(limiterFlexible, opts = {}) {
2998
+ const maxQueueSize = opts.maxQueueSize !== void 0 ? opts.maxQueueSize : MAX_QUEUE_SIZE;
2999
+ this._queueLimiters = {
3000
+ KEY_DEFAULT: new RateLimiterQueueInternal(limiterFlexible, {
3001
+ ...opts,
3002
+ maxQueueSize,
3003
+ key: KEY_DEFAULT
3004
+ })
3005
+ };
3006
+ this._limiterFlexible = limiterFlexible;
3007
+ this._maxQueueSize = maxQueueSize;
3008
+ }
3009
+ getTokensRemaining(key = KEY_DEFAULT) {
3010
+ if (this._queueLimiters[key]) {
3011
+ return this._queueLimiters[key].getTokensRemaining();
3012
+ } else {
3013
+ return Promise.resolve(this._limiterFlexible.points);
3014
+ }
3015
+ }
3016
+ removeTokens(tokens, key = KEY_DEFAULT, expiresUnixAt = 0) {
3017
+ if (!this._queueLimiters[key]) {
3018
+ this._queueLimiters[key] = new RateLimiterQueueInternal(
3019
+ this._limiterFlexible,
3020
+ {
3021
+ key,
3022
+ maxQueueSize: this._maxQueueSize
3023
+ }
3024
+ );
3025
+ }
3026
+ return this._queueLimiters[key].removeTokens(tokens, expiresUnixAt);
3027
+ }
3028
+ };
3029
+ var RateLimiterQueueInternal = class {
3030
+ constructor(limiterFlexible, opts = {
3031
+ maxQueueSize: MAX_QUEUE_SIZE,
3032
+ key: KEY_DEFAULT
3033
+ }) {
3034
+ this._key = opts.key;
3035
+ this._waitTimeout = null;
3036
+ this._queue = [];
3037
+ this._limiterFlexible = limiterFlexible;
3038
+ this._hasExpiringRequests = false;
3039
+ this._maxQueueSize = opts.maxQueueSize;
3040
+ }
3041
+ getTokensRemaining() {
3042
+ return this._limiterFlexible.get(this._key).then((rlRes) => {
3043
+ return rlRes !== null ? rlRes.remainingPoints : this._limiterFlexible.points;
3044
+ });
3045
+ }
3046
+ removeTokens(tokens, expiresUnixAt = 0) {
3047
+ const _this = this;
3048
+ return new Promise((resolve, reject) => {
3049
+ if (tokens > _this._limiterFlexible.points) {
3050
+ reject(new RateLimiterQueueError(`Requested tokens ${tokens} exceeds maximum ${_this._limiterFlexible.points} tokens per interval`));
3051
+ return;
3052
+ }
3053
+ if (_this._queue.length > 0) {
3054
+ _this._queueRequest.call(_this, resolve, reject, tokens, expiresUnixAt);
3055
+ } else {
3056
+ _this._limiterFlexible.consume(_this._key, tokens).then((res) => {
3057
+ resolve(res.remainingPoints);
3058
+ }).catch((rej) => {
3059
+ if (rej instanceof Error) {
3060
+ reject(rej);
3061
+ } else {
3062
+ _this._queueRequest.call(_this, resolve, reject, tokens, expiresUnixAt);
3063
+ if (_this._waitTimeout === null) {
3064
+ _this._waitTimeout = setTimeout(_this._processFIFO.bind(_this), rej.msBeforeNext);
3065
+ }
3066
+ }
3067
+ });
3068
+ }
3069
+ });
3070
+ }
3071
+ _queueRequest(resolve, reject, tokens, expiresUnixAt = 0) {
3072
+ const _this = this;
3073
+ if (_this._queue.length < _this._maxQueueSize) {
3074
+ _this._queue.push({ resolve, reject, tokens, expiresUnixAt });
3075
+ if (expiresUnixAt > 0) {
3076
+ _this._hasExpiringRequests = true;
3077
+ }
3078
+ } else {
3079
+ reject(new RateLimiterQueueError(`Number of requests reached it's maximum ${_this._maxQueueSize}`));
3080
+ }
3081
+ }
3082
+ _processFIFO() {
3083
+ const _this = this;
3084
+ if (_this._waitTimeout !== null) {
3085
+ clearTimeout(_this._waitTimeout);
3086
+ _this._waitTimeout = null;
3087
+ }
3088
+ if (_this._hasExpiringRequests) {
3089
+ const nowSecs = Math.floor(Date.now() / 1e3);
3090
+ _this._queue = _this._queue.filter((item2) => {
3091
+ if (item2.expiresUnixAt > 0 && nowSecs >= item2.expiresUnixAt) {
3092
+ item2.reject(new RateLimiterQueueError("The request to remove tokens expired before it could be fulfilled"));
3093
+ return false;
3094
+ }
3095
+ return true;
3096
+ });
3097
+ }
3098
+ if (_this._queue.length === 0) {
3099
+ return;
3100
+ }
3101
+ const item = _this._queue.shift();
3102
+ _this._limiterFlexible.consume(_this._key, item.tokens).then((res) => {
3103
+ item.resolve(res.remainingPoints);
3104
+ _this._processFIFO.call(_this);
3105
+ }).catch((rej) => {
3106
+ if (rej instanceof Error) {
3107
+ item.reject(rej);
3108
+ _this._processFIFO.call(_this);
3109
+ } else {
3110
+ _this._queue.unshift(item);
3111
+ if (_this._waitTimeout === null) {
3112
+ _this._waitTimeout = setTimeout(_this._processFIFO.bind(_this), rej.msBeforeNext);
3113
+ }
3114
+ }
3115
+ });
3116
+ }
3117
+ };
3118
+ }
3119
+ });
3120
+
3121
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/BurstyRateLimiter.js
3122
+ var require_BurstyRateLimiter = __commonJS({
3123
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/BurstyRateLimiter.js"(exports, module) {
3124
+ "use strict";
3125
+ var RateLimiterRes2 = require_RateLimiterRes();
3126
+ module.exports = class BurstyRateLimiter {
3127
+ constructor(rateLimiter, burstLimiter) {
3128
+ this._rateLimiter = rateLimiter;
3129
+ this._burstLimiter = burstLimiter;
3130
+ }
3131
+ /**
3132
+ * Merge rate limiter response objects. Responses can be null
3133
+ *
3134
+ * @param {RateLimiterRes} [rlRes] Rate limiter response
3135
+ * @param {RateLimiterRes} [blRes] Bursty limiter response
3136
+ */
3137
+ _combineRes(rlRes, blRes) {
3138
+ if (!rlRes) {
3139
+ return null;
3140
+ }
3141
+ return new RateLimiterRes2(
3142
+ rlRes.remainingPoints,
3143
+ Math.min(rlRes.msBeforeNext, blRes ? blRes.msBeforeNext : 0),
3144
+ rlRes.consumedPoints,
3145
+ rlRes.isFirstInDuration
3146
+ );
3147
+ }
3148
+ /**
3149
+ * @param key
3150
+ * @param pointsToConsume
3151
+ * @param options
3152
+ * @returns {Promise<any>}
3153
+ */
3154
+ consume(key, pointsToConsume = 1, options = {}) {
3155
+ return this._rateLimiter.consume(key, pointsToConsume, options).catch((rlRej) => {
3156
+ if (rlRej instanceof RateLimiterRes2) {
3157
+ return this._burstLimiter.consume(key, pointsToConsume, options).then((blRes) => {
3158
+ return Promise.resolve(this._combineRes(rlRej, blRes));
3159
+ }).catch(
3160
+ (blRej) => {
3161
+ if (blRej instanceof RateLimiterRes2) {
3162
+ return Promise.reject(this._combineRes(rlRej, blRej));
3163
+ } else {
3164
+ return Promise.reject(blRej);
3165
+ }
3166
+ }
3167
+ );
3168
+ } else {
3169
+ return Promise.reject(rlRej);
3170
+ }
3171
+ });
3172
+ }
3173
+ /**
3174
+ * It doesn't expose available points from burstLimiter
3175
+ *
3176
+ * @param key
3177
+ * @returns {Promise<RateLimiterRes>}
3178
+ */
3179
+ get(key) {
3180
+ return Promise.all([
3181
+ this._rateLimiter.get(key),
3182
+ this._burstLimiter.get(key)
3183
+ ]).then(([rlRes, blRes]) => {
3184
+ return this._combineRes(rlRes, blRes);
3185
+ });
3186
+ }
3187
+ get points() {
3188
+ return this._rateLimiter.points;
3189
+ }
3190
+ };
3191
+ }
3192
+ });
3193
+
3194
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterDynamo.js
3195
+ var require_RateLimiterDynamo = __commonJS({
3196
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterDynamo.js"(exports, module) {
3197
+ "use strict";
3198
+ var RateLimiterRes2 = require_RateLimiterRes();
3199
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
3200
+ var DynamoItem = class {
3201
+ /**
3202
+ * Create a DynamoItem.
3203
+ * @param {string} rlKey - The key for the rate limiter.
3204
+ * @param {number} points - The number of points.
3205
+ * @param {number} expire - The expiration time in seconds.
3206
+ */
3207
+ constructor(rlKey, points, expire) {
3208
+ this.key = rlKey;
3209
+ this.points = points;
3210
+ this.expire = expire;
3211
+ }
3212
+ };
3213
+ var DEFAULT_READ_CAPACITY_UNITS = 25;
3214
+ var DEFAULT_WRITE_CAPACITY_UNITS = 25;
3215
+ var RateLimiterDynamo = class extends RateLimiterStoreAbstract {
3216
+ /**
3217
+ * Constructs a new instance of the class.
3218
+ * The storeClient MUST be an instance of AWS.DynamoDB NOT of AWS.DynamoDBClient.
3219
+ *
3220
+ * @param {Object} opts - The options for the constructor.
3221
+ * @param {function} cb - The callback function (optional).
3222
+ * @return {void}
3223
+ */
3224
+ constructor(opts, cb = null) {
3225
+ super(opts);
3226
+ this.client = opts.storeClient;
3227
+ this.tableName = opts.tableName;
3228
+ this.tableCreated = opts.tableCreated;
3229
+ this.ttlManuallySet = opts.ttlSet;
3230
+ if (!this.tableCreated) {
3231
+ this._createTable(opts.dynamoTableOpts).then((data) => {
3232
+ this.tableCreated = true;
3233
+ this._setTTL().finally(() => {
3234
+ if (typeof cb === "function") {
3235
+ cb();
3236
+ }
3237
+ });
3238
+ }).catch((err) => {
3239
+ if (typeof cb === "function") {
3240
+ cb(err);
3241
+ } else {
3242
+ throw err;
3243
+ }
3244
+ });
3245
+ } else {
3246
+ this._setTTL().finally(() => {
3247
+ if (typeof cb === "function") {
3248
+ cb();
3249
+ }
3250
+ });
3251
+ }
3252
+ }
3253
+ get tableName() {
3254
+ return this._tableName;
3255
+ }
3256
+ set tableName(value) {
3257
+ this._tableName = typeof value === "undefined" ? "node-rate-limiter-flexible" : value;
3258
+ }
3259
+ get tableCreated() {
3260
+ return this._tableCreated;
3261
+ }
3262
+ set tableCreated(value) {
3263
+ this._tableCreated = typeof value === "undefined" ? false : !!value;
3264
+ }
3265
+ /**
3266
+ * Creates a table in the database. Return null if the table already exists.
3267
+ *
3268
+ * @param {{readCapacityUnits: number, writeCapacityUnits: number}} tableOpts
3269
+ * @return {Promise} A promise that resolves with the result of creating the table.
3270
+ */
3271
+ async _createTable(tableOpts) {
3272
+ const params = {
3273
+ TableName: this.tableName,
3274
+ AttributeDefinitions: [
3275
+ {
3276
+ AttributeName: "key",
3277
+ AttributeType: "S"
3278
+ }
3279
+ ],
3280
+ KeySchema: [
3281
+ {
3282
+ AttributeName: "key",
3283
+ KeyType: "HASH"
3284
+ }
3285
+ ],
3286
+ ProvisionedThroughput: {
3287
+ ReadCapacityUnits: tableOpts && tableOpts.readCapacityUnits ? tableOpts.readCapacityUnits : DEFAULT_READ_CAPACITY_UNITS,
3288
+ WriteCapacityUnits: tableOpts && tableOpts.writeCapacityUnits ? tableOpts.writeCapacityUnits : DEFAULT_WRITE_CAPACITY_UNITS
3289
+ }
3290
+ };
3291
+ try {
3292
+ const data = await this.client.createTable(params);
3293
+ return data;
3294
+ } catch (err) {
3295
+ if (err.__type && err.__type.includes("ResourceInUseException")) {
3296
+ return null;
3297
+ } else {
3298
+ throw err;
3299
+ }
3300
+ }
3301
+ }
3302
+ /**
3303
+ * Retrieves an item from the table based on the provided key.
3304
+ *
3305
+ * @param {string} rlKey - The key used to retrieve the item.
3306
+ * @throws {Error} Throws an error if the table is not created yet.
3307
+ * @return {DynamoItem|null} - The retrieved item, or null if it doesn't exist.
3308
+ */
3309
+ async _get(rlKey) {
3310
+ if (!this.tableCreated) {
3311
+ throw new Error("Table is not created yet");
3312
+ }
3313
+ const params = {
3314
+ TableName: this.tableName,
3315
+ Key: {
3316
+ key: { S: rlKey }
3317
+ }
3318
+ };
3319
+ const data = await this.client.getItem(params);
3320
+ if (!data.Item) {
3321
+ return null;
3322
+ }
3323
+ const item = new DynamoItem(
3324
+ data.Item.key.S,
3325
+ Number(data.Item.points.N),
3326
+ Number(data.Item.expire.N)
3327
+ );
3328
+ const dateNowSec = Date.now() / 1e3;
3329
+ if (item.expire !== -1 && item.expire <= dateNowSec) {
3330
+ return null;
3331
+ }
3332
+ return item;
3333
+ }
3334
+ /**
3335
+ * Deletes an item from the table based on the given rlKey.
3336
+ *
3337
+ * @param {string} rlKey - The rlKey of the item to delete.
3338
+ * @throws {Error} Throws an error if the table is not created yet.
3339
+ * @return {boolean} Returns true if the item was successfully deleted, otherwise false.
3340
+ */
3341
+ async _delete(rlKey) {
3342
+ if (!this.tableCreated) {
3343
+ throw new Error("Table is not created yet");
3344
+ }
3345
+ const params = {
3346
+ TableName: this.tableName,
3347
+ Key: {
3348
+ key: { S: rlKey }
3349
+ },
3350
+ ConditionExpression: "attribute_exists(#k)",
3351
+ ExpressionAttributeNames: {
3352
+ "#k": "key"
3353
+ }
3354
+ };
3355
+ try {
3356
+ const data = await this._client.deleteItem(params);
3357
+ return data.$metadata.httpStatusCode === 200;
3358
+ } catch (err) {
3359
+ if (err.__type && err.__type.includes("ConditionalCheckFailedException")) {
3360
+ return false;
3361
+ } else {
3362
+ throw err;
3363
+ }
3364
+ }
3365
+ }
3366
+ /**
3367
+ * Implemented with DynamoDB Atomic Counters. 3 calls are made to DynamoDB but each call is atomic.
3368
+ * From the documentation: "UpdateItem calls are naturally serialized within DynamoDB,
3369
+ * so there are no race condition concerns with making multiple simultaneous calls."
3370
+ * See: https://aws.amazon.com/it/blogs/database/implement-resource-counters-with-amazon-dynamodb/
3371
+ * @param {*} rlKey
3372
+ * @param {*} points
3373
+ * @param {*} msDuration
3374
+ * @param {*} forceExpire
3375
+ * @param {*} options
3376
+ * @returns
3377
+ */
3378
+ async _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) {
3379
+ if (!this.tableCreated) {
3380
+ throw new Error("Table is not created yet");
3381
+ }
3382
+ const dateNow = Date.now();
3383
+ const dateNowSec = dateNow / 1e3;
3384
+ const newExpireSec = msDuration > 0 ? (dateNow + msDuration) / 1e3 : -1;
3385
+ if (forceExpire) {
3386
+ return await this._baseUpsert({
3387
+ TableName: this.tableName,
3388
+ Key: { key: { S: rlKey } },
3389
+ UpdateExpression: "SET points = :points, expire = :expire",
3390
+ ExpressionAttributeValues: {
3391
+ ":points": { N: points.toString() },
3392
+ ":expire": { N: newExpireSec.toString() }
3393
+ },
3394
+ ReturnValues: "ALL_NEW"
3395
+ });
3396
+ }
3397
+ try {
3398
+ return await this._baseUpsert({
3399
+ TableName: this.tableName,
3400
+ Key: { key: { S: rlKey } },
3401
+ UpdateExpression: "SET points = :new_points, expire = :new_expire",
3402
+ ExpressionAttributeValues: {
3403
+ ":new_points": { N: points.toString() },
3404
+ ":new_expire": { N: newExpireSec.toString() },
3405
+ ":where_expire": { N: dateNowSec.toString() }
3406
+ },
3407
+ ConditionExpression: "expire <= :where_expire OR attribute_not_exists(points)",
3408
+ ReturnValues: "ALL_NEW"
3409
+ });
3410
+ } catch (err) {
3411
+ return await this._baseUpsert({
3412
+ TableName: this.tableName,
3413
+ Key: { key: { S: rlKey } },
3414
+ UpdateExpression: "SET points = points + :new_points",
3415
+ ExpressionAttributeValues: {
3416
+ ":new_points": { N: points.toString() },
3417
+ ":where_expire": { N: dateNowSec.toString() }
3418
+ },
3419
+ ConditionExpression: "expire > :where_expire",
3420
+ ReturnValues: "ALL_NEW"
3421
+ });
3422
+ }
3423
+ }
3424
+ /**
3425
+ * Asynchronously upserts data into the table. params is a DynamoDB params object.
3426
+ *
3427
+ * @param {Object} params - The parameters for the upsert operation.
3428
+ * @throws {Error} Throws an error if the table is not created yet.
3429
+ * @return {DynamoItem} Returns a DynamoItem object with the updated data.
3430
+ */
3431
+ async _baseUpsert(params) {
3432
+ if (!this.tableCreated) {
3433
+ throw new Error("Table is not created yet");
3434
+ }
3435
+ try {
3436
+ const data = await this.client.updateItem(params);
3437
+ return new DynamoItem(
3438
+ data.Attributes.key.S,
3439
+ Number(data.Attributes.points.N),
3440
+ Number(data.Attributes.expire.N)
3441
+ );
3442
+ } catch (err) {
3443
+ throw err;
3444
+ }
3445
+ }
3446
+ /**
3447
+ * Sets the Time-to-Live (TTL) for the table. TTL use the expire field in the table.
3448
+ * See: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/howitworks-ttl.html
3449
+ *
3450
+ * @return {Promise} A promise that resolves when the TTL is successfully set.
3451
+ * @throws {Error} Throws an error if the table is not created yet.
3452
+ * @returns {Promise}
3453
+ */
3454
+ async _setTTL() {
3455
+ if (!this.tableCreated) {
3456
+ throw new Error("Table is not created yet");
3457
+ }
3458
+ try {
3459
+ const isTTLSet = await this._isTTLSet();
3460
+ if (isTTLSet) {
3461
+ return;
3462
+ }
3463
+ const params = {
3464
+ TableName: this.tableName,
3465
+ TimeToLiveSpecification: {
3466
+ AttributeName: "expire",
3467
+ Enabled: true
3468
+ }
3469
+ };
3470
+ const res = await this.client.updateTimeToLive(params);
3471
+ return res;
3472
+ } catch (err) {
3473
+ throw err;
3474
+ }
3475
+ }
3476
+ /**
3477
+ * Checks if the Time To Live (TTL) feature is set for the DynamoDB table.
3478
+ *
3479
+ * @return {boolean} Returns true if the TTL feature is enabled for the table, otherwise false.
3480
+ * @throws {Error} Throws an error if the table is not created yet or if there is an error while checking the TTL status.
3481
+ */
3482
+ async _isTTLSet() {
3483
+ if (!this.tableCreated) {
3484
+ throw new Error("Table is not created yet");
3485
+ }
3486
+ if (this.ttlManuallySet) {
3487
+ return true;
3488
+ }
3489
+ try {
3490
+ const res = await this.client.describeTimeToLive({ TableName: this.tableName });
3491
+ return res.$metadata.httpStatusCode == 200 && res.TimeToLiveDescription.TimeToLiveStatus === "ENABLED" && res.TimeToLiveDescription.AttributeName === "expire";
3492
+ } catch (err) {
3493
+ throw err;
3494
+ }
3495
+ }
3496
+ /**
3497
+ * Generate a RateLimiterRes object based on the provided parameters.
3498
+ *
3499
+ * @param {string} rlKey - The key for the rate limiter.
3500
+ * @param {number} changedPoints - The number of points that have changed.
3501
+ * @param {DynamoItem} result - The result object of _get() method.
3502
+ * @returns {RateLimiterRes} - The generated RateLimiterRes object.
3503
+ */
3504
+ _getRateLimiterRes(rlKey, changedPoints, result) {
3505
+ const res = new RateLimiterRes2();
3506
+ res.isFirstInDuration = changedPoints === result.points;
3507
+ res.consumedPoints = res.isFirstInDuration ? changedPoints : result.points;
3508
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
3509
+ res.msBeforeNext = result.expire != -1 ? Math.max(result.expire * 1e3 - Date.now(), 0) : -1;
3510
+ return res;
3511
+ }
3512
+ };
3513
+ module.exports = RateLimiterDynamo;
3514
+ }
3515
+ });
3516
+
3517
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterPrisma.js
3518
+ var require_RateLimiterPrisma = __commonJS({
3519
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterPrisma.js"(exports, module) {
3520
+ "use strict";
3521
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
3522
+ var RateLimiterRes2 = require_RateLimiterRes();
3523
+ var RateLimiterPrisma = class extends RateLimiterStoreAbstract {
3524
+ /**
3525
+ * Constructor for the rate limiter
3526
+ * @param {Object} opts - Options for the rate limiter
3527
+ */
3528
+ constructor(opts) {
3529
+ super(opts);
3530
+ this.modelName = opts.tableName || "RateLimiterFlexible";
3531
+ this.prismaClient = opts.storeClient;
3532
+ this.clearExpiredByTimeout = opts.clearExpiredByTimeout || true;
3533
+ if (!this.prismaClient) {
3534
+ throw new Error("Prisma client is not provided");
3535
+ }
3536
+ if (this.clearExpiredByTimeout) {
3537
+ this._clearExpiredHourAgo();
3538
+ }
3539
+ }
3540
+ _getRateLimiterRes(rlKey, changedPoints, result) {
3541
+ const res = new RateLimiterRes2();
3542
+ let doc = result;
3543
+ res.isFirstInDuration = doc.points === changedPoints;
3544
+ res.consumedPoints = doc.points;
3545
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
3546
+ res.msBeforeNext = doc.expire !== null ? Math.max(new Date(doc.expire).getTime() - Date.now(), 0) : -1;
3547
+ return res;
3548
+ }
3549
+ _upsert(key, points, msDuration, forceExpire = false) {
3550
+ if (!this.prismaClient) {
3551
+ return Promise.reject(new Error("Prisma client is not established"));
3552
+ }
3553
+ const now = /* @__PURE__ */ new Date();
3554
+ const newExpire = msDuration > 0 ? new Date(now.getTime() + msDuration) : null;
3555
+ return this.prismaClient.$transaction(async (prisma) => {
3556
+ const existingRecord = await prisma[this.modelName].findFirst({
3557
+ where: { key }
3558
+ });
3559
+ if (existingRecord) {
3560
+ const shouldUpdateExpire = forceExpire || !existingRecord.expire || existingRecord.expire <= now || newExpire === null;
3561
+ return prisma[this.modelName].update({
3562
+ where: { key },
3563
+ data: {
3564
+ points: !shouldUpdateExpire ? existingRecord.points + points : points,
3565
+ ...shouldUpdateExpire && { expire: newExpire }
3566
+ }
3567
+ });
3568
+ } else {
3569
+ return prisma[this.modelName].create({
3570
+ data: {
3571
+ key,
3572
+ points,
3573
+ expire: newExpire
3574
+ }
3575
+ });
3576
+ }
3577
+ });
3578
+ }
3579
+ _get(rlKey) {
3580
+ if (!this.prismaClient) {
3581
+ return Promise.reject(new Error("Prisma client is not established"));
3582
+ }
3583
+ return this.prismaClient[this.modelName].findFirst({
3584
+ where: {
3585
+ AND: [
3586
+ { key: rlKey },
3587
+ {
3588
+ OR: [
3589
+ { expire: { gt: /* @__PURE__ */ new Date() } },
3590
+ { expire: null }
3591
+ ]
3592
+ }
3593
+ ]
3594
+ }
3595
+ });
3596
+ }
3597
+ _delete(rlKey) {
3598
+ if (!this.prismaClient) {
3599
+ return Promise.reject(new Error("Prisma client is not established"));
3600
+ }
3601
+ return this.prismaClient[this.modelName].deleteMany({
3602
+ where: {
3603
+ key: rlKey
3604
+ }
3605
+ }).then((res) => res.count > 0);
3606
+ }
3607
+ _clearExpiredHourAgo() {
3608
+ if (this._clearExpiredTimeoutId) {
3609
+ clearTimeout(this._clearExpiredTimeoutId);
3610
+ }
3611
+ this._clearExpiredTimeoutId = setTimeout(async () => {
3612
+ await this.prismaClient[this.modelName].deleteMany({
3613
+ where: {
3614
+ expire: {
3615
+ lt: new Date(Date.now() - 36e5)
3616
+ }
3617
+ }
3618
+ });
3619
+ this._clearExpiredHourAgo();
3620
+ }, 3e5);
3621
+ this._clearExpiredTimeoutId.unref();
3622
+ }
3623
+ };
3624
+ module.exports = RateLimiterPrisma;
3625
+ }
3626
+ });
3627
+
3628
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterDrizzle.js
3629
+ var require_RateLimiterDrizzle = __commonJS({
3630
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterDrizzle.js"(exports, module) {
3631
+ "use strict";
3632
+ var drizzleOperators = null;
3633
+ var CLEANUP_INTERVAL_MS = 3e5;
3634
+ var EXPIRED_THRESHOLD_MS = 36e5;
3635
+ var RateLimiterDrizzleError = class extends Error {
3636
+ constructor(message) {
3637
+ super(message);
3638
+ this.name = "RateLimiterDrizzleError";
3639
+ }
3640
+ };
3641
+ async function loadDrizzleOperators() {
3642
+ if (drizzleOperators) return drizzleOperators;
3643
+ const requiredOperators = ["and", "or", "gt", "lt", "eq", "isNull", "sql"];
3644
+ function getPackageName() {
3645
+ return ["drizzle", "orm"].join("-");
3646
+ }
3647
+ const collectModuleLayers = (mod) => {
3648
+ const layers = [];
3649
+ const seen = /* @__PURE__ */ new Set();
3650
+ let current = mod;
3651
+ while (current && (typeof current === "object" || typeof current === "function") && !seen.has(current)) {
3652
+ layers.push(current);
3653
+ seen.add(current);
3654
+ current = current.default;
3655
+ }
3656
+ return layers;
3657
+ };
3658
+ const importModule = async (specifier, { optional = false } = {}) => {
3659
+ try {
3660
+ return await import(
3661
+ /* @vite-ignore */
3662
+ specifier
3663
+ );
3664
+ } catch (error) {
3665
+ if (optional) {
3666
+ return null;
3667
+ }
3668
+ throw new RateLimiterDrizzleError(
3669
+ error.message || "Failed to import drizzle-orm package."
3670
+ );
3671
+ }
3672
+ };
3673
+ const mainModule = await importModule(`${getPackageName()}`);
3674
+ const sqlModule = await importModule(`${getPackageName()}/sql`, { optional: true });
3675
+ const mainCandidates = collectModuleLayers(mainModule);
3676
+ const sqlCandidates = sqlModule ? collectModuleLayers(sqlModule) : [];
3677
+ const resolvedOperators = {};
3678
+ const missingOperators = [];
3679
+ for (const operatorName of requiredOperators) {
3680
+ const candidates = operatorName === "sql" ? [...sqlCandidates, ...mainCandidates] : mainCandidates;
3681
+ const operator = candidates.map((candidate) => candidate?.[operatorName]).find((value) => typeof value === "function");
3682
+ if (!operator) {
3683
+ missingOperators.push(operatorName);
3684
+ continue;
3685
+ }
3686
+ resolvedOperators[operatorName] = operator;
3687
+ }
3688
+ if (missingOperators.length > 0) {
3689
+ throw new RateLimiterDrizzleError(
3690
+ `Failed to load drizzle-orm operators: missing ${missingOperators.join(", ")}`
3691
+ );
3692
+ }
3693
+ drizzleOperators = resolvedOperators;
3694
+ return drizzleOperators;
3695
+ }
3696
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
3697
+ var RateLimiterRes2 = require_RateLimiterRes();
3698
+ var RateLimiterDrizzle = class extends RateLimiterStoreAbstract {
3699
+ constructor(opts) {
3700
+ super(opts);
3701
+ if (!opts?.schema) {
3702
+ throw new RateLimiterDrizzleError("Drizzle schema is required");
3703
+ }
3704
+ if (!opts?.storeClient) {
3705
+ throw new RateLimiterDrizzleError("Drizzle client is required");
3706
+ }
3707
+ this.schema = opts.schema;
3708
+ this.drizzleClient = opts.storeClient;
3709
+ this.clearExpiredByTimeout = opts.clearExpiredByTimeout ?? true;
3710
+ if (this.clearExpiredByTimeout) {
3711
+ this._clearExpiredHourAgo();
3712
+ }
3713
+ }
3714
+ _getRateLimiterRes(rlKey, changedPoints, result) {
3715
+ const res = new RateLimiterRes2();
3716
+ let doc = result;
3717
+ res.isFirstInDuration = doc.points === changedPoints;
3718
+ res.consumedPoints = doc.points;
3719
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
3720
+ res.msBeforeNext = doc.expire !== null ? Math.max(new Date(doc.expire).getTime() - Date.now(), 0) : -1;
3721
+ return res;
3722
+ }
3723
+ async _upsert(key, points, msDuration, forceExpire = false) {
3724
+ if (!this.drizzleClient) {
3725
+ return Promise.reject(new RateLimiterDrizzleError("Drizzle client is not established"));
3726
+ }
3727
+ const { eq, sql } = await loadDrizzleOperators();
3728
+ const now = /* @__PURE__ */ new Date();
3729
+ const newExpire = msDuration > 0 ? new Date(now.getTime() + msDuration) : null;
3730
+ const query = await this.drizzleClient.transaction(async (tx) => {
3731
+ const [existingRecord] = await tx.select().from(this.schema).where(eq(this.schema.key, key)).limit(1);
3732
+ const shouldUpdateExpire = forceExpire || !existingRecord?.expire || existingRecord?.expire <= now || newExpire === null;
3733
+ const [data] = await tx.insert(this.schema).values({
3734
+ key,
3735
+ points,
3736
+ expire: newExpire
3737
+ }).onConflictDoUpdate({
3738
+ target: this.schema.key,
3739
+ set: {
3740
+ points: !shouldUpdateExpire ? sql`${this.schema.points} + ${points}` : points,
3741
+ ...shouldUpdateExpire && { expire: newExpire }
3742
+ }
3743
+ }).returning();
3744
+ return data;
3745
+ });
3746
+ return query;
3747
+ }
3748
+ async _get(rlKey) {
3749
+ if (!this.drizzleClient) {
3750
+ return Promise.reject(new RateLimiterDrizzleError("Drizzle client is not established"));
3751
+ }
3752
+ const { and, or, gt, eq, isNull } = await loadDrizzleOperators();
3753
+ const [response] = await this.drizzleClient.select().from(this.schema).where(
3754
+ and(
3755
+ eq(this.schema.key, rlKey),
3756
+ or(gt(this.schema.expire, /* @__PURE__ */ new Date()), isNull(this.schema.expire))
3757
+ )
3758
+ ).limit(1);
3759
+ return response || null;
3760
+ }
3761
+ async _delete(rlKey) {
3762
+ if (!this.drizzleClient) {
3763
+ return Promise.reject(new RateLimiterDrizzleError("Drizzle client is not established"));
3764
+ }
3765
+ const { eq } = await loadDrizzleOperators();
3766
+ const [result] = await this.drizzleClient.delete(this.schema).where(eq(this.schema.key, rlKey)).returning({ key: this.schema.key });
3767
+ return !!result?.key;
3768
+ }
3769
+ _clearExpiredHourAgo() {
3770
+ if (this._clearExpiredTimeoutId) {
3771
+ clearTimeout(this._clearExpiredTimeoutId);
3772
+ }
3773
+ this._clearExpiredTimeoutId = setTimeout(async () => {
3774
+ try {
3775
+ const { lt } = await loadDrizzleOperators();
3776
+ await this.drizzleClient.delete(this.schema).where(lt(this.schema.expire, new Date(Date.now() - EXPIRED_THRESHOLD_MS)));
3777
+ } catch (error) {
3778
+ console.warn("Failed to clear expired records:", error);
3779
+ }
3780
+ this._clearExpiredHourAgo();
3781
+ }, CLEANUP_INTERVAL_MS);
3782
+ this._clearExpiredTimeoutId.unref();
3783
+ }
3784
+ };
3785
+ module.exports = RateLimiterDrizzle;
3786
+ }
3787
+ });
3788
+
3789
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterDrizzleNonAtomic.js
3790
+ var require_RateLimiterDrizzleNonAtomic = __commonJS({
3791
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterDrizzleNonAtomic.js"(exports, module) {
3792
+ "use strict";
3793
+ var drizzleOperators = null;
3794
+ var CLEANUP_INTERVAL_MS = 3e5;
3795
+ var EXPIRED_THRESHOLD_MS = 36e5;
3796
+ var RateLimiterDrizzleError = class extends Error {
3797
+ constructor(message) {
3798
+ super(message);
3799
+ this.name = "RateLimiterDrizzleError";
3800
+ }
3801
+ };
3802
+ async function getDrizzleOperators() {
3803
+ if (drizzleOperators) return drizzleOperators;
3804
+ try {
3805
+ let getPackageName2 = function() {
3806
+ return ["drizzle", "orm"].join("-");
3807
+ };
3808
+ var getPackageName = getPackageName2;
3809
+ const drizzleOrm = await import(`${getPackageName2()}`);
3810
+ const { and, or, gt, lt, eq, isNull, sql } = drizzleOrm.default || drizzleOrm;
3811
+ drizzleOperators = { and, or, gt, lt, eq, isNull, sql };
3812
+ return drizzleOperators;
3813
+ } catch (error) {
3814
+ throw new RateLimiterDrizzleError(
3815
+ "drizzle-orm is not installed. Please install drizzle-orm to use RateLimiterDrizzleNonAtomic."
3816
+ );
3817
+ }
3818
+ }
3819
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
3820
+ var RateLimiterRes2 = require_RateLimiterRes();
3821
+ var RateLimiterDrizzleNonAtomic = class extends RateLimiterStoreAbstract {
3822
+ constructor(opts) {
3823
+ super(opts);
3824
+ if (!opts?.schema) {
3825
+ throw new RateLimiterDrizzleError("Drizzle schema is required");
3826
+ }
3827
+ if (!opts?.storeClient) {
3828
+ throw new RateLimiterDrizzleError("Drizzle client is required");
3829
+ }
3830
+ this.schema = opts.schema;
3831
+ this.drizzleClient = opts.storeClient;
3832
+ this.clearExpiredByTimeout = opts.clearExpiredByTimeout ?? true;
3833
+ if (this.clearExpiredByTimeout) {
3834
+ this._clearExpiredHourAgo();
3835
+ }
3836
+ }
3837
+ _getRateLimiterRes(rlKey, changedPoints, result) {
3838
+ const res = new RateLimiterRes2();
3839
+ let doc = result;
3840
+ res.isFirstInDuration = doc.points === changedPoints;
3841
+ res.consumedPoints = doc.points;
3842
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
3843
+ res.msBeforeNext = doc.expire !== null ? Math.max(new Date(doc.expire).getTime() - Date.now(), 0) : -1;
3844
+ return res;
3845
+ }
3846
+ async _upsert(key, points, msDuration, forceExpire = false) {
3847
+ if (!this.drizzleClient) {
3848
+ return Promise.reject(new RateLimiterDrizzleError("Drizzle client is not established"));
3849
+ }
3850
+ const { eq } = await getDrizzleOperators();
3851
+ const now = /* @__PURE__ */ new Date();
3852
+ const newExpire = msDuration > 0 ? new Date(now.getTime() + msDuration) : null;
3853
+ const [existingRecord] = await this.drizzleClient.select().from(this.schema).where(eq(this.schema.key, key)).limit(1);
3854
+ const shouldUpdateExpire = forceExpire || !existingRecord || !existingRecord.expire || existingRecord.expire <= now || newExpire === null;
3855
+ let newPoints;
3856
+ if (existingRecord && !shouldUpdateExpire) {
3857
+ newPoints = existingRecord.points + points;
3858
+ } else {
3859
+ newPoints = points;
3860
+ }
3861
+ const [data] = await this.drizzleClient.insert(this.schema).values({
3862
+ key,
3863
+ points: newPoints,
3864
+ expire: newExpire
3865
+ }).onConflictDoUpdate({
3866
+ target: this.schema.key,
3867
+ set: {
3868
+ points: newPoints,
3869
+ ...shouldUpdateExpire && { expire: newExpire }
3870
+ }
3871
+ }).returning();
3872
+ return data;
3873
+ }
3874
+ async _get(rlKey) {
3875
+ if (!this.drizzleClient) {
3876
+ return Promise.reject(new RateLimiterDrizzleError("Drizzle client is not established"));
3877
+ }
3878
+ const { and, or, gt, eq, isNull } = await getDrizzleOperators();
3879
+ const [response] = await this.drizzleClient.select().from(this.schema).where(
3880
+ and(
3881
+ eq(this.schema.key, rlKey),
3882
+ or(gt(this.schema.expire, /* @__PURE__ */ new Date()), isNull(this.schema.expire))
3883
+ )
3884
+ ).limit(1);
3885
+ return response || null;
3886
+ }
3887
+ async _delete(rlKey) {
3888
+ if (!this.drizzleClient) {
3889
+ return Promise.reject(new RateLimiterDrizzleError("Drizzle client is not established"));
3890
+ }
3891
+ const { eq } = await getDrizzleOperators();
3892
+ const [result] = await this.drizzleClient.delete(this.schema).where(eq(this.schema.key, rlKey)).returning({ key: this.schema.key });
3893
+ return !!(result && result.key);
3894
+ }
3895
+ _clearExpiredHourAgo() {
3896
+ if (this._clearExpiredTimeoutId) {
3897
+ clearTimeout(this._clearExpiredTimeoutId);
3898
+ }
3899
+ this._clearExpiredTimeoutId = setTimeout(async () => {
3900
+ try {
3901
+ const { lt } = await getDrizzleOperators();
3902
+ await this.drizzleClient.delete(this.schema).where(lt(this.schema.expire, new Date(Date.now() - EXPIRED_THRESHOLD_MS)));
3903
+ } catch (error) {
3904
+ console.warn("Failed to clear expired records:", error);
3905
+ }
3906
+ this._clearExpiredHourAgo();
3907
+ }, CLEANUP_INTERVAL_MS);
3908
+ this._clearExpiredTimeoutId.unref();
3909
+ }
3910
+ };
3911
+ module.exports = RateLimiterDrizzleNonAtomic;
3912
+ }
3913
+ });
3914
+
3915
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterValkey.js
3916
+ var require_RateLimiterValkey = __commonJS({
3917
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterValkey.js"(exports, module) {
3918
+ "use strict";
3919
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
3920
+ var RateLimiterRes2 = require_RateLimiterRes();
3921
+ var incrTtlLuaScript = `
3922
+ server.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX')
3923
+ local consumed = server.call('incrby', KEYS[1], ARGV[1])
3924
+ local ttl = server.call('pttl', KEYS[1])
3925
+ return {consumed, ttl}
3926
+ `;
3927
+ var RateLimiterValkey = class extends RateLimiterStoreAbstract {
3928
+ /**
3929
+ *
3930
+ * @param {Object} opts
3931
+ * Defaults {
3932
+ * ... see other in RateLimiterStoreAbstract
3933
+ *
3934
+ * storeClient: ValkeyClient
3935
+ * rejectIfValkeyNotReady: boolean = false - reject / invoke insuranceLimiter immediately when valkey connection is not "ready"
3936
+ * }
3937
+ */
3938
+ constructor(opts) {
3939
+ super(opts);
3940
+ this.client = opts.storeClient;
3941
+ this._rejectIfValkeyNotReady = !!opts.rejectIfValkeyNotReady;
3942
+ this._incrTtlLuaScript = opts.customIncrTtlLuaScript || incrTtlLuaScript;
3943
+ this.client.defineCommand("rlflxIncr", {
3944
+ numberOfKeys: 1,
3945
+ lua: this._incrTtlLuaScript
3946
+ });
3947
+ }
3948
+ /**
3949
+ * Prevent actual valkey call if valkey connection is not ready
3950
+ * @return {boolean}
3951
+ * @private
3952
+ */
3953
+ _isValkeyReady() {
3954
+ if (!this._rejectIfValkeyNotReady) {
3955
+ return true;
3956
+ }
3957
+ return this.client.status === "ready";
3958
+ }
3959
+ _getRateLimiterRes(rlKey, changedPoints, result) {
3960
+ let consumed;
3961
+ let resTtlMs;
3962
+ if (Array.isArray(result[0])) {
3963
+ [[, consumed], [, resTtlMs]] = result;
3964
+ } else {
3965
+ [consumed, resTtlMs] = result;
3966
+ }
3967
+ const res = new RateLimiterRes2();
3968
+ res.consumedPoints = +consumed;
3969
+ res.isFirstInDuration = res.consumedPoints === changedPoints;
3970
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
3971
+ res.msBeforeNext = resTtlMs;
3972
+ return res;
3973
+ }
3974
+ _upsert(rlKey, points, msDuration, forceExpire = false) {
3975
+ if (!this._isValkeyReady()) {
3976
+ throw new Error("Valkey connection is not ready");
3977
+ }
3978
+ const secDuration = Math.floor(msDuration / 1e3);
3979
+ if (forceExpire) {
3980
+ const multi = this.client.multi();
3981
+ if (secDuration > 0) {
3982
+ multi.set(rlKey, points, "EX", secDuration);
3983
+ } else {
3984
+ multi.set(rlKey, points);
3985
+ }
3986
+ return multi.pttl(rlKey).exec();
3987
+ }
3988
+ if (secDuration > 0) {
3989
+ return this.client.rlflxIncr([rlKey, String(points), String(secDuration), String(this.points), String(this.duration)]);
3990
+ }
3991
+ return this.client.multi().incrby(rlKey, points).pttl(rlKey).exec();
3992
+ }
3993
+ _get(rlKey) {
3994
+ if (!this._isValkeyReady()) {
3995
+ throw new Error("Valkey connection is not ready");
3996
+ }
3997
+ return this.client.multi().get(rlKey).pttl(rlKey).exec().then((result) => {
3998
+ const [[, points]] = result;
3999
+ if (points === null) return null;
4000
+ return result;
4001
+ });
4002
+ }
4003
+ _delete(rlKey) {
4004
+ return this.client.del(rlKey).then((result) => result > 0);
4005
+ }
4006
+ };
4007
+ module.exports = RateLimiterValkey;
4008
+ }
4009
+ });
4010
+
4011
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterValkeyGlide.js
4012
+ var require_RateLimiterValkeyGlide = __commonJS({
4013
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterValkeyGlide.js"(exports, module) {
4014
+ "use strict";
4015
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
4016
+ var RateLimiterRes2 = require_RateLimiterRes();
4017
+ var DEFAULT_LIBRARY_NAME = "ratelimiterflexible";
4018
+ var DEFAULT_VALKEY_SCRIPT = `local key = KEYS[1]
4019
+ local pointsToConsume = tonumber(ARGV[1])
4020
+ if tonumber(ARGV[2]) > 0 then
4021
+ server.call('set', key, "0", 'EX', ARGV[2], 'NX')
4022
+ local consumed = server.call('incrby', key, pointsToConsume)
4023
+ local pttl = server.call('pttl', key)
4024
+ return {consumed, pttl}
4025
+ end
4026
+ local consumed = server.call('incrby', key, pointsToConsume)
4027
+ local pttl = server.call('pttl', key)
4028
+ return {consumed, pttl}`;
4029
+ var GET_VALKEY_SCRIPT = `local key = KEYS[1]
4030
+ local value = server.call('get', key)
4031
+ if value == nil then
4032
+ return value
4033
+ end
4034
+ local pttl = server.call('pttl', key)
4035
+ return {tonumber(value), pttl}`;
4036
+ var RateLimiterValkeyGlide = class extends RateLimiterStoreAbstract {
4037
+ /**
4038
+ * Constructor for RateLimiterValkeyGlide
4039
+ *
4040
+ * @param {Object} opts - Configuration options
4041
+ * @param {GlideClient|GlideClusterClient} opts.storeClient - Valkey Glide client instance (required)
4042
+ * @param {number} opts.points - Maximum number of points that can be consumed over duration (required)
4043
+ * @param {number} opts.duration - Duration in seconds before points are reset (required, 0 = never expires)
4044
+ * @param {number} [opts.blockDuration=0] - Duration in seconds that a key will be blocked for if consumed more than points
4045
+ * @param {boolean} [opts.rejectIfValkeyNotReady=false] - Whether to reject requests if Valkey is not ready
4046
+ * @param {boolean} [opts.execEvenly=false] - Delay actions to distribute them evenly over duration
4047
+ * @param {number} [opts.execEvenlyMinDelayMs] - Minimum delay between actions when execEvenly is true
4048
+ * @param {string} [opts.customFunction] - Custom Lua script for rate limiting logic
4049
+ * @param {number} [opts.inMemoryBlockOnConsumed] - Points threshold for in-memory blocking
4050
+ * @param {number} [opts.inMemoryBlockDuration] - Duration in seconds for in-memory blocking
4051
+ * @param {string} [opts.customFunctionLibName] - Custom name for the function library, defaults to 'ratelimiter'.
4052
+ * The name is used to identify the library of the lua function. An custom name should be used only if you
4053
+ * you want to use different libraries for different rate limiters, otherwise it is not needed.
4054
+ * @param {RateLimiterAbstract} [opts.insuranceLimiter] - Backup limiter to use when the primary client fails
4055
+ *
4056
+ * @example
4057
+ * const rateLimiter = new RateLimiterValkeyGlide({
4058
+ * storeClient: glideClient,
4059
+ * points: 5,
4060
+ * duration: 1
4061
+ * });
4062
+ *
4063
+ * @example <caption>With custom Lua function</caption>
4064
+ * const customScript = `local key = KEYS[1]
4065
+ * local pointsToConsume = tonumber(ARGV[1]) or 0
4066
+ * local secDuration = tonumber(ARGV[2]) or 0
4067
+ *
4068
+ * -- Custom implementation
4069
+ * -- ...
4070
+ *
4071
+ * -- Must return exactly two values: [consumed_points, ttl_in_ms]
4072
+ * return {consumed, ttl}`
4073
+ *
4074
+ * const rateLimiter = new RateLimiterValkeyGlide({
4075
+ * storeClient: glideClient,
4076
+ * points: 5,
4077
+ * customFunction: customScript
4078
+ * });
4079
+ *
4080
+ * @example <caption>With insurance limiter</caption>
4081
+ * const rateLimiter = new RateLimiterValkeyGlide({
4082
+ * storeClient: primaryGlideClient,
4083
+ * points: 5,
4084
+ * duration: 2,
4085
+ * insuranceLimiter: new RateLimiterMemory({
4086
+ * points: 5,
4087
+ * duration: 2
4088
+ * })
4089
+ * });
4090
+ *
4091
+ * @description
4092
+ * When providing a custom Lua script via `opts.customFunction`, it must:
4093
+ *
4094
+ * 1. Accept parameters:
4095
+ * - KEYS[1]: The key being rate limited
4096
+ * - ARGV[1]: Points to consume (as string, use tonumber() to convert)
4097
+ * - ARGV[2]: Duration in seconds (as string, use tonumber() to convert)
4098
+ *
4099
+ * 2. Return an array with exactly two elements:
4100
+ * - [0]: Consumed points (number)
4101
+ * - [1]: TTL in milliseconds (number)
4102
+ *
4103
+ * 3. Handle scenarios:
4104
+ * - New key creation: Initialize with expiry for fixed windows
4105
+ * - Key updates: Increment existing counters
4106
+ */
4107
+ constructor(opts) {
4108
+ super(opts);
4109
+ this.client = opts.storeClient;
4110
+ this._scriptLoaded = false;
4111
+ this._getScriptLoaded = false;
4112
+ this._rejectIfValkeyNotReady = !!opts.rejectIfValkeyNotReady;
4113
+ this._luaScript = opts.customFunction || DEFAULT_VALKEY_SCRIPT;
4114
+ this._libraryName = opts.customFunctionLibName || DEFAULT_LIBRARY_NAME;
4115
+ }
4116
+ /**
4117
+ * Ensure scripts are loaded in the Valkey server
4118
+ * @returns {Promise<boolean>} True if scripts are loaded
4119
+ * @private
4120
+ */
4121
+ async _loadScripts() {
4122
+ if (this._scriptLoaded && this._getScriptLoaded) {
4123
+ return true;
4124
+ }
4125
+ if (!this.client) {
4126
+ throw new Error("Valkey client is not set");
4127
+ }
4128
+ const promises = [];
4129
+ if (!this._scriptLoaded) {
4130
+ const script = Buffer.from(`#!lua name=${this._libraryName}
4131
+ local function consume(KEYS, ARGV)
4132
+ ${this._luaScript.trim()}
4133
+ end
4134
+ server.register_function('consume', consume)`);
4135
+ promises.push(this.client.functionLoad(script, { replace: true }));
4136
+ } else promises.push(Promise.resolve(this._libraryName));
4137
+ if (!this._getScriptLoaded) {
4138
+ const script = Buffer.from(`#!lua name=ratelimiter_get
4139
+ local function getValue(KEYS, ARGV)
4140
+ ${GET_VALKEY_SCRIPT.trim()}
4141
+ end
4142
+ server.register_function('getValue', getValue)`);
4143
+ promises.push(this.client.functionLoad(script, { replace: true }));
4144
+ } else promises.push(Promise.resolve("ratelimiter_get"));
4145
+ const results = await Promise.all(promises);
4146
+ this._scriptLoaded = results[0] === this._libraryName;
4147
+ this._getScriptLoaded = results[1] === "ratelimiter_get";
4148
+ if (!this._scriptLoaded || !this._getScriptLoaded) {
4149
+ throw new Error("Valkey connection is not ready, scripts not loaded");
4150
+ }
4151
+ return true;
4152
+ }
4153
+ /**
4154
+ * Update or insert the rate limiter record
4155
+ *
4156
+ * @param {string} rlKey - The rate limiter key
4157
+ * @param {number} pointsToConsume - Points to be consumed
4158
+ * @param {number} msDuration - Duration in milliseconds
4159
+ * @param {boolean} [forceExpire=false] - Whether to force expiration
4160
+ * @param {Object} [options={}] - Additional options
4161
+ * @returns {Promise<Array>} Array containing consumed points and TTL
4162
+ * @private
4163
+ */
4164
+ async _upsert(rlKey, pointsToConsume, msDuration, forceExpire = false, options = {}) {
4165
+ await this._loadScripts();
4166
+ const secDuration = Math.floor(msDuration / 1e3);
4167
+ if (forceExpire) {
4168
+ if (secDuration > 0) {
4169
+ await this.client.set(
4170
+ rlKey,
4171
+ String(pointsToConsume),
4172
+ { expiry: { type: "EX", count: secDuration } }
4173
+ );
4174
+ return [pointsToConsume, secDuration * 1e3];
4175
+ }
4176
+ await this.client.set(rlKey, String(pointsToConsume));
4177
+ return [pointsToConsume, -1];
4178
+ }
4179
+ const result = await this.client.fcall(
4180
+ "consume",
4181
+ [rlKey],
4182
+ [String(pointsToConsume), String(secDuration)]
4183
+ );
4184
+ return result;
4185
+ }
4186
+ /**
4187
+ * Get the rate limiter record
4188
+ *
4189
+ * @param {string} rlKey - The rate limiter key
4190
+ * @param {Object} [options={}] - Additional options
4191
+ * @returns {Promise<Array|null>} Array containing consumed points and TTL, or null if not found
4192
+ * @private
4193
+ */
4194
+ async _get(rlKey, options = {}) {
4195
+ await this._loadScripts();
4196
+ const res = await this.client.fcall("getValue", [rlKey], []);
4197
+ return res.length > 0 ? res : null;
4198
+ }
4199
+ /**
4200
+ * Delete the rate limiter record
4201
+ *
4202
+ * @param {string} rlKey - The rate limiter key
4203
+ * @param {Object} [options={}] - Additional options
4204
+ * @returns {Promise<boolean>} True if successful, false otherwise
4205
+ * @private
4206
+ */
4207
+ async _delete(rlKey, options = {}) {
4208
+ const result = await this.client.del([rlKey]);
4209
+ return result > 0;
4210
+ }
4211
+ /**
4212
+ * Convert raw result to RateLimiterRes object
4213
+ *
4214
+ * @param {string} rlKey - The rate limiter key
4215
+ * @param {number} changedPoints - Points changed in this operation
4216
+ * @param {Array|null} result - Result from Valkey operation
4217
+ * @returns {RateLimiterRes|null} RateLimiterRes object or null if result is null
4218
+ * @private
4219
+ */
4220
+ _getRateLimiterRes(rlKey, changedPoints, result) {
4221
+ if (result === null) {
4222
+ return null;
4223
+ }
4224
+ const res = new RateLimiterRes2();
4225
+ const [consumedPointsStr, pttl] = result;
4226
+ const consumedPoints = Number(consumedPointsStr);
4227
+ res.isFirstInDuration = consumedPoints === changedPoints;
4228
+ res.consumedPoints = consumedPoints;
4229
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
4230
+ res.msBeforeNext = pttl;
4231
+ return res;
4232
+ }
4233
+ /**
4234
+ * Close the rate limiter and release resources
4235
+ * Note: The method won't going to close the Valkey client, as it may be shared with other instances.
4236
+ * @returns {Promise<void>} Promise that resolves when the rate limiter is closed
4237
+ */
4238
+ async close() {
4239
+ if (this._scriptLoaded) {
4240
+ await this.client.functionDelete(this._libraryName);
4241
+ this._scriptLoaded = false;
4242
+ }
4243
+ if (this._getScriptLoaded) {
4244
+ await this.client.functionDelete("ratelimiter_get");
4245
+ this._getScriptLoaded = false;
4246
+ }
4247
+ if (this.insuranceLimiter) {
4248
+ try {
4249
+ await this.insuranceLimiter.close();
4250
+ } catch (e) {
4251
+ }
4252
+ }
4253
+ this.client = null;
4254
+ this._scriptLoaded = false;
4255
+ this._getScriptLoaded = false;
4256
+ this._rejectIfValkeyNotReady = false;
4257
+ this._luaScript = null;
4258
+ this._libraryName = null;
4259
+ this.insuranceLimiter = null;
4260
+ }
4261
+ };
4262
+ module.exports = RateLimiterValkeyGlide;
4263
+ }
4264
+ });
4265
+
4266
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterSQLite.js
4267
+ var require_RateLimiterSQLite = __commonJS({
4268
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterSQLite.js"(exports, module) {
4269
+ "use strict";
4270
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
4271
+ var RateLimiterRes2 = require_RateLimiterRes();
4272
+ var RateLimiterSQLite = class extends RateLimiterStoreAbstract {
4273
+ /**
4274
+ * @callback callback
4275
+ * @param {Object} err
4276
+ *
4277
+ * @param {Object} opts
4278
+ * @param {callback} cb
4279
+ * Defaults {
4280
+ * ... see other in RateLimiterStoreAbstract
4281
+ * storeClient: sqliteClient, // SQLite database instance (sqlite3, better-sqlite3, or knex instance)
4282
+ * storeType: 'sqlite3' | 'better-sqlite3' | 'knex', // Optional, defaults to 'sqlite3'
4283
+ * tableName: 'string',
4284
+ * tableCreated: boolean,
4285
+ * clearExpiredByTimeout: boolean,
4286
+ * }
4287
+ */
4288
+ constructor(opts, cb = null) {
4289
+ super(opts);
4290
+ /**
4291
+ * Internal store type used to determine the SQLite client in use.
4292
+ * It can be one of the following:
4293
+ * - `"sqlite3".
4294
+ * - `"better-sqlite3".
4295
+ *
4296
+ * @type {("sqlite3" | "better-sqlite3" | null)}
4297
+ * @private
4298
+ */
4299
+ __publicField(this, "_internalStoreType", null);
4300
+ this.client = opts.storeClient;
4301
+ this.storeType = opts.storeType || "sqlite3";
4302
+ this.tableName = opts.tableName;
4303
+ this.tableCreated = opts.tableCreated || false;
4304
+ this.clearExpiredByTimeout = opts.clearExpiredByTimeout;
4305
+ this._validateStoreTypes(cb);
4306
+ this._validateStoreClient(cb);
4307
+ this._setInternalStoreType(cb);
4308
+ this._validateTableName(cb);
4309
+ if (!this.tableCreated) {
4310
+ this._createDbAndTable().then(() => {
4311
+ this.tableCreated = true;
4312
+ if (this.clearExpiredByTimeout) this._clearExpiredHourAgo();
4313
+ if (typeof cb === "function") cb();
4314
+ }).catch((err) => {
4315
+ if (typeof cb === "function") cb(err);
4316
+ else throw err;
4317
+ });
4318
+ } else {
4319
+ if (this.clearExpiredByTimeout) this._clearExpiredHourAgo();
4320
+ if (typeof cb === "function") cb();
4321
+ }
4322
+ }
4323
+ _validateStoreTypes(cb) {
4324
+ const validStoreTypes = ["sqlite3", "better-sqlite3", "knex"];
4325
+ if (!validStoreTypes.includes(this.storeType)) {
4326
+ const err = new Error(
4327
+ `storeType must be one of: ${validStoreTypes.join(", ")}`
4328
+ );
4329
+ if (typeof cb === "function") return cb(err);
4330
+ throw err;
4331
+ }
4332
+ }
4333
+ _validateStoreClient(cb) {
4334
+ if (this.storeType === "sqlite3") {
4335
+ if (typeof this.client.run !== "function") {
4336
+ const err = new Error(
4337
+ "storeClient must be an instance of sqlite3.Database when storeType is 'sqlite3' or no storeType was provided"
4338
+ );
4339
+ if (typeof cb === "function") return cb(err);
4340
+ throw err;
4341
+ }
4342
+ } else if (this.storeType === "better-sqlite3") {
4343
+ if (typeof this.client.prepare !== "function" || typeof this.client.run !== "undefined") {
4344
+ const err = new Error(
4345
+ "storeClient must be an instance of better-sqlite3.Database when storeType is 'better-sqlite3'"
4346
+ );
4347
+ if (typeof cb === "function") return cb(err);
4348
+ throw err;
4349
+ }
4350
+ } else if (this.storeType === "knex") {
4351
+ if (typeof this.client.raw !== "function") {
4352
+ const err = new Error(
4353
+ "storeClient must be an instance of Knex when storeType is 'knex'"
4354
+ );
4355
+ if (typeof cb === "function") return cb(err);
4356
+ throw err;
4357
+ }
4358
+ }
4359
+ }
4360
+ _setInternalStoreType(cb) {
4361
+ if (this.storeType === "knex") {
4362
+ const knexClientType = this.client.client.config.client;
4363
+ if (knexClientType === "sqlite3") {
4364
+ this._internalStoreType = "sqlite3";
4365
+ } else if (knexClientType === "better-sqlite3") {
4366
+ this._internalStoreType = "better-sqlite3";
4367
+ } else {
4368
+ const err = new Error(
4369
+ "Knex must be configured with 'sqlite3' or 'better-sqlite3' for RateLimiterSQLite"
4370
+ );
4371
+ if (typeof cb === "function") return cb(err);
4372
+ throw err;
4373
+ }
4374
+ } else {
4375
+ this._internalStoreType = this.storeType;
4376
+ }
4377
+ }
4378
+ _validateTableName(cb) {
4379
+ if (!/^[A-Za-z0-9_]*$/.test(this.tableName)) {
4380
+ const err = new Error("Table name must contain only letters and numbers");
4381
+ if (typeof cb === "function") return cb(err);
4382
+ throw err;
4383
+ }
4384
+ }
4385
+ /**
4386
+ * Acquires the database connection based on the storeType.
4387
+ * @returns {Promise<Object>} The database client or connection
4388
+ */
4389
+ async _getConnection() {
4390
+ if (this.storeType === "knex") {
4391
+ return this.client.client.acquireConnection();
4392
+ }
4393
+ return this.client;
4394
+ }
4395
+ /**
4396
+ * Releases the database connection if necessary.
4397
+ * @param {Object} conn The database client or connection
4398
+ */
4399
+ _releaseConnection(conn) {
4400
+ if (this.storeType === "knex") {
4401
+ this.client.client.releaseConnection(conn);
4402
+ }
4403
+ }
4404
+ async _createDbAndTable() {
4405
+ const conn = await this._getConnection();
4406
+ try {
4407
+ switch (this._internalStoreType) {
4408
+ case "sqlite3":
4409
+ await new Promise((resolve, reject) => {
4410
+ conn.run(
4411
+ this._getCreateTableSQL(),
4412
+ (err) => err ? reject(err) : resolve()
4413
+ );
4414
+ });
4415
+ break;
4416
+ case "better-sqlite3":
4417
+ conn.prepare(this._getCreateTableSQL()).run();
4418
+ break;
4419
+ default:
4420
+ throw new Error("Unsupported internalStoreType");
4421
+ }
4422
+ } finally {
4423
+ this._releaseConnection(conn);
4424
+ }
4425
+ }
4426
+ _getCreateTableSQL() {
4427
+ return `CREATE TABLE IF NOT EXISTS ${this.tableName} (
4428
+ key TEXT PRIMARY KEY,
4429
+ points INTEGER NOT NULL DEFAULT 0,
4430
+ expire INTEGER
4431
+ )`;
4432
+ }
4433
+ _clearExpiredHourAgo() {
4434
+ if (this._clearExpiredTimeoutId) clearTimeout(this._clearExpiredTimeoutId);
4435
+ this._clearExpiredTimeoutId = setTimeout(() => {
4436
+ this.clearExpired(Date.now() - 36e5).then(() => this._clearExpiredHourAgo());
4437
+ }, 3e5);
4438
+ this._clearExpiredTimeoutId.unref();
4439
+ }
4440
+ async clearExpired(nowMs) {
4441
+ const sql = `DELETE FROM ${this.tableName} WHERE expire < ?`;
4442
+ const conn = await this._getConnection();
4443
+ try {
4444
+ switch (this._internalStoreType) {
4445
+ case "sqlite3":
4446
+ await new Promise((resolve, reject) => {
4447
+ conn.run(sql, [nowMs], (err) => err ? reject(err) : resolve());
4448
+ });
4449
+ break;
4450
+ case "better-sqlite3":
4451
+ conn.prepare(sql).run(nowMs);
4452
+ break;
4453
+ default:
4454
+ throw new Error("Unsupported internalStoreType");
4455
+ }
4456
+ } finally {
4457
+ this._releaseConnection(conn);
4458
+ }
4459
+ }
4460
+ _getRateLimiterRes(rlKey, changedPoints, result) {
4461
+ const res = new RateLimiterRes2();
4462
+ res.isFirstInDuration = changedPoints === result.points;
4463
+ res.consumedPoints = res.isFirstInDuration ? changedPoints : result.points;
4464
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
4465
+ res.msBeforeNext = result.expire ? Math.max(result.expire - Date.now(), 0) : -1;
4466
+ return res;
4467
+ }
4468
+ async _upsertTransactionSQLite3(conn, upsertQuery, upsertParams) {
4469
+ return await new Promise((resolve, reject) => {
4470
+ conn.serialize(() => {
4471
+ conn.run("SAVEPOINT rate_limiter_trx;", (err) => {
4472
+ if (err) return reject(err);
4473
+ conn.get(upsertQuery, upsertParams, (err2, row) => {
4474
+ if (err2) {
4475
+ conn.run(
4476
+ "ROLLBACK TO SAVEPOINT rate_limiter_trx;",
4477
+ () => reject(err2)
4478
+ );
4479
+ return;
4480
+ }
4481
+ conn.run("RELEASE SAVEPOINT rate_limiter_trx;", () => resolve(row));
4482
+ });
4483
+ });
4484
+ });
4485
+ });
4486
+ }
4487
+ async _upsertTransactionBetterSQLite3(conn, upsertQuery, upsertParams) {
4488
+ return conn.transaction(
4489
+ () => conn.prepare(upsertQuery).get(...upsertParams)
4490
+ )();
4491
+ }
4492
+ async _upsertTransaction(rlKey, points, msDuration, forceExpire) {
4493
+ const dateNow = Date.now();
4494
+ const newExpire = msDuration > 0 ? dateNow + msDuration : null;
4495
+ const upsertQuery = forceExpire ? `INSERT OR REPLACE INTO ${this.tableName} (key, points, expire) VALUES (?, ?, ?) RETURNING points, expire` : `INSERT INTO ${this.tableName} (key, points, expire)
4496
+ VALUES (?, ?, ?)
4497
+ ON CONFLICT(key) DO UPDATE SET
4498
+ points = CASE WHEN expire IS NULL OR expire > ? THEN points + excluded.points ELSE excluded.points END,
4499
+ expire = CASE WHEN expire IS NULL OR expire > ? THEN expire ELSE excluded.expire END
4500
+ RETURNING points, expire`;
4501
+ const upsertParams = forceExpire ? [rlKey, points, newExpire] : [rlKey, points, newExpire, dateNow, dateNow];
4502
+ const conn = await this._getConnection();
4503
+ try {
4504
+ switch (this._internalStoreType) {
4505
+ case "sqlite3":
4506
+ return this._upsertTransactionSQLite3(
4507
+ conn,
4508
+ upsertQuery,
4509
+ upsertParams
4510
+ );
4511
+ case "better-sqlite3":
4512
+ return this._upsertTransactionBetterSQLite3(
4513
+ conn,
4514
+ upsertQuery,
4515
+ upsertParams
4516
+ );
4517
+ default:
4518
+ throw new Error("Unsupported internalStoreType");
4519
+ }
4520
+ } finally {
4521
+ this._releaseConnection(conn);
4522
+ }
4523
+ }
4524
+ _upsert(rlKey, points, msDuration, forceExpire = false) {
4525
+ if (!this.tableCreated) {
4526
+ return Promise.reject(new Error("Table is not created yet"));
4527
+ }
4528
+ return this._upsertTransaction(rlKey, points, msDuration, forceExpire);
4529
+ }
4530
+ async _get(rlKey) {
4531
+ const sql = `SELECT points, expire FROM ${this.tableName} WHERE key = ? AND (expire > ? OR expire IS NULL)`;
4532
+ const now = Date.now();
4533
+ const conn = await this._getConnection();
4534
+ try {
4535
+ switch (this._internalStoreType) {
4536
+ case "sqlite3":
4537
+ return await new Promise((resolve, reject) => {
4538
+ conn.get(
4539
+ sql,
4540
+ [rlKey, now],
4541
+ (err, row) => err ? reject(err) : resolve(row || null)
4542
+ );
4543
+ });
4544
+ case "better-sqlite3":
4545
+ return conn.prepare(sql).get(rlKey, now) || null;
4546
+ default:
4547
+ throw new Error("Unsupported internalStoreType");
4548
+ }
4549
+ } finally {
4550
+ this._releaseConnection(conn);
4551
+ }
4552
+ }
4553
+ async _delete(rlKey) {
4554
+ if (!this.tableCreated) {
4555
+ return Promise.reject(new Error("Table is not created yet"));
4556
+ }
4557
+ const sql = `DELETE FROM ${this.tableName} WHERE key = ?`;
4558
+ const conn = await this._getConnection();
4559
+ try {
4560
+ switch (this._internalStoreType) {
4561
+ case "sqlite3":
4562
+ return await new Promise((resolve, reject) => {
4563
+ conn.run(sql, [rlKey], function(err) {
4564
+ if (err) reject(err);
4565
+ else resolve(this.changes > 0);
4566
+ });
4567
+ });
4568
+ case "better-sqlite3":
4569
+ const result = conn.prepare(sql).run(rlKey);
4570
+ return result.changes > 0;
4571
+ default:
4572
+ throw new Error("Unsupported internalStoreType");
4573
+ }
4574
+ } finally {
4575
+ this._releaseConnection(conn);
4576
+ }
4577
+ }
4578
+ };
4579
+ module.exports = RateLimiterSQLite;
4580
+ }
4581
+ });
4582
+
4583
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/RateLimiterEtcdTransactionFailedError.js
4584
+ var require_RateLimiterEtcdTransactionFailedError = __commonJS({
4585
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/RateLimiterEtcdTransactionFailedError.js"(exports, module) {
4586
+ "use strict";
4587
+ module.exports = class RateLimiterEtcdTransactionFailedError extends Error {
4588
+ constructor(message) {
4589
+ super();
4590
+ if (Error.captureStackTrace) {
4591
+ Error.captureStackTrace(this, this.constructor);
4592
+ }
4593
+ this.name = "RateLimiterEtcdTransactionFailedError";
4594
+ this.message = message;
4595
+ }
4596
+ };
4597
+ }
4598
+ });
4599
+
4600
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/RateLimiterSetupError.js
4601
+ var require_RateLimiterSetupError = __commonJS({
4602
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/component/RateLimiterSetupError.js"(exports, module) {
4603
+ "use strict";
4604
+ module.exports = class RateLimiterSetupError extends Error {
4605
+ constructor(message) {
4606
+ super();
4607
+ if (Error.captureStackTrace) {
4608
+ Error.captureStackTrace(this, this.constructor);
4609
+ }
4610
+ this.name = "RateLimiterSetupError";
4611
+ this.message = message;
4612
+ }
4613
+ };
4614
+ }
4615
+ });
4616
+
4617
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterEtcdNonAtomic.js
4618
+ var require_RateLimiterEtcdNonAtomic = __commonJS({
4619
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterEtcdNonAtomic.js"(exports, module) {
4620
+ "use strict";
4621
+ var RateLimiterStoreAbstract = require_RateLimiterStoreAbstract();
4622
+ var RateLimiterRes2 = require_RateLimiterRes();
4623
+ var RateLimiterSetupError = require_RateLimiterSetupError();
4624
+ var RateLimiterEtcdNonAtomic = class extends RateLimiterStoreAbstract {
4625
+ /**
4626
+ * @param {Object} opts
4627
+ */
4628
+ constructor(opts) {
4629
+ super(opts);
4630
+ if (!opts.storeClient) {
4631
+ throw new RateLimiterSetupError('You need to set the option "storeClient" to an instance of class "Etcd3".');
4632
+ }
4633
+ this.client = opts.storeClient;
4634
+ }
4635
+ /**
4636
+ * Get RateLimiterRes object filled depending on storeResult, which specific for exact store.
4637
+ */
4638
+ _getRateLimiterRes(rlKey, changedPoints, result) {
4639
+ const res = new RateLimiterRes2();
4640
+ res.isFirstInDuration = changedPoints === result.points;
4641
+ res.consumedPoints = res.isFirstInDuration ? changedPoints : result.points;
4642
+ res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);
4643
+ res.msBeforeNext = result.expire ? Math.max(result.expire - Date.now(), 0) : -1;
4644
+ return res;
4645
+ }
4646
+ /**
4647
+ * Resolve with object used for {@link _getRateLimiterRes} to generate {@link RateLimiterRes}.
4648
+ */
4649
+ async _upsert(rlKey, points, msDuration, forceExpire = false) {
4650
+ const expire = msDuration > 0 ? Date.now() + msDuration : null;
4651
+ let newValue = { points, expire };
4652
+ if (forceExpire) {
4653
+ await this.client.put(rlKey).value(JSON.stringify(newValue));
4654
+ } else {
4655
+ const oldValue = await this._get(rlKey);
4656
+ newValue = { points: (oldValue !== null ? oldValue.points : 0) + points, expire };
4657
+ await this.client.put(rlKey).value(JSON.stringify(newValue));
4658
+ }
4659
+ return newValue;
4660
+ }
4661
+ /**
4662
+ * Resolve with raw result from Store OR null if rlKey is not set
4663
+ * or Reject with error
4664
+ */
4665
+ async _get(rlKey) {
4666
+ return this.client.get(rlKey).string().then((result) => result !== null ? JSON.parse(result) : null);
4667
+ }
4668
+ /**
4669
+ * Resolve with true OR false if rlKey doesn't exist.
4670
+ * or Reject with error.
4671
+ */
4672
+ async _delete(rlKey) {
4673
+ return this.client.delete().key(rlKey).then((result) => result.deleted === "1");
4674
+ }
4675
+ };
4676
+ module.exports = RateLimiterEtcdNonAtomic;
4677
+ }
4678
+ });
4679
+
4680
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterEtcd.js
4681
+ var require_RateLimiterEtcd = __commonJS({
4682
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/lib/RateLimiterEtcd.js"(exports, module) {
4683
+ "use strict";
4684
+ var RateLimiterEtcdTransactionFailedError = require_RateLimiterEtcdTransactionFailedError();
4685
+ var RateLimiterEtcdNonAtomic = require_RateLimiterEtcdNonAtomic();
4686
+ var MAX_TRANSACTION_TRIES = 5;
4687
+ var RateLimiterEtcd = class extends RateLimiterEtcdNonAtomic {
4688
+ /**
4689
+ * Resolve with object used for {@link _getRateLimiterRes} to generate {@link RateLimiterRes}.
4690
+ */
4691
+ async _upsert(rlKey, points, msDuration, forceExpire = false) {
4692
+ const expire = msDuration > 0 ? Date.now() + msDuration : null;
4693
+ let newValue = { points, expire };
4694
+ let oldValue;
4695
+ if (forceExpire) {
4696
+ await this.client.put(rlKey).value(JSON.stringify(newValue));
4697
+ } else {
4698
+ const added = await this.client.if(rlKey, "Version", "===", "0").then(this.client.put(rlKey).value(JSON.stringify(newValue))).commit().then((result) => !!result.succeeded);
4699
+ if (!added) {
4700
+ let success = false;
4701
+ for (let i = 0; i < MAX_TRANSACTION_TRIES; i++) {
4702
+ oldValue = await this._get(rlKey);
4703
+ newValue = { points: oldValue.points + points, expire };
4704
+ success = await this.client.if(rlKey, "Value", "===", JSON.stringify(oldValue)).then(this.client.put(rlKey).value(JSON.stringify(newValue))).commit().then((result) => !!result.succeeded);
4705
+ if (success) {
4706
+ break;
4707
+ }
4708
+ }
4709
+ if (!success) {
4710
+ throw new RateLimiterEtcdTransactionFailedError("Could not set new value in a transaction.");
4711
+ }
4712
+ }
4713
+ }
4714
+ return newValue;
4715
+ }
4716
+ };
4717
+ module.exports = RateLimiterEtcd;
4718
+ }
4719
+ });
4720
+
4721
+ // ../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/index.js
4722
+ var require_rate_limiter_flexible = __commonJS({
4723
+ "../../node_modules/.pnpm/rate-limiter-flexible@11.2.1/node_modules/rate-limiter-flexible/index.js"(exports, module) {
4724
+ "use strict";
4725
+ var RateLimiterRedis = require_RateLimiterRedis();
4726
+ var RateLimiterRedisNonAtomic = require_RateLimiterRedisNonAtomic();
4727
+ var RateLimiterMongo = require_RateLimiterMongo();
4728
+ var RateLimiterMySQL = require_RateLimiterMySQL();
4729
+ var RateLimiterPostgres2 = require_RateLimiterPostgres();
4730
+ var { RateLimiterClusterMaster, RateLimiterClusterMasterPM2, RateLimiterCluster } = require_RateLimiterCluster();
4731
+ var RateLimiterMemory2 = require_RateLimiterMemory();
4732
+ var RateLimiterMemcache = require_RateLimiterMemcache();
4733
+ var RLWrapperBlackAndWhite = require_RLWrapperBlackAndWhite();
4734
+ var RLWrapperTimeouts = require_RLWrapperTimeouts();
4735
+ var RateLimiterUnion = require_RateLimiterUnion();
4736
+ var RateLimiterQueue = require_RateLimiterQueue();
4737
+ var BurstyRateLimiter = require_BurstyRateLimiter();
4738
+ var RateLimiterRes2 = require_RateLimiterRes();
4739
+ var RateLimiterCompatibleAbstract = require_RateLimiterCompatibleAbstract();
4740
+ var RateLimiterDynamo = require_RateLimiterDynamo();
4741
+ var RateLimiterPrisma = require_RateLimiterPrisma();
4742
+ var RateLimiterDrizzle = require_RateLimiterDrizzle();
4743
+ var RateLimiterDrizzleNonAtomic = require_RateLimiterDrizzleNonAtomic();
4744
+ var RateLimiterValkey = require_RateLimiterValkey();
4745
+ var RateLimiterValkeyGlide = require_RateLimiterValkeyGlide();
4746
+ var RateLimiterSQLite = require_RateLimiterSQLite();
4747
+ var RateLimiterEtcd = require_RateLimiterEtcd();
4748
+ var RateLimiterEtcdNonAtomic = require_RateLimiterEtcdNonAtomic();
4749
+ var RateLimiterQueueError = require_RateLimiterQueueError();
4750
+ var RateLimiterEtcdTransactionFailedError = require_RateLimiterEtcdTransactionFailedError();
4751
+ module.exports = {
4752
+ RateLimiterRedis,
4753
+ RateLimiterRedisNonAtomic,
4754
+ RateLimiterMongo,
4755
+ RateLimiterMySQL,
4756
+ RateLimiterPostgres: RateLimiterPostgres2,
4757
+ RateLimiterMemory: RateLimiterMemory2,
4758
+ RateLimiterMemcache,
4759
+ RateLimiterClusterMaster,
4760
+ RateLimiterClusterMasterPM2,
4761
+ RateLimiterCluster,
4762
+ RLWrapperBlackAndWhite,
4763
+ RLWrapperTimeouts,
4764
+ RateLimiterUnion,
4765
+ RateLimiterQueue,
4766
+ BurstyRateLimiter,
4767
+ RateLimiterRes: RateLimiterRes2,
4768
+ RateLimiterCompatibleAbstract,
4769
+ RateLimiterDynamo,
4770
+ RateLimiterPrisma,
4771
+ RateLimiterValkey,
4772
+ RateLimiterValkeyGlide,
4773
+ RateLimiterSQLite,
4774
+ RateLimiterEtcd,
4775
+ RateLimiterDrizzle,
4776
+ RateLimiterDrizzleNonAtomic,
4777
+ RateLimiterEtcdNonAtomic,
4778
+ RateLimiterQueueError,
4779
+ RateLimiterEtcdTransactionFailedError
4780
+ };
4781
+ }
4782
+ });
4783
+
4784
+ // src/rate-limit.ts
4785
+ var import_rate_limiter_flexible = __toESM(require_rate_limiter_flexible(), 1);
4786
+ function memoryRateLimitStore() {
4787
+ return storeOf(async (limit, windowSeconds) => new import_rate_limiter_flexible.RateLimiterMemory({ points: limit, duration: windowSeconds }));
4788
+ }
4789
+ function postgresRateLimitStore(client, options = {}) {
4790
+ const { table = "rate_limits", schema, createTable = true } = options;
4791
+ const storeClient = { query: (q) => client.query(q.text, q.values) };
4792
+ let hits = 0;
4793
+ return storeOf(
4794
+ (limit, windowSeconds) => new Promise((resolve, reject) => {
4795
+ const limiter = new import_rate_limiter_flexible.RateLimiterPostgres(
4796
+ {
4797
+ storeClient,
4798
+ storeType: "pool",
4799
+ tableName: table,
4800
+ schemaName: schema,
4801
+ tableCreated: !createTable,
4802
+ clearExpiredByTimeout: false,
4803
+ points: limit,
4804
+ duration: windowSeconds,
4805
+ insuranceLimiter: new import_rate_limiter_flexible.RateLimiterMemory({ points: limit, duration: windowSeconds })
4806
+ },
4807
+ // Called inside the constructor when the table exists already: resolve once it returned.
4808
+ (error) => error ? reject(error) : queueMicrotask(() => resolve(limiter))
4809
+ );
4810
+ }),
4811
+ (limiter) => {
4812
+ const sweep = limiter;
4813
+ if (++hits % 1e3 === 0) void sweep.clearExpired(Date.now() - 36e5).catch(() => {
4814
+ });
4815
+ }
4816
+ );
4817
+ }
4818
+ function storeOf(make, onHit) {
4819
+ const limiters = /* @__PURE__ */ new Map();
4820
+ return {
4821
+ async hit(key, limit, windowSeconds) {
4822
+ const id = `${limit}/${windowSeconds}`;
4823
+ let pending = limiters.get(id);
4824
+ if (!pending) {
4825
+ limiters.set(id, pending = make(limit, windowSeconds));
4826
+ pending.catch(() => limiters.delete(id));
4827
+ }
4828
+ const limiter = await pending;
4829
+ onHit?.(limiter);
4830
+ try {
4831
+ const res = await limiter.consume(key);
4832
+ return { allowed: true, remaining: res.remainingPoints, resetMs: res.msBeforeNext };
4833
+ } catch (thrown) {
4834
+ if (thrown instanceof import_rate_limiter_flexible.RateLimiterRes) return { allowed: false, remaining: 0, resetMs: thrown.msBeforeNext };
4835
+ throw thrown;
4836
+ }
4837
+ }
4838
+ };
4839
+ }
4840
+ var ADDRESSES = /* @__PURE__ */ Symbol.for("fluixi.clientAddress");
4841
+ var sharedMemory = memoryRateLimitStore();
4842
+ var created = 0;
4843
+ function clientAddressOf(request) {
4844
+ return globalThis[ADDRESSES]?.get(request);
4845
+ }
4846
+ function rateLimit(options) {
4847
+ const { match, methods, limit, window, key = clientAddressOf, store = sharedMemory } = options;
4848
+ const applies = matcher(match);
4849
+ const methodSet = methods && new Set(methods.map((m) => m.toUpperCase()));
4850
+ const bucket = options.name ?? `limit${++created}`;
4851
+ return async (request, next) => {
4852
+ if (methodSet && !methodSet.has(request.method)) return next();
4853
+ if (!applies(request)) return next();
4854
+ const who = await key(request);
4855
+ if (!who) return next();
4856
+ const { allowed, remaining, resetMs } = await store.hit(`${bucket}:${who}`, limit, window);
4857
+ const reset = String(Math.ceil(resetMs / 1e3));
4858
+ const set = (headers) => {
4859
+ headers.set("ratelimit-limit", String(limit));
4860
+ headers.set("ratelimit-remaining", String(remaining));
4861
+ headers.set("ratelimit-reset", reset);
4862
+ };
4863
+ if (!allowed) {
4864
+ const refused = errorResponse(new ApiError(429, "rate_limited", "Too many requests. Try again later."));
4865
+ refused.headers.set("retry-after", reset);
4866
+ set(refused.headers);
4867
+ return refused;
4868
+ }
4869
+ return withHeaders(await next(), set);
4870
+ };
4871
+ }
4872
+ function matcher(match) {
4873
+ if (!match) return () => true;
4874
+ if (typeof match === "function") return match;
4875
+ const exact = new Set(match.filter((p) => !p.endsWith("/*")));
4876
+ const prefixes = match.filter((p) => p.endsWith("/*")).map((p) => p.slice(0, -1));
4877
+ return (request) => {
4878
+ const { pathname } = new URL(request.url);
4879
+ return exact.has(pathname) || prefixes.some((p) => pathname.startsWith(p));
4880
+ };
4881
+ }
4882
+
4883
+ export {
4884
+ memoryRateLimitStore,
4885
+ postgresRateLimitStore,
4886
+ clientAddressOf,
4887
+ rateLimit
4888
+ };