@aomex/rate-limit 0.0.21 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,129 +1,9 @@
1
1
  # @aomex/rate-limit
2
2
 
3
- ## 0.0.21
3
+ ## 0.0.22
4
4
 
5
5
  ### Patch Changes
6
6
 
7
- - Updated dependencies [[`e9996cb`](https://github.com/aomex/aomex/commit/e9996cb33cc0ef70b42147be02fbbe2b4954e022)]:
8
- - @aomex/web@0.0.22
9
- - @aomex/core@0.0.21
10
-
11
- ## 0.0.20
12
-
13
- ### Patch Changes
14
-
15
- - [`5a33ba1`](https://github.com/aomex/aomex/commit/5a33ba1134abafa7d8bf38bd258e30f05473cfaf) Thanks [@geekact](https://github.com/geekact)! - refactor(rate-limit)!: rename option cache to driver
16
-
17
- ## 0.0.19
18
-
19
- ### Patch Changes
20
-
21
- - Updated dependencies [[`a8dbaf3`](https://github.com/aomex/aomex/commit/a8dbaf38524f5a5d58337bc617175115742f9e1a), [`ddcec91`](https://github.com/aomex/aomex/commit/ddcec91803b00f35f7c55964d1a2d97c40a22c6e)]:
22
- - @aomex/web@0.0.21
23
- - @aomex/core@0.0.20
24
-
25
- ## 0.0.18
26
-
27
- ### Patch Changes
28
-
29
- - Updated dependencies []:
30
- - @aomex/core@0.0.19
31
- - @aomex/web@0.0.20
32
-
33
- ## 0.0.17
34
-
35
- ### Patch Changes
36
-
37
- - Updated dependencies []:
38
- - @aomex/core@0.0.18
39
- - @aomex/web@0.0.19
40
-
41
- ## 0.0.16
42
-
43
- ### Patch Changes
44
-
45
- - Updated dependencies []:
46
- - @aomex/core@0.0.17
47
- - @aomex/web@0.0.18
48
-
49
- ## 0.0.15
50
-
51
- ### Patch Changes
52
-
53
- - Updated dependencies [[`216aa79`](https://github.com/aomex/aomex/commit/216aa798bcd2d0856f5fe4028235aa54d4b10922)]:
54
- - @aomex/web@0.0.17
55
- - @aomex/core@0.0.16
56
-
57
- ## 0.0.14
58
-
59
- ### Patch Changes
60
-
61
- - Updated dependencies [[`280359e`](https://github.com/aomex/aomex/commit/280359eb90b71720304cfc212374b6dc4c90236d), [`9881653`](https://github.com/aomex/aomex/commit/988165361439738d27bc29bd0ed5a85c608db5ef), [`15ecd1c`](https://github.com/aomex/aomex/commit/15ecd1c75bc21929f79980b32e63ea46e081cc6a)]:
62
- - @aomex/web@0.0.16
63
- - @aomex/core@0.0.15
64
-
65
- ## 0.0.13
66
-
67
- ### Patch Changes
68
-
69
- - Updated dependencies []:
70
- - @aomex/core@0.0.14
71
- - @aomex/web@0.0.15
72
-
73
- ## 0.0.12
74
-
75
- ### Patch Changes
76
-
77
- - Updated dependencies [[`715cf66`](https://github.com/aomex/aomex/commit/715cf660e3b275b338dcf15c25ba9523cf6fb204)]:
78
- - @aomex/web@0.0.14
79
- - @aomex/core@0.0.13
80
-
81
- ## 0.0.11
82
-
83
- ### Patch Changes
84
-
85
- - Updated dependencies [[`6e63df8`](https://github.com/aomex/aomex/commit/6e63df84d1b32e713aba8c52451e289a72b57bae), [`67acf4f`](https://github.com/aomex/aomex/commit/67acf4f42cd86bf1f0a7c647a5ff779c7cd0fa10)]:
86
- - @aomex/web@0.0.13
87
- - @aomex/core@0.0.12
88
-
89
- ## 0.0.10
90
-
91
- ### Patch Changes
92
-
93
- - Updated dependencies [[`f14eb5f`](https://github.com/aomex/aomex/commit/f14eb5fe7bf06e1e2f64d45e3546c96d6079a2f1), [`7d923cf`](https://github.com/aomex/aomex/commit/7d923cf971b6a23d50113ab104c67041c6489053), [`3c5ad4e`](https://github.com/aomex/aomex/commit/3c5ad4e2f34be7da54c8b63f6fd4b88fd1e593c4), [`6154ee5`](https://github.com/aomex/aomex/commit/6154ee5ed500984f969d4c335ac3ad800c739937), [`92273f9`](https://github.com/aomex/aomex/commit/92273f913e38543f34f41ec5941ff43b6e1caaa9), [`a0fd49e`](https://github.com/aomex/aomex/commit/a0fd49ef276c05f312257521c75887458857bbb7)]:
94
- - @aomex/web@0.0.12
95
- - @aomex/core@0.0.11
96
-
97
- ## 0.0.9
98
-
99
- ### Patch Changes
100
-
101
- - Updated dependencies [[`d9dc050`](https://github.com/aomex/aomex/commit/d9dc050897367353588c4bb778cbafb7607406ab), [`41ae605`](https://github.com/aomex/aomex/commit/41ae6054b2e87c4120f3fcee12302bb3d96f1df3)]:
102
- - @aomex/web@0.0.11
103
- - @aomex/core@0.0.10
104
-
105
- ## 0.0.8
106
-
107
- ### Patch Changes
108
-
109
- - Updated dependencies [[`2439286`](https://github.com/aomex/aomex/commit/2439286e69dcc7211ac280b91dbca5de95cc488b)]:
110
- - @aomex/web@0.0.10
111
- - @aomex/core@0.0.9
112
-
113
- ## 0.0.7
114
-
115
- ### Patch Changes
116
-
117
- - Updated dependencies [[`dcf2f4b`](https://github.com/aomex/aomex/commit/dcf2f4b6a13228d4731e4969e6abff9bef8ef0e2), [`d788ce7`](https://github.com/aomex/aomex/commit/d788ce731af885eae3819683813b2a9502742cea), [`c6fe6cb`](https://github.com/aomex/aomex/commit/c6fe6cb2f21acf74bc06db1509deff4aa35c48b3), [`a2727fb`](https://github.com/aomex/aomex/commit/a2727fb7619341dc3b23736e5dc11cee7d65e0bc), [`4253004`](https://github.com/aomex/aomex/commit/42530043854956a42d16be090b89fbac70e2fa17), [`fc7008e`](https://github.com/aomex/aomex/commit/fc7008e889a55e6a0a268bb77cab5be0f0bd9d30), [`d80df1a`](https://github.com/aomex/aomex/commit/d80df1a07eb92214a9c3c7fa15c629ea1ee88c43)]:
118
- - @aomex/web@0.0.9
119
- - @aomex/core@0.0.8
120
-
121
- ## 0.0.5
122
-
123
- ### Patch Changes
124
-
125
- - [`bbc8dda`](https://github.com/aomex/aomex/commit/bbc8dda9f0876c3402608133085350cc693def6f) Thanks [@geekact](https://github.com/geekact)! - refactor: rename package helper to utility
126
-
127
- - Updated dependencies [[`bbc8dda`](https://github.com/aomex/aomex/commit/bbc8dda9f0876c3402608133085350cc693def6f), [`ceb2d82`](https://github.com/aomex/aomex/commit/ceb2d8269755dca3f79b755224259b8a99bc65d0)]:
128
- - @aomex/core@0.0.6
129
- - @aomex/web@0.0.7
7
+ - Updated dependencies [[`6f7d706`](https://github.com/aomex/aomex/commit/6f7d7066c23711abdd149eb1c9a293ab8c4284a4), [`e21007a`](https://github.com/aomex/aomex/commit/e21007a82cb8eac73e1f696340bbe986d57dc159), [`e7bf93c`](https://github.com/aomex/aomex/commit/e7bf93cee6896c61d0bf3eb0921151dc6c1bc107), [`e21007a`](https://github.com/aomex/aomex/commit/e21007a82cb8eac73e1f696340bbe986d57dc159), [`818e840`](https://github.com/aomex/aomex/commit/818e840d36c7456a863fc071968b246c123c17f5), [`fb6c72d`](https://github.com/aomex/aomex/commit/fb6c72dbb266be4db92a542afe93dfa5d8c7cd41)]:
8
+ - @aomex/core@0.0.22
9
+ - @aomex/web@0.0.23
package/dist/index.d.ts CHANGED
@@ -3,63 +3,48 @@ import { WebContext, WebMiddleware } from '@aomex/web';
3
3
 
4
4
  interface RateLimitOptions {
5
5
  /**
6
- * The database powering the backing rate-limiter package.
6
+ * 存储和共享请求记录。默认值:`MemoryCache`
7
7
  */
8
8
  driver?: Cache;
9
9
  /**
10
- * The length of a single limiting period. This value is expressed
11
- * in milliseconds. Defaults `3600 * 1000`(1 hour)
10
+ * 限速时间周期。默认值:`3600 * 1000`ms
12
11
  */
13
12
  duration?: number;
14
13
  /**
15
- * The maximum amount of requests a client (see the `id` field) may
16
- * make during a limiting period.
17
- *
18
- * @see duration
14
+ * 一个客户端(根据id字段)在一个时间周期内的最大可请求数量
19
15
  */
20
16
  max?: number;
21
17
  /**
22
- * Get the unique-identifier for a request. This defaults to the
23
- * client's IP address. Returning "false" will skip rate-limiting.
18
+ * 请求客户端的身份识别信息,默认使用客户端的IP地址。如果返回`false`,则代表该请求不需要限速
24
19
  */
25
20
  id?: (ctx: WebContext) => string | false;
26
21
  /**
27
- * Whether or not to disable the usage of rate limit headers. Defaults `false`
28
- */
29
- disableHeader?: boolean;
30
- /**
31
- * The message used on the response body if a client is rate-limited. There is
32
- * a default message which includes when they should try again.
22
+ * 被限速(状态码:429)时响应的报错信息
33
23
  */
34
24
  errorMessage?: string;
35
25
  /**
36
- * Whether or not to throw an error upon being rate-limited. This uses
37
- * the `ctx.throw()`.
38
- */
39
- throw?: boolean;
40
- /**
41
- * A relation of header to the header's display name.
26
+ * 相关的响应头部名称。如果传入`false`,则代表不设置
42
27
  */
43
- headers?: {
28
+ headers?: false | {
44
29
  /**
45
- * The amount of requests remaining in the current limiting period.
30
+ * 指定时间段内剩下的请求次数。默认名称:`X-RateLimit-Remaining`
46
31
  */
47
32
  remaining?: string;
48
33
  /**
49
- * The time, expressed as a UNIX epoch timestamp, at which your rate-limit expires.
34
+ * 以UTC秒为单位,限流重置之前的剩余时间。默认名称:`X-RateLimit-Reset`
50
35
  */
51
36
  reset?: string;
52
37
  /**
53
- * The total amount of requests a client may make during a limiting period.
38
+ * 指定时间内允许的最大请求次数。默认名称:`X-RateLimit-Limit`
54
39
  */
55
40
  total?: string;
56
41
  };
57
42
  /**
58
- * If function returns true, middleware exits before limiting
43
+ * 白名单,不做请求频率限制
59
44
  */
60
45
  allowList?: (ctx: WebContext) => boolean | Promise<boolean>;
61
46
  /**
62
- * If function returns true, 403 error is thrown
47
+ * 黑名单,直接抛出`403`状态码
63
48
  */
64
49
  denyList?: (ctx: WebContext) => boolean | Promise<boolean>;
65
50
  }
package/dist/index.js CHANGED
@@ -27,16 +27,10 @@ var rateLimit = (options = {}) => {
27
27
  // 1 hour
28
28
  max = 2500,
29
29
  id: getId = (ctx) => ctx.request.ip,
30
- headers = {},
31
- disableHeader = false,
30
+ headers: headerNames = {},
32
31
  denyList,
33
32
  allowList
34
33
  } = options;
35
- const {
36
- remaining = "X-RateLimit-Remaining",
37
- reset = "X-RateLimit-Reset",
38
- total = "X-RateLimit-Limit"
39
- } = headers;
40
34
  return middleware.web(async (ctx, next) => {
41
35
  if (denyList && await denyList(ctx)) {
42
36
  ctx.throw(403);
@@ -47,29 +41,27 @@ var rateLimit = (options = {}) => {
47
41
  }
48
42
  const { response } = ctx;
49
43
  const state = await getState(cache, id, max, duration);
50
- let headers2 = {};
51
- if (!disableHeader) {
52
- headers2 = {
44
+ let headers = {};
45
+ if (headerNames !== false) {
46
+ const {
47
+ remaining = "X-RateLimit-Remaining",
48
+ reset = "X-RateLimit-Reset",
49
+ total = "X-RateLimit-Limit"
50
+ } = headerNames;
51
+ headers = {
53
52
  [remaining]: state.current > 0 ? state.current - 1 : 0,
54
53
  [reset]: state.reset,
55
54
  [total]: state.total
56
55
  };
57
- response.setHeaders(headers2);
56
+ response.setHeaders(headers);
58
57
  }
59
58
  if (state.current)
60
59
  return next();
61
60
  const now = Date.now();
62
61
  const delta = Math.round(state.reset * 1e3 - now);
63
- const after = Math.round(state.reset - now / 1e3);
64
- const status = 429;
65
62
  const body = options.errorMessage || `Rate limit exceeded, retry in ${ms(delta, { long: true })}.`;
66
- response.setHeader("Retry-After", after);
67
- response.statusCode = status;
68
- if (options.throw) {
69
- ctx.throw(status, body, { headers: headers2 });
70
- } else {
71
- ctx.send(body);
72
- }
63
+ headers["Retry-After"] = Math.round(state.reset - now / 1e3);
64
+ ctx.throw(429, body, { headers });
73
65
  });
74
66
  };
75
67
  export {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { middleware, Cache, MemoryCache } from '@aomex/core';\nimport type { WebContext, WebMiddleware } from '@aomex/web';\nimport microtime from 'microtime';\nimport ms from 'ms';\n\nexport interface RateLimitOptions {\n /**\n * The database powering the backing rate-limiter package.\n */\n driver?: Cache;\n\n /**\n * The length of a single limiting period. This value is expressed\n * in milliseconds. Defaults `3600 * 1000`(1 hour)\n */\n duration?: number;\n\n /**\n * The maximum amount of requests a client (see the `id` field) may\n * make during a limiting period.\n *\n * @see duration\n */\n max?: number;\n\n /**\n * Get the unique-identifier for a request. This defaults to the\n * client's IP address. Returning \"false\" will skip rate-limiting.\n */\n id?: (ctx: WebContext) => string | false;\n\n /**\n * Whether or not to disable the usage of rate limit headers. Defaults `false`\n */\n disableHeader?: boolean;\n\n /**\n * The message used on the response body if a client is rate-limited. There is\n * a default message which includes when they should try again.\n */\n errorMessage?: string;\n\n /**\n * Whether or not to throw an error upon being rate-limited. This uses\n * the `ctx.throw()`.\n */\n throw?: boolean;\n\n /**\n * A relation of header to the header's display name.\n */\n headers?: {\n /**\n * The amount of requests remaining in the current limiting period.\n */\n remaining?: string;\n\n /**\n * The time, expressed as a UNIX epoch timestamp, at which your rate-limit expires.\n */\n reset?: string;\n\n /**\n * The total amount of requests a client may make during a limiting period.\n */\n total?: string;\n };\n\n /**\n * If function returns true, middleware exits before limiting\n */\n allowList?: (ctx: WebContext) => boolean | Promise<boolean>;\n\n /**\n * If function returns true, 403 error is thrown\n */\n denyList?: (ctx: WebContext) => boolean | Promise<boolean>;\n}\n\ninterface LimitState {\n id: string;\n reset: number;\n current: number;\n total: number;\n}\n\nconst getState = async (\n cache: Cache,\n id: string,\n max: number,\n duration: number,\n) => {\n const key = `ratelimit:${id}`;\n let state = await cache.get<LimitState>(key);\n const now = microtime.now();\n const expired = state && state.reset * 1e6 < now;\n\n if (!state || expired) {\n state = {\n id,\n reset: (now + duration * 1e3) / 1e6,\n current: max,\n total: max,\n };\n } else {\n state.current = state.current > 0 ? state.current - 1 : 0;\n }\n\n await cache.set(key, state);\n return state!;\n};\n\nexport const rateLimit = (options: RateLimitOptions = {}): WebMiddleware => {\n const {\n driver: cache = new MemoryCache(),\n duration = 3600 * 1000, // 1 hour\n max = 2500,\n id: getId = (ctx) => ctx.request.ip,\n headers = {},\n disableHeader = false,\n denyList,\n allowList,\n } = options;\n\n const {\n remaining = 'X-RateLimit-Remaining',\n reset = 'X-RateLimit-Reset',\n total = 'X-RateLimit-Limit',\n } = headers;\n\n return middleware.web(async (ctx, next) => {\n if (denyList && (await denyList(ctx))) {\n ctx.throw(403);\n }\n\n const id = getId(ctx);\n if (id === false || (allowList && (await allowList(ctx)))) {\n return next();\n }\n\n const { response } = ctx;\n const state = await getState(cache, id, max, duration);\n let headers: Record<string, number> = {};\n if (!disableHeader) {\n headers = {\n [remaining]: state.current > 0 ? state.current - 1 : 0,\n [reset]: state.reset,\n [total]: state.total,\n };\n response.setHeaders(headers);\n }\n\n if (state.current) return next();\n\n const now = Date.now();\n const delta = Math.round(state.reset * 1e3 - now);\n const after = Math.round(state.reset - now / 1e3);\n const status = 429;\n const body =\n options.errorMessage ||\n `Rate limit exceeded, retry in ${ms(delta, { long: true })}.`;\n\n response.setHeader('Retry-After', after);\n response.statusCode = status;\n\n if (options.throw) {\n ctx.throw(status, body, { headers });\n } else {\n ctx.send(body);\n }\n });\n};\n"],"mappings":";AAAA,SAAS,YAAmB,mBAAmB;AAE/C,OAAO,eAAe;AACtB,OAAO,QAAQ;AAmFf,IAAM,WAAW,OACf,OACA,IACA,KACA,aACG;AACH,QAAM,MAAM,aAAa;AACzB,MAAI,QAAQ,MAAM,MAAM,IAAgB,GAAG;AAC3C,QAAM,MAAM,UAAU,IAAI;AAC1B,QAAM,UAAU,SAAS,MAAM,QAAQ,MAAM;AAE7C,MAAI,CAAC,SAAS,SAAS;AACrB,YAAQ;AAAA,MACN;AAAA,MACA,QAAQ,MAAM,WAAW,OAAO;AAAA,MAChC,SAAS;AAAA,MACT,OAAO;AAAA,IACT;AAAA,EACF,OAAO;AACL,UAAM,UAAU,MAAM,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,EAC1D;AAEA,QAAM,MAAM,IAAI,KAAK,KAAK;AAC1B,SAAO;AACT;AAEO,IAAM,YAAY,CAAC,UAA4B,CAAC,MAAqB;AAC1E,QAAM;AAAA,IACJ,QAAQ,QAAQ,IAAI,YAAY;AAAA,IAChC,WAAW,OAAO;AAAA;AAAA,IAClB,MAAM;AAAA,IACN,IAAI,QAAQ,CAAC,QAAQ,IAAI,QAAQ;AAAA,IACjC,UAAU,CAAC;AAA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ts"],"sourcesContent":["import { middleware, Cache, MemoryCache } from '@aomex/core';\nimport type { WebContext, WebMiddleware } from '@aomex/web';\nimport microtime from 'microtime';\nimport ms from 'ms';\n\nexport interface RateLimitOptions {\n /**\n * 存储和共享请求记录。默认值:`MemoryCache`\n */\n driver?: Cache;\n\n /**\n * 限速时间周期。默认值:`3600 * 1000`ms\n */\n duration?: number;\n\n /**\n * 一个客户端(根据id字段)在一个时间周期内的最大可请求数量\n */\n max?: number;\n\n /**\n * 请求客户端的身份识别信息,默认使用客户端的IP地址。如果返回`false`,则代表该请求不需要限速\n */\n id?: (ctx: WebContext) => string | false;\n\n /**\n * 被限速(状态码:429)时响应的报错信息\n */\n errorMessage?: string;\n\n /**\n * 相关的响应头部名称。如果传入`false`,则代表不设置\n */\n headers?:\n | false\n | {\n /**\n * 指定时间段内剩下的请求次数。默认名称:`X-RateLimit-Remaining`\n */\n remaining?: string;\n\n /**\n * 以UTC秒为单位,限流重置之前的剩余时间。默认名称:`X-RateLimit-Reset`\n */\n reset?: string;\n\n /**\n * 指定时间内允许的最大请求次数。默认名称:`X-RateLimit-Limit`\n */\n total?: string;\n };\n\n /**\n * 白名单,不做请求频率限制\n */\n allowList?: (ctx: WebContext) => boolean | Promise<boolean>;\n\n /**\n * 黑名单,直接抛出`403`状态码\n */\n denyList?: (ctx: WebContext) => boolean | Promise<boolean>;\n}\n\ninterface LimitState {\n id: string;\n reset: number;\n current: number;\n total: number;\n}\n\nconst getState = async (\n cache: Cache,\n id: string,\n max: number,\n duration: number,\n) => {\n const key = `ratelimit:${id}`;\n let state = await cache.get<LimitState>(key);\n const now = microtime.now();\n const expired = state && state.reset * 1e6 < now;\n\n if (!state || expired) {\n state = {\n id,\n reset: (now + duration * 1e3) / 1e6,\n current: max,\n total: max,\n };\n } else {\n state.current = state.current > 0 ? state.current - 1 : 0;\n }\n\n await cache.set(key, state);\n return state!;\n};\n\nexport const rateLimit = (options: RateLimitOptions = {}): WebMiddleware => {\n const {\n driver: cache = new MemoryCache(),\n duration = 3600 * 1000, // 1 hour\n max = 2500,\n id: getId = (ctx) => ctx.request.ip,\n headers: headerNames = {},\n denyList,\n allowList,\n } = options;\n\n return middleware.web(async (ctx, next) => {\n if (denyList && (await denyList(ctx))) {\n ctx.throw(403);\n }\n\n const id = getId(ctx);\n if (id === false || (allowList && (await allowList(ctx)))) {\n return next();\n }\n\n const { response } = ctx;\n const state = await getState(cache, id, max, duration);\n let headers: Record<string, number> = {};\n if (headerNames !== false) {\n const {\n remaining = 'X-RateLimit-Remaining',\n reset = 'X-RateLimit-Reset',\n total = 'X-RateLimit-Limit',\n } = headerNames;\n\n headers = {\n [remaining]: state.current > 0 ? state.current - 1 : 0,\n [reset]: state.reset,\n [total]: state.total,\n };\n response.setHeaders(headers);\n }\n\n if (state.current) return next();\n\n const now = Date.now();\n const delta = Math.round(state.reset * 1e3 - now);\n const body =\n options.errorMessage ||\n `Rate limit exceeded, retry in ${ms(delta, { long: true })}.`;\n\n headers['Retry-After'] = Math.round(state.reset - now / 1e3);\n ctx.throw(429, body, { headers });\n });\n};\n"],"mappings":";AAAA,SAAS,YAAmB,mBAAmB;AAE/C,OAAO,eAAe;AACtB,OAAO,QAAQ;AAoEf,IAAM,WAAW,OACf,OACA,IACA,KACA,aACG;AACH,QAAM,MAAM,aAAa,EAAE;AAC3B,MAAI,QAAQ,MAAM,MAAM,IAAgB,GAAG;AAC3C,QAAM,MAAM,UAAU,IAAI;AAC1B,QAAM,UAAU,SAAS,MAAM,QAAQ,MAAM;AAE7C,MAAI,CAAC,SAAS,SAAS;AACrB,YAAQ;AAAA,MACN;AAAA,MACA,QAAQ,MAAM,WAAW,OAAO;AAAA,MAChC,SAAS;AAAA,MACT,OAAO;AAAA,IACT;AAAA,EACF,OAAO;AACL,UAAM,UAAU,MAAM,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,EAC1D;AAEA,QAAM,MAAM,IAAI,KAAK,KAAK;AAC1B,SAAO;AACT;AAEO,IAAM,YAAY,CA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AAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aomex/rate-limit",
3
- "version": "0.0.21",
3
+ "version": "0.0.22",
4
4
  "description": "Web request rate limit",
5
5
  "repository": "git@github.com:aomex/aomex.git",
6
6
  "homepage": "https://aomex.js.org",
@@ -26,17 +26,16 @@
26
26
  "access": "public"
27
27
  },
28
28
  "peerDependencies": {
29
- "@aomex/core": "^0.0.21",
30
- "@aomex/web": "^0.0.22"
29
+ "@aomex/core": "^0.0.22",
30
+ "@aomex/web": "^0.0.23"
31
31
  },
32
32
  "dependencies": {
33
33
  "microtime": "^3.1.1",
34
34
  "ms": "^2.1.3"
35
35
  },
36
36
  "devDependencies": {
37
- "@aomex/core": "^0.0.21",
38
- "@aomex/utility": "^0.0.7",
39
- "@aomex/web": "^0.0.22",
37
+ "@aomex/core": "^0.0.22",
38
+ "@aomex/web": "^0.0.23",
40
39
  "@types/microtime": "^2.1.0",
41
40
  "@types/ms": "^0.7.31"
42
41
  },