@vite-hub/rate-limit 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +18 -14
  2. package/dist/cli-szm60zN5.d.ts +163 -0
  3. package/dist/cli.d.ts +1 -1
  4. package/dist/cli.js +12 -26
  5. package/dist/{cloudflare-DUDRACVB.js → cloudflare-otBvOPv4.js} +5 -4
  6. package/dist/{counters-pKORpgGd.d.ts → counters-DXpF67J_.d.ts} +3 -3
  7. package/dist/{counters-wdEMxDEY.js → counters-DgVdHwdL.js} +13 -6
  8. package/dist/dev-peer-CHafxbtj.js +238 -0
  9. package/dist/drivers/cloudflare.d.ts +1 -1
  10. package/dist/drivers/cloudflare.js +1 -1
  11. package/dist/drivers/kv.d.ts +2 -0
  12. package/dist/drivers/kv.js +92 -0
  13. package/dist/drivers/memory.d.ts +1 -1
  14. package/dist/drivers/memory.js +5 -5
  15. package/dist/durability.d.ts +12 -0
  16. package/dist/durability.js +35 -0
  17. package/dist/error-diagnostics-MgAnhRTP.js +234 -0
  18. package/dist/index.d.ts +16 -7
  19. package/dist/index.js +108 -38
  20. package/dist/{inspect-D-FzyM_x.js → inspect-B6gTdgy9.js} +7 -1
  21. package/dist/kv-C1wpLulE.d.ts +29 -0
  22. package/dist/{limiter-DBrMI4vi.js → kv-provider-C1S6dRTR.js} +16 -9
  23. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  24. package/dist/operations-BYRa7wpx.js +1355 -0
  25. package/dist/{operations-Bu-xulNd.js → operations-CLI9w3rO.js} +9 -14
  26. package/dist/operations.d.ts +9 -4
  27. package/dist/operations.js +51 -23
  28. package/dist/runtime.d.ts +21 -3
  29. package/dist/runtime.js +2 -2
  30. package/dist/state-BU-zcLNY.js +89 -0
  31. package/dist/{types-CQEJpgtz.d.ts → types-CMyR1JeW.d.ts} +43 -23
  32. package/dist/vite.d.ts +131 -21
  33. package/dist/vite.js +349 -2479
  34. package/package.json +21 -17
  35. package/dist/cli-Cniq99iX.d.ts +0 -85
  36. package/dist/error-diagnostics-CTAC_bbr.js +0 -56
  37. package/dist/h3-v1-request-qoGwJr5-.js +0 -235
  38. package/dist/operations-B09NnEjT.js +0 -1438
  39. package/dist/state-Ct7zR8fD.js +0 -43
@@ -0,0 +1,234 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ const rateLimitErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: "https://vitehub.dev/docs/rate-limit/diagnostics",
6
+ codes: {
7
+ RATE_LIMIT_OPERATION_FAILED: {
8
+ why: "The Rate Limit operation failed.",
9
+ fix: "Read `error.cause` for the driver error. Check that the store of the Rate Limit is reachable, then retry."
10
+ },
11
+ RATE_LIMIT_R0001: {
12
+ ...dynamicError,
13
+ fix: "Call `requireRateLimit()` or `checkRateLimit()` at the place that the message names with a static string ID and an object literal of static `limit`, `window`, `enforcement`, and `failure` options, without spreads. `key` can stay a runtime value."
14
+ },
15
+ RATE_LIMIT_R0002: {
16
+ ...dynamicError,
17
+ fix: "Fix the syntax error in the file that the message names, so that ViteHub can read its Rate Limits."
18
+ },
19
+ RATE_LIMIT_R0003: {
20
+ ...dynamicError,
21
+ fix: "Give the files that the message lists the same `limit`, `window`, `enforcement`, and `failure` for this Rate Limit ID, or use a different ID for each policy."
22
+ },
23
+ RATE_LIMIT_R0004: {
24
+ ...dynamicError,
25
+ fix: "Pass `cloudflareRateLimitDriver({ binding })` the Rate Limiting binding from the Worker `env`, the object that has a `limit()` method."
26
+ },
27
+ RATE_LIMIT_R0005: {
28
+ ...dynamicError,
29
+ fix: "Read `error.cause` for the error of the Cloudflare Rate Limiting binding and check the `ratelimits` binding of the Worker. A retry can help when Cloudflare had a short outage."
30
+ },
31
+ RATE_LIMIT_R0006: {
32
+ ...dynamicError,
33
+ fix: "Check that the binding that you pass to `cloudflareRateLimitDriver()` is a Cloudflare Rate Limiting binding, whose `limit()` returns `{ success }`."
34
+ },
35
+ RATE_LIMIT_R0007: {
36
+ ...dynamicError,
37
+ fix: "Set `maxEntries` of `memoryRateLimitDriver()` to a whole number of 1 or more, or remove it to keep 100000."
38
+ },
39
+ RATE_LIMIT_R0008: {
40
+ ...dynamicError,
41
+ fix: "Set a larger `maxEntries` in `memoryRateLimitDriver()`, or use the `kv` driver, which keeps its counters out of process memory."
42
+ },
43
+ RATE_LIMIT_R0009: {
44
+ ...dynamicError,
45
+ fix: "Build the app for the Cloudflare host, so that the build adds the Rate Limiting bindings to the Wrangler config, and deploy the Worker with that config."
46
+ },
47
+ RATE_LIMIT_R0010: {
48
+ ...dynamicError,
49
+ fix: "Pass a non-empty static string ID, such as `\"image-upload\"`, as the second argument of `requireRateLimit()` or `checkRateLimit()`."
50
+ },
51
+ RATE_LIMIT_R0011: {
52
+ ...dynamicError,
53
+ fix: "Pass only `key`, `limit`, `window`, `enforcement`, and `failure` in the options of `checkRateLimit()`. `requireRateLimit()` also accepts `message` and `code`."
54
+ },
55
+ RATE_LIMIT_R0012: {
56
+ ...dynamicError,
57
+ fix: "Pass `key` as a non-empty string, such as the user ID, or remove `key` to limit by the client address."
58
+ },
59
+ RATE_LIMIT_R0013: {
60
+ ...dynamicError,
61
+ fix: "Pass `key`, such as the user or tenant ID, to `requireRateLimit()` or `checkRateLimit()` when the request has no client address."
62
+ },
63
+ RATE_LIMIT_R0015: {
64
+ ...dynamicError,
65
+ fix: "Remove `enforcement: \"strict\"` from this Rate Limit to use the Cloudflare binding, or use the `kv` driver for strict counts."
66
+ },
67
+ RATE_LIMIT_R0016: {
68
+ ...dynamicError,
69
+ fix: "Set `window` of this Rate Limit to \"10s\" or \"1m\" to use the Cloudflare binding, or use the `kv` driver for other windows."
70
+ },
71
+ RATE_LIMIT_R0019: {
72
+ ...dynamicError,
73
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: add `capabilities` with `enforcement`, `scope`, and `rejectedAttempts`."
74
+ },
75
+ RATE_LIMIT_R0020: {
76
+ ...dynamicError,
77
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: set `capabilities.enforcement` to \"best-effort\" or \"strict\"."
78
+ },
79
+ RATE_LIMIT_R0021: {
80
+ ...dynamicError,
81
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: set `capabilities.scope` to \"process\", \"location\", or \"global\"."
82
+ },
83
+ RATE_LIMIT_R0022: {
84
+ ...dynamicError,
85
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: set `capabilities.rejectedAttempts` to \"counted\", \"not-counted\", or \"unknown\"."
86
+ },
87
+ RATE_LIMIT_R0023: {
88
+ ...dynamicError,
89
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: list `capabilities.windows` as an array of whole numbers of milliseconds, or remove it to accept every window."
90
+ },
91
+ RATE_LIMIT_R0024: {
92
+ ...dynamicError,
93
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `remaining`, `retryAfter`, and `used` from `consume()` as whole numbers of 0 or more, or leave them out."
94
+ },
95
+ RATE_LIMIT_R0025: {
96
+ ...dynamicError,
97
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, { allowed }]` from `consume()`, with `allowed` as a boolean."
98
+ },
99
+ RATE_LIMIT_R0026: {
100
+ ...dynamicError,
101
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `resetAt` from `consume()` as a Unix timestamp in milliseconds, or leave it out."
102
+ },
103
+ RATE_LIMIT_R0027: {
104
+ ...dynamicError,
105
+ fix: "Remove `enforcement: \"strict\"` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()`, or use a driver with strict enforcement, such as the memory or kv driver."
106
+ },
107
+ RATE_LIMIT_R0028: {
108
+ ...dynamicError,
109
+ fix: "Set `window` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to one of the windows that the message lists, or use a driver without a window limit."
110
+ },
111
+ RATE_LIMIT_R0029: {
112
+ ...dynamicError,
113
+ fix: "Pass `createRateLimiter()` a plain object with a `driver`, such as `memoryRateLimitDriver()`, and the `limit` and `window` of the policy."
114
+ },
115
+ RATE_LIMIT_R0030: {
116
+ ...dynamicError,
117
+ fix: "Pass `consume({ key })` a non-empty string `key`, such as the user ID or the client address."
118
+ },
119
+ RATE_LIMIT_R0031: {
120
+ ...dynamicError,
121
+ fix: "Set `window` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to a duration string such as \"10s\", \"1m\", \"1h\", or \"1d\"."
122
+ },
123
+ RATE_LIMIT_R0032: {
124
+ ...dynamicError,
125
+ fix: "Set `window` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to a duration greater than zero and shorter than 100000000 days."
126
+ },
127
+ RATE_LIMIT_R0033: {
128
+ ...dynamicError,
129
+ fix: "Pass the Rate Limit policy as an object with `limit` and `window`, such as `{ limit: 10, window: \"1m\" }`."
130
+ },
131
+ RATE_LIMIT_R0034: {
132
+ ...dynamicError,
133
+ fix: "Set `limit` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to a whole number of 1 or more."
134
+ },
135
+ RATE_LIMIT_R0035: {
136
+ ...dynamicError,
137
+ fix: "Set `enforcement` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to \"best-effort\" or \"strict\", or remove it."
138
+ },
139
+ RATE_LIMIT_R0036: {
140
+ ...dynamicError,
141
+ fix: "Set `failure` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to \"allow\" or \"deny\", or remove it."
142
+ },
143
+ RATE_LIMIT_R0037: {
144
+ ...dynamicError,
145
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, { used }]` from `peek()`, with `used` as a whole number of 0 or more and an optional `resetAt` in milliseconds."
146
+ },
147
+ RATE_LIMIT_R0038: {
148
+ ...dynamicError,
149
+ fix: "Pass `peek({ key })` or `reset({ key })` a non-empty string `key`."
150
+ },
151
+ RATE_LIMIT_R0039: {
152
+ ...dynamicError,
153
+ fix: "Pass `peekRateLimit(id, key)` or `resetRateLimit(id, key)` the stable ID of a `requireRateLimit()` call and a non-empty key."
154
+ },
155
+ RATE_LIMIT_R0040: {
156
+ ...dynamicError,
157
+ fix: "Run `vitehub rate-limit peek <id> <key>` or `vitehub rate-limit reset <id> <key>` with only the options that `--help` lists. Put `--` before a key that starts with a dash."
158
+ },
159
+ RATE_LIMIT_R0041: {
160
+ ...dynamicError,
161
+ fix: "Pass `--timeout` as a whole number of milliseconds from 1 to 2147483647, such as `--timeout 5000`."
162
+ },
163
+ RATE_LIMIT_R0042: {
164
+ ...dynamicError,
165
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, undefined]` from `reset()`, or `[error, undefined]` for an outage."
166
+ },
167
+ RATE_LIMIT_R0043: {
168
+ ...dynamicError,
169
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, result]` from `peek()`, or `[error, undefined]` for an outage."
170
+ },
171
+ RATE_LIMIT_R0044: {
172
+ ...dynamicError,
173
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, result]` from `consume()`, or `[error, undefined]` for an outage."
174
+ },
175
+ RATE_LIMIT_R0045: {
176
+ ...dynamicError,
177
+ fix: "Use a shorter `window` in the Rate Limit policy. With `memoryRateLimitDriver({ now })`, return the current time in milliseconds from `now`."
178
+ },
179
+ RATE_LIMIT_R0046: {
180
+ ...dynamicError,
181
+ fix: "Pass `kv` or `kv.store(name)` from `@vite-hub/kv` as the `storage` option to `kvRateLimitDriver()`."
182
+ },
183
+ RATE_LIMIT_R0047: {
184
+ ...dynamicError,
185
+ fix: "Enable KV in the app and build again. For a custom runtime, pass the KV driver, storage, and store name to `setRateLimitRuntimeConfig()`."
186
+ },
187
+ RATE_LIMIT_B0001: {
188
+ ...dynamicError,
189
+ fix: "Set `rateLimit: { namespace }` in `vitehub()`, or `namespace` in `hubRateLimit()`, to a name that is different for each Worker and environment, such as `\"acme-api-production\"`."
190
+ },
191
+ RATE_LIMIT_B0002: {
192
+ ...dynamicError,
193
+ fix: "Set `driver: \"kv\"` in `hubRateLimit()` with a Redis or Upstash KV store, or call `createRateLimiter()` with your own driver."
194
+ },
195
+ RATE_LIMIT_B0003: {
196
+ ...dynamicError,
197
+ fix: "Set `driver` in `hubRateLimit()` to `\"cloudflare\"` or `\"kv\"`, or to `\"memory\"` only for a deploy with one server process."
198
+ },
199
+ RATE_LIMIT_B0004: {
200
+ ...dynamicError,
201
+ fix: "Write every file that declares a Rate Limit before `vite build` starts. Do not create or change these files from a plugin during the build."
202
+ },
203
+ RATE_LIMIT_KV_RUNTIME_STORE_UNSUPPORTED: {
204
+ ...dynamicError,
205
+ fix: "Use a KV driver that every server process shares: Redis, a Postgres Database, or Upstash. To count in the memory of each process instead, pass `memoryFallback: true` to `setRateLimitRuntimeConfig()`."
206
+ },
207
+ RATE_LIMIT_KV_STORE_UNSUPPORTED: {
208
+ ...dynamicError,
209
+ fix: "Use a KV driver that every server process shares: `kv: { driver: 'redis' }`, a Postgres Database, or Upstash. Or remove `driver: 'kv'` to let ViteHub choose."
210
+ },
211
+ RATE_LIMIT_KV_TIMEOUT: {
212
+ why: "The KV store did not answer the Rate Limit within 1000 milliseconds.",
213
+ fix: "Check that the KV store of the Rate Limit is reachable and not overloaded, then retry. Until it answers, `consume()` applies the `failure` policy of the Rate Limit."
214
+ },
215
+ RATE_LIMIT_MEMORY_PER_PROCESS: {
216
+ why: "Rate Limit counts requests in the memory of each server process. With several instances, each one allows the full limit.",
217
+ fix: "Enable KV on Node so that ViteHub selects the kv driver, or set `rateLimit.driver` to \"kv\" and configure a Redis KV store or a Postgres Database. Keep `memory` only for one server process."
218
+ },
219
+ RATE_LIMIT_MEMORY_STRICT_UNSUPPORTED: {
220
+ ...dynamicError,
221
+ fix: "Count in a shared store: on Node, set `rateLimit: { driver: 'kv' }` with a Redis or Postgres KV store. Or set `enforcement: 'best-effort'` on the Rate Limit."
222
+ },
223
+ RATE_LIMIT_REFUSAL_OPTION_INVALID: {
224
+ ...dynamicError,
225
+ fix: "Pass `message` and `code` of `requireRateLimit()` as non-empty strings, such as `message: \"Too many tries. Wait a minute.\"`, or remove them to use the default `429` error."
226
+ },
227
+ RATE_LIMIT_RENAMED_PROVIDER_KEY: {
228
+ why: ({ value }) => `\`rateLimit.provider\` is ${value}. ViteHub renamed this key to \`driver\`, and it does not read \`provider\`, so Rate Limit would not use the driver you chose.`,
229
+ fix: ({ value }) => `Set \`rateLimit: { driver: ${value} }\`, or run \`npx @vite-hub/codemods driver-key\` to rename it in every config file.`
230
+ }
231
+ }
232
+ });
233
+ //#endregion
234
+ export { rateLimitErrorDiagnostics as t };
package/dist/index.d.ts CHANGED
@@ -1,15 +1,24 @@
1
- import { C as RateLimitRuntimeConfig, D as ResolvedRateLimitPolicy, E as RequireRateLimitOptions, S as RateLimitResetResult, T as RateLimiter, _ as RateLimitPeekResult, a as RateLimitDeclaration, b as RateLimitRejectedAttemptBehavior, c as RateLimitDriverInput, d as RateLimitDriverPeekResult, f as RateLimitDriverResetOutcome, g as RateLimitModuleOptions, h as RateLimitFailurePolicy, i as RateLimitDecision, l as RateLimitDriverOutcome, m as RateLimitEnforcement, n as RateLimitConsumeInput, o as RateLimitDriver, p as RateLimitDriverResult, r as RateLimitCounterScope, s as RateLimitDriverCapabilities, t as CreateRateLimiterOptions, u as RateLimitDriverPeekOutcome, v as RateLimitPolicy, w as RateLimitWindow, x as RateLimitRequestEvent, y as RateLimitProvider } from "./types-CQEJpgtz.js";
2
- import { a as resetRateLimit, i as peekRateLimit, n as RateLimitPeekInspection, r as RateLimitResetInspection, t as RateLimitCounterSnapshot } from "./counters-pKORpgGd.js";
1
+ import { A as ResolvedRateLimitPolicy, C as RateLimitRequest, D as RateLimitWindow, E as RateLimitRuntimeConfig, O as RateLimiter, S as RateLimitRejectedAttemptBehavior, T as RateLimitResetResult, _ as RateLimitEnforcement, a as RateLimitCounterScope, b as RateLimitPeekResult, c as RateLimitDriver, d as RateLimitDriverName, f as RateLimitDriverOutcome, g as RateLimitDriverResult, h as RateLimitDriverResetOutcome, i as RateLimitConsumeInput, k as RequireRateLimitOptions, l as RateLimitDriverCapabilities, m as RateLimitDriverPeekResult, n as CheckRateLimitOptions, o as RateLimitDecision, p as RateLimitDriverPeekOutcome, r as CreateRateLimiterOptions, s as RateLimitDeclaration, t as CheckRateLimitErrorCode, u as RateLimitDriverInput, v as RateLimitFailurePolicy, w as RateLimitRequestEvent, x as RateLimitPolicy, y as RateLimitOptions } from "./types-CMyR1JeW.js";
2
+ import { a as resetRateLimit, i as peekRateLimit, n as RateLimitPeekInspection, r as RateLimitResetInspection, t as RateLimitCounterSnapshot } from "./counters-DXpF67J_.js";
3
+ import { Result } from "@vite-hub/runtime";
3
4
  //#region src/limiter.d.ts
4
5
  export declare function createRateLimiter(options: CreateRateLimiterOptions): RateLimiter;
5
6
  //#endregion
6
7
  //#region src/guard.d.ts
7
8
  /**
8
- * Consumes one request from a managed Rate Limit and returns the decision instead of throwing. Use it when a limited
9
- * request still gets an answer, such as a cheaper fallback. `reason` is `limited` or `unavailable` when not allowed.
10
- * Shares counters, discovery, and Provider Output with `requireRateLimit()`. Invalid options still throw.
9
+ * Consumes one request from a managed Rate Limit and returns `[error, decision]`. Use it when a limited request still
10
+ * gets an answer, such as a cheaper fallback. `decision.reason` is `limited` or `unavailable` when not allowed.
11
+ * `error` is set when the check cannot run: `RATE_LIMIT_R0013` for a request without a key, `RATE_LIMIT_R0009` for a
12
+ * missing Cloudflare binding. Shares counters, discovery, and Provider Output with `requireRateLimit()`. Invalid
13
+ * options throw.
14
+ */
15
+ export declare function checkRateLimit(event: RateLimitRequestEvent, name: string, options: CheckRateLimitOptions): Promise<Result<RateLimitDecision, CheckRateLimitErrorCode>>;
16
+ /**
17
+ * Consumes one request from a managed Rate Limit inside a handler. Returns when the request is allowed. Otherwise
18
+ * it throws an HTTP error: `429` with `Retry-After` when the limit is reached, `503` when the limiter is unavailable.
19
+ * `message` and `code` set the message and `data.code` of the `429` error. It also throws the errors that
20
+ * `checkRateLimit()` returns.
11
21
  */
12
- export declare function checkRateLimit(event: RateLimitRequestEvent, name: string, options: RequireRateLimitOptions): Promise<RateLimitDecision>;
13
22
  export declare function requireRateLimit(event: RateLimitRequestEvent, name: string, options: RequireRateLimitOptions): Promise<void>;
14
23
  //#endregion
15
- export { type CreateRateLimiterOptions, type RateLimitConsumeInput, type RateLimitCounterScope, type RateLimitCounterSnapshot, type RateLimitDecision, type RateLimitDeclaration, type RateLimitDriver, type RateLimitDriverCapabilities, type RateLimitDriverInput, type RateLimitDriverOutcome, type RateLimitDriverPeekOutcome, type RateLimitDriverPeekResult, type RateLimitDriverResetOutcome, type RateLimitDriverResult, type RateLimitEnforcement, type RateLimitFailurePolicy, type RateLimitModuleOptions, type RateLimitPeekInspection, type RateLimitPeekResult, type RateLimitPolicy, type RateLimitProvider, type RateLimitRejectedAttemptBehavior, type RateLimitRequestEvent, type RateLimitResetInspection, type RateLimitResetResult, type RateLimitRuntimeConfig, type RateLimitWindow, type RateLimiter, type RequireRateLimitOptions, type ResolvedRateLimitPolicy, peekRateLimit, resetRateLimit };
24
+ export { type CheckRateLimitErrorCode, type CheckRateLimitOptions, type CreateRateLimiterOptions, type RateLimitConsumeInput, type RateLimitCounterScope, type RateLimitCounterSnapshot, type RateLimitDecision, type RateLimitDeclaration, type RateLimitDriver, type RateLimitDriverCapabilities, type RateLimitDriverInput, type RateLimitDriverName, type RateLimitDriverOutcome, type RateLimitDriverPeekOutcome, type RateLimitDriverPeekResult, type RateLimitDriverResetOutcome, type RateLimitDriverResult, type RateLimitEnforcement, type RateLimitFailurePolicy, type RateLimitOptions, type RateLimitPeekInspection, type RateLimitPeekResult, type RateLimitPolicy, type RateLimitRejectedAttemptBehavior, type RateLimitRequest, type RateLimitRequestEvent, type RateLimitResetInspection, type RateLimitResetResult, type RateLimitRuntimeConfig, type RateLimitWindow, type RateLimiter, type RequireRateLimitOptions, type ResolvedRateLimitPolicy, peekRateLimit, resetRateLimit };
package/dist/index.js CHANGED
@@ -1,74 +1,144 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
2
- import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-DBrMI4vi.js";
3
- import { n as getRateLimitRuntimeConfig, t as getMemoryRateLimiter } from "./state-Ct7zR8fD.js";
4
- import { n as resetRateLimit, t as peekRateLimit } from "./counters-wdEMxDEY.js";
5
- import { n as toEventRequest, r as getCloudflareEnv, t as isH3V1Event } from "./h3-v1-request-qoGwJr5-.js";
6
- import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-DUDRACVB.js";
7
- import { createError, getRequestIP } from "h3";
8
- //#region src/guard.ts
9
- const guardOptionKeys = /* @__PURE__ */ new Set([...rateLimitPolicyKeys, "key"]);
10
- function getCloudflareEventEnv(event) {
11
- return getCloudflareEnv(event, { fallback: false });
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
2
+ import { a as rateLimitPolicyKeys, i as normalizeRateLimitPolicy, n as createRateLimiter, r as declaredRateLimitPolicy } from "./kv-provider-C1S6dRTR.js";
3
+ import { i as resolveRateLimitDriver, n as getRuntimeRateLimiter } from "./state-BU-zcLNY.js";
4
+ import { n as resetRateLimit, t as peekRateLimit } from "./counters-DgVdHwdL.js";
5
+ import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-otBvOPv4.js";
6
+ import { toResultError } from "@vite-hub/runtime";
7
+ import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
8
+ import { getStandardContext } from "@vite-hub/runtime/internal/h3";
9
+ import { createError } from "nitro/h3";
10
+ //#region ../internal/src/runtime/cloudflare-env-lookup.ts
11
+ /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
12
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
13
+ let activeEnv;
14
+ /** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
15
+ function getScopedCloudflareEnv() {
16
+ return globalThis[activeEnvStorageKey]?.getStore();
17
+ }
18
+ function getActiveCloudflareEnv() {
19
+ const scoped = getScopedCloudflareEnv();
20
+ if (scoped) return scoped.env;
21
+ const host = globalThis;
22
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
12
23
  }
24
+ //#endregion
25
+ //#region src/guard.ts
26
+ const guardOptionKeys = {
27
+ checkRateLimit: /* @__PURE__ */ new Set([...rateLimitPolicyKeys, "key"]),
28
+ requireRateLimit: /* @__PURE__ */ new Set([
29
+ ...rateLimitPolicyKeys,
30
+ "code",
31
+ "key",
32
+ "message"
33
+ ])
34
+ };
13
35
  function isCloudflareBinding(value) {
14
36
  return Boolean(value) && typeof value === "object" && typeof value.limit === "function";
15
37
  }
16
- function getRequestKey(event, provider) {
17
- return provider === "cloudflare" ? toEventRequest(event).headers.get("cf-connecting-ip") || getRequestIP(event) : getRequestIP(event);
38
+ function isObject(value) {
39
+ return value !== null && typeof value === "object";
40
+ }
41
+ function isWebRequest(value) {
42
+ if (value instanceof Request) return true;
43
+ if (!isObject(value)) return false;
44
+ const headers = Reflect.get(value, "headers");
45
+ return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObject(headers) && typeof Reflect.get(headers, "get") === "function";
46
+ }
47
+ /** Structural Requests may carry unrelated event-named properties, so identify the event's shape. */
48
+ function isRequestEvent(input) {
49
+ if ("~standard" in input) {
50
+ const standard = input["~standard"];
51
+ return isObject(standard) && typeof Reflect.get(standard, "vendor") === "string" && isWebRequest(Reflect.get(standard, "req")) && isObject(Reflect.get(standard, "res"));
52
+ }
53
+ return Object.hasOwn(input, "req") && isWebRequest(Reflect.get(input, "req")) && isObject(Reflect.get(input, "res"));
54
+ }
55
+ function getRequestScope(input) {
56
+ if (!isRequestEvent(input)) return {
57
+ cloudflareEnv: getActiveCloudflareEnv(),
58
+ headers: input.headers
59
+ };
60
+ const standard = getStandardContext(input);
61
+ return {
62
+ clientAddress: standard.runtime?.clientAddress,
63
+ cloudflareEnv: standard.runtime?.cloudflare?.env,
64
+ headers: standard.req.headers
65
+ };
66
+ }
67
+ function getRequestKey(scope, driver) {
68
+ return driver === "cloudflare" ? scope.headers.get("cf-connecting-ip") || scope.clientAddress : scope.clientAddress;
18
69
  }
19
- function getCloudflareRateLimiter(event, name, policy) {
70
+ /** A failure of one check, such as a request without a key. Option errors throw instead. */
71
+ function checkError(code, message) {
72
+ const diagnostic = code === "RATE_LIMIT_R0009" ? rateLimitErrorDiagnostics.RATE_LIMIT_R0009({ message }) : rateLimitErrorDiagnostics.RATE_LIMIT_R0013({ message });
73
+ return toResultError(diagnostic);
74
+ }
75
+ function getCloudflareRateLimiter(scope, name, policy) {
20
76
  const bindingName = getCloudflareRateLimitBindingName(name);
21
- const binding = getCloudflareEventEnv(event)?.[bindingName];
22
- if (!isCloudflareBinding(binding)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0009({ message: `[vitehub] Cloudflare Rate Limit binding "${bindingName}" was not found on the request event.` });
23
- return createRateLimiter({
77
+ const env = scope.cloudflareEnv;
78
+ const binding = env && Object.hasOwn(env, bindingName) ? env[bindingName] : void 0;
79
+ if (!isCloudflareBinding(binding)) return [checkError("RATE_LIMIT_R0009", `[vitehub] Cloudflare Rate Limit binding "${bindingName}" was not found on the request event.`), void 0];
80
+ return [void 0, createRateLimiter({
24
81
  ...policy,
25
82
  driver: cloudflareRateLimitDriver({ binding }),
26
83
  name
27
- });
84
+ })];
28
85
  }
29
86
  async function consumeRateLimit(event, name, options, guard) {
30
87
  const id = typeof name === "string" ? name.trim() : "";
31
88
  if (!id) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0010({ message: `\`${guard}()\` requires a non-empty stable ID.` });
32
- const unknownKey = options && typeof options === "object" && !Array.isArray(options) ? Object.keys(options).find((key) => !guardOptionKeys.has(key)) : void 0;
89
+ const unknownKey = options && typeof options === "object" && !Array.isArray(options) ? Object.keys(options).find((key) => !guardOptionKeys[guard].has(key)) : void 0;
33
90
  if (unknownKey) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0011({ message: `\`${guard}()\` does not support the "${unknownKey}" option.` });
34
91
  if (options?.key !== void 0 && (typeof options.key !== "string" || options.key.length === 0)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0012({ message: `\`${guard}()\` key must be a non-empty string.` });
35
92
  const policy = declaredRateLimitPolicy(normalizeRateLimitPolicy(options));
36
- const { provider } = getRateLimitRuntimeConfig();
37
- const key = options.key ?? getRequestKey(event, provider);
38
- if (!key) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0013({ message: `[vitehub] \`${guard}()\` could not determine a request key. Pass key when limiting by user or tenant or when the request has no client address.` });
39
- return await (provider === "cloudflare" ? getCloudflareRateLimiter(event, id, policy) : getMemoryRateLimiter(id, policy)).consume({ key });
93
+ const driver = await resolveRateLimitDriver();
94
+ const scope = getRequestScope(event);
95
+ const key = options.key ?? getRequestKey(scope, driver) ?? (getViteHubTestMode() ? "test-client" : void 0);
96
+ if (!key) return [checkError("RATE_LIMIT_R0013", `[vitehub] \`${guard}()\` could not determine a request key. Pass key when limiting by user or tenant or when the request has no client address.`), void 0];
97
+ const [error, limiter] = driver === "cloudflare" ? getCloudflareRateLimiter(scope, id, policy) : [void 0, getRuntimeRateLimiter(driver, id, policy)];
98
+ if (error) return [error, void 0];
99
+ return [void 0, await limiter.consume({ key })];
40
100
  }
41
101
  /**
42
- * Consumes one request from a managed Rate Limit and returns the decision instead of throwing. Use it when a limited
43
- * request still gets an answer, such as a cheaper fallback. `reason` is `limited` or `unavailable` when not allowed.
44
- * Shares counters, discovery, and Provider Output with `requireRateLimit()`. Invalid options still throw.
102
+ * Consumes one request from a managed Rate Limit and returns `[error, decision]`. Use it when a limited request still
103
+ * gets an answer, such as a cheaper fallback. `decision.reason` is `limited` or `unavailable` when not allowed.
104
+ * `error` is set when the check cannot run: `RATE_LIMIT_R0013` for a request without a key, `RATE_LIMIT_R0009` for a
105
+ * missing Cloudflare binding. Shares counters, discovery, and Provider Output with `requireRateLimit()`. Invalid
106
+ * options throw.
45
107
  */
46
108
  async function checkRateLimit(event, name, options) {
47
109
  return await consumeRateLimit(event, name, options, "checkRateLimit");
48
110
  }
111
+ function refusalText(options, option) {
112
+ const value = options?.[option];
113
+ if (value === void 0) return;
114
+ if (typeof value !== "string" || !value.trim()) throw rateLimitErrorDiagnostics.RATE_LIMIT_REFUSAL_OPTION_INVALID({ message: `\`requireRateLimit()\` ${option} must be a non-empty string.` });
115
+ return value;
116
+ }
117
+ /**
118
+ * Consumes one request from a managed Rate Limit inside a handler. Returns when the request is allowed. Otherwise
119
+ * it throws an HTTP error: `429` with `Retry-After` when the limit is reached, `503` when the limiter is unavailable.
120
+ * `message` and `code` set the message and `data.code` of the `429` error. It also throws the errors that
121
+ * `checkRateLimit()` returns.
122
+ */
49
123
  async function requireRateLimit(event, name, options) {
50
- const decision = await consumeRateLimit(event, name, options, "requireRateLimit");
124
+ const message = refusalText(options, "message");
125
+ const code = refusalText(options, "code");
126
+ const [error, decision] = await consumeRateLimit(event, name, options, "requireRateLimit");
127
+ if (error) throw error;
51
128
  if (decision.allowed) return;
52
- if (decision.reason === "unavailable") throw rateLimitHTTPError(event, {
129
+ if (decision.reason === "unavailable") throw createError({
53
130
  cause: decision.cause,
54
131
  message: "Rate limiting is unavailable.",
55
132
  status: 503,
56
133
  statusText: "Service Unavailable"
57
134
  });
58
- throw rateLimitHTTPError(event, {
135
+ throw createError({
136
+ ...code === void 0 ? {} : { data: { code } },
59
137
  headers: decision.retryAfter === void 0 ? void 0 : { "Retry-After": String(decision.retryAfter) },
60
- message: "Rate limit exceeded.",
138
+ message: message ?? "Rate limit exceeded.",
61
139
  status: 429,
62
140
  statusText: "Too Many Requests"
63
141
  });
64
142
  }
65
- /**
66
- * Nuxt 4 bundles every `h3` import as its own h3 1, which has `createError()` but no `HTTPError`. h3 2's
67
- * `createError()` returns an `HTTPError`. h3 1 errors carry no headers, so an H3 1 event gets them on its response.
68
- */
69
- function rateLimitHTTPError(event, details) {
70
- if (details.headers && isH3V1Event(event)) for (const [name, value] of Object.entries(details.headers)) event.node.res?.setHeader(name, value);
71
- return createError(details);
72
- }
73
143
  //#endregion
74
144
  export { checkRateLimit, createRateLimiter, peekRateLimit, requireRateLimit, resetRateLimit };
@@ -5,6 +5,7 @@ function normalizeWindowsPath(input = "") {
5
5
  return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
6
6
  }
7
7
  const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
8
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
8
9
  const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
9
10
  function cwd() {
10
11
  if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
@@ -89,6 +90,11 @@ const relative = function(from, to) {
89
90
  }
90
91
  return [..._from.map(() => ".."), ..._to].join("/");
91
92
  };
93
+ const dirname = function(p) {
94
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
95
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
96
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
97
+ };
92
98
  //#endregion
93
99
  //#region ../internal/src/inspect.ts
94
100
  function relativeDefinitionFile(projectRoot, file) {
@@ -109,4 +115,4 @@ function redactInspectionText(value) {
109
115
  return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
110
116
  }
111
117
  //#endregion
112
- export { relativeDefinitionFile as n, resolve as r, redactInspectionText as t };
118
+ export { resolve as i, relativeDefinitionFile as n, dirname as r, redactInspectionText as t };
@@ -0,0 +1,29 @@
1
+ import { c as RateLimitDriver } from "./types-CMyR1JeW.js";
2
+ import { Result } from "@vite-hub/runtime";
3
+ //#region src/drivers/kv.d.ts
4
+ /** `[error, data]`, as KV operations return it. */
5
+ type KVOperationResult<T> = Result<T>;
6
+ /**
7
+ * The KV operations that the driver uses. `kv` and `kv.store(name)` from `@vite-hub/kv` match it. `increment` must be
8
+ * atomic and set the TTL with the first increment, as the `redis`, `database`, and `upstash` drivers do.
9
+ */
10
+ interface RateLimitKVStorage {
11
+ delete: (key: string) => Promise<KVOperationResult<void>>;
12
+ get: (key: string) => Promise<KVOperationResult<unknown>>;
13
+ increment: (key: string, ttl: number) => Promise<KVOperationResult<number>>;
14
+ }
15
+ interface KVRateLimitDriverOptions {
16
+ now?: () => number;
17
+ storage: RateLimitKVStorage;
18
+ }
19
+ interface KVRateLimitDriver extends RateLimitDriver {
20
+ peek: NonNullable<RateLimitDriver["peek"]>;
21
+ reset: NonNullable<RateLimitDriver["reset"]>;
22
+ }
23
+ /**
24
+ * Counts fixed windows in a KV store with one atomic `increment` for each request. Every server process that uses the
25
+ * same store shares the counters. Rejected requests also increment the counter.
26
+ */
27
+ declare function kvRateLimitDriver(options: KVRateLimitDriverOptions): KVRateLimitDriver;
28
+ //#endregion
29
+ export { kvRateLimitDriver as i, KVRateLimitDriverOptions as n, RateLimitKVStorage as r, KVRateLimitDriver as t };
@@ -1,4 +1,4 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
2
2
  import * as v from "valibot";
3
3
  import { Diagnostic } from "nostics";
4
4
  //#region src/policy.ts
@@ -59,7 +59,8 @@ const driverErrorSchema = v.custom((value) => {
59
59
  name: v.string()
60
60
  }), value);
61
61
  });
62
- const driverOutcomeSchema = v.pipe(v.array(v.unknown()), v.length(2), v.union([v.strictTuple([v.null(), v.unknown()]), v.strictTuple([driverErrorSchema, v.undefined()])]));
62
+ const driverOutcomeSchema = v.pipe(v.array(v.unknown()), v.length(2), v.union([v.strictTuple([v.undefined(), v.unknown()]), v.strictTuple([driverErrorSchema, v.undefined()])]));
63
+ const driverResetOutcomeSchema = v.pipe(v.array(v.unknown()), v.length(2), v.strictTuple([v.optional(driverErrorSchema), v.undefined()]));
63
64
  function resolveDriverCapabilities(options, capabilities = options.driver.capabilities, driverName = options.driver.name) {
64
65
  if (!capabilities || typeof capabilities !== "object") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0019({ message: `[vitehub] Rate Limit driver "${driverName}" must declare capabilities.` });
65
66
  if (capabilities.enforcement !== "best-effort" && capabilities.enforcement !== "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0020({ message: `[vitehub] Rate Limit driver "${driverName}" must declare valid enforcement.` });
@@ -149,7 +150,7 @@ function ownOption(options, key) {
149
150
  function inspectRateLimiterOptions(options) {
150
151
  const driver = Reflect.get(options, "driver");
151
152
  const consume = Reflect.get(driver, "consume");
152
- if (typeof consume !== "function") throw new TypeError("Rate Limit driver consume() must be callable");
153
+ if (typeof consume !== "function") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0029({ message: "[vitehub] createRateLimiter() requires a Rate Limit driver with a consume() function." });
153
154
  const peek = Reflect.get(driver, "peek");
154
155
  const reset = Reflect.get(driver, "reset");
155
156
  const policy = {
@@ -193,7 +194,7 @@ function isRateLimitDiagnostic(value) {
193
194
  }
194
195
  }
195
196
  const rateLimitDiagnosticCodes = /* @__PURE__ */ new Set([
196
- ...Array.from({ length: 45 }, (_, index) => `RATE_LIMIT_R${String(index + 1).padStart(4, "0")}`),
197
+ ...Array.from({ length: 47 }, (_, index) => `RATE_LIMIT_R${String(index + 1).padStart(4, "0")}`),
197
198
  "RATE_LIMIT_B0001",
198
199
  "RATE_LIMIT_B0002",
199
200
  "RATE_LIMIT_B0003",
@@ -233,7 +234,7 @@ function createRateLimiter(options) {
233
234
  async consume(input) {
234
235
  if (!input || !v.is(v.string(), input.key) || input.key.length === 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0030({ message: "[vitehub] Rate Limiter consume() requires a non-empty key." });
235
236
  const outcome = await consume.call(driver, driverInput(input));
236
- if (!v.is(driverOutcomeSchema, outcome)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0044({ message: "[vitehub] Rate Limit driver consume() must return [null, value] or [Error, undefined]." });
237
+ if (!v.is(driverOutcomeSchema, outcome)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0044({ message: "[vitehub] Rate Limit driver consume() must return [undefined, value] or [error, undefined]." });
237
238
  const [error, result] = outcome;
238
239
  if (error) return {
239
240
  allowed: policy.failure === "allow",
@@ -254,7 +255,7 @@ function createRateLimiter(options) {
254
255
  };
255
256
  const outcome = await peek.call(driver, driverInput(input));
256
257
  const parsed = v.safeParse(driverOutcomeSchema, outcome);
257
- if (!parsed.success) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0043({ message: "[vitehub] Rate Limit driver peek() must return [null, value] or [Error, undefined]." });
258
+ if (!parsed.success) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0043({ message: "[vitehub] Rate Limit driver peek() must return [undefined, value] or [error, undefined]." });
258
259
  const [error, result] = parsed.output;
259
260
  if (error) return {
260
261
  cause: error.cause ?? error,
@@ -272,8 +273,8 @@ function createRateLimiter(options) {
272
273
  status: "unsupported"
273
274
  };
274
275
  const outcome = await reset.call(driver, driverInput(input));
275
- const parsed = v.safeParse(v.strictTuple([v.nullable(driverErrorSchema)]), outcome);
276
- if (!parsed.success) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0042({ message: "[vitehub] Rate Limit driver reset() must return [null] or [Error]." });
276
+ const parsed = v.safeParse(driverResetOutcomeSchema, outcome);
277
+ if (!parsed.success) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0042({ message: "[vitehub] Rate Limit driver reset() must return [undefined, undefined] or [error, undefined]." });
277
278
  const [error] = parsed.output;
278
279
  return error ? {
279
280
  cause: error.cause ?? error,
@@ -283,4 +284,10 @@ function createRateLimiter(options) {
283
284
  };
284
285
  }
285
286
  //#endregion
286
- export { rateLimitPolicyKeys as i, declaredRateLimitPolicy as n, normalizeRateLimitPolicy as r, createRateLimiter as t };
287
+ //#region src/internal/kv-provider.ts
288
+ /** KV drivers with a shared atomic increment, as required by the KV Rate Limit driver. */
289
+ function resolveKVRateLimitDriver(driver) {
290
+ return driver === "database" || driver === "redis" || driver === "upstash" ? "kv" : "memory";
291
+ }
292
+ //#endregion
293
+ export { rateLimitPolicyKeys as a, normalizeRateLimitPolicy as i, createRateLimiter as n, declaredRateLimitPolicy as r, resolveKVRateLimitDriver as t };