rossa 0.0.6 → 0.1.2
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/CHANGELOG.md +50 -0
- package/README.md +175 -77
- package/dist/index.d.ts +969 -77
- package/dist/index.js +31 -29
- package/package.json +10 -5
package/dist/index.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
class ne{data;constructor(e={}){this.data={...e}}_add(e,t){return this.data[e]=t,this}add(e,t){return this._add(e,t)}}class se extends ne{frameOptions(e="DENY"){return this._add("X-Frame-Options",e)}noSniff(){return this._add("X-Content-Type-Options","nosniff")}hsts(e=31536000){return this._add("Strict-Transport-Security",`max-age=${e}; includeSubDomains; preload`)}csp(e="default-src 'self'"){return this._add("Content-Security-Policy",e)}referrer(e="strict-origin-when-cross-origin"){return this._add("Referrer-Policy",e)}coop(e="same-origin"){return this._add("Cross-Origin-Opener-Policy",e)}coep(e="require-corp"){return this._add("Cross-Origin-Embedder-Policy",e)}permissions(e){return this._add("Permissions-Policy",e)}}class ie extends se{cors(e="*"){return this._add("Access-Control-Allow-Origin",e),this._add("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),this._add("Access-Control-Allow-Headers","Content-Type, Authorization"),this}cache(e=3600){return this._add("Cache-Control",`public, max-age=${e}`)}noCache(){return this._add("Cache-Control","no-store, no-cache, must-revalidate")}etag(e){return this._add("ETag",`"${e}"`)}serverTiming(e,t,r=""){return this._add("Server-Timing",`${e};dur=${t};desc="${r}"`)}rateLimit(e,t,r){return this._add("X-RateLimit-Limit",e.toString()),this._add("X-RateLimit-Remaining",t.toString()),this._add("X-RateLimit-Reset",r.toString())}retryAfter(e){return this._add("Retry-After",e.toString())}expires(e){return this._add("Expires",e.toUTCString())}lastModified(e){return this._add("Last-Modified",e.toUTCString())}}class ae extends ie{authenticate(e,t){let r=t?`${e} ${t}`:e;return this._add("WWW-Authenticate",r)}proxyAuthenticate(e){return this._add("Proxy-Authenticate",e)}}class oe extends ae{content(e){if(e.length!==void 0)this.contentLength(e.length);if(e.type)this.contentType(e.type);if(e.encoding)this.contentEncoding(e.encoding);if(e.language)this.language(e.language);if(e.range)this.contentRange(e.range);if(e.location)this.contentLocation(e.location);if(e.md5)this.contentMD5(e.md5);if(e.disposition)this.disposition(e.disposition.type,e.disposition.filename);return this}contentLength(e){return this._add("Content-Length",e.toString())}contentMD5(e){return this._add("Content-MD5",e)}contentType(e){return this._add("Content-Type",e)}contentEncoding(e){return this._add("Content-Encoding",e)}contentLocation(e){return this._add("Content-Location",e)}contentRange(e){return this._add("Content-Range",e)}contentSecurity(e){return this._add("Content-Security",e)}disposition(e="attachment",t){let r=t?`${e}; filename="${t}"`:e;return this._add("Content-Disposition",r)}vary(...e){return this._add("Vary",e.join(", "))}language(e){return this._add("Content-Language",e)}}class ce extends oe{location(e){return this._add("Location",e)}origin(e="*"){return this._add("Access-Control-Allow-Origin",e)}date(e=new Date){return this._add("Date",e.toUTCString())}server(e){return this._add("Server",e)}connection(e){return this._add("Connection",e)}keepAlive(e){return this._add("Keep-Alive",String(e))}cookie(e,t,r={sameSite:"Strict",httpOnly:!0,path:"/"}){if(!r.expires){let n=new Date;n.setDate(n.getDate()+31),r.expires=n}return this._add("Set-Cookie",dt(e,t,r))}}var dt=(e,t="",r={})=>{let{maxAge:n,expires:s,path:i,domain:a,secure:o,httpOnly:c,sameSite:d}=r,u=n instanceof Date?Math.floor(n.getTime()/1000):typeof n==="number"?n:void 0,m;if(s instanceof Date)m=s.toUTCString();else if(typeof s==="number")m=new Date(s).toUTCString();else if(typeof s==="string")m=s;else if(s===0)m=new Date().toUTCString();let f=[];if(a)f.push(`Domain=${a}`);if(m)f.push(`Expires=${m}`);if(u!==void 0)f.push(`Max-Age=${u}`);if(o)f.push("Secure");if(c)f.push("HttpOnly");if(i!=null)f.push(`Path=${i}`);if(d!=null)f.push(`SameSite=${d}`);return[`${e}=${t}`,...f].join("; ")};class D extends ce{get copy(){return new D(this.data)}use(e){return e(this),this}merge(e){return Object.assign(this.data,e instanceof D?e.data:e),this}static init(e){return new this(e)}static get $(){return new this}get done(){return this.data}}class L{res;params={};headr;url;data={};jwtData={};session;body;query={};form={};req;method="GET";methods=[];clientDirectory="";constructor(e){this.res=e;this.headr=new D,this.req=e.req,this.url=this.req.url}}import{isAbsolute as _e,relative as Le,resolve as Ie,sep as Pe}from"path";import{realpath as ke}from"fs/promises";var ue=new Map,qe=new Set([".js",".css",".html",".htm",".css",".js",".mjs",".cjs",".jsx",".tsx",".xml",".xhtml",".jpg",".jpeg",".png",".gif",".webp",".avif",".bmp",".tiff",".svg",".txt",".ico",".woff",".woff2",".json"]);function Ue(e){let t=e.trim().toLowerCase();if(!t)return"";return t.startsWith(".")?t:`.${t}`}function le(e,t=new Set){let r=e.slice(e.lastIndexOf("/")+1).toLowerCase();return[...qe,...t].map(Ue).filter(Boolean).some((s)=>r.endsWith(s))}class de{absoluteClientPath;additionalExtensions;SMALL_FILE_THRESHOLD=51200;CACHE_TTL=900000;constructor(e,t=[]){this.absoluteClientPath=Ie(e),this.additionalExtensions=new Set(t.map(Ue).filter(Boolean))}isFile(e){return le(e,this.additionalExtensions)}async serve(e,t){let r=e.url.pathname,n=Ie(this.absoluteClientPath,`.${r}`),s=Le(this.absoluteClientPath,n);if(s===".."||s.startsWith(`..${Pe}`)||_e(s))return t.error(403,"Forbidden");let i,a;try{[i,a]=await Promise.all([ke(this.absoluteClientPath),ke(n)])}catch{return t.null(404)}let o=Le(i,a);if(o===".."||o.startsWith(`..${Pe}`)||_e(o))return t.error(403,"Forbidden");let c=Date.now(),d=ue.get(a);if(d&&c>d.expiresAt)ue.delete(a),d=void 0;if(!d){let m=Bun.file(a);if(!await m.exists())return t.null(404);if(m.size<=this.SMALL_FILE_THRESHOLD){let f=await m.arrayBuffer(),h=new Uint8Array(f),A=`W/"${Bun.hash(h).toString(16)}"`;d={buffer:h,contentType:m.type||"application/octet-stream",etag:A,expiresAt:c+this.CACHE_TTL},ue.set(a,d)}}if(d){let m=e.headers.get("If-None-Match"),f={ETag:d.etag,"Cache-Control":`public, max-age=${this.CACHE_TTL/1000}, must-revalidate`};if(m===d.etag)return new Response(null,{status:304,headers:f});return t.file(d.buffer,{type:d.contentType,size:d.buffer.length},f)}let u=Bun.file(a);if(await u.exists())return t.file(u);return t.null(404)}}class I{request;server;fileDetector;params={};_url;_query;_cookies;_formData;_json;_txt;constructor(e,t,r=le){this.request=e;this.server=t;this.fileDetector=r}async text(){if(this._txt!==void 0)return this._txt;try{return this._txt=await this.request.text(),this._txt}catch{return this._txt=""}}async json(){if(this._json!==void 0)return this._json;try{let e=await this.text();return this._json=e?JSON.parse(e):{},this._json}catch{return this._json={}}}async form(){if(!this.isForm)return new FormData;if(this._formData!==void 0)return this._formData;try{return this._formData=await this.request.formData(),this._formData}catch{return this._formData=new FormData}}get url(){return this._url??=new URL(this.request.url)}get query(){if(this._query)return this._query;return this._query=Object.fromEntries(this.url.searchParams.entries()),this._query}get cookies(){if(!this._cookies){let e=this.request.headers.get("cookie");if(this._cookies=new Map,e)e.split(";").forEach((t)=>{let[r,...n]=t.trim().split("=");this._cookies.set(r,n.join("="))})}return this._cookies}get auth(){let e=this.request.headers.get("authorization");if(!e?.startsWith("Bearer "))return;return e.substring(7)}get method(){return this.request.method.toUpperCase()}get headers(){return this.request.headers}header(e){return this.request.headers.get(e)}get ip(){return this.server?.requestIP(this.request)??null}get path(){return this.url.pathname}get isForm(){let e=this.request.headers.get("content-type");return!!e&&(e.includes("multipart/form-data")||e.includes("application/x-www-form-urlencoded"))}get isWSS(){return this.request.headers.get("upgrade")?.toLowerCase()==="websocket"}get isEventStream(){if(this.request.method.toUpperCase()!=="GET")return!1;return(this.request.headers.get("accept")??"").split(",").some((e)=>{let[t,...r]=e.trim().split(";");if(t?.trim().toLowerCase()!=="text/event-stream")return!1;for(let n of r){let s=n.trim().match(/^q\s*=\s*(0(?:\.\d+)?|1(?:\.0+)?)$/i);if(s&&Number(s[1])===0)return!1}return!0})}get isFile(){return this.fileDetector(this.path)}async getAuthCredentials(){let e=this.isForm?await this.form():null;return{sid:this.cookies.get("session")??"",jwt:this.auth??"",refresh:e?.get("refresh_token")?.toString()??""}}upgrade(e={}){return this.server?.upgrade(this.request,{data:e})??!1}}var ft={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",413:"Payload Too Large",415:"Unsupported Media Type",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",503:"Service Unavailable"};function l(e,t){let r=e.code??400,n={"Access-Control-Allow-Origin":"*",...e.headers||{}};if(e.redirect)return n.Location=e.redirect,new Response(null,{status:302,headers:n});n["Content-Type"]="application/json; charset=utf-8";let s=e.message??ft[r]??"An unexpected error occurred",i=JSON.stringify({success:!1,error:s,...t!==void 0&&{details:t}});return new Response(i,{status:r,headers:n})}var{gzipSync:mt,deflateSync:pt,zstdCompressSync:ht}=globalThis.Bun;import{brotliCompressSync as gt}from"zlib";var yt=["br","gzip","deflate","zstd"];class P{static negotiate(e,t){if(!e||e==="none"||!t)return;let r=new Map;for(let i of t.split(",")){let[a,...o]=i.trim().toLowerCase().split(";");if(!a)continue;let c=1;for(let d of o){let u=d.trim().match(/^q\s*=\s*(0(?:\.\d+)?|1(?:\.0+)?)$/);if(u)c=Number(u[1])}r.set(a,c)}let n=r.get("*"),s=yt.map((i,a)=>({encoding:i,order:a,q:r.get(i)??n??0})).filter((i)=>i.q>0);if(s.sort((i,a)=>a.q-i.q||i.order-a.order),r.get(e)===0)return s.find((i)=>i.encoding!==e)?.encoding;return s.find((i)=>i.encoding===e)?.encoding??s[0]?.encoding}static handle(e,t){if(!t||t==="none")return{payload:e};try{let r=e;switch(t){case"gzip":return{payload:mt(r),encoding:"gzip"};case"deflate":return{payload:pt(r),encoding:"deflate"};case"br":return{payload:gt(r),encoding:"br"};case"zstd":return{payload:ht(r),encoding:"zstd"};default:return{payload:e}}}catch(r){return console.error(`[Compressor] Failed to compress using ${t}:`,r),{payload:e}}}static toUint8(e){if(e===null||e===void 0)return new Uint8Array;if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);let t=typeof e==="string"?e:JSON.stringify(e);return new TextEncoder().encode(t)}}class K{static data(e){return`data: ${typeof e==="object"?JSON.stringify(e):String(e)}
|
|
2
|
+
var Gt=Object.defineProperty;var Jt=(e)=>e;function Vt(e,t){this[e]=Jt.bind(null,t)}var Yt=(e,t)=>{for(var r in t)Gt(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Vt.bind(t,r)})};var Ft={};Yt(Ft,{array:()=>tn,boolean:()=>en,coerce:()=>nn,number:()=>Zr,object:()=>rn,string:()=>Xr});class we{data;constructor(e={}){this.data={...e}}_add(e,t){return this.data[e]=t,this}add(e,t){return this._add(e,t)}}class Te extends we{frameOptions(e="DENY"){return this._add("X-Frame-Options",e)}noSniff(){return this._add("X-Content-Type-Options","nosniff")}hsts(e=31536000){return this._add("Strict-Transport-Security",`max-age=${e}; includeSubDomains; preload`)}csp(e="default-src 'self'"){return this._add("Content-Security-Policy",e)}referrer(e="strict-origin-when-cross-origin"){return this._add("Referrer-Policy",e)}coop(e="same-origin"){return this._add("Cross-Origin-Opener-Policy",e)}coep(e="require-corp"){return this._add("Cross-Origin-Embedder-Policy",e)}permissions(e){return this._add("Permissions-Policy",e)}}class Re extends Te{cors(e="*"){return this._add("Access-Control-Allow-Origin",e),this._add("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),this._add("Access-Control-Allow-Headers","Content-Type, Authorization"),this}cache(e=3600){return this._add("Cache-Control",`public, max-age=${e}`)}noCache(){return this._add("Cache-Control","no-store, no-cache, must-revalidate")}etag(e){return this._add("ETag",`"${e}"`)}serverTiming(e,t,r=""){return this._add("Server-Timing",`${e};dur=${t};desc="${r}"`)}rateLimit(e,t,r){return this._add("X-RateLimit-Limit",e.toString()),this._add("X-RateLimit-Remaining",t.toString()),this._add("X-RateLimit-Reset",r.toString())}retryAfter(e){return this._add("Retry-After",e.toString())}expires(e){return this._add("Expires",e.toUTCString())}lastModified(e){return this._add("Last-Modified",e.toUTCString())}}class Ee extends Re{authenticate(e,t){let r=t?`${e} ${t}`:e;return this._add("WWW-Authenticate",r)}proxyAuthenticate(e){return this._add("Proxy-Authenticate",e)}}class xe extends Ee{content(e){if(e.length!==void 0)this.contentLength(e.length);if(e.type)this.contentType(e.type);if(e.encoding)this.contentEncoding(e.encoding);if(e.language)this.language(e.language);if(e.range)this.contentRange(e.range);if(e.location)this.contentLocation(e.location);if(e.md5)this.contentMD5(e.md5);if(e.disposition)this.disposition(e.disposition.type,e.disposition.filename);return this}contentLength(e){return this._add("Content-Length",e.toString())}contentMD5(e){return this._add("Content-MD5",e)}contentType(e){return this._add("Content-Type",e)}contentEncoding(e){return this._add("Content-Encoding",e)}contentLocation(e){return this._add("Content-Location",e)}contentRange(e){return this._add("Content-Range",e)}contentSecurity(e){return this._add("Content-Security",e)}disposition(e="attachment",t){let r=t?`${e}; filename="${t}"`:e;return this._add("Content-Disposition",r)}vary(...e){return this._add("Vary",e.join(", "))}language(e){return this._add("Content-Language",e)}}class Ce extends xe{location(e){return this._add("Location",e)}origin(e="*"){return this._add("Access-Control-Allow-Origin",e)}date(e=new Date){return this._add("Date",e.toUTCString())}server(e){return this._add("Server",e)}connection(e){return this._add("Connection",e)}keepAlive(e){return this._add("Keep-Alive",String(e))}cookie(e,t,r={sameSite:"Strict",httpOnly:!0,path:"/"}){if(!r.expires){let n=new Date;n.setDate(n.getDate()+31),r.expires=n}return this._add("Set-Cookie",Qt(e,t,r))}}var Qt=(e,t="",r={})=>{let{maxAge:n,expires:s,path:i,domain:a,secure:o,httpOnly:c,sameSite:u}=r,l=n instanceof Date?Math.floor(n.getTime()/1000):typeof n==="number"?n:void 0,m;if(s instanceof Date)m=s.toUTCString();else if(typeof s==="number")m=new Date(s).toUTCString();else if(typeof s==="string")m=s;else if(s===0)m=new Date().toUTCString();let f=[];if(a)f.push(`Domain=${a}`);if(m)f.push(`Expires=${m}`);if(l!==void 0)f.push(`Max-Age=${l}`);if(o)f.push("Secure");if(c)f.push("HttpOnly");if(i!=null)f.push(`Path=${i}`);if(u!=null)f.push(`SameSite=${u}`);return[`${e}=${t}`,...f].join("; ")};class I extends Ce{get copy(){return new I(this.data)}use(e){return e(this),this}merge(e){return Object.assign(this.data,e instanceof I?e.data:e),this}static init(e){return new this(e)}static get $(){return new this}get done(){return this.data}}class H{res;params={};headr;url;data={};jwtData={};session;body;query={};form={};req;method="GET";methods=[];clientDirectory="";constructor(e){this.res=e;this.headr=new I,this.req=e.req,this.url=this.req.url}}import{isAbsolute as Xe,relative as Ze,resolve as et,sep as tt}from"path";import{realpath as rt}from"fs/promises";var N=new Map,nt=1000;function Xt(e){if(N.size<nt)return;for(let[t,r]of N)if(r.expiresAt<=e)N.delete(t);while(N.size>=nt){let t=N.keys().next().value;if(t===void 0)break;N.delete(t)}}var st=new Set([".js",".css",".html",".htm",".css",".js",".mjs",".cjs",".jsx",".tsx",".xml",".xhtml",".jpg",".jpeg",".png",".gif",".webp",".avif",".bmp",".tiff",".svg",".txt",".ico",".woff",".woff2",".json"]);function it(e){let t=e.trim().toLowerCase();if(!t)return"";return t.startsWith(".")?t:`.${t}`}function ee(e,t=new Set){let r=e.slice(e.lastIndexOf("/")+1).toLowerCase();return[...st,...t].map(it).filter(Boolean).some((s)=>r.endsWith(s))}class te{absoluteClientPath;additionalExtensions;SMALL_FILE_THRESHOLD=51200;CACHE_TTL=900000;constructor(e,t=[]){this.absoluteClientPath=et(e),this.additionalExtensions=new Set(t.map(it).filter(Boolean))}isFile(e){return ee(e,this.additionalExtensions)}async serve(e,t,r){let n;if(r===void 0)try{n=decodeURIComponent(e.url.pathname)}catch{return t.error(400,"Bad Request")}else n=r;if(n.includes("\x00"))return t.error(400,"Bad Request");let s=et(this.absoluteClientPath,`.${n}`),i=Ze(this.absoluteClientPath,s);if(i===".."||i.startsWith(`..${tt}`)||Xe(i))return t.error(403,"Forbidden");let a,o;try{[a,o]=await Promise.all([rt(this.absoluteClientPath),rt(s)])}catch{return t.null(404)}let c=Ze(a,o);if(c===".."||c.startsWith(`..${tt}`)||Xe(c))return t.error(403,"Forbidden");let u=Date.now(),l=N.get(o);if(l&&u>l.expiresAt)N.delete(o),l=void 0;if(!l){let f=Bun.file(o);if(!await f.exists())return t.null(404);if(f.size<=this.SMALL_FILE_THRESHOLD){let p=await f.arrayBuffer(),T=new Uint8Array(p),x=`W/"${Bun.hash(T).toString(16)}"`;l={buffer:T,contentType:f.type||"application/octet-stream",etag:x,expiresAt:u+this.CACHE_TTL},Xt(u),N.set(o,l)}}if(l){let f=e.headers.get("If-None-Match"),p={ETag:l.etag,"Cache-Control":`public, max-age=${this.CACHE_TTL/1000}, must-revalidate`};if(f===l.etag)return new Response(null,{status:304,headers:p});return t.file(l.buffer,{type:l.contentType,size:l.buffer.length},p)}let m=Bun.file(o);if(await m.exists())return t.file(m);return t.null(404)}}class W{request;server;fileDetector;params={};_url;_query;_cookies;_formData;_json;_txt;constructor(e,t,r=ee){this.request=e;this.server=t;this.fileDetector=r}async text(){if(this._txt!==void 0)return this._txt;try{return this._txt=await this.request.text(),this._txt}catch{return this._txt=""}}async json(){if(this._json!==void 0)return this._json;try{let e=await this.text();return this._json=e?JSON.parse(e):{},this._json}catch{return this._json={}}}async form(){if(!this.isForm)return new FormData;if(this._formData!==void 0)return this._formData;try{return this._formData=await this.request.formData(),this._formData}catch{return this._formData=new FormData}}get url(){return this._url??=new URL(this.request.url)}get query(){if(this._query)return this._query;return this._query=Object.fromEntries(this.url.searchParams.entries()),this._query}get cookies(){if(!this._cookies){let e=this.request.headers.get("cookie");if(this._cookies=new Map,e)e.split(";").forEach((t)=>{let[r,...n]=t.trim().split("=");this._cookies.set(r,n.join("="))})}return this._cookies}get auth(){let e=this.request.headers.get("authorization");if(!e?.startsWith("Bearer "))return;return e.substring(7)}get method(){return this.request.method.toUpperCase()}get headers(){return this.request.headers}header(e){return this.request.headers.get(e)}get ip(){return this.server?.requestIP(this.request)??null}get path(){return this.url.pathname}get isForm(){let e=this.request.headers.get("content-type");return!!e&&(e.includes("multipart/form-data")||e.includes("application/x-www-form-urlencoded"))}get isWSS(){return this.request.headers.get("upgrade")?.toLowerCase()==="websocket"}get isEventStream(){if(this.request.method.toUpperCase()!=="GET")return!1;return(this.request.headers.get("accept")??"").split(",").some((e)=>{let[t,...r]=e.trim().split(";");if(t?.trim().toLowerCase()!=="text/event-stream")return!1;for(let n of r){let s=n.trim().match(/^q\s*=\s*(0(?:\.\d+)?|1(?:\.0+)?)$/i);if(s&&Number(s[1])===0)return!1}return!0})}get isFile(){return this.fileDetector(this.path)}async getAuthCredentials(){let e=this.isForm?await this.form():null;return{sid:this.cookies.get("session")??"",jwt:this.auth??"",refresh:e?.get("refresh_token")?.toString()??""}}upgrade(e={}){return this.server?.upgrade(this.request,{data:e})??!1}}var Zt={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",413:"Payload Too Large",415:"Unsupported Media Type",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",503:"Service Unavailable"};function d(e,t){let r=e.code??400,n={...e.headers||{}};if(e.redirect)return n.Location=e.redirect,new Response(null,{status:302,headers:n});n["Content-Type"]="application/json; charset=utf-8";let s=e.message??Zt[r]??"An unexpected error occurred",i=JSON.stringify({success:!1,error:s,...t!==void 0&&{details:t}});return new Response(i,{status:r,headers:n})}var{gzipSync:er,deflateSync:tr,zstdCompressSync:rr}=globalThis.Bun;import{brotliCompressSync as nr}from"zlib";var sr=["br","gzip","deflate","zstd"];class B{static negotiate(e,t){if(!e||e==="none"||!t)return;let r=new Map;for(let i of t.split(",")){let[a,...o]=i.trim().toLowerCase().split(";");if(!a)continue;let c=1;for(let u of o){let l=u.trim().match(/^q\s*=\s*(0(?:\.\d+)?|1(?:\.0+)?)$/);if(l)c=Number(l[1])}r.set(a,c)}let n=r.get("*"),s=sr.map((i,a)=>({encoding:i,order:a,q:r.get(i)??n??0})).filter((i)=>i.q>0);if(s.sort((i,a)=>a.q-i.q||i.order-a.order),r.get(e)===0)return s.find((i)=>i.encoding!==e)?.encoding;return s.find((i)=>i.encoding===e)?.encoding??s[0]?.encoding}static handle(e,t){if(!t||t==="none")return{payload:e};try{let r=e;switch(t){case"gzip":return{payload:er(r),encoding:"gzip"};case"deflate":return{payload:tr(r),encoding:"deflate"};case"br":return{payload:nr(r),encoding:"br"};case"zstd":return{payload:rr(r),encoding:"zstd"};default:return{payload:e}}}catch(r){return console.error(`[Compressor] Failed to compress using ${t}:`,r),{payload:e}}}static toUint8(e){if(e===null||e===void 0)return new Uint8Array;if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);let t=typeof e==="string"?e:JSON.stringify(e);return new TextEncoder().encode(t)}}class re{static data(e){return`data: ${typeof e==="object"?JSON.stringify(e):String(e)}
|
|
3
3
|
|
|
4
4
|
`}static event(e){return`event: ${e}
|
|
5
5
|
`}static id(e){return`id: ${e}
|
|
6
6
|
`}static retry(e){return`retry: ${e}
|
|
7
|
-
`}}class
|
|
8
|
-
`)??[])[e]||"").match(/at\s+([^(]+)\s*\(/);return(t?t[1].split(".").pop()?.trim():"?")??"?"}class
|
|
7
|
+
`}}class Oe{intervalIDs=[];async push(e,t,r=2000){let n,s=Math.max(r,1000),i=setInterval(()=>{try{let{id:a,retry:o,data:c,event:u,end:l,fn:m}=t(n);if(l){this.close();try{e.close()}catch(f){}return}if(o)e.enqueue(re.retry(Math.max(o,2000)));if(a)e.enqueue(re.id(a));if(u)e.enqueue(re.event(u));if(e.enqueue(re.data(c)),m)n=m()}catch(a){console.error("[eStream Error] Interval iteration failed:",a),this.close();try{e.error(a)}catch(o){}}},s);this.intervalIDs.push(i)}close(){while(this.intervalIDs.length>0){let e=this.intervalIDs.pop();if(e)clearInterval(e)}}}var ir=(e)=>typeof e==="string";var ar=(e)=>Array.isArray(e);var or=(e)=>ot(e)&&typeof e==="object",cr=(e)=>ot(e)&&or(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null);var at=(e)=>cr(e);var ot=(e)=>e!==null;var K=(e)=>ar(e)?e:[e];function ve(e=3){let t=((Error().stack?.split(`
|
|
8
|
+
`)??[])[e]||"").match(/at\s+([^(]+)\s*\(/);return(t?t[1].split(".").pop()?.trim():"?")??"?"}class ct{name;constructor(e){this.name=e}log=(...e)=>{let t=ve(3);console.log(`[${this.name}.${t}]`,...e)};set i(e){let t=ve(3);console.log(`[${this.name}.${t}]`,...K(e))}}class Ae{static logger=(e)=>new ct(ir(e)?e:e.constructor.name);static set f(e){let t=ve();console.log(`[${t}]`,...K(e))}static set i(e){console.info(...K(e))}static set e(e){console.error(...K(e))}static set w(e){console.warn(...K(e))}static set d(e){let t=new Date().toLocaleTimeString();console.log(...K(e),`@ ${t}`)}static get d(){let e=new Date().toLocaleTimeString();console.log(`@ ${e}`);return}}class y{key;target;propertyKey;constructor(e,t,r){this.key=e,this.target=t,this.propertyKey=r}getReflect(){return this.propertyKey!==void 0?Reflect.getMetadata(this.key,this.target,this.propertyKey):Reflect.getMetadata(this.key,this.target)}setReflect(e){if(this.propertyKey!==void 0)Reflect.defineMetadata(this.key,e,this.target,this.propertyKey);else Reflect.defineMetadata(this.key,e,this.target)}static get get(){let e=(t,r,n)=>new this(`${r}:${t}`,n).get();return{class(t,r){return e("class",t,r)},method(t,r){return e("method",t,r)}}}get(){let e=this.getReflect();return Array.isArray(e)?e:[]}set(e){return this.setReflect(e),this}push(e){let t=this.get();return t.push(e),this.set(t)}unshift(e){let t=this.get();return t.unshift(e),this.set(t)}static getContextKey(e,t){return typeof e==="symbol"?Symbol.for(`${e.description}:${t}`):`${e}:${t}`}static decorate(e,t,r){return function(n,s){if(!s)return r;let i=s.kind??"class";if(t!=="all"&&!t.includes(i))throw Error(`Invalid decorator usage. Expected ${t.join(" or ")}, but applied to a ${i}.`);let a=y.getContextKey(e,i),o=r(s);if(i==="class"||i==="method"||i==="getter"||i==="setter")new y(a,n).push(o);else s.addInitializer(function(){new y(a,this,s.name).push(o)});return n}}static decorateClass(e,t){return this.decorate(e,["class"],t)}static decorateArray(e,t,r){return function(n,s){if(!r.length)return n;let i=s.kind??"class";if(t!=="all"&&!t.includes(i))throw Error(`Invalid decorator usage. Expected ${t.join(" or ")}, but applied to a ${i}.`);let a=y.getContextKey(e,i);if(i==="class"||i==="method"||i==="getter"||i==="setter")for(let o of r)new y(a,n).push(o);else s.addInitializer(function(){for(let o of r)new y(a,this,s.name).push(o)});return n}}}class z{req;staticServer;server;_code=200;_headers={};_encoding;constructor(e={},t,r,n){this.req=t;this.staticServer=r;this.server=n;if(e.encoding)this.encode(B.negotiate(e.encoding,t.headers.get("accept-encoding"))??"none")}status(e){return this._code=e,this}encode(e){if(this._encoding=e,e&&e!=="none")this._headers["Content-Encoding"]=e;else delete this._headers["Content-Encoding"];return this}header(e){let t=e instanceof I?e.done:e;for(let[r,n]of Object.entries(t))if(r.toLowerCase()==="vary"&&this._headers.Vary){let s=this._headers.Vary;if(s.trim()==="*")continue;let i=s.split(",").map((a)=>a.trim());for(let a of n.split(",").map((o)=>o.trim()))if(!i.some((o)=>o.toLowerCase()===a.toLowerCase()))i.push(a);this._headers.Vary=i.join(", ")}else this._headers[r]=n;return this}_assemble(e,t){let r=B.toUint8(e),{payload:n,encoding:s}=B.handle(r,this._encoding);if(s)this._headers["Content-Encoding"]=s;let i=(t.startsWith("text/")||t==="application/json")&&!t.includes("charset=");return new Response(n,{status:this._code,headers:{"Content-Type":i?`${t}; charset=utf-8`:t,"Content-Length":n.length.toString(),...this._headers}})}null(e=this._code){return new Response(null,{status:e,headers:this._headers})}json(e){return this._assemble(e,"application/json")}html(e){return this._assemble(e,"text/html")}text(e=""){return this._assemble(e,"text/plain")}error(e,t){this._code=e;let r="",n="text/plain";if(at(t))r=JSON.stringify(t),n="application/json";else r=String(t);return this._assemble(r,n)}success(e=200,t,r){return this._code=e,this.json({success:!0,...r&&{message:r},...t!==void 0&&{data:t}})}redirect(e,t=302){return new Response(null,{status:t,headers:{Location:e,...this._headers}})}async fileServer(){return this.staticServer.serve(this.req,this)}async file(e,t,r){if(r)this.header(r);let n="slice"in e&&"type"in e;if(n&&!await e.exists())return this.error(404,"File Not Found");let s=n?e.size:t?.size??0,a={"Content-Type":n?e.type:t?.type??"application/octet-stream","Accept-Ranges":n?"bytes":"none",...this._headers},o=n?this.req.headers.get("range"):null;if(!o){let T=e,x={...a};if(this._encoding&&this._encoding!=="none")try{let U=n?new Uint8Array(await e.arrayBuffer()):e,{payload:Ye,encoding:Qe}=B.handle(U,this._encoding);if(T=Ye,Qe)x["Content-Encoding"]=Qe;x["Content-Length"]=Ye.length.toString()}catch(U){return this.error(500,"Error reading file")}else x["Content-Length"]=s.toString();return new Response(T,{status:this._code,headers:x})}let c=()=>new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`,...this._headers}}),u=/^bytes=(\d*)-(\d*)$/.exec(o.trim());if(!u)return c();let l=u[1]??"",m=u[2]??"",f,p;if(l===""){let T=Number(m);if(!Number.isSafeInteger(T)||T<=0)return c();f=Math.max(s-T,0),p=s-1}else f=Number(l),p=m===""?s-1:Number(m);if(!Number.isSafeInteger(f)||!Number.isSafeInteger(p)||f<0||f>p||f>=s)return c();return p=Math.min(p,s-1),new Response(e.slice(f,p+1),{status:206,headers:{...a,"Content-Range":`bytes ${f}-${p}/${s}`,"Content-Length":(p-f+1).toString()}})}get event(){let e=()=>{this.server?.timeout(this.req.request,0)};return{asyncStream:(t)=>{if(!this.server)return this.null(500);e();let r=t(),n=new ReadableStream({async start(s){try{for await(let i of r){let a=typeof i==="object"?JSON.stringify(i):String(i);s.enqueue(Buffer.from(`data: ${a}
|
|
9
9
|
|
|
10
|
-
`))}s.close()}catch(i){s.error(i)}},cancel(){r.return?.()}});return new Response(n,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...this._headers}})},eStream:(t,{interval:r=2000,onCancel:n}={})=>{if(!this.server)return this.null(500);e();let s=new
|
|
11
|
-
--- Registered WSS Routes ---`),console.table(this.wssRoutes.map((e)=>({Path:e.path,Controller:e.instance.constructor.name})))}getPaths(){return this.httpRoutes.map(({path:e})=>e.replace(/:([a-zA-Z0-9_]+)/g,"$1"))}}import{dirname as xt,isAbsolute as ze,join as Ge}from"path";class G{ws;id;constructor(e,t){this.ws=e;this.id=E.register(e,t)}subscribe(e){E.subscribe(this.id,e)}unsubscribe(e){E.unsubscribe(this.id,e)}cleanup(){E.cleanup(this.id)}unregister(){E.unregister(this.id)}setAdmin(e){E.setAdmin(this.id,e)}isAdmin(e){return E.isAdmin(this.id,e)}isSubscribed(e){return E.isSubscribed(this.id,e)}setTopicConfig(e,t={}){E.setTopicConfig(e,t)}broadcast(e,t){return E.broadcastToTopics(this.ws,e,t)}}class V{connections=new Map;topicConfigs=new Map;topicRegistry=new Map;memberTopics=new Map;roomAdmins=new Map;defaultTopicConfig={maxClients:1/0,maxPayloadSize:65536};register(e,t){let r=crypto.randomUUID();return e.data={...e.data,id:r,nickname:t},this.connections.set(r,e),r}getMemberDetails(e){let t=this.topicRegistry.get(e)||new Set,r=[];for(let n of t){let s=this.connections.get(n);if(s)r.push({id:n,userId:s.data.contextData?.chatUser?.id,nickname:s.data.nickname})}return r}getUserTopics(e){return Array.from(this.memberTopics.get(e)||[])}get(e){return this.getMemberDetails(e)}unregister(e){this.cleanup(e)}subscribe(e,t){let r=this.connections.get(e);if(!r)throw Error("Connection not found");if(this.isSubscribed(e,t))return;let n=this.getConfigForTopic(t),s=this.topicRegistry.get(t)??new Set;if(s.size>=(n.maxClients??1/0))throw Error("Topic capacity reached");if(!r.subscribe(t))throw Error("WebSocket is closed");if(this.topicRegistry.set(t,s),s.add(e),!this.memberTopics.has(e))this.memberTopics.set(e,new Set);this.memberTopics.get(e).add(t)}isSubscribed(e,t){return this.memberTopics.get(e)?.has(t)??!1}unsubscribe(e,t){let r=this.connections.get(e);if(r)r.unsubscribe(t);let n=this.topicRegistry.get(t);if(n){if(n.delete(e),n.size===0)this.topicRegistry.delete(t),this.roomAdmins.delete(t)}let s=this.roomAdmins.get(t);if(s?.delete(e),s?.size===0)this.roomAdmins.delete(t);if(this.topicRegistry.get(t)?.delete(e),this.topicRegistry.get(t)?.size===0)this.topicRegistry.delete(t);if(this.memberTopics.get(e)?.delete(t),this.memberTopics.get(e)?.size===0)this.memberTopics.delete(e)}setAdmin(e,t){if(!this.roomAdmins.has(t))this.roomAdmins.set(t,new Set);this.roomAdmins.get(t).add(e)}isAdmin(e,t){return this.roomAdmins.get(t)?.has(e)??!1}isPayloadTooLarge(e,t){let r=this.getConfigForTopic(e);return t>(r.maxPayloadSize??65536)}getConfigForTopic(e){if(this.topicConfigs.has(e))return this.topicConfigs.get(e);return this.defaultTopicConfig}setTopicConfig(e,t={}){this.topicConfigs.set(e,t)}broadcastToTopics(e,t,r){let n=typeof r==="string"?r:JSON.stringify(r);if(n===void 0)return[];let s=new TextEncoder().encode(n).byteLength,i=[];for(let a of new Set(t)){if(this.isPayloadTooLarge(a,s)){i.push({topic:a,status:"oversize"});continue}let o=e.publish(a,n);i.push({topic:a,status:o===0?"dropped":o===-1?"backpressured":"sent"})}return i}cleanup(e){let t=this.getUserTopics(e);for(let r of t)this.unsubscribe(e,r);for(let[r,n]of this.roomAdmins)if(n.delete(e),n.size===0)this.roomAdmins.delete(r);this.connections.delete(e)}}var E=new V;function ye(e){if(e&&(!Number.isSafeInteger(e.max)||e.max<1||!Number.isFinite(e.windowMs)||e.windowMs<=0))throw RangeError("Invalid WebSocket message rate limit");let t=new WeakMap,r=(n)=>{if(!e)return!0;let s=Date.now(),i=t.get(n);if(!i||s>=i.resetAt)return t.set(n,{count:1,resetAt:s+e.windowMs}),!0;if(i.count>=e.max)return!1;return i.count+=1,!0};return{open:async(n)=>{let{instance:s,contextData:i}=n.data;s.ws=n,s.contextData=i??{},s.manager=new G(n,s.contextData.chatUser?.nickname),await s.open()},message:async(n,s)=>{if(!r(n)){n.close(1008,"Message rate limit exceeded");return}let{instance:i}=n.data;await i.message(Rt(s))},drain:async(n)=>{let{instance:s}=n.data;await s.drain()},close:async(n,s,i)=>{let{instance:a}=n.data;try{await a.close(s,i)}finally{a.manager.cleanup()}}}}var wn=ye();function Rt(e){let t=typeof e==="string"?e:e.toString(),r={},n=void 0;try{let{topic:s,...i}=JSON.parse(t);r=i,n=typeof s==="string"&&s.length>0?s:void 0,t=""}catch{}return{text:t,json:r,topic:n}}class Ve extends z{options;clientRoot;constructor(e={}){super(e.basePath||"");this.options={basePath:e.basePath||"",clientPath:e.clientPath||"./public",dirPath:e.dirPath||"./src",logError:Boolean(e.logError),Encoding:e.Encoding||"br"},this.clientRoot=this.getClientRoot,this.fileServer=new de(this.clientRoot,e.fileExtensions||[])}get getClientRoot(){let e;if(ze(this.options.clientPath))e=this.options.clientPath;else{let t=ze(this.options.dirPath)?this.options.dirPath:Ge(process.cwd(),this.options.dirPath),r=xt(t);e=Ge(r,this.options.clientPath)}return e}async pipeline(e){let t=0,r=async()=>{if(t>=this.globalGuards.length)return await this.processRouter(e);let n=this.globalGuards[t++];return await n(e,r)};try{return await r()}catch(n){return this.errorHandler(e.res,n)}}async processRouter(e){let t=e.req.url,r=e.req.method,n=t.pathname;if(n.endsWith("/")&&n.length>1)n=n.slice(0,-1);if(e.req.isWSS)return this.processWSS(e,n);let s=e.req.isEventStream?"EVENT":r,{guards:i=[],handler:a,params:o,methodKeys:c=[],controller:d}=this.match(s,n);if(!a)return e.res.null(404);e.params=o,e.method=s,e.methods=c;let u=0,m=async()=>{if(u>=i.length)return await a(e);let f=i[u++];return await f(e,m)};return await m()}async processWSS(e,t){let{instance:r,guards:n=[],params:s={}}=this.matchWSS(t)||{};if(!r)return e.res.error(404,"WebSocket Route Not Found.");e.params=s;let i=0,a=async()=>{if(i>=n.length){let c=new r;if(e.req.server?.upgrade(e.req.request,{data:{instance:c,contextData:e.data}}))return e.res.null(200);return e.res.error(500,"WebSocket Upgrade Failed")}let o=n[i++];return await o(e,a)};return await a()}async test(e,t){let r=new L(new q({encoding:t??this.options.Encoding},new I(e,void 0,this.fileServer.isFile.bind(this.fileServer)),this.fileServer));return r.clientDirectory=this.clientRoot,await this.pipeline(r)}serve(e={},t={}){let{fn:r,port:n,...s}=e,{messageRateLimit:i,...a}=t,o=r,c=n??3000,d=Bun.serve({...s,port:c,fetch:async(u,m)=>{let f=new L(new q({encoding:this.options.Encoding},new I(u,m,this.fileServer.isFile.bind(this.fileServer)),this.fileServer,m));f.clientDirectory=this.clientRoot;try{return await this.pipeline(f)}catch(h){return f.res.error(500,h.message||"Internal Server Error")}},websocket:{...a,...ye(i)}});if(o)o(c);else{let u=s.tls?"https":"http";pe.i=`${u}://localhost:${d.port??c}`}return d}errorHandler(e,t){if(this.options.logError)console.error(t.message);return e.null(500)}}class R{type;precision;scale;primaryKey=!1;required=!1;isUnique=!1;hasDefault=!1;defaultIsCurrentTimestamp=!1;defaultValue=null;constructor(e,t,r){this.type=e;this.precision=t;this.scale=r;if(e==="numeric"){let n=t??10,s=r??2;if(!Number.isInteger(n)||!Number.isInteger(s)||n<1||n>1000||s<0||s>n)throw RangeError("Numeric precision and scale must satisfy 1 <= p <= 1000 and 0 <= s <= p.")}}get primary(){return this.primaryKey=!0,this}get notNull(){return this.required=!0,this}get unique(){return this.isUnique=!0,this}get defaultNow(){return this.hasDefault=!0,this.defaultIsCurrentTimestamp=!0,this.defaultValue=null,this}default(e){if(typeof e==="number"&&!Number.isFinite(e))throw RangeError("Numeric SQL defaults must be finite.");return this.hasDefault=!0,this.defaultIsCurrentTimestamp=!1,this.defaultValue=e,this}}var Ct={text:()=>new R("text"),int:()=>new R("integer"),bigint:()=>new R("bigint"),boolean:()=>new R("boolean"),json:()=>new R("json"),timestamp:()=>new R("timestamp"),serial:()=>new R("serial"),numeric:(e=10,t=2)=>new R("numeric",e,t)};class O extends Error{constructor(e){super(e);this.name="DatabaseError"}}class J extends O{constructor(e){super(e);this.name="UniqueConstraintError"}}class Y extends O{constructor(e="Cannot modify a record referenced by another table."){super(e);this.name="ForeignKeyError"}}var{sql:N}=globalThis.Bun;function g(e){if(!e||e.includes("\x00"))throw Error("SQL identifiers must be non-empty and cannot contain NUL.");return`"${e.replace(/"/g,'""')}"`}function T(e){let t=e.split(".");if(t.length>2||t.some((r)=>!r||r.includes("\x00")))throw Error("Table names must be `table` or `schema.table`.");return t.map(g).join(".")}function S(e){let t=e.split(".");if(t.length>2||t.some((r)=>!r||r.includes("\x00")))throw Error("Table names must be `table` or `schema.table`.");return t.length===2?[t[0],t[1]]:[void 0,t[0]]}function be(e){return N.unsafe(T(e.table))}function Je(e){if(!e.hasDefault)return"";if(e.defaultIsCurrentTimestamp)return" DEFAULT CURRENT_TIMESTAMP";if(typeof e.defaultValue==="string")return` DEFAULT '${e.defaultValue.replace(/'/g,"''")}'`;return` DEFAULT ${e.defaultValue}`}function Ye(e){switch(e.type){case"text":return"TEXT";case"integer":return"INTEGER";case"bigint":return"BIGINT";case"boolean":return"BOOLEAN";case"json":return"JSONB";case"timestamp":return"TIMESTAMPTZ";case"serial":return"SERIAL";case"numeric":return`NUMERIC(${e.precision??10}, ${e.scale??2})`}}function At(e,t){return[g(e),Ye(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",Je(t).trim()].filter(Boolean).join(" ")}async function Ot(e,t){let[r,n]=S(t.table);return(r?await e`
|
|
10
|
+
`))}s.close()}catch(i){s.error(i)}},cancel(){r.return?.()}});return new Response(n,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...this._headers}})},eStream:(t,{interval:r=2000,onCancel:n}={})=>{if(!this.server)return this.null(500);e();let s=new Oe,i=new ReadableStream({async start(a){await s.push(a,t,r)},cancel(){s.close(),n?.()}});return new Response(i,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...this._headers}})},readableStream:(t,r)=>{if(!this.server)return this.null(500);e();let n=new ReadableStream({async start(s){await t(s)},cancel(){r?.()}});return new Response(n,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...this._headers}})}}}}var ut=["GET","POST","PUT","HEAD","DELETE","PATCH","EVENT","OPTIONS"];class Ne{options({res:e,methods:t}){let r=[...new Set([...t])];return e.header({Allow:r.join(", ")}).null(204)}}var G="rossa:route";function Me(e="/"){return y.decorateClass(G,()=>({basePath:e}))}function lt(e="/"){return y.decorateClass(G,()=>({basePath:e,wss:!0}))}import"reflect-metadata";var J="rossa:guard";function ur(...e){return y.decorateArray(J,["class","method"],e)}function dt(e,t){let r=y.get.method(J,t),n=[],s=new Map;for(let i of r)if(i._middlewareId)s.set(i._middlewareId,i);for(let i of e)if(i._middlewareId&&s.has(i._middlewareId))n.push(s.get(i._middlewareId)),s.delete(i._middlewareId);else n.push(i);for(let i of r)if(!i._middlewareId||s.has(i._middlewareId)){if(n.push(i),i._middlewareId)s.delete(i._middlewareId)}return n}class ne{globalBasePath;httpRoutes=[];wssRoutes=[];globalGuards=[];registeredSignatures=new Set;programmaticRoutes=new Set;constructor(e=""){if(this.globalBasePath=e.startsWith("/")?e:`/${e}`,this.globalBasePath==="/")this.globalBasePath=""}use(...e){for(let t of e)this.globalGuards.unshift(t)}fullRoutePath(e){return`${this.globalBasePath}${e}`.replace(/\/+/g,"/").replace(/\/$/,"")||"/"}compiler(e){let t=[],r=e.replace(/[.*+?^${}()|[\]\\]|:([a-zA-Z0-9_]+)/g,(n,s)=>{if(s)return t.push(s),"([^/]+)";return`\\${n}`});return{regex:new RegExp(`^${r}\\/?$`),paramNames:t}}checkSignature(e,t,r="http"){let n=`${r}:${e}`;if(this.registeredSignatures.has(n))throw Error(`[Router Error] Duplicate ${r} route collision detected: ${e} in controller ${t}`);this.registeredSignatures.add(n)}registerWSS(...e){for(let t of e){let r=y.get.class(G,t),n=y.get.class(J,t);if(!r.length)continue;for(let s of r){let i=s.basePath??"/",a=this.fullRoutePath(i);this.checkSignature(a,t.name,"wss");let{regex:o,paramNames:c}=this.compiler(a);this.wssRoutes.push({path:a,regex:o,paramNames:c,instance:t,guards:n})}}}register(...e){for(let t of e){let r=y.get.class(G,t);if(!r.length)continue;let n={};for(let c of r){let u=c.basePath??"/",l=this.fullRoutePath(u);this.checkSignature(l,t.name);let{regex:m,paramNames:f}=this.compiler(l);n[l]={regex:m,paramNames:f,controller:t}}let s=new t,i=y.get.class(J,t),a=new Set,o={};for(let c of ut){let u=s[c.toLowerCase()];if(typeof u!=="function")continue;if(o[c]={guards:dt(i,u),handler:u.bind(s)},c!=="EVENT")a.add(c)}for(let[c,u]of Object.entries(n))this.httpRoutes.push({path:c,...u,methods:o,methodKeys:[...a]})}}registerHandlerRoute(e,t,r={}){let n=this.fullRoutePath(e),s=this.httpRoutes.findIndex((c)=>c.path===n);if(s!==-1){if(!r.replace||!this.programmaticRoutes.has(n))throw Error(`[Router Error] Route collision detected: ${n} is already registered as an HTTP route.`);this.httpRoutes.splice(s,1),this.registeredSignatures.delete(`http:${n}`),this.programmaticRoutes.delete(n)}this.checkSignature(n,"programmatic route");let{regex:i,paramNames:a}=this.compiler(n),o={};for(let[c,u]of Object.entries(t)){if(!u)continue;o[c]={guards:[],handler:u}}this.httpRoutes.push({path:n,regex:i,paramNames:a,controller:mt,methods:o,methodKeys:Object.keys(o)}),this.programmaticRoutes.add(n)}matchWSS(e){let t=e.split("?")[0]??e;for(let r of this.wssRoutes){let n=t.match(r.regex);if(!n)continue;let s={};r.paramNames.forEach((i,a)=>{s[i]=n[a+1]??""});try{return{...r,params:s}}catch(i){return console.error(`WSS Route Execution Error [${r.instance.name}]:`,i),{params:s}}}return{params:{}}}match(e,t){let r=t.split("?")[0]??t;for(let n of this.httpRoutes){let s=r.match(n.regex);if(!s)continue;let i=n.methods[e];if(!i)continue;let a={};n.paramNames.forEach((o,c)=>{a[o]=s[c+1]??""});try{return{...i,methodKeys:n.methodKeys,controller:n.controller,params:a}}catch(o){return console.error(`Route Execution Error [${n.controller.name}]:`,o),{params:a}}}return{params:{}}}printRoutes(){console.log("--- Registered HTTP Routes ---"),console.table(this.httpRoutes.map((e)=>({Methods:e.methodKeys.join(", "),Path:e.path,Type:"HTTP"}))),console.log(`
|
|
11
|
+
--- Registered WSS Routes ---`),console.table(this.wssRoutes.map((e)=>({Path:e.path,Controller:e.instance.constructor.name})))}getPaths(){return this.httpRoutes.map(({path:e})=>e.replace(/:([a-zA-Z0-9_]+)/g,"$1"))}}class mt{}import{dirname as gr,isAbsolute as pt,join as ht}from"path";class ce{ws;id;constructor(e,t){this.ws=e;this.id=C.register(e,t)}subscribe(e){C.subscribe(this.id,e)}unsubscribe(e){C.unsubscribe(this.id,e)}cleanup(){C.cleanup(this.id)}unregister(){C.unregister(this.id)}setAdmin(e){C.setAdmin(this.id,e)}isAdmin(e){return C.isAdmin(this.id,e)}isSubscribed(e){return C.isSubscribed(this.id,e)}setTopicConfig(e,t={}){C.setTopicConfig(e,t)}broadcast(e,t){return C.broadcastToTopics(this.ws,e,t)}}class ue{connections=new Map;topicConfigs=new Map;topicRegistry=new Map;memberTopics=new Map;roomAdmins=new Map;defaultTopicConfig={maxClients:1/0,maxPayloadSize:65536};register(e,t){let r=crypto.randomUUID();return e.data={...e.data,id:r,nickname:t},this.connections.set(r,e),r}getMemberDetails(e){let t=this.topicRegistry.get(e)||new Set,r=[];for(let n of t){let s=this.connections.get(n);if(s)r.push({id:n,userId:s.data.contextData?.chatUser?.id,nickname:s.data.nickname})}return r}getUserTopics(e){return Array.from(this.memberTopics.get(e)||[])}get(e){return this.getMemberDetails(e)}unregister(e){this.cleanup(e)}subscribe(e,t){let r=this.connections.get(e);if(!r)throw Error("Connection not found");if(this.isSubscribed(e,t))return;let n=this.getConfigForTopic(t),s=this.topicRegistry.get(t)??new Set;if(s.size>=(n.maxClients??1/0))throw Error("Topic capacity reached");if(!r.subscribe(t))throw Error("WebSocket is closed");if(this.topicRegistry.set(t,s),s.add(e),!this.memberTopics.has(e))this.memberTopics.set(e,new Set);this.memberTopics.get(e).add(t)}isSubscribed(e,t){return this.memberTopics.get(e)?.has(t)??!1}unsubscribe(e,t){let r=this.connections.get(e);if(r)r.unsubscribe(t);let n=this.topicRegistry.get(t);if(n){if(n.delete(e),n.size===0)this.topicRegistry.delete(t),this.roomAdmins.delete(t)}let s=this.roomAdmins.get(t);if(s?.delete(e),s?.size===0)this.roomAdmins.delete(t);if(this.topicRegistry.get(t)?.delete(e),this.topicRegistry.get(t)?.size===0)this.topicRegistry.delete(t);if(this.memberTopics.get(e)?.delete(t),this.memberTopics.get(e)?.size===0)this.memberTopics.delete(e)}setAdmin(e,t){if(!this.roomAdmins.has(t))this.roomAdmins.set(t,new Set);this.roomAdmins.get(t).add(e)}isAdmin(e,t){return this.roomAdmins.get(t)?.has(e)??!1}isPayloadTooLarge(e,t){let r=this.getConfigForTopic(e);return t>(r.maxPayloadSize??65536)}getConfigForTopic(e){if(this.topicConfigs.has(e))return this.topicConfigs.get(e);return this.defaultTopicConfig}setTopicConfig(e,t={}){this.topicConfigs.set(e,t)}broadcastToTopics(e,t,r){let n=typeof r==="string"?r:JSON.stringify(r);if(n===void 0)return[];let s=new TextEncoder().encode(n).byteLength,i=[];for(let a of new Set(t)){if(this.isPayloadTooLarge(a,s)){i.push({topic:a,status:"oversize"});continue}let o=e.publish(a,n);i.push({topic:a,status:o===0?"dropped":o===-1?"backpressured":"sent"})}return i}cleanup(e){let t=this.getUserTopics(e);for(let r of t)this.unsubscribe(e,r);for(let[r,n]of this.roomAdmins)if(n.delete(e),n.size===0)this.roomAdmins.delete(r);this.connections.delete(e)}}var C=new ue;function De(e){if(e&&(!Number.isSafeInteger(e.max)||e.max<1||!Number.isFinite(e.windowMs)||e.windowMs<=0))throw RangeError("Invalid WebSocket message rate limit");let t=new WeakMap,r=(n)=>{if(!e)return!0;let s=Date.now(),i=t.get(n);if(!i||s>=i.resetAt)return t.set(n,{count:1,resetAt:s+e.windowMs}),!0;if(i.count>=e.max)return!1;return i.count+=1,!0};return{open:async(n)=>{let{instance:s,contextData:i}=n.data;s.ws=n,s.contextData=i??{},s.manager=new ce(n,s.contextData.chatUser?.nickname),await s.open()},message:async(n,s)=>{if(!r(n)){n.close(1008,"Message rate limit exceeded");return}let{instance:i}=n.data;await i.message(lr(s))},drain:async(n)=>{let{instance:s}=n.data;await s.drain()},close:async(n,s,i)=>{let{instance:a}=n.data;try{await a.close(s,i)}finally{a.manager.cleanup()}}}}var Ms=De();function lr(e){let t=typeof e==="string"?e:e.toString(),r={},n=void 0;try{let{topic:s,...i}=JSON.parse(t);r=i,n=typeof s==="string"&&s.length>0?s:void 0,t=""}catch{}return{text:t,json:r,topic:n}}var _e="rossa:mcp";function Ie(e){return y.get.class(_e,e).at(-1)}function ft(e="/",t={}){return y.decorateClass(_e,()=>({path:e,options:{...t}}))}class se{}import{createMcpHandler as dr,originValidationResponse as mr,McpServer as fr}from"@modelcontextprotocol/server";function $e(e){return async()=>{let t=new fr({name:e.constructor.name||"McpController",version:"0.0.0"});return await e.build(t),t}}function pr(e){let t={origins:new Set,hostnames:[]};for(let r of Array.isArray(e)?e:[e]){let n=r.trim();if(!n)continue;if(/^[a-z][a-z0-9+.-]*:\/\/\*$/i.test(n)){t.hostnames.push(n);continue}try{t.origins.add(new URL(n).origin)}catch{t.hostnames.push(n)}}return t}function hr(e,t){let r=e.headers.get("origin");if(!r)return;try{if(t.origins.has(new URL(r).origin))return}catch{}return mr(e,t.hostnames)}function ke(e,t={}){let r=dr(e),n=t.origin===void 0?void 0:pr(t.origin);return async(s)=>{if(n){let i=hr(s.req.request,n);if(i)return i}return r.fetch(s.req.request)}}function yr(e){if(e instanceof Response)return e;return console.error("[rossa] Guard factory not invoked? Expected a Response but got:",e),new Response("Internal Server Error: guard factory not invoked",{status:500})}class gt extends ne{options;clientRoot;constructor(e={}){super(e.basePath||"");this.options={basePath:e.basePath||"",clientPath:e.clientPath||"./public",dirPath:e.dirPath||"./src",logError:Boolean(e.logError),Encoding:e.Encoding||"br"},this.clientRoot=this.getClientRoot,this.fileServer=new te(this.clientRoot,e.fileExtensions||[])}registerMCP(e,t={},r={}){if(typeof e==="string"){let u=t;if(typeof u!=="function")throw TypeError("[MCP Error] registerMCP(path, factory) requires an McpServerFactory function.");this.mountMcp(e,u,r);return}let n=e instanceof se,s=n?e.constructor:e,i=Ie(s);if(!i)throw Error(`[MCP Error] ${s.name||"Controller"} is missing the @mcp decorator. Decorate it with @mcp("/path") or register it with an explicit path and factory.`);let a=n?e:new e,o=t,c={...i.options,...o.origin!==void 0?{origin:o.origin}:{}};this.mountMcp(i.path,$e(a),c)}mountMcp(e,t,r){let n=ke(t,r);this.registerHandlerRoute(e,{POST:n,GET:n,DELETE:n,EVENT:n},{replace:!0})}get getClientRoot(){let e;if(pt(this.options.clientPath))e=this.options.clientPath;else{let t=pt(this.options.dirPath)?this.options.dirPath:ht(process.cwd(),this.options.dirPath),r=gr(t);e=ht(r,this.options.clientPath)}return e}async pipeline(e){let t=0,r=async()=>{if(t>=this.globalGuards.length)return await this.processRouter(e);let n=this.globalGuards[t++];return await n(e,r)};try{return yr(await r())}catch(n){return this.errorHandler(e.res,n)}}async processRouter(e){let t=e.req.url,r=e.req.method,n=t.pathname;if(n.endsWith("/")&&n.length>1)n=n.slice(0,-1);if(e.req.isWSS)return this.processWSS(e,n);let s=e.req.isEventStream?"EVENT":r,{guards:i=[],handler:a,params:o,methodKeys:c=[],controller:u}=this.match(s,n);if(!a)return e.res.null(404);e.params=o,e.method=s,e.methods=c;let l=0,m=async()=>{if(l>=i.length)return await a(e);let f=i[l++];return await f(e,m)};return await m()}async processWSS(e,t){let{instance:r,guards:n=[],params:s={}}=this.matchWSS(t)||{};if(!r)return e.res.error(404,"WebSocket Route Not Found.");e.params=s;let i=0,a=async()=>{if(i>=n.length){let c=new r;if(e.req.server?.upgrade(e.req.request,{data:{instance:c,contextData:e.data}}))return e.res.null(200);return e.res.error(500,"WebSocket Upgrade Failed")}let o=n[i++];return await o(e,a)};return await a()}async test(e,t){let r=new H(new z({encoding:t??this.options.Encoding},new W(e,void 0,this.fileServer.isFile.bind(this.fileServer)),this.fileServer));return r.clientDirectory=this.clientRoot,await this.pipeline(r)}serve(e={},t={}){let{fn:r,port:n,...s}=e,{messageRateLimit:i,...a}=t,o=r,c=n??3000,u=Bun.serve({...s,port:c,fetch:async(m,f)=>{let p=new H(new z({encoding:this.options.Encoding},new W(m,f,this.fileServer.isFile.bind(this.fileServer)),this.fileServer,f));p.clientDirectory=this.clientRoot;try{return await this.pipeline(p)}catch(T){return p.res.error(500,T.message||"Internal Server Error")}},websocket:{...a,...De(i)}}),l=u.port??c;if(o)o(l,u);else{let m=s.tls?"https":"http";Ae.i=u.url?.href??`${m}://localhost:${l}`}return u}errorHandler(e,t){if(this.options.logError)console.error(t.message);return e.null(500)}}import{McpServer as pc}from"@modelcontextprotocol/server";class O{type;precision;scale;primaryKey=!1;required=!1;isUnique=!1;hasDefault=!1;defaultIsCurrentTimestamp=!1;defaultValue=null;constructor(e,t,r){this.type=e;this.precision=t;this.scale=r;if(e==="numeric"){let n=t??10,s=r??2;if(!Number.isInteger(n)||!Number.isInteger(s)||n<1||n>1000||s<0||s>n)throw RangeError("Numeric precision and scale must satisfy 1 <= p <= 1000 and 0 <= s <= p.")}}get primary(){return this.primaryKey=!0,this}get notNull(){return this.required=!0,this}get unique(){return this.isUnique=!0,this}get defaultNow(){return this.hasDefault=!0,this.defaultIsCurrentTimestamp=!0,this.defaultValue=null,this}default(e){if(typeof e==="number"&&!Number.isFinite(e))throw RangeError("Numeric SQL defaults must be finite.");return this.hasDefault=!0,this.defaultIsCurrentTimestamp=!1,this.defaultValue=e,this}}var br={text:()=>new O("text"),int:()=>new O("integer"),bigint:()=>new O("bigint"),boolean:()=>new O("boolean"),json:()=>new O("json"),timestamp:()=>new O("timestamp"),serial:()=>new O("serial"),numeric:(e=10,t=2)=>new O("numeric",e,t)};class M extends Error{constructor(e){super(e);this.name="DatabaseError"}}class le extends M{constructor(e){super(e);this.name="UniqueConstraintError"}}class de extends M{constructor(e="Cannot modify a record referenced by another table."){super(e);this.name="ForeignKeyError"}}var{sql:D}=globalThis.Bun;function g(e){if(!e||e.includes("\x00"))throw Error("SQL identifiers must be non-empty and cannot contain NUL.");return`"${e.replace(/"/g,'""')}"`}function R(e){let t=e.split(".");if(t.length>2||t.some((r)=>!r||r.includes("\x00")))throw Error("Table names must be `table` or `schema.table`.");return t.map(g).join(".")}function E(e){let t=e.split(".");if(t.length>2||t.some((r)=>!r||r.includes("\x00")))throw Error("Table names must be `table` or `schema.table`.");return t.length===2?[t[0],t[1]]:[void 0,t[0]]}function Pe(e){return D.unsafe(R(e.table))}function yt(e){if(!e.hasDefault)return"";if(e.defaultIsCurrentTimestamp)return" DEFAULT CURRENT_TIMESTAMP";if(typeof e.defaultValue==="string")return` DEFAULT '${e.defaultValue.replace(/'/g,"''")}'`;return` DEFAULT ${e.defaultValue}`}function bt(e){switch(e.type){case"text":return"TEXT";case"integer":return"INTEGER";case"bigint":return"BIGINT";case"boolean":return"BOOLEAN";case"json":return"JSONB";case"timestamp":return"TIMESTAMPTZ";case"serial":return"SERIAL";case"numeric":return`NUMERIC(${e.precision??10}, ${e.scale??2})`}}function Sr(e,t){return[g(e),bt(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",yt(t).trim()].filter(Boolean).join(" ")}async function wr(e,t){let[r,n]=E(t.table);return(r?await e`
|
|
12
12
|
SELECT column_name FROM information_schema.columns
|
|
13
13
|
WHERE table_schema = ${r} AND table_name = ${n}
|
|
14
14
|
`:await e`
|
|
15
15
|
SELECT column_name FROM information_schema.columns
|
|
16
16
|
WHERE table_schema = current_schema() AND table_name = ${n}
|
|
17
|
-
`).map((i)=>i.column_name)}var
|
|
18
|
-
INSERT INTO ${
|
|
19
|
-
ON CONFLICT (${
|
|
20
|
-
DO UPDATE SET ${
|
|
17
|
+
`).map((i)=>i.column_name)}var Le={name:"postgres",quoteIdentifier:g,quoteTable:R,normalizeColumnName(e){return e},buildColumn:Sr,buildColumnType(e){return[bt(e),e.primaryKey?"PRIMARY KEY":"",e.required?"NOT NULL":"",e.isUnique?"UNIQUE":"",yt(e).trim()].filter(Boolean).join(" ")},normalizeOperator(e){return e.toUpperCase()},async version(e){let[t]=await e`SELECT version() AS version`;if(!t?.version)throw Error("PostgreSQL did not return its version.");return t.version},async createTable(e,t){await e`${D.unsafe(t.createSQL(this))}`},getColumns:wr,async addColumn(e,t,r,n){await e`${D.unsafe(`ALTER TABLE ${R(t.table)} ADD COLUMN ${g(r)} ${n}`)}`},async dropColumn(e,t,r){await e`${D.unsafe(`ALTER TABLE ${R(t.table)} DROP COLUMN ${g(r)}`)}`},async upsert(e,t,r,n){if(Object.keys(r).length===0)throw Error("Upsert requires at least one column value.");let[s]=await e`
|
|
18
|
+
INSERT INTO ${Pe(t)} ${D(r)}
|
|
19
|
+
ON CONFLICT (${D.unsafe(g(String(n)))})
|
|
20
|
+
DO UPDATE SET ${D(r)}
|
|
21
21
|
RETURNING *
|
|
22
22
|
`;return s},async listTables(e){return(await e`
|
|
23
23
|
SELECT tablename FROM pg_catalog.pg_tables
|
|
24
24
|
WHERE schemaname = current_schema()
|
|
25
|
-
`).map((r)=>r.tablename)},async dropTable(e,t){await e`${
|
|
26
|
-
SELECT COUNT(*) AS total FROM ${
|
|
27
|
-
`,i=
|
|
25
|
+
`).map((r)=>r.tablename)},async dropTable(e,t){await e`${D.unsafe(`DROP TABLE ${R(t.table)}`)}`},async truncateTable(e,t){await e`${D.unsafe(`TRUNCATE TABLE ${R(t.table)} RESTART IDENTITY`)}`},async getTableStats(e,t){let[r,n]=E(t.table),[s]=await e`
|
|
26
|
+
SELECT COUNT(*) AS total FROM ${Pe(t)}
|
|
27
|
+
`,i=R(t.table),[a]=await e`
|
|
28
28
|
SELECT
|
|
29
29
|
pg_size_pretty(pg_total_relation_size(${i}::regclass)) AS size,
|
|
30
30
|
(SELECT COUNT(*) FROM pg_indexes
|
|
31
31
|
WHERE schemaname = COALESCE(${r??null}, current_schema())
|
|
32
32
|
AND tablename = ${n}) AS index_count
|
|
33
|
-
`;return{rowCount:Number(s?.total??0),diskSize:a?.size??"unknown",indexCount:Number(a?.index_count??0)}},async getTableIndices(e,t){let[r,n]=
|
|
33
|
+
`;return{rowCount:Number(s?.total??0),diskSize:a?.size??"unknown",indexCount:Number(a?.index_count??0)}},async getTableIndices(e,t){let[r,n]=E(t.table);return r?e`
|
|
34
34
|
SELECT indexname, indexdef FROM pg_indexes
|
|
35
35
|
WHERE schemaname = ${r} AND tablename = ${n}
|
|
36
36
|
`:e`
|
|
37
37
|
SELECT indexname, indexdef FROM pg_indexes
|
|
38
38
|
WHERE schemaname = current_schema() AND tablename = ${n}
|
|
39
|
-
`},async getTableSchema(e,t){let[r,n]=
|
|
39
|
+
`},async getTableSchema(e,t){let[r,n]=E(t.table);return r?e`
|
|
40
40
|
SELECT column_name, data_type, column_default, is_nullable
|
|
41
41
|
FROM information_schema.columns
|
|
42
42
|
WHERE table_schema = ${r} AND table_name = ${n}
|
|
@@ -45,31 +45,33 @@ class ne{data;constructor(e={}){this.data={...e}}_add(e,t){return this.data[e]=t
|
|
|
45
45
|
FROM information_schema.columns
|
|
46
46
|
WHERE table_schema = current_schema() AND table_name = ${n}
|
|
47
47
|
`},async getTableData(e,t,r,n){return await e`
|
|
48
|
-
SELECT * FROM ${
|
|
48
|
+
SELECT * FROM ${Pe(t)}
|
|
49
49
|
LIMIT ${r} OFFSET ${n}
|
|
50
|
-
`},async optimize(e,t){await e.unsafe(`VACUUM ANALYZE ${
|
|
51
|
-
INSERT INTO ${
|
|
52
|
-
ON CONFLICT (${
|
|
50
|
+
`},async optimize(e,t){await e.unsafe(`VACUUM ANALYZE ${R(t.table)}`)}};var{sql:S}=globalThis.Bun;function qe(e){return S.unsafe(R(e.table))}function Tr(e){return e.reduce((t,r,n)=>n===0?r:S`${t}, ${r}`)}function St(e){if(!e.hasDefault)return"";if(e.defaultIsCurrentTimestamp)return" DEFAULT CURRENT_TIMESTAMP";if(typeof e.defaultValue==="string")return` DEFAULT '${e.defaultValue.replace(/'/g,"''")}'`;if(typeof e.defaultValue==="boolean")return` DEFAULT ${e.defaultValue?1:0}`;return` DEFAULT ${e.defaultValue}`}function wt(e){switch(e.type){case"text":case"json":case"timestamp":return"TEXT";case"integer":case"bigint":case"serial":return"INTEGER";case"boolean":return"INTEGER";case"numeric":return"REAL"}}function Rr(e,t){return[g(e),wt(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",St(t).trim()].filter(Boolean).join(" ")}async function Er(e,t){let[r,n]=E(t.table),s=r?`${g(r)}.`:"";return(await e`${S.unsafe(`PRAGMA ${s}table_info(${g(n)})`)}`).map((a)=>a.name)}var je={name:"sqlite",quoteIdentifier:g,quoteTable:R,normalizeColumnName(e){return e.toLowerCase()},buildColumn:Rr,buildColumnType(e){return[wt(e),e.primaryKey?"PRIMARY KEY":"",e.required?"NOT NULL":"",e.isUnique?"UNIQUE":"",St(e).trim()].filter(Boolean).join(" ")},normalizeOperator(e){return e.toUpperCase()==="ILIKE"?"LIKE":e.toUpperCase()},async version(e){let[t]=await e`SELECT sqlite_version() AS version`;if(!t?.version)throw Error("SQLite did not return its version.");return t.version},async createTable(e,t){await e`${S.unsafe(t.createSQL(this))}`},getColumns:Er,async addColumn(e,t,r,n){if(/\bPRIMARY KEY\b|\bUNIQUE\b/i.test(n))throw Error("SQLite cannot add PRIMARY KEY or UNIQUE constraints with ADD COLUMN; rebuild the table instead.");await e`${S.unsafe(`ALTER TABLE ${R(t.table)} ADD COLUMN ${g(r)} ${n}`)}`},async dropColumn(e,t,r){await e`${S.unsafe(`ALTER TABLE ${R(t.table)} DROP COLUMN ${g(r)}`)}`},async upsert(e,t,r,n){let s=Object.keys(r);if(s.length===0)throw Error("Upsert requires at least one column value.");let i=String(n),a=s.filter((l)=>l!==i),o=a.length?a:[i],c=Tr(o.map((l)=>S`${S.unsafe(g(l))} = excluded.${S.unsafe(g(l))}`)),[u]=await e`
|
|
51
|
+
INSERT INTO ${qe(t)} ${S(r)}
|
|
52
|
+
ON CONFLICT (${S.unsafe(g(i))})
|
|
53
53
|
DO UPDATE SET ${c}
|
|
54
54
|
RETURNING *
|
|
55
|
-
`;return
|
|
55
|
+
`;return u},async listTables(e){return(await e`
|
|
56
56
|
SELECT name FROM sqlite_schema
|
|
57
57
|
WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
|
|
58
|
-
`).map((r)=>r.name)},async dropTable(e,t){await e`${
|
|
59
|
-
SELECT COUNT(*) AS total FROM ${
|
|
60
|
-
`,i=r?`${g(r)}.`:"",a=await e`${
|
|
61
|
-
SELECT * FROM ${
|
|
58
|
+
`).map((r)=>r.name)},async dropTable(e,t){await e`${S.unsafe(`DROP TABLE ${R(t.table)}`)}`},async truncateTable(e,t){await e.begin(async(r)=>{await r`${S.unsafe(`DELETE FROM ${R(t.table)}`)}`;let[n,s]=E(t.table),i=g(n??"main"),[a]=await r`${S.unsafe(`SELECT name FROM ${i}.sqlite_schema WHERE type = 'table' AND name = 'sqlite_sequence'`)}`;if(a)await r`${S.unsafe(`DELETE FROM ${i}.sqlite_sequence WHERE name = `)}${s}`})},async getTableStats(e,t){let[r,n]=E(t.table),[s]=await e`
|
|
59
|
+
SELECT COUNT(*) AS total FROM ${qe(t)}
|
|
60
|
+
`,i=r?`${g(r)}.`:"",a=await e`${S.unsafe(`PRAGMA ${i}index_list(${g(n)})`)}`;return{rowCount:Number(s?.total??0),diskSize:"N/A (SQLite file-level)",indexCount:a.length}},async getTableIndices(e,t){let[r,n]=E(t.table),s=r?`${g(r)}.`:"";return e`${S.unsafe(`PRAGMA ${s}index_list(${g(n)})`)}`},async getTableSchema(e,t){let[r,n]=E(t.table),s=r?`${g(r)}.`:"";return e`${S.unsafe(`PRAGMA ${s}table_info(${g(n)})`)}`},async getTableData(e,t,r,n){return await e`
|
|
61
|
+
SELECT * FROM ${qe(t)}
|
|
62
62
|
LIMIT ${r} OFFSET ${n}
|
|
63
|
-
`},async optimize(e){await e`${
|
|
63
|
+
`},async optimize(e){await e`${S.unsafe("VACUUM")}`}};var{sql:v}=globalThis.Bun;var A=(e)=>{if(!e||e.includes("\x00"))throw Error("SQL identifiers must be non-empty and cannot contain NUL.");return"`"+e.replace(/`/g,"``")+"`"},k=(e)=>{let t=e.split(".");if(t.length>2||t.some((r)=>!r||r.includes("\x00")))throw Error("Table names must be a table name or a schema-qualified table name.");return t.map(A).join(".")},me=(e)=>v.unsafe(k(e.table));function Tt(e){switch(e.type){case"text":return"TEXT";case"integer":return"INT";case"bigint":return"BIGINT";case"boolean":return"BOOLEAN";case"json":return"JSON";case"timestamp":return"DATETIME(3)";case"serial":return"BIGINT AUTO_INCREMENT";case"numeric":return`DECIMAL(${e.precision??10}, ${e.scale??2})`}}function Rt(e){if(!e.hasDefault)return"";if(e.defaultIsCurrentTimestamp)return" DEFAULT CURRENT_TIMESTAMP";if(typeof e.defaultValue==="string")return` DEFAULT '${e.defaultValue.replace(/'/g,"''")}'`;if(typeof e.defaultValue==="boolean")return` DEFAULT ${e.defaultValue?1:0}`;return` DEFAULT ${e.defaultValue}`}function xr(e,t){return[A(e),Tt(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",Rt(t).trim()].filter(Boolean).join(" ")}async function Cr(e,t){let[r,n]=E(t.table);return(r?await e`SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = ${r} AND table_name = ${n}`:await e`SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${n}`).map((i)=>i.COLUMN_NAME)}function Et(e){return{name:e,quoteIdentifier:A,quoteTable:k,normalizeColumnName(t){return t.toLowerCase()},buildColumn:xr,buildColumnType(t){return[Tt(t),t.primaryKey?"PRIMARY KEY":"",t.required?"NOT NULL":"",t.isUnique?"UNIQUE":"",Rt(t).trim()].filter(Boolean).join(" ")},normalizeOperator(t){return t.toUpperCase()==="ILIKE"?"LIKE":t.toUpperCase()},async version(t){let[r]=await t`SELECT VERSION() AS version`;if(!r?.version)throw Error("MySQL-compatible server did not return its version.");return r.version},async createTable(t,r){await t`${v.unsafe(r.createSQL(this))}`},getColumns:Cr,async addColumn(t,r,n,s){await t`${v.unsafe(`ALTER TABLE ${k(r.table)} ADD COLUMN ${A(n)} ${s}`)}`},async dropColumn(t,r,n){await t`${v.unsafe(`ALTER TABLE ${k(r.table)} DROP COLUMN ${A(n)}`)}`},async upsert(t,r,n,s){let i=Object.keys(n);if(!i.length)throw Error("Upsert requires at least one column value.");let a=i.filter((l)=>l!==String(s)),o=a.length?a.map((l)=>`${A(l)} = VALUES(${A(l)})`).join(", "):`${A(String(s))} = VALUES(${A(String(s))})`;await t`INSERT INTO ${me(r)} ${v(n)} ON DUPLICATE KEY UPDATE ${v.unsafe(o)}`;let c=n[s];if(c===void 0)return;let[u]=await t`SELECT * FROM ${me(r)} WHERE ${v.unsafe(A(String(s)))} = ${c} LIMIT 1`;return u},async listTables(t){return(await t`SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'`).map((n)=>n.TABLE_NAME)},async dropTable(t,r){await t`${v.unsafe(`DROP TABLE ${k(r.table)}`)}`},async truncateTable(t,r){await t`${v.unsafe(`TRUNCATE TABLE ${k(r.table)}`)}`},async getTableStats(t,r){let[n,s]=E(r.table),[i]=await t`SELECT COUNT(*) AS total FROM ${me(r)}`,[a]=n?await t`SELECT data_length + index_length AS size, (SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema = ${n} AND table_name = ${s}) AS index_count FROM information_schema.tables WHERE table_schema = ${n} AND table_name = ${s}`:await t`SELECT data_length + index_length AS size, (SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ${s}) AS index_count FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ${s}`;return{rowCount:Number(i?.total??0),diskSize:a?.size==null?"unknown":`${a.size} bytes`,indexCount:Number(a?.index_count??0)}},async getTableIndices(t,r){let[n,s]=E(r.table);return n?t`SELECT * FROM information_schema.statistics WHERE table_schema = ${n} AND table_name = ${s}`:t`SELECT * FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ${s}`},async getTableSchema(t,r){let[n,s]=E(r.table);return n?t`SELECT column_name, column_type, column_default, is_nullable FROM information_schema.columns WHERE table_schema = ${n} AND table_name = ${s}`:t`SELECT column_name, column_type, column_default, is_nullable FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${s}`},async getTableData(t,r,n,s){return t`SELECT * FROM ${me(r)} LIMIT ${n} OFFSET ${s}`},async optimize(t,r){await t`${v.unsafe(`OPTIMIZE TABLE ${k(r.table)}`)}`}}}var Fe=Et("mysql"),Ue=Et("mariadb");var Or={sqlite:je,postgres:Le,mysql:Fe,mariadb:Ue};function fe(e){let t=Or[e];if(!t)throw Error(`Unsupported database dialect: ${e}`);return t}class V{db;schema;constructor(e,t){this.db=e;this.schema=t}listTables(){return this.schema.dialect.listTables(this.db)}dropTable(){return this.schema.dialect.dropTable(this.db,this.schema)}truncateTable(){return this.schema.dialect.truncateTable(this.db,this.schema)}getTableStats(){return this.schema.dialect.getTableStats(this.db,this.schema)}getTableIndices(){return this.schema.dialect.getTableIndices(this.db,this.schema)}getTableSchema(){return this.schema.dialect.getTableSchema(this.db,this.schema)}getTableData(e=50,t=0){if(!Number.isSafeInteger(e)||e<0)throw RangeError("Limit must be a non-negative safe integer.");if(!Number.isSafeInteger(t)||t<0)throw RangeError("Offset must be a non-negative safe integer.");return this.schema.dialect.getTableData(this.db,this.schema,e,t)}optimize(){return this.schema.dialect.optimize(this.db,this.schema)}static sqlite(e,t){return new V(e,t.withDialect(fe("sqlite")))}static postgres(e,t){return new V(e,t.withDialect(fe("postgres")))}}var{sql:b}=globalThis.Bun;var vr=new Set(["=","!=","<","<=",">",">=","LIKE","ILIKE","IS","IS NOT","IN","NOT IN"]);class He{db;schema;constructor(e,t){this.db=e;this.schema=t}get dialect(){return this.schema.dialect}get inspect(){return new V(this.db,this.schema)}withContext(e){return new He(e,this.schema)}create(){return this.dialect.createTable(this.db,this.schema)}testConnection(){return this.dialect.version(this.db)}async syncColumns(e=!1){let t=await this.dialect.getColumns(this.db,this.schema),r=new Map(t.map((a)=>[this.dialect.normalizeColumnName(a),a])),n=this.schema.columnDefinitions(),s=Object.keys(n),i=new Set(s.map((a)=>this.dialect.normalizeColumnName(a)));for(let a of s)if(!r.has(this.dialect.normalizeColumnName(a)))await this.dialect.addColumn(this.db,this.schema,a,n[a]);if(e){for(let[a,o]of r)if(!i.has(a))await this.dialect.dropColumn(this.db,this.schema,o)}}identifier(e){return b.unsafe(this.dialect.quoteIdentifier(e))}get table(){return b.unsafe(this.dialect.quoteTable(this.schema.table))}joinSql(e,t){if(e.length===0)return b``;return e.slice(1).reduce((r,n)=>b`${r}${t}${n}`,e[0])}buildWhere(e={}){let t=Object.entries(e).map(([r,n])=>{if(n!==null&&typeof n==="object"&&"operator"in n&&"value"in n){let s=String(n.operator).toUpperCase();if(!vr.has(s))throw TypeError(`Unsupported SQL operator: ${s}`);let i=this.dialect.normalizeOperator(s),a=n.value;if(i==="IN"||i==="NOT IN"){if(!Array.isArray(a))throw TypeError(`${i} requires an array value.`);if(a.length===0)return i==="IN"?b`1=0`:b`1=1`;let o=this.joinSql(a.map((c)=>b`${c}`),b`, `);return b`${this.identifier(r)} ${b.unsafe(i)} (${o})`}if(a===null&&(i==="="||i==="IS"))return b`${this.identifier(r)} IS NULL`;if(a===null&&(i==="!="||i==="IS NOT"))return b`${this.identifier(r)} IS NOT NULL`;return b`${this.identifier(r)} ${b.unsafe(i)} ${a}`}return n===null?b`${this.identifier(r)} IS NULL`:b`${this.identifier(r)} = ${n}`});return t.length?this.joinSql(t,b` AND `):b`1=1`}async insert(e){try{if(this.dialect.name==="mysql"||this.dialect.name==="mariadb"){let r=Object.keys(e).length===0?await this.db`INSERT INTO ${this.table} () VALUES ()`:await this.db`INSERT INTO ${this.table} ${b(e)}`,[n]=this.schema.entries().find(([,o])=>o.primaryKey)??[];if(!n)return;let s=e[n],i=s??r.lastInsertRowid;if(i==null||s===void 0&&i===0)return;let[a]=await this.db`SELECT * FROM ${this.table} WHERE ${this.identifier(n)} = ${i} LIMIT 1`;return a}let[t]=Object.keys(e).length===0?await this.db`INSERT INTO ${this.table} DEFAULT VALUES RETURNING *`:await this.db`INSERT INTO ${this.table} ${b(e)} RETURNING *`;return t}catch(t){this.handleDbError(t)}}async upsert(e,t){try{return await this.dialect.upsert(this.db,this.schema,e,t)}catch(r){this.handleDbError(r)}}async find(e){let[t]=await this.db`
|
|
64
64
|
SELECT * FROM ${this.table} WHERE ${this.buildWhere(e)} LIMIT 1
|
|
65
65
|
`;return t??null}async findAll(e){return e&&Object.keys(e).length?await this.db`SELECT * FROM ${this.table} WHERE ${this.buildWhere(e)}`:await this.db`SELECT * FROM ${this.table}`}async count(e){let[t]=e&&Object.keys(e).length?await this.db`SELECT COUNT(*) AS total FROM ${this.table} WHERE ${this.buildWhere(e)}`:await this.db`SELECT COUNT(*) AS total FROM ${this.table}`;return Number(t?.total??0)}async exists(e){let[t]=await this.db`
|
|
66
66
|
SELECT 1 FROM ${this.table} WHERE ${this.buildWhere(e)} LIMIT 1
|
|
67
|
-
`;return t!==void 0}async paginate(e,t,r){if(!Number.isSafeInteger(e)||e<1)throw RangeError("Page must be a positive safe integer.");if(!Number.isSafeInteger(t)||t<1)throw RangeError("Limit must be a positive safe integer.");let n=(e-1)*t;if(!Number.isSafeInteger(n))throw RangeError("Pagination offset exceeds the safe integer range.");return r&&Object.keys(r).length?await this.db`SELECT * FROM ${this.table} WHERE ${this.buildWhere(r)} LIMIT ${t} OFFSET ${n}`:await this.db`SELECT * FROM ${this.table} LIMIT ${t} OFFSET ${n}`}async update(e,t){try{if(Object.keys(e??{}).length===0)throw new
|
|
68
|
-
UPDATE ${this.table} SET ${
|
|
67
|
+
`;return t!==void 0}async paginate(e,t,r){if(!Number.isSafeInteger(e)||e<1)throw RangeError("Page must be a positive safe integer.");if(!Number.isSafeInteger(t)||t<1)throw RangeError("Limit must be a positive safe integer.");let n=(e-1)*t;if(!Number.isSafeInteger(n))throw RangeError("Pagination offset exceeds the safe integer range.");return r&&Object.keys(r).length?await this.db`SELECT * FROM ${this.table} WHERE ${this.buildWhere(r)} LIMIT ${t} OFFSET ${n}`:await this.db`SELECT * FROM ${this.table} LIMIT ${t} OFFSET ${n}`}async update(e,t){try{if(Object.keys(e??{}).length===0)throw new M("Refusing to update rows without a WHERE condition.");if(Object.keys(t).length===0)throw new M("Refusing to run an UPDATE with no values.");if(this.dialect.name==="mysql"||this.dialect.name==="mariadb")return await this.db.begin(async(r)=>{let n=await r`SELECT * FROM ${this.table} WHERE ${this.buildWhere(e)} FOR UPDATE`;return await r`UPDATE ${this.table} SET ${b(t)} WHERE ${this.buildWhere(e)}`,n.map((s)=>({...s,...t}))});return await this.db`
|
|
68
|
+
UPDATE ${this.table} SET ${b(t)}
|
|
69
69
|
WHERE ${this.buildWhere(e)} RETURNING *
|
|
70
|
-
`}catch(r){this.handleDbError(r)}}async delete(e){try{if(Object.keys(e??{}).length===0)throw new
|
|
70
|
+
`}catch(r){this.handleDbError(r)}}async delete(e){try{if(Object.keys(e??{}).length===0)throw new M("Refusing to delete rows without a WHERE condition.");if(this.dialect.name==="mysql"||this.dialect.name==="mariadb")return await this.db.begin(async(t)=>{let r=await t`SELECT * FROM ${this.table} WHERE ${this.buildWhere(e)} FOR UPDATE`;return await t`DELETE FROM ${this.table} WHERE ${this.buildWhere(e)}`,r});return await this.db`
|
|
71
71
|
DELETE FROM ${this.table} WHERE ${this.buildWhere(e)} RETURNING *
|
|
72
|
-
`}catch(t){this.handleDbError(t)}}async transaction(e){try{return await this.db.begin(async(t)=>e(this.withContext(t),t))}catch(t){this.handleDbError(t)}}handleDbError(e){let r=(e instanceof Error?e.message:String(e)).toLowerCase();if(r.includes("unique constraint failed")||r.includes("duplicate key value violates unique constraint")||r.includes("duplicate entry"))throw new
|
|
72
|
+
`}catch(t){this.handleDbError(t)}}async transaction(e){try{return await this.db.begin(async(t)=>e(this.withContext(t),t))}catch(t){this.handleDbError(t)}}handleDbError(e){let r=(e instanceof Error?e.message:String(e)).toLowerCase();if(r.includes("unique constraint failed")||r.includes("duplicate key value violates unique constraint")||r.includes("duplicate entry"))throw new le(`A record with this unique value already exists in ${this.schema.table}.`);if(r.includes("foreign key constraint failed")||r.includes("violates foreign key constraint")||r.includes("foreign key constraint fails"))throw new de("Cannot delete or update this record because it is referenced by another table.");if(r.includes("database is locked")||r.includes("sqlite_busy"))throw new M("The database is busy. Please retry the operation.");throw e}}class We{table;definitions;dialect;constructor(e,t,r){this.table=e;this.definitions=t;this.dialect=r}entries(){return Object.entries(this.definitions)}withDialect(e){let t=Object.fromEntries(this.entries());return new We(this.table,t,e)}createSQL(e=this.dialect){let t=this.entries();if(t.length===0)throw Error(`Cannot create table '${this.table}' without columns.`);return`CREATE TABLE IF NOT EXISTS ${e.quoteTable(this.table)} (
|
|
73
73
|
${t.map(([r,n])=>e.buildColumn(r,n)).join(`,
|
|
74
74
|
`)}
|
|
75
|
-
);`}columnDefinitions(e=this.dialect){return Object.fromEntries(this.entries().map(([t,r])=>[t,e.buildColumnType(r)]))}get columns(){return new Proxy({},{get:(e,t)=>typeof t==="string"?t:void 0})}}function p(e,t={}){return function(r,n={}){let{id:s,...i}=t,a={...i,...n,code:t.code??400,message:n.message??t.message??"Request Failed",headers:{...t.headers,...n.headers}};if(n.redirect!==void 0||t.redirect!==void 0)a.redirect=n.redirect??t.redirect;let o=async(c,d)=>e(c,d,r,a);if(s)o._middlewareId=s,o.id=s;return o}}var ps=p(async(e,t,r,n)=>{let i=e.req.headers.get("Authorization")?.trim()?.match(/^Bearer\s+(\S+)$/i);if(!i||!await r(e,i[1]))return l(n);return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),hs=p(async(e,t,r,n)=>{let s=e.req.headers.get("x-api-key");if(!s)return l({code:401,message:"Missing api key"});if(!await r(e,s))return l({code:401,message:"Invalid API Key."});return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),gs=p(async(e,t,r,n)=>{for(let[s,i]of Object.entries(r)){let a=e.req.headers.get(s);if(!a)return l({code:401,message:`Missing ${s} header.`});if(!await i(e,a))return l({code:401,message:"Invalid."})}return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),ys=p(async(e,t,r,n)=>{if(!r||!await r(e))return l(n);return t()},{id:"authorize-guard",code:403,message:"Forbidden"});var _=new Map,It=1000,Pt=new Set(["no-cache","no-store"]),kt=new Set(["private","no-store","no-cache"]),qt=/(?:^|,)\s*(?:max-age|s-maxage)\s*=\s*["']?0(?:\s|,|$)/i;function rt(e,t){return e?.split(",").some((r)=>t.has(r.trim().split("=",1)[0].toLowerCase()))??!1}function Ut(e){let t=e.req.headers;if(t.has("authorization")||t.has("cookie")||t.has("range"))return!0;return rt(t.get("cache-control"),Pt)||t.get("pragma")?.toLowerCase().includes("no-cache")===!0}function jt(e){let t=e.headers.get("cache-control")??"";return e.status===200&&!e.headers.has("set-cookie")&&!e.headers.has("content-range")&&!e.headers.has("vary")&&!rt(t,kt)&&!qt.test(t)}var Ts=p(async(e,t,r)=>{if(e.req.method!=="GET"||Ut(e))return await t();let n=r?.ttlMs;if(!Number.isFinite(n)||n<=0)return await t();let s=Date.now();for(let[u,m]of _)if(m.expires<=s)_.delete(u);let i=e.req.url.href,a=_.get(i);if(a)return new Response(a.body.slice(),{status:a.status,statusText:a.statusText,headers:new Headers(a.headers)});let o=await t();if(!jt(o))return o;let c=o.clone(),d=new Uint8Array(await c.arrayBuffer());if(_.size>=It){let u=_.keys().next().value;if(u!==void 0)_.delete(u)}return _.set(i,{expires:s+n,body:d,headers:new Headers(c.headers),status:c.status,statusText:c.statusText}),o});var xs=p(async(e,t,r,n)=>{if(!r)return t();let s=e.req.header("content-type")??null,i=s?s.split(";")[0].trim().toLowerCase():null,a=!1;if(typeof r==="function")a=r(i,e);else{let o=Array.isArray(r)?r.map(nt):[nt(r)];a=i!==null&&o.includes(i)}if(!a)return l(n);return t()},{id:"content-type",code:415,message:"Unsupported Media Type. The request Content-Type is invalid or missing."});function nt(e){return e.split(";")[0].trim().toLowerCase()}var Ns=p(async(e,t,r,n)=>{if(!e.req.cookies.has(r))return l(n);return await t()},{id:"cookie-checker",code:401,message:"Required cookie is missing."});function Ae(e){if(!e)return;return Array.isArray(e)?e.join(", "):e}var $s=p(async(e,t,r,n)=>{let{origin:s="*",allowHeaders:i="*",methods:a,exposeHeaders:o,credentials:c=!1,maxAge:d=86400}=r||{},u=e.req?.headers?.get("origin")||null,m=null;if(typeof s==="function"){let h=s(u,e);m=typeof h==="string"?h:h?u:null}else if(Array.isArray(s)){if(u&&s.some((h)=>h===u))m=u}else if(s==="*")m=c?u:"*";else if(u===s)m=u;if(u&&!m)return l(n);let f={};if(m)f["Access-Control-Allow-Origin"]=m;if(c)f["Access-Control-Allow-Credentials"]="true";if(o){let h=Ae(o);if(h)f["Access-Control-Expose-Headers"]=h}if(i){let h=Ae(i);if(h)f["Access-Control-Allow-Headers"]=h}if(a){let h=Ae(a);if(h)f["Access-Control-Allow-Methods"]=h}if(d!==void 0)f["Access-Control-Max-Age"]=d.toString();if(m&&m!=="*")f.Vary="Origin";return e.res.header(f),await t()},{code:403,message:"CORS Origin Not Allowed",id:"cors-guard"});var Ps=p(async(e,t,r,n)=>{if(["POST","PUT","DELETE","PATCH"].includes(e.req.method)){let s=r?.headerName||"x-csrf-token",i=e.req.headers.get(s),a=e.req.cookies.get("csrf_token")||"";if(!i||!a||i!==a)return l(n)}return await t()},{id:"csrf-guard",code:403,message:"CSRF Token Validation Failed"});var Us=p(async(e,t,r)=>{try{return await t()}catch(n){if(r?.logErrors)console.error(n);if(r?.onError)return await r.onError(n,e);return e.res.error(500,r?.message??"Internal Server Error")}},{id:"error-handler"});var Ws=p(async(e,t,r,n)=>{let s=(i)=>e.req.headers.get(i);if(r){let i=null;if(Array.isArray(r))i=r;else if(typeof r==="string")i=[r];if(i){for(let a of i)if(!s(a))return l({code:401,message:`Missing required ${a} property.`})}else for(let[a,o]of Object.entries(r)){let c=s(a);if(!c)return l({code:401,message:`Missing required ${a} property.`});if(!o(e,a,c))return l(n)}}return await t()},{code:400,message:"Required headers are missing or invalid."});var Z=(e)=>{let t=e.req.server;if(t)return t.requestIP(e.req.request)?.address??"";return e.req.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||"127.0.0.1"};function ee(e){let t=e.split(".");if(t.length!==4)return null;let r=[];for(let n of t){if(!/^(0|[1-9]\d{0,2})$/.test(n))return null;let s=Number(n);if(s>255)return null;r.push(s)}return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0}class te{rules=[];constructor(e){this.compileRules(e)}test(e){let t=e.split(",")[0]?.trim()??"",r=ee(t);if(r===null)return!1;return this.rules.some((n)=>n(t,r))}compileRules(e){for(let t of e){let r=t.trim();if(r.includes("/"))this.rules.push(this.compileCidr(r));else if(r.includes("*"))this.rules.push(this.compileWildcard(r));else{let n=ee(r);if(n===null)throw RangeError(`Invalid IPv4 rule: ${t}`);this.rules.push((s,i)=>i===n)}}}compileCidr(e){let t=e.match(/^([^/]+)\/(0|[1-9]\d?)$/);if(!t)throw RangeError(`Invalid IPv4 CIDR rule: ${e}`);let r=ee(t[1]),n=Number(t[2]);if(r===null||n>32)throw RangeError(`Invalid IPv4 CIDR rule: ${e}`);let s=n===0?0:4294967295<<32-n>>>0,i=(r&s)>>>0;return(a,o)=>(o&s)>>>0===i}compileWildcard(e){let t=e.split(".");if(t.length!==4||t.some((r)=>r!=="*"&&ee(`0.0.0.${r}`)===null))throw RangeError(`Invalid IPv4 wildcard rule: ${e}`);return(r)=>r.split(".").every((n,s)=>{let i=t[s];return i==="*"||n===i})}}var Qs=p(async(e,t,r,n)=>{let s=Z(e),{blacklist:i=[],whitelist:a=[]}=r??{};if(i.length){if(new te(i).test(s))return l(n)}if(a.length){if(!new te(a).test(s))return l(n)}return await t()},{id:"ip-filter",code:403,message:"Forbidden"});var Ft=["POST","PUT","PATCH"],Ht=1048576,ti=p(async(e,t,r,n)=>{if(!Ft.includes(e.req.method.toUpperCase()))return await t();if(e.req.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()!=="application/json")return l({code:415,message:"Content-Type must be application/json"});let i=n.maxSize,a=typeof i==="number"&&i>0?i:Ht,o=e.req.headers.get("content-length");if(o!==null){if(!/^\d+$/.test(o))return l({code:400,message:"Invalid Content-Length header"});let f=Number(o);if(!Number.isSafeInteger(f)||f<0)return l({code:400,message:"Invalid Content-Length header"});if(f>a)return l({code:413,message:`Payload exceeded maximum allowed size of ${a/1024} KB`})}let c="";try{c=await e.req.text()}catch{return l({code:400,message:"Failed to read request stream"})}if(new TextEncoder().encode(c).byteLength>a)return l({code:413,message:`Payload exceeded maximum allowed size of ${a/1024} KB`});if(!c||c.trim().length===0)return l({code:400,message:"Request body cannot be empty"});let d;try{d=JSON.parse(c)}catch(f){return l({code:400,message:`Invalid JSON syntax: ${f.message}`})}if(typeof d!=="object"||d===null)return l({code:400,message:"JSON payload must be a valid JSON object or array"});let{errors:u,processedData:m}=r.validate(d);if(u.length>0)return l({...n,message:`Validation failed: ${u.join(", ")}`});return e.req._json=m,await t()},{id:"json-validator",code:400}),ri=p(async(e,t,r)=>{let n=await e.req.json();if(!n||typeof n!=="object"||Array.isArray(n))return l({code:400,message:"JSON body must be an object"});let s=r.filter((i)=>!Object.hasOwn(n,i));if(s.length>0)return l({code:400,message:`Missing required fields: ${s.join(", ")}`});return e.body=n,await t()},{id:"require-keys",code:400});var ai=p(async(e,t,r,n)=>{if(!r)throw Error("jwtAuth requires a JWTAuthService instance.");let i=e.req.headers.get("Authorization")?.trim().match(/^Bearer\s+(\S+)$/i);if(!i)return l(n);let a=r.verify(i[1]);if(!a)return l(n);return e.jwtData=a,await t()},{id:"jwt-auth-guard",code:401,message:"Unauthorized Access"}),oi=p(async(e,t,r,n)=>{if(!r)throw Error("jwtRefresh requires a JWTAuthService instance.");let s=e.req.headers.get("x-refresh-token")?.trim();if(!s||/\s/.test(s))return l(n);let i=await r.consume(s);if(!i)return l(n);return e.jwtData=i,e.data.jwtTokens=await r.issue(i),await t()},{id:"jwt-refresh-guard",code:401,message:"Refresh Token Failed"});var li=p(async(e,t,r="",n)=>{let s=e.req.method,i=new URL(e.req.url).pathname,a=new Date().toLocaleString();return console.log(`${s} ${i} @ ${a}${r?` | ${r}`:""}`),await t()}),di=p(async(e,t,r,n)=>{let s=e.req.method,i=new URL(e.req.url).pathname,a=new Date().toLocaleTimeString(),o=await t(),c=r({ctx:e,res:o,timestamp:a,method:s,url:i});if(c)console.log(c);return o});function H(e){let t=Object.create(null);for(let[r,n]of e.entries()){if(!Object.prototype.hasOwnProperty.call(t,r)){t[r]=n;continue}let s=t[r];t[r]=Array.isArray(s)?[...s,n]:[s,n]}return t}var yi=p(async(e,t)=>{if(!(e.req.headers.get("content-type")?.toLowerCase()??"").startsWith("multipart/form-data"))return t();try{let n=await e.req.request.formData();e.req._formData=n,e.form=H(n)}catch{return l({code:400,message:"Invalid multipart form data"})}return t()},{id:"multipart-parser",code:400,message:"Invalid multipart form data"});class Oe{schema={};rules={};defaults={};string(e,t){if(this.schema[e]="string",t!==void 0)this.defaults[e]=t;return this}number(e,t){if(this.schema[e]="number",t!==void 0)this.defaults[e]=t;return this}boolean(e,t){if(this.schema[e]="boolean",t!==void 0)this.defaults[e]=t;return this}min(e,t){return this.noKey(e,"min"),this.addRule(e,(r)=>(this.noBool(r,"min"),(typeof r==="string"?r.length:r)>=t),`must have at least ${t} ${typeof t==="number"?"characters/value":""}`),this}max(e,t){return this.noKey(e,"max"),this.addRule(e,(r)=>(this.noBool(r,"max"),(typeof r==="string"?r.length:r)<=t),`must have at most ${t} ${typeof t==="number"?"characters/value":""}`),this}email(e){let t=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return this.addRule(e,(r)=>typeof r==="string"&&t.test(r),"must be a valid email"),this}addRule(e,t,r){if(!this.rules[e])this.rules[e]=[];this.rules[e].push({fn:t,message:r})}noBool(e,t){if(typeof e==="boolean")throw Error(`Can't use ${t} with Boolean`)}noKey(e,t){if(!this.schema[e])throw Error(`Can't use ${t} with missing key: ${String(e)}`)}validate(e){if(Array.isArray(e)){let t=[],r=[];return e.forEach((n,s)=>{let{errors:i,processedData:a}=this.validateObject(n);i.forEach((o)=>t.push(`[Item ${s}] ${o}`)),r.push(a)}),{errors:t,processedData:r}}return this.validateObject(e)}validateObject(e){let t=[],r={...e};for(let[n,s]of Object.entries(this.schema)){if(!(n in r))if(n in this.defaults)r[n]=this.defaults[n];else{t.push(`Missing field: '${n}'`);continue}if(typeof r[n]!==s){t.push(`Invalid type for '${n}': Expected ${s}, got ${typeof r[n]}`);continue}if(this.rules[n]){for(let i of this.rules[n])if(!i.fn(r[n]))t.push(`'${n}' ${i.message}`)}}return{errors:t,processedData:r}}}function Wt(){return new Oe}function Ne(e,t){let r=t.schema,n={...e};for(let[s,i]of Object.entries(r)){if(!(s in e)||e[s]===void 0)continue;let a=e[s];if(i==="number"&&typeof a==="string"){let o=Number(a);if(Number.isFinite(o)&&a.trim()!=="")n[s]=o}else if(i==="boolean"&&typeof a==="string"){if(a.toLowerCase()==="true"||a==="1")n[s]=!0;if(a.toLowerCase()==="false"||a==="0")n[s]=!1}}return n}var xi=p(async(e,t,r,n)=>{let s=r;if(!s||typeof s.validate!=="function")return l({code:500,message:"Framework Error: Missing schema in validateQuery guard."});let i;try{i=typeof e.req.url==="string"?new URL(e.req.url,"http://localhost"):e.req.url}catch{return l({code:n.code??400,message:"Malformed URL structure."})}let a=Object.create(null);i.searchParams.forEach((u,m)=>{a[m]=u});let o=Ne(a,s),{errors:c,processedData:d}=s.validate(o);if(c.length>0)return l({code:n.code??400,message:`Query Validation Error: ${c.join("; ")}`});return e.query=d,await t()},{id:"query-validator",code:400,message:"Query validation failed"}),Ci=p(async(e,t,r,n)=>{let s=r;if(!s||typeof s.validate!=="function")return l({code:500,message:"Framework Error: Missing schema in validateForm guard."});let i;try{let d=await e.req.form();i=H(d)}catch{return l({code:n.code??400,message:"Invalid or malformed form payload."})}let a=Ne(i,s),{errors:o,processedData:c}=s.validate(a);if(o.length>0)return l({code:n.code??400,message:`Form Validation Error: ${o.join("; ")}`});return e.form=c,await t()},{id:"form-validator",code:400,message:"Form validation failed"});var st=new Map;function it(e,t,r){let n=Date.now(),s=st.get(e);if(!s||s.reset<n){let i=n+r;return st.set(e,{count:1,reset:i}),{allowed:!0,remaining:Math.max(0,t-1),resetTime:i}}if(s.count>=t)return{allowed:!1,remaining:0,resetTime:s.reset};return s.count+=1,{allowed:!0,remaining:Math.max(0,t-s.count),resetTime:s.reset}}var $i=p(async(e,t,r,n)=>{let{max:s=100,windowMs:i=60000,expose:a=!0}=r||{},o=Z(e),c=e.req.method,d=`rate_${o}_${c}_${new URL(e.req.url).pathname}`,{allowed:u,remaining:m,resetTime:f}=it(d,s,i),h={};if(a)h["X-RateLimit-Limit"]=s.toString(),h["X-RateLimit-Remaining"]=m.toString(),h["X-RateLimit-Reset"]=Math.ceil(f/1000).toString();if(!u){if(a){let v=Math.max(1,Math.ceil((f-Date.now())/1000));h["Retry-After"]=v.toString()}return l({...n,headers:h})}let A=await t();if(a)Object.entries(h).forEach(([v,re])=>{A.headers.set(v,re)});return A},{id:"rate-limiter",code:429,message:"Too Many Requests"});function Bt(e){return e.replace(/[&<>"']/g,(t)=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}function W(e,t,r=new WeakMap){if(typeof e==="string")return t(e);if(Array.isArray(e)){if(r.has(e))return r.get(e);let s=[];r.set(e,s);for(let i of e)s.push(W(i,t,r));return s}if(e===null||typeof e!=="object"||e instanceof Blob)return e;if(r.has(e))return r.get(e);let n=Object.create(null);r.set(e,n);for(let[s,i]of Object.entries(e))n[s]=W(i,t,r);return n}var Ii=p(async(e,t,r)=>{let n=r?.sanitizeString??Bt;if(r?.query!==!1)e.query=W(e.query,n);if(r?.form!==!1)e.form=W(e.form,n);if(r?.body!==!1){if(e.body!==void 0)e.body=W(e.body,n);let s=e.req._json;if(s!==void 0)e.req._json=W(s,n)}return t()},{id:"sanitize-guard"});function Kt(e,t){let r={"Content-Security-Policy":t.contentSecurityPolicy,"Cross-Origin-Embedder-Policy":t.crossOriginEmbedderPolicy,"Cross-Origin-Opener-Policy":t.crossOriginOpenerPolicy,"Cross-Origin-Resource-Policy":t.crossOriginResourcePolicy,"Strict-Transport-Security":t.hsts,"Permissions-Policy":t.permissionsPolicy,"Referrer-Policy":t.referrerPolicy??"strict-origin-when-cross-origin","X-Content-Type-Options":t.xContentTypeOptions??"nosniff","X-Frame-Options":t.xFrameOptions??"DENY"},n=new Headers(e.headers);for(let[s,i]of Object.entries(r))if(i===!1)n.delete(s);else if(i)n.set(s,i);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}var qi=p(async(e,t,r)=>{let n=await t();return Kt(n,r??{})},{id:"security-headers"});var Fi=p(async(e,t,r,n)=>{let[s,i]=await r.loadHeader(e.req.request);e.session=i;let a=await t();if(!e.session.isReadOnly){if(!e.session.length){if(e.session.isNew){if(s)await r.deleteSession(e.session,a.headers)}else if(e.session.isModified)await r.deleteSession(e.session,a.headers)}else if(e.session.isModified)await r.saveSession(e.session,a.headers)}return a},{id:"session-manager"});var Bi=p(async(e,t)=>{if(!e.req.isFile||!["GET","HEAD"].includes(e.req.method))return t();let r=await e.res.fileServer();if(e.req.method!=="HEAD")return r;return new Response(null,{status:r.status,statusText:r.statusText,headers:r.headers})},{id:"static-files"});var Vi=p(async(e,t,r,n)=>{let s,i=new Promise((a)=>{s=setTimeout(()=>a(l(n)),r)});try{return await Promise.race([t(),i])}finally{if(s)clearTimeout(s)}},{id:"timeout-guard",code:408,message:"Request Timeout"});var zt=2048,Gt=1024,Xi=p(async(e,t,r,n)=>{let s=typeof r==="number"?{maxUrlLength:r}:r||{},i=s.maxUrlLength??zt,a=s.maxQueryLength??Gt,o;try{o=typeof e.req.url==="string"?new URL(e.req.url,"http://localhost"):e.req.url}catch{return l({code:400,message:"Malformed URL structure."})}let c=o.href;if(c.length>i)return l({code:414,message:`URI Too Long. Exceeds limit of ${i} characters.`});if((o.search.startsWith("?")?o.search.slice(1):o.search).length>a)return l({code:414,message:`Query string too long. Exceeds limit of ${a} characters.`});if(s.sanitizePaths!==!1){let f=c;try{let h="";while(f!==h&&f.includes("%"))h=f,f=decodeURIComponent(f)}catch{return l({code:400,message:"Malformed percent-encoding in URL."})}if(f.includes("\x00"))return l({code:400,message:"Null byte injection detected in URL."});if(f.includes("../")||f.includes("..\\")||f.includes("/.."))return l({code:400,message:"Path traversal attempt detected in URL."})}let u=o.searchParams,m=Array.from(u.keys());if(m.length>0){if(s.noDuplicates){if(new Set(m).size!==m.length)return l({code:n.code??400,message:"Duplicate query parameters are not allowed."})}if(s.allowedKeys){let f=new Set(s.allowedKeys);for(let h of m)if(!f.has(h))return l({code:n.code??400,message:`Unauthorized query parameter: '${h}'`})}if(s.disallowedKeys){let f=new Set(s.disallowedKeys);for(let h of m)if(f.has(h))return l({code:n.code??400,message:`Forbidden query parameter: '${h}'`})}if(s.patterns)for(let[f,h]of Object.entries(s.patterns)){let A=u.getAll(f);for(let v of A){h.lastIndex=0;let re=h.test(v);if(h.lastIndex=0,!re)return l({code:n.code??400,message:`Invalid format for query parameter '${f}'.`})}}}return await t()},{id:"url-validator",code:400,message:"URL validation failed"});var na=p(async(e,t)=>{if(!(e.req.headers.get("content-type")?.toLowerCase()??"").startsWith("application/x-www-form-urlencoded"))return t();try{let n=await e.req.request.formData();e.req._formData=n,e.form=H(n)}catch{return l({code:400,message:"Invalid URL-encoded form data"})}return t()},{id:"urlencoded-parser",code:400,message:"Invalid URL-encoded form data"});import{createHmac as at,timingSafeEqual as Vt}from"crypto";class ve{secretKey;constructor(e){if(!e)throw Error("JWT secret key must be provided.");this.secretKey=Buffer.from(e,"utf8")}sign(e,t=15){if(!Number.isFinite(t)||t<=0)throw RangeError("Token validity must be a positive number of minutes.");let r={alg:"HS256",typ:"JWT"},n=Math.floor(Date.now()/1000),s={...e,iat:n,exp:n+t*60},i=Buffer.from(JSON.stringify(r)).toString("base64url"),a=Buffer.from(JSON.stringify(s)).toString("base64url"),o=`${i}.${a}`,c=at("sha256",this.secretKey).update(o).digest("base64url");return`${o}.${c}`}verify(e){try{let t=e.split(".");if(t.length!==3)return null;let[r,n,s]=t,i=`${r}.${n}`,a=JSON.parse(Buffer.from(r||"","base64url").toString("utf8"));if(!a||typeof a!=="object"||a.alg!=="HS256"||a.typ!=="JWT")return null;let o=at("sha256",this.secretKey).update(i).digest("base64url"),c=Buffer.from(o),d=Buffer.from(s||"");if(c.length!==d.length||!Vt(c,d))return null;let u=JSON.parse(Buffer.from(n||"","base64url").toString("utf8"));if(!u||typeof u!=="object"||!Number.isFinite(u.iat)||!Number.isFinite(u.exp))return null;let m=Math.floor(Date.now()/1000);if(u.exp<=m)return null;return u}catch{return null}}issue(e,t=7){let r=t*24*60;return this.sign(e,r)}}class ot{refreshTokens;config;engine;constructor(e,t,r={}){this.refreshTokens=e;this.engine=new ve(t);let{refreshValidity:n=7,tokenValidity:s=15}=r;if(!Number.isFinite(n)||n<=0)throw RangeError("Refresh token validity must be a positive number of days.");if(!Number.isFinite(s)||s<=0)throw RangeError("Access token validity must be a positive number of minutes.");this.config={refreshValidity:n,tokenValidity:s}}async init(){await this.refreshTokens.initialize?.()}sign(e){return this.engine.sign(e,this.config.tokenValidity)}verify(e){return this.engine.verify(e)}async consume(e){let t=this.engine.verify(e);if(!t)return null;return await this.refreshTokens.consume(e)?t:null}async issue(e){let t=this.engine.issue(e,this.config.refreshValidity),r=Date.now()+this.config.refreshValidity*24*60*60*1000;return await this.refreshTokens.save(t,r),{accessToken:this.sign(e),refreshToken:t}}}class B{sid;data;isNew;isModified;isReadOnly;isFound;length=0;constructor(e="",t={},r=!1,n=!0,s=!1){if(this.sid=e,this.data={...t},this.length=Object.keys(t).length,this.length)n=!1;this.isReadOnly=r,this.isNew=n,this.isModified=!1,this.isFound=s}get session(){return new Proxy(this,{get(e,t){if(t in e)return Reflect.get(e,t);return e.data[t]},set(e,t,r){if(e.isReadOnly)return console.warn("session: readonly"),!0;if(t in e)throw Error(`Cannot overwrite internal session property: ${String(t)}`);if(e.data[t]!==r){if(e.isModified=!0,!(t in e.data))e.length++;e.data[t]=r}return!0},deleteProperty(e,t){if(e.isReadOnly)return console.warn("session: readonly"),!0;if(t in e)return!1;if(t in e.data)e.isModified=!0,delete e.data[t],e.length--;return!0},has(e,t){return t in e||t in e.data},ownKeys(e){return Reflect.ownKeys(e.data)},getOwnPropertyDescriptor(e,t){if(t in e.data)return{enumerable:!0,configurable:!0,value:e.data[t]};return}})}}import{randomBytes as Xt}from"crypto";import{createHmac as Jt,createHash as Yt,timingSafeEqual as Qt}from"crypto";class De{salt;key;constructor(e){this.salt=e;this.key=Yt("sha256").update(e).digest()}getSignature(e){return Jt("sha256",this.key).update(e).digest("base64url")}sign(e){let t=this.getSignature(e);return`${e}.${t}`}unsign(e){let t=e.indexOf(".");if(t===-1)return null;let r=e.slice(0,t),n=e.slice(t+1);if(this.verifySignature(r,n))return r;return null}verifySignature(e,t){let r=Buffer.from(this.getSignature(e),"utf8"),n=Buffer.from(t,"utf8");if(r.length!==n.length)return!1;return Qt(r,n)}}class Me{signer;constructor(e){this.signer=new De(e)}generate(e=21){let t=Xt(e).toString("base64url");return this.signer.sign(t)}}class ct extends Me{config;constructor(e,t){super(t??"salty");e.COOKIE_NAME=e.COOKIE_NAME??"session";let{COOKIE_NAME:r="session",COOKIE_LIFETIME:n=31,COOKIE_DOMAIN:s=void 0,COOKIE_PATH:i="/",COOKIE_HTTPONLY:a=!0,COOKIE_SECURE:o=!0,COOKIE_SAMESITE:c="Lax",MAX_COOKIE_SIZE:d=4093,SESSION_LIFETIME:u=31}=e;this.config={COOKIE_NAME:r,COOKIE_LIFETIME:n,COOKIE_DOMAIN:s,COOKIE_PATH:i,COOKIE_HTTPONLY:a,COOKIE_SECURE:o,COOKIE_SAMESITE:c,MAX_COOKIE_SIZE:d,SESSION_LIFETIME:u}}async init(){}async openSession(e,t=!1){if(e&&this.signer.unsign(e))return await this.fetchSession(e,t);return this.new({})}async fetchSession(e,t){try{let r=await this.fetchData(e);if(r){let n=r.data??{};if(this.isNotExpired(new Date(r.expiration)))return new B(e,n,t,!1,!0).session;return this.new({sid:e,isFound:!0,readonly:t})}}catch(r){console.error(`[AuthEngine] Failed to parse session ${e}:`,r)}return this.new({sid:e,readonly:t})}new({sid:e,isFound:t=!1,readonly:r=!1}){return new B(e??this.generate(),{},r,!0,t).session}get readonly(){return new B(this.generate(),{},!0).session}get getSessionExpirationDate(){let e=new Date,t=this.config.SESSION_LIFETIME;return e.setDate(e.getDate()+t),e}get getCookieExpirationDate(){let e=new Date,t=this.config.COOKIE_LIFETIME;return e.setDate(e.getDate()+t),e}isNotExpired(e){let t=e.getTime(),r=Date.now();return t>r}buildCookieString(e,t,r){let n=[`${this.config.COOKIE_NAME}=${e.sid}`];if(n.push(`Path=${this.config.COOKIE_PATH}`),this.config.COOKIE_DOMAIN)n.push(`Domain=${this.config.COOKIE_DOMAIN}`);if(typeof t==="number")n.push(`Max-Age=${t}`);else{let c=t||this.getCookieExpirationDate;n.push(`Expires=${c.toUTCString()}`)}if(this.config.COOKIE_HTTPONLY)n.push("HttpOnly");if(this.config.COOKIE_SECURE)n.push("Secure");let s=r||this.config.COOKIE_SAMESITE;if(s)n.push(`SameSite=${s}`);let i=n.join("; "),a=Buffer.byteLength(i,"utf8"),o=this.config.MAX_COOKIE_SIZE;if(a>o)throw Error(`[Framework Guard] Cookie exceeds maximum allowed size! Size: ${a} bytes. Max allowed: ${o} bytes. The browser will reject this cookie.`);return i}setCookie(e,t){let r=this.buildCookieString(e);t.append("Set-Cookie",r)}removeCookie(e,t){let r=this.buildCookieString(e,0);t.append("Set-Cookie",r)}async loadHeader(e,t=!1){let r=e.headers.get("cookie");if(r){let n=r.match(new RegExp(`(^| )${this.config.COOKIE_NAME}=([^;]+)`));if(n){let s=n[2];return[s,await this.openSession(s,t)]}}return[void 0,this.new({readonly:t})]}}class ut{contextData={};data={};constructor(){}open(){}message({text:e,json:t,topic:r}){}drain(){}close(e,t){}set send(e){this.ws.send(e)}}class $e{static registry=new Map;static register(e){for(let[t,r]of Object.entries(e)){let n=Object.seal({...r});this.registry.set(t,n)}return{use:(t)=>this.use(t)}}static use(e){return new Proxy({},{get:(t,r)=>(n,s)=>{if(s.kind!=="field")throw Error("Field decorators can only be used on class fields.");return function(){let i=$e.registry.get(e);return i?i[r]:void 0}}})}}var Zt=$e;class lt{static registry=new Map;static register(e){for(let[t,r]of Object.entries(e))this.registry.set(t,Object.seal({...r}));return{use:(t)=>this.use(t)}}static use(e){let t=this.registry.get(e);if(!t)throw Error(`Scope "${e}" has not been registered.`);return t}}var er=lt;export{R as Column,Ht as DEFAULT_MAX_SIZE,O as DatabaseError,F as DbInspector,xe as DbRepository,Zt as Field,Y as ForeignKeyError,ot as JWTAuthService,he as Methods,I as Req,q as Res,Ve as Rossa,z as RouterManager,Ce as Schema,Oe as SchemaBuilder,er as Scope,B as ServerSide,ct as SessionAuthInterface,J as UniqueConstraintError,E as WSSMAN,ut as Websocket,V as WssManager,hs as apiKey,gs as auth,ps as authBearer,ys as authorize,xs as contentType,Ns as cookies,$s as cors,p as createGuard,Ps as csrf,L as ctx,Us as errorHandler,X as getDialect,Ws as header,Qs as ipFilter,ti as json,ai as jwtAuth,oi as jwtRefresh,ri as keys,li as logger,di as loggerFN,Re as mariadbDialect,yi as multipart,Ee as mysqlDialect,we as postgresDialect,$i as rateLimit,ge as route,Ii as sanitize,qi as security,l as sendError,Fi as session,Ts as smartCache,Se as sqliteDialect,Bi as staticFiles,G as subManager,Ct as t,Vi as timeout,na as urlencoded,Et as use,Ci as validateForm,xi as validateQuery,Xi as validateUrl,Be as wss,Wt as z};
|
|
75
|
+
);`}columnDefinitions(e=this.dialect){return Object.fromEntries(this.entries().map(([t,r])=>[t,e.buildColumnType(r)]))}get columns(){return new Proxy({},{get:(e,t)=>typeof t==="string"?t:void 0})}}function h(e,t={}){return function(r,n={}){let{id:s,...i}=t,a={...i,...n,code:n.code??t.code??400,message:n.message??t.message??"Request Failed",headers:{...t.headers,...n.headers}};if(n.redirect!==void 0||t.redirect!==void 0)a.redirect=n.redirect??t.redirect;let o=async(c,u)=>e(c,u,r,a);if(s)o._middlewareId=s,o.id=s;return o}}var ki=h(async(e,t,r,n)=>{let i=e.req.headers.get("Authorization")?.trim()?.match(/^Bearer\s+(\S+)$/i);if(!i||!await r(e,i[1]))return d(n);return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),Pi=h(async(e,t,r,n)=>{let s=e.req.headers.get("x-api-key");if(!s)return d({code:401,message:"Missing api key"});if(!await r(e,s))return d({code:401,message:"Invalid API Key."});return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),Li=h(async(e,t,r,n)=>{for(let[s,i]of Object.entries(r)){let a=e.req.headers.get(s);if(!a)return d({code:401,message:`Missing ${s} header.`});if(!await i(e,a))return d({code:401,message:"Invalid."})}return await t()},{id:"auth-guard",code:401,message:"Unauthorized Access"}),qi=h(async(e,t,r,n)=>{if(!r||!await r(e))return d(n);return t()},{id:"authorize-guard",code:403,message:"Forbidden"});var P=new Map,Ar=1000,Nr=new Set(["no-cache","no-store"]),Mr=new Set(["private","no-store","no-cache"]),Dr=/(?:^|,)\s*(?:max-age|s-maxage)\s*=\s*["']?0(?:\s|,|$)/i;function xt(e,t){return e?.split(",").some((r)=>t.has(r.trim().split("=",1)[0].toLowerCase()))??!1}function _r(e){let t=e.req.headers;if(t.has("authorization")||t.has("cookie")||t.has("range"))return!0;return xt(t.get("cache-control"),Nr)||t.get("pragma")?.toLowerCase().includes("no-cache")===!0}function Ir(e){let t=e.headers.get("cache-control")??"";return e.status===200&&!e.headers.has("set-cookie")&&!e.headers.has("content-range")&&!e.headers.has("vary")&&!xt(t,Mr)&&!Dr.test(t)}var Ui=h(async(e,t,r)=>{if(e.req.method!=="GET"||_r(e))return await t();let n=r?.ttlMs;if(!Number.isFinite(n)||n<=0)return await t();let s=Date.now();for(let[l,m]of P)if(m.expires<=s)P.delete(l);let i=e.req.url.href,a=P.get(i);if(a)return new Response(a.body.slice(),{status:a.status,statusText:a.statusText,headers:new Headers(a.headers)});let o=await t();if(!Ir(o))return o;let c=o.clone(),u=new Uint8Array(await c.arrayBuffer());if(P.size>=Ar){let l=P.keys().next().value;if(l!==void 0)P.delete(l)}return P.set(i,{expires:s+n,body:u,headers:new Headers(c.headers),status:c.status,statusText:c.statusText}),o});var Ki=h(async(e,t,r,n)=>{if(!r)return t();let s=e.req.header("content-type")??null,i=s?s.split(";")[0].trim().toLowerCase():null,a=!1;if(typeof r==="function")a=r(i,e);else{let o=Array.isArray(r)?r.map(Ct):[Ct(r)];a=i!==null&&o.includes(i)}if(!a)return d(n);return t()},{id:"content-type",code:415,message:"Unsupported Media Type. The request Content-Type is invalid or missing."});function Ct(e){return e.split(";")[0].trim().toLowerCase()}var Vi=h(async(e,t,r,n)=>{if(!e.req.cookies.has(r))return d(n);return await t()},{id:"cookie-checker",code:401,message:"Required cookie is missing."});function Be(e){if(!e)return;return Array.isArray(e)?e.join(", "):e}var Zi=h(async(e,t,r,n)=>{let{origin:s="*",allowHeaders:i="*",methods:a,exposeHeaders:o,credentials:c=!1,maxAge:u=86400}=r||{},l=e.req?.headers?.get("origin")||null,m=null;if(typeof s==="function"){let p=s(l,e);m=typeof p==="string"?p:p?l:null}else if(Array.isArray(s)){if(l&&s.some((p)=>p===l))m=l}else if(s==="*")m=c?l:"*";else if(l===s)m=l;if(l&&!m)return d(n);let f={};if(m)f["Access-Control-Allow-Origin"]=m;if(c)f["Access-Control-Allow-Credentials"]="true";if(o){let p=Be(o);if(p)f["Access-Control-Expose-Headers"]=p}if(i){let p=Be(i);if(p)f["Access-Control-Allow-Headers"]=p}if(a){let p=Be(a);if(p)f["Access-Control-Allow-Methods"]=p}if(u!==void 0)f["Access-Control-Max-Age"]=u.toString();if(m&&m!=="*")f.Vary="Origin";return e.res.header(f),await t()},{code:403,message:"CORS Origin Not Allowed",id:"cors-guard"});var na=h(async(e,t,r,n)=>{if(["POST","PUT","DELETE","PATCH"].includes(e.req.method)){let s=r?.headerName||"x-csrf-token",i=e.req.headers.get(s),a=e.req.cookies.get("csrf_token")||"";if(!i||!a||i!==a)return d(n)}return await t()},{id:"csrf-guard",code:403,message:"CSRF Token Validation Failed"});var oa=h(async(e,t,r,n)=>{let{when:s,...i}=r??{};if(s&&!await s(e))return await t();let a=Object.fromEntries(Object.entries(i).filter(([,o])=>o!==void 0));return d({...n,...a})},{id:"deny",code:403,message:"Forbidden"});var la=h(async(e,t,r)=>{try{return await t()}catch(n){if(r?.logErrors)console.error(n);if(r?.onError)return await r.onError(n,e);return e.res.error(500,r?.message??"Internal Server Error")}},{id:"error-handler"});var pa=h(async(e,t,r,n)=>{let s=(i)=>e.req.headers.get(i);if(r){let i=null;if(Array.isArray(r))i=r;else if(typeof r==="string")i=[r];if(i){for(let a of i)if(!s(a))return d({code:401,message:`Missing required ${a} property.`})}else for(let[a,o]of Object.entries(r)){let c=s(a);if(!c)return d({code:401,message:`Missing required ${a} property.`});if(!o(e,a,c))return d(n)}}return await t()},{code:400,message:"Required headers are missing or invalid."});var pe=(e)=>{let t=e.req.server;if(t)return t.requestIP(e.req.request)?.address??"";return e.req.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||"127.0.0.1"};function Y(e){let t=e.split(".");if(t.length!==4)return null;let r=[];for(let n of t){if(!/^(0|[1-9]\d{0,2})$/.test(n))return null;let s=Number(n);if(s>255)return null;r.push(s)}return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0}function he(e){let t=e.trim();if(t.startsWith("[")&&t.endsWith("]"))t=t.slice(1,-1);let r=t.indexOf("%");if(r!==-1)t=t.slice(0,r);if(!t.includes(":"))return null;let n=t.lastIndexOf(":"),s=t.slice(n+1);if(s.includes(".")){let u=Y(s);if(u===null)return null;let l=(u>>>16).toString(16),m=(u&65535).toString(16);t=`${t.slice(0,n+1)}${l}:${m}`}let i=(u)=>{if(u==="")return[];let l=[];for(let m of u.split(":")){if(!/^[0-9a-fA-F]{1,4}$/.test(m))return null;l.push(parseInt(m,16))}return l},a=t.split("::");if(a.length>2)return null;let o;if(a.length===2){let u=i(a[0]??""),l=i(a[1]??"");if(!u||!l)return null;let m=8-u.length-l.length;if(m<1)return null;o=[...u,...Array(m).fill(0),...l]}else{let u=i(t);if(!u)return null;o=u}if(o.length!==8)return null;let c=new Uint8Array(16);return o.forEach((u,l)=>{c[l*2]=u>>>8&255,c[l*2+1]=u&255}),c}function Ot(e){let t=e.trim();if(t.startsWith("[")&&t.endsWith("]"))t=t.slice(1,-1);let r=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(t);if(r&&Y(r[1])!==null)return r[1];return t}function $r(e,t){return e.every((r,n)=>r===t[n])}function kr(e,t,r){let n=Math.floor(r/8);for(let a=0;a<n;a++)if(e[a]!==t[a])return!1;let s=r%8;if(s===0)return!0;let i=255<<8-s&255;return(e[n]&i)===(t[n]&i)}class ge{rules=[];constructor(e){this.compileRules(e)}test(e){let t=Ot(e.split(",")[0]?.trim()??""),r=Y(t);return this.rules.some((n)=>n(t,r))}compileRules(e){for(let t of e){let r=Ot(t),n=r.lastIndexOf("/");if(n!==-1)this.rules.push(this.compileCidr(r,n));else if(r.includes("*"))this.rules.push(this.compileWildcard(r));else{let s=Y(r);if(s!==null){this.rules.push((a,o)=>o===s);continue}let i=he(r);if(i===null)throw RangeError(`Invalid IP rule: ${t}`);this.rules.push((a)=>{let o=he(a);return o!==null&&$r(o,i)})}}}compileCidr(e,t){let r=e.slice(0,t),n=e.slice(t+1),s=Y(r);if(s!==null){if(!/^(0|[1-9]\d?)$/.test(n))throw RangeError(`Invalid CIDR rule: ${e}`);let o=Number(n);if(o>32)throw RangeError(`Invalid CIDR rule: ${e}`);let c=o===0?0:4294967295<<32-o>>>0,u=(s&c)>>>0;return(l,m)=>m!==null&&(m&c)>>>0===u}let i=he(r);if(i===null)throw RangeError(`Invalid CIDR rule: ${e}`);if(!/^(0|[1-9]\d{0,2})$/.test(n))throw RangeError(`Invalid CIDR rule: ${e}`);let a=Number(n);if(a>128)throw RangeError(`Invalid CIDR rule: ${e}`);return(o)=>{let c=he(o);return c!==null&&kr(c,i,a)}}compileWildcard(e){let t=e.split(".");if(t.length!==4||t.some((r)=>r!=="*"&&Y(`0.0.0.${r}`)===null))throw RangeError(`Invalid IPv4 wildcard rule: ${e}`);return(r,n)=>n!==null&&r.split(".").every((s,i)=>{let a=t[i];return a==="*"||s===a})}}var Ra=h(async(e,t,r,n)=>{let s=pe(e),{blacklist:i=[],whitelist:a=[]}=r??{};if(i.length){if(new ge(i).test(s))return d(n)}if(a.length){if(!new ge(a).test(s))return d(n)}return await t()},{id:"ip-filter",code:403,message:"Forbidden"});var Pr=["POST","PUT","PATCH"],Lr=1048576,Oa=h(async(e,t,r,n)=>{if(!Pr.includes(e.req.method.toUpperCase()))return await t();if(e.req.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()!=="application/json")return d({code:415,message:"Content-Type must be application/json"});let i=n.maxSize,a=typeof i==="number"&&i>0?i:Lr,o=e.req.headers.get("content-length");if(o!==null){if(!/^\d+$/.test(o))return d({code:400,message:"Invalid Content-Length header"});let m=Number(o);if(!Number.isSafeInteger(m)||m<0)return d({code:400,message:"Invalid Content-Length header"});if(m>a)return d({code:413,message:`Payload exceeded maximum allowed size of ${a/1024} KB`})}let c="";try{c=await e.req.text()}catch{return d({code:400,message:"Failed to read request stream"})}if(new TextEncoder().encode(c).byteLength>a)return d({code:413,message:`Payload exceeded maximum allowed size of ${a/1024} KB`});if(!c||c.trim().length===0)return d({code:400,message:"Request body cannot be empty"});let u;try{u=JSON.parse(c)}catch(m){return d({code:400,message:`Invalid JSON syntax: ${m.message}`})}if(typeof u!=="object"||u===null)return d({code:400,message:"JSON payload must be a valid JSON object or array"});let l=r.safeParse(u);if(!l.success)return d({...n,message:`Validation failed: ${l.error.issues.map((m)=>m.message).join(", ")}`});return e.req._json=l.data,e.body=l.data,await t()},{id:"json-validator",code:400}),va=h(async(e,t,r)=>{let n=await e.req.json();if(!n||typeof n!=="object"||Array.isArray(n))return d({code:400,message:"JSON body must be an object"});let s=r.filter((i)=>!Object.hasOwn(n,i));if(s.length>0)return d({code:400,message:`Missing required fields: ${s.join(", ")}`});return e.body=n,await t()},{id:"require-keys",code:400});function ye(e){return{...e??{},"WWW-Authenticate":"Bearer"}}function Ke(e){if(!e)return null;return e.trim().match(/^Bearer\s+(\S+)$/i)?.[1]??null}function vt(e){return d({code:401,message:"Unauthorized Access",headers:ye(e)})}async function be(e,t){let r=d({...e,headers:ye(e.headers)});if(r.status===302)return r;let n=new Headers(r.headers),s;try{s=await r.json()}catch{s={success:!1,error:e.message??"Refresh Token Failed"}}return s.error_code=t,new Response(JSON.stringify(s),{status:r.status,headers:n})}async function At(e,t){let r=e;if(typeof r.consumeWithReason==="function")return r.consumeWithReason(t);let n=await e.consume(t);return n?{ok:!0,claims:n}:{ok:!1,reason:"invalid"}}var Da=h(async(e,t,r,n)=>{if(!r)throw Error("jwtAuth requires a JWTAuthService instance.");let s=e.req.headers.get("Authorization"),i=Ke(s);if(!i)return d({...n,headers:ye(n.headers)});let a=r.verify(i);if(!a)return d({...n,headers:ye(n.headers)});return e.jwtData=a,await t()},{id:"jwt-auth-guard",code:401,message:"Unauthorized Access"}),_a=h(async(e,t,r,n)=>{if(!r)throw Error("jwtRefresh requires a JWTAuthService instance.");let s=e.req.headers.get("Authorization");if(s!==null){let c=Ke(s);if(!c||!r.verify(c))return vt(n.headers)}let i=e.req.headers.get("x-refresh-token")?.trim();if(!i||/\s/.test(i))return await be(n,"invalid");let a=await At(r,i);if(!a.ok)return await be(n,a.reason);let o=a.claims;if(e.data.jwtRefreshData=o,Object.keys(e.jwtData).length===0)e.jwtData=o;return e.data.jwtTokens=await r.issue(o),await t()},{id:"jwt-refresh-guard",code:401,message:"Refresh Token Failed"}),Ia=h(async(e,t,r,n)=>{if(!r)throw Error("jwtRotate requires a JWTAuthService instance.");let s=e.req.headers.get("Authorization"),i=null;if(s!==null){let u=Ke(s);if(i=u?r.verify(u):null,!i)return vt(n.headers)}let a=e.req.headers.get("x-refresh-token")?.trim();if(!a||/\s/.test(a))return await be(n,"invalid");let o=await At(r,a);if(!o.ok)return await be(n,o.reason);let c=o.claims;if(e.data.jwtRefreshData=c,i)e.jwtData=i;else if(Object.keys(e.jwtData).length===0)e.jwtData=c;return e.data.jwtTokens=await r.issue(c),await t()},{id:"jwt-rotate-guard",code:401,message:"Refresh Token Failed"});var Pa=h(async(e,t,r="",n)=>{let s=e.req.method,i=new URL(e.req.url).pathname,a=new Date().toLocaleString();return console.log(`${s} ${i} @ ${a}${r?` | ${r}`:""}`),await t()}),La=h(async(e,t,r,n)=>{let s=e.req.method,i=new URL(e.req.url).pathname,a=new Date().toLocaleTimeString(),o=await t(),c=r({ctx:e,res:o,timestamp:a,method:s,url:i});if(c)console.log(c);return o});function L(e){let t=Object.create(null);for(let[r,n]of e.entries()){if(!Object.prototype.hasOwnProperty.call(t,r)){t[r]=n;continue}let s=t[r];t[r]=Array.isArray(s)?[...s,n]:[s,n]}return t}function qr(e){let t=/boundary=(?:"([^"]+)"|([^;]+))/i.exec(e);return(t?.[1]??t?.[2])?.trim()||void 0}function jr(e,t){let r=qr(e);if(!r||t.byteLength===0)return[];let s=new TextDecoder("latin1").decode(t).split(`--${r}`),i=[];for(let a=1;a<s.length;a+=1){let o=s[a];if(o.startsWith("--"))break;if(o.startsWith(`\r
|
|
76
|
+
`))o=o.slice(2);else if(o.startsWith(`
|
|
77
|
+
`))o=o.slice(1);let c=/\r?\n\r?\n/.exec(o);if(!c)continue;let u=o.slice(0,c.index),l=/content-disposition:[^\r\n]*/i.exec(u)?.[0]??"",m=/\bname="([^"]*)"/i.exec(l)?.[1];if(m===void 0)continue;let f=/\bfilename\*?=/i.test(l),p=/^content-type:[ \t]*([^\r\n]+)$/im.exec(u)?.[1]?.trim();i.push({name:m,isFile:f,...p?{type:p}:{}})}return i}function Nt(e,t,r){let n=jr(t,r);if(n.length===0)return e;let s=new FormData,i=0;for(let[a,o]of e.entries()){while(i<n.length&&n[i].name!==a)i+=1;let c=n[i];if(c)i+=1;let u=o;if(u instanceof File&&c?.isFile&&c.type){s.append(a,new File([u],u.name,{type:c.type,lastModified:u.lastModified}));continue}s.append(a,o)}return s}var Wa=h(async(e,t)=>{let r=e.req.headers.get("content-type")??"";if(!r.toLowerCase().startsWith("multipart/form-data"))return t();try{let n=new Uint8Array(await e.req.request.arrayBuffer()),s=await new Response(n,{headers:{"content-type":r}}).formData(),i=Nt(s,r,n);e.req._formData=i,e.form=L(i)}catch{return d({code:400,message:"Invalid multipart form data"})}return t()},{id:"multipart-parser",code:400,message:"Invalid multipart form data"});var Ja=h(async(e,t,r,n)=>{let s=r;if(typeof s?.safeParse!=="function")return d({code:500,message:"Framework Error: Missing schema in validateQuery guard."});let i;try{i=typeof e.req.url==="string"?new URL(e.req.url,"http://localhost"):e.req.url}catch{return d({code:n.code??400,message:"Malformed URL structure."})}let a=Object.create(null);i.searchParams.forEach((c,u)=>{a[u]=c});let o=s.safeParse(a);if(!o.success)return d({code:n.code??400,message:`Query Validation Error: ${o.error.issues.map((c)=>c.message).join("; ")}`});return e.query=o.data,await t()},{id:"query-validator",code:400,message:"Query validation failed"}),Va=h(async(e,t,r,n)=>{let s=r;if(typeof s?.safeParse!=="function")return d({code:500,message:"Framework Error: Missing schema in validateForm guard."});let i;try{let o=await e.req.form();i=L(o)}catch{return d({code:n.code??400,message:"Invalid or malformed form payload."})}let a=s.safeParse(i);if(!a.success)return d({code:n.code??400,message:`Form Validation Error: ${a.error.issues.map((o)=>o.message).join("; ")}`});return e.form=a.data,await t()},{id:"form-validator",code:400,message:"Form validation failed"});var q=new Map;var Mt=0;function Fr(e=Date.now()){for(let[t,r]of q)if(r.reset<=e)q.delete(t);Mt=e+60000}function Dt(e,t,r){let n=Date.now();if(n>=Mt)Fr(n);let s=q.get(e);if(!s||s.reset<n){let i=n+r;if(!s&&q.size>=1e5){let a=q.keys().next().value;if(a!==void 0)q.delete(a)}return q.set(e,{count:1,reset:i}),{allowed:!0,remaining:Math.max(0,t-1),resetTime:i}}if(s.count>=t)return{allowed:!1,remaining:0,resetTime:s.reset};return s.count+=1,{allowed:!0,remaining:Math.max(0,t-s.count),resetTime:s.reset}}var ro=h(async(e,t,r,n)=>{let{max:s=100,windowMs:i=60000,expose:a=!0}=r||{},o=pe(e),c=e.req.method,u=`rate_${o}_${c}_${new URL(e.req.url).pathname}`,{allowed:l,remaining:m,resetTime:f}=Dt(u,s,i),p={};if(a)p["X-RateLimit-Limit"]=s.toString(),p["X-RateLimit-Remaining"]=m.toString(),p["X-RateLimit-Reset"]=Math.ceil(f/1000).toString();if(!l){if(a){let x=Math.max(1,Math.ceil((f-Date.now())/1000));p["Retry-After"]=x.toString()}return d({...n,headers:p})}let T=await t();if(a)Object.entries(p).forEach(([x,U])=>{T.headers.set(x,U)});return T},{id:"rate-limiter",code:429,message:"Too Many Requests"});function Ur(e){return e.replace(/[&<>"']/g,(t)=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}function j(e,t,r=new WeakMap){if(typeof e==="string")return t(e);if(Array.isArray(e)){if(r.has(e))return r.get(e);let s=[];r.set(e,s);for(let i of e)s.push(j(i,t,r));return s}if(e===null||typeof e!=="object"||e instanceof Blob)return e;if(r.has(e))return r.get(e);let n=Object.create(null);r.set(e,n);for(let[s,i]of Object.entries(e))n[s]=j(i,t,r);return n}var io=h(async(e,t,r)=>{let n=r?.sanitizeString??Ur;if(r?.query!==!1)e.query=j(e.query,n);if(r?.form!==!1)e.form=j(e.form,n);if(r?.body!==!1){let s=e.req._json;if(e.body!==void 0&&e.body===s){let i=j(e.body,n);e.body=i,e.req._json=i}else{if(e.body!==void 0)e.body=j(e.body,n);if(s!==void 0)e.req._json=j(s,n)}}return t()},{id:"sanitize-guard"});function Hr(e,t){let r={"Content-Security-Policy":t.contentSecurityPolicy,"Cross-Origin-Embedder-Policy":t.crossOriginEmbedderPolicy,"Cross-Origin-Opener-Policy":t.crossOriginOpenerPolicy,"Cross-Origin-Resource-Policy":t.crossOriginResourcePolicy,"Strict-Transport-Security":t.hsts,"Permissions-Policy":t.permissionsPolicy,"Referrer-Policy":t.referrerPolicy??"strict-origin-when-cross-origin","X-Content-Type-Options":t.xContentTypeOptions??"nosniff","X-Frame-Options":t.xFrameOptions??"DENY"},n=new Headers(e.headers);for(let[s,i]of Object.entries(r))if(i===!1)n.delete(s);else if(i)n.set(s,i);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}var co=h(async(e,t,r)=>{let n=await t();return Hr(n,r??{})},{id:"security-headers"});function Wr(e){return typeof e==="object"&&e!==null&&"auth"in e&&Boolean(e.auth)}var Br=h(async(e,t,r,n)=>{let{auth:s,readonly:i}=r,[a,o]=await s.loadHeader(e.req.request,i);e.session=o;let c=o,u=await t();if(c.isReadOnly)return u;let l=c.length===0&&(c.isNew?Boolean(a):c.isModified),m=!l&&c.length>0&&c.isModified;if(!l&&!m)return u;if(m&&typeof s.buildCookieString==="function")try{s.buildCookieString(c)}catch(f){return console.error("[session] Refusing to persist a session whose cookie cannot be serialized:",f),d(n)}try{if(l)await s.deleteSession(c,u.headers);else await s.saveSession(c,u.headers)}catch(f){if(m&&!c.isFound)try{await s.deleteSession(c,new Headers)}catch{}return console.error("[session] Failed to persist the request session:",f),d(n)}return u},{id:"session-manager",code:500,message:"Internal Server Error"});function fo(e,t={}){let r=Wr(e)?{auth:e.auth,readonly:e.readonly??!1}:{auth:e,readonly:!1};return Br(r,t)}var po=h(async(e,t,r,n)=>{let s=e.session;if(!s||!s.isFound||s.isNew)return d(n);if(r&&!await r(s))return d(n);return await t()},{id:"require-session",code:401,message:"Authentication required"});var _t=new WeakMap;function Kr(e){let t=e.root?.trim(),r=e.extensions?.filter((s)=>s.trim())??[];if(!t&&r.length===0)return;let n=_t.get(e);if(!n){let s=t?new te(t,r):void 0,i=new Set(r);n={server:s,isFile:s?(a)=>s.isFile(a):(a)=>ee(a,i)},_t.set(e,n)}return n}function zr(e){if(!e)return;let t=e.trim().replace(/\/+$/,"");if(!t)return;if(!t.startsWith("/"))t=`/${t}`;return t}function Gr(e,t){return e===t||e.startsWith(`${t}/`)}var bo=h(async(e,t,r)=>{if(!["GET","HEAD"].includes(e.req.method))return t();let n=r??{},s=zr(n.prefix),i=e.req.path;if(s){let l;try{l=decodeURIComponent(i)}catch{return t()}if(!Gr(l,s))return t();i=l}let a=Kr(n);if(!(e.req.isFile||(a?a.isFile(i):!1)))return t();let c=s&&a?.server?i.slice(s.length)||"/":void 0,u=a?.server?await a.server.serve(e.req,e.res,c):await e.res.fileServer();if(e.req.method!=="HEAD")return u;return new Response(null,{status:u.status,statusText:u.statusText,headers:u.headers})},{id:"static-files"});var Ro=h(async(e,t,r,n)=>{let s,i=new Promise((a)=>{s=setTimeout(()=>a(d(n)),r)});try{return await Promise.race([t(),i])}finally{if(s)clearTimeout(s)}},{id:"timeout-guard",code:408,message:"Request Timeout"});var Jr=2048,Vr=1024;function It(e){let t=e,r="";while(t!==r&&t.includes("%"))r=t,t=decodeURIComponent(t);return t}function $t(e){return e.includes("../")||e.includes("..\\")||e.includes("/..")}var Oo=h(async(e,t,r,n)=>{let s=typeof r==="number"?{maxUrlLength:r}:r||{},i=s.maxUrlLength??Jr,a=s.maxQueryLength??Vr,o;try{o=typeof e.req.url==="string"?new URL(e.req.url,"http://localhost"):e.req.url}catch{return d({code:400,message:"Malformed URL structure."})}if(o.href.length>i)return d({code:414,message:`URI Too Long. Exceeds limit of ${i} characters.`});if((o.search.startsWith("?")?o.search.slice(1):o.search).length>a)return d({code:414,message:`Query string too long. Exceeds limit of ${a} characters.`});if(s.sanitizePaths!==!1){let f,p;try{f=It(o.pathname),p=It(o.search)}catch{return d({code:400,message:"Malformed percent-encoding in URL."})}if(f.includes("\x00")||p.includes("\x00"))return d({code:400,message:"Null byte injection detected in URL."});if($t(f)||$t(p))return d({code:400,message:"Path traversal attempt detected in URL."})}let l=o.searchParams,m=Array.from(l.keys());if(m.length>0){if(s.noDuplicates){if(new Set(m).size!==m.length)return d({code:n.code??400,message:"Duplicate query parameters are not allowed."})}if(s.allowedKeys){let f=new Set(s.allowedKeys);for(let p of m)if(!f.has(p))return d({code:n.code??400,message:`Unauthorized query parameter: '${p}'`})}if(s.disallowedKeys){let f=new Set(s.disallowedKeys);for(let p of m)if(f.has(p))return d({code:n.code??400,message:`Forbidden query parameter: '${p}'`})}if(s.patterns)for(let[f,p]of Object.entries(s.patterns)){let T=l.getAll(f);for(let x of T){p.lastIndex=0;let U=p.test(x);if(p.lastIndex=0,!U)return d({code:n.code??400,message:`Invalid format for query parameter '${f}'.`})}}}return await t()},{id:"url-validator",code:400,message:"URL validation failed"});var Yr=/%(?![0-9A-Fa-f]{2})/,Do=h(async(e,t,r,n)=>{if(!(e.req.headers.get("content-type")?.toLowerCase()??"").startsWith("application/x-www-form-urlencoded"))return t();if(r?.strict){let i=await e.req.text();if(Yr.test(i)||i.includes("\x00"))return d(n);let a=new FormData;for(let[o,c]of new URLSearchParams(i)){if(o.includes("\x00")||c.includes("\x00"))return d(n);a.append(o,c)}return e.req._formData=a,e.form=L(a),t()}try{let i=await e.req.request.formData();e.req._formData=i,e.form=L(i)}catch{return d({code:400,message:"Invalid URL-encoded form data"})}return t()},{id:"urlencoded-parser",code:400,message:"Invalid URL-encoded form data"});class ze extends Error{issues;constructor(e){super(e.map((t)=>t.message).join(", "));this.name="SchemaError",this.issues=e}}function Qr(){return{optional:!1,nullable:!1,hasDefault:!1,defaultValue:void 0}}function w(e){if(e.length===0)return"value";let t="";for(let r of e)if(typeof r==="number")t+=`[${r}]`;else t+=t===""?r:`.${r}`;return`'${t}'`}class _{"~standard";_state;constructor(e=Qr()){this._state=e,this["~standard"]={version:1,vendor:"rossa",validate:(t)=>{let r=this.safeParse(t);if(r.success)return{value:r.data};return{issues:r.error.issues.map((n)=>({message:n.message,path:n.path}))}},jsonSchema:{input:(t)=>this.toJSONSchema(t),output:(t)=>this.toJSONSchema(t)}}}toJSONSchema(e={target:"draft-2020-12"}){return this._jsonSchema(e)}_isRequired(){return!this._state.optional&&!this._state.hasDefault}optional(){let e=this._clone();return e._state.optional=!0,e}nullable(){let e=this._clone();return e._state.nullable=!0,e}default(e){let t=this._clone();return t._state.hasDefault=!0,t._state.defaultValue=e,t}_run(e,t,r){if(e===void 0){if(this._state.hasDefault)return this._state.defaultValue;if(this._state.optional)return;r.push({path:[...t],message:`${w(t)} is required`});return}if(e===null){if(this._state.nullable)return null;r.push({path:[...t],message:`${w(t)} must not be null`});return}return this._validate(e,t,r)}safeParse(e){let t=[],r=this._run(e,[],t);if(t.length>0)return{success:!1,error:new ze(t)};return{success:!0,data:r}}parse(e){let t=this.safeParse(e);if(!t.success)throw t.error;return t.data}}function ie(e,t){let r=e;if(t.nullable)r={anyOf:[r,{type:"null"}]};if(t.hasDefault)r={...r,default:t.defaultValue};return r}function kt(e,t){let r,n,s=!1;for(let a of e)if(a.kind==="min"&&a.value!==void 0)r=r===void 0?a.value:Math.max(r,a.value);else if(a.kind==="max"&&a.value!==void 0)n=n===void 0?a.value:Math.min(n,a.value);else if(a.kind==="email")s=!0;let i={type:"string"};if(r!==void 0)i.minLength=r;if(n!==void 0)i.maxLength=n;if(s)i.format="email";return ie(i,t)}function Pt(e,t){let r,n,s=!1;for(let a of e)if(a.kind==="min"&&a.value!==void 0)r=r===void 0?a.value:Math.max(r,a.value);else if(a.kind==="max"&&a.value!==void 0)n=n===void 0?a.value:Math.min(n,a.value);else if(a.kind==="int")s=!0;let i={type:s?"integer":"number"};if(r!==void 0)i.minimum=r;if(n!==void 0)i.maximum=n;return ie(i,t)}function Lt(e){return ie({type:"boolean"},e)}function qt(e,t,r){let n,s;for(let a of t)if(a.kind==="min"&&a.value!==void 0)n=n===void 0?a.value:Math.max(n,a.value);else if(a.kind==="max"&&a.value!==void 0)s=s===void 0?a.value:Math.min(s,a.value);let i={type:"array",items:e};if(n!==void 0)i.minItems=n;if(s!==void 0)i.maxItems=s;return ie(i,r)}function jt(e,t,r){let n={type:"object"};if(Object.keys(e).length>0){if(n.properties=e,t.length>0)n.required=[...t]}return n.additionalProperties=!1,ie(n,r)}class Q extends _{_rules;_coerce;constructor(e={}){super(e.state);this._rules=e.rules?[...e.rules]:[],this._coerce=e.coerce??!1}_clone(){return new Q({coerce:this._coerce,rules:this._rules,state:{...this._state}})}min(e){return this._withRule({kind:"min",value:e})}max(e){return this._withRule({kind:"max",value:e})}email(){return this._withRule({kind:"email"})}trim(){return this._withRule({kind:"trim"})}_withRule(e){let t=this._clone();return t._rules.push(e),t}_jsonSchema(e){return kt(this._rules,this._state)}_validate(e,t,r){let n=e;if(this._coerce&&typeof n!=="string"){if(typeof n==="number"||typeof n==="boolean"||typeof n==="bigint")n=String(n)}if(typeof n!=="string"){r.push({path:[...t],message:`${w(t)} must be a string`});return}let s=this._rules.some((i)=>i.kind==="trim")?n.trim():n;for(let i of this._rules){if(i.kind==="min"&&s.length<i.value)r.push({path:[...t],message:`${w(t)} must have at least ${i.value} characters`});if(i.kind==="max"&&s.length>i.value)r.push({path:[...t],message:`${w(t)} must have at most ${i.value} characters`});if(i.kind==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))r.push({path:[...t],message:`${w(t)} must be a valid email`})}return s}}class X extends _{_rules;_coerce;constructor(e={}){super(e.state);this._rules=e.rules?[...e.rules]:[],this._coerce=e.coerce??!1}_clone(){return new X({coerce:this._coerce,rules:this._rules,state:{...this._state}})}min(e){return this._withRule({kind:"min",value:e})}max(e){return this._withRule({kind:"max",value:e})}int(){return this._withRule({kind:"int"})}_withRule(e){let t=this._clone();return t._rules.push(e),t}_jsonSchema(e){return Pt(this._rules,this._state)}_validate(e,t,r){let n=e;if(this._coerce&&typeof n==="string"){let s=n.trim(),i=s===""?Number.NaN:Number(s);if(!Number.isFinite(i)){r.push({path:[...t],message:`${w(t)} must be a number`});return}n=i}if(typeof n!=="number"||!Number.isFinite(n)){r.push({path:[...t],message:`${w(t)} must be a number`});return}for(let s of this._rules){if(s.kind==="min"&&n<s.value)r.push({path:[...t],message:`${w(t)} must be at least ${s.value}`});if(s.kind==="max"&&n>s.value)r.push({path:[...t],message:`${w(t)} must be at most ${s.value}`});if(s.kind==="int"&&!Number.isInteger(n))r.push({path:[...t],message:`${w(t)} must be an integer`})}return n}}class Z extends _{_coerce;constructor(e={}){super(e.state);this._coerce=e.coerce??!1}_clone(){return new Z({coerce:this._coerce,state:{...this._state}})}_jsonSchema(e){return Lt(this._state)}_validate(e,t,r){let n=e;if(this._coerce&&typeof n==="string"){let s=n.toLowerCase();if(s==="true"||s==="1")n=!0;else if(s==="false"||s==="0")n=!1;else{r.push({path:[...t],message:`${w(t)} must be a boolean`});return}}if(typeof n!=="boolean"){r.push({path:[...t],message:`${w(t)} must be a boolean`});return}return n}}class ae extends _{_item;_rules;constructor(e,t={}){super(t.state);this._item=e,this._rules=t.rules?[...t.rules]:[]}_clone(){return new ae(this._item,{rules:this._rules,state:{...this._state}})}min(e){return this._withRule({kind:"min",value:e})}max(e){return this._withRule({kind:"max",value:e})}_withRule(e){let t=this._clone();return t._rules.push(e),t}_jsonSchema(e){return qt(this._item.toJSONSchema(e),this._rules,this._state)}_validate(e,t,r){if(!Array.isArray(e)){r.push({path:[...t],message:`${w(t)} must be an array`});return}for(let n of this._rules){if(n.kind==="min"&&e.length<n.value)r.push({path:[...t],message:`${w(t)} must have at least ${n.value} items`});if(n.kind==="max"&&e.length>n.value)r.push({path:[...t],message:`${w(t)} must have at most ${n.value} items`})}return e.map((n,s)=>this._item._run(n,[...t,s],r))}}class oe extends _{shape;constructor(e,t={}){super(t.state);this.shape=e}_clone(){return new oe(this.shape,{state:{...this._state}})}_jsonSchema(e){let t={},r=[];for(let n of Object.keys(this.shape)){let s=this.shape[n];if(!s)continue;if(t[n]=s.toJSONSchema(e),s._isRequired())r.push(n)}return jt(t,r,this._state)}_validate(e,t,r){if(typeof e!=="object"||e===null||Array.isArray(e)){r.push({path:[...t],message:`${w(t)} must be an object`});return}let n=e,s={};for(let i of Object.keys(this.shape)){let a=this.shape[i];if(!a)continue;let o=Object.hasOwn(n,i),c=a._run(o?n[i]:void 0,[...t,i],r);if(!o&&c===void 0)continue;s[i]=c}return s}}var Xr=()=>new Q,Zr=()=>new X,en=()=>new Z,tn=(e)=>new ae(e),rn=(e)=>new oe(e),nn={string:()=>new Q({coerce:!0}),number:()=>new X({coerce:!0}),boolean:()=>new Z({coerce:!0})};import{createHmac as Ut,randomUUID as sn,timingSafeEqual as an}from"crypto";class Se{secretKey;constructor(e){if(!e)throw Error("JWT secret key must be provided.");this.secretKey=Buffer.from(e,"utf8")}sign(e,t=15){if(!Number.isFinite(t)||t<=0)throw RangeError("Token validity must be a positive number of minutes.");return this.build(e,t*60)}signSeconds(e,t){if(!Number.isFinite(t)||t<=0)throw RangeError("Token lifetime must be a positive number of seconds.");return this.build(e,t)}build(e,t){let r={alg:"HS256",typ:"JWT"},n=Math.floor(Date.now()/1000),s={...e,iat:n,exp:n+t,jti:sn()},i=Buffer.from(JSON.stringify(r)).toString("base64url"),a=Buffer.from(JSON.stringify(s)).toString("base64url"),o=`${i}.${a}`,c=Ut("sha256",this.secretKey).update(o).digest("base64url");return`${o}.${c}`}inspect(e){try{let t=e.split(".");if(t.length!==3)return{ok:!1,reason:"invalid"};let[r,n,s]=t,i=`${r}.${n}`,a=JSON.parse(Buffer.from(r||"","base64url").toString("utf8"));if(!a||typeof a!=="object"||a.alg!=="HS256"||a.typ!=="JWT")return{ok:!1,reason:"invalid"};let o=Ut("sha256",this.secretKey).update(i).digest("base64url"),c=Buffer.from(o),u=Buffer.from(s||"");if(c.length!==u.length||!an(c,u))return{ok:!1,reason:"invalid"};let l=JSON.parse(Buffer.from(n||"","base64url").toString("utf8"));if(!l||typeof l!=="object"||!Number.isFinite(l.iat)||!Number.isFinite(l.exp))return{ok:!1,reason:"invalid"};let m=Math.floor(Date.now()/1000);if(l.exp<=m)return{ok:!1,reason:"expired"};return{ok:!0,payload:l}}catch{return{ok:!1,reason:"invalid"}}}verify(e){let t=this.inspect(e);return t.ok?t.payload:null}issue(e,t=7){return this.signSeconds(e,t*24*60*60)}}class Ht{refreshTokens;config;engine;constructor(e,t,r={}){this.refreshTokens=e;this.engine=new Se(t);let{refreshValidity:n=7,tokenValidity:s=15}=r;if(!Number.isFinite(n)||n<=0)throw RangeError("Refresh token validity must be a positive number of days.");if(!Number.isFinite(s)||s<=0)throw RangeError("Access token validity must be a positive number of minutes.");this.config={refreshValidity:n,tokenValidity:s}}async init(){await this.refreshTokens.initialize?.()}sign(e,t){if(t===void 0)return this.engine.sign(e,this.config.tokenValidity);return this.engine.signSeconds(e,t)}verify(e){return this.engine.verify(e)}async consume(e){let t=await this.consumeWithReason(e);return t.ok?t.claims:null}async consumeWithReason(e){let t=this.engine.inspect(e);if(!t.ok)return{ok:!1,reason:t.reason};if(!await this.refreshTokens.consume(e))return{ok:!1,reason:"reused"};return{ok:!0,claims:t.payload}}async deleteExpired(e=Date.now()){return this.refreshTokens.deleteExpired?.(e)}async issue(e){let t=this.engine.issue(e,this.config.refreshValidity),r=Date.now()+this.config.refreshValidity*24*60*60*1000;return await this.refreshTokens.save(t,r),{accessToken:this.sign(e),refreshToken:t}}}class F{sid;data;isNew;isModified;isReadOnly;isFound;length=0;_rotator;constructor(e="",t={},r=!1,n=!0,s=!1){if(this.sid=e,this.data={...t},this.length=Object.keys(t).length,this.length)n=!1;this.isReadOnly=r,this.isNew=n,this.isModified=!1,this.isFound=s}get session(){return new Proxy(this,{get(e,t){if(t in e)return Reflect.get(e,t);return e.data[t]},set(e,t,r){if(e.isReadOnly)return console.warn("session: readonly"),!0;if(t in e)throw Error(`Cannot overwrite internal session property: ${String(t)}`);if(e.data[t]!==r){if(e.isModified=!0,!(t in e.data))e.length++;e.data[t]=r}return!0},deleteProperty(e,t){if(e.isReadOnly)return console.warn("session: readonly"),!0;if(t in e)return!1;if(t in e.data)e.isModified=!0,delete e.data[t],e.length--;return!0},has(e,t){return t in e||t in e.data},ownKeys(e){return Reflect.ownKeys(e.data)},getOwnPropertyDescriptor(e,t){if(t in e.data)return{enumerable:!0,configurable:!0,value:e.data[t]};return}})}setRotator(e){this._rotator=e}renewSid(e){this.sid=e}async rotate(){if(this.isReadOnly){console.warn("session: readonly");return}if(!this._rotator)throw Error("session: rotate() requires a session service; use session(auth) first.");await this._rotator()}}import{randomBytes as ln}from"crypto";import{createHmac as on,createHash as cn,timingSafeEqual as un}from"crypto";class Ge{salt;key;constructor(e){this.salt=e;this.key=cn("sha256").update(e).digest()}getSignature(e){return on("sha256",this.key).update(e).digest("base64url")}sign(e){let t=this.getSignature(e);return`${e}.${t}`}unsign(e){let t=e.indexOf(".");if(t===-1)return null;let r=e.slice(0,t),n=e.slice(t+1);if(this.verifySignature(r,n))return r;return null}verifySignature(e,t){let r=Buffer.from(this.getSignature(e),"utf8"),n=Buffer.from(t,"utf8");if(r.length!==n.length)return!1;return un(r,n)}}class Je{signer;constructor(e){this.signer=new Ge(e)}generate(e=21){let t=ln(e).toString("base64url");return this.signer.sign(t)}}var Wt=86400000;class Bt extends Je{config;constructor(e,t){super(t??"salty");e.COOKIE_NAME=e.COOKIE_NAME??"session";let{COOKIE_NAME:r="session",COOKIE_LIFETIME:n=31,COOKIE_DOMAIN:s=void 0,COOKIE_PATH:i="/",COOKIE_HTTPONLY:a=!0,COOKIE_SECURE:o=!0,COOKIE_SAMESITE:c="Lax",MAX_COOKIE_SIZE:u=4093,SESSION_LIFETIME:l=31}=e;this.config={COOKIE_NAME:r,COOKIE_LIFETIME:n,COOKIE_DOMAIN:s,COOKIE_PATH:i,COOKIE_HTTPONLY:a,COOKIE_SECURE:o,COOKIE_SAMESITE:c,MAX_COOKIE_SIZE:u,SESSION_LIFETIME:l}}async init(){}async openSession(e,t=!1){if(e&&this.signer.unsign(e))return await this.fetchSession(e,t);return this.new({})}async fetchSession(e,t){try{let r=await this.fetchData(e);if(r){let n=r.data??{};if(this.isNotExpired(new Date(r.expiration)))return this.materialize(new F(e,n,t,!1,!0));return this.new({sid:e,isFound:!0,readonly:t})}}catch(r){console.error(`[AuthEngine] Failed to parse session ${e}:`,r)}return this.new({sid:e,readonly:t})}new({sid:e,isFound:t=!1,readonly:r=!1}){return this.materialize(new F(e??this.generate(),{},r,!0,t))}get readonly(){return this.materialize(new F(this.generate(),{},!0))}materialize(e){return e.setRotator(()=>this.rotateSession(e)),e.session}async rotateSession(e){if(e.isReadOnly){console.warn("session: readonly");return}let t=e.sid;if(t&&e.isFound)await this.removeStoredSession(t);e.renewSid(this.generate()),e.isNew=!1,e.isFound=!0,e.isModified=!0}async removeStoredSession(e){let t=new F(e,{},!1,!1,!0);try{await this.deleteSession(t,new Headers)}catch(r){let n=!0;try{n=Boolean(await this.fetchData(e))}catch{n=!0}if(n)throw r}}get getSessionExpirationDate(){return new Date(Date.now()+this.config.SESSION_LIFETIME*Wt)}get getCookieExpirationDate(){return new Date(Date.now()+this.config.COOKIE_LIFETIME*Wt)}isNotExpired(e){let t=e.getTime(),r=Date.now();return t>r}buildCookieString(e,t,r){let n=[`${this.config.COOKIE_NAME}=${e.sid}`];if(n.push(`Path=${this.config.COOKIE_PATH}`),this.config.COOKIE_DOMAIN)n.push(`Domain=${this.config.COOKIE_DOMAIN}`);if(typeof t==="number")n.push(`Max-Age=${t}`);else{let c=t||this.getCookieExpirationDate;n.push(`Expires=${c.toUTCString()}`)}if(this.config.COOKIE_HTTPONLY)n.push("HttpOnly");if(this.config.COOKIE_SECURE)n.push("Secure");let s=r||this.config.COOKIE_SAMESITE;if(s)n.push(`SameSite=${s}`);let i=n.join("; "),a=Buffer.byteLength(i,"utf8"),o=this.config.MAX_COOKIE_SIZE;if(a>o)throw Error(`[Framework Guard] Cookie exceeds maximum allowed size! Size: ${a} bytes. Max allowed: ${o} bytes. The browser will reject this cookie.`);return i}setCookie(e,t){let r=this.buildCookieString(e);t.append("Set-Cookie",r)}removeCookie(e,t){let r=this.buildCookieString(e,0);t.append("Set-Cookie",r)}async loadHeader(e,t=!1){let r=e.headers.get("cookie");if(r){let n=r.match(new RegExp(`(^| )${this.config.COOKIE_NAME}=([^;]+)`));if(n){let s=n[2];return[s,await this.openSession(s,t)]}}return[void 0,this.new({readonly:t})]}}class Kt{contextData={};data={};constructor(){}open(){}message({text:e,json:t,topic:r}){}drain(){}close(e,t){}set send(e){this.ws.send(e)}}class Ve{static registry=new Map;static register(e){for(let[t,r]of Object.entries(e)){let n=Object.seal({...r});this.registry.set(t,n)}return{use:(t)=>this.use(t)}}static use(e){return new Proxy({},{get:(t,r)=>(n,s)=>{if(s.kind!=="field")throw Error("Field decorators can only be used on class fields.");return function(){let i=Ve.registry.get(e);return i?i[r]:void 0}}})}}var dn=Ve;class zt{static registry=new Map;static register(e){for(let[t,r]of Object.entries(e))this.registry.set(t,Object.seal({...r}));return{use:(t)=>this.use(t)}}static use(e){let t=this.registry.get(e);if(!t)throw Error(`Scope "${e}" has not been registered.`);return t}}var mn=zt;export{ae as ArraySchema,Z as BooleanSchema,O as Column,Lr as DEFAULT_MAX_SIZE,M as DatabaseError,V as DbInspector,He as DbRepository,We as DbSchema,dn as Field,de as ForeignKeyError,Ht as JWTAuthService,Se as JwtEngine,se as McpController,pc as McpServer,Ne as Methods,X as NumberSchema,oe as ObjectSchema,W as Req,z as Res,gt as Rossa,ne as RouterManager,_ as Schema,ze as SchemaError,mn as Scope,F as ServerSide,Bt as SessionAuthInterface,Q as StringSchema,le as UniqueConstraintError,C as WSSMAN,Kt as Websocket,ue as WssManager,Pi as apiKey,Li as auth,ki as authBearer,qi as authorize,Ki as contentType,Vi as cookies,Zi as cors,h as createGuard,na as csrf,H as ctx,oa as deny,la as errorHandler,fe as getDialect,pa as header,Ra as ipFilter,Oa as json,Da as jwtAuth,_a as jwtRefresh,Ia as jwtRotate,va as keys,Pa as logger,La as loggerFN,Ue as mariadbDialect,ft as mcp,Wa as multipart,Fe as mysqlDialect,Le as postgresDialect,ro as rateLimit,po as requireSession,Me as route,io as sanitize,co as security,d as sendError,fo as session,Ui as smartCache,je as sqliteDialect,bo as staticFiles,ce as subManager,br as t,Ro as timeout,Do as urlencoded,ur as use,Va as validateForm,Ja as validateQuery,Oo as validateUrl,lt as wss,Ft as z};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rossa",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "A Bun and TypeScript web framework with routing, middleware guards, WebSockets, authentication, and database tools.",
|
|
5
5
|
"author": "Marky <markjotep@gmail.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
}
|
|
15
15
|
},
|
|
16
16
|
"files": [
|
|
17
|
-
"dist"
|
|
17
|
+
"dist",
|
|
18
|
+
"CHANGELOG.md"
|
|
18
19
|
],
|
|
19
20
|
"directories": {
|
|
20
21
|
"test": "test"
|
|
@@ -22,7 +23,9 @@
|
|
|
22
23
|
"scripts": {
|
|
23
24
|
"init": "bun update && mkdir -p ./src ./dist ./types && { [ ! -f ./src/index.ts ] && touch ./src/index.ts; }",
|
|
24
25
|
"test": "bun test",
|
|
25
|
-
"test:load": "bun run test/load/benchmark.ts"
|
|
26
|
+
"test:load": "bun run test/load/benchmark.ts",
|
|
27
|
+
"build": "bun run builder.ts",
|
|
28
|
+
"prepublishOnly": "bun test && bun run build"
|
|
26
29
|
},
|
|
27
30
|
"keywords": [
|
|
28
31
|
"ts",
|
|
@@ -36,13 +39,15 @@
|
|
|
36
39
|
"url": "https://github.com/MARKjotep/rossa/issues"
|
|
37
40
|
},
|
|
38
41
|
"homepage": "https://github.com/MARKjotep/rossa#readme",
|
|
39
|
-
"dependencies": {
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
44
|
+
"reflect-metadata": "^0.2.2"
|
|
45
|
+
},
|
|
40
46
|
"devDependencies": {
|
|
41
47
|
"@ohmyqt/oven": "link:@ohmyqt/oven",
|
|
42
48
|
"@ohmyqt/u": "link:@ohmyqt/u",
|
|
43
49
|
"@types/bun": "^1.4.4",
|
|
44
50
|
"fake-indexeddb": "^6.2.8",
|
|
45
|
-
"reflect-metadata": "^0.2.2",
|
|
46
51
|
"typescript": "^5.9.3"
|
|
47
52
|
},
|
|
48
53
|
"type": "module"
|