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.d.cts
CHANGED
|
@@ -1776,4 +1776,4 @@ declare const timeout: (options: TimeoutOptions) => ServerRouteMiddleware;
|
|
|
1776
1776
|
*/
|
|
1777
1777
|
declare const router: ClientRouter;
|
|
1778
1778
|
|
|
1779
|
-
export { BasePlugin, type BunTapOptions, Command, CommandRegistry, type DenoTapOptions, type HttpMethod, type NextFunction, type NodeTapOptions, Request$1 as Request, Response, type RuntimeServer, type RuntimeServerMap, Server, type ServerConnectInput, type ServerErrorHandler, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerPlugin, type ServerRoute, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type ServerTapOptionsBuilder, type SignalEvent, type StandardMethodOptions, commandRegistry, controller, cookie, cors, del, fileParser, get, getContentType, helmet, json, log, middleware, patch, post, put, rateLimiter, router, serveStatic, session, timeout, trustProxy, urlencoded, validate };
|
|
1779
|
+
export { BasePlugin, type BunTapOptions, Command, type CommandOptions, CommandRegistry, type DenoTapOptions, type HttpMethod, type NextFunction, type NodeTapOptions, Request$1 as Request, Response, type RuntimeServer, type RuntimeServerMap, Server, type ServerConnectInput, type ServerErrorHandler, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerPlugin, type ServerRoute, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type ServerTapOptionsBuilder, type SignalEvent, type StandardMethodOptions, commandRegistry, controller, cookie, cors, del, fileParser, get, getContentType, helmet, json, log, middleware, patch, post, put, rateLimiter, router, serveStatic, session, timeout, trustProxy, urlencoded, validate };
|
package/lib/index.d.ts
CHANGED
|
@@ -1776,4 +1776,4 @@ declare const timeout: (options: TimeoutOptions) => ServerRouteMiddleware;
|
|
|
1776
1776
|
*/
|
|
1777
1777
|
declare const router: ClientRouter;
|
|
1778
1778
|
|
|
1779
|
-
export { BasePlugin, type BunTapOptions, Command, CommandRegistry, type DenoTapOptions, type HttpMethod, type NextFunction, type NodeTapOptions, Request$1 as Request, Response, type RuntimeServer, type RuntimeServerMap, Server, type ServerConnectInput, type ServerErrorHandler, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerPlugin, type ServerRoute, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type ServerTapOptionsBuilder, type SignalEvent, type StandardMethodOptions, commandRegistry, controller, cookie, cors, del, fileParser, get, getContentType, helmet, json, log, middleware, patch, post, put, rateLimiter, router, serveStatic, session, timeout, trustProxy, urlencoded, validate };
|
|
1779
|
+
export { BasePlugin, type BunTapOptions, Command, type CommandOptions, CommandRegistry, type DenoTapOptions, type HttpMethod, type NextFunction, type NodeTapOptions, Request$1 as Request, Response, type RuntimeServer, type RuntimeServerMap, Server, type ServerConnectInput, type ServerErrorHandler, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerPlugin, type ServerRoute, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type ServerTapOptionsBuilder, type SignalEvent, type StandardMethodOptions, commandRegistry, controller, cookie, cors, del, fileParser, get, getContentType, helmet, json, log, middleware, patch, post, put, rateLimiter, router, serveStatic, session, timeout, trustProxy, urlencoded, validate };
|
package/lib/index.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
var at=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var E=(s,e,t,r)=>{for(var o=r>1?void 0:r?dt(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&&at(e,t,o),o};import{join as pt}from"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 G=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null}},ge=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 G,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 G),c=c.wildcardChild;break}if(f.startsWith(":")){let g=f.slice(1);c.paramChild||(c.paramChild={node:new G,name:g}),c=c.paramChild.node;continue}c.staticChildren.has(f)||c.staticChildren.set(f,new G),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 ge;var sr=(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?pt(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 ir=(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 pr=(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 lr=(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 hr=(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 vr=(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 Rr=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};import{ValidationError as ct}from"ajv";var _=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 ct))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};_.query=(s,e)=>_({query:s,customError:e});_.body=(s,e)=>_({body:s,customError:e});_.all=(s,e)=>_({all:s,customError:e});var Tr=_;import{glob as ht}from"glob";import{join as xe}from"path";var ye=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 ye;var ve=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}},we=new ve;var ut=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:Me(r)}}return{name:s,value:!0}},Me=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},j=()=>{let s=we.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=ut(o);if(n){if(n.value===!0&&r+1<s.length){let a=s[r+1];a&&typeof a=="string"&&!a.startsWith("-")&&(n.value=Me(a),r++)}t[n.name]=n.value}continue}e.push(o)}}return{args:e,flags:t}};var se=()=>we.getCliArgs()[0]||null;var N="VALIDATION_ERROR";var Ae=j().args.slice(1),J=s=>(e,t)=>{let r=se();if(!r||r!==e.commandName)return;let o=t;l.set(e,t,{type:"arg",name:o,description:s.description});let n=Ae.length?Ae.shift():s.defaultValue;if(s.required&&!n){let a=l.get(e,N);l.set(e,N,[...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 Se=class{exit(e){switch(y.type){case"bun":case"node":process.exit(e);case"deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},Re=new Se;import lt from"pino";var mt=()=>lt({level:"info",formatters:{level:e=>({level:e})}}),v=mt();var O=class{static commandName=this.name;static description="";static help=[];static options={keepAlive:!1};static args=j().args.slice(1);static flags=j().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),Re.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,N)||[]);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}`),Re.exit(1)}}};var be=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 be;var W=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=xe(this.path,`${this.name}.ts`),await R.exists(xe(process.cwd(),this.path))||await R.mkdir(xe(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";
|
|
2
|
+
`)};static validateContext=e=>{let t=Array.from(l.get(e,N)||[]);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}`),Re.exit(1)}}};var be=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 be;var W=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=xe(this.path,`${this.name}.ts`),await R.exists(xe(process.cwd(),this.path))||await R.mkdir(xe(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,7 +46,7 @@ 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 Ce=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 ht(e,{absolute:!0,cwd:F.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=[I,W,q,B,K];for(let o of r)this.commands.set(o.commandName,o)}},Fe=Ce.getInstance();import{Type as Y}from"@sinclair/typebox";import gt,{ValidationError as yt}from"ajv";import vt from"ajv-formats";var wt=vt(new gt,["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"]),L=(s,e,t=!1)=>{let r=wt.compile(s);if(!r(e)){if(t)return e;throw new yt(r.errors||[])}return e};var oe=class extends Request{};import{randomUUID as St}from"crypto";var A=class s extends oe{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(Y)),L(t,e.body||{},r)),e.validateQuery=(t,r=!1)=>(typeof t=="function"&&(t=t(Y)),L(t,e.query||{},r)),e.validateAll=(t,r=!1)=>(typeof t=="function"&&(t=t(Y)),L(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=St()),this._id}body;validate(e,t=!1){return typeof e=="function"&&(e=e(Y)),L(e,this.body||{},t)}validateQuery(e,t=!1){return typeof e=="function"&&(e=e(Y)),L(e,this.query||{},t)}validateAll(e,t=!1){return typeof e=="function"&&(e=e(Y)),L(e,{...this.body?{body:this.body}:{},...this.query?{query:this.query}:{}},t)}};import Rt from"fs/promises";var $e=class{file(e){switch(y.type){case"bun":return Bun.file(e);case"node":return Rt.readFile(e);case"deno":return Deno.readFile(e);default:throw new Error("Unsupported runtime")}}},ne=new $e;import{extname as bt,join as xt,resolve as Ot}from"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 ie=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 He=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 ke=(s="public",e)=>(h.addOrUpdate("GET",`${s}/*`,[],async(t,r)=>Tt(t,r,s),{service:"StaticFiles",...e}),async(t,r,o)=>o());async function Tt(s,e,t){if(s.method!=="GET"&&s.method!=="HEAD")return e.status(405).json({...w(new ie(s.url,s.method))});let r=s.params["*"]||"",o=xt(t,r),n=Ot(F.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=Ee(bt(n));e.setHeader("Content-Type",a);let p=await ne.file(n);e.raw(p)}function Ee(s){return He.get(s)||"application/octet-stream"}var V=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=Ee(e),r=ne.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}};import{glob as Xt}from"glob";import{join as tt}from"path";import{glob as Ct}from"glob";var X=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 Ct(r,{absolute:!0,cwd:F.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 Q=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 H=async(s,e,t,r=new V)=>{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},k=s=>s?["post","put","patch","delete"].includes(s.toLowerCase()):!0;var ae=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 V(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new Q(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 A(u.toString(),{method:e.toUpperCase(),body:k(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 H(d.middleware,d.handler,f);return new Q(g)}catch(g){v.error(`Error processing mock request ${e} ${t}:`,g);let m=new V(500);return m.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new Q(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 Ce=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 ht(e,{absolute:!0,cwd:F.getCwd()});if(t.some(o=>o.endsWith(".ts")))try{let{register:o}=await import("module");o("ts-node/esm",import.meta.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=[I,W,q,B,K];for(let o of r)this.commands.set(o.commandName,o)}},Fe=Ce.getInstance();import{Type as Y}from"@sinclair/typebox";import gt,{ValidationError as yt}from"ajv";import vt from"ajv-formats";var wt=vt(new gt,["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"]),L=(s,e,t=!1)=>{let r=wt.compile(s);if(!r(e)){if(t)return e;throw new yt(r.errors||[])}return e};var oe=class extends Request{};import{randomUUID as St}from"crypto";var A=class s extends oe{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(Y)),L(t,e.body||{},r)),e.validateQuery=(t,r=!1)=>(typeof t=="function"&&(t=t(Y)),L(t,e.query||{},r)),e.validateAll=(t,r=!1)=>(typeof t=="function"&&(t=t(Y)),L(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=St()),this._id}body;validate(e,t=!1){return typeof e=="function"&&(e=e(Y)),L(e,this.body||{},t)}validateQuery(e,t=!1){return typeof e=="function"&&(e=e(Y)),L(e,this.query||{},t)}validateAll(e,t=!1){return typeof e=="function"&&(e=e(Y)),L(e,{...this.body?{body:this.body}:{},...this.query?{query:this.query}:{}},t)}};import Rt from"fs/promises";var $e=class{file(e){switch(y.type){case"bun":return Bun.file(e);case"node":return Rt.readFile(e);case"deno":return Deno.readFile(e);default:throw new Error("Unsupported runtime")}}},ne=new $e;import{extname as bt,join as xt,resolve as Ot}from"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 ie=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 He=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 ke=(s="public",e)=>(h.addOrUpdate("GET",`${s}/*`,[],async(t,r)=>Tt(t,r,s),{service:"StaticFiles",...e}),async(t,r,o)=>o());async function Tt(s,e,t){if(s.method!=="GET"&&s.method!=="HEAD")return e.status(405).json({...w(new ie(s.url,s.method))});let r=s.params["*"]||"",o=xt(t,r),n=Ot(F.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=Ee(bt(n));e.setHeader("Content-Type",a);let p=await ne.file(n);e.raw(p)}function Ee(s){return He.get(s)||"application/octet-stream"}var V=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=Ee(e),r=ne.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}};import{glob as Xt}from"glob";import{join as tt}from"path";import{glob as Ct}from"glob";var X=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 Ct(r,{absolute:!0,cwd:F.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 Q=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 H=async(s,e,t,r=new V)=>{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},k=s=>s?["post","put","patch","delete"].includes(s.toLowerCase()):!0;var ae=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 V(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new Q(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 A(u.toString(),{method:e.toUpperCase(),body:k(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 H(d.middleware,d.handler,f);return new Q(g)}catch(g){v.error(`Error processing mock request ${e} ${t}:`,g);let m=new V(500);return m.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new Q(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
|