@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.
@@ -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 };
@@ -0,0 +1,293 @@
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
2
+ import * as v from "valibot";
3
+ import { Diagnostic } from "nostics";
4
+ //#region src/policy.ts
5
+ const rateLimitPolicyKeys = /* @__PURE__ */ new Set([
6
+ "enforcement",
7
+ "failure",
8
+ "limit",
9
+ "window"
10
+ ]);
11
+ const unitMilliseconds = {
12
+ d: 864e5,
13
+ h: 36e5,
14
+ m: 6e4,
15
+ ms: 1,
16
+ s: 1e3
17
+ };
18
+ function parseRateLimitWindow(value) {
19
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(value);
20
+ if (!match) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0031({ message: "[vitehub] Rate Limit window must use a duration such as \"10s\", \"1m\", \"1h\", or \"1d\"." });
21
+ const unitMs = unitMilliseconds[match[2]];
22
+ const [integer, fraction = ""] = match[1].split(".");
23
+ const fractionalOverflow = Number(integer) === 864e13 / unitMs && /[1-9]/.test(fraction);
24
+ const windowMs = Math.ceil(Number(match[1]) * unitMs);
25
+ if (!Number.isFinite(windowMs) || windowMs <= 0 || windowMs > 864e13 || fractionalOverflow) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0032({ message: "[vitehub] Rate Limit window must resolve to finite milliseconds greater than zero and at most 8640000000000000." });
26
+ return windowMs;
27
+ }
28
+ function normalizeRateLimitPolicy(policy) {
29
+ if (!policy || typeof policy !== "object" || Array.isArray(policy)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0033({ message: "[vitehub] Rate Limit policy must be an object." });
30
+ const limit = Object.hasOwn(policy, "limit") ? policy.limit : void 0;
31
+ const duration = Object.hasOwn(policy, "window") ? policy.window : void 0;
32
+ const enforcement = Object.hasOwn(policy, "enforcement") ? policy.enforcement : void 0;
33
+ const failure = Object.hasOwn(policy, "failure") ? policy.failure : void 0;
34
+ if (limit === void 0 || !Number.isInteger(limit) || limit <= 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0034({ message: "[vitehub] Rate Limit limit must be a positive integer." });
35
+ if (typeof duration !== "string") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0031({ message: "[vitehub] Rate Limit window must use a duration such as \"10s\", \"1m\", \"1h\", or \"1d\"." });
36
+ if (enforcement !== void 0 && enforcement !== "best-effort" && enforcement !== "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0035({ message: "[vitehub] Rate Limit enforcement must be \"best-effort\" or \"strict\"." });
37
+ if (failure !== void 0 && failure !== "allow" && failure !== "deny") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0036({ message: "[vitehub] Rate Limit failure must be \"allow\" or \"deny\"." });
38
+ return {
39
+ enforcement: enforcement ?? "best-effort",
40
+ failure: failure ?? "deny",
41
+ limit,
42
+ window: duration,
43
+ windowMs: parseRateLimitWindow(duration)
44
+ };
45
+ }
46
+ function declaredRateLimitPolicy(policy) {
47
+ return {
48
+ enforcement: policy.enforcement,
49
+ failure: policy.failure,
50
+ limit: policy.limit,
51
+ window: policy.window
52
+ };
53
+ }
54
+ //#endregion
55
+ //#region src/limiter.ts
56
+ const driverErrorSchema = v.custom((value) => {
57
+ return ("isError" in Error && v.is(v.function(), Error.isError) ? Error.isError(value) === true : v.is(v.instance(Error), value) || v.is(v.object({}), value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null && Object.prototype.toString.call(value) === "[object Error]") && v.is(v.object({
58
+ message: v.string(),
59
+ name: v.string()
60
+ }), value);
61
+ });
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()]));
64
+ function resolveDriverCapabilities(options, capabilities = options.driver.capabilities, driverName = options.driver.name) {
65
+ if (!capabilities || typeof capabilities !== "object") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0019({ message: `[vitehub] Rate Limit driver "${driverName}" must declare capabilities.` });
66
+ if (capabilities.enforcement !== "best-effort" && capabilities.enforcement !== "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0020({ message: `[vitehub] Rate Limit driver "${driverName}" must declare valid enforcement.` });
67
+ if (capabilities.scope !== "process" && capabilities.scope !== "location" && capabilities.scope !== "global") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0021({ message: `[vitehub] Rate Limit driver "${driverName}" must declare counter scope.` });
68
+ if (capabilities.rejectedAttempts !== "counted" && capabilities.rejectedAttempts !== "not-counted" && capabilities.rejectedAttempts !== "unknown") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0022({ message: `[vitehub] Rate Limit driver "${driverName}" must declare rejected-attempt behavior.` });
69
+ if (capabilities.windows !== void 0 && hasInvalidSupportedWindows(capabilities.windows)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0023({ message: `[vitehub] Rate Limit driver "${driverName}" windows must contain positive integer milliseconds.` });
70
+ return {
71
+ enforcement: capabilities.enforcement,
72
+ rejectedAttempts: capabilities.rejectedAttempts,
73
+ scope: capabilities.scope,
74
+ ...capabilities.windows ? { windows: [...capabilities.windows] } : {}
75
+ };
76
+ }
77
+ function hasInvalidSupportedWindows(value) {
78
+ if (!Array.isArray(value)) return true;
79
+ for (let index = 0; index < value.length; index++) {
80
+ const windowMs = value[index];
81
+ if (typeof windowMs !== "number" || !Number.isInteger(windowMs) || windowMs <= 0 || windowMs > 864e13) return true;
82
+ }
83
+ return false;
84
+ }
85
+ function normalizeOptionalInteger(value, label) {
86
+ if (value === void 0) return;
87
+ if (!Number.isInteger(value) || value < 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0024({ message: `[vitehub] Rate Limit driver result ${label} must be a non-negative integer.` });
88
+ return value;
89
+ }
90
+ function normalizeDriverResult(result, limit, windowMs) {
91
+ if (!result || typeof result !== "object" || typeof result.allowed !== "boolean") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0025({ message: "[vitehub] Rate Limit driver consume() must return an object with an allowed boolean." });
92
+ const resetAt = result.resetAt;
93
+ if (resetAt !== void 0 && (!v.is(v.number(), resetAt) || !Number.isFinite(resetAt) || resetAt <= 0 || resetAt > 864e13)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0026({ message: "[vitehub] Rate Limit driver result resetAt must be a positive timestamp at most 8640000000000000 milliseconds." });
94
+ const decision = {
95
+ limit,
96
+ remaining: normalizeOptionalInteger(result.remaining, "remaining"),
97
+ resetAt,
98
+ retryAfter: normalizeOptionalInteger(result.retryAfter, "retryAfter"),
99
+ used: normalizeOptionalInteger(result.used, "used"),
100
+ windowMs
101
+ };
102
+ return result.allowed ? {
103
+ ...decision,
104
+ allowed: true
105
+ } : {
106
+ ...decision,
107
+ allowed: false,
108
+ reason: "limited"
109
+ };
110
+ }
111
+ function assertDriverSupportsPolicy(options, capabilities, windowMs, driverName = options.driver.name) {
112
+ if ((options.enforcement ?? "best-effort") === "strict" && capabilities.enforcement !== "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0027({ message: `[vitehub] Rate Limit driver "${driverName}" provides best-effort enforcement, but this policy requires strict enforcement.` });
113
+ const windows = capabilities.windows;
114
+ if (windows?.length && !windows.includes(windowMs)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0028({ message: `[vitehub] Rate Limit driver "${driverName}" does not support a ${windowMs}ms window. Supported windows: ${windows.join(", ")}ms.` });
115
+ }
116
+ const driverPeekResultSchema = v.object({
117
+ resetAt: v.optional(v.unknown()),
118
+ used: v.pipe(v.number(), v.integer(), v.minValue(0))
119
+ });
120
+ function normalizePeekResult(result, policy) {
121
+ if (!v.is(driverPeekResultSchema, result)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0037({ message: "[vitehub] Rate Limit driver peek() must return an object with a non-negative integer used count." });
122
+ const resetAt = result.resetAt;
123
+ if (resetAt !== void 0 && (!v.is(v.number(), resetAt) || !Number.isFinite(resetAt) || resetAt <= 0 || resetAt > 864e13)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0037({ message: "[vitehub] Rate Limit driver peek() resetAt must be a positive timestamp at most 8640000000000000 milliseconds." });
124
+ return {
125
+ limit: policy.limit,
126
+ remaining: Math.max(0, policy.limit - result.used),
127
+ ...resetAt === void 0 ? {} : { resetAt },
128
+ status: "known",
129
+ used: result.used,
130
+ windowMs: policy.windowMs
131
+ };
132
+ }
133
+ function unsupportedReason(driverName, operation) {
134
+ return operation === "peek" ? `The "${driverName}" Rate Limit driver cannot read a counter without consuming a token.` : `The "${driverName}" Rate Limit driver cannot reset a counter.`;
135
+ }
136
+ function assertKey(input, operation) {
137
+ if (!input || !v.is(v.string(), input.key) || input.key.length === 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0038({ message: `[vitehub] Rate Limiter ${operation}() requires a non-empty key.` });
138
+ }
139
+ function isRateLimiterOptions(value) {
140
+ if (!value || typeof value !== "object") return false;
141
+ try {
142
+ return !Array.isArray(value);
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+ function ownOption(options, key) {
148
+ return Object.hasOwn(options, key) ? Reflect.get(options, key) : void 0;
149
+ }
150
+ function inspectRateLimiterOptions(options) {
151
+ const driver = Reflect.get(options, "driver");
152
+ const consume = Reflect.get(driver, "consume");
153
+ if (typeof consume !== "function") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0029({ message: "[vitehub] createRateLimiter() requires a Rate Limit driver with a consume() function." });
154
+ const peek = Reflect.get(driver, "peek");
155
+ const reset = Reflect.get(driver, "reset");
156
+ const policy = {
157
+ driver,
158
+ limit: ownOption(options, "limit"),
159
+ window: ownOption(options, "window"),
160
+ enforcement: ownOption(options, "enforcement"),
161
+ failure: ownOption(options, "failure"),
162
+ name: Reflect.get(options, "name")
163
+ };
164
+ const capabilities = Reflect.get(driver, "capabilities");
165
+ if (!capabilities || typeof capabilities !== "object") return {
166
+ policy,
167
+ capabilities,
168
+ driverName: Reflect.get(driver, "name"),
169
+ consume,
170
+ peek,
171
+ reset
172
+ };
173
+ const windows = Reflect.get(capabilities, "windows");
174
+ const inspectedCapabilities = {
175
+ enforcement: Reflect.get(capabilities, "enforcement"),
176
+ rejectedAttempts: Reflect.get(capabilities, "rejectedAttempts"),
177
+ scope: Reflect.get(capabilities, "scope")
178
+ };
179
+ if (windows !== void 0) Object.assign(inspectedCapabilities, { windows });
180
+ return {
181
+ policy,
182
+ capabilities: inspectedCapabilities,
183
+ driverName: Reflect.get(driver, "name"),
184
+ consume,
185
+ peek,
186
+ reset
187
+ };
188
+ }
189
+ function isRateLimitDiagnostic(value) {
190
+ try {
191
+ return value instanceof Diagnostic && rateLimitDiagnosticCodes.has(value.code);
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+ const rateLimitDiagnosticCodes = /* @__PURE__ */ new Set([
197
+ ...Array.from({ length: 47 }, (_, index) => `RATE_LIMIT_R${String(index + 1).padStart(4, "0")}`),
198
+ "RATE_LIMIT_B0001",
199
+ "RATE_LIMIT_B0002",
200
+ "RATE_LIMIT_B0003",
201
+ "RATE_LIMIT_B0004"
202
+ ]);
203
+ function createRateLimiter(options) {
204
+ if (!isRateLimiterOptions(options)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0029({ message: "[vitehub] createRateLimiter() requires a Rate Limit driver." });
205
+ let inspected;
206
+ try {
207
+ inspected = inspectRateLimiterOptions(options);
208
+ } catch (error) {
209
+ if (isRateLimitDiagnostic(error)) throw error;
210
+ throw rateLimitErrorDiagnostics.RATE_LIMIT_R0029({ message: "[vitehub] createRateLimiter() requires inspectable Rate Limit options." });
211
+ }
212
+ let policy;
213
+ let capabilities;
214
+ try {
215
+ policy = normalizeRateLimitPolicy(inspected.policy);
216
+ capabilities = resolveDriverCapabilities(inspected.policy, inspected.capabilities, inspected.driverName);
217
+ assertDriverSupportsPolicy(inspected.policy, capabilities, policy.windowMs, inspected.driverName);
218
+ } catch (error) {
219
+ if (isRateLimitDiagnostic(error)) throw error;
220
+ throw rateLimitErrorDiagnostics.RATE_LIMIT_R0029({ message: "[vitehub] createRateLimiter() requires inspectable Rate Limit options." });
221
+ }
222
+ const driverInput = (input) => ({
223
+ key: input.key,
224
+ limit: policy.limit,
225
+ name: inspected.policy.name,
226
+ windowMs: policy.windowMs
227
+ });
228
+ const driver = inspected.policy.driver;
229
+ const consume = inspected.consume;
230
+ const peek = inspected.peek;
231
+ const reset = inspected.reset;
232
+ return {
233
+ capabilities,
234
+ async consume(input) {
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." });
236
+ const outcome = await consume.call(driver, driverInput(input));
237
+ if (!v.is(driverOutcomeSchema, outcome)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0044({ message: "[vitehub] Rate Limit driver consume() must return [undefined, value] or [error, undefined]." });
238
+ const [error, result] = outcome;
239
+ if (error) return {
240
+ allowed: policy.failure === "allow",
241
+ cause: error.cause ?? error,
242
+ limit: policy.limit,
243
+ reason: "unavailable",
244
+ windowMs: policy.windowMs
245
+ };
246
+ return normalizeDriverResult(result, policy.limit, policy.windowMs);
247
+ },
248
+ async peek(input) {
249
+ assertKey(input, "peek");
250
+ if (!v.is(v.function(), peek)) return {
251
+ limit: policy.limit,
252
+ reason: unsupportedReason(inspected.driverName, "peek"),
253
+ status: "unsupported",
254
+ windowMs: policy.windowMs
255
+ };
256
+ const outcome = await peek.call(driver, driverInput(input));
257
+ const parsed = v.safeParse(driverOutcomeSchema, outcome);
258
+ if (!parsed.success) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0043({ message: "[vitehub] Rate Limit driver peek() must return [undefined, value] or [error, undefined]." });
259
+ const [error, result] = parsed.output;
260
+ if (error) return {
261
+ cause: error.cause ?? error,
262
+ limit: policy.limit,
263
+ status: "unavailable",
264
+ windowMs: policy.windowMs
265
+ };
266
+ return normalizePeekResult(result, policy);
267
+ },
268
+ policy,
269
+ async reset(input) {
270
+ assertKey(input, "reset");
271
+ if (!v.is(v.function(), reset)) return {
272
+ reason: unsupportedReason(inspected.driverName, "reset"),
273
+ status: "unsupported"
274
+ };
275
+ const outcome = await reset.call(driver, driverInput(input));
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]." });
278
+ const [error] = parsed.output;
279
+ return error ? {
280
+ cause: error.cause ?? error,
281
+ status: "unavailable"
282
+ } : { status: "reset" };
283
+ }
284
+ };
285
+ }
286
+ //#endregion
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 };
@@ -0,0 +1,234 @@
1
+ //#region ../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
2
+ /** The Standard Typed interface. This is a base type extended by other specs. */
3
+ interface StandardTypedV1<Input = unknown, Output = Input> {
4
+ /** The Standard properties. */
5
+ readonly "~standard": StandardTypedV1.Props<Input, Output>;
6
+ }
7
+ declare namespace StandardTypedV1 {
8
+ /** The Standard Typed properties interface. */
9
+ interface Props<Input = unknown, Output = Input> {
10
+ /** The version number of the standard. */
11
+ readonly version: 1;
12
+ /** The vendor name of the schema library. */
13
+ readonly vendor: string;
14
+ /** Inferred types associated with the schema. */
15
+ readonly types?: Types<Input, Output> | undefined;
16
+ }
17
+ /** The Standard Typed types interface. */
18
+ interface Types<Input = unknown, Output = Input> {
19
+ /** The input type of the schema. */
20
+ readonly input: Input;
21
+ /** The output type of the schema. */
22
+ readonly output: Output;
23
+ }
24
+ /** Infers the input type of a Standard Typed. */
25
+ type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
26
+ /** Infers the output type of a Standard Typed. */
27
+ type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
28
+ }
29
+ /** The Standard Schema interface. */
30
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
31
+ /** The Standard Schema properties. */
32
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
33
+ }
34
+ declare namespace StandardSchemaV1 {
35
+ /** The Standard Schema properties interface. */
36
+ interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
37
+ /** Validates unknown input values. */
38
+ readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
39
+ }
40
+ /** The result interface of the validate function. */
41
+ type Result<Output> = SuccessResult<Output> | FailureResult;
42
+ /** The result interface if validation succeeds. */
43
+ interface SuccessResult<Output> {
44
+ /** The typed output value. */
45
+ readonly value: Output;
46
+ /** A falsy value for `issues` indicates success. */
47
+ readonly issues?: undefined;
48
+ }
49
+ interface Options {
50
+ /** Explicit support for additional vendor-specific parameters, if needed. */
51
+ readonly libraryOptions?: Record<string, unknown> | undefined;
52
+ }
53
+ /** The result interface if validation fails. */
54
+ interface FailureResult {
55
+ /** The issues of failed validation. */
56
+ readonly issues: ReadonlyArray<Issue>;
57
+ }
58
+ /** The issue interface of the failure output. */
59
+ interface Issue {
60
+ /** The error message of the issue. */
61
+ readonly message: string;
62
+ /** The path of the issue, if any. */
63
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
64
+ }
65
+ /** The path segment interface of the issue. */
66
+ interface PathSegment {
67
+ /** The key representing a path segment. */
68
+ readonly key: PropertyKey;
69
+ }
70
+ /** The Standard types interface. */
71
+ interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {}
72
+ /** Infers the input type of a Standard. */
73
+ type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
74
+ /** Infers the output type of a Standard. */
75
+ type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
76
+ }
77
+ //#endregion
78
+ //#region ../internal/src/operation-definition.d.ts
79
+ /** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
80
+ type OperationKind = "read" | "write" | "destructive";
81
+ /** The signed-in user of a call. */
82
+ interface OperationUser {
83
+ id: string;
84
+ name?: string;
85
+ email?: string;
86
+ image?: string;
87
+ [key: string]: unknown;
88
+ }
89
+ /** The Agent Actor when an agent calls through a capability or MCP on behalf of a user. */
90
+ interface OperationActor {
91
+ id: string;
92
+ kind?: string;
93
+ label?: string;
94
+ meta?: object;
95
+ }
96
+ /** The checked Console access of a call. `vite-hub` issues it. `ConsoleAccess` has this shape. */
97
+ interface OperationAccess {
98
+ readonly mode: string;
99
+ /**
100
+ * The sections that the call may use. `"all"` when no section filter applies. An entry is a section id (`"kv"`, every
101
+ * operation of the section), `"<section>:read"` (only the operations that read), or `"<section>:<scope>"` (only the
102
+ * calls of a scoped operation for that scope, such as `"blob:media"` for one Blob store). `"<section>:<scope>:read"`
103
+ * allows only the reads of that scope.
104
+ */
105
+ readonly sections: "all" | readonly string[];
106
+ readonly user?: OperationUser;
107
+ }
108
+ interface OperationContext {
109
+ /** The checked Console access of the call. */
110
+ access: OperationAccess;
111
+ /** The signed-in user, or null. */
112
+ user: OperationUser | null;
113
+ /** The Agent Actor when an agent calls on behalf of `user`. */
114
+ actor?: OperationActor;
115
+ surface: "console" | "cli" | "mcp" | "agent";
116
+ /** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
117
+ development?: boolean;
118
+ env?: Record<string, unknown>;
119
+ waitUntil?: (task: Promise<unknown>) => void;
120
+ request?: Request;
121
+ /**
122
+ * The request event of the HTTP request that carries the call, when there is one: the Request of the Console route,
123
+ * with its Standard Context. Operations hand it to app hooks that read the request's own session, such as `identify`
124
+ * of Comments.
125
+ */
126
+ event?: unknown;
127
+ /** Operations set a success status here, such as 202 for an accepted call. */
128
+ response?: {
129
+ status?: number;
130
+ };
131
+ /**
132
+ * An agent or an MCP client may pass `lease: "override"` to `content.save`, `content.remove`, and `content.restore`
133
+ * only when the developer allowed it. Defaults to false, so a model cannot take over a document that a person is editing.
134
+ */
135
+ overrideLeases?: boolean;
136
+ /**
137
+ * What an Agent may read of the Channel conversations, set by `operations({ conversations })`. `participant`: only the
138
+ * threads that the Actor takes part in. `all`: every thread. Unset: none.
139
+ */
140
+ conversations?: "all" | "participant";
141
+ }
142
+ interface OperationDefinition<Input, Output> {
143
+ /** `<section>.<verb>`, such as `content.publish`. Unique per app. */
144
+ name: string;
145
+ /** One sentence. Becomes the CLI help line and the MCP tool description. */
146
+ description: string;
147
+ /**
148
+ * Console section that grants access, such as `content`. `false`: any Console user. A function reads the section
149
+ * from the input, for operations that serve several sections. Section ids cannot contain `:`; it is reserved for
150
+ * scope and read-only grants. A function that returns an invalid id denies the call.
151
+ */
152
+ section: string | false | ((input: Input) => string | undefined);
153
+ /**
154
+ * The part of a string `section` that one call uses, such as the Blob store that the input names. The call then needs
155
+ * the section (every scope) or `"<section>:<scope>"` (only this scope). A scope that is empty, is `read`, or has a
156
+ * `:` needs the whole section.
157
+ */
158
+ scope?: (input: Input) => string | undefined;
159
+ /** `read` never changes state. `write` changes state. `destructive` deletes or publishes; the CLI asks for `--yes`, MCP marks `destructiveHint`, agents require approval by default. */
160
+ kind: OperationKind;
161
+ /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
162
+ input: StandardSchemaV1<unknown, Input>;
163
+ output?: StandardSchemaV1<unknown, Output>;
164
+ cli?: {
165
+ /** Defaults: namespace = section, command = verb. */
166
+ namespace?: string;
167
+ /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
168
+ command?: string;
169
+ /** Input keys read from positional arguments, in order. */
170
+ positional?: string[];
171
+ /** Human output, written verbatim. Without it the CLI prints JSON. `--json` always prints JSON. */
172
+ format?: (output: Output) => string;
173
+ /** `vitehub <namespace>` runs this command when no command is named. */
174
+ default?: boolean;
175
+ };
176
+ /** Largest request body in bytes. It can raise the 64 KiB default but not lower it. */
177
+ maxRequestBytes?: number;
178
+ /**
179
+ * Returns true when this call only reads, such as a dry run of a `destructive` operation. The CLI then skips the
180
+ * confirmation, and agents run it without approval. Without it, every call of a `destructive` operation asks.
181
+ */
182
+ readOnlyWhen?: (input: Input) => boolean;
183
+ /**
184
+ * How MCP offers the operation as a tool. `false`: MCP does not offer it, such as an editor transport that only the
185
+ * Console uses. `title`: the short title that clients show, instead of the name in words. `format`: the text of a
186
+ * result for the Agent, such as a list of lines. The result stays the structured content. Without `format`, the text
187
+ * is the result as JSON.
188
+ */
189
+ mcp?: false | {
190
+ title?: string;
191
+ format?: (output: NoInfer<Output>) => string;
192
+ };
193
+ /** `false`: the operation never reads `context.user`, so the Console skips the session lookup for it. */
194
+ user?: false;
195
+ /**
196
+ * The operation runs code of the app, such as a workflow, a job, a task, or a schedule. The Console registers it only
197
+ * when `console.invoke` is on, which is the default in development and off in a production build.
198
+ */
199
+ invoke?: true;
200
+ run: (input: Input, context: OperationContext) => Output | Promise<Output>;
201
+ }
202
+ /** An operation of any input and output, as a registry holds it. */
203
+ interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
204
+ readOnlyWhen?: (input: never) => boolean;
205
+ cli?: {
206
+ namespace?: string;
207
+ command?: string;
208
+ default?: boolean;
209
+ positional?: string[];
210
+ format?: (output: never) => string;
211
+ };
212
+ mcp?: false | {
213
+ title?: string;
214
+ format?: (output: never) => string;
215
+ };
216
+ input: StandardSchemaV1;
217
+ output?: StandardSchemaV1;
218
+ run: (input: never, context: OperationContext) => unknown;
219
+ scope?: (input: never) => string | undefined;
220
+ section: string | false | ((input: never) => string | undefined);
221
+ }
222
+ /** The contribution of one plugin: operations, or a module that exports them. */
223
+ interface OperationContributionEntry {
224
+ /** The absolute path of the module that generated code imports, such as `ownModule(import.meta.url, "operations")`. */
225
+ module: string;
226
+ /** Named export that holds an operation or an array of operations. Defaults to `default`. */
227
+ export?: string;
228
+ /** Loads the export in the tool process, for a module that the tool cannot resolve by name. */
229
+ load?: () => Promise<unknown>;
230
+ /** `false`: the app already has these operations at runtime. Only tools such as the CLI and `vitehub inspect` read the entry. */
231
+ runtime?: false;
232
+ }
233
+ //#endregion
234
+ export { OperationContributionEntry as n, AnyOperation as t };