@adonix.org/cloud-spark 0.0.182 → 0.0.183
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.d.ts +37 -12
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +8 -8
package/dist/index.d.ts
CHANGED
|
@@ -368,7 +368,7 @@ type RouteTable = Iterable<RouteTuple>;
|
|
|
368
368
|
* This middleware:
|
|
369
369
|
* - Caches `GET` requests **only**.
|
|
370
370
|
* - Respects the `Vary` header of responses, ensuring that requests
|
|
371
|
-
* with different headers (e.g., `
|
|
371
|
+
* with different headers (e.g., `Accept-Language`) receive the correct cached response.
|
|
372
372
|
* - Skips caching for non-cacheable responses (e.g., error responses or
|
|
373
373
|
* responses with `Vary: *`).
|
|
374
374
|
*
|
|
@@ -467,7 +467,6 @@ type ExtendedEventType = keyof ExtendedEventMap;
|
|
|
467
467
|
type ExtendedEventListener<K extends ExtendedEventType> = (ev: ExtendedEventMap[K]) => void;
|
|
468
468
|
/**
|
|
469
469
|
* Represents a user-defined attachment object that can be associated with a WebSocket connection.
|
|
470
|
-
* Typically used to store metadata or state for the connection.
|
|
471
470
|
*/
|
|
472
471
|
type WSAttachment = object;
|
|
473
472
|
/**
|
|
@@ -489,14 +488,13 @@ interface WebSocketConnection<A extends WSAttachment> {
|
|
|
489
488
|
isState(...states: number[]): boolean;
|
|
490
489
|
/**
|
|
491
490
|
* Accepts the WebSocket connection if not already accepted.
|
|
492
|
-
* Typically called internally after upgrade validation.
|
|
493
491
|
*
|
|
494
492
|
* @returns The readonly native WebSocket instance.
|
|
495
493
|
*/
|
|
496
494
|
accept(): Readonly<WebSocket>;
|
|
497
495
|
/**
|
|
498
496
|
* Accepts the WebSocket connection in the context of a Durable Object.
|
|
499
|
-
* Optionally associates tags for
|
|
497
|
+
* Optionally associates tags for filtering.
|
|
500
498
|
*
|
|
501
499
|
* @param ctx - DurableObjectState for the WebSocket.
|
|
502
500
|
* @param tags - Optional list of string tags.
|
|
@@ -505,12 +503,17 @@ interface WebSocketConnection<A extends WSAttachment> {
|
|
|
505
503
|
acceptWebSocket(ctx: DurableObjectState, tags?: string[]): Readonly<WebSocket>;
|
|
506
504
|
/**
|
|
507
505
|
* Retrieves the user-defined attachment object associated with this connection.
|
|
506
|
+
*
|
|
507
|
+
* The returned object is a read-only view of the attachment to prevent
|
|
508
|
+
* accidental mutation. To modify the attachment, call {@link attach}.
|
|
509
|
+
*
|
|
510
|
+
* @returns A read-only view of the current attachment.
|
|
508
511
|
*/
|
|
509
512
|
get attachment(): Readonly<A>;
|
|
510
513
|
/**
|
|
511
514
|
* Attaches a user-defined object to this WebSocket connection.
|
|
512
515
|
*
|
|
513
|
-
* @param attachment - Object containing metadata
|
|
516
|
+
* @param attachment - Object containing the metadata to attach.
|
|
514
517
|
*/
|
|
515
518
|
attach(attachment: A): void;
|
|
516
519
|
/**
|
|
@@ -596,9 +599,29 @@ declare class WebSocketSessions<A extends WSAttachment = WSAttachment> {
|
|
|
596
599
|
* @returns Corresponding `WebSocketConnection` or `undefined` if not managed.
|
|
597
600
|
*/
|
|
598
601
|
get(ws: WebSocket): WebSocketConnection<A> | undefined;
|
|
599
|
-
/**
|
|
602
|
+
/**
|
|
603
|
+
* Selects the managed `WebSocketConnection` objects corresponding to the given WebSockets.
|
|
604
|
+
*
|
|
605
|
+
* @param sockets - Array of WebSocket instances to resolve.
|
|
606
|
+
* @returns Array of corresponding `WebSocketConnection` objects.
|
|
607
|
+
*/
|
|
608
|
+
select(sockets: WebSocket[]): WebSocketConnection<A>[];
|
|
609
|
+
/**
|
|
610
|
+
* Returns an iterator over all active `WebSocketConnection` objects
|
|
611
|
+
* managed by this session.
|
|
612
|
+
*
|
|
613
|
+
* Useful for iterating over all connections to perform actions such as
|
|
614
|
+
* broadcasting messages.
|
|
615
|
+
*
|
|
616
|
+
* @returns Iterable iterator of all active `WebSocketConnection` objects.
|
|
617
|
+
*/
|
|
600
618
|
values(): IterableIterator<WebSocketConnection<A>>;
|
|
601
|
-
/**
|
|
619
|
+
/**
|
|
620
|
+
* Returns an iterator over all active raw `WebSocket` instances
|
|
621
|
+
* currently tracked by this session.
|
|
622
|
+
*
|
|
623
|
+
* @returns Iterable iterator of all active `WebSocket` instances.
|
|
624
|
+
*/
|
|
602
625
|
keys(): IterableIterator<WebSocket>;
|
|
603
626
|
/**
|
|
604
627
|
* Closes a managed WebSocket connection with optional code and reason.
|
|
@@ -613,7 +636,7 @@ declare class WebSocketSessions<A extends WSAttachment = WSAttachment> {
|
|
|
613
636
|
[Symbol.iterator](): IterableIterator<WebSocketConnection<A>>;
|
|
614
637
|
/** Registers a connection internally. */
|
|
615
638
|
private register;
|
|
616
|
-
/**
|
|
639
|
+
/** Un-registers a connection internally. */
|
|
617
640
|
private unregister;
|
|
618
641
|
}
|
|
619
642
|
|
|
@@ -670,9 +693,6 @@ declare abstract class BaseWorker implements Worker {
|
|
|
670
693
|
* - Other methods are allowed only if included in the array returned by
|
|
671
694
|
* `getAllowedMethods()` and are valid HTTP methods.
|
|
672
695
|
*
|
|
673
|
-
* This check is used internally to enforce method constraints while
|
|
674
|
-
* preserving RFC compliance for mandatory methods.
|
|
675
|
-
*
|
|
676
696
|
* @param method - The HTTP method to check (e.g., "GET", "POST").
|
|
677
697
|
* @returns `true` if the method is allowed, `false` otherwise.
|
|
678
698
|
*/
|
|
@@ -833,7 +853,8 @@ declare abstract class RouteWorker extends BasicWorker {
|
|
|
833
853
|
* - If the handler is a Worker class, a new instance is created and its `fetch()` is called.
|
|
834
854
|
* - If the handler is a callback function, it is invoked with the extracted path parameters.
|
|
835
855
|
*
|
|
836
|
-
* If no route matches, the request is passed to the
|
|
856
|
+
* If no route matches, the request is passed to the superclass ({@link BasicWorker})
|
|
857
|
+
* `dispatch()` handler.
|
|
837
858
|
*
|
|
838
859
|
* @returns A `Promise<Response>` from the matched handler or parent dispatch.
|
|
839
860
|
*/
|
|
@@ -847,6 +868,10 @@ declare abstract class RouteWorker extends BasicWorker {
|
|
|
847
868
|
* @returns `true` if `handler` is a subclass of `BaseWorker` at runtime, `false` otherwise.
|
|
848
869
|
*/
|
|
849
870
|
private static isWorkerClass;
|
|
871
|
+
protected put(): Promise<Response>;
|
|
872
|
+
protected post(): Promise<Response>;
|
|
873
|
+
protected patch(): Promise<Response>;
|
|
874
|
+
protected delete(): Promise<Response>;
|
|
850
875
|
}
|
|
851
876
|
|
|
852
877
|
/**
|
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 q=(c=>(c.GET="GET",c.PUT="PUT",c.HEAD="HEAD",c.POST="POST",c.PATCH="PATCH",c.DELETE="DELETE",c.OPTIONS="OPTIONS",c))(q||{}),{GET:u,PUT:tr,HEAD:O,POST:rr,PATCH:sr,DELETE:or,OPTIONS:B}=q;var He={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};function F(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 b(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])=>b(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 z=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"},Me=[n.CONTENT_TYPE,n.CONTENT_LENGTH,n.CONTENT_RANGE,n.CONTENT_ENCODING,n.CONTENT_LANGUAGE,n.CONTENT_DISPOSITION,n.CONTENT_MD5],ke=[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(b);if(!o.length){t.delete(e);return}t.set(e,o.join(", "))}function j(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(b)}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!==u||t.headers.has(n.AUTHORIZATION)||t.headers.has(n.COOKIE)||w(t.headers)["no-store"]||!e.headers.has(n.CACHE_CONTROL))return!1;let s=w(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)||Oe(e).includes(Lt))return!1;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 w(t){return R.parse(t.get(n.CACHE_CONTROL)??"")}function Oe(t){return y(d(t.headers,n.VARY))}function y(t){let e=t.map(r=>r.toLowerCase()).filter(r=>r!==n.ACCEPT_ENCODING).sort(b);return Array.from(new Set(e))}function _(t,e,r){let s=[],o=y(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&&!Be(t,e,Ve)}function qe(t,e){return Be(t,Fe(e),Ve)}function Be(t,...e){return t.some(r=>e.includes(r))}function $(t){if(!C(t))return;let e=Date.parse(t);return Number.isNaN(e)?void 0:e}function Fe(t){return t.startsWith(Ge)?t.slice(2):t}function Te(t){return{ifMatch:d(t,n.IF_MATCH).filter(e=>!e.startsWith(Ge)),ifNoneMatch:d(t,n.IF_NONE_MATCH).map(Fe),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}=Te(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 X=class{async apply(e,r){let s=w(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 Mt=new Set(Object.values(q));function be(t){return C(t)&&Mt.has(t)}function kt(t){return Array.isArray(t)&&t.every(be)}function T(t){if(!kt(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 p}from"http-status-codes";var k="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 D(t,e){return!e||t.toLowerCase().includes("charset=")?t:`${t}; charset=${e.toLowerCase()}`}var xe=class{headers=new Headers;status=p.OK;statusText;webSocket;mediaType=D("text/plain",k);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){j(this.headers,e,r)}addContentType(){this.headers.get(n.CONTENT_TYPE)||this.setHeader(n.CONTENT_TYPE,this.mediaType)}filterHeaders(){this.status===p.NO_CONTENT?Ae(this.headers,ke):this.status===p.NOT_MODIFIED&&Ae(this.headers,Me)}},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=[p.NO_CONTENT,p.NOT_MODIFIED].includes(this.status)?null:this.body;return r&&this.addContentType(),this.filterHeaders(),new Response(r,this.responseInit)}},G=class extends m{constructor(e,r){super(e.body,r),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},I=class extends m{constructor(e){super(),this.status=p.NOT_MODIFIED,this.headers=new Headers(e.headers)}},V=class extends m{constructor(e=null,r,s=p.OK){super(e,r),this.status=s}},Y=class extends V{constructor(e={},r,s=p.OK){super(JSON.stringify(e),r,s),this.mediaType=D("application/json",k)}},Je=class extends V{constructor(e,r,s=p.OK,o=k){super(e,r,s),this.mediaType=D("text/html",o)}},Ze=class extends V{constructor(e,r,s=p.OK,o=k){super(e,r,s),this.mediaType=D("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=p.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=p.SWITCHING_PROTOCOLS,this.webSocket=e}},H=class extends m{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers)}},J=class extends m{constructor(e){let r=Array.from(new Set([u,O,...e.getAllowedMethods()]));T(r),super(),this.status=p.NO_CONTENT,this.setHeader(n.ALLOW,r)}};var l=class extends Y{constructor(r,s){let o={status:r,error:Gt(r),details:s??""};super(o,R.DISABLE,r);this.details=s}},U=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)}},Z=class extends l{constructor(e){super(g.NOT_FOUND,e)}},L=class extends l{constructor(e){let r=e.getAllowedMethods();T(r),super(g.METHOD_NOT_ALLOWED,`${e.request.method} method not allowed.`),this.setHeader(n.ALLOW,r)}},v=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)}},x=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 W=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=Te(e.request.headers);return this.response(s,o,i)}};var te=class extends W{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 v(`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 I(e).response()}};var oe=class{async apply(e,r){if(e.request.method===u)return r();if(e.request.method===O){let s=await r();return s?new H(s).response():void 0}}};var ne=class extends W{getHeader(e){return $(e.headers.get(n.LAST_MODIFIED))}},ie=class extends ne{async response(e,r,s){let o=$(s.ifModifiedSince);if(o===void 0)return e;if(r<=o)return new I(e).response()}},ae=class extends ne{async response(e,r,s){let o=$(s.ifUnmodifiedSince);return o===void 0?e:r>o?new v(`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 ue=class{async apply(e,r){let s=e.request.headers;if(!s.has(n.AUTHORIZATION)&&!s.has(n.COOKIE))return r()}};var pe=class{async apply(e,r){if(!e.request.headers.has(n.UPGRADE))return r()}};var A=class t extends m{_isModified=!1;constructor(e){let r=y(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(y(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,y(e)),this._isModified=this.vary.length!==r}static isVariantResponse(e){return e.headers.has(n.INTERNAL_VARIANT_SET)}expireAfter(e){let r=w(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 z().use(new X).use(new oe).use(new pe).use(new ue).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(!A.isVariantResponse(o))return o;let i=A.restore(o).vary,a=_(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=Oe(i),c=await e.match(o),wt=c&&A.isVariantResponse(c);if(!c){if(a.length===0){await e.put(o,i);return}let S=A.new(a);S.expireAfter(i),await e.put(o,await S.response()),await e.put(_(r,S.vary,o),i);return}if(wt){let S=A.restore(c);S.expireAfter(i),a.length>0&&(S.append(a),S.isModified&&await e.put(o,await S.response())),await e.put(_(r,S.vary,o),i);return}if(a.length===0){await e.put(o,i);return}let K=A.new(a);K.expireAfter(c),K.expireAfter(i),await e.put(o,await K.response()),await e.put(_(r,K.vary,o),i),await e.put(_(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&&!F(e.allowedOrigins))throw new TypeError("CorsInit.allowedOrigins must be a string array.");if(e.allowedHeaders!==void 0&&!F(e.allowedHeaders))throw new TypeError("CorsInit.allowedHeaders must be a string array.");if(e.exposedHeaders!==void 0&&!F(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 G(t),o=ht(e.request);return ft(s.headers),pt(s.headers,r),o&&(dt(s.headers,r,o),lt(s.headers,r,o),Kt(s.headers,e),Bt(s.headers,r),qt(s.headers,r)),s.response()}async function ut(t,e,r){let s=new G(t),o=ht(e.request);return ft(s.headers),pt(s.headers,r),o&&(dt(s.headers,r,o),lt(s.headers,r,o),Ft(s.headers,r)),s.response()}function pt(t,e){_e(e)||j(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();T(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 Bt(t,e){f(t,n.ACCESS_CONTROL_ALLOW_HEADERS,e.allowedHeaders)}function Ft(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:ut(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!==u||!this.isMatch(e.request))return r();let s=e.request.headers;return Ct(s)?Et(s)?gt(s)?r():new Q().response():new U("Missing or invalid 'Upgrade' header").response():new U("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 N={NORMAL:1e3,NO_STATUS:1005,ABNORMAL:1006,TLS_HANDSHAKE:1015},At=new Set([N.NO_STATUS,N.ABNORMAL,N.TLS_HANDSHAKE]);function Ot(t){return E(t)?Yt(t)&&!Jt(t)?t:N.NORMAL:N.NORMAL}function Yt(t){return t>=N.NORMAL&&t<=4999}function Jt(t){return At.has(t)}function Tt(t){if(C(t))return t.replaceAll(/[^\x20-\x7E]/g,"").slice(0,123)}var P=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(Ot(e),Tt(r))}onclose=e=>{this.close(e.code,e.reason)}};var Ce=class extends P{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 P{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)}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 T(r),e===u||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}fetch(){return this.middlewares.reduceRight((r,s)=>()=>s.handle(this,r),()=>this.isAllowed(this.request.method)?this.dispatch():this.response(L,this))()}};var Se=class extends ge{async fetch(){try{return await this.init(),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(L,this)))()}get(){return this.response(Z)}put(){return this.response(x,this)}post(){return this.response(x,this)}patch(){return this.response(x,this)}delete(){return this.response(x,this)}options(){return this.response(J,this)}async head(){let e=this.create(new Request(this.request.url,{method:u,headers:this.request.headers}));return this.response(H,await e.fetch())}getAllowedMethods(){return[u,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)}};export{U as BadRequest,Se as BasicWorker,R as CacheControl,G as CopyResponse,or as DELETE,rt as Forbidden,u as GET,O as HEAD,H as Head,Je as HtmlResponse,l as HttpError,ee as InternalServerError,Y as JsonResponse,q as Method,L as MethodNotAllowed,x as MethodNotImplemented,Z as NotFound,ye as NotImplemented,I as NotModified,B as OPTIONS,we as OctetStream,J as Options,sr as PATCH,rr as POST,tr as PUT,v as PreconditionFailed,Qe as R2ObjectStream,Nt as RouteWorker,st as ServiceUnavailable,h as StatusCodes,V 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}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};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|