@adonix.org/cloud-spark 2.0.8 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cors.js CHANGED
@@ -1,2 +1,2 @@
1
- import D from'cache-control-parser';function c(r){return Array.isArray(r)&&r.every(t=>typeof t=="string")}function g(r){return typeof r=="string"}function d(r){return typeof r=="number"&&!Number.isNaN(r)}function L(r){return typeof r=="boolean"}function H(r){if(r===void 0)return;if(typeof r!="object"||r===null)throw new TypeError("CorsInit must be an object.");let t=r;if(t.allowedOrigins!==void 0&&!c(t.allowedOrigins))throw new TypeError("CorsInit.allowedOrigins must be a string array.");if(t.allowedHeaders!==void 0&&!c(t.allowedHeaders))throw new TypeError("CorsInit.allowedHeaders must be a string array.");if(t.exposedHeaders!==void 0&&!c(t.exposedHeaders))throw new TypeError("CorsInit.exposedHeaders must be a string array.");if(t.allowCredentials!==void 0&&!L(t.allowCredentials))throw new TypeError("CorsInit.allowCredentials must be a boolean.");if(t.maxAge!==void 0&&!d(t.maxAge))throw new TypeError("CorsInit.maxAge must be a number.")}var l=(T=>(T.GET="GET",T.PUT="PUT",T.HEAD="HEAD",T.POST="POST",T.PATCH="PATCH",T.DELETE="DELETE",T.OPTIONS="OPTIONS",T))(l||{}),{GET:ne,PUT:ie,HEAD:oe,POST:se,PATCH:Ee,DELETE:Te,OPTIONS:x}=l;var u={parse:D.parse,stringify:D.stringify,DISABLE:Object.freeze({"no-cache":true,"no-store":true,"must-revalidate":true,"max-age":0})};var _=(e=>(e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.FOUND=302]="FOUND",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",e))(_||{});var w={Minute:60};var i={CACHE_CONTROL:"cache-control",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",ORIGIN:"origin",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",UPGRADE:"upgrade"},y=[i.CONTENT_TYPE,i.CONTENT_LENGTH,i.CONTENT_RANGE,i.CONTENT_ENCODING,i.CONTENT_LANGUAGE,i.CONTENT_DISPOSITION,i.CONTENT_MD5],P=[i.CONTENT_LENGTH,i.CONTENT_RANGE];var N="*",M=[101,100,102,103,301,302,303,307,308],b={allowedOrigins:[N],allowedHeaders:[i.CONTENT_TYPE],exposedHeaders:[],allowCredentials:false,maxAge:5*w.Minute};var V=new Set(Object.values(l));function X(r){return g(r)&&V.has(r)}function j(r){return Array.isArray(r)&&r.every(X)}function G(r){if(!j(r)){let t=Array.isArray(r)?JSON.stringify(r):String(r);throw new TypeError(`Invalid method array: ${t}`)}}function f(r,t){return r<t?-1:r>t?1:0}function E(r,t,n){let o=Array.isArray(n)?n:[n],s=Array.from(new Set(o.map(a=>a.trim()))).filter(a=>a.length).sort(f);if(!s.length){r.delete(t);return}r.set(t,s.join(", "));}function p(r,t,n){let o=Array.isArray(n)?n:[n];if(o.length===0)return;let a=q(r,t).concat(o.map(Q=>Q.trim()));E(r,t,a);}function q(r,t){let n=r.get(t)?.split(",").map(o=>o.trim()).filter(o=>o.length>0)??[];return Array.from(new Set(n)).sort(f)}function R(r,t){for(let n of t)r.delete(n);}function S(r){return _[r].toLowerCase().replaceAll("_"," ").replaceAll(/\b\w/g,t=>t.toUpperCase())}var I=class{headers=new Headers;status=200;statusText;webSocket;mediaType="text/plain; charset=utf-8";get responseInit(){return {headers:this.headers,status:this.status,statusText:this.statusText??S(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(t,n){E(this.headers,t,n);}mergeHeader(t,n){p(this.headers,t,n);}addContentType(){this.headers.get(i.CONTENT_TYPE)||this.setHeader(i.CONTENT_TYPE,this.mediaType);}filterHeaders(){this.status===204?R(this.headers,P):this.status===304&&R(this.headers,y);}},m=class extends I{constructor(n){super();this.cache=n;}addCacheHeader(){this.cache&&this.setHeader(i.CACHE_CONTROL,u.stringify(this.cache));}},C=class extends m{constructor(n=null,o){super(o);this.body=n;}async response(){this.addCacheHeader();let n=[204,304].includes(this.status)?null:this.body;return n&&this.addContentType(),this.filterHeaders(),new Response(n,this.responseInit)}},O=class extends C{constructor(t,n){super(t.body,n),this.status=t.status,this.statusText=t.statusText,this.headers=new Headers(t.headers);}};function U(r,t,n){let o=new O(r),s=K(t.request);return Y(o.headers),F(o.headers,n),s&&(k(o.headers,n,s),v(o.headers,n,s),z(o.headers,t),J(o.headers,n),$(o.headers,n)),o.response()}function W(r,t,n){let o=new O(r),s=K(t.request);return Y(o.headers),F(o.headers,n),s&&(k(o.headers,n,s),v(o.headers,n,s),Z(o.headers,n)),o.response()}function F(r,t){h(t)||p(r,i.VARY,i.ORIGIN);}function k(r,t,n){if(h(t)){E(r,i.ACCESS_CONTROL_ALLOW_ORIGIN,N);return}t.allowedOrigins.includes(n)&&E(r,i.ACCESS_CONTROL_ALLOW_ORIGIN,n);}function v(r,t,n){t.allowCredentials&&(h(t)||t.allowedOrigins.includes(n)&&E(r,i.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true"));}function z(r,t){let n=t.getAllowedMethods();G(n),E(r,i.ACCESS_CONTROL_ALLOW_METHODS,n);}function $(r,t){let n=Math.max(0,Math.floor(t.maxAge));E(r,i.ACCESS_CONTROL_MAX_AGE,String(n));}function J(r,t){E(r,i.ACCESS_CONTROL_ALLOW_HEADERS,t.allowedHeaders);}function Z(r,t){E(r,i.ACCESS_CONTROL_EXPOSE_HEADERS,t.exposedHeaders);}function h(r){return r.allowedOrigins.includes(N)}function Y(r){r.delete(i.ACCESS_CONTROL_MAX_AGE),r.delete(i.ACCESS_CONTROL_ALLOW_ORIGIN),r.delete(i.ACCESS_CONTROL_ALLOW_HEADERS),r.delete(i.ACCESS_CONTROL_ALLOW_METHODS),r.delete(i.ACCESS_CONTROL_EXPOSE_HEADERS),r.delete(i.ACCESS_CONTROL_ALLOW_CREDENTIALS);}function B(r){let{status:t,headers:n}=r;return !!(M.includes(t)||n.has(i.UPGRADE))}function K(r){let t=r.headers.get(i.ORIGIN)?.trim();if(!t||t==="null")return null;try{return new URL(t).origin}catch{return null}}var A=class{config;constructor(t){this.config={...b,...t};}async handle(t,n){let o=await n();return t.request.method===x?U(o,t,this.config):B(o)?o:W(o,t,this.config)}};function Be(r){return H(r),new A(r)}export{Be as cors};//# sourceMappingURL=cors.js.map
1
+ import D from'cache-control-parser';function c(r){return Array.isArray(r)&&r.every(t=>typeof t=="string")}function g(r){return typeof r=="string"}function d(r){return typeof r=="number"&&!Number.isNaN(r)}function L(r){return typeof r=="boolean"}function H(r){if(r===void 0)return;if(typeof r!="object"||r===null)throw new TypeError("CorsInit must be an object.");let t=r;if(t.allowedOrigins!==void 0&&!c(t.allowedOrigins))throw new TypeError("CorsInit.allowedOrigins must be a string array.");if(t.allowedHeaders!==void 0&&!c(t.allowedHeaders))throw new TypeError("CorsInit.allowedHeaders must be a string array.");if(t.exposedHeaders!==void 0&&!c(t.exposedHeaders))throw new TypeError("CorsInit.exposedHeaders must be a string array.");if(t.allowCredentials!==void 0&&!L(t.allowCredentials))throw new TypeError("CorsInit.allowCredentials must be a boolean.");if(t.maxAge!==void 0&&!d(t.maxAge))throw new TypeError("CorsInit.maxAge must be a number.")}var l=(T=>(T.GET="GET",T.PUT="PUT",T.HEAD="HEAD",T.POST="POST",T.PATCH="PATCH",T.DELETE="DELETE",T.OPTIONS="OPTIONS",T))(l||{}),{GET:ne,PUT:ie,HEAD:oe,POST:se,PATCH:Ee,DELETE:Te,OPTIONS:x}=l;var u={parse:D.parse,stringify:D.stringify,DISABLE:Object.freeze({"no-cache":true,"no-store":true,"must-revalidate":true,"max-age":0})};var A=(e=>(e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.FOUND=302]="FOUND",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",e))(A||{});var y={Minute:60};var i={CACHE_CONTROL:"cache-control",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",ORIGIN:"origin",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",UPGRADE:"upgrade"},w=[i.CONTENT_TYPE,i.CONTENT_LENGTH,i.CONTENT_RANGE,i.CONTENT_ENCODING,i.CONTENT_LANGUAGE,i.CONTENT_DISPOSITION,i.CONTENT_MD5],P=[i.CONTENT_LENGTH,i.CONTENT_RANGE];var N="*",M=[101,100,102,103,301,302,303,307,308],S={allowedOrigins:[N],allowedHeaders:[i.CONTENT_TYPE],exposedHeaders:[],allowCredentials:false,maxAge:5*y.Minute};var V=new Set(Object.values(l));function X(r){return g(r)&&V.has(r)}function q(r){return Array.isArray(r)&&r.every(X)}function b(r){if(!q(r)){let t=Array.isArray(r)?JSON.stringify(r):String(r);throw new TypeError(`Invalid method array: ${t}`)}}function f(r,t){return r<t?-1:r>t?1:0}function E(r,t,n){let o=Array.isArray(n)?n:[n],s=Array.from(new Set(o.map(a=>a.trim()))).filter(a=>a.length).sort(f);if(!s.length){r.delete(t);return}r.set(t,s.join(", "));}function p(r,t,n){let o=Array.isArray(n)?n:[n];if(o.length===0)return;let a=j(r,t).concat(o.map(Q=>Q.trim()));E(r,t,a);}function j(r,t){let n=r.get(t)?.split(",").map(o=>o.trim()).filter(o=>o.length>0)??[];return Array.from(new Set(n)).sort(f)}function R(r,t){for(let n of t)r.delete(n);}function G(r){return A[r].toLowerCase().replaceAll("_"," ").replaceAll(/\b\w/g,t=>t.toUpperCase())}var I=class{headers=new Headers;status=200;statusText;webSocket;mediaType="text/plain; charset=utf-8";get responseInit(){return {headers:this.headers,status:this.status,statusText:this.statusText??G(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(t,n){E(this.headers,t,n);}mergeHeader(t,n){p(this.headers,t,n);}addContentType(){this.headers.get(i.CONTENT_TYPE)||this.setHeader(i.CONTENT_TYPE,this.mediaType);}filterHeaders(){this.status===204?R(this.headers,P):this.status===304&&R(this.headers,w);}},m=class extends I{constructor(n){super();this.cache=n;}addCacheHeader(){this.cache&&this.setHeader(i.CACHE_CONTROL,u.stringify(this.cache));}},C=class extends m{constructor(n=null,o){super(o);this.body=n;}async response(){this.addCacheHeader();let n=[204,304].includes(this.status)?null:this.body;return n&&this.addContentType(),this.filterHeaders(),new Response(n,this.responseInit)}},O=class extends C{constructor(t,n){super(t.body,n),this.status=t.status,this.statusText=t.statusText,this.headers=new Headers(t.headers);}};function U(r,t,n){let o=new O(r),s=K(t.request);return Y(o.headers),F(o.headers,n),s&&(k(o.headers,n,s),v(o.headers,n,s),z(o.headers,t),J(o.headers,n),$(o.headers,n)),o.response()}function W(r,t,n){let o=new O(r),s=K(t.request);return Y(o.headers),F(o.headers,n),s&&(k(o.headers,n,s),v(o.headers,n,s),Z(o.headers,n)),o.response()}function F(r,t){h(t)||p(r,i.VARY,i.ORIGIN);}function k(r,t,n){if(h(t)){E(r,i.ACCESS_CONTROL_ALLOW_ORIGIN,N);return}t.allowedOrigins.includes(n)&&E(r,i.ACCESS_CONTROL_ALLOW_ORIGIN,n);}function v(r,t,n){t.allowCredentials&&(h(t)||t.allowedOrigins.includes(n)&&E(r,i.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true"));}function z(r,t){let n=t.getAllowedMethods();b(n),E(r,i.ACCESS_CONTROL_ALLOW_METHODS,n);}function $(r,t){let n=Math.max(0,Math.floor(t.maxAge));E(r,i.ACCESS_CONTROL_MAX_AGE,String(n));}function J(r,t){E(r,i.ACCESS_CONTROL_ALLOW_HEADERS,t.allowedHeaders);}function Z(r,t){E(r,i.ACCESS_CONTROL_EXPOSE_HEADERS,t.exposedHeaders);}function h(r){return r.allowedOrigins.includes(N)}function Y(r){r.delete(i.ACCESS_CONTROL_MAX_AGE),r.delete(i.ACCESS_CONTROL_ALLOW_ORIGIN),r.delete(i.ACCESS_CONTROL_ALLOW_HEADERS),r.delete(i.ACCESS_CONTROL_ALLOW_METHODS),r.delete(i.ACCESS_CONTROL_EXPOSE_HEADERS),r.delete(i.ACCESS_CONTROL_ALLOW_CREDENTIALS);}function B(r){let{status:t,headers:n}=r;return !!(M.includes(t)||n.has(i.UPGRADE))}function K(r){let t=r.headers.get(i.ORIGIN)?.trim();if(!t||t==="null")return null;try{return new URL(t).origin}catch{return null}}var _=class{config;constructor(t){this.config={...S,...t};}async handle(t,n){let o=await n();return t.request.method===x?U(o,t,this.config):B(o)?o:W(o,t,this.config)}};function Be(r){return H(r),new _(r)}export{Be as cors};//# sourceMappingURL=cors.js.map
2
2
  //# sourceMappingURL=cors.js.map
package/dist/cors.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/guards/basic.ts","../src/guards/cors.ts","../src/constants/methods.ts","../src/constants/cache.ts","../src/constants/status.ts","../src/constants/time.ts","../src/constants/headers.ts","../src/middleware/cors/constants.ts","../src/guards/methods.ts","../src/utils/compare.ts","../src/utils/headers.ts","../src/utils/reasons.ts","../src/responses.ts","../src/middleware/cors/utils.ts","../src/middleware/cors/handler.ts","../src/middleware/cors/cors.ts"],"names":["isStringArray","value","item","isString","isNumber","isBoolean","assertCorsInit","obj","Method","GET","PUT","HEAD","POST","PATCH","DELETE","OPTIONS","CacheControl","CacheLib","StatusCodes","Time","HttpHeader","FORBIDDEN_304_HEADERS","FORBIDDEN_204_HEADERS","ALLOW_ALL_ORIGINS","SKIP_CORS_STATUSES","defaultCorsConfig","METHOD_SET","isMethod","isMethodArray","assertMethods","desc","lexCompare","a","b","setHeader","headers","key","raw","values","v","mergeHeader","merged","getHeaderValues","filterHeaders","keys","getReasonPhrase","status","c","BaseResponse","CacheResponse","cache","WorkerResponse","body","CopyResponse","response","options","worker","cors","copy","origin","getOrigin","deleteCorsHeaders","setVaryOrigin","setAllowOrigin","setAllowCredentials","setAllowMethods","setAllowHeaders","setMaxAge","apply","setExposedHeaders","allowAllOrigins","allowed","maxAge","skipCors","request","CorsHandler","init","next"],"mappings":"oCAsBO,SAASA,EAAcC,CAAAA,CAAmC,CAC7D,OAAO,KAAA,CAAM,OAAA,CAAQA,CAAK,CAAA,EAAKA,CAAAA,CAAM,KAAA,CAAOC,CAAAA,EAAS,OAAOA,CAAAA,EAAS,QAAQ,CACjF,CAQO,SAASC,EAASF,CAAAA,CAAiC,CACtD,OAAO,OAAOA,GAAU,QAC5B,CAYO,SAASG,CAAAA,CAASH,CAAAA,CAAiC,CACtD,OAAO,OAAOA,GAAU,QAAA,EAAY,CAAC,OAAO,KAAA,CAAMA,CAAK,CAC3D,CAQO,SAASI,EAAUJ,CAAAA,CAAkC,CACxD,OAAO,OAAOA,GAAU,SAC5B,CC9BO,SAASK,CAAAA,CAAeL,CAAAA,CAA2C,CACtE,GAAIA,CAAAA,GAAU,OAAW,OAEzB,GAAI,OAAOA,CAAAA,EAAU,QAAA,EAAYA,IAAU,IAAA,CACvC,MAAM,IAAI,SAAA,CAAU,6BAA6B,CAAA,CAGrD,IAAMM,EAAMN,CAAAA,CAEZ,GAAIM,EAAI,cAAA,GAAsB,MAAA,EAAa,CAACP,CAAAA,CAAcO,CAAAA,CAAI,cAAiB,CAAA,CAC3E,MAAM,IAAI,SAAA,CAAU,iDAAiD,EAGzE,GAAIA,CAAAA,CAAI,iBAAsB,MAAA,EAAa,CAACP,CAAAA,CAAcO,CAAAA,CAAI,cAAiB,CAAA,CAC3E,MAAM,IAAI,SAAA,CAAU,iDAAiD,EAGzE,GAAIA,CAAAA,CAAI,cAAA,GAAsB,MAAA,EAAa,CAACP,CAAAA,CAAcO,CAAAA,CAAI,cAAiB,CAAA,CAC3E,MAAM,IAAI,SAAA,CAAU,iDAAiD,CAAA,CAGzE,GAAIA,EAAI,gBAAA,GAAwB,MAAA,EAAa,CAACF,CAA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ClD,CAaA,MAAa,MAAA,CAAOpB,EAAgBqB,CAAAA,CAAkD,CAClF,IAAMvB,CAAAA,CAAW,MAAMuB,GAAK,CAE5B,OAAIrB,EAAO,OAAA,CAAQ,MAAA,GAAWzC,EACnBwC,CAAAA,CAAQD,CAAAA,CAAUE,EAAQ,IAAA,CAAK,MAAM,EAG5CiB,CAAAA,CAASnB,CAAQ,CAAA,CAAUA,CAAAA,CAExBc,EAAMd,CAAAA,CAAUE,CAAAA,CAAQ,KAAK,MAAM,CAC9C,CACJ,CAAA,CC/CO,SAASC,GAAKmB,CAAAA,CAA6B,CAC9C,OAAAtE,CAAAA,CAAesE,CAAI,EACZ,IAAID,CAAAA,CAAYC,CAAI,CAC/B","file":"cors.js","sourcesContent":["/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks if the provided value is an array of strings.\n *\n * @param value - The value to check.\n * @returns True if `array` is an array where every item is a string.\n */\nexport function isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\n/**\n * Checks if a value is a string.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a string, otherwise `false`.\n */\nexport function isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n\n/**\n * Checks if a value is a valid number (not NaN).\n *\n * This function returns `true` if the value is of type `number`\n * and is not `NaN`. It works as a type guard for TypeScript.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a number and not `NaN`, otherwise `false`.\n */\nexport function isNumber(value: unknown): value is number {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\n\n/**\n * Checks if a value is a boolean.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a boolean (`true` or `false`), otherwise `false`.\n */\nexport function isBoolean(value: unknown): value is boolean {\n return typeof value === \"boolean\";\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CorsInit } from \"../middleware/cors/interfaces\";\n\nimport { isBoolean, isNumber, isStringArray } from \"./basic\";\n\n/**\n * Throws if the given value is not a valid CorsInit.\n *\n * Checks only the fields that are present, since CorsInit is Partial<CorsConfig>.\n *\n * @param value - The value to check.\n * @throws TypeError If `value` is not a valid {@link CorsInit}.\n */\nexport function assertCorsInit(value: unknown): asserts value is CorsInit {\n if (value === undefined) return;\n\n if (typeof value !== \"object\" || value === null) {\n throw new TypeError(\"CorsInit must be an object.\");\n }\n\n const obj = value as Record<string, unknown>;\n\n if (obj[\"allowedOrigins\"] !== undefined && !isStringArray(obj[\"allowedOrigins\"])) {\n throw new TypeError(\"CorsInit.allowedOrigins must be a string array.\");\n }\n\n if (obj[\"allowedHeaders\"] !== undefined && !isStringArray(obj[\"allowedHeaders\"])) {\n throw new TypeError(\"CorsInit.allowedHeaders must be a string array.\");\n }\n\n if (obj[\"exposedHeaders\"] !== undefined && !isStringArray(obj[\"exposedHeaders\"])) {\n throw new TypeError(\"CorsInit.exposedHeaders must be a string array.\");\n }\n\n if (obj[\"allowCredentials\"] !== undefined && !isBoolean(obj[\"allowCredentials\"])) {\n throw new TypeError(\"CorsInit.allowCredentials must be a boolean.\");\n }\n\n if (obj[\"maxAge\"] !== undefined && !isNumber(obj[\"maxAge\"])) {\n throw new TypeError(\"CorsInit.maxAge must be a number.\");\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Standard HTTP request methods.\n */\nexport enum Method {\n GET = \"GET\",\n PUT = \"PUT\",\n HEAD = \"HEAD\",\n POST = \"POST\",\n PATCH = \"PATCH\",\n DELETE = \"DELETE\",\n OPTIONS = \"OPTIONS\",\n}\n\n/**\n * Shorthand constants for each HTTP method.\n *\n * These are equivalent to the corresponding enum members in `Method`.\n * For example, `GET === Method.GET`.\n */\nexport const { GET, PUT, HEAD, POST, PATCH, DELETE, OPTIONS } = Method;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport CacheLib from \"cache-control-parser\";\n\n/**\n * @see {@link https://github.com/etienne-martin/cache-control-parser | cache-control-parser}\n */\nexport type CacheControl = CacheLib.CacheControl;\nexport const CacheControl = {\n parse: CacheLib.parse,\n stringify: CacheLib.stringify,\n\n /** A CacheControl directive that disables all caching. */\n DISABLE: Object.freeze({\n \"no-cache\": true,\n \"no-store\": true,\n \"must-revalidate\": true,\n \"max-age\": 0,\n }) satisfies CacheControl,\n};\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * https://github.com/prettymuchbryce/http-status-codes\n */\nexport enum StatusCodes {\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1\n *\n * This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.\n */\n CONTINUE = 100,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2\n *\n * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too.\n */\n SWITCHING_PROTOCOLS = 101,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1\n *\n * This code indicates that the server has received and is processing the request, but no response is available yet.\n */\n PROCESSING = 102,\n /**\n * Official Documentation @ https://www.rfc-editor.org/rfc/rfc8297#page-3\n *\n * This code indicates to the client that the server is likely to send a final response with the header fields included in the informational response.\n */\n EARLY_HINTS = 103,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1\n *\n * The request has succeeded. The meaning of a success varies depending on the HTTP method:\n * GET: The resource has been fetched and is transmitted in the message body.\n * HEAD: The entity headers are in the message body.\n * POST: The resource describing the result of the action is transmitted in the message body.\n * TRACE: The message body contains the request message as received by the server\n */\n OK = 200,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2\n *\n * The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request.\n */\n CREATED = 201,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3\n *\n * The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.\n */\n ACCEPTED = 202,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4\n *\n * This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response.\n */\n NON_AUTHORITATIVE_INFORMATION = 203,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5\n *\n * There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.\n */\n NO_CONTENT = 204,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6\n *\n * This response code is sent after accomplishing request to tell user agent reset document view which sent this request.\n */\n RESET_CONTENT = 205,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1\n *\n * This response code is used because of range header sent by the client to separate download into multiple streams.\n */\n PARTIAL_CONTENT = 206,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2\n *\n * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate.\n */\n MULTI_STATUS = 207,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1\n *\n * The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses.\n */\n MULTIPLE_CHOICES = 300,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2\n *\n * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response.\n */\n MOVED_PERMANENTLY = 301,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3\n *\n * This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.\n */\n FOUND = 302,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4\n *\n * The 302 (Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests.\n */\n SEE_OTHER = 303,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1\n *\n * This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response.\n */\n NOT_MODIFIED = 304,\n /**\n * @deprecated\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6\n *\n * Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.\n */\n USE_PROXY = 305,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7\n *\n * Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.\n */\n TEMPORARY_REDIRECT = 307,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3\n *\n * This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.\n */\n PERMANENT_REDIRECT = 308,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1\n *\n * This response means that server could not understand the request due to invalid syntax.\n */\n BAD_REQUEST = 400,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1\n *\n * Although the HTTP standard specifies \"unauthorized\", semantically this response means \"unauthenticated\". That is, the client must authenticate itself to get the requested response.\n */\n UNAUTHORIZED = 401,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2\n *\n * This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently.\n */\n PAYMENT_REQUIRED = 402,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3\n *\n * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server.\n */\n FORBIDDEN = 403,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4\n *\n * The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurrence on the web.\n */\n NOT_FOUND = 404,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5\n *\n * The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.\n */\n METHOD_NOT_ALLOWED = 405,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6\n *\n * This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent.\n */\n NOT_ACCEPTABLE = 406,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2\n *\n * This is similar to 401 but authentication is needed to be done by a proxy.\n */\n PROXY_AUTHENTICATION_REQUIRED = 407,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7\n *\n * This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.\n */\n REQUEST_TIMEOUT = 408,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8\n *\n * This response is sent when a request conflicts with the current state of the server.\n */\n CONFLICT = 409,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9\n *\n * This response would be sent when the requested content has been permenently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for \"limited-time, promotional services\". APIs should not feel compelled to indicate resources that have been deleted with this status code.\n */\n GONE = 410,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10\n *\n * The server rejected the request because the Content-Length header field is not defined and the server requires it.\n */\n LENGTH_REQUIRED = 411,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2\n *\n * The client has indicated preconditions in its headers which the server does not meet.\n */\n PRECONDITION_FAILED = 412,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11\n *\n * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field.\n */\n REQUEST_TOO_LONG = 413,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12\n *\n * The URI requested by the client is longer than the server is willing to interpret.\n */\n REQUEST_URI_TOO_LONG = 414,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13\n *\n * The media format of the requested data is not supported by the server, so the server is rejecting the request.\n */\n UNSUPPORTED_MEDIA_TYPE = 415,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4\n *\n * The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data.\n */\n REQUESTED_RANGE_NOT_SATISFIABLE = 416,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14\n *\n * This response code means the expectation indicated by the Expect request header field can't be met by the server.\n */\n EXPECTATION_FAILED = 417,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2\n *\n * Any attempt to brew coffee with a teapot should result in the error code \"418 I'm a teapot\". The resulting entity body MAY be short and stout.\n */\n IM_A_TEAPOT = 418,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6\n *\n * The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request which received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action.\n */\n INSUFFICIENT_SPACE_ON_RESOURCE = 419,\n /**\n * @deprecated\n * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt\n *\n * A deprecated response used by the Spring Framework when a method has failed.\n */\n METHOD_FAILURE = 420,\n /**\n * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2\n *\n * Defined in the specification of HTTP/2 to indicate that a server is not able to produce a response for the combination of scheme and authority that are included in the request URI.\n */\n MISDIRECTED_REQUEST = 421,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3\n *\n * The request was well-formed but was unable to be followed due to semantic errors.\n */\n UNPROCESSABLE_ENTITY = 422,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4\n *\n * The resource that is being accessed is locked.\n */\n LOCKED = 423,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5\n *\n * The request failed due to failure of a previous request.\n */\n FAILED_DEPENDENCY = 424,\n /**\n * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.15\n *\n * The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.\n */\n UPGRADE_REQUIRED = 426,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3\n *\n * The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.\n */\n PRECONDITION_REQUIRED = 428,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4\n *\n * The user has sent too many requests in a given amount of time (\"rate limiting\").\n */\n TOO_MANY_REQUESTS = 429,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5\n *\n * The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.\n */\n REQUEST_HEADER_FIELDS_TOO_LARGE = 431,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7725\n *\n * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government.\n */\n UNAVAILABLE_FOR_LEGAL_REASONS = 451,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1\n *\n * The server encountered an unexpected condition that prevented it from fulfilling the request.\n */\n INTERNAL_SERVER_ERROR = 500,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2\n *\n * The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.\n */\n NOT_IMPLEMENTED = 501,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3\n *\n * This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.\n */\n BAD_GATEWAY = 502,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4\n *\n * The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.\n */\n SERVICE_UNAVAILABLE = 503,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5\n *\n * This error response is given when the server is acting as a gateway and cannot get a response in time.\n */\n GATEWAY_TIMEOUT = 504,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6\n *\n * The HTTP version used in the request is not supported by the server.\n */\n HTTP_VERSION_NOT_SUPPORTED = 505,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6\n *\n * The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.\n */\n INSUFFICIENT_STORAGE = 507,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6\n *\n * The 511 status code indicates that the client needs to authenticate to gain network access.\n */\n NETWORK_AUTHENTICATION_REQUIRED = 511,\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Time constants in seconds. Month is approximated as 30 days.\n */\nexport const Time = {\n Second: 1,\n Minute: 60,\n Hour: 3600, // 60 * 60\n Day: 86400, // 60 * 60 * 24\n Week: 604800, // 60 * 60 * 24 * 7\n Month: 2592000, // 60 * 60 * 24 * 30\n Year: 31536000, // 60 * 60 * 24 * 365\n} as const;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Internally used headers.\n */\nexport const HttpHeader = {\n ACCEPT: \"accept\",\n ACCEPT_ENCODING: \"accept-encoding\",\n ACCEPT_LANGUAGE: \"accept-language\",\n ACCEPT_RANGES: \"accept-ranges\",\n ALLOW: \"allow\",\n AUTHORIZATION: \"authorization\",\n CACHE_CONTROL: \"cache-control\",\n CONNECTION: \"connection\",\n CONTENT_DISPOSITION: \"content-disposition\",\n CONTENT_ENCODING: \"content-encoding\",\n CONTENT_LANGUAGE: \"content-language\",\n CONTENT_LENGTH: \"content-length\",\n CONTENT_RANGE: \"content-range\",\n CONTENT_TYPE: \"content-type\",\n CONTENT_MD5: \"content-md5\",\n COOKIE: \"cookie\",\n ETAG: \"etag\",\n IF_MODIFIED_SINCE: \"if-modified-since\",\n IF_NONE_MATCH: \"if-none-match\",\n ORIGIN: \"origin\",\n RANGE: \"range\",\n SET_COOKIE: \"set-cookie\",\n VARY: \"vary\",\n\n // Cors Headers\n ACCESS_CONTROL_ALLOW_CREDENTIALS: \"access-control-allow-credentials\",\n ACCESS_CONTROL_ALLOW_HEADERS: \"access-control-allow-headers\",\n ACCESS_CONTROL_ALLOW_METHODS: \"access-control-allow-methods\",\n ACCESS_CONTROL_ALLOW_ORIGIN: \"access-control-allow-origin\",\n ACCESS_CONTROL_EXPOSE_HEADERS: \"access-control-expose-headers\",\n ACCESS_CONTROL_MAX_AGE: \"access-control-max-age\",\n\n // Websocket Headers\n SEC_WEBSOCKET_VERSION: \"sec-websocket-version\",\n UPGRADE: \"upgrade\",\n\n // Internal Headers\n INTERNAL_VARIANT_SET: \"internal-variant-set\",\n} as const;\n\n/**\n * Headers that must not be sent in 304 Not Modified responses.\n * These are stripped to comply with the HTTP spec.\n */\nexport const FORBIDDEN_304_HEADERS = [\n HttpHeader.CONTENT_TYPE,\n HttpHeader.CONTENT_LENGTH,\n HttpHeader.CONTENT_RANGE,\n HttpHeader.CONTENT_ENCODING,\n HttpHeader.CONTENT_LANGUAGE,\n HttpHeader.CONTENT_DISPOSITION,\n HttpHeader.CONTENT_MD5,\n];\n\n/**\n * Headers that should not be sent in 204 No Content responses.\n * Stripping them is recommended but optional per spec.\n */\nexport const FORBIDDEN_204_HEADERS = [HttpHeader.CONTENT_LENGTH, HttpHeader.CONTENT_RANGE];\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StatusCodes } from \"../../constants\";\nimport { HttpHeader } from \"../../constants/headers\";\nimport { Time } from \"../../constants/time\";\n\nimport { CorsConfig } from \"./interfaces\";\n\n/**\n * A wildcard value used in the CORS `Access-Control-Allow-Origin` header\n * to permit requests from **any** origin.\n */\nexport const ALLOW_ALL_ORIGINS = \"*\";\n\n/**\n * Status codes for which `CORS` should be skipped.\n *\n * Skips `CORS` for:\n * - 101 Switching Protocols (WebSocket upgrade)\n * - 100 Continue\n * - 3xx Redirects (`CORS` is applied to the final URL only)\n */\nexport const SKIP_CORS_STATUSES = [\n StatusCodes.SWITCHING_PROTOCOLS,\n StatusCodes.CONTINUE,\n StatusCodes.PROCESSING,\n StatusCodes.EARLY_HINTS,\n StatusCodes.MOVED_PERMANENTLY,\n StatusCodes.FOUND,\n StatusCodes.SEE_OTHER,\n StatusCodes.TEMPORARY_REDIRECT,\n StatusCodes.PERMANENT_REDIRECT,\n];\n\n/**\n * Default configuration for `CORS` middleware.\n */\nexport const defaultCorsConfig: CorsConfig = {\n allowedOrigins: [ALLOW_ALL_ORIGINS],\n allowedHeaders: [HttpHeader.CONTENT_TYPE],\n exposedHeaders: [],\n allowCredentials: false,\n maxAge: 5 * Time.Minute,\n} as const;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Method } from \"../constants/methods\";\n\nimport { isString } from \"./basic\";\n\n/**\n * A set containing all supported HTTP methods.\n *\n * Useful for runtime checks like validating request methods.\n */\nconst METHOD_SET: Set<string> = new Set(Object.values(Method));\n\n/**\n * Type guard that checks if a string is a valid HTTP method.\n *\n * @param value - The string to test.\n * @returns True if `value` is a recognized HTTP method.\n */\nexport function isMethod(value: unknown): value is Method {\n return isString(value) && METHOD_SET.has(value);\n}\n\n/**\n * Checks if a value is an array of valid HTTP methods.\n *\n * Each element is verified using the `isMethod` type guard.\n *\n * @param value - The value to check.\n * @returns `true` if `value` is an array and every element is a valid `Method`, otherwise `false`.\n */\nexport function isMethodArray(value: unknown): value is Method[] {\n return Array.isArray(value) && value.every(isMethod);\n}\n\n/**\n * Asserts that a value is an array of valid HTTP methods.\n *\n * This function uses {@link isMethodArray} to validate the input. If the\n * value is not an array of `Method` elements, it throws a `TypeError`.\n * Otherwise, TypeScript will narrow the type of `value` to `Method[]`\n * within the calling scope.\n *\n * @param value - The value to check.\n * @throws TypeError If `value` is not a valid {@link Method} array.\n */\nexport function assertMethods(value: unknown): asserts value is Method[] {\n if (!isMethodArray(value)) {\n const desc = Array.isArray(value) ? JSON.stringify(value) : String(value);\n throw new TypeError(`Invalid method array: ${desc}`);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Lexicographically compares two strings.\n *\n * This comparator can be used in `Array.prototype.sort()` to produce a\n * consistent, stable ordering of string arrays.\n *\n * @param a - The first string to compare.\n * @param b - The second string to compare.\n * @returns A number indicating the relative order of `a` and `b`.\n */\nexport function lexCompare(a: string, b: string): number {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { lexCompare } from \"./compare\";\n\n/**\n * Sets a header on the given Headers object.\n *\n * - If `value` is an array, any duplicates and empty strings are removed.\n * - If the resulting value is empty, the header is deleted.\n * - Otherwise, values are joined with `\", \"` and set as the header value.\n *\n * @param headers - The Headers object to modify.\n * @param key - The header name to set.\n * @param value - The header value(s) to set. Can be a string or array of strings.\n */\nexport function setHeader(headers: Headers, key: string, value: string | string[]): void {\n const raw = Array.isArray(value) ? value : [value];\n const values = Array.from(new Set(raw.map((v) => v.trim())))\n .filter((v) => v.length)\n .sort(lexCompare);\n\n if (!values.length) {\n headers.delete(key);\n return;\n }\n\n headers.set(key, values.join(\", \"));\n}\n\n/**\n * Merges new value(s) into an existing header on the given Headers object.\n *\n * - Preserves any existing values and adds new ones.\n * - Removes duplicates and trims all values.\n * - If the header does not exist, it is created.\n * - If the resulting value array is empty, the header is deleted.\n *\n * @param headers - The Headers object to modify.\n * @param key - The header name to merge into.\n * @param value - The new header value(s) to add. Can be a string or array of strings.\n */\nexport function mergeHeader(headers: Headers, key: string, value: string | string[]): void {\n const values = Array.isArray(value) ? value : [value];\n if (values.length === 0) return;\n\n const existing = getHeaderValues(headers, key);\n const merged = existing.concat(values.map((v) => v.trim()));\n\n setHeader(headers, key, merged);\n}\n\n/**\n * Returns the values of an HTTP header as an array of strings.\n *\n * This helper:\n * - Retrieves the header value by `key`.\n * - Splits the value on commas.\n * - Trims surrounding whitespace from each entry.\n * - Filters out any empty tokens.\n * - Removes duplicate values (case-sensitive)\n *\n * If the header is not present, an empty array is returned.\n *\n */\nexport function getHeaderValues(headers: Headers, key: string): string[] {\n const values =\n headers\n .get(key)\n ?.split(\",\")\n .map((v) => v.trim())\n .filter((v) => v.length > 0) ?? [];\n return Array.from(new Set(values)).sort(lexCompare);\n}\n\n/**\n * Removes a list of header fields from a {@link Headers} object.\n *\n * @param headers - The {@link Headers} object to modify in place.\n * @param keys - An array of header field names to remove. Header names are\n * matched case-insensitively per the Fetch spec.\n */\nexport function filterHeaders(headers: Headers, keys: string[]): void {\n for (const key of keys) {\n headers.delete(key);\n }\n}\n\n/**\n * Extracts all header names from a `Headers` object, normalizes them,\n * and returns them in a stable, lexicographically sorted array.\n *\n * @param headers - The `Headers` object to extract keys from.\n * @returns A sorted array of lowercase header names.\n */\nexport function getHeaderKeys(headers: Headers): string[] {\n return [...headers.keys()].sort(lexCompare);\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StatusCodes } from \"../constants\";\n\n/**\n * Returns the standard HTTP reason phrase for a status code.\n * Converts enum names (e.g. NOT_FOUND) into title-cased phrases.\n */\nexport function getReasonPhrase(status: StatusCodes): string {\n return StatusCodes[status]\n .toLowerCase()\n .replaceAll(\"_\", \" \")\n .replaceAll(/\\b\\w/g, (c) => c.toUpperCase());\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StatusCodes } from \"./constants\";\nimport { CacheControl } from \"./constants/cache\";\nimport { FORBIDDEN_204_HEADERS, FORBIDDEN_304_HEADERS, HttpHeader } from \"./constants/headers\";\nimport { MediaType, UTF8_CHARSET } from \"./constants/media\";\nimport { GET, HEAD } from \"./constants/methods\";\nimport { assertMethods } from \"./guards/methods\";\nimport { assertOctetStreamInit } from \"./guards/responses\";\nimport { Worker } from \"./interfaces\";\nimport { OctetStreamInit } from \"./interfaces/response\";\nimport { filterHeaders, mergeHeader, setHeader } from \"./utils/headers\";\nimport { withCharset } from \"./utils/media\";\nimport { getReasonPhrase } from \"./utils/reasons\";\n\n/**\n * Base class for building HTTP responses.\n * Manages headers, status, and media type.\n */\nabstract class BaseResponse {\n /** HTTP headers for the response. */\n public headers: Headers = new Headers();\n\n /** HTTP status code (default 200 OK). */\n public status: StatusCodes = StatusCodes.OK;\n\n /** Optional status text. Defaults to standard reason phrase. */\n public statusText?: string;\n\n /** Optional websocket property. */\n public webSocket?: WebSocket | null;\n\n /** Default media type of the response body. */\n public mediaType: string = \"text/plain; charset=utf-8\";\n\n /** Converts current state to ResponseInit for constructing a Response. */\n protected get responseInit(): ResponseInit {\n return {\n headers: this.headers,\n status: this.status,\n statusText: this.statusText ?? getReasonPhrase(this.status),\n webSocket: this.webSocket,\n encodeBody: \"automatic\",\n };\n }\n\n /** Sets a header, overwriting any existing value. */\n public setHeader(key: string, value: string | string[]): void {\n setHeader(this.headers, key, value);\n }\n\n /** Merges a header with existing values (does not overwrite). */\n public mergeHeader(key: string, value: string | string[]): void {\n mergeHeader(this.headers, key, value);\n }\n\n /** Adds a Content-Type header if not already existing (does not overwrite). */\n public addContentType() {\n if (!this.headers.get(HttpHeader.CONTENT_TYPE)) {\n this.setHeader(HttpHeader.CONTENT_TYPE, this.mediaType);\n }\n }\n\n /**\n * Removes headers that are disallowed or discouraged based on the current\n * status code.\n *\n * - **204 No Content:** strips headers that \"should not\" be sent\n * (`Content-Length`, `Content-Range`), per the HTTP spec.\n * - **304 Not Modified:** strips headers that \"must not\" be sent\n * (`Content-Type`, `Content-Length`, `Content-Range`, etc.), per the HTTP spec.\n *\n * This ensures that responses remain compliant with HTTP/1.1 standards while preserving\n * custom headers that are allowed.\n */\n public filterHeaders(): void {\n if (this.status === StatusCodes.NO_CONTENT) {\n filterHeaders(this.headers, FORBIDDEN_204_HEADERS);\n } else if (this.status === StatusCodes.NOT_MODIFIED) {\n filterHeaders(this.headers, FORBIDDEN_304_HEADERS);\n }\n }\n}\n\n/**\n * Base response class that adds caching headers.\n */\nabstract class CacheResponse extends BaseResponse {\n constructor(public cache?: CacheControl) {\n super();\n }\n\n /** Adds Cache-Control header if caching is configured. */\n protected addCacheHeader(): void {\n if (this.cache) {\n this.setHeader(HttpHeader.CACHE_CONTROL, CacheControl.stringify(this.cache));\n }\n }\n}\n\n/**\n * Core response. Combines caching, and content type headers.\n */\nexport abstract class WorkerResponse extends CacheResponse {\n constructor(\n private readonly body: BodyInit | null = null,\n cache?: CacheControl,\n ) {\n super(cache);\n }\n\n /** Builds the Response with body, headers, and status. */\n public async response(): Promise<Response> {\n this.addCacheHeader();\n\n const body = [StatusCodes.NO_CONTENT, StatusCodes.NOT_MODIFIED].includes(this.status)\n ? null\n : this.body;\n\n if (body) this.addContentType();\n\n this.filterHeaders();\n\n return new Response(body, this.responseInit);\n }\n}\n\n/**\n * Copies an existing response for mutation. Pass in a CacheControl\n * to be used for the response, overriding any existing `cache-control`\n * on the source response.\n */\nexport class CopyResponse extends WorkerResponse {\n constructor(response: Response, cache?: CacheControl) {\n super(response.body, cache);\n this.status = response.status;\n this.statusText = response.statusText;\n this.headers = new Headers(response.headers);\n }\n}\n\n/**\n * Copies the response, but with null body and status 304 Not Modified.\n */\nexport class NotModified extends WorkerResponse {\n constructor(response: Response) {\n super();\n this.status = StatusCodes.NOT_MODIFIED;\n this.headers = new Headers(response.headers);\n }\n}\n\n/**\n * Represents a successful response with customizable body, cache and status.\n */\nexport class SuccessResponse extends WorkerResponse {\n constructor(\n body: BodyInit | null = null,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n ) {\n super(body, cache);\n this.status = status;\n }\n}\n\n/**\n * JSON response. Automatically sets Content-Type to application/json.\n */\nexport class JsonResponse extends SuccessResponse {\n constructor(json: unknown = {}, cache?: CacheControl, status: StatusCodes = StatusCodes.OK) {\n super(JSON.stringify(json), cache, status);\n this.mediaType = withCharset(MediaType.JSON, UTF8_CHARSET);\n }\n}\n\n/**\n * HTML response. Automatically sets Content-Type to text/html.\n */\nexport class HtmlResponse extends SuccessResponse {\n constructor(\n body: string,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n charset: string = UTF8_CHARSET,\n ) {\n super(body, cache, status);\n this.mediaType = withCharset(MediaType.HTML, charset);\n }\n}\n\n/**\n * Plain text response. Automatically sets Content-Type to text/plain.\n */\nexport class TextResponse extends SuccessResponse {\n constructor(\n body: string,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n charset: string = UTF8_CHARSET,\n ) {\n super(body, cache, status);\n this.mediaType = withCharset(MediaType.PLAIN_TEXT, charset);\n }\n}\n\n/**\n * Represents an HTTP response for serving binary data as `application/octet-stream`.\n *\n * This class wraps a `ReadableStream` and sets all necessary headers for both\n * full and partial content responses, handling range requests in a hybrid way\n * to maximize browser and CDN caching.\n *\n * Key behaviors:\n * - `Content-Type` is set to `application/octet-stream`.\n * - `Accept-Ranges: bytes` is always included.\n * - `Content-Length` is always set to the validated length of the response body.\n * - If the request is a true partial range (offset > 0 or length < size), the response\n * will be `206 Partial Content` with the appropriate `Content-Range` header.\n * - If the requested range covers the entire file (even if a Range header is present),\n * the response will return `200 OK` to enable browser and edge caching.\n * - Zero-length streams (`size = 0`) are never treated as partial.\n * - Special case: a requested range of `0-0` on a non-empty file is normalized to 1 byte.\n */\nexport class OctetStream extends WorkerResponse {\n constructor(stream: ReadableStream, init: OctetStreamInit, cache?: CacheControl) {\n assertOctetStreamInit(init);\n\n super(stream, cache);\n this.mediaType = MediaType.OCTET_STREAM;\n\n const normalized = OctetStream.normalizeInit(init);\n const { size, offset, length } = normalized;\n\n if (OctetStream.isPartial(normalized)) {\n this.setHeader(\n HttpHeader.CONTENT_RANGE,\n `bytes ${offset}-${offset + length - 1}/${size}`,\n );\n this.status = StatusCodes.PARTIAL_CONTENT;\n }\n\n this.setHeader(HttpHeader.ACCEPT_RANGES, \"bytes\");\n this.setHeader(HttpHeader.CONTENT_LENGTH, `${length}`);\n }\n\n /**\n * Normalizes a partially-specified `OctetStreamInit` into a fully-specified object.\n *\n * Ensures that all required fields (`size`, `offset`, `length`) are defined:\n * - `offset` defaults to 0 if not provided.\n * - `length` defaults to `size - offset` if not provided.\n * - Special case: if `offset` and `length` are both 0 but `size > 0`, `length` is set to 1\n * to avoid zero-length partial streams.\n *\n * @param init - The initial `OctetStreamInit` object, possibly with missing `offset` or `length`.\n * @returns A fully-specified `OctetStreamInit` object with `size`, `offset`, and `length` guaranteed.\n */\n private static normalizeInit(init: OctetStreamInit): Required<OctetStreamInit> {\n const { size } = init;\n const offset = init.offset ?? 0;\n let length = init.length ?? size - offset;\n\n if (offset === 0 && length === 0 && size > 0) {\n length = 1;\n }\n\n return { size, offset, length };\n }\n\n /**\n * Determines whether the given `OctetStreamInit` represents a partial range.\n *\n * Partial ranges are defined as any range that does **not** cover the entire file:\n * - If `size === 0`, the stream is never partial.\n * - If `offset === 0` and `length === size`, the stream is treated as a full file (not partial),\n * even if a Range header is present. This enables browser and CDN caching.\n * - All other cases are considered partial, and will result in a `206 Partial Content` response.\n *\n * @param init - A fully-normalized `OctetStreamInit` object.\n * @returns `true` if the stream represents a partial range; `false` if it represents the full file.\n */\n private static isPartial(init: Required<OctetStreamInit>): boolean {\n if (init.size === 0) return false;\n return !(init.offset === 0 && init.length === init.size);\n }\n}\n\n/**\n * A streaming response for Cloudflare R2 objects.\n *\n * **Partial content support:** To enable HTTP 206 streaming, you must provide\n * request headers containing the `Range` header when calling the R2 bucket's `get()` method.\n *\n * Example:\n * ```ts\n * const stream = await this.env.R2_BUCKET.get(\"key\", { range: this.request.headers });\n * ```\n *\n * @param source - The R2 object to stream.\n * @param cache - Optional caching override.\n */\nexport class R2ObjectStream extends OctetStream {\n constructor(source: R2ObjectBody, cache?: CacheControl) {\n let useCache = cache;\n if (!useCache && source.httpMetadata?.cacheControl) {\n useCache = CacheControl.parse(source.httpMetadata.cacheControl);\n }\n\n super(source.body, R2ObjectStream.computeRange(source.size, source.range), useCache);\n\n this.setHeader(HttpHeader.ETAG, source.httpEtag);\n\n if (source.httpMetadata?.contentType) {\n this.mediaType = source.httpMetadata.contentType;\n }\n }\n\n /**\n * Computes an `OctetStreamInit` object from a given R2 range.\n *\n * This function normalizes a Cloudflare R2 `R2Range` into the shape expected\n * by `OctetStream`. It handles the following cases:\n *\n * - No range provided: returns `{ size }` (full content).\n * - `suffix` range: calculates the offset and length from the end of the file.\n * - Explicit `offset` and/or `length`: passed through as-is.\n *\n * @param size - The total size of the file/object.\n * @param range - Optional range to extract (from R2). Can be:\n * - `{ offset: number; length?: number }`\n * - `{ offset?: number; length: number }`\n * - `{ suffix: number }`\n * @returns An `OctetStreamInit` object suitable for `OctetStream`.\n */\n private static computeRange(size: number, range?: R2Range): OctetStreamInit {\n if (!range) return { size };\n\n if (\"suffix\" in range) {\n const offset = Math.max(0, size - range.suffix);\n const length = size - offset;\n return { size, offset, length };\n }\n\n return { size, ...range };\n }\n}\n\n/**\n * Response for WebSocket upgrade requests.\n * Automatically sets status to 101 and attaches the client socket.\n */\nexport class WebSocketUpgrade extends WorkerResponse {\n constructor(client: WebSocket) {\n super();\n this.status = StatusCodes.SWITCHING_PROTOCOLS;\n this.webSocket = client;\n }\n}\n\n/**\n * Response for `HEAD` requests. Copy headers and status from a `GET` response\n * without the body.\n */\nexport class Head extends WorkerResponse {\n constructor(get: Response) {\n super();\n this.status = get.status;\n this.statusText = get.statusText;\n this.headers = new Headers(get.headers);\n }\n}\n\n/**\n * Response for `OPTIONS` requests.\n */\nexport class Options extends WorkerResponse {\n constructor(worker: Worker) {\n const allowed = Array.from(new Set([GET, HEAD, ...worker.getAllowedMethods()]));\n assertMethods(allowed);\n\n super();\n this.status = StatusCodes.NO_CONTENT;\n this.setHeader(HttpHeader.ALLOW, allowed);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader } from \"../../constants/headers\";\nimport { assertMethods } from \"../../guards/methods\";\nimport { Worker } from \"../../interfaces/worker\";\nimport { CopyResponse } from \"../../responses\";\nimport { mergeHeader, setHeader } from \"../../utils/headers\";\n\nimport { ALLOW_ALL_ORIGINS, SKIP_CORS_STATUSES } from \"./constants\";\nimport { CorsConfig } from \"./interfaces\";\n\n/**\n * Handles a `CORS` preflight `OPTIONS` request.\n *\n * This function **modifies the provided response** to include the appropriate\n * CORS headers based on the configuration and the request's origin.\n *\n * Steps:\n * 1. Clears any existing CORS headers from the response.\n * 2. Sets `Vary: Origin` if needed for caching purposes.\n * 3. If an `Origin` header is present in the request:\n * - Sets `Access-Control-Allow-Origin`\n * - Sets `Access-Control-Allow-Credentials`\n * - Sets `Access-Control-Allow-Methods`\n * - Sets `Access-Control-Allow-Headers`\n * - Sets `Access-Control-Max-Age`\n *\n * @param response - The original Response object to modify for the preflight.\n * @param worker - The Worker handling the request.\n * @param cors - The CORS configuration to apply.\n * @returns A Response object suitable for responding to the preflight request.\n */\nexport function options(response: Response, worker: Worker, cors: CorsConfig): Promise<Response> {\n const copy = new CopyResponse(response);\n const origin = getOrigin(worker.request);\n\n deleteCorsHeaders(copy.headers);\n setVaryOrigin(copy.headers, cors);\n\n if (origin) {\n setAllowOrigin(copy.headers, cors, origin);\n setAllowCredentials(copy.headers, cors, origin);\n setAllowMethods(copy.headers, worker);\n setAllowHeaders(copy.headers, cors);\n setMaxAge(copy.headers, cors);\n }\n\n return copy.response();\n}\n\n/**\n * Applies CORS headers to an existing response for non-preflight requests.\n *\n * This function **modifies the provided response** to include the appropriate\n * CORS headers based on the configuration and the request's origin.\n *\n * Steps:\n * 1. Clears any existing CORS headers from the response.\n * 2. Sets `Vary: Origin` if needed for caching purposes.\n * 3. If an `Origin` header is present in the request:\n * - Sets `Access-Control-Allow-Origin`\n * - Sets `Access-Control-Allow-Credentials`\n * - Sets `Access-Control-Expose-Headers`\n *\n * @param response - The original Response object to modify.\n * @param worker - The Worker handling the request.\n * @param cors - The CORS configuration to apply.\n * @returns A Response object with CORS headers applied, suitable for returning\n * to the client.\n */\nexport function apply(response: Response, worker: Worker, cors: CorsConfig): Promise<Response> {\n const copy = new CopyResponse(response);\n const origin = getOrigin(worker.request);\n\n deleteCorsHeaders(copy.headers);\n setVaryOrigin(copy.headers, cors);\n\n if (origin) {\n setAllowOrigin(copy.headers, cors, origin);\n setAllowCredentials(copy.headers, cors, origin);\n setExposedHeaders(copy.headers, cors);\n }\n\n return copy.response();\n}\n\n/**\n * Adds `Vary: Origin` when `CORS` is restricted to specific origins.\n * This ensures caches differentiate responses by request origin.\n *\n * Skipped when all origins are allowed.\n *\n * @param headers - The headers object to modify.\n * @param cors - The `CORS` configuration.\n */\nexport function setVaryOrigin(headers: Headers, cors: CorsConfig): void {\n if (!allowAllOrigins(cors)) {\n mergeHeader(headers, HttpHeader.VARY, HttpHeader.ORIGIN);\n }\n}\n\n/**\n * Sets the Access-Control-Allow-Origin header based on the `CORS` config\n * and request origin.\n *\n * @param headers - The headers object to modify.\n * @param cors - The `CORS` configuration.\n * @param origin - The request's origin, or null if not present.\n */\nexport function setAllowOrigin(headers: Headers, cors: CorsConfig, origin: string): void {\n if (allowAllOrigins(cors)) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN, ALLOW_ALL_ORIGINS);\n return;\n }\n\n if (cors.allowedOrigins.includes(origin)) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN, origin);\n }\n}\n\n/**\n * Conditionally sets the `Access-Control-Allow-Credentials` header\n * for a `CORS` response.\n *\n * This header is only set if:\n * 1. `cors.allowCredentials` is true,\n * 2. The configuration does **not** allow any origin (`*`), and\n * 3. The provided `origin` is explicitly listed in `cors.allowedOrigins`.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The `CORS` configuration.\n * @param origin - The origin of the incoming request.\n */\nexport function setAllowCredentials(headers: Headers, cors: CorsConfig, origin: string): void {\n if (!cors.allowCredentials) return;\n if (allowAllOrigins(cors)) return;\n if (!cors.allowedOrigins.includes(origin)) return;\n\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS, \"true\");\n}\n\n/**\n * Sets the `Access-Control-Allow-Methods` header for a `CORS` response.\n *\n * @param headers - The Headers object to modify.\n * @param worker - The Worker instance used to retrieve allowed methods.\n */\nexport function setAllowMethods(headers: Headers, worker: Worker): void {\n const allowed = worker.getAllowedMethods();\n assertMethods(allowed);\n\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_METHODS, allowed);\n}\n\n/**\n * Sets the `Access-Control-Max-Age` header for a `CORS` response.\n *\n * This header indicates how long the results of a preflight request\n * can be cached by the client (in seconds).\n *\n * The value is **clamped to a non-negative integer** to comply with\n * the `CORS` specification:\n * - Decimal values are floored to the nearest integer.\n * - Negative values are treated as `0`.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The `CORS` configuration containing the `maxAge` value in seconds.\n */\nexport function setMaxAge(headers: Headers, cors: CorsConfig): void {\n const maxAge = Math.max(0, Math.floor(cors.maxAge));\n setHeader(headers, HttpHeader.ACCESS_CONTROL_MAX_AGE, String(maxAge));\n}\n\n/**\n * Sets the Access-Control-Allow-Headers header based on the `CORS` configuration.\n *\n * Only the headers explicitly listed in `cors.allowedHeaders` are sent.\n * If the array is empty, no Access-Control-Allow-Headers header is added.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The `CORS` configuration.\n */\nexport function setAllowHeaders(headers: Headers, cors: CorsConfig): void {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS, cors.allowedHeaders);\n}\n\n/**\n * Sets the Access-Control-Expose-Headers header for a response.\n *\n * @param headers - The headers object to modify.\n * @param cors - The `CORS` configuration.\n */\nexport function setExposedHeaders(headers: Headers, cors: CorsConfig): void {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_EXPOSE_HEADERS, cors.exposedHeaders);\n}\n\n/**\n * Returns true if the `CORS` config allows all origins ('*').\n *\n * @param cors - The `CORS` configuration.\n */\nexport function allowAllOrigins(cors: CorsConfig): boolean {\n return cors.allowedOrigins.includes(ALLOW_ALL_ORIGINS);\n}\n\n/**\n * Deletes any existing `CORS` headers from the provided headers object.\n *\n * @param headers - The headers object to modify.\n */\nexport function deleteCorsHeaders(headers: Headers): void {\n headers.delete(HttpHeader.ACCESS_CONTROL_MAX_AGE);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_METHODS);\n headers.delete(HttpHeader.ACCESS_CONTROL_EXPOSE_HEADERS);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS);\n}\n\n/**\n * Determines whether CORS headers should be skipped for a response.\n *\n * Certain responses do not require CORS headers, such as:\n * - Informational or protocol-level responses (1xx)\n * - Redirect responses (3xx)\n * - Responses initiating a protocol upgrade\n *\n * @param response - The Response object to inspect.\n * @returns `true` if CORS headers should be omitted, `false` otherwise.\n */\nexport function skipCors(response: Response): boolean {\n const { status, headers } = response;\n if (SKIP_CORS_STATUSES.includes(status)) return true;\n if (headers.has(HttpHeader.UPGRADE)) return true;\n\n return false;\n}\n\n/**\n * Extracts and normalizes the `Origin` header from a request.\n *\n * Returns the origin (scheme + host + port) as a string if present and valid.\n * Returns `null` if:\n * - The `Origin` header is missing\n * - The `Origin` header is `\"null\"` (opaque origin)\n * - The `Origin` header is malformed\n *\n * @param request - The incoming {@link Request} object.\n * @returns The normalized origin string, or `null` if not present or invalid.\n */\nexport function getOrigin(request: Request): string | null {\n const origin = request.headers.get(HttpHeader.ORIGIN)?.trim();\n if (!origin || origin === \"null\") return null;\n\n try {\n return new URL(origin).origin;\n } catch {\n return null;\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OPTIONS } from \"../../constants/methods\";\nimport { Middleware } from \"../../interfaces/middleware\";\nimport { Worker } from \"../../interfaces/worker\";\n\nimport { defaultCorsConfig } from \"./constants\";\nimport { CorsConfig, CorsInit } from \"./interfaces\";\nimport { apply, options, skipCors } from \"./utils\";\n\n/**\n * CORS Middleware Implementation\n *\n * Handles Cross-Origin Resource Sharing (CORS) for incoming requests.\n *\n * Behavior:\n * - Invokes the downstream middleware for all requests first by calling `next()`.\n * - If the request is an `OPTIONS` request (preflight), transforms the downstream\n * response into a preflight CORS response.\n * - For other HTTP methods, applies CORS headers to the downstream response,\n * unless the response explicitly opts out via `skipCors`.\n *\n * This ensures that all responses comply with the configured CORS rules\n * while still allowing downstream middleware to run for every request.\n *\n * @see {@link cors} for full configuration options and defaults.\n */\nexport class CorsHandler implements Middleware {\n /** The resolved CORS configuration for this middleware instance. */\n private readonly config: CorsConfig;\n\n /**\n * Constructs a new `CorsHandler` instance.\n *\n * Merges the provided partial configuration with the default settings.\n *\n * @param init - Optional partial configuration to override defaults.\n * Any fields not provided will use `defaultCorsConfig`.\n */\n constructor(init?: CorsInit) {\n this.config = { ...defaultCorsConfig, ...init };\n }\n\n /**\n * Applies CORS handling to an incoming request.\n *\n * @param worker - The Worker instance containing the request and context.\n * @param next - Function invoking the next middleware in the chain.\n * @returns A Response object with CORS headers applied.\n * - For `OPTIONS` requests, returns a preflight response based on\n * the downstream response.\n * - For other methods, returns the downstream response with\n * CORS headers applied, unless `skipCors` prevents it.\n */\n public async handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {\n const response = await next();\n\n if (worker.request.method === OPTIONS) {\n return options(response, worker, this.config);\n }\n\n if (skipCors(response)) return response;\n\n return apply(response, worker, this.config);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertCorsInit } from \"../../guards/cors\";\nimport { Middleware } from \"../../interfaces/middleware\";\n\nimport { CorsHandler } from \"./handler\";\nimport { CorsInit } from \"./interfaces\";\n\n/**\n * Returns a `CORS` middleware instance.\n *\n * This middleware automatically handles Cross-Origin Resource Sharing (CORS)\n * for incoming requests, including preflight `OPTIONS` requests, and adds\n * appropriate headers to responses.\n *\n * @param init - Optional configuration for `CORS` behavior. See {@link CorsConfig}.\n * @returns A {@link Middleware} instance that can be used in your middleware chain.\n */\nexport function cors(init?: CorsInit): Middleware {\n assertCorsInit(init);\n return new CorsHandler(init);\n}\n"]}
1
+ {"version":3,"sources":["../src/guards/basic.ts","../src/guards/cors.ts","../src/constants/methods.ts","../src/constants/cache.ts","../src/constants/status.ts","../src/constants/time.ts","../src/constants/headers.ts","../src/middleware/cors/constants.ts","../src/guards/methods.ts","../src/utils/compare.ts","../src/utils/headers.ts","../src/utils/reasons.ts","../src/responses.ts","../src/middleware/cors/utils.ts","../src/middleware/cors/handler.ts","../src/middleware/cors/cors.ts"],"names":["isStringArray","value","item","isString","isNumber","isBoolean","assertCorsInit","obj","Method","GET","PUT","HEAD","POST","PATCH","DELETE","OPTIONS","CacheControl","CacheLib","StatusCodes","Time","HttpHeader","FORBIDDEN_304_HEADERS","FORBIDDEN_204_HEADERS","ALLOW_ALL_ORIGINS","SKIP_CORS_STATUSES","defaultCorsConfig","METHOD_SET","isMethod","isMethodArray","assertMethods","desc","lexCompare","a","b","setHeader","headers","key","raw","values","v","mergeHeader","merged","getHeaderValues","filterHeaders","keys","getReasonPhrase","status","c","BaseResponse","CacheResponse","cache","WorkerResponse","body","CopyResponse","response","options","worker","cors","copy","origin","getOrigin","deleteCorsHeaders","setVaryOrigin","setAllowOrigin","setAllowCredentials","setAllowMethods","setAllowHeaders","setMaxAge","apply","setExposedHeaders","allowAllOrigins","allowed","maxAge","skipCors","request","CorsHandler","init","next"],"mappings":"oCAsBO,SAASA,EAAcC,CAAAA,CAAmC,CAC7D,OAAO,KAAA,CAAM,OAAA,CAAQA,CAAK,CAAA,EAAKA,CAAAA,CAAM,KAAA,CAAOC,CAAAA,EAAS,OAAOA,CAAAA,EAAS,QAAQ,CACjF,CAQO,SAASC,EAASF,CAAAA,CAAiC,CACtD,OAAO,OAAOA,GAAU,QAC5B,CAYO,SAASG,CAAAA,CAASH,CAAAA,CAAiC,CACtD,OAAO,OAAOA,GAAU,QAAA,EAAY,CAAC,OAAO,KAAA,CAAMA,CAAK,CAC3D,CAQO,SAASI,EAAUJ,CAAAA,CAAkC,CACxD,OAAO,OAAOA,GAAU,SAC5B,CC9BO,SAASK,CAAAA,CAAeL,CAAAA,CAA2C,CACtE,GAAIA,CAAAA,GAAU,OAAW,OAEzB,GAAI,OAAOA,CAAAA,EAAU,QAAA,EAAYA,IAAU,IAAA,CACvC,MAAM,IAAI,SAAA,CAAU,6BAA6B,CAAA,CAGrD,IAAMM,EAAMN,CAAAA,CAEZ,GAAIM,EAAI,cAAA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vD,IAAMf,CAAAA,CAASe,CAAAA,CAAQ,OAAA,CAAQ,IAAItD,CAAAA,CAAW,MAAM,GAAG,IAAA,EAAK,CAC5D,GAAI,CAACuC,CAAAA,EAAUA,IAAW,MAAA,CAAQ,OAAO,KAEzC,GAAI,CACA,OAAO,IAAI,GAAA,CAAIA,CAAM,CAAA,CAAE,MAC3B,CAAA,KAAQ,CACJ,OAAO,IACX,CACJ,CCxOO,IAAMgB,CAAAA,CAAN,KAAwC,CAE1B,MAAA,CAUjB,YAAYC,CAAAA,CAAiB,CACzB,KAAK,MAAA,CAAS,CAAE,GAAGnD,CAAAA,CAAmB,GAAGmD,CAAK,EAClD,CAaA,MAAa,MAAA,CAAOpB,EAAgBqB,CAAAA,CAAkD,CAClF,IAAMvB,CAAAA,CAAW,MAAMuB,GAAK,CAE5B,OAAIrB,EAAO,OAAA,CAAQ,MAAA,GAAWzC,EACnBwC,CAAAA,CAAQD,CAAAA,CAAUE,EAAQ,IAAA,CAAK,MAAM,EAG5CiB,CAAAA,CAASnB,CAAQ,CAAA,CAAUA,CAAAA,CAExBc,EAAMd,CAAAA,CAAUE,CAAAA,CAAQ,KAAK,MAAM,CAC9C,CACJ,CAAA,CC/CO,SAASC,GAAKmB,CAAAA,CAA6B,CAC9C,OAAAtE,CAAAA,CAAesE,CAAI,EACZ,IAAID,CAAAA,CAAYC,CAAI,CAC/B","file":"cors.js","sourcesContent":["/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks if the provided value is an array of strings.\n *\n * @param value - The value to check.\n * @returns True if `array` is an array where every item is a string.\n */\nexport function isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\n/**\n * Checks if a value is a string.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a string, otherwise `false`.\n */\nexport function isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n\n/**\n * Checks if a value is a valid number (not NaN).\n *\n * This function returns `true` if the value is of type `number`\n * and is not `NaN`. It works as a type guard for TypeScript.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a number and not `NaN`, otherwise `false`.\n */\nexport function isNumber(value: unknown): value is number {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\n\n/**\n * Checks if a value is a boolean.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a boolean (`true` or `false`), otherwise `false`.\n */\nexport function isBoolean(value: unknown): value is boolean {\n return typeof value === \"boolean\";\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CorsInit } from \"../middleware/cors/interfaces\";\n\nimport { isBoolean, isNumber, isStringArray } from \"./basic\";\n\n/**\n * Throws if the given value is not a valid CorsInit.\n *\n * Checks only the fields that are present, since CorsInit is Partial<CorsConfig>.\n *\n * @param value - The value to check.\n * @throws TypeError If `value` is not a valid {@link CorsInit}.\n */\nexport function assertCorsInit(value: unknown): asserts value is CorsInit {\n if (value === undefined) return;\n\n if (typeof value !== \"object\" || value === null) {\n throw new TypeError(\"CorsInit must be an object.\");\n }\n\n const obj = value as Record<string, unknown>;\n\n if (obj[\"allowedOrigins\"] !== undefined && !isStringArray(obj[\"allowedOrigins\"])) {\n throw new TypeError(\"CorsInit.allowedOrigins must be a string array.\");\n }\n\n if (obj[\"allowedHeaders\"] !== undefined && !isStringArray(obj[\"allowedHeaders\"])) {\n throw new TypeError(\"CorsInit.allowedHeaders must be a string array.\");\n }\n\n if (obj[\"exposedHeaders\"] !== undefined && !isStringArray(obj[\"exposedHeaders\"])) {\n throw new TypeError(\"CorsInit.exposedHeaders must be a string array.\");\n }\n\n if (obj[\"allowCredentials\"] !== undefined && !isBoolean(obj[\"allowCredentials\"])) {\n throw new TypeError(\"CorsInit.allowCredentials must be a boolean.\");\n }\n\n if (obj[\"maxAge\"] !== undefined && !isNumber(obj[\"maxAge\"])) {\n throw new TypeError(\"CorsInit.maxAge must be a number.\");\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Standard HTTP request methods.\n */\nexport enum Method {\n GET = \"GET\",\n PUT = \"PUT\",\n HEAD = \"HEAD\",\n POST = \"POST\",\n PATCH = \"PATCH\",\n DELETE = \"DELETE\",\n OPTIONS = \"OPTIONS\",\n}\n\n/**\n * Shorthand constants for each HTTP method.\n *\n * These are equivalent to the corresponding enum members in `Method`.\n * For example, `GET === Method.GET`.\n */\nexport const { GET, PUT, HEAD, POST, PATCH, DELETE, OPTIONS } = Method;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport CacheLib from \"cache-control-parser\";\n\n/**\n * @see {@link https://github.com/etienne-martin/cache-control-parser | cache-control-parser}\n */\nexport type CacheControl = CacheLib.CacheControl;\nexport const CacheControl = {\n parse: CacheLib.parse,\n stringify: CacheLib.stringify,\n\n /** A CacheControl directive that disables all caching. */\n DISABLE: Object.freeze({\n \"no-cache\": true,\n \"no-store\": true,\n \"must-revalidate\": true,\n \"max-age\": 0,\n }) satisfies CacheControl,\n};\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * https://github.com/prettymuchbryce/http-status-codes\n */\nexport enum StatusCodes {\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1\n *\n * This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.\n */\n CONTINUE = 100,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2\n *\n * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too.\n */\n SWITCHING_PROTOCOLS = 101,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1\n *\n * This code indicates that the server has received and is processing the request, but no response is available yet.\n */\n PROCESSING = 102,\n /**\n * Official Documentation @ https://www.rfc-editor.org/rfc/rfc8297#page-3\n *\n * This code indicates to the client that the server is likely to send a final response with the header fields included in the informational response.\n */\n EARLY_HINTS = 103,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1\n *\n * The request has succeeded. The meaning of a success varies depending on the HTTP method:\n * GET: The resource has been fetched and is transmitted in the message body.\n * HEAD: The entity headers are in the message body.\n * POST: The resource describing the result of the action is transmitted in the message body.\n * TRACE: The message body contains the request message as received by the server\n */\n OK = 200,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2\n *\n * The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request.\n */\n CREATED = 201,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3\n *\n * The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.\n */\n ACCEPTED = 202,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4\n *\n * This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response.\n */\n NON_AUTHORITATIVE_INFORMATION = 203,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5\n *\n * There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.\n */\n NO_CONTENT = 204,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6\n *\n * This response code is sent after accomplishing request to tell user agent reset document view which sent this request.\n */\n RESET_CONTENT = 205,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1\n *\n * This response code is used because of range header sent by the client to separate download into multiple streams.\n */\n PARTIAL_CONTENT = 206,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2\n *\n * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate.\n */\n MULTI_STATUS = 207,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1\n *\n * The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses.\n */\n MULTIPLE_CHOICES = 300,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2\n *\n * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response.\n */\n MOVED_PERMANENTLY = 301,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3\n *\n * This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.\n */\n FOUND = 302,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4\n *\n * The 302 (Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests.\n */\n SEE_OTHER = 303,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1\n *\n * This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response.\n */\n NOT_MODIFIED = 304,\n /**\n * @deprecated\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6\n *\n * Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.\n */\n USE_PROXY = 305,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7\n *\n * Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.\n */\n TEMPORARY_REDIRECT = 307,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3\n *\n * This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.\n */\n PERMANENT_REDIRECT = 308,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1\n *\n * This response means that server could not understand the request due to invalid syntax.\n */\n BAD_REQUEST = 400,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1\n *\n * Although the HTTP standard specifies \"unauthorized\", semantically this response means \"unauthenticated\". That is, the client must authenticate itself to get the requested response.\n */\n UNAUTHORIZED = 401,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2\n *\n * This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently.\n */\n PAYMENT_REQUIRED = 402,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3\n *\n * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server.\n */\n FORBIDDEN = 403,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4\n *\n * The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurrence on the web.\n */\n NOT_FOUND = 404,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5\n *\n * The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.\n */\n METHOD_NOT_ALLOWED = 405,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6\n *\n * This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent.\n */\n NOT_ACCEPTABLE = 406,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2\n *\n * This is similar to 401 but authentication is needed to be done by a proxy.\n */\n PROXY_AUTHENTICATION_REQUIRED = 407,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7\n *\n * This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.\n */\n REQUEST_TIMEOUT = 408,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8\n *\n * This response is sent when a request conflicts with the current state of the server.\n */\n CONFLICT = 409,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9\n *\n * This response would be sent when the requested content has been permenently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for \"limited-time, promotional services\". APIs should not feel compelled to indicate resources that have been deleted with this status code.\n */\n GONE = 410,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10\n *\n * The server rejected the request because the Content-Length header field is not defined and the server requires it.\n */\n LENGTH_REQUIRED = 411,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2\n *\n * The client has indicated preconditions in its headers which the server does not meet.\n */\n PRECONDITION_FAILED = 412,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11\n *\n * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field.\n */\n REQUEST_TOO_LONG = 413,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12\n *\n * The URI requested by the client is longer than the server is willing to interpret.\n */\n REQUEST_URI_TOO_LONG = 414,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13\n *\n * The media format of the requested data is not supported by the server, so the server is rejecting the request.\n */\n UNSUPPORTED_MEDIA_TYPE = 415,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4\n *\n * The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data.\n */\n REQUESTED_RANGE_NOT_SATISFIABLE = 416,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14\n *\n * This response code means the expectation indicated by the Expect request header field can't be met by the server.\n */\n EXPECTATION_FAILED = 417,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2\n *\n * Any attempt to brew coffee with a teapot should result in the error code \"418 I'm a teapot\". The resulting entity body MAY be short and stout.\n */\n IM_A_TEAPOT = 418,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6\n *\n * The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request which received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action.\n */\n INSUFFICIENT_SPACE_ON_RESOURCE = 419,\n /**\n * @deprecated\n * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt\n *\n * A deprecated response used by the Spring Framework when a method has failed.\n */\n METHOD_FAILURE = 420,\n /**\n * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2\n *\n * Defined in the specification of HTTP/2 to indicate that a server is not able to produce a response for the combination of scheme and authority that are included in the request URI.\n */\n MISDIRECTED_REQUEST = 421,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3\n *\n * The request was well-formed but was unable to be followed due to semantic errors.\n */\n UNPROCESSABLE_ENTITY = 422,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4\n *\n * The resource that is being accessed is locked.\n */\n LOCKED = 423,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5\n *\n * The request failed due to failure of a previous request.\n */\n FAILED_DEPENDENCY = 424,\n /**\n * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.15\n *\n * The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.\n */\n UPGRADE_REQUIRED = 426,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3\n *\n * The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.\n */\n PRECONDITION_REQUIRED = 428,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4\n *\n * The user has sent too many requests in a given amount of time (\"rate limiting\").\n */\n TOO_MANY_REQUESTS = 429,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5\n *\n * The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.\n */\n REQUEST_HEADER_FIELDS_TOO_LARGE = 431,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7725\n *\n * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government.\n */\n UNAVAILABLE_FOR_LEGAL_REASONS = 451,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1\n *\n * The server encountered an unexpected condition that prevented it from fulfilling the request.\n */\n INTERNAL_SERVER_ERROR = 500,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2\n *\n * The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.\n */\n NOT_IMPLEMENTED = 501,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3\n *\n * This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.\n */\n BAD_GATEWAY = 502,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4\n *\n * The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.\n */\n SERVICE_UNAVAILABLE = 503,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5\n *\n * This error response is given when the server is acting as a gateway and cannot get a response in time.\n */\n GATEWAY_TIMEOUT = 504,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6\n *\n * The HTTP version used in the request is not supported by the server.\n */\n HTTP_VERSION_NOT_SUPPORTED = 505,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6\n *\n * The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.\n */\n INSUFFICIENT_STORAGE = 507,\n /**\n * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6\n *\n * The 511 status code indicates that the client needs to authenticate to gain network access.\n */\n NETWORK_AUTHENTICATION_REQUIRED = 511,\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Time constants in seconds. Month is approximated as 30 days.\n */\nexport const Time = {\n Second: 1,\n Minute: 60,\n Hour: 3600, // 60 * 60\n Day: 86400, // 60 * 60 * 24\n Week: 604800, // 60 * 60 * 24 * 7\n Month: 2592000, // 60 * 60 * 24 * 30\n Year: 31536000, // 60 * 60 * 24 * 365\n} as const;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Internally used headers.\n */\nexport const HttpHeader = {\n ACCEPT: \"accept\",\n ACCEPT_ENCODING: \"accept-encoding\",\n ACCEPT_LANGUAGE: \"accept-language\",\n ACCEPT_RANGES: \"accept-ranges\",\n ALLOW: \"allow\",\n AUTHORIZATION: \"authorization\",\n CACHE_CONTROL: \"cache-control\",\n CONNECTION: \"connection\",\n CONTENT_DISPOSITION: \"content-disposition\",\n CONTENT_ENCODING: \"content-encoding\",\n CONTENT_LANGUAGE: \"content-language\",\n CONTENT_LENGTH: \"content-length\",\n CONTENT_RANGE: \"content-range\",\n CONTENT_TYPE: \"content-type\",\n CONTENT_MD5: \"content-md5\",\n COOKIE: \"cookie\",\n ETAG: \"etag\",\n IF_MODIFIED_SINCE: \"if-modified-since\",\n IF_NONE_MATCH: \"if-none-match\",\n ORIGIN: \"origin\",\n RANGE: \"range\",\n SET_COOKIE: \"set-cookie\",\n VARY: \"vary\",\n\n // Cors Headers\n ACCESS_CONTROL_ALLOW_CREDENTIALS: \"access-control-allow-credentials\",\n ACCESS_CONTROL_ALLOW_HEADERS: \"access-control-allow-headers\",\n ACCESS_CONTROL_ALLOW_METHODS: \"access-control-allow-methods\",\n ACCESS_CONTROL_ALLOW_ORIGIN: \"access-control-allow-origin\",\n ACCESS_CONTROL_EXPOSE_HEADERS: \"access-control-expose-headers\",\n ACCESS_CONTROL_MAX_AGE: \"access-control-max-age\",\n\n // Websocket Headers\n SEC_WEBSOCKET_VERSION: \"sec-websocket-version\",\n UPGRADE: \"upgrade\",\n\n // Internal Headers\n INTERNAL_VARIANT_SET: \"cs-internal-variant-set\",\n CACHE_KEY: \"cs-cache-key\",\n CACHE_DECODED_KEY: \"cs-cache-decoded-key\",\n CACHE_REQUEST_HEADERS: \"cs-cache-req-headers\",\n} as const;\n\n/**\n * Headers that must not be sent in 304 Not Modified responses.\n * These are stripped to comply with the HTTP spec.\n */\nexport const FORBIDDEN_304_HEADERS = [\n HttpHeader.CONTENT_TYPE,\n HttpHeader.CONTENT_LENGTH,\n HttpHeader.CONTENT_RANGE,\n HttpHeader.CONTENT_ENCODING,\n HttpHeader.CONTENT_LANGUAGE,\n HttpHeader.CONTENT_DISPOSITION,\n HttpHeader.CONTENT_MD5,\n];\n\n/**\n * Headers that should not be sent in 204 No Content responses.\n * Stripping them is recommended but optional per spec.\n */\nexport const FORBIDDEN_204_HEADERS = [HttpHeader.CONTENT_LENGTH, HttpHeader.CONTENT_RANGE];\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StatusCodes } from \"../../constants\";\nimport { HttpHeader } from \"../../constants/headers\";\nimport { Time } from \"../../constants/time\";\n\nimport { CorsConfig } from \"./interfaces\";\n\n/**\n * A wildcard value used in the CORS `Access-Control-Allow-Origin` header\n * to permit requests from **any** origin.\n */\nexport const ALLOW_ALL_ORIGINS = \"*\";\n\n/**\n * Status codes for which `CORS` should be skipped.\n *\n * Skips `CORS` for:\n * - 101 Switching Protocols (WebSocket upgrade)\n * - 100 Continue\n * - 3xx Redirects (`CORS` is applied to the final URL only)\n */\nexport const SKIP_CORS_STATUSES = [\n StatusCodes.SWITCHING_PROTOCOLS,\n StatusCodes.CONTINUE,\n StatusCodes.PROCESSING,\n StatusCodes.EARLY_HINTS,\n StatusCodes.MOVED_PERMANENTLY,\n StatusCodes.FOUND,\n StatusCodes.SEE_OTHER,\n StatusCodes.TEMPORARY_REDIRECT,\n StatusCodes.PERMANENT_REDIRECT,\n];\n\n/**\n * Default configuration for `CORS` middleware.\n */\nexport const defaultCorsConfig: CorsConfig = {\n allowedOrigins: [ALLOW_ALL_ORIGINS],\n allowedHeaders: [HttpHeader.CONTENT_TYPE],\n exposedHeaders: [],\n allowCredentials: false,\n maxAge: 5 * Time.Minute,\n} as const;\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Method } from \"../constants/methods\";\n\nimport { isString } from \"./basic\";\n\n/**\n * A set containing all supported HTTP methods.\n *\n * Useful for runtime checks like validating request methods.\n */\nconst METHOD_SET: Set<string> = new Set(Object.values(Method));\n\n/**\n * Type guard that checks if a string is a valid HTTP method.\n *\n * @param value - The string to test.\n * @returns True if `value` is a recognized HTTP method.\n */\nexport function isMethod(value: unknown): value is Method {\n return isString(value) && METHOD_SET.has(value);\n}\n\n/**\n * Checks if a value is an array of valid HTTP methods.\n *\n * Each element is verified using the `isMethod` type guard.\n *\n * @param value - The value to check.\n * @returns `true` if `value` is an array and every element is a valid `Method`, otherwise `false`.\n */\nexport function isMethodArray(value: unknown): value is Method[] {\n return Array.isArray(value) && value.every(isMethod);\n}\n\n/**\n * Asserts that a value is an array of valid HTTP methods.\n *\n * This function uses {@link isMethodArray} to validate the input. If the\n * value is not an array of `Method` elements, it throws a `TypeError`.\n * Otherwise, TypeScript will narrow the type of `value` to `Method[]`\n * within the calling scope.\n *\n * @param value - The value to check.\n * @throws TypeError If `value` is not a valid {@link Method} array.\n */\nexport function assertMethods(value: unknown): asserts value is Method[] {\n if (!isMethodArray(value)) {\n const desc = Array.isArray(value) ? JSON.stringify(value) : String(value);\n throw new TypeError(`Invalid method array: ${desc}`);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Lexicographically compares two strings.\n *\n * This comparator can be used in `Array.prototype.sort()` to produce a\n * consistent, stable ordering of string arrays.\n *\n * @param a - The first string to compare.\n * @param b - The second string to compare.\n * @returns A number indicating the relative order of `a` and `b`.\n */\nexport function lexCompare(a: string, b: string): number {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { lexCompare } from \"./compare\";\n\n/**\n * Sets a header on the given Headers object.\n *\n * - If `value` is an array, any duplicates and empty strings are removed.\n * - If the resulting value is empty, the header is deleted.\n * - Otherwise, values are joined with `\", \"` and set as the header value.\n *\n * @param headers - The Headers object to modify.\n * @param key - The header name to set.\n * @param value - The header value(s) to set. Can be a string or array of strings.\n */\nexport function setHeader(headers: Headers, key: string, value: string | string[]): void {\n const raw = Array.isArray(value) ? value : [value];\n const values = Array.from(new Set(raw.map((v) => v.trim())))\n .filter((v) => v.length)\n .sort(lexCompare);\n\n if (!values.length) {\n headers.delete(key);\n return;\n }\n\n headers.set(key, values.join(\", \"));\n}\n\n/**\n * Merges new value(s) into an existing header on the given Headers object.\n *\n * - Preserves any existing values and adds new ones.\n * - Removes duplicates and trims all values.\n * - If the header does not exist, it is created.\n * - If the resulting value array is empty, the header is deleted.\n *\n * @param headers - The Headers object to modify.\n * @param key - The header name to merge into.\n * @param value - The new header value(s) to add. Can be a string or array of strings.\n */\nexport function mergeHeader(headers: Headers, key: string, value: string | string[]): void {\n const values = Array.isArray(value) ? value : [value];\n if (values.length === 0) return;\n\n const existing = getHeaderValues(headers, key);\n const merged = existing.concat(values.map((v) => v.trim()));\n\n setHeader(headers, key, merged);\n}\n\n/**\n * Returns the values of an HTTP header as an array of strings.\n *\n * This helper:\n * - Retrieves the header value by `key`.\n * - Splits the value on commas.\n * - Trims surrounding whitespace from each entry.\n * - Filters out any empty tokens.\n * - Removes duplicate values (case-sensitive)\n *\n * If the header is not present, an empty array is returned.\n *\n */\nexport function getHeaderValues(headers: Headers, key: string): string[] {\n const values =\n headers\n .get(key)\n ?.split(\",\")\n .map((v) => v.trim())\n .filter((v) => v.length > 0) ?? [];\n return Array.from(new Set(values)).sort(lexCompare);\n}\n\n/**\n * Removes a list of header fields from a {@link Headers} object.\n *\n * @param headers - The {@link Headers} object to modify in place.\n * @param keys - An array of header field names to remove. Header names are\n * matched case-insensitively per the Fetch spec.\n */\nexport function filterHeaders(headers: Headers, keys: string[]): void {\n for (const key of keys) {\n headers.delete(key);\n }\n}\n\n/**\n * Extracts all header names from a `Headers` object, normalizes them,\n * and returns them in a stable, lexicographically sorted array.\n *\n * @param headers - The `Headers` object to extract keys from.\n * @returns A sorted array of lowercase header names.\n */\nexport function getHeaderKeys(headers: Headers): string[] {\n return [...headers.keys()].sort(lexCompare);\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StatusCodes } from \"../constants\";\n\n/**\n * Returns the standard HTTP reason phrase for a status code.\n * Converts enum names (e.g. NOT_FOUND) into title-cased phrases.\n */\nexport function getReasonPhrase(status: StatusCodes): string {\n return StatusCodes[status]\n .toLowerCase()\n .replaceAll(\"_\", \" \")\n .replaceAll(/\\b\\w/g, (c) => c.toUpperCase());\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StatusCodes } from \"./constants\";\nimport { CacheControl } from \"./constants/cache\";\nimport { FORBIDDEN_204_HEADERS, FORBIDDEN_304_HEADERS, HttpHeader } from \"./constants/headers\";\nimport { MediaType, UTF8_CHARSET } from \"./constants/media\";\nimport { GET, HEAD } from \"./constants/methods\";\nimport { assertMethods } from \"./guards/methods\";\nimport { assertOctetStreamInit } from \"./guards/responses\";\nimport { Worker } from \"./interfaces\";\nimport { OctetStreamInit } from \"./interfaces/response\";\nimport { filterHeaders, mergeHeader, setHeader } from \"./utils/headers\";\nimport { withCharset } from \"./utils/media\";\nimport { getReasonPhrase } from \"./utils/reasons\";\n\n/**\n * Base class for building HTTP responses.\n * Manages headers, status, and media type.\n */\nabstract class BaseResponse {\n /** HTTP headers for the response. */\n public headers: Headers = new Headers();\n\n /** HTTP status code (default 200 OK). */\n public status: StatusCodes = StatusCodes.OK;\n\n /** Optional status text. Defaults to standard reason phrase. */\n public statusText?: string;\n\n /** Optional websocket property. */\n public webSocket?: WebSocket | null;\n\n /** Default media type of the response body. */\n public mediaType: string = \"text/plain; charset=utf-8\";\n\n /** Converts current state to ResponseInit for constructing a Response. */\n protected get responseInit(): ResponseInit {\n return {\n headers: this.headers,\n status: this.status,\n statusText: this.statusText ?? getReasonPhrase(this.status),\n webSocket: this.webSocket,\n encodeBody: \"automatic\",\n };\n }\n\n /** Sets a header, overwriting any existing value. */\n public setHeader(key: string, value: string | string[]): void {\n setHeader(this.headers, key, value);\n }\n\n /** Merges a header with existing values (does not overwrite). */\n public mergeHeader(key: string, value: string | string[]): void {\n mergeHeader(this.headers, key, value);\n }\n\n /** Adds a Content-Type header if not already existing (does not overwrite). */\n public addContentType() {\n if (!this.headers.get(HttpHeader.CONTENT_TYPE)) {\n this.setHeader(HttpHeader.CONTENT_TYPE, this.mediaType);\n }\n }\n\n /**\n * Removes headers that are disallowed or discouraged based on the current\n * status code.\n *\n * - **204 No Content:** strips headers that \"should not\" be sent\n * (`Content-Length`, `Content-Range`), per the HTTP spec.\n * - **304 Not Modified:** strips headers that \"must not\" be sent\n * (`Content-Type`, `Content-Length`, `Content-Range`, etc.), per the HTTP spec.\n *\n * This ensures that responses remain compliant with HTTP/1.1 standards while preserving\n * custom headers that are allowed.\n */\n public filterHeaders(): void {\n if (this.status === StatusCodes.NO_CONTENT) {\n filterHeaders(this.headers, FORBIDDEN_204_HEADERS);\n } else if (this.status === StatusCodes.NOT_MODIFIED) {\n filterHeaders(this.headers, FORBIDDEN_304_HEADERS);\n }\n }\n}\n\n/**\n * Base response class that adds caching headers.\n */\nabstract class CacheResponse extends BaseResponse {\n constructor(public cache?: CacheControl) {\n super();\n }\n\n /** Adds Cache-Control header if caching is configured. */\n protected addCacheHeader(): void {\n if (this.cache) {\n this.setHeader(HttpHeader.CACHE_CONTROL, CacheControl.stringify(this.cache));\n }\n }\n}\n\n/**\n * Core response. Combines caching, and content type headers.\n */\nexport abstract class WorkerResponse extends CacheResponse {\n constructor(\n private readonly body: BodyInit | null = null,\n cache?: CacheControl,\n ) {\n super(cache);\n }\n\n /** Builds the Response with body, headers, and status. */\n public async response(): Promise<Response> {\n this.addCacheHeader();\n\n const body = [StatusCodes.NO_CONTENT, StatusCodes.NOT_MODIFIED].includes(this.status)\n ? null\n : this.body;\n\n if (body) this.addContentType();\n\n this.filterHeaders();\n\n return new Response(body, this.responseInit);\n }\n}\n\n/**\n * Copies an existing response for mutation. Pass in a CacheControl\n * to be used for the response, overriding any existing `cache-control`\n * on the source response.\n */\nexport class CopyResponse extends WorkerResponse {\n constructor(response: Response, cache?: CacheControl) {\n super(response.body, cache);\n this.status = response.status;\n this.statusText = response.statusText;\n this.headers = new Headers(response.headers);\n }\n}\n\n/**\n * Copies the response, but with null body and status 304 Not Modified.\n */\nexport class NotModified extends WorkerResponse {\n constructor(response: Response) {\n super();\n this.status = StatusCodes.NOT_MODIFIED;\n this.headers = new Headers(response.headers);\n }\n}\n\n/**\n * Represents a successful response with customizable body, cache and status.\n */\nexport class SuccessResponse extends WorkerResponse {\n constructor(\n body: BodyInit | null = null,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n ) {\n super(body, cache);\n this.status = status;\n }\n}\n\n/**\n * JSON response. Automatically sets Content-Type to application/json.\n */\nexport class JsonResponse extends SuccessResponse {\n constructor(json: unknown = {}, cache?: CacheControl, status: StatusCodes = StatusCodes.OK) {\n super(JSON.stringify(json), cache, status);\n this.mediaType = withCharset(MediaType.JSON, UTF8_CHARSET);\n }\n}\n\n/**\n * HTML response. Automatically sets Content-Type to text/html.\n */\nexport class HtmlResponse extends SuccessResponse {\n constructor(\n body: string,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n charset: string = UTF8_CHARSET,\n ) {\n super(body, cache, status);\n this.mediaType = withCharset(MediaType.HTML, charset);\n }\n}\n\n/**\n * Plain text response. Automatically sets Content-Type to text/plain.\n */\nexport class TextResponse extends SuccessResponse {\n constructor(\n body: string,\n cache?: CacheControl,\n status: StatusCodes = StatusCodes.OK,\n charset: string = UTF8_CHARSET,\n ) {\n super(body, cache, status);\n this.mediaType = withCharset(MediaType.PLAIN_TEXT, charset);\n }\n}\n\n/**\n * Represents an HTTP response for serving binary data as `application/octet-stream`.\n *\n * This class wraps a `ReadableStream` and sets all necessary headers for both\n * full and partial content responses, handling range requests in a hybrid way\n * to maximize browser and CDN caching.\n *\n * Key behaviors:\n * - `Content-Type` is set to `application/octet-stream`.\n * - `Accept-Ranges: bytes` is always included.\n * - `Content-Length` is always set to the validated length of the response body.\n * - If the request is a true partial range (offset > 0 or length < size), the response\n * will be `206 Partial Content` with the appropriate `Content-Range` header.\n * - If the requested range covers the entire file (even if a Range header is present),\n * the response will return `200 OK` to enable browser and edge caching.\n * - Zero-length streams (`size = 0`) are never treated as partial.\n * - Special case: a requested range of `0-0` on a non-empty file is normalized to 1 byte.\n */\nexport class OctetStream extends WorkerResponse {\n constructor(stream: ReadableStream, init: OctetStreamInit, cache?: CacheControl) {\n assertOctetStreamInit(init);\n\n super(stream, cache);\n this.mediaType = MediaType.OCTET_STREAM;\n\n const normalized = OctetStream.normalizeInit(init);\n const { size, offset, length } = normalized;\n\n if (OctetStream.isPartial(normalized)) {\n this.setHeader(\n HttpHeader.CONTENT_RANGE,\n `bytes ${offset}-${offset + length - 1}/${size}`,\n );\n this.status = StatusCodes.PARTIAL_CONTENT;\n }\n\n this.setHeader(HttpHeader.ACCEPT_RANGES, \"bytes\");\n this.setHeader(HttpHeader.CONTENT_LENGTH, `${length}`);\n }\n\n /**\n * Normalizes a partially-specified `OctetStreamInit` into a fully-specified object.\n *\n * Ensures that all required fields (`size`, `offset`, `length`) are defined:\n * - `offset` defaults to 0 if not provided.\n * - `length` defaults to `size - offset` if not provided.\n * - Special case: if `offset` and `length` are both 0 but `size > 0`, `length` is set to 1\n * to avoid zero-length partial streams.\n *\n * @param init - The initial `OctetStreamInit` object, possibly with missing `offset` or `length`.\n * @returns A fully-specified `OctetStreamInit` object with `size`, `offset`, and `length` guaranteed.\n */\n private static normalizeInit(init: OctetStreamInit): Required<OctetStreamInit> {\n const { size } = init;\n const offset = init.offset ?? 0;\n let length = init.length ?? size - offset;\n\n if (offset === 0 && length === 0 && size > 0) {\n length = 1;\n }\n\n return { size, offset, length };\n }\n\n /**\n * Determines whether the given `OctetStreamInit` represents a partial range.\n *\n * Partial ranges are defined as any range that does **not** cover the entire file:\n * - If `size === 0`, the stream is never partial.\n * - If `offset === 0` and `length === size`, the stream is treated as a full file (not partial),\n * even if a Range header is present. This enables browser and CDN caching.\n * - All other cases are considered partial, and will result in a `206 Partial Content` response.\n *\n * @param init - A fully-normalized `OctetStreamInit` object.\n * @returns `true` if the stream represents a partial range; `false` if it represents the full file.\n */\n private static isPartial(init: Required<OctetStreamInit>): boolean {\n if (init.size === 0) return false;\n return !(init.offset === 0 && init.length === init.size);\n }\n}\n\n/**\n * A streaming response for Cloudflare R2 objects.\n *\n * **Partial content support:** To enable HTTP 206 streaming, you must provide\n * request headers containing the `Range` header when calling the R2 bucket's `get()` method.\n *\n * Example:\n * ```ts\n * const stream = await this.env.R2_BUCKET.get(\"key\", { range: this.request.headers });\n * ```\n *\n * @param source - The R2 object to stream.\n * @param cache - Optional caching override.\n */\nexport class R2ObjectStream extends OctetStream {\n constructor(source: R2ObjectBody, cache?: CacheControl) {\n let useCache = cache;\n if (!useCache && source.httpMetadata?.cacheControl) {\n useCache = CacheControl.parse(source.httpMetadata.cacheControl);\n }\n\n super(source.body, R2ObjectStream.computeRange(source.size, source.range), useCache);\n\n this.setHeader(HttpHeader.ETAG, source.httpEtag);\n\n if (source.httpMetadata?.contentType) {\n this.mediaType = source.httpMetadata.contentType;\n }\n }\n\n /**\n * Computes an `OctetStreamInit` object from a given R2 range.\n *\n * This function normalizes a Cloudflare R2 `R2Range` into the shape expected\n * by `OctetStream`. It handles the following cases:\n *\n * - No range provided: returns `{ size }` (full content).\n * - `suffix` range: calculates the offset and length from the end of the file.\n * - Explicit `offset` and/or `length`: passed through as-is.\n *\n * @param size - The total size of the file/object.\n * @param range - Optional range to extract (from R2). Can be:\n * - `{ offset: number; length?: number }`\n * - `{ offset?: number; length: number }`\n * - `{ suffix: number }`\n * @returns An `OctetStreamInit` object suitable for `OctetStream`.\n */\n private static computeRange(size: number, range?: R2Range): OctetStreamInit {\n if (!range) return { size };\n\n if (\"offset\" in range || \"length\" in range) {\n return { size, offset: range.offset, length: range.length };\n }\n\n /**\n * Cloudflare introduced a defect around 2025-12-18 where the runtime `R2Range`\n * included a `suffix` property alongside `offset` and `length`, even though this\n * is invalid per their TypeScript R2Range interface.\n */\n if (\"suffix\" in range && typeof range.suffix === \"number\") {\n const offset = Math.max(0, size - range.suffix);\n const length = size - offset;\n return { size, offset, length };\n }\n\n return { size };\n }\n}\n\n/**\n * Response for WebSocket upgrade requests.\n * Automatically sets status to 101 and attaches the client socket.\n */\nexport class WebSocketUpgrade extends WorkerResponse {\n constructor(client: WebSocket) {\n super();\n this.status = StatusCodes.SWITCHING_PROTOCOLS;\n this.webSocket = client;\n }\n}\n\n/**\n * Response for `HEAD` requests. Copy headers and status from a `GET` response\n * without the body.\n */\nexport class Head extends WorkerResponse {\n constructor(get: Response) {\n super();\n this.status = get.status;\n this.statusText = get.statusText;\n this.headers = new Headers(get.headers);\n }\n}\n\n/**\n * Response for `OPTIONS` requests.\n */\nexport class Options extends WorkerResponse {\n constructor(worker: Worker) {\n const allowed = Array.from(new Set([GET, HEAD, ...worker.getAllowedMethods()]));\n assertMethods(allowed);\n\n super();\n this.status = StatusCodes.NO_CONTENT;\n this.setHeader(HttpHeader.ALLOW, allowed);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpHeader } from \"../../constants/headers\";\nimport { assertMethods } from \"../../guards/methods\";\nimport { Worker } from \"../../interfaces/worker\";\nimport { CopyResponse } from \"../../responses\";\nimport { mergeHeader, setHeader } from \"../../utils/headers\";\n\nimport { ALLOW_ALL_ORIGINS, SKIP_CORS_STATUSES } from \"./constants\";\nimport { CorsConfig } from \"./interfaces\";\n\n/**\n * Handles a `CORS` preflight `OPTIONS` request.\n *\n * This function **modifies the provided response** to include the appropriate\n * CORS headers based on the configuration and the request's origin.\n *\n * Steps:\n * 1. Clears any existing CORS headers from the response.\n * 2. Sets `Vary: Origin` if needed for caching purposes.\n * 3. If an `Origin` header is present in the request:\n * - Sets `Access-Control-Allow-Origin`\n * - Sets `Access-Control-Allow-Credentials`\n * - Sets `Access-Control-Allow-Methods`\n * - Sets `Access-Control-Allow-Headers`\n * - Sets `Access-Control-Max-Age`\n *\n * @param response - The original Response object to modify for the preflight.\n * @param worker - The Worker handling the request.\n * @param cors - The CORS configuration to apply.\n * @returns A Response object suitable for responding to the preflight request.\n */\nexport function options(response: Response, worker: Worker, cors: CorsConfig): Promise<Response> {\n const copy = new CopyResponse(response);\n const origin = getOrigin(worker.request);\n\n deleteCorsHeaders(copy.headers);\n setVaryOrigin(copy.headers, cors);\n\n if (origin) {\n setAllowOrigin(copy.headers, cors, origin);\n setAllowCredentials(copy.headers, cors, origin);\n setAllowMethods(copy.headers, worker);\n setAllowHeaders(copy.headers, cors);\n setMaxAge(copy.headers, cors);\n }\n\n return copy.response();\n}\n\n/**\n * Applies CORS headers to an existing response for non-preflight requests.\n *\n * This function **modifies the provided response** to include the appropriate\n * CORS headers based on the configuration and the request's origin.\n *\n * Steps:\n * 1. Clears any existing CORS headers from the response.\n * 2. Sets `Vary: Origin` if needed for caching purposes.\n * 3. If an `Origin` header is present in the request:\n * - Sets `Access-Control-Allow-Origin`\n * - Sets `Access-Control-Allow-Credentials`\n * - Sets `Access-Control-Expose-Headers`\n *\n * @param response - The original Response object to modify.\n * @param worker - The Worker handling the request.\n * @param cors - The CORS configuration to apply.\n * @returns A Response object with CORS headers applied, suitable for returning\n * to the client.\n */\nexport function apply(response: Response, worker: Worker, cors: CorsConfig): Promise<Response> {\n const copy = new CopyResponse(response);\n const origin = getOrigin(worker.request);\n\n deleteCorsHeaders(copy.headers);\n setVaryOrigin(copy.headers, cors);\n\n if (origin) {\n setAllowOrigin(copy.headers, cors, origin);\n setAllowCredentials(copy.headers, cors, origin);\n setExposedHeaders(copy.headers, cors);\n }\n\n return copy.response();\n}\n\n/**\n * Adds `Vary: Origin` when `CORS` is restricted to specific origins.\n * This ensures caches differentiate responses by request origin.\n *\n * Skipped when all origins are allowed.\n *\n * @param headers - The headers object to modify.\n * @param cors - The `CORS` configuration.\n */\nexport function setVaryOrigin(headers: Headers, cors: CorsConfig): void {\n if (!allowAllOrigins(cors)) {\n mergeHeader(headers, HttpHeader.VARY, HttpHeader.ORIGIN);\n }\n}\n\n/**\n * Sets the Access-Control-Allow-Origin header based on the `CORS` config\n * and request origin.\n *\n * @param headers - The headers object to modify.\n * @param cors - The `CORS` configuration.\n * @param origin - The request's origin, or null if not present.\n */\nexport function setAllowOrigin(headers: Headers, cors: CorsConfig, origin: string): void {\n if (allowAllOrigins(cors)) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN, ALLOW_ALL_ORIGINS);\n return;\n }\n\n if (cors.allowedOrigins.includes(origin)) {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN, origin);\n }\n}\n\n/**\n * Conditionally sets the `Access-Control-Allow-Credentials` header\n * for a `CORS` response.\n *\n * This header is only set if:\n * 1. `cors.allowCredentials` is true,\n * 2. The configuration does **not** allow any origin (`*`), and\n * 3. The provided `origin` is explicitly listed in `cors.allowedOrigins`.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The `CORS` configuration.\n * @param origin - The origin of the incoming request.\n */\nexport function setAllowCredentials(headers: Headers, cors: CorsConfig, origin: string): void {\n if (!cors.allowCredentials) return;\n if (allowAllOrigins(cors)) return;\n if (!cors.allowedOrigins.includes(origin)) return;\n\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS, \"true\");\n}\n\n/**\n * Sets the `Access-Control-Allow-Methods` header for a `CORS` response.\n *\n * @param headers - The Headers object to modify.\n * @param worker - The Worker instance used to retrieve allowed methods.\n */\nexport function setAllowMethods(headers: Headers, worker: Worker): void {\n const allowed = worker.getAllowedMethods();\n assertMethods(allowed);\n\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_METHODS, allowed);\n}\n\n/**\n * Sets the `Access-Control-Max-Age` header for a `CORS` response.\n *\n * This header indicates how long the results of a preflight request\n * can be cached by the client (in seconds).\n *\n * The value is **clamped to a non-negative integer** to comply with\n * the `CORS` specification:\n * - Decimal values are floored to the nearest integer.\n * - Negative values are treated as `0`.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The `CORS` configuration containing the `maxAge` value in seconds.\n */\nexport function setMaxAge(headers: Headers, cors: CorsConfig): void {\n const maxAge = Math.max(0, Math.floor(cors.maxAge));\n setHeader(headers, HttpHeader.ACCESS_CONTROL_MAX_AGE, String(maxAge));\n}\n\n/**\n * Sets the Access-Control-Allow-Headers header based on the `CORS` configuration.\n *\n * Only the headers explicitly listed in `cors.allowedHeaders` are sent.\n * If the array is empty, no Access-Control-Allow-Headers header is added.\n *\n * @param headers - The Headers object to modify.\n * @param cors - The `CORS` configuration.\n */\nexport function setAllowHeaders(headers: Headers, cors: CorsConfig): void {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS, cors.allowedHeaders);\n}\n\n/**\n * Sets the Access-Control-Expose-Headers header for a response.\n *\n * @param headers - The headers object to modify.\n * @param cors - The `CORS` configuration.\n */\nexport function setExposedHeaders(headers: Headers, cors: CorsConfig): void {\n setHeader(headers, HttpHeader.ACCESS_CONTROL_EXPOSE_HEADERS, cors.exposedHeaders);\n}\n\n/**\n * Returns true if the `CORS` config allows all origins ('*').\n *\n * @param cors - The `CORS` configuration.\n */\nexport function allowAllOrigins(cors: CorsConfig): boolean {\n return cors.allowedOrigins.includes(ALLOW_ALL_ORIGINS);\n}\n\n/**\n * Deletes any existing `CORS` headers from the provided headers object.\n *\n * @param headers - The headers object to modify.\n */\nexport function deleteCorsHeaders(headers: Headers): void {\n headers.delete(HttpHeader.ACCESS_CONTROL_MAX_AGE);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_METHODS);\n headers.delete(HttpHeader.ACCESS_CONTROL_EXPOSE_HEADERS);\n headers.delete(HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS);\n}\n\n/**\n * Determines whether CORS headers should be skipped for a response.\n *\n * Certain responses do not require CORS headers, such as:\n * - Informational or protocol-level responses (1xx)\n * - Redirect responses (3xx)\n * - Responses initiating a protocol upgrade\n *\n * @param response - The Response object to inspect.\n * @returns `true` if CORS headers should be omitted, `false` otherwise.\n */\nexport function skipCors(response: Response): boolean {\n const { status, headers } = response;\n if (SKIP_CORS_STATUSES.includes(status)) return true;\n if (headers.has(HttpHeader.UPGRADE)) return true;\n\n return false;\n}\n\n/**\n * Extracts and normalizes the `Origin` header from a request.\n *\n * Returns the origin (scheme + host + port) as a string if present and valid.\n * Returns `null` if:\n * - The `Origin` header is missing\n * - The `Origin` header is `\"null\"` (opaque origin)\n * - The `Origin` header is malformed\n *\n * @param request - The incoming {@link Request} object.\n * @returns The normalized origin string, or `null` if not present or invalid.\n */\nexport function getOrigin(request: Request): string | null {\n const origin = request.headers.get(HttpHeader.ORIGIN)?.trim();\n if (!origin || origin === \"null\") return null;\n\n try {\n return new URL(origin).origin;\n } catch {\n return null;\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OPTIONS } from \"../../constants/methods\";\nimport { Middleware } from \"../../interfaces/middleware\";\nimport { Worker } from \"../../interfaces/worker\";\n\nimport { defaultCorsConfig } from \"./constants\";\nimport { CorsConfig, CorsInit } from \"./interfaces\";\nimport { apply, options, skipCors } from \"./utils\";\n\n/**\n * CORS Middleware Implementation\n *\n * Handles Cross-Origin Resource Sharing (CORS) for incoming requests.\n *\n * Behavior:\n * - Invokes the downstream middleware for all requests first by calling `next()`.\n * - If the request is an `OPTIONS` request (preflight), transforms the downstream\n * response into a preflight CORS response.\n * - For other HTTP methods, applies CORS headers to the downstream response,\n * unless the response explicitly opts out via `skipCors`.\n *\n * This ensures that all responses comply with the configured CORS rules\n * while still allowing downstream middleware to run for every request.\n *\n * @see {@link cors} for full configuration options and defaults.\n */\nexport class CorsHandler implements Middleware {\n /** The resolved CORS configuration for this middleware instance. */\n private readonly config: CorsConfig;\n\n /**\n * Constructs a new `CorsHandler` instance.\n *\n * Merges the provided partial configuration with the default settings.\n *\n * @param init - Optional partial configuration to override defaults.\n * Any fields not provided will use `defaultCorsConfig`.\n */\n constructor(init?: CorsInit) {\n this.config = { ...defaultCorsConfig, ...init };\n }\n\n /**\n * Applies CORS handling to an incoming request.\n *\n * @param worker - The Worker instance containing the request and context.\n * @param next - Function invoking the next middleware in the chain.\n * @returns A Response object with CORS headers applied.\n * - For `OPTIONS` requests, returns a preflight response based on\n * the downstream response.\n * - For other methods, returns the downstream response with\n * CORS headers applied, unless `skipCors` prevents it.\n */\n public async handle(worker: Worker, next: () => Promise<Response>): Promise<Response> {\n const response = await next();\n\n if (worker.request.method === OPTIONS) {\n return options(response, worker, this.config);\n }\n\n if (skipCors(response)) return response;\n\n return apply(response, worker, this.config);\n }\n}\n","/*\n * Copyright (C) 2025 Ty Busby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertCorsInit } from \"../../guards/cors\";\nimport { Middleware } from \"../../interfaces/middleware\";\n\nimport { CorsHandler } from \"./handler\";\nimport { CorsInit } from \"./interfaces\";\n\n/**\n * Returns a `CORS` middleware instance.\n *\n * This middleware automatically handles Cross-Origin Resource Sharing (CORS)\n * for incoming requests, including preflight `OPTIONS` requests, and adds\n * appropriate headers to responses.\n *\n * @param init - Optional configuration for `CORS` behavior. See {@link CorsConfig}.\n * @returns A {@link Middleware} instance that can be used in your middleware chain.\n */\nexport function cors(init?: CorsInit): Middleware {\n assertCorsInit(init);\n return new CorsHandler(init);\n}\n"]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import B from'cache-control-parser';import {match}from'path-to-regexp';var f={parse:B.parse,stringify:B.stringify,DISABLE:Object.freeze({"no-cache":true,"no-store":true,"must-revalidate":true,"max-age":0})};var _=(p=>(p.GET="GET",p.PUT="PUT",p.HEAD="HEAD",p.POST="POST",p.PATCH="PATCH",p.DELETE="DELETE",p.OPTIONS="OPTIONS",p))(_||{}),{GET:T,PUT:Ne,HEAD:m,POST:ue,PATCH:fe,DELETE:Re,OPTIONS:q}=_;var M=(t=>(t[t.CONTINUE=100]="CONTINUE",t[t.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",t[t.PROCESSING=102]="PROCESSING",t[t.EARLY_HINTS=103]="EARLY_HINTS",t[t.OK=200]="OK",t[t.CREATED=201]="CREATED",t[t.ACCEPTED=202]="ACCEPTED",t[t.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",t[t.NO_CONTENT=204]="NO_CONTENT",t[t.RESET_CONTENT=205]="RESET_CONTENT",t[t.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",t[t.MULTI_STATUS=207]="MULTI_STATUS",t[t.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",t[t.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",t[t.FOUND=302]="FOUND",t[t.SEE_OTHER=303]="SEE_OTHER",t[t.NOT_MODIFIED=304]="NOT_MODIFIED",t[t.USE_PROXY=305]="USE_PROXY",t[t.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",t[t.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",t[t.BAD_REQUEST=400]="BAD_REQUEST",t[t.UNAUTHORIZED=401]="UNAUTHORIZED",t[t.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",t[t.FORBIDDEN=403]="FORBIDDEN",t[t.NOT_FOUND=404]="NOT_FOUND",t[t.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",t[t.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",t[t.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",t[t.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",t[t.CONFLICT=409]="CONFLICT",t[t.GONE=410]="GONE",t[t.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",t[t.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",t[t.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",t[t.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",t[t.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",t[t.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",t[t.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",t[t.IM_A_TEAPOT=418]="IM_A_TEAPOT",t[t.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",t[t.METHOD_FAILURE=420]="METHOD_FAILURE",t[t.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",t[t.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",t[t.LOCKED=423]="LOCKED",t[t.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",t[t.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",t[t.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",t[t.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",t[t.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",t[t.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",t[t.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",t[t.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",t[t.BAD_GATEWAY=502]="BAD_GATEWAY",t[t.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",t[t.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",t[t.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",t[t.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",t[t.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",t))(M||{});var Ae={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};var i={ACCEPT_RANGES:"accept-ranges",ALLOW:"allow",CACHE_CONTROL:"cache-control",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",ETAG:"etag",SEC_WEBSOCKET_VERSION:"sec-websocket-version"},Y=[i.CONTENT_TYPE,i.CONTENT_LENGTH,i.CONTENT_RANGE,i.CONTENT_ENCODING,i.CONTENT_LANGUAGE,i.CONTENT_DISPOSITION,i.CONTENT_MD5],V=[i.CONTENT_LENGTH,i.CONTENT_RANGE];function Q(o){return typeof o=="string"}function A(o){return typeof o=="number"&&!Number.isNaN(o)}var Ee=new Set(Object.values(_));function C(o){return Q(o)&&Ee.has(o)}function he(o){return Array.isArray(o)&&o.every(C)}function O(o){if(!he(o)){let e=Array.isArray(o)?JSON.stringify(o):String(o);throw new TypeError(`Invalid method array: ${e}`)}}var I="utf-8";function $(o){if(typeof o!="object"||o===null)throw new TypeError("OctetStreamInit must be an object.");let e=o,r=e.size;if(!A(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(!A(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 n=e.length??r-s;if(!A(n)||n<0||s+n>r||!Number.isInteger(n))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(n)}).`)}function U(o,e){return o<e?-1:o>e?1:0}function G(o,e,r){let s=Array.isArray(r)?r:[r],n=Array.from(new Set(s.map(a=>a.trim()))).filter(a=>a.length).sort(U);if(!n.length){o.delete(e);return}o.set(e,n.join(", "));}function z(o,e,r){let s=Array.isArray(r)?r:[r];if(s.length===0)return;let a=Te(o,e).concat(s.map(d=>d.trim()));G(o,e,a);}function Te(o,e){let r=o.get(e)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(r)).sort(U)}function v(o,e){for(let r of e)o.delete(r);}function g(o,e){return !e||o.toLowerCase().includes("charset=")?o:`${o}; charset=${e.toLowerCase()}`}function x(o){return M[o].toLowerCase().replaceAll("_"," ").replaceAll(/\b\w/g,e=>e.toUpperCase())}var k=class{headers=new Headers;status=200;statusText;webSocket;mediaType="text/plain; charset=utf-8";get responseInit(){return {headers:this.headers,status:this.status,statusText:this.statusText??x(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(e,r){G(this.headers,e,r);}mergeHeader(e,r){z(this.headers,e,r);}addContentType(){this.headers.get(i.CONTENT_TYPE)||this.setHeader(i.CONTENT_TYPE,this.mediaType);}filterHeaders(){this.status===204?v(this.headers,V):this.status===304&&v(this.headers,Y);}},W=class extends k{constructor(r){super();this.cache=r;}addCacheHeader(){this.cache&&this.setHeader(i.CACHE_CONTROL,f.stringify(this.cache));}},E=class extends W{constructor(r=null,s){super(s);this.body=r;}async response(){this.addCacheHeader();let r=[204,304].includes(this.status)?null:this.body;return r&&this.addContentType(),this.filterHeaders(),new Response(r,this.responseInit)}},K=class extends E{constructor(e,r){super(e.body,r),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers);}},J=class extends E{constructor(e){super(),this.status=304,this.headers=new Headers(e.headers);}},R=class extends E{constructor(e=null,r,s=200){super(e,r),this.status=s;}},D=class extends R{constructor(e={},r,s=200){super(JSON.stringify(e),r,s),this.mediaType=g("application/json",I);}},j=class extends R{constructor(e,r,s=200,n=I){super(e,r,s),this.mediaType=g("text/html",n);}},X=class extends R{constructor(e,r,s=200,n=I){super(e,r,s),this.mediaType=g("text/plain",n);}},F=class o extends E{constructor(e,r,s){$(r),super(e,s),this.mediaType="application/octet-stream";let n=o.normalizeInit(r),{size:a,offset:d,length:p}=n;o.isPartial(n)&&(this.setHeader(i.CONTENT_RANGE,`bytes ${d}-${d+p-1}/${a}`),this.status=206),this.setHeader(i.ACCEPT_RANGES,"bytes"),this.setHeader(i.CONTENT_LENGTH,`${p}`);}static normalizeInit(e){let{size:r}=e,s=e.offset??0,n=e.length??r-s;return s===0&&n===0&&r>0&&(n=1),{size:r,offset:s,length:n}}static isPartial(e){return e.size===0?false:!(e.offset===0&&e.length===e.size)}},Z=class o extends F{constructor(e,r){let s=r;!s&&e.httpMetadata?.cacheControl&&(s=f.parse(e.httpMetadata.cacheControl)),super(e.body,o.computeRange(e.size,e.range),s),this.setHeader(i.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),n=e-s;return {size:e,offset:s,length:n}}return {size:e,...r}}},ee=class extends E{constructor(e){super(),this.status=101,this.webSocket=e;}},P=class extends E{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers);}},H=class extends E{constructor(e){let r=Array.from(new Set([T,m,...e.getAllowedMethods()]));O(r),super(),this.status=204,this.setHeader(i.ALLOW,r);}};var c=class extends D{constructor(r,s){let n={status:r,error:x(r),details:s??""};super(n,f.DISABLE,r);this.details=s;}},L=class extends c{constructor(e,r=500){let s=crypto.randomUUID();console.error(s,e),super(r,s);}},te=class extends c{constructor(e){super(400,e);}},re=class extends c{constructor(e){super(401,e);}},oe=class extends c{constructor(e){super(403,e);}},h=class extends c{constructor(e){super(404,e);}},N=class extends c{constructor(e){let r=e.getAllowedMethods();O(r),super(405,`${e.request.method} method not allowed.`),this.setHeader(i.ALLOW,r);}},se=class extends c{constructor(e){super(412,e);}},ne=class extends c{constructor(){super(426),this.setHeader(i.SEC_WEBSOCKET_VERSION,"13");}},ie=class extends c{constructor(e){super(500,e);}},S=class extends c{constructor(e){super(501,e);}},l=class extends S{constructor(e){super(`${e.request.method} method not implemented.`);}},ce=class extends c{constructor(e){super(503,e);}};function ae(o){if(o===null||typeof o!="object"||typeof o.handle!="function")throw new TypeError("Handler must implement the Middleware interface (have a handle method).")}var u=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 O(r),e===T||e===m?true:C(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 w=class extends u{middlewares=[];init(){}use(...e){for(let r of e)ae(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(N,this))()}};var y=class extends w{async fetch(){try{return await super.fetch()}catch(e){return this.response(L,e)}}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(N,this)))()}get(){return this.response(h)}put(){return this.response(l,this)}post(){return this.response(l,this)}patch(){return this.response(l,this)}delete(){return this.response(l,this)}options(){return this.response(H,this)}async head(){let e=this.create(new Request(this.request.url,{method:T,headers:this.request.headers}));return this.response(P,await e.fetch())}getAllowedMethods(){return [T,m,q]}};var b=class{routes=[];add(e){for(let[r,s,n]of e){let a=match(s,{sensitive:true});this.routes.push({method:r,matcher:a,handler:n});}}match(e,r){let s=new URL(r).pathname;for(let n of this){if(n.method!==e)continue;let a=n.matcher(s);if(a)return {route:n,params:a.params}}return null}*[Symbol.iterator](){yield*this.routes;}};var pe=class o extends y{_routes=new b;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 o.isWorkerClass(r)?new r(this.request,this.env,this.ctx).fetch():r.call(this,e.params)}static isWorkerClass(e){return Object.prototype.isPrototypeOf.call(u.prototype,e.prototype)}put(){return this.response(h)}post(){return this.response(h)}patch(){return this.response(h)}delete(){return this.response(h)}};export{te as BadRequest,y as BasicWorker,f as CacheControl,K as CopyResponse,Re as DELETE,oe as Forbidden,T as GET,m as HEAD,P as Head,j as HtmlResponse,c as HttpError,ie as InternalServerError,D as JsonResponse,L as LoggedHttpError,_ as Method,N as MethodNotAllowed,l as MethodNotImplemented,h as NotFound,S as NotImplemented,J as NotModified,q as OPTIONS,F as OctetStream,H as Options,fe as PATCH,ue as POST,Ne as PUT,se as PreconditionFailed,Z as R2ObjectStream,pe as RouteWorker,ce as ServiceUnavailable,M as StatusCodes,R as SuccessResponse,X as TextResponse,Ae as Time,re as Unauthorized,ne as UpgradeRequired,ee as WebSocketUpgrade,E as WorkerResponse};//# sourceMappingURL=index.js.map
1
+ import B from'cache-control-parser';import {match}from'path-to-regexp';var f={parse:B.parse,stringify:B.stringify,DISABLE:Object.freeze({"no-cache":true,"no-store":true,"must-revalidate":true,"max-age":0})};var _=(p=>(p.GET="GET",p.PUT="PUT",p.HEAD="HEAD",p.POST="POST",p.PATCH="PATCH",p.DELETE="DELETE",p.OPTIONS="OPTIONS",p))(_||{}),{GET:T,PUT:Ne,HEAD:m,POST:ue,PATCH:fe,DELETE:Re,OPTIONS:q}=_;var C=(t=>(t[t.CONTINUE=100]="CONTINUE",t[t.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",t[t.PROCESSING=102]="PROCESSING",t[t.EARLY_HINTS=103]="EARLY_HINTS",t[t.OK=200]="OK",t[t.CREATED=201]="CREATED",t[t.ACCEPTED=202]="ACCEPTED",t[t.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",t[t.NO_CONTENT=204]="NO_CONTENT",t[t.RESET_CONTENT=205]="RESET_CONTENT",t[t.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",t[t.MULTI_STATUS=207]="MULTI_STATUS",t[t.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",t[t.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",t[t.FOUND=302]="FOUND",t[t.SEE_OTHER=303]="SEE_OTHER",t[t.NOT_MODIFIED=304]="NOT_MODIFIED",t[t.USE_PROXY=305]="USE_PROXY",t[t.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",t[t.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",t[t.BAD_REQUEST=400]="BAD_REQUEST",t[t.UNAUTHORIZED=401]="UNAUTHORIZED",t[t.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",t[t.FORBIDDEN=403]="FORBIDDEN",t[t.NOT_FOUND=404]="NOT_FOUND",t[t.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",t[t.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",t[t.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",t[t.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",t[t.CONFLICT=409]="CONFLICT",t[t.GONE=410]="GONE",t[t.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",t[t.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",t[t.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",t[t.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",t[t.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",t[t.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",t[t.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",t[t.IM_A_TEAPOT=418]="IM_A_TEAPOT",t[t.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",t[t.METHOD_FAILURE=420]="METHOD_FAILURE",t[t.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",t[t.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",t[t.LOCKED=423]="LOCKED",t[t.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",t[t.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",t[t.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",t[t.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",t[t.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",t[t.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",t[t.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",t[t.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",t[t.BAD_GATEWAY=502]="BAD_GATEWAY",t[t.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",t[t.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",t[t.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",t[t.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",t[t.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",t))(C||{});var Ae={Second:1,Minute:60,Hour:3600,Day:86400,Week:604800,Month:2592e3,Year:31536e3};var i={ACCEPT_RANGES:"accept-ranges",ALLOW:"allow",CACHE_CONTROL:"cache-control",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",ETAG:"etag",SEC_WEBSOCKET_VERSION:"sec-websocket-version"},Y=[i.CONTENT_TYPE,i.CONTENT_LENGTH,i.CONTENT_RANGE,i.CONTENT_ENCODING,i.CONTENT_LANGUAGE,i.CONTENT_DISPOSITION,i.CONTENT_MD5],Q=[i.CONTENT_LENGTH,i.CONTENT_RANGE];function V(o){return typeof o=="string"}function A(o){return typeof o=="number"&&!Number.isNaN(o)}var Ee=new Set(Object.values(_));function M(o){return V(o)&&Ee.has(o)}function he(o){return Array.isArray(o)&&o.every(M)}function O(o){if(!he(o)){let e=Array.isArray(o)?JSON.stringify(o):String(o);throw new TypeError(`Invalid method array: ${e}`)}}var I="utf-8";function K(o){if(typeof o!="object"||o===null)throw new TypeError("OctetStreamInit must be an object.");let e=o,r=e.size;if(!A(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(!A(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 n=e.length??r-s;if(!A(n)||n<0||s+n>r||!Number.isInteger(n))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(n)}).`)}function U(o,e){return o<e?-1:o>e?1:0}function G(o,e,r){let s=Array.isArray(r)?r:[r],n=Array.from(new Set(s.map(a=>a.trim()))).filter(a=>a.length).sort(U);if(!n.length){o.delete(e);return}o.set(e,n.join(", "));}function $(o,e,r){let s=Array.isArray(r)?r:[r];if(s.length===0)return;let a=Te(o,e).concat(s.map(d=>d.trim()));G(o,e,a);}function Te(o,e){let r=o.get(e)?.split(",").map(s=>s.trim()).filter(s=>s.length>0)??[];return Array.from(new Set(r)).sort(U)}function v(o,e){for(let r of e)o.delete(r);}function g(o,e){return !e||o.toLowerCase().includes("charset=")?o:`${o}; charset=${e.toLowerCase()}`}function x(o){return C[o].toLowerCase().replaceAll("_"," ").replaceAll(/\b\w/g,e=>e.toUpperCase())}var k=class{headers=new Headers;status=200;statusText;webSocket;mediaType="text/plain; charset=utf-8";get responseInit(){return {headers:this.headers,status:this.status,statusText:this.statusText??x(this.status),webSocket:this.webSocket,encodeBody:"automatic"}}setHeader(e,r){G(this.headers,e,r);}mergeHeader(e,r){$(this.headers,e,r);}addContentType(){this.headers.get(i.CONTENT_TYPE)||this.setHeader(i.CONTENT_TYPE,this.mediaType);}filterHeaders(){this.status===204?v(this.headers,Q):this.status===304&&v(this.headers,Y);}},W=class extends k{constructor(r){super();this.cache=r;}addCacheHeader(){this.cache&&this.setHeader(i.CACHE_CONTROL,f.stringify(this.cache));}},E=class extends W{constructor(r=null,s){super(s);this.body=r;}async response(){this.addCacheHeader();let r=[204,304].includes(this.status)?null:this.body;return r&&this.addContentType(),this.filterHeaders(),new Response(r,this.responseInit)}},z=class extends E{constructor(e,r){super(e.body,r),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers);}},J=class extends E{constructor(e){super(),this.status=304,this.headers=new Headers(e.headers);}},R=class extends E{constructor(e=null,r,s=200){super(e,r),this.status=s;}},D=class extends R{constructor(e={},r,s=200){super(JSON.stringify(e),r,s),this.mediaType=g("application/json",I);}},j=class extends R{constructor(e,r,s=200,n=I){super(e,r,s),this.mediaType=g("text/html",n);}},X=class extends R{constructor(e,r,s=200,n=I){super(e,r,s),this.mediaType=g("text/plain",n);}},F=class o extends E{constructor(e,r,s){K(r),super(e,s),this.mediaType="application/octet-stream";let n=o.normalizeInit(r),{size:a,offset:d,length:p}=n;o.isPartial(n)&&(this.setHeader(i.CONTENT_RANGE,`bytes ${d}-${d+p-1}/${a}`),this.status=206),this.setHeader(i.ACCEPT_RANGES,"bytes"),this.setHeader(i.CONTENT_LENGTH,`${p}`);}static normalizeInit(e){let{size:r}=e,s=e.offset??0,n=e.length??r-s;return s===0&&n===0&&r>0&&(n=1),{size:r,offset:s,length:n}}static isPartial(e){return e.size===0?false:!(e.offset===0&&e.length===e.size)}},Z=class o extends F{constructor(e,r){let s=r;!s&&e.httpMetadata?.cacheControl&&(s=f.parse(e.httpMetadata.cacheControl)),super(e.body,o.computeRange(e.size,e.range),s),this.setHeader(i.ETAG,e.httpEtag),e.httpMetadata?.contentType&&(this.mediaType=e.httpMetadata.contentType);}static computeRange(e,r){if(!r)return {size:e};if("offset"in r||"length"in r)return {size:e,offset:r.offset,length:r.length};if("suffix"in r&&typeof r.suffix=="number"){let s=Math.max(0,e-r.suffix),n=e-s;return {size:e,offset:s,length:n}}return {size:e}}},ee=class extends E{constructor(e){super(),this.status=101,this.webSocket=e;}},P=class extends E{constructor(e){super(),this.status=e.status,this.statusText=e.statusText,this.headers=new Headers(e.headers);}},H=class extends E{constructor(e){let r=Array.from(new Set([T,m,...e.getAllowedMethods()]));O(r),super(),this.status=204,this.setHeader(i.ALLOW,r);}};var c=class extends D{constructor(r,s){let n={status:r,error:x(r),details:s??""};super(n,f.DISABLE,r);this.details=s;}},L=class extends c{constructor(e,r=500){let s=crypto.randomUUID();console.error(s,e),super(r,s);}},te=class extends c{constructor(e){super(400,e);}},re=class extends c{constructor(e){super(401,e);}},oe=class extends c{constructor(e){super(403,e);}},h=class extends c{constructor(e){super(404,e);}},N=class extends c{constructor(e){let r=e.getAllowedMethods();O(r),super(405,`${e.request.method} method not allowed.`),this.setHeader(i.ALLOW,r);}},se=class extends c{constructor(e){super(412,e);}},ne=class extends c{constructor(){super(426),this.setHeader(i.SEC_WEBSOCKET_VERSION,"13");}},ie=class extends c{constructor(e){super(500,e);}},S=class extends c{constructor(e){super(501,e);}},l=class extends S{constructor(e){super(`${e.request.method} method not implemented.`);}},ce=class extends c{constructor(e){super(503,e);}};function ae(o){if(o===null||typeof o!="object"||typeof o.handle!="function")throw new TypeError("Handler must implement the Middleware interface (have a handle method).")}var u=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 O(r),e===T||e===m?true:M(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 y=class extends u{middlewares=[];init(){}use(...e){for(let r of e)ae(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(N,this))()}};var w=class extends y{async fetch(){try{return await super.fetch()}catch(e){return this.response(L,e)}}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(N,this)))()}get(){return this.response(h)}put(){return this.response(l,this)}post(){return this.response(l,this)}patch(){return this.response(l,this)}delete(){return this.response(l,this)}options(){return this.response(H,this)}async head(){let e=this.create(new Request(this.request.url,{method:T,headers:this.request.headers}));return this.response(P,await e.fetch())}getAllowedMethods(){return [T,m,q]}};var b=class{routes=[];add(e){for(let[r,s,n]of e){let a=match(s,{sensitive:true});this.routes.push({method:r,matcher:a,handler:n});}}match(e,r){let s=new URL(r).pathname;for(let n of this){if(n.method!==e)continue;let a=n.matcher(s);if(a)return {route:n,params:a.params}}return null}*[Symbol.iterator](){yield*this.routes;}};var pe=class o extends w{_routes=new b;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 o.isWorkerClass(r)?new r(this.request,this.env,this.ctx).fetch():r.call(this,e.params)}static isWorkerClass(e){return Object.prototype.isPrototypeOf.call(u.prototype,e.prototype)}put(){return this.response(h)}post(){return this.response(h)}patch(){return this.response(h)}delete(){return this.response(h)}};export{te as BadRequest,w as BasicWorker,f as CacheControl,z as CopyResponse,Re as DELETE,oe as Forbidden,T as GET,m as HEAD,P as Head,j as HtmlResponse,c as HttpError,ie as InternalServerError,D as JsonResponse,L as LoggedHttpError,_ as Method,N as MethodNotAllowed,l as MethodNotImplemented,h as NotFound,S as NotImplemented,J as NotModified,q as OPTIONS,F as OctetStream,H as Options,fe as PATCH,ue as POST,Ne as PUT,se as PreconditionFailed,Z as R2ObjectStream,pe as RouteWorker,ce as ServiceUnavailable,C as StatusCodes,R as SuccessResponse,X as TextResponse,Ae as Time,re as Unauthorized,ne as UpgradeRequired,ee as WebSocketUpgrade,E as WorkerResponse};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map