@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
@@ -1,16 +1,7 @@
1
- import { n as resetRateLimit, t as peekRateLimit } from "./counters-wdEMxDEY.js";
2
- import { t as redactInspectionText } from "./inspect-D-FzyM_x.js";
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
2
+ import { n as resetRateLimit, t as peekRateLimit } from "./counters-DgVdHwdL.js";
3
+ import { t as redactInspectionText } from "./inspect-B6gTdgy9.js";
3
4
  //#region src/runtime/operations.ts
4
- /** A failure with the fields that every surface reports. */
5
- var RateLimitOperationError = class extends Error {
6
- status;
7
- code;
8
- constructor(message, status, code) {
9
- super(redactInspectionText(message));
10
- this.status = status;
11
- this.code = code;
12
- }
13
- };
14
5
  /** Removes credentials from the echoed key and from driver error text before the result leaves the runtime. */
15
6
  function redact(result) {
16
7
  return {
@@ -23,7 +14,11 @@ async function guarded(run) {
23
14
  try {
24
15
  return redact(await run());
25
16
  } catch (error) {
26
- throw new RateLimitOperationError(error instanceof Error ? error.message : "The Rate Limit operation failed.", 500, "RATE_LIMIT_OPERATION_FAILED");
17
+ const failure = rateLimitErrorDiagnostics.RATE_LIMIT_OPERATION_FAILED({ cause: error });
18
+ throw Object.assign(failure, {
19
+ status: 500,
20
+ statusMessage: redactInspectionText(error instanceof Error ? error.message : failure.message)
21
+ });
27
22
  }
28
23
  }
29
24
  /** Reads the counter of one key without consuming a token. */
@@ -35,4 +30,4 @@ async function resetRateLimitOperation(name, key) {
35
30
  return await guarded(() => resetRateLimit(name, key));
36
31
  }
37
32
  //#endregion
38
- export { RateLimitOperationError, peekRateLimitOperation, resetRateLimitOperation };
33
+ export { peekRateLimitOperation, resetRateLimitOperation };
@@ -1,11 +1,16 @@
1
- import { n as RateLimitPeekInspection, r as RateLimitResetInspection } from "./counters-pKORpgGd.js";
2
- import { t as AnyOperation } from "./operations-tNUdj3G4.js";
1
+ import { n as RateLimitPeekInspection, r as RateLimitResetInspection } from "./counters-DXpF67J_.js";
2
+ import { t as AnyOperation } from "./operation-definition-8gOe-ubD.js";
3
3
  //#region ../internal/src/operations-dev.d.ts
4
- /** Bundled into owner packages and used only by their serve-only generated Nitro route. */
4
+ /**
5
+ * Bundled into owner packages and used only by their serve-only generated Nitro route. Operations get the Request as
6
+ * `context.event`, so owner hooks such as `identify` of Comments read its Standard Context.
7
+ */
5
8
  export declare function createStandaloneOperationHandler(sources: {
6
9
  operations: unknown;
7
10
  plugin: string;
8
- }[], root: string): (event: object) => Promise<Response>;
11
+ }[], root: string): {
12
+ fetch(request: Request): Promise<Response>;
13
+ };
9
14
  //#endregion
10
15
  //#region src/operations.d.ts
11
16
  /** The `rate-limit.*` operations: peek and reset. The Console, `vitehub rate-limit`, and agents run them. */
@@ -1,5 +1,5 @@
1
- import { i as resolveWaitUntil, n as toEventRequest, r as getCloudflareEnv } from "./h3-v1-request-qoGwJr5-.js";
2
- import { a as defineOperation, d as runOperation, f as toOperationFailure, i as createOperationRegistry, l as operationsOf, o as operationRootHeader, s as operationRpcHeader, t as assertOperationProject, u as projectRootHash } from "./operations-B09NnEjT.js";
1
+ import { a as operationRootHeader, c as projectRootHash, d as toOperationFailure, f as defineOperation, g as readOperationRpcCall, h as operationRpcRefusal, i as createOperationRegistry, l as runOperation, o as operationRpcHeader, p as answerOperationRpc, s as operationsOf, t as assertOperationProject, v as internalErrorDiagnostics } from "./operations-BYRa7wpx.js";
2
+ import { n as isViteHubLoopbackPeer } from "./dev-peer-CHafxbtj.js";
3
3
  import * as v from "valibot";
4
4
  //#region ../internal/src/secret.ts
5
5
  const secretEncoder = new TextEncoder();
@@ -15,6 +15,7 @@ function isViteHubSecretEqual(actual, expected) {
15
15
  for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
16
16
  return difference === 0;
17
17
  }
18
+ Object.freeze({ prefix: "sha256=" });
18
19
  //#endregion
19
20
  //#region ../internal/src/dev-endpoint.ts
20
21
  const viteHubDevRequestGrantBrand = Symbol("vitehub.devRequestGrant");
@@ -102,6 +103,22 @@ function readPath(value, ...path) {
102
103
  for (const key of path) value = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
103
104
  return value;
104
105
  }
106
+ /** The Cloudflare bindings of a Request: from the Standard Context that Nitro sets, else where srvx puts them. */
107
+ function requestEnv(request) {
108
+ const env = readPath(request, "~standard", "runtime", "cloudflare", "env") ?? readPath(request, "runtime", "cloudflare", "env");
109
+ return env !== null && typeof env === "object" ? env : void 0;
110
+ }
111
+ /** The `waitUntil` of a Request: from its Standard Context, else from the Request or its Worker ExecutionContext. */
112
+ function requestWaitUntil(request) {
113
+ for (const owner of [
114
+ readPath(request, "~standard"),
115
+ request,
116
+ readPath(request, "runtime", "cloudflare", "context")
117
+ ]) {
118
+ const waitUntil = readPath(owner, "waitUntil");
119
+ if (typeof waitUntil === "function") return waitUntil.bind(owner);
120
+ }
121
+ }
105
122
  function localHost(host) {
106
123
  try {
107
124
  const name = new URL(`http://${host}`).hostname;
@@ -116,7 +133,10 @@ function reject(status, message) {
116
133
  status
117
134
  });
118
135
  }
119
- /** Bundled into owner packages and used only by their serve-only generated Nitro route. */
136
+ /**
137
+ * Bundled into owner packages and used only by their serve-only generated Nitro route. Operations get the Request as
138
+ * `context.event`, so owner hooks such as `identify` of Comments read its Standard Context.
139
+ */
120
140
  function createStandaloneOperationHandler(sources, root) {
121
141
  const registry = createOperationRegistry(sources.map((source) => ({
122
142
  ...source,
@@ -124,22 +144,21 @@ function createStandaloneOperationHandler(sources, root) {
124
144
  })));
125
145
  const defaultLimit = 65536;
126
146
  const maximum = Math.max(defaultLimit, ...registry.list().map((operation) => operation.maxRequestBytes ?? defaultLimit));
127
- return async (event) => {
147
+ const operations = Object.fromEntries(registry.list().map((operation) => [operation.name, operation]));
148
+ return { async fetch(request) {
128
149
  const headers = {
129
150
  "cache-control": "no-store",
130
151
  "x-content-type-options": "nosniff",
131
152
  [operationRootHeader]: projectRootHash(root)
132
153
  };
133
154
  try {
134
- const request = toEventRequest(event);
135
155
  const address = [
136
- readPath(event, "req", "ip"),
137
- readPath(event, "req", "context", "clientAddress"),
138
- readPath(event, "req", "runtime", "node", "req", "socket", "remoteAddress"),
139
- readPath(event, "node", "req", "socket", "remoteAddress")
156
+ readPath(request, "ip"),
157
+ readPath(request, "context", "clientAddress"),
158
+ readPath(request, "runtime", "node", "req", "socket", "remoteAddress")
140
159
  ].find((value) => typeof value === "string" && value !== "");
141
160
  const forwarded = request.headers.get("x-forwarded-host");
142
- if (!localHost(request.headers.get("host") ?? new URL(request.url).host) || forwarded && !localHost(forwarded) || address && address !== "::1" && !address.startsWith("127.") && !address.startsWith("::ffff:127.")) reject(403, "Standalone development operations accept only local requests.");
161
+ if (!localHost(request.headers.get("host") ?? new URL(request.url).host) || forwarded && !localHost(forwarded) || !await isViteHubLoopbackPeer(request, address)) reject(403, "Standalone development operations accept only local requests.");
143
162
  const site = request.headers.get("sec-fetch-site");
144
163
  if (site === "cross-site" || site === "same-site") reject(403, "Cross-origin operation requests are not allowed.");
145
164
  const checked = await validateViteHubNitroDevRequest(request, {
@@ -174,10 +193,11 @@ function createStandaloneOperationHandler(sources, root) {
174
193
  } catch {
175
194
  reject(400, "Malformed operation request.");
176
195
  }
177
- if (!payload || typeof payload !== "object" || !("operation" in payload) || typeof payload.operation !== "string") reject(400, "Invalid operation request.");
178
- if (bytes > (registry.get(payload.operation)?.maxRequestBytes ?? defaultLimit)) reject(413, "Operation request exceeds the byte limit.");
196
+ const call = readOperationRpcCall(payload);
197
+ if (!call) reject(400, "Invalid operation request.");
198
+ if (bytes > (registry.get(call.m)?.maxRequestBytes ?? defaultLimit)) reject(413, "Operation request exceeds the byte limit.");
179
199
  const response = {};
180
- const result = await runOperation(registry, payload.operation, "input" in payload ? payload.input : void 0, {
200
+ const context = {
181
201
  access: {
182
202
  mode: "local",
183
203
  sections: "all"
@@ -186,29 +206,37 @@ function createStandaloneOperationHandler(sources, root) {
186
206
  surface: "cli",
187
207
  user: null,
188
208
  request,
209
+ event: request,
189
210
  response,
190
- env: getCloudflareEnv(event, { fallback: false }),
191
- waitUntil: resolveWaitUntil(event, { preferHost: true })
211
+ env: requestEnv(request),
212
+ waitUntil: requestWaitUntil(request)
213
+ };
214
+ const reply = await answerOperationRpc(call, {
215
+ failure: toOperationFailure,
216
+ operations,
217
+ run: async (operation, input) => {
218
+ const result = await runOperation(registry, operation.name, input, context);
219
+ if (!result.ok) throw Object.assign(new Error(result.message), result);
220
+ return result.value;
221
+ },
222
+ unknown: (name) => Object.assign(internalErrorDiagnostics.INTERNAL_R0021({ message: `No operation is named ${JSON.stringify(name)}.` }), { status: 404 })
192
223
  });
193
- return Response.json(result, {
224
+ return Response.json(reply, {
194
225
  headers,
195
- status: result.ok ? response.status ?? 200 : result.status
226
+ status: "e" in reply ? reply.e.status : response.status ?? 200
196
227
  });
197
228
  } catch (error) {
198
229
  const failure = toOperationFailure(error);
199
- return Response.json({
200
- ok: false,
201
- ...failure
202
- }, {
230
+ return Response.json(operationRpcRefusal(failure), {
203
231
  headers,
204
232
  status: failure.status
205
233
  });
206
234
  }
207
- };
235
+ } };
208
236
  }
209
237
  //#endregion
210
238
  //#region src/operations.ts
211
- const runtime = () => import("./operations-Bu-xulNd.js");
239
+ const runtime = () => import("./operations-CLI9w3rO.js");
212
240
  const target = v.object({
213
241
  key: v.pipe(v.string(), v.minLength(1, "Name the limited key, for example a client IP or user ID.")),
214
242
  name: v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name the stable ID of `requireRateLimit()`."))
package/dist/runtime.d.ts CHANGED
@@ -1,5 +1,23 @@
1
- import { C as RateLimitRuntimeConfig } from "./types-CQEJpgtz.js";
1
+ import { E as RateLimitRuntimeConfig } from "./types-CMyR1JeW.js";
2
+ import { r as RateLimitKVStorage } from "./kv-C1wpLulE.js";
2
3
  //#region src/runtime/state.d.ts
3
- export declare function setRateLimitRuntimeConfig(config: RateLimitRuntimeConfig): void;
4
+ /** The KV store of the `kv` driver. The generated Nitro plugin passes it from `@vite-hub/kv`. */
5
+ interface RateLimitKVRuntime {
6
+ /** The KV driver that the store uses in this process, for example `getKVStoreDriver()` of `@vite-hub/kv`. */
7
+ driver: () => Promise<string>;
8
+ storage: RateLimitKVStorage;
9
+ /** The KV store name, for the boot log. */
10
+ store: string;
11
+ }
12
+ /** `kv` needs the KV store of the app in `kv`. Other drivers ignore it. */
13
+ export declare function setRateLimitRuntimeConfig(config: RateLimitRuntimeConfig, kv?: RateLimitKVRuntime): void;
14
+ /** In app tests, Rate Limit counts in memory for the current test, whatever the host. */
4
15
  export declare function getRateLimitRuntimeConfig(): RateLimitRuntimeConfig;
5
- //#endregion
16
+ /**
17
+ * The driver that counts in this process. For `kv`, the first call asks KV for its configured driver
18
+ * and prints the choice: `kv` with a shared driver. Another driver fails, or counts in `memory` with `memoryFallback`.
19
+ * The generated Nitro plugin calls it at boot.
20
+ */
21
+ export declare function resolveRateLimitDriver(): Promise<RateLimitRuntimeConfig["driver"]>;
22
+ //#endregion
23
+ export type { RateLimitKVRuntime };
package/dist/runtime.js CHANGED
@@ -1,2 +1,2 @@
1
- import { i as setRateLimitRuntimeConfig, n as getRateLimitRuntimeConfig } from "./state-Ct7zR8fD.js";
2
- export { getRateLimitRuntimeConfig, setRateLimitRuntimeConfig };
1
+ import { a as setRateLimitRuntimeConfig, i as resolveRateLimitDriver, t as getRateLimitRuntimeConfig } from "./state-BU-zcLNY.js";
2
+ export { getRateLimitRuntimeConfig, resolveRateLimitDriver, setRateLimitRuntimeConfig };
@@ -0,0 +1,89 @@
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
2
+ import { i as normalizeRateLimitPolicy, n as createRateLimiter, t as resolveKVRateLimitDriver } from "./kv-provider-C1S6dRTR.js";
3
+ import { kvRateLimitDriver } from "./drivers/kv.js";
4
+ import { memoryRateLimitDriver } from "./drivers/memory.js";
5
+ import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
6
+ //#region src/runtime/state.ts
7
+ let runtimeConfig = { driver: "memory" };
8
+ let kvRuntime;
9
+ let activeDriver;
10
+ const runtimeLimiters = /* @__PURE__ */ new Map();
11
+ /** The counters of this process, or in app tests the counters of the current test. */
12
+ function limiters() {
13
+ const test = getViteHubTestMode();
14
+ return test ? test.backend("rate-limit", () => /* @__PURE__ */ new Map()) : runtimeLimiters;
15
+ }
16
+ /** `kv` needs the KV store of the app in `kv`. Other drivers ignore it. */
17
+ function setRateLimitRuntimeConfig(config, kv) {
18
+ runtimeConfig = config;
19
+ kvRuntime = kv;
20
+ activeDriver = void 0;
21
+ runtimeLimiters.clear();
22
+ }
23
+ /** In app tests, Rate Limit counts in memory for the current test, whatever the host. */
24
+ function getRateLimitRuntimeConfig() {
25
+ return getViteHubTestMode() ? { driver: "memory" } : runtimeConfig;
26
+ }
27
+ function requireKVRuntime() {
28
+ if (kvRuntime) return kvRuntime;
29
+ throw rateLimitErrorDiagnostics.RATE_LIMIT_R0047({ message: "[vitehub] The kv Rate Limit driver needs KV. Enable KV in the app, or pass a KV store to setRateLimitRuntimeConfig()." });
30
+ }
31
+ async function resolveKVDriver(kv, memoryFallback) {
32
+ const driver = await kv.driver();
33
+ if (resolveKVRateLimitDriver(driver) === "kv") {
34
+ console.info(`[vitehub] Rate Limit counts in the KV store "${kv.store}" (${driver}). Every server process that uses this store shares the counts.`);
35
+ return "kv";
36
+ }
37
+ if (!memoryFallback) throw rateLimitErrorDiagnostics.RATE_LIMIT_KV_RUNTIME_STORE_UNSUPPORTED({ message: `[vitehub] The kv Rate Limit driver needs a KV store that every server process shares, but the KV store "${kv.store}" uses ${driver}, which has no shared atomic increment.` });
38
+ console.warn(`[vitehub] Rate Limit counts in the memory of this process, because the KV store "${kv.store}" uses ${driver}, which has no shared atomic increment. Each server process allows the full limit. Configure a Redis KV store or use a Postgres Database to share the counts.`);
39
+ return "memory";
40
+ }
41
+ /**
42
+ * The driver that counts in this process. For `kv`, the first call asks KV for its configured driver
43
+ * and prints the choice: `kv` with a shared driver. Another driver fails, or counts in `memory` with `memoryFallback`.
44
+ * The generated Nitro plugin calls it at boot.
45
+ */
46
+ async function resolveRateLimitDriver() {
47
+ const { driver, memoryFallback = false } = getRateLimitRuntimeConfig();
48
+ if (driver !== "kv") return driver;
49
+ if (activeDriver) return await activeDriver;
50
+ const pending = resolveKVDriver(requireKVRuntime(), memoryFallback);
51
+ activeDriver = pending;
52
+ pending.catch(() => {
53
+ if (activeDriver === pending) activeDriver = void 0;
54
+ });
55
+ return await pending;
56
+ }
57
+ function policyKey(policy) {
58
+ return JSON.stringify([
59
+ policy.enforcement,
60
+ policy.failure,
61
+ policy.limit,
62
+ normalizeRateLimitPolicy(policy).windowMs
63
+ ]);
64
+ }
65
+ /** The Rate Limiter of one name and policy in this process. `kv` limiters share their counters through KV. */
66
+ function getRuntimeRateLimiter(driver, name, policy) {
67
+ const all = limiters();
68
+ let policies = all.get(name);
69
+ const key = policyKey(policy);
70
+ const existing = policies?.get(key);
71
+ if (existing) return existing;
72
+ const limiter = createRateLimiter({
73
+ ...policy,
74
+ driver: driver === "kv" ? kvRateLimitDriver({ storage: requireKVRuntime().storage }) : memoryRateLimitDriver(),
75
+ name
76
+ });
77
+ if (!policies) {
78
+ policies = /* @__PURE__ */ new Map();
79
+ all.set(name, policies);
80
+ }
81
+ policies.set(key, limiter);
82
+ return limiter;
83
+ }
84
+ /** Lists each policy used by this name in this process. */
85
+ function listRuntimeRateLimiters(name) {
86
+ return [...limiters().get(name)?.values() ?? []];
87
+ }
88
+ //#endregion
89
+ export { setRateLimitRuntimeConfig as a, resolveRateLimitDriver as i, getRuntimeRateLimiter as n, listRuntimeRateLimiters as r, getRateLimitRuntimeConfig as t };
@@ -1,3 +1,4 @@
1
+ import { Result, ViteHubContext } from "@vite-hub/runtime";
1
2
  //#region src/types.d.ts
2
3
  type MaybePromise<T> = Promise<T> | T;
3
4
  type RateLimitWindow = `${number}ms` | `${number}s` | `${number}m` | `${number}h` | `${number}d`;
@@ -11,23 +12,24 @@ interface RateLimitPolicy {
11
12
  limit: number;
12
13
  window: RateLimitWindow;
13
14
  }
14
- interface RequireRateLimitOptions extends RateLimitPolicy {
15
+ interface CheckRateLimitOptions extends RateLimitPolicy {
15
16
  key?: string;
16
17
  }
17
- /** A server request event: an H3 2 event, as in Nitro 3, or an H3 1 event, as in Nuxt 4. */
18
- type RateLimitRequestEvent = {
19
- readonly req: {
20
- readonly headers: {
21
- get: (name: string) => string | null;
22
- };
23
- };
24
- } | {
25
- readonly node: {
26
- readonly req: {
27
- readonly headers: Readonly<Record<string, string | string[] | undefined>>;
28
- };
29
- };
30
- };
18
+ interface RequireRateLimitOptions extends CheckRateLimitOptions {
19
+ /** `data.code` of the `429` error, such as a translation key that the client reads. */
20
+ code?: string;
21
+ /** Message of the `429` error, which the client can show. Defaults to `"Rate limit exceeded."`. */
22
+ message?: string;
23
+ }
24
+ /** A Web `Request`. The guard reads only its headers. */
25
+ type RateLimitRequest = Pick<Request, "headers">;
26
+ /**
27
+ * The request that a guard limits: a request event with Standard Context properties, such as an H3 2 event in a
28
+ * ViteHub app, or a Web `Request`. From an event, the guard reads the client address, the request headers, and
29
+ * the Cloudflare bindings from `event["~standard"]`. A `Request` has no client address, so pass `key`. On Cloudflare,
30
+ * the guard reads `cf-connecting-ip` from its headers and the bindings of the request that runs.
31
+ */
32
+ type RateLimitRequestEvent = RateLimitRequest | ViteHubContext;
31
33
  interface ResolvedRateLimitPolicy {
32
34
  readonly enforcement: RateLimitEnforcement;
33
35
  readonly failure: RateLimitFailurePolicy;
@@ -51,7 +53,8 @@ interface RateLimitDriverResult {
51
53
  retryAfter?: number;
52
54
  used?: number;
53
55
  }
54
- type RateLimitDriverOutcome = [error: null, value: RateLimitDriverResult] | [error: Error, value: undefined];
56
+ /** `[undefined, result]` after the driver consumed the counter, or `[error, undefined]` for an outage. */
57
+ type RateLimitDriverOutcome = Result<RateLimitDriverResult>;
55
58
  interface RateLimitDecisionBase extends RateLimitDriverResult {
56
59
  limit: number;
57
60
  windowMs: number;
@@ -71,6 +74,11 @@ interface RateLimitUnavailableDecision extends RateLimitDecisionBase {
71
74
  reason: "unavailable";
72
75
  }
73
76
  type RateLimitDecision = RateLimitAllowedDecision | RateLimitLimitedDecision | RateLimitUnavailableDecision;
77
+ /**
78
+ * The errors that `checkRateLimit()` returns. `RATE_LIMIT_R0013`: the request has no client address and the call has
79
+ * no `key`. `RATE_LIMIT_R0009`: the Cloudflare Rate Limiting binding of the policy is not on the request.
80
+ */
81
+ type CheckRateLimitErrorCode = "RATE_LIMIT_R0009" | "RATE_LIMIT_R0013";
74
82
  interface RateLimitDriverCapabilities {
75
83
  readonly enforcement: RateLimitEnforcement;
76
84
  readonly rejectedAttempts: RateLimitRejectedAttemptBehavior;
@@ -84,8 +92,10 @@ interface RateLimitDriverPeekResult {
84
92
  /** Tokens consumed in the current window. `0` when the key has no active counter. */
85
93
  used: number;
86
94
  }
87
- type RateLimitDriverPeekOutcome = [error: null, value: RateLimitDriverPeekResult] | [error: Error, value: undefined];
88
- type RateLimitDriverResetOutcome = [error: Error | null];
95
+ /** `[undefined, result]` with the counter state, or `[error, undefined]` for an outage. */
96
+ type RateLimitDriverPeekOutcome = Result<RateLimitDriverPeekResult>;
97
+ /** `[undefined, undefined]` after the driver deleted the counter, or `[error, undefined]` for an outage. */
98
+ type RateLimitDriverResetOutcome = Result<void>;
89
99
  interface RateLimitDriver {
90
100
  capabilities: RateLimitDriverCapabilities;
91
101
  consume: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverOutcome>;
@@ -146,15 +156,25 @@ interface CreateRateLimiterOptions extends RateLimitPolicy {
146
156
  driver: RateLimitDriver;
147
157
  name?: string;
148
158
  }
149
- type RateLimitProvider = "auto" | "cloudflare" | "memory";
150
- interface RateLimitModuleOptions {
159
+ /**
160
+ * `kv` counts in the default KV store, shared by every server process when KV uses `redis`, `database`, or `upstash`.
161
+ * With another KV driver, it counts in process memory and prints a warning at boot.
162
+ */
163
+ type RateLimitDriverName = "auto" | "cloudflare" | "kv" | "memory";
164
+ interface RateLimitOptions {
165
+ /** The driver of the counters. Defaults to `auto`. */
166
+ driver?: RateLimitDriverName;
151
167
  namespace?: string;
152
- provider?: RateLimitProvider;
153
168
  projectRoot?: string;
154
169
  scanDirs?: string[];
155
170
  }
156
171
  interface RateLimitRuntimeConfig {
157
- provider: Exclude<RateLimitProvider, "auto">;
172
+ driver: Exclude<RateLimitDriverName, "auto">;
173
+ /**
174
+ * With the `kv` driver: count in the memory of this process, with a warning, when the KV store cannot share counts.
175
+ * Without it, such a store fails with `RATE_LIMIT_KV_RUNTIME_STORE_UNSUPPORTED`. ViteHub sets it in `vite dev` and when it selects `kv` itself.
176
+ */
177
+ memoryFallback?: boolean;
158
178
  }
159
179
  //#endregion
160
- export { RateLimitRuntimeConfig as C, ResolvedRateLimitPolicy as D, RequireRateLimitOptions as E, RateLimitResetResult as S, RateLimiter as T, RateLimitPeekResult as _, RateLimitDeclaration as a, RateLimitRejectedAttemptBehavior as b, RateLimitDriverInput as c, RateLimitDriverPeekResult as d, RateLimitDriverResetOutcome as f, RateLimitModuleOptions as g, RateLimitFailurePolicy as h, RateLimitDecision as i, RateLimitDriverOutcome as l, RateLimitEnforcement as m, RateLimitConsumeInput as n, RateLimitDriver as o, RateLimitDriverResult as p, RateLimitCounterScope as r, RateLimitDriverCapabilities as s, CreateRateLimiterOptions as t, RateLimitDriverPeekOutcome as u, RateLimitPolicy as v, RateLimitWindow as w, RateLimitRequestEvent as x, RateLimitProvider as y };
180
+ export { ResolvedRateLimitPolicy as A, RateLimitRequest as C, RateLimitWindow as D, RateLimitRuntimeConfig as E, RateLimiter as O, RateLimitRejectedAttemptBehavior as S, RateLimitResetResult as T, RateLimitEnforcement as _, RateLimitCounterScope as a, RateLimitPeekResult as b, RateLimitDriver as c, RateLimitDriverName as d, RateLimitDriverOutcome as f, RateLimitDriverResult as g, RateLimitDriverResetOutcome as h, RateLimitConsumeInput as i, RequireRateLimitOptions as k, RateLimitDriverCapabilities as l, RateLimitDriverPeekResult as m, CheckRateLimitOptions as n, RateLimitDecision as o, RateLimitDriverPeekOutcome as p, CreateRateLimiterOptions as r, RateLimitDeclaration as s, CheckRateLimitErrorCode as t, RateLimitDriverInput as u, RateLimitFailurePolicy as v, RateLimitRequestEvent as w, RateLimitPolicy as x, RateLimitOptions as y };