@adonix.org/cloud-spark 0.0.153 → 0.0.155
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 +3 -1
- package/dist/index.d.ts +21 -12
- package/dist/index.js +19 -13
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,6 +19,8 @@ npm install @adonix.org/cloud-spark
|
|
|
19
19
|
|
|
20
20
|
## :stopwatch: Quickstart
|
|
21
21
|
|
|
22
|
+
If you are new to Cloudflare Workers, be sure to check out the [Wrangler](#cowboy_hat_face-wrangler) section first.
|
|
23
|
+
|
|
22
24
|
:page_facing_up: hello-world.ts
|
|
23
25
|
|
|
24
26
|
```ts
|
|
@@ -26,7 +28,7 @@ import { BasicWorker, TextResponse } from "@adonix.org/cloud-spark";
|
|
|
26
28
|
|
|
27
29
|
export class HelloWorld extends BasicWorker {
|
|
28
30
|
protected override async get(): Promise<Response> {
|
|
29
|
-
return this.getResponse(TextResponse, "
|
|
31
|
+
return this.getResponse(TextResponse, "Hi from Cloud Spark!");
|
|
30
32
|
}
|
|
31
33
|
}
|
|
32
34
|
```
|
package/dist/index.d.ts
CHANGED
|
@@ -534,6 +534,26 @@ declare function getHeaderValues(headers: Headers, key: string): string[];
|
|
|
534
534
|
* @returns The normalized origin string, or `null` if not present or invalid.
|
|
535
535
|
*/
|
|
536
536
|
declare function getOrigin(request: Request): string | null;
|
|
537
|
+
/**
|
|
538
|
+
* Returns a new URL with its query parameters sorted into a stable order.
|
|
539
|
+
*
|
|
540
|
+
* This is useful for cache key generation: URLs that differ only in the
|
|
541
|
+
* order of their query parameters will normalize to the same key.
|
|
542
|
+
*
|
|
543
|
+
* @param request - The incoming Request whose URL will be normalized.
|
|
544
|
+
* @returns A new URL with query parameters sorted by name.
|
|
545
|
+
*/
|
|
546
|
+
declare function sortSearchParams(request: Request): URL;
|
|
547
|
+
/**
|
|
548
|
+
* Returns a new URL with all query parameters removed.
|
|
549
|
+
*
|
|
550
|
+
* This is useful when query parameters are not relevant to cache lookups,
|
|
551
|
+
* ensuring that variants of the same resource share a single cache entry.
|
|
552
|
+
*
|
|
553
|
+
* @param request - The incoming Request whose URL will be normalized.
|
|
554
|
+
* @returns A new URL with no query parameters.
|
|
555
|
+
*/
|
|
556
|
+
declare function stripSearchParams(request: Request): URL;
|
|
537
557
|
|
|
538
558
|
/**
|
|
539
559
|
* Returns the proper Content-Type string for a given media type.
|
|
@@ -544,17 +564,6 @@ declare function getOrigin(request: Request): string | null;
|
|
|
544
564
|
*/
|
|
545
565
|
declare function getContentType(type: MediaType): string;
|
|
546
566
|
|
|
547
|
-
/**
|
|
548
|
-
* Normalizes a URL string for use as a consistent cache key.
|
|
549
|
-
*
|
|
550
|
-
* - Sorts query parameters alphabetically so `?b=2&a=1` and `?a=1&b=2` are treated the same.
|
|
551
|
-
* - Leaves protocol, host, path, and query values intact.
|
|
552
|
-
*
|
|
553
|
-
* @param url The original URL string to normalize.
|
|
554
|
-
* @returns A normalized URL string suitable for hashing or direct cache key use.
|
|
555
|
-
*/
|
|
556
|
-
declare function normalizeUrl(url: string): URL;
|
|
557
|
-
|
|
558
567
|
/**
|
|
559
568
|
* A type-safe Cloudflare Worker handler with a guaranteed `fetch` method.
|
|
560
569
|
*
|
|
@@ -923,4 +932,4 @@ declare class ServiceUnavailable extends HttpError {
|
|
|
923
932
|
constructor(details?: string);
|
|
924
933
|
}
|
|
925
934
|
|
|
926
|
-
export { BadRequest, BasicWorker, CacheControl, ClonedResponse, type CorsConfig, type CorsInit, DELETE, type ErrorJson, Forbidden, GET, HEAD, Head, HtmlResponse, HttpError, HttpHeader, InternalServerError, JsonResponse, type MatchedRoute, MediaType, Method, MethodNotAllowed, MethodNotImplemented, Middleware, NotFound, NotImplemented, OPTIONS, Options, PATCH, POST, PUT, type PathParams, type Route, type RouteCallback, type RouteHandler, type RouteTable, type RouteTuple, RouteWorker, ServiceUnavailable, SuccessResponse, TextResponse, Time, Unauthorized, type Worker, type WorkerClass, WorkerResponse, assertMethods, cache, cors, getContentType, getHeaderValues, getOrigin, isMethod, isMethodArray, lexCompare, mergeHeader,
|
|
935
|
+
export { BadRequest, BasicWorker, CacheControl, ClonedResponse, type CorsConfig, type CorsInit, DELETE, type ErrorJson, Forbidden, GET, HEAD, Head, HtmlResponse, HttpError, HttpHeader, InternalServerError, JsonResponse, type MatchedRoute, MediaType, Method, MethodNotAllowed, MethodNotImplemented, Middleware, NotFound, NotImplemented, OPTIONS, Options, PATCH, POST, PUT, type PathParams, type Route, type RouteCallback, type RouteHandler, type RouteTable, type RouteTuple, RouteWorker, ServiceUnavailable, SuccessResponse, TextResponse, Time, Unauthorized, type Worker, type WorkerClass, WorkerResponse, assertMethods, cache, cors, getContentType, getHeaderValues, getOrigin, isMethod, isMethodArray, lexCompare, mergeHeader, setHeader, sortSearchParams, stripSearchParams };
|
package/dist/index.js
CHANGED
|
@@ -207,6 +207,21 @@ function getOrigin(request) {
|
|
|
207
207
|
return null;
|
|
208
208
|
}
|
|
209
209
|
}
|
|
210
|
+
function sortSearchParams(request) {
|
|
211
|
+
const url = new URL(request.url);
|
|
212
|
+
const sorted = new URLSearchParams(
|
|
213
|
+
[...url.searchParams.entries()].sort(([a], [b]) => lexCompare(a, b))
|
|
214
|
+
);
|
|
215
|
+
url.search = sorted.toString();
|
|
216
|
+
url.hash = "";
|
|
217
|
+
return url;
|
|
218
|
+
}
|
|
219
|
+
function stripSearchParams(request) {
|
|
220
|
+
const url = new URL(request.url);
|
|
221
|
+
url.search = "";
|
|
222
|
+
url.hash = "";
|
|
223
|
+
return url;
|
|
224
|
+
}
|
|
210
225
|
|
|
211
226
|
// src/utils/response.ts
|
|
212
227
|
var ADD_CHARSET = /* @__PURE__ */ new Set([
|
|
@@ -230,16 +245,6 @@ function getContentType(type) {
|
|
|
230
245
|
return type;
|
|
231
246
|
}
|
|
232
247
|
|
|
233
|
-
// src/utils/url.ts
|
|
234
|
-
function normalizeUrl(url) {
|
|
235
|
-
const u = new URL(url);
|
|
236
|
-
const params = [...u.searchParams.entries()];
|
|
237
|
-
params.sort(([a], [b]) => lexCompare(a, b));
|
|
238
|
-
u.search = params.map(([k, v]) => `${k}=${v}`).join("&");
|
|
239
|
-
u.hash = "";
|
|
240
|
-
return u;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
248
|
// src/middleware/cache/constants.ts
|
|
244
249
|
var VARY_WILDCARD = "*";
|
|
245
250
|
|
|
@@ -383,7 +388,7 @@ var CacheHandler = class extends Middleware {
|
|
|
383
388
|
* @returns A URL representing the main cache key for this request.
|
|
384
389
|
*/
|
|
385
390
|
getCacheKey(request) {
|
|
386
|
-
const key = this.getKey ? this.getKey(request) :
|
|
391
|
+
const key = this.getKey ? this.getKey(request) : sortSearchParams(request);
|
|
387
392
|
assertKey(key);
|
|
388
393
|
key.hash = "";
|
|
389
394
|
return key;
|
|
@@ -1078,7 +1083,8 @@ export {
|
|
|
1078
1083
|
isMethodArray,
|
|
1079
1084
|
lexCompare,
|
|
1080
1085
|
mergeHeader,
|
|
1081
|
-
|
|
1082
|
-
|
|
1086
|
+
setHeader,
|
|
1087
|
+
sortSearchParams,
|
|
1088
|
+
stripSearchParams
|
|
1083
1089
|
};
|
|
1084
1090
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/constants/cache.ts","../src/constants/http.ts","../src/constants/media-types.ts","../src/constants/time.ts","../src/guards/basic.ts","../src/guards/methods.ts","../src/middleware/middleware.ts","../src/guards/cache.ts","../src/utils/compare.ts","../src/utils/header.ts","../src/utils/request.ts","../src/utils/response.ts","../src/utils/url.ts","../src/middleware/cache/constants.ts","../src/middleware/cache/utils.ts","../src/middleware/cache/handler.ts","../src/responses.ts","../src/middleware/cors/constants.ts","../src/middleware/cors/utils.ts","../src/guards/cors.ts","../src/middleware/cors/handler.ts","../src/errors.ts","../src/workers/base-worker.ts","../src/guards/middleware.ts","../src/workers/middleware-worker.ts","../src/workers/basic-worker.ts","../src/routes.ts","../src/workers/route-worker.ts"],"sourcesContent":["/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport CacheLib from \"cache-control-parser\";\n\n/**\n * @see {@link https://github.com/etienne-martin/cache-control-parser | cache-control-parser}\n */\nexport type CacheControl = CacheLib.CacheControl;\nexport const CacheControl = {\n parse: CacheLib.parse,\n stringify: CacheLib.stringify,\n\n /** A CacheControl directive that disables all caching. */\n DISABLE: Object.freeze({\n \"no-cache\": true,\n \"no-store\": true,\n \"must-revalidate\": true,\n \"max-age\": 0,\n }) satisfies CacheControl,\n};\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * https://github.com/prettymuchbryce/http-status-codes\n */\nexport { StatusCodes } from \"http-status-codes\";\n\n/**\n * Standard HTTP header names and common values.\n */\nexport namespace HttpHeader {\n export const ALLOW = \"Allow\";\n export const ACCEPT_ENCODING = \"Accept-Encoding\";\n export const ORIGIN = \"Origin\";\n export const CONTENT_TYPE = \"Content-Type\";\n export const CACHE_CONTROL = \"Cache-Control\";\n export const USER_AGENT = \"User-Agent\";\n export const VARY = \"Vary\";\n\n // Security Headers\n export const CONTENT_SECURITY_POLICY = \"Content-Security-Policy\"; // fine-grained script/style/image restrictions\n export const PERMISSIONS_POLICY = \"Permissions-Policy\"; // formerly Feature-Policy, controls APIs like geolocation/camera\n export const STRICT_TRANSPORT_SECURITY = \"Strict-Transport-Security\"; // e.g. \"max-age=63072000; includeSubDomains; preload\"\n export const REFERRER_POLICY = \"Referrer-Policy\"; // e.g. \"no-referrer\", \"strict-origin-when-cross-origin\"\n export const X_CONTENT_TYPE_OPTIONS = \"X-Content-Type-Options\"; // usually \"nosniff\"\n export const X_FRAME_OPTIONS = \"X-Frame-Options\"; // e.g. \"DENY\" or \"SAMEORIGIN\"\n\n // Cors Headers\n export const ACCESS_CONTROL_ALLOW_CREDENTIALS = \"Access-Control-Allow-Credentials\";\n export const ACCESS_CONTROL_ALLOW_HEADERS = \"Access-Control-Allow-Headers\";\n export const ACCESS_CONTROL_ALLOW_METHODS = \"Access-Control-Allow-Methods\";\n export const ACCESS_CONTROL_ALLOW_ORIGIN = \"Access-Control-Allow-Origin\";\n export const ACCESS_CONTROL_EXPOSE_HEADERS = \"Access-Control-Expose-Headers\";\n export const ACCESS_CONTROL_MAX_AGE = \"Access-Control-Max-Age\";\n export const ACCESS_CONTROL_REQUEST_HEADERS = \"Access-Control-Request-Headers\";\n}\n\n/**\n * Standard HTTP request methods.\n */\nexport enum Method {\n GET = \"GET\",\n PUT = \"PUT\",\n HEAD = \"HEAD\",\n POST = \"POST\",\n PATCH = \"PATCH\",\n DELETE = \"DELETE\",\n OPTIONS = \"OPTIONS\",\n}\n\n/**\n * Shorthand constants for each HTTP method.\n *\n * These are equivalent to the corresponding enum members in `Method`.\n * For example, `GET === Method.GET`.\n */\nexport const { GET, PUT, HEAD, POST, PATCH, DELETE, OPTIONS } = Method;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Common media types used for HTTP headers.\n */\nexport enum MediaType {\n PLAIN_TEXT = \"text/plain\",\n HTML = \"text/html\",\n CSS = \"text/css\",\n CSV = \"text/csv\",\n XML = \"text/xml\",\n MARKDOWN = \"text/markdown\",\n RICH_TEXT = \"text/richtext\",\n JSON = \"application/json\",\n XML_APP = \"application/xml\",\n YAML = \"application/x-yaml\",\n FORM_URLENCODED = \"application/x-www-form-urlencoded\",\n NDJSON = \"application/x-ndjson\",\n MSGPACK = \"application/x-msgpack\",\n PROTOBUF = \"application/x-protobuf\",\n MULTIPART_FORM_DATA = \"multipart/form-data\",\n MULTIPART_MIXED = \"multipart/mixed\",\n MULTIPART_ALTERNATIVE = \"multipart/alternative\",\n MULTIPART_DIGEST = \"multipart/digest\",\n MULTIPART_RELATED = \"multipart/related\",\n MULTIPART_SIGNED = \"multipart/signed\",\n MULTIPART_ENCRYPTED = \"multipart/encrypted\",\n OCTET_STREAM = \"application/octet-stream\",\n PDF = \"application/pdf\",\n ZIP = \"application/zip\",\n GZIP = \"application/gzip\",\n MSWORD = \"application/msword\",\n DOCX = \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n EXCEL = \"application/vnd.ms-excel\",\n XLSX = \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n POWERPOINT = \"application/vnd.ms-powerpoint\",\n PPTX = \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n ICO = \"image/x-icon\",\n ICO_MS = \"image/vnd.microsoft.icon\",\n GIF = \"image/gif\",\n PNG = \"image/png\",\n JPEG = \"image/jpeg\",\n WEBP = \"image/webp\",\n SVG = \"image/svg+xml\",\n HEIF = \"image/heif\",\n AVIF = \"image/avif\",\n EVENT_STREAM = \"text/event-stream\",\n TAR = \"application/x-tar\",\n BZIP2 = \"application/x-bzip2\",\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Time constants in seconds. Month is approximated as 30 days.\n */\nexport const Time = {\n Second: 1,\n Minute: 60,\n Hour: 3600, // 60 * 60\n Day: 86400, // 60 * 60 * 24\n Week: 604800, // 60 * 60 * 24 * 7\n Month: 2592000, // 60 * 60 * 24 * 30\n Year: 31536000, // 60 * 60 * 24 * 365\n} as const;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks if the provided value is an array of strings.\n *\n * @param value - The value to check.\n * @returns True if `array` is an array where every item is a string.\n */\nexport function isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\n/**\n * Checks if a value is a string.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a string, otherwise `false`.\n */\nexport function isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n/**\n * Checks if a value is a function.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a function, otherwise `false`.\n */\nexport function isFunction(value: unknown): value is Function {\n return typeof value === \"function\";\n}\n\n/**\n * Checks if a value is a valid number (not NaN).\n *\n * This function returns `true` if the value is of type `number`\n * and is not `NaN`. It works as a type guard for TypeScript.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a number and not `NaN`, otherwise `false`.\n */\nexport function isNumber(value: unknown): value is number {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\n\n/**\n * Checks if a value is a boolean.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a boolean (`true` or `false`), otherwise `false`.\n */\nexport function isBoolean(value: unknown): value is boolean {\n return typeof value === \"boolean\";\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Method } from \"../constants/http\";\nimport { isString } from \"./basic\";\n\n/**\n * A set containing all supported HTTP methods.\n *\n * Useful for runtime checks like validating request methods.\n */\nconst METHOD_SET: Set<string> = new Set(Object.values(Method));\n\n/**\n * Type guard that checks if a string is a valid HTTP method.\n *\n * @param value - The string to test.\n * @returns True if `value` is a recognized HTTP method.\n */\nexport function isMethod(value: unknown): value is Method {\n return isString(value) && METHOD_SET.has(value);\n}\n\n/**\n * Checks if a value is an array of valid HTTP methods.\n *\n * Each element is verified using the `isMethod` type guard.\n *\n * @param value - The value to check.\n * @returns `true` if `value` is an array and every element is a valid `Method`, otherwise `false`.\n */\nexport function isMethodArray(value: unknown): value is Method[] {\n return Array.isArray(value) && value.every(isMethod);\n}\n\n/**\n * Asserts that a value is an array of valid HTTP methods.\n *\n * This function uses {@link isMethodArray} to validate the input. If the\n * value is not an array of `Method` elements, it throws a `TypeError`.\n * Otherwise, TypeScript will narrow the type of `value` to `Method[]`\n * within the calling scope.\n *\n * @param value - The value to check.\n * @throws TypeError If `value` is not a valid method array.\n */\nexport function assertMethods(value: unknown): asserts value is Method[] {\n if (!isMethodArray(value)) {\n const desc = Array.isArray(value) ? JSON.stringify(value) : String(value);\n throw new TypeError(`Invalid method array: ${desc}`);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Worker } from \"../interfaces/worker\";\n\n/**\n * Abstract base class for middleware.\n *\n * Middleware classes implement request/response processing logic in a\n * chainable manner. Each middleware receives a `Worker` object and a\n * `next` function that invokes the next middleware in the chain.\n *\n * Subclasses **must implement** the `handle` method.\n *\n * Example subclass:\n * ```ts\n * class LoggingMiddleware extends Middleware {\n * public async handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {\n * console.log(`Processing request: ${worker.request.url}`);\n * const response = await next();\n * console.log(`Response status: ${response.status}`);\n * return response;\n * }\n * }\n * ```\n */\nexport abstract class Middleware {\n /**\n * Process a request in the middleware chain.\n *\n * @param worker - The `Worker` instance representing the request context.\n * @param next - Function to invoke the next middleware in the chain.\n * Must be called to continue the chain unless the middleware\n * terminates early (e.g., returns a response directly).\n * @returns A `Response` object, either returned directly or from `next()`.\n */\n public abstract handle(worker: Worker, next: () => Promise<Response>): Promise<Response>;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isFunction, isString } from \"./basic\";\n\n/**\n * Asserts that a value is a string suitable for a cache name.\n *\n * If the value is `undefined`, this function does nothing.\n * Otherwise, it throws a `TypeError` if the value is not a string.\n *\n * @param value - The value to check.\n * @throws TypeError If the value is defined but not a string.\n */\nexport function assertCacheName(value: unknown): asserts value is string | undefined {\n if (value === undefined) return;\n if (!isString(value)) {\n throw new TypeError(\"Cache name must be a string.\");\n }\n}\n\n/**\n * Asserts that a value is a function suitable for `getKey`.\n *\n * If the value is `undefined`, this function does nothing.\n * Otherwise, it throws a `TypeError` if the value is not a function.\n *\n * @param value - The value to check.\n * @throws TypeError If the value is defined but not a function.\n */\nexport function assertGetKey(value: unknown): asserts value is Function | undefined {\n if (value === undefined) return;\n if (!isFunction(value)) {\n throw new TypeError(\"getKey must be a function.\");\n }\n}\n\n/**\n * Asserts that a value is a `URL` instance suitable for use as a cache key.\n *\n * If the value is not a `URL`, this function throws a `TypeError`.\n *\n * @param value - The value to check.\n * @throws TypeError If the value is not a `URL`.\n */\nexport function assertKey(value: unknown): asserts value is URL {\n if (!(value instanceof URL)) {\n throw new TypeError(\"getKey must return a URL.\");\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Lexicographically compares two strings.\n *\n * This comparator can be used in `Array.prototype.sort()` to produce a\n * consistent, stable ordering of string arrays.\n *\n * @param a - The first string to compare.\n * @param b - The second string to compare.\n * @returns A number indicating the relative order of `a` and `b`.\n */\nexport function lexCompare(a: string, b: string): number {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { lexCompare } from \"./compare\";\n\n/**\n * Sets a header on the given Headers object.\n *\n * - If `value` is an array, any duplicates and empty strings are removed.\n * - If the resulting value is empty, the header is deleted.\n * - Otherwise, values are joined with `\", \"` and set as the header value.\n *\n * @param headers - The Headers object to modify.\n * @param key - The header name to set.\n * @param value - The header value(s) to set. Can be a string or array of strings.\n */\nexport function setHeader(headers: Headers, key: string, value: string | string[]): void {\n const raw = Array.isArray(value) ? value : [value];\n const values = Array.from(new Set(raw.map((v) => v.trim())))\n .filter((v) => v.length)\n .sort(lexCompare);\n\n if (!values.length) {\n headers.delete(key);\n return;\n }\n\n headers.set(key, values.join(\", \"));\n}\n\n/**\n * Merges new value(s) into an existing header on the given Headers object.\n *\n * - Preserves any existing values and adds new ones.\n * - Removes duplicates and trims all values.\n * - If the header does not exist, it is created.\n * - If the resulting value array is empty, the header is deleted.\n *\n * @param headers - The Headers object to modify.\n * @param key - The header name to merge into.\n * @param value - The new header value(s) to add. Can be a string or array of strings.\n */\nexport function mergeHeader(headers: Headers, key: string, value: string | string[]): void {\n const values = Array.isArray(value) ? value : [value];\n if (values.length === 0) return;\n\n const existing = getHeaderValues(headers, key);\n const merged = existing.concat(values.map((v) => v.trim()));\n\n setHeader(headers, key, merged);\n}\n\n/**\n * Returns the values of an HTTP header as an array of strings.\n *\n * This helper:\n * - Retrieves the header value by `key`.\n * - Splits the value on commas.\n * - Trims surrounding whitespace from each entry.\n * - Filters out any empty tokens.\n * - Removes duplicate values (case-sensitive)\n *\n * If the header is not present, an empty array is returned.\n *\n */\nexport function getHeaderValues(headers: Headers, key: string): string[] {\n const values =\n headers\n .get(key)\n ?.split(\",\")\n .map((v) => v.trim())\n .filter((v) => v.length > 0) ?? [];\n return Array.from(new Set(values)).sort(lexCompare);\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader } from \"../constants/http\";\n\n/**\n * Extracts and normalizes the `Origin` header from a request.\n *\n * Returns the origin (scheme + host + port) as a string if present and valid.\n * Returns `null` if:\n * - The `Origin` header is missing\n * - The `Origin` header is `\"null\"` (opaque origin)\n * - The `Origin` header is malformed\n *\n * @param request - The incoming {@link Request} object.\n * @returns The normalized origin string, or `null` if not present or invalid.\n */\nexport function getOrigin(request: Request): string | null {\n const origin = request.headers.get(HttpHeader.ORIGIN)?.trim();\n if (!origin || origin === \"null\") return null;\n\n try {\n return new URL(origin).origin;\n } catch {\n return null;\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MediaType } from \"../constants/media-types\";\n\n/**\n * A set of media types that require a `charset` parameter when setting\n * the `Content-Type` header.\n *\n * This includes common text-based media types such as HTML, CSS, JSON,\n * XML, CSV, Markdown, and others.\n */\nconst ADD_CHARSET: Set<MediaType> = new Set([\n MediaType.CSS,\n MediaType.CSV,\n MediaType.XML,\n MediaType.SVG,\n MediaType.HTML,\n MediaType.JSON,\n MediaType.NDJSON,\n MediaType.XML_APP,\n MediaType.MARKDOWN,\n MediaType.RICH_TEXT,\n MediaType.PLAIN_TEXT,\n MediaType.FORM_URLENCODED,\n]);\n\n/**\n * Returns the proper Content-Type string for a given media type.\n * Appends `charset=utf-8` for text-based types that require it.\n *\n * @param type - The media type.\n * @returns A string suitable for the `Content-Type` header.\n */\nexport function getContentType(type: MediaType): string {\n if (ADD_CHARSET.has(type)) {\n return `${type}; charset=utf-8`;\n }\n return type;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { lexCompare } from \"./compare\";\n\n/**\n * Normalizes a URL string for use as a consistent cache key.\n *\n * - Sorts query parameters alphabetically so `?b=2&a=1` and `?a=1&b=2` are treated the same.\n * - Leaves protocol, host, path, and query values intact.\n *\n * @param url The original URL string to normalize.\n * @returns A normalized URL string suitable for hashing or direct cache key use.\n */\nexport function normalizeUrl(url: string): URL {\n const u = new URL(url);\n const params = [...u.searchParams.entries()];\n\n params.sort(([a], [b]) => lexCompare(a, b));\n\n u.search = params.map(([k, v]) => `${k}=${v}`).join(\"&\");\n u.hash = \"\";\n return u;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Wildcard member (`*`) for the `Vary` header.\n *\n * When present, it indicates that the response can vary based on unspecified\n * request headers. Such a response **MUST NOT be stored by a shared cache**,\n * since it cannot be reliably reused for any request.\n *\n * Example:\n * ```http\n * Vary: *\n * ```\n */\nexport const VARY_WILDCARD = \"*\";\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader } from \"../../constants/http\";\nimport { getHeaderValues, lexCompare } from \"../../utils\";\nimport { VARY_WILDCARD } from \"./constants\";\n\n/** Base URL used for constructing cache keys. Only used internally. */\nconst VARY_CACHE_URL = \"https://vary\";\n\n/**\n * Determines whether a Response is cacheable.\n * - Must have `ok` status (2xx-3xx)\n * - Must not contain a Vary header with a wildcard (`*`)\n *\n * @param response The Response object to check.\n * @returns `true` if the response can be cached; `false` otherwise.\n */\nexport function isCacheable(response: Response): boolean {\n if (!response.ok) return false;\n if (getVaryHeader(response).includes(VARY_WILDCARD)) return false;\n\n return true;\n}\n\n/**\n * Extracts and normalizes the `Vary` header from a Response.\n * - Splits comma-separated values\n * - Deduplicates\n * - Converts all values to lowercase\n * - Sorts lexicographically\n *\n * @param response The Response object containing headers.\n * @returns An array of normalized header names from the Vary header.\n */\nexport function getVaryHeader(response: Response): string[] {\n const values = getHeaderValues(response.headers, HttpHeader.VARY);\n return Array.from(new Set(values.map((v) => v.toLowerCase()))).sort(lexCompare);\n}\n\n/**\n * Filters out headers that should be ignored for caching, currently:\n * - `Accept-Encoding` (handled automatically by the platform)\n *\n * @param vary Array of normalized Vary header names.\n * @returns Array of headers used for computing cache variations.\n */\nexport function filterVaryHeader(vary: string[]): string[] {\n return vary\n .map((h) => h.toLowerCase())\n .filter((value) => value !== HttpHeader.ACCEPT_ENCODING.toLowerCase());\n}\n\n/**\n * Generates a Vary-aware cache key for a request.\n *\n * The key is based on:\n * 1. The provided `key` URL, which is normalized by default but can be fully customized\n * by the caller. For example, users can:\n * - Sort query parameters\n * - Remove the search/query string entirely\n * - Exclude certain query parameters\n * This allows full control over how this cache key is generated.\n * 2. The request headers listed in `vary` (after filtering and lowercasing).\n *\n * Behavior:\n * - Headers in `vary` are sorted and included in the key.\n * - The combination of the key URL and header values is base64-encoded to produce\n * a safe cache key.\n * - The resulting string is returned as an absolute URL rooted at `VARY_CACHE_URL`.\n *\n * @param request The Request object to generate a key for.\n * @param vary Array of header names from the `Vary` header that affect caching.\n * @param key The cache key to be used for this request. Can be modified by the caller for\n * custom cache key behavior.\n * @returns A string URL representing a unique cache key for this request + Vary headers.\n */\nexport function getVaryKey(request: Request, vary: string[], key: URL): string {\n const varyPairs: [string, string][] = [];\n const filtered = filterVaryHeader(vary);\n\n filtered.sort(lexCompare);\n filtered.forEach((header) => {\n const value = request.headers.get(header);\n if (value !== null) {\n varyPairs.push([header, value]);\n }\n });\n\n const encoded = base64UrlEncode(JSON.stringify([key.toString(), varyPairs]));\n return new URL(encoded, VARY_CACHE_URL).href;\n}\n\n/**\n * Encodes a string as URL-safe Base64.\n * - Converts to UTF-8 bytes\n * - Base64-encodes\n * - Replaces `+` with `-` and `/` with `_`\n * - Removes trailing `=`\n *\n * @param str The input string to encode.\n * @returns URL-safe Base64 string.\n */\nexport function base64UrlEncode(str: string): string {\n const utf8 = new TextEncoder().encode(str);\n let base64 = btoa(String.fromCharCode(...utf8));\n while (base64.endsWith(\"=\")) {\n base64 = base64.slice(0, -1);\n }\n return base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Middleware } from \"../middleware\";\nimport { Worker } from \"../../interfaces/worker\";\nimport { GET } from \"../../constants/http\";\nimport { assertCacheName, assertGetKey, assertKey } from \"../../guards/cache\";\nimport { filterVaryHeader, getVaryHeader, getVaryKey, isCacheable } from \"./utils\";\nimport { normalizeUrl } from \"../../utils/url\";\n\n/**\n * Creates a Vary-aware caching middleware for Workers.\n *\n * This middleware:\n * - Caches **GET requests** only.\n * - Respects the `Vary` header of responses, ensuring that requests\n * with different headers (e.g., `Origin`) receive the correct cached response.\n * - Skips caching for non-cacheable responses (e.g., error responses or\n * responses with `Vary: *`).\n *\n * @param cacheName Optional name of the cache to use. If omitted, the default cache is used.\n * @param getKey Optional function to compute a custom cache key from a request.\n * If omitted, the request URL is normalized and used as the key.\n * @returns A `Middleware` instance that can be used in a Worker pipeline.\n */\nexport function cache(cacheName?: string, getKey?: (request: Request) => URL): Middleware {\n assertCacheName(cacheName);\n assertGetKey(getKey);\n\n return new CacheHandler(cacheName, getKey);\n}\n\n/**\n * Cache Middleware Implementation\n * @see {@link cache}\n */\nclass CacheHandler extends Middleware {\n constructor(\n private readonly cacheName?: string,\n private readonly getKey?: (request: Request) => URL,\n ) {\n super();\n this.cacheName = cacheName?.trim() || undefined;\n }\n\n /**\n * Handles an incoming request.\n * - Bypasses caching for non-GET requests.\n * - Checks the cache for a stored response.\n * - Calls next if no cached response exists.\n * - Caches the response if it is cacheable.\n *\n * @param worker The Worker instance containing the request and context.\n * @param next Function to call the next middleware or origin fetch.\n * @returns A cached or freshly fetched Response.\n */\n public override async handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {\n if (worker.request.method !== GET) {\n return next();\n }\n\n const cache = this.cacheName ? await caches.open(this.cacheName) : caches.default;\n const cached = await this.getCached(cache, worker.request);\n if (cached) return cached;\n\n const response = await next();\n\n this.setCached(cache, worker, response);\n return response;\n }\n\n /**\n * Retrieves a cached response for a given request.\n * - Checks both the base cache key and any Vary-specific keys.\n *\n * @param cache The Cache object to check.\n * @param request The request to retrieve a cached response for.\n * @returns A cached Response if available, otherwise `undefined`.\n */\n public async getCached(cache: Cache, request: Request): Promise<Response | undefined> {\n const url = this.getCacheKey(request);\n const response = await cache.match(url);\n if (!response) return;\n\n const vary = this.getFilteredVary(response);\n if (vary.length === 0) return response;\n\n const key = getVaryKey(request, vary, url);\n return cache.match(key);\n }\n\n /**\n * Caches a response if it is cacheable.\n *\n * Behavior:\n * - Always stores the response under the main cache key. This ensures that\n * the response’s Vary headers are available for later cache lookups.\n * - If the response varies based on certain request headers (per the Vary header),\n * also stores a copy under a Vary-specific cache key so future requests\n * with matching headers can retrieve the correct response.\n *\n * @param cache The Cache object to store the response in.\n * @param worker The Worker instance containing the request and context.\n * @param response The Response to cache.\n */\n public async setCached(cache: Cache, worker: Worker, response: Response): Promise<void> {\n if (!isCacheable(response)) return;\n\n const url = this.getCacheKey(worker.request);\n\n // Always store the main cache entry to preserve Vary headers\n worker.ctx.waitUntil(cache.put(url, response.clone()));\n\n // Store request-specific cache entry if the response varies\n const vary = this.getFilteredVary(response);\n if (vary.length > 0) {\n worker.ctx.waitUntil(\n cache.put(getVaryKey(worker.request, vary, url), response.clone()),\n );\n }\n }\n\n /**\n * Extracts and filters the `Vary` header from a response.\n *\n * @param response - The HTTP response to inspect.\n * @returns An array of filtered header names from the `Vary` header.\n */\n public getFilteredVary(response: Response): string[] {\n return filterVaryHeader(getVaryHeader(response));\n }\n\n /**\n * Returns the cache key for a request.\n *\n * By default, this is a normalized URL including the path and query string.\n * However, users can provide a custom `getKey` function when creating the\n * `cache` middleware to fully control how the cache keys are generated.\n *\n * For example, a custom function could:\n * - Sort or remove query parameters\n * - Exclude the search/query string entirely\n * - Modify the path or host\n *\n * This allows complete flexibility over cache key generation.\n *\n * @param request The Request object to generate a cache key for.\n * @returns A URL representing the main cache key for this request.\n */\n public getCacheKey(request: Request): URL {\n const key = this.getKey ? this.getKey(request) : normalizeUrl(request.url);\n assertKey(key);\n\n key.hash = \"\";\n return key;\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getReasonPhrase, StatusCodes } from \"http-status-codes\";\nimport { CacheControl } from \"./constants/cache\";\nimport { setHeader, mergeHeader } from \"./utils/header\";\nimport { getContentType } from \"./utils/response\";\nimport { MediaType } from \"./constants/media-types\";\nimport { HttpHeader } from \"./constants/http\";\n\n/**\n * Base class for building HTTP responses.\n * Manages headers, status, and media type.\n */\nabstract class BaseResponse {\n /** HTTP headers for the response. */\n public headers: Headers = new Headers();\n\n /** HTTP status code (default 200 OK). */\n public status: StatusCodes = StatusCodes.OK;\n\n /** Optional status text. Defaults to standard reason phrase. */\n public statusText?: string;\n\n /** Default media type of the response body. */\n public mediaType: MediaType = MediaType.PLAIN_TEXT;\n\n /** Converts current state to ResponseInit for constructing a Response. */\n protected get responseInit(): ResponseInit {\n return {\n headers: this.headers,\n status: this.status,\n statusText: this.statusText ?? getReasonPhrase(this.status),\n };\n }\n\n /** Sets a header, overwriting any existing value. */\n public setHeader(key: string, value: string | string[]): void {\n setHeader(this.headers, key, value);\n }\n\n /** Merges a header with existing values (does not overwrite). */\n public mergeHeader(key: string, value: string | string[]): void {\n mergeHeader(this.headers, key, value);\n }\n\n /** Adds a Content-Type header if not already existing (does not overwrite). */\n public addContentType() {\n if (!this.headers.get(HttpHeader.CONTENT_TYPE)) {\n this.headers.set(HttpHeader.CONTENT_TYPE, getContentType(this.mediaType));\n }\n }\n}\n\n/**\n * Base response class that adds caching headers.\n */\nabstract class CacheResponse extends BaseResponse {\n constructor(public cache?: CacheControl) {\n super();\n }\n\n /** Adds Cache-Control header if caching is configured. */\n protected addCacheHeader(): void {\n if (this.cache) {\n this.headers.set(HttpHeader.CACHE_CONTROL, CacheControl.stringify(this.cache));\n }\n }\n}\n\n/**\n * Core worker response. Combines caching, and security headers.\n */\nexport abstract class WorkerResponse extends CacheResponse {\n constructor(\n private readonly body: BodyInit | null = null,\n cache?: CacheControl,\n ) {\n super(cache);\n }\n\n /** Builds the Response object with body, headers, and status. */\n public async getResponse(): Promise<Response> {\n this.addCacheHeader();\n\n const body = this.status === StatusCodes.NO_CONTENT ? null : this.body;\n\n if (body) this.addContentType();\n return new Response(body, this.responseInit);\n }\n}\n\n/**\n * Wraps an existing Response and clones its body, headers, and status.\n */\nexport class ClonedResponse extends WorkerResponse {\n constructor(response: Response, cache?: CacheControl) {\n const clone = response.clone();\n super(clone.body, cache);\n this.headers = new Headers(clone.headers);\n this.status = clone.status;\n this.statusText = clone.statusText;\n }\n}\n\n/**\n * Represents a successful response with customizable body, cache and status.\n */\nexport class SuccessResponse extends WorkerResponse {\n constructor(\n body: BodyInit | null = null,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n ) {\n super(body, cache);\n this.status = status;\n }\n}\n\n/**\n * JSON response. Automatically sets Content-Type to application/json.\n */\nexport class JsonResponse extends SuccessResponse {\n constructor(json: unknown = {}, cache?: CacheControl, status: StatusCodes = StatusCodes.OK) {\n super(JSON.stringify(json), cache, status);\n this.mediaType = MediaType.JSON;\n }\n}\n\n/**\n * HTML response. Automatically sets Content-Type to text/html.\n */\nexport class HtmlResponse extends SuccessResponse {\n constructor(body: string, cache?: CacheControl, status: StatusCodes = StatusCodes.OK) {\n super(body, cache, status);\n this.mediaType = MediaType.HTML;\n }\n}\n\n/**\n * Plain text response. Automatically sets Content-Type to text/plain.\n */\nexport class TextResponse extends SuccessResponse {\n constructor(content: string, cache?: CacheControl, status: StatusCodes = StatusCodes.OK) {\n super(content, cache, status);\n this.mediaType = MediaType.PLAIN_TEXT;\n }\n}\n\n/**\n * Response for HEAD requests. Copy headers and status from a GET response\n * without the body.\n */\nexport class Head extends WorkerResponse {\n constructor(get: Response) {\n super();\n this.status = get.status;\n this.statusText = get.statusText;\n this.headers = new Headers(get.headers);\n }\n}\n\n/**\n * Response for OPTIONS preflight requests.\n */\nexport class Options extends SuccessResponse {\n constructor() {\n super(null, undefined, StatusCodes.NO_CONTENT);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader } from \"../../constants/http\";\nimport { Time } from \"../../constants/time\";\nimport { CorsConfig } from \"../../interfaces/cors-config\";\n\nexport const ALLOW_ALL_ORIGINS = \"*\";\n\n/**\n * Default configuration for CORS middleware.\n */\nexport const defaultCorsConfig: CorsConfig = {\n allowedOrigins: [ALLOW_ALL_ORIGINS],\n allowedHeaders: [HttpHeader.CONTENT_TYPE],\n exposedHeaders: [],\n allowCredentials: false,\n maxAge: 5 * Time.Minute,\n} as const;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader, Method, GET, HEAD, OPTIONS } from \"../../constants/http\";\nimport { assertMethods } from \"../../guards/methods\";\nimport { CorsConfig } from \"../../interfaces/cors-config\";\nimport { Worker } from \"../../interfaces/worker\";\nimport { ClonedResponse, Options } from \"../../responses\";\nimport { mergeHeader, setHeader } from \"../../utils/header\";\nimport { getOrigin } from \"../../utils/request\";\nimport { ALLOW_ALL_ORIGINS } from \"./constants\";\n\n/**\n * Set of HTTP methods considered \"simple\" under the CORS specification.\n *\n * Simple methods do not trigger a preflight request:\n * - GET\n * - HEAD\n * - OPTIONS\n */\nconst SIMPLE_METHODS = new Set<Method>([GET, HEAD, OPTIONS]);\n\n/**\n * Handles a CORS preflight OPTIONS request.\n *\n * Sets the appropriate CORS headers based on the provided configuration\n * and the origin of the request.\n *\n * @param worker - The Worker handling the request.\n * @param cors - The CORS configuration.\n * @returns A Response object for the preflight request.\n */\nexport async function options(worker: Worker, cors: CorsConfig): Promise<Response> {\n const options = new Options();\n const origin = getOrigin(worker.request);\n\n if (origin) {\n setAllowOrigin(options.headers, cors, origin);\n setAllowCredentials(options.headers, cors, origin);\n }\n\n setAllowMethods(options.headers, worker);\n setMaxAge(options.headers, cors);\n setAllowHeaders(options.headers, cors);\n\n return options.getResponse();\n}\n\n/**\n * Applies CORS headers to an existing response.\n *\n * Useful for normal (non-preflight) responses where the response\n * should include CORS headers based on the request origin.\n *\n * @param response - The original Response object.\n * @param worker - The Worker handling the request.\n * @param cors - The CORS configuration.\n * @returns A new Response object with CORS headers applied.\n */\nexport async function apply(\n response: Response,\n worker: Worker,\n cors: CorsConfig,\n): Promise<Response> {\n const clone = new ClonedResponse(response);\n const origin = getOrigin(worker.request);\n\n deleteCorsHeaders(clone.headers);\n\n if (origin) {\n setAllowOrigin(clone.headers, cors, origin);\n setAllowCredentials(clone.headers, cors, origin);\n }\n\n setExposedHeaders(clone.headers, cors);\n\n return clone.getResponse();\n}\n\n/**\n * Sets the Access-Control-Allow-Origin header based on the CORS config\n * and request origin.\n *\n * @param headers - The headers object to modify.\n * @param cors - The CORS configuration.\n * @param origin - The request's origin, or null if not present.\n */\nexport function setAllowOrigin(headers: Headers, cors: CorsConfig, origin: string): void {\n if (allowAllOrigins(cors)) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN, ALLOW_ALL_ORIGINS);\n } else {\n if (cors.allowedOrigins.includes(origin)) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN, origin);\n }\n mergeHeader(headers, HttpHeader.VARY, HttpHeader.ORIGIN);\n }\n}\n\n/**\n * Conditionally sets the `Access-Control-Allow-Credentials` header\n * for a CORS response.\n *\n * This header is only set if:\n * 1. `cors.allowCredentials` is true,\n * 2. The configuration does **not** allow any origin (`*`), and\n * 3. The provided `origin` is explicitly listed in `cors.allowedOrigins`.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The CORS configuration.\n * @param origin - The origin of the incoming request.\n */\nexport function setAllowCredentials(headers: Headers, cors: CorsConfig, origin: string): void {\n if (!cors.allowCredentials) return;\n if (allowAllOrigins(cors)) return;\n if (!cors.allowedOrigins.includes(origin)) return;\n\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS, \"true\");\n}\n\n/**\n * Sets the `Access-Control-Allow-Methods` header for a CORS response,\n * but only for non-simple methods.\n *\n * Simple methods (GET, HEAD, OPTIONS) are automatically allowed by the\n * CORS spec, so this function only adds methods beyond those.\n *\n * @param headers - The Headers object to modify.\n * @param worker - The Worker instance used to retrieve allowed methods.\n */\nexport function setAllowMethods(headers: Headers, worker: Worker): void {\n const methods = worker.getAllowedMethods();\n assertMethods(methods);\n\n const allowed = methods.filter((method) => !SIMPLE_METHODS.has(method));\n\n if (allowed.length > 0) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_METHODS, allowed);\n }\n}\n\n/**\n * Sets the `Access-Control-Max-Age` header for a CORS response.\n *\n * This header indicates how long the results of a preflight request\n * can be cached by the client (in seconds).\n *\n * The value is **clamped to a non-negative integer** to comply with\n * the CORS specification:\n * - Decimal values are floored to the nearest integer.\n * - Negative values are treated as `0`.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The CORS configuration containing the `maxAge` value in seconds.\n */\nexport function setMaxAge(headers: Headers, cors: CorsConfig): void {\n const maxAge = Math.max(0, Math.floor(cors.maxAge));\n setHeader(headers, HttpHeader.ACCESS_CONTROL_MAX_AGE, String(maxAge));\n}\n\n/**\n * Sets the Access-Control-Allow-Headers header based on the CORS configuration.\n *\n * Only the headers explicitly listed in `cors.allowedHeaders` are sent.\n * If the array is empty, no Access-Control-Allow-Headers header is added.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The CORS configuration.\n */\nexport function setAllowHeaders(headers: Headers, cors: CorsConfig): void {\n if (cors.allowedHeaders.length > 0) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS, cors.allowedHeaders);\n }\n}\n\n/**\n * Sets the Access-Control-Expose-Headers header for a response.\n *\n * @param headers - The headers object to modify.\n * @param cors - The CORS configuration.\n */\nexport function setExposedHeaders(headers: Headers, cors: CorsConfig): void {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_EXPOSE_HEADERS, cors.exposedHeaders);\n}\n\n/**\n * Returns true if the CORS config allows all origins ('*').\n *\n * @param cors - The CORS configuration.\n */\nexport function allowAllOrigins(cors: CorsConfig): boolean {\n return cors.allowedOrigins.includes(ALLOW_ALL_ORIGINS);\n}\n\n/**\n * Deletes any existing CORS headers from the provided headers object.\n *\n * @param headers - The headers object to modify.\n */\nexport function deleteCorsHeaders(headers: Headers): void {\n headers.delete(HttpHeader.ACCESS_CONTROL_MAX_AGE);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_METHODS);\n headers.delete(HttpHeader.ACCESS_CONTROL_EXPOSE_HEADERS);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS);\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CorsInit } from \"../interfaces/cors-config\";\nimport { isBoolean, isNumber, isStringArray } from \"./basic\";\n\n/**\n * Throws if the given value is not a valid CorsInit.\n *\n * Checks only the fields that are present, since CorsInit is Partial<CorsConfig>.\n *\n * @param value - The value to check.\n */\nexport function assertCorsInit(value: unknown): asserts value is CorsInit {\n if (value === undefined) return;\n\n if (typeof value !== \"object\" || value === null) {\n throw new TypeError(\"CorsInit must be an object.\");\n }\n\n const obj = value as Record<string, unknown>;\n\n if (obj[\"allowedOrigins\"] !== undefined && !isStringArray(obj[\"allowedOrigins\"])) {\n throw new TypeError(\"CorsInit.allowedOrigins must be a string array.\");\n }\n\n if (obj[\"allowedHeaders\"] !== undefined && !isStringArray(obj[\"allowedHeaders\"])) {\n throw new TypeError(\"CorsInit.allowedHeaders must be a string array.\");\n }\n\n if (obj[\"exposedHeaders\"] !== undefined && !isStringArray(obj[\"exposedHeaders\"])) {\n throw new TypeError(\"CorsInit.exposedHeaders must be a string array.\");\n }\n\n if (obj[\"allowCredentials\"] !== undefined && !isBoolean(obj[\"allowCredentials\"])) {\n throw new TypeError(\"CorsInit.allowCredentials must be a boolean.\");\n }\n\n if (obj[\"maxAge\"] !== undefined && !isNumber(obj[\"maxAge\"])) {\n throw new TypeError(\"CorsInit.maxAge must be a number.\");\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { apply, options } from \"./utils\";\nimport { Worker } from \"../../interfaces/worker\";\nimport { Middleware } from \"../middleware\";\nimport { CorsConfig, CorsInit } from \"../../interfaces/cors-config\";\nimport { defaultCorsConfig } from \"./constants\";\nimport { OPTIONS } from \"../../constants/http\";\nimport { assertCorsInit } from \"../../guards/cors\";\n\n/**\n * Creates a CORS middleware instance.\n *\n * This middleware automatically handles Cross-Origin Resource Sharing (CORS)\n * for incoming requests, including preflight OPTIONS requests, and adds\n * appropriate headers to responses.\n *\n * @param init - Optional configuration for CORS behavior. See {@link CorsConfig}.\n * @returns A {@link Middleware} instance that can be used in your middleware chain.\n */\nexport function cors(init?: CorsInit): Middleware {\n assertCorsInit(init);\n return new CorsHandler(init);\n}\n\n/**\n * Cors Middleware Implementation\n * @see {@link cors}\n */\nclass CorsHandler extends Middleware {\n /** The configuration used for this instance, with all defaults applied. */\n private readonly config: CorsConfig;\n\n /**\n * Create a new CORS middleware instance.\n *\n * @param init - Partial configuration to override the defaults. Any values\n * not provided will use `defaultCorsConfig`.\n */\n constructor(init?: CorsInit) {\n super();\n this.config = { ...defaultCorsConfig, ...init };\n }\n\n /**\n * Applies CORS headers to a request.\n *\n * - Returns a preflight response for `OPTIONS` requests.\n * - For other methods, calls `next()` and applies CORS headers to the result.\n *\n * @param worker - The Worker handling the request.\n * @param next - Function to invoke the next middleware.\n * @returns Response with CORS headers applied.\n */\n public override async handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {\n if (worker.request.method === OPTIONS) {\n return options(worker, this.config);\n }\n\n const response = await next();\n\n return apply(response, worker, this.config);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getReasonPhrase, StatusCodes } from \"http-status-codes\";\nimport { JsonResponse } from \"./responses\";\nimport { ErrorJson } from \"./interfaces/error-json\";\nimport { Worker } from \"./interfaces/worker\";\nimport { CacheControl } from \"./constants/cache\";\nimport { HttpHeader } from \"./constants/http\";\nimport { assertMethods } from \"./guards\";\n\n/**\n * Generic HTTP error response.\n * Sends a JSON body with status, error message, and details.\n */\nexport class HttpError extends JsonResponse {\n /**\n * @param worker The worker handling the request.\n * @param status HTTP status code.\n * @param details Optional detailed error message.\n */\n constructor(\n status: StatusCodes,\n protected readonly details?: string,\n ) {\n const json: ErrorJson = {\n status,\n error: getReasonPhrase(status),\n details: details ?? \"\",\n };\n super(json, CacheControl.DISABLE, status);\n }\n}\n\n/** 400 Bad Request error response. */\nexport class BadRequest extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.BAD_REQUEST, details);\n }\n}\n\n/** 401 Unauthorized error response. */\nexport class Unauthorized extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.UNAUTHORIZED, details);\n }\n}\n\n/** 403 Forbidden error response. */\nexport class Forbidden extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.FORBIDDEN, details);\n }\n}\n\n/** 404 Not Found error response. */\nexport class NotFound extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.NOT_FOUND, details);\n }\n}\n\n/** 405 Method Not Allowed error response. */\nexport class MethodNotAllowed extends HttpError {\n constructor(worker: Worker) {\n const methods = worker.getAllowedMethods();\n assertMethods(methods);\n\n super(StatusCodes.METHOD_NOT_ALLOWED, `${worker.request.method} method not allowed.`);\n this.setHeader(HttpHeader.ALLOW, methods);\n }\n}\n\n/** 500 Internal Server Error response. */\nexport class InternalServerError extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.INTERNAL_SERVER_ERROR, details);\n }\n}\n\n/** 501 Not Implemented error response. */\nexport class NotImplemented extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.NOT_IMPLEMENTED, details);\n }\n}\n\n/** 501 Method Not Implemented error response for unsupported HTTP methods. */\nexport class MethodNotImplemented extends NotImplemented {\n constructor(worker: Worker) {\n super(`${worker.request.method} method not implemented.`);\n }\n}\n\n/** 503 Service Unavailable error response. */\nexport class ServiceUnavailable extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.SERVICE_UNAVAILABLE, details);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Method } from \"../constants/http\";\nimport { FetchHandler } from \"../interfaces/fetch-handler\";\nimport { Worker, WorkerClass } from \"../interfaces/worker\";\n\n/**\n * Provides the foundational structure for handling requests,\n * environment bindings, and the worker execution context.\n *\n * Features:\n * - Holds the current `Request` object (`request` getter).\n * - Provides access to environment bindings (`env` getter).\n * - Provides access to the worker execution context (`ctx` getter).\n * - Subclasses must implement `fetch()` to process the request.\n */\nexport abstract class BaseWorker implements Worker {\n constructor(\n private readonly _request: Request,\n private readonly _env: Env,\n private readonly _ctx: ExecutionContext,\n ) {}\n\n /** The Request object associated with this worker invocation */\n public get request(): Request {\n return this._request;\n }\n\n /** Environment bindings (e.g., KV, secrets, or other globals) */\n public get env(): Env {\n return this._env;\n }\n\n /** Execution context for background tasks or `waitUntil` */\n public get ctx(): ExecutionContext {\n return this._ctx;\n }\n\n /**\n * Dispatches the incoming request to the appropriate handler and produces a response.\n *\n * Subclasses must implement this method to define how the worker generates a `Response`\n * for the current request. This is the central point where request processing occurs.\n *\n * @returns A Promise that resolves to the `Response` for the request.\n */\n protected abstract dispatch(): Promise<Response>;\n\n public abstract getAllowedMethods(): Method[];\n\n /**\n * Creates a new instance of the current Worker subclass.\n *\n * @param request - The {@link Request} to pass to the new worker instance.\n * @returns A new worker instance of the same subclass as `this`.\n */\n protected create(request: Request): this {\n const ctor = this.constructor as WorkerClass<this>;\n return new ctor(request, this.env, this.ctx);\n }\n\n /**\n * Process the {@link Request} and produce a {@link Response}.\n *\n * @returns A {@link Response} promise for the {@link Request}.\n */\n public abstract fetch(): Promise<Response>;\n\n /**\n * **Ignite** your `Worker` implementation into a Cloudflare handler.\n *\n * @returns A `FetchHandler` that launches a new worker instance for each request.\n *\n * ```ts\n * export default MyWorker.ignite();\n * ```\n */\n public static ignite<W extends Worker>(this: WorkerClass<W>): FetchHandler {\n return {\n fetch: (request: Request, env: Env, ctx: ExecutionContext) =>\n new this(request, env, ctx).fetch(),\n };\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Middleware } from \"../middleware/middleware\";\n\n/**\n * Asserts at runtime that a value is a Middleware instance.\n *\n * @param handler - The value to check.\n * @throws TypeError If `handler` is not a `Middleware` subclass instance.\n */\nexport function assertMiddleware(handler: unknown): asserts handler is Middleware {\n if (!(handler instanceof Middleware)) {\n throw new TypeError(\"Handler must be a subclass of Middleware.\");\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseWorker } from \"./base-worker\";\nimport { Middleware } from \"../middleware/middleware\";\nimport { assertMiddleware } from \"../guards/middleware\";\n\n/** Internal base worker for handling middleware chains. */\nexport abstract class MiddlewareWorker extends BaseWorker {\n /** Middleware handlers registered for this worker. */\n protected readonly middlewares: Middleware[] = [];\n\n /**\n * Add a middleware instance to this worker.\n *\n * The middleware will run for every request handled by this worker,\n * in the order they are added.\n *\n * @param handler - The middleware to run.\n * @returns `this` to allow chaining multiple `.use()` calls.\n */\n public use(handler: Middleware): this {\n assertMiddleware(handler);\n\n this.middlewares.push(handler);\n return this;\n }\n\n /**\n * Executes the middleware chain and dispatches the request.\n *\n * @returns The Response produced by the last middleware or `dispatch()`.\n */\n public override async fetch(): Promise<Response> {\n const chain = this.middlewares.reduceRight(\n (next, handler) => () => handler.handle(this, next),\n () => this.dispatch(),\n );\n return await chain();\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MethodNotAllowed, InternalServerError, MethodNotImplemented } from \"../errors\";\nimport { MiddlewareWorker } from \"./middleware-worker\";\nimport { Head, WorkerResponse } from \"../responses\";\nimport { Method, GET, HEAD, OPTIONS } from \"../constants/http\";\nimport { assertMethods, isMethod } from \"../guards/methods\";\n\n/**\n * Basic worker class providing HTTP method dispatching and error handling.\n */\nexport abstract class BasicWorker extends MiddlewareWorker {\n /**\n * Entry point to handle a fetch request.\n */\n public override async fetch(): Promise<Response> {\n if (!this.isAllowed(this.request.method)) {\n return this.getResponse(MethodNotAllowed, this);\n }\n\n try {\n await this.init();\n return await super.fetch();\n } catch (error) {\n console.error(error);\n return this.getResponse(InternalServerError);\n }\n }\n\n /**\n * Dispatches the request to the method-specific handler.\n */\n protected override async dispatch(): Promise<Response> {\n const method = this.request.method as Method;\n const handler: Record<Method, () => Promise<Response>> = {\n GET: () => this.get(),\n PUT: () => this.put(),\n HEAD: () => this.head(),\n POST: () => this.post(),\n PATCH: () => this.patch(),\n DELETE: () => this.delete(),\n OPTIONS: () => this.options(),\n };\n\n return (handler[method] ?? (() => this.getResponse(MethodNotAllowed, this)))();\n }\n\n /**\n * Hook for subclasses to perform any initialization.\n */\n protected init(): void | Promise<void> {\n return;\n }\n\n /**\n * Checks if the given HTTP method is allowed for this worker.\n * @param method HTTP method string\n * @returns true if the method is allowed\n */\n public isAllowed(method: string): boolean {\n const methods = this.getAllowedMethods();\n assertMethods(methods);\n\n return isMethod(method) && methods.includes(method);\n }\n\n /** Override and implement this method for GET requests. */\n protected async get(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /** Override and implement this method for PUT requests. */\n protected async put(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /** Override and implement this method for POST requests. */\n protected async post(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /** Override and implement this method for PATCH requests. */\n protected async patch(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /** Override and implement this method for DELETE requests. */\n protected async delete(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /** Override and implement this method for OPTIONS requests. */\n protected async options(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /**\n * Default handler for HEAD requests.\n * Performs a GET request and removes the body for HEAD semantics.\n *\n * Usually does not need to be overridden as this behavior covers\n * standard HEAD requirements.\n */\n protected async head(): Promise<Response> {\n const worker = this.create(new Request(this.request, { method: GET }));\n return this.getResponse(Head, await worker.fetch());\n }\n\n /**\n * DEFAULT allowed HTTP methods for subclasses.\n *\n * These defaults were selected for getting started quickly and should be\n * overridden for each specific worker.\n */\n public getAllowedMethods(): Method[] {\n return [GET, HEAD, OPTIONS];\n }\n\n /**\n * Simplify and standardize {@link Response} creation by extending {@link WorkerResponse}\n * or any of its subclasses and passing to this method.\n *\n * Or directly use any of the built-in classes.\n *\n * ```ts\n * this.getResponse(TextResponse, \"Hello World!\")\n * ```\n *\n * @param ResponseClass The response class to instantiate\n * @param args Additional constructor arguments\n * @returns A Promise resolving to the {@link Response} object\n */\n protected async getResponse<\n Ctor extends new (...args: any[]) => { getResponse(): Promise<Response> },\n >(ResponseClass: Ctor, ...args: ConstructorParameters<Ctor>): Promise<Response> {\n return new ResponseClass(...args).getResponse();\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { match } from \"path-to-regexp\";\nimport { MatchedRoute, Route, PathParams, RouteTable } from \"./interfaces/route\";\nimport { Method } from \"./constants/http\";\n\n/**\n * Container for route definitions and matching logic.\n * Implements Iterable to allow iteration over all routes.\n */\nexport class Routes implements Iterable<Route> {\n /** Internal array of registered routes */\n private readonly routes: Route[] = [];\n\n /**\n * Add routes to the router.\n *\n * Accepts any iterable of [method, path, handler] tuples.\n * This includes arrays, Sets, or generators.\n *\n * @param routes - Iterable of route tuples to add.\n */\n public add(routes: RouteTable): void {\n for (const [method, path, handler] of routes) {\n const matcher = match<PathParams>(path);\n this.routes.push({ method, matcher, handler });\n }\n }\n\n /**\n * Attempt to match a URL against the registered routes.\n *\n * @param method - HTTP method of the request\n * @param url - Full URL string to match against\n * @returns A MatchedRoute object if a route matches, otherwise null\n */\n public match(method: Method, url: string): MatchedRoute | null {\n const pathname = new URL(url).pathname;\n\n for (const route of this) {\n if (route.method !== method) continue;\n\n const found = route.matcher(pathname);\n if (found) return { route, params: found.params };\n }\n\n return null;\n }\n\n /**\n * Iterate over all registered routes.\n */\n public *[Symbol.iterator](): Iterator<Route> {\n yield* this.routes;\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BasicWorker } from \"./basic-worker\";\nimport { NotFound } from \"../errors\";\nimport { Routes } from \"../routes\";\nimport { RouteHandler, RouteTable } from \"../interfaces/route\";\nimport { WorkerClass } from \"../interfaces/worker\";\nimport { BaseWorker } from \"./base-worker\";\nimport { Method } from \"../constants/http\";\n\n/**\n * Base worker supporting route-based request handling.\n *\n * Subclass `RouteWorker` to define a worker with multiple route handlers.\n *\n * Routes can be registered individually via `route()` or in bulk via `routes()`.\n */\nexport abstract class RouteWorker extends BasicWorker {\n /** Internal table of registered routes. */\n private readonly _routes: Routes = new Routes();\n\n /**\n * Registers a single new route in the worker.\n *\n * When a request matches the specified method and path, the provided handler\n * will be executed. The handler can be either:\n * - A function that receives URL parameters, or\n * - A Worker subclass that will handle the request.\n *\n * @param method - HTTP method for the route (GET, POST, etc.).\n * @param path - URL path pattern (Express-style, e.g., \"/users/:id\").\n * @param handler - The function or Worker class to run when the route matches.\n * @returns The current worker instance, allowing method chaining.\n */\n protected route(method: Method, path: string, handler: RouteHandler): this {\n this.routes([[method, path, handler]]);\n return this;\n }\n\n /**\n * Registers multiple routes at once in the worker.\n *\n * Each route should be a tuple `[method, path, handler]` where:\n * - `method` - HTTP method for the route (GET, POST, etc.).\n * - `path` - URL path pattern (Express-style, e.g., \"/users/:id\").\n * - `handler` - A function that receives URL parameters or a Worker subclass\n * that will handle the request.\n *\n * @param routes - An iterable of routes to register. Each item is a `[method, path, handler]` tuple.\n * @returns The current worker instance, allowing method chaining.\n */\n protected routes(routes: RouteTable): this {\n this._routes.add(routes);\n return this;\n }\n\n /**\n * Matches the incoming request against registered routes and dispatches it.\n *\n * If a route is found:\n * - If the handler is a Worker class, a new instance is created and its `fetch()` is called.\n * - If the handler is a callback function, it is invoked with the extracted path parameters.\n *\n * If no route matches, the request is passed to the parent `dispatch()` handler.\n *\n * @returns A `Promise<Response>` from the matched handler or parent dispatch.\n */\n protected override async dispatch(): Promise<Response> {\n const found = this._routes.match(this.request.method as Method, this.request.url);\n if (!found) return super.dispatch();\n\n const { handler } = found.route;\n if (RouteWorker.isWorkerClass(handler)) {\n return new handler(this.request, this.env, this.ctx).fetch();\n }\n return handler.call(this, found.params);\n }\n\n /**\n * Runtime type guard to check if a given handler is a Worker class.\n *\n * A Worker class is any class that extends `BaseWorker`.\n *\n * @param handler - The constructor function to test.\n * @returns `true` if `handler` is a subclass of `BaseWorker` at runtime, `false` otherwise.\n */\n private static isWorkerClass(handler: RouteHandler): handler is WorkerClass {\n return BaseWorker.prototype.isPrototypeOf(handler.prototype);\n }\n\n protected override async get(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n\n protected override async put(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n\n protected override async post(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n\n protected override async patch(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n\n protected override async delete(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n\n protected override async options(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n}\n"],"mappings":";AAgBA,OAAO,cAAc;AAMd,IAAM,eAAe;AAAA,EACxB,OAAO,SAAS;AAAA,EAChB,WAAW,SAAS;AAAA;AAAA,EAGpB,SAAS,OAAO,OAAO;AAAA,IACnB,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,mBAAmB;AAAA,IACnB,WAAW;AAAA,EACf,CAAC;AACL;;;ACdA,SAAS,mBAAmB;AAKrB,IAAU;AAAA,CAAV,CAAUA,gBAAV;AACI,EAAMA,YAAA,QAAQ;AACd,EAAMA,YAAA,kBAAkB;AACxB,EAAMA,YAAA,SAAS;AACf,EAAMA,YAAA,eAAe;AACrB,EAAMA,YAAA,gBAAgB;AACtB,EAAMA,YAAA,aAAa;AACnB,EAAMA,YAAA,OAAO;AAGb,EAAMA,YAAA,0BAA0B;AAChC,EAAMA,YAAA,qBAAqB;AAC3B,EAAMA,YAAA,4BAA4B;AAClC,EAAMA,YAAA,kBAAkB;AACxB,EAAMA,YAAA,yBAAyB;AAC/B,EAAMA,YAAA,kBAAkB;AAGxB,EAAMA,YAAA,mCAAmC;AACzC,EAAMA,YAAA,+BAA+B;AACrC,EAAMA,YAAA,+BAA+B;AACrC,EAAMA,YAAA,8BAA8B;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Codes"]}
|
|
1
|
+
{"version":3,"sources":["../src/constants/cache.ts","../src/constants/http.ts","../src/constants/media-types.ts","../src/constants/time.ts","../src/guards/basic.ts","../src/guards/methods.ts","../src/middleware/middleware.ts","../src/guards/cache.ts","../src/utils/compare.ts","../src/utils/header.ts","../src/utils/request.ts","../src/utils/response.ts","../src/middleware/cache/constants.ts","../src/middleware/cache/utils.ts","../src/middleware/cache/handler.ts","../src/responses.ts","../src/middleware/cors/constants.ts","../src/middleware/cors/utils.ts","../src/guards/cors.ts","../src/middleware/cors/handler.ts","../src/errors.ts","../src/workers/base-worker.ts","../src/guards/middleware.ts","../src/workers/middleware-worker.ts","../src/workers/basic-worker.ts","../src/routes.ts","../src/workers/route-worker.ts"],"sourcesContent":["/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport CacheLib from \"cache-control-parser\";\n\n/**\n * @see {@link https://github.com/etienne-martin/cache-control-parser | cache-control-parser}\n */\nexport type CacheControl = CacheLib.CacheControl;\nexport const CacheControl = {\n parse: CacheLib.parse,\n stringify: CacheLib.stringify,\n\n /** A CacheControl directive that disables all caching. */\n DISABLE: Object.freeze({\n \"no-cache\": true,\n \"no-store\": true,\n \"must-revalidate\": true,\n \"max-age\": 0,\n }) satisfies CacheControl,\n};\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * https://github.com/prettymuchbryce/http-status-codes\n */\nexport { StatusCodes } from \"http-status-codes\";\n\n/**\n * Standard HTTP header names and common values.\n */\nexport namespace HttpHeader {\n export const ALLOW = \"Allow\";\n export const ACCEPT_ENCODING = \"Accept-Encoding\";\n export const ORIGIN = \"Origin\";\n export const CONTENT_TYPE = \"Content-Type\";\n export const CACHE_CONTROL = \"Cache-Control\";\n export const USER_AGENT = \"User-Agent\";\n export const VARY = \"Vary\";\n\n // Security Headers\n export const CONTENT_SECURITY_POLICY = \"Content-Security-Policy\"; // fine-grained script/style/image restrictions\n export const PERMISSIONS_POLICY = \"Permissions-Policy\"; // formerly Feature-Policy, controls APIs like geolocation/camera\n export const STRICT_TRANSPORT_SECURITY = \"Strict-Transport-Security\"; // e.g. \"max-age=63072000; includeSubDomains; preload\"\n export const REFERRER_POLICY = \"Referrer-Policy\"; // e.g. \"no-referrer\", \"strict-origin-when-cross-origin\"\n export const X_CONTENT_TYPE_OPTIONS = \"X-Content-Type-Options\"; // usually \"nosniff\"\n export const X_FRAME_OPTIONS = \"X-Frame-Options\"; // e.g. \"DENY\" or \"SAMEORIGIN\"\n\n // Cors Headers\n export const ACCESS_CONTROL_ALLOW_CREDENTIALS = \"Access-Control-Allow-Credentials\";\n export const ACCESS_CONTROL_ALLOW_HEADERS = \"Access-Control-Allow-Headers\";\n export const ACCESS_CONTROL_ALLOW_METHODS = \"Access-Control-Allow-Methods\";\n export const ACCESS_CONTROL_ALLOW_ORIGIN = \"Access-Control-Allow-Origin\";\n export const ACCESS_CONTROL_EXPOSE_HEADERS = \"Access-Control-Expose-Headers\";\n export const ACCESS_CONTROL_MAX_AGE = \"Access-Control-Max-Age\";\n export const ACCESS_CONTROL_REQUEST_HEADERS = \"Access-Control-Request-Headers\";\n}\n\n/**\n * Standard HTTP request methods.\n */\nexport enum Method {\n GET = \"GET\",\n PUT = \"PUT\",\n HEAD = \"HEAD\",\n POST = \"POST\",\n PATCH = \"PATCH\",\n DELETE = \"DELETE\",\n OPTIONS = \"OPTIONS\",\n}\n\n/**\n * Shorthand constants for each HTTP method.\n *\n * These are equivalent to the corresponding enum members in `Method`.\n * For example, `GET === Method.GET`.\n */\nexport const { GET, PUT, HEAD, POST, PATCH, DELETE, OPTIONS } = Method;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Common media types used for HTTP headers.\n */\nexport enum MediaType {\n PLAIN_TEXT = \"text/plain\",\n HTML = \"text/html\",\n CSS = \"text/css\",\n CSV = \"text/csv\",\n XML = \"text/xml\",\n MARKDOWN = \"text/markdown\",\n RICH_TEXT = \"text/richtext\",\n JSON = \"application/json\",\n XML_APP = \"application/xml\",\n YAML = \"application/x-yaml\",\n FORM_URLENCODED = \"application/x-www-form-urlencoded\",\n NDJSON = \"application/x-ndjson\",\n MSGPACK = \"application/x-msgpack\",\n PROTOBUF = \"application/x-protobuf\",\n MULTIPART_FORM_DATA = \"multipart/form-data\",\n MULTIPART_MIXED = \"multipart/mixed\",\n MULTIPART_ALTERNATIVE = \"multipart/alternative\",\n MULTIPART_DIGEST = \"multipart/digest\",\n MULTIPART_RELATED = \"multipart/related\",\n MULTIPART_SIGNED = \"multipart/signed\",\n MULTIPART_ENCRYPTED = \"multipart/encrypted\",\n OCTET_STREAM = \"application/octet-stream\",\n PDF = \"application/pdf\",\n ZIP = \"application/zip\",\n GZIP = \"application/gzip\",\n MSWORD = \"application/msword\",\n DOCX = \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n EXCEL = \"application/vnd.ms-excel\",\n XLSX = \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n POWERPOINT = \"application/vnd.ms-powerpoint\",\n PPTX = \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n ICO = \"image/x-icon\",\n ICO_MS = \"image/vnd.microsoft.icon\",\n GIF = \"image/gif\",\n PNG = \"image/png\",\n JPEG = \"image/jpeg\",\n WEBP = \"image/webp\",\n SVG = \"image/svg+xml\",\n HEIF = \"image/heif\",\n AVIF = \"image/avif\",\n EVENT_STREAM = \"text/event-stream\",\n TAR = \"application/x-tar\",\n BZIP2 = \"application/x-bzip2\",\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Time constants in seconds. Month is approximated as 30 days.\n */\nexport const Time = {\n Second: 1,\n Minute: 60,\n Hour: 3600, // 60 * 60\n Day: 86400, // 60 * 60 * 24\n Week: 604800, // 60 * 60 * 24 * 7\n Month: 2592000, // 60 * 60 * 24 * 30\n Year: 31536000, // 60 * 60 * 24 * 365\n} as const;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks if the provided value is an array of strings.\n *\n * @param value - The value to check.\n * @returns True if `array` is an array where every item is a string.\n */\nexport function isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\n/**\n * Checks if a value is a string.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a string, otherwise `false`.\n */\nexport function isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n/**\n * Checks if a value is a function.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a function, otherwise `false`.\n */\nexport function isFunction(value: unknown): value is Function {\n return typeof value === \"function\";\n}\n\n/**\n * Checks if a value is a valid number (not NaN).\n *\n * This function returns `true` if the value is of type `number`\n * and is not `NaN`. It works as a type guard for TypeScript.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a number and not `NaN`, otherwise `false`.\n */\nexport function isNumber(value: unknown): value is number {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\n\n/**\n * Checks if a value is a boolean.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a boolean (`true` or `false`), otherwise `false`.\n */\nexport function isBoolean(value: unknown): value is boolean {\n return typeof value === \"boolean\";\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Method } from \"../constants/http\";\nimport { isString } from \"./basic\";\n\n/**\n * A set containing all supported HTTP methods.\n *\n * Useful for runtime checks like validating request methods.\n */\nconst METHOD_SET: Set<string> = new Set(Object.values(Method));\n\n/**\n * Type guard that checks if a string is a valid HTTP method.\n *\n * @param value - The string to test.\n * @returns True if `value` is a recognized HTTP method.\n */\nexport function isMethod(value: unknown): value is Method {\n return isString(value) && METHOD_SET.has(value);\n}\n\n/**\n * Checks if a value is an array of valid HTTP methods.\n *\n * Each element is verified using the `isMethod` type guard.\n *\n * @param value - The value to check.\n * @returns `true` if `value` is an array and every element is a valid `Method`, otherwise `false`.\n */\nexport function isMethodArray(value: unknown): value is Method[] {\n return Array.isArray(value) && value.every(isMethod);\n}\n\n/**\n * Asserts that a value is an array of valid HTTP methods.\n *\n * This function uses {@link isMethodArray} to validate the input. If the\n * value is not an array of `Method` elements, it throws a `TypeError`.\n * Otherwise, TypeScript will narrow the type of `value` to `Method[]`\n * within the calling scope.\n *\n * @param value - The value to check.\n * @throws TypeError If `value` is not a valid method array.\n */\nexport function assertMethods(value: unknown): asserts value is Method[] {\n if (!isMethodArray(value)) {\n const desc = Array.isArray(value) ? JSON.stringify(value) : String(value);\n throw new TypeError(`Invalid method array: ${desc}`);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Worker } from \"../interfaces/worker\";\n\n/**\n * Abstract base class for middleware.\n *\n * Middleware classes implement request/response processing logic in a\n * chainable manner. Each middleware receives a `Worker` object and a\n * `next` function that invokes the next middleware in the chain.\n *\n * Subclasses **must implement** the `handle` method.\n *\n * Example subclass:\n * ```ts\n * class LoggingMiddleware extends Middleware {\n * public async handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {\n * console.log(`Processing request: ${worker.request.url}`);\n * const response = await next();\n * console.log(`Response status: ${response.status}`);\n * return response;\n * }\n * }\n * ```\n */\nexport abstract class Middleware {\n /**\n * Process a request in the middleware chain.\n *\n * @param worker - The `Worker` instance representing the request context.\n * @param next - Function to invoke the next middleware in the chain.\n * Must be called to continue the chain unless the middleware\n * terminates early (e.g., returns a response directly).\n * @returns A `Response` object, either returned directly or from `next()`.\n */\n public abstract handle(worker: Worker, next: () => Promise<Response>): Promise<Response>;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isFunction, isString } from \"./basic\";\n\n/**\n * Asserts that a value is a string suitable for a cache name.\n *\n * If the value is `undefined`, this function does nothing.\n * Otherwise, it throws a `TypeError` if the value is not a string.\n *\n * @param value - The value to check.\n * @throws TypeError If the value is defined but not a string.\n */\nexport function assertCacheName(value: unknown): asserts value is string | undefined {\n if (value === undefined) return;\n if (!isString(value)) {\n throw new TypeError(\"Cache name must be a string.\");\n }\n}\n\n/**\n * Asserts that a value is a function suitable for `getKey`.\n *\n * If the value is `undefined`, this function does nothing.\n * Otherwise, it throws a `TypeError` if the value is not a function.\n *\n * @param value - The value to check.\n * @throws TypeError If the value is defined but not a function.\n */\nexport function assertGetKey(value: unknown): asserts value is Function | undefined {\n if (value === undefined) return;\n if (!isFunction(value)) {\n throw new TypeError(\"getKey must be a function.\");\n }\n}\n\n/**\n * Asserts that a value is a `URL` instance suitable for use as a cache key.\n *\n * If the value is not a `URL`, this function throws a `TypeError`.\n *\n * @param value - The value to check.\n * @throws TypeError If the value is not a `URL`.\n */\nexport function assertKey(value: unknown): asserts value is URL {\n if (!(value instanceof URL)) {\n throw new TypeError(\"getKey must return a URL.\");\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Lexicographically compares two strings.\n *\n * This comparator can be used in `Array.prototype.sort()` to produce a\n * consistent, stable ordering of string arrays.\n *\n * @param a - The first string to compare.\n * @param b - The second string to compare.\n * @returns A number indicating the relative order of `a` and `b`.\n */\nexport function lexCompare(a: string, b: string): number {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { lexCompare } from \"./compare\";\n\n/**\n * Sets a header on the given Headers object.\n *\n * - If `value` is an array, any duplicates and empty strings are removed.\n * - If the resulting value is empty, the header is deleted.\n * - Otherwise, values are joined with `\", \"` and set as the header value.\n *\n * @param headers - The Headers object to modify.\n * @param key - The header name to set.\n * @param value - The header value(s) to set. Can be a string or array of strings.\n */\nexport function setHeader(headers: Headers, key: string, value: string | string[]): void {\n const raw = Array.isArray(value) ? value : [value];\n const values = Array.from(new Set(raw.map((v) => v.trim())))\n .filter((v) => v.length)\n .sort(lexCompare);\n\n if (!values.length) {\n headers.delete(key);\n return;\n }\n\n headers.set(key, values.join(\", \"));\n}\n\n/**\n * Merges new value(s) into an existing header on the given Headers object.\n *\n * - Preserves any existing values and adds new ones.\n * - Removes duplicates and trims all values.\n * - If the header does not exist, it is created.\n * - If the resulting value array is empty, the header is deleted.\n *\n * @param headers - The Headers object to modify.\n * @param key - The header name to merge into.\n * @param value - The new header value(s) to add. Can be a string or array of strings.\n */\nexport function mergeHeader(headers: Headers, key: string, value: string | string[]): void {\n const values = Array.isArray(value) ? value : [value];\n if (values.length === 0) return;\n\n const existing = getHeaderValues(headers, key);\n const merged = existing.concat(values.map((v) => v.trim()));\n\n setHeader(headers, key, merged);\n}\n\n/**\n * Returns the values of an HTTP header as an array of strings.\n *\n * This helper:\n * - Retrieves the header value by `key`.\n * - Splits the value on commas.\n * - Trims surrounding whitespace from each entry.\n * - Filters out any empty tokens.\n * - Removes duplicate values (case-sensitive)\n *\n * If the header is not present, an empty array is returned.\n *\n */\nexport function getHeaderValues(headers: Headers, key: string): string[] {\n const values =\n headers\n .get(key)\n ?.split(\",\")\n .map((v) => v.trim())\n .filter((v) => v.length > 0) ?? [];\n return Array.from(new Set(values)).sort(lexCompare);\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader } from \"../constants/http\";\nimport { lexCompare } from \"./compare\";\n\n/**\n * Extracts and normalizes the `Origin` header from a request.\n *\n * Returns the origin (scheme + host + port) as a string if present and valid.\n * Returns `null` if:\n * - The `Origin` header is missing\n * - The `Origin` header is `\"null\"` (opaque origin)\n * - The `Origin` header is malformed\n *\n * @param request - The incoming {@link Request} object.\n * @returns The normalized origin string, or `null` if not present or invalid.\n */\nexport function getOrigin(request: Request): string | null {\n const origin = request.headers.get(HttpHeader.ORIGIN)?.trim();\n if (!origin || origin === \"null\") return null;\n\n try {\n return new URL(origin).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Returns a new URL with its query parameters sorted into a stable order.\n *\n * This is useful for cache key generation: URLs that differ only in the\n * order of their query parameters will normalize to the same key.\n *\n * @param request - The incoming Request whose URL will be normalized.\n * @returns A new URL with query parameters sorted by name.\n */\nexport function sortSearchParams(request: Request): URL {\n const url = new URL(request.url);\n const sorted = new URLSearchParams(\n [...url.searchParams.entries()].sort(([a], [b]) => lexCompare(a, b)),\n );\n url.search = sorted.toString();\n url.hash = \"\";\n return url;\n}\n\n/**\n * Returns a new URL with all query parameters removed.\n *\n * This is useful when query parameters are not relevant to cache lookups,\n * ensuring that variants of the same resource share a single cache entry.\n *\n * @param request - The incoming Request whose URL will be normalized.\n * @returns A new URL with no query parameters.\n */\nexport function stripSearchParams(request: Request): URL {\n const url = new URL(request.url);\n url.search = \"\";\n url.hash = \"\";\n return url;\n}\n\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MediaType } from \"../constants/media-types\";\n\n/**\n * A set of media types that require a `charset` parameter when setting\n * the `Content-Type` header.\n *\n * This includes common text-based media types such as HTML, CSS, JSON,\n * XML, CSV, Markdown, and others.\n */\nconst ADD_CHARSET: Set<MediaType> = new Set([\n MediaType.CSS,\n MediaType.CSV,\n MediaType.XML,\n MediaType.SVG,\n MediaType.HTML,\n MediaType.JSON,\n MediaType.NDJSON,\n MediaType.XML_APP,\n MediaType.MARKDOWN,\n MediaType.RICH_TEXT,\n MediaType.PLAIN_TEXT,\n MediaType.FORM_URLENCODED,\n]);\n\n/**\n * Returns the proper Content-Type string for a given media type.\n * Appends `charset=utf-8` for text-based types that require it.\n *\n * @param type - The media type.\n * @returns A string suitable for the `Content-Type` header.\n */\nexport function getContentType(type: MediaType): string {\n if (ADD_CHARSET.has(type)) {\n return `${type}; charset=utf-8`;\n }\n return type;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Wildcard member (`*`) for the `Vary` header.\n *\n * When present, it indicates that the response can vary based on unspecified\n * request headers. Such a response **MUST NOT be stored by a shared cache**,\n * since it cannot be reliably reused for any request.\n *\n * Example:\n * ```http\n * Vary: *\n * ```\n */\nexport const VARY_WILDCARD = \"*\";\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader } from \"../../constants/http\";\nimport { getHeaderValues, lexCompare } from \"../../utils\";\nimport { VARY_WILDCARD } from \"./constants\";\n\n/** Base URL used for constructing cache keys. Only used internally. */\nconst VARY_CACHE_URL = \"https://vary\";\n\n/**\n * Determines whether a Response is cacheable.\n * - Must have `ok` status (2xx-3xx)\n * - Must not contain a Vary header with a wildcard (`*`)\n *\n * @param response The Response object to check.\n * @returns `true` if the response can be cached; `false` otherwise.\n */\nexport function isCacheable(response: Response): boolean {\n if (!response.ok) return false;\n if (getVaryHeader(response).includes(VARY_WILDCARD)) return false;\n\n return true;\n}\n\n/**\n * Extracts and normalizes the `Vary` header from a Response.\n * - Splits comma-separated values\n * - Deduplicates\n * - Converts all values to lowercase\n * - Sorts lexicographically\n *\n * @param response The Response object containing headers.\n * @returns An array of normalized header names from the Vary header.\n */\nexport function getVaryHeader(response: Response): string[] {\n const values = getHeaderValues(response.headers, HttpHeader.VARY);\n return Array.from(new Set(values.map((v) => v.toLowerCase()))).sort(lexCompare);\n}\n\n/**\n * Filters out headers that should be ignored for caching, currently:\n * - `Accept-Encoding` (handled automatically by the platform)\n *\n * @param vary Array of normalized Vary header names.\n * @returns Array of headers used for computing cache variations.\n */\nexport function filterVaryHeader(vary: string[]): string[] {\n return vary\n .map((h) => h.toLowerCase())\n .filter((value) => value !== HttpHeader.ACCEPT_ENCODING.toLowerCase());\n}\n\n/**\n * Generates a Vary-aware cache key for a request.\n *\n * The key is based on:\n * 1. The provided `key` URL, which is normalized by default but can be fully customized\n * by the caller. For example, users can:\n * - Sort query parameters\n * - Remove the search/query string entirely\n * - Exclude certain query parameters\n * This allows full control over how this cache key is generated.\n * 2. The request headers listed in `vary` (after filtering and lowercasing).\n *\n * Behavior:\n * - Headers in `vary` are sorted and included in the key.\n * - The combination of the key URL and header values is base64-encoded to produce\n * a safe cache key.\n * - The resulting string is returned as an absolute URL rooted at `VARY_CACHE_URL`.\n *\n * @param request The Request object to generate a key for.\n * @param vary Array of header names from the `Vary` header that affect caching.\n * @param key The cache key to be used for this request. Can be modified by the caller for\n * custom cache key behavior.\n * @returns A string URL representing a unique cache key for this request + Vary headers.\n */\nexport function getVaryKey(request: Request, vary: string[], key: URL): string {\n const varyPairs: [string, string][] = [];\n const filtered = filterVaryHeader(vary);\n\n filtered.sort(lexCompare);\n filtered.forEach((header) => {\n const value = request.headers.get(header);\n if (value !== null) {\n varyPairs.push([header, value]);\n }\n });\n\n const encoded = base64UrlEncode(JSON.stringify([key.toString(), varyPairs]));\n return new URL(encoded, VARY_CACHE_URL).href;\n}\n\n/**\n * Encodes a string as URL-safe Base64.\n * - Converts to UTF-8 bytes\n * - Base64-encodes\n * - Replaces `+` with `-` and `/` with `_`\n * - Removes trailing `=`\n *\n * @param str The input string to encode.\n * @returns URL-safe Base64 string.\n */\nexport function base64UrlEncode(str: string): string {\n const utf8 = new TextEncoder().encode(str);\n let base64 = btoa(String.fromCharCode(...utf8));\n while (base64.endsWith(\"=\")) {\n base64 = base64.slice(0, -1);\n }\n return base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Middleware } from \"../middleware\";\nimport { Worker } from \"../../interfaces/worker\";\nimport { GET } from \"../../constants/http\";\nimport { assertCacheName, assertGetKey, assertKey } from \"../../guards/cache\";\nimport { filterVaryHeader, getVaryHeader, getVaryKey, isCacheable } from \"./utils\";\nimport { sortSearchParams } from \"../../utils/request\";\n\n/**\n * Creates a Vary-aware caching middleware for Workers.\n *\n * This middleware:\n * - Caches **GET requests** only.\n * - Respects the `Vary` header of responses, ensuring that requests\n * with different headers (e.g., `Origin`) receive the correct cached response.\n * - Skips caching for non-cacheable responses (e.g., error responses or\n * responses with `Vary: *`).\n *\n * @param cacheName Optional name of the cache to use. If omitted, the default cache is used.\n * @param getKey Optional function to compute a custom cache key from a request.\n * If omitted, the request URL is normalized and used as the key.\n * @returns A `Middleware` instance that can be used in a Worker pipeline.\n */\nexport function cache(cacheName?: string, getKey?: (request: Request) => URL): Middleware {\n assertCacheName(cacheName);\n assertGetKey(getKey);\n\n return new CacheHandler(cacheName, getKey);\n}\n\n/**\n * Cache Middleware Implementation\n * @see {@link cache}\n */\nclass CacheHandler extends Middleware {\n constructor(\n private readonly cacheName?: string,\n private readonly getKey?: (request: Request) => URL,\n ) {\n super();\n this.cacheName = cacheName?.trim() || undefined;\n }\n\n /**\n * Handles an incoming request.\n * - Bypasses caching for non-GET requests.\n * - Checks the cache for a stored response.\n * - Calls next if no cached response exists.\n * - Caches the response if it is cacheable.\n *\n * @param worker The Worker instance containing the request and context.\n * @param next Function to call the next middleware or origin fetch.\n * @returns A cached or freshly fetched Response.\n */\n public override async handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {\n if (worker.request.method !== GET) {\n return next();\n }\n\n const cache = this.cacheName ? await caches.open(this.cacheName) : caches.default;\n const cached = await this.getCached(cache, worker.request);\n if (cached) return cached;\n\n const response = await next();\n\n this.setCached(cache, worker, response);\n return response;\n }\n\n /**\n * Retrieves a cached response for a given request.\n * - Checks both the base cache key and any Vary-specific keys.\n *\n * @param cache The Cache object to check.\n * @param request The request to retrieve a cached response for.\n * @returns A cached Response if available, otherwise `undefined`.\n */\n public async getCached(cache: Cache, request: Request): Promise<Response | undefined> {\n const url = this.getCacheKey(request);\n const response = await cache.match(url);\n if (!response) return;\n\n const vary = this.getFilteredVary(response);\n if (vary.length === 0) return response;\n\n const key = getVaryKey(request, vary, url);\n return cache.match(key);\n }\n\n /**\n * Caches a response if it is cacheable.\n *\n * Behavior:\n * - Always stores the response under the main cache key. This ensures that\n * the response’s Vary headers are available for later cache lookups.\n * - If the response varies based on certain request headers (per the Vary header),\n * also stores a copy under a Vary-specific cache key so future requests\n * with matching headers can retrieve the correct response.\n *\n * @param cache The Cache object to store the response in.\n * @param worker The Worker instance containing the request and context.\n * @param response The Response to cache.\n */\n public async setCached(cache: Cache, worker: Worker, response: Response): Promise<void> {\n if (!isCacheable(response)) return;\n\n const url = this.getCacheKey(worker.request);\n\n // Always store the main cache entry to preserve Vary headers\n worker.ctx.waitUntil(cache.put(url, response.clone()));\n\n // Store request-specific cache entry if the response varies\n const vary = this.getFilteredVary(response);\n if (vary.length > 0) {\n worker.ctx.waitUntil(\n cache.put(getVaryKey(worker.request, vary, url), response.clone()),\n );\n }\n }\n\n /**\n * Extracts and filters the `Vary` header from a response.\n *\n * @param response - The HTTP response to inspect.\n * @returns An array of filtered header names from the `Vary` header.\n */\n public getFilteredVary(response: Response): string[] {\n return filterVaryHeader(getVaryHeader(response));\n }\n\n /**\n * Returns the cache key for a request.\n *\n * By default, this is a normalized URL including the path and query string.\n * However, users can provide a custom `getKey` function when creating the\n * `cache` middleware to fully control how the cache keys are generated.\n *\n * For example, a custom function could:\n * - Sort or remove query parameters\n * - Exclude the search/query string entirely\n * - Modify the path or host\n *\n * This allows complete flexibility over cache key generation.\n *\n * @param request The Request object to generate a cache key for.\n * @returns A URL representing the main cache key for this request.\n */\n public getCacheKey(request: Request): URL {\n const key = this.getKey ? this.getKey(request) : sortSearchParams(request);\n assertKey(key);\n\n key.hash = \"\";\n return key;\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getReasonPhrase, StatusCodes } from \"http-status-codes\";\nimport { CacheControl } from \"./constants/cache\";\nimport { setHeader, mergeHeader } from \"./utils/header\";\nimport { getContentType } from \"./utils/response\";\nimport { MediaType } from \"./constants/media-types\";\nimport { HttpHeader } from \"./constants/http\";\n\n/**\n * Base class for building HTTP responses.\n * Manages headers, status, and media type.\n */\nabstract class BaseResponse {\n /** HTTP headers for the response. */\n public headers: Headers = new Headers();\n\n /** HTTP status code (default 200 OK). */\n public status: StatusCodes = StatusCodes.OK;\n\n /** Optional status text. Defaults to standard reason phrase. */\n public statusText?: string;\n\n /** Default media type of the response body. */\n public mediaType: MediaType = MediaType.PLAIN_TEXT;\n\n /** Converts current state to ResponseInit for constructing a Response. */\n protected get responseInit(): ResponseInit {\n return {\n headers: this.headers,\n status: this.status,\n statusText: this.statusText ?? getReasonPhrase(this.status),\n };\n }\n\n /** Sets a header, overwriting any existing value. */\n public setHeader(key: string, value: string | string[]): void {\n setHeader(this.headers, key, value);\n }\n\n /** Merges a header with existing values (does not overwrite). */\n public mergeHeader(key: string, value: string | string[]): void {\n mergeHeader(this.headers, key, value);\n }\n\n /** Adds a Content-Type header if not already existing (does not overwrite). */\n public addContentType() {\n if (!this.headers.get(HttpHeader.CONTENT_TYPE)) {\n this.headers.set(HttpHeader.CONTENT_TYPE, getContentType(this.mediaType));\n }\n }\n}\n\n/**\n * Base response class that adds caching headers.\n */\nabstract class CacheResponse extends BaseResponse {\n constructor(public cache?: CacheControl) {\n super();\n }\n\n /** Adds Cache-Control header if caching is configured. */\n protected addCacheHeader(): void {\n if (this.cache) {\n this.headers.set(HttpHeader.CACHE_CONTROL, CacheControl.stringify(this.cache));\n }\n }\n}\n\n/**\n * Core worker response. Combines caching, and security headers.\n */\nexport abstract class WorkerResponse extends CacheResponse {\n constructor(\n private readonly body: BodyInit | null = null,\n cache?: CacheControl,\n ) {\n super(cache);\n }\n\n /** Builds the Response object with body, headers, and status. */\n public async getResponse(): Promise<Response> {\n this.addCacheHeader();\n\n const body = this.status === StatusCodes.NO_CONTENT ? null : this.body;\n\n if (body) this.addContentType();\n return new Response(body, this.responseInit);\n }\n}\n\n/**\n * Wraps an existing Response and clones its body, headers, and status.\n */\nexport class ClonedResponse extends WorkerResponse {\n constructor(response: Response, cache?: CacheControl) {\n const clone = response.clone();\n super(clone.body, cache);\n this.headers = new Headers(clone.headers);\n this.status = clone.status;\n this.statusText = clone.statusText;\n }\n}\n\n/**\n * Represents a successful response with customizable body, cache and status.\n */\nexport class SuccessResponse extends WorkerResponse {\n constructor(\n body: BodyInit | null = null,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n ) {\n super(body, cache);\n this.status = status;\n }\n}\n\n/**\n * JSON response. Automatically sets Content-Type to application/json.\n */\nexport class JsonResponse extends SuccessResponse {\n constructor(json: unknown = {}, cache?: CacheControl, status: StatusCodes = StatusCodes.OK) {\n super(JSON.stringify(json), cache, status);\n this.mediaType = MediaType.JSON;\n }\n}\n\n/**\n * HTML response. Automatically sets Content-Type to text/html.\n */\nexport class HtmlResponse extends SuccessResponse {\n constructor(body: string, cache?: CacheControl, status: StatusCodes = StatusCodes.OK) {\n super(body, cache, status);\n this.mediaType = MediaType.HTML;\n }\n}\n\n/**\n * Plain text response. Automatically sets Content-Type to text/plain.\n */\nexport class TextResponse extends SuccessResponse {\n constructor(content: string, cache?: CacheControl, status: StatusCodes = StatusCodes.OK) {\n super(content, cache, status);\n this.mediaType = MediaType.PLAIN_TEXT;\n }\n}\n\n/**\n * Response for HEAD requests. Copy headers and status from a GET response\n * without the body.\n */\nexport class Head extends WorkerResponse {\n constructor(get: Response) {\n super();\n this.status = get.status;\n this.statusText = get.statusText;\n this.headers = new Headers(get.headers);\n }\n}\n\n/**\n * Response for OPTIONS preflight requests.\n */\nexport class Options extends SuccessResponse {\n constructor() {\n super(null, undefined, StatusCodes.NO_CONTENT);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader } from \"../../constants/http\";\nimport { Time } from \"../../constants/time\";\nimport { CorsConfig } from \"../../interfaces/cors-config\";\n\nexport const ALLOW_ALL_ORIGINS = \"*\";\n\n/**\n * Default configuration for CORS middleware.\n */\nexport const defaultCorsConfig: CorsConfig = {\n allowedOrigins: [ALLOW_ALL_ORIGINS],\n allowedHeaders: [HttpHeader.CONTENT_TYPE],\n exposedHeaders: [],\n allowCredentials: false,\n maxAge: 5 * Time.Minute,\n} as const;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader, Method, GET, HEAD, OPTIONS } from \"../../constants/http\";\nimport { assertMethods } from \"../../guards/methods\";\nimport { CorsConfig } from \"../../interfaces/cors-config\";\nimport { Worker } from \"../../interfaces/worker\";\nimport { ClonedResponse, Options } from \"../../responses\";\nimport { mergeHeader, setHeader } from \"../../utils/header\";\nimport { getOrigin } from \"../../utils/request\";\nimport { ALLOW_ALL_ORIGINS } from \"./constants\";\n\n/**\n * Set of HTTP methods considered \"simple\" under the CORS specification.\n *\n * Simple methods do not trigger a preflight request:\n * - GET\n * - HEAD\n * - OPTIONS\n */\nconst SIMPLE_METHODS = new Set<Method>([GET, HEAD, OPTIONS]);\n\n/**\n * Handles a CORS preflight OPTIONS request.\n *\n * Sets the appropriate CORS headers based on the provided configuration\n * and the origin of the request.\n *\n * @param worker - The Worker handling the request.\n * @param cors - The CORS configuration.\n * @returns A Response object for the preflight request.\n */\nexport async function options(worker: Worker, cors: CorsConfig): Promise<Response> {\n const options = new Options();\n const origin = getOrigin(worker.request);\n\n if (origin) {\n setAllowOrigin(options.headers, cors, origin);\n setAllowCredentials(options.headers, cors, origin);\n }\n\n setAllowMethods(options.headers, worker);\n setMaxAge(options.headers, cors);\n setAllowHeaders(options.headers, cors);\n\n return options.getResponse();\n}\n\n/**\n * Applies CORS headers to an existing response.\n *\n * Useful for normal (non-preflight) responses where the response\n * should include CORS headers based on the request origin.\n *\n * @param response - The original Response object.\n * @param worker - The Worker handling the request.\n * @param cors - The CORS configuration.\n * @returns A new Response object with CORS headers applied.\n */\nexport async function apply(\n response: Response,\n worker: Worker,\n cors: CorsConfig,\n): Promise<Response> {\n const clone = new ClonedResponse(response);\n const origin = getOrigin(worker.request);\n\n deleteCorsHeaders(clone.headers);\n\n if (origin) {\n setAllowOrigin(clone.headers, cors, origin);\n setAllowCredentials(clone.headers, cors, origin);\n }\n\n setExposedHeaders(clone.headers, cors);\n\n return clone.getResponse();\n}\n\n/**\n * Sets the Access-Control-Allow-Origin header based on the CORS config\n * and request origin.\n *\n * @param headers - The headers object to modify.\n * @param cors - The CORS configuration.\n * @param origin - The request's origin, or null if not present.\n */\nexport function setAllowOrigin(headers: Headers, cors: CorsConfig, origin: string): void {\n if (allowAllOrigins(cors)) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN, ALLOW_ALL_ORIGINS);\n } else {\n if (cors.allowedOrigins.includes(origin)) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN, origin);\n }\n mergeHeader(headers, HttpHeader.VARY, HttpHeader.ORIGIN);\n }\n}\n\n/**\n * Conditionally sets the `Access-Control-Allow-Credentials` header\n * for a CORS response.\n *\n * This header is only set if:\n * 1. `cors.allowCredentials` is true,\n * 2. The configuration does **not** allow any origin (`*`), and\n * 3. The provided `origin` is explicitly listed in `cors.allowedOrigins`.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The CORS configuration.\n * @param origin - The origin of the incoming request.\n */\nexport function setAllowCredentials(headers: Headers, cors: CorsConfig, origin: string): void {\n if (!cors.allowCredentials) return;\n if (allowAllOrigins(cors)) return;\n if (!cors.allowedOrigins.includes(origin)) return;\n\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS, \"true\");\n}\n\n/**\n * Sets the `Access-Control-Allow-Methods` header for a CORS response,\n * but only for non-simple methods.\n *\n * Simple methods (GET, HEAD, OPTIONS) are automatically allowed by the\n * CORS spec, so this function only adds methods beyond those.\n *\n * @param headers - The Headers object to modify.\n * @param worker - The Worker instance used to retrieve allowed methods.\n */\nexport function setAllowMethods(headers: Headers, worker: Worker): void {\n const methods = worker.getAllowedMethods();\n assertMethods(methods);\n\n const allowed = methods.filter((method) => !SIMPLE_METHODS.has(method));\n\n if (allowed.length > 0) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_METHODS, allowed);\n }\n}\n\n/**\n * Sets the `Access-Control-Max-Age` header for a CORS response.\n *\n * This header indicates how long the results of a preflight request\n * can be cached by the client (in seconds).\n *\n * The value is **clamped to a non-negative integer** to comply with\n * the CORS specification:\n * - Decimal values are floored to the nearest integer.\n * - Negative values are treated as `0`.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The CORS configuration containing the `maxAge` value in seconds.\n */\nexport function setMaxAge(headers: Headers, cors: CorsConfig): void {\n const maxAge = Math.max(0, Math.floor(cors.maxAge));\n setHeader(headers, HttpHeader.ACCESS_CONTROL_MAX_AGE, String(maxAge));\n}\n\n/**\n * Sets the Access-Control-Allow-Headers header based on the CORS configuration.\n *\n * Only the headers explicitly listed in `cors.allowedHeaders` are sent.\n * If the array is empty, no Access-Control-Allow-Headers header is added.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The CORS configuration.\n */\nexport function setAllowHeaders(headers: Headers, cors: CorsConfig): void {\n if (cors.allowedHeaders.length > 0) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS, cors.allowedHeaders);\n }\n}\n\n/**\n * Sets the Access-Control-Expose-Headers header for a response.\n *\n * @param headers - The headers object to modify.\n * @param cors - The CORS configuration.\n */\nexport function setExposedHeaders(headers: Headers, cors: CorsConfig): void {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_EXPOSE_HEADERS, cors.exposedHeaders);\n}\n\n/**\n * Returns true if the CORS config allows all origins ('*').\n *\n * @param cors - The CORS configuration.\n */\nexport function allowAllOrigins(cors: CorsConfig): boolean {\n return cors.allowedOrigins.includes(ALLOW_ALL_ORIGINS);\n}\n\n/**\n * Deletes any existing CORS headers from the provided headers object.\n *\n * @param headers - The headers object to modify.\n */\nexport function deleteCorsHeaders(headers: Headers): void {\n headers.delete(HttpHeader.ACCESS_CONTROL_MAX_AGE);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_METHODS);\n headers.delete(HttpHeader.ACCESS_CONTROL_EXPOSE_HEADERS);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS);\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CorsInit } from \"../interfaces/cors-config\";\nimport { isBoolean, isNumber, isStringArray } from \"./basic\";\n\n/**\n * Throws if the given value is not a valid CorsInit.\n *\n * Checks only the fields that are present, since CorsInit is Partial<CorsConfig>.\n *\n * @param value - The value to check.\n */\nexport function assertCorsInit(value: unknown): asserts value is CorsInit {\n if (value === undefined) return;\n\n if (typeof value !== \"object\" || value === null) {\n throw new TypeError(\"CorsInit must be an object.\");\n }\n\n const obj = value as Record<string, unknown>;\n\n if (obj[\"allowedOrigins\"] !== undefined && !isStringArray(obj[\"allowedOrigins\"])) {\n throw new TypeError(\"CorsInit.allowedOrigins must be a string array.\");\n }\n\n if (obj[\"allowedHeaders\"] !== undefined && !isStringArray(obj[\"allowedHeaders\"])) {\n throw new TypeError(\"CorsInit.allowedHeaders must be a string array.\");\n }\n\n if (obj[\"exposedHeaders\"] !== undefined && !isStringArray(obj[\"exposedHeaders\"])) {\n throw new TypeError(\"CorsInit.exposedHeaders must be a string array.\");\n }\n\n if (obj[\"allowCredentials\"] !== undefined && !isBoolean(obj[\"allowCredentials\"])) {\n throw new TypeError(\"CorsInit.allowCredentials must be a boolean.\");\n }\n\n if (obj[\"maxAge\"] !== undefined && !isNumber(obj[\"maxAge\"])) {\n throw new TypeError(\"CorsInit.maxAge must be a number.\");\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { apply, options } from \"./utils\";\nimport { Worker } from \"../../interfaces/worker\";\nimport { Middleware } from \"../middleware\";\nimport { CorsConfig, CorsInit } from \"../../interfaces/cors-config\";\nimport { defaultCorsConfig } from \"./constants\";\nimport { OPTIONS } from \"../../constants/http\";\nimport { assertCorsInit } from \"../../guards/cors\";\n\n/**\n * Creates a CORS middleware instance.\n *\n * This middleware automatically handles Cross-Origin Resource Sharing (CORS)\n * for incoming requests, including preflight OPTIONS requests, and adds\n * appropriate headers to responses.\n *\n * @param init - Optional configuration for CORS behavior. See {@link CorsConfig}.\n * @returns A {@link Middleware} instance that can be used in your middleware chain.\n */\nexport function cors(init?: CorsInit): Middleware {\n assertCorsInit(init);\n return new CorsHandler(init);\n}\n\n/**\n * Cors Middleware Implementation\n * @see {@link cors}\n */\nclass CorsHandler extends Middleware {\n /** The configuration used for this instance, with all defaults applied. */\n private readonly config: CorsConfig;\n\n /**\n * Create a new CORS middleware instance.\n *\n * @param init - Partial configuration to override the defaults. Any values\n * not provided will use `defaultCorsConfig`.\n */\n constructor(init?: CorsInit) {\n super();\n this.config = { ...defaultCorsConfig, ...init };\n }\n\n /**\n * Applies CORS headers to a request.\n *\n * - Returns a preflight response for `OPTIONS` requests.\n * - For other methods, calls `next()` and applies CORS headers to the result.\n *\n * @param worker - The Worker handling the request.\n * @param next - Function to invoke the next middleware.\n * @returns Response with CORS headers applied.\n */\n public override async handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {\n if (worker.request.method === OPTIONS) {\n return options(worker, this.config);\n }\n\n const response = await next();\n\n return apply(response, worker, this.config);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getReasonPhrase, StatusCodes } from \"http-status-codes\";\nimport { JsonResponse } from \"./responses\";\nimport { ErrorJson } from \"./interfaces/error-json\";\nimport { Worker } from \"./interfaces/worker\";\nimport { CacheControl } from \"./constants/cache\";\nimport { HttpHeader } from \"./constants/http\";\nimport { assertMethods } from \"./guards\";\n\n/**\n * Generic HTTP error response.\n * Sends a JSON body with status, error message, and details.\n */\nexport class HttpError extends JsonResponse {\n /**\n * @param worker The worker handling the request.\n * @param status HTTP status code.\n * @param details Optional detailed error message.\n */\n constructor(\n status: StatusCodes,\n protected readonly details?: string,\n ) {\n const json: ErrorJson = {\n status,\n error: getReasonPhrase(status),\n details: details ?? \"\",\n };\n super(json, CacheControl.DISABLE, status);\n }\n}\n\n/** 400 Bad Request error response. */\nexport class BadRequest extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.BAD_REQUEST, details);\n }\n}\n\n/** 401 Unauthorized error response. */\nexport class Unauthorized extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.UNAUTHORIZED, details);\n }\n}\n\n/** 403 Forbidden error response. */\nexport class Forbidden extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.FORBIDDEN, details);\n }\n}\n\n/** 404 Not Found error response. */\nexport class NotFound extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.NOT_FOUND, details);\n }\n}\n\n/** 405 Method Not Allowed error response. */\nexport class MethodNotAllowed extends HttpError {\n constructor(worker: Worker) {\n const methods = worker.getAllowedMethods();\n assertMethods(methods);\n\n super(StatusCodes.METHOD_NOT_ALLOWED, `${worker.request.method} method not allowed.`);\n this.setHeader(HttpHeader.ALLOW, methods);\n }\n}\n\n/** 500 Internal Server Error response. */\nexport class InternalServerError extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.INTERNAL_SERVER_ERROR, details);\n }\n}\n\n/** 501 Not Implemented error response. */\nexport class NotImplemented extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.NOT_IMPLEMENTED, details);\n }\n}\n\n/** 501 Method Not Implemented error response for unsupported HTTP methods. */\nexport class MethodNotImplemented extends NotImplemented {\n constructor(worker: Worker) {\n super(`${worker.request.method} method not implemented.`);\n }\n}\n\n/** 503 Service Unavailable error response. */\nexport class ServiceUnavailable extends HttpError {\n constructor(details?: string) {\n super(StatusCodes.SERVICE_UNAVAILABLE, details);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Method } from \"../constants/http\";\nimport { FetchHandler } from \"../interfaces/fetch-handler\";\nimport { Worker, WorkerClass } from \"../interfaces/worker\";\n\n/**\n * Provides the foundational structure for handling requests,\n * environment bindings, and the worker execution context.\n *\n * Features:\n * - Holds the current `Request` object (`request` getter).\n * - Provides access to environment bindings (`env` getter).\n * - Provides access to the worker execution context (`ctx` getter).\n * - Subclasses must implement `fetch()` to process the request.\n */\nexport abstract class BaseWorker implements Worker {\n constructor(\n private readonly _request: Request,\n private readonly _env: Env,\n private readonly _ctx: ExecutionContext,\n ) {}\n\n /** The Request object associated with this worker invocation */\n public get request(): Request {\n return this._request;\n }\n\n /** Environment bindings (e.g., KV, secrets, or other globals) */\n public get env(): Env {\n return this._env;\n }\n\n /** Execution context for background tasks or `waitUntil` */\n public get ctx(): ExecutionContext {\n return this._ctx;\n }\n\n /**\n * Dispatches the incoming request to the appropriate handler and produces a response.\n *\n * Subclasses must implement this method to define how the worker generates a `Response`\n * for the current request. This is the central point where request processing occurs.\n *\n * @returns A Promise that resolves to the `Response` for the request.\n */\n protected abstract dispatch(): Promise<Response>;\n\n public abstract getAllowedMethods(): Method[];\n\n /**\n * Creates a new instance of the current Worker subclass.\n *\n * @param request - The {@link Request} to pass to the new worker instance.\n * @returns A new worker instance of the same subclass as `this`.\n */\n protected create(request: Request): this {\n const ctor = this.constructor as WorkerClass<this>;\n return new ctor(request, this.env, this.ctx);\n }\n\n /**\n * Process the {@link Request} and produce a {@link Response}.\n *\n * @returns A {@link Response} promise for the {@link Request}.\n */\n public abstract fetch(): Promise<Response>;\n\n /**\n * **Ignite** your `Worker` implementation into a Cloudflare handler.\n *\n * @returns A `FetchHandler` that launches a new worker instance for each request.\n *\n * ```ts\n * export default MyWorker.ignite();\n * ```\n */\n public static ignite<W extends Worker>(this: WorkerClass<W>): FetchHandler {\n return {\n fetch: (request: Request, env: Env, ctx: ExecutionContext) =>\n new this(request, env, ctx).fetch(),\n };\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Middleware } from \"../middleware/middleware\";\n\n/**\n * Asserts at runtime that a value is a Middleware instance.\n *\n * @param handler - The value to check.\n * @throws TypeError If `handler` is not a `Middleware` subclass instance.\n */\nexport function assertMiddleware(handler: unknown): asserts handler is Middleware {\n if (!(handler instanceof Middleware)) {\n throw new TypeError(\"Handler must be a subclass of Middleware.\");\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseWorker } from \"./base-worker\";\nimport { Middleware } from \"../middleware/middleware\";\nimport { assertMiddleware } from \"../guards/middleware\";\n\n/** Internal base worker for handling middleware chains. */\nexport abstract class MiddlewareWorker extends BaseWorker {\n /** Middleware handlers registered for this worker. */\n protected readonly middlewares: Middleware[] = [];\n\n /**\n * Add a middleware instance to this worker.\n *\n * The middleware will run for every request handled by this worker,\n * in the order they are added.\n *\n * @param handler - The middleware to run.\n * @returns `this` to allow chaining multiple `.use()` calls.\n */\n public use(handler: Middleware): this {\n assertMiddleware(handler);\n\n this.middlewares.push(handler);\n return this;\n }\n\n /**\n * Executes the middleware chain and dispatches the request.\n *\n * @returns The Response produced by the last middleware or `dispatch()`.\n */\n public override async fetch(): Promise<Response> {\n const chain = this.middlewares.reduceRight(\n (next, handler) => () => handler.handle(this, next),\n () => this.dispatch(),\n );\n return await chain();\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MethodNotAllowed, InternalServerError, MethodNotImplemented } from \"../errors\";\nimport { MiddlewareWorker } from \"./middleware-worker\";\nimport { Head, WorkerResponse } from \"../responses\";\nimport { Method, GET, HEAD, OPTIONS } from \"../constants/http\";\nimport { assertMethods, isMethod } from \"../guards/methods\";\n\n/**\n * Basic worker class providing HTTP method dispatching and error handling.\n */\nexport abstract class BasicWorker extends MiddlewareWorker {\n /**\n * Entry point to handle a fetch request.\n */\n public override async fetch(): Promise<Response> {\n if (!this.isAllowed(this.request.method)) {\n return this.getResponse(MethodNotAllowed, this);\n }\n\n try {\n await this.init();\n return await super.fetch();\n } catch (error) {\n console.error(error);\n return this.getResponse(InternalServerError);\n }\n }\n\n /**\n * Dispatches the request to the method-specific handler.\n */\n protected override async dispatch(): Promise<Response> {\n const method = this.request.method as Method;\n const handler: Record<Method, () => Promise<Response>> = {\n GET: () => this.get(),\n PUT: () => this.put(),\n HEAD: () => this.head(),\n POST: () => this.post(),\n PATCH: () => this.patch(),\n DELETE: () => this.delete(),\n OPTIONS: () => this.options(),\n };\n\n return (handler[method] ?? (() => this.getResponse(MethodNotAllowed, this)))();\n }\n\n /**\n * Hook for subclasses to perform any initialization.\n */\n protected init(): void | Promise<void> {\n return;\n }\n\n /**\n * Checks if the given HTTP method is allowed for this worker.\n * @param method HTTP method string\n * @returns true if the method is allowed\n */\n public isAllowed(method: string): boolean {\n const methods = this.getAllowedMethods();\n assertMethods(methods);\n\n return isMethod(method) && methods.includes(method);\n }\n\n /** Override and implement this method for GET requests. */\n protected async get(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /** Override and implement this method for PUT requests. */\n protected async put(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /** Override and implement this method for POST requests. */\n protected async post(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /** Override and implement this method for PATCH requests. */\n protected async patch(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /** Override and implement this method for DELETE requests. */\n protected async delete(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /** Override and implement this method for OPTIONS requests. */\n protected async options(): Promise<Response> {\n return this.getResponse(MethodNotImplemented, this);\n }\n\n /**\n * Default handler for HEAD requests.\n * Performs a GET request and removes the body for HEAD semantics.\n *\n * Usually does not need to be overridden as this behavior covers\n * standard HEAD requirements.\n */\n protected async head(): Promise<Response> {\n const worker = this.create(new Request(this.request, { method: GET }));\n return this.getResponse(Head, await worker.fetch());\n }\n\n /**\n * DEFAULT allowed HTTP methods for subclasses.\n *\n * These defaults were selected for getting started quickly and should be\n * overridden for each specific worker.\n */\n public getAllowedMethods(): Method[] {\n return [GET, HEAD, OPTIONS];\n }\n\n /**\n * Simplify and standardize {@link Response} creation by extending {@link WorkerResponse}\n * or any of its subclasses and passing to this method.\n *\n * Or directly use any of the built-in classes.\n *\n * ```ts\n * this.getResponse(TextResponse, \"Hello World!\")\n * ```\n *\n * @param ResponseClass The response class to instantiate\n * @param args Additional constructor arguments\n * @returns A Promise resolving to the {@link Response} object\n */\n protected async getResponse<\n Ctor extends new (...args: any[]) => { getResponse(): Promise<Response> },\n >(ResponseClass: Ctor, ...args: ConstructorParameters<Ctor>): Promise<Response> {\n return new ResponseClass(...args).getResponse();\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { match } from \"path-to-regexp\";\nimport { MatchedRoute, Route, PathParams, RouteTable } from \"./interfaces/route\";\nimport { Method } from \"./constants/http\";\n\n/**\n * Container for route definitions and matching logic.\n * Implements Iterable to allow iteration over all routes.\n */\nexport class Routes implements Iterable<Route> {\n /** Internal array of registered routes */\n private readonly routes: Route[] = [];\n\n /**\n * Add routes to the router.\n *\n * Accepts any iterable of [method, path, handler] tuples.\n * This includes arrays, Sets, or generators.\n *\n * @param routes - Iterable of route tuples to add.\n */\n public add(routes: RouteTable): void {\n for (const [method, path, handler] of routes) {\n const matcher = match<PathParams>(path);\n this.routes.push({ method, matcher, handler });\n }\n }\n\n /**\n * Attempt to match a URL against the registered routes.\n *\n * @param method - HTTP method of the request\n * @param url - Full URL string to match against\n * @returns A MatchedRoute object if a route matches, otherwise null\n */\n public match(method: Method, url: string): MatchedRoute | null {\n const pathname = new URL(url).pathname;\n\n for (const route of this) {\n if (route.method !== method) continue;\n\n const found = route.matcher(pathname);\n if (found) return { route, params: found.params };\n }\n\n return null;\n }\n\n /**\n * Iterate over all registered routes.\n */\n public *[Symbol.iterator](): Iterator<Route> {\n yield* this.routes;\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BasicWorker } from \"./basic-worker\";\nimport { NotFound } from \"../errors\";\nimport { Routes } from \"../routes\";\nimport { RouteHandler, RouteTable } from \"../interfaces/route\";\nimport { WorkerClass } from \"../interfaces/worker\";\nimport { BaseWorker } from \"./base-worker\";\nimport { Method } from \"../constants/http\";\n\n/**\n * Base worker supporting route-based request handling.\n *\n * Subclass `RouteWorker` to define a worker with multiple route handlers.\n *\n * Routes can be registered individually via `route()` or in bulk via `routes()`.\n */\nexport abstract class RouteWorker extends BasicWorker {\n /** Internal table of registered routes. */\n private readonly _routes: Routes = new Routes();\n\n /**\n * Registers a single new route in the worker.\n *\n * When a request matches the specified method and path, the provided handler\n * will be executed. The handler can be either:\n * - A function that receives URL parameters, or\n * - A Worker subclass that will handle the request.\n *\n * @param method - HTTP method for the route (GET, POST, etc.).\n * @param path - URL path pattern (Express-style, e.g., \"/users/:id\").\n * @param handler - The function or Worker class to run when the route matches.\n * @returns The current worker instance, allowing method chaining.\n */\n protected route(method: Method, path: string, handler: RouteHandler): this {\n this.routes([[method, path, handler]]);\n return this;\n }\n\n /**\n * Registers multiple routes at once in the worker.\n *\n * Each route should be a tuple `[method, path, handler]` where:\n * - `method` - HTTP method for the route (GET, POST, etc.).\n * - `path` - URL path pattern (Express-style, e.g., \"/users/:id\").\n * - `handler` - A function that receives URL parameters or a Worker subclass\n * that will handle the request.\n *\n * @param routes - An iterable of routes to register. Each item is a `[method, path, handler]` tuple.\n * @returns The current worker instance, allowing method chaining.\n */\n protected routes(routes: RouteTable): this {\n this._routes.add(routes);\n return this;\n }\n\n /**\n * Matches the incoming request against registered routes and dispatches it.\n *\n * If a route is found:\n * - If the handler is a Worker class, a new instance is created and its `fetch()` is called.\n * - If the handler is a callback function, it is invoked with the extracted path parameters.\n *\n * If no route matches, the request is passed to the parent `dispatch()` handler.\n *\n * @returns A `Promise<Response>` from the matched handler or parent dispatch.\n */\n protected override async dispatch(): Promise<Response> {\n const found = this._routes.match(this.request.method as Method, this.request.url);\n if (!found) return super.dispatch();\n\n const { handler } = found.route;\n if (RouteWorker.isWorkerClass(handler)) {\n return new handler(this.request, this.env, this.ctx).fetch();\n }\n return handler.call(this, found.params);\n }\n\n /**\n * Runtime type guard to check if a given handler is a Worker class.\n *\n * A Worker class is any class that extends `BaseWorker`.\n *\n * @param handler - The constructor function to test.\n * @returns `true` if `handler` is a subclass of `BaseWorker` at runtime, `false` otherwise.\n */\n private static isWorkerClass(handler: RouteHandler): handler is WorkerClass {\n return BaseWorker.prototype.isPrototypeOf(handler.prototype);\n }\n\n protected override async get(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n\n protected override async put(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n\n protected override async post(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n\n protected override async patch(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n\n protected override async delete(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n\n protected override async options(): Promise<Response> {\n return this.getResponse(NotFound);\n }\n}\n"],"mappings":";AAgBA,OAAO,cAAc;AAMd,IAAM,eAAe;AAAA,EACxB,OAAO,SAAS;AAAA,EAChB,WAAW,SAAS;AAAA;AAAA,EAGpB,SAAS,OAAO,OAAO;AAAA,IACnB,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,mBAAmB;AAAA,IACnB,WAAW;AAAA,EACf,CAAC;AACL;;;ACdA,SAAS,mBAAmB;AAKrB,IAAU;AAAA,CAAV,CAAUA,gBAAV;AACI,EAAMA,YAAA,QAAQ;AACd,EAAMA,YAAA,kBAAkB;AACxB,EAAMA,YAAA,SAAS;AACf,EAAMA,YAAA,eAAe;AACrB,EAAMA,YAAA,gBAAgB;AACtB,EAAMA,YAAA,aAAa;AACnB,EAAMA,YAAA,OAAO;AA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