@vite-hub/rate-limit 0.0.4 → 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.
package/README.md CHANGED
@@ -1,8 +1,13 @@
1
1
  # @vite-hub/rate-limit
2
2
 
3
+ [![npm version](https://comark-ui.onmax.me/badge.svg?source=npm-version&package=%40vite-hub%2Frate-limit&icon=npm)](https://npmx.dev/package/@vite-hub/rate-limit)
4
+ [![npm downloads](https://comark-ui.onmax.me/badge.svg?source=npm-downloads&package=%40vite-hub%2Frate-limit&period=month&icon=npm)](https://npmx.dev/package/@vite-hub/rate-limit)
5
+ [![license](https://comark-ui.onmax.me/badge.svg?label=license&value=Apache-2.0)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
+ [![docs](https://comark-ui.onmax.me/badge.svg?label=docs&value=vitehub.dev)](https://vitehub.dev/docs)
7
+
3
8
  `@vite-hub/rate-limit` gives server code one atomic consume-and-decide operation for fixed-window request budgets. It keeps policy separate from the driver that stores and updates each counter.
4
9
 
5
- Install this owner package when you need a direct Rate Limiter, a custom driver, or the standalone Vite integration. If your application already uses the `vite-hub` framework distribution, enable Rate Limit there and import from `vite-hub/rate-limit` instead. See the [Rate Limit guide](https://vitehub.dev/docs/server-primitives/rate-limit) for that application setup.
10
+ Install this owner package when you need a direct Rate Limiter, a custom driver, or the Vite integration without the full framework. If your application already uses the `vite-hub` framework distribution, enable Rate Limit there and import from `vite-hub/rate-limit` instead. See the [Rate Limit guide](https://vitehub.dev/docs/rate-limit) for that application setup.
6
11
 
7
12
  ## Install the owner package
8
13
 
@@ -10,7 +15,7 @@ Install this owner package when you need a direct Rate Limiter, a custom driver,
10
15
  pnpm add @vite-hub/rate-limit
11
16
  ```
12
17
 
13
- The package requires Node 24 or newer. Vite is an optional peer dependency and is needed only for the managed Vite integration.
18
+ The package requires Node.js 22.18 or newer. Vite is an optional peer dependency and is needed only for the managed Vite integration.
14
19
 
15
20
  ## Get the first decision
16
21
 
@@ -42,44 +47,50 @@ node rate-limit.mjs
42
47
 
43
48
  The first two calls consume the budget. The third call returns a limited decision.
44
49
 
50
+ The window must resolve to finite milliseconds greater than zero, up to JavaScript's timestamp limit of `8.64e15` milliseconds. Invalid policies fail when you create the limiter.
51
+
52
+ Reset timestamps must also be positive and at most `8.64e15`. The memory driver rejects a fixed window whose end exceeds that range before it stores a counter. It preserves the configured duration. Custom driver timestamps outside that range throw regardless of the failure policy.
53
+
45
54
  ```text
46
55
  1: allowed
47
56
  2: allowed
48
57
  3: limited
49
58
  ```
50
59
 
51
- Direct Rate Limiters return a decision. Your code must stop the operation when `allowed` is false. The memory driver performs strict atomic consumption inside one process, so use it for development, tests, or a known single-process host. Its counters do not coordinate across processes, regions, or request-scoped runtimes.
60
+ Direct Rate Limiters return a decision. Your code must stop the operation when `allowed` is false. The memory driver performs strict atomic consumption inside one process, so use it for development, tests, or a known single-process host. A production build of declared Rate Limits does not accept `enforcement: "strict"` on memory. Its counters do not coordinate across processes, regions, or request-scoped runtimes.
52
61
 
53
62
  ## Choose managed guards or a direct driver
54
63
 
55
64
  | Need | Use |
56
65
  | -------------------------------------------------------------------------------------- | ------------------------------------------ |
57
- | Enforce a discovered Rate Limit in an H3 handler and let Vite generate provider output | `requireRateLimit()` with `hubRateLimit()` |
66
+ | Enforce a discovered Rate Limit in an H3 handler and let Nitro generate host bindings | `requireRateLimit()` with `hubRateLimit()` |
67
+ | The same managed limit, but answer a limited request yourself, such as with a fallback | `checkRateLimit()` with `hubRateLimit()` |
58
68
  | Return a custom response, use another transport, or supply storage yourself | `createRateLimiter()` with a direct driver |
59
69
 
60
70
  The managed path selects and configures a driver. The direct path gives your code the decision and leaves deployment integration to the application.
61
71
 
62
72
  ## Let Vite manage an H3 guard
63
73
 
64
- Register the standalone integration:
74
+ Register the integration with the Nitro Vite plugin. Nitro is the only host output:
65
75
 
66
76
  ```ts
67
77
  import { hubRateLimit } from "@vite-hub/rate-limit/vite";
78
+ import { nitro } from "nitro/vite";
68
79
  import { defineConfig } from "vite";
69
80
 
70
81
  export default defineConfig({
71
- plugins: [hubRateLimit({ namespace: "acme-image-service-production" })],
82
+ plugins: [hubRateLimit({ namespace: "acme-image-service-production" }), nitro()],
72
83
  });
73
84
  ```
74
85
 
75
86
  Then require a budget before expensive work:
76
87
 
77
- ```ts
88
+ ```ts fragment
78
89
  import { requireRateLimit } from "@vite-hub/rate-limit";
79
90
 
80
- export async function handleImageUpload(event): Promise<Response> {
81
- await requireRateLimit(event, "image-upload", {
82
- key: authenticatedUser.id,
91
+ export async function handleImageUpload(request: Request, userId: string): Promise<Response> {
92
+ await requireRateLimit(request, "image-upload", {
93
+ key: userId,
83
94
  limit: 10,
84
95
  window: "1m",
85
96
  });
@@ -88,36 +99,51 @@ export async function handleImageUpload(event): Promise<Response> {
88
99
  }
89
100
  ```
90
101
 
91
- The stable ID and provider policy must use static literals so the Vite integration can discover them and generate provider configuration. `event` and `key` are runtime values. If you omit `key`, the guard uses the request client address and fails when it cannot find one.
102
+ The stable ID and provider policy must use literals, or a `const` with a literal value in the same file, so the Vite integration can discover them and generate provider configuration. The request, `key`, `message`, and `code` are runtime values. `message` and `code` customize the `429` error of `requireRateLimit()`, and `checkRateLimit()` does not take them. The guard takes a Web `Request` or a request event with Standard Context properties, such as an H3 event in a ViteHub app. If you omit `key`, the guard uses the client address of the event and fails when it cannot find one. A `Request` has no client address, so pass `key`, except on Cloudflare, where the guard reads `cf-connecting-ip`.
92
103
 
93
- An allowed request continues. An exhausted budget throws an H3 `HTTPError` with status `429`. The default `failure: "deny"` turns an expected driver outage into status `503`; `failure: "allow"` lets the request continue. Use fail-open behavior only when the protected operation is safe without enforcement. Invalid configuration, malformed provider results, missing bindings, and driver defects still throw instead of following the failure policy.
104
+ An allowed request continues. An exhausted budget throws an H3 `HTTPError` with status `429` and the message `Rate limit exceeded.`. Pass `message` to set the message of the `429`, and `code` to set its `data.code`, for example `{ code: "errorTooManyTries", message: "Too many tries. Wait a minute and try again." }`. Both can be runtime values. `checkRateLimit()` does not accept them. The default `failure: "deny"` turns an expected driver outage into status `503`; `failure: "allow"` lets the request continue. Use fail-open behavior only when the protected operation is safe without enforcement. Invalid configuration, malformed provider results, missing bindings, and driver defects still throw instead of following the failure policy.
94
105
 
95
- Local Vite development uses the process-local memory driver. A Cloudflare Nitro preset selects Cloudflare Rate Limiting, and every deployed Worker and environment needs a unique namespace. ViteHub has no native Rate Limit driver for Vercel, Netlify, or Deno. Automatic provider selection fails for an unknown production host instead of falling back to unsafe per-instance memory. Select memory explicitly only for a known single-process deployment; otherwise supply a direct production driver. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before choosing a deployment target.
106
+ Local Vite development uses the process-local memory driver. `driver: "kv"` counts in the default KV store of `@vite-hub/kv` with one atomic `increment` for each request. The Nitro plugin asks KV at boot which driver the store uses: with `redis`, `database`, or `upstash`, every server process shares the counts. An explicit `driver: "kv"` on another driver, such as `fs-lite`, fails the build with `RATE_LIMIT_KV_STORE_UNSUPPORTED`; `vite dev` counts in memory. With ViteHub, a `node` build selects `kv` when KV is on, and `memory` otherwise; when ViteHub selected `kv` and the store cannot share counts, it counts in memory and prints a warning. A build that counts declared Rate Limits in memory prints a warning, and fails with `RATE_LIMIT_MEMORY_STRICT_UNSUPPORTED` for a Rate Limit with `enforcement: "strict"`. A Cloudflare Nitro preset selects Cloudflare Rate Limiting, and every deployed Worker and environment needs a unique namespace. ViteHub has no native Rate Limit driver for Vercel, Netlify, or Deno. Automatic driver selection fails for an unknown production host instead of falling back to unsafe per-instance memory. Select memory explicitly only for a known single-process deployment; otherwise supply a direct production driver. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before choosing a deployment target.
96
107
 
97
- Cloudflare enforcement is best-effort, location-scoped, and limited to `10s` and `1m` windows. It does not report portable remaining, reset, or retry metadata. A policy that requests strict enforcement or another window fails before deployment. The [Cloudflare host guide](https://vitehub.dev/docs/frameworks-hosts/cloudflare#rate-limiting-bindings) covers generated bindings and deployment verification.
108
+ Cloudflare enforcement is best-effort, location-scoped, and limited to `10s` and `1m` windows. It does not report portable remaining, reset, or retry metadata. A policy that requests strict enforcement or another window fails before deployment, and `vite dev` fails the same way when the build targets Cloudflare, although the dev server counts in memory. The [Cloudflare host guide](https://vitehub.dev/docs/frameworks-hosts/cloudflare#rate-limiting-bindings) covers generated bindings and deployment verification.
98
109
 
99
110
  ## Supply a direct driver
100
111
 
101
- Use `createRateLimiter()` when the application selects the driver and handles the decision. A production driver must implement one atomic `consume()` operation for its backend. A generic KV `get()` followed by `set()` is not safe under concurrent requests.
112
+ Use `createRateLimiter()` when the application selects the driver and handles the decision. A production driver must implement one atomic `consume()` operation for its backend. A generic KV `get()` followed by `set()` is not safe under concurrent requests. `kvRateLimitDriver({ storage })` uses an atomic `increment` instead, so it works with any KV store that has one, for example `kv.store("limits")` from `vite-hub/kv` on Redis or Postgres. Its counters also count rejected requests.
113
+
114
+ The KV driver waits at most one second for each storage operation. A timed-out operation returns `RATE_LIMIT_KV_TIMEOUT`: consume follows the `failure` policy; peek and reset return `unavailable`. The deadline does not cancel the storage operation, so a timed-out consume can still count. KV configuration errors still throw.
102
115
 
103
- Drivers return `[null, result]` after consuming the counter. They return `[error, undefined]` only for an expected operational outage. The limiter then returns `reason: "unavailable"` and sets `allowed` from the failure policy, which defaults to deny. Configuration errors, malformed provider results, and implementation defects must throw normally.
116
+ Drivers return a `Result`: `[undefined, result]` after consuming the counter, and `[error, undefined]` only for an expected operational outage. Return the error of the store when it has one, such as a KV `Result` error, or a `ResultError` from your own `defineErrors()` catalog. The limiter then returns `reason: "unavailable"` and sets `allowed` from the failure policy, which defaults to deny. ViteHub-owned configuration errors, malformed provider results, and implementation defects throw Nostics diagnostics with `RATE_LIMIT_B####` or `RATE_LIMIT_R####` codes. Application driver errors keep their identity. See [Errors and diagnostics](https://vitehub.dev/docs/reference/errors-diagnostics).
104
117
 
105
118
  The limiter exposes its resolved `policy` and the driver's declared `capabilities`, including enforcement, counter scope, rejected-attempt behavior, and supported windows. Inspect them when deciding whether a driver fits a deployment.
106
119
 
120
+ ## Read or reset a counter
121
+
122
+ `limiter.peek({ key })` reads the counter of a key without consuming a token. `limiter.reset({ key })` deletes the counter. A driver supports them through optional `peek(input)` and `reset(input)` methods. Like `consume()`, `peek()` returns `[undefined, value]` or `[error, undefined]`. The `reset()` method returns `[undefined, undefined]` or `[error, undefined]`. When the driver omits a method, the result has `status: "unsupported"` and a `reason`.
123
+
124
+ | Driver | `peek()` | `reset()` |
125
+ | ---------- | ------------------------------------------------------------------------- | --------------------- |
126
+ | memory | `used`, `remaining`, and `resetAt` in this process. `used: 0` when no counter exists. | Deletes the counter. |
127
+ | kv | `used`, `remaining`, and `resetAt` of the current window, shared by every process. | Deletes the counter of the current window. |
128
+ | cloudflare | `unsupported`. The binding exposes only `limit()`, which consumes a token. | `unsupported`. |
129
+
130
+ For managed guards, `peekRateLimit(id, key)` and `resetRateLimit(id, key)` use the counters of `requireRateLimit()` in the current runtime. `vitehub rate-limit peek <id> <key>` and `vitehub rate-limit reset <id> <key>` (which asks on a terminal, or needs `--yes`) run the `rate-limit.peek` and `rate-limit.reset` operations of the running app, on the dev server or with `--url` on a deployed app that enables the Console. The Console **Rate Limits** page runs the same operations.
131
+
107
132
  ## Public imports
108
133
 
109
134
  | Import | Purpose |
110
135
  | ----------------------------------------- | ------------------------------------------------------------------------- |
111
- | `@vite-hub/rate-limit` | `requireRateLimit()`, `createRateLimiter()`, and public contract types |
136
+ | `@vite-hub/rate-limit` | `requireRateLimit()`, `checkRateLimit()`, `createRateLimiter()`, `peekRateLimit()`, `resetRateLimit()`, and public contract types |
112
137
  | `@vite-hub/rate-limit/drivers/memory` | Process-local fixed-window driver |
138
+ | `@vite-hub/rate-limit/drivers/kv` | Fixed-window driver on a KV store with an atomic `increment` |
113
139
  | `@vite-hub/rate-limit/drivers/cloudflare` | Direct adapter for a request-scoped Cloudflare Rate Limiting binding |
114
- | `@vite-hub/rate-limit/vite` | Source discovery, runtime setup, manifest generation, and provider output |
140
+ | `@vite-hub/rate-limit/vite` | Source discovery, Nitro runtime setup, manifest generation, and Cloudflare bindings |
115
141
 
116
142
  `@vite-hub/rate-limit/runtime` is reserved for framework integrations. Application code should use the guard or a direct Rate Limiter.
117
143
 
118
144
  ## Go deeper
119
145
 
120
- - [Rate Limit guide](https://vitehub.dev/docs/server-primitives/rate-limit)
121
- - [Rate Limit Capability for Agents](https://vitehub.dev/docs/capabilities/rate-limit)
146
+ - [Rate Limit guide](https://vitehub.dev/docs/rate-limit)
147
+ - [Rate Limit Capability for Agents](https://vitehub.dev/docs/rate-limit/agent-capability)
122
148
  - [Runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix)
123
149
  - [Public import paths](https://vitehub.dev/docs/reference/import-paths)
@@ -0,0 +1,163 @@
1
+ import { Diagnostic } from "nostics";
2
+ //#region ../internal/src/host-credentials.d.ts
3
+ interface HostCliRunResult {
4
+ exitCode: number | null;
5
+ stdout: string;
6
+ }
7
+ /** Runs a host CLI with an argument array and no shell, and returns its stdout. */
8
+ type HostCliRun = (command: string, args: readonly string[], options: {
9
+ cwd?: string;
10
+ env: NodeJS.ProcessEnv;
11
+ signal?: AbortSignal;
12
+ }) => Promise<HostCliRunResult>;
13
+ //#endregion
14
+ //#region ../internal/src/provision.d.ts
15
+ type ProvisionProvider = "cloudflare" | "vercel";
16
+ interface ProvisionLogger {
17
+ log: (message: string) => void;
18
+ warn: (message: string) => void;
19
+ }
20
+ interface ProvisionContext {
21
+ env: Record<string, string | undefined>;
22
+ fetch: typeof globalThis.fetch;
23
+ logger: ProvisionLogger;
24
+ markPlanUnchecked?: () => void;
25
+ }
26
+ interface ProvisionState {
27
+ cloudflare?: Record<string, Record<string, string>>;
28
+ vercel?: Record<string, Record<string, string>>;
29
+ }
30
+ interface ProvisionResult {
31
+ ids?: ProvisionState;
32
+ }
33
+ interface ProvisionAction {
34
+ kind: string;
35
+ name: string;
36
+ exists: boolean;
37
+ pending?: boolean;
38
+ /** Describes the change that `apply()` makes to an existing resource, for example `read replication: disabled -> auto`. */
39
+ update?: string;
40
+ apply: () => Promise<ProvisionResult>;
41
+ }
42
+ /** One Provision State category that a step records, with the keys that current Definitions use. */
43
+ interface ProvisionStateCategory {
44
+ category: string;
45
+ declared: readonly string[];
46
+ /** Provider resource identity for shared-resource checks. Return undefined when the recorded id lacks enough information. Defaults to the recorded id. */
47
+ resourceIdentity?: (entry: {
48
+ id: string;
49
+ key: string;
50
+ }) => string | undefined;
51
+ /** Identity expected by current config for a declared key. Omit when it cannot be established without provider access. */
52
+ declaredResourceIdentity?: (key: string) => string | undefined;
53
+ /** Tells a developer how to delete the resource of a recorded entry that no Definition declares. ViteHub never runs it. */
54
+ deleteHint: (entry: {
55
+ id: string;
56
+ key: string;
57
+ }) => string;
58
+ }
59
+ interface ProvisionStep {
60
+ id: string;
61
+ provider: ProvisionProvider;
62
+ plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
63
+ /** Describes the Provision State this step records. Runs without network access, also without credentials. */
64
+ recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
65
+ }
66
+ //#endregion
67
+ //#region ../internal/src/cli.d.ts
68
+ interface ViteHubCliStreams {
69
+ stderr: {
70
+ write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
71
+ };
72
+ stdout: {
73
+ write: (chunk: string | Uint8Array) => unknown;
74
+ };
75
+ }
76
+ interface ViteHubCliSpawnResult {
77
+ exitCode: number | null;
78
+ signal?: NodeJS.Signals | null;
79
+ /** The output of the child when `stdout` is `pipe`. */
80
+ stdout?: string;
81
+ }
82
+ interface ViteHubCliSpawnOptions {
83
+ cwd?: string;
84
+ env?: NodeJS.ProcessEnv;
85
+ stderr?: "inherit" | "pipe";
86
+ /** `ignore` gives the child no terminal input, so a tool that asks questions on a terminal does not ask. */
87
+ stdin?: "ignore" | "inherit";
88
+ /** `stderr` sends the child's stdout to the parent's stderr, so the parent's stdout keeps only its own output. */
89
+ stdout?: "inherit" | "pipe" | "stderr";
90
+ }
91
+ type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
92
+ interface ViteHubCliContext extends ViteHubCliStreams {
93
+ cwd: string;
94
+ env: NodeJS.ProcessEnv;
95
+ /** Replaces `fetch` for commands that call a running app, so tests need no server. */
96
+ fetch?: typeof fetch;
97
+ /**
98
+ * Loads the project config for a build on `host` and returns the Provision Steps of its plugins, with the config root
99
+ * that holds `.vitehub/provision.json`. Setup commands, such as `vitehub deploy`, call it only when they need the
100
+ * steps, so they still run on a config that throws.
101
+ */
102
+ loadProvision?: (host: ProvisionProvider) => Promise<ViteHubCliProvision>;
103
+ /** The deployed app's public origin from `vitehub({ publicUrl })`, when it is one string. */
104
+ publicUrl?: string;
105
+ rootDir: string;
106
+ /** Replaces the host CLI runner, such as for `wrangler auth token`, so tests need no real host CLI. */
107
+ runHostCli?: HostCliRun;
108
+ spawn: ViteHubCliSpawn;
109
+ }
110
+ interface ViteHubCliProvision {
111
+ rootDir: string;
112
+ steps: readonly ProvisionStep[];
113
+ }
114
+ interface ViteHubCliFeature {
115
+ description?: string;
116
+ name: string;
117
+ run: (args: string[], context: ViteHubCliContext) => Promise<number | void> | number | void;
118
+ usage?: string;
119
+ }
120
+ interface ViteHubCliCommandNamespace {
121
+ /** The feature that `vitehub <name>` runs when the next argument names no other feature. It gets every argument after `<name>`. */
122
+ defaultFeature?: string;
123
+ description?: string;
124
+ features: ViteHubCliFeature[];
125
+ name: string;
126
+ }
127
+ /** The flags of `vitehub seed` that every seed gets. */
128
+ interface ViteHubCliSeedOptions {
129
+ /** `--database <name>`: seed only this Database. Only the Database seed runs. */
130
+ database?: string;
131
+ /** The process environment with the env files of `--stage`. */
132
+ env: NodeJS.ProcessEnv;
133
+ /** `--remote`: write the deployed stores. Without it, a seed writes only local data. */
134
+ remote: boolean;
135
+ /** `--timeout <ms>` of each call to the app. */
136
+ timeout?: number;
137
+ /** The deployed app with `--remote`: `--url`, or `vitehub({ publicUrl })`. */
138
+ url?: string;
139
+ }
140
+ /** The seed files of one primitive, which `vitehub seed` writes. */
141
+ interface ViteHubCliSeed {
142
+ /** Where the seed files are, such as `server/seed/kv/`. `vitehub seed` names it when it finds no seed files. */
143
+ files: string;
144
+ /** The primitive, such as `database` or `kv`. `vitehub seed <name>` runs only this seed. */
145
+ name: string;
146
+ /** Writes the seed files and returns the exit code, or `undefined` when the project has no seed files for this primitive. */
147
+ run: (options: ViteHubCliSeedOptions, context: ViteHubCliContext) => Promise<number | undefined>;
148
+ }
149
+ interface ViteHubCliContributor {
150
+ namespaces: ViteHubCliCommandNamespace[];
151
+ provision?: ProvisionStep[];
152
+ /** The seed files that `vitehub seed` writes. */
153
+ seeds?: ViteHubCliSeed[];
154
+ /** The deployed app's public origin. Commands receive it as `context.publicUrl`. */
155
+ publicUrl?: string;
156
+ }
157
+ type ViteHubCliContributorFactory = () => ViteHubCliContributor | undefined | Promise<ViteHubCliContributor | undefined>;
158
+ interface ViteHubCliPluginMetadata {
159
+ cli?: ViteHubCliContributor | ViteHubCliContributorFactory;
160
+ }
161
+ type StdoutWriteCallback = (error?: Error | null) => void;
162
+ //#endregion
163
+ export { ViteHubCliStreams as i, ViteHubCliContributor as n, ViteHubCliPluginMetadata as r, ViteHubCliContext as t };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-szm60zN5.js";
2
+ //#region src/cli.d.ts
3
+ export type RateLimitCliContext = Pick<ViteHubCliContext, "cwd" | "env" | "fetch" | "rootDir"> & ViteHubCliStreams;
4
+ export interface RateLimitCliOptions {
5
+ /** Asks whether `reset` may delete a counter. Defaults to a prompt on a terminal, and refuses without one. */
6
+ confirm?: (question: string) => boolean | Promise<boolean>;
7
+ fetch?: typeof fetch;
8
+ }
9
+ /**
10
+ * Runs one `vitehub rate-limit` command through the `rate-limit.*` operations, on the dev server of this project or on a
11
+ * deployed app with `--url`.
12
+ * `args[0]` is the command name, `peek` or `reset`.
13
+ */
14
+ export declare function runRateLimitCli(args: string[], context: RateLimitCliContext, options?: RateLimitCliOptions): Promise<number>;
15
+ export declare function createRateLimitCliContributor(options?: RateLimitCliOptions): ViteHubCliContributor;
16
+ //#endregion
package/dist/cli.js ADDED
@@ -0,0 +1,259 @@
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
2
+ import { t as redactInspectionText } from "./inspect-B6gTdgy9.js";
3
+ import { A as writeCliFailure, E as askOnTerminal, O as readViteHubDevTargetOption, n as callOperationFromCli, u as table } from "./operations-BYRa7wpx.js";
4
+ import * as v from "valibot";
5
+ //#region src/cli.ts
6
+ const rateLimitDevTargetErrors = {
7
+ invalidInlineTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
8
+ invalidTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
9
+ missingValue: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message })
10
+ };
11
+ const rateLimitCommands = [{
12
+ description: "Show the counter of one key without consuming a token.",
13
+ name: "peek"
14
+ }, {
15
+ description: "Delete the counter of one key, where the provider supports it.",
16
+ name: "reset"
17
+ }];
18
+ function commandUsage(command) {
19
+ return `vitehub rate-limit ${command.name} <id> <key> [--json]${command.name === "reset" ? " [--yes]" : ""} [--url <url>]`;
20
+ }
21
+ function writeUsage(command, stream) {
22
+ stream.write([
23
+ `Usage: ${commandUsage(command)}`,
24
+ "",
25
+ command.description,
26
+ "The command runs the rate-limit operation of the app: on the dev server of this project, or on a deployed app with --url.",
27
+ "`<id>` is the stable ID of `requireRateLimit()`. `<key>` is the limited key, for example a client IP or user ID.",
28
+ "",
29
+ "Use -- before a key that starts with a dash.",
30
+ "",
31
+ "Options:",
32
+ ...command.name === "reset" ? [" --yes, -y Reset without asking. Without it, the command asks on a terminal and refuses elsewhere."] : [],
33
+ " --json Print JSON.",
34
+ " --url <url> Deployed app URL. Set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to sign the calls. Defaults to the dev server of this project.",
35
+ " --timeout <ms> Request timeout.",
36
+ " -h, --help Show this help.",
37
+ ""
38
+ ].join("\n"));
39
+ }
40
+ function parseArgs(args) {
41
+ const parsed = {
42
+ help: false,
43
+ json: false,
44
+ yes: false
45
+ };
46
+ let positionalOnly = false;
47
+ for (let index = 0; index < args.length; index += 1) {
48
+ const arg = args[index];
49
+ if (!positionalOnly && arg === "--") {
50
+ positionalOnly = true;
51
+ continue;
52
+ }
53
+ if (!positionalOnly && (arg === "-h" || arg === "--help")) {
54
+ parsed.help = true;
55
+ continue;
56
+ }
57
+ if (!positionalOnly && (arg === "--yes" || arg === "-y")) {
58
+ parsed.yes = true;
59
+ continue;
60
+ }
61
+ if (!positionalOnly && arg === "--json") {
62
+ parsed.json = true;
63
+ continue;
64
+ }
65
+ const targetOption = positionalOnly ? void 0 : readViteHubDevTargetOption(args, index, parsed, rateLimitDevTargetErrors);
66
+ if (targetOption !== void 0) {
67
+ index += targetOption;
68
+ continue;
69
+ }
70
+ if (!positionalOnly && arg.startsWith("-")) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: `Unknown option: ${arg}.` });
71
+ if (parsed.name === void 0) {
72
+ parsed.name = arg;
73
+ continue;
74
+ }
75
+ if (parsed.key === void 0) {
76
+ parsed.key = arg;
77
+ continue;
78
+ }
79
+ throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: `Unexpected argument: ${arg}.` });
80
+ }
81
+ if (!parsed.help && !parsed.name) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: "Missing Rate Limit ID." });
82
+ if (!parsed.help && !parsed.key) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: "Missing Rate Limit key." });
83
+ return parsed;
84
+ }
85
+ function scopeNotice(scope) {
86
+ return scope === "process" ? "Scope: process. The counter exists only in this server process." : `Scope: ${scope}.`;
87
+ }
88
+ function formatPeek(result) {
89
+ const header = `Rate Limit ${result.name}, key ${result.key}\nProvider: ${result.provider}\n`;
90
+ if (result.status !== "known") return `${header}${result.status === "unused" ? "No counter" : "Counter unknown"}: ${result.reason}\n`;
91
+ return `${header}${scopeNotice(result.scope)}\n${table([[
92
+ "LIMIT",
93
+ "WINDOW",
94
+ "USED",
95
+ "REMAINING",
96
+ "RESETS AT"
97
+ ], ...result.counters.map((counter) => [
98
+ String(counter.limit),
99
+ counter.window,
100
+ String(counter.used),
101
+ String(counter.remaining),
102
+ counter.resetAt === void 0 ? "-" : new Date(counter.resetAt).toISOString()
103
+ ])])}\n`;
104
+ }
105
+ function formatReset(result) {
106
+ if (result.status !== "reset") return `Rate Limit ${result.name}, key ${result.key}\nProvider: ${result.provider}\nNot reset: ${result.reason}\n`;
107
+ return `Reset Rate Limit ${result.name} for key ${result.key}.\nProvider: ${result.provider}\n${scopeNotice(result.scope)}\n`;
108
+ }
109
+ const windowSchema = v.custom((value) => v.is(v.pipe(v.string(), v.regex(/^\d+(?:\.\d+)?(?:ms|s|m|h|d)$/)), value));
110
+ const finiteNumber = v.pipe(v.number(), v.finite());
111
+ const targetFields = {
112
+ key: v.string(),
113
+ name: v.string(),
114
+ provider: v.picklist([
115
+ "memory",
116
+ "kv",
117
+ "cloudflare"
118
+ ])
119
+ };
120
+ const scopeSchema = v.picklist([
121
+ "global",
122
+ "location",
123
+ "process"
124
+ ]);
125
+ const counterSchema = v.object({
126
+ limit: finiteNumber,
127
+ remaining: finiteNumber,
128
+ resetAt: v.optional(v.pipe(finiteNumber, v.minValue(-864e13), v.maxValue(864e13))),
129
+ used: finiteNumber,
130
+ window: windowSchema,
131
+ windowMs: finiteNumber
132
+ });
133
+ const unavailableSchema = v.object({
134
+ ...targetFields,
135
+ reason: v.string(),
136
+ status: v.literal("unavailable")
137
+ });
138
+ const unsupportedSchema = v.object({
139
+ ...targetFields,
140
+ reason: v.string(),
141
+ status: v.literal("unsupported")
142
+ });
143
+ const peekSchema = v.variant("status", [
144
+ v.object({
145
+ ...targetFields,
146
+ counters: v.array(counterSchema),
147
+ scope: scopeSchema,
148
+ status: v.literal("known")
149
+ }),
150
+ v.object({
151
+ ...targetFields,
152
+ reason: v.string(),
153
+ status: v.literal("unused")
154
+ }),
155
+ unavailableSchema,
156
+ unsupportedSchema
157
+ ]);
158
+ const resetSchema = v.variant("status", [
159
+ v.object({
160
+ ...targetFields,
161
+ scope: scopeSchema,
162
+ status: v.literal("reset")
163
+ }),
164
+ unavailableSchema,
165
+ unsupportedSchema
166
+ ]);
167
+ function parseInspection(operation, value) {
168
+ if (operation === "peek") {
169
+ const parsed = v.safeParse(peekSchema, value);
170
+ return parsed.success ? {
171
+ operation,
172
+ value: parsed.output
173
+ } : void 0;
174
+ }
175
+ const parsed = v.safeParse(resetSchema, value);
176
+ return parsed.success ? {
177
+ operation,
178
+ value: parsed.output
179
+ } : void 0;
180
+ }
181
+ /** Writes a failure like the other primitive CLIs, but redacts the message, since it can echo a limited key. */
182
+ function writeFailure(parsed, context, failure) {
183
+ return writeCliFailure(parsed.json, context, {
184
+ ...failure,
185
+ message: redactInspectionText(failure.message)
186
+ });
187
+ }
188
+ async function runRateLimitCommand(command, args, context, options) {
189
+ let parsed;
190
+ try {
191
+ parsed = parseArgs(args);
192
+ } catch (error) {
193
+ const terminator = args.indexOf("--");
194
+ if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json")) return writeFailure({ json: true }, context, { message: error instanceof Error ? error.message : String(error) });
195
+ writeFailure({ json: false }, context, { message: error instanceof Error ? error.message : String(error) });
196
+ writeUsage(command, context.stderr);
197
+ return 1;
198
+ }
199
+ if (parsed.help) {
200
+ writeUsage(command, context.stdout);
201
+ return 0;
202
+ }
203
+ if (command.name === "reset" && !parsed.yes) {
204
+ const question = `Reset the Rate Limit ${parsed.name} for key ${redactInspectionText(parsed.key)}? The next request starts a new window. [y/N] `;
205
+ if (!(options.confirm ? await options.confirm(question) : process.stdin.isTTY && process.stderr.isTTY ? await askOnTerminal(question) : false)) return writeFailure(parsed, context, {
206
+ code: "RATE_LIMIT_NOT_CONFIRMED",
207
+ fix: "Run it again with --yes.",
208
+ message: "rate-limit reset deletes a counter and was not confirmed."
209
+ });
210
+ }
211
+ const called = await callOperationFromCli({
212
+ env: context.env,
213
+ fetch: context.fetch ?? options.fetch ?? globalThis.fetch,
214
+ rootDir: context.rootDir,
215
+ ...parsed.timeout ? { timeout: parsed.timeout } : {},
216
+ ...parsed.url ? { url: parsed.url } : {}
217
+ }, `rate-limit.${command.name}`, {
218
+ key: parsed.key,
219
+ name: parsed.name
220
+ });
221
+ if (!called.ok) return writeFailure(parsed, context, {
222
+ code: called.code,
223
+ message: called.message,
224
+ ...called.fix ? { fix: called.fix } : {}
225
+ });
226
+ const result = parseInspection(command.name, called.value);
227
+ if (!result) return writeFailure(parsed, context, { message: "The rate-limit operation answered with an invalid result." });
228
+ const output = result.operation === "peek" ? formatPeek(result.value) : formatReset(result.value);
229
+ context.stdout.write(parsed.json ? `${JSON.stringify(result.value, null, 2)}\n` : output);
230
+ return result.value.status === "unsupported" || result.value.status === "unavailable" ? 1 : 0;
231
+ }
232
+ /**
233
+ * Runs one `vitehub rate-limit` command through the `rate-limit.*` operations, on the dev server of this project or on a
234
+ * deployed app with `--url`.
235
+ * `args[0]` is the command name, `peek` or `reset`.
236
+ */
237
+ async function runRateLimitCli(args, context, options = {}) {
238
+ const [name, ...rest] = args;
239
+ const command = rateLimitCommands.find((entry) => entry.name === name);
240
+ if (!command) {
241
+ context.stderr.write(`${name ? `Unknown rate-limit command: ${redactInspectionText(name)}\n` : ""}Commands: ${rateLimitCommands.map((entry) => entry.name).join(", ")}\n`);
242
+ return 1;
243
+ }
244
+ return await runRateLimitCommand(command, rest, context, options);
245
+ }
246
+ function createRateLimitCliContributor(options = {}) {
247
+ return { namespaces: [{
248
+ description: "Read and reset Rate Limit counters in the running app.",
249
+ features: rateLimitCommands.map((command) => ({
250
+ description: command.description,
251
+ name: command.name,
252
+ run: async (args, context) => await runRateLimitCommand(command, args, context, options),
253
+ usage: commandUsage(command)
254
+ })),
255
+ name: "rate-limit"
256
+ }] };
257
+ }
258
+ //#endregion
259
+ export { createRateLimitCliContributor, runRateLimitCli };
@@ -1,3 +1,5 @@
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
2
+ import { toResultError } from "@vite-hub/runtime";
1
3
  //#region ../internal/src/integrations/hex.ts
2
4
  const textEncoder = new TextEncoder();
3
5
  new TextDecoder();
@@ -17,7 +19,7 @@ function isBinding(value) {
17
19
  return Boolean(value) && typeof value === "object" && typeof value.limit === "function";
18
20
  }
19
21
  function cloudflareRateLimitDriver(options) {
20
- if (!isBinding(options?.binding)) throw new TypeError("[vitehub] cloudflareRateLimitDriver() requires a Cloudflare Rate Limit binding.");
22
+ if (!isBinding(options?.binding)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0004({ message: "[vitehub] cloudflareRateLimitDriver() requires a Cloudflare Rate Limit binding." });
21
23
  return {
22
24
  capabilities: {
23
25
  enforcement: "best-effort",
@@ -30,10 +32,13 @@ function cloudflareRateLimitDriver(options) {
30
32
  try {
31
33
  result = await options.binding.limit({ key: input.key });
32
34
  } catch (cause) {
33
- return [new Error("[vitehub] Cloudflare Rate Limit binding failed.", { cause }), void 0];
35
+ return [toResultError(rateLimitErrorDiagnostics.RATE_LIMIT_R0005({
36
+ message: "[vitehub] Cloudflare Rate Limit binding failed.",
37
+ cause
38
+ })), void 0];
34
39
  }
35
- if (!result || typeof result.success !== "boolean") throw new TypeError("[vitehub] Cloudflare Rate Limit binding returned an invalid result.");
36
- return [null, { allowed: result.success }];
40
+ if (!result || typeof result.success !== "boolean") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0006({ message: "[vitehub] Cloudflare Rate Limit binding returned an invalid result." });
41
+ return [void 0, { allowed: result.success }];
37
42
  },
38
43
  name: "cloudflare"
39
44
  };