@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.
@@ -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 { _ as RateLimitRuntimeConfig, a as RateLimitDriver, b as RequireRateLimitOptions, c as RateLimitDriverOutcome, d as RateLimitFailurePolicy, f as RateLimitModuleOptions, g as RateLimitRequestEvent, h as RateLimitRejectedAttemptBehavior, i as RateLimitDecision, l as RateLimitDriverResult, m as RateLimitProvider, n as RateLimitConsumeInput, o as RateLimitDriverCapabilities, p as RateLimitPolicy, r as RateLimitCounterScope, s as RateLimitDriverInput, t as CreateRateLimiterOptions, u as RateLimitEnforcement, v as RateLimitWindow, x as ResolvedRateLimitPolicy, y as RateLimiter } from "./types-BX4hSfYX.js";
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
- declare function requireRateLimit(event: RateLimitRequestEvent, name: string, options: RequireRateLimitOptions): Promise<void>;
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 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, createRateLimiter, requireRateLimit };
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 { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-CHaHluMr.js";
2
- import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-BYZQ2tim.js";
3
- import { memoryRateLimitDriver } from "./drivers/memory.js";
4
- import { n as getRateLimitRuntimeConfig, t as getRateLimitLimiterCache } from "./state-DB4uJN5P.js";
5
- import { HTTPError, getRequestIP } from "h3";
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
- const target = event;
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.req.headers.get("cf-connecting-ip") || getRequestIP(event) : getRequestIP(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 new Error(`[vitehub] Cloudflare Rate Limit binding "${bindingName}" was not found on the request event.`);
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 requireRateLimit(event, name, options) {
29
+ async function consumeRateLimit(event, name, options, guard) {
51
30
  const id = typeof name === "string" ? name.trim() : "";
52
- if (!id) throw new TypeError("`requireRateLimit()` requires a non-empty stable ID.");
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 new TypeError(`\`requireRateLimit()\` does not support the "${unknownKey}" option.`);
55
- if (options?.key !== void 0 && (typeof options.key !== "string" || options.key.length === 0)) throw new TypeError("`requireRateLimit()` key must be a non-empty string.");
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 new Error("[vitehub] Rate Limit could not determine a request key. Pass key when limiting by user or tenant or when the request has no client address.");
60
- const decision = await (provider === "cloudflare" ? getCloudflareRateLimiter(event, id, policy) : await getMemoryRateLimiter(id, policy)).consume({ key });
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 new HTTPError({
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 new HTTPError({
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 };
@@ -0,0 +1,112 @@
1
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
2
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
3
+ function normalizeWindowsPath(input = "") {
4
+ if (!input) return input;
5
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
6
+ }
7
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
8
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
9
+ function cwd() {
10
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
11
+ return "/";
12
+ }
13
+ const resolve = function(...arguments_) {
14
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
15
+ let resolvedPath = "";
16
+ let resolvedAbsolute = false;
17
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
18
+ const path = index >= 0 ? arguments_[index] : cwd();
19
+ if (!path || path.length === 0) continue;
20
+ resolvedPath = `${path}/${resolvedPath}`;
21
+ resolvedAbsolute = isAbsolute(path);
22
+ }
23
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
24
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
25
+ return resolvedPath.length > 0 ? resolvedPath : ".";
26
+ };
27
+ function normalizeString(path, allowAboveRoot) {
28
+ let res = "";
29
+ let lastSegmentLength = 0;
30
+ let lastSlash = -1;
31
+ let dots = 0;
32
+ let char = null;
33
+ for (let index = 0; index <= path.length; ++index) {
34
+ if (index < path.length) char = path[index];
35
+ else if (char === "/") break;
36
+ else char = "/";
37
+ if (char === "/") {
38
+ if (lastSlash === index - 1 || dots === 1);
39
+ else if (dots === 2) {
40
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
41
+ if (res.length > 2) {
42
+ const lastSlashIndex = res.lastIndexOf("/");
43
+ if (lastSlashIndex === -1) {
44
+ res = "";
45
+ lastSegmentLength = 0;
46
+ } else {
47
+ res = res.slice(0, lastSlashIndex);
48
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
49
+ }
50
+ lastSlash = index;
51
+ dots = 0;
52
+ continue;
53
+ } else if (res.length > 0) {
54
+ res = "";
55
+ lastSegmentLength = 0;
56
+ lastSlash = index;
57
+ dots = 0;
58
+ continue;
59
+ }
60
+ }
61
+ if (allowAboveRoot) {
62
+ res += res.length > 0 ? "/.." : "..";
63
+ lastSegmentLength = 2;
64
+ }
65
+ } else {
66
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
67
+ else res = path.slice(lastSlash + 1, index);
68
+ lastSegmentLength = index - lastSlash - 1;
69
+ }
70
+ lastSlash = index;
71
+ dots = 0;
72
+ } else if (char === "." && dots !== -1) ++dots;
73
+ else dots = -1;
74
+ }
75
+ return res;
76
+ }
77
+ const isAbsolute = function(p) {
78
+ return _IS_ABSOLUTE_RE.test(p);
79
+ };
80
+ const relative = function(from, to) {
81
+ const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
82
+ const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
83
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
84
+ const _fromCopy = [..._from];
85
+ for (const segment of _fromCopy) {
86
+ if (_to[0] !== segment) break;
87
+ _from.shift();
88
+ _to.shift();
89
+ }
90
+ return [..._from.map(() => ".."), ..._to].join("/");
91
+ };
92
+ //#endregion
93
+ //#region ../internal/src/inspect.ts
94
+ function relativeDefinitionFile(projectRoot, file) {
95
+ return relative(projectRoot, file).replaceAll("\\", "/");
96
+ }
97
+ const redactedInspectionValue = "[redacted]";
98
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
99
+ const embeddedUrlCredentialPattern = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]*@/gi;
100
+ const embeddedCookiePattern = /\b([\w-]*cookie[\w-]*["']?\s*[:=]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n])*"(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|'(?:\\[^\r\n]|[^'\\\r\n])*'(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|[^\r\n]+?(?=\s*(?:;\s*[^;=\r\n/]+\s*(?:\r?\n|$)|&|\r?\n|$)))/gi;
101
+ const embeddedBearerPattern = /\bbearer\s+[^\s,;]+/gi;
102
+ const embeddedAuthorizationPattern = new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
103
+ const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
104
+ /**
105
+ * Removes credentials inside free text, for example an error message. URL credentials, bearer tokens, and
106
+ * `name=value` pairs with a secret name are replaced with `[redacted]`.
107
+ */
108
+ function redactInspectionText(value) {
109
+ return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
110
+ }
111
+ //#endregion
112
+ export { relativeDefinitionFile as n, resolve as r, redactInspectionText as t };