balda 0.0.4 → 0.0.5

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/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';var glob=require('glob'),At=require('pino'),Ge=require('path'),ajv=require('ajv'),Je=require('fs'),child_process=require('child_process'),Ut=require('readline'),async_hooks=require('async_hooks'),zlib=require('zlib'),http=require('http'),http2=require('http2'),https=require('https'),stream=require('stream');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var At__default=/*#__PURE__*/_interopDefault(At);var Ge__default=/*#__PURE__*/_interopDefault(Ge);var Je__default=/*#__PURE__*/_interopDefault(Je);var Ut__namespace=/*#__PURE__*/_interopNamespace(Ut);var Mt=Object.defineProperty;var Nr=(i,e)=>()=>(i&&(e=i(i=0)),e);var _r=(i,e)=>{for(var t in e)Mt(i,t,{get:e[t],enumerable:true});};var y=(i,e,t,r)=>{for(var s=void 0,o=i.length-1,n;o>=0;o--)(n=i[o])&&(s=(n(e,t,s))||s);return s&&Mt(e,t,s),s};var kt={};_r(kt,{runtime:()=>P});var mt,P,Q=Nr(()=>{mt=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")}},P=new mt;});var T=class extends Error{constructor(e){super(e);}};var Dr=()=>At__default.default({level:"info",formatters:{level:e=>({level:e})}});exports.logger=Dr();var zs=i=>{exports.logger=At__default.default(i);};Q();var ht=class{getCwd(){switch(P.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},$=new ht;var xe=class{static scheduledJobs=[];static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t});}static async run(){let e=(await import('node-cron').catch(()=>{throw new T("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(exports.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){exports.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)exports.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",o=>this.globalErrorHandler(o));exports.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){exports.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await glob.glob(r,{absolute:true,cwd:$.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{exports.logger.error(`Error importing cron job: ${r}`),exports.logger.error(s);});}));}},Xs=i=>{xe.globalErrorHandler=i.bind(xe);};var ro=(i,e)=>function(t,r,s){let o=s.value,n=async(...a)=>{let c=new t.constructor;return await o.apply(c,a)};return xe.register(`${t.constructor.name}.${r}`,i,n,e),s};Q();var gt=class{getCliArgs(){switch(P.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(P.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 o=t+1;o<e.length;o++)if(!e[o].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[o]))return o;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},ft=new gt;var Qe=i=>i.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),Ue=i=>i.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),$t=i=>i.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var Re=(i,e)=>{if(!i||typeof i!="string")return e;let t=i.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),s=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let o=Number.parseFloat(r[1]);return Number.isNaN(o)||o<0?e:Math.floor(o*1024)}if(s){let o=Number.parseFloat(s[1]);return Number.isNaN(o)||o<0?e:Math.floor(o*1024*1024)}return e};var Ir=i=>{if(!i||i==="-"||i==="--")return null;let e=i.indexOf("=");if(e>0){let t=i.substring(0,e),r=i.substring(e+1);return {name:t,value:Ht(r)}}return {name:i,value:true}},Ht=i=>{if(i.toLowerCase()==="true")return true;if(i.toLowerCase()==="false")return false;let e=Number(i);return !Number.isNaN(e)&&Number.isFinite(e)?e:i},ce=()=>{let i=ft.getCliArgs(),e=[],t={};if(!i||!i.length)return {args:e,flags:t};for(let r=0;r<i.length;r++){let s=i[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let o=Ir(s);if(o){if(o.value===true&&r+1<i.length){let n=i[r+1];n&&typeof n=="string"&&!n.startsWith("-")&&(o.value=Ht(n),r++);}if(o.name in t){let n=t[o.name];Array.isArray(n)?n.push(o.value):t[o.name]=[n,o.value];}else t[o.name]=o.value;}continue}e.push(s);}}return {args:e,flags:t}};var ze=()=>ft.getCliArgs()[0]||null;var w=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r);}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)||new Map}static delete(e,t){this.metadata.get(e)?.delete(t.toString());}static clear(e){this.metadata.delete(e);}};var pe="VALIDATION_ERROR",go="ARG",Bt=ce().args.slice(1),A=i=>(e,t)=>{let r=ze();if(!r||r!==e.commandName)return;let s=t;w.set(e,t,{type:"arg",name:s,description:i.description});let o=Bt.length?Bt.shift():i.defaultValue;if(i.required&&!o){let n=w.get(e,pe);w.set(e,pe,[...n||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}i.parse&&o&&(o=i.parse(o)),Object.defineProperty(e,t,{value:o,enumerable:true,configurable:true,writable:true});};var J=i=>(e,t)=>{let r=ze();if(!r||r!==e.commandName)return;let s=i.name||t,o=ce().flags,n=i.aliases||[],a=[s,...n],c=i.defaultValue;for(let p of a){let l=[p,`-${p}`,`--${p}`];for(let d of l)if(d in o){let h=o[d];i.type==="list"?c=(Array.isArray(h)?h:[h]).map(f=>{let b=String(f);return i.parse?i.parse(b):b}):(c=h,i.type==="boolean"?c=!!c:i.type==="number"&&(c=Number(c)),i.parse&&(c=i.parse(c)));break}if(c!==i.defaultValue)break}if(w.set(e,t,{type:"flag",name:s,aliases:n||[],description:i.description}),i.required&&(i.type==="list"?!c||Array.isArray(c)&&c.length===0:!c)){let l=w.get(e,pe);w.set(e,pe,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:c,enumerable:true,configurable:true,writable:true});};J.boolean=i=>J({...i,type:"boolean"});J.string=i=>J({...i,type:"string"});J.number=i=>J({...i,type:"number"});J.list=i=>J({...i,type:"list"});var x=J;Q();var yt=class{basename(e){switch(P.type){case "node":case "bun":case "deno":return Ge__default.default.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(P.type){case "node":case "bun":case "deno":return Ge__default.default.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(P.type){case "bun":case "node":case "deno":return Ge__default.default.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(P.type){case "bun":case "node":case "deno":return Ge__default.default.resolve(...e);default:throw new Error("Unsupported runtime")}}},g=new yt;var Pe=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null;}},vt=class i{trees;routes;middlewares;basePath;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e);}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,o){e=e.toUpperCase();let n=this.trees.get(e);n||(n=new Pe,this.trees.set(e,n));let c=t.split("?")[0].replace(/^\/+|\/+$/g,""),p=c.length===0?[]:c.split("/"),l=n;for(let h of p){if(h==="*"){l.wildcardChild||(l.wildcardChild=new Pe),l=l.wildcardChild;break}if(h.startsWith(":")){let m=h.slice(1);l.paramChild||(l.paramChild={node:new Pe,name:m}),l=l.paramChild.node;continue}l.staticChildren.has(h)||l.staticChildren.set(h,new Pe),l=l.staticChildren.get(h);}l.middleware=r,l.handler=s;let d=this.routes.findIndex(h=>h.method===e&&h.path===t);if(d!==-1){this.routes[d].middleware=r,this.routes[d].handler=s;return}this.routes.push({method:e,path:t,middleware:r,handler:s,swaggerOptions:o});}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let o=t.split("?")[0].replace(/^\/+|\/+$/g,""),n=o.length===0?[]:o.split("/"),a={},c=r;for(let p=0;p<n.length;p++){let l=n[p];if(c.staticChildren.has(l)){c=c.staticChildren.get(l);continue}if(c.paramChild){a[c.paramChild.name]=l,c=c.paramChild.node;continue}if(c.wildcardChild){a["*"]=n.slice(p).join("/"),c=c.wildcardChild;break}return null}return !c.handler||!c.middleware?null:{middleware:c.middleware,handler:c.handler,params:a}}get(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("GET",o,p,a,l);}post(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("POST",o,p,a,l);}patch(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("PATCH",o,p,a,l);}put(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("PUT",o,p,a,l);}delete(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("DELETE",o,p,a,l);}options(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("OPTIONS",o,p,a,l);}head(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("HEAD",o,p,a,l);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],o=Array.isArray(t)?r:typeof t=="function"?t:void 0,n=this.joinPath(e),a=new i(n,[...this.middlewares,...s]);o?.(a);for(let c of a.getRoutes())this.addOrUpdate(c.method,c.path,c.middleware,c.handler,c.swaggerOptions);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes)this.addOrUpdate(t.method,t.path,[...e,...t.middleware||[]],t.handler);}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(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}},O=new vt;var Fr=i=>async(e,t,r)=>{for(let s of i)if(!await s.manager.canAccess(s.scope,s.handler,e))return t.unauthorized({error:"Unauthorized"});return r()},jo=(i,e)=>t=>{let r=w.get(t.prototype,"__class__"),s=r?.middlewares||[],o=r?.policies||[],n=w.getAll(t.prototype),a=new t;for(let[c,p]of n.entries()){if(!p.route)continue;let l=t.prototype[c].bind(a),d=i?g.join(i,p.route.path):p.route.path,h=[...o,...p.policies||[]],m=h.length>0?[Fr(h)]:[],f=[...s,...m,...p.middlewares||[]];O.addOrUpdate(p.route.method,d,f,l,{service:t.name.replace(/Controller$/,""),...e,...p.documentation});}w.clear(t.prototype);};var Mo=(i,e)=>(t,r,s)=>{let o=w.get(t,r);return o||(o={middlewares:[],route:{path:i,method:"DELETE"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:i,method:"DELETE"},w.set(t,r,o),s};var $o=(i,e)=>(t,r,s)=>{let o=w.get(t,r);return o||(o={middlewares:[],route:{path:i,method:"GET"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:i,method:"GET"},w.set(t,r,o),s};var No=(i,e)=>(t,r,s)=>{let o=w.get(t,r);return o||(o={middlewares:[],route:{path:i,method:"PATCH"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:i,method:"PATCH"},w.set(t,r,o),s};var Lo=(i,e)=>(t,r,s)=>{let o=w.get(t,r);return o||(o={middlewares:[],route:{path:i,method:"POST"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:i,method:"POST"},w.set(t,r,o),s};var Qo=(i,e)=>(t,r,s)=>{let o=w.get(t,r);return o||(o={middlewares:[],route:{path:i,method:"PUT"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:i,method:"PUT"},w.set(t,r,o),s};var Go=i=>(e,t,r)=>{if(typeof t>"u"){let o=w.get(e.prototype,"__class__");if(o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),!i)throw new Error(`Middleware ${String(i)} not found, are you sure you defined it before using it?`);return Array.isArray(i)||(i=[i]),o.middlewares.push(...i),w.set(e.prototype,"__class__",o),e}let s=w.get(e,t);return s||(s={middlewares:[]}),s.middlewares||(s.middlewares=[]),Array.isArray(i)||(i=[i]),s.middlewares.push(...i),w.set(e,t,s),r};var N=class{static ajv=new ajv.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 k=new Map;var Te=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
2
2
  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 _=(i,e,t=false)=>{if(!i(e)){if(t)return e;throw new ajv.ValidationError(i.errors||[])}return e};var Y=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
3
- 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 Nt=Symbol("serializeWrapped"),Oe=Symbol("serializeMetadata"),Ce=new WeakMap,ai=(i,e)=>(t,r,s)=>{let o=w.get(t,r)||{middlewares:[],route:{}};o.documentation||(o.documentation={}),o.documentation.responses||(o.documentation.responses={}),o.serializeOptions||(o.serializeOptions={});let n=Number(e?.status??200);if(o.documentation.responses[n]=i,o.serializeOptions[n]=e?.safe??true,w.set(t,r,o),s.value[Oe]||(s.value[Oe]={}),s.value[Oe][n]={name:r,schema:i,safe:e?.safe??true},!s.value[Nt]){let a=s.value,c=async function(...p){let l=p[1];await a.apply(this,p);let d=l.responseStatus,h=c[Oe],m=h?.[d]?.schema,f=h?.[d]?.safe??true;if(m&&!f){let b=l.getBody();try{let q;if(Y.isZodSchema(m)){let R=Ce.get(m);R||(R=Symbol("serialize_zod_schema"),Ce.set(m,R));let E=k.get(R);if(!E){let F=m.toJSONSchema();E=N.ajv.compile(F),k.set(R,E);}await _(E,b,f),l.send(b);}else if(Te.isTypeBoxSchema(m)){let R=Ce.get(m);R||(R=Symbol("serialize_typebox_schema"),Ce.set(m,R));let E=k.get(R);E||(E=N.ajv.compile(m),k.set(R,E)),await _(E,b,f),l.send(b);}else if(typeof m=="object"&&m!==null){let R=Ce.get(m);R||(R=Symbol("serialize_json_schema"),Ce.set(m,R));let E=k.get(R);E||(E=N.ajv.compile(m),k.set(R,E)),await _(E,b,f),l.send(b);}else {q=JSON.stringify(m);let R=k.get(q);R||(R=N.ajv.compile(m),k.set(q,R)),await _(R,b,f),l.send(b);}}catch(q){let R=await Y.load();if(q instanceof R.ZodError){l.internalServerError({received:b,schema:m,error:q});return}throw q}}};c[Nt]=true,c[Oe]=a[Oe],s.value=c;}};var le=i=>(e,t,r)=>{let s=r.value,o=w.get(e,t);return o||(o={middlewares:[],route:{}}),o.documentation||(o.documentation={}),i.body&&(o.documentation.requestBody=i.body),i.query&&(o.documentation.query=i.query),i.all&&(o.documentation.requestBody=i.body,o.documentation.query=i.query),w.set(e,t,o),r.value=async function(...n){let a=n[0],c=n[1];try{let p,l,d;i.body&&(p=a.validate(i.body,i.safe)),i.query&&(l=a.validateQuery(i.query,i.safe)),i.all&&(d=a.validateAll(i.all,i.safe));let h=[...n];return p!==void 0&&h.push(p),l!==void 0&&h.push(l),d!==void 0&&h.push(d),s.apply(this,h)}catch(p){let l=await Y.load();if(!(p instanceof l.ZodError))throw p;return i.customError?c.status(i.customError.status||400).json({received:a.body,schema:i.body,error:p}):c.badRequest(p)}},r};le.query=(i,e)=>le({query:i,customError:e});le.body=(i,e)=>le({body:i,customError:e});le.all=(i,e)=>le({all:i,customError:e});var di=le;var _t=class{logger=exports.logger.child({scope:this.constructor.name})};var Dt=class{logger=exports.logger.child({scope:this.constructor.name})};var Gr=i=>{if(!Buffer.isBuffer(i))return i;let e=i.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},_e=class i{static subscriptions=[];static client=null;static connectionOptions={};static register(e,t,r,s){this.subscriptions.push({name:e,topic:t,handler:r,options:s});}static async connect(e={}){let t=await import('mqtt').catch(()=>{throw new T("mqtt not installed as a dependency, it is required in order to use MQTT subscriptions with the @mqtt decorator")});this.connectionOptions=e,exports.logger.info("Starting MQTT client"),this.subscriptions.length||exports.logger.info("No MQTT subscriptions to register");let{host:r="localhost",port:s=1883,protocol:o="mqtt",...n}=e,a=`${o}://${r}:${s}`;this.client=await t.connectAsync(a,n),exports.logger.info("MQTT client connected"),this.client.on("error",async c=>{await this.globalErrorHandler(c);}),this.client.on("message",(c,p)=>{this.handleMessage(c,p);}),this.client.on("disconnect",()=>{exports.logger.info("MQTT client disconnected");}),this.client.on("reconnect",async()=>{await this.globalErrorHandler(new Error("MQTT client reconnecting"));}),this.subscribeToTopics();}static subscribeToTopics(){if(this.client)for(let{name:e,topic:t,options:r}of this.subscriptions)exports.logger.info(`Subscribing to MQTT topic: ${t} (${e})`),this.client.subscribe(t,r||{},s=>{if(s){exports.logger.error(`Failed to subscribe to topic ${t}: ${s.message}`);return}exports.logger.info(`Successfully subscribed to topic: ${t}`);});}static async handleMessage(e,t){let r=this.subscriptions.filter(s=>{if(s.topic===e)return true;if(!e||typeof e!="string")return false;let o=s.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${o}$`).test(e)});for(let s of r)try{await s.handler(e,t);}catch(o){exports.logger.error(`Error handling MQTT message for topic ${e} in ${s.name}`),this.globalErrorHandler(o);}}static globalErrorHandler(e){exports.logger.error(e);}static setOnDisconnectHandler(e){this.client?.on("disconnect",e);}static setOnReconnectHandler(e){this.client?.on("reconnect",e);}static async massiveImportMqttHandlers(e){let t=[];for(let r of e){let s=await glob.glob(r,{absolute:true,cwd:$.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{exports.logger.error(`Error importing MQTT handler: ${r}`),exports.logger.error(s);});}));}subscribe(e,t){return function(r,s,o){let n=o.value;if(!n)return o;let a=async(c,p)=>{let l=new r.constructor,d=Gr(p);if(n.length===1){await n.call(l,d);return}await n.call(l,c,d);};return i.register(`${r.constructor.name}.${s}`,e,a,t),o}}async publish(e,t,r){if(!i.client)throw new T("MQTT client is not connected. Call MqttService.connect() first.");if(!i.client.connected)throw new T("MQTT client is not connected. Call MqttService.connect() first.");let s;Buffer.isBuffer(t)?s=t:typeof t=="object"?s=JSON.stringify(t):s=String(t);try{await i.client.publishAsync(e,s,r||{}),exports.logger.debug(`Published message to topic: ${String(e)}`);}catch(o){throw exports.logger.error(`Failed to publish to topic ${String(e)}: ${o.message}`),o}}static async disconnect(){if(this.client)return new Promise(e=>{this.client?.end(false,{},()=>{exports.logger.info("MQTT client disconnected gracefully"),this.client=null,e();});})}},Si=i=>{_e.globalErrorHandler=i.bind(_e);},xi=new _e;var Lt=class{logger=exports.logger.child({scope:this.constructor.name})};var W=class{static options={connection:{}}},It=i=>{W.options=i??{connection:{}};};var U=class extends T{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var wt=class{randomUUID(){return crypto.randomUUID()}},X=new wt;var We=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),o=X.randomUUID();return await s.add(e,t,{jobId:o,...W.options?.defaultJobOptions,...r}),{id:o}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=W.options??{},o=await this.getBullMQClient(),n=new o.Worker(e,async a=>{try{await t(a.data);}catch(c){await r?.(a,c)??Promise.reject(c);}},{...s});this.workers.set(e,n);}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new U("bullmq","ioredis")}),r=new t.Queue(e,{...W.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 U("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let o=await this.getQueueWithConfig(e,s),n=X.randomUUID(),a={jobId:n,...W.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await o.add(e,t,a),{id:n}}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 o=W.options??{},{errorHandler:n}=o,a=await this.getBullMQClient(),c={...o,...r};delete c.errorHandler,delete c.defaultJobOptions;let p=new a.Worker(e,async l=>{try{await t(l.data);}catch(d){await n?.(l,d)??Promise.reject(d);}},c);this.workers.set(s,p);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new U("bullmq","ioredis")}),o={...W.options||{connection:{}},...t},n=new s.Queue(e,o);this.queues.set(r,n);}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 G=class{static options={}},Ft=i=>{G.options=i??{};};var Ke=class{createdQueues=new Set;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let o=r||{},n=await s.send(e,t,o);return {id:String(n??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=G.options;s.errorHandler&&r.on("error",s.errorHandler),await r.work(e,async o=>{let n=Array.isArray(o)?o:[o];for(let a of n)await t(a.data);});}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new U("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:o}=G.options,n=s??o,a=new r(n);return G.options?.errorHandler&&a.on("error",G.options.errorHandler),await a.start(),this.boss=a,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 o=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,o);let n=r||{},a=await o.send(e,t,n);return {id:String(a??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let o=G.options;o.errorHandler&&s.on("error",o.errorHandler),await s.work(e,async n=>{let a=Array.isArray(n)?n:[n];for(let c of a)await t(c.data);});}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 U("pg-boss","pg")}),o=r.PgBoss.default??r.PgBoss,n=new o(e.connectionString);return G.options?.errorHandler&&n.on("error",G.options.errorHandler),await n.start(),this.bossInstances.set(t,n),n}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var se=class{static options={}},Qt=i=>{se.options=i??{};};var Ve=class{consumers=new Map;client;async publish(e,t,r){let{...s}=r??{},o=await this.getClient(),{SendMessageCommand:n}=await this.getSqsLib(),a=await this.resolveQueueUrl(e);if(!a)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let c=new n({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},...s,QueueUrl:a});return {id:(await o.send(c)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=se.options,s=await this.getSqsConsumerLib(),o={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async c=>{let p=JSON.parse(c.Body||"{}");await t(p);}},n=s.Consumer.create(o),a=r.errorHandler;a&&(n.on("error",a),n.on("processing_error",a)),n.start(),this.consumers.set(e,n);}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=se.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 U("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new U("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=se.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{...o}=r??{},n=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),c=s?.queueUrl??await this.resolveQueueUrl(e),p=new a({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},...o,QueueUrl:c});return {id:(await n.send(p)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=se.options,o=await this.getSqsConsumerLib(),n=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:n,handleMessage:async l=>{let d=JSON.parse(l.Body||"{}");await t(d);}},c=o.Consumer.create(a),p=s.errorHandler;p&&(c.on("error",p),c.on("processing_error",p)),c.start(),this.consumers.set(e,c);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var ee=class{static map=new Map;static{this.map.set("bullmq",new We),this.map.set("sqs",new Ve),this.map.set("pgboss",new Ke);}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);}};var Zi=i=>{let e=["bullmq","pgboss","sqs"];i.bullmq&&It(i.bullmq),i.pgboss&&Ft(i.pgboss),i.sqs&&Qt(i.sqs);for(let t of Object.keys(i)){let r=t;e.includes(r)||ee.setProvider(r,i[r]);}};var de=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,o){let n=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(n)&&exports.logger.warn(`Queue handler for ${n} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(n,{name:e,topic:t,handler:r,provider:s,queueOptions:o});}static registerCustomQueue(e,t,r,s){let o=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(o)&&exports.logger.warn(`Custom queue handler for ${o} already registered, overwriting previous handler`),this.customQueueSubscribers.set(o,{name:e,topic:t,handler:r,pubsub:s});}static async run(){exports.logger.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){exports.logger.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:o,provider:n,queueOptions:a}=r;exports.logger.info(`Subscribing to queue: ${s}`);let c=ee.getProvider(n);a&&"subscribeWithConfig"in c&&typeof c.subscribeWithConfig=="function"?await c.subscribeWithConfig(s,o,a):await c.subscribe(s,o);}for(let{topic:r,handler:s,pubsub:o}of this.customQueueSubscribers.values())exports.logger.info(`Subscribing to custom queue: ${r}`),await o.subscribe(r,s);exports.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let o=await glob.glob(s,{absolute:true,cwd:$.getCwd()});r.push(...o);}await Promise.all(r.map(async s=>{await import(s).catch(o=>{if(exports.logger.error(`Error importing queue handler: ${s}`),exports.logger.error(o),t.throwOnError)throw o});}));}};var Ze=new WeakMap,ue=class{constructor(e,t,r){this.topic=e;this.provider=t;this.queueOptions=r;}async publish(e,t){let r=ee.getProvider(this.provider);return this.queueOptions?r.publishWithConfig(this.topic,e,t,this.queueOptions):r.publish(this.topic,e,t??{})}subscribe(e){return e?this.subscribeWithCallback(e):this.createSubscribeDecorator()}createSubscribeDecorator(){let e=this.topic,t=this.provider,r=this.queueOptions;return function(s,o,n){let a=n.value,c=async p=>{let l=Ze.get(s.constructor);return l||(l=de.instanceFactory(s.constructor),Ze.set(s.constructor,l)),a.apply(l,[p])};return de.registerTypedQueue(`${s.constructor.name}.${String(o)}`,e,c,t,r),n}}async subscribeWithCallback(e){let t=ee.getProvider(this.provider);return this.queueOptions?t.subscribeWithConfig(this.topic,e,this.queueOptions):t.subscribe(this.topic,e)}},De=class{constructor(e,t){this.topic=e;this.pubsub=t;}async publish(e,t){return this.pubsub.publish(this.topic,e,t)}subscribe(e){return e?this.pubsub.subscribe(this.topic,e):this.createSubscribeDecorator()}createSubscribeDecorator(){let e=this.topic,t=this.pubsub;return function(r,s,o){let n=o.value,a=async c=>{let p=Ze.get(r.constructor);return p||(p=de.instanceFactory(r.constructor),Ze.set(r.constructor,p)),n.apply(p,[c])};return de.registerCustomQueue(`${r.constructor.name}.${String(s)}`,e,a,t),o}}};function Kr(i,e){return new ue(i,"sqs",e)}function Vr(i,e){return new ue(i,"bullmq",e)}function Zr(i,e){return new ue(i,"pgboss",e)}function Jr(i,e){return new De(i,e)}Q();var bt=class{exit(e){switch(P.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},St=new bt;var j=class{static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false};static args=ce().args.slice(1);static flags=ce().flags;static logger=exports.logger;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(p=>t.includes(p)))return;let s=this.commandName,o=this.description||"No description available",n=this.help||[],a=this.options,c=this.generateHelpOutput({name:s,description:o,helpText:n,options:a,args:this.args,flags:this.flags},this);console.log(c),St.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:o,options:n,args:a,flags:c}=e,p={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=[`${p.title}${r}${p.reset}`,`${p.description}${s}${p.reset}`,"",`${p.subtitle}Usage:${p.reset}`,` ${p.code}${r}${p.reset} [options] [arguments]`,"",`${p.subtitle}Options:${p.reset}`,` ${p.flag}-h, --help${p.reset} Show this help message`,"",`${p.subtitle}Command Options:${p.reset}`,` ${p.flag}keepAlive${p.reset} ${n?.keepAlive??false?p.success+"Enabled"+p.reset:p.error+"Disabled"+p.reset}`,""];if(o){let f=Array.isArray(o)?o:[o];l.push(`${p.subtitle}Help:${p.reset}`),f.forEach(b=>{l.push(` ${p.description}${b}${p.reset}`);}),l.push("");}let d=w.getAll(t),h=Array.from(d.values()).filter(f=>f.type==="arg"),m=Array.from(d.values()).filter(f=>f.type==="flag");return h.length&&(l.push(`${p.subtitle}Available Arguments:${p.reset}`),h.forEach(f=>{let b=f.required?` ${p.error}(required)${p.reset}`:"",q=f.description?` ${p.description}${f.description}${p.reset}`:"";l.push(` ${p.code}${f.name}${p.reset}${b}${q}`);}),l.push("")),m.length&&(l.push(`${p.subtitle}Available Flags:${p.reset}`),m.forEach(f=>{f.aliases&&!Array.isArray(f.aliases)&&(f.aliases=[f.aliases]);let b=f.aliases.length?` ${p.flag}(${f.aliases.join(", ")})${p.reset}`:"",q=f.required?` ${p.error}(required)${p.reset}`:"",R=f.description?` ${p.description}${f.description}${p.reset}`:"";l.push(` ${p.flag}--${f.name}${b}${p.reset}${q}${R}`);}),l.push("")),((a?.length??0)>0||c&&Object.keys(c).length>0)&&(l.push(`${p.subtitle}Current Context:${p.reset}`),a?.length&&l.push(` ${p.info}Provided Arguments:${p.reset} ${p.code}${a.join(" ")}${p.reset}`),c&&Object.keys(c).length>0&&(l.push(` ${p.info}Provided Flags:${p.reset}`),Object.keys(c).forEach(f=>{let b=c[f],q=b!=null?` = ${p.code}${b}${p.reset}`:"";l.push(` ${p.flag}${f}${p.reset}${q}`);})),l.push("")),o&&(Array.isArray(o)?o.some(f=>f.includes("example")):o.includes("example"))&&(l.push(`${p.subtitle}Examples:${p.reset}`),(Array.isArray(o)?o.filter(b=>b.includes("example")):[o.split("example")[1].trim()]).forEach(b=>{l.push(` ${p.code}${b}${p.reset}`);}),l.push("")),l.join(`
3
+ 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 Nt=Symbol("serializeWrapped"),Oe=Symbol("serializeMetadata"),Ce=new WeakMap,ai=(i,e)=>(t,r,s)=>{let o=w.get(t,r)||{middlewares:[],route:{}};o.documentation||(o.documentation={}),o.documentation.responses||(o.documentation.responses={}),o.serializeOptions||(o.serializeOptions={});let n=Number(e?.status??200);if(o.documentation.responses[n]=i,o.serializeOptions[n]=e?.safe??true,w.set(t,r,o),s.value[Oe]||(s.value[Oe]={}),s.value[Oe][n]={name:r,schema:i,safe:e?.safe??true},!s.value[Nt]){let a=s.value,c=async function(...p){let l=p[1];await a.apply(this,p);let d=l.responseStatus,h=c[Oe],m=h?.[d]?.schema,f=h?.[d]?.safe??true;if(m&&!f){let b=l.getBody();try{let q;if(Y.isZodSchema(m)){let R=Ce.get(m);R||(R=Symbol("serialize_zod_schema"),Ce.set(m,R));let E=k.get(R);if(!E){let F=m.toJSONSchema();E=N.ajv.compile(F),k.set(R,E);}await _(E,b,f),l.send(b);}else if(Te.isTypeBoxSchema(m)){let R=Ce.get(m);R||(R=Symbol("serialize_typebox_schema"),Ce.set(m,R));let E=k.get(R);E||(E=N.ajv.compile(m),k.set(R,E)),await _(E,b,f),l.send(b);}else if(typeof m=="object"&&m!==null){let R=Ce.get(m);R||(R=Symbol("serialize_json_schema"),Ce.set(m,R));let E=k.get(R);E||(E=N.ajv.compile(m),k.set(R,E)),await _(E,b,f),l.send(b);}else {q=JSON.stringify(m);let R=k.get(q);R||(R=N.ajv.compile(m),k.set(q,R)),await _(R,b,f),l.send(b);}}catch(q){let R=await Y.load();if(q instanceof R.ZodError){l.internalServerError({received:b,schema:m,error:q});return}throw q}}};c[Nt]=true,c[Oe]=a[Oe],s.value=c;}};var le=i=>(e,t,r)=>{let s=r.value,o=w.get(e,t);return o||(o={middlewares:[],route:{}}),o.documentation||(o.documentation={}),i.body&&(o.documentation.requestBody=i.body),i.query&&(o.documentation.query=i.query),i.all&&(o.documentation.requestBody=i.body,o.documentation.query=i.query),w.set(e,t,o),r.value=async function(...n){let a=n[0],c=n[1];try{let p,l,d;i.body&&(p=a.validate(i.body,i.safe)),i.query&&(l=a.validateQuery(i.query,i.safe)),i.all&&(d=a.validateAll(i.all,i.safe));let h=[...n];return p!==void 0&&h.push(p),l!==void 0&&h.push(l),d!==void 0&&h.push(d),s.apply(this,h)}catch(p){let l=await Y.load();if(!(p instanceof l.ZodError))throw p;return i.customError?c.status(i.customError.status||400).json({received:a.body,schema:i.body,error:p}):c.badRequest(p)}},r};le.query=(i,e)=>le({query:i,customError:e});le.body=(i,e)=>le({body:i,customError:e});le.all=(i,e)=>le({all:i,customError:e});var di=le;var _t=class{logger=exports.logger.child({scope:this.constructor.name})};var Dt=class{logger=exports.logger.child({scope:this.constructor.name})};var Gr=i=>{if(!Buffer.isBuffer(i))return i;let e=i.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},_e=class i{static subscriptions=[];static client=null;static connectionOptions={};static register(e,t,r,s){this.subscriptions.push({name:e,topic:t,handler:r,options:s});}static async connect(e={}){let t=await import('mqtt').catch(()=>{throw new T("mqtt not installed as a dependency, it is required in order to use MQTT subscriptions with the @mqtt decorator")});this.connectionOptions=e,exports.logger.info("Starting MQTT client"),this.subscriptions.length||exports.logger.info("No MQTT subscriptions to register");let{host:r="localhost",port:s=1883,protocol:o="mqtt",...n}=e,a=`${o}://${r}:${s}`;this.client=await t.connectAsync(a,n),exports.logger.info("MQTT client connected"),this.client.on("error",async c=>{await this.globalErrorHandler(c);}),this.client.on("message",(c,p)=>{this.handleMessage(c,p);}),this.client.on("disconnect",()=>{exports.logger.info("MQTT client disconnected");}),this.client.on("reconnect",async()=>{await this.globalErrorHandler(new Error("MQTT client reconnecting"));}),this.subscribeToTopics();}static subscribeToTopics(){if(this.client)for(let{name:e,topic:t,options:r}of this.subscriptions)exports.logger.info(`Subscribing to MQTT topic: ${t} (${e})`),this.client.subscribe(t,r||{},s=>{if(s){exports.logger.error(`Failed to subscribe to topic ${t}: ${s.message}`);return}exports.logger.info(`Successfully subscribed to topic: ${t}`);});}static async handleMessage(e,t){let r=this.subscriptions.filter(s=>{if(s.topic===e)return true;if(!e||typeof e!="string")return false;let o=s.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${o}$`).test(e)});for(let s of r)try{await s.handler(e,t);}catch(o){exports.logger.error(`Error handling MQTT message for topic ${e} in ${s.name}`),this.globalErrorHandler(o);}}static globalErrorHandler(e){exports.logger.error(e);}static setOnDisconnectHandler(e){this.client?.on("disconnect",e);}static setOnReconnectHandler(e){this.client?.on("reconnect",e);}static async massiveImportMqttHandlers(e){let t=[];for(let r of e){let s=await glob.glob(r,{absolute:true,cwd:$.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{exports.logger.error(`Error importing MQTT handler: ${r}`),exports.logger.error(s);});}));}subscribe(e,t){return function(r,s,o){let n=o.value;if(!n)return o;let a=async(c,p)=>{let l=new r.constructor,d=Gr(p);if(n.length===1){await n.call(l,d);return}await n.call(l,c,d);};return i.register(`${r.constructor.name}.${s}`,e,a,t),o}}async publish(e,t,r){if(!i.client)throw new T("MQTT client is not connected. Call MqttService.connect() first.");if(!i.client.connected)throw new T("MQTT client is not connected. Call MqttService.connect() first.");let s;Buffer.isBuffer(t)?s=t:typeof t=="object"?s=JSON.stringify(t):s=String(t);try{await i.client.publishAsync(e,s,r||{}),exports.logger.debug(`Published message to topic: ${String(e)}`);}catch(o){throw exports.logger.error(`Failed to publish to topic ${String(e)}: ${o.message}`),o}}static async disconnect(){if(this.client)return new Promise(e=>{this.client?.end(false,{},()=>{exports.logger.info("MQTT client disconnected gracefully"),this.client=null,e();});})}},Si=i=>{_e.globalErrorHandler=i.bind(_e);},xi=new _e;var Lt=class{logger=exports.logger.child({scope:this.constructor.name})};var W=class{static options={connection:{}}},It=i=>{W.options=i??{connection:{}};};var U=class extends T{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var wt=class{randomUUID(){return crypto.randomUUID()}},X=new wt;var We=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),o=X.randomUUID();return await s.add(e,t,{jobId:o,...W.options?.defaultJobOptions,...r}),{id:o}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=W.options??{},o=await this.getBullMQClient(),n=new o.Worker(e,async a=>{try{await t(a.data);}catch(c){await r?.(a,c)??Promise.reject(c);}},{...s});this.workers.set(e,n);}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new U("bullmq","ioredis")}),r=new t.Queue(e,{...W.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 U("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let o=await this.getQueueWithConfig(e,s),n=X.randomUUID(),a={jobId:n,...W.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await o.add(e,t,a),{id:n}}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 o=W.options??{},{errorHandler:n}=o,a=await this.getBullMQClient(),c={...o,...r};delete c.errorHandler,delete c.defaultJobOptions;let p=new a.Worker(e,async l=>{try{await t(l.data);}catch(d){await n?.(l,d)??Promise.reject(d);}},c);this.workers.set(s,p);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new U("bullmq","ioredis")}),o={...W.options||{connection:{}},...t},n=new s.Queue(e,o);this.queues.set(r,n);}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 G=class{static options={}},Ft=i=>{G.options=i??{};};var Ke=class{createdQueues=new Set;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let o=r||{},n=await s.send(e,t,o);return {id:String(n??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=G.options;s.errorHandler&&r.on("error",s.errorHandler),await r.work(e,async o=>{let n=Array.isArray(o)?o:[o];for(let a of n)await t(a.data);});}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new U("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:o}=G.options,n=s??o,a=new r(n);return G.options?.errorHandler&&a.on("error",G.options.errorHandler),await a.start(),this.boss=a,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 o=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,o);let n=r||{},a=await o.send(e,t,n);return {id:String(a??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let o=G.options;o.errorHandler&&s.on("error",o.errorHandler),await s.work(e,async n=>{let a=Array.isArray(n)?n:[n];for(let c of a)await t(c.data);});}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 U("pg-boss","pg")}),o=r.PgBoss.default??r.PgBoss,n=new o(e.connectionString);return G.options?.errorHandler&&n.on("error",G.options.errorHandler),await n.start(),this.bossInstances.set(t,n),n}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var se=class{static options={}},Qt=i=>{se.options=i??{};};var Ve=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:o}=await this.getSqsLib(),n=await this.resolveQueueUrl(e);if(!n)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new o({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:n,...r??{}});return {id:(await s.send(a)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=se.options,s=await this.getSqsConsumerLib(),o={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async c=>{let p=JSON.parse(c.Body||"{}");await t(p);}},n=s.Consumer.create(o),a=r.errorHandler;a&&(n.on("error",a),n.on("processing_error",a)),n.start(),this.consumers.set(e,n);}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=se.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 U("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new U("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=se.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{...o}=r??{},n=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),c=s?.queueUrl??await this.resolveQueueUrl(e),p=new a({...o,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c});return {id:(await n.send(p)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=se.options,o=await this.getSqsConsumerLib(),n=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:n,handleMessage:async l=>{let d=JSON.parse(l.Body||"{}");await t(d);}},c=o.Consumer.create(a),p=s.errorHandler;p&&(c.on("error",p),c.on("processing_error",p)),c.start(),this.consumers.set(e,c);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var ee=class{static map=new Map;static{this.map.set("bullmq",new We),this.map.set("sqs",new Ve),this.map.set("pgboss",new Ke);}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);}};var Zi=i=>{let e=["bullmq","pgboss","sqs"];i.bullmq&&It(i.bullmq),i.pgboss&&Ft(i.pgboss),i.sqs&&Qt(i.sqs);for(let t of Object.keys(i)){let r=t;e.includes(r)||ee.setProvider(r,i[r]);}};var de=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,o){let n=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(n)&&exports.logger.warn(`Queue handler for ${n} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(n,{name:e,topic:t,handler:r,provider:s,queueOptions:o});}static registerCustomQueue(e,t,r,s){let o=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(o)&&exports.logger.warn(`Custom queue handler for ${o} already registered, overwriting previous handler`),this.customQueueSubscribers.set(o,{name:e,topic:t,handler:r,pubsub:s});}static async run(){exports.logger.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){exports.logger.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:o,provider:n,queueOptions:a}=r;exports.logger.info(`Subscribing to queue: ${s}`);let c=ee.getProvider(n);a&&"subscribeWithConfig"in c&&typeof c.subscribeWithConfig=="function"?await c.subscribeWithConfig(s,o,a):await c.subscribe(s,o);}for(let{topic:r,handler:s,pubsub:o}of this.customQueueSubscribers.values())exports.logger.info(`Subscribing to custom queue: ${r}`),await o.subscribe(r,s);exports.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let o=await glob.glob(s,{absolute:true,cwd:$.getCwd()});r.push(...o);}await Promise.all(r.map(async s=>{await import(s).catch(o=>{if(exports.logger.error(`Error importing queue handler: ${s}`),exports.logger.error(o),t.throwOnError)throw o});}));}};var Ze=new WeakMap,ue=class{constructor(e,t,r){this.topic=e;this.provider=t;this.queueOptions=r;}async publish(e,t){let r=ee.getProvider(this.provider);return this.queueOptions?r.publishWithConfig(this.topic,e,t,this.queueOptions):r.publish(this.topic,e,t??{})}subscribe(e){return e?this.subscribeWithCallback(e):this.createSubscribeDecorator()}createSubscribeDecorator(){let e=this.topic,t=this.provider,r=this.queueOptions;return function(s,o,n){let a=n.value,c=async p=>{let l=Ze.get(s.constructor);return l||(l=de.instanceFactory(s.constructor),Ze.set(s.constructor,l)),a.apply(l,[p])};return de.registerTypedQueue(`${s.constructor.name}.${String(o)}`,e,c,t,r),n}}async subscribeWithCallback(e){let t=ee.getProvider(this.provider);return this.queueOptions?t.subscribeWithConfig(this.topic,e,this.queueOptions):t.subscribe(this.topic,e)}},De=class{constructor(e,t){this.topic=e;this.pubsub=t;}async publish(e,t){return this.pubsub.publish(this.topic,e,t)}subscribe(e){return e?this.pubsub.subscribe(this.topic,e):this.createSubscribeDecorator()}createSubscribeDecorator(){let e=this.topic,t=this.pubsub;return function(r,s,o){let n=o.value,a=async c=>{let p=Ze.get(r.constructor);return p||(p=de.instanceFactory(r.constructor),Ze.set(r.constructor,p)),n.apply(p,[c])};return de.registerCustomQueue(`${r.constructor.name}.${String(s)}`,e,a,t),o}}};function Kr(i,e){return new ue(i,"sqs",e)}function Vr(i,e){return new ue(i,"bullmq",e)}function Zr(i,e){return new ue(i,"pgboss",e)}function Jr(i,e){return new De(i,e)}Q();var bt=class{exit(e){switch(P.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},St=new bt;var j=class{static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false};static args=ce().args.slice(1);static flags=ce().flags;static logger=exports.logger;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(p=>t.includes(p)))return;let s=this.commandName,o=this.description||"No description available",n=this.help||[],a=this.options,c=this.generateHelpOutput({name:s,description:o,helpText:n,options:a,args:this.args,flags:this.flags},this);console.log(c),St.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:o,options:n,args:a,flags:c}=e,p={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=[`${p.title}${r}${p.reset}`,`${p.description}${s}${p.reset}`,"",`${p.subtitle}Usage:${p.reset}`,` ${p.code}${r}${p.reset} [options] [arguments]`,"",`${p.subtitle}Options:${p.reset}`,` ${p.flag}-h, --help${p.reset} Show this help message`,"",`${p.subtitle}Command Options:${p.reset}`,` ${p.flag}keepAlive${p.reset} ${n?.keepAlive??false?p.success+"Enabled"+p.reset:p.error+"Disabled"+p.reset}`,""];if(o){let f=Array.isArray(o)?o:[o];l.push(`${p.subtitle}Help:${p.reset}`),f.forEach(b=>{l.push(` ${p.description}${b}${p.reset}`);}),l.push("");}let d=w.getAll(t),h=Array.from(d.values()).filter(f=>f.type==="arg"),m=Array.from(d.values()).filter(f=>f.type==="flag");return h.length&&(l.push(`${p.subtitle}Available Arguments:${p.reset}`),h.forEach(f=>{let b=f.required?` ${p.error}(required)${p.reset}`:"",q=f.description?` ${p.description}${f.description}${p.reset}`:"";l.push(` ${p.code}${f.name}${p.reset}${b}${q}`);}),l.push("")),m.length&&(l.push(`${p.subtitle}Available Flags:${p.reset}`),m.forEach(f=>{f.aliases&&!Array.isArray(f.aliases)&&(f.aliases=[f.aliases]);let b=f.aliases.length?` ${p.flag}(${f.aliases.join(", ")})${p.reset}`:"",q=f.required?` ${p.error}(required)${p.reset}`:"",R=f.description?` ${p.description}${f.description}${p.reset}`:"";l.push(` ${p.flag}--${f.name}${b}${p.reset}${q}${R}`);}),l.push("")),((a?.length??0)>0||c&&Object.keys(c).length>0)&&(l.push(`${p.subtitle}Current Context:${p.reset}`),a?.length&&l.push(` ${p.info}Provided Arguments:${p.reset} ${p.code}${a.join(" ")}${p.reset}`),c&&Object.keys(c).length>0&&(l.push(` ${p.info}Provided Flags:${p.reset}`),Object.keys(c).forEach(f=>{let b=c[f],q=b!=null?` = ${p.code}${b}${p.reset}`:"";l.push(` ${p.flag}${f}${p.reset}${q}`);})),l.push("")),o&&(Array.isArray(o)?o.some(f=>f.includes("example")):o.includes("example"))&&(l.push(`${p.subtitle}Examples:${p.reset}`),(Array.isArray(o)?o.filter(b=>b.includes("example")):[o.split("example")[1].trim()]).forEach(b=>{l.push(` ${p.code}${b}${p.reset}`);}),l.push("")),l.join(`
4
4
  `)};static validateContext=e=>{let t=Array.from(w.get(e,pe)||[]);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,o)=>{let n=`${r.info}${o+1}.${r.reset}`,a=`${r.error}${s.type.toUpperCase()}${r.reset}`,c=`${r.code}${s.name}${r.reset}`;console.error(` ${n} ${a} ${c}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),St.exit(1);}}};Q();var xt=class{async mkdir(e,t){switch(P.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(P.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(P.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 o=Bun.file(e);return t?.encoding==="utf8"?o.text():new Uint8Array(await o.arrayBuffer());case "deno":let n=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(n):new Uint8Array(n)}}async writeFile(e,t){switch(P.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(P.type){case "node":let r=await(await import('fs/promises')).stat(e);return {isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case "bun":let o=await(await import('fs/promises')).stat(e);return {isDirectory:o.isDirectory(),isFile:o.isFile(),isSymbolicLink:o.isSymbolicLink(),size:o.size};case "deno":let n=await Deno.stat(e);return {isDirectory:n.isDirectory,isFile:n.isFile,isSymbolicLink:false,size:n.size}}}async unlink(e){switch(P.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(P.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(P.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")}}},u=new xt;var je=async i=>{let e=g.join(process.cwd(),"node_modules");if(!await u.exists(e))return i;let r=[];for(let s of i){let o=g.join(e,s);await u.exists(o)||r.push(s);}return r},z=async()=>await u.exists(g.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await u.exists(g.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await u.exists(g.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await u.exists(g.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await u.exists(g.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],D=async(i,e,t,r,s=true)=>{let o=Ut__namespace.createInterface({input:process.stdin,output:process.stdout}),n=t.join(", "),a=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
5
5
  ${n}
6
6
  (y/n): `;return new Promise(c=>{o.question(a,p=>{if(o.close(),p.toLowerCase()==="y"||p.toLowerCase()==="yes"){child_process.execSync(i,r),c(true);return}c(false);});})};var I=class extends j{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(a=>true).catch(()=>false)){let[a,c,p]=await z();await D(`${a} ${c} esbuild ${p}`,a,["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(a=>{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=Ge__default.default.join(this.output,"assets"),s=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(c=>{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")});Je__default.default.existsSync(r)||Je__default.default.mkdirSync(r,{recursive:true}),s.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&Je__default.default.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Je__default.default.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let o=Ge__default.default.join(this.output,"server.js"),n=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:o,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});n.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:n.errors},null,2)),process.exit(1)),n.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:n.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${o}`,output:o,assets:!!this.assets},null,2)),process.exit(0);}};y([x({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],I,"clearDist"),y([x({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"),y([x({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],I,"output"),y([x({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"),y([x({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"),y([x({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"),y([x({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"),y([x({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],I,"sourcemap");var Ee=class extends j{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(qe.getCommand(this.name)){let s=qe.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=g.join(this.path,`${this.name}.ts`),await u.exists(g.join(process.cwd(),this.path))||await u.mkdir(g.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.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";