balda 0.0.26 → 0.0.27

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 CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import {glob}from'glob';import Pt from'pino';import Pe from'fs';import je from'path';import {execSync}from'child_process';import*as it from'readline';import {Ajv}from'ajv';import Ot from'fast-json-stringify';import Nt from'crypto';var Qe=Object.defineProperty;var b=(o,e,t,r)=>{for(var s=void 0,a=o.length-1,c;a>=0;a--)(c=o[a])&&(s=(c(e,t,s))||s);return s&&Qe(e,t,s),s};var Fe=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")}},R=new Fe;var Be=class{getCliArgs(){switch(R.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(R.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";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],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="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(s)){for(let a=t+1;a<e.length;a++)if(!e[a].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[a]))return a;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},ve=new Be;var et=(o,e)=>{let t=Array(e.length+1).fill(null).map(()=>Array(o.length+1).fill(null));for(let r=0;r<=o.length;r++)t[0][r]=r;for(let r=0;r<=e.length;r++)t[r][0]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=o.length;s++){let a=o[s-1]===e[r-1]?0:1;t[r][s]=Math.min(t[r][s-1]+1,t[r-1][s]+1,t[r-1][s-1]+a);}return t[e.length][o.length]},Oe=o=>o.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),Ee=o=>o.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),tt=o=>o.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var St=o=>{if(!o||o==="-"||o==="--")return null;let e=o.indexOf("=");if(e>0){let t=o.substring(0,e),r=o.substring(e+1);return {name:t,value:rt(r)}}return {name:o,value:true}},rt=o=>{if(o.toLowerCase()==="true")return true;if(o.toLowerCase()==="false")return false;let e=Number(o);return !Number.isNaN(e)&&Number.isFinite(e)?e:o},te=()=>{let o=ve.getCliArgs(),e=[],t={};if(!o||!o.length)return {args:e,flags:t};for(let r=0;r<o.length;r++){let s=o[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let a=St(s);if(a){if(a.value===true&&r+1<o.length){let c=o[r+1];c&&typeof c=="string"&&!c.startsWith("-")&&(a.value=rt(c),r++);}if(a.name in t){let c=t[a.name];Array.isArray(c)?c.push(a.value):t[a.name]=[c,a.value];}else t[a.name]=a.value;}continue}e.push(s);}}return {args:e,flags:t}},st=(o,e)=>{if(!o||typeof o!="string"||!e||!Array.isArray(e)||e.length===0)return "";let t=o.toLowerCase().trim(),r=e.filter(c=>{let n=c.toLowerCase();if(n===t||n.includes(t)||t.includes(n))return true;let u=et(n,t),d=Math.max(t.length,n.length)*.4;return u<=d});if(r.length===0)return "";let a=r.slice(0,3).map(c=>`\x1B[36m${c}\x1B[0m`).join(", ");return `\x1B[31m\u2717\x1B[0m Command \x1B[33m${o}\x1B[0m not found
3
- \x1B[32m\u{1F4A1}\x1B[0m Did you mean: ${a}?`},$e=()=>ve.getCliArgs()[0]||null;var Tt=()=>Pt({level:"info",formatters:{level:e=>({level:e})}}),F=Tt();var Ue=class{getCwd(){switch(R.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},B=new Ue;var _=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)}static getOrCreateAll(e){return this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e)}static delete(e,t){this.metadata.get(e)?.delete(t);}static clear(e){this.metadata.delete(e);}};var re="VALIDATION_ERROR";var ot=te().args.slice(1),O=o=>(e,t)=>{let r=$e();if(!r||r!==e.commandName)return;let s=t;_.set(e,t,{type:"arg",name:s,description:o.description});let a=ot.length?ot.shift():o.defaultValue;if(o.required&&!a){let c=_.get(e,re);_.set(e,re,[...c||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}o.parse&&a&&(a=o.parse(a)),Object.defineProperty(e,t,{value:a,enumerable:true,configurable:true,writable:true});};var U=o=>(e,t)=>{let r=$e();if(!r||r!==e.commandName)return;let s=o.name||t,a=te().flags,c=o.aliases?Array.isArray(o.aliases)?o.aliases:[o.aliases]:[],n=[s,...c],u=o.defaultValue;for(let d of n){let l=[d,`-${d}`,`--${d}`];for(let i of l)if(i in a){let h=a[i];o.type==="list"?u=(Array.isArray(h)?h:[h]).map(m=>{let g=String(m);return o.parse?o.parse(g):g}):(u=h,o.type==="boolean"?u=!!u:o.type==="number"?u=Number(u):o.type==="string"&&(u=String(u)),o.parse&&(u=o.parse(u)));break}if(u!==o.defaultValue)break}if(_.set(e,t,{type:"flag",name:s,aliases:c||[],description:o.description}),o.required&&(o.type==="list"?!u||Array.isArray(u)&&u.length===0:!u)){let l=_.get(e,re);_.set(e,re,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:u,enumerable:true,configurable:true,writable:true});};U.boolean=o=>U({...o,type:"boolean"});U.string=o=>U({...o,type:"string"});U.number=o=>U({...o,type:"number"});U.list=o=>U({...o,type:"list"});U.array=o=>U({...o,type:"list"});var P=U;var ze=class{exit(e){switch(R.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},W=new ze;var q=class{static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false};static args=te().args.slice(1);static flags=te().flags;static logger=F.child({scope:this.constructor.name});static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help"];if(!Object.keys(e).some(d=>t.includes(d)))return;let s=this.commandName,a=this.description||"No description available",c=this.help||[],n=this.options,u=this.generateHelpOutput({name:s,description:a,helpText:c,options:n,args:this.args,flags:this.flags},this);console.log(u),W.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:a,options:c,args:n,flags:u}=e,d={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"},l=[`${d.title}${r}${d.reset}`,`${d.description}${s}${d.reset}`,"",`${d.subtitle}Usage:${d.reset}`,` ${d.code}${r}${d.reset} [options] [arguments]`,"",`${d.subtitle}Options:${d.reset}`,` ${d.flag}-h, --help${d.reset} Show this help message`,"",`${d.subtitle}Command Options:${d.reset}`,` ${d.flag}keepAlive${d.reset} ${c?.keepAlive??false?d.success+"Enabled"+d.reset:d.error+"Disabled"+d.reset}`,""];if(a){let m=Array.isArray(a)?a:[a];l.push(`${d.subtitle}Help:${d.reset}`),m.forEach(g=>{l.push(` ${d.description}${g}${d.reset}`);}),l.push("");}let i=_.getAll(t),h=i?Array.from(i.values()).filter(m=>m.type==="arg"):[],p=i?Array.from(i.values()).filter(m=>m.type==="flag"):[];return h.length&&(l.push(`${d.subtitle}Available Arguments:${d.reset}`),h.forEach(m=>{let g=m.required?` ${d.error}(required)${d.reset}`:"",f=m.description?` ${d.description}${m.description}${d.reset}`:"";l.push(` ${d.code}${m.name}${d.reset}${g}${f}`);}),l.push("")),p.length&&(l.push(`${d.subtitle}Available Flags:${d.reset}`),p.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let g=m.aliases.length?` ${d.flag}(${m.aliases.join(", ")})${d.reset}`:"",f=m.required?` ${d.error}(required)${d.reset}`:"",v=m.description?` ${d.description}${m.description}${d.reset}`:"";l.push(` ${d.flag}--${m.name}${g}${d.reset}${f}${v}`);}),l.push("")),((n?.length??0)>0||u&&Object.keys(u).length>0)&&(l.push(`${d.subtitle}Current Context:${d.reset}`),n?.length&&l.push(` ${d.info}Provided Arguments:${d.reset} ${d.code}${n.join(" ")}${d.reset}`),u&&Object.keys(u).length>0&&(l.push(` ${d.info}Provided Flags:${d.reset}`),Object.keys(u).forEach(m=>{let g=u[m],f=g!=null?` = ${d.code}${g}${d.reset}`:"";l.push(` ${d.flag}${m}${d.reset}${f}`);})),l.push("")),a&&(Array.isArray(a)?a.some(m=>m.includes("example")):a.includes("example"))&&(l.push(`${d.subtitle}Examples:${d.reset}`),(Array.isArray(a)?a.filter(g=>g.includes("example")):[a.split("example")[1].trim()]).forEach(g=>{l.push(` ${d.code}${g}${d.reset}`);}),l.push("")),l.join(`
4
- `)};static validateContext=e=>{let t=Array.from(_.get(e,re)||[]);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((s,a)=>{let c=`${r.info}${a+1}.${r.reset}`,n=`${r.error}${s.type.toUpperCase()}${r.reset}`,u=`${r.code}${s.name}${r.reset}`;console.error(` ${c} ${n} ${u}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),W.exit(1);}}};var Le=class{async mkdir(e,t){switch(R.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(R.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(R.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let a=Bun.file(e);return t?.encoding==="utf8"?a.text():new Uint8Array(await a.arrayBuffer());case "deno":let c=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(c):new Uint8Array(c)}}async writeFile(e,t){switch(R.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(R.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 a=await(await import('fs/promises')).stat(e);return {isDirectory:a.isDirectory(),isFile:a.isFile(),isSymbolicLink:a.isSymbolicLink(),size:a.size};case "deno":let c=await Deno.stat(e);return {isDirectory:c.isDirectory,isFile:c.isFile,isSymbolicLink:false,size:c.size}}}async unlink(e){switch(R.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")}}async streamFile(e){switch(R.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(R.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},y=new Le;var He=class{basename(e){switch(R.type){case "node":case "bun":case "deno":return je.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(R.type){case "node":case "bun":case "deno":return je.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(R.type){case "bun":case "node":case "deno":return je.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(R.type){case "bun":case "node":case "deno":return je.resolve(...e);default:throw new Error("Unsupported runtime")}}},x=new He;var K=async o=>{let e=x.join(process.cwd(),"node_modules");if(!await y.exists(e))return o;let r=[];for(let s of o){let a=x.join(e,s);await y.exists(a)||r.push(s);}return r},N=async()=>await y.exists(x.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await y.exists(x.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await y.exists(x.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await y.exists(x.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await y.exists(x.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],$=async(o,e,t,r,s=true)=>{let a=it.createInterface({input:process.stdin,output:process.stdout}),c=t.join(", "),n=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
2
+ import {glob}from'glob';import Ct from'pino';import Pe from'fs';import je from'path';import {execSync}from'child_process';import*as nt from'readline';import {createRequire}from'module';import {Ajv}from'ajv';import jt from'fast-json-stringify';import Dt from'crypto';var Qe=Object.defineProperty;var Fe=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var b=(o,e,t,r)=>{for(var s=void 0,a=o.length-1,c;a>=0;a--)(c=o[a])&&(s=(c(e,t,s))||s);return s&&Qe(e,t,s),s};var Be=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")}},R=new Be;var Ue=class{getCliArgs(){switch(R.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(R.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";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],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="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(s)){for(let a=t+1;a<e.length;a++)if(!e[a].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[a]))return a;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},ve=new Ue;var tt=(o,e)=>{let t=Array(e.length+1).fill(null).map(()=>Array(o.length+1).fill(null));for(let r=0;r<=o.length;r++)t[0][r]=r;for(let r=0;r<=e.length;r++)t[r][0]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=o.length;s++){let a=o[s-1]===e[r-1]?0:1;t[r][s]=Math.min(t[r][s-1]+1,t[r-1][s]+1,t[r-1][s-1]+a);}return t[e.length][o.length]},Oe=o=>o.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),Ee=o=>o.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),rt=o=>o.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var Tt=o=>{if(!o||o==="-"||o==="--")return null;let e=o.indexOf("=");if(e>0){let t=o.substring(0,e),r=o.substring(e+1);return {name:t,value:st(r)}}return {name:o,value:true}},st=o=>{if(o.toLowerCase()==="true")return true;if(o.toLowerCase()==="false")return false;let e=Number(o);return !Number.isNaN(e)&&Number.isFinite(e)?e:o},te=()=>{let o=ve.getCliArgs(),e=[],t={};if(!o||!o.length)return {args:e,flags:t};for(let r=0;r<o.length;r++){let s=o[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let a=Tt(s);if(a){if(a.value===true&&r+1<o.length){let c=o[r+1];c&&typeof c=="string"&&!c.startsWith("-")&&(a.value=st(c),r++);}if(a.name in t){let c=t[a.name];Array.isArray(c)?c.push(a.value):t[a.name]=[c,a.value];}else t[a.name]=a.value;}continue}e.push(s);}}return {args:e,flags:t}},ot=(o,e)=>{if(!o||typeof o!="string"||!e||!Array.isArray(e)||e.length===0)return "";let t=o.toLowerCase().trim(),r=e.filter(c=>{let n=c.toLowerCase();if(n===t||n.includes(t)||t.includes(n))return true;let u=tt(n,t),d=Math.max(t.length,n.length)*.4;return u<=d});if(r.length===0)return "";let a=r.slice(0,3).map(c=>`\x1B[36m${c}\x1B[0m`).join(", ");return `\x1B[31m\u2717\x1B[0m Command \x1B[33m${o}\x1B[0m not found
3
+ \x1B[32m\u{1F4A1}\x1B[0m Did you mean: ${a}?`},$e=()=>ve.getCliArgs()[0]||null;var qt=()=>Ct({level:"info",formatters:{level:e=>({level:e})}}),B=qt();var ze=class{getCwd(){switch(R.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},U=new ze;var _=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)}static getOrCreateAll(e){return this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e)}static delete(e,t){this.metadata.get(e)?.delete(t);}static clear(e){this.metadata.delete(e);}};var re="VALIDATION_ERROR";var it=te().args.slice(1),O=o=>(e,t)=>{let r=$e();if(!r||r!==e.commandName)return;let s=t;_.set(e,t,{type:"arg",name:s,description:o.description});let a=it.length?it.shift():o.defaultValue;if(o.required&&!a){let c=_.get(e,re);_.set(e,re,[...c||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}o.parse&&a&&(a=o.parse(a)),Object.defineProperty(e,t,{value:a,enumerable:true,configurable:true,writable:true});};var z=o=>(e,t)=>{let r=$e();if(!r||r!==e.commandName)return;let s=o.name||t,a=te().flags,c=o.aliases?Array.isArray(o.aliases)?o.aliases:[o.aliases]:[],n=[s,...c],u=o.defaultValue;for(let d of n){let l=[d,`-${d}`,`--${d}`];for(let i of l)if(i in a){let h=a[i];o.type==="list"?u=(Array.isArray(h)?h:[h]).map(m=>{let g=String(m);return o.parse?o.parse(g):g}):(u=h,o.type==="boolean"?u=!!u:o.type==="number"?u=Number(u):o.type==="string"&&(u=String(u)),o.parse&&(u=o.parse(u)));break}if(u!==o.defaultValue)break}if(_.set(e,t,{type:"flag",name:s,aliases:c||[],description:o.description}),o.required&&(o.type==="list"?!u||Array.isArray(u)&&u.length===0:!u)){let l=_.get(e,re);_.set(e,re,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:u,enumerable:true,configurable:true,writable:true});};z.boolean=o=>z({...o,type:"boolean"});z.string=o=>z({...o,type:"string"});z.number=o=>z({...o,type:"number"});z.list=o=>z({...o,type:"list"});z.array=o=>z({...o,type:"list"});var P=z;var Le=class{exit(e){switch(R.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},K=new Le;var q=class{static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false};static args=te().args.slice(1);static flags=te().flags;static logger=B.child({scope:this.constructor.name});static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help"];if(!Object.keys(e).some(d=>t.includes(d)))return;let s=this.commandName,a=this.description||"No description available",c=this.help||[],n=this.options,u=this.generateHelpOutput({name:s,description:a,helpText:c,options:n,args:this.args,flags:this.flags},this);console.log(u),K.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:a,options:c,args:n,flags:u}=e,d={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"},l=[`${d.title}${r}${d.reset}`,`${d.description}${s}${d.reset}`,"",`${d.subtitle}Usage:${d.reset}`,` ${d.code}${r}${d.reset} [options] [arguments]`,"",`${d.subtitle}Options:${d.reset}`,` ${d.flag}-h, --help${d.reset} Show this help message`,"",`${d.subtitle}Command Options:${d.reset}`,` ${d.flag}keepAlive${d.reset} ${c?.keepAlive??false?d.success+"Enabled"+d.reset:d.error+"Disabled"+d.reset}`,""];if(a){let m=Array.isArray(a)?a:[a];l.push(`${d.subtitle}Help:${d.reset}`),m.forEach(g=>{l.push(` ${d.description}${g}${d.reset}`);}),l.push("");}let i=_.getAll(t),h=i?Array.from(i.values()).filter(m=>m.type==="arg"):[],p=i?Array.from(i.values()).filter(m=>m.type==="flag"):[];return h.length&&(l.push(`${d.subtitle}Available Arguments:${d.reset}`),h.forEach(m=>{let g=m.required?` ${d.error}(required)${d.reset}`:"",f=m.description?` ${d.description}${m.description}${d.reset}`:"";l.push(` ${d.code}${m.name}${d.reset}${g}${f}`);}),l.push("")),p.length&&(l.push(`${d.subtitle}Available Flags:${d.reset}`),p.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let g=m.aliases.length?` ${d.flag}(${m.aliases.join(", ")})${d.reset}`:"",f=m.required?` ${d.error}(required)${d.reset}`:"",v=m.description?` ${d.description}${m.description}${d.reset}`:"";l.push(` ${d.flag}--${m.name}${g}${d.reset}${f}${v}`);}),l.push("")),((n?.length??0)>0||u&&Object.keys(u).length>0)&&(l.push(`${d.subtitle}Current Context:${d.reset}`),n?.length&&l.push(` ${d.info}Provided Arguments:${d.reset} ${d.code}${n.join(" ")}${d.reset}`),u&&Object.keys(u).length>0&&(l.push(` ${d.info}Provided Flags:${d.reset}`),Object.keys(u).forEach(m=>{let g=u[m],f=g!=null?` = ${d.code}${g}${d.reset}`:"";l.push(` ${d.flag}${m}${d.reset}${f}`);})),l.push("")),a&&(Array.isArray(a)?a.some(m=>m.includes("example")):a.includes("example"))&&(l.push(`${d.subtitle}Examples:${d.reset}`),(Array.isArray(a)?a.filter(g=>g.includes("example")):[a.split("example")[1].trim()]).forEach(g=>{l.push(` ${d.code}${g}${d.reset}`);}),l.push("")),l.join(`
4
+ `)};static validateContext=e=>{let t=Array.from(_.get(e,re)||[]);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((s,a)=>{let c=`${r.info}${a+1}.${r.reset}`,n=`${r.error}${s.type.toUpperCase()}${r.reset}`,u=`${r.code}${s.name}${r.reset}`;console.error(` ${c} ${n} ${u}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),K.exit(1);}}};var He=class{async mkdir(e,t){switch(R.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(R.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(R.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let a=Bun.file(e);return t?.encoding==="utf8"?a.text():new Uint8Array(await a.arrayBuffer());case "deno":let c=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(c):new Uint8Array(c)}}async writeFile(e,t){switch(R.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(R.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 a=await(await import('fs/promises')).stat(e);return {isDirectory:a.isDirectory(),isFile:a.isFile(),isSymbolicLink:a.isSymbolicLink(),size:a.size};case "deno":let c=await Deno.stat(e);return {isDirectory:c.isDirectory,isFile:c.isFile,isSymbolicLink:false,size:c.size}}}async unlink(e){switch(R.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")}}async streamFile(e){switch(R.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(R.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},y=new He;var We=class{basename(e){switch(R.type){case "node":case "bun":case "deno":return je.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(R.type){case "node":case "bun":case "deno":return je.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(R.type){case "bun":case "node":case "deno":return je.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(R.type){case "bun":case "node":case "deno":return je.resolve(...e);default:throw new Error("Unsupported runtime")}}},x=new We;var at=typeof import.meta<"u"?createRequire(import.meta.url):Fe("module").createRequire?.(import.meta?.url??__filename)??Fe,X=async o=>{let e=x.join(process.cwd(),"node_modules");if(!await y.exists(e))return o;let r=[];for(let s of o){let a=x.join(e,s);await y.exists(a)||r.push(s);}return r},N=async()=>await y.exists(x.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await y.exists(x.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await y.exists(x.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await y.exists(x.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await y.exists(x.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],$=async(o,e,t,r,s=true)=>{let a=nt.createInterface({input:process.stdin,output:process.stdout}),c=t.join(", "),n=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
5
5
  ${c}
6
- (y/n): `;return new Promise(u=>{a.question(n,d=>{if(a.close(),d.toLowerCase()==="y"||d.toLowerCase()==="yes"){execSync(o,r),u(true);return}u(false);});})};var I=class extends q{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){if(typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1)),!await import('esbuild').then(n=>true).catch(()=>false)){let[n,u,d]=await N();await $(`${n} ${u} esbuild ${d}`,n,["esbuild"],{stdio:"inherit"})||(this.logger.warn("User chose to not continue with the installation of esbuild, exiting..."),process.exit(0));}let t=await import('esbuild').catch(n=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),r=je.join(this.output,"assets"),s=[];if(this.assets){let{copy:n}=await import('esbuild-plugin-copy').catch(u=>{throw this.logger.error("esbuild-plugin-copy is not installed, please install it with `npm install -D esbuild-plugin-copy` to use the build command"),new Error("esbuild-plugin-copy is not installed")});Pe.existsSync(r)||Pe.mkdirSync(r,{recursive:true}),s.push(n({assets:{from:this.assets,to:r}}));}this.clearDist&&Pe.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Pe.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let a=je.join(this.output,"server.js"),c=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:a,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});c.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:c.errors},null,2)),process.exit(1)),c.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:c.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${a}`,output:a,assets:!!this.assets},null,2)),process.exit(0);}};b([P({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],I,"clearDist"),b([P({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],I,"entry"),b([P({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],I,"output"),b([P({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],I,"tsconfig"),b([P({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],I,"assets"),b([P({type:"string",aliases:["f"],name:"format",required:false,defaultValue:"esm",description:"The format to build the project, default is esm, can be 'esm' or 'cjs'"})],I,"format"),b([P({type:"string",aliases:["p"],name:"packages",required:false,defaultValue:"external",description:"Weather to bundle node_modules or not, default is external, can be 'bundle' or 'external'"})],I,"packages"),b([P({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],I,"sourcemap");var Z=class extends Error{constructor(e){super(e);}};var z=class{static ajv=new Ajv({validateSchema:false,strict:false});static{this.ajv.addFormat("email",/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/),this.ajv.addFormat("url",/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/),this.ajv.addFormat("date",/^\d{4}-\d{2}-\d{2}$/),this.ajv.addFormat("datetime",/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})$/),this.ajv.addFormat("time",/^\d{2}:\d{2}:\d{2}$/),this.ajv.addFormat("binary",/^(?:[0-9a-fA-F]{2})+$/),this.ajv.addFormat("base64",/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/),this.ajv.addFormat("uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);}static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}};var j=new Map;var at=new WeakMap,Rt=0,M=(o,e="schema_ref")=>{let t=at.get(o);return t||(t=Symbol(`${e}_${++Rt}`),at.set(o,t)),t};var X=class{static typeboxModule=null;static loadPromise=null;static async load(){return this.typeboxModule?this.typeboxModule:this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{try{return this.typeboxModule=await import('@sinclair/typebox'),this.typeboxModule}catch{throw new Error(`TypeBox is not installed. Install it with: npm install @sinclair/typebox
7
- TypeBox is a peer dependency required when using TypeBox schemas for validation.`)}})(),this.loadPromise)}static get(){if(!this.typeboxModule)throw new Error("TypeBox has not been loaded yet. Call TypeBoxLoader.load() first.");return this.typeboxModule}static isTypeBoxSchema(e){return typeof e=="object"&&e!==null&&"type"in e&&Object.getOwnPropertySymbols(e).some(t=>t.toString()==="Symbol(TypeBox.Kind)")}};var J=class{static zodModule=null;static loadPromise=null;static async load(){return this.zodModule?this.zodModule:this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{try{return this.zodModule=await import('zod'),this.zodModule}catch{throw new Error(`Zod is not installed. Install it with: npm install zod
8
- Zod is a peer dependency required when using Zod schemas for validation.`)}})(),this.loadPromise)}static get(){if(!this.zodModule)throw new Error("Zod has not been loaded yet. Call ZodLoader.load() first.");return this.zodModule}static isZodSchema(e){let t=typeof e=="object"&&e!==null&&"_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";if(t&&!("toJSONSchema"in e))throw new Error("Zod4 is required with the toJSONSchema() method in order to work. Install it with: npm install zod with minimum version 4.0.0");return t}};var lt=new Map,ct=o=>{if(!o)return null;try{let{jsonSchema:e,cacheKey:t}=Et(o),r=lt.get(t);if(r)return r.serializer;let s=Ot(e),a={serializer:s,schema:e,compiledAt:Date.now()};return lt.set(t,a),s}catch(e){return console.error("Failed to compile fast-json-stringify serializer:",e),null}},Et=o=>{if(J.isZodSchema(o)){let t=M(o,"fast_stringify_zod");return {jsonSchema:o.toJSONSchema(),cacheKey:t}}if(X.isTypeBoxSchema(o)){let t=M(o,"fast_stringify_typebox");return {jsonSchema:o,cacheKey:t}}if(typeof o=="object"&&o!==null){let t=M(o,"fast_stringify_json");return {jsonSchema:o,cacheKey:t}}let e=JSON.stringify(o);return {jsonSchema:o,cacheKey:e}};var We=new Map;var se=(o,e)=>{if(!o||typeof o!="object")return;if(J.isZodSchema(o)){let r=M(o,"json_schema_zod");We.set(r,e);return}if(X.isTypeBoxSchema(o)){let r=M(o,"json_schema_typebox");We.set(r,e);return}let t=M(o,"json_schema_json");We.set(t,e);};var $t=o=>{if(J.isZodSchema(o)){let t=M(o,"serialize_zod");if(!j.has(t))try{let r=o.toJSONSchema();se(o,r);let s=z.ajv.compile(r);j.set(t,s);}catch(r){F.debug({error:r},"Failed to convert Zod schema to JSON Schema");return}return}if(X.isTypeBoxSchema(o)){let t=M(o,"serialize_typebox");if(!j.has(t)){se(o,o);let r=z.ajv.compile(o);j.set(t,r);}return}if(typeof o=="object"&&o!==null){let t=M(o,"serialize_json");if(!j.has(t)){se(o,o);let r=z.ajv.compile(o);j.set(t,r);}return}let e=JSON.stringify(o);if(!j.has(e)){let t=z.ajv.compile(o);j.set(e,t);}},dt=o=>{if(J.isZodSchema(o)){let t=M(o,"zod_schema");if(!j.has(t))try{let r=o.toJSONSchema();se(o,r);let s=z.ajv.compile(r);j.set(t,s);}catch{return}return}if(X.isTypeBoxSchema(o)){let t=M(o,"typebox_schema");if(!j.has(t)){se(o,o);let r=z.ajv.compile(o);j.set(t,r);}return}if(typeof o=="object"&&o!==null){let t=M(o,"json_schema");if(!j.has(t)){se(o,o);let r=z.ajv.compile(o);j.set(t,r);}return}let e=JSON.stringify(o);if(!j.has(e)){let t=z.ajv.compile(o);j.set(e,t);}},ut=(o,e)=>{o&&dt(o),e&&dt(e);},pt=o=>{if(!o||Object.keys(o).length===0)return;let e={};for(let[t,r]of Object.entries(o)){let s=Number(t);e[s]=r,$t(r),ct(r);}return e};var we=class{staticChildren;paramChild;wildcardChild;middleware;handler;paramName;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null,this.paramName=null;}},Ke=class o{trees;routes;middlewares;basePath;staticRouteCache;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e),this.staticRouteCache=new Map;}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,a){e=e.toUpperCase();let c=t.split("?")[0];ut(a?.requestBody,a?.query);let n=pt(a?.responses),u=this.trees.get(e);u||(u=new we,this.trees.set(e,u));let d=c.replace(/^\/+|\/+$/g,""),l=d.length===0?[]:d.split("/"),i=true,h=[],p=u;for(let g of l){if(g==="*"){i=false,p.wildcardChild||(p.wildcardChild=new we),p=p.wildcardChild;break}if(g.startsWith(":")){i=false;let f=g.slice(1);h.push(f),p.paramChild||(p.paramChild={node:new we,name:f}),p=p.paramChild.node;continue}p.staticChildren.has(g)||p.staticChildren.set(g,new we),p=p.staticChildren.get(g);}if(p.middleware=r,p.handler=s,h.length>0&&(p.paramName=h.join(",")),i){let g="/"+d,f=`${e}:${g}`;this.staticRouteCache.set(f,{middleware:r,handler:s,params:{},responseSchemas:n});}else {let g="/"+d.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),f=`${e}:${g}`;this.staticRouteCache.delete(f);}let m=this.routes.findIndex(g=>g.method===e&&g.path===t);if(m!==-1){this.routes[m].middleware=r,this.routes[m].handler=s,this.routes[m].swaggerOptions=a,this.routes[m].responseSchemas=n;return}this.routes.push({method:e,path:t,middleware:r,handler:s,swaggerOptions:a,responseSchemas:n});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let a=`${e}:${r}`,c=this.staticRouteCache.get(a);if(c)return c;let n=this.trees.get(e);if(!n)return null;let u=r.replace(/^\/+|\/+$/g,""),d=u.length===0?[]:u.split("/"),l={},i=n;for(let p=0;p<d.length;p++){let m=d[p];if(i.staticChildren.has(m)){i=i.staticChildren.get(m);continue}if(i.paramChild){l[i.paramChild.name]=m,i=i.paramChild.node;continue}if(i.wildcardChild){l["*"]=d.slice(p).join("/"),i=i.wildcardChild;break}return null}if(!i.handler||!i.middleware)return null;let h=this.routes.find(p=>p.method===e&&p.handler===i.handler);return {middleware:i.middleware,handler:i.handler,params:l,responseSchemas:h?.responseSchemas}}registerRoute(e,t,r,s,a){let c=this.joinPath(t),n=typeof r=="function"&&r.length!==3,u=n?r:s,d=n?[]:Array.isArray(r)?r:[r],l=[...this.middlewares,...d],i=n?s:a;this.addOrUpdate(e,c,l,u,i);}get(e,t,r,s){this.registerRoute("GET",e,t,r,s);}post(e,t,r,s){this.registerRoute("POST",e,t,r,s);}patch(e,t,r,s){this.registerRoute("PATCH",e,t,r,s);}put(e,t,r,s){this.registerRoute("PUT",e,t,r,s);}delete(e,t,r,s){this.registerRoute("DELETE",e,t,r,s);}options(e,t,r,s){this.registerRoute("OPTIONS",e,t,r,s);}head(e,t,r,s){this.registerRoute("HEAD",e,t,r,s);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],a=Array.isArray(t)?r:typeof t=="function"?t:void 0,c=this.joinPath(e),n=new o(c,[...this.middlewares,...s]);a?.(n);for(let u of n.getRoutes())this.addOrUpdate(u.method,u.path,u.middleware,u.handler,u.swaggerOptions);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,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(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}clearRoutes(){this.routes=[],this.staticRouteCache.clear(),this.trees.clear();}};new Ke;var Y=class{static scheduledJobs=[];static logger=F.child({scope:"CronService"});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 Z("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(this.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){this.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)this.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",a=>this.globalErrorHandler(a));this.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){this.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await glob(r,{absolute:true,cwd:B.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),F.error(s);});}));}};var oe=class extends q{static commandName="cron-start";static description="Start cron job scheduler";static help=["Start the cron job scheduler to run scheduled tasks","Loads cron jobs from specified patterns and starts scheduling","Example: npx balda cron-start","Example: npx balda cron-start src/crons/**/*.ts --patterns src/schedules/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting cron scheduler...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading cron jobs from patterns: ${e.join(", ")}`),await Y.massiveImportCronJobs(e);let t=Y.scheduledJobs.length;if(t===0){this.logger.warn("No cron jobs found. Make sure your cron jobs are decorated with @cron decorator");return}this.logger.info(`Found ${t} cron job(s)`),Y.run().then(()=>{this.logger.info("Cron scheduler started successfully. Press Ctrl+C to stop.");}).catch(r=>{this.logger.error("Error starting cron scheduler",r);});}};b([O({required:false,defaultValue:"src/crons/**/*.{ts,js}",description:"Primary glob pattern for cron jobs (default: src/crons/**/*.{ts,js})"})],oe,"pattern"),b([P.array({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for cron jobs"})],oe,"additionalPatterns");var xe=class extends q{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(){if(D.getCommand(this.name)){let s=D.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:s},`Command "${this.name}" already exists as a ${s} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=x.join(this.path,`${this.name}.ts`),await y.exists(x.join(process.cwd(),this.path))||await y.mkdir(x.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda";
6
+ (y/n): `;return new Promise(u=>{a.question(n,d=>{if(a.close(),d.toLowerCase()==="y"||d.toLowerCase()==="yes"){execSync(o,r),u(true);return}u(false);});})};var I=class extends q{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){if(typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1)),!await import('esbuild').then(n=>true).catch(()=>false)){let[n,u,d]=await N();await $(`${n} ${u} esbuild ${d}`,n,["esbuild"],{stdio:"inherit"})||(this.logger.warn("User chose to not continue with the installation of esbuild, exiting..."),process.exit(0));}let t=await import('esbuild').catch(n=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),r=je.join(this.output,"assets"),s=[];if(this.assets){let{copy:n}=await import('esbuild-plugin-copy').catch(u=>{throw this.logger.error("esbuild-plugin-copy is not installed, please install it with `npm install -D esbuild-plugin-copy` to use the build command"),new Error("esbuild-plugin-copy is not installed")});Pe.existsSync(r)||Pe.mkdirSync(r,{recursive:true}),s.push(n({assets:{from:this.assets,to:r}}));}this.clearDist&&Pe.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Pe.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let a=je.join(this.output,"server.js"),c=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:a,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});c.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:c.errors},null,2)),process.exit(1)),c.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:c.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${a}`,output:a,assets:!!this.assets},null,2)),process.exit(0);}};b([P({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],I,"clearDist"),b([P({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],I,"entry"),b([P({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],I,"output"),b([P({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],I,"tsconfig"),b([P({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],I,"assets"),b([P({type:"string",aliases:["f"],name:"format",required:false,defaultValue:"esm",description:"The format to build the project, default is esm, can be 'esm' or 'cjs'"})],I,"format"),b([P({type:"string",aliases:["p"],name:"packages",required:false,defaultValue:"external",description:"Weather to bundle node_modules or not, default is external, can be 'bundle' or 'external'"})],I,"packages"),b([P({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],I,"sourcemap");var Z=class extends Error{constructor(e){super(e);}};var L=class{static ajv=new Ajv({validateSchema:false,strict:false});static{this.ajv.addFormat("email",/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/),this.ajv.addFormat("url",/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/),this.ajv.addFormat("date",/^\d{4}-\d{2}-\d{2}$/),this.ajv.addFormat("datetime",/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})$/),this.ajv.addFormat("time",/^\d{2}:\d{2}:\d{2}$/),this.ajv.addFormat("binary",/^(?:[0-9a-fA-F]{2})+$/),this.ajv.addFormat("base64",/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/),this.ajv.addFormat("uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);}static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}};var j=new Map;var ct=new WeakMap,$t=0,M=(o,e="schema_ref")=>{let t=ct.get(o);return t||(t=Symbol(`${e}_${++$t}`),ct.set(o,t)),t};var J=class{static typeboxModule=null;static loadPromise=null;static async load(){return this.typeboxModule?this.typeboxModule:this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{try{return this.typeboxModule=await import('@sinclair/typebox'),this.typeboxModule}catch{throw new Error(`TypeBox is not installed. Install it with: npm install @sinclair/typebox
7
+ TypeBox is a peer dependency required when using TypeBox schemas for validation.`)}})(),this.loadPromise)}static get(){if(!this.typeboxModule)throw new Error("TypeBox has not been loaded yet. Call TypeBoxLoader.load() first.");return this.typeboxModule}static isTypeBoxSchema(e){return typeof e=="object"&&e!==null&&"type"in e&&Object.getOwnPropertySymbols(e).some(t=>t.toString()==="Symbol(TypeBox.Kind)")}};var D=class{static zodModule=null;static load(){if(this.zodModule)return this.zodModule;try{return this.zodModule=at("zod"),this.zodModule}catch{throw new Error(`Zod is not installed. Install it with: npm install zod
8
+ Zod is a peer dependency required when using Zod schemas for validation.`)}}static get(){return this.load()}static isZodSchema(e){this.load();let t=typeof e=="object"&&e!==null&&"_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function",r=this.zodModule?.z;if(t&&r&&!("toJSONSchema"in r))throw new Error("Zod4 is required with the toJSONSchema() method in order to work. Install it with: npm install zod with minimum version 4.0.0");return t}static toJSONSchema(e){return this.load(),this.zodModule?.z?.toJSONSchema?.(e)}};var dt=new Map,ut=o=>{if(!o)return null;try{let{jsonSchema:e,cacheKey:t}=Mt(o),r=dt.get(t);if(r)return r.serializer;let s=jt(e),a={serializer:s,schema:e,compiledAt:Date.now()};return dt.set(t,a),s}catch(e){return console.error("Failed to compile fast-json-stringify serializer:",e),null}},Mt=o=>{if(D.isZodSchema(o)){let t=M(o,"fast_stringify_zod");return {jsonSchema:D.toJSONSchema(o),cacheKey:t}}if(J.isTypeBoxSchema(o)){let t=M(o,"fast_stringify_typebox");return {jsonSchema:o,cacheKey:t}}if(typeof o=="object"&&o!==null){let t=M(o,"fast_stringify_json");return {jsonSchema:o,cacheKey:t}}let e=JSON.stringify(o);return {jsonSchema:o,cacheKey:e}};var Ke=new Map;var se=(o,e)=>{if(!o||typeof o!="object")return;if(D.isZodSchema(o)){let r=M(o,"json_schema_zod");Ke.set(r,e);return}if(J.isTypeBoxSchema(o)){let r=M(o,"json_schema_typebox");Ke.set(r,e);return}let t=M(o,"json_schema_json");Ke.set(t,e);};var At=o=>{if(D.isZodSchema(o)){let t=M(o,"serialize_zod");if(!j.has(t))try{let r=D.toJSONSchema(o);se(o,r);let s=L.ajv.compile(r);j.set(t,s);}catch(r){B.debug({error:r},"Failed to convert Zod schema to JSON Schema");return}return}if(J.isTypeBoxSchema(o)){let t=M(o,"serialize_typebox");if(!j.has(t)){se(o,o);let r=L.ajv.compile(o);j.set(t,r);}return}if(typeof o=="object"&&o!==null){let t=M(o,"serialize_json");if(!j.has(t)){se(o,o);let r=L.ajv.compile(o);j.set(t,r);}return}let e=JSON.stringify(o);if(!j.has(e)){let t=L.ajv.compile(o);j.set(e,t);}},pt=o=>{if(D.isZodSchema(o)){let t=M(o,"zod_schema");if(!j.has(t))try{let r=D.toJSONSchema(o);se(o,r);let s=L.ajv.compile(r);j.set(t,s);}catch{return}return}if(J.isTypeBoxSchema(o)){let t=M(o,"typebox_schema");if(!j.has(t)){se(o,o);let r=L.ajv.compile(o);j.set(t,r);}return}if(typeof o=="object"&&o!==null){let t=M(o,"json_schema");if(!j.has(t)){se(o,o);let r=L.ajv.compile(o);j.set(t,r);}return}let e=JSON.stringify(o);if(!j.has(e)){let t=L.ajv.compile(o);j.set(e,t);}},mt=(o,e)=>{o&&pt(o),e&&pt(e);},ht=o=>{if(!o||Object.keys(o).length===0)return;let e={};for(let[t,r]of Object.entries(o)){let s=Number(t);e[s]=r,At(r),ut(r);}return e};var we=class{staticChildren;paramChild;wildcardChild;middleware;handler;paramName;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null,this.paramName=null;}},Xe=class o{trees;routes;middlewares;basePath;staticRouteCache;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e),this.staticRouteCache=new Map;}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,a){e=e.toUpperCase();let c=t.split("?")[0];mt(a?.requestBody,a?.query);let n=ht(a?.responses),u=this.trees.get(e);u||(u=new we,this.trees.set(e,u));let d=c.replace(/^\/+|\/+$/g,""),l=d.length===0?[]:d.split("/"),i=true,h=[],p=u;for(let g of l){if(g==="*"){i=false,p.wildcardChild||(p.wildcardChild=new we),p=p.wildcardChild;break}if(g.startsWith(":")){i=false;let f=g.slice(1);h.push(f),p.paramChild||(p.paramChild={node:new we,name:f}),p=p.paramChild.node;continue}p.staticChildren.has(g)||p.staticChildren.set(g,new we),p=p.staticChildren.get(g);}if(p.middleware=r,p.handler=s,h.length>0&&(p.paramName=h.join(",")),i){let g="/"+d,f=`${e}:${g}`;this.staticRouteCache.set(f,{middleware:r,handler:s,params:{},responseSchemas:n});}else {let g="/"+d.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),f=`${e}:${g}`;this.staticRouteCache.delete(f);}let m=this.routes.findIndex(g=>g.method===e&&g.path===t);if(m!==-1){this.routes[m].middleware=r,this.routes[m].handler=s,this.routes[m].swaggerOptions=a,this.routes[m].responseSchemas=n;return}this.routes.push({method:e,path:t,middleware:r,handler:s,swaggerOptions:a,responseSchemas:n});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let a=`${e}:${r}`,c=this.staticRouteCache.get(a);if(c)return c;let n=this.trees.get(e);if(!n)return null;let u=r.replace(/^\/+|\/+$/g,""),d=u.length===0?[]:u.split("/"),l={},i=n;for(let p=0;p<d.length;p++){let m=d[p];if(i.staticChildren.has(m)){i=i.staticChildren.get(m);continue}if(i.paramChild){l[i.paramChild.name]=m,i=i.paramChild.node;continue}if(i.wildcardChild){l["*"]=d.slice(p).join("/"),i=i.wildcardChild;break}return null}if(!i.handler||!i.middleware)return null;let h=this.routes.find(p=>p.method===e&&p.handler===i.handler);return {middleware:i.middleware,handler:i.handler,params:l,responseSchemas:h?.responseSchemas}}registerRoute(e,t,r,s,a){let c=this.joinPath(t),n=typeof r=="function"&&r.length!==3,u=n?r:s,d=n?[]:Array.isArray(r)?r:[r],l=[...this.middlewares,...d],i=n?s:a;this.addOrUpdate(e,c,l,u,i);}get(e,t,r,s){this.registerRoute("GET",e,t,r,s);}post(e,t,r,s){this.registerRoute("POST",e,t,r,s);}patch(e,t,r,s){this.registerRoute("PATCH",e,t,r,s);}put(e,t,r,s){this.registerRoute("PUT",e,t,r,s);}delete(e,t,r,s){this.registerRoute("DELETE",e,t,r,s);}options(e,t,r,s){this.registerRoute("OPTIONS",e,t,r,s);}head(e,t,r,s){this.registerRoute("HEAD",e,t,r,s);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],a=Array.isArray(t)?r:typeof t=="function"?t:void 0,c=this.joinPath(e),n=new o(c,[...this.middlewares,...s]);a?.(n);for(let u of n.getRoutes())this.addOrUpdate(u.method,u.path,u.middleware,u.handler,u.swaggerOptions);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,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(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}clearRoutes(){this.routes=[],this.staticRouteCache.clear(),this.trees.clear();}};new Xe;var Y=class{static scheduledJobs=[];static logger=B.child({scope:"CronService"});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 Z("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(this.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){this.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)this.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",a=>this.globalErrorHandler(a));this.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){this.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await glob(r,{absolute:true,cwd:U.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),B.error(s);});}));}};var oe=class extends q{static commandName="cron-start";static description="Start cron job scheduler";static help=["Start the cron job scheduler to run scheduled tasks","Loads cron jobs from specified patterns and starts scheduling","Example: npx balda cron-start","Example: npx balda cron-start src/crons/**/*.ts --patterns src/schedules/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting cron scheduler...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading cron jobs from patterns: ${e.join(", ")}`),await Y.massiveImportCronJobs(e);let t=Y.scheduledJobs.length;if(t===0){this.logger.warn("No cron jobs found. Make sure your cron jobs are decorated with @cron decorator");return}this.logger.info(`Found ${t} cron job(s)`),Y.run().then(()=>{this.logger.info("Cron scheduler started successfully. Press Ctrl+C to stop.");}).catch(r=>{this.logger.error("Error starting cron scheduler",r);});}};b([O({required:false,defaultValue:"src/crons/**/*.{ts,js}",description:"Primary glob pattern for cron jobs (default: src/crons/**/*.{ts,js})"})],oe,"pattern"),b([P.array({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for cron jobs"})],oe,"additionalPatterns");var xe=class extends q{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(){if(Q.getCommand(this.name)){let s=Q.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:s},`Command "${this.name}" already exists as a ${s} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=x.join(this.path,`${this.name}.ts`),await y.exists(x.join(process.cwd(),this.path))||await y.mkdir(x.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda";
9
9
 
10
10
  export default class extends Command {
11
11
  static commandName = "${this.name}";
@@ -21,7 +21,7 @@ export default class extends Command {
21
21
  }
22
22
  }`}};b([O({description:"The name of the command to generate",required:true})],xe,"name");var ie=class extends q{static commandName="generate-controller";static description="Generate a new controller in the specified path";static help=["Generate a new controller in the specified path","Example: npx balda generate-controller user -p src/controllers"];static controllerName;static path;static async handle(){let e=this.getControllerTemplate(),t=`${this.controllerName.toLowerCase()}.ts`;this.path=x.join(this.path,t),await y.exists(x.join(process.cwd(),this.path))||await y.mkdir(x.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Controller ${this.controllerName} created successfully at ${this.path}`);}static getControllerTemplate(){let e=Ee(this.controllerName);return `import { controller, get, post, put, del, Request, Response } from "balda";
23
23
 
24
- @controller("/${tt(this.controllerName)}")
24
+ @controller("/${rt(this.controllerName)}")
25
25
  export default class ${e}Controller {
26
26
  @get("/")
27
27
  async index(req: Request, res: Response) {
@@ -128,7 +128,7 @@ export default class extends BaseQueue {
128
128
  `);}catch(w){console.error("\x1B[31m\u274C Error generating SDK:\x1B[0m",w);}finally{try{await y.unlink(C);}catch{}if(i){let w=l;try{console.log("\u{1F6D1} Stopping server..."),await w.close?.(),console.log(`\u2705 Server stopped.
129
129
  `);}catch{console.log(`\x1B[33m\u26A0\uFE0F Could not stop server gracefully.\x1B[0m
130
130
  `);}}}console.log(`\x1B[32m\u2728 SDK generation complete!\x1B[0m
131
- `);}};b([O({description:"Path to the server instance file (should export a Server instance)",required:false,defaultValue:"test/server/instance.ts"})],A,"serverPath"),b([P({description:"Output directory for generated SDK",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"sdk"})],A,"outputPath"),b([P({description:"Swagger UI path on your server",type:"string",aliases:["s"],name:"swagger-path",required:false})],A,"swaggerPath"),b([P({description:"HTTP client to use (axios or fetch)",type:"string",aliases:["c"],name:"client",required:false,defaultValue:"fetch"})],A,"httpClient"),b([P({description:"Unwrap response data automatically",type:"boolean",name:"unwrap-response-data",required:false,defaultValue:false})],A,"unwrapResponseData"),b([P({description:"Generate single HTTP client instance",type:"boolean",name:"single-http-client",required:false,defaultValue:false})],A,"singleHttpClient"),b([P({description:"Add prefix to all generated types",type:"string",name:"type-prefix",required:false})],A,"typePrefix"),b([P({description:"Add suffix to all generated types",type:"string",name:"type-suffix",required:false})],A,"typeSuffix"),b([P({description:"Use enum names as values",type:"boolean",name:"enum-names-as-values",required:false,defaultValue:false})],A,"enumNamesAsValues"),b([P({description:"Sort types alphabetically",type:"boolean",name:"sort-types",required:false,defaultValue:false})],A,"sortTypes");var L=class extends q{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static mqtt;static cron;static graphql;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await N();if(["npm","yarn","pnpm"].includes(e)){let n=await K(this.devDependencies);if(n.length&&(this.logger.info(`Found ${n.length} missing dev dependencies`),!await $(`${e} ${t} ${n.join(" ")} -${r}`,e,n,{stdio:"inherit"}))){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}n.length||this.logger.info("All dev dependencies are already installed");}if(this.mqtt&&["npm","yarn","pnpm"].includes(e)){let n=await K(["mqtt"]);n.length&&(await $(`${e} ${t} mqtt`,e,["mqtt"],{stdio:"inherit"},false)||(this.logger.info("MQTT installation cancelled by user. Skipping MQTT scaffolding."),this.mqtt=false)),n.length||this.logger.info("MQTT package is already installed");}if(this.cron&&["npm","yarn","pnpm"].includes(e)){let n=await K(["node-cron"]);n.length>0&&(await $(`${e} ${t} node-cron`,e,["node-cron"],{stdio:"inherit"},false)||(this.logger.info("node-cron installation cancelled by user. Skipping Cron scaffolding."),this.cron=false)),n.length||this.logger.info("node-cron package is already installed");}if(this.graphql&&["npm","yarn","pnpm"].includes(e)){let n=await K(["@apollo/server","@graphql-tools/schema","graphql"]);n.length>0&&(await $(`${e} ${t} ${n.join(" ")}`,e,n,{stdio:"inherit"},false)||(this.logger.info("GraphQL installation cancelled by user. Skipping GraphQL scaffolding."),this.graphql=false)),n.length||this.logger.info("GraphQL packages are already installed");}let s=this.typescript?"ts":"js",a=this.getServerTemplate(),c=this.getIndexTemplate();if(y.exists(this.srcPath)||await y.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${s} file...`),await y.writeFile(`${this.srcPath}/server.${s}`,new TextEncoder().encode(a)),this.logger.info(`Creating index.${s} file...`),await y.writeFile(`${this.srcPath}/index.${s}`,new TextEncoder().encode(c)),this.mqtt){let n=x.join(this.srcPath,"mqtt");await y.exists(n)||await y.mkdir(n,{recursive:true});let u=this.getMqttConfigTemplate();this.logger.info(`Creating mqtt/mqtt.config.${s} file...`),await y.writeFile(x.join(n,`mqtt.config.${s}`),new TextEncoder().encode(u));}if(this.cron){let n=x.join(this.srcPath,"cron");await y.exists(n)||await y.mkdir(n,{recursive:true});let u=this.getCronConfigTemplate();this.logger.info(`Creating cron/cron.config.${s} file...`),await y.writeFile(x.join(n,`cron.config.${s}`),new TextEncoder().encode(u));}if(this.graphql){let n=x.join(this.srcPath,"graphql");await y.exists(n)||await y.mkdir(n,{recursive:true});let u=this.getGraphqlConfigTemplate();this.logger.info(`Creating graphql/graphql.config.${s} file...`),await y.writeFile(x.join(n,`graphql.config.${s}`),new TextEncoder().encode(u));}this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda";
131
+ `);}};b([O({description:"Path to the server instance file (should export a Server instance)",required:false,defaultValue:"test/server/instance.ts"})],A,"serverPath"),b([P({description:"Output directory for generated SDK",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"sdk"})],A,"outputPath"),b([P({description:"Swagger UI path on your server",type:"string",aliases:["s"],name:"swagger-path",required:false})],A,"swaggerPath"),b([P({description:"HTTP client to use (axios or fetch)",type:"string",aliases:["c"],name:"client",required:false,defaultValue:"fetch"})],A,"httpClient"),b([P({description:"Unwrap response data automatically",type:"boolean",name:"unwrap-response-data",required:false,defaultValue:false})],A,"unwrapResponseData"),b([P({description:"Generate single HTTP client instance",type:"boolean",name:"single-http-client",required:false,defaultValue:false})],A,"singleHttpClient"),b([P({description:"Add prefix to all generated types",type:"string",name:"type-prefix",required:false})],A,"typePrefix"),b([P({description:"Add suffix to all generated types",type:"string",name:"type-suffix",required:false})],A,"typeSuffix"),b([P({description:"Use enum names as values",type:"boolean",name:"enum-names-as-values",required:false,defaultValue:false})],A,"enumNamesAsValues"),b([P({description:"Sort types alphabetically",type:"boolean",name:"sort-types",required:false,defaultValue:false})],A,"sortTypes");var H=class extends q{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static mqtt;static cron;static graphql;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await N();if(["npm","yarn","pnpm"].includes(e)){let n=await X(this.devDependencies);if(n.length&&(this.logger.info(`Found ${n.length} missing dev dependencies`),!await $(`${e} ${t} ${n.join(" ")} -${r}`,e,n,{stdio:"inherit"}))){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}n.length||this.logger.info("All dev dependencies are already installed");}if(this.mqtt&&["npm","yarn","pnpm"].includes(e)){let n=await X(["mqtt"]);n.length&&(await $(`${e} ${t} mqtt`,e,["mqtt"],{stdio:"inherit"},false)||(this.logger.info("MQTT installation cancelled by user. Skipping MQTT scaffolding."),this.mqtt=false)),n.length||this.logger.info("MQTT package is already installed");}if(this.cron&&["npm","yarn","pnpm"].includes(e)){let n=await X(["node-cron"]);n.length>0&&(await $(`${e} ${t} node-cron`,e,["node-cron"],{stdio:"inherit"},false)||(this.logger.info("node-cron installation cancelled by user. Skipping Cron scaffolding."),this.cron=false)),n.length||this.logger.info("node-cron package is already installed");}if(this.graphql&&["npm","yarn","pnpm"].includes(e)){let n=await X(["@apollo/server","@graphql-tools/schema","graphql"]);n.length>0&&(await $(`${e} ${t} ${n.join(" ")}`,e,n,{stdio:"inherit"},false)||(this.logger.info("GraphQL installation cancelled by user. Skipping GraphQL scaffolding."),this.graphql=false)),n.length||this.logger.info("GraphQL packages are already installed");}let s=this.typescript?"ts":"js",a=this.getServerTemplate(),c=this.getIndexTemplate();if(y.exists(this.srcPath)||await y.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${s} file...`),await y.writeFile(`${this.srcPath}/server.${s}`,new TextEncoder().encode(a)),this.logger.info(`Creating index.${s} file...`),await y.writeFile(`${this.srcPath}/index.${s}`,new TextEncoder().encode(c)),this.mqtt){let n=x.join(this.srcPath,"mqtt");await y.exists(n)||await y.mkdir(n,{recursive:true});let u=this.getMqttConfigTemplate();this.logger.info(`Creating mqtt/mqtt.config.${s} file...`),await y.writeFile(x.join(n,`mqtt.config.${s}`),new TextEncoder().encode(u));}if(this.cron){let n=x.join(this.srcPath,"cron");await y.exists(n)||await y.mkdir(n,{recursive:true});let u=this.getCronConfigTemplate();this.logger.info(`Creating cron/cron.config.${s} file...`),await y.writeFile(x.join(n,`cron.config.${s}`),new TextEncoder().encode(u));}if(this.graphql){let n=x.join(this.srcPath,"graphql");await y.exists(n)||await y.mkdir(n,{recursive:true});let u=this.getGraphqlConfigTemplate();this.logger.info(`Creating graphql/graphql.config.${s} file...`),await y.writeFile(x.join(n,`graphql.config.${s}`),new TextEncoder().encode(u));}this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda";
132
132
 
133
133
  const serverInstance = new Server({
134
134
  port: 80,
@@ -191,7 +191,7 @@ server.listen(({ url }) => {
191
191
  // Add your GraphQL type definitions and resolvers in separate files within this directory
192
192
  // The GraphQL endpoint is automatically available at /graphql
193
193
  // You can extend the schema using server.graphql.addTypeDef() and server.graphql.addResolver()
194
- `}};b([P.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],L,"srcPath"),b([P.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],L,"typescript"),b([P.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],L,"mqtt"),b([P.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],L,"cron"),b([P.boolean({description:"Initialize GraphQL service",aliases:"g",name:"graphql",required:false,defaultValue:false})],L,"graphql");var de=class extends q{static commandName="init-mailer";static description="Initialize mailer configuration with required dependencies";static help=["Initialize a mailer configuration file with basic setup","Automatically installs required packages for nodemailer and optional template engines","Supports Handlebars, EJS, Edge.js, Mustache, or custom adapters","Example: npx balda init-mailer -t handlebars -o src/mailer"];static templateEngine;static outputPath;static mailerDependencies={base:["nodemailer","@types/nodemailer"],handlebars:["handlebars","@types/handlebars"],ejs:["ejs","@types/ejs"],edge:["edge.js"],mustache:["mustache","@types/mustache"]};static async handle(){if(this.logger.info("Initializing mailer configuration..."),!["handlebars","ejs","edge","mustache","custom","none"].includes(this.templateEngine)){this.logger.error(`Invalid template engine: ${this.templateEngine}. Must be one of: handlebars, ejs, edge, mustache, custom, none`);return}let[e,t]=await N();if(["npm","yarn","pnpm"].includes(e)){let c=[...this.mailerDependencies.base,...this.templateEngine!=="none"&&this.templateEngine!=="custom"?this.mailerDependencies[this.templateEngine]||[]:[]],n=await K(c);if(n.length>0&&(this.logger.info(`Found ${n.length} missing dependencies for mailer`),!await $(`${e} ${t} ${n.join(" ")}`,e,n,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Mailer initialization aborted.");return}n.length===0&&this.logger.info("All mailer dependencies are already installed");}let r=this.getConfigTemplate(),s="mailer.config.ts",a=x.join(this.outputPath,s);await y.exists(this.outputPath)||await y.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await y.writeFile(a,new TextEncoder().encode(r)),this.logger.info(`Mailer configuration initialized successfully at ${a}`),this.logger.info("Remember to update the configuration with your actual SMTP credentials"),this.templateEngine!=="none"&&this.logger.info(`Template engine '${this.templateEngine}' configured and ready to use`);}static getConfigTemplate(){let e=this.templateEngine!=="none";return `import { createTransport } from "nodemailer";
194
+ `}};b([P.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],H,"srcPath"),b([P.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],H,"typescript"),b([P.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],H,"mqtt"),b([P.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],H,"cron"),b([P.boolean({description:"Initialize GraphQL service",aliases:"g",name:"graphql",required:false,defaultValue:false})],H,"graphql");var de=class extends q{static commandName="init-mailer";static description="Initialize mailer configuration with required dependencies";static help=["Initialize a mailer configuration file with basic setup","Automatically installs required packages for nodemailer and optional template engines","Supports Handlebars, EJS, Edge.js, Mustache, or custom adapters","Example: npx balda init-mailer -t handlebars -o src/mailer"];static templateEngine;static outputPath;static mailerDependencies={base:["nodemailer","@types/nodemailer"],handlebars:["handlebars","@types/handlebars"],ejs:["ejs","@types/ejs"],edge:["edge.js"],mustache:["mustache","@types/mustache"]};static async handle(){if(this.logger.info("Initializing mailer configuration..."),!["handlebars","ejs","edge","mustache","custom","none"].includes(this.templateEngine)){this.logger.error(`Invalid template engine: ${this.templateEngine}. Must be one of: handlebars, ejs, edge, mustache, custom, none`);return}let[e,t]=await N();if(["npm","yarn","pnpm"].includes(e)){let c=[...this.mailerDependencies.base,...this.templateEngine!=="none"&&this.templateEngine!=="custom"?this.mailerDependencies[this.templateEngine]||[]:[]],n=await X(c);if(n.length>0&&(this.logger.info(`Found ${n.length} missing dependencies for mailer`),!await $(`${e} ${t} ${n.join(" ")}`,e,n,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Mailer initialization aborted.");return}n.length===0&&this.logger.info("All mailer dependencies are already installed");}let r=this.getConfigTemplate(),s="mailer.config.ts",a=x.join(this.outputPath,s);await y.exists(this.outputPath)||await y.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await y.writeFile(a,new TextEncoder().encode(r)),this.logger.info(`Mailer configuration initialized successfully at ${a}`),this.logger.info("Remember to update the configuration with your actual SMTP credentials"),this.templateEngine!=="none"&&this.logger.info(`Template engine '${this.templateEngine}' configured and ready to use`);}static getConfigTemplate(){let e=this.templateEngine!=="none";return `import { createTransport } from "nodemailer";
195
195
  import { Mailer${e?`, ${this.getAdapterImport()}`:""} } from "balda";
196
196
 
197
197
  /**
@@ -318,7 +318,7 @@ const adapter = new CustomAdapter();
318
318
  * appName: "My App",
319
319
  * },
320
320
  * });
321
- *`}};b([P.string({description:"Template engine (handlebars, ejs, edge, mustache, custom, none) - optional",aliases:"t",name:"template",required:false,defaultValue:"none"})],de,"templateEngine"),b([P.string({description:"Output directory for mailer configuration, default is src/mailer",aliases:"o",name:"output",required:false,defaultValue:"src/mailer"})],de,"outputPath");var ue=class extends q{static commandName="init-queue";static description="Initialize queue provider configuration with required dependencies";static help=["Initialize a queue provider configuration file with basic credentials","Automatically installs required packages for the selected provider","Only scaffolds the connection, handlers should be created with generate-queue command","Example: npx balda init-queue -t bullmq -o src/queue"];static queueType;static outputPath;static queueDependencies={bullmq:["bullmq","ioredis"],sqs:["@aws-sdk/client-sqs","sqs-consumer"],pgboss:["pg-boss","pg"]};static async handle(){if(this.logger.info(`Initializing ${this.queueType} queue provider...`),!["bullmq","sqs","pgboss"].includes(this.queueType)){this.logger.error(`Invalid queue type: ${this.queueType}. Must be one of: bullmq, sqs, pgboss`);return}let[e,t]=await N();if(["npm","yarn","pnpm"].includes(e)){let c=this.queueDependencies[this.queueType],n=await K(c);if(n.length>0&&(this.logger.info(`Found ${n.length} missing dependencies for ${this.queueType}`),!await $(`${e} ${t} ${n.join(" ")}`,e,n,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Queue initialization aborted.");return}n.length===0&&this.logger.info(`All ${this.queueType} dependencies are already installed`);}let r=this.getConfigTemplate(),s=`${this.queueType}.config.ts`,a=x.join(this.outputPath,s);await y.exists(this.outputPath)||await y.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await y.writeFile(a,new TextEncoder().encode(r)),this.logger.info(`Queue configuration initialized successfully at ${a}`),this.logger.info("Remember to update the configuration with your actual credentials"),this.logger.info("Use 'npx balda generate-queue' to create queue handlers");}static getConfigTemplate(){return this.queueType==="bullmq"?this.getBullMQTemplate():this.queueType==="sqs"?this.getSQSTemplate():this.queueType==="pgboss"?this.getPGBossTemplate():""}static getBullMQTemplate(){return `import { defineBullMQConfiguration } from "balda";
321
+ *`}};b([P.string({description:"Template engine (handlebars, ejs, edge, mustache, custom, none) - optional",aliases:"t",name:"template",required:false,defaultValue:"none"})],de,"templateEngine"),b([P.string({description:"Output directory for mailer configuration, default is src/mailer",aliases:"o",name:"output",required:false,defaultValue:"src/mailer"})],de,"outputPath");var ue=class extends q{static commandName="init-queue";static description="Initialize queue provider configuration with required dependencies";static help=["Initialize a queue provider configuration file with basic credentials","Automatically installs required packages for the selected provider","Only scaffolds the connection, handlers should be created with generate-queue command","Example: npx balda init-queue -t bullmq -o src/queue"];static queueType;static outputPath;static queueDependencies={bullmq:["bullmq","ioredis"],sqs:["@aws-sdk/client-sqs","sqs-consumer"],pgboss:["pg-boss","pg"]};static async handle(){if(this.logger.info(`Initializing ${this.queueType} queue provider...`),!["bullmq","sqs","pgboss"].includes(this.queueType)){this.logger.error(`Invalid queue type: ${this.queueType}. Must be one of: bullmq, sqs, pgboss`);return}let[e,t]=await N();if(["npm","yarn","pnpm"].includes(e)){let c=this.queueDependencies[this.queueType],n=await X(c);if(n.length>0&&(this.logger.info(`Found ${n.length} missing dependencies for ${this.queueType}`),!await $(`${e} ${t} ${n.join(" ")}`,e,n,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Queue initialization aborted.");return}n.length===0&&this.logger.info(`All ${this.queueType} dependencies are already installed`);}let r=this.getConfigTemplate(),s=`${this.queueType}.config.ts`,a=x.join(this.outputPath,s);await y.exists(this.outputPath)||await y.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await y.writeFile(a,new TextEncoder().encode(r)),this.logger.info(`Queue configuration initialized successfully at ${a}`),this.logger.info("Remember to update the configuration with your actual credentials"),this.logger.info("Use 'npx balda generate-queue' to create queue handlers");}static getConfigTemplate(){return this.queueType==="bullmq"?this.getBullMQTemplate():this.queueType==="sqs"?this.getSQSTemplate():this.queueType==="pgboss"?this.getPGBossTemplate():""}static getBullMQTemplate(){return `import { defineBullMQConfiguration } from "balda";
322
322
 
323
323
  // Configure BullMQ connection and default options
324
324
  defineBullMQConfiguration({
@@ -487,18 +487,18 @@ definePGBossConfiguration({
487
487
  * console.log("Processing:", payload);
488
488
  * });
489
489
  */
490
- `}};b([P.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],ue,"queueType"),b([P.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],ue,"outputPath");var Se=class extends q{static commandName="key-generate";static description="Generate application encryption key pairs";static help=["Generate secure RSA public/private key pairs for application encryption","Keys are automatically saved to .env file","Example: npx balda key-generate","Example: npx balda key-generate --type async"];static type;static async handle(){let e=this.type??"sync";if(!["sync","async"].includes(e)){this.logger.error(`Invalid key type: ${e}. Must be sync or async`);return}let{publicKey:t,privateKey:r}=Nt.generateKeyPairSync("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),s=e==="sync"?"APP_PUBLIC_KEY":"APP_PUBLIC_KEY_ASYNC",a=e==="sync"?"APP_PRIVATE_KEY":"APP_PRIVATE_KEY_ASYNC";console.log(`
490
+ `}};b([P.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],ue,"queueType"),b([P.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],ue,"outputPath");var Se=class extends q{static commandName="key-generate";static description="Generate application encryption key pairs";static help=["Generate secure RSA public/private key pairs for application encryption","Keys are automatically saved to .env file","Example: npx balda key-generate","Example: npx balda key-generate --type async"];static type;static async handle(){let e=this.type??"sync";if(!["sync","async"].includes(e)){this.logger.error(`Invalid key type: ${e}. Must be sync or async`);return}let{publicKey:t,privateKey:r}=Dt.generateKeyPairSync("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),s=e==="sync"?"APP_PUBLIC_KEY":"APP_PUBLIC_KEY_ASYNC",a=e==="sync"?"APP_PRIVATE_KEY":"APP_PRIVATE_KEY_ASYNC";console.log(`
491
491
  \u2728 Generated ${e==="sync"?"Sync":"Async"} Key Pair:
492
492
  `),console.log(`\x1B[33mPublic Key (${s}):\x1B[0m`),console.log(`\x1B[32m${t}\x1B[0m`),console.log(`\x1B[33mPrivate Key (${a}):\x1B[0m`),console.log(`\x1B[32m${r}\x1B[0m`),await this.saveKeyToEnvFile(s,t),await this.saveKeyToEnvFile(a,r),console.log(`\x1B[90m\u{1F4A1} Keys saved to .env file as ${s} and ${a}\x1B[0m
493
- `);}static async saveKeyToEnvFile(e,t){let r=je.join(B.getCwd(),".env"),s=`${e}="${t}"`;if(Pe.existsSync(r)){let a=Pe.readFileSync(r,"utf-8"),c=new RegExp(`^${e}=.*$`,"m");if(c.test(a)){let n=a.replace(c,s);Pe.writeFileSync(r,n),this.logger.info(`Updated ${e} in .env file`);return}Pe.appendFileSync(r,`
493
+ `);}static async saveKeyToEnvFile(e,t){let r=je.join(U.getCwd(),".env"),s=`${e}="${t}"`;if(Pe.existsSync(r)){let a=Pe.readFileSync(r,"utf-8"),c=new RegExp(`^${e}=.*$`,"m");if(c.test(a)){let n=a.replace(c,s);Pe.writeFileSync(r,n),this.logger.info(`Updated ${e} in .env file`);return}Pe.appendFileSync(r,`
494
494
  ${s}
495
495
  `),this.logger.info(`Added ${e} to .env file`);return}Pe.writeFileSync(r,`${s}
496
- `),this.logger.info(`Created .env file with ${e}`);}};b([P.string({aliases:["t"],name:"type",required:false,defaultValue:"sync",description:"Key type: sync or async (default: sync)"})],Se,"type");var Te=class extends q{static commandName="list";static description="List all available commands";static help=["Display all registered Balda CLI commands with their descriptions","Example: npx balda list"];static async handle(){let e=D.getBuiltInCommands(),t=D.getUserDefinedCommands();if(console.log(`
496
+ `),this.logger.info(`Created .env file with ${e}`);}};b([P.string({aliases:["t"],name:"type",required:false,defaultValue:"sync",description:"Key type: sync or async (default: sync)"})],Se,"type");var Te=class extends q{static commandName="list";static description="List all available commands";static help=["Display all registered Balda CLI commands with their descriptions","Example: npx balda list"];static async handle(){let e=Q.getBuiltInCommands(),t=Q.getUserDefinedCommands();if(console.log(`
497
497
  \u2728 Available Balda Commands:
498
498
  `),t.length>0){console.log(`\x1B[1;33mUser Commands:\x1B[0m
499
499
  `);let r=this.groupByCategory(t);this.displayCategorizedCommands(r);}if(e.length>0){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
500
500
  `);let r=e.sort((a,c)=>a.commandName.localeCompare(c.commandName)),s=Math.max(...r.map(a=>a.commandName.length));for(let a of r){let c=a.commandName.padEnd(s+2),n=a.description||"No description available",u="";a.options?.deprecated&&(u=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${c}\x1B[0m ${n}${u}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
501
- `);}static groupByCategory(e){let t=new Map;for(let r of e){let s=r.options?.category||"other";t.has(s)||t.set(s,[]),t.get(s).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let s=e.get(r).filter(u=>u&&u.commandName).sort((u,d)=>u.commandName.localeCompare(d.commandName));if(s.length===0)continue;let c={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${c}${r.toUpperCase()}:\x1B[0m`);let n=Math.max(...s.map(u=>u.commandName.length));for(let u of s){let d=u.commandName.padEnd(n+2),l=u.description||"No description available",i="";u.options?.deprecated&&(i=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${d}\x1B[0m ${l}${i}`);}console.log("");}}};var Q=class extends Z{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var Ge=class{randomUUID(){return crypto.randomUUID()}},Ce=new Ge;var G=class{static options={connection:{}}};var ke=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),a=Ce.randomUUID();return await s.add(e,t,{jobId:a,...G.options?.defaultJobOptions,...r}),{id:a}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=G.options??{},a=await this.getBullMQClient(),c=new a.Worker(e,async n=>{try{await t(n.data);}catch(u){await r?.(n,u)??Promise.reject(u);}},{...s});this.workers.set(e,c);}async unsubscribe(e){let t=this.workers.get(e);t&&(await t.close(),this.workers.delete(e));}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new Q("bullmq","ioredis")}),r=new t.Queue(e,{...G.options||{connection:{}}});this.queues.set(e,r);}return this.queues.get(e)}async getBullMQClient(){return this.bullmqClient||(this.bullmqClient=await import('bullmq').catch(()=>{throw new Q("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let a=await this.getQueueWithConfig(e,s),c=Ce.randomUUID(),n={jobId:c,...G.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await a.add(e,t,n),{id:c}}async subscribeWithConfig(e,t,r){let s=this.getWorkerKey(e,r);if(this.workers.has(s))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let a=G.options??{},{errorHandler:c}=a,n=await this.getBullMQClient(),u={...a,...r};delete u.errorHandler,delete u.defaultJobOptions;let d=new n.Worker(e,async l=>{try{await t(l.data);}catch(i){await c?.(l,i)??Promise.reject(i);}},u);this.workers.set(s,d);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new Q("bullmq","ioredis")}),a={...G.options||{connection:{}},...t},c=new s.Queue(e,a);this.queues.set(r,c);}return this.queues.get(r)}getQueueKey(e,t){return t?.connection?`${e}:${JSON.stringify(t.connection)}`:e}getWorkerKey(e,t){return this.getQueueKey(e,t)}};var Ne=class{subscribers=new Map;messageQueue=[];maxQueueSize;processingPromise=null;constructor(e=1e4){this.maxQueueSize=e;}clear(){this.subscribers.clear(),this.messageQueue=[],this.processingPromise=null;}async publish(e,t,r){if(this.messageQueue.length>=this.maxQueueSize)throw new Error(`Queue full: ${this.maxQueueSize} messages pending`);let s=Ce.randomUUID();return this.messageQueue.push({topic:e,payload:t}),this.processingPromise||(this.processingPromise=this.processQueue().catch(a=>{console.error("[MemoryPubSub] Fatal queue processing error:",a);}).finally(()=>{this.processingPromise=null;})),{id:s}}async subscribe(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=t;this.subscribers.get(e).add(r);}async unsubscribe(e){this.subscribers.delete(e);}async processQueue(){for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();if(!e)break;let t=this.subscribers.get(e.topic);t&&t.size>0&&await Promise.allSettled(Array.from(t).map(r=>r(e.payload).catch(s=>{console.error(`[MemoryPubSub] Handler error for topic "${e.topic}":`,s);})));}}};var H=class{static options={}};var _e=class{createdQueues=new Set;workers=new Map;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let a=r||{},c=await s.send(e,t,a);return {id:String(c??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=H.options;s.errorHandler&&r.on("error",s.errorHandler);let a=await r.work(e,async c=>{let n=Array.isArray(c)?c:[c];for(let u of n)await t(u.data);});this.workers.set(e,a);}async unsubscribe(e){let t=await this.getBoss(),r=this.workers.get(e);r&&(await t.offWork(r),this.workers.delete(e));}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new Q("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:a}=H.options,c=s??a,n=new r(c);return H.options?.errorHandler&&n.on("error",H.options.errorHandler),await n.start(),this.boss=n,this.boss}async ensureQueue(e){if(this.createdQueues.has(e))return;let t=await this.getBoss();typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e);}async publishWithConfig(e,t,r,s){let a=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,a);let c=r||{},n=await a.send(e,t,c);return {id:String(n??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let a=H.options;a.errorHandler&&s.on("error",a.errorHandler);let c=`${e}:${r?.connectionString??"default"}`,n=await s.work(e,async u=>{let d=Array.isArray(u)?u:[u];for(let l of d)await t(l.data);});this.workers.set(c,n);}bossInstances=new Map;async getBossWithConfig(e){if(!e?.connectionString)return this.getBoss();let t=e.connectionString;if(this.bossInstances.has(t))return this.bossInstances.get(t);let r=await import('pg-boss').catch(()=>{throw new Q("pg-boss","pg")}),a=r.PgBoss.default??r.PgBoss,c=new a(e.connectionString);return H.options?.errorHandler&&c.on("error",H.options.errorHandler),await c.start(),this.bossInstances.set(t,c),c}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var pe=class{static options={}};var Ie=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:a}=await this.getSqsLib(),c=await this.resolveQueueUrl(e);if(!c)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let n=new a({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c,...r??{}});return {id:(await s.send(n)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=pe.options,s=await this.getSqsConsumerLib(),a={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async u=>{let d=JSON.parse(u.Body||"{}");await t(d);}},c=s.Consumer.create(a),n=r.errorHandler;n&&(c.on("error",n),c.on("processing_error",n)),c.start(),this.consumers.set(e,c);}async unsubscribe(e){let t=this.consumers.get(e);t&&(t.stop(),this.consumers.delete(e));}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=pe.options.client;return this.client=new e(t??{}),this.client}async getSqsLib(){return this.sqsLib||(this.sqsLib=await import('@aws-sdk/client-sqs').catch(()=>{throw new Q("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new Q("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=pe.options.consumer?.queueUrlMap;if(!r?.[e])throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r[e]}async publishWithConfig(e,t,r,s){let{...a}=r??{},c=await this.getClientWithConfig(s?.client),{SendMessageCommand:n}=await this.getSqsLib(),u=s?.queueUrl??await this.resolveQueueUrl(e),d=new n({...a,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:u});return {id:(await c.send(d)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=pe.options,a=await this.getSqsConsumerLib(),c=r?.queueUrl??await this.resolveQueueUrl(e),n={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:c,handleMessage:async l=>{let i=JSON.parse(l.Body||"{}");await t(i);}},u=a.Consumer.create(n),d=s.errorHandler;d&&(u.on("error",d),u.on("processing_error",d)),u.start(),this.consumers.set(e,u);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var De=class{static map=new Map;static{this.map.set("bullmq",new ke),this.map.set("sqs",new Ie),this.map.set("pgboss",new _e),this.map.set("memory",new Ne);}static getProvider(e){if(!this.map.has(e))throw new Error(`[QueueSubscriber] Provider ${e} not found`);return this.map.get(e)}static setProvider(e,t){this.map.set(e,t);}static clearMemoryProvider(){let e=this.map.get("memory");e&&"clear"in e&&e.clear();}};var me=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static logger=F.child({scope:"QueueService"});static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,a){let c=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(c)&&this.logger.warn(`Queue handler for ${c} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(c,{name:e,topic:t,handler:r,provider:s,queueOptions:a});}static registerCustomQueue(e,t,r,s){let a=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(a)&&this.logger.warn(`Custom queue handler for ${a} already registered, overwriting previous handler`),this.customQueueSubscribers.set(a,{name:e,topic:t,handler:r,pubsub:s});}static async run(){this.logger.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){this.logger.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:a,provider:c,queueOptions:n}=r;this.logger.info(`Subscribing to queue: ${s}`);let u=De.getProvider(c);n&&"subscribeWithConfig"in u&&typeof u.subscribeWithConfig=="function"?await u.subscribeWithConfig(s,a,n):await u.subscribe(s,a);}for(let{topic:r,handler:s,pubsub:a}of this.customQueueSubscribers.values())this.logger.info(`Subscribing to custom queue: ${r}`),await a.subscribe(r,s);this.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let a=await glob(s,{absolute:true,cwd:B.getCwd()});this.logger.info(`Pattern "${s}" matched ${a.length} file(s)`),r.push(...a);}if(r.length===0){this.logger.warn("No files matched the provided patterns");return}this.logger.info(`Importing ${r.length} queue handler file(s)`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing: ${s}`),await import(s).catch(a=>{if(this.logger.error(`Error importing queue handler: ${s}`),this.logger.error(a),t.throwOnError)throw a});})),this.logger.info(`Successfully imported ${r.length} file(s)`);}};var he=class extends q{static commandName="queue-start";static description="Start queue workers to process jobs";static help=["Start queue workers to process jobs from registered queues","Loads queue handlers from specified patterns and starts processing","Example: npx balda queue-start","Example: npx balda queue-start src/queues/**/*.ts --patterns src/jobs/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting queue workers...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading queue handlers from patterns: ${e.join(", ")}`),await me.massiveImportQueues(e,{throwOnError:false});let t=me.typedQueueSubscribers.size,r=me.customQueueSubscribers.size,s=t+r;if(s===0){this.logger.warn("No queue handlers found. Make sure your queue handlers are decorated with @queue decorator");return}this.logger.info(`Found ${s} queue handler(s) (${t} typed, ${r} custom)`),me.run().then(()=>{this.logger.info("Queue workers started successfully. Press Ctrl+C to stop.");}).catch(a=>{this.logger.error("Error starting queue workers",a);});}};b([O({required:false,defaultValue:"src/queues/**/*.{ts,js}",description:"Primary glob pattern for queue handlers (default: src/queues/**/*.{ts,js})"})],he,"pattern"),b([P.list({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for queue handlers"})],he,"additionalPatterns");var ge=class extends q{static commandName="serve";static description="Run the server in dev mode with hot reload";static help=["This command is intended to be run from the root of the project","Bun and Deno have native dev hot reload","Runtime is automatically inferred","Node.js requires tsx to be installed for both typescript and javascript files","Node.js dev dependencies (tsx) are installed automatically if not detected"];static runtime=R.type;static options={keepAlive:true};static entry;static denoImportMap;static async handle(){if(this.runtime==="bun"){execSync(`bun run --watch ${this.entry}`,{stdio:"inherit",cwd:B.getCwd()});return}if(this.runtime==="deno"){let e="deno run --watch --unstable-sloppy-imports --allow-all";this.denoImportMap&&(e=`${e} --import-map ${this.denoImportMap}`),execSync(`${e} ${this.entry}`,{stdio:"inherit",cwd:B.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!Pe.existsSync("node_modules/.bin/tsx")){let[r,s,a]=await N();if(!await $(`${r} ${s} tsx ${a}`,r,["tsx"],{stdio:"inherit"})){this.logger.info("Installation cancelled by user. Cannot start dev server without tsx.");return}}let t=this.calledBy!=="node"?this.calledBy:"npx";execSync(`${t} tsx watch ${this.entry}`,{stdio:"inherit",cwd:process.cwd()});}};b([O({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],ge,"entry"),b([P.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],ge,"denoImportMap");var fe=class extends q{static commandName="init-storage";static description="Setup storage provider with required dependencies";static help=["Install dependencies and create storage configuration for a specific provider","Flags:"," -t, --type <provider> Storage provider type (s3, azure, local)"," -o, --output <path> Output directory for storage setup (default: src/storage/)","","Examples:"," npx balda setup:storage -t s3"," npx balda setup:storage --type azure --output src/config/"];static storageType;static outputPath;static async handle(){if(!this.storageType){console.error("\x1B[31m\u274C Error: Storage type is required. Use -t or --type flag.\x1B[0m"),console.log(`\x1B[90mExample: npx balda setup:storage -t s3\x1B[0m
501
+ `);}static groupByCategory(e){let t=new Map;for(let r of e){let s=r.options?.category||"other";t.has(s)||t.set(s,[]),t.get(s).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let s=e.get(r).filter(u=>u&&u.commandName).sort((u,d)=>u.commandName.localeCompare(d.commandName));if(s.length===0)continue;let c={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${c}${r.toUpperCase()}:\x1B[0m`);let n=Math.max(...s.map(u=>u.commandName.length));for(let u of s){let d=u.commandName.padEnd(n+2),l=u.description||"No description available",i="";u.options?.deprecated&&(i=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${d}\x1B[0m ${l}${i}`);}console.log("");}}};var F=class extends Z{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var Ve=class{randomUUID(){return crypto.randomUUID()}},Ce=new Ve;var G=class{static options={connection:{}}};var ke=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),a=Ce.randomUUID();return await s.add(e,t,{jobId:a,...G.options?.defaultJobOptions,...r}),{id:a}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=G.options??{},a=await this.getBullMQClient(),c=new a.Worker(e,async n=>{try{await t(n.data);}catch(u){await r?.(n,u)??Promise.reject(u);}},{...s});this.workers.set(e,c);}async unsubscribe(e){let t=this.workers.get(e);t&&(await t.close(),this.workers.delete(e));}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new F("bullmq","ioredis")}),r=new t.Queue(e,{...G.options||{connection:{}}});this.queues.set(e,r);}return this.queues.get(e)}async getBullMQClient(){return this.bullmqClient||(this.bullmqClient=await import('bullmq').catch(()=>{throw new F("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let a=await this.getQueueWithConfig(e,s),c=Ce.randomUUID(),n={jobId:c,...G.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await a.add(e,t,n),{id:c}}async subscribeWithConfig(e,t,r){let s=this.getWorkerKey(e,r);if(this.workers.has(s))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let a=G.options??{},{errorHandler:c}=a,n=await this.getBullMQClient(),u={...a,...r};delete u.errorHandler,delete u.defaultJobOptions;let d=new n.Worker(e,async l=>{try{await t(l.data);}catch(i){await c?.(l,i)??Promise.reject(i);}},u);this.workers.set(s,d);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new F("bullmq","ioredis")}),a={...G.options||{connection:{}},...t},c=new s.Queue(e,a);this.queues.set(r,c);}return this.queues.get(r)}getQueueKey(e,t){return t?.connection?`${e}:${JSON.stringify(t.connection)}`:e}getWorkerKey(e,t){return this.getQueueKey(e,t)}};var Ne=class{subscribers=new Map;messageQueue=[];maxQueueSize;processingPromise=null;constructor(e=1e4){this.maxQueueSize=e;}clear(){this.subscribers.clear(),this.messageQueue=[],this.processingPromise=null;}async publish(e,t,r){if(this.messageQueue.length>=this.maxQueueSize)throw new Error(`Queue full: ${this.maxQueueSize} messages pending`);let s=Ce.randomUUID();return this.messageQueue.push({topic:e,payload:t}),this.processingPromise||(this.processingPromise=this.processQueue().catch(a=>{console.error("[MemoryPubSub] Fatal queue processing error:",a);}).finally(()=>{this.processingPromise=null;})),{id:s}}async subscribe(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=t;this.subscribers.get(e).add(r);}async unsubscribe(e){this.subscribers.delete(e);}async processQueue(){for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();if(!e)break;let t=this.subscribers.get(e.topic);t&&t.size>0&&await Promise.allSettled(Array.from(t).map(r=>r(e.payload).catch(s=>{console.error(`[MemoryPubSub] Handler error for topic "${e.topic}":`,s);})));}}};var W=class{static options={}};var _e=class{createdQueues=new Set;workers=new Map;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let a=r||{},c=await s.send(e,t,a);return {id:String(c??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=W.options;s.errorHandler&&r.on("error",s.errorHandler);let a=await r.work(e,async c=>{let n=Array.isArray(c)?c:[c];for(let u of n)await t(u.data);});this.workers.set(e,a);}async unsubscribe(e){let t=await this.getBoss(),r=this.workers.get(e);r&&(await t.offWork(r),this.workers.delete(e));}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new F("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:a}=W.options,c=s??a,n=new r(c);return W.options?.errorHandler&&n.on("error",W.options.errorHandler),await n.start(),this.boss=n,this.boss}async ensureQueue(e){if(this.createdQueues.has(e))return;let t=await this.getBoss();typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e);}async publishWithConfig(e,t,r,s){let a=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,a);let c=r||{},n=await a.send(e,t,c);return {id:String(n??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let a=W.options;a.errorHandler&&s.on("error",a.errorHandler);let c=`${e}:${r?.connectionString??"default"}`,n=await s.work(e,async u=>{let d=Array.isArray(u)?u:[u];for(let l of d)await t(l.data);});this.workers.set(c,n);}bossInstances=new Map;async getBossWithConfig(e){if(!e?.connectionString)return this.getBoss();let t=e.connectionString;if(this.bossInstances.has(t))return this.bossInstances.get(t);let r=await import('pg-boss').catch(()=>{throw new F("pg-boss","pg")}),a=r.PgBoss.default??r.PgBoss,c=new a(e.connectionString);return W.options?.errorHandler&&c.on("error",W.options.errorHandler),await c.start(),this.bossInstances.set(t,c),c}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var pe=class{static options={}};var Ie=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:a}=await this.getSqsLib(),c=await this.resolveQueueUrl(e);if(!c)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let n=new a({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c,...r??{}});return {id:(await s.send(n)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=pe.options,s=await this.getSqsConsumerLib(),a={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async u=>{let d=JSON.parse(u.Body||"{}");await t(d);}},c=s.Consumer.create(a),n=r.errorHandler;n&&(c.on("error",n),c.on("processing_error",n)),c.start(),this.consumers.set(e,c);}async unsubscribe(e){let t=this.consumers.get(e);t&&(t.stop(),this.consumers.delete(e));}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=pe.options.client;return this.client=new e(t??{}),this.client}async getSqsLib(){return this.sqsLib||(this.sqsLib=await import('@aws-sdk/client-sqs').catch(()=>{throw new F("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new F("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=pe.options.consumer?.queueUrlMap;if(!r?.[e])throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r[e]}async publishWithConfig(e,t,r,s){let{...a}=r??{},c=await this.getClientWithConfig(s?.client),{SendMessageCommand:n}=await this.getSqsLib(),u=s?.queueUrl??await this.resolveQueueUrl(e),d=new n({...a,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:u});return {id:(await c.send(d)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=pe.options,a=await this.getSqsConsumerLib(),c=r?.queueUrl??await this.resolveQueueUrl(e),n={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:c,handleMessage:async l=>{let i=JSON.parse(l.Body||"{}");await t(i);}},u=a.Consumer.create(n),d=s.errorHandler;d&&(u.on("error",d),u.on("processing_error",d)),u.start(),this.consumers.set(e,u);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var De=class{static map=new Map;static{this.map.set("bullmq",new ke),this.map.set("sqs",new Ie),this.map.set("pgboss",new _e),this.map.set("memory",new Ne);}static getProvider(e){if(!this.map.has(e))throw new Error(`[QueueSubscriber] Provider ${e} not found`);return this.map.get(e)}static setProvider(e,t){this.map.set(e,t);}static clearMemoryProvider(){let e=this.map.get("memory");e&&"clear"in e&&e.clear();}};var me=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static logger=B.child({scope:"QueueService"});static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,a){let c=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(c)&&this.logger.warn(`Queue handler for ${c} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(c,{name:e,topic:t,handler:r,provider:s,queueOptions:a});}static registerCustomQueue(e,t,r,s){let a=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(a)&&this.logger.warn(`Custom queue handler for ${a} already registered, overwriting previous handler`),this.customQueueSubscribers.set(a,{name:e,topic:t,handler:r,pubsub:s});}static async run(){this.logger.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){this.logger.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:a,provider:c,queueOptions:n}=r;this.logger.info(`Subscribing to queue: ${s}`);let u=De.getProvider(c);n&&"subscribeWithConfig"in u&&typeof u.subscribeWithConfig=="function"?await u.subscribeWithConfig(s,a,n):await u.subscribe(s,a);}for(let{topic:r,handler:s,pubsub:a}of this.customQueueSubscribers.values())this.logger.info(`Subscribing to custom queue: ${r}`),await a.subscribe(r,s);this.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let a=await glob(s,{absolute:true,cwd:U.getCwd()});this.logger.info(`Pattern "${s}" matched ${a.length} file(s)`),r.push(...a);}if(r.length===0){this.logger.warn("No files matched the provided patterns");return}this.logger.info(`Importing ${r.length} queue handler file(s)`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing: ${s}`),await import(s).catch(a=>{if(this.logger.error(`Error importing queue handler: ${s}`),this.logger.error(a),t.throwOnError)throw a});})),this.logger.info(`Successfully imported ${r.length} file(s)`);}};var he=class extends q{static commandName="queue-start";static description="Start queue workers to process jobs";static help=["Start queue workers to process jobs from registered queues","Loads queue handlers from specified patterns and starts processing","Example: npx balda queue-start","Example: npx balda queue-start src/queues/**/*.ts --patterns src/jobs/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting queue workers...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading queue handlers from patterns: ${e.join(", ")}`),await me.massiveImportQueues(e,{throwOnError:false});let t=me.typedQueueSubscribers.size,r=me.customQueueSubscribers.size,s=t+r;if(s===0){this.logger.warn("No queue handlers found. Make sure your queue handlers are decorated with @queue decorator");return}this.logger.info(`Found ${s} queue handler(s) (${t} typed, ${r} custom)`),me.run().then(()=>{this.logger.info("Queue workers started successfully. Press Ctrl+C to stop.");}).catch(a=>{this.logger.error("Error starting queue workers",a);});}};b([O({required:false,defaultValue:"src/queues/**/*.{ts,js}",description:"Primary glob pattern for queue handlers (default: src/queues/**/*.{ts,js})"})],he,"pattern"),b([P.list({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for queue handlers"})],he,"additionalPatterns");var ge=class extends q{static commandName="serve";static description="Run the server in dev mode with hot reload";static help=["This command is intended to be run from the root of the project","Bun and Deno have native dev hot reload","Runtime is automatically inferred","Node.js requires tsx to be installed for both typescript and javascript files","Node.js dev dependencies (tsx) are installed automatically if not detected"];static runtime=R.type;static options={keepAlive:true};static entry;static denoImportMap;static async handle(){if(this.runtime==="bun"){execSync(`bun run --watch ${this.entry}`,{stdio:"inherit",cwd:U.getCwd()});return}if(this.runtime==="deno"){let e="deno run --watch --unstable-sloppy-imports --allow-all";this.denoImportMap&&(e=`${e} --import-map ${this.denoImportMap}`),execSync(`${e} ${this.entry}`,{stdio:"inherit",cwd:U.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!Pe.existsSync("node_modules/.bin/tsx")){let[r,s,a]=await N();if(!await $(`${r} ${s} tsx ${a}`,r,["tsx"],{stdio:"inherit"})){this.logger.info("Installation cancelled by user. Cannot start dev server without tsx.");return}}let t=this.calledBy!=="node"?this.calledBy:"npx";execSync(`${t} tsx watch ${this.entry}`,{stdio:"inherit",cwd:process.cwd()});}};b([O({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],ge,"entry"),b([P.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],ge,"denoImportMap");var fe=class extends q{static commandName="init-storage";static description="Setup storage provider with required dependencies";static help=["Install dependencies and create storage configuration for a specific provider","Flags:"," -t, --type <provider> Storage provider type (s3, azure, local)"," -o, --output <path> Output directory for storage setup (default: src/storage/)","","Examples:"," npx balda setup:storage -t s3"," npx balda setup:storage --type azure --output src/config/"];static storageType;static outputPath;static async handle(){if(!this.storageType){console.error("\x1B[31m\u274C Error: Storage type is required. Use -t or --type flag.\x1B[0m"),console.log(`\x1B[90mExample: npx balda setup:storage -t s3\x1B[0m
502
502
  `);return}this.outputPath||await y.mkdir(x.join(process.cwd(),this.outputPath),{recursive:true});let e=["s3","azure","local"];if(!e.includes(this.storageType)){console.error(`\x1B[31m\u274C Error: Invalid storage type '${this.storageType}'. Valid types: ${e.join(", ")}\x1B[0m
503
503
  `);return}console.log(`
504
504
  \u{1F680} Setting up ${this.storageType.toUpperCase()} storage provider...
@@ -588,11 +588,11 @@ export const storage = new Storage(
588
588
  defaultProvider: "local",
589
589
  },
590
590
  );
591
- `}[e]||""}};b([P({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],fe,"storageType"),b([P({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],fe,"outputPath");var Ft=[ce,xe,ne,le,ee,ie,ae,A,L,de,ue,Te,I,ge,fe,Se,he,oe],V=class o{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=F.child({scope:"CommandRegistry"});constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new o}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){o.logger.info(`Loading commands from ${e}`);let t=await glob(e,{absolute:true,cwd:B.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",import.meta.url);}catch{o.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 r of t){let s=await import(r).then(a=>a.default?a.default:a).catch(a=>(o.logger.error(`Error loading command ${r}: ${a}`),null));s&&this.commands.set(s.commandName,s);}for(let r of Ft)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},D=V.getInstance();var Bt=o=>{let e=new Map;for(let t of o){let r=t.options?.category||"other";e.has(r)||e.set(r,[]),e.get(r).push(t);}return e},Ut=o=>{let e=Array.from(o.keys()).sort();for(let t of e){let r=o.get(t).filter(n=>n&&n.commandName);if(!r.length)continue;let a={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[t]||"\x1B[37m";console.log(` ${a}${t.toUpperCase()}:\x1B[0m`);let c=Math.max(...r.map(n=>n.commandName.length));for(let n of r){let u=n.commandName.padEnd(c+2),d=n.description||"No description available",l="";n.options?.deprecated&&(l=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${u}\x1B[0m ${d}${l}`);}console.log("");}},Ze=async()=>{await D.loadCommands(V.commandsPattern);let[o,...e]=ve.getCliArgs();if(!o||o==="-h"||o==="--help"){let a=D.getBuiltInCommands(),c=D.getUserDefinedCommands();if(console.log(`
591
+ `}[e]||""}};b([P({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],fe,"storageType"),b([P({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],fe,"outputPath");var zt=[ce,xe,ne,le,ee,ie,ae,A,H,de,ue,Te,I,ge,fe,Se,he,oe],V=class o{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=B.child({scope:"CommandRegistry"});constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new o}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){o.logger.info(`Loading commands from ${e}`);let t=await glob(e,{absolute:true,cwd:U.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",import.meta.url);}catch{o.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 r of t){let s=await import(r).then(a=>a.default?a.default:a).catch(a=>(o.logger.error(`Error loading command ${r}: ${a}`),null));s&&this.commands.set(s.commandName,s);}for(let r of zt)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Q=V.getInstance();var Lt=o=>{let e=new Map;for(let t of o){let r=t.options?.category||"other";e.has(r)||e.set(r,[]),e.get(r).push(t);}return e},Ht=o=>{let e=Array.from(o.keys()).sort();for(let t of e){let r=o.get(t).filter(n=>n&&n.commandName);if(!r.length)continue;let a={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[t]||"\x1B[37m";console.log(` ${a}${t.toUpperCase()}:\x1B[0m`);let c=Math.max(...r.map(n=>n.commandName.length));for(let n of r){let u=n.commandName.padEnd(c+2),d=n.description||"No description available",l="";n.options?.deprecated&&(l=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${u}\x1B[0m ${d}${l}`);}console.log("");}},Ye=async()=>{await Q.loadCommands(V.commandsPattern);let[o,...e]=ve.getCliArgs();if(!o||o==="-h"||o==="--help"){let a=Q.getBuiltInCommands(),c=Q.getUserDefinedCommands();if(console.log(`
592
592
  \u2728 Available Balda Commands:
593
593
  `),c.length&&(console.log(`\x1B[1;33mUser Commands:\x1B[0m
594
- `),Ut(Bt(c))),a.length){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
594
+ `),Ht(Lt(c))),a.length){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
595
595
  `);let n=Math.max(...a.map(u=>u.commandName.length));for(let u of a){let d=u.commandName.padEnd(n+2),l=u.description||"No description available",i="";u.options?.deprecated&&(i=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${d}\x1B[0m ${l}${i}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
596
- `),W.exit(0);return}let t=D.getCommand(o);if(!t){console.error(st(o,D.getCommands().filter(a=>a&&a.commandName).map(a=>a.commandName))||`Command ${o} not found`),W.exit(1);return}let r=t;if(r.calledBy=x.basename(ve.getCliCaller()),r.options?.deprecated){let a=r.options.deprecated.message||"This command is deprecated",c=r.options.deprecated.replacement;console.warn(`\x1B[33m\u26A0\uFE0F Warning: ${a}\x1B[0m`),c&&console.warn(`\x1B[33m Use '${c}' instead.\x1B[0m
597
- `);}if(r.handleHelpFlag(r.flags),r.validateContext(r),r.options?.validate&&!await r.options.validate(r)){console.error("Command validation failed"),W.exit(1);return}await r.handle(),(t.options?.keepAlive??false)||W.exit(0);};typeof process<"u"?Ze().catch(async o=>{if(o?.message?.includes("SyntaxError")||o?.code==="ERR_UNKNOWN_FILE_EXTENSION")try{let{register:e}=await import('module');e("ts-node/esm",import.meta.url),Ze().catch(t=>{V.logger.error(t),process.exit(1);});}catch{V.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);}else V.logger.error(o),process.exit(1);}):Ze().catch(o=>{V.logger.error(o),W.exit(1);});export{Ze as cli};//# sourceMappingURL=cli.js.map
596
+ `),K.exit(0);return}let t=Q.getCommand(o);if(!t){console.error(ot(o,Q.getCommands().filter(a=>a&&a.commandName).map(a=>a.commandName))||`Command ${o} not found`),K.exit(1);return}let r=t;if(r.calledBy=x.basename(ve.getCliCaller()),r.options?.deprecated){let a=r.options.deprecated.message||"This command is deprecated",c=r.options.deprecated.replacement;console.warn(`\x1B[33m\u26A0\uFE0F Warning: ${a}\x1B[0m`),c&&console.warn(`\x1B[33m Use '${c}' instead.\x1B[0m
597
+ `);}if(r.handleHelpFlag(r.flags),r.validateContext(r),r.options?.validate&&!await r.options.validate(r)){console.error("Command validation failed"),K.exit(1);return}await r.handle(),(t.options?.keepAlive??false)||K.exit(0);};typeof process<"u"?Ye().catch(async o=>{if(o?.message?.includes("SyntaxError")||o?.code==="ERR_UNKNOWN_FILE_EXTENSION")try{let{register:e}=await import('module');e("ts-node/esm",import.meta.url),Ye().catch(t=>{V.logger.error(t),process.exit(1);});}catch{V.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);}else V.logger.error(o),process.exit(1);}):Ye().catch(o=>{V.logger.error(o),K.exit(1);});export{Ye as cli};//# sourceMappingURL=cli.js.map
598
598
  //# sourceMappingURL=cli.js.map