@adonix.org/cloud-spark 0.0.141 → 0.0.143

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/dist/index.js CHANGED
@@ -1,10 +1,9 @@
1
- // src/common.ts
1
+ // src/constants/cache.ts
2
2
  import CacheLib from "cache-control-parser";
3
- import { StatusCodes } from "http-status-codes";
4
3
  var CacheControl = {
5
4
  parse: CacheLib.parse,
6
5
  stringify: CacheLib.stringify,
7
- /** A Cache-Control directive that disables all caching. */
6
+ /** A CacheControl directive that disables all caching. */
8
7
  DISABLE: Object.freeze({
9
8
  "no-cache": true,
10
9
  "no-store": true,
@@ -12,14 +11,17 @@ var CacheControl = {
12
11
  "max-age": 0
13
12
  })
14
13
  };
14
+
15
+ // src/constants/http.ts
16
+ import { StatusCodes } from "http-status-codes";
15
17
  var HttpHeader;
16
18
  ((HttpHeader2) => {
17
19
  HttpHeader2.VARY = "Vary";
18
20
  HttpHeader2.ALLOW = "Allow";
21
+ HttpHeader2.ORIGIN = "Origin";
19
22
  HttpHeader2.USER_AGENT = "User-Agent";
20
23
  HttpHeader2.CONTENT_TYPE = "Content-Type";
21
24
  HttpHeader2.CACHE_CONTROL = "Cache-Control";
22
- HttpHeader2.SEC_FETCH_SITE = "Sec-Fetch-Site";
23
25
  HttpHeader2.X_FRAME_OPTIONS = "X-Frame-Options";
24
26
  HttpHeader2.X_CONTENT_TYPE_OPTIONS = "X-Content-Type-Options";
25
27
  HttpHeader2.REFERRER_POLICY = "Referrer-Policy";
@@ -32,45 +34,22 @@ var HttpHeader;
32
34
  HttpHeader2.ALLOW_METHODS = "Access-Control-Allow-Methods";
33
35
  HttpHeader2.EXPOSE_HEADERS = "Access-Control-Expose-Headers";
34
36
  HttpHeader2.ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
35
- HttpHeader2.ORIGIN = "Origin";
36
37
  HttpHeader2.ALLOW_ALL_ORIGINS = "*";
37
38
  HttpHeader2.CROSS_SITE = "cross-site";
38
39
  })(HttpHeader || (HttpHeader = {}));
39
- var Time = {
40
- Second: 1,
41
- Minute: 60,
42
- Hour: 3600,
43
- // 60 * 60
44
- Day: 86400,
45
- // 60 * 60 * 24
46
- Week: 604800,
47
- // 60 * 60 * 24 * 7
48
- Month: 2592e3,
49
- // 60 * 60 * 24 * 30
50
- Year: 31536e3
51
- // 60 * 60 * 24 * 365
52
- };
53
- var Method = /* @__PURE__ */ ((Method4) => {
54
- Method4["GET"] = "GET";
55
- Method4["PUT"] = "PUT";
56
- Method4["HEAD"] = "HEAD";
57
- Method4["POST"] = "POST";
58
- Method4["PATCH"] = "PATCH";
59
- Method4["DELETE"] = "DELETE";
60
- Method4["OPTIONS"] = "OPTIONS";
61
- return Method4;
40
+ var Method = /* @__PURE__ */ ((Method3) => {
41
+ Method3["GET"] = "GET";
42
+ Method3["PUT"] = "PUT";
43
+ Method3["HEAD"] = "HEAD";
44
+ Method3["POST"] = "POST";
45
+ Method3["PATCH"] = "PATCH";
46
+ Method3["DELETE"] = "DELETE";
47
+ Method3["OPTIONS"] = "OPTIONS";
48
+ return Method3;
62
49
  })(Method || {});
63
50
  var { GET, PUT, HEAD, POST, PATCH, DELETE, OPTIONS } = Method;
64
- var METHOD_SET = new Set(Object.values(Method));
65
- function isMethod(value) {
66
- return METHOD_SET.has(value);
67
- }
68
- function getContentType(type) {
69
- if (ADD_CHARSET.has(type)) {
70
- return `${type}; charset=utf-8`;
71
- }
72
- return type;
73
- }
51
+
52
+ // src/constants/media-types.ts
74
53
  var MediaType = /* @__PURE__ */ ((MediaType2) => {
75
54
  MediaType2["PLAIN_TEXT"] = "text/plain";
76
55
  MediaType2["HTML"] = "text/html";
@@ -117,20 +96,98 @@ var MediaType = /* @__PURE__ */ ((MediaType2) => {
117
96
  MediaType2["BZIP2"] = "application/x-bzip2";
118
97
  return MediaType2;
119
98
  })(MediaType || {});
120
- var ADD_CHARSET = /* @__PURE__ */ new Set([
121
- "text/css" /* CSS */,
122
- "text/csv" /* CSV */,
123
- "text/xml" /* XML */,
124
- "image/svg+xml" /* SVG */,
125
- "text/html" /* HTML */,
126
- "application/json" /* JSON */,
127
- "application/x-ndjson" /* NDJSON */,
128
- "application/xml" /* XML_APP */,
129
- "text/markdown" /* MARKDOWN */,
130
- "text/richtext" /* RICH_TEXT */,
131
- "text/plain" /* PLAIN_TEXT */,
132
- "application/x-www-form-urlencoded" /* FORM_URLENCODED */
133
- ]);
99
+
100
+ // src/constants/time.ts
101
+ var Time = {
102
+ Second: 1,
103
+ Minute: 60,
104
+ Hour: 3600,
105
+ // 60 * 60
106
+ Day: 86400,
107
+ // 60 * 60 * 24
108
+ Week: 604800,
109
+ // 60 * 60 * 24 * 7
110
+ Month: 2592e3,
111
+ // 60 * 60 * 24 * 30
112
+ Year: 31536e3
113
+ // 60 * 60 * 24 * 365
114
+ };
115
+
116
+ // src/middleware/middleware.ts
117
+ var Middleware = class {
118
+ };
119
+
120
+ // src/utils/compare.ts
121
+ function lexCompare(a, b) {
122
+ if (a < b) return -1;
123
+ if (a > b) return 1;
124
+ return 0;
125
+ }
126
+
127
+ // src/utils/url.ts
128
+ function normalizeUrl(url) {
129
+ const u = new URL(url);
130
+ const params = [...u.searchParams.entries()];
131
+ params.sort(([a], [b]) => lexCompare(a, b));
132
+ u.search = params.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
133
+ u.hash = "";
134
+ return u;
135
+ }
136
+
137
+ // src/middleware/cache/handler.ts
138
+ function cache(cacheName, getKey) {
139
+ return new CacheHandler(cacheName, getKey);
140
+ }
141
+ var CacheHandler = class extends Middleware {
142
+ /**
143
+ * @param cacheName - Optional name of the cache to use. If omitted,
144
+ * `caches.default` is used.
145
+ * @param getKey - Optional function to generate a cache key from a request.
146
+ * Defaults to using the normalized request URL.
147
+ */
148
+ constructor(cacheName, getKey) {
149
+ super();
150
+ this.cacheName = cacheName;
151
+ this.getKey = getKey;
152
+ }
153
+ /**
154
+ * Handle a request in the caching middleware.
155
+ *
156
+ * Checks the cache for GET requests and returns the cached response if available.
157
+ * Otherwise, calls `next()` to continue the middleware chain and caches
158
+ * the response if successful.
159
+ *
160
+ * @param worker - The Worker instance containing the request context.
161
+ * @param next - Function to invoke the next middleware in the chain.
162
+ * @returns A Response object, either from cache or the next middleware.
163
+ */
164
+ async handle(worker, next) {
165
+ const cache2 = this.cacheName ? await caches.open(this.cacheName) : caches.default;
166
+ if (worker.request.method === GET) {
167
+ const cached = await cache2.match(this.getCacheKey(worker.request));
168
+ if (cached) return cached;
169
+ }
170
+ const response = await next();
171
+ if (worker.request.method === GET && response.ok) {
172
+ worker.ctx.waitUntil(cache2.put(this.getCacheKey(worker.request), response.clone()));
173
+ }
174
+ return response;
175
+ }
176
+ /**
177
+ * Generate the cache key for a request.
178
+ *
179
+ * @param request - The Request object to generate a cache key for.
180
+ * @returns A URL or RequestInfo used as the cache key.
181
+ *
182
+ * If a custom `getKey` function was provided in the constructor, it is used.
183
+ * Otherwise, the request URL is normalized.
184
+ */
185
+ getCacheKey(request) {
186
+ return this.getKey ? this.getKey(request) : normalizeUrl(request.url);
187
+ }
188
+ };
189
+
190
+ // src/utils/header.ts
134
191
  function setHeader(headers, key, value) {
135
192
  const raw = Array.isArray(value) ? value : [value];
136
193
  const values = Array.from(new Set(raw.map((v) => v.trim()))).filter((v) => v.length).sort(lexCompare);
@@ -152,32 +209,88 @@ function mergeHeader(headers, key, value) {
152
209
  setHeader(headers, key, values);
153
210
  }
154
211
  }
155
- function normalizeUrl(url) {
156
- const u = new URL(url);
157
- const params = [...u.searchParams.entries()];
158
- params.sort(([a], [b]) => lexCompare(a, b));
159
- u.search = params.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
160
- u.hash = "";
161
- return u;
212
+
213
+ // src/utils/request.ts
214
+ var METHOD_SET = new Set(Object.values(Method));
215
+ function isMethod(value) {
216
+ return METHOD_SET.has(value);
162
217
  }
163
- function lexCompare(a, b) {
164
- if (a < b) return -1;
165
- if (a > b) return 1;
166
- return 0;
218
+ var ADD_CHARSET = /* @__PURE__ */ new Set([
219
+ "text/css" /* CSS */,
220
+ "text/csv" /* CSV */,
221
+ "text/xml" /* XML */,
222
+ "image/svg+xml" /* SVG */,
223
+ "text/html" /* HTML */,
224
+ "application/json" /* JSON */,
225
+ "application/x-ndjson" /* NDJSON */,
226
+ "application/xml" /* XML_APP */,
227
+ "text/markdown" /* MARKDOWN */,
228
+ "text/richtext" /* RICH_TEXT */,
229
+ "text/plain" /* PLAIN_TEXT */,
230
+ "application/x-www-form-urlencoded" /* FORM_URLENCODED */
231
+ ]);
232
+ function getContentType(type) {
233
+ if (ADD_CHARSET.has(type)) {
234
+ return `${type}; charset=utf-8`;
235
+ }
236
+ return type;
167
237
  }
168
238
  function getOrigin(request) {
169
- const origin = request.headers.get(HttpHeader.ORIGIN);
170
- return origin ? origin.trim() : null;
239
+ const origin = request.headers.get(HttpHeader.ORIGIN)?.trim();
240
+ if (!origin || origin === "null") return null;
241
+ try {
242
+ return new URL(origin).origin;
243
+ } catch {
244
+ return null;
245
+ }
171
246
  }
172
247
 
173
- // src/errors.ts
174
- import { getReasonPhrase as getReasonPhrase2 } from "http-status-codes";
248
+ // src/middleware/cors/utils.ts
249
+ function addCorsHeaders(worker, cors2, headers) {
250
+ deleteCorsHeaders(headers);
251
+ const origin = getOrigin(worker.request);
252
+ if (!origin) return;
253
+ if (allowAnyOrigin(cors2)) {
254
+ setHeader(headers, HttpHeader.ALLOW_ORIGIN, HttpHeader.ALLOW_ALL_ORIGINS);
255
+ } else if (cors2.allowedOrigins.length > 0) {
256
+ mergeHeader(headers, HttpHeader.VARY, HttpHeader.ORIGIN);
257
+ if (cors2.allowedOrigins.includes(origin)) {
258
+ setHeader(headers, HttpHeader.ALLOW_ORIGIN, origin);
259
+ setHeader(headers, HttpHeader.ALLOW_CREDENTIALS, "true");
260
+ }
261
+ }
262
+ setHeader(headers, HttpHeader.MAX_AGE, String(cors2.maxAge));
263
+ setHeader(headers, HttpHeader.ALLOW_HEADERS, cors2.allowedHeaders);
264
+ mergeHeader(headers, HttpHeader.ALLOW_METHODS, worker.getAllowedMethods());
265
+ mergeHeader(headers, HttpHeader.EXPOSE_HEADERS, cors2.exposedHeaders);
266
+ }
267
+ function allowAnyOrigin(cors2) {
268
+ return cors2.allowedOrigins.includes("*");
269
+ }
270
+ function deleteCorsHeaders(headers) {
271
+ headers.delete(HttpHeader.MAX_AGE);
272
+ headers.delete(HttpHeader.ALLOW_ORIGIN);
273
+ headers.delete(HttpHeader.ALLOW_HEADERS);
274
+ headers.delete(HttpHeader.ALLOW_METHODS);
275
+ headers.delete(HttpHeader.EXPOSE_HEADERS);
276
+ headers.delete(HttpHeader.ALLOW_CREDENTIALS);
277
+ }
278
+
279
+ // src/middleware/cors/constants.ts
280
+ var defaultCorsConfig = {
281
+ allowedOrigins: ["*"],
282
+ // Origins allowed for CORS requests
283
+ allowedHeaders: [HttpHeader.CONTENT_TYPE],
284
+ // HTTP headers allowed in requests
285
+ exposedHeaders: [],
286
+ // Headers exposed to the client
287
+ maxAge: Time.Week
288
+ // Max age in seconds for preflight caching
289
+ };
175
290
 
176
291
  // src/responses.ts
177
292
  import { getReasonPhrase, StatusCodes as StatusCodes2 } from "http-status-codes";
178
293
  var BaseResponse = class {
179
- constructor() {
180
- }
181
294
  /** HTTP headers for the response. */
182
295
  headers = new Headers();
183
296
  /** HTTP status code (default 200 OK). */
@@ -222,9 +335,8 @@ var CacheResponse = class extends BaseResponse {
222
335
  }
223
336
  };
224
337
  var WorkerResponse = class extends CacheResponse {
225
- constructor(worker, body = null, cache2) {
338
+ constructor(body = null, cache2) {
226
339
  super(cache2);
227
- this.worker = worker;
228
340
  this.body = body;
229
341
  }
230
342
  /** Builds the Response object with body, headers, and status. */
@@ -236,252 +348,151 @@ var WorkerResponse = class extends CacheResponse {
236
348
  }
237
349
  };
238
350
  var ClonedResponse = class extends WorkerResponse {
239
- constructor(worker, response, cache2) {
351
+ constructor(response, cache2) {
240
352
  const clone = response.clone();
241
- super(worker, clone.body, cache2);
353
+ super(clone.body, cache2);
242
354
  this.headers = new Headers(clone.headers);
243
355
  this.status = clone.status;
244
356
  this.statusText = clone.statusText;
245
357
  }
246
358
  };
247
359
  var SuccessResponse = class extends WorkerResponse {
248
- constructor(worker, body = null, cache2, status = StatusCodes2.OK) {
249
- super(worker, body, cache2);
360
+ constructor(body = null, cache2, status = StatusCodes2.OK) {
361
+ super(body, cache2);
250
362
  this.status = status;
251
363
  }
252
364
  };
253
365
  var JsonResponse = class extends SuccessResponse {
254
- constructor(worker, json = {}, cache2, status = StatusCodes2.OK) {
255
- super(worker, JSON.stringify(json), cache2, status);
366
+ constructor(json = {}, cache2, status = StatusCodes2.OK) {
367
+ super(JSON.stringify(json), cache2, status);
256
368
  this.mediaType = "application/json" /* JSON */;
257
369
  }
258
370
  };
259
371
  var HtmlResponse = class extends SuccessResponse {
260
- constructor(worker, body, cache2, status = StatusCodes2.OK) {
261
- super(worker, body, cache2, status);
372
+ constructor(body, cache2, status = StatusCodes2.OK) {
373
+ super(body, cache2, status);
262
374
  this.mediaType = "text/html" /* HTML */;
263
375
  }
264
376
  };
265
377
  var TextResponse = class extends SuccessResponse {
266
- constructor(worker, content, cache2, status = StatusCodes2.OK) {
267
- super(worker, content, cache2, status);
378
+ constructor(content, cache2, status = StatusCodes2.OK) {
379
+ super(content, cache2, status);
268
380
  this.mediaType = "text/plain" /* PLAIN_TEXT */;
269
381
  }
270
382
  };
271
383
  var Head = class extends WorkerResponse {
272
- constructor(worker, get) {
273
- super(worker);
384
+ constructor(get) {
385
+ super();
386
+ this.status = get.status;
387
+ this.statusText = get.statusText;
274
388
  this.headers = new Headers(get.headers);
275
389
  }
276
390
  };
277
391
  var Options = class extends SuccessResponse {
278
- constructor(worker) {
279
- super(worker, null, void 0, StatusCodes2.NO_CONTENT);
392
+ constructor() {
393
+ super(null, void 0, StatusCodes2.NO_CONTENT);
394
+ }
395
+ };
396
+
397
+ // src/middleware/cors/handler.ts
398
+ function cors(init) {
399
+ return new CorsHandler(init);
400
+ }
401
+ var CorsHandler = class extends Middleware {
402
+ /** The configuration used for this instance, with all defaults applied. */
403
+ config;
404
+ /**
405
+ * Create a new CORS middleware instance.
406
+ *
407
+ * @param init - Partial configuration to override the defaults. Any values
408
+ * not provided will use `defaultCorsConfig`.
409
+ */
410
+ constructor(init) {
411
+ super();
412
+ this.config = { ...defaultCorsConfig, ...init };
413
+ }
414
+ /**
415
+ * Handle a request by applying CORS headers to the response.
416
+ *
417
+ * @param worker - The Worker instance containing the request context.
418
+ * @param next - Function to invoke the next middleware in the chain.
419
+ * @returns A Response object with CORS headers applied.
420
+ */
421
+ async handle(worker, next) {
422
+ if (worker.request.method === OPTIONS) {
423
+ const options = new Options();
424
+ addCorsHeaders(worker, this.config, options.headers);
425
+ return options.getResponse();
426
+ }
427
+ const response = await next();
428
+ const clone = new ClonedResponse(response);
429
+ addCorsHeaders(worker, this.config, clone.headers);
430
+ return clone.getResponse();
280
431
  }
281
432
  };
282
433
 
283
434
  // src/errors.ts
435
+ import { getReasonPhrase as getReasonPhrase2, StatusCodes as StatusCodes3 } from "http-status-codes";
284
436
  var HttpError = class extends JsonResponse {
285
437
  /**
286
438
  * @param worker The worker handling the request.
287
439
  * @param status HTTP status code.
288
440
  * @param details Optional detailed error message.
289
441
  */
290
- constructor(worker, status, details) {
442
+ constructor(status, details) {
291
443
  const json = {
292
444
  status,
293
445
  error: getReasonPhrase2(status),
294
446
  details: details ?? ""
295
447
  };
296
- super(worker, json, CacheControl.DISABLE, status);
448
+ super(json, CacheControl.DISABLE, status);
297
449
  this.details = details;
298
450
  }
299
451
  };
300
452
  var BadRequest = class extends HttpError {
301
- constructor(worker, details) {
302
- super(worker, StatusCodes.BAD_REQUEST, details);
453
+ constructor(details) {
454
+ super(StatusCodes3.BAD_REQUEST, details);
303
455
  }
304
456
  };
305
457
  var Unauthorized = class extends HttpError {
306
- constructor(worker, details) {
307
- super(worker, StatusCodes.UNAUTHORIZED, details);
458
+ constructor(details) {
459
+ super(StatusCodes3.UNAUTHORIZED, details);
308
460
  }
309
461
  };
310
462
  var Forbidden = class extends HttpError {
311
- constructor(worker, details) {
312
- super(worker, StatusCodes.FORBIDDEN, details);
463
+ constructor(details) {
464
+ super(StatusCodes3.FORBIDDEN, details);
313
465
  }
314
466
  };
315
467
  var NotFound = class extends HttpError {
316
- constructor(worker, details) {
317
- super(worker, StatusCodes.NOT_FOUND, details);
468
+ constructor(details) {
469
+ super(StatusCodes3.NOT_FOUND, details);
318
470
  }
319
471
  };
320
472
  var MethodNotAllowed = class extends HttpError {
321
473
  constructor(worker) {
322
- super(
323
- worker,
324
- StatusCodes.METHOD_NOT_ALLOWED,
325
- `${worker.request.method} method not allowed.`
326
- );
327
- this.setHeader(HttpHeader.ALLOW, this.worker.getAllowedMethods());
474
+ super(StatusCodes3.METHOD_NOT_ALLOWED, `${worker.request.method} method not allowed.`);
475
+ this.setHeader(HttpHeader.ALLOW, worker.getAllowedMethods());
328
476
  }
329
477
  };
330
478
  var InternalServerError = class extends HttpError {
331
- constructor(worker, details) {
332
- super(worker, StatusCodes.INTERNAL_SERVER_ERROR, details);
479
+ constructor(details) {
480
+ super(StatusCodes3.INTERNAL_SERVER_ERROR, details);
333
481
  }
334
482
  };
335
483
  var NotImplemented = class extends HttpError {
336
- constructor(worker, details) {
337
- super(worker, StatusCodes.NOT_IMPLEMENTED, details);
484
+ constructor(details) {
485
+ super(StatusCodes3.NOT_IMPLEMENTED, details);
338
486
  }
339
487
  };
340
488
  var MethodNotImplemented = class extends NotImplemented {
341
489
  constructor(worker) {
342
- super(worker, `${worker.request.method} method not implemented.`);
490
+ super(`${worker.request.method} method not implemented.`);
343
491
  }
344
492
  };
345
493
  var ServiceUnavailable = class extends HttpError {
346
- constructor(worker, details) {
347
- super(worker, StatusCodes.SERVICE_UNAVAILABLE, details);
348
- }
349
- };
350
-
351
- // src/middleware/cors/utils.ts
352
- function addCorsHeaders(worker, cors2, headers) {
353
- deleteCorsHeaders(headers);
354
- const origin = getOrigin(worker.request);
355
- if (!origin) return;
356
- if (allowAnyOrigin(cors2)) {
357
- setHeader(headers, HttpHeader.ALLOW_ORIGIN, HttpHeader.ALLOW_ALL_ORIGINS);
358
- } else {
359
- mergeHeader(headers, HttpHeader.VARY, HttpHeader.ORIGIN);
360
- if (cors2.allowedOrigins.includes(origin)) {
361
- setHeader(headers, HttpHeader.ALLOW_ORIGIN, origin);
362
- setHeader(headers, HttpHeader.ALLOW_CREDENTIALS, "true");
363
- }
364
- }
365
- setHeader(headers, HttpHeader.MAX_AGE, String(cors2.maxAge));
366
- setHeader(headers, HttpHeader.ALLOW_HEADERS, cors2.allowedHeaders);
367
- mergeHeader(headers, HttpHeader.ALLOW_METHODS, worker.getAllowedMethods());
368
- mergeHeader(headers, HttpHeader.EXPOSE_HEADERS, cors2.exposedHeaders);
369
- }
370
- function allowAnyOrigin(cors2) {
371
- return cors2.allowedOrigins.includes("*");
372
- }
373
- function deleteCorsHeaders(headers) {
374
- headers.delete(HttpHeader.MAX_AGE);
375
- headers.delete(HttpHeader.ALLOW_ORIGIN);
376
- headers.delete(HttpHeader.ALLOW_HEADERS);
377
- headers.delete(HttpHeader.ALLOW_METHODS);
378
- headers.delete(HttpHeader.EXPOSE_HEADERS);
379
- headers.delete(HttpHeader.ALLOW_CREDENTIALS);
380
- }
381
-
382
- // src/middleware/middleware.ts
383
- var Middleware = class {
384
- };
385
-
386
- // src/middleware/cors/constants.ts
387
- var defaultCorsConfig = {
388
- allowedOrigins: ["*"],
389
- // Origins allowed for CORS requests
390
- allowedHeaders: ["Content-Type"],
391
- // HTTP headers allowed in requests
392
- exposedHeaders: [],
393
- // Headers exposed to the client
394
- maxAge: Time.Week
395
- // Max age in seconds for preflight caching
396
- };
397
-
398
- // src/middleware/cors/handler.ts
399
- function cors(init) {
400
- return new CorsHandler(init);
401
- }
402
- var CorsHandler = class extends Middleware {
403
- /** The configuration used for this instance, with all defaults applied. */
404
- config;
405
- /**
406
- * Create a new CORS middleware instance.
407
- *
408
- * @param init - Partial configuration to override the defaults. Any values
409
- * not provided will use `defaultCorsConfig`.
410
- */
411
- constructor(init) {
412
- super();
413
- this.config = { ...defaultCorsConfig, ...init };
414
- }
415
- /**
416
- * Handle a request by applying CORS headers to the response.
417
- *
418
- * @param worker - The Worker instance containing the request context.
419
- * @param next - Function to invoke the next middleware in the chain.
420
- * @returns A Response object with CORS headers applied.
421
- */
422
- async handle(worker, next) {
423
- if (worker.request.method === OPTIONS) {
424
- const options = new Options(worker);
425
- addCorsHeaders(worker, this.config, options.headers);
426
- return options.getResponse();
427
- }
428
- const response = await next();
429
- const clone = new ClonedResponse(worker, response);
430
- addCorsHeaders(worker, this.config, clone.headers);
431
- return clone.getResponse();
432
- }
433
- };
434
-
435
- // src/middleware/cache/handler.ts
436
- function cache(cacheName, getKey) {
437
- return new CacheHandler(cacheName, getKey);
438
- }
439
- var CacheHandler = class extends Middleware {
440
- /**
441
- * @param cacheName - Optional name of the cache to use. If omitted,
442
- * `caches.default` is used.
443
- * @param getKey - Optional function to generate a cache key from a request.
444
- * Defaults to using the normalized request URL.
445
- */
446
- constructor(cacheName, getKey) {
447
- super();
448
- this.cacheName = cacheName;
449
- this.getKey = getKey;
450
- }
451
- /**
452
- * Handle a request in the caching middleware.
453
- *
454
- * Checks the cache for GET requests and returns the cached response if available.
455
- * Otherwise, calls `next()` to continue the middleware chain and caches
456
- * the response if successful.
457
- *
458
- * @param worker - The Worker instance containing the request context.
459
- * @param next - Function to invoke the next middleware in the chain.
460
- * @returns A Response object, either from cache or the next middleware.
461
- */
462
- async handle(worker, next) {
463
- const cache2 = this.cacheName ? await caches.open(this.cacheName) : caches.default;
464
- if (worker.request.method === GET) {
465
- const cached = await cache2.match(this.getCacheKey(worker.request));
466
- if (cached) return cached;
467
- }
468
- const response = await next();
469
- if (worker.request.method === GET && response.ok) {
470
- worker.ctx.waitUntil(cache2.put(this.getCacheKey(worker.request), response.clone()));
471
- }
472
- return response;
473
- }
474
- /**
475
- * Generate the cache key for a request.
476
- *
477
- * @param request - The Request object to generate a cache key for.
478
- * @returns A URL or RequestInfo used as the cache key.
479
- *
480
- * If a custom `getKey` function was provided in the constructor, it is used.
481
- * Otherwise, the request URL is normalized.
482
- */
483
- getCacheKey(request) {
484
- return this.getKey ? this.getKey(request) : normalizeUrl(request.url);
494
+ constructor(details) {
495
+ super(StatusCodes3.SERVICE_UNAVAILABLE, details);
485
496
  }
486
497
  };
487
498
 
@@ -504,15 +515,6 @@ var BaseWorker = class {
504
515
  get ctx() {
505
516
  return this._ctx;
506
517
  }
507
- /**
508
- * DEFAULT allowed HTTP methods for subclasses.
509
- *
510
- * These defaults were selected for getting started quickly and should be
511
- * overridden for the specific worker.
512
- */
513
- getAllowedMethods() {
514
- return [GET, HEAD, OPTIONS];
515
- }
516
518
  /**
517
519
  * Creates a new instance of the current Worker subclass.
518
520
  *
@@ -577,7 +579,7 @@ var BasicWorker = class extends MiddlewareWorker {
577
579
  */
578
580
  async fetch() {
579
581
  if (!this.isAllowed(this.request.method)) {
580
- return this.getResponse(MethodNotAllowed);
582
+ return this.getResponse(MethodNotAllowed, this);
581
583
  }
582
584
  try {
583
585
  await this.init();
@@ -601,7 +603,7 @@ var BasicWorker = class extends MiddlewareWorker {
601
603
  DELETE: () => this.delete(),
602
604
  OPTIONS: () => this.options()
603
605
  };
604
- return (handler[method] ?? (() => this.getResponse(MethodNotAllowed)))();
606
+ return (handler[method] ?? (() => this.getResponse(MethodNotAllowed, this)))();
605
607
  }
606
608
  /**
607
609
  * Hook for subclasses to perform any initialization.
@@ -619,27 +621,27 @@ var BasicWorker = class extends MiddlewareWorker {
619
621
  }
620
622
  /** Override and implement this method for GET requests. */
621
623
  async get() {
622
- return this.getResponse(MethodNotImplemented);
624
+ return this.getResponse(MethodNotImplemented, this);
623
625
  }
624
626
  /** Override and implement this method for PUT requests. */
625
627
  async put() {
626
- return this.getResponse(MethodNotImplemented);
628
+ return this.getResponse(MethodNotImplemented, this);
627
629
  }
628
630
  /** Override and implement this method for POST requests. */
629
631
  async post() {
630
- return this.getResponse(MethodNotImplemented);
632
+ return this.getResponse(MethodNotImplemented, this);
631
633
  }
632
634
  /** Override and implement this method for PATCH requests. */
633
635
  async patch() {
634
- return this.getResponse(MethodNotImplemented);
636
+ return this.getResponse(MethodNotImplemented, this);
635
637
  }
636
638
  /** Override and implement this method for DELETE requests. */
637
639
  async delete() {
638
- return this.getResponse(MethodNotImplemented);
640
+ return this.getResponse(MethodNotImplemented, this);
639
641
  }
640
642
  /** Override and implement this method for OPTIONS requests. */
641
643
  async options() {
642
- return this.getResponse(MethodNotImplemented);
644
+ return this.getResponse(MethodNotImplemented, this);
643
645
  }
644
646
  /**
645
647
  * Default handler for HEAD requests.
@@ -652,6 +654,15 @@ var BasicWorker = class extends MiddlewareWorker {
652
654
  const worker = this.create(new Request(this.request, { method: GET }));
653
655
  return this.getResponse(Head, await worker.fetch());
654
656
  }
657
+ /**
658
+ * DEFAULT allowed HTTP methods for subclasses.
659
+ *
660
+ * These defaults were selected for getting started quickly and should be
661
+ * overridden for each specific worker.
662
+ */
663
+ getAllowedMethods() {
664
+ return [GET, HEAD, OPTIONS];
665
+ }
655
666
  /**
656
667
  * Simplify and standardize {@link Response} creation by extending {@link WorkerResponse}
657
668
  * or any of its subclasses and passing to this method.
@@ -667,7 +678,7 @@ var BasicWorker = class extends MiddlewareWorker {
667
678
  * @returns A Promise resolving to the {@link Response} object
668
679
  */
669
680
  async getResponse(ResponseClass, ...args) {
670
- return new ResponseClass(this, ...args).getResponse();
681
+ return new ResponseClass(...args).getResponse();
671
682
  }
672
683
  };
673
684