@vite-hub/rate-limit 0.0.4 → 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/README.md +32 -10
- 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-DoyUiUt1.d.ts → types-CQEJpgtz.d.ts} +57 -3
- package/dist/vite.d.ts +325 -7
- package/dist/vite.js +467 -2137
- package/package.json +49 -14
- package/dist/limiter-CHaHluMr.js +0 -118
- package/dist/state-DB4uJN5P.js +0 -15
|
@@ -1,19 +1,17 @@
|
|
|
1
|
-
import { o as RateLimitDriver } from "../types-
|
|
2
|
-
|
|
1
|
+
import { o as RateLimitDriver } from "../types-CQEJpgtz.js";
|
|
3
2
|
//#region src/integrations/cloudflare.d.ts
|
|
4
|
-
declare function getCloudflareRateLimitBindingName(name: string): string;
|
|
3
|
+
export declare function getCloudflareRateLimitBindingName(name: string): string;
|
|
5
4
|
//#endregion
|
|
6
5
|
//#region src/drivers/cloudflare.d.ts
|
|
7
|
-
interface CloudflareRateLimitBinding {
|
|
6
|
+
export interface CloudflareRateLimitBinding {
|
|
8
7
|
limit(input: {
|
|
9
8
|
key: string;
|
|
10
9
|
}): Promise<{
|
|
11
10
|
success: boolean;
|
|
12
11
|
}>;
|
|
13
12
|
}
|
|
14
|
-
interface CloudflareRateLimitDriverOptions {
|
|
13
|
+
export interface CloudflareRateLimitDriverOptions {
|
|
15
14
|
binding: CloudflareRateLimitBinding;
|
|
16
15
|
}
|
|
17
|
-
declare function cloudflareRateLimitDriver(options: CloudflareRateLimitDriverOptions): RateLimitDriver;
|
|
18
|
-
//#endregion
|
|
19
|
-
export { CloudflareRateLimitBinding, CloudflareRateLimitDriverOptions, cloudflareRateLimitDriver, getCloudflareRateLimitBindingName };
|
|
16
|
+
export declare function cloudflareRateLimitDriver(options: CloudflareRateLimitDriverOptions): RateLimitDriver;
|
|
17
|
+
//#endregion
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "../cloudflare-
|
|
1
|
+
import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "../cloudflare-DUDRACVB.js";
|
|
2
2
|
export { cloudflareRateLimitDriver, getCloudflareRateLimitBindingName };
|
package/dist/drivers/memory.d.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { o as RateLimitDriver } from "../types-
|
|
2
|
-
|
|
1
|
+
import { o as RateLimitDriver } from "../types-CQEJpgtz.js";
|
|
3
2
|
//#region src/drivers/memory.d.ts
|
|
4
|
-
interface MemoryRateLimitDriverOptions {
|
|
3
|
+
export interface MemoryRateLimitDriverOptions {
|
|
5
4
|
maxEntries?: number;
|
|
6
5
|
now?: () => number;
|
|
7
6
|
}
|
|
8
|
-
interface MemoryRateLimitDriver extends RateLimitDriver {
|
|
7
|
+
export interface MemoryRateLimitDriver extends RateLimitDriver {
|
|
9
8
|
clear: () => void;
|
|
9
|
+
peek: NonNullable<RateLimitDriver["peek"]>;
|
|
10
|
+
reset: NonNullable<RateLimitDriver["reset"]>;
|
|
10
11
|
size: () => number;
|
|
11
12
|
}
|
|
12
|
-
declare function memoryRateLimitDriver(options?: MemoryRateLimitDriverOptions): MemoryRateLimitDriver;
|
|
13
|
-
//#endregion
|
|
14
|
-
export { MemoryRateLimitDriver, MemoryRateLimitDriverOptions, memoryRateLimitDriver };
|
|
13
|
+
export declare function memoryRateLimitDriver(options?: MemoryRateLimitDriverOptions): MemoryRateLimitDriver;
|
|
14
|
+
//#endregion
|
package/dist/drivers/memory.js
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-CTAC_bbr.js";
|
|
1
2
|
//#region src/drivers/memory.ts
|
|
2
3
|
const defaultMaxEntries = 1e5;
|
|
3
4
|
function memoryRateLimitDriver(options = {}) {
|
|
4
5
|
const entries = /* @__PURE__ */ new Map();
|
|
6
|
+
let nextExpiry = Number.POSITIVE_INFINITY;
|
|
5
7
|
const maxEntries = options.maxEntries ?? defaultMaxEntries;
|
|
6
|
-
if (!Number.isInteger(maxEntries) || maxEntries <= 0) throw
|
|
8
|
+
if (!Number.isInteger(maxEntries) || maxEntries <= 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0007({ message: "[vitehub] Memory Rate Limit driver maxEntries must be a positive integer." });
|
|
7
9
|
const now = options.now ?? Date.now;
|
|
8
10
|
function prune(timestamp) {
|
|
11
|
+
if (timestamp < nextExpiry) return;
|
|
12
|
+
nextExpiry = Number.POSITIVE_INFINITY;
|
|
9
13
|
for (const [key, entry] of entries) if (entry.resetAt <= timestamp) entries.delete(key);
|
|
14
|
+
else nextExpiry = Math.min(nextExpiry, entry.resetAt);
|
|
10
15
|
}
|
|
11
16
|
return {
|
|
12
17
|
capabilities: {
|
|
@@ -16,18 +21,23 @@ function memoryRateLimitDriver(options = {}) {
|
|
|
16
21
|
},
|
|
17
22
|
clear() {
|
|
18
23
|
entries.clear();
|
|
24
|
+
nextExpiry = Number.POSITIVE_INFINITY;
|
|
19
25
|
},
|
|
20
26
|
consume(input) {
|
|
21
27
|
const timestamp = now();
|
|
22
28
|
prune(timestamp);
|
|
23
|
-
const key =
|
|
24
|
-
const resetAt = Math.floor(timestamp / input.windowMs) * input.windowMs + input.windowMs;
|
|
29
|
+
const key = JSON.stringify([input.name ?? "default", input.key]);
|
|
25
30
|
const current = entries.get(key);
|
|
26
|
-
if (!current && entries.size >= maxEntries) throw
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
resetAt
|
|
30
|
-
|
|
31
|
+
if (!current && entries.size >= maxEntries) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0008({ message: `[vitehub] Memory Rate Limit driver reached maxEntries (${maxEntries}) while active counters remain.` });
|
|
32
|
+
let entry = current;
|
|
33
|
+
if (!entry || entry.resetAt <= timestamp) {
|
|
34
|
+
const resetAt = Math.floor(timestamp / input.windowMs) * input.windowMs + input.windowMs;
|
|
35
|
+
if (!Number.isFinite(resetAt) || resetAt <= 0 || resetAt > 864e13) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0045({ message: "[vitehub] Memory Rate Limit fixed-window end must be a positive timestamp at most 8640000000000000 milliseconds." });
|
|
36
|
+
entry = {
|
|
37
|
+
count: 0,
|
|
38
|
+
resetAt
|
|
39
|
+
};
|
|
40
|
+
}
|
|
31
41
|
if (entry.count >= input.limit) return [null, {
|
|
32
42
|
allowed: false,
|
|
33
43
|
remaining: 0,
|
|
@@ -37,6 +47,7 @@ function memoryRateLimitDriver(options = {}) {
|
|
|
37
47
|
}];
|
|
38
48
|
entry.count += 1;
|
|
39
49
|
entries.set(key, entry);
|
|
50
|
+
nextExpiry = Math.min(nextExpiry, entry.resetAt);
|
|
40
51
|
return [null, {
|
|
41
52
|
allowed: true,
|
|
42
53
|
remaining: input.limit - entry.count,
|
|
@@ -44,7 +55,22 @@ function memoryRateLimitDriver(options = {}) {
|
|
|
44
55
|
used: entry.count
|
|
45
56
|
}];
|
|
46
57
|
},
|
|
58
|
+
peek(input) {
|
|
59
|
+
const timestamp = now();
|
|
60
|
+
prune(timestamp);
|
|
61
|
+
const key = JSON.stringify([input.name ?? "default", input.key]);
|
|
62
|
+
const entry = entries.get(key);
|
|
63
|
+
return [null, {
|
|
64
|
+
resetAt: entry && entry.resetAt > timestamp ? entry.resetAt : void 0,
|
|
65
|
+
used: entry && entry.resetAt > timestamp ? entry.count : 0
|
|
66
|
+
}];
|
|
67
|
+
},
|
|
47
68
|
name: "memory",
|
|
69
|
+
reset(input) {
|
|
70
|
+
const key = JSON.stringify([input.name ?? "default", input.key]);
|
|
71
|
+
entries.delete(key);
|
|
72
|
+
return [null];
|
|
73
|
+
},
|
|
48
74
|
size() {
|
|
49
75
|
return entries.size;
|
|
50
76
|
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { defineDiagnostics } from "nostics";
|
|
2
|
+
//#region src/error-diagnostics.ts
|
|
3
|
+
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
4
|
+
const rateLimitErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
5
|
+
docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
|
|
6
|
+
codes: {
|
|
7
|
+
RATE_LIMIT_R0001: dynamicError,
|
|
8
|
+
RATE_LIMIT_R0002: dynamicError,
|
|
9
|
+
RATE_LIMIT_R0003: dynamicError,
|
|
10
|
+
RATE_LIMIT_R0004: dynamicError,
|
|
11
|
+
RATE_LIMIT_R0005: dynamicError,
|
|
12
|
+
RATE_LIMIT_R0006: dynamicError,
|
|
13
|
+
RATE_LIMIT_R0007: dynamicError,
|
|
14
|
+
RATE_LIMIT_R0008: dynamicError,
|
|
15
|
+
RATE_LIMIT_R0009: dynamicError,
|
|
16
|
+
RATE_LIMIT_R0010: dynamicError,
|
|
17
|
+
RATE_LIMIT_R0011: dynamicError,
|
|
18
|
+
RATE_LIMIT_R0012: dynamicError,
|
|
19
|
+
RATE_LIMIT_R0013: dynamicError,
|
|
20
|
+
RATE_LIMIT_R0015: dynamicError,
|
|
21
|
+
RATE_LIMIT_R0016: dynamicError,
|
|
22
|
+
RATE_LIMIT_R0019: dynamicError,
|
|
23
|
+
RATE_LIMIT_R0020: dynamicError,
|
|
24
|
+
RATE_LIMIT_R0021: dynamicError,
|
|
25
|
+
RATE_LIMIT_R0022: dynamicError,
|
|
26
|
+
RATE_LIMIT_R0023: dynamicError,
|
|
27
|
+
RATE_LIMIT_R0024: dynamicError,
|
|
28
|
+
RATE_LIMIT_R0025: dynamicError,
|
|
29
|
+
RATE_LIMIT_R0026: dynamicError,
|
|
30
|
+
RATE_LIMIT_R0027: dynamicError,
|
|
31
|
+
RATE_LIMIT_R0028: dynamicError,
|
|
32
|
+
RATE_LIMIT_R0029: dynamicError,
|
|
33
|
+
RATE_LIMIT_R0030: dynamicError,
|
|
34
|
+
RATE_LIMIT_R0031: dynamicError,
|
|
35
|
+
RATE_LIMIT_R0032: dynamicError,
|
|
36
|
+
RATE_LIMIT_R0033: dynamicError,
|
|
37
|
+
RATE_LIMIT_R0034: dynamicError,
|
|
38
|
+
RATE_LIMIT_R0035: dynamicError,
|
|
39
|
+
RATE_LIMIT_R0036: dynamicError,
|
|
40
|
+
RATE_LIMIT_R0037: dynamicError,
|
|
41
|
+
RATE_LIMIT_R0038: dynamicError,
|
|
42
|
+
RATE_LIMIT_R0039: dynamicError,
|
|
43
|
+
RATE_LIMIT_R0040: dynamicError,
|
|
44
|
+
RATE_LIMIT_R0041: dynamicError,
|
|
45
|
+
RATE_LIMIT_R0042: dynamicError,
|
|
46
|
+
RATE_LIMIT_R0043: dynamicError,
|
|
47
|
+
RATE_LIMIT_R0044: dynamicError,
|
|
48
|
+
RATE_LIMIT_R0045: dynamicError,
|
|
49
|
+
RATE_LIMIT_B0001: dynamicError,
|
|
50
|
+
RATE_LIMIT_B0002: dynamicError,
|
|
51
|
+
RATE_LIMIT_B0003: dynamicError,
|
|
52
|
+
RATE_LIMIT_B0004: dynamicError
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
//#endregion
|
|
56
|
+
export { rateLimitErrorDiagnostics as t };
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
//#region ../internal/src/runtime/cloudflare-env.ts
|
|
3
|
+
let activeEnv;
|
|
4
|
+
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
5
|
+
const runtimeGlobal = globalThis;
|
|
6
|
+
const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
|
|
7
|
+
function getActiveCloudflareEnv() {
|
|
8
|
+
const scoped = activeEnvStorage.getStore();
|
|
9
|
+
if (scoped) return scoped.env;
|
|
10
|
+
const host = globalThis;
|
|
11
|
+
return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
|
|
12
|
+
}
|
|
13
|
+
function ownValue(value, key) {
|
|
14
|
+
if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
|
|
15
|
+
return Reflect.get(value, key);
|
|
16
|
+
}
|
|
17
|
+
function ownObject(value) {
|
|
18
|
+
return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
|
|
19
|
+
}
|
|
20
|
+
/** The objects where H3 1, H3 2, and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
|
|
21
|
+
function cloudflareOwners(target) {
|
|
22
|
+
const context = ownObject(ownValue(target, "context"));
|
|
23
|
+
const platform = ownObject(ownValue(context, "_platform"));
|
|
24
|
+
const req = ownObject(ownValue(target, "req"));
|
|
25
|
+
const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
|
|
26
|
+
return [
|
|
27
|
+
ownObject(ownValue(context, "cloudflare")),
|
|
28
|
+
ownObject(ownValue(platform, "cloudflare")),
|
|
29
|
+
ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare")),
|
|
30
|
+
ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"))
|
|
31
|
+
];
|
|
32
|
+
}
|
|
33
|
+
function getCloudflareEnv(event, options = {}) {
|
|
34
|
+
const target = ownObject(event);
|
|
35
|
+
for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
|
|
36
|
+
return options.fallback === false ? void 0 : getActiveCloudflareEnv();
|
|
37
|
+
}
|
|
38
|
+
function resolveWaitUntil(event, options = {}) {
|
|
39
|
+
const target = ownObject(event);
|
|
40
|
+
const context = ownObject(ownValue(target, "context"));
|
|
41
|
+
const cloudflare = ownObject(ownValue(context, "cloudflare"));
|
|
42
|
+
const cloudflareContext = ownObject(ownValue(cloudflare, "context"));
|
|
43
|
+
const platformCloudflare = ownObject(ownValue(ownObject(ownValue(context, "_platform")), "cloudflare"));
|
|
44
|
+
const platformCloudflareContext = ownObject(ownValue(platformCloudflare, "context"));
|
|
45
|
+
const req = ownObject(ownValue(target, "req"));
|
|
46
|
+
const reqCloudflare = ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare"));
|
|
47
|
+
const reqCloudflareContext = ownObject(ownValue(reqCloudflare, "context"));
|
|
48
|
+
const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
|
|
49
|
+
const nodeCloudflare = ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"));
|
|
50
|
+
const hosts = [
|
|
51
|
+
context,
|
|
52
|
+
cloudflare,
|
|
53
|
+
cloudflareContext,
|
|
54
|
+
platformCloudflare,
|
|
55
|
+
platformCloudflareContext,
|
|
56
|
+
req,
|
|
57
|
+
reqCloudflare,
|
|
58
|
+
reqCloudflareContext,
|
|
59
|
+
nodeReq,
|
|
60
|
+
nodeCloudflare,
|
|
61
|
+
ownObject(ownValue(nodeCloudflare, "context"))
|
|
62
|
+
];
|
|
63
|
+
const owners = options.preferHost ? [...hosts, target] : [target, ...hosts];
|
|
64
|
+
for (const owner of owners) {
|
|
65
|
+
const waitUntil = ownValue(owner, "waitUntil");
|
|
66
|
+
if (typeof waitUntil === "function") return waitUntil.bind(owner);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
//#region ../internal/src/runtime/h3-v1-request.ts
|
|
71
|
+
const payloadMethods = /* @__PURE__ */ new Set([
|
|
72
|
+
"DELETE",
|
|
73
|
+
"PATCH",
|
|
74
|
+
"POST",
|
|
75
|
+
"PUT"
|
|
76
|
+
]);
|
|
77
|
+
const rawBodySymbol = Symbol.for("h3RawBody");
|
|
78
|
+
const nodeEventRequests = /* @__PURE__ */ new WeakMap();
|
|
79
|
+
/** Return true for an event with an own `node.req` object, such as an H3 1 event. */
|
|
80
|
+
function isH3V1Event(input) {
|
|
81
|
+
if (!Object.hasOwn(input, "node")) return false;
|
|
82
|
+
const node = Reflect.get(input, "node");
|
|
83
|
+
return isObjectLike(node) && isObjectLike(Reflect.get(node, "req"));
|
|
84
|
+
}
|
|
85
|
+
function isObjectLike(value) {
|
|
86
|
+
return value !== null && (typeof value === "object" || typeof value === "function");
|
|
87
|
+
}
|
|
88
|
+
function isWebRequest(value) {
|
|
89
|
+
if (!isObjectLike(value)) return false;
|
|
90
|
+
const headers = Reflect.get(value, "headers");
|
|
91
|
+
return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObjectLike(headers) && typeof Reflect.get(headers, "get") === "function";
|
|
92
|
+
}
|
|
93
|
+
function firstHeader(value) {
|
|
94
|
+
return Array.isArray(value) ? value[0] : value;
|
|
95
|
+
}
|
|
96
|
+
function readNodeRequestHeaders(request) {
|
|
97
|
+
const headers = new Headers();
|
|
98
|
+
for (const [name, value] of Object.entries(request.headers)) if (Array.isArray(value)) for (const item of value) headers.append(name, item);
|
|
99
|
+
else if (value !== void 0) headers.set(name, value);
|
|
100
|
+
return headers;
|
|
101
|
+
}
|
|
102
|
+
/** Rebuild the public URL. H3 1 removes the app base path from `url` and keeps it in `originalUrl`. */
|
|
103
|
+
function readNodeRequestURL(request) {
|
|
104
|
+
const host = firstHeader(request.headers.host) || "localhost";
|
|
105
|
+
const encrypted = request.socket?.encrypted || request.connection?.encrypted;
|
|
106
|
+
const protocol = firstHeader(request.headers["x-forwarded-proto"]) === "https" || encrypted ? "https" : "http";
|
|
107
|
+
const path = (request.originalUrl || request.url || "/").replace(/^[/\\]+/, "/");
|
|
108
|
+
return new URL(path, `${protocol}://${host}`);
|
|
109
|
+
}
|
|
110
|
+
function toBodyStream(value) {
|
|
111
|
+
if (value instanceof ReadableStream) return value;
|
|
112
|
+
if (value instanceof Uint8Array) return new ReadableStream({ start(controller) {
|
|
113
|
+
controller.enqueue(value);
|
|
114
|
+
controller.close();
|
|
115
|
+
} });
|
|
116
|
+
if (typeof value === "string") return new Blob([value]).stream();
|
|
117
|
+
if (value instanceof URLSearchParams) return new Blob([value.toString()]).stream();
|
|
118
|
+
if (value instanceof Object && Object.getPrototypeOf(value) === Object.prototype) return new Blob([JSON.stringify(value)]).stream();
|
|
119
|
+
}
|
|
120
|
+
async function openNodeRequestBody(event) {
|
|
121
|
+
const request = event.node.req;
|
|
122
|
+
const stored = event._requestBody ?? request[rawBodySymbol] ?? request.rawBody ?? request.body;
|
|
123
|
+
if (stored !== void 0 && stored !== null) {
|
|
124
|
+
const stream = toBodyStream(await stored);
|
|
125
|
+
if (stream) {
|
|
126
|
+
const reader = stream.getReader();
|
|
127
|
+
return () => reader.read();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const iterator = request[Symbol.asyncIterator]?.();
|
|
131
|
+
if (!iterator) return void 0;
|
|
132
|
+
const chunks = [];
|
|
133
|
+
const collected = [];
|
|
134
|
+
let total = 0;
|
|
135
|
+
let ended = false;
|
|
136
|
+
let failed = false;
|
|
137
|
+
let failure;
|
|
138
|
+
let waiting;
|
|
139
|
+
const produce = async () => {
|
|
140
|
+
try {
|
|
141
|
+
for await (const chunk of { [Symbol.asyncIterator]: () => iterator }) {
|
|
142
|
+
let bytes;
|
|
143
|
+
if (typeof chunk === "string") bytes = new TextEncoder().encode(chunk);
|
|
144
|
+
else if (chunk instanceof Uint8Array) bytes = chunk;
|
|
145
|
+
else throw new TypeError("[vitehub] Request body chunks must be strings or bytes.");
|
|
146
|
+
collected.push(bytes);
|
|
147
|
+
total += bytes.byteLength;
|
|
148
|
+
if (waiting) {
|
|
149
|
+
waiting.resolve({ value: bytes });
|
|
150
|
+
waiting = void 0;
|
|
151
|
+
} else chunks.push(bytes);
|
|
152
|
+
}
|
|
153
|
+
ended = true;
|
|
154
|
+
waiting?.resolve({ done: true });
|
|
155
|
+
waiting = void 0;
|
|
156
|
+
} catch (error) {
|
|
157
|
+
failed = true;
|
|
158
|
+
failure = error;
|
|
159
|
+
ended = true;
|
|
160
|
+
waiting?.reject(error);
|
|
161
|
+
waiting = void 0;
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
const bytes = new Uint8Array(total);
|
|
165
|
+
let offset = 0;
|
|
166
|
+
for (const chunk of collected) {
|
|
167
|
+
bytes.set(chunk, offset);
|
|
168
|
+
offset += chunk.byteLength;
|
|
169
|
+
}
|
|
170
|
+
return bytes;
|
|
171
|
+
};
|
|
172
|
+
let body;
|
|
173
|
+
const start = () => body ??= produce();
|
|
174
|
+
event._requestBody = { then: (resolve, reject) => start().then(resolve, reject) };
|
|
175
|
+
return async () => {
|
|
176
|
+
start();
|
|
177
|
+
body?.catch(() => {});
|
|
178
|
+
if (failed) throw failure;
|
|
179
|
+
if (chunks.length) return { value: chunks.shift() };
|
|
180
|
+
if (ended) return { done: true };
|
|
181
|
+
return new Promise((resolve, reject) => {
|
|
182
|
+
waiting = {
|
|
183
|
+
resolve,
|
|
184
|
+
reject
|
|
185
|
+
};
|
|
186
|
+
});
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/** Read the body lazily, from a value a host already read or from the Node request stream. */
|
|
190
|
+
function readNodeRequestBody(event) {
|
|
191
|
+
let reader;
|
|
192
|
+
return new ReadableStream({ async pull(controller) {
|
|
193
|
+
const chunk = await (await (reader ??= openNodeRequestBody(event)))?.();
|
|
194
|
+
if (!chunk || chunk.done) {
|
|
195
|
+
controller.close();
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const value = chunk.value;
|
|
199
|
+
if (typeof value === "string") controller.enqueue(new TextEncoder().encode(value));
|
|
200
|
+
else if (value instanceof Uint8Array) controller.enqueue(value);
|
|
201
|
+
else controller.error(/* @__PURE__ */ new TypeError("[vitehub] Request body chunks must be strings or bytes."));
|
|
202
|
+
} }, { highWaterMark: 0 });
|
|
203
|
+
}
|
|
204
|
+
/** Return one Web Request per H3 1 event. The body is read only when a caller reads the Request body. */
|
|
205
|
+
function toH3V1Request(event) {
|
|
206
|
+
const cached = nodeEventRequests.get(event);
|
|
207
|
+
if (cached) return cached;
|
|
208
|
+
if (isWebRequest(event.web?.request)) return event.web.request;
|
|
209
|
+
const request = event.node.req;
|
|
210
|
+
const method = (request.method || "GET").toUpperCase();
|
|
211
|
+
const init = {
|
|
212
|
+
headers: readNodeRequestHeaders(request),
|
|
213
|
+
method
|
|
214
|
+
};
|
|
215
|
+
if (payloadMethods.has(method)) {
|
|
216
|
+
init.body = readNodeRequestBody(event);
|
|
217
|
+
init.duplex = "half";
|
|
218
|
+
}
|
|
219
|
+
const webRequest = new Request(readNodeRequestURL(request), init);
|
|
220
|
+
nodeEventRequests.set(event, webRequest);
|
|
221
|
+
return webRequest;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Return the Web Request of a request, an H3 2 event with an own `req` request, or an H3 1 event such as Nuxt 4's.
|
|
225
|
+
* H3 1 events have no `url`, so read the URL from the request this returns. Throws a `TypeError` for any other value.
|
|
226
|
+
*/
|
|
227
|
+
function toEventRequest(event) {
|
|
228
|
+
if (isWebRequest(event)) return event;
|
|
229
|
+
const req = Object.hasOwn(event, "req") ? Reflect.get(event, "req") : void 0;
|
|
230
|
+
if (isWebRequest(req)) return req;
|
|
231
|
+
if (isH3V1Event(event)) return toH3V1Request(event);
|
|
232
|
+
throw new TypeError("[vitehub] Expected a Request, an H3 2 event, or an H3 1 event.");
|
|
233
|
+
}
|
|
234
|
+
//#endregion
|
|
235
|
+
export { resolveWaitUntil as i, toEventRequest as n, getCloudflareEnv as r, isH3V1Event as t };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { C as RateLimitRuntimeConfig, D as ResolvedRateLimitPolicy, E as RequireRateLimitOptions, S as RateLimitResetResult, T as RateLimiter, _ as RateLimitPeekResult, a as RateLimitDeclaration, b as RateLimitRejectedAttemptBehavior, c as RateLimitDriverInput, d as RateLimitDriverPeekResult, f as RateLimitDriverResetOutcome, g as RateLimitModuleOptions, h as RateLimitFailurePolicy, i as RateLimitDecision, l as RateLimitDriverOutcome, m as RateLimitEnforcement, n as RateLimitConsumeInput, o as RateLimitDriver, p as RateLimitDriverResult, r as RateLimitCounterScope, s as RateLimitDriverCapabilities, t as CreateRateLimiterOptions, u as RateLimitDriverPeekOutcome, v as RateLimitPolicy, w as RateLimitWindow, x as RateLimitRequestEvent, y as RateLimitProvider } from "./types-CQEJpgtz.js";
|
|
2
|
+
import { a as resetRateLimit, i as peekRateLimit, n as RateLimitPeekInspection, r as RateLimitResetInspection, t as RateLimitCounterSnapshot } from "./counters-pKORpgGd.js";
|
|
3
3
|
//#region src/limiter.d.ts
|
|
4
|
-
declare function createRateLimiter(options: CreateRateLimiterOptions): RateLimiter;
|
|
4
|
+
export declare function createRateLimiter(options: CreateRateLimiterOptions): RateLimiter;
|
|
5
5
|
//#endregion
|
|
6
6
|
//#region src/guard.d.ts
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Consumes one request from a managed Rate Limit and returns the decision instead of throwing. Use it when a limited
|
|
9
|
+
* request still gets an answer, such as a cheaper fallback. `reason` is `limited` or `unavailable` when not allowed.
|
|
10
|
+
* Shares counters, discovery, and Provider Output with `requireRateLimit()`. Invalid options still throw.
|
|
11
|
+
*/
|
|
12
|
+
export declare function checkRateLimit(event: RateLimitRequestEvent, name: string, options: RequireRateLimitOptions): Promise<RateLimitDecision>;
|
|
13
|
+
export declare function requireRateLimit(event: RateLimitRequestEvent, name: string, options: RequireRateLimitOptions): Promise<void>;
|
|
8
14
|
//#endregion
|
|
9
|
-
export { type CreateRateLimiterOptions, type RateLimitConsumeInput, type RateLimitCounterScope, type RateLimitDecision, type RateLimitDeclaration, type RateLimitDriver, type RateLimitDriverCapabilities, type RateLimitDriverInput, type RateLimitDriverOutcome, type RateLimitDriverResult, type RateLimitEnforcement, type RateLimitFailurePolicy, type RateLimitModuleOptions, type RateLimitPolicy, type RateLimitProvider, type RateLimitRejectedAttemptBehavior, type RateLimitRequestEvent, type RateLimitRuntimeConfig, type RateLimitWindow, type RateLimiter, type RequireRateLimitOptions, type ResolvedRateLimitPolicy,
|
|
15
|
+
export { type CreateRateLimiterOptions, type RateLimitConsumeInput, type RateLimitCounterScope, type RateLimitCounterSnapshot, type RateLimitDecision, type RateLimitDeclaration, type RateLimitDriver, type RateLimitDriverCapabilities, type RateLimitDriverInput, type RateLimitDriverOutcome, type RateLimitDriverPeekOutcome, type RateLimitDriverPeekResult, type RateLimitDriverResetOutcome, type RateLimitDriverResult, type RateLimitEnforcement, type RateLimitFailurePolicy, type RateLimitModuleOptions, type RateLimitPeekInspection, type RateLimitPeekResult, type RateLimitPolicy, type RateLimitProvider, type RateLimitRejectedAttemptBehavior, type RateLimitRequestEvent, type RateLimitResetInspection, type RateLimitResetResult, type RateLimitRuntimeConfig, type RateLimitWindow, type RateLimiter, type RequireRateLimitOptions, type ResolvedRateLimitPolicy, peekRateLimit, resetRateLimit };
|
package/dist/index.js
CHANGED
|
@@ -1,76 +1,74 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as
|
|
3
|
-
import {
|
|
4
|
-
import { n as
|
|
5
|
-
import {
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
|
|
2
|
+
import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-DBrMI4vi.js";
|
|
3
|
+
import { n as getRateLimitRuntimeConfig, t as getMemoryRateLimiter } from "./state-Ct7zR8fD.js";
|
|
4
|
+
import { n as resetRateLimit, t as peekRateLimit } from "./counters-wdEMxDEY.js";
|
|
5
|
+
import { n as toEventRequest, r as getCloudflareEnv, t as isH3V1Event } from "./h3-v1-request-qoGwJr5-.js";
|
|
6
|
+
import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-DUDRACVB.js";
|
|
7
|
+
import { createError, getRequestIP } from "h3";
|
|
6
8
|
//#region src/guard.ts
|
|
7
|
-
const guardOptionKeys = new Set([...rateLimitPolicyKeys, "key"]);
|
|
9
|
+
const guardOptionKeys = /* @__PURE__ */ new Set([...rateLimitPolicyKeys, "key"]);
|
|
8
10
|
function getCloudflareEventEnv(event) {
|
|
9
|
-
|
|
10
|
-
return target.env ?? target.context?.cloudflare?.env ?? target.context?._platform?.cloudflare?.env ?? target.req?.runtime?.cloudflare?.env ?? target.node?.req?.runtime?.cloudflare?.env;
|
|
11
|
+
return getCloudflareEnv(event, { fallback: false });
|
|
11
12
|
}
|
|
12
13
|
function isCloudflareBinding(value) {
|
|
13
14
|
return Boolean(value) && typeof value === "object" && typeof value.limit === "function";
|
|
14
15
|
}
|
|
15
16
|
function getRequestKey(event, provider) {
|
|
16
|
-
return provider === "cloudflare" ? event.
|
|
17
|
-
}
|
|
18
|
-
function getMemoryRateLimiter(name, policy) {
|
|
19
|
-
const cache = getRateLimitLimiterCache();
|
|
20
|
-
const cacheKey = JSON.stringify([
|
|
21
|
-
name,
|
|
22
|
-
policy.enforcement,
|
|
23
|
-
policy.failure,
|
|
24
|
-
policy.limit,
|
|
25
|
-
policy.window
|
|
26
|
-
]);
|
|
27
|
-
const existing = cache.get(cacheKey);
|
|
28
|
-
if (existing) return existing;
|
|
29
|
-
const pending = Promise.resolve(createRateLimiter({
|
|
30
|
-
...policy,
|
|
31
|
-
driver: memoryRateLimitDriver(),
|
|
32
|
-
name
|
|
33
|
-
})).catch((error) => {
|
|
34
|
-
cache.delete(cacheKey);
|
|
35
|
-
throw error;
|
|
36
|
-
});
|
|
37
|
-
cache.set(cacheKey, pending);
|
|
38
|
-
return pending;
|
|
17
|
+
return provider === "cloudflare" ? toEventRequest(event).headers.get("cf-connecting-ip") || getRequestIP(event) : getRequestIP(event);
|
|
39
18
|
}
|
|
40
19
|
function getCloudflareRateLimiter(event, name, policy) {
|
|
41
20
|
const bindingName = getCloudflareRateLimitBindingName(name);
|
|
42
21
|
const binding = getCloudflareEventEnv(event)?.[bindingName];
|
|
43
|
-
if (!isCloudflareBinding(binding)) throw
|
|
22
|
+
if (!isCloudflareBinding(binding)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0009({ message: `[vitehub] Cloudflare Rate Limit binding "${bindingName}" was not found on the request event.` });
|
|
44
23
|
return createRateLimiter({
|
|
45
24
|
...policy,
|
|
46
25
|
driver: cloudflareRateLimitDriver({ binding }),
|
|
47
26
|
name
|
|
48
27
|
});
|
|
49
28
|
}
|
|
50
|
-
async function
|
|
29
|
+
async function consumeRateLimit(event, name, options, guard) {
|
|
51
30
|
const id = typeof name === "string" ? name.trim() : "";
|
|
52
|
-
if (!id) throw
|
|
31
|
+
if (!id) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0010({ message: `\`${guard}()\` requires a non-empty stable ID.` });
|
|
53
32
|
const unknownKey = options && typeof options === "object" && !Array.isArray(options) ? Object.keys(options).find((key) => !guardOptionKeys.has(key)) : void 0;
|
|
54
|
-
if (unknownKey) throw
|
|
55
|
-
if (options?.key !== void 0 && (typeof options.key !== "string" || options.key.length === 0)) throw
|
|
33
|
+
if (unknownKey) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0011({ message: `\`${guard}()\` does not support the "${unknownKey}" option.` });
|
|
34
|
+
if (options?.key !== void 0 && (typeof options.key !== "string" || options.key.length === 0)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0012({ message: `\`${guard}()\` key must be a non-empty string.` });
|
|
56
35
|
const policy = declaredRateLimitPolicy(normalizeRateLimitPolicy(options));
|
|
57
36
|
const { provider } = getRateLimitRuntimeConfig();
|
|
58
37
|
const key = options.key ?? getRequestKey(event, provider);
|
|
59
|
-
if (!key) throw
|
|
60
|
-
|
|
38
|
+
if (!key) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0013({ message: `[vitehub] \`${guard}()\` could not determine a request key. Pass key when limiting by user or tenant or when the request has no client address.` });
|
|
39
|
+
return await (provider === "cloudflare" ? getCloudflareRateLimiter(event, id, policy) : getMemoryRateLimiter(id, policy)).consume({ key });
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Consumes one request from a managed Rate Limit and returns the decision instead of throwing. Use it when a limited
|
|
43
|
+
* request still gets an answer, such as a cheaper fallback. `reason` is `limited` or `unavailable` when not allowed.
|
|
44
|
+
* Shares counters, discovery, and Provider Output with `requireRateLimit()`. Invalid options still throw.
|
|
45
|
+
*/
|
|
46
|
+
async function checkRateLimit(event, name, options) {
|
|
47
|
+
return await consumeRateLimit(event, name, options, "checkRateLimit");
|
|
48
|
+
}
|
|
49
|
+
async function requireRateLimit(event, name, options) {
|
|
50
|
+
const decision = await consumeRateLimit(event, name, options, "requireRateLimit");
|
|
61
51
|
if (decision.allowed) return;
|
|
62
|
-
if (decision.reason === "unavailable") throw
|
|
52
|
+
if (decision.reason === "unavailable") throw rateLimitHTTPError(event, {
|
|
63
53
|
cause: decision.cause,
|
|
64
54
|
message: "Rate limiting is unavailable.",
|
|
65
55
|
status: 503,
|
|
66
56
|
statusText: "Service Unavailable"
|
|
67
57
|
});
|
|
68
|
-
throw
|
|
58
|
+
throw rateLimitHTTPError(event, {
|
|
69
59
|
headers: decision.retryAfter === void 0 ? void 0 : { "Retry-After": String(decision.retryAfter) },
|
|
70
60
|
message: "Rate limit exceeded.",
|
|
71
61
|
status: 429,
|
|
72
62
|
statusText: "Too Many Requests"
|
|
73
63
|
});
|
|
74
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Nuxt 4 bundles every `h3` import as its own h3 1, which has `createError()` but no `HTTPError`. h3 2's
|
|
67
|
+
* `createError()` returns an `HTTPError`. h3 1 errors carry no headers, so an H3 1 event gets them on its response.
|
|
68
|
+
*/
|
|
69
|
+
function rateLimitHTTPError(event, details) {
|
|
70
|
+
if (details.headers && isH3V1Event(event)) for (const [name, value] of Object.entries(details.headers)) event.node.res?.setHeader(name, value);
|
|
71
|
+
return createError(details);
|
|
72
|
+
}
|
|
75
73
|
//#endregion
|
|
76
|
-
export { createRateLimiter, requireRateLimit };
|
|
74
|
+
export { checkRateLimit, createRateLimiter, peekRateLimit, requireRateLimit, resetRateLimit };
|