balda-js 0.0.19 → 0.0.21
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/lib/cli.js +9 -7
- package/lib/cli.js.map +1 -1
- package/lib/index.cjs +13 -10
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +6 -3
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
package/lib/index.cjs
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
"use strict";var $t=Object.create;var ee=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Et=Object.getOwnPropertyNames;var Pt=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty;var At=(s,e)=>{for(var t in e)ee(s,t,{get:e[t],enumerable:!0})},Ke=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Et(e))!Mt.call(s,o)&&o!==t&&ee(s,o,{get:()=>e[o],enumerable:!(r=Qe(e,o))||r.enumerable});return s};var E=(s,e,t)=>(t=s!=null?$t(Pt(s)):{},Ke(e||!s||!s.__esModule?ee(t,"default",{value:s,enumerable:!0}):t,s)),Ft=s=>Ke(ee({},"__esModule",{value:!0}),s),P=(s,e,t,r)=>{for(var o=r>1?void 0:r?Qe(e,t):e,n=s.length-1,a;n>=0;n--)(a=s[n])&&(o=(r?a(e,t,o):a(o))||o);return r&&o&&ee(e,t,o),o};var cr={};At(cr,{BasePlugin:()=>Ye,Command:()=>O,CommandRegistry:()=>pe,Request:()=>M,Response:()=>k,Server:()=>We,commandRegistry:()=>He,controller:()=>Ht,cookie:()=>je,cors:()=>Le,del:()=>kt,fileParser:()=>Ve,get:()=>_t,getContentType:()=>fe,helmet:()=>ze,json:()=>Ge,log:()=>Ne,middleware:()=>Ut,patch:()=>jt,post:()=>Nt,put:()=>Dt,rateLimiter:()=>De,router:()=>pr,serveStatic:()=>_e,session:()=>Ue,timeout:()=>Ie,trustProxy:()=>qe,urlencoded:()=>Be,validate:()=>It});module.exports=Ft(cr);var Ze=require("path");var l=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r)}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)||new Map}static delete(e,t){this.metadata.get(e)?.delete(t.toString())}static clear(e){this.metadata.delete(e)}};var W=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null}},Te=class s{trees;routes;middlewares;basePath;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e)}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,o,n){e=e.toUpperCase();let a=this.trees.get(e);a||(a=new W,this.trees.set(e,a));let d=t.split("?")[0].replace(/^\/+|\/+$/g,""),i=d.length===0?[]:d.split("/"),c=a;for(let f of i){if(f==="*"){c.wildcardChild||(c.wildcardChild=new W),c=c.wildcardChild;break}if(f.startsWith(":")){let g=f.slice(1);c.paramChild||(c.paramChild={node:new W,name:g}),c=c.paramChild.node;continue}c.staticChildren.has(f)||c.staticChildren.set(f,new W),c=c.staticChildren.get(f)}c.middleware=r,c.handler=o;let u=this.routes.findIndex(f=>f.method===e&&f.path===t);if(u!==-1){this.routes[u].middleware=r,this.routes[u].handler=o;return}this.routes.push({method:e,path:t,middleware:r,handler:o,swaggerOptions:n})}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let n=t.split("?")[0].replace(/^\/+|\/+$/g,""),a=n.length===0?[]:n.split("/"),p={},d=r;for(let i=0;i<a.length;i++){let c=a[i];if(d.staticChildren.has(c)){d=d.staticChildren.get(c);continue}if(d.paramChild){p[d.paramChild.name]=c,d=d.paramChild.node;continue}if(d.wildcardChild){p["*"]=a.slice(i).join("/"),d=d.wildcardChild;break}return null}return!d.handler||!d.middleware?null:{middleware:d.middleware,handler:d.handler,params:p}}get(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("GET",n,i,p,c)}post(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("POST",n,i,p,c)}patch(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("PATCH",n,i,p,c)}put(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("PUT",n,i,p,c)}delete(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("DELETE",n,i,p,c)}options(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("OPTIONS",n,i,p,c)}group(e,t,r){let o=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,a=this.joinPath(e),p=new s(a,[...this.middlewares,...o]);n?.(p);for(let d of p.getRoutes())this.addOrUpdate(d.method,d.path,d.middleware,d.handler,d.swaggerOptions)}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes)this.addOrUpdate(t.method,t.path,[...e,...t.middleware||[]],t.handler)}normalizeBasePath(e){if(!e)return"";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(o=>typeof o=="string"&&o.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}},h=new Te;var Ht=(s,e)=>t=>{let o=l.get(t.prototype,"__class__")?.middlewares||[],n=l.getAll(t.prototype);for(let[a,p]of n.entries()){if(!p.route)continue;let d=t.prototype[a],i=s?(0,Ze.join)(s,p.route.path):p.route.path,c=[...o,...p.middlewares||[]];h.addOrUpdate(p.route.method,i,c,d,{service:t.name.replace(/Controller$/,""),...e,...p.documentation})}l.clear(t.prototype)};var kt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"DELETE"},l.set(t,r,n),o};var _t=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"GET"},l.set(t,r,n),o};var jt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PATCH"},l.set(t,r,n),o};var Nt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"POST"},l.set(t,r,n),o};var Dt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PUT"},l.set(t,r,n),o};var Ut=s=>(e,t,r)=>{if(typeof t>"u"){let n=l.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!s)throw new Error(`Middleware ${String(s)} not found, are you sure you defined it before using it?`);return Array.isArray(s)||(s=[s]),n.middlewares.push(...s),l.set(e.prototype,"__class__",n),e}let o=l.get(e,t);return o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),Array.isArray(s)||(s=[s]),o.middlewares.push(...s),l.set(e,t,o),r};var et=require("ajv");var N=s=>(e,t,r)=>{let o=r.value,n=l.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),s.body&&(n.documentation.requestBody=s.body),s.query&&(n.documentation.query=s.query),l.set(e,t,n),r.value=async function(...a){let p=a[0],d=a[1];try{let i,c,u;s.body&&(i=p.validate(s.body,s.safe)),s.query&&(c=p.validateQuery(s.query,s.safe)),s.all&&(u=p.validateAll(s.all,s.safe));let f=[...a];return i!==void 0&&f.push(i),c!==void 0&&f.push(c),u!==void 0&&f.push(u),o.apply(this,f)}catch(i){if(!(i instanceof et.ValidationError))throw i;return s.customError?d.status(s.customError.status||400).json({received:p.body,schema:s.body,error:i.errors}):d.badRequest(i)}},r};N.query=(s,e)=>N({query:s,customError:e});N.body=(s,e)=>N({body:s,customError:e});N.all=(s,e)=>N({all:s,customError:e});var It=N;var nt=require("glob");var ae=require("path");var Ce=class{type;constructor(){this.type=this.getRunTime()}getRunTime(){if(typeof Bun<"u")return"bun";if(typeof Deno<"u")return"deno";if(typeof process<"u")return"node";throw new Error("No environment detected")}},y=new Ce;var $e=class{getCliArgs(){switch(y.type){case"bun":return this.getBunArgs();case"node":return this.getNodeArgs();case"deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],o=r.split("/").pop()||r;if(!r.startsWith("-")){if(o==="yarn"&&t+1<e.length&&e[t+1]==="run"||o==="npx"&&t+1<e.length)return t+1;if(o==="yarn"||o==="pnpm")return t;if(o==="npm"&&t+1<e.length&&e[t+1]==="run"||o==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(o)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},Ee=new $e;var qt=s=>{if(!s||s==="-"||s==="--")return null;let e=s.indexOf("=");if(e>0){let t=s.substring(0,e),r=s.substring(e+1);return{name:t,value:tt(r)}}return{name:s,value:!0}},tt=s=>{if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1;let e=Number(s);return!Number.isNaN(e)&&Number.isFinite(e)?e:s},D=()=>{let s=Ee.getCliArgs(),e=[],t={};if(!s||!s.length)return{args:e,flags:t};for(let r=0;r<s.length;r++){let o=s[r];if(!(!o||typeof o!="string")){if(o.startsWith("-")){let n=qt(o);if(n){if(n.value===!0&&r+1<s.length){let a=s[r+1];a&&typeof a=="string"&&!a.startsWith("-")&&(n.value=tt(a),r++)}t[n.name]=n.value}continue}e.push(o)}}return{args:e,flags:t}};var ie=()=>Ee.getCliArgs()[0]||null;var U="VALIDATION_ERROR";var rt=D().args.slice(1),Y=s=>(e,t)=>{let r=ie();if(!r||r!==e.commandName)return;let o=t;l.set(e,t,{type:"arg",name:o,description:s.description});let n=rt.length?rt.shift():s.defaultValue;if(s.required&&!n){let a=l.get(e,U);l.set(e,U,[...a||[],{type:"arg",name:o,message:"Required argument not provided"}]);return}s.parse&&n&&(n=s.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})};var Pe=class{exit(e){switch(y.type){case"bun":case"node":process.exit(e);case"deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},Me=new Pe;var st=E(require("pino"),1),Bt=()=>(0,st.default)({level:"info",formatters:{level:e=>({level:e})}}),v=Bt();var O=class{static commandName=this.name;static description="";static help=[];static options={keepAlive:!1};static args=D().args.slice(1);static flags=D().flags;static logger=v;static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help","-?","--usage"];if(!Object.keys(e).some(i=>t.includes(i)))return;let o=this.commandName,n=this.description||"No description available",a=this.help||[],p=this.options,d=this.generateHelpOutput({name:o,description:n,helpText:a,options:p,args:this.args,flags:this.flags},this);console.log(d),Me.exit(0)}static generateHelpOutput=(e,t)=>{let{name:r,description:o,helpText:n,options:a,args:p,flags:d}=e,i={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},c=[`${i.title}${r}${i.reset}`,`${i.description}${o}${i.reset}`,"",`${i.subtitle}Usage:${i.reset}`,` ${i.code}${r}${i.reset} [options] [arguments]`,"",`${i.subtitle}Options:${i.reset}`,` ${i.flag}-h, --help${i.reset} Show this help message`,` ${i.flag}-?, --usage${i.reset} Show usage information`,"",`${i.subtitle}Command Options:${i.reset}`,` ${i.flag}keepAlive${i.reset} ${a?.keepAlive??!1?i.success+"Enabled"+i.reset:i.error+"Disabled"+i.reset}`,""];if(n){let m=Array.isArray(n)?n:[n];c.push(`${i.subtitle}Help:${i.reset}`),m.forEach(x=>{c.push(` ${i.description}${x}${i.reset}`)}),c.push("")}let u=l.getAll(t),f=Array.from(u.values()).filter(m=>m.type==="arg"),g=Array.from(u.values()).filter(m=>m.type==="flag");return f.length&&(c.push(`${i.subtitle}Available Arguments:${i.reset}`),f.forEach(m=>{let x=m.required?` ${i.error}(required)${i.reset}`:"",S=m.description?` ${i.description}${m.description}${i.reset}`:"";c.push(` ${i.code}${m.name}${i.reset}${x}${S}`)}),c.push("")),g.length&&(c.push(`${i.subtitle}Available Flags:${i.reset}`),g.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let x=m.aliases.length?` ${i.flag}(${m.aliases.join(", ")})${i.reset}`:"",S=m.required?` ${i.error}(required)${i.reset}`:"",C=m.description?` ${i.description}${m.description}${i.reset}`:"";c.push(` ${i.flag}--${m.name}${x}${i.reset}${S}${C}`)}),c.push("")),((p?.length??0)>0||d&&Object.keys(d).length>0)&&(c.push(`${i.subtitle}Current Context:${i.reset}`),p?.length&&c.push(` ${i.info}Provided Arguments:${i.reset} ${i.code}${p.join(" ")}${i.reset}`),d&&Object.keys(d).length>0&&(c.push(` ${i.info}Provided Flags:${i.reset}`),Object.keys(d).forEach(m=>{let x=d[m],S=x!=null?` = ${i.code}${x}${i.reset}`:"";c.push(` ${i.flag}${m}${i.reset}${S}`)})),c.push("")),n&&(Array.isArray(n)?n.some(m=>m.includes("example")):n.includes("example"))&&(c.push(`${i.subtitle}Examples:${i.reset}`),(Array.isArray(n)?n.filter(x=>x.includes("example")):[n.split("example")[1].trim()]).forEach(x=>{c.push(` ${i.code}${x}${i.reset}`)}),c.push("")),c.join(`
|
|
2
|
-
`)};static validateContext=e=>{let t=Array.from(l.get(e,U)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((o,n)=>{let a=`${r.info}${n+1}.${r.reset}`,p=`${r.error}${o.type.toUpperCase()}${r.reset}`,d=`${r.code}${o.name}${r.reset}`;console.error(` ${a} ${p} ${d}: ${r.error}${o.message}${r.reset}`)}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),Me.exit(1)}}};var Ae=class{async mkdir(e,t){switch(y.type){case"bun":case"node":await(await import("fs/promises")).mkdir(e,{recursive:t?.recursive??!1});break;case"deno":await Deno.mkdir(e,{recursive:t?.recursive??!1});break}}async exists(e){switch(y.type){case"node":return(await import("fs")).existsSync(e);case"bun":return Bun.file(e).exists();case"deno":return Deno.stat(e).then(()=>!0).catch(()=>!1);default:throw new Error("Unsupported runtime")}}async readFile(e){switch(y.type){case"node":let r=await(await import("fs/promises")).readFile(e);return new Uint8Array(r);case"bun":let o=await Bun.file(e).arrayBuffer();return new Uint8Array(o);case"deno":return new Uint8Array(await Deno.readFile(e))}}async writeFile(e,t){switch(y.type){case"node":await(await import("fs/promises")).writeFile(e,t);break;case"bun":await Bun.write(e,t);break;case"deno":await Deno.writeFile(e,t);break}}async stat(e){switch(y.type){case"node":let r=await(await import("fs/promises")).stat(e);return{isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case"bun":let o=await Bun.file(e).stat();return{isDirectory:o.isDirectory(),isFile:o.isFile(),isSymbolicLink:o.isSymbolicLink(),size:o.size};case"deno":let n=await Deno.stat(e);return{isDirectory:n.isDirectory,isFile:n.isFile,isSymbolicLink:!1,size:n.size}}}async unlink(e){switch(y.type){case"node":await(await import("fs/promises")).unlink(e);break;case"bun":await Bun.file(e).delete();break;case"deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}},R=new Ae;var X=class extends O{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){let e=this.getCommandTemplate();this.path=(0,ae.join)(this.path,`${this.name}.ts`),await R.exists((0,ae.join)(process.cwd(),this.path))||await R.mkdir((0,ae.join)(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:!0}),await R.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`)}static getCommandTemplate(){return`import { Command } from "balda-js";
|
|
1
|
+
"use strict";var $t=Object.create;var ee=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Et=Object.getOwnPropertyNames;var Pt=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty;var At=(s,e)=>{for(var t in e)ee(s,t,{get:e[t],enumerable:!0})},Ke=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Et(e))!Mt.call(s,o)&&o!==t&&ee(s,o,{get:()=>e[o],enumerable:!(r=Qe(e,o))||r.enumerable});return s};var T=(s,e,t)=>(t=s!=null?$t(Pt(s)):{},Ke(e||!s||!s.__esModule?ee(t,"default",{value:s,enumerable:!0}):t,s)),Ft=s=>Ke(ee({},"__esModule",{value:!0}),s),P=(s,e,t,r)=>{for(var o=r>1?void 0:r?Qe(e,t):e,n=s.length-1,a;n>=0;n--)(a=s[n])&&(o=(r?a(e,t,o):a(o))||o);return r&&o&&ee(e,t,o),o};var ur={};At(ur,{BasePlugin:()=>Ye,Command:()=>O,CommandRegistry:()=>pe,Request:()=>M,Response:()=>k,Server:()=>We,commandRegistry:()=>He,controller:()=>Ht,cookie:()=>je,cors:()=>Le,del:()=>kt,fileParser:()=>Ve,get:()=>_t,getContentType:()=>fe,helmet:()=>ze,json:()=>Ge,log:()=>Ne,middleware:()=>Ut,patch:()=>jt,post:()=>Nt,put:()=>Dt,rateLimiter:()=>De,router:()=>cr,serveStatic:()=>_e,session:()=>Ue,timeout:()=>Ie,trustProxy:()=>qe,urlencoded:()=>Be,validate:()=>It});module.exports=Ft(ur);var Ze=require("path");var l=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r)}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)||new Map}static delete(e,t){this.metadata.get(e)?.delete(t.toString())}static clear(e){this.metadata.delete(e)}};var W=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null}},Te=class s{trees;routes;middlewares;basePath;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e)}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,o,n){e=e.toUpperCase();let a=this.trees.get(e);a||(a=new W,this.trees.set(e,a));let d=t.split("?")[0].replace(/^\/+|\/+$/g,""),i=d.length===0?[]:d.split("/"),c=a;for(let f of i){if(f==="*"){c.wildcardChild||(c.wildcardChild=new W),c=c.wildcardChild;break}if(f.startsWith(":")){let g=f.slice(1);c.paramChild||(c.paramChild={node:new W,name:g}),c=c.paramChild.node;continue}c.staticChildren.has(f)||c.staticChildren.set(f,new W),c=c.staticChildren.get(f)}c.middleware=r,c.handler=o;let u=this.routes.findIndex(f=>f.method===e&&f.path===t);if(u!==-1){this.routes[u].middleware=r,this.routes[u].handler=o;return}this.routes.push({method:e,path:t,middleware:r,handler:o,swaggerOptions:n})}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let n=t.split("?")[0].replace(/^\/+|\/+$/g,""),a=n.length===0?[]:n.split("/"),p={},d=r;for(let i=0;i<a.length;i++){let c=a[i];if(d.staticChildren.has(c)){d=d.staticChildren.get(c);continue}if(d.paramChild){p[d.paramChild.name]=c,d=d.paramChild.node;continue}if(d.wildcardChild){p["*"]=a.slice(i).join("/"),d=d.wildcardChild;break}return null}return!d.handler||!d.middleware?null:{middleware:d.middleware,handler:d.handler,params:p}}get(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("GET",n,i,p,c)}post(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("POST",n,i,p,c)}patch(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("PATCH",n,i,p,c)}put(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("PUT",n,i,p,c)}delete(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("DELETE",n,i,p,c)}options(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("OPTIONS",n,i,p,c)}group(e,t,r){let o=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,a=this.joinPath(e),p=new s(a,[...this.middlewares,...o]);n?.(p);for(let d of p.getRoutes())this.addOrUpdate(d.method,d.path,d.middleware,d.handler,d.swaggerOptions)}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes)this.addOrUpdate(t.method,t.path,[...e,...t.middleware||[]],t.handler)}normalizeBasePath(e){if(!e)return"";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(o=>typeof o=="string"&&o.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}},h=new Te;var Ht=(s,e)=>t=>{let o=l.get(t.prototype,"__class__")?.middlewares||[],n=l.getAll(t.prototype);for(let[a,p]of n.entries()){if(!p.route)continue;let d=t.prototype[a],i=s?(0,Ze.join)(s,p.route.path):p.route.path,c=[...o,...p.middlewares||[]];h.addOrUpdate(p.route.method,i,c,d,{service:t.name.replace(/Controller$/,""),...e,...p.documentation})}l.clear(t.prototype)};var kt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"DELETE"},l.set(t,r,n),o};var _t=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"GET"},l.set(t,r,n),o};var jt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PATCH"},l.set(t,r,n),o};var Nt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"POST"},l.set(t,r,n),o};var Dt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PUT"},l.set(t,r,n),o};var Ut=s=>(e,t,r)=>{if(typeof t>"u"){let n=l.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!s)throw new Error(`Middleware ${String(s)} not found, are you sure you defined it before using it?`);return Array.isArray(s)||(s=[s]),n.middlewares.push(...s),l.set(e.prototype,"__class__",n),e}let o=l.get(e,t);return o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),Array.isArray(s)||(s=[s]),o.middlewares.push(...s),l.set(e,t,o),r};var et=require("ajv");var N=s=>(e,t,r)=>{let o=r.value,n=l.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),s.body&&(n.documentation.requestBody=s.body),s.query&&(n.documentation.query=s.query),l.set(e,t,n),r.value=async function(...a){let p=a[0],d=a[1];try{let i,c,u;s.body&&(i=p.validate(s.body,s.safe)),s.query&&(c=p.validateQuery(s.query,s.safe)),s.all&&(u=p.validateAll(s.all,s.safe));let f=[...a];return i!==void 0&&f.push(i),c!==void 0&&f.push(c),u!==void 0&&f.push(u),o.apply(this,f)}catch(i){if(!(i instanceof et.ValidationError))throw i;return s.customError?d.status(s.customError.status||400).json({received:p.body,schema:s.body,error:i.errors}):d.badRequest(i)}},r};N.query=(s,e)=>N({query:s,customError:e});N.body=(s,e)=>N({body:s,customError:e});N.all=(s,e)=>N({all:s,customError:e});var It=N;var nt=require("glob");var ae=require("path");var Ce=class{type;constructor(){this.type=this.getRunTime()}getRunTime(){if(typeof Bun<"u")return"bun";if(typeof Deno<"u")return"deno";if(typeof process<"u")return"node";throw new Error("No environment detected")}},y=new Ce;var $e=class{getCliArgs(){switch(y.type){case"bun":return this.getBunArgs();case"node":return this.getNodeArgs();case"deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],o=r.split("/").pop()||r;if(!r.startsWith("-")){if(o==="yarn"&&t+1<e.length&&e[t+1]==="run"||o==="npx"&&t+1<e.length)return t+1;if(o==="yarn"||o==="pnpm")return t;if(o==="npm"&&t+1<e.length&&e[t+1]==="run"||o==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(o)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},Ee=new $e;var qt=s=>{if(!s||s==="-"||s==="--")return null;let e=s.indexOf("=");if(e>0){let t=s.substring(0,e),r=s.substring(e+1);return{name:t,value:tt(r)}}return{name:s,value:!0}},tt=s=>{if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1;let e=Number(s);return!Number.isNaN(e)&&Number.isFinite(e)?e:s},D=()=>{let s=Ee.getCliArgs(),e=[],t={};if(!s||!s.length)return{args:e,flags:t};for(let r=0;r<s.length;r++){let o=s[r];if(!(!o||typeof o!="string")){if(o.startsWith("-")){let n=qt(o);if(n){if(n.value===!0&&r+1<s.length){let a=s[r+1];a&&typeof a=="string"&&!a.startsWith("-")&&(n.value=tt(a),r++)}t[n.name]=n.value}continue}e.push(o)}}return{args:e,flags:t}};var ie=()=>Ee.getCliArgs()[0]||null;var U="VALIDATION_ERROR";var rt=D().args.slice(1),Y=s=>(e,t)=>{let r=ie();if(!r||r!==e.commandName)return;let o=t;l.set(e,t,{type:"arg",name:o,description:s.description});let n=rt.length?rt.shift():s.defaultValue;if(s.required&&!n){let a=l.get(e,U);l.set(e,U,[...a||[],{type:"arg",name:o,message:"Required argument not provided"}]);return}s.parse&&n&&(n=s.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})};var Pe=class{exit(e){switch(y.type){case"bun":case"node":process.exit(e);case"deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},Me=new Pe;var st=T(require("pino"),1),Bt=()=>(0,st.default)({level:"info",formatters:{level:e=>({level:e})}}),v=Bt();var O=class{static commandName=this.name;static description="";static help=[];static options={keepAlive:!1};static args=D().args.slice(1);static flags=D().flags;static logger=v;static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help","-?","--usage"];if(!Object.keys(e).some(i=>t.includes(i)))return;let o=this.commandName,n=this.description||"No description available",a=this.help||[],p=this.options,d=this.generateHelpOutput({name:o,description:n,helpText:a,options:p,args:this.args,flags:this.flags},this);console.log(d),Me.exit(0)}static generateHelpOutput=(e,t)=>{let{name:r,description:o,helpText:n,options:a,args:p,flags:d}=e,i={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},c=[`${i.title}${r}${i.reset}`,`${i.description}${o}${i.reset}`,"",`${i.subtitle}Usage:${i.reset}`,` ${i.code}${r}${i.reset} [options] [arguments]`,"",`${i.subtitle}Options:${i.reset}`,` ${i.flag}-h, --help${i.reset} Show this help message`,` ${i.flag}-?, --usage${i.reset} Show usage information`,"",`${i.subtitle}Command Options:${i.reset}`,` ${i.flag}keepAlive${i.reset} ${a?.keepAlive??!1?i.success+"Enabled"+i.reset:i.error+"Disabled"+i.reset}`,""];if(n){let m=Array.isArray(n)?n:[n];c.push(`${i.subtitle}Help:${i.reset}`),m.forEach(x=>{c.push(` ${i.description}${x}${i.reset}`)}),c.push("")}let u=l.getAll(t),f=Array.from(u.values()).filter(m=>m.type==="arg"),g=Array.from(u.values()).filter(m=>m.type==="flag");return f.length&&(c.push(`${i.subtitle}Available Arguments:${i.reset}`),f.forEach(m=>{let x=m.required?` ${i.error}(required)${i.reset}`:"",S=m.description?` ${i.description}${m.description}${i.reset}`:"";c.push(` ${i.code}${m.name}${i.reset}${x}${S}`)}),c.push("")),g.length&&(c.push(`${i.subtitle}Available Flags:${i.reset}`),g.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let x=m.aliases.length?` ${i.flag}(${m.aliases.join(", ")})${i.reset}`:"",S=m.required?` ${i.error}(required)${i.reset}`:"",$=m.description?` ${i.description}${m.description}${i.reset}`:"";c.push(` ${i.flag}--${m.name}${x}${i.reset}${S}${$}`)}),c.push("")),((p?.length??0)>0||d&&Object.keys(d).length>0)&&(c.push(`${i.subtitle}Current Context:${i.reset}`),p?.length&&c.push(` ${i.info}Provided Arguments:${i.reset} ${i.code}${p.join(" ")}${i.reset}`),d&&Object.keys(d).length>0&&(c.push(` ${i.info}Provided Flags:${i.reset}`),Object.keys(d).forEach(m=>{let x=d[m],S=x!=null?` = ${i.code}${x}${i.reset}`:"";c.push(` ${i.flag}${m}${i.reset}${S}`)})),c.push("")),n&&(Array.isArray(n)?n.some(m=>m.includes("example")):n.includes("example"))&&(c.push(`${i.subtitle}Examples:${i.reset}`),(Array.isArray(n)?n.filter(x=>x.includes("example")):[n.split("example")[1].trim()]).forEach(x=>{c.push(` ${i.code}${x}${i.reset}`)}),c.push("")),c.join(`
|
|
2
|
+
`)};static validateContext=e=>{let t=Array.from(l.get(e,U)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((o,n)=>{let a=`${r.info}${n+1}.${r.reset}`,p=`${r.error}${o.type.toUpperCase()}${r.reset}`,d=`${r.code}${o.name}${r.reset}`;console.error(` ${a} ${p} ${d}: ${r.error}${o.message}${r.reset}`)}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),Me.exit(1)}}};var Ae=class{async mkdir(e,t){switch(y.type){case"bun":case"node":await(await import("fs/promises")).mkdir(e,{recursive:t?.recursive??!1});break;case"deno":await Deno.mkdir(e,{recursive:t?.recursive??!1});break}}async exists(e){switch(y.type){case"node":return(await import("fs")).existsSync(e);case"bun":return Bun.file(e).exists();case"deno":return Deno.stat(e).then(()=>!0).catch(()=>!1);default:throw new Error("Unsupported runtime")}}async readFile(e){switch(y.type){case"node":let r=await(await import("fs/promises")).readFile(e);return new Uint8Array(r);case"bun":let o=await Bun.file(e).arrayBuffer();return new Uint8Array(o);case"deno":return new Uint8Array(await Deno.readFile(e))}}async writeFile(e,t){switch(y.type){case"node":await(await import("fs/promises")).writeFile(e,t);break;case"bun":await Bun.write(e,t);break;case"deno":await Deno.writeFile(e,t);break}}async stat(e){switch(y.type){case"node":let r=await(await import("fs/promises")).stat(e);return{isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case"bun":let o=await Bun.file(e).stat();return{isDirectory:o.isDirectory(),isFile:o.isFile(),isSymbolicLink:o.isSymbolicLink(),size:o.size};case"deno":let n=await Deno.stat(e);return{isDirectory:n.isDirectory,isFile:n.isFile,isSymbolicLink:!1,size:n.size}}}async unlink(e){switch(y.type){case"node":await(await import("fs/promises")).unlink(e);break;case"bun":await Bun.file(e).delete();break;case"deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}},R=new Ae;var X=class extends O{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){let e=this.getCommandTemplate();this.path=(0,ae.join)(this.path,`${this.name}.ts`),await R.exists((0,ae.join)(process.cwd(),this.path))||await R.mkdir((0,ae.join)(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:!0}),await R.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`)}static getCommandTemplate(){return`import { Command, CommandOptions } from "balda-js";
|
|
3
3
|
|
|
4
4
|
export default class extends Command {
|
|
5
5
|
static commandName = "${this.name}";
|
|
6
6
|
static description = "${this.description}";
|
|
7
7
|
|
|
8
|
-
static options = {
|
|
8
|
+
static options: CommandOptions = {
|
|
9
|
+
// Define your command options here
|
|
10
|
+
stayAlive: false,
|
|
11
|
+
};
|
|
9
12
|
|
|
10
13
|
static async handle(): Promise<void> {
|
|
11
14
|
// Implement your command logic here
|
|
@@ -43,16 +46,16 @@ server.listen(({ url }) => {
|
|
|
43
46
|
\u2728 Available Balda Commands:
|
|
44
47
|
`);let t=Math.max(...e.map(r=>r.commandName.length));for(let r of e){let o=r.commandName.padEnd(t+2),n=r.description||"No description available";console.log(` \x1B[36m${o}\x1B[0m ${n}`)}console.log(`
|
|
45
48
|
\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
|
|
46
|
-
`)}};var pe=class s{commands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=v;constructor(){this.commands=new Map}static getInstance(){return new s}static setCommandsPattern(e){this.commandsPattern=e}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}async loadCommands(e){s.logger.info(`Loading commands from ${e}`);let t=await(0,nt.glob)(e,{absolute:!0,cwd:H.getCwd()});for(let o of t){let n=await import(o).then(a=>a.default?a.default:a).catch(a=>(s.logger.error(`Error loading command ${o}: ${a}`),null));n&&this.commands.set(n.commandName,n)}let r=[B,X,L,V,te];for(let o of r)this.commands.set(o.commandName,o)}},He=pe.getInstance();var G=require("@sinclair/typebox");var ce=E(require("ajv"),1),it=E(require("ajv-formats"),1),Lt=(0,it.default)(new ce.default,["date-time","time","date","email","hostname","ipv4","ipv6","uri","uri-reference","uuid","uri-template","json-pointer","relative-json-pointer","regex","password","binary","byte","iso-date-time","iso-time"]),z=(s,e,t=!1)=>{let r=Lt.compile(s);if(!r(e)){if(t)return e;throw new ce.ValidationError(r.errors||[])}return e};var ue=class extends Request{};var at=require("crypto"),M=class s extends ue{static fromRequest(e){return new s(e.url,{method:e.method,body:e.body,headers:e.headers})}static enrichRequest(e){return e.validate=(t,r=!1)=>(typeof t=="function"&&(t=t(G.Type)),z(t,e.body||{},r)),e.validateQuery=(t,r=!1)=>(typeof t=="function"&&(t=t(G.Type)),z(t,e.query||{},r)),e.validateAll=(t,r=!1)=>(typeof t=="function"&&(t=t(G.Type)),z(t,{...e.body?{body:e.body}:{},...e.query?{query:e.query}:{}},r)),e.file=t=>e.files.find(r=>r.formName===t)??null,e.files=[],e.saveSession=async()=>{},e.destroySession=async()=>{},e.session={},e.cookies={},e.cookie=t=>e.cookies[t],e}file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};query={};get id(){return this._id||(this._id=(0,at.randomUUID)()),this._id}body;validate(e,t=!1){return typeof e=="function"&&(e=e(G.Type)),z(e,this.body||{},t)}validateQuery(e,t=!1){return typeof e=="function"&&(e=e(G.Type)),z(e,this.query||{},t)}validateAll(e,t=!1){return typeof e=="function"&&(e=e(G.Type)),z(e,{...this.body?{body:this.body}:{},...this.query?{query:this.query}:{}},t)}};var dt=E(require("fs/promises"),1),ke=class{file(e){switch(y.type){case"bun":return Bun.file(e);case"node":return dt.default.readFile(e);case"deno":return Deno.readFile(e);default:throw new Error("Unsupported runtime")}}},le=new ke;var Q=require("path");var w=s=>({name:s.constructor.name,cause:s.cause,message:s.message,stack:s.stack});var T=class extends Error{constructor(e){super(e)}};var me=class extends T{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`)}};var b=class extends T{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`)}};var pt=new Map([[".html","text/html"],[".css","text/css"],[".js","application/javascript"],[".png","image/png"],[".jpg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".json","application/json"],[".txt","text/plain"],[".ico","image/x-icon"],[".webp","image/webp"],[".mp4","video/mp4"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".webm","video/webm"]]);var _e=(s="public",e)=>(h.addOrUpdate("GET",`${s}/*`,[],async(t,r)=>Vt(t,r,s),{service:"StaticFiles",...e}),async(t,r,o)=>o());async function Vt(s,e,t){if(s.method!=="GET"&&s.method!=="HEAD")return e.status(405).json({...w(new me(s.url,s.method))});let r=s.params["*"]||"",o=(0,Q.join)(t,r),n=(0,Q.resolve)(H.getCwd(),o);try{if(!(await R.stat(n)).isFile)return e.notFound({...w(new b(s.url,s.method))})}catch(d){if(d.code==="ENOENT")return e.notFound({...w(new b(s.url,s.method))});throw d}let a=fe((0,Q.extname)(n));e.setHeader("Content-Type",a);let p=await le.file(n);e.raw(p)}function fe(s){return pt.get(s)||"application/octet-stream"}var k=class{responseStatus;headers;body;constructor(e=200){this.responseStatus=e,this.headers={}}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.text(String(e));if(e instanceof Date)return this.text(e.toISOString());if(e instanceof RegExp)return this.text(e.toString());if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="function")return this.text(e.toString());if(typeof e=="symbol")return this.text(e.toString());this.body=e}raw(e){this.body=e}text(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/plain"}}json(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/json"}}html(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/html"}}xml(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/xml"}}download(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/octet-stream"}}file(e){let t=fe(e),r=le.file(e);this.headers={...this.headers,"Content-Type":t}}ok(e){this.status(200).send(e)}created(e){this.status(201).send(e)}accepted(e){this.status(202).send(e)}noContent(){this.status(204).send("")}partialContent(e){this.status(206).send(e)}multipleChoices(e){this.status(300).setHeader("Location",e)}redirect(e){this.status(302).setHeader("Location",e)}movedPermanently(e){this.status(301).setHeader("Location",e)}found(e){this.status(302).setHeader("Location",e)}seeOther(e){this.status(303).setHeader("Location",e)}notModified(){this.status(304).send("")}temporaryRedirect(e){this.status(307).setHeader("Location",e)}permanentRedirect(e){this.status(308).setHeader("Location",e)}badRequest(e){this.status(400).send(e)}unauthorized(e){this.status(401).send(e)}forbidden(e){this.status(403).send(e)}notFound(e){this.status(404).send(e)}methodNotAllowed(e){this.status(405).send(e)}notAcceptable(e){this.status(406).send(e)}conflict(e){this.status(409).send(e)}gone(e){this.status(410).send(e)}payloadTooLarge(e){this.status(413).send(e)}unsupportedMediaType(e){this.status(415).send(e)}unprocessableEntity(e){this.status(422).send(e)}tooManyRequests(e){this.status(429).send(e)}internalServerError(e){this.status(500).send(e)}notImplemented(e){this.status(501).send(e)}badGateway(e){this.status(502).send(e)}serviceUnavailable(e){this.status(503).send(e)}gatewayTimeout(e){this.status(504).send(e)}httpVersionNotSupported(e){this.status(505).send(e)}getBody(){return this.body}};var xt=require("glob"),Je=require("path");var ct=require("glob");var K=class{static scheduledJobs=[];static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t})}static async run(){let e=(await import("node-cron").catch(()=>{throw new T("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(v.info("Scheduling cron jobs"),!this.scheduledJobs.length){v.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)v.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));v.info("Cron jobs scheduled")}static globalErrorHandler(e){v.error(e.execution?.error)}static async massiveImportCronJobs(e){let t=[];for(let r of e){let o=await(0,ct.glob)(r,{absolute:!0,cwd:H.getCwd()});t.push(...o)}await Promise.all(t.map(async r=>{await import(r).catch(o=>{v.error(`Error importing cron job: ${r}`),v.error(o)})}))}};var Z=class{constructor(e){this.response=e}body(){return this.response.getBody()}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let o in t){let n=r===""?o:`${r}.${o}`,a=e[o],p=t[o];if(!(o in e))throw new Error(`Expected ${r} to have key ${o}, but it was not found`);if(this.isObject(p)&&this.isObject(a))this.assertSubset(a,p,n);else if(Array.isArray(p)&&Array.isArray(a))this.assertArraySubset(a,p,n);else if(a!==p)throw new Error(`Expected ${n} to be ${p}, but got ${a}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${o.length}`);for(let a of n){let p=r==="body"?a:`${r}.${a}`;this.assertDeepEqual(e[a],t[a],p)}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`,a=e[o],p=t[o];if(this.isObject(p)&&this.isObject(a))this.assertSubset(a,p,n);else if(Array.isArray(p)&&Array.isArray(a))this.assertArraySubset(a,p,n);else if(a!==p)throw new Error(`Expected ${n} to be ${p}, but got ${a}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`;this.assertDeepEqual(e[o],t[o],n)}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var _=async(s,e,t,r=new k)=>{let o=0;if(!s.length)return await e(t,r),r;let n=async()=>{if(o++,o>=s.length){await e(t,r);return}let p=s[o];await p(t,r,n)},a=s[0];return await a(t,r,n),r},j=s=>s?["post","put","patch","delete"].includes(s.toLowerCase()):!0;var he=class{server;constructor(e){this.server=e}async request(e,t,r={}){let{headers:o={},query:n={},cookies:a={},ip:p}=r;this.validateOptions(r);let d=h.find(e.toUpperCase(),t);if(!d){let g=new k(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new Z(g)}let i=r.body,c="application/json";if(i&&typeof i=="object"&&!(i instanceof Uint8Array)&&!(i instanceof ArrayBuffer)&&(i=JSON.stringify(i)),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;c=`multipart/form-data; boundary=${g}`,i=await this.formDataToMultipart(r.formData,g)}r.urlencoded&&(c="application/x-www-form-urlencoded",i=new URLSearchParams(r.urlencoded).toString());let u=new URL(`http://${this.server.host}:${this.server.port}${t}`);u.search=new URLSearchParams(n).toString();let f=new M(u.toString(),{method:e.toUpperCase(),body:j(e)?i:void 0,headers:{"content-type":c,...o}});f.query={...Object.fromEntries(u.searchParams.entries()),...n},f.params=d.params,f.cookies=a,f.ip=p;try{let g=await _(d.middleware,d.handler,f);return new Z(g)}catch(g){v.error(`Error processing mock request ${e} ${t}:`,g);let m=new k(500);return m.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new Z(m)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,o=[];for(let[d,i]of e.entries()){o.push(r.encode(`--${t}\r
|
|
49
|
+
`)}};var Lt={},pe=class s{commands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=v;constructor(){this.commands=new Map}static getInstance(){return new s}static setCommandsPattern(e){this.commandsPattern=e}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}async loadCommands(e){s.logger.info(`Loading commands from ${e}`);let t=await(0,nt.glob)(e,{absolute:!0,cwd:H.getCwd()});if(t.some(o=>o.endsWith(".ts")))try{let{register:o}=await import("module");o("ts-node/esm",Lt.url)}catch{s.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1)}for(let o of t){let n=await import(o).then(a=>a.default?a.default:a).catch(a=>(s.logger.error(`Error loading command ${o}: ${a}`),null));n&&this.commands.set(n.commandName,n)}let r=[B,X,L,V,te];for(let o of r)this.commands.set(o.commandName,o)}},He=pe.getInstance();var G=require("@sinclair/typebox");var ce=T(require("ajv"),1),it=T(require("ajv-formats"),1),Vt=(0,it.default)(new ce.default,["date-time","time","date","email","hostname","ipv4","ipv6","uri","uri-reference","uuid","uri-template","json-pointer","relative-json-pointer","regex","password","binary","byte","iso-date-time","iso-time"]),z=(s,e,t=!1)=>{let r=Vt.compile(s);if(!r(e)){if(t)return e;throw new ce.ValidationError(r.errors||[])}return e};var ue=class extends Request{};var at=require("crypto"),M=class s extends ue{static fromRequest(e){return new s(e.url,{method:e.method,body:e.body,headers:e.headers})}static enrichRequest(e){return e.validate=(t,r=!1)=>(typeof t=="function"&&(t=t(G.Type)),z(t,e.body||{},r)),e.validateQuery=(t,r=!1)=>(typeof t=="function"&&(t=t(G.Type)),z(t,e.query||{},r)),e.validateAll=(t,r=!1)=>(typeof t=="function"&&(t=t(G.Type)),z(t,{...e.body?{body:e.body}:{},...e.query?{query:e.query}:{}},r)),e.file=t=>e.files.find(r=>r.formName===t)??null,e.files=[],e.saveSession=async()=>{},e.destroySession=async()=>{},e.session={},e.cookies={},e.cookie=t=>e.cookies[t],e}file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};query={};get id(){return this._id||(this._id=(0,at.randomUUID)()),this._id}body;validate(e,t=!1){return typeof e=="function"&&(e=e(G.Type)),z(e,this.body||{},t)}validateQuery(e,t=!1){return typeof e=="function"&&(e=e(G.Type)),z(e,this.query||{},t)}validateAll(e,t=!1){return typeof e=="function"&&(e=e(G.Type)),z(e,{...this.body?{body:this.body}:{},...this.query?{query:this.query}:{}},t)}};var dt=T(require("fs/promises"),1),ke=class{file(e){switch(y.type){case"bun":return Bun.file(e);case"node":return dt.default.readFile(e);case"deno":return Deno.readFile(e);default:throw new Error("Unsupported runtime")}}},le=new ke;var Q=require("path");var w=s=>({name:s.constructor.name,cause:s.cause,message:s.message,stack:s.stack});var C=class extends Error{constructor(e){super(e)}};var me=class extends C{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`)}};var b=class extends C{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`)}};var pt=new Map([[".html","text/html"],[".css","text/css"],[".js","application/javascript"],[".png","image/png"],[".jpg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".json","application/json"],[".txt","text/plain"],[".ico","image/x-icon"],[".webp","image/webp"],[".mp4","video/mp4"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".webm","video/webm"]]);var _e=(s="public",e)=>(h.addOrUpdate("GET",`${s}/*`,[],async(t,r)=>zt(t,r,s),{service:"StaticFiles",...e}),async(t,r,o)=>o());async function zt(s,e,t){if(s.method!=="GET"&&s.method!=="HEAD")return e.status(405).json({...w(new me(s.url,s.method))});let r=s.params["*"]||"",o=(0,Q.join)(t,r),n=(0,Q.resolve)(H.getCwd(),o);try{if(!(await R.stat(n)).isFile)return e.notFound({...w(new b(s.url,s.method))})}catch(d){if(d.code==="ENOENT")return e.notFound({...w(new b(s.url,s.method))});throw d}let a=fe((0,Q.extname)(n));e.setHeader("Content-Type",a);let p=await le.file(n);e.raw(p)}function fe(s){return pt.get(s)||"application/octet-stream"}var k=class{responseStatus;headers;body;constructor(e=200){this.responseStatus=e,this.headers={}}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.text(String(e));if(e instanceof Date)return this.text(e.toISOString());if(e instanceof RegExp)return this.text(e.toString());if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="function")return this.text(e.toString());if(typeof e=="symbol")return this.text(e.toString());this.body=e}raw(e){this.body=e}text(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/plain"}}json(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/json"}}html(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/html"}}xml(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/xml"}}download(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/octet-stream"}}file(e){let t=fe(e),r=le.file(e);this.headers={...this.headers,"Content-Type":t}}ok(e){this.status(200).send(e)}created(e){this.status(201).send(e)}accepted(e){this.status(202).send(e)}noContent(){this.status(204).send("")}partialContent(e){this.status(206).send(e)}multipleChoices(e){this.status(300).setHeader("Location",e)}redirect(e){this.status(302).setHeader("Location",e)}movedPermanently(e){this.status(301).setHeader("Location",e)}found(e){this.status(302).setHeader("Location",e)}seeOther(e){this.status(303).setHeader("Location",e)}notModified(){this.status(304).send("")}temporaryRedirect(e){this.status(307).setHeader("Location",e)}permanentRedirect(e){this.status(308).setHeader("Location",e)}badRequest(e){this.status(400).send(e)}unauthorized(e){this.status(401).send(e)}forbidden(e){this.status(403).send(e)}notFound(e){this.status(404).send(e)}methodNotAllowed(e){this.status(405).send(e)}notAcceptable(e){this.status(406).send(e)}conflict(e){this.status(409).send(e)}gone(e){this.status(410).send(e)}payloadTooLarge(e){this.status(413).send(e)}unsupportedMediaType(e){this.status(415).send(e)}unprocessableEntity(e){this.status(422).send(e)}tooManyRequests(e){this.status(429).send(e)}internalServerError(e){this.status(500).send(e)}notImplemented(e){this.status(501).send(e)}badGateway(e){this.status(502).send(e)}serviceUnavailable(e){this.status(503).send(e)}gatewayTimeout(e){this.status(504).send(e)}httpVersionNotSupported(e){this.status(505).send(e)}getBody(){return this.body}};var xt=require("glob"),Je=require("path");var ct=require("glob");var K=class{static scheduledJobs=[];static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t})}static async run(){let e=(await import("node-cron").catch(()=>{throw new C("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(v.info("Scheduling cron jobs"),!this.scheduledJobs.length){v.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)v.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));v.info("Cron jobs scheduled")}static globalErrorHandler(e){v.error(e.execution?.error)}static async massiveImportCronJobs(e){let t=[];for(let r of e){let o=await(0,ct.glob)(r,{absolute:!0,cwd:H.getCwd()});t.push(...o)}await Promise.all(t.map(async r=>{await import(r).catch(o=>{v.error(`Error importing cron job: ${r}`),v.error(o)})}))}};var Z=class{constructor(e){this.response=e}body(){return this.response.getBody()}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let o in t){let n=r===""?o:`${r}.${o}`,a=e[o],p=t[o];if(!(o in e))throw new Error(`Expected ${r} to have key ${o}, but it was not found`);if(this.isObject(p)&&this.isObject(a))this.assertSubset(a,p,n);else if(Array.isArray(p)&&Array.isArray(a))this.assertArraySubset(a,p,n);else if(a!==p)throw new Error(`Expected ${n} to be ${p}, but got ${a}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${o.length}`);for(let a of n){let p=r==="body"?a:`${r}.${a}`;this.assertDeepEqual(e[a],t[a],p)}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`,a=e[o],p=t[o];if(this.isObject(p)&&this.isObject(a))this.assertSubset(a,p,n);else if(Array.isArray(p)&&Array.isArray(a))this.assertArraySubset(a,p,n);else if(a!==p)throw new Error(`Expected ${n} to be ${p}, but got ${a}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`;this.assertDeepEqual(e[o],t[o],n)}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var _=async(s,e,t,r=new k)=>{let o=0;if(!s.length)return await e(t,r),r;let n=async()=>{if(o++,o>=s.length){await e(t,r);return}let p=s[o];await p(t,r,n)},a=s[0];return await a(t,r,n),r},j=s=>s?["post","put","patch","delete"].includes(s.toLowerCase()):!0;var he=class{server;constructor(e){this.server=e}async request(e,t,r={}){let{headers:o={},query:n={},cookies:a={},ip:p}=r;this.validateOptions(r);let d=h.find(e.toUpperCase(),t);if(!d){let g=new k(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new Z(g)}let i=r.body,c="application/json";if(i&&typeof i=="object"&&!(i instanceof Uint8Array)&&!(i instanceof ArrayBuffer)&&(i=JSON.stringify(i)),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;c=`multipart/form-data; boundary=${g}`,i=await this.formDataToMultipart(r.formData,g)}r.urlencoded&&(c="application/x-www-form-urlencoded",i=new URLSearchParams(r.urlencoded).toString());let u=new URL(`http://${this.server.host}:${this.server.port}${t}`);u.search=new URLSearchParams(n).toString();let f=new M(u.toString(),{method:e.toUpperCase(),body:j(e)?i:void 0,headers:{"content-type":c,...o}});f.query={...Object.fromEntries(u.searchParams.entries()),...n},f.params=d.params,f.cookies=a,f.ip=p;try{let g=await _(d.middleware,d.handler,f);return new Z(g)}catch(g){v.error(`Error processing mock request ${e} ${t}:`,g);let m=new k(500);return m.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new Z(m)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,o=[];for(let[d,i]of e.entries()){o.push(r.encode(`--${t}\r
|
|
47
50
|
`));let c=`Content-Disposition: form-data; name="${d}"`,u="";if(i instanceof File&&(c+=`; filename="${i.name}"`,u=`Content-Type: ${i.type||"application/octet-stream"}\r
|
|
48
51
|
`),o.push(r.encode(`${c}\r
|
|
49
52
|
${u}\r
|
|
50
53
|
`)),i instanceof File){let f=await i.arrayBuffer();o.push(new Uint8Array(f)),o.push(r.encode(`\r
|
|
51
54
|
`))}else o.push(r.encode(`${String(i)}\r
|
|
52
55
|
`))}o.push(r.encode(`--${t}--\r
|
|
53
|
-
`));let n=o.reduce((d,i)=>d+i.byteLength,0),a=new Uint8Array(n),p=0;for(let d of o)a.set(d,p),p+=d.byteLength;return a}validateOptions(e){let{body:t,formData:r,urlencoded:o}=e;if(t&&(r||o))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(o||t))throw new Error("Only one of formData, urlencoded can be provided");if(o&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var je=s=>{let e={secret:s?.secret??"",defaults:{path:"/",httpOnly:!0,secure:!1,sameSite:"Lax",...s?.defaults},parse:s?.parse??!0,sign:s?.sign??!1};return async(t,r,o)=>{if(e.parse){let n=
|
|
54
|
-
`).find(ne=>ne.toLowerCase().startsWith("content-disposition:"));if(
|
|
55
|
-
`).find(Ct=>Ct.toLowerCase().startsWith("content-type:")),Ot=ne?ne.split(":")[1].trim():"application/octet-stream",Tt=(0,we.extname)(F),Oe=(0,we.join)((0,vt.tmpdir)(),`${
|
|
56
|
+
`));let n=o.reduce((d,i)=>d+i.byteLength,0),a=new Uint8Array(n),p=0;for(let d of o)a.set(d,p),p+=d.byteLength;return a}validateOptions(e){let{body:t,formData:r,urlencoded:o}=e;if(t&&(r||o))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(o||t))throw new Error("Only one of formData, urlencoded can be provided");if(o&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var je=s=>{let e={secret:s?.secret??"",defaults:{path:"/",httpOnly:!0,secure:!1,sameSite:"Lax",...s?.defaults},parse:s?.parse??!0,sign:s?.sign??!1};return async(t,r,o)=>{if(e.parse){let n=Gt(t.headers.get("cookie")||"");t.cookies={};for(let[a,p]of Object.entries(n)){if(e.sign&&e.secret){let d=await Yt(p,e.secret);d!==!1&&(t.cookies[a]=d);continue}t.cookies[a]=p}}r.cookie=(n,a,p)=>{ut(r,n,a,{...e.defaults,...p},e)},r.clearCookie=(n,a)=>{Jt(r,n,{...e.defaults,...a})},await o()}};function Gt(s){let e={};if(!s)return e;let t=s.split(";");for(let r of t){let[o,n]=r.trim().split("=");o&&n&&(e[decodeURIComponent(o)]=decodeURIComponent(n))}return e}async function ut(s,e,t,r,o){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires&&(n+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(n+=`; Max-Age=${r.maxAge}`),r.secure&&(n+="; Secure"),r.httpOnly&&(n+="; HttpOnly"),r.sameSite&&(n+=`; SameSite=${r.sameSite}`),r.priority&&(n+=`; Priority=${r.priority}`),o.sign&&o.secret&&(n=await Wt(n,o.secret));let a=s.headers["set-cookie"]||"",p=a?`${a}, ${n}`:n;s.setHeader("Set-Cookie",p)}function Jt(s,e,t){let r={...t,expires:new Date(0),maxAge:0};ut(s,e,"",r,{secret:"",defaults:{},parse:!0,sign:!1})}async function Wt(s,e){let t=new TextEncoder,r=t.encode(e),o=t.encode(s),n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",n,o),p=new Uint8Array(a),d=Array.from(p).map(i=>i.toString(16).padStart(2,"0")).join("");return`${s}.${d}`}async function Yt(s,e){let t=s.split(".");if(t.length!==2)return!1;let[r,o]=t,n=new TextEncoder,a=n.encode(e),p=n.encode(r),d=await crypto.subtle.importKey("raw",a,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",d,p),c=new Uint8Array(i),u=Array.from(c).map(f=>f.toString(16).padStart(2,"0")).join("");return o===u?r:!1}var Ne=s=>async(e,t,r)=>{try{let o=e.body;(s?.logRequest??!0)&&v.info({type:"request",requestId:e.id,method:s?.requestPayload?.method??!0?e.method:void 0,url:s?.requestPayload?.url??!0?e.url:void 0,ip:s?.requestPayload?.ip??!0?e.ip:void 0,headers:s?.requestPayload?.headers??!0?e.headers:void 0,body:s?.requestPayload?.body??!1?lt(o):void 0}),await r(),(s?.logResponse??!0)&&v.info({type:"response",requestId:e.id,status:s?.responsePayload?.status??t.responseStatus,body:s?.responsePayload?.body??!1?lt(t.getBody()):void 0,headers:s?.responsePayload?.headers??!1?t.headers:void 0})}catch(o){throw v.error(o),o}};function lt(s){if(typeof s=="string"||s&&typeof s=="object"&&s.constructor===Object)return s}var ge=class{storage=new Map;windowMs;constructor(e){this.windowMs=e}async set(e,t){this.storage.set(e,t),setTimeout(()=>{this.storage.delete(e)},this.windowMs)}async get(e){let t=this.storage.get(e);return t||0}async delete(e){this.storage.delete(e)}};var De=(s,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...s},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let o=r.type==="memory"?new ge(r.windowMs):{get:r.get,set:r.set};return async(n,a,p)=>{let d=t.type==="ip"?n.ip:t.key(n),i=await o.get(d);return i>=t.limit?a.status(t.statusCode).json({message:t.message}):(await o.set(d,i+1),p())}};var mt=require("crypto");var ye=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let o=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:o})}async destroy(e){this.store.delete(e)}};var Ue=s=>{let e=s?.name??"sid",t=s?.ttl??60*60*24,r=s?.store??new ye,o={path:"/",httpOnly:!0,secure:!1,sameSite:"Lax",...s?.cookie??{}};return async(n,a,p)=>{let i=n.cookies&&n.cookies[e],c=i?await r.get(i):void 0;(!i||!c)&&(i||=(0,mt.randomUUID)(),c||={},await r.set(i,c,t),a.cookie?.(e,i,o)),n.session=c,n.saveSession=async()=>r.set(i,c,t),n.destroySession=async()=>{await r.destroy(i),a.clearCookie?.(e,o)},await p(),await r.set(i,c,t)}};var Ie=s=>async(e,t,r)=>{e.timeout=!1;let o=setTimeout(()=>{e.timeout=!0},s.ms);try{await r()}finally{clearTimeout(o)}};var qe=s=>{let e=s?.header??"x-forwarded-for",t=s?.trust??!0,r=s?.hop??"first";return async(o,n,a)=>{if(!t)return a();let p=o.headers.get(e);if(p&&typeof p=="string"){let d=p.split(",").map(i=>i.trim()).filter(Boolean);d.length&&(o.ip=r==="first"?d[0]:d[d.length-1])}return a()}};var Be=s=>{let e={limit:1048576,extended:!1,charset:"utf8",allowEmpty:!0,parameterLimit:1e3,...s};return async(t,r,o)=>{if(!(t.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return o();try{await Xt(t,e),await o()}catch(a){if(a instanceof Error&&a.message.includes("limit")){r.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw a}}};async function Xt(s,e){let t=s.rawBody;if(t.byteLength>e.limit)throw new Error(`Body size ${t.byteLength} exceeds limit ${e.limit}`);let o=new TextDecoder(e.charset).decode(t),n=Qt(o,e);s.body=n}function Qt(s,e){let t={},r=new URLSearchParams(s);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[o,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?Kt(t,o,n):t[o]=n);return t}function Kt(s,e,t){let r=e.match(/\[([^\]]*)\]/g);if(!r){s[e]=t;return}let o=s,n=e.split("[")[0];for(let p=0;p<r.length-1;p++){let d=r[p].slice(1,-1);if(o[n]||(o[n]={}),d===""){Array.isArray(o[n])||(o[n]=[]),o=o[n];continue}o[n][d]||(o[n][d]={}),o=o[n][d]}let a=r[r.length-1].slice(1,-1);if(a===""){Array.isArray(o)||(o=[]),o.push(t);return}o[a]=t}var ft=()=>async(s,e,t)=>(j(s.method)&&(s.rawBody=await s.arrayBuffer(),Object.defineProperty(s,"body",{value:void 0,writable:!0,configurable:!0,enumerable:!0})),t());var Le=s=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:!1,maxAge:void 0,preflightContinue:!1,optionsSuccessStatus:204,...s};return async(t,r,o)=>{let n=t.headers.get("origin")||"";if(t.method==="OPTIONS")return Zt(t,r,e,n,o);er(t,r,e,n),await o()}};function Zt(s,e,t,r,o){let n=ht(t,r);if(!n){e.forbidden("CORS origin not allowed");return}if(gt(e,t,n),t.preflightContinue){o();return}e.status(t.optionsSuccessStatus||204),e.send("")}function er(s,e,t,r){let o=ht(t,r);o&>(e,t,o)}function ht(s,e){if(typeof s.origin=="string")return s.origin;if(Array.isArray(s.origin)){let t=s.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:!1}return"*"}function gt(s,e,t){if(s.setHeader("Access-Control-Allow-Origin",t),e.credentials&&s.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let o=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;s.setHeader("Access-Control-Expose-Headers",o)}if(e.allowedHeaders&&e.allowedHeaders!==""){let o=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;s.setHeader("Access-Control-Allow-Headers",o)}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;s.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&s.setHeader("Access-Control-Max-Age",e.maxAge.toString())}var vt=require("os"),we=require("path");var ve=class extends C{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`)}};var Ve=s=>async(e,t,r)=>{let o=[];try{let n=e.headers.get("content-type")??e.headers.get("Content-Type");if(!n||!n.startsWith("multipart/form-data")||!e.rawBody)return r();let a=n.match(/boundary=(.*)(;|$)/i);if(!a)return r();let p=a[1].replace(/(^\s*"?|"?\s*$)/g,""),d=new Uint8Array(e.rawBody),i=new TextEncoder().encode(`--${p}`),c=new Uint8Array([13,10,13,10]),u=[],f=(S,$,J=0)=>{e:for(let A=J;A<=S.length-$.length;A++){for(let E=0;E<$.length;E++)if(S[A+E]!==$[E])continue e;return A}return-1},g=f(d,i);for(;g!==-1&&(g+=i.length,!(d[g]===45&&d[g+1]===45));){d[g]===13&&d[g+1]===10&&(g+=2);let S=f(d,c,g);if(S===-1)break;let $=d.subarray(g,S),J=new TextDecoder().decode($),A=S+c.length,E=f(d,i,A);if(E===-1)break;let F=E-1;d[F]===10&&F--,d[F]===13&&F--;let Xe=d.subarray(A,F+1);u.push({headers:J,data:Xe}),g=E}let m=[],x={};for(let S of u){let $=S.headers.split(`\r
|
|
57
|
+
`).find(ne=>ne.toLowerCase().startsWith("content-disposition:"));if(!$)continue;let J=$.match(/name="([^"]+)"/);if(!J)continue;let A=J[1],E=$.match(/filename="([^"]*)"/),F=E?E[1]:"";if(!!F){if(s?.maxFileSize&&S.data.length>s.maxFileSize)return t.badRequest({...w(new ve(F,S.data.length,s.maxFileSize))});let ne=S.headers.split(`\r
|
|
58
|
+
`).find(Ct=>Ct.toLowerCase().startsWith("content-type:")),Ot=ne?ne.split(":")[1].trim():"application/octet-stream",Tt=(0,we.extname)(F),Oe=(0,we.join)((0,vt.tmpdir)(),`${tr(10)}${Tt}`);await R.writeFile(Oe,S.data),o.push(Oe),m.push({formName:A,mimeType:Ot,size:S.data.length,tmpPath:Oe,originalName:F})}else x[A]=new TextDecoder().decode(S.data)}e.files=m,e.body=x,await r(),await yt(o)}catch(n){throw await yt(o),n}};async function yt(s){await Promise.allSettled(s.map(e=>R.unlink(e)))}function tr(s){return Math.random().toString(36).substring(2,2+s)}var ze=s=>{let e={dnsPrefetchControl:!0,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:!0,preload:!1},contentTypeOptions:!0,ieNoOpen:!0,xssFilter:!0,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:!1,...s};return async(t,r,o)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let n="SAMEORIGIN";typeof e.frameguard=="object"&&(n=e.frameguard.action),r.setHeader("X-Frame-Options",n)}if(e.hsts){let n={};typeof e.hsts=="object"&&(n=e.hsts);let a=n.maxAge!==void 0?n.maxAge:15552e3,p=n.includeSubDomains!==void 0?n.includeSubDomains:!0,d=n.preload!==void 0?n.preload:!1,i=`max-age=${a}`;p!==!1&&(i+="; includeSubDomains"),d&&(i+="; preload"),r.setHeader("Strict-Transport-Security",i)}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await o()}};var re=class extends C{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`)}};var Ge=s=>async(e,t,r)=>{if(!rr(e)||!j(e.method))return r();let o=s?.sizeLimit??5*1024*1024,n=e.rawBody;if(!n)return s?.parseEmptyBodyAsObject&&(e.body={}),r();let a=n.byteLength;if(!a)return s?.parseEmptyBodyAsObject&&(e.body={}),r();if(a>o){let p={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...s?.customErrorMessage};return t.status(p.status).json({error:p.message})}try{let p=s?.encoding??"utf-8",d=new TextDecoder(p).decode(n);e.body=JSON.parse(d)}catch(p){return p instanceof SyntaxError?t.badRequest({...w(new re("Invalid JSON syntax"))}):t.badRequest({...w(new re("Invalid request body encoding"))})}await r()};function rr(s){let e=sr(s);return e?or(e)==="application/json":!1}function sr(s){let e=s.headers.get("content-type")??s.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function or(s){let e=s.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var St=s=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};typeof s!="boolean"&&(e={...e,...s});let t=nr(e),r=`${e.path}`,o=`${r}/json`,n=e.type==="redoc"?ar(o,e):e.type==="rapidoc"?dr(o,e):ir(o,e);h.addOrUpdate("GET",r,[],(a,p)=>{p.html(n)}),h.addOrUpdate("GET",o,[],(a,p)=>{p.json(t)})};function nr(s){let e=h.getRoutes(),t={},r={...s.components,securitySchemes:s.securitySchemes||{},schemas:s.models?{...s.components?.schemas||{},...s.models}:s.components?.schemas?{...s.components.schemas}:void 0};for(let o of e){let n=o.swaggerOptions;if(n?.excludeFromSwagger)continue;t[o.path]||(t[o.path]={});let a=o.method.toLowerCase(),p={summary:n?.name||`${a.toUpperCase()} ${o.path}`,description:n?.description||"",tags:n?.service?[n.service]:[],deprecated:n?.deprecated||!1},d=[];if(n?.query&&n.query.type==="object"&&n.query.properties)for(let[i,c]of Object.entries(n.query.properties))d.push({name:i,in:"query",required:Array.isArray(n.query.required)?n.query.required.includes(i):!1,schema:se(c)});if(n&&n.params?d=d.concat(wt(o.path,n.params)):d=d.concat(wt(o.path)),d.length>0&&(p.parameters=d),n?.requestBody){let i="application/json";n.bodyType==="form-data"?i="multipart/form-data":n.bodyType==="urlencoded"&&(i="application/x-www-form-urlencoded"),p.requestBody={content:{[i]:{schema:se(n.requestBody)}},required:!0}}else n?.bodyType&&(n.bodyType.includes("form-data")||n.bodyType.includes("urlencoded"))&&(p.requestBody={content:{[n.bodyType]:{schema:{type:"object"}}},required:!0});if(p.responses={},n?.responses)for(let[i,c]of Object.entries(n.responses))p.responses[i]={description:`Response for ${i}`,content:{"application/json":{schema:se(c)}}};if(n?.errors)for(let[i,c]of Object.entries(n.errors))p.responses[i]={description:`Error response for ${i}`,content:{"application/json":{schema:se(c)}}};if(Object.keys(p.responses).length===0&&(p.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),n?.security){let i=[];Array.isArray(n.security)||(n.security=[n.security]);for(let c of n.security)if(c.type==="bearer")r.securitySchemes.bearer||(r.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:c.bearerFormat||"JWT",description:c.description}),i.push({bearer:[]});else if(c.type==="apiKey")r.securitySchemes[c.name]||(r.securitySchemes[c.name]={type:"apiKey",name:c.name,in:c.in,description:c.description}),i.push({[c.name]:[]});else if(c.type==="oauth2"){let u=c.name||"oauth2";r.securitySchemes[u]||(r.securitySchemes[u]={type:"oauth2",flows:c.flows,description:c.description}),i.push({[u]:[]})}else if(c.type==="openIdConnect"){let u=c.name||"openIdConnect";r.securitySchemes[u]||(r.securitySchemes[u]={type:"openIdConnect",openIdConnectUrl:c.openIdConnectUrl,description:c.description}),i.push({[u]:[]})}i.length&&(p.security=i)}else s.security&&(p.security=s.security);t[o.path][a]=p}return{openapi:"3.0.0",info:{title:s.title,description:s.description,version:s.version,...s.info},servers:s.servers?.map(o=>({url:o}))||[{url:"/"}],paths:t,components:r,security:s.security||[],tags:s.tags?Object.entries(s.tags).map(([o,n])=>({name:o,...n})):[]}}function ir(s,e){return`
|
|
56
59
|
<!DOCTYPE html>
|
|
57
60
|
<html lang="en">
|
|
58
61
|
<head>
|
|
@@ -100,7 +103,7 @@ ${u}\r
|
|
|
100
103
|
};
|
|
101
104
|
</script>
|
|
102
105
|
</body>
|
|
103
|
-
</html>`}function
|
|
106
|
+
</html>`}function ar(s,e){return`
|
|
104
107
|
<!DOCTYPE html>
|
|
105
108
|
<html>
|
|
106
109
|
<head>
|
|
@@ -118,7 +121,7 @@ ${u}\r
|
|
|
118
121
|
<script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"></script>
|
|
119
122
|
</body>
|
|
120
123
|
</html>
|
|
121
|
-
`}function
|
|
124
|
+
`}function dr(s,e){return`
|
|
122
125
|
<!DOCTYPE html>
|
|
123
126
|
<html>
|
|
124
127
|
<head>
|
|
@@ -149,5 +152,5 @@ ${u}\r
|
|
|
149
152
|
<script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
|
|
150
153
|
</body>
|
|
151
154
|
</html>
|
|
152
|
-
`}function se(s){if(!s)return;let{$id:e,$schema:t,...r}=s;return r}function wt(s,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,o;for(;(o=r.exec(s))!==null;){let n=o[1],a={type:"string"};e&&e.type==="object"&&e.properties&&e.properties[n]&&(a=se(e.properties[n])||{type:"string"}),t.push({name:n,in:"path",required:!0,schema:a})}return t}var Se=class{port;hostname;host;routes;tapOptions;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions}listen(){let e=this.tapOptions?.options,{fetch:t,...r}=e??{};this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(o,n)=>{let a=new URL(o.url),p=h.find(o.method,a.pathname);M.enrichRequest(o),o.params=p?.params??{},o.query=Object.fromEntries(a.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.requestIP(o)?.address,await t?.call(this,o,n);let d=await _(p?.middleware??[],p?.handler??((c,u)=>{u.notFound({...w(new b(c.url,c.method))})}),o);return d.headers["Content-Type"]==="application/json"?Response.json(d.getBody(),{status:d.responseStatus,headers:d.headers}):new Response(d.getBody(),{status:d.responseStatus,headers:d.headers})},...r}),this.url=this.runtimeServer.url.toString()}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.stop()}};var Re=class{constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions}listen(){let e=this.tapOptions?.options,{handler:t,...r}=e??{};this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(o,n)=>{let a=new URL(o.url),p=h.find(o.method,a.pathname);M.enrichRequest(o),o.params=p?.params??{},o.query=Object.fromEntries(a.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.remoteAddr?.hostname,await t?.(o,n);let d=await _(p?.middleware??[],p?.handler??((c,u)=>{u.notFound({...w(new b(c.url,c.method))})}),o);return d.headers["Content-Type"]==="application/json"?Response.json(d.getBody(),{status:d.responseStatus,headers:d.headers}):new Response(d.getBody(),{status:d.responseStatus,headers:d.headers})},...r}),this.url=`http://${this.host}:${this.port}`}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.shutdown()}};var Rt=require("http");async function dr(s,e){let t=s.getReader();try{for(;;){let{done:r,value:o}=await t.read();if(r){e.end();break}e.write(o)}}catch(r){e.destroy(r)}}var be=class{port;host;url;routes;tapOptions;runtimeServer;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.runtimeServer=(0,Rt.createServer)(async(t,r)=>{if(this.tapOptions){let{options:u}=this.tapOptions;await u?.(t)}let o=h.find(t.method,t.url),n=new M(`${this.url}${t.url}`,{method:t.method,body:j(t.method)?await this.readRequestBody(t):void 0,headers:t.headers}),a=t.headers["x-forwarded-for"];Array.isArray(a)&&(a=a[0]),n.ip=a??t.socket.remoteAddress;let[p,d=""]=t.url?.split("?",2)??[];n.query=Object.fromEntries(new URLSearchParams(d)),n.params=o?.params??{};let i=await _(o?.middleware??[],o?.handler??((u,f)=>{f.notFound({...w(new b(u.url,u.method))})}),n),c=i.getBody();if(c instanceof ReadableStream){dr(c,r);return}c instanceof Buffer||c instanceof Uint8Array||typeof c=="string"?c=c:i.headers["Content-Type"]==="application/json"?c=JSON.stringify(c):c=String(c),r.writeHead(i.responseStatus,i.headers),r.end(c)})}listen(){this.runtimeServer.listen(this.port,this.host)}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e()})})}async readRequestBody(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>o.push(Buffer.from(n))),e.on("error",r),e.on("end",()=>t(Buffer.concat(o).toString()))})}};var xe=class{server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Se(e);if(e?.runtime==="node")return new be(e);if(e?.runtime==="deno")return new Re(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};var bt=["isListening","url","port","host","routes","embed","constructor","get","post","put","patch","delete","getNodeServer","getBunServer","getDenoServer","use","setErrorHandler","listen","close","tapOptions","startUpOptions","tmpDir","logger","getMockServer"];var oe=class{get(e){switch(y.type){case"node":return process.env[e]??"";case"bun":return Bun.env[e]??"";case"deno":return Deno.env.get(e)??"";default:throw new Error(`Unsupported runtime: ${y.type}`)}}};var We=class{isListening;router=h;wasInitialized;serverConnector;globalMiddlewares=[];serverOptions;controllerImportBlacklistedPaths=["node_modules"];constructor(e){this.wasInitialized=!1,this.serverOptions={port:e?.port??Number(new oe().get("PORT"))??80,host:e?.host??new oe().get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??!0,useBodyParser:e?.useBodyParser??!0},this.serverConnector=new xe({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:y.type}),this.serverOptions.useBodyParser&&this.use(ft()),this.isListening=!1}get url(){return this.serverConnector.url}get port(){return this.serverConnector.port}get host(){return this.serverConnector.host}get routes(){return h.getRoutes()}tmpDir(...e){let t="tmp";return e?(0,Je.join)(t,...e):(0,Je.join)(H.getCwd(),t)}get(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("GET",e,o,n,a)}post(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("POST",e,o,n,a)}patch(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("PATCH",e,o,n,a)}put(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("PUT",e,o,n,a)}delete(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("DELETE",e,o,n,a)}options(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("OPTIONS",e,o,n,a)}group(e,t,r){this.router.group(e,t,r)}getNodeServer(){if(y.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.serverConnector.getServer("node")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(bt.includes(e))throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property.`);Object.defineProperty(this,e,{value:t,writable:!1,configurable:!0,enumerable:!0})}exit(e=0){switch(y.type){case"bun":case"node":process.exit(e);case"deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${y.type}`)}}on(e,t){switch(y.type){case"bun":case"node":process.on(e,t);break;case"deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${y.type}, only node, bun and deno are supported`)}}once(e,t){switch(y.type){case"bun":case"node":process.once(e,t);break;case"deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${y.type}, only node, bun and deno are supported`)}}use(...e){this.globalMiddlewares.push(...e)}setErrorHandler(e){this.globalMiddlewares.unshift(async(t,r,o)=>{try{await o()}catch(n){await e?.(t,r,o,n)}})}setGlobalCronErrorHandler(e){K.globalErrorHandler=e}startRegisteredCrons=async(e,t)=>{e?.length&&await K.massiveImportCronJobs(e),K.run().then(()=>{t?.()})};listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");this.bootstrap().then(()=>{this.serverConnector.listen(),this.isListening=!0,this.serverOptions.swagger&&St(this.serverOptions.swagger),e?.({port:this.port,host:this.host,url:this.url})})}async close(){await this.serverConnector.close(),this.isListening=!1}async getMockServer(){return await this.bootstrap(),new he(this)}async importControllers(){let e=this.serverOptions.controllerPatterns,t=await Promise.all(e.map(async r=>(0,xt.glob)(r,{absolute:!0,cwd:H.getCwd()}))).then(r=>r.flat());t=t.flat(),t=t.filter(r=>!this.controllerImportBlacklistedPaths.some(o=>r.includes(o))),v.debug(`Found ${t.length} controllers to import`),await Promise.all(t.map(async r=>{v.debug(`Importing controller ${r}`),await import(r).catch(o=>{v.error(`Error importing controller ${r}: ${o}`)})}))}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return{middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return{middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case"cors":this.use(Le(r));break;case"json":this.use(Ge(r));break;case"static":this.use(_e(r));break;case"fileParser":this.use(Ve(r));break;case"helmet":this.use(ze(r));break;case"cookie":this.use(je(r));break;case"log":this.use(Ne(r));break;case"rateLimiter":let{keyOptions:o,storageOptions:n}=r;this.use(De(o,n));break;case"urlencoded":this.use(Be(r));break;case"trustProxy":this.use(qe(r));break;case"timeout":this.use(Ie(r));break;case"session":this.use(Ue(r));break;default:v.warn(`Unknown plugin ${t}`);break}})}async bootstrap(){this.wasInitialized||(await this.importControllers(),this.applyPlugins(this.serverOptions.plugins),this.registerNotFoundRoutes(),this.globalMiddlewares.length&&h.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares),this.wasInitialized=!0)}registerNotFoundRoutes(){h.addOrUpdate("GET","*",[],(e,t)=>{let r=new b(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("POST","*",[],(e,t)=>{let r=new b(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("PUT","*",[],(e,t)=>{let r=new b(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("PATCH","*",[],(e,t)=>{let r=new b(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("DELETE","*",[],(e,t)=>{let r=new b(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0})}};var Ye=class{};var pr=h;0&&(module.exports={BasePlugin,Command,CommandRegistry,Request,Response,Server,commandRegistry,controller,cookie,cors,del,fileParser,get,getContentType,helmet,json,log,middleware,patch,post,put,rateLimiter,router,serveStatic,session,timeout,trustProxy,urlencoded,validate});
|
|
155
|
+
`}function se(s){if(!s)return;let{$id:e,$schema:t,...r}=s;return r}function wt(s,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,o;for(;(o=r.exec(s))!==null;){let n=o[1],a={type:"string"};e&&e.type==="object"&&e.properties&&e.properties[n]&&(a=se(e.properties[n])||{type:"string"}),t.push({name:n,in:"path",required:!0,schema:a})}return t}var Se=class{port;hostname;host;routes;tapOptions;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions}listen(){let e=this.tapOptions?.options,{fetch:t,...r}=e??{};this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(o,n)=>{let a=new URL(o.url),p=h.find(o.method,a.pathname);M.enrichRequest(o),o.params=p?.params??{},o.query=Object.fromEntries(a.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.requestIP(o)?.address,await t?.call(this,o,n);let d=await _(p?.middleware??[],p?.handler??((c,u)=>{u.notFound({...w(new b(c.url,c.method))})}),o);return d.headers["Content-Type"]==="application/json"?Response.json(d.getBody(),{status:d.responseStatus,headers:d.headers}):new Response(d.getBody(),{status:d.responseStatus,headers:d.headers})},...r}),this.url=this.runtimeServer.url.toString()}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.stop()}};var Re=class{constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions}listen(){let e=this.tapOptions?.options,{handler:t,...r}=e??{};this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(o,n)=>{let a=new URL(o.url),p=h.find(o.method,a.pathname);M.enrichRequest(o),o.params=p?.params??{},o.query=Object.fromEntries(a.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.remoteAddr?.hostname,await t?.(o,n);let d=await _(p?.middleware??[],p?.handler??((c,u)=>{u.notFound({...w(new b(c.url,c.method))})}),o);return d.headers["Content-Type"]==="application/json"?Response.json(d.getBody(),{status:d.responseStatus,headers:d.headers}):new Response(d.getBody(),{status:d.responseStatus,headers:d.headers})},...r}),this.url=`http://${this.host}:${this.port}`}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.shutdown()}};var Rt=require("http");async function pr(s,e){let t=s.getReader();try{for(;;){let{done:r,value:o}=await t.read();if(r){e.end();break}e.write(o)}}catch(r){e.destroy(r)}}var be=class{port;host;url;routes;tapOptions;runtimeServer;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.runtimeServer=(0,Rt.createServer)(async(t,r)=>{if(this.tapOptions){let{options:u}=this.tapOptions;await u?.(t)}let o=h.find(t.method,t.url),n=new M(`${this.url}${t.url}`,{method:t.method,body:j(t.method)?await this.readRequestBody(t):void 0,headers:t.headers}),a=t.headers["x-forwarded-for"];Array.isArray(a)&&(a=a[0]),n.ip=a??t.socket.remoteAddress;let[p,d=""]=t.url?.split("?",2)??[];n.query=Object.fromEntries(new URLSearchParams(d)),n.params=o?.params??{};let i=await _(o?.middleware??[],o?.handler??((u,f)=>{f.notFound({...w(new b(u.url,u.method))})}),n),c=i.getBody();if(c instanceof ReadableStream){pr(c,r);return}c instanceof Buffer||c instanceof Uint8Array||typeof c=="string"?c=c:i.headers["Content-Type"]==="application/json"?c=JSON.stringify(c):c=String(c),r.writeHead(i.responseStatus,i.headers),r.end(c)})}listen(){this.runtimeServer.listen(this.port,this.host)}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e()})})}async readRequestBody(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>o.push(Buffer.from(n))),e.on("error",r),e.on("end",()=>t(Buffer.concat(o).toString()))})}};var xe=class{server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Se(e);if(e?.runtime==="node")return new be(e);if(e?.runtime==="deno")return new Re(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};var bt=["isListening","url","port","host","routes","embed","constructor","get","post","put","patch","delete","getNodeServer","getBunServer","getDenoServer","use","setErrorHandler","listen","close","tapOptions","startUpOptions","tmpDir","logger","getMockServer"];var oe=class{get(e){switch(y.type){case"node":return process.env[e]??"";case"bun":return Bun.env[e]??"";case"deno":return Deno.env.get(e)??"";default:throw new Error(`Unsupported runtime: ${y.type}`)}}};var We=class{isListening;router=h;wasInitialized;serverConnector;globalMiddlewares=[];serverOptions;controllerImportBlacklistedPaths=["node_modules"];constructor(e){this.wasInitialized=!1,this.serverOptions={port:e?.port??Number(new oe().get("PORT"))??80,host:e?.host??new oe().get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??!0,useBodyParser:e?.useBodyParser??!0},this.serverConnector=new xe({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:y.type}),this.serverOptions.useBodyParser&&this.use(ft()),this.isListening=!1}get url(){return this.serverConnector.url}get port(){return this.serverConnector.port}get host(){return this.serverConnector.host}get routes(){return h.getRoutes()}tmpDir(...e){let t="tmp";return e?(0,Je.join)(t,...e):(0,Je.join)(H.getCwd(),t)}get(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("GET",e,o,n,a)}post(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("POST",e,o,n,a)}patch(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("PATCH",e,o,n,a)}put(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("PUT",e,o,n,a)}delete(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("DELETE",e,o,n,a)}options(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("OPTIONS",e,o,n,a)}group(e,t,r){this.router.group(e,t,r)}getNodeServer(){if(y.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.serverConnector.getServer("node")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(bt.includes(e))throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property.`);Object.defineProperty(this,e,{value:t,writable:!1,configurable:!0,enumerable:!0})}exit(e=0){switch(y.type){case"bun":case"node":process.exit(e);case"deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${y.type}`)}}on(e,t){switch(y.type){case"bun":case"node":process.on(e,t);break;case"deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${y.type}, only node, bun and deno are supported`)}}once(e,t){switch(y.type){case"bun":case"node":process.once(e,t);break;case"deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${y.type}, only node, bun and deno are supported`)}}use(...e){this.globalMiddlewares.push(...e)}setErrorHandler(e){this.globalMiddlewares.unshift(async(t,r,o)=>{try{await o()}catch(n){await e?.(t,r,o,n)}})}setGlobalCronErrorHandler(e){K.globalErrorHandler=e}startRegisteredCrons=async(e,t)=>{e?.length&&await K.massiveImportCronJobs(e),K.run().then(()=>{t?.()})};listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");this.bootstrap().then(()=>{this.serverConnector.listen(),this.isListening=!0,this.serverOptions.swagger&&St(this.serverOptions.swagger),e?.({port:this.port,host:this.host,url:this.url})})}async close(){await this.serverConnector.close(),this.isListening=!1}async getMockServer(){return await this.bootstrap(),new he(this)}async importControllers(){let e=this.serverOptions.controllerPatterns,t=await Promise.all(e.map(async r=>(0,xt.glob)(r,{absolute:!0,cwd:H.getCwd()}))).then(r=>r.flat());t=t.flat(),t=t.filter(r=>!this.controllerImportBlacklistedPaths.some(o=>r.includes(o))),v.debug(`Found ${t.length} controllers to import`),await Promise.all(t.map(async r=>{v.debug(`Importing controller ${r}`),await import(r).catch(o=>{v.error(`Error importing controller ${r}: ${o}`)})}))}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return{middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return{middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case"cors":this.use(Le(r));break;case"json":this.use(Ge(r));break;case"static":this.use(_e(r));break;case"fileParser":this.use(Ve(r));break;case"helmet":this.use(ze(r));break;case"cookie":this.use(je(r));break;case"log":this.use(Ne(r));break;case"rateLimiter":let{keyOptions:o,storageOptions:n}=r;this.use(De(o,n));break;case"urlencoded":this.use(Be(r));break;case"trustProxy":this.use(qe(r));break;case"timeout":this.use(Ie(r));break;case"session":this.use(Ue(r));break;default:v.warn(`Unknown plugin ${t}`);break}})}async bootstrap(){this.wasInitialized||(await this.importControllers(),this.applyPlugins(this.serverOptions.plugins),this.registerNotFoundRoutes(),this.globalMiddlewares.length&&h.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares),this.wasInitialized=!0)}registerNotFoundRoutes(){h.addOrUpdate("GET","*",[],(e,t)=>{let r=new b(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("POST","*",[],(e,t)=>{let r=new b(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("PUT","*",[],(e,t)=>{let r=new b(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("PATCH","*",[],(e,t)=>{let r=new b(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("DELETE","*",[],(e,t)=>{let r=new b(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0})}};var Ye=class{};var cr=h;0&&(module.exports={BasePlugin,Command,CommandRegistry,Request,Response,Server,commandRegistry,controller,cookie,cors,del,fileParser,get,getContentType,helmet,json,log,middleware,patch,post,put,rateLimiter,router,serveStatic,session,timeout,trustProxy,urlencoded,validate});
|
|
153
156
|
//# sourceMappingURL=index.cjs.map
|