@adonix.org/cloud-spark 0.0.183 → 0.0.184

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 CHANGED
@@ -1,4 +1,4 @@
1
- # ⚡️Cloud Spark
1
+ # Cloud⚡️Spark
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/@adonix.org/cloud-spark.svg?color=blue)](https://www.npmjs.com/package/@adonix.org/cloud-spark)
4
4
  [![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/adonix-org/cloud-spark/blob/main/LICENSE)
@@ -9,9 +9,22 @@
9
9
 
10
10
  **_Ignite_** your Cloudflare Workers with a type-safe library for rapid development.
11
11
 
12
- If you are new to _Cloudflare Workers_, create a free [Cloudflare account](https://dash.cloudflare.com/sign-up) and install their command line interface [Wrangler](#cowboy_hat_face-wrangler). Detailed worker documentation can also be found [here](https://developers.cloudflare.com/workers/).
12
+ Get instant access to common essentials:
13
13
 
14
- Then let's get started!
14
+ - Method & Route dispatch
15
+ - CORS
16
+ - Caching
17
+ - WebSockets
18
+
19
+ And then explore:
20
+
21
+ - Custom Middleware
22
+ - Nested Workers
23
+ - Advanced Routing
24
+
25
+ :bulb: If you are new to _Cloudflare Workers_, create a free [Cloudflare account](https://dash.cloudflare.com/sign-up) and install their command line interface [Wrangler](#cowboy_hat_face-wrangler). Detailed worker documentation can also be found [here](https://developers.cloudflare.com/workers/).
26
+
27
+ <br>
15
28
 
16
29
  ## :package: Install
17
30
 
@@ -55,6 +68,73 @@ And it's ready on http://localhost:8787
55
68
 
56
69
  ## :arrow_right: Basic Worker
57
70
 
71
+ As shown in the [Quickstart](#rocket-quickstart), BasicWorker is the base class for building Cloudflare Workers with this library. It handles common tasks, including:
72
+
73
+ - Dispatching incoming HTTP requests to the corresponding handler (GET, POST, PUT, etc.).
74
+ - Catching unhandled errors and returning a structured 500 InternalServerError.
75
+ - Providing defaults for standard HTTP behavior, such as HEAD requests and OPTIONS responses.
76
+ - Ensuring type safety and consistent response formatting.
77
+
78
+ Subclasses only need to implement the HTTP methods that their Worker will handle. Each method can be overridden independently, and additional functionality such as middleware can be added as needed.
79
+
80
+ ## :hammer_and_wrench: Basic Worker API
81
+
82
+ #### `getAllowedMethods(): Method[]`
83
+
84
+ Returns the HTTP methods supported by this Worker.
85
+
86
+ - **Default:** `[GET, HEAD, OPTIONS]`
87
+ - **Notes:** Subclasses must override to allow additional methods. Any request using a method not listed will automatically return a `405 Method Not Allowed` response.
88
+
89
+ #### `get(): Promise<Response>`
90
+
91
+ Override this method to handle `GET` requests.
92
+
93
+ - **Default behavior:** Returns a `404 Not Found`.
94
+ - **Notes:** Typically used to return content or data for read requests.
95
+
96
+ #### `head(): Promise<Response>`
97
+
98
+ Handles `HEAD` requests.
99
+
100
+ - **Default behavior:** Performs a `GET` request internally and strips the body.
101
+ - **Notes:** Rarely needs to be overridden; ensures compliance with [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.3.2).
102
+
103
+ #### `post(): Promise<Response>`
104
+
105
+ Override to handle `POST` requests.
106
+
107
+ - **Default behavior:** Returns `501 Method Not Implemented`.
108
+ - **Notes:** Ideal for form submissions, JSON payloads, or resource creation.
109
+
110
+ #### `put(): Promise<Response>`
111
+
112
+ Override to handle `PUT` requests.
113
+
114
+ - **Default behavior:** Returns `501 Method Not Implemented`.
115
+ - **Notes:** Used for full resource creation or replacement.
116
+
117
+ #### `patch(): Promise<Response>`
118
+
119
+ Override to handle `PATCH` requests.
120
+
121
+ - **Default behavior:** Returns `501 Method Not Implemented`.
122
+ - **Notes:** Used for partial updates to existing resources.
123
+
124
+ #### `delete(): Promise<Response>`
125
+
126
+ Override to handle `DELETE` requests.
127
+
128
+ - **Default behavior:** Returns `501 Method Not Implemented`.
129
+ - **Notes:** Used to remove resources.
130
+
131
+ #### `options(): Promise<Response>`
132
+
133
+ Override to handle `OPTIONS` requests.
134
+
135
+ - **Default behavior:** Returns `200 OK` with the `Allow` header listing supported methods.
136
+ - **Notes:** `GET`, `HEAD`, and `OPTIONS` are included by default.
137
+
58
138
  <br>
59
139
 
60
140
  ## :twisted_rightwards_arrows: Route Worker
package/dist/index.d.ts CHANGED
@@ -688,7 +688,7 @@ declare abstract class BaseWorker implements Worker {
688
688
  /**
689
689
  * Determines whether a given HTTP method is allowed for this worker.
690
690
  *
691
- * - GET and HEAD are **always allowed**, in compliance with RFC 7231,
691
+ * - GET and HEAD are **always allowed**, in compliance with RFC 9110,
692
692
  * even if they are not explicitly listed in `getAllowedMethods()`.
693
693
  * - Other methods are allowed only if included in the array returned by
694
694
  * `getAllowedMethods()` and are valid HTTP methods.
@@ -802,7 +802,7 @@ declare abstract class BasicWorker extends MiddlewareWorker {
802
802
  /**
803
803
  * Returns the HTTP methods allowed by this worker.
804
804
  *
805
- * - GET and HEAD are always allowed per RFC 7231, even if subclasses do not include them here.
805
+ * - GET and HEAD are always allowed per RFC 9110, even if subclasses do not include them here.
806
806
  * - OPTIONS is included by default since a default handler is implemented.
807
807
  * - Subclasses can override this method to allow additional methods or change the defaults.
808
808
  */
@@ -828,7 +828,7 @@ declare abstract class RouteWorker extends BasicWorker {
828
828
  * - A Worker subclass that will handle the request.
829
829
  *
830
830
  * @param method - HTTP method for the route (`GET`, `POST`, etc.).
831
- * @param path - URL path pattern (Express-style, e.g., "/users/:id").
831
+ * @param path - URL path pattern (path-to-regex, e.g., "/users/:id").
832
832
  * @param handler - The function or Worker class to run when the route matches.
833
833
  * @returns The current worker instance, allowing method chaining.
834
834
  */
@@ -838,7 +838,7 @@ declare abstract class RouteWorker extends BasicWorker {
838
838
  *
839
839
  * Each route should be a tuple `[method, path, handler]` where:
840
840
  * - `method` - HTTP method for the route (`GET`, `POST`, etc.).
841
- * - `path` - URL path pattern (Express-style, e.g., "/users/:id").
841
+ * - `path` - URL path pattern (path-to-regex e.g., "/users/:id").
842
842
  * - `handler` - A function that receives URL parameters or a Worker subclass
843
843
  * that will handle the request.
844
844
  *
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{StatusCodes as h}from"http-status-codes";import Ie from"cache-control-parser";var R={parse:Ie.parse,stringify:Ie.stringify,DISABLE:Object.freeze({"no-cache":!0,"no-store":!0,"must-revalidate":!0,"max-age":0})};var F=(c=>(c.GET="GET",c.PUT="PUT",c.HEAD="HEAD",c.POST="POST",c.PATCH="PATCH",c.DELETE="DELETE",c.OPTIONS="OPTIONS",c))(F||{}),{GET:p,PUT:tr,HEAD:O,POST:rr,PATCH:sr,DELETE:or,OPTIONS:B}=F;var He={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};function z(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function C(t){return typeof t=="string"}function E(t){return typeof t=="number"&&!Number.isNaN(t)}function Le(t){return typeof t=="boolean"}function ve(t){if(typeof t!="object"||t===null)throw new TypeError("CacheInit must be an object.");let{name:e,getKey:r}=t;yt(e),_t(r)}function yt(t){if(t!==void 0&&!C(t))throw new TypeError("Cache name must be a string.")}function _t(t){if(t!==void 0&&typeof t!="function")throw new TypeError("getKey must be a function.")}function We(t){if(!(t instanceof URL))throw new TypeError("getKey must return a URL.")}function x(t,e){return t<e?-1:t>e?1:0}function Pe(t){let e=new URL(t.url),r=new URLSearchParams([...e.searchParams.entries()].sort(([s],[o])=>x(s,o)));return e.search=r.toString(),e.hash="",e}function Er(t){let e=new URL(t.url);return e.search="",e.hash="",e}var j=class{rules=[];use(...e){return this.rules.push(...e),this}async execute(e,r){return this.rules.reduceRight((o,i)=>()=>i.apply(e,o),()=>r())()}};import{StatusCodes as It}from"http-status-codes";var n={ACCEPT:"accept",ACCEPT_ENCODING:"accept-encoding",ACCEPT_LANGUAGE:"accept-language",ACCEPT_RANGES:"accept-ranges",ALLOW:"allow",AUTHORIZATION:"authorization",CACHE_CONTROL:"cache-control",CONNECTION:"connection",CONTENT_DISPOSITION:"content-disposition",CONTENT_ENCODING:"content-encoding",CONTENT_LANGUAGE:"content-language",CONTENT_LENGTH:"content-length",CONTENT_RANGE:"content-range",CONTENT_TYPE:"content-type",CONTENT_MD5:"content-md5",COOKIE:"cookie",ETAG:"etag",IF_MATCH:"if-match",IF_MODIFIED_SINCE:"if-modified-since",IF_NONE_MATCH:"if-none-match",IF_UNMODIFIED_SINCE:"if-unmodified-since",LAST_MODIFIED:"last-modified",ORIGIN:"origin",RANGE:"range",SET_COOKIE:"set-cookie",VARY:"vary",ACCESS_CONTROL_ALLOW_CREDENTIALS:"access-control-allow-credentials",ACCESS_CONTROL_ALLOW_HEADERS:"access-control-allow-headers",ACCESS_CONTROL_ALLOW_METHODS:"access-control-allow-methods",ACCESS_CONTROL_ALLOW_ORIGIN:"access-control-allow-origin",ACCESS_CONTROL_EXPOSE_HEADERS:"access-control-expose-headers",ACCESS_CONTROL_MAX_AGE:"access-control-max-age",SEC_WEBSOCKET_VERSION:"sec-websocket-version",UPGRADE:"upgrade",INTERNAL_VARIANT_SET:"internal-variant-set"},ke=[n.CONTENT_TYPE,n.CONTENT_LENGTH,n.CONTENT_RANGE,n.CONTENT_ENCODING,n.CONTENT_LANGUAGE,n.CONTENT_DISPOSITION,n.CONTENT_MD5],Me=[n.CONTENT_LENGTH,n.CONTENT_RANGE];function f(t,e,r){let s=Array.isArray(r)?r:[r],o=Array.from(new Set(s.map(i=>i.trim()))).filter(i=>i.length).sort(x);if(!o.length){t.delete(e);return}t.set(e,o.join(", "))}function $(t,e,r){let s=Array.isArray(r)?r:[r];if(s.length===0)return;let i=d(t,e).concat(s.map(a=>a.trim()));f(t,e,i)}function d(t,e){let r=t.get(e)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(r)).sort(x)}function Ae(t,e){for(let r of e)t.delete(r)}var Ht="https://vary",Lt="*";function De(t,e){if(e.status!==It.OK||t.method!==p||t.headers.has(n.AUTHORIZATION)||t.headers.has(n.COOKIE)||y(t.headers)["no-store"]||!e.headers.has(n.CACHE_CONTROL))return!1;let s=y(e.headers),o=s["s-maxage"]??s["max-age"];if(o===void 0||o===0||s["no-store"]||s["no-cache"]||s.private||e.headers.has(n.SET_COOKIE)||Te(e).includes(Lt))return!1;if(e.headers.has(n.INTERNAL_VARIANT_SET))throw new Error("Found conflicting vary header.");if(e.headers.has(n.CONTENT_RANGE))throw new Error("Found content-range header on 200 OK. Must use 206 Partial Content");return!0}function y(t){return R.parse(t.get(n.CACHE_CONTROL)??"")}function Te(t){return _(d(t.headers,n.VARY))}function _(t){let e=t.map(r=>r.toLowerCase()).filter(r=>r!==n.ACCEPT_ENCODING).sort(x);return Array.from(new Set(e))}function I(t,e,r){let s=[],o=_(e);for(let a of o){let c=t.headers.get(a);c!==null&&s.push([a,vt(a,c)])}let i=Wt(JSON.stringify([r.toString(),s]));return new URL(i,Ht).toString()}function vt(t,e){switch(t.toLowerCase()){case n.ACCEPT:case n.ACCEPT_LANGUAGE:case n.ORIGIN:return e.toLowerCase();default:return e}}function Wt(t){let e=new TextEncoder().encode(t),r="";for(let s of e)r+=String.fromCodePoint(s);return btoa(r).replaceAll("+","-").replaceAll("/","_").replace(/={1,2}$/,"")}var Pt=/^bytes=(\d{1,12})-(\d{0,12})$/,Ge="W/",Ve="*";function Ue(t){let e=t.headers.get(n.RANGE);if(!e)return;let r=Pt.exec(e);if(!r)return;let s=Number(r[1]),o=r[2]===""?void 0:Number(r[2]);return o===void 0?{start:s}:{start:s,end:o}}function Ke(t,e){return t.length>0&&!Fe(t,e,Ve)}function qe(t,e){return Fe(t,Be(e),Ve)}function Fe(t,...e){return t.some(r=>e.includes(r))}function X(t){if(!C(t))return;let e=Date.parse(t);return Number.isNaN(e)?void 0:e}function Be(t){return t.startsWith(Ge)?t.slice(2):t}function Oe(t){return{ifMatch:d(t,n.IF_MATCH).filter(e=>!e.startsWith(Ge)),ifNoneMatch:d(t,n.IF_NONE_MATCH).map(Be),ifModifiedSince:t.get(n.IF_MODIFIED_SINCE),ifUnmodifiedSince:t.get(n.IF_UNMODIFIED_SINCE)}}function ze(t){let{ifNoneMatch:e,ifMatch:r,ifModifiedSince:s,ifUnmodifiedSince:o}=Oe(t);return e.length>0||r.length>0||s!==null||o!==null}function je(t){let e=t.get(n.CONTENT_LENGTH);if(e===null||e.trim()==="")return;let r=Number(e);if(E(r))return r}var Y=class{async apply(e,r){let s=y(e.request.headers);if(!s["no-store"]&&!((s["no-cache"]||s["max-age"]===0)&&!ze(e.request.headers)))return r()}};import{getReasonPhrase as Gt,StatusCodes as g}from"http-status-codes";var kt=new Set(Object.values(F));function be(t){return C(t)&&kt.has(t)}function Mt(t){return Array.isArray(t)&&t.every(be)}function b(t){if(!Mt(t)){let e=Array.isArray(t)?JSON.stringify(t):String(t);throw new TypeError(`Invalid method array: ${e}`)}}var $e="upgrade",Xe="websocket";import{getReasonPhrase as Dt,StatusCodes as u}from"http-status-codes";var D="utf-8";function Ye(t){if(typeof t!="object"||t===null)throw new TypeError("OctetStreamInit must be an object.");let e=t,r=e.size;if(!E(r)||r<0||!Number.isInteger(r))throw new RangeError(`OctetStreamInit.size must be a non-negative integer (size=${JSON.stringify(r)}).`);let s=e.offset??0;if(!E(s)||s<0||s>r||!Number.isInteger(s))throw new RangeError(`OctetStreamInit.offset must be a non-negative integer less than or equal to size (size=${JSON.stringify(r)}, offset=${JSON.stringify(s)}).`);let o=e.length??r-s;if(!E(o)||o<0||s+o>r||!Number.isInteger(o))throw new RangeError(`OctetStreamInit.length must be a non-negative integer less than or equal to size - offset (size=${JSON.stringify(r)}, offset=${JSON.stringify(s)}, length=${JSON.stringify(o)}).`)}function G(t,e){return!e||t.toLowerCase().includes("charset=")?t:`${t}; charset=${e.toLowerCase()}`}var xe=class{headers=new Headers;status=u.OK;statusText;webSocket;mediaType=G("text/plain",D);get responseInit(){return{headers:this.headers,status:this.status,statusText:this.statusText??Dt(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(e,r){f(this.headers,e,r)}mergeHeader(e,r){$(this.headers,e,r)}addContentType(){this.headers.get(n.CONTENT_TYPE)||this.setHeader(n.CONTENT_TYPE,this.mediaType)}filterHeaders(){this.status===u.NO_CONTENT?Ae(this.headers,Me):this.status===u.NOT_MODIFIED&&Ae(this.headers,ke)}},Ne=class extends xe{constructor(r){super();this.cache=r}addCacheHeader(){this.cache&&this.setHeader(n.CACHE_CONTROL,R.stringify(this.cache))}},m=class extends Ne{constructor(r=null,s){super(s);this.body=r}async response(){this.addCacheHeader();let r=[u.NO_CONTENT,u.NOT_MODIFIED].includes(this.status)?null:this.body;return r&&this.addContentType(),this.filterHeaders(),new Response(r,this.responseInit)}},V=class extends m{constructor(e,r){super(e.body,r),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},H=class extends m{constructor(e){super(),this.status=u.NOT_MODIFIED,this.headers=new Headers(e.headers)}},U=class extends m{constructor(e=null,r,s=u.OK){super(e,r),this.status=s}},J=class extends U{constructor(e={},r,s=u.OK){super(JSON.stringify(e),r,s),this.mediaType=G("application/json",D)}},Je=class extends U{constructor(e,r,s=u.OK,o=D){super(e,r,s),this.mediaType=G("text/html",o)}},Ze=class extends U{constructor(e,r,s=u.OK,o=D){super(e,r,s),this.mediaType=G("text/plain",o)}},we=class t extends m{constructor(e,r,s){Ye(r),super(e,s),this.mediaType="application/octet-stream";let o=t.normalizeInit(r),{size:i,offset:a,length:c}=o;t.isPartial(o)&&(this.setHeader(n.CONTENT_RANGE,`bytes ${a}-${a+c-1}/${i}`),this.status=u.PARTIAL_CONTENT),this.setHeader(n.ACCEPT_RANGES,"bytes"),this.setHeader(n.CONTENT_LENGTH,`${c}`)}static normalizeInit(e){let{size:r}=e,s=e.offset??0,o=e.length??r-s;return s===0&&o===0&&r>0&&(o=1),{size:r,offset:s,length:o}}static isPartial(e){return e.size===0?!1:!(e.offset===0&&e.length===e.size)}},Qe=class t extends we{constructor(e,r){let s=r;!s&&e.httpMetadata?.cacheControl&&(s=R.parse(e.httpMetadata.cacheControl)),super(e.body,t.computeRange(e.size,e.range),s),this.setHeader(n.ETAG,e.httpEtag),e.httpMetadata?.contentType&&(this.mediaType=e.httpMetadata.contentType)}static computeRange(e,r){if(!r)return{size:e};if("suffix"in r){let s=Math.max(0,e-r.suffix),o=e-s;return{size:e,offset:s,length:o}}return{size:e,...r}}},et=class extends m{constructor(e){super(),this.status=u.SWITCHING_PROTOCOLS,this.webSocket=e}},L=class extends m{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},Z=class extends m{constructor(e){let r=Array.from(new Set([p,O,...e.getAllowedMethods()]));b(r),super(),this.status=u.NO_CONTENT,this.setHeader(n.ALLOW,r)}};var l=class extends J{constructor(r,s){let o={status:r,error:Gt(r),details:s??""};super(o,R.DISABLE,r);this.details=s}},K=class extends l{constructor(e){super(g.BAD_REQUEST,e)}},tt=class extends l{constructor(e){super(g.UNAUTHORIZED,e)}},rt=class extends l{constructor(e){super(g.FORBIDDEN,e)}},A=class extends l{constructor(e){super(g.NOT_FOUND,e)}},v=class extends l{constructor(e){let r=e.getAllowedMethods();b(r),super(g.METHOD_NOT_ALLOWED,`${e.request.method} method not allowed.`),this.setHeader(n.ALLOW,r)}},W=class extends l{constructor(e){super(g.PRECONDITION_FAILED,e)}},Q=class extends l{constructor(){super(g.UPGRADE_REQUIRED),this.setHeader(n.SEC_WEBSOCKET_VERSION,"13")}},ee=class extends l{constructor(e){super(g.INTERNAL_SERVER_ERROR,e)}},ye=class extends l{constructor(e){super(g.NOT_IMPLEMENTED,e)}},N=class extends ye{constructor(e){super(`${e.request.method} method not implemented.`)}},st=class extends l{constructor(e){super(g.SERVICE_UNAVAILABLE,e)}};import{StatusCodes as Vt}from"http-status-codes";var P=class{async apply(e,r){let s=await r();if(!s||s.status!==Vt.OK)return s;let o=this.getHeader(s);if(o===void 0)return s;let i=Oe(e.request.headers);return this.response(s,o,i)}};var te=class extends P{getHeader(e){return e.headers.get(n.ETAG)??void 0}},re=class extends te{async response(e,r,s){return Ke(s.ifMatch,r)?new W(`ETag: ${r}`).response():e}},se=class extends te{async response(e,r,s){if(s.ifNoneMatch.length===0)return e;if(qe(s.ifNoneMatch,r))return new H(e).response()}};var oe=class{async apply(e,r){if(e.request.method===p)return r();if(e.request.method===O){let s=await r();return s?new L(s).response():void 0}}};var ne=class extends P{getHeader(e){return X(e.headers.get(n.LAST_MODIFIED))}},ie=class extends ne{async response(e,r,s){let o=X(s.ifModifiedSince);if(o===void 0)return e;if(r<=o)return new H(e).response()}},ae=class extends ne{async response(e,r,s){let o=X(s.ifUnmodifiedSince);return o===void 0?e:r>o?new W(`Last-Modified: ${new Date(r).toUTCString()}`).response():e}};import{StatusCodes as Ut}from"http-status-codes";var ce=class{async apply(e,r){let s=Ue(e.request);if(s&&(s.start!==0||s.end===0))return;let o=await r();if(!o||o.status!==Ut.OK||!s||s.end===void 0)return o;let i=je(o.headers);if(i&&s.end===i-1)return o}};var pe=class{async apply(e,r){let s=e.request.headers;if(!s.has(n.AUTHORIZATION)&&!s.has(n.COOKIE))return r()}};var ue=class{async apply(e,r){if(!e.request.headers.has(n.UPGRADE))return r()}};var T=class t extends m{_isModified=!1;constructor(e){let r=_(e);if(r.length===0)throw new Error("The filtered vary array is empty.");super(),this.setHeader(n.INTERNAL_VARIANT_SET,r)}static new(e){return new t(_(e))}static restore(e){if(!t.isVariantResponse(e))throw new Error("The source response is not a variant response");let r=t.new(d(e.headers,n.INTERNAL_VARIANT_SET)),s=e.headers.get(n.CACHE_CONTROL);return s&&(r.cache=R.parse(s)),r}get vary(){return d(this.headers,n.INTERNAL_VARIANT_SET)}get isModified(){return this._isModified}append(e){let r=this.vary.length;this.mergeHeader(n.INTERNAL_VARIANT_SET,_(e)),this._isModified=this.vary.length!==r}static isVariantResponse(e){return e.headers.has(n.INTERNAL_VARIANT_SET)}expireAfter(e){let r=y(e.headers),s=r["s-maxage"]??r["max-age"];if(s===void 0)return;let o=this.cache?.["s-maxage"];(o===void 0||s>o)&&(this.cache={"s-maxage":s},this._isModified=!0)}};var de=class{init;constructor(e){let{name:r,getKey:s=Pe}=e;this.init={name:r?.trim()||void 0,getKey:s}}async handle(e,r){let s=this.init.name?await caches.open(this.init.name):caches.default,i=await new j().use(new Y).use(new oe).use(new ue).use(new pe).use(new ce).use(new ie).use(new se).use(new ae).use(new re).execute(e,()=>this.getCached(s,e.request));if(i)return i;let a=await r();return e.ctx.waitUntil(this.setCached(s,e.request,a)),a}async getCached(e,r){let s=this.getCacheKey(r),o=await e.match(s.toString());if(!o)return;if(!T.isVariantResponse(o))return o;let i=T.restore(o).vary,a=I(r,i,s);return e.match(a)}async setCached(e,r,s){if(!De(r,s))return;let o=this.getCacheKey(r),i=s.clone(),a=Te(i),c=await e.match(o),wt=c&&T.isVariantResponse(c);if(!c){if(a.length===0){await e.put(o,i);return}let S=T.new(a);S.expireAfter(i),await e.put(o,await S.response()),await e.put(I(r,S.vary,o),i);return}if(wt){let S=T.restore(c);S.expireAfter(i),a.length>0&&(S.append(a),S.isModified&&await e.put(o,await S.response())),await e.put(I(r,S.vary,o),i);return}if(a.length===0){await e.put(o,i);return}let q=T.new(a);q.expireAfter(c),q.expireAfter(i),await e.put(o,await q.response()),await e.put(I(r,q.vary,o),i),await e.put(I(r,[],o),c)}getCacheKey(e){let r=this.init.getKey(e);return We(r),r.hash="",r}};function Qs(t={}){return ve(t),new de(t)}function nt(t){if(t===void 0)return;if(typeof t!="object"||t===null)throw new TypeError("CorsInit must be an object.");let e=t;if(e.allowedOrigins!==void 0&&!z(e.allowedOrigins))throw new TypeError("CorsInit.allowedOrigins must be a string array.");if(e.allowedHeaders!==void 0&&!z(e.allowedHeaders))throw new TypeError("CorsInit.allowedHeaders must be a string array.");if(e.exposedHeaders!==void 0&&!z(e.exposedHeaders))throw new TypeError("CorsInit.exposedHeaders must be a string array.");if(e.allowCredentials!==void 0&&!Le(e.allowCredentials))throw new TypeError("CorsInit.allowCredentials must be a boolean.");if(e.maxAge!==void 0&&!E(e.maxAge))throw new TypeError("CorsInit.maxAge must be a number.")}var le="*",it=[h.SWITCHING_PROTOCOLS,h.CONTINUE,h.PROCESSING,h.EARLY_HINTS,h.MOVED_PERMANENTLY,h.MOVED_TEMPORARILY,h.SEE_OTHER,h.TEMPORARY_REDIRECT,h.PERMANENT_REDIRECT],at={allowedOrigins:[le],allowedHeaders:[n.CONTENT_TYPE],exposedHeaders:[],allowCredentials:!1,maxAge:5*He.Minute};async function ct(t,e,r){let s=new V(t),o=ht(e.request);return ft(s.headers),ut(s.headers,r),o&&(dt(s.headers,r,o),lt(s.headers,r,o),Kt(s.headers,e),Ft(s.headers,r),qt(s.headers,r)),s.response()}async function pt(t,e,r){let s=new V(t),o=ht(e.request);return ft(s.headers),ut(s.headers,r),o&&(dt(s.headers,r,o),lt(s.headers,r,o),Bt(s.headers,r)),s.response()}function ut(t,e){_e(e)||$(t,n.VARY,n.ORIGIN)}function dt(t,e,r){if(_e(e)){f(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,le);return}e.allowedOrigins.includes(r)&&f(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,r)}function lt(t,e,r){e.allowCredentials&&(_e(e)||e.allowedOrigins.includes(r)&&f(t,n.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true"))}function Kt(t,e){let r=e.getAllowedMethods();b(r),f(t,n.ACCESS_CONTROL_ALLOW_METHODS,r)}function qt(t,e){let r=Math.max(0,Math.floor(e.maxAge));f(t,n.ACCESS_CONTROL_MAX_AGE,String(r))}function Ft(t,e){f(t,n.ACCESS_CONTROL_ALLOW_HEADERS,e.allowedHeaders)}function Bt(t,e){f(t,n.ACCESS_CONTROL_EXPOSE_HEADERS,e.exposedHeaders)}function _e(t){return t.allowedOrigins.includes(le)}function ft(t){t.delete(n.ACCESS_CONTROL_MAX_AGE),t.delete(n.ACCESS_CONTROL_ALLOW_ORIGIN),t.delete(n.ACCESS_CONTROL_ALLOW_HEADERS),t.delete(n.ACCESS_CONTROL_ALLOW_METHODS),t.delete(n.ACCESS_CONTROL_EXPOSE_HEADERS),t.delete(n.ACCESS_CONTROL_ALLOW_CREDENTIALS)}function mt(t){let{status:e,headers:r}=t;return!!(it.includes(e)||r.has(n.UPGRADE))}function ht(t){let e=t.headers.get(n.ORIGIN)?.trim();if(!e||e==="null")return null;try{return new URL(e).origin}catch{return null}}var fe=class{config;constructor(e){this.config={...at,...e}}async handle(e,r){let s=await r();return e.request.method===B?ct(s,e,this.config):mt(s)?s:pt(s,e,this.config)}};function Ro(t){return nt(t),new fe(t)}import{match as zt}from"path-to-regexp";function Ct(t){return d(t,n.CONNECTION).some(e=>e.toLowerCase()===$e)}function Et(t){return d(t,n.UPGRADE).some(e=>e.toLowerCase()===Xe)}function gt(t){return t.get(n.SEC_WEBSOCKET_VERSION)?.trim()==="13"}var me=class{constructor(e){this.path=e}handle(e,r){if(e.request.method!==p||!this.isMatch(e.request))return r();let s=e.request.headers;return Ct(s)?Et(s)?gt(s)?r():new Q().response():new K("Missing or invalid 'Upgrade' header").response():new K("Missing or invalid 'Connection' header").response()}isMatch(e){return zt(this.path)(new URL(e.url).pathname)!==!1}};function Lo(t="/"){return new me(t)}function jt(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}function St(t){return C(t)?t.length>0:jt(t)?t.byteLength>0:!1}function Rt(t){if(t===null||typeof t!="object")throw new TypeError("WebSocket attachment must be an object");try{JSON.stringify(t)}catch{throw new TypeError("WebSocket attachment is not serializable")}}var he=class t{server;customListeners={};constructor(e){this.server=e}addEventListener(e,r,s){if(t.isCustomEvent(e)){let o=this.customListeners[e];o||(o=[],this.customListeners[e]=o),o.push(r)}else{let o=e==="close"?{...s,once:!0}:s;this.server.addEventListener(e,r,o)}}removeEventListener(e,r){if(t.isCustomEvent(e)){let s=this.customListeners[e];if(s){let o=s.indexOf(r);o!==-1&&s.splice(o,1)}}else this.server.removeEventListener(e,r)}dispatch(e,r,s=!1){let o=this.customListeners[e]?.slice()??[];s&&(this.customListeners[e]=[]);for(let i of o)i(r)}warn(e){this.dispatch("warn",{type:"warn",message:e})}open(){this.dispatch("open",new Event("open"),!0)}static isCustomEvent(e){return["open","warn"].includes(e)}};var w={NORMAL:1e3,NO_STATUS:1005,ABNORMAL:1006,TLS_HANDSHAKE:1015},At=new Set([w.NO_STATUS,w.ABNORMAL,w.TLS_HANDSHAKE]);function Tt(t){return E(t)?Yt(t)&&!Jt(t)?t:w.NORMAL:w.NORMAL}function Yt(t){return t>=w.NORMAL&&t<=4999}function Jt(t){return At.has(t)}function Ot(t){if(C(t))return t.replaceAll(/[^\x20-\x7E]/g,"").slice(0,123)}var k=class extends he{accepted=!1;server;constructor(e){super(e),this.server=e,this.server.addEventListener("close",this.onclose)}send(e){if(this.isState(WebSocket.CONNECTING,WebSocket.CLOSED)){this.warn("Cannot send: WebSocket not open");return}if(!St(e)){this.warn("Cannot send: empty or invalid data");return}this.server.send(e)}get attachment(){return this.server.deserializeAttachment()??{}}attach(e){if(e!==void 0)if(e===null)this.server.serializeAttachment({});else{let s={...this.attachment,...e};Rt(s),this.server.serializeAttachment(s)}}get readyState(){return this.accepted?this.server.readyState:WebSocket.CONNECTING}isState(...e){return e.includes(this.readyState)}close(e,r){this.server.removeEventListener("close",this.onclose),this.server.close(Tt(e),Ot(r))}onclose=e=>{this.close(e.code,e.reason)}};var Ce=class extends k{client;constructor(){let e=new WebSocketPair,[r,s]=[e[0],e[1]];super(s),this.client=r}acceptWebSocket(e,r){return this.accepted?this.client:(e.acceptWebSocket(this.server,r),this.ready())}accept(){return this.accepted?this.client:(this.server.accept(),this.ready())}ready(){return this.accepted=!0,this.open(),this.client}};var Ee=class extends k{constructor(e){super(e),this.accepted=!0}accept(){throw new Error("Do not call accept() on restore")}acceptWebSocket(){throw new Error("Do not call acceptWebSocket() on restore")}};var bt=class{map=new Map;create(e){class r extends Ce{constructor(a){super();this.sessions=a}accept(){return this.addEventListener("close",()=>this.sessions.unregister(this.server)),this.sessions.register(this.server,this),super.accept()}acceptWebSocket(a,c){return this.sessions.register(this.server,this),super.acceptWebSocket(a,c)}}let s=new r(this);return s.attach(e),s}restore(e){class r extends Ee{constructor(o,i){super(i),o.register(this.server,this)}}return new r(this,e)}restoreAll(e){let r=[];for(let s of e)r.push(this.restore(s));return r}get(e){return this.map.get(e)}select(e){let r=[];for(let s of e){let o=this.map.get(s);o&&r.push(o)}return r}values(){return this.map.values()}keys(){return this.map.keys()}close(e,r,s){let o=this.get(e);return o&&o.close(r,s),this.unregister(e)}*[Symbol.iterator](){yield*this.values()}register(e,r){this.map.set(e,r)}unregister(e){return this.map.delete(e)}};function xt(t){if(t===null||typeof t!="object"||typeof t.handle!="function")throw new TypeError("Handler must implement the Middleware interface (have a handle method).")}var M=class{constructor(e,r,s){this._request=e;this._env=r;this._ctx=s}get request(){return this._request}get env(){return this._env}get ctx(){return this._ctx}isAllowed(e){let r=this.getAllowedMethods();return b(r),e===p||e===O?!0:be(e)&&r.includes(e)}create(e){let r=this.constructor;return new r(e,this.env,this.ctx)}response(e,...r){return new e(...r).response()}static ignite(){return{fetch:(e,r,s)=>new this(e,r,s).fetch()}}};var ge=class extends M{middlewares=[];init(){}use(...e){for(let r of e)xt(r);return this.middlewares.push(...e),this}async fetch(){return await this.init(),this.middlewares.reduceRight((r,s)=>()=>s.handle(this,r),()=>this.isAllowed(this.request.method)?this.dispatch():this.response(v,this))()}};var Se=class extends ge{async fetch(){try{return await super.fetch()}catch(e){return console.error(e),this.response(ee)}}dispatch(){let e=this.request.method;return({GET:()=>this.get(),PUT:()=>this.put(),HEAD:()=>this.head(),POST:()=>this.post(),PATCH:()=>this.patch(),DELETE:()=>this.delete(),OPTIONS:()=>this.options()}[e]??(()=>this.response(v,this)))()}get(){return this.response(A)}put(){return this.response(N,this)}post(){return this.response(N,this)}patch(){return this.response(N,this)}delete(){return this.response(N,this)}options(){return this.response(Z,this)}async head(){let e=this.create(new Request(this.request.url,{method:p,headers:this.request.headers}));return this.response(L,await e.fetch())}getAllowedMethods(){return[p,O,B]}};import{match as Zt}from"path-to-regexp";var Re=class{routes=[];add(e){for(let[r,s,o]of e){let i=Zt(s);this.routes.push({method:r,matcher:i,handler:o})}}match(e,r){let s=new URL(r).pathname;for(let o of this){if(o.method!==e)continue;let i=o.matcher(s);if(i)return{route:o,params:i.params}}return null}*[Symbol.iterator](){yield*this.routes}};var Nt=class t extends Se{_routes=new Re;route(e,r,s){return this.routes([[e,r,s]]),this}routes(e){return this._routes.add(e),this}async dispatch(){let e=this._routes.match(this.request.method,this.request.url);if(!e)return super.dispatch();let{handler:r}=e.route;return t.isWorkerClass(r)?new r(this.request,this.env,this.ctx).fetch():r.call(this,e.params)}static isWorkerClass(e){return Object.prototype.isPrototypeOf.call(M.prototype,e.prototype)}put(){return this.response(A)}post(){return this.response(A)}patch(){return this.response(A)}delete(){return this.response(A)}};export{K as BadRequest,Se as BasicWorker,R as CacheControl,V as CopyResponse,or as DELETE,rt as Forbidden,p as GET,O as HEAD,L as Head,Je as HtmlResponse,l as HttpError,ee as InternalServerError,J as JsonResponse,F as Method,v as MethodNotAllowed,N as MethodNotImplemented,A as NotFound,ye as NotImplemented,H as NotModified,B as OPTIONS,we as OctetStream,Z as Options,sr as PATCH,rr as POST,tr as PUT,W as PreconditionFailed,Qe as R2ObjectStream,Nt as RouteWorker,st as ServiceUnavailable,h as StatusCodes,U as SuccessResponse,Ze as TextResponse,He as Time,tt as Unauthorized,Q as UpgradeRequired,bt as WebSocketSessions,et as WebSocketUpgrade,m as WorkerResponse,Qs as cache,Ro as cors,Pe as sortSearchParams,Er as stripSearchParams,Lo as websocket};
1
+ import{StatusCodes as h}from"http-status-codes";import Ie from"cache-control-parser";var R={parse:Ie.parse,stringify:Ie.stringify,DISABLE:Object.freeze({"no-cache":!0,"no-store":!0,"must-revalidate":!0,"max-age":0})};var F=(c=>(c.GET="GET",c.PUT="PUT",c.HEAD="HEAD",c.POST="POST",c.PATCH="PATCH",c.DELETE="DELETE",c.OPTIONS="OPTIONS",c))(F||{}),{GET:p,PUT:tr,HEAD:O,POST:rr,PATCH:sr,DELETE:or,OPTIONS:B}=F;var He={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};function z(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function C(t){return typeof t=="string"}function E(t){return typeof t=="number"&&!Number.isNaN(t)}function Le(t){return typeof t=="boolean"}function ve(t){if(typeof t!="object"||t===null)throw new TypeError("CacheInit must be an object.");let{name:e,getKey:r}=t;yt(e),_t(r)}function yt(t){if(t!==void 0&&!C(t))throw new TypeError("Cache name must be a string.")}function _t(t){if(t!==void 0&&typeof t!="function")throw new TypeError("getKey must be a function.")}function We(t){if(!(t instanceof URL))throw new TypeError("getKey must return a URL.")}function x(t,e){return t<e?-1:t>e?1:0}function Pe(t){let e=new URL(t.url),r=new URLSearchParams([...e.searchParams.entries()].sort(([s],[o])=>x(s,o)));return e.search=r.toString(),e.hash="",e}function Er(t){let e=new URL(t.url);return e.search="",e.hash="",e}var j=class{rules=[];use(...e){return this.rules.push(...e),this}execute(e,r){return this.rules.reduceRight((o,i)=>()=>i.apply(e,o),()=>r())()}};import{StatusCodes as It}from"http-status-codes";var n={ACCEPT:"accept",ACCEPT_ENCODING:"accept-encoding",ACCEPT_LANGUAGE:"accept-language",ACCEPT_RANGES:"accept-ranges",ALLOW:"allow",AUTHORIZATION:"authorization",CACHE_CONTROL:"cache-control",CONNECTION:"connection",CONTENT_DISPOSITION:"content-disposition",CONTENT_ENCODING:"content-encoding",CONTENT_LANGUAGE:"content-language",CONTENT_LENGTH:"content-length",CONTENT_RANGE:"content-range",CONTENT_TYPE:"content-type",CONTENT_MD5:"content-md5",COOKIE:"cookie",ETAG:"etag",IF_MATCH:"if-match",IF_MODIFIED_SINCE:"if-modified-since",IF_NONE_MATCH:"if-none-match",IF_UNMODIFIED_SINCE:"if-unmodified-since",LAST_MODIFIED:"last-modified",ORIGIN:"origin",RANGE:"range",SET_COOKIE:"set-cookie",VARY:"vary",ACCESS_CONTROL_ALLOW_CREDENTIALS:"access-control-allow-credentials",ACCESS_CONTROL_ALLOW_HEADERS:"access-control-allow-headers",ACCESS_CONTROL_ALLOW_METHODS:"access-control-allow-methods",ACCESS_CONTROL_ALLOW_ORIGIN:"access-control-allow-origin",ACCESS_CONTROL_EXPOSE_HEADERS:"access-control-expose-headers",ACCESS_CONTROL_MAX_AGE:"access-control-max-age",SEC_WEBSOCKET_VERSION:"sec-websocket-version",UPGRADE:"upgrade",INTERNAL_VARIANT_SET:"internal-variant-set"},ke=[n.CONTENT_TYPE,n.CONTENT_LENGTH,n.CONTENT_RANGE,n.CONTENT_ENCODING,n.CONTENT_LANGUAGE,n.CONTENT_DISPOSITION,n.CONTENT_MD5],Me=[n.CONTENT_LENGTH,n.CONTENT_RANGE];function f(t,e,r){let s=Array.isArray(r)?r:[r],o=Array.from(new Set(s.map(i=>i.trim()))).filter(i=>i.length).sort(x);if(!o.length){t.delete(e);return}t.set(e,o.join(", "))}function $(t,e,r){let s=Array.isArray(r)?r:[r];if(s.length===0)return;let i=d(t,e).concat(s.map(a=>a.trim()));f(t,e,i)}function d(t,e){let r=t.get(e)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(r)).sort(x)}function Ae(t,e){for(let r of e)t.delete(r)}var Ht="https://vary",Lt="*";function De(t,e){if(e.status!==It.OK||t.method!==p||t.headers.has(n.AUTHORIZATION)||t.headers.has(n.COOKIE)||y(t.headers)["no-store"]||!e.headers.has(n.CACHE_CONTROL))return!1;let s=y(e.headers),o=s["s-maxage"]??s["max-age"];if(o===void 0||o===0||s["no-store"]||s["no-cache"]||s.private||e.headers.has(n.SET_COOKIE)||Te(e).includes(Lt))return!1;if(e.headers.has(n.INTERNAL_VARIANT_SET))throw new Error("Found conflicting vary header.");if(e.headers.has(n.CONTENT_RANGE))throw new Error("Found content-range header on 200 OK. Must use 206 Partial Content");return!0}function y(t){return R.parse(t.get(n.CACHE_CONTROL)??"")}function Te(t){return _(d(t.headers,n.VARY))}function _(t){let e=t.map(r=>r.toLowerCase()).filter(r=>r!==n.ACCEPT_ENCODING).sort(x);return Array.from(new Set(e))}function I(t,e,r){let s=[],o=_(e);for(let a of o){let c=t.headers.get(a);c!==null&&s.push([a,vt(a,c)])}let i=Wt(JSON.stringify([r.toString(),s]));return new URL(i,Ht).toString()}function vt(t,e){switch(t.toLowerCase()){case n.ACCEPT:case n.ACCEPT_LANGUAGE:case n.ORIGIN:return e.toLowerCase();default:return e}}function Wt(t){let e=new TextEncoder().encode(t),r="";for(let s of e)r+=String.fromCodePoint(s);return btoa(r).replaceAll("+","-").replaceAll("/","_").replace(/={1,2}$/,"")}var Pt=/^bytes=(\d{1,12})-(\d{0,12})$/,Ge="W/",Ve="*";function Ue(t){let e=t.headers.get(n.RANGE);if(!e)return;let r=Pt.exec(e);if(!r)return;let s=Number(r[1]),o=r[2]===""?void 0:Number(r[2]);return o===void 0?{start:s}:{start:s,end:o}}function Ke(t,e){return t.length>0&&!Fe(t,e,Ve)}function qe(t,e){return Fe(t,Be(e),Ve)}function Fe(t,...e){return t.some(r=>e.includes(r))}function X(t){if(!C(t))return;let e=Date.parse(t);return Number.isNaN(e)?void 0:e}function Be(t){return t.startsWith(Ge)?t.slice(2):t}function Oe(t){return{ifMatch:d(t,n.IF_MATCH).filter(e=>!e.startsWith(Ge)),ifNoneMatch:d(t,n.IF_NONE_MATCH).map(Be),ifModifiedSince:t.get(n.IF_MODIFIED_SINCE),ifUnmodifiedSince:t.get(n.IF_UNMODIFIED_SINCE)}}function ze(t){let{ifNoneMatch:e,ifMatch:r,ifModifiedSince:s,ifUnmodifiedSince:o}=Oe(t);return e.length>0||r.length>0||s!==null||o!==null}function je(t){let e=t.get(n.CONTENT_LENGTH);if(e===null||e.trim()==="")return;let r=Number(e);if(E(r))return r}var Y=class{async apply(e,r){let s=y(e.request.headers);if(!s["no-store"]&&!((s["no-cache"]||s["max-age"]===0)&&!ze(e.request.headers)))return r()}};import{getReasonPhrase as Gt,StatusCodes as g}from"http-status-codes";var kt=new Set(Object.values(F));function be(t){return C(t)&&kt.has(t)}function Mt(t){return Array.isArray(t)&&t.every(be)}function b(t){if(!Mt(t)){let e=Array.isArray(t)?JSON.stringify(t):String(t);throw new TypeError(`Invalid method array: ${e}`)}}var $e="upgrade",Xe="websocket";import{getReasonPhrase as Dt,StatusCodes as u}from"http-status-codes";var D="utf-8";function Ye(t){if(typeof t!="object"||t===null)throw new TypeError("OctetStreamInit must be an object.");let e=t,r=e.size;if(!E(r)||r<0||!Number.isInteger(r))throw new RangeError(`OctetStreamInit.size must be a non-negative integer (size=${JSON.stringify(r)}).`);let s=e.offset??0;if(!E(s)||s<0||s>r||!Number.isInteger(s))throw new RangeError(`OctetStreamInit.offset must be a non-negative integer less than or equal to size (size=${JSON.stringify(r)}, offset=${JSON.stringify(s)}).`);let o=e.length??r-s;if(!E(o)||o<0||s+o>r||!Number.isInteger(o))throw new RangeError(`OctetStreamInit.length must be a non-negative integer less than or equal to size - offset (size=${JSON.stringify(r)}, offset=${JSON.stringify(s)}, length=${JSON.stringify(o)}).`)}function G(t,e){return!e||t.toLowerCase().includes("charset=")?t:`${t}; charset=${e.toLowerCase()}`}var xe=class{headers=new Headers;status=u.OK;statusText;webSocket;mediaType=G("text/plain",D);get responseInit(){return{headers:this.headers,status:this.status,statusText:this.statusText??Dt(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(e,r){f(this.headers,e,r)}mergeHeader(e,r){$(this.headers,e,r)}addContentType(){this.headers.get(n.CONTENT_TYPE)||this.setHeader(n.CONTENT_TYPE,this.mediaType)}filterHeaders(){this.status===u.NO_CONTENT?Ae(this.headers,Me):this.status===u.NOT_MODIFIED&&Ae(this.headers,ke)}},Ne=class extends xe{constructor(r){super();this.cache=r}addCacheHeader(){this.cache&&this.setHeader(n.CACHE_CONTROL,R.stringify(this.cache))}},m=class extends Ne{constructor(r=null,s){super(s);this.body=r}async response(){this.addCacheHeader();let r=[u.NO_CONTENT,u.NOT_MODIFIED].includes(this.status)?null:this.body;return r&&this.addContentType(),this.filterHeaders(),new Response(r,this.responseInit)}},V=class extends m{constructor(e,r){super(e.body,r),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},H=class extends m{constructor(e){super(),this.status=u.NOT_MODIFIED,this.headers=new Headers(e.headers)}},U=class extends m{constructor(e=null,r,s=u.OK){super(e,r),this.status=s}},J=class extends U{constructor(e={},r,s=u.OK){super(JSON.stringify(e),r,s),this.mediaType=G("application/json",D)}},Je=class extends U{constructor(e,r,s=u.OK,o=D){super(e,r,s),this.mediaType=G("text/html",o)}},Ze=class extends U{constructor(e,r,s=u.OK,o=D){super(e,r,s),this.mediaType=G("text/plain",o)}},we=class t extends m{constructor(e,r,s){Ye(r),super(e,s),this.mediaType="application/octet-stream";let o=t.normalizeInit(r),{size:i,offset:a,length:c}=o;t.isPartial(o)&&(this.setHeader(n.CONTENT_RANGE,`bytes ${a}-${a+c-1}/${i}`),this.status=u.PARTIAL_CONTENT),this.setHeader(n.ACCEPT_RANGES,"bytes"),this.setHeader(n.CONTENT_LENGTH,`${c}`)}static normalizeInit(e){let{size:r}=e,s=e.offset??0,o=e.length??r-s;return s===0&&o===0&&r>0&&(o=1),{size:r,offset:s,length:o}}static isPartial(e){return e.size===0?!1:!(e.offset===0&&e.length===e.size)}},Qe=class t extends we{constructor(e,r){let s=r;!s&&e.httpMetadata?.cacheControl&&(s=R.parse(e.httpMetadata.cacheControl)),super(e.body,t.computeRange(e.size,e.range),s),this.setHeader(n.ETAG,e.httpEtag),e.httpMetadata?.contentType&&(this.mediaType=e.httpMetadata.contentType)}static computeRange(e,r){if(!r)return{size:e};if("suffix"in r){let s=Math.max(0,e-r.suffix),o=e-s;return{size:e,offset:s,length:o}}return{size:e,...r}}},et=class extends m{constructor(e){super(),this.status=u.SWITCHING_PROTOCOLS,this.webSocket=e}},L=class extends m{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},Z=class extends m{constructor(e){let r=Array.from(new Set([p,O,...e.getAllowedMethods()]));b(r),super(),this.status=u.NO_CONTENT,this.setHeader(n.ALLOW,r)}};var l=class extends J{constructor(r,s){let o={status:r,error:Gt(r),details:s??""};super(o,R.DISABLE,r);this.details=s}},K=class extends l{constructor(e){super(g.BAD_REQUEST,e)}},tt=class extends l{constructor(e){super(g.UNAUTHORIZED,e)}},rt=class extends l{constructor(e){super(g.FORBIDDEN,e)}},A=class extends l{constructor(e){super(g.NOT_FOUND,e)}},v=class extends l{constructor(e){let r=e.getAllowedMethods();b(r),super(g.METHOD_NOT_ALLOWED,`${e.request.method} method not allowed.`),this.setHeader(n.ALLOW,r)}},W=class extends l{constructor(e){super(g.PRECONDITION_FAILED,e)}},Q=class extends l{constructor(){super(g.UPGRADE_REQUIRED),this.setHeader(n.SEC_WEBSOCKET_VERSION,"13")}},ee=class extends l{constructor(e){super(g.INTERNAL_SERVER_ERROR,e)}},ye=class extends l{constructor(e){super(g.NOT_IMPLEMENTED,e)}},N=class extends ye{constructor(e){super(`${e.request.method} method not implemented.`)}},st=class extends l{constructor(e){super(g.SERVICE_UNAVAILABLE,e)}};import{StatusCodes as Vt}from"http-status-codes";var P=class{async apply(e,r){let s=await r();if(!s||s.status!==Vt.OK)return s;let o=this.getHeader(s);if(o===void 0)return s;let i=Oe(e.request.headers);return this.response(s,o,i)}};var te=class extends P{getHeader(e){return e.headers.get(n.ETAG)??void 0}},re=class extends te{async response(e,r,s){return Ke(s.ifMatch,r)?new W(`ETag: ${r}`).response():e}},se=class extends te{async response(e,r,s){if(s.ifNoneMatch.length===0)return e;if(qe(s.ifNoneMatch,r))return new H(e).response()}};var oe=class{async apply(e,r){if(e.request.method===p)return r();if(e.request.method===O){let s=await r();return s?new L(s).response():void 0}}};var ne=class extends P{getHeader(e){return X(e.headers.get(n.LAST_MODIFIED))}},ie=class extends ne{async response(e,r,s){let o=X(s.ifModifiedSince);if(o===void 0)return e;if(r<=o)return new H(e).response()}},ae=class extends ne{async response(e,r,s){let o=X(s.ifUnmodifiedSince);return o===void 0?e:r>o?new W(`Last-Modified: ${new Date(r).toUTCString()}`).response():e}};import{StatusCodes as Ut}from"http-status-codes";var ce=class{async apply(e,r){let s=Ue(e.request);if(s&&(s.start!==0||s.end===0))return;let o=await r();if(!o||o.status!==Ut.OK||!s||s.end===void 0)return o;let i=je(o.headers);if(i&&s.end===i-1)return o}};var pe=class{async apply(e,r){let s=e.request.headers;if(!s.has(n.AUTHORIZATION)&&!s.has(n.COOKIE))return r()}};var ue=class{async apply(e,r){if(!e.request.headers.has(n.UPGRADE))return r()}};var T=class t extends m{_isModified=!1;constructor(e){let r=_(e);if(r.length===0)throw new Error("The filtered vary array is empty.");super(),this.setHeader(n.INTERNAL_VARIANT_SET,r)}static new(e){return new t(_(e))}static restore(e){if(!t.isVariantResponse(e))throw new Error("The source response is not a variant response");let r=t.new(d(e.headers,n.INTERNAL_VARIANT_SET)),s=e.headers.get(n.CACHE_CONTROL);return s&&(r.cache=R.parse(s)),r}get vary(){return d(this.headers,n.INTERNAL_VARIANT_SET)}get isModified(){return this._isModified}append(e){let r=this.vary.length;this.mergeHeader(n.INTERNAL_VARIANT_SET,_(e)),this._isModified=this.vary.length!==r}static isVariantResponse(e){return e.headers.has(n.INTERNAL_VARIANT_SET)}expireAfter(e){let r=y(e.headers),s=r["s-maxage"]??r["max-age"];if(s===void 0)return;let o=this.cache?.["s-maxage"];(o===void 0||s>o)&&(this.cache={"s-maxage":s},this._isModified=!0)}};var de=class{init;constructor(e){let{name:r,getKey:s=Pe}=e;this.init={name:r?.trim()||void 0,getKey:s}}async handle(e,r){let s=this.init.name?await caches.open(this.init.name):caches.default,i=await new j().use(new Y).use(new oe).use(new ue).use(new pe).use(new ce).use(new ie).use(new se).use(new ae).use(new re).execute(e,()=>this.getCached(s,e.request));if(i)return i;let a=await r();return e.ctx.waitUntil(this.setCached(s,e.request,a)),a}async getCached(e,r){let s=this.getCacheKey(r),o=await e.match(s.toString());if(!o)return;if(!T.isVariantResponse(o))return o;let i=T.restore(o).vary,a=I(r,i,s);return e.match(a)}async setCached(e,r,s){if(!De(r,s))return;let o=this.getCacheKey(r),i=s.clone(),a=Te(i),c=await e.match(o),wt=c&&T.isVariantResponse(c);if(!c){if(a.length===0){await e.put(o,i);return}let S=T.new(a);S.expireAfter(i),await e.put(o,await S.response()),await e.put(I(r,S.vary,o),i);return}if(wt){let S=T.restore(c);S.expireAfter(i),a.length>0&&(S.append(a),S.isModified&&await e.put(o,await S.response())),await e.put(I(r,S.vary,o),i);return}if(a.length===0){await e.put(o,i);return}let q=T.new(a);q.expireAfter(c),q.expireAfter(i),await e.put(o,await q.response()),await e.put(I(r,q.vary,o),i),await e.put(I(r,[],o),c)}getCacheKey(e){let r=this.init.getKey(e);return We(r),r.hash="",r}};function Qs(t={}){return ve(t),new de(t)}function nt(t){if(t===void 0)return;if(typeof t!="object"||t===null)throw new TypeError("CorsInit must be an object.");let e=t;if(e.allowedOrigins!==void 0&&!z(e.allowedOrigins))throw new TypeError("CorsInit.allowedOrigins must be a string array.");if(e.allowedHeaders!==void 0&&!z(e.allowedHeaders))throw new TypeError("CorsInit.allowedHeaders must be a string array.");if(e.exposedHeaders!==void 0&&!z(e.exposedHeaders))throw new TypeError("CorsInit.exposedHeaders must be a string array.");if(e.allowCredentials!==void 0&&!Le(e.allowCredentials))throw new TypeError("CorsInit.allowCredentials must be a boolean.");if(e.maxAge!==void 0&&!E(e.maxAge))throw new TypeError("CorsInit.maxAge must be a number.")}var le="*",it=[h.SWITCHING_PROTOCOLS,h.CONTINUE,h.PROCESSING,h.EARLY_HINTS,h.MOVED_PERMANENTLY,h.MOVED_TEMPORARILY,h.SEE_OTHER,h.TEMPORARY_REDIRECT,h.PERMANENT_REDIRECT],at={allowedOrigins:[le],allowedHeaders:[n.CONTENT_TYPE],exposedHeaders:[],allowCredentials:!1,maxAge:5*He.Minute};function ct(t,e,r){let s=new V(t),o=ht(e.request);return ft(s.headers),ut(s.headers,r),o&&(dt(s.headers,r,o),lt(s.headers,r,o),Kt(s.headers,e),Ft(s.headers,r),qt(s.headers,r)),s.response()}function pt(t,e,r){let s=new V(t),o=ht(e.request);return ft(s.headers),ut(s.headers,r),o&&(dt(s.headers,r,o),lt(s.headers,r,o),Bt(s.headers,r)),s.response()}function ut(t,e){_e(e)||$(t,n.VARY,n.ORIGIN)}function dt(t,e,r){if(_e(e)){f(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,le);return}e.allowedOrigins.includes(r)&&f(t,n.ACCESS_CONTROL_ALLOW_ORIGIN,r)}function lt(t,e,r){e.allowCredentials&&(_e(e)||e.allowedOrigins.includes(r)&&f(t,n.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true"))}function Kt(t,e){let r=e.getAllowedMethods();b(r),f(t,n.ACCESS_CONTROL_ALLOW_METHODS,r)}function qt(t,e){let r=Math.max(0,Math.floor(e.maxAge));f(t,n.ACCESS_CONTROL_MAX_AGE,String(r))}function Ft(t,e){f(t,n.ACCESS_CONTROL_ALLOW_HEADERS,e.allowedHeaders)}function Bt(t,e){f(t,n.ACCESS_CONTROL_EXPOSE_HEADERS,e.exposedHeaders)}function _e(t){return t.allowedOrigins.includes(le)}function ft(t){t.delete(n.ACCESS_CONTROL_MAX_AGE),t.delete(n.ACCESS_CONTROL_ALLOW_ORIGIN),t.delete(n.ACCESS_CONTROL_ALLOW_HEADERS),t.delete(n.ACCESS_CONTROL_ALLOW_METHODS),t.delete(n.ACCESS_CONTROL_EXPOSE_HEADERS),t.delete(n.ACCESS_CONTROL_ALLOW_CREDENTIALS)}function mt(t){let{status:e,headers:r}=t;return!!(it.includes(e)||r.has(n.UPGRADE))}function ht(t){let e=t.headers.get(n.ORIGIN)?.trim();if(!e||e==="null")return null;try{return new URL(e).origin}catch{return null}}var fe=class{config;constructor(e){this.config={...at,...e}}async handle(e,r){let s=await r();return e.request.method===B?ct(s,e,this.config):mt(s)?s:pt(s,e,this.config)}};function Ro(t){return nt(t),new fe(t)}import{match as zt}from"path-to-regexp";function Ct(t){return d(t,n.CONNECTION).some(e=>e.toLowerCase()===$e)}function Et(t){return d(t,n.UPGRADE).some(e=>e.toLowerCase()===Xe)}function gt(t){return t.get(n.SEC_WEBSOCKET_VERSION)?.trim()==="13"}var me=class{constructor(e){this.path=e}handle(e,r){if(e.request.method!==p||!this.isMatch(e.request))return r();let s=e.request.headers;return Ct(s)?Et(s)?gt(s)?r():new Q().response():new K("Missing or invalid 'Upgrade' header").response():new K("Missing or invalid 'Connection' header").response()}isMatch(e){return zt(this.path)(new URL(e.url).pathname)!==!1}};function Lo(t="/"){return new me(t)}function jt(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}function St(t){return C(t)?t.length>0:jt(t)?t.byteLength>0:!1}function Rt(t){if(t===null||typeof t!="object")throw new TypeError("WebSocket attachment must be an object");try{JSON.stringify(t)}catch{throw new TypeError("WebSocket attachment is not serializable")}}var he=class t{server;customListeners={};constructor(e){this.server=e}addEventListener(e,r,s){if(t.isCustomEvent(e)){let o=this.customListeners[e];o||(o=[],this.customListeners[e]=o),o.push(r)}else{let o=e==="close"?{...s,once:!0}:s;this.server.addEventListener(e,r,o)}}removeEventListener(e,r){if(t.isCustomEvent(e)){let s=this.customListeners[e];if(s){let o=s.indexOf(r);o!==-1&&s.splice(o,1)}}else this.server.removeEventListener(e,r)}dispatch(e,r,s=!1){let o=this.customListeners[e]?.slice()??[];s&&(this.customListeners[e]=[]);for(let i of o)i(r)}warn(e){this.dispatch("warn",{type:"warn",message:e})}open(){this.dispatch("open",new Event("open"),!0)}static isCustomEvent(e){return["open","warn"].includes(e)}};var w={NORMAL:1e3,NO_STATUS:1005,ABNORMAL:1006,TLS_HANDSHAKE:1015},At=new Set([w.NO_STATUS,w.ABNORMAL,w.TLS_HANDSHAKE]);function Tt(t){return E(t)?Yt(t)&&!Jt(t)?t:w.NORMAL:w.NORMAL}function Yt(t){return t>=w.NORMAL&&t<=4999}function Jt(t){return At.has(t)}function Ot(t){if(C(t))return t.replaceAll(/[^\x20-\x7E]/g,"").slice(0,123)}var k=class extends he{accepted=!1;server;constructor(e){super(e),this.server=e,this.server.addEventListener("close",this.onclose)}send(e){if(this.isState(WebSocket.CONNECTING,WebSocket.CLOSED)){this.warn("Cannot send: WebSocket not open");return}if(!St(e)){this.warn("Cannot send: empty or invalid data");return}this.server.send(e)}get attachment(){return this.server.deserializeAttachment()??{}}attach(e){if(e!==void 0)if(e===null)this.server.serializeAttachment({});else{let s={...this.attachment,...e};Rt(s),this.server.serializeAttachment(s)}}get readyState(){return this.accepted?this.server.readyState:WebSocket.CONNECTING}isState(...e){return e.includes(this.readyState)}close(e,r){this.server.removeEventListener("close",this.onclose),this.server.close(Tt(e),Ot(r))}onclose=e=>{this.close(e.code,e.reason)}};var Ce=class extends k{client;constructor(){let e=new WebSocketPair,[r,s]=[e[0],e[1]];super(s),this.client=r}acceptWebSocket(e,r){return this.accepted?this.client:(e.acceptWebSocket(this.server,r),this.ready())}accept(){return this.accepted?this.client:(this.server.accept(),this.ready())}ready(){return this.accepted=!0,this.open(),this.client}};var Ee=class extends k{constructor(e){super(e),this.accepted=!0}accept(){throw new Error("Do not call accept() on restore")}acceptWebSocket(){throw new Error("Do not call acceptWebSocket() on restore")}};var bt=class{map=new Map;create(e){class r extends Ce{constructor(a){super();this.sessions=a}accept(){return this.addEventListener("close",()=>this.sessions.unregister(this.server)),this.sessions.register(this.server,this),super.accept()}acceptWebSocket(a,c){return this.sessions.register(this.server,this),super.acceptWebSocket(a,c)}}let s=new r(this);return s.attach(e),s}restore(e){class r extends Ee{constructor(o,i){super(i),o.register(this.server,this)}}return new r(this,e)}restoreAll(e){let r=[];for(let s of e)r.push(this.restore(s));return r}get(e){return this.map.get(e)}select(e){let r=[];for(let s of e){let o=this.map.get(s);o&&r.push(o)}return r}values(){return this.map.values()}keys(){return this.map.keys()}close(e,r,s){let o=this.get(e);return o&&o.close(r,s),this.unregister(e)}*[Symbol.iterator](){yield*this.values()}register(e,r){this.map.set(e,r)}unregister(e){return this.map.delete(e)}};function xt(t){if(t===null||typeof t!="object"||typeof t.handle!="function")throw new TypeError("Handler must implement the Middleware interface (have a handle method).")}var M=class{constructor(e,r,s){this._request=e;this._env=r;this._ctx=s}get request(){return this._request}get env(){return this._env}get ctx(){return this._ctx}isAllowed(e){let r=this.getAllowedMethods();return b(r),e===p||e===O?!0:be(e)&&r.includes(e)}create(e){let r=this.constructor;return new r(e,this.env,this.ctx)}response(e,...r){return new e(...r).response()}static ignite(){return{fetch:(e,r,s)=>new this(e,r,s).fetch()}}};var ge=class extends M{middlewares=[];init(){}use(...e){for(let r of e)xt(r);return this.middlewares.push(...e),this}async fetch(){return await this.init(),this.middlewares.reduceRight((r,s)=>()=>s.handle(this,r),()=>this.isAllowed(this.request.method)?this.dispatch():this.response(v,this))()}};var Se=class extends ge{async fetch(){try{return await super.fetch()}catch(e){return console.error(e),this.response(ee)}}dispatch(){let e=this.request.method;return({GET:()=>this.get(),PUT:()=>this.put(),HEAD:()=>this.head(),POST:()=>this.post(),PATCH:()=>this.patch(),DELETE:()=>this.delete(),OPTIONS:()=>this.options()}[e]??(()=>this.response(v,this)))()}get(){return this.response(A)}put(){return this.response(N,this)}post(){return this.response(N,this)}patch(){return this.response(N,this)}delete(){return this.response(N,this)}options(){return this.response(Z,this)}async head(){let e=this.create(new Request(this.request.url,{method:p,headers:this.request.headers}));return this.response(L,await e.fetch())}getAllowedMethods(){return[p,O,B]}};import{match as Zt}from"path-to-regexp";var Re=class{routes=[];add(e){for(let[r,s,o]of e){let i=Zt(s);this.routes.push({method:r,matcher:i,handler:o})}}match(e,r){let s=new URL(r).pathname;for(let o of this){if(o.method!==e)continue;let i=o.matcher(s);if(i)return{route:o,params:i.params}}return null}*[Symbol.iterator](){yield*this.routes}};var Nt=class t extends Se{_routes=new Re;route(e,r,s){return this.routes([[e,r,s]]),this}routes(e){return this._routes.add(e),this}async dispatch(){let e=this._routes.match(this.request.method,this.request.url);if(!e)return super.dispatch();let{handler:r}=e.route;return t.isWorkerClass(r)?new r(this.request,this.env,this.ctx).fetch():r.call(this,e.params)}static isWorkerClass(e){return Object.prototype.isPrototypeOf.call(M.prototype,e.prototype)}put(){return this.response(A)}post(){return this.response(A)}patch(){return this.response(A)}delete(){return this.response(A)}};export{K as BadRequest,Se as BasicWorker,R as CacheControl,V as CopyResponse,or as DELETE,rt as Forbidden,p as GET,O as HEAD,L as Head,Je as HtmlResponse,l as HttpError,ee as InternalServerError,J as JsonResponse,F as Method,v as MethodNotAllowed,N as MethodNotImplemented,A as NotFound,ye as NotImplemented,H as NotModified,B as OPTIONS,we as OctetStream,Z as Options,sr as PATCH,rr as POST,tr as PUT,W as PreconditionFailed,Qe as R2ObjectStream,Nt as RouteWorker,st as ServiceUnavailable,h as StatusCodes,U as SuccessResponse,Ze as TextResponse,He as Time,tt as Unauthorized,Q as UpgradeRequired,bt as WebSocketSessions,et as WebSocketUpgrade,m as WorkerResponse,Qs as cache,Ro as cors,Pe as sortSearchParams,Er as stripSearchParams,Lo as websocket};
2
2
  //# sourceMappingURL=index.js.map