@vite-hub/rate-limit 0.0.3 → 0.1.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/LICENSE +201 -0
- package/README.md +111 -36
- package/dist/cli-Cniq99iX.d.ts +85 -0
- package/dist/cli.d.ts +16 -0
- package/dist/cli.js +273 -0
- package/dist/{cloudflare-BYZQ2tim.js → cloudflare-DUDRACVB.js} +7 -3
- package/dist/counters-pKORpgGd.d.ts +47 -0
- package/dist/counters-wdEMxDEY.js +106 -0
- package/dist/drivers/cloudflare.d.ts +6 -8
- package/dist/drivers/cloudflare.js +1 -1
- package/dist/drivers/memory.d.ts +7 -7
- package/dist/drivers/memory.js +34 -8
- package/dist/error-diagnostics-CTAC_bbr.js +56 -0
- package/dist/h3-v1-request-qoGwJr5-.js +235 -0
- package/dist/index.d.ts +11 -5
- package/dist/index.js +39 -41
- package/dist/inspect-D-FzyM_x.js +112 -0
- package/dist/limiter-DBrMI4vi.js +286 -0
- package/dist/operations-B09NnEjT.js +1438 -0
- package/dist/operations-Bu-xulNd.js +38 -0
- package/dist/operations-tNUdj3G4.d.ts +212 -0
- package/dist/operations.d.ts +14 -0
- package/dist/operations.js +244 -0
- package/dist/runtime.d.ts +4 -6
- package/dist/runtime.js +1 -1
- package/dist/state-Ct7zR8fD.js +43 -0
- package/dist/types-CQEJpgtz.d.ts +160 -0
- package/dist/vite.d.ts +330 -6
- package/dist/vite.js +767 -1066
- package/package.json +49 -14
- package/dist/limiter-CHaHluMr.js +0 -118
- package/dist/state-DB4uJN5P.js +0 -15
- package/dist/types-BX4hSfYX.d.ts +0 -97
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.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.null(), v.unknown()]), v.strictTuple([driverErrorSchema, v.undefined()])]));
|
|
63
|
+
function resolveDriverCapabilities(options, capabilities = options.driver.capabilities, driverName = options.driver.name) {
|
|
64
|
+
if (!capabilities || typeof capabilities !== "object") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0019({ message: `[vitehub] Rate Limit driver "${driverName}" must declare capabilities.` });
|
|
65
|
+
if (capabilities.enforcement !== "best-effort" && capabilities.enforcement !== "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0020({ message: `[vitehub] Rate Limit driver "${driverName}" must declare valid enforcement.` });
|
|
66
|
+
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.` });
|
|
67
|
+
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.` });
|
|
68
|
+
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.` });
|
|
69
|
+
return {
|
|
70
|
+
enforcement: capabilities.enforcement,
|
|
71
|
+
rejectedAttempts: capabilities.rejectedAttempts,
|
|
72
|
+
scope: capabilities.scope,
|
|
73
|
+
...capabilities.windows ? { windows: [...capabilities.windows] } : {}
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function hasInvalidSupportedWindows(value) {
|
|
77
|
+
if (!Array.isArray(value)) return true;
|
|
78
|
+
for (let index = 0; index < value.length; index++) {
|
|
79
|
+
const windowMs = value[index];
|
|
80
|
+
if (typeof windowMs !== "number" || !Number.isInteger(windowMs) || windowMs <= 0 || windowMs > 864e13) return true;
|
|
81
|
+
}
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
function normalizeOptionalInteger(value, label) {
|
|
85
|
+
if (value === void 0) return;
|
|
86
|
+
if (!Number.isInteger(value) || value < 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0024({ message: `[vitehub] Rate Limit driver result ${label} must be a non-negative integer.` });
|
|
87
|
+
return value;
|
|
88
|
+
}
|
|
89
|
+
function normalizeDriverResult(result, limit, windowMs) {
|
|
90
|
+
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." });
|
|
91
|
+
const resetAt = result.resetAt;
|
|
92
|
+
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." });
|
|
93
|
+
const decision = {
|
|
94
|
+
limit,
|
|
95
|
+
remaining: normalizeOptionalInteger(result.remaining, "remaining"),
|
|
96
|
+
resetAt,
|
|
97
|
+
retryAfter: normalizeOptionalInteger(result.retryAfter, "retryAfter"),
|
|
98
|
+
used: normalizeOptionalInteger(result.used, "used"),
|
|
99
|
+
windowMs
|
|
100
|
+
};
|
|
101
|
+
return result.allowed ? {
|
|
102
|
+
...decision,
|
|
103
|
+
allowed: true
|
|
104
|
+
} : {
|
|
105
|
+
...decision,
|
|
106
|
+
allowed: false,
|
|
107
|
+
reason: "limited"
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function assertDriverSupportsPolicy(options, capabilities, windowMs, driverName = options.driver.name) {
|
|
111
|
+
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.` });
|
|
112
|
+
const windows = capabilities.windows;
|
|
113
|
+
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.` });
|
|
114
|
+
}
|
|
115
|
+
const driverPeekResultSchema = v.object({
|
|
116
|
+
resetAt: v.optional(v.unknown()),
|
|
117
|
+
used: v.pipe(v.number(), v.integer(), v.minValue(0))
|
|
118
|
+
});
|
|
119
|
+
function normalizePeekResult(result, policy) {
|
|
120
|
+
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." });
|
|
121
|
+
const resetAt = result.resetAt;
|
|
122
|
+
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." });
|
|
123
|
+
return {
|
|
124
|
+
limit: policy.limit,
|
|
125
|
+
remaining: Math.max(0, policy.limit - result.used),
|
|
126
|
+
...resetAt === void 0 ? {} : { resetAt },
|
|
127
|
+
status: "known",
|
|
128
|
+
used: result.used,
|
|
129
|
+
windowMs: policy.windowMs
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function unsupportedReason(driverName, operation) {
|
|
133
|
+
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.`;
|
|
134
|
+
}
|
|
135
|
+
function assertKey(input, operation) {
|
|
136
|
+
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.` });
|
|
137
|
+
}
|
|
138
|
+
function isRateLimiterOptions(value) {
|
|
139
|
+
if (!value || typeof value !== "object") return false;
|
|
140
|
+
try {
|
|
141
|
+
return !Array.isArray(value);
|
|
142
|
+
} catch {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function ownOption(options, key) {
|
|
147
|
+
return Object.hasOwn(options, key) ? Reflect.get(options, key) : void 0;
|
|
148
|
+
}
|
|
149
|
+
function inspectRateLimiterOptions(options) {
|
|
150
|
+
const driver = Reflect.get(options, "driver");
|
|
151
|
+
const consume = Reflect.get(driver, "consume");
|
|
152
|
+
if (typeof consume !== "function") throw new TypeError("Rate Limit driver consume() must be callable");
|
|
153
|
+
const peek = Reflect.get(driver, "peek");
|
|
154
|
+
const reset = Reflect.get(driver, "reset");
|
|
155
|
+
const policy = {
|
|
156
|
+
driver,
|
|
157
|
+
limit: ownOption(options, "limit"),
|
|
158
|
+
window: ownOption(options, "window"),
|
|
159
|
+
enforcement: ownOption(options, "enforcement"),
|
|
160
|
+
failure: ownOption(options, "failure"),
|
|
161
|
+
name: Reflect.get(options, "name")
|
|
162
|
+
};
|
|
163
|
+
const capabilities = Reflect.get(driver, "capabilities");
|
|
164
|
+
if (!capabilities || typeof capabilities !== "object") return {
|
|
165
|
+
policy,
|
|
166
|
+
capabilities,
|
|
167
|
+
driverName: Reflect.get(driver, "name"),
|
|
168
|
+
consume,
|
|
169
|
+
peek,
|
|
170
|
+
reset
|
|
171
|
+
};
|
|
172
|
+
const windows = Reflect.get(capabilities, "windows");
|
|
173
|
+
const inspectedCapabilities = {
|
|
174
|
+
enforcement: Reflect.get(capabilities, "enforcement"),
|
|
175
|
+
rejectedAttempts: Reflect.get(capabilities, "rejectedAttempts"),
|
|
176
|
+
scope: Reflect.get(capabilities, "scope")
|
|
177
|
+
};
|
|
178
|
+
if (windows !== void 0) Object.assign(inspectedCapabilities, { windows });
|
|
179
|
+
return {
|
|
180
|
+
policy,
|
|
181
|
+
capabilities: inspectedCapabilities,
|
|
182
|
+
driverName: Reflect.get(driver, "name"),
|
|
183
|
+
consume,
|
|
184
|
+
peek,
|
|
185
|
+
reset
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
function isRateLimitDiagnostic(value) {
|
|
189
|
+
try {
|
|
190
|
+
return value instanceof Diagnostic && rateLimitDiagnosticCodes.has(value.code);
|
|
191
|
+
} catch {
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const rateLimitDiagnosticCodes = /* @__PURE__ */ new Set([
|
|
196
|
+
...Array.from({ length: 45 }, (_, index) => `RATE_LIMIT_R${String(index + 1).padStart(4, "0")}`),
|
|
197
|
+
"RATE_LIMIT_B0001",
|
|
198
|
+
"RATE_LIMIT_B0002",
|
|
199
|
+
"RATE_LIMIT_B0003",
|
|
200
|
+
"RATE_LIMIT_B0004"
|
|
201
|
+
]);
|
|
202
|
+
function createRateLimiter(options) {
|
|
203
|
+
if (!isRateLimiterOptions(options)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0029({ message: "[vitehub] createRateLimiter() requires a Rate Limit driver." });
|
|
204
|
+
let inspected;
|
|
205
|
+
try {
|
|
206
|
+
inspected = inspectRateLimiterOptions(options);
|
|
207
|
+
} catch (error) {
|
|
208
|
+
if (isRateLimitDiagnostic(error)) throw error;
|
|
209
|
+
throw rateLimitErrorDiagnostics.RATE_LIMIT_R0029({ message: "[vitehub] createRateLimiter() requires inspectable Rate Limit options." });
|
|
210
|
+
}
|
|
211
|
+
let policy;
|
|
212
|
+
let capabilities;
|
|
213
|
+
try {
|
|
214
|
+
policy = normalizeRateLimitPolicy(inspected.policy);
|
|
215
|
+
capabilities = resolveDriverCapabilities(inspected.policy, inspected.capabilities, inspected.driverName);
|
|
216
|
+
assertDriverSupportsPolicy(inspected.policy, capabilities, policy.windowMs, inspected.driverName);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
if (isRateLimitDiagnostic(error)) throw error;
|
|
219
|
+
throw rateLimitErrorDiagnostics.RATE_LIMIT_R0029({ message: "[vitehub] createRateLimiter() requires inspectable Rate Limit options." });
|
|
220
|
+
}
|
|
221
|
+
const driverInput = (input) => ({
|
|
222
|
+
key: input.key,
|
|
223
|
+
limit: policy.limit,
|
|
224
|
+
name: inspected.policy.name,
|
|
225
|
+
windowMs: policy.windowMs
|
|
226
|
+
});
|
|
227
|
+
const driver = inspected.policy.driver;
|
|
228
|
+
const consume = inspected.consume;
|
|
229
|
+
const peek = inspected.peek;
|
|
230
|
+
const reset = inspected.reset;
|
|
231
|
+
return {
|
|
232
|
+
capabilities,
|
|
233
|
+
async consume(input) {
|
|
234
|
+
if (!input || !v.is(v.string(), input.key) || input.key.length === 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0030({ message: "[vitehub] Rate Limiter consume() requires a non-empty key." });
|
|
235
|
+
const outcome = await consume.call(driver, driverInput(input));
|
|
236
|
+
if (!v.is(driverOutcomeSchema, outcome)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0044({ message: "[vitehub] Rate Limit driver consume() must return [null, value] or [Error, undefined]." });
|
|
237
|
+
const [error, result] = outcome;
|
|
238
|
+
if (error) return {
|
|
239
|
+
allowed: policy.failure === "allow",
|
|
240
|
+
cause: error.cause ?? error,
|
|
241
|
+
limit: policy.limit,
|
|
242
|
+
reason: "unavailable",
|
|
243
|
+
windowMs: policy.windowMs
|
|
244
|
+
};
|
|
245
|
+
return normalizeDriverResult(result, policy.limit, policy.windowMs);
|
|
246
|
+
},
|
|
247
|
+
async peek(input) {
|
|
248
|
+
assertKey(input, "peek");
|
|
249
|
+
if (!v.is(v.function(), peek)) return {
|
|
250
|
+
limit: policy.limit,
|
|
251
|
+
reason: unsupportedReason(inspected.driverName, "peek"),
|
|
252
|
+
status: "unsupported",
|
|
253
|
+
windowMs: policy.windowMs
|
|
254
|
+
};
|
|
255
|
+
const outcome = await peek.call(driver, driverInput(input));
|
|
256
|
+
const parsed = v.safeParse(driverOutcomeSchema, outcome);
|
|
257
|
+
if (!parsed.success) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0043({ message: "[vitehub] Rate Limit driver peek() must return [null, value] or [Error, undefined]." });
|
|
258
|
+
const [error, result] = parsed.output;
|
|
259
|
+
if (error) return {
|
|
260
|
+
cause: error.cause ?? error,
|
|
261
|
+
limit: policy.limit,
|
|
262
|
+
status: "unavailable",
|
|
263
|
+
windowMs: policy.windowMs
|
|
264
|
+
};
|
|
265
|
+
return normalizePeekResult(result, policy);
|
|
266
|
+
},
|
|
267
|
+
policy,
|
|
268
|
+
async reset(input) {
|
|
269
|
+
assertKey(input, "reset");
|
|
270
|
+
if (!v.is(v.function(), reset)) return {
|
|
271
|
+
reason: unsupportedReason(inspected.driverName, "reset"),
|
|
272
|
+
status: "unsupported"
|
|
273
|
+
};
|
|
274
|
+
const outcome = await reset.call(driver, driverInput(input));
|
|
275
|
+
const parsed = v.safeParse(v.strictTuple([v.nullable(driverErrorSchema)]), outcome);
|
|
276
|
+
if (!parsed.success) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0042({ message: "[vitehub] Rate Limit driver reset() must return [null] or [Error]." });
|
|
277
|
+
const [error] = parsed.output;
|
|
278
|
+
return error ? {
|
|
279
|
+
cause: error.cause ?? error,
|
|
280
|
+
status: "unavailable"
|
|
281
|
+
} : { status: "reset" };
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
//#endregion
|
|
286
|
+
export { rateLimitPolicyKeys as i, declaredRateLimitPolicy as n, normalizeRateLimitPolicy as r, createRateLimiter as t };
|