balda 0.0.1 → 0.0.3

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.js CHANGED
@@ -1,8 +1,8 @@
1
- import {glob}from'glob';import Et from'pino';import Be from'path';import {Ajv,ValidationError}from'ajv';import Ke from'fs';import {execSync}from'child_process';import*as Bt from'readline';import {AsyncLocalStorage}from'async_hooks';import {gzipSync}from'zlib';import {z as z$1}from'zod';import {createServer}from'http';import {createServer as createServer$1,createSecureServer}from'http2';import {createServer as createServer$2}from'https';import {Readable}from'stream';var jt=Object.defineProperty;var $r=(s,e)=>()=>(s&&(e=s(s=0)),e);var Hr=(s,e)=>{for(var t in e)jt(s,t,{get:e[t],enumerable:true});};var w=(s,e,t,r)=>{for(var o=void 0,n=s.length-1,i;n>=0;n--)(i=s[n])&&(o=(i(e,t,o))||o);return o&&jt(e,t,o),o};var Mt={};Hr(Mt,{runtime:()=>S});var ct,S,H=$r(()=>{ct=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")}},S=new ct;});var x=class extends Error{constructor(e){super(e);}};var Nr=()=>Et({level:"info",formatters:{level:e=>({level:e})}}),y=Nr(),Ls=s=>{y=Et(s);};H();var dt=class{getCwd(){switch(S.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},M=new dt;var be=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 x("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(y.info("Scheduling cron jobs"),!this.scheduledJobs.length){y.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)y.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));y.info("Cron jobs scheduled");}static globalErrorHandler(e){y.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let o=await glob(r,{absolute:true,cwd:M.getCwd()});t.push(...o);}await Promise.all(t.map(async r=>{await import(r).catch(o=>{y.error(`Error importing cron job: ${r}`),y.error(o);});}));}},Gs=s=>{be.globalErrorHandler=s.bind(be);};var Vs=(s,e)=>function(t,r,o){let n=o.value,i=async(...a)=>{let p=new t.constructor;return await n.apply(p,a)};return be.register(`${t.constructor.name}.${r}`,s,i,e),o};H();var lt=class{getCliArgs(){switch(S.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(S.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],o=r.split("/").pop()||r;if(!r.startsWith("-")){if(o==="yarn"&&t+1<e.length&&e[t+1]==="run"||o==="npx"&&t+1<e.length)return t+1;if(o==="yarn"||o==="pnpm")return t;if(o==="npm"&&t+1<e.length&&e[t+1]==="run"||o==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(o)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},ut=new lt;var Le=s=>s.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),De=s=>s.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),At=s=>s.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var Se=(s,e)=>{if(!s||typeof s!="string")return e;let t=s.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),o=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let n=Number.parseFloat(r[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024)}if(o){let n=Number.parseFloat(o[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024*1024)}return e};var Lr=s=>{if(!s||s==="-"||s==="--")return null;let e=s.indexOf("=");if(e>0){let t=s.substring(0,e),r=s.substring(e+1);return {name:t,value:qt(r)}}return {name:s,value:true}},qt=s=>{if(s.toLowerCase()==="true")return true;if(s.toLowerCase()==="false")return false;let e=Number(s);return !Number.isNaN(e)&&Number.isFinite(e)?e:s},ie=()=>{let s=ut.getCliArgs(),e=[],t={};if(!s||!s.length)return {args:e,flags:t};for(let r=0;r<s.length;r++){let o=s[r];if(!(!o||typeof o!="string")){if(o.startsWith("-")){let n=Lr(o);if(n){if(n.value===true&&r+1<s.length){let i=s[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(n.value=qt(i),r++);}if(n.name in t){let i=t[n.name];Array.isArray(i)?i.push(n.value):t[n.name]=[i,n.value];}else t[n.name]=n.value;}continue}e.push(o);}}return {args:e,flags:t}};var Fe=()=>ut.getCliArgs()[0]||null;var v=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 ae="VALIDATION_ERROR",ao="ARG",kt=ie().args.slice(1),A=s=>(e,t)=>{let r=Fe();if(!r||r!==e.commandName)return;let o=t;v.set(e,t,{type:"arg",name:o,description:s.description});let n=kt.length?kt.shift():s.defaultValue;if(s.required&&!n){let i=v.get(e,ae);v.set(e,ae,[...i||[],{type:"arg",name:o,message:"Required argument not provided"}]);return}s.parse&&n&&(n=s.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var K=s=>(e,t)=>{let r=Fe();if(!r||r!==e.commandName)return;let o=s.name||t,n=ie().flags,i=s.aliases||[],a=[o,...i],p=s.defaultValue;for(let c of a){let d=[c,`-${c}`,`--${c}`];for(let l of d)if(l in n){let h=n[l];s.type==="list"?p=(Array.isArray(h)?h:[h]).map(g=>{let b=String(g);return s.parse?s.parse(b):b}):(p=h,s.type==="boolean"?p=!!p:s.type==="number"&&(p=Number(p)),s.parse&&(p=s.parse(p)));break}if(p!==s.defaultValue)break}if(v.set(e,t,{type:"flag",name:o,aliases:i||[],description:s.description}),s.required&&(s.type==="list"?!p||Array.isArray(p)&&p.length===0:!p)){let d=v.get(e,ae);v.set(e,ae,[...d||[],{type:"flag",name:o,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:p,enumerable:true,configurable:true,writable:true});};K.boolean=s=>K({...s,type:"boolean"});K.string=s=>K({...s,type:"string"});K.number=s=>K({...s,type:"number"});K.list=s=>K({...s,type:"list"});var T=K;H();var mt=class{basename(e){switch(S.type){case "node":case "bun":case "deno":return Be.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(S.type){case "node":case "bun":case "deno":return Be.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(S.type){case "bun":case "node":case "deno":return Be.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(S.type){case "bun":case "node":case "deno":return Be.resolve(...e);default:throw new Error("Unsupported runtime")}}},f=new mt;var xe=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null;}},ht=class s{trees;routes;middlewares;basePath;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e);}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,o,n){e=e.toUpperCase();let i=this.trees.get(e);i||(i=new xe,this.trees.set(e,i));let p=t.split("?")[0].replace(/^\/+|\/+$/g,""),c=p.length===0?[]:p.split("/"),d=i;for(let h of c){if(h==="*"){d.wildcardChild||(d.wildcardChild=new xe),d=d.wildcardChild;break}if(h.startsWith(":")){let u=h.slice(1);d.paramChild||(d.paramChild={node:new xe,name:u}),d=d.paramChild.node;continue}d.staticChildren.has(h)||d.staticChildren.set(h,new xe),d=d.staticChildren.get(h);}d.middleware=r,d.handler=o;let l=this.routes.findIndex(h=>h.method===e&&h.path===t);if(l!==-1){this.routes[l].middleware=r,this.routes[l].handler=o;return}this.routes.push({method:e,path:t,middleware:r,handler:o,swaggerOptions:n});}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let n=t.split("?")[0].replace(/^\/+|\/+$/g,""),i=n.length===0?[]:n.split("/"),a={},p=r;for(let c=0;c<i.length;c++){let d=i[c];if(p.staticChildren.has(d)){p=p.staticChildren.get(d);continue}if(p.paramChild){a[p.paramChild.name]=d,p=p.paramChild.node;continue}if(p.wildcardChild){a["*"]=i.slice(c).join("/"),p=p.wildcardChild;break}return null}return !p.handler||!p.middleware?null:{middleware:p.middleware,handler:p.handler,params:a}}get(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],d=i?r:o;this.addOrUpdate("GET",n,c,a,d);}post(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],d=i?r:o;this.addOrUpdate("POST",n,c,a,d);}patch(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],d=i?r:o;this.addOrUpdate("PATCH",n,c,a,d);}put(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],d=i?r:o;this.addOrUpdate("PUT",n,c,a,d);}delete(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],d=i?r:o;this.addOrUpdate("DELETE",n,c,a,d);}options(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],d=i?r:o;this.addOrUpdate("OPTIONS",n,c,a,d);}head(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],d=i?r:o;this.addOrUpdate("HEAD",n,c,a,d);}group(e,t,r){let o=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),a=new s(i,[...this.middlewares,...o]);n?.(a);for(let p of a.getRoutes())this.addOrUpdate(p.method,p.path,p.middleware,p.handler,p.swaggerOptions);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes)this.addOrUpdate(t.method,t.path,[...e,...t.middleware||[]],t.handler);}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(o=>typeof o=="string"&&o.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}},C=new ht;var Dr=s=>async(e,t,r)=>{for(let o of s)if(!await o.manager.canAccess(o.scope,o.handler,e))return t.unauthorized({error:"Unauthorized"});return r()},So=(s,e)=>t=>{let r=v.get(t.prototype,"__class__"),o=r?.middlewares||[],n=r?.policies||[],i=v.getAll(t.prototype),a=new t;for(let[p,c]of i.entries()){if(!c.route)continue;let d=t.prototype[p].bind(a),l=s?f.join(s,c.route.path):c.route.path,h=[...n,...c.policies||[]],u=h.length>0?[Dr(h)]:[],g=[...o,...u,...c.middlewares||[]];C.addOrUpdate(c.route.method,l,g,d,{service:t.name.replace(/Controller$/,""),...e,...c.documentation});}v.clear(t.prototype);};var To=(s,e)=>(t,r,o)=>{let n=v.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"DELETE"},v.set(t,r,n),o};var Po=(s,e)=>(t,r,o)=>{let n=v.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"GET"},v.set(t,r,n),o};var Mo=(s,e)=>(t,r,o)=>{let n=v.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PATCH"},v.set(t,r,n),o};var ko=(s,e)=>(t,r,o)=>{let n=v.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"POST"},v.set(t,r,n),o};var No=(s,e)=>(t,r,o)=>{let n=v.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PUT"},v.set(t,r,n),o};var Do=s=>(e,t,r)=>{if(typeof t>"u"){let n=v.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!s)throw new Error(`Middleware ${String(s)} not found, are you sure you defined it before using it?`);return Array.isArray(s)||(s=[s]),n.middlewares.push(...s),v.set(e.prototype,"__class__",n),e}let o=v.get(e,t);return o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),Array.isArray(s)||(s=[s]),o.middlewares.push(...s),v.set(e,t,o),r};var N=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 q=new Map;var D=(s,e,t=false)=>{if(!s(e)){if(t)return e;throw new ValidationError(s.errors||[])}return e};var Z=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
2
- 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 $t=Symbol("serializeWrapped"),Re=Symbol("serializeMetadata"),Ie=new WeakMap,Yo=(s,e)=>(t,r,o)=>{let n=v.get(t,r)||{middlewares:[],route:{}};n.documentation||(n.documentation={}),n.documentation.responses||(n.documentation.responses={}),n.serializeOptions||(n.serializeOptions={});let i=Number(e?.status??200);if(n.documentation.responses[i]=s,n.serializeOptions[i]=e?.safe??true,v.set(t,r,n),o.value[Re]||(o.value[Re]={}),o.value[Re][i]={name:r,schema:s,safe:e?.safe??true},!o.value[$t]){let a=o.value,p=async function(...c){let d=c[1];await a.apply(this,c);let l=d.responseStatus,h=p[Re],u=h?.[l]?.schema,g=h?.[l]?.safe??true;if(u&&!g){let b=d.getBody();try{let j;if(Z.isZodSchema(u)){let R=Ie.get(u);R||(R=Symbol("serialize_zod_schema"),Ie.set(u,R));let E=q.get(R);if(!E){let J=u.toJSONSchema();E=N.ajv.compile(J),q.set(R,E);}await D(E,b,g),d.send(b);}else if(typeof u=="object"&&u!==null){let R=Ie.get(u);R||(R=Symbol("serialize_json_schema"),Ie.set(u,R));let E=q.get(R);E||(E=N.ajv.compile(u),q.set(R,E)),await D(E,b,g),d.send(b);}else {j=JSON.stringify(u);let R=q.get(j);R||(R=N.ajv.compile(u),q.set(j,R)),await D(R,b,g),d.send(b);}}catch(j){let R=await Z.load();if(j instanceof R.ZodError){d.internalServerError({received:b,schema:u,error:j});return}throw j}}};p[$t]=true,p[Re]=a[Re],o.value=p;}};var pe=s=>(e,t,r)=>{let o=r.value,n=v.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),s.body&&(n.documentation.requestBody=s.body),s.query&&(n.documentation.query=s.query),s.all&&(n.documentation.requestBody=s.body,n.documentation.query=s.query),v.set(e,t,n),r.value=async function(...i){let a=i[0],p=i[1];try{let c,d,l;s.body&&(c=a.validate(s.body,s.safe)),s.query&&(d=a.validateQuery(s.query,s.safe)),s.all&&(l=a.validateAll(s.all,s.safe));let h=[...i];return c!==void 0&&h.push(c),d!==void 0&&h.push(d),l!==void 0&&h.push(l),o.apply(this,h)}catch(c){let d=await Z.load();if(!(c instanceof d.ZodError))throw c;return s.customError?p.status(s.customError.status||400).json({received:a.body,schema:s.body,error:c}):p.badRequest(c)}},r};pe.query=(s,e)=>pe({query:s,customError:e});pe.body=(s,e)=>pe({body:s,customError:e});pe.all=(s,e)=>pe({all:s,customError:e});var rn=pe;var Ht=class{logger=y.child({scope:this.constructor.name})};var ce=class{static options={connection:{}}},Nt=s=>{ce.options=s??{connection:{}};};var I=class extends x{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var ft=class{randomUUID(){return crypto.randomUUID()}},Y=new ft;var Ue=class{queues=new Map;workers=new Map;async publish(e,t,r){let o=await this.getQueue(e),n=Y.randomUUID();return await o.add(e,t,{jobId:n,...ce.options?.defaultJobOptions,...r}),{id:n}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...o}=ce.options??{},n=await this.getBullMQClient(),i=new n.Worker(e,async a=>{try{await t(a.data);}catch(p){await r?.(a,p)??Promise.reject(p);}},{...o});this.workers.set(e,i);}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new I("bullmq","ioredis")}),r=new t.Queue(e,{...ce.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 I("bullmq","ioredis")})),this.bullmqClient}};var X=class{static options={}},_t=s=>{X.options=s??{};};var Qe=class{createdQueues=new Set;async publish(e,t,r){let o=await this.getBoss();await this.ensureQueue(String(e));let n=r||{},i=await o.send(String(e),t,n);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(String(e));let o=X.options;o.errorHandler&&r.on("error",o.errorHandler),await r.work(String(e),async n=>{let i=Array.isArray(n)?n:[n];for(let a of i)await t(a.data);});}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new I("pg-boss","pg")}),r=e.default??e,{connectionString:o,boss:n}=X.options,i=o??n,a=new r(i);return X.options?.errorHandler&&a.on("error",X.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);}};var de=class{static options={}},Lt=s=>{de.options=s??{};};var ze=class{consumers=new Map;client;async publish(e,t,r){let{...o}=r??{},n=await this.getClient(),{SendMessageCommand:i}=await this.getSqsLib(),a=await this.resolveQueueUrl(String(e));if(!a)throw new Error(`[SQS] Queue url not configured for topic "${String(e)}"`);let p=new i({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:String(e)}},...o,QueueUrl:a});return {id:(await n.send(p)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(String(e)))throw new Error(`[SQS] Already subscribed to topic "${String(e)}"`);let r=de.options,o=await this.getSqsConsumerLib(),n={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(String(e)),handleMessage:async p=>{let c=JSON.parse(p.Body||"{}");await t(c);}},i=o.Consumer.create(n),a=r.errorHandler;a&&(i.on("error",a),i.on("processing_error",a)),i.start(),this.consumers.set(String(e),i);}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=de.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 I("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new I("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=de.options.consumer?.queueUrlMap?.[e];if(!r)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r}};var ee=class{static map=new Map;static{this.map.set("bullmq",new Ue),this.map.set("sqs",new ze),this.map.set("pgboss",new Qe);}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 Ge=class{static scheduledSubscribers=[];static register(e,t,r,o){this.scheduledSubscribers.push({name:e,topic:t,handler:r,provider:o?.provider??"bullmq"});}static async run(){if(y.info("Subscribing queue handlers"),!this.scheduledSubscribers.length){y.info("No queue handlers to subscribe");return}for(let{topic:e,handler:t,provider:r}of this.scheduledSubscribers)y.info(`Subscribing to queue: ${String(e)}`),await ee.getProvider(r).subscribe(e,t);y.info("Queue handlers subscribed");}static async massiveImportQueues(e){let t=[];for(let r of e){let o=await glob(r,{absolute:true,cwd:M.getCwd()});t.push(...o);}await Promise.all(t.map(async r=>{await import(r).catch(o=>{y.error(`Error importing queue handler: ${r}`),y.error(o);});}));}};var Te=(s,e)=>function(t,r,o){let n=o.value,i=async a=>{let p=new t.constructor;return n.apply(p,[a])};return Ge.register(`${t.constructor.name}.${r}`,e,i,{provider:s}),o};Te.bullmq=s=>Te("bullmq",s);Te.sqs=s=>Te("sqs",s);Te.pgboss=s=>Te("pgboss",s);var Dt=class{logger=y.child({scope:this.constructor.name})};var Qr=s=>{if(!Buffer.isBuffer(s))return s;let e=s.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 s{static subscriptions=[];static client=null;static connectionOptions={};static register(e,t,r,o){this.subscriptions.push({name:e,topic:t,handler:r,options:o});}static async connect(e={}){let t=await import('mqtt').catch(()=>{throw new x("mqtt not installed as a dependency, it is required in order to use MQTT subscriptions with the @mqtt decorator")});this.connectionOptions=e,y.info("Starting MQTT client"),this.subscriptions.length||y.info("No MQTT subscriptions to register");let{host:r="localhost",port:o=1883,protocol:n="mqtt",...i}=e,a=`${n}://${r}:${o}`;this.client=await t.connectAsync(a,i),y.info("MQTT client connected"),this.client.on("error",async p=>{await this.globalErrorHandler(p);}),this.client.on("message",(p,c)=>{this.handleMessage(p,c);}),this.client.on("disconnect",()=>{y.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)y.info(`Subscribing to MQTT topic: ${t} (${e})`),this.client.subscribe(t,r||{},o=>{if(o){y.error(`Failed to subscribe to topic ${t}: ${o.message}`);return}y.info(`Successfully subscribed to topic: ${t}`);});}static async handleMessage(e,t){let r=this.subscriptions.filter(o=>{if(o.topic===e)return true;if(!e||typeof e!="string")return false;let n=o.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${n}$`).test(e)});for(let o of r)try{await o.handler(e,t);}catch(n){y.error(`Error handling MQTT message for topic ${e} in ${o.name}`),this.globalErrorHandler(n);}}static globalErrorHandler(e){y.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 o=await glob(r,{absolute:true,cwd:M.getCwd()});t.push(...o);}await Promise.all(t.map(async r=>{await import(r).catch(o=>{y.error(`Error importing MQTT handler: ${r}`),y.error(o);});}));}subscribe(e,t){return function(r,o,n){let i=n.value;if(!i)return n;let a=async(p,c)=>{let d=new r.constructor,l=Qr(c);if(i.length===1){await i.call(d,l);return}await i.call(d,p,l);};return s.register(`${r.constructor.name}.${o}`,e,a,t),n}}async publish(e,t,r){if(!s.client)throw new x("MQTT client is not connected. Call MqttService.connect() first.");if(!s.client.connected)throw new x("MQTT client is not connected. Call MqttService.connect() first.");let o;Buffer.isBuffer(t)?o=t:typeof t=="object"?o=JSON.stringify(t):o=String(t);try{await s.client.publishAsync(e,o,r||{}),y.debug(`Published message to topic: ${String(e)}`);}catch(n){throw y.error(`Failed to publish to topic ${String(e)}: ${n.message}`),n}}static async disconnect(){if(this.client)return new Promise(e=>{this.client?.end(false,{},()=>{y.info("MQTT client disconnected gracefully"),this.client=null,e();});})}},Fn=s=>{$e.globalErrorHandler=s.bind($e);},Bn=new $e;var Ft=class{logger=y.child({scope:this.constructor.name})};var le=async(s,e,t,r)=>ee.getProvider(s).publish(e,t,r??{});le.bullmq=async(s,e,t)=>le("bullmq",s,e,t);le.sqs=async(s,e,t)=>le("sqs",s,e,t);le.pgboss=async(s,e,t)=>le("pgboss",s,e,t);var Gn=le;var Yn=s=>{let e=["bullmq","pgboss","sqs"];s.bullmq&&Nt(s.bullmq),s.pgboss&&_t(s.pgboss),s.sqs&&Lt(s.sqs);for(let t of Object.keys(s)){let r=t;e.includes(r)||ee.setProvider(r,s[r]);}};H();var gt=class{exit(e){switch(S.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},yt=new gt;var O=class{static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false};static args=ie().args.slice(1);static flags=ie().flags;static logger=y;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(c=>t.includes(c)))return;let o=this.commandName,n=this.description||"No description available",i=this.help||[],a=this.options,p=this.generateHelpOutput({name:o,description:n,helpText:i,options:a,args:this.args,flags:this.flags},this);console.log(p),yt.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:o,helpText:n,options:i,args:a,flags:p}=e,c={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"},d=[`${c.title}${r}${c.reset}`,`${c.description}${o}${c.reset}`,"",`${c.subtitle}Usage:${c.reset}`,` ${c.code}${r}${c.reset} [options] [arguments]`,"",`${c.subtitle}Options:${c.reset}`,` ${c.flag}-h, --help${c.reset} Show this help message`,"",`${c.subtitle}Command Options:${c.reset}`,` ${c.flag}keepAlive${c.reset} ${i?.keepAlive??false?c.success+"Enabled"+c.reset:c.error+"Disabled"+c.reset}`,""];if(n){let g=Array.isArray(n)?n:[n];d.push(`${c.subtitle}Help:${c.reset}`),g.forEach(b=>{d.push(` ${c.description}${b}${c.reset}`);}),d.push("");}let l=v.getAll(t),h=Array.from(l.values()).filter(g=>g.type==="arg"),u=Array.from(l.values()).filter(g=>g.type==="flag");return h.length&&(d.push(`${c.subtitle}Available Arguments:${c.reset}`),h.forEach(g=>{let b=g.required?` ${c.error}(required)${c.reset}`:"",j=g.description?` ${c.description}${g.description}${c.reset}`:"";d.push(` ${c.code}${g.name}${c.reset}${b}${j}`);}),d.push("")),u.length&&(d.push(`${c.subtitle}Available Flags:${c.reset}`),u.forEach(g=>{g.aliases&&!Array.isArray(g.aliases)&&(g.aliases=[g.aliases]);let b=g.aliases.length?` ${c.flag}(${g.aliases.join(", ")})${c.reset}`:"",j=g.required?` ${c.error}(required)${c.reset}`:"",R=g.description?` ${c.description}${g.description}${c.reset}`:"";d.push(` ${c.flag}--${g.name}${b}${c.reset}${j}${R}`);}),d.push("")),((a?.length??0)>0||p&&Object.keys(p).length>0)&&(d.push(`${c.subtitle}Current Context:${c.reset}`),a?.length&&d.push(` ${c.info}Provided Arguments:${c.reset} ${c.code}${a.join(" ")}${c.reset}`),p&&Object.keys(p).length>0&&(d.push(` ${c.info}Provided Flags:${c.reset}`),Object.keys(p).forEach(g=>{let b=p[g],j=b!=null?` = ${c.code}${b}${c.reset}`:"";d.push(` ${c.flag}${g}${c.reset}${j}`);})),d.push("")),n&&(Array.isArray(n)?n.some(g=>g.includes("example")):n.includes("example"))&&(d.push(`${c.subtitle}Examples:${c.reset}`),(Array.isArray(n)?n.filter(b=>b.includes("example")):[n.split("example")[1].trim()]).forEach(b=>{d.push(` ${c.code}${b}${c.reset}`);}),d.push("")),d.join(`
3
- `)};static validateContext=e=>{let t=Array.from(v.get(e,ae)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((o,n)=>{let i=`${r.info}${n+1}.${r.reset}`,a=`${r.error}${o.type.toUpperCase()}${r.reset}`,p=`${r.code}${o.name}${r.reset}`;console.error(` ${i} ${a} ${p}: ${r.error}${o.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),yt.exit(1);}}};H();var vt=class{async mkdir(e,t){switch(S.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(S.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(S.type){case "node":let o=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?o:new Uint8Array(o);case "bun":let n=Bun.file(e);return t?.encoding==="utf8"?n.text():new Uint8Array(await n.arrayBuffer());case "deno":let i=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(i):new Uint8Array(i)}}async writeFile(e,t){switch(S.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(S.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 n=await(await import('fs/promises')).stat(e);return {isDirectory:n.isDirectory(),isFile:n.isFile(),isSymbolicLink:n.isSymbolicLink(),size:n.size};case "deno":let i=await Deno.stat(e);return {isDirectory:i.isDirectory,isFile:i.isFile,isSymbolicLink:false,size:i.size}}}async unlink(e){switch(S.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(S.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),o=t.createReadStream(e);return r.toWeb(o);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(S.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let o of Deno.readDir(e))r.push(o.name);return r;default:throw new Error("Unsupported runtime")}}},m=new vt;var Ce=async s=>{let e=f.join(process.cwd(),"node_modules");if(!await m.exists(e))return s;let r=[];for(let o of s){let n=f.join(e,o);await m.exists(n)||r.push(o);}return r},U=async()=>await m.exists(f.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await m.exists(f.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await m.exists(f.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await m.exists(f.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await m.exists(f.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],_=async(s,e,t,r,o=true)=>{let n=Bt.createInterface({input:process.stdin,output:process.stdout}),i=t.join(", "),a=`Do you want to install the following ${o?"dev":""} dependencies using ${e}?
1
+ import {glob}from'glob';import At from'pino';import Ie from'path';import {Ajv,ValidationError}from'ajv';import Ve from'fs';import {execSync}from'child_process';import*as It from'readline';import {AsyncLocalStorage}from'async_hooks';import {gzipSync}from'zlib';import {createServer}from'http';import {createServer as createServer$1,createSecureServer}from'http2';import {createServer as createServer$2}from'https';import {Readable}from'stream';var Et=Object.defineProperty;var Hr=(s,e)=>()=>(s&&(e=s(s=0)),e);var Nr=(s,e)=>{for(var t in e)Et(s,t,{get:e[t],enumerable:true});};var y=(s,e,t,r)=>{for(var o=void 0,n=s.length-1,i;n>=0;n--)(i=s[n])&&(o=(i(e,t,o))||o);return o&&Et(e,t,o),o};var Mt={};Nr(Mt,{runtime:()=>R});var lt,R,F=Hr(()=>{lt=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 lt;});var T=class extends Error{constructor(e){super(e);}};var _r=()=>At({level:"info",formatters:{level:e=>({level:e})}}),v=_r(),Ds=s=>{v=At(s);};F();var dt=class{getCwd(){switch(R.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},k=new dt;var Se=class{static scheduledJobs=[];static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t});}static async run(){let e=(await import('node-cron').catch(()=>{throw new T("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(v.info("Scheduling cron jobs"),!this.scheduledJobs.length){v.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)v.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));v.info("Cron jobs scheduled");}static globalErrorHandler(e){v.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let o=await glob(r,{absolute:true,cwd:k.getCwd()});t.push(...o);}await Promise.all(t.map(async r=>{await import(r).catch(o=>{v.error(`Error importing cron job: ${r}`),v.error(o);});}));}},Ks=s=>{Se.globalErrorHandler=s.bind(Se);};var Ws=(s,e)=>function(t,r,o){let n=o.value,i=async(...a)=>{let p=new t.constructor;return await n.apply(p,a)};return Se.register(`${t.constructor.name}.${r}`,s,i,e),o};F();var ut=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],o=r.split("/").pop()||r;if(!r.startsWith("-")){if(o==="yarn"&&t+1<e.length&&e[t+1]==="run"||o==="npx"&&t+1<e.length)return t+1;if(o==="yarn"||o==="pnpm")return t;if(o==="npm"&&t+1<e.length&&e[t+1]==="run"||o==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(o)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},mt=new ut;var De=s=>s.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),Fe=s=>s.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),qt=s=>s.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var xe=(s,e)=>{if(!s||typeof s!="string")return e;let t=s.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),o=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let n=Number.parseFloat(r[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024)}if(o){let n=Number.parseFloat(o[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024*1024)}return e};var Dr=s=>{if(!s||s==="-"||s==="--")return null;let e=s.indexOf("=");if(e>0){let t=s.substring(0,e),r=s.substring(e+1);return {name:t,value:kt(r)}}return {name:s,value:true}},kt=s=>{if(s.toLowerCase()==="true")return true;if(s.toLowerCase()==="false")return false;let e=Number(s);return !Number.isNaN(e)&&Number.isFinite(e)?e:s},ie=()=>{let s=mt.getCliArgs(),e=[],t={};if(!s||!s.length)return {args:e,flags:t};for(let r=0;r<s.length;r++){let o=s[r];if(!(!o||typeof o!="string")){if(o.startsWith("-")){let n=Dr(o);if(n){if(n.value===true&&r+1<s.length){let i=s[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(n.value=kt(i),r++);}if(n.name in t){let i=t[n.name];Array.isArray(i)?i.push(n.value):t[n.name]=[i,n.value];}else t[n.name]=n.value;}continue}e.push(o);}}return {args:e,flags:t}};var Be=()=>mt.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 ae="VALIDATION_ERROR",po="ARG",$t=ie().args.slice(1),q=s=>(e,t)=>{let r=Be();if(!r||r!==e.commandName)return;let o=t;w.set(e,t,{type:"arg",name:o,description:s.description});let n=$t.length?$t.shift():s.defaultValue;if(s.required&&!n){let i=w.get(e,ae);w.set(e,ae,[...i||[],{type:"arg",name:o,message:"Required argument not provided"}]);return}s.parse&&n&&(n=s.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var Z=s=>(e,t)=>{let r=Be();if(!r||r!==e.commandName)return;let o=s.name||t,n=ie().flags,i=s.aliases||[],a=[o,...i],p=s.defaultValue;for(let c of a){let l=[c,`-${c}`,`--${c}`];for(let d of l)if(d in n){let f=n[d];s.type==="list"?p=(Array.isArray(f)?f:[f]).map(g=>{let S=String(g);return s.parse?s.parse(S):S}):(p=f,s.type==="boolean"?p=!!p:s.type==="number"&&(p=Number(p)),s.parse&&(p=s.parse(p)));break}if(p!==s.defaultValue)break}if(w.set(e,t,{type:"flag",name:o,aliases:i||[],description:s.description}),s.required&&(s.type==="list"?!p||Array.isArray(p)&&p.length===0:!p)){let l=w.get(e,ae);w.set(e,ae,[...l||[],{type:"flag",name:o,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:p,enumerable:true,configurable:true,writable:true});};Z.boolean=s=>Z({...s,type:"boolean"});Z.string=s=>Z({...s,type:"string"});Z.number=s=>Z({...s,type:"number"});Z.list=s=>Z({...s,type:"list"});var x=Z;F();var ht=class{basename(e){switch(R.type){case "node":case "bun":case "deno":return Ie.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(R.type){case "node":case "bun":case "deno":return Ie.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(R.type){case "bun":case "node":case "deno":return Ie.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(R.type){case "bun":case "node":case "deno":return Ie.resolve(...e);default:throw new Error("Unsupported runtime")}}},h=new ht;var Re=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null;}},ft=class s{trees;routes;middlewares;basePath;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e);}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,o,n){e=e.toUpperCase();let i=this.trees.get(e);i||(i=new Re,this.trees.set(e,i));let p=t.split("?")[0].replace(/^\/+|\/+$/g,""),c=p.length===0?[]:p.split("/"),l=i;for(let f of c){if(f==="*"){l.wildcardChild||(l.wildcardChild=new Re),l=l.wildcardChild;break}if(f.startsWith(":")){let m=f.slice(1);l.paramChild||(l.paramChild={node:new Re,name:m}),l=l.paramChild.node;continue}l.staticChildren.has(f)||l.staticChildren.set(f,new Re),l=l.staticChildren.get(f);}l.middleware=r,l.handler=o;let d=this.routes.findIndex(f=>f.method===e&&f.path===t);if(d!==-1){this.routes[d].middleware=r,this.routes[d].handler=o;return}this.routes.push({method:e,path:t,middleware:r,handler:o,swaggerOptions:n});}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let n=t.split("?")[0].replace(/^\/+|\/+$/g,""),i=n.length===0?[]:n.split("/"),a={},p=r;for(let c=0;c<i.length;c++){let l=i[c];if(p.staticChildren.has(l)){p=p.staticChildren.get(l);continue}if(p.paramChild){a[p.paramChild.name]=l,p=p.paramChild.node;continue}if(p.wildcardChild){a["*"]=i.slice(c).join("/"),p=p.wildcardChild;break}return null}return !p.handler||!p.middleware?null:{middleware:p.middleware,handler:p.handler,params:a}}get(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],l=i?r:o;this.addOrUpdate("GET",n,c,a,l);}post(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],l=i?r:o;this.addOrUpdate("POST",n,c,a,l);}patch(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],l=i?r:o;this.addOrUpdate("PATCH",n,c,a,l);}put(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],l=i?r:o;this.addOrUpdate("PUT",n,c,a,l);}delete(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],l=i?r:o;this.addOrUpdate("DELETE",n,c,a,l);}options(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],l=i?r:o;this.addOrUpdate("OPTIONS",n,c,a,l);}head(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,p=i?[]:Array.isArray(t)?t:[t],c=[...this.middlewares,...p],l=i?r:o;this.addOrUpdate("HEAD",n,c,a,l);}group(e,t,r){let o=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),a=new s(i,[...this.middlewares,...o]);n?.(a);for(let p of a.getRoutes())this.addOrUpdate(p.method,p.path,p.middleware,p.handler,p.swaggerOptions);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes)this.addOrUpdate(t.method,t.path,[...e,...t.middleware||[]],t.handler);}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(o=>typeof o=="string"&&o.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}},O=new ft;var Fr=s=>async(e,t,r)=>{for(let o of s)if(!await o.manager.canAccess(o.scope,o.handler,e))return t.unauthorized({error:"Unauthorized"});return r()},xo=(s,e)=>t=>{let r=w.get(t.prototype,"__class__"),o=r?.middlewares||[],n=r?.policies||[],i=w.getAll(t.prototype),a=new t;for(let[p,c]of i.entries()){if(!c.route)continue;let l=t.prototype[p].bind(a),d=s?h.join(s,c.route.path):c.route.path,f=[...n,...c.policies||[]],m=f.length>0?[Fr(f)]:[],g=[...o,...m,...c.middlewares||[]];O.addOrUpdate(c.route.method,d,g,l,{service:t.name.replace(/Controller$/,""),...e,...c.documentation});}w.clear(t.prototype);};var Co=(s,e)=>(t,r,o)=>{let n=w.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"DELETE"},w.set(t,r,n),o};var jo=(s,e)=>(t,r,o)=>{let n=w.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"GET"},w.set(t,r,n),o};var Mo=(s,e)=>(t,r,o)=>{let n=w.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PATCH"},w.set(t,r,n),o};var $o=(s,e)=>(t,r,o)=>{let n=w.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"POST"},w.set(t,r,n),o};var _o=(s,e)=>(t,r,o)=>{let n=w.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PUT"},w.set(t,r,n),o};var Fo=s=>(e,t,r)=>{if(typeof t>"u"){let n=w.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!s)throw new Error(`Middleware ${String(s)} not found, are you sure you defined it before using it?`);return Array.isArray(s)||(s=[s]),n.middlewares.push(...s),w.set(e.prototype,"__class__",n),e}let o=w.get(e,t);return o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),Array.isArray(s)||(s=[s]),o.middlewares.push(...s),w.set(e,t,o),r};var B=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 H=new Map;var Q=(s,e,t=false)=>{if(!s(e)){if(t)return e;throw new ValidationError(s.errors||[])}return e};var W=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
2
+ 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 Ht=Symbol("serializeWrapped"),Te=Symbol("serializeMetadata"),Ue=new WeakMap,Xo=(s,e)=>(t,r,o)=>{let n=w.get(t,r)||{middlewares:[],route:{}};n.documentation||(n.documentation={}),n.documentation.responses||(n.documentation.responses={}),n.serializeOptions||(n.serializeOptions={});let i=Number(e?.status??200);if(n.documentation.responses[i]=s,n.serializeOptions[i]=e?.safe??true,w.set(t,r,n),o.value[Te]||(o.value[Te]={}),o.value[Te][i]={name:r,schema:s,safe:e?.safe??true},!o.value[Ht]){let a=o.value,p=async function(...c){let l=c[1];await a.apply(this,c);let d=l.responseStatus,f=p[Te],m=f?.[d]?.schema,g=f?.[d]?.safe??true;if(m&&!g){let S=l.getBody();try{let E;if(W.isZodSchema(m)){let C=Ue.get(m);C||(C=Symbol("serialize_zod_schema"),Ue.set(m,C));let A=H.get(C);if(!A){let b=m.toJSONSchema();A=B.ajv.compile(b),H.set(C,A);}await Q(A,S,g),l.send(S);}else if(typeof m=="object"&&m!==null){let C=Ue.get(m);C||(C=Symbol("serialize_json_schema"),Ue.set(m,C));let A=H.get(C);A||(A=B.ajv.compile(m),H.set(C,A)),await Q(A,S,g),l.send(S);}else {E=JSON.stringify(m);let C=H.get(E);C||(C=B.ajv.compile(m),H.set(E,C)),await Q(C,S,g),l.send(S);}}catch(E){let C=await W.load();if(E instanceof C.ZodError){l.internalServerError({received:S,schema:m,error:E});return}throw E}}};p[Ht]=true,p[Te]=a[Te],o.value=p;}};var pe=s=>(e,t,r)=>{let o=r.value,n=w.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),s.body&&(n.documentation.requestBody=s.body),s.query&&(n.documentation.query=s.query),s.all&&(n.documentation.requestBody=s.body,n.documentation.query=s.query),w.set(e,t,n),r.value=async function(...i){let a=i[0],p=i[1];try{let c,l,d;s.body&&(c=a.validate(s.body,s.safe)),s.query&&(l=a.validateQuery(s.query,s.safe)),s.all&&(d=a.validateAll(s.all,s.safe));let f=[...i];return c!==void 0&&f.push(c),l!==void 0&&f.push(l),d!==void 0&&f.push(d),o.apply(this,f)}catch(c){let l=await W.load();if(!(c instanceof l.ZodError))throw c;return s.customError?p.status(s.customError.status||400).json({received:a.body,schema:s.body,error:c}):p.badRequest(c)}},r};pe.query=(s,e)=>pe({query:s,customError:e});pe.body=(s,e)=>pe({body:s,customError:e});pe.all=(s,e)=>pe({all:s,customError:e});var sn=pe;var Nt=class{logger=v.child({scope:this.constructor.name})};var ce=class{static options={connection:{}}},_t=s=>{ce.options=s??{connection:{}};};var z=class extends T{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var gt=class{randomUUID(){return crypto.randomUUID()}},X=new gt;var Qe=class{queues=new Map;workers=new Map;async publish(e,t,r){let o=await this.getQueue(e),n=X.randomUUID();return await o.add(e,t,{jobId:n,...ce.options?.defaultJobOptions,...r}),{id:n}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...o}=ce.options??{},n=await this.getBullMQClient(),i=new n.Worker(e,async a=>{try{await t(a.data);}catch(p){await r?.(a,p)??Promise.reject(p);}},{...o});this.workers.set(e,i);}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new z("bullmq","ioredis")}),r=new t.Queue(e,{...ce.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 z("bullmq","ioredis")})),this.bullmqClient}};var ee=class{static options={}},Lt=s=>{ee.options=s??{};};var ze=class{createdQueues=new Set;async publish(e,t,r){let o=await this.getBoss();await this.ensureQueue(String(e));let n=r||{},i=await o.send(String(e),t,n);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(String(e));let o=ee.options;o.errorHandler&&r.on("error",o.errorHandler),await r.work(String(e),async n=>{let i=Array.isArray(n)?n:[n];for(let a of i)await t(a.data);});}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new z("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:o,boss:n}=ee.options,i=o??n,a=new r(i);return ee.options?.errorHandler&&a.on("error",ee.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);}};var le=class{static options={}},Dt=s=>{le.options=s??{};};var Ge=class{consumers=new Map;client;async publish(e,t,r){let{...o}=r??{},n=await this.getClient(),{SendMessageCommand:i}=await this.getSqsLib(),a=await this.resolveQueueUrl(String(e));if(!a)throw new Error(`[SQS] Queue url not configured for topic "${String(e)}"`);let p=new i({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:String(e)}},...o,QueueUrl:a});return {id:(await n.send(p)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(String(e)))throw new Error(`[SQS] Already subscribed to topic "${String(e)}"`);let r=le.options,o=await this.getSqsConsumerLib(),n={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(String(e)),handleMessage:async p=>{let c=JSON.parse(p.Body||"{}");await t(c);}},i=o.Consumer.create(n),a=r.errorHandler;a&&(i.on("error",a),i.on("processing_error",a)),i.start(),this.consumers.set(String(e),i);}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=le.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 z("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new z("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=le.options.consumer?.queueUrlMap?.[e];if(!r)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r}};var te=class{static map=new Map;static{this.map.set("bullmq",new Qe),this.map.set("sqs",new Ge),this.map.set("pgboss",new ze);}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 Ke=class{static scheduledSubscribers=[];static register(e,t,r,o){this.scheduledSubscribers.push({name:e,topic:t,handler:r,provider:o?.provider??"bullmq"});}static async run(){if(v.info("Subscribing queue handlers"),!this.scheduledSubscribers.length){v.info("No queue handlers to subscribe");return}for(let{topic:e,handler:t,provider:r}of this.scheduledSubscribers)v.info(`Subscribing to queue: ${String(e)}`),await te.getProvider(r).subscribe(e,t);v.info("Queue handlers subscribed");}static async massiveImportQueues(e){let t=[];for(let r of e){let o=await glob(r,{absolute:true,cwd:k.getCwd()});t.push(...o);}await Promise.all(t.map(async r=>{await import(r).catch(o=>{v.error(`Error importing queue handler: ${r}`),v.error(o);});}));}};var Ce=(s,e)=>function(t,r,o){let n=o.value,i=async a=>{let p=new t.constructor;return n.apply(p,[a])};return Ke.register(`${t.constructor.name}.${r}`,e,i,{provider:s}),o};Ce.bullmq=s=>Ce("bullmq",s);Ce.sqs=s=>Ce("sqs",s);Ce.pgboss=s=>Ce("pgboss",s);var Ft=class{logger=v.child({scope:this.constructor.name})};var zr=s=>{if(!Buffer.isBuffer(s))return s;let e=s.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},He=class s{static subscriptions=[];static client=null;static connectionOptions={};static register(e,t,r,o){this.subscriptions.push({name:e,topic:t,handler:r,options:o});}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,v.info("Starting MQTT client"),this.subscriptions.length||v.info("No MQTT subscriptions to register");let{host:r="localhost",port:o=1883,protocol:n="mqtt",...i}=e,a=`${n}://${r}:${o}`;this.client=await t.connectAsync(a,i),v.info("MQTT client connected"),this.client.on("error",async p=>{await this.globalErrorHandler(p);}),this.client.on("message",(p,c)=>{this.handleMessage(p,c);}),this.client.on("disconnect",()=>{v.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)v.info(`Subscribing to MQTT topic: ${t} (${e})`),this.client.subscribe(t,r||{},o=>{if(o){v.error(`Failed to subscribe to topic ${t}: ${o.message}`);return}v.info(`Successfully subscribed to topic: ${t}`);});}static async handleMessage(e,t){let r=this.subscriptions.filter(o=>{if(o.topic===e)return true;if(!e||typeof e!="string")return false;let n=o.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${n}$`).test(e)});for(let o of r)try{await o.handler(e,t);}catch(n){v.error(`Error handling MQTT message for topic ${e} in ${o.name}`),this.globalErrorHandler(n);}}static globalErrorHandler(e){v.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 o=await glob(r,{absolute:true,cwd:k.getCwd()});t.push(...o);}await Promise.all(t.map(async r=>{await import(r).catch(o=>{v.error(`Error importing MQTT handler: ${r}`),v.error(o);});}));}subscribe(e,t){return function(r,o,n){let i=n.value;if(!i)return n;let a=async(p,c)=>{let l=new r.constructor,d=zr(c);if(i.length===1){await i.call(l,d);return}await i.call(l,p,d);};return s.register(`${r.constructor.name}.${o}`,e,a,t),n}}async publish(e,t,r){if(!s.client)throw new T("MQTT client is not connected. Call MqttService.connect() first.");if(!s.client.connected)throw new T("MQTT client is not connected. Call MqttService.connect() first.");let o;Buffer.isBuffer(t)?o=t:typeof t=="object"?o=JSON.stringify(t):o=String(t);try{await s.client.publishAsync(e,o,r||{}),v.debug(`Published message to topic: ${String(e)}`);}catch(n){throw v.error(`Failed to publish to topic ${String(e)}: ${n.message}`),n}}static async disconnect(){if(this.client)return new Promise(e=>{this.client?.end(false,{},()=>{v.info("MQTT client disconnected gracefully"),this.client=null,e();});})}},Bn=s=>{He.globalErrorHandler=s.bind(He);},In=new He;var Bt=class{logger=v.child({scope:this.constructor.name})};var de=async(s,e,t,r)=>te.getProvider(s).publish(e,t,r??{});de.bullmq=async(s,e,t)=>de("bullmq",s,e,t);de.sqs=async(s,e,t)=>de("sqs",s,e,t);de.pgboss=async(s,e,t)=>de("pgboss",s,e,t);var Kn=de;var Xn=s=>{let e=["bullmq","pgboss","sqs"];s.bullmq&&_t(s.bullmq),s.pgboss&&Lt(s.pgboss),s.sqs&&Dt(s.sqs);for(let t of Object.keys(s)){let r=t;e.includes(r)||te.setProvider(r,s[r]);}};F();var yt=class{exit(e){switch(R.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},vt=new yt;var P=class{static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false};static args=ie().args.slice(1);static flags=ie().flags;static logger=v;static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help"];if(!Object.keys(e).some(c=>t.includes(c)))return;let o=this.commandName,n=this.description||"No description available",i=this.help||[],a=this.options,p=this.generateHelpOutput({name:o,description:n,helpText:i,options:a,args:this.args,flags:this.flags},this);console.log(p),vt.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:o,helpText:n,options:i,args:a,flags:p}=e,c={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=[`${c.title}${r}${c.reset}`,`${c.description}${o}${c.reset}`,"",`${c.subtitle}Usage:${c.reset}`,` ${c.code}${r}${c.reset} [options] [arguments]`,"",`${c.subtitle}Options:${c.reset}`,` ${c.flag}-h, --help${c.reset} Show this help message`,"",`${c.subtitle}Command Options:${c.reset}`,` ${c.flag}keepAlive${c.reset} ${i?.keepAlive??false?c.success+"Enabled"+c.reset:c.error+"Disabled"+c.reset}`,""];if(n){let g=Array.isArray(n)?n:[n];l.push(`${c.subtitle}Help:${c.reset}`),g.forEach(S=>{l.push(` ${c.description}${S}${c.reset}`);}),l.push("");}let d=w.getAll(t),f=Array.from(d.values()).filter(g=>g.type==="arg"),m=Array.from(d.values()).filter(g=>g.type==="flag");return f.length&&(l.push(`${c.subtitle}Available Arguments:${c.reset}`),f.forEach(g=>{let S=g.required?` ${c.error}(required)${c.reset}`:"",E=g.description?` ${c.description}${g.description}${c.reset}`:"";l.push(` ${c.code}${g.name}${c.reset}${S}${E}`);}),l.push("")),m.length&&(l.push(`${c.subtitle}Available Flags:${c.reset}`),m.forEach(g=>{g.aliases&&!Array.isArray(g.aliases)&&(g.aliases=[g.aliases]);let S=g.aliases.length?` ${c.flag}(${g.aliases.join(", ")})${c.reset}`:"",E=g.required?` ${c.error}(required)${c.reset}`:"",C=g.description?` ${c.description}${g.description}${c.reset}`:"";l.push(` ${c.flag}--${g.name}${S}${c.reset}${E}${C}`);}),l.push("")),((a?.length??0)>0||p&&Object.keys(p).length>0)&&(l.push(`${c.subtitle}Current Context:${c.reset}`),a?.length&&l.push(` ${c.info}Provided Arguments:${c.reset} ${c.code}${a.join(" ")}${c.reset}`),p&&Object.keys(p).length>0&&(l.push(` ${c.info}Provided Flags:${c.reset}`),Object.keys(p).forEach(g=>{let S=p[g],E=S!=null?` = ${c.code}${S}${c.reset}`:"";l.push(` ${c.flag}${g}${c.reset}${E}`);})),l.push("")),n&&(Array.isArray(n)?n.some(g=>g.includes("example")):n.includes("example"))&&(l.push(`${c.subtitle}Examples:${c.reset}`),(Array.isArray(n)?n.filter(S=>S.includes("example")):[n.split("example")[1].trim()]).forEach(S=>{l.push(` ${c.code}${S}${c.reset}`);}),l.push("")),l.join(`
3
+ `)};static validateContext=e=>{let t=Array.from(w.get(e,ae)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((o,n)=>{let i=`${r.info}${n+1}.${r.reset}`,a=`${r.error}${o.type.toUpperCase()}${r.reset}`,p=`${r.code}${o.name}${r.reset}`;console.error(` ${i} ${a} ${p}: ${r.error}${o.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),vt.exit(1);}}};F();var wt=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 o=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?o:new Uint8Array(o);case "bun":let n=Bun.file(e);return t?.encoding==="utf8"?n.text():new Uint8Array(await n.arrayBuffer());case "deno":let i=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(i):new Uint8Array(i)}}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 n=await(await import('fs/promises')).stat(e);return {isDirectory:n.isDirectory(),isFile:n.isFile(),isSymbolicLink:n.isSymbolicLink(),size:n.size};case "deno":let i=await Deno.stat(e);return {isDirectory:i.isDirectory,isFile:i.isFile,isSymbolicLink:false,size:i.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'),o=t.createReadStream(e);return r.toWeb(o);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 o of Deno.readDir(e))r.push(o.name);return r;default:throw new Error("Unsupported runtime")}}},u=new wt;var Oe=async s=>{let e=h.join(process.cwd(),"node_modules");if(!await u.exists(e))return s;let r=[];for(let o of s){let n=h.join(e,o);await u.exists(n)||r.push(o);}return r},I=async()=>await u.exists(h.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await u.exists(h.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await u.exists(h.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await u.exists(h.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await u.exists(h.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],N=async(s,e,t,r,o=true)=>{let n=It.createInterface({input:process.stdin,output:process.stdout}),i=t.join(", "),a=`Do you want to install the following ${o?"dev":""} dependencies using ${e}?
4
4
  ${i}
5
- (y/n): `;return new Promise(p=>{n.question(a,c=>{if(n.close(),c.toLowerCase()==="y"||c.toLowerCase()==="yes"){execSync(s,r),p(true);return}p(false);});})};var $=class extends O{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,p,c]=await U();await _(`${a} ${p} esbuild ${c}`,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=Be.join(this.output,"assets"),o=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(p=>{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")});Ke.existsSync(r)||Ke.mkdirSync(r,{recursive:true}),o.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&Ke.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Ke.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let n=Be.join(this.output,"server.js"),i=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:n,minify:true,sourcemap:this.sourcemap,plugins:o,format:this.format,packages:this.packages});i.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:i.errors},null,2)),process.exit(1)),i.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:i.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${n}`,output:n,assets:!!this.assets},null,2)),process.exit(0);}};w([T({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],$,"clearDist"),w([T({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],$,"entry"),w([T({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],$,"output"),w([T({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],$,"tsconfig"),w([T({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],$,"assets"),w([T({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'"})],$,"format"),w([T({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'"})],$,"packages"),w([T({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],$,"sourcemap");var Oe=class extends O{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){if(Pe.getCommand(this.name)){let o=Pe.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:o},`Command "${this.name}" already exists as a ${o} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=f.join(this.path,`${this.name}.ts`),await m.exists(f.join(process.cwd(),this.path))||await m.mkdir(f.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.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";
5
+ (y/n): `;return new Promise(p=>{n.question(a,c=>{if(n.close(),c.toLowerCase()==="y"||c.toLowerCase()==="yes"){execSync(s,r),p(true);return}p(false);});})};var D=class extends P{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,p,c]=await I();await N(`${a} ${p} esbuild ${c}`,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=Ie.join(this.output,"assets"),o=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(p=>{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")});Ve.existsSync(r)||Ve.mkdirSync(r,{recursive:true}),o.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&Ve.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Ve.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let n=Ie.join(this.output,"server.js"),i=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:n,minify:true,sourcemap:this.sourcemap,plugins:o,format:this.format,packages:this.packages});i.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:i.errors},null,2)),process.exit(1)),i.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:i.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${n}`,output:n,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"})],D,"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"})],D,"entry"),y([x({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],D,"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"})],D,"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"})],D,"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'"})],D,"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'"})],D,"packages"),y([x({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],D,"sourcemap");var Pe=class extends P{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(je.getCommand(this.name)){let o=je.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:o},`Command "${this.name}" already exists as a ${o} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=h.join(this.path,`${this.name}.ts`),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.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";
6
6
 
7
7
  export default class extends Command {
8
8
  static commandName = "${this.name}";
@@ -16,9 +16,9 @@ export default class extends Command {
16
16
  static async handle(): Promise<void> {
17
17
  // Implement your command logic here
18
18
  }
19
- }`}};w([A({description:"The name of the command to generate",required:true})],Oe,"name");var ue=class extends O{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=f.join(this.path,t),await m.exists(f.join(process.cwd(),this.path))||await m.mkdir(f.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Controller ${this.controllerName} created successfully at ${this.path}`);}static getControllerTemplate(){let e=De(this.controllerName);return `import { controller, get, post, put, del, Request, Response } from "balda";
19
+ }`}};y([q({description:"The name of the command to generate",required:true})],Pe,"name");var ue=class extends P{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=h.join(this.path,t),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Controller ${this.controllerName} created successfully at ${this.path}`);}static getControllerTemplate(){let e=Fe(this.controllerName);return `import { controller, get, post, put, del, Request, Response } from "balda";
20
20
 
21
- @controller("/${At(this.controllerName)}")
21
+ @controller("/${qt(this.controllerName)}")
22
22
  export default class ${e}Controller {
23
23
  @get("/")
24
24
  async index(req: Request, res: Response) {
@@ -44,7 +44,7 @@ export default class ${e}Controller {
44
44
  async destroy(req: Request, res: Response) {
45
45
  return { message: \`Delete ${this.controllerName.toLowerCase()} with id \${req.params.id}\` };
46
46
  }
47
- }`}};w([A({description:"The name of the controller to generate",required:true})],ue,"controllerName"),w([T({description:"The path to the controller to generate, default is src/controllers",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/controllers"})],ue,"path");var me=class extends O{static commandName="generate-cron";static description="Generate a new cron job in the specified path";static help=["Generate a new cron job in the specified path","Example: npx balda generate-cron my-cron -p src/cron"];static fileName;static path;static async handle(){let e=this.getCronTemplate();this.path=f.join(this.path,`${this.fileName}.ts`),await m.exists(f.join(process.cwd(),this.path))||await m.mkdir(f.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`);}static getCronTemplate(){return `import { BaseCron, cron } from "balda";
47
+ }`}};y([q({description:"The name of the controller to generate",required:true})],ue,"controllerName"),y([x({description:"The path to the controller to generate, default is src/controllers",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/controllers"})],ue,"path");var me=class extends P{static commandName="generate-cron";static description="Generate a new cron job in the specified path";static help=["Generate a new cron job in the specified path","Example: npx balda generate-cron my-cron -p src/cron"];static fileName;static path;static async handle(){let e=this.getCronTemplate();this.path=h.join(this.path,`${this.fileName}.ts`),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`);}static getCronTemplate(){return `import { BaseCron, cron } from "balda";
48
48
 
49
49
  export default class extends BaseCron {
50
50
  @cron("* * * * *")
@@ -52,7 +52,7 @@ export default class extends BaseCron {
52
52
  this.logger.info("Running cron job");
53
53
  // Implement your cron job logic here
54
54
  }
55
- }`}};w([A({description:"The name of the cron job file to generate",required:true})],me,"fileName"),w([T({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],me,"path");var he=class extends O{static commandName="generate-middleware";static description="Generate a new middleware in the specified path";static help=["Generate a new middleware in the specified path","Example: npx balda generate-middleware auth -p src/middlewares"];static middlewareName;static path;static async handle(){let e=this.getMiddlewareTemplate(),t=`${this.middlewareName.toLowerCase()}.ts`;this.path=f.join(this.path,t),await m.exists(f.join(process.cwd(),this.path))||await m.mkdir(f.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Middleware ${this.middlewareName} created successfully at ${this.path}`);}static getMiddlewareTemplate(){let e=De(this.middlewareName);return `import type { Request, Response, NextFunction, ServerRouteMiddleware } from "balda";
55
+ }`}};y([q({description:"The name of the cron job file to generate",required:true})],me,"fileName"),y([x({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],me,"path");var he=class extends P{static commandName="generate-middleware";static description="Generate a new middleware in the specified path";static help=["Generate a new middleware in the specified path","Example: npx balda generate-middleware auth -p src/middlewares"];static middlewareName;static path;static async handle(){let e=this.getMiddlewareTemplate(),t=`${this.middlewareName.toLowerCase()}.ts`;this.path=h.join(this.path,t),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Middleware ${this.middlewareName} created successfully at ${this.path}`);}static getMiddlewareTemplate(){let e=Fe(this.middlewareName);return `import type { Request, Response, NextFunction, ServerRouteMiddleware } from "balda";
56
56
 
57
57
  /**
58
58
  * ${e} middleware
@@ -63,7 +63,7 @@ export const ${e}: ServerRouteMiddleware = async () => {
63
63
  // Add your middleware logic here
64
64
  return next();
65
65
  };
66
- };`}};w([A({description:"The name of the middleware to generate",required:true})],he,"middlewareName"),w([T({description:"The path to the middleware to generate, default is src/middlewares",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/middlewares"})],he,"path");var fe=class extends O{static commandName="generate-mqtt";static description="Generate a new MQTT handler in the specified path";static help=["Generate a new MQTT handler in the specified path","Example: npx balda generate-mqtt temperature-handler -p src/mqtt"];static path;static topic;static async handle(){let e=this.topic.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getMqttTemplate(!!e);this.path=f.join(this.path,`${Le(this.topic.replace(/\//g,"_"))}.ts`),await m.exists(f.join(process.cwd(),this.path))||await m.mkdir(f.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`MQTT handler for topic ${this.topic} created successfully at ${this.path}`);}static getMqttTemplate(e){return `import { BaseMqtt, mqtt } from "balda";
66
+ };`}};y([q({description:"The name of the middleware to generate",required:true})],he,"middlewareName"),y([x({description:"The path to the middleware to generate, default is src/middlewares",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/middlewares"})],he,"path");var fe=class extends P{static commandName="generate-mqtt";static description="Generate a new MQTT handler in the specified path";static help=["Generate a new MQTT handler in the specified path","Example: npx balda generate-mqtt temperature-handler -p src/mqtt"];static path;static topic;static async handle(){let e=this.topic.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getMqttTemplate(!!e);this.path=h.join(this.path,`${De(this.topic.replace(/\//g,"_"))}.ts`),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`MQTT handler for topic ${this.topic} created successfully at ${this.path}`);}static getMqttTemplate(e){return `import { BaseMqtt, mqtt } from "balda";
67
67
 
68
68
  /**
69
69
  * Define your MQTT topics interface for type safety
@@ -80,7 +80,7 @@ export default class extends BaseMqtt {
80
80
  this.logger.info({ message }, "Message received");
81
81
  // Implement your MQTT handler logic here
82
82
  }
83
- }`}};w([T({description:"The path to the MQTT handler to generate, default is src/mqtt",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/mqtt"})],fe,"path"),w([A({description:"The MQTT topic to subscribe to",required:true})],fe,"topic");var ge=class extends O{static commandName="generate-plugin";static description="Generate a new plugin in the specified path";static help=["Generate a new plugin in the specified path","Example: npx balda generate-plugin my-plugin -p src/plugins"];static pluginName;static pluginPath;static async handle(){let e=this.getPluginTemplate();this.pluginPath=f.join(this.pluginPath,`${this.pluginName}.ts`),await m.exists(f.join(process.cwd(),this.pluginPath))||await m.mkdir(f.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.pluginPath,new TextEncoder().encode(e)),this.logger.info(`Plugin ${this.name} created successfully at ${this.pluginPath}`);}static getPluginTemplate(){return `import { BasePlugin, Request, Response, NextFunction, ServerRouteMiddleware } from "balda";
83
+ }`}};y([x({description:"The path to the MQTT handler to generate, default is src/mqtt",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/mqtt"})],fe,"path"),y([q({description:"The MQTT topic to subscribe to",required:true})],fe,"topic");var ge=class extends P{static commandName="generate-plugin";static description="Generate a new plugin in the specified path";static help=["Generate a new plugin in the specified path","Example: npx balda generate-plugin my-plugin -p src/plugins"];static pluginName;static pluginPath;static async handle(){let e=this.getPluginTemplate();this.pluginPath=h.join(this.pluginPath,`${this.pluginName}.ts`),await u.exists(h.join(process.cwd(),this.pluginPath))||await u.mkdir(h.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.pluginPath,new TextEncoder().encode(e)),this.logger.info(`Plugin ${this.name} created successfully at ${this.pluginPath}`);}static getPluginTemplate(){return `import { BasePlugin, Request, Response, NextFunction, ServerRouteMiddleware } from "balda";
84
84
 
85
85
  export default class extends BasePlugin {
86
86
  async handle(): Promise<ServerRouteMiddleware> {
@@ -89,7 +89,7 @@ export default class extends BasePlugin {
89
89
  await next();
90
90
  };
91
91
  }
92
- }`}};w([A({description:"The name of the plugin to generate",required:true})],ge,"pluginName"),w([T({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],ge,"pluginPath");var te=class extends O{static commandName="generate-queue";static description="Generate a new queue in the specified path";static help=["Generate a new queue in the specified path","Example: npx balda generate-queue my-queue -p src/queues --provider bullmq"];static queueName;static path;static provider;static async handle(){let e=this.queueName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getQueueTemplate(!!e);this.path=f.join(this.path,`${Le(this.queueName)}.ts`),await m.exists(f.join(process.cwd(),this.path))||await m.mkdir(f.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { BaseQueue, queue } from "balda";
92
+ }`}};y([q({description:"The name of the plugin to generate",required:true})],ge,"pluginName"),y([x({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],ge,"pluginPath");var re=class extends P{static commandName="generate-queue";static description="Generate a new queue in the specified path";static help=["Generate a new queue in the specified path","Example: npx balda generate-queue my-queue -p src/queues --provider bullmq"];static queueName;static path;static provider;static async handle(){let e=this.queueName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getQueueTemplate(!!e);this.path=h.join(this.path,`${De(this.queueName)}.ts`),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { BaseQueue, queue } from "balda";
93
93
 
94
94
  export type Payload = {
95
95
  // Add your payload here
@@ -108,7 +108,24 @@ export default class extends BaseQueue {
108
108
  this.logger.info({ payload }, 'Payload received');
109
109
  return Promise.resolve();
110
110
  }
111
- }`}};w([A({description:"The name of the queue to generate",required:true})],te,"queueName"),w([T({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],te,"path"),w([T({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],te,"provider");var V=class extends O{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 devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await U();if(["npm","yarn","pnpm"].includes(e)){let a=await Ce(this.devDependencies);if(a.length&&(this.logger.info(`Found ${a.length} missing dev dependencies`),!await _(`${e} ${t} ${a.join(" ")} -${r}`,e,a,{stdio:"inherit"}))){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}a.length||this.logger.info("All dev dependencies are already installed");}if(this.mqtt&&["npm","yarn","pnpm"].includes(e)){let a=await Ce(["mqtt"]);a.length&&(await _(`${e} ${t} mqtt`,e,["mqtt"],{stdio:"inherit"},false)||(this.logger.info("MQTT installation cancelled by user. Skipping MQTT scaffolding."),this.mqtt=false)),a.length||this.logger.info("MQTT package is already installed");}if(this.cron&&["npm","yarn","pnpm"].includes(e)){let a=await Ce(["node-cron"]);a.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)),a.length||this.logger.info("node-cron package is already installed");}let o=this.typescript?"ts":"js",n=this.getServerTemplate(),i=this.getIndexTemplate();if(m.exists(this.srcPath)||await m.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${o} file...`),await m.writeFile(`${this.srcPath}/server.${o}`,new TextEncoder().encode(n)),this.logger.info(`Creating index.${o} file...`),await m.writeFile(`${this.srcPath}/index.${o}`,new TextEncoder().encode(i)),this.mqtt){let a=f.join(this.srcPath,"mqtt");await m.exists(a)||await m.mkdir(a,{recursive:true});let p=this.getMqttConfigTemplate();this.logger.info(`Creating mqtt/mqtt.config.${o} file...`),await m.writeFile(f.join(a,`mqtt.config.${o}`),new TextEncoder().encode(p));}if(this.cron){let a=f.join(this.srcPath,"cron");await m.exists(a)||await m.mkdir(a,{recursive:true});let p=this.getCronConfigTemplate();this.logger.info(`Creating cron/cron.config.${o} file...`),await m.writeFile(f.join(a,`cron.config.${o}`),new TextEncoder().encode(p));}this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda";
111
+ }`}};y([q({description:"The name of the queue to generate",required:true})],re,"queueName"),y([x({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],re,"path"),y([x({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],re,"provider");var $=class extends P{static commandName="generate-sdk";static description="Generate a TypeScript SDK from your server's OpenAPI specification";static help=["Generate a TypeScript SDK from your server's OpenAPI specification","This command imports your server instance, starts it if needed, downloads the OpenAPI spec, and generates an SDK","","Arguments:"," serverPath Path to the server instance file (default: test/server/instance.ts)","","Flags:"," -o, --output <path> Output directory for generated SDK (default: sdk)"," -s, --swagger-path <path> Swagger UI path on your server (default: /docs)"," -c, --client <type> HTTP client to use: axios or fetch (default: fetch)"," --unwrap-response-data Automatically unwrap response data property"," --single-http-client Generate single HTTP client instance"," --type-prefix <prefix> Add prefix to all generated types"," --type-suffix <suffix> Add suffix to all generated types"," --enum-names-as-values Use enum names as values"," --sort-types Sort types alphabetically","","Examples:"," npx balda generate-sdk"," npx balda generate-sdk src/server/index.ts -o ./client-sdk"," npx balda generate-sdk src/server.ts --client axios"," npx balda generate-sdk --unwrap-response-data --single-http-client"," npx balda generate-sdk --type-prefix Api --sort-types"];static serverPath;static outputPath;static swaggerPath;static httpClient;static unwrapResponseData;static singleHttpClient;static typePrefix;static typeSuffix;static enumNamesAsValues;static sortTypes;static async handle(){console.log(`
112
+ \u{1F680} Starting SDK generation...
113
+ `);let e="swagger-typescript-api",t=h.join(process.cwd(),"node_modules"),r=await u.exists(t),o=h.join(t,e);if(!(r?await u.exists(o):false)){console.log(`\u{1F4E6} ${e} not found. Installing as dev dependency...
114
+ `);let[b,j,L]=await I();if(!await N(`${b} ${j} ${e} ${L}`,b,[e],{stdio:"inherit"},true)){console.log(`\x1B[33m\u26A0\uFE0F SDK generation cancelled: swagger-typescript-api installation was skipped.\x1B[0m
115
+ `);return}console.log(`
116
+ \x1B[32m\u2705 ${e} installed successfully!\x1B[0m
117
+ `);}let i=h.resolve(process.cwd(),this.serverPath);if(!await u.exists(i)){console.error(`\x1B[31m\u274C Error: Server file not found at ${i}\x1B[0m
118
+ `);return}console.log(`\u{1F4C2} Loading server from: ${this.serverPath}`);let p;try{p=await import(`file://${i}`);}catch(b){console.error("\x1B[31m\u274C Error importing server module:\x1B[0m",b);return}let c=null,l=["server","serverBuilder","app","default","Server"];for(let b of l)if(p[b]){let j=p[b];if(j&&typeof j=="object"&&(j.constructor?.name==="Server"||typeof j.listen=="function"||typeof j.start=="function")){c=j,console.log(`\u2705 Found server instance in export: "${b}"
119
+ `);break}}if(!c){console.error(`\x1B[31m\u274C Error: No Server instance found in ${this.serverPath}\x1B[0m`),console.log(`\x1B[90mExpected exports: ${l.join(", ")}\x1B[0m
120
+ `);return}let d=false,f="",m=80,g="localhost";try{let b=c;if(b.options&&(m=b.options.port||80,g=b.options.host||"localhost"),f=`http://${g}:${m}`,console.log(`\u{1F310} Starting server on ${f}...`),typeof b.listen=="function")await b.listen(),d=!0,console.log(`\u2705 Server started successfully!
121
+ `);else throw new Error("Server instance does not have a listen() method")}catch(b){console.error("\x1B[31m\u274C Error starting server:\x1B[0m",b);return}let S=`${f}${this.swaggerPath}/json`;console.log(`\u{1F4E5} Downloading OpenAPI spec from: ${S}`);let E;try{let b=await globalThis.fetch(S);if(!b.ok)throw new Error(`Failed to fetch OpenAPI spec: ${b.status} ${b.statusText}`);E=await b.json(),console.log(`\u2705 OpenAPI spec downloaded successfully!
122
+ `);}catch(b){if(console.error("\x1B[31m\u274C Error downloading OpenAPI spec:\x1B[0m",b),d){let j=c;try{await j.close?.();}catch{}}return}let C=h.join(process.cwd(),".openapi-spec.json");try{await u.writeFile(C,new TextEncoder().encode(JSON.stringify(E,null,2)));}catch(b){if(console.error("\x1B[31m\u274C Error saving OpenAPI spec to file:\x1B[0m",b),d){let j=c;try{await j.close?.();}catch{}}return}let A=h.resolve(process.cwd(),this.outputPath);console.log(`\u{1F528} Generating SDK...
123
+ `);try{await u.exists(A)||await u.mkdir(A,{recursive:!0});let b=["npx swagger-typescript-api generate",`--path="${C}"`,`--output="${this.outputPath}"`,`--http-client ${this.httpClient}`,"--modular","--extract-request-params","--extract-request-body","--extract-response-body","--extract-response-error"];this.unwrapResponseData&&b.push("--unwrap-response-data"),this.singleHttpClient&&b.push("--single-http-client"),this.typePrefix&&b.push(`--type-prefix "${this.typePrefix}"`),this.typeSuffix&&b.push(`--type-suffix "${this.typeSuffix}"`),this.enumNamesAsValues&&b.push("--enum-names-as-values"),this.sortTypes&&b.push("--sort-types");let j=b.join(" ");execSync(j,{stdio:"inherit",cwd:process.cwd()}),console.log(`
124
+ \x1B[32m\u2705 SDK generated successfully!\x1B[0m`),console.log(`\x1B[32m\u{1F4C1} SDK location: ${A}\x1B[0m
125
+ `);}catch(b){console.error("\x1B[31m\u274C Error generating SDK:\x1B[0m",b);}finally{try{await u.unlink(C);}catch{}if(d){let b=c;try{console.log("\u{1F6D1} Stopping server..."),await b.close?.(),console.log(`\u2705 Server stopped.
126
+ `);}catch{console.log(`\x1B[33m\u26A0\uFE0F Could not stop server gracefully.\x1B[0m
127
+ `);}}}console.log(`\x1B[32m\u2728 SDK generation complete!\x1B[0m
128
+ `);}};y([q({description:"Path to the server instance file (should export a Server instance)",required:false,defaultValue:"test/server/instance.ts"})],$,"serverPath"),y([x({description:"Output directory for generated SDK",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"sdk"})],$,"outputPath"),y([x({description:"Swagger UI path on your server",type:"string",aliases:["s"],name:"swagger-path",required:false,defaultValue:"/docs"})],$,"swaggerPath"),y([x({description:"HTTP client to use (axios or fetch)",type:"string",aliases:["c"],name:"client",required:false,defaultValue:"fetch"})],$,"httpClient"),y([x({description:"Unwrap response data automatically",type:"boolean",name:"unwrap-response-data",required:false,defaultValue:false})],$,"unwrapResponseData"),y([x({description:"Generate single HTTP client instance",type:"boolean",name:"single-http-client",required:false,defaultValue:false})],$,"singleHttpClient"),y([x({description:"Add prefix to all generated types",type:"string",name:"type-prefix",required:false})],$,"typePrefix"),y([x({description:"Add suffix to all generated types",type:"string",name:"type-suffix",required:false})],$,"typeSuffix"),y([x({description:"Use enum names as values",type:"boolean",name:"enum-names-as-values",required:false,defaultValue:false})],$,"enumNamesAsValues"),y([x({description:"Sort types alphabetically",type:"boolean",name:"sort-types",required:false,defaultValue:false})],$,"sortTypes");var J=class extends P{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 devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await I();if(["npm","yarn","pnpm"].includes(e)){let a=await Oe(this.devDependencies);if(a.length&&(this.logger.info(`Found ${a.length} missing dev dependencies`),!await N(`${e} ${t} ${a.join(" ")} -${r}`,e,a,{stdio:"inherit"}))){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}a.length||this.logger.info("All dev dependencies are already installed");}if(this.mqtt&&["npm","yarn","pnpm"].includes(e)){let a=await Oe(["mqtt"]);a.length&&(await N(`${e} ${t} mqtt`,e,["mqtt"],{stdio:"inherit"},false)||(this.logger.info("MQTT installation cancelled by user. Skipping MQTT scaffolding."),this.mqtt=false)),a.length||this.logger.info("MQTT package is already installed");}if(this.cron&&["npm","yarn","pnpm"].includes(e)){let a=await Oe(["node-cron"]);a.length>0&&(await N(`${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)),a.length||this.logger.info("node-cron package is already installed");}let o=this.typescript?"ts":"js",n=this.getServerTemplate(),i=this.getIndexTemplate();if(u.exists(this.srcPath)||await u.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${o} file...`),await u.writeFile(`${this.srcPath}/server.${o}`,new TextEncoder().encode(n)),this.logger.info(`Creating index.${o} file...`),await u.writeFile(`${this.srcPath}/index.${o}`,new TextEncoder().encode(i)),this.mqtt){let a=h.join(this.srcPath,"mqtt");await u.exists(a)||await u.mkdir(a,{recursive:true});let p=this.getMqttConfigTemplate();this.logger.info(`Creating mqtt/mqtt.config.${o} file...`),await u.writeFile(h.join(a,`mqtt.config.${o}`),new TextEncoder().encode(p));}if(this.cron){let a=h.join(this.srcPath,"cron");await u.exists(a)||await u.mkdir(a,{recursive:true});let p=this.getCronConfigTemplate();this.logger.info(`Creating cron/cron.config.${o} file...`),await u.writeFile(h.join(a,`cron.config.${o}`),new TextEncoder().encode(p));}this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda";
112
129
 
113
130
  const serverInstance = new Server({
114
131
  port: 80,
@@ -148,7 +165,7 @@ server.listen(({ url }) => {
148
165
  // This file is imported to set up Cron jobs
149
166
  // Add your cron jobs in separate files within this directory
150
167
  // Use: npx balda generate-cron <job-name> to create new cron jobs
151
- `}};w([T.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],V,"srcPath"),w([T.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],V,"typescript"),w([T.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],V,"mqtt"),w([T.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],V,"cron");var ye=class extends O{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 U();if(["npm","yarn","pnpm"].includes(e)){let i=this.queueDependencies[this.queueType],a=await Ce(i);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for ${this.queueType}`),!await _(`${e} ${t} ${a.join(" ")}`,e,a,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Queue initialization aborted.");return}a.length===0&&this.logger.info(`All ${this.queueType} dependencies are already installed`);}let r=this.getConfigTemplate(),o=`${this.queueType}.config.ts`,n=f.join(this.outputPath,o);await m.exists(this.outputPath)||await m.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${o} file at ${this.outputPath}...`),await m.writeFile(n,new TextEncoder().encode(r)),this.logger.info(`Queue configuration initialized successfully at ${n}`),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";
168
+ `}};y([x.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],J,"srcPath"),y([x.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],J,"typescript"),y([x.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],J,"mqtt"),y([x.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],J,"cron");var ye=class extends P{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 I();if(["npm","yarn","pnpm"].includes(e)){let i=this.queueDependencies[this.queueType],a=await Oe(i);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for ${this.queueType}`),!await N(`${e} ${t} ${a.join(" ")}`,e,a,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Queue initialization aborted.");return}a.length===0&&this.logger.info(`All ${this.queueType} dependencies are already installed`);}let r=this.getConfigTemplate(),o=`${this.queueType}.config.ts`,n=h.join(this.outputPath,o);await u.exists(this.outputPath)||await u.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${o} file at ${this.outputPath}...`),await u.writeFile(n,new TextEncoder().encode(r)),this.logger.info(`Queue configuration initialized successfully at ${n}`),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";
152
169
 
153
170
  defineBullMQConfiguration({
154
171
  connection: {
@@ -200,22 +217,22 @@ definePGBossConfiguration({
200
217
  console.error("PG-Boss error:", error);
201
218
  },
202
219
  });
203
- `}};w([T.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],ye,"queueType"),w([T.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],ye,"outputPath");var He=class extends O{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=Pe.getBuiltInCommands(),t=Pe.getUserDefinedCommands();if(console.log(`
220
+ `}};y([x.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],ye,"queueType"),y([x.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],ye,"outputPath");var Ne=class extends P{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=je.getBuiltInCommands(),t=je.getUserDefinedCommands();if(console.log(`
204
221
  \u2728 Available Balda Commands:
205
222
  `),t.length>0){console.log(`\x1B[1;33mUser Commands:\x1B[0m
206
223
  `);let r=this.groupByCategory(t);this.displayCategorizedCommands(r);}if(e.length>0){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
207
224
  `);let r=Math.max(...e.map(o=>o.commandName.length));for(let o of e){let n=o.commandName.padEnd(r+2),i=o.description||"No description available",a="";o.options?.deprecated&&(a=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${n}\x1B[0m ${i}${a}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
208
- `);}static groupByCategory(e){let t=new Map;for(let r of e){let o=r.options?.category||"other";t.has(o)||t.set(o,[]),t.get(o).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let o=e.get(r).filter(p=>p&&p.commandName);if(o.length===0)continue;let i={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${i}${r.toUpperCase()}:\x1B[0m`);let a=Math.max(...o.map(p=>p.commandName.length));for(let p of o){let c=p.commandName.padEnd(a+2),d=p.description||"No description available",l="";p.options?.deprecated&&(l=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${c}\x1B[0m ${d}${l}`);}console.log("");}}};H();var ve=class extends O{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=S.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:M.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:M.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!Ke.existsSync("node_modules/.bin/tsx")){let[r,o,n]=await U();if(!await _(`${r} ${o} tsx ${n}`,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()});}};w([A({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],ve,"entry"),w([T.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],ve,"denoImportMap");var we=class extends O{static commandName="setup-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
209
- `);return}this.outputPath||await m.mkdir(f.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
225
+ `);}static groupByCategory(e){let t=new Map;for(let r of e){let o=r.options?.category||"other";t.has(o)||t.set(o,[]),t.get(o).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let o=e.get(r).filter(p=>p&&p.commandName);if(o.length===0)continue;let i={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${i}${r.toUpperCase()}:\x1B[0m`);let a=Math.max(...o.map(p=>p.commandName.length));for(let p of o){let c=p.commandName.padEnd(a+2),l=p.description||"No description available",d="";p.options?.deprecated&&(d=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${c}\x1B[0m ${l}${d}`);}console.log("");}}};F();var ve=class extends P{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:k.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:k.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!Ve.existsSync("node_modules/.bin/tsx")){let[r,o,n]=await I();if(!await N(`${r} ${o} tsx ${n}`,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()});}};y([q({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],ve,"entry"),y([x.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],ve,"denoImportMap");var we=class extends P{static commandName="setup-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
226
+ `);return}this.outputPath||await u.mkdir(h.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
210
227
  `);return}console.log(`
211
228
  \u{1F680} Setting up ${this.storageType.toUpperCase()} storage provider...
212
229
  `);let t=this.getDependencies(this.storageType);if(t.length===0&&console.log(`\x1B[32m\u2705 ${this.storageType.toUpperCase()} storage doesn't require additional dependencies.\x1B[0m
213
230
  `),t.length){let r=await this.checkMissingDependencies(t);if(r.length===0&&console.log(`\x1B[32m\u2705 All required dependencies are already installed.\x1B[0m
214
- `),r.length){let[o,n]=await U(),i=`${o} ${n} ${r.join(" ")}`;if(!await _(i,o,r,{stdio:"inherit"},false)){console.log(`\x1B[33m\u26A0\uFE0F Dependency installation skipped by user.\x1B[0m
231
+ `),r.length){let[o,n]=await I(),i=`${o} ${n} ${r.join(" ")}`;if(!await N(i,o,r,{stdio:"inherit"},false)){console.log(`\x1B[33m\u26A0\uFE0F Dependency installation skipped by user.\x1B[0m
215
232
  `);return}console.log(`
216
233
  \x1B[32m\u2705 Dependencies installed successfully!\x1B[0m
217
234
  `);}}await this.createStorageSetup(this.storageType,this.outputPath),console.log(`\x1B[32m\u2728 ${this.storageType.toUpperCase()} storage setup complete!\x1B[0m
218
- `);}static getDependencies(e){return {s3:["@aws-sdk/client-s3","@aws-sdk/s3-request-presigner","@aws-sdk/cloudfront-signer"],azure:["@azure/storage-blob"],local:[]}[e]||[]}static async checkMissingDependencies(e){let t=f.join(process.cwd(),"package.json");if(!await m.exists(t))return e;let o=f.join(process.cwd(),"node_modules");if(!await m.exists(o))return e;let i=[];for(let a of e){let p=f.join(o,a);await m.exists(p)||i.push(a);}return i}static async createStorageSetup(e,t){let r=f.join(process.cwd(),t);await m.exists(r)||await m.mkdir(r,{recursive:true});let n=f.join(r,"storage.ts");if(await m.exists(n)){console.log(`\x1B[33m\u26A0\uFE0F Configuration file already exists: ${n}\x1B[0m`);return}let a=this.getConfigTemplate(e);await m.writeFile(n,new TextEncoder().encode(a)),console.log(`\x1B[32m\u2705 Created configuration file: ${n}\x1B[0m`);}static getConfigTemplate(e){return {s3:`import { Storage, S3StorageProvider } from "balda";
235
+ `);}static getDependencies(e){return {s3:["@aws-sdk/client-s3","@aws-sdk/s3-request-presigner","@aws-sdk/cloudfront-signer"],azure:["@azure/storage-blob"],local:[]}[e]||[]}static async checkMissingDependencies(e){let t=h.join(process.cwd(),"package.json");if(!await u.exists(t))return e;let o=h.join(process.cwd(),"node_modules");if(!await u.exists(o))return e;let i=[];for(let a of e){let p=h.join(o,a);await u.exists(p)||i.push(a);}return i}static async createStorageSetup(e,t){let r=h.join(process.cwd(),t);await u.exists(r)||await u.mkdir(r,{recursive:true});let n=h.join(r,"storage.ts");if(await u.exists(n)){console.log(`\x1B[33m\u26A0\uFE0F Configuration file already exists: ${n}\x1B[0m`);return}let a=this.getConfigTemplate(e);await u.writeFile(n,new TextEncoder().encode(a)),console.log(`\x1B[32m\u2705 Created configuration file: ${n}\x1B[0m`);}static getConfigTemplate(e){return {s3:`import { Storage, S3StorageProvider } from "balda";
219
236
 
220
237
  /**
221
238
  * S3 Storage Configuration
@@ -295,16 +312,16 @@ export const storage = new Storage(
295
312
  defaultProvider: "local",
296
313
  },
297
314
  );
298
- `}[e]||""}};w([T({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],we,"storageType"),w([T({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],we,"outputPath");var Zr=[ge,Oe,me,fe,te,ue,he,V,ye,He,$,ve,we],bt=class s{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=y;constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new s}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}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){s.logger.info(`Loading commands from ${e}`);let t=await glob(e,{absolute:true,cwd:M.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",import.meta.url);}catch{s.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1);}for(let r of t){let o=await import(r).then(n=>n.default?n.default:n).catch(n=>(s.logger.error(`Error loading command ${r}: ${n}`),null));o&&this.commands.set(o.commandName,o);}for(let r of Zr)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Pe=bt.getInstance();var Ze=class extends Request{};var Ve=new WeakMap,Q=class s extends Ze{static fromRequest(e){return new s(e.url,{method:e.method,body:e.body,headers:e.headers})}static compileAndValidate(e,t,r){let o,n;if(Z.isZodSchema(e)){let c=e,d=Ve.get(c);d||(d=Symbol("zod_schema"),Ve.set(c,d));let l=q.get(d);if(l)return D(l,t,r);o=c.toJSONSchema();let h=N.ajv.compile(o);return q.set(d,h),D(h,t,r)}let i=e;if(typeof i=="object"&&i!==null){let c=Ve.get(i);c||(c=Symbol("json_schema"),Ve.set(i,c));let d=q.get(c);if(d)return D(d,t,r);let l=N.ajv.compile(i);return q.set(c,l),D(l,t,r)}n=JSON.stringify(i);let a=q.get(n);if(a)return D(a,t,r);let p=N.ajv.compile(i);return q.set(n,p),D(p,t,r)}static enrichRequest(e){return e.validate=(t,r=false)=>s.compileAndValidate(t,e.body||{},r),e.validateQuery=(t,r=false)=>s.compileAndValidate(t,e.query||{},r),e.validateAll=(t,r=false)=>s.compileAndValidate(t,{...e.body?{body:e.body}:{},...e.query?{query:e.query}:{}},r),e.file=t=>e.files.find(r=>r.formName===t)??null,e.files=[],e.saveSession=async()=>{},e.destroySession=async()=>{},e.session={},e.cookies={},e.cookie=t=>e.cookies[t],e}ctx={};file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};query={};get id(){return this._id||(this._id=Y.randomUUID()),this._id}set id(e){this._id=e;}body;validate(e,t=false){return s.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return s.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return s.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}};H();var je=class{get(e){switch(S.type){case "node":case "bun":case "deno":return process.env[e]??"";default:throw new Error(`Unsupported runtime: ${S.type}`)}}getEnvironment(){switch(S.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var Vr=new je,P=s=>{let e=Vr.get("NODE_ENV")!=="production";return {code:s.name||"INTERNAL_ERROR",message:s.message,...e&&{stack:s.stack,cause:s.cause}}};var Ee=class extends x{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var k=class extends x{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};H();var St=class{file(e,t){switch(S.type){case "bun":case "node":return Ke.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},We=new St;var Ut=new Map([[".html","text/html"],[".htm","text/html"],[".css","text/css"],[".js","application/javascript"],[".mjs","application/javascript"],[".cjs","application/javascript"],[".ts","application/typescript"],[".jsx","text/jsx"],[".tsx","text/tsx"],[".json","application/json"],[".xml","application/xml"],[".yaml","application/yaml"],[".yml","application/yaml"],[".csv","text/csv"],[".txt","text/plain"],[".md","text/markdown"],[".markdown","text/markdown"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".ico","image/x-icon"],[".webp","image/webp"],[".avif","image/avif"],[".bmp","image/bmp"],[".tiff","image/tiff"],[".tif","image/tiff"],[".heic","image/heic"],[".heif","image/heif"],[".mp4","video/mp4"],[".webm","video/webm"],[".avi","video/x-msvideo"],[".mov","video/quicktime"],[".mkv","video/x-matroska"],[".wmv","video/x-ms-wmv"],[".flv","video/x-flv"],[".m4v","video/x-m4v"],[".mpeg","video/mpeg"],[".mpg","video/mpeg"],[".3gp","video/3gpp"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".flac","audio/flac"],[".aac","audio/aac"],[".m4a","audio/mp4"],[".wma","audio/x-ms-wma"],[".opus","audio/opus"],[".mid","audio/midi"],[".midi","audio/midi"],[".woff","font/woff"],[".woff2","font/woff2"],[".ttf","font/ttf"],[".otf","font/otf"],[".eot","application/vnd.ms-fontobject"],[".pdf","application/pdf"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".ppt","application/vnd.ms-powerpoint"],[".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],[".odt","application/vnd.oasis.opendocument.text"],[".ods","application/vnd.oasis.opendocument.spreadsheet"],[".odp","application/vnd.oasis.opendocument.presentation"],[".rtf","application/rtf"],[".epub","application/epub+zip"],[".zip","application/zip"],[".tar","application/x-tar"],[".gz","application/gzip"],[".gzip","application/gzip"],[".bz2","application/x-bzip2"],[".xz","application/x-xz"],[".rar","application/vnd.rar"],[".7z","application/x-7z-compressed"],[".wasm","application/wasm"],[".map","application/json"],[".webmanifest","application/manifest+json"],[".ics","text/calendar"],[".vcf","text/vcard"],[".sql","application/sql"],[".sh","application/x-sh"],[".bat","application/x-msdos-program"],[".exe","application/x-msdownload"],[".dll","application/x-msdownload"],[".bin","application/octet-stream"],[".iso","application/x-iso9660-image"],[".dmg","application/x-apple-diskimage"],[".apk","application/vnd.android.package-archive"],[".jar","application/java-archive"],[".swf","application/x-shockwave-flash"]]);var Qt=(s,e)=>{let{source:t,path:r}=s,o=r;return o.startsWith("/")||(o="/"+o),o!=="/"&&o.endsWith("/")&&(o=o.slice(0,-1)),C.addOrUpdate("GET",`${o}/*`,[],async(n,i)=>Jr(n,i,t),{service:"StaticFiles",...e}),async(n,i,a)=>a()};async function Jr(s,e,t){if(s.method!=="GET"&&s.method!=="HEAD")return e.status(405).json({...P(new Ee(s.url,s.method))});let r=s.params["*"]||"",o=f.join(t,r),n=f.resolve(M.getCwd(),o),i=f.resolve(M.getCwd(),t);if(!n.startsWith(i))return e.notFound({...P(new k(s.url,s.method))});try{if(!(await m.stat(n)).isFile)return e.notFound({...P(new k(s.url,s.method))})}catch(c){if(c.code==="ENOENT")return e.notFound({...P(new k(s.url,s.method))});throw c}let a=xt(f.extName(n));e.setHeader("Content-Type",a);let p=We.file(n);e.raw(p);}function xt(s){return Ut.get(s)||"application/octet-stream"}var W=class{responseStatus;headers;body;constructor(e=200){this.responseStatus=e,this.headers={};}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.raw(e);if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="symbol")return this.text(e.toString());this.body=e;}raw(e){this.body=e;}text(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/plain"};}json(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/json"};}html(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/html"};}xml(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/xml"};}download(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/octet-stream"};}file(e,t){let r=f.extName(e),o=xt(r);this.body=We.file(e,t),this.headers={...this.headers,"Content-Type":o};}ok(e){this.status(200).send(e);}created(e){this.status(201).send(e);}accepted(e){this.status(202).send(e);}noContent(){this.status(204).send("");}partialContent(e){this.status(206).send(e);}multipleChoices(e){this.status(300).setHeader("Location",e);}redirect(e){this.status(302).setHeader("Location",e);}movedPermanently(e){this.status(301).setHeader("Location",e);}found(e){this.status(302).setHeader("Location",e);}seeOther(e){this.status(303).setHeader("Location",e);}notModified(){this.status(304).send("");}temporaryRedirect(e){this.status(307).setHeader("Location",e);}permanentRedirect(e){this.status(308).setHeader("Location",e);}badRequest(e){this.status(400).send(e);}unauthorized(e){this.status(401).send(e);}forbidden(e){this.status(403).send(e);}notFound(e){this.status(404).send(e);}methodNotAllowed(e){this.status(405).send(e);}notAcceptable(e){this.status(406).send(e);}conflict(e){this.status(409).send(e);}gone(e){this.status(410).send(e);}payloadTooLarge(e){this.status(413).send(e);}unsupportedMediaType(e){this.status(415).send(e);}unprocessableEntity(e){this.status(422).send(e);}tooManyRequests(e){this.status(429).send(e);}internalServerError(e){this.status(500).send(e);}notImplemented(e){this.status(501).send(e);}badGateway(e){this.status(502).send(e);}serviceUnavailable(e){this.status(503).send(e);}gatewayTimeout(e){this.status(504).send(e);}httpVersionNotSupported(e){this.status(505).send(e);}stream(e,t){if(this.headers={...this.headers,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...t?.customHeaders},e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let o of e)r.enqueue(new TextEncoder().encode(o));r.close();}});}getBody(){return this.body}};var z=class{schemaOptions;yogaOptions;isEnabled;constructor(e){let t=this.initializeConfiguration(e);this.schemaOptions=t.schemaOptions,this.yogaOptions=t.yogaOptions,this.isEnabled=t.isEnabled;}getSchema(e){return e(this.schemaOptions)}getYogaOptions(){return this.yogaOptions}addTypeDef(e){if(typeof e=="function"){this.addTypeDef(e());return}if(Array.isArray(e)){this.addTypeDefArray(e);return}this.ensureTypeDefsArray(),this.schemaOptions.typeDefs.push(e);}addResolver(e,t){if(typeof e=="string"&&t){this.addResolverByType(e,t);return}this.addFullResolver(e);}initializeConfiguration(e){return e?this.createEnabledConfiguration(e):this.createDisabledConfiguration()}createDisabledConfiguration(){return {schemaOptions:{typeDefs:"",resolvers:{}},yogaOptions:{},isEnabled:false}}createEnabledConfiguration(e){return {schemaOptions:this.resolveSchemaOptions(e.schema),yogaOptions:this.resolveYogaOptions(e.yogaOptions),isEnabled:true}}resolveSchemaOptions(e){return e!==void 0?e:{typeDefs:"",resolvers:{}}}resolveYogaOptions(e){return e!==void 0?e:{}}addResolverByType(e,t){if(this.ensureResolversInitialized(),Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers.push({[e]:t});return}this.mergeResolverIntoObject(e,t);}ensureResolversInitialized(){!this.schemaOptions.resolvers&&(this.schemaOptions.resolvers={});}mergeResolverIntoObject(e,t){let r=this.schemaOptions.resolvers,o=r[e];if(o&&typeof o=="object"){r[e]={...o,...t};return}r[e]=t;}addFullResolver(e){if(this.ensureResolversInitialized(),Array.isArray(e)){this.addResolverArray(e);return}if(typeof e=="object"&&e!==null){this.addResolverObject(e);return}this.schemaOptions.resolvers=e;}addResolverArray(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,...e];return}this.schemaOptions.resolvers=[this.schemaOptions.resolvers,...e];}addResolverObject(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,e];return}this.schemaOptions.resolvers={...this.schemaOptions.resolvers,...e};}addTypeDefArray(e){for(let t of e)this.addTypeDef(t);}ensureTypeDefsArray(){if(Array.isArray(this.schemaOptions.typeDefs))return;if(this.schemaOptions.typeDefs!==void 0){this.schemaOptions.typeDefs=[this.schemaOptions.typeDefs];return}this.schemaOptions.typeDefs=[];}};var Me=class{constructor(e){this.response=e;}body(){return this.response.getBody()}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let o in t){let n=r===""?o:`${r}.${o}`,i=e[o],a=t[o];if(!(o in e))throw new Error(`Expected ${r} to have key ${o}, but it was not found`);if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} to be ${a}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${o.length}`);for(let i of n){let a=r==="body"?i:`${r}.${i}`;this.assertDeepEqual(e[i],t[i],a);}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`,i=e[o],a=t[o];if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} to be ${a}, but got ${i}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`;this.assertDeepEqual(e[o],t[o],n);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var re=async(s,e,t,r=new W)=>{let o=0;if(!s.length)return await e(t,r),r;let n=async()=>{if(o++,o>=s.length){await e(t,r);return}let a=s[o];await a(t,r,n);},i=s[0];return await i(t,r,n),r},se=s=>s?["post","put","patch","delete"].includes(s.toLowerCase()):true,Ae=s=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(n=>setTimeout(n,10));},o=async()=>{try{let{createYoga:n,createSchema:i}=await import('graphql-yoga'),a=s.getSchema(i),p=s.getYogaOptions();return n({graphqlEndpoint:"/graphql",...p,schema:a})}catch(n){throw n instanceof Error&&(n.message.includes("Cannot find module")||n.message.includes("Cannot find package"))?new Error("GraphQL is enabled but 'graphql-yoga' is not installed. Install it with: npm install graphql graphql-yoga"):n}};return async()=>{if(!s.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=o(),await e}catch(p){throw e=null,p}finally{t=false;}}};var Je=class{server;constructor(e){this.server=e;}async request(e,t,r={}){let{headers:o={},query:n={},cookies:i={},ip:a}=r;this.validateOptions(r);let p=C.find(e.toUpperCase(),t);if(!p){let u=new W(404);return u.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new Me(u)}let c=r.body,d="application/json";if(c&&typeof c=="object"&&!(c instanceof Uint8Array)&&!(c instanceof ArrayBuffer)&&(c=JSON.stringify(c)),r.formData){let u=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;d=`multipart/form-data; boundary=${u}`,c=await this.formDataToMultipart(r.formData,u);}r.urlencoded&&(d="application/x-www-form-urlencoded",c=new URLSearchParams(r.urlencoded).toString());let l=new URL(`http://${this.server.host}:${this.server.port}${t}`);l.search=new URLSearchParams(n).toString();let h=new Q(l.toString(),{method:e.toUpperCase(),body:se(e)?c:void 0,headers:{"content-type":d,...o}});h.query={...Object.fromEntries(l.searchParams.entries()),...n},h.params=p.params,h.cookies=i,h.ip=a;try{let u=await re(p.middleware,p.handler,h);return new Me(u)}catch(u){y.error({error:u},`Error processing mock request ${e} ${t}:`);let g=new W(500);return g.json({error:"Internal server error",message:u instanceof Error?u.message:String(u)}),new Me(g)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,o=[];for(let[p,c]of e.entries()){o.push(r.encode(`--${t}\r
299
- `));let d=`Content-Disposition: form-data; name="${p}"`,l="";if(c instanceof File&&(d+=`; filename="${c.name}"`,l=`Content-Type: ${c.type||"application/octet-stream"}\r
300
- `),o.push(r.encode(`${d}\r
301
- ${l}\r
302
- `)),c instanceof File){let h=await c.arrayBuffer();o.push(new Uint8Array(h)),o.push(r.encode(`\r
315
+ `}[e]||""}};y([x({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],we,"storageType"),y([x({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],we,"outputPath");var Wr=[ge,Pe,me,fe,re,ue,he,$,J,ye,Ne,D,ve,we],St=class s{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=v;constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new s}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}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){s.logger.info(`Loading commands from ${e}`);let t=await glob(e,{absolute:true,cwd:k.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",import.meta.url);}catch{s.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1);}for(let r of t){let o=await import(r).then(n=>n.default?n.default:n).catch(n=>(s.logger.error(`Error loading command ${r}: ${n}`),null));o&&this.commands.set(o.commandName,o);}for(let r of Wr)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},je=St.getInstance();var Ze=class extends Request{};var We=new WeakMap,G=class s extends Ze{static fromRequest(e){return new s(e.url,{method:e.method,body:e.body,headers:e.headers})}static compileAndValidate(e,t,r){let o,n;if(W.isZodSchema(e)){let c=e,l=We.get(c);l||(l=Symbol("zod_schema"),We.set(c,l));let d=H.get(l);if(d)return Q(d,t,r);o=c.toJSONSchema();let f=B.ajv.compile(o);return H.set(l,f),Q(f,t,r)}let i=e;if(typeof i=="object"&&i!==null){let c=We.get(i);c||(c=Symbol("json_schema"),We.set(i,c));let l=H.get(c);if(l)return Q(l,t,r);let d=B.ajv.compile(i);return H.set(c,d),Q(d,t,r)}n=JSON.stringify(i);let a=H.get(n);if(a)return Q(a,t,r);let p=B.ajv.compile(i);return H.set(n,p),Q(p,t,r)}static enrichRequest(e){return e.validate=(t,r=false)=>s.compileAndValidate(t,e.body||{},r),e.validateQuery=(t,r=false)=>s.compileAndValidate(t,e.query||{},r),e.validateAll=(t,r=false)=>s.compileAndValidate(t,{...e.body?{body:e.body}:{},...e.query?{query:e.query}:{}},r),e.file=t=>e.files.find(r=>r.formName===t)??null,e.files=[],e.saveSession=async()=>{},e.destroySession=async()=>{},e.session={},e.cookies={},e.cookie=t=>e.cookies[t],e}ctx={};file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};query={};get id(){return this._id||(this._id=X.randomUUID()),this._id}set id(e){this._id=e;}body;validate(e,t=false){return s.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return s.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return s.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}};F();var Ee=class{get(e){switch(R.type){case "node":case "bun":case "deno":return process.env[e]??"";default:throw new Error(`Unsupported runtime: ${R.type}`)}}getEnvironment(){switch(R.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var Jr=new Ee,M=s=>{let e=Jr.get("NODE_ENV")!=="production";return {code:s.name||"INTERNAL_ERROR",message:s.message,...e&&{stack:s.stack,cause:s.cause}}};var Ae=class extends T{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var _=class extends T{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};F();var xt=class{file(e,t){switch(R.type){case "bun":case "node":return Ve.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},Je=new xt;var Qt=new Map([[".html","text/html"],[".htm","text/html"],[".css","text/css"],[".js","application/javascript"],[".mjs","application/javascript"],[".cjs","application/javascript"],[".ts","application/typescript"],[".jsx","text/jsx"],[".tsx","text/tsx"],[".json","application/json"],[".xml","application/xml"],[".yaml","application/yaml"],[".yml","application/yaml"],[".csv","text/csv"],[".txt","text/plain"],[".md","text/markdown"],[".markdown","text/markdown"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".ico","image/x-icon"],[".webp","image/webp"],[".avif","image/avif"],[".bmp","image/bmp"],[".tiff","image/tiff"],[".tif","image/tiff"],[".heic","image/heic"],[".heif","image/heif"],[".mp4","video/mp4"],[".webm","video/webm"],[".avi","video/x-msvideo"],[".mov","video/quicktime"],[".mkv","video/x-matroska"],[".wmv","video/x-ms-wmv"],[".flv","video/x-flv"],[".m4v","video/x-m4v"],[".mpeg","video/mpeg"],[".mpg","video/mpeg"],[".3gp","video/3gpp"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".flac","audio/flac"],[".aac","audio/aac"],[".m4a","audio/mp4"],[".wma","audio/x-ms-wma"],[".opus","audio/opus"],[".mid","audio/midi"],[".midi","audio/midi"],[".woff","font/woff"],[".woff2","font/woff2"],[".ttf","font/ttf"],[".otf","font/otf"],[".eot","application/vnd.ms-fontobject"],[".pdf","application/pdf"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".ppt","application/vnd.ms-powerpoint"],[".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],[".odt","application/vnd.oasis.opendocument.text"],[".ods","application/vnd.oasis.opendocument.spreadsheet"],[".odp","application/vnd.oasis.opendocument.presentation"],[".rtf","application/rtf"],[".epub","application/epub+zip"],[".zip","application/zip"],[".tar","application/x-tar"],[".gz","application/gzip"],[".gzip","application/gzip"],[".bz2","application/x-bzip2"],[".xz","application/x-xz"],[".rar","application/vnd.rar"],[".7z","application/x-7z-compressed"],[".wasm","application/wasm"],[".map","application/json"],[".webmanifest","application/manifest+json"],[".ics","text/calendar"],[".vcf","text/vcard"],[".sql","application/sql"],[".sh","application/x-sh"],[".bat","application/x-msdos-program"],[".exe","application/x-msdownload"],[".dll","application/x-msdownload"],[".bin","application/octet-stream"],[".iso","application/x-iso9660-image"],[".dmg","application/x-apple-diskimage"],[".apk","application/vnd.android.package-archive"],[".jar","application/java-archive"],[".swf","application/x-shockwave-flash"]]);var zt=(s,e)=>{let{source:t,path:r}=s,o=r;return o.startsWith("/")||(o="/"+o),o!=="/"&&o.endsWith("/")&&(o=o.slice(0,-1)),O.addOrUpdate("GET",`${o}/*`,[],async(n,i)=>Xr(n,i,t),{service:"StaticFiles",...e}),async(n,i,a)=>a()};async function Xr(s,e,t){if(s.method!=="GET"&&s.method!=="HEAD")return e.status(405).json({...M(new Ae(s.url,s.method))});let r=s.params["*"]||"",o=h.join(t,r),n=h.resolve(k.getCwd(),o),i=h.resolve(k.getCwd(),t);if(!n.startsWith(i))return e.notFound({...M(new _(s.url,s.method))});try{if(!(await u.stat(n)).isFile)return e.notFound({...M(new _(s.url,s.method))})}catch(c){if(c.code==="ENOENT")return e.notFound({...M(new _(s.url,s.method))});throw c}let a=Rt(h.extName(n));e.setHeader("Content-Type",a);let p=Je.file(n);e.raw(p);}function Rt(s){return Qt.get(s)||"application/octet-stream"}var Y=class{responseStatus;headers;body;constructor(e=200){this.responseStatus=e,this.headers={};}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.raw(e);if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="symbol")return this.text(e.toString());this.body=e;}raw(e){this.body=e;}text(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/plain"};}json(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/json"};}html(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/html"};}xml(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/xml"};}download(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/octet-stream"};}file(e,t){let r=h.extName(e),o=Rt(r);this.body=Je.file(e,t),this.headers={...this.headers,"Content-Type":o};}ok(e){this.status(200).send(e);}created(e){this.status(201).send(e);}accepted(e){this.status(202).send(e);}noContent(){this.status(204).send("");}partialContent(e){this.status(206).send(e);}multipleChoices(e){this.status(300).setHeader("Location",e);}redirect(e){this.status(302).setHeader("Location",e);}movedPermanently(e){this.status(301).setHeader("Location",e);}found(e){this.status(302).setHeader("Location",e);}seeOther(e){this.status(303).setHeader("Location",e);}notModified(){this.status(304).send("");}temporaryRedirect(e){this.status(307).setHeader("Location",e);}permanentRedirect(e){this.status(308).setHeader("Location",e);}badRequest(e){this.status(400).send(e);}unauthorized(e){this.status(401).send(e);}forbidden(e){this.status(403).send(e);}notFound(e){this.status(404).send(e);}methodNotAllowed(e){this.status(405).send(e);}notAcceptable(e){this.status(406).send(e);}conflict(e){this.status(409).send(e);}gone(e){this.status(410).send(e);}payloadTooLarge(e){this.status(413).send(e);}unsupportedMediaType(e){this.status(415).send(e);}unprocessableEntity(e){this.status(422).send(e);}tooManyRequests(e){this.status(429).send(e);}internalServerError(e){this.status(500).send(e);}notImplemented(e){this.status(501).send(e);}badGateway(e){this.status(502).send(e);}serviceUnavailable(e){this.status(503).send(e);}gatewayTimeout(e){this.status(504).send(e);}httpVersionNotSupported(e){this.status(505).send(e);}stream(e,t){if(this.headers={...this.headers,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...t?.customHeaders},e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let o of e)r.enqueue(new TextEncoder().encode(o));r.close();}});}getBody(){return this.body}};var K=class{schemaOptions;yogaOptions;isEnabled;constructor(e){let t=this.initializeConfiguration(e);this.schemaOptions=t.schemaOptions,this.yogaOptions=t.yogaOptions,this.isEnabled=t.isEnabled;}getSchema(e){return e(this.schemaOptions)}getYogaOptions(){return this.yogaOptions}addTypeDef(e){if(typeof e=="function"){this.addTypeDef(e());return}if(Array.isArray(e)){this.addTypeDefArray(e);return}this.ensureTypeDefsArray(),this.schemaOptions.typeDefs.push(e);}addResolver(e,t){if(typeof e=="string"&&t){this.addResolverByType(e,t);return}this.addFullResolver(e);}initializeConfiguration(e){return e?this.createEnabledConfiguration(e):this.createDisabledConfiguration()}createDisabledConfiguration(){return {schemaOptions:{typeDefs:"",resolvers:{}},yogaOptions:{},isEnabled:false}}createEnabledConfiguration(e){return {schemaOptions:this.resolveSchemaOptions(e.schema),yogaOptions:this.resolveYogaOptions(e.yogaOptions),isEnabled:true}}resolveSchemaOptions(e){return e!==void 0?e:{typeDefs:"",resolvers:{}}}resolveYogaOptions(e){return e!==void 0?e:{}}addResolverByType(e,t){if(this.ensureResolversInitialized(),Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers.push({[e]:t});return}this.mergeResolverIntoObject(e,t);}ensureResolversInitialized(){!this.schemaOptions.resolvers&&(this.schemaOptions.resolvers={});}mergeResolverIntoObject(e,t){let r=this.schemaOptions.resolvers,o=r[e];if(o&&typeof o=="object"){r[e]={...o,...t};return}r[e]=t;}addFullResolver(e){if(this.ensureResolversInitialized(),Array.isArray(e)){this.addResolverArray(e);return}if(typeof e=="object"&&e!==null){this.addResolverObject(e);return}this.schemaOptions.resolvers=e;}addResolverArray(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,...e];return}this.schemaOptions.resolvers=[this.schemaOptions.resolvers,...e];}addResolverObject(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,e];return}this.schemaOptions.resolvers={...this.schemaOptions.resolvers,...e};}addTypeDefArray(e){for(let t of e)this.addTypeDef(t);}ensureTypeDefsArray(){if(Array.isArray(this.schemaOptions.typeDefs))return;if(this.schemaOptions.typeDefs!==void 0){this.schemaOptions.typeDefs=[this.schemaOptions.typeDefs];return}this.schemaOptions.typeDefs=[];}};var Me=class{constructor(e){this.response=e;}body(){return this.response.getBody()}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let o in t){let n=r===""?o:`${r}.${o}`,i=e[o],a=t[o];if(!(o in e))throw new Error(`Expected ${r} to have key ${o}, but it was not found`);if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} to be ${a}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${o.length}`);for(let i of n){let a=r==="body"?i:`${r}.${i}`;this.assertDeepEqual(e[i],t[i],a);}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`,i=e[o],a=t[o];if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,n);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,n);else if(i!==a)throw new Error(`Expected ${n} to be ${a}, but got ${i}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`;this.assertDeepEqual(e[o],t[o],n);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var se=async(s,e,t,r=new Y)=>{let o=0;if(!s.length)return await e(t,r),r;let n=async()=>{if(o++,o>=s.length){await e(t,r);return}let a=s[o];await a(t,r,n);},i=s[0];return await i(t,r,n),r},oe=s=>s?["post","put","patch","delete"].includes(s.toLowerCase()):true,qe=s=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(n=>setTimeout(n,10));},o=async()=>{try{let{createYoga:n,createSchema:i}=await import('graphql-yoga'),a=s.getSchema(i),p=s.getYogaOptions();return n({graphqlEndpoint:"/graphql",...p,schema:a})}catch(n){throw n instanceof Error&&(n.message.includes("Cannot find module")||n.message.includes("Cannot find package"))?new Error("GraphQL is enabled but 'graphql-yoga' is not installed. Install it with: npm install graphql graphql-yoga"):n}};return async()=>{if(!s.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=o(),await e}catch(p){throw e=null,p}finally{t=false;}}};var Ye=class{server;constructor(e){this.server=e;}async request(e,t,r={}){let{headers:o={},query:n={},cookies:i={},ip:a}=r;this.validateOptions(r);let p=O.find(e.toUpperCase(),t);if(!p){let m=new Y(404);return m.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new Me(m)}let c=r.body,l="application/json";if(c&&typeof c=="object"&&!(c instanceof Uint8Array)&&!(c instanceof ArrayBuffer)&&(c=JSON.stringify(c)),r.formData){let m=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;l=`multipart/form-data; boundary=${m}`,c=await this.formDataToMultipart(r.formData,m);}r.urlencoded&&(l="application/x-www-form-urlencoded",c=new URLSearchParams(r.urlencoded).toString());let d=new URL(`http://${this.server.host}:${this.server.port}${t}`);d.search=new URLSearchParams(n).toString();let f=new G(d.toString(),{method:e.toUpperCase(),body:oe(e)?c:void 0,headers:{"content-type":l,...o}});f.query={...Object.fromEntries(d.searchParams.entries()),...n},f.params=p.params,f.cookies=i,f.ip=a;try{let m=await se(p.middleware,p.handler,f);return new Me(m)}catch(m){v.error({error:m},`Error processing mock request ${e} ${t}:`);let g=new Y(500);return g.json({error:"Internal server error",message:m instanceof Error?m.message:String(m)}),new Me(g)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,o=[];for(let[p,c]of e.entries()){o.push(r.encode(`--${t}\r
316
+ `));let l=`Content-Disposition: form-data; name="${p}"`,d="";if(c instanceof File&&(l+=`; filename="${c.name}"`,d=`Content-Type: ${c.type||"application/octet-stream"}\r
317
+ `),o.push(r.encode(`${l}\r
318
+ ${d}\r
319
+ `)),c instanceof File){let f=await c.arrayBuffer();o.push(new Uint8Array(f)),o.push(r.encode(`\r
303
320
  `));}else o.push(r.encode(`${String(c)}\r
304
321
  `));}o.push(r.encode(`--${t}--\r
305
- `));let n=o.reduce((p,c)=>p+c.byteLength,0),i=new Uint8Array(n),a=0;for(let p of o)i.set(p,a),a+=p.byteLength;return i}validateOptions(e){let{body:t,formData:r,urlencoded:o}=e;if(t&&(r||o))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(o||t))throw new Error("Only one of formData, urlencoded can be provided");if(o&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var qe=new AsyncLocalStorage,Rt=s=>async(e,t,r)=>{let o={};for(let[n,i]of Object.entries(s))o[n]=i(e);qe.run(o,()=>{e.ctx=new Proxy({},{get(n,i){return qe.getStore()?.[i]},set(n,i,a){let p=qe.getStore();return p?(p[i]=a,true):false},ownKeys(){let n=qe.getStore();return n?Object.keys(n):[]},has(n,i){let a=qe.getStore();return a?i in a:false}}),r();});};var zt=()=>async(s,e,t)=>(se(s.method)&&(s.rawBody=await s.arrayBuffer(),Object.defineProperty(s,"body",{value:void 0,writable:true,configurable:true,enumerable:true})),t());var es=1024,ts=6,rs=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],Gt=s=>{let e=s?.threshold??es,t=Math.max(0,Math.min(9,s?.level??ts)),r=s?.filter??rs;return async(o,n,i)=>{if(!(o.headers.get("accept-encoding")||"").includes("gzip"))return i();let c=n.send.bind(n),d=n.json.bind(n),l=n.text.bind(n),h=(u,g)=>{if(!ss(u,g,e,r))return u;let b=Kt(u);if(!b||b.length<e)return u;let j=gzipSync(b,{level:t});return n.setHeader("Content-Encoding","gzip"),n.setHeader("Content-Length",j.length.toString()),j};n.send=function(u){let g=n.headers["content-type"],b=h(u,g);return c(b)},n.json=function(u){let g=JSON.stringify(u),b=h(g,"application/json");return b!==g?(n.setHeader("Content-Type","application/json"),c(b)):d(u)},n.text=function(u){let g=h(u,"text/plain");return g!==u?(n.setHeader("Content-Type","text/plain"),c(g)):l(u)},await i();}},ss=(s,e,t,r)=>{if(!s||!e)return false;let o=Kt(s);return !o||o.length<t?false:r.some(n=>n.test(e))},Kt=s=>typeof s=="string"?Buffer.from(s,"utf-8"):Buffer.isBuffer(s)?s:s instanceof Uint8Array?Buffer.from(s):typeof s=="object"?Buffer.from(JSON.stringify(s),"utf-8"):null;var Zt=s=>{let e={secret:s?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...s?.defaults},parse:s?.parse??true,sign:s?.sign??false};return async(t,r,o)=>{if(e.parse){let n=os(t.headers.get("cookie")||"");t.cookies={};for(let[i,a]of Object.entries(n)){if(e.sign&&e.secret){let p=await as(a,e.secret);p!==false&&(t.cookies[i]=p);continue}t.cookies[i]=a;}}r.cookie=(n,i,a)=>{Vt(r,n,i,{...e.defaults,...a},e);},r.clearCookie=(n,i)=>{ns(r,n,{...e.defaults,...i});},await o();}};function os(s){let e={};if(!s)return e;let t=s.split(";");for(let r of t){let[o,n]=r.trim().split("=");o&&n&&(e[decodeURIComponent(o)]=decodeURIComponent(n));}return e}async function Vt(s,e,t,r,o){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires&&(n+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(n+=`; Max-Age=${r.maxAge}`),r.secure&&(n+="; Secure"),r.httpOnly&&(n+="; HttpOnly"),r.sameSite&&(n+=`; SameSite=${r.sameSite}`),r.priority&&(n+=`; Priority=${r.priority}`),o.sign&&o.secret&&(n=await is(n,o.secret));let i=s.headers["set-cookie"]||"",a=i?`${i}, ${n}`:n;s.setHeader("Set-Cookie",a);}function ns(s,e,t){let r={...t,expires:new Date(0),maxAge:0};Vt(s,e,"",r,{secret:"",sign:false});}async function is(s,e){let t=new TextEncoder,r=t.encode(e),o=t.encode(s),n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=await crypto.subtle.sign("HMAC",n,o),a=new Uint8Array(i),p=Array.from(a).map(c=>c.toString(16).padStart(2,"0")).join("");return `${s}.${p}`}async function as(s,e){let t=s.split(".");if(t.length!==2)return false;let[r,o]=t,n=new TextEncoder,i=n.encode(e),a=n.encode(r),p=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},false,["sign"]),c=await crypto.subtle.sign("HMAC",p,a),d=new Uint8Array(c),l=Array.from(d).map(h=>h.toString(16).padStart(2,"0")).join("");return o===l?r:false}var Wt=s=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...s};return async(t,r,o)=>{let n=t.headers.get("origin")||"";if(t.method==="OPTIONS")return ps(t,r,e,n,o);cs(t,r,e,n),await o();}};function ps(s,e,t,r,o){let n=Jt(t,r);if(!n){e.forbidden("CORS origin not allowed");return}if(Yt(e,t,n),t.preflightContinue){o();return}e.status(t.optionsSuccessStatus||204),e.send("");}function cs(s,e,t,r){let o=Jt(t,r);o&&Yt(e,t,o);}function Jt(s,e){if(typeof s.origin=="string")return s.origin;if(Array.isArray(s.origin)){let t=s.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function Yt(s,e,t){if(s.setHeader("Access-Control-Allow-Origin",t),e.credentials&&s.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let o=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;s.setHeader("Access-Control-Expose-Headers",o);}if(e.allowedHeaders&&e.allowedHeaders!==""){let o=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;s.setHeader("Access-Control-Allow-Headers",o);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;s.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&s.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function Xt(s,e=""){let t=new URL(s.url),r=Object.fromEntries(s.headers.entries());return {body:s.body,query:s.query,params:s.params,cookies:s.cookies,session:s.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:s.method,ip:s.ip,headers:r,url:t.pathname,get(n){return s.headers.get(n.toLowerCase())??void 0},header(n){return s.headers.get(n.toLowerCase())??void 0},app:{},res:null,route:null,protocol:t.protocol.replace(":",""),secure:t.protocol==="https:",hostname:t.hostname,host:t.host,fresh:false,stale:true,xhr:r["x-requested-with"]?.toLowerCase()==="xmlhttprequest",accepts:()=>{},acceptsCharsets:()=>{},acceptsEncodings:()=>{},acceptsLanguages:()=>{},is:()=>null,range:()=>{},param:n=>s.params[n]??s.query[n],files:s.files,file:s.file,rawBody:s.rawBody}}function er(s){return {locals:{},headersSent:false,statusCode:s.responseStatus,status(t){return s.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!s.headers["Content-Type"]&&typeof t=="string"){let o=t.trim();if(o.startsWith("<!DOCTYPE")||o.startsWith("<html")||o.startsWith("<HTML"))return s.html(t),this}return s.send(t),this},json(t){return this.headersSent=true,s.json(t),this},redirect(t,r){this.headersSent=true;let o=typeof t=="string"?t:r,n=typeof t=="number"?t:302;return s.status(n).setHeader("Location",o),s.send(""),this},setHeader(t,r){let o=Array.isArray(r)?r.join(", "):String(r);return s.setHeader(t,o),this},set(t,r){if(typeof t=="object")for(let[o,n]of Object.entries(t))s.setHeader(o,n);else r!==void 0&&s.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return s.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,s.send(t??""),this},write(t){return true},get(t){return s.headers[t]},getHeader(t){return s.headers[t]},removeHeader(t){return delete s.headers[t],this},append(t,r){let o=s.headers[t],n=Array.isArray(r)?r.join(", "):r;return s.setHeader(t,o?`${o}, ${n}`:n),this},cookie(t,r,o){return s.cookie?.(t,r,o),this},clearCookie(t,r){return s.clearCookie?.(t,r),this},render(t,r,o){throw new Error("render() is not supported in Express compatibility layer")},format(t){return this},attachment(t){return t?s.setHeader("Content-Disposition",`attachment; filename="${t}"`):s.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,o){s.file(t);},download(t,r,o,n){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),s.file(t);},links(t){let r=Object.entries(t).map(([o,n])=>`<${n}>; rel="${o}"`).join(", ");return s.setHeader("Link",r),this},location(t){return s.setHeader("Location",t),this},vary(t){return s.setHeader("Vary",t),this},app:{},req:null}}function ke(s,e=""){return async(t,r,o)=>{let n=Xt(t,e),i=er(r);await new Promise((a,p)=>{let c=d=>{if(d){p(d);return}a();};try{let d=s(n,i,c);d instanceof Promise&&d.catch(p);}catch(d){p(d);}}),await o();}}function ds(s,e=""){return async(t,r)=>{let o=Xt(t,e),n=er(r);await s(o,n,()=>{});}}function Ye(s,e){let t=Tt(s),r=e.stack;if(!r){console.warn("Express router has no stack - routes may not be registered");return}for(let o of r)tr(o,t);}function tr(s,e){if(s.route){let t=Tt(e+s.route.path),r=Object.keys(s.route.methods).filter(o=>s.route.methods[o]);for(let o of r){let n=s.route.stack.map(i=>i.handle);ls(o.toUpperCase(),t,n,e);}return}if(s.handle&&typeof s.handle=="function"){let t=s.path||"",r=Tt(e+t),o=s.handle.stack;if(o&&Array.isArray(o)){for(let p of o)tr(p,r);return}let n=r==="/"?"/*":`${r}/*`,i=ke(s.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let p of a)C.addOrUpdate(p,n,[i],async()=>{},{excludeFromSwagger:true});}}function ls(s,e,t,r){let o=t.slice(0,-1).map(a=>ke(a,r)),n=t[t.length-1],i=ds(n,r);C.addOrUpdate(s,e,o,i,{excludeFromSwagger:true});}function Tt(s){let e=s.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function rr(s){return {use(e,t){if(typeof e=="string"){let n=e,i=t,a=i.stack;if(a&&Array.isArray(a)){Ye(n,i);return}s.use(ke(i,n));return}let r=e,o=r.stack;if(o&&Array.isArray(o)){Ye("/",r);return}s.use(ke(r));}}}var Xe=class extends x{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};H();var Ct=class{async tmpdir(){switch(S.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},sr=new Ct;var or=1024*1024,ir=s=>async(e,t,r)=>{let o=[];try{let n=e.headers.get("content-type")??e.headers.get("Content-Type");if(!n||!n.startsWith("multipart/form-data")||!e.rawBody)return r();let i=n.match(/boundary=(.*)(;|$)/i);if(!i)return r();let a=i[1].replace(/(^\s*"?|"?\s*$)/g,""),p=new Uint8Array(e.rawBody),c=new TextEncoder().encode(`--${a}`),d=new Uint8Array([13,10,13,10]),l=[],h=(R,E,J=0)=>{e:for(let F=J;F<=R.length-E.length;F++){for(let L=0;L<E.length;L++)if(R[F+L]!==E[L])continue e;return F}return -1},u=h(p,c);for(;u!==-1&&(u+=c.length,!(p[u]===45&&p[u+1]===45));){p[u]===13&&p[u+1]===10&&(u+=2);let R=h(p,d,u);if(R===-1)break;let E=p.subarray(u,R),J=new TextDecoder().decode(E),F=R+d.length,L=h(p,c,F);if(L===-1)break;let B=L-1;p[B]===10&&B--,p[B]===13&&B--;let Pt=p.subarray(F,B+1);l.push({headers:J,data:Pt}),u=L;}let g=[],b={},j=Se(s?.maxFileSize,or)??or;for(let R of l){let E=R.headers.split(`\r
306
- `).find(_e=>_e.toLowerCase().startsWith("content-disposition:"));if(!E)continue;let J=E.match(/name="([^"]+)"/);if(!J)continue;let F=J[1],L=E.match(/filename="([^"]*)"/),B=L?L[1]:"";if(!!B){if(s?.maxFiles&&g.length>=s.maxFiles)return t.badRequest({...P(new x(`Too many files: Maximum ${s.maxFiles} files allowed`))});if(j&&R.data.length>j)return t.badRequest({...P(new Xe(B,R.data.length,j))});let _e=R.headers.split(`\r
307
- `).find(qr=>qr.toLowerCase().startsWith("content-type:")),at=_e?_e.split(":")[1].trim():"application/octet-stream";if(s?.allowedMimeTypes&&!s.allowedMimeTypes.includes(at))return t.badRequest({...P(new x(`Invalid file type: "${at}" is not allowed. Allowed types: ${s.allowedMimeTypes.join(", ")}`))});let Mr=us(B),Ar=f.extName(Mr),pt=f.join(await sr.tmpdir(),`${Y.randomUUID()}${Ar}`);await m.writeFile(pt,R.data),o.push(pt),g.push({formName:F,mimeType:at,size:R.data.length,tmpPath:pt,originalName:B});}else b[F]=new TextDecoder().decode(R.data);}e.files=g,e.body=b,await r(),await nr(o);}catch(n){throw await nr(o),n}},nr=async s=>{await Promise.allSettled(s.map(e=>m.unlink(e)));},us=s=>s.replace(/\.\./g,"").replace(/[\/\\]/g,"").replace(/\0/g,"").replace(/[\x00-\x1f\x80-\x9f]/g,"").trim();var ar=s=>{let e={dnsPrefetchControl:true,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:true,preload:false},contentTypeOptions:true,ieNoOpen:true,xssFilter:true,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:false,...s};return async(t,r,o)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let n="SAMEORIGIN";typeof e.frameguard=="object"&&(n=e.frameguard.action),r.setHeader("X-Frame-Options",n);}if(e.hsts){let n={};typeof e.hsts=="object"&&(n=e.hsts);let i=n.maxAge!==void 0?n.maxAge:15552e3,a=n.includeSubDomains!==void 0?n.includeSubDomains:true,p=n.preload!==void 0?n.preload:false,c=`max-age=${i}`;a!==false&&(c+="; includeSubDomains"),p&&(c+="; preload"),r.setHeader("Strict-Transport-Security",c);}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await o();}};var Ne=class extends x{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var pr=100*1024,cr=s=>async(e,t,r)=>{if(!ms(e)||!se(e.method))return r();let o=Se(s?.sizeLimit,pr)??pr,n=e.rawBody;if(!n)return s?.parseEmptyBodyAsObject&&(e.body={}),r();let i=n.byteLength;if(!i)return s?.parseEmptyBodyAsObject&&(e.body={}),r();if(i>o){let a={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...s?.customErrorMessage};return t.status(a.status).json({error:a.message})}try{let a=s?.encoding??"utf-8",p=new TextDecoder(a).decode(n);e.body=JSON.parse(p);}catch(a){return a instanceof SyntaxError?t.badRequest({...P(new Ne("Invalid JSON syntax"))}):t.badRequest({...P(new Ne("Invalid request body encoding"))})}await r();};function ms(s){let e=hs(s);return e?fs(e)==="application/json":false}function hs(s){let e=s.headers.get("content-type")??s.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function fs(s){let e=s.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var lr=s=>async(e,t,r)=>{try{let o=e.body;(s?.logRequest??!0)&&y.info({type:"request",requestId:e.id,method:s?.requestPayload?.method??!0?e.method:void 0,url:s?.requestPayload?.url??!0?e.url:void 0,ip:s?.requestPayload?.ip??!0?e.ip:void 0,headers:s?.requestPayload?.headers??!0?e.headers:void 0,body:s?.requestPayload?.body??!1?dr(o):void 0});let n=performance.now();await r();let a=performance.now()-n;(s?.logResponse??!0)&&y.info({type:"response",requestId:e.id,status:s?.responsePayload?.status??t.responseStatus,duration:`${a.toFixed(2)}ms`,body:s?.responsePayload?.body??!1?dr(t.getBody()):void 0,headers:s?.responsePayload?.headers??!1?t.headers:void 0});}catch(o){throw y.error(o),o}};function dr(s){if(typeof s=="string"||s&&typeof s=="object"&&s.constructor===Object)return s}var gs=["POST"],ys="X-HTTP-Method-Override",vs=["GET","POST","PUT","PATCH","DELETE"],ur=s=>{let e=(s?.methods??gs).map(r=>r.toUpperCase()),t=s?.header??ys;return async(r,o,n)=>{let i=r.method.toUpperCase();if(!e.includes(i))return n();let a=r.headers.get(t);if(!a)return n();let p=a.toUpperCase();if(!vs.includes(p))return n();r.method=p,await n();}};var et=class{storage=new Map;windowMs;constructor(e){this.windowMs=e;}async set(e,t){this.storage.set(e,t),setTimeout(()=>{this.storage.delete(e);},this.windowMs);}async get(e){let t=this.storage.get(e);return t||0}async delete(e){this.storage.delete(e);}};var mr=(s,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...s},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let o=r.type==="memory"?new et(r.windowMs):{get:r.get,set:r.set};return async(n,i,a)=>{let p=t.type==="ip"?n.ip:t.key(n),c=await o.get(p);return c>=t.limit?i.status(t.statusCode).json({message:t.message}):(await o.set(p,c+1),a())}};var tt=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let o=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:o});}async destroy(e){this.store.delete(e);}};var hr=s=>{let e=s?.name??"sid",t=s?.ttl??3600*24,r=s?.store??new tt,o={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...s?.cookie??{}};return async(n,i,a)=>{let c=n.cookies&&n.cookies[e],d=c?await r.get(c):void 0;(!c||!d)&&(c||=Y.randomUUID(),d||={},await r.set(c,d,t),i.cookie?.(e,c,o)),n.session=d,n.saveSession=async()=>r.set(c,d,t),n.destroySession=async()=>{await r.destroy(c),i.clearCookie?.(e,o);},await a(),await r.set(c,d,t);}};var gr=s=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};s&&typeof s!="boolean"&&(e={...e,...s});let t=bs(e),r=`${e.path}`,o=`${r}/json`,n;e.type==="rapidoc"?n=xs(o,e):e.type==="scalar"?n=Rs(o,e):e.type==="elements"?n=Ts(o,e):e.type==="custom"?n=e.customUIGenerator(o,e):n=Ss(o,e),C.addOrUpdate("GET",r,[],(i,a)=>{a.html(n);}),C.addOrUpdate("GET",o,[],(i,a)=>{a.json(t);});},ne=s=>s?s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):"";function oe(s){try{return z$1.toJSONSchema(s)}catch(e){if(e instanceof Error&&e.message.includes("Custom types cannot be represented in JSON Schema")){let t=s._def;if(t?.typeName==="ZodInstanceof"){let r=new File([],"test");if(s.safeParse(r).success)return {type:"string",format:"binary"}}if(t?.typeName==="ZodObject"&&t?.shape){let r={},o=[];for(let[n,i]of Object.entries(t.shape))try{r[n]=oe(i);let a=i._def;a?.typeName!=="ZodOptional"&&a?.typeName!=="ZodDefault"&&o.push(n);}catch{r[n]={type:"string",format:"binary"};}return {type:"object",properties:r,...o.length>0?{required:o}:{}}}return {type:"object",description:"Custom type"}}throw e}}function bs(s){let e=C.getRoutes(),t={},r;if(s.models)if(Array.isArray(s.models))r=s.models.reduce((n,i,a)=>{let c=i&&typeof i=="object"&&"_def"in i?oe(i):i,d=c.$id||c.title||`Model${a}`;return n[d]=c,n},{});else {r={};for(let[n,i]of Object.entries(s.models)){let a=i&&typeof i=="object"&&"_def"in i;r[n]=a?oe(i):i;}}let o={...s.components,securitySchemes:s.securitySchemes||{},schemas:r?{...s.components?.schemas||{},...r}:s.components?.schemas?{...s.components.schemas}:void 0};for(let n of e){let i=n.swaggerOptions;if(i?.excludeFromSwagger)continue;t[n.path]||(t[n.path]={});let a=n.method.toLowerCase(),p={summary:i?.name||`${a.toUpperCase()} ${n.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},c=[];if(i?.query&&i.query.type==="object"&&i.query.shape)for(let[d,l]of Object.entries(i.query.shape))c.push({name:d,in:"query",required:Array.isArray(i.query.shape[d].required)?i.query.shape[d].required.includes(d):false,schema:oe(l)});if(i&&i.params?c=c.concat(fr(n.path,i.params)):c=c.concat(fr(n.path)),c.length>0&&(p.parameters=c),i?.requestBody){let d="application/json";i.bodyType==="form-data"?d="multipart/form-data":i.bodyType==="urlencoded"&&(d="application/x-www-form-urlencoded"),p.requestBody={content:{[d]:{schema:oe(i.requestBody)}},required:true};}else i?.bodyType&&(i.bodyType.includes("form-data")||i.bodyType.includes("urlencoded"))&&(p.requestBody={content:{[i.bodyType]:{schema:{type:"object"}}},required:true});if(p.responses={},i?.responses)for(let[d,l]of Object.entries(i.responses))p.responses[d]={description:`Response for ${d}`,content:{"application/json":{schema:oe(l)}}};if(i?.errors)for(let[d,l]of Object.entries(i.errors))p.responses[d]={description:`Error response for ${d}`,content:{"application/json":{schema:oe(l)}}};if(Object.keys(p.responses).length===0&&(p.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),i?.security){let d=[];Array.isArray(i.security)||(i.security=[i.security]);for(let l of i.security)if(l.type==="bearer")o.securitySchemes.bearer||(o.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:l.bearerFormat||"JWT",description:l.description}),d.push({bearer:[]});else if(l.type==="apiKey")o.securitySchemes[l.name]||(o.securitySchemes[l.name]={type:"apiKey",name:l.name,in:l.in,description:l.description}),d.push({[l.name]:[]});else if(l.type==="oauth2"){let h=l.name||"oauth2";o.securitySchemes[h]||(o.securitySchemes[h]={type:"oauth2",flows:l.flows,description:l.description}),d.push({[h]:[]});}else if(l.type==="openIdConnect"){let h=l.name||"openIdConnect";o.securitySchemes[h]||(o.securitySchemes[h]={type:"openIdConnect",openIdConnectUrl:l.openIdConnectUrl,description:l.description}),d.push({[h]:[]});}d.length&&(p.security=d);}else s.security&&(p.security=s.security);t[n.path][a]=p;}return {openapi:"3.0.0",info:{title:s.title,description:s.description,version:s.version,...s.info},servers:s.servers?.map(n=>({url:n}))||[{url:"/"}],paths:t,components:o,security:s.security||[],tags:s.tags?Object.entries(s.tags).map(([n,i])=>({name:n,...i})):[]}}function Ss(s,e){return `
322
+ `));let n=o.reduce((p,c)=>p+c.byteLength,0),i=new Uint8Array(n),a=0;for(let p of o)i.set(p,a),a+=p.byteLength;return i}validateOptions(e){let{body:t,formData:r,urlencoded:o}=e;if(t&&(r||o))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(o||t))throw new Error("Only one of formData, urlencoded can be provided");if(o&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var ke=new AsyncLocalStorage,Tt=s=>async(e,t,r)=>{let o={};for(let[n,i]of Object.entries(s))o[n]=i(e);ke.run(o,()=>{e.ctx=new Proxy({},{get(n,i){return ke.getStore()?.[i]},set(n,i,a){let p=ke.getStore();return p?(p[i]=a,true):false},ownKeys(){let n=ke.getStore();return n?Object.keys(n):[]},has(n,i){let a=ke.getStore();return a?i in a:false}}),r();});};var Gt=()=>async(s,e,t)=>(oe(s.method)&&(s.rawBody=await s.arrayBuffer(),Object.defineProperty(s,"body",{value:void 0,writable:true,configurable:true,enumerable:true})),t());var rs=1024,ss=6,os=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],Kt=s=>{let e=s?.threshold??rs,t=Math.max(0,Math.min(9,s?.level??ss)),r=s?.filter??os;return async(o,n,i)=>{if(!(o.headers.get("accept-encoding")||"").includes("gzip"))return i();let c=n.send.bind(n),l=n.json.bind(n),d=n.text.bind(n),f=(m,g)=>{if(!ns(m,g,e,r))return m;let S=Vt(m);if(!S||S.length<e)return m;let E=gzipSync(S,{level:t});return n.setHeader("Content-Encoding","gzip"),n.setHeader("Content-Length",E.length.toString()),E};n.send=function(m){let g=n.headers["content-type"],S=f(m,g);return c(S)},n.json=function(m){let g=JSON.stringify(m),S=f(g,"application/json");return S!==g?(n.setHeader("Content-Type","application/json"),c(S)):l(m)},n.text=function(m){let g=f(m,"text/plain");return g!==m?(n.setHeader("Content-Type","text/plain"),c(g)):d(m)},await i();}},ns=(s,e,t,r)=>{if(!s||!e)return false;let o=Vt(s);return !o||o.length<t?false:r.some(n=>n.test(e))},Vt=s=>typeof s=="string"?Buffer.from(s,"utf-8"):Buffer.isBuffer(s)?s:s instanceof Uint8Array?Buffer.from(s):typeof s=="object"?Buffer.from(JSON.stringify(s),"utf-8"):null;var Zt=s=>{let e={secret:s?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...s?.defaults},parse:s?.parse??true,sign:s?.sign??false};return async(t,r,o)=>{if(e.parse){let n=is(t.headers.get("cookie")||"");t.cookies={};for(let[i,a]of Object.entries(n)){if(e.sign&&e.secret){let p=await cs(a,e.secret);p!==false&&(t.cookies[i]=p);continue}t.cookies[i]=a;}}r.cookie=(n,i,a)=>{Wt(r,n,i,{...e.defaults,...a},e);},r.clearCookie=(n,i)=>{as(r,n,{...e.defaults,...i});},await o();}};function is(s){let e={};if(!s)return e;let t=s.split(";");for(let r of t){let[o,n]=r.trim().split("=");o&&n&&(e[decodeURIComponent(o)]=decodeURIComponent(n));}return e}async function Wt(s,e,t,r,o){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires&&(n+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(n+=`; Max-Age=${r.maxAge}`),r.secure&&(n+="; Secure"),r.httpOnly&&(n+="; HttpOnly"),r.sameSite&&(n+=`; SameSite=${r.sameSite}`),r.priority&&(n+=`; Priority=${r.priority}`),o.sign&&o.secret&&(n=await ps(n,o.secret));let i=s.headers["set-cookie"]||"",a=i?`${i}, ${n}`:n;s.setHeader("Set-Cookie",a);}function as(s,e,t){let r={...t,expires:new Date(0),maxAge:0};Wt(s,e,"",r,{secret:"",sign:false});}async function ps(s,e){let t=new TextEncoder,r=t.encode(e),o=t.encode(s),n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=await crypto.subtle.sign("HMAC",n,o),a=new Uint8Array(i),p=Array.from(a).map(c=>c.toString(16).padStart(2,"0")).join("");return `${s}.${p}`}async function cs(s,e){let t=s.split(".");if(t.length!==2)return false;let[r,o]=t,n=new TextEncoder,i=n.encode(e),a=n.encode(r),p=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},false,["sign"]),c=await crypto.subtle.sign("HMAC",p,a),l=new Uint8Array(c),d=Array.from(l).map(f=>f.toString(16).padStart(2,"0")).join("");return o===d?r:false}var Jt=s=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...s};return async(t,r,o)=>{let n=t.headers.get("origin")||"";if(t.method==="OPTIONS")return ls(t,r,e,n,o);ds(t,r,e,n),await o();}};function ls(s,e,t,r,o){let n=Yt(t,r);if(!n){e.forbidden("CORS origin not allowed");return}if(Xt(e,t,n),t.preflightContinue){o();return}e.status(t.optionsSuccessStatus||204),e.send("");}function ds(s,e,t,r){let o=Yt(t,r);o&&Xt(e,t,o);}function Yt(s,e){if(typeof s.origin=="string")return s.origin;if(Array.isArray(s.origin)){let t=s.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function Xt(s,e,t){if(s.setHeader("Access-Control-Allow-Origin",t),e.credentials&&s.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let o=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;s.setHeader("Access-Control-Expose-Headers",o);}if(e.allowedHeaders&&e.allowedHeaders!==""){let o=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;s.setHeader("Access-Control-Allow-Headers",o);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;s.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&s.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function er(s,e=""){let t=new URL(s.url),r=Object.fromEntries(s.headers.entries());return {body:s.body,query:s.query,params:s.params,cookies:s.cookies,session:s.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:s.method,ip:s.ip,headers:r,url:t.pathname,get(n){return s.headers.get(n.toLowerCase())??void 0},header(n){return s.headers.get(n.toLowerCase())??void 0},app:{},res:null,route:null,protocol:t.protocol.replace(":",""),secure:t.protocol==="https:",hostname:t.hostname,host:t.host,fresh:false,stale:true,xhr:r["x-requested-with"]?.toLowerCase()==="xmlhttprequest",accepts:()=>{},acceptsCharsets:()=>{},acceptsEncodings:()=>{},acceptsLanguages:()=>{},is:()=>null,range:()=>{},param:n=>s.params[n]??s.query[n],files:s.files,file:s.file,rawBody:s.rawBody}}function tr(s){return {locals:{},headersSent:false,statusCode:s.responseStatus,status(t){return s.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!s.headers["Content-Type"]&&typeof t=="string"){let o=t.trim();if(o.startsWith("<!DOCTYPE")||o.startsWith("<html")||o.startsWith("<HTML"))return s.html(t),this}return s.send(t),this},json(t){return this.headersSent=true,s.json(t),this},redirect(t,r){this.headersSent=true;let o=typeof t=="string"?t:r,n=typeof t=="number"?t:302;return s.status(n).setHeader("Location",o),s.send(""),this},setHeader(t,r){let o=Array.isArray(r)?r.join(", "):String(r);return s.setHeader(t,o),this},set(t,r){if(typeof t=="object")for(let[o,n]of Object.entries(t))s.setHeader(o,n);else r!==void 0&&s.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return s.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,s.send(t??""),this},write(t){return true},get(t){return s.headers[t]},getHeader(t){return s.headers[t]},removeHeader(t){return delete s.headers[t],this},append(t,r){let o=s.headers[t],n=Array.isArray(r)?r.join(", "):r;return s.setHeader(t,o?`${o}, ${n}`:n),this},cookie(t,r,o){return s.cookie?.(t,r,o),this},clearCookie(t,r){return s.clearCookie?.(t,r),this},render(t,r,o){throw new Error("render() is not supported in Express compatibility layer")},format(t){return this},attachment(t){return t?s.setHeader("Content-Disposition",`attachment; filename="${t}"`):s.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,o){s.file(t);},download(t,r,o,n){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),s.file(t);},links(t){let r=Object.entries(t).map(([o,n])=>`<${n}>; rel="${o}"`).join(", ");return s.setHeader("Link",r),this},location(t){return s.setHeader("Location",t),this},vary(t){return s.setHeader("Vary",t),this},app:{},req:null}}function $e(s,e=""){return async(t,r,o)=>{let n=er(t,e),i=tr(r);await new Promise((a,p)=>{let c=l=>{if(l){p(l);return}a();};try{let l=s(n,i,c);l instanceof Promise&&l.catch(p);}catch(l){p(l);}}),await o();}}function us(s,e=""){return async(t,r)=>{let o=er(t,e),n=tr(r);await s(o,n,()=>{});}}function Xe(s,e){let t=Ct(s),r=e.stack;if(!r){console.warn("Express router has no stack - routes may not be registered");return}for(let o of r)rr(o,t);}function rr(s,e){if(s.route){let t=Ct(e+s.route.path),r=Object.keys(s.route.methods).filter(o=>s.route.methods[o]);for(let o of r){let n=s.route.stack.map(i=>i.handle);ms(o.toUpperCase(),t,n,e);}return}if(s.handle&&typeof s.handle=="function"){let t=s.path||"",r=Ct(e+t),o=s.handle.stack;if(o&&Array.isArray(o)){for(let p of o)rr(p,r);return}let n=r==="/"?"/*":`${r}/*`,i=$e(s.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let p of a)O.addOrUpdate(p,n,[i],async()=>{},{excludeFromSwagger:true});}}function ms(s,e,t,r){let o=t.slice(0,-1).map(a=>$e(a,r)),n=t[t.length-1],i=us(n,r);O.addOrUpdate(s,e,o,i,{excludeFromSwagger:true});}function Ct(s){let e=s.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function sr(s){return {use(e,t){if(typeof e=="string"){let n=e,i=t,a=i.stack;if(a&&Array.isArray(a)){Xe(n,i);return}s.use($e(i,n));return}let r=e,o=r.stack;if(o&&Array.isArray(o)){Xe("/",r);return}s.use($e(r));}}}var et=class extends T{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};F();var Ot=class{async tmpdir(){switch(R.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},or=new Ot;var nr=1024*1024,ar=s=>async(e,t,r)=>{let o=[];try{let n=e.headers.get("content-type")??e.headers.get("Content-Type");if(!n||!n.startsWith("multipart/form-data")||!e.rawBody)return r();let i=n.match(/boundary=(.*)(;|$)/i);if(!i)return r();let a=i[1].replace(/(^\s*"?|"?\s*$)/g,""),p=new Uint8Array(e.rawBody),c=new TextEncoder().encode(`--${a}`),l=new Uint8Array([13,10,13,10]),d=[],f=(C,A,b=0)=>{e:for(let j=b;j<=C.length-A.length;j++){for(let L=0;L<A.length;L++)if(C[j+L]!==A[L])continue e;return j}return -1},m=f(p,c);for(;m!==-1&&(m+=c.length,!(p[m]===45&&p[m+1]===45));){p[m]===13&&p[m+1]===10&&(m+=2);let C=f(p,l,m);if(C===-1)break;let A=p.subarray(m,C),b=new TextDecoder().decode(A),j=C+l.length,L=f(p,c,j);if(L===-1)break;let U=L-1;p[U]===10&&U--,p[U]===13&&U--;let jt=p.subarray(j,U+1);d.push({headers:b,data:jt}),m=L;}let g=[],S={},E=xe(s?.maxFileSize,nr)??nr;for(let C of d){let A=C.headers.split(`\r
323
+ `).find(Le=>Le.toLowerCase().startsWith("content-disposition:"));if(!A)continue;let b=A.match(/name="([^"]+)"/);if(!b)continue;let j=b[1],L=A.match(/filename="([^"]*)"/),U=L?L[1]:"";if(!!U){if(s?.maxFiles&&g.length>=s.maxFiles)return t.badRequest({...M(new T(`Too many files: Maximum ${s.maxFiles} files allowed`))});if(E&&C.data.length>E)return t.badRequest({...M(new et(U,C.data.length,E))});let Le=C.headers.split(`\r
324
+ `).find(kr=>kr.toLowerCase().startsWith("content-type:")),pt=Le?Le.split(":")[1].trim():"application/octet-stream";if(s?.allowedMimeTypes&&!s.allowedMimeTypes.includes(pt))return t.badRequest({...M(new T(`Invalid file type: "${pt}" is not allowed. Allowed types: ${s.allowedMimeTypes.join(", ")}`))});let Mr=hs(U),qr=h.extName(Mr),ct=h.join(await or.tmpdir(),`${X.randomUUID()}${qr}`);await u.writeFile(ct,C.data),o.push(ct),g.push({formName:j,mimeType:pt,size:C.data.length,tmpPath:ct,originalName:U});}else S[j]=new TextDecoder().decode(C.data);}e.files=g,e.body=S,await r(),await ir(o);}catch(n){throw await ir(o),n}},ir=async s=>{await Promise.allSettled(s.map(e=>u.unlink(e)));},hs=s=>s.replace(/\.\./g,"").replace(/[\/\\]/g,"").replace(/\0/g,"").replace(/[\x00-\x1f\x80-\x9f]/g,"").trim();var pr=s=>{let e={dnsPrefetchControl:true,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:true,preload:false},contentTypeOptions:true,ieNoOpen:true,xssFilter:true,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:false,...s};return async(t,r,o)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let n="SAMEORIGIN";typeof e.frameguard=="object"&&(n=e.frameguard.action),r.setHeader("X-Frame-Options",n);}if(e.hsts){let n={};typeof e.hsts=="object"&&(n=e.hsts);let i=n.maxAge!==void 0?n.maxAge:15552e3,a=n.includeSubDomains!==void 0?n.includeSubDomains:true,p=n.preload!==void 0?n.preload:false,c=`max-age=${i}`;a!==false&&(c+="; includeSubDomains"),p&&(c+="; preload"),r.setHeader("Strict-Transport-Security",c);}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await o();}};var _e=class extends T{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var cr=100*1024,lr=s=>async(e,t,r)=>{if(!fs(e)||!oe(e.method))return r();let o=xe(s?.sizeLimit,cr)??cr,n=e.rawBody;if(!n)return s?.parseEmptyBodyAsObject&&(e.body={}),r();let i=n.byteLength;if(!i)return s?.parseEmptyBodyAsObject&&(e.body={}),r();if(i>o){let a={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...s?.customErrorMessage};return t.status(a.status).json({error:a.message})}try{let a=s?.encoding??"utf-8",p=new TextDecoder(a).decode(n);e.body=JSON.parse(p);}catch(a){return a instanceof SyntaxError?t.badRequest({...M(new _e("Invalid JSON syntax"))}):t.badRequest({...M(new _e("Invalid request body encoding"))})}await r();};function fs(s){let e=gs(s);return e?ys(e)==="application/json":false}function gs(s){let e=s.headers.get("content-type")??s.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function ys(s){let e=s.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var ur=s=>async(e,t,r)=>{try{let o=e.body;(s?.logRequest??!0)&&v.info({type:"request",requestId:e.id,method:s?.requestPayload?.method??!0?e.method:void 0,url:s?.requestPayload?.url??!0?e.url:void 0,ip:s?.requestPayload?.ip??!0?e.ip:void 0,headers:s?.requestPayload?.headers??!0?e.headers:void 0,body:s?.requestPayload?.body??!1?dr(o):void 0});let n=performance.now();await r();let a=performance.now()-n;(s?.logResponse??!0)&&v.info({type:"response",requestId:e.id,status:s?.responsePayload?.status??t.responseStatus,duration:`${a.toFixed(2)}ms`,body:s?.responsePayload?.body??!1?dr(t.getBody()):void 0,headers:s?.responsePayload?.headers??!1?t.headers:void 0});}catch(o){throw v.error(o),o}};function dr(s){if(typeof s=="string"||s&&typeof s=="object"&&s.constructor===Object)return s}var vs=["POST"],ws="X-HTTP-Method-Override",bs=["GET","POST","PUT","PATCH","DELETE"],mr=s=>{let e=(s?.methods??vs).map(r=>r.toUpperCase()),t=s?.header??ws;return async(r,o,n)=>{let i=r.method.toUpperCase();if(!e.includes(i))return n();let a=r.headers.get(t);if(!a)return n();let p=a.toUpperCase();if(!bs.includes(p))return n();r.method=p,await n();}};var tt=class{storage=new Map;windowMs;constructor(e){this.windowMs=e;}async set(e,t){this.storage.set(e,t),setTimeout(()=>{this.storage.delete(e);},this.windowMs);}async get(e){let t=this.storage.get(e);return t||0}async delete(e){this.storage.delete(e);}};var hr=(s,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...s},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let o=r.type==="memory"?new tt(r.windowMs):{get:r.get,set:r.set};return async(n,i,a)=>{let p=t.type==="ip"?n.ip:t.key(n),c=await o.get(p);return c>=t.limit?i.status(t.statusCode).json({message:t.message}):(await o.set(p,c+1),a())}};var rt=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let o=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:o});}async destroy(e){this.store.delete(e);}};var fr=s=>{let e=s?.name??"sid",t=s?.ttl??3600*24,r=s?.store??new rt,o={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...s?.cookie??{}};return async(n,i,a)=>{let c=n.cookies&&n.cookies[e],l=c?await r.get(c):void 0;(!c||!l)&&(c||=X.randomUUID(),l||={},await r.set(c,l,t),i.cookie?.(e,c,o)),n.session=l,n.saveSession=async()=>r.set(c,l,t),n.destroySession=async()=>{await r.destroy(c),i.clearCookie?.(e,o);},await a(),await r.set(c,l,t);}};var yr=s=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};s&&typeof s!="boolean"&&(e={...e,...s});let t=Ss(e),r=`${e.path}`,o=`${r}/json`,n;e.type==="rapidoc"?n=Rs(o,e):e.type==="scalar"?n=Ts(o,e):e.type==="elements"?n=Cs(o,e):e.type==="custom"?n=e.customUIGenerator(o,e):n=xs(o,e),O.addOrUpdate("GET",r,[],(i,a)=>{a.html(n);}),O.addOrUpdate("GET",o,[],(i,a)=>{a.json(t);});},ne=s=>s?s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):"";function be(s){return !s||typeof s!="object"?{type:"string"}:s}function Ss(s){let e=O.getRoutes(),t={},r;if(s.models)if(Array.isArray(s.models))r=s.models.reduce((n,i,a)=>{let p=be(i),c=p.$id||p.title||`Model${a}`;return n[c]=p,n},{});else {r={};for(let[n,i]of Object.entries(s.models))r[n]=be(i);}let o={...s.components,securitySchemes:s.securitySchemes||{},schemas:r?{...s.components?.schemas||{},...r}:s.components?.schemas?{...s.components.schemas}:void 0};for(let n of e){let i=n.swaggerOptions;if(i?.excludeFromSwagger)continue;t[n.path]||(t[n.path]={});let a=n.method.toLowerCase(),p={summary:i?.name||`${a.toUpperCase()} ${n.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},c=[];if(i?.query&&i.query.type==="object"&&i.query.shape)for(let[l,d]of Object.entries(i.query.shape))!d||typeof d!="object"||c.push({name:l,in:"query",required:Array.isArray(i.query.shape[l].required)?i.query.shape[l].required.includes(l):false,schema:be(d)});if(i&&i.params?c=c.concat(gr(n.path,i.params)):c=c.concat(gr(n.path)),c.length>0&&(p.parameters=c),i?.requestBody){let l="application/json";i.bodyType==="form-data"?l="multipart/form-data":i.bodyType==="urlencoded"&&(l="application/x-www-form-urlencoded"),p.requestBody={content:{[l]:{schema:be(i.requestBody)}},required:true};}else i?.bodyType&&(i.bodyType.includes("form-data")||i.bodyType.includes("urlencoded"))&&(p.requestBody={content:{[i.bodyType]:{schema:{type:"object"}}},required:true});if(p.responses={},i?.responses)for(let[l,d]of Object.entries(i.responses))p.responses[l]={description:`Response for ${l}`,content:{"application/json":{schema:be(d)}}};if(i?.errors)for(let[l,d]of Object.entries(i.errors))p.responses[l]={description:`Error response for ${l}`,content:{"application/json":{schema:be(d)}}};if(Object.keys(p.responses).length===0&&(p.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),i?.security){let l=[];Array.isArray(i.security)||(i.security=[i.security]);for(let d of i.security)if(d.type==="bearer")o.securitySchemes.bearer||(o.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:d.bearerFormat||"JWT",description:d.description}),l.push({bearer:[]});else if(d.type==="apiKey")o.securitySchemes[d.name]||(o.securitySchemes[d.name]={type:"apiKey",name:d.name,in:d.in,description:d.description}),l.push({[d.name]:[]});else if(d.type==="oauth2"){let f=d.name||"oauth2";o.securitySchemes[f]||(o.securitySchemes[f]={type:"oauth2",flows:d.flows,description:d.description}),l.push({[f]:[]});}else if(d.type==="openIdConnect"){let f=d.name||"openIdConnect";o.securitySchemes[f]||(o.securitySchemes[f]={type:"openIdConnect",openIdConnectUrl:d.openIdConnectUrl,description:d.description}),l.push({[f]:[]});}l.length&&(p.security=l);}else s.security&&(p.security=s.security);t[n.path][a]=p;}return {openapi:"3.0.0",info:{title:s.title,description:s.description,version:s.version,...s.info},servers:s.servers?.map(n=>({url:n}))||[{url:"/"}],paths:t,components:o,security:s.security||[],tags:s.tags?Object.entries(s.tags).map(([n,i])=>({name:n,...i})):[]}}function xs(s,e){return `
308
325
  <!DOCTYPE html>
309
326
  <html lang="en">
310
327
  <head>
@@ -352,7 +369,7 @@ ${l}\r
352
369
  };
353
370
  </script>
354
371
  </body>
355
- </html>`}function xs(s,e){return `
372
+ </html>`}function Rs(s,e){return `
356
373
  <!DOCTYPE html>
357
374
  <html>
358
375
  <head>
@@ -383,7 +400,7 @@ ${l}\r
383
400
  <script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
384
401
  </body>
385
402
  </html>
386
- `}function Rs(s,e){return `
403
+ `}function Ts(s,e){return `
387
404
  <!DOCTYPE html>
388
405
  <html lang="en">
389
406
  <head>
@@ -407,7 +424,7 @@ ${l}\r
407
424
  <script src="https://unpkg.com/@scalar/api-reference@latest/dist/browser/standalone.js"></script>
408
425
  </body>
409
426
  </html>
410
- `}function Ts(s,e){return `
427
+ `}function Cs(s,e){return `
411
428
  <!DOCTYPE html>
412
429
  <html lang="en">
413
430
  <head>
@@ -434,6 +451,6 @@ ${l}\r
434
451
  <script src="https://unpkg.com/@stoplight/elements@7.7.9/web-components.min.js"></script>
435
452
  </body>
436
453
  </html>
437
- `}function fr(s,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,o;for(;(o=r.exec(s))!==null;){let n=o[1],i={type:"string"};e&&e.shape&&e.shape[n]&&(i=oe(e.shape[n])||{type:"string"}),t.push({name:n,in:"path",required:true,schema:i});}return t}var yr=s=>async(e,t,r)=>{e.timeout=false;let o=setTimeout(()=>{e.timeout=true;},s.ms);try{await r();}finally{clearTimeout(o);}};var vr=s=>{let e=s?.header??"x-forwarded-for",t=s?.trust??true,r=s?.hop??"first";return async(o,n,i)=>{if(!t)return i();let a=o.headers.get(e);if(a&&typeof a=="string"){let p=a.split(",").map(c=>c.trim()).filter(Boolean);p.length&&(o.ip=r==="first"?p[0]:p[p.length-1]);}return i()}};var wr=1024*1024,br=s=>{let t={limit:Se(s?.limit,wr)??wr,extended:s?.extended??false,charset:s?.charset??"utf8",allowEmpty:s?.allowEmpty??true,parameterLimit:s?.parameterLimit??1e3};return async(r,o,n)=>{if(!(r.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return n();try{await Cs(r,t),await n();}catch(a){if(a instanceof Error&&a.message.includes("limit")){o.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw a}}};async function Cs(s,e){let t=s.rawBody;if(t.byteLength>e.limit)throw new Error(`Body size ${t.byteLength} exceeds limit ${e.limit}`);let o=new TextDecoder(e.charset).decode(t),n=Os(o,e);s.body=n;}function Os(s,e){let t={},r=new URLSearchParams(s);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[o,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?Ps(t,o,n):t[o]=n);return t}function Ps(s,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let o=e.match(/\[([^\]]*)\]/g);if(!o){r.includes(e)||(s[e]=t);return}let n=s,i=e.split("[")[0];if(r.includes(i))return;for(let p=0;p<o.length-1;p++){let c=o[p].slice(1,-1);if(r.includes(c))return;if(n[i]||(n[i]={}),c===""){Array.isArray(n[i])||(n[i]=[]),n=n[i];continue}n[i][c]||(n[i][c]={}),n=n[i][c];}let a=o[o.length-1].slice(1,-1);if(!r.includes(a)){if(a===""){Array.isArray(n)||(n=[]),n.push(t);return}n[a]=t;}}var Ot=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),o=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),n=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:o,iterations:this.ITERATIONS,hash:"SHA-256"},n,this.KEY_LENGTH),a=this.encodeBase64(o),p=this.encodeBase64(new Uint8Array(i));return `${a}:${p}`}async compare(e,t){if(!e||!t)return false;try{let o=new TextEncoder().encode(t),n=e.split(":");if(n.length!==2)throw new Error("Invalid hash format");let[i,a]=n,p=this.decodeBase64(i),c=this.decodeBase64(a),d=await crypto.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveBits"]),l=await crypto.subtle.deriveBits({name:"PBKDF2",salt:p,iterations:this.ITERATIONS,hash:"SHA-256"},d,this.KEY_LENGTH),h=new Uint8Array(l);if(h.length!==c.length)return !1;let u=0;for(let g=0;g<h.length;g++)u|=h[g]^c[g];return u===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let o=0;o<r;o++)t+=String.fromCharCode(e[o]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,o=new Uint8Array(r);for(let n=0;n<r;n++)o[n]=t.charCodeAt(n);return o}},rt=new Ot;var st=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new z,this.ensureGraphQLHandler=Ae(this.graphql);}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...o}=e??{};this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(n,i)=>{let a=new URL(n.url),p=C.find(n.method,a.pathname);if(Q.enrichRequest(n),n.params=p?.params??{},n.query=Object.fromEntries(a.searchParams.entries()),n.ip=n.headers.get("x-forwarded-for")?.split(",")[0]??i.requestIP(n)?.address,await t?.call(this,n,i),this.graphql.isEnabled&&a.pathname.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let l=await this.ensureGraphQLHandler();if(l)return l.fetch(n,{server:i})}if(r&&n.headers.get("upgrade")==="websocket"&&i.upgrade(n,{data:{}}))return;let c=await re(p?.middleware??[],p?.handler??((l,h)=>{h.notFound({...P(new k(l.url,l.method))});}),n);return c.headers["Content-Type"]==="application/json"?Response.json(c.getBody(),{status:c.responseStatus,headers:c.headers}):new Response(c.getBody(),{status:c.responseStatus,headers:c.headers})},...r?{websocket:r}:{},...o}),this.url=this.runtimeServer.url.toString();}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.stop();}};var ot=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new z,this.ensureGraphQLHandler=Ae(this.graphql);}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{};this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(o,n)=>{let i=new URL(o.url),a=C.find(o.method,i.pathname);if(Q.enrichRequest(o),o.params=a?.params??{},o.query=Object.fromEntries(i.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.remoteAddr?.hostname,await t?.(o,n))return new Response(null,{status:426});if(this.graphql.isEnabled&&i.pathname.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let l=await this.ensureGraphQLHandler();if(l)return l.fetch(o,{info:n})}if(o.headers.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let{socket:l,response:h}=Deno.upgradeWebSocket(o);return this.tapOptions?.deno?.websocket?.open&&(l.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(l)),this.tapOptions?.deno?.websocket?.message&&(l.onmessage=u=>{this.tapOptions?.deno?.websocket?.message?.(l,u.data);}),this.tapOptions?.deno?.websocket?.close&&(l.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(l)),h}let c=await re(a?.middleware??[],a?.handler??((l,h)=>{h.notFound({...P(new k(l.url,l.method))});}),o);return c.headers["Content-Type"]==="application/json"?Response.json(c.getBody(),{status:c.responseStatus,headers:c.headers}):new Response(c.getBody(),{status:c.responseStatus,headers:c.headers})},...r}),this.url=`http://${this.host}:${this.port}`;}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.shutdown();}};async function qs(s,e){let t=s.getReader();try{for(;;){let{done:r,value:o}=await t.read();if(r){e.end();break}e.write(o);}}catch(r){e.destroy(r);}}var nt=class{port;host;url;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new z,this.ensureGraphQLHandler=Ae(this.graphql);let t=this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http";this.url=`${t}://${this.host}:${this.port}`,this.runtimeServer=this.createServer(async(r,o)=>{if(this.tapOptions&&this.tapOptions.node){let g=this.tapOptions.node;await g?.(r);}if(this.graphql.isEnabled&&r.url?.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let g=await this.ensureGraphQLHandler();if(g){g(r,o);return}}let n=C.find(r.method,r.url),i={};for(let g of Object.keys(r.headers)){if(g.startsWith(":"))continue;let b=r.headers[g];b!==void 0&&(i[g]=Array.isArray(b)?b.join(", "):b);}let a=new Q(`${this.url}${r.url}`,{method:r.method,body:se(r.method)?await this.readRequestBody(r):void 0,headers:i}),p=r.headers["x-forwarded-for"];Array.isArray(p)&&(p=p[0]),a.ip=p??r.socket.remoteAddress;let[c,d=""]=r.url?.split("?",2)??[];a.query=Object.fromEntries(new URLSearchParams(d)),a.params=n?.params??{};let l=new W;l.nodeResponse=o;let h=await re(n?.middleware??[],n?.handler??((g,b)=>{b.notFound({...P(new k(g.url,g.method))});}),a,l);if(o.headersSent||o.writableEnded)return;let u=h.getBody();if(u instanceof ReadableStream){qs(u,o);return}u instanceof Buffer||u instanceof Uint8Array||typeof u=="string"?u=u:h.headers["Content-Type"]==="application/json"&&typeof u!="string"?u=JSON.stringify(u):u=String(u),o.writeHead(h.responseStatus,h.headers),o.end(u);});}listen(){this.runtimeServer.listen(this.port,this.host);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}async readRequestBody(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>o.push(Buffer.from(n))),e.on("error",r),e.on("end",()=>t(Buffer.concat(o).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return createServer(e);if(this.nodeHttpClient==="http2")return createServer$1(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return createServer$2(this.httpsOptions,e)}};var it=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new st(e);if(e?.runtime==="node")return new nt(e);if(e?.runtime==="deno")return new ot(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};H();var Sr=["isListening","url","port","host","routes","embed","constructor","get","post","put","patch","delete","getNodeServer","getBunServer","getDenoServer","use","setErrorHandler","listen","close","tapOptions","startUpOptions","tmpDir","logger","getMockServer","useExpress","expressMiddleware","mountExpressRouter","setNotFoundHandler","setGlobalCronErrorHandler","startRegisteredCrons","bootstrap","handleNotFound","registerNotFoundRoutes","importControllers","applyPlugins"];var xr=class{isListening;isProduction;graphql;router=C;wasInitialized;serverConnector;globalMiddlewares=[];serverOptions;controllerImportBlacklistedPaths=["node_modules"];notFoundHandler;nativeEnv=new je;httpsOptions;constructor(e){this.wasInitialized=false,this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:e?.port??Number(this.nativeEnv.get("PORT"))??80,host:e?.host??this.nativeEnv.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,useBodyParser:e?.useBodyParser??true,graphql:e?.graphql??void 0},e?.ajvInstance&&N.setGlobalInstance(e.ajvInstance),this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.nativeEnv.get("NODE_ENV")==="production",this.graphql=new z(this.serverOptions.graphql),this.serverConnector=new it({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:S.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.httpsOptions,graphql:this.graphql}),this.serverOptions.useBodyParser&&this.use(zt());}get url(){return this.serverConnector.url}get port(){return this.serverConnector.port}get host(){return this.serverConnector.host}get routes(){return C.getRoutes()||[]}async hash(e){return rt.hash(e)}async compareHash(e,t){return rt.compare(e,t)}getEnvironment(){return this.nativeEnv.getEnvironment()}tmpDir(...e){return f.join("tmp",...e)}async mkdir(e,t){await m.mkdir(e,t);}get(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("GET",e,o,n,i);}post(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("POST",e,o,n,i);}patch(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("PATCH",e,o,n,i);}put(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("PUT",e,o,n,i);}delete(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("DELETE",e,o,n,i);}options(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("OPTIONS",e,o,n,i);}head(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("HEAD",e,o,n,i);}group(e,t,r){this.router.group(e,t,r);}getNodeServer(){if(S.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.serverConnector.getServer("node")}getBunServer(){if(S.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.serverConnector.getServer("bun")}getDenoServer(){if(S.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.serverConnector.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(Sr.includes(e))throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property.`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){switch(S.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${S.type}`)}}on(e,t){switch(S.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${S.type}, only node, bun and deno are supported`)}}once(e,t){switch(S.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${S.type}, only node, bun and deno are supported`)}}use(...e){this.globalMiddlewares.push(...e);}useExpress(e,t){rr(this).use(e,t);}expressMiddleware(e){return ke(e)}mountExpressRouter(e,t){Ye(e,t);}setErrorHandler(e){this.globalMiddlewares.unshift(async(t,r,o)=>{try{await o();}catch(n){await e?.(t,r,o,n);}});}setNotFoundHandler(e){this.notFoundHandler=e?.bind(this);}listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");this.bootstrap().then(()=>{this.serverConnector.listen(),this.isListening=true,this.serverOptions.swagger&&gr(this.serverOptions.swagger),e?.({port:this.port,host:this.host,url:this.url});});}async close(){await this.serverConnector.close(),this.isListening=false;}async getMockServer(e){return await this.bootstrap(e),new Je(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns,r=await Promise.all(t.map(async o=>glob(o,{absolute:true,cwd:M.getCwd()}))).then(o=>o.flat());r=r.flat(),r=r.filter(o=>!this.controllerImportBlacklistedPaths.some(n=>o.includes(n))),y.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async o=>{y.debug(`Importing controller ${o}`),await import(o).catch(n=>{y.error(`Error importing controller ${o}: ${n}`);});}));}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return {middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "cors":this.use(Wt(r));break;case "json":this.use(cr(r));break;case "static":this.use(Qt(r));break;case "fileParser":this.use(ir(r));break;case "helmet":this.use(ar(r));break;case "cookie":this.use(Zt(r));break;case "methodOverride":this.use(ur(r));break;case "compression":this.use(Gt(r));break;case "log":this.use(lr(r));break;case "rateLimiter":let{keyOptions:o,storageOptions:n}=r;this.use(mr(o,n));break;case "urlencoded":this.use(br(r));break;case "trustProxy":this.use(vr(r));break;case "timeout":this.use(yr(r));break;case "session":this.use(hr(r));break;case "asyncLocalStorage":this.use(Rt(r));break;default:y.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.wasInitialized||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.registerNotFoundRoutes(),this.globalMiddlewares.length&&C.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares),this.wasInitialized=true);}handleNotFound=(e,t)=>{if(this.notFoundHandler){this.notFoundHandler(e,t);return}let r=new URL(e.url).pathname,o=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"],n=[];for(let a of o){if(a===e.method.toUpperCase())continue;let p=C.find(a,r);p&&p.handler!==this.handleNotFound&&n.push(a);}if(n.length){t.setHeader("Allow",n.join(", "));let a=new Ee(r,e.method);t.methodNotAllowed({...P(a)});return}let i=new k(r,e.method);t.notFound({...P(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)C.addOrUpdate(t,"*",[],this.handleNotFound,{excludeFromSwagger:true});}};var G=class extends x{constructor(e){super(`File not found: ${e}`);}};var Rr=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),o=new Date(Date.now()-300*1e3),n=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:o,expiresOn:n},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),o=new Date(Date.now()-300*1e3),n=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:o,expiresOn:n},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let o of this.containerClient.listBlobsFlat({prefix:r}))t.push(o.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let o=await this.containerClient.getBlockBlobClient(e).download();if(!o.readableStreamBody)throw new G(e);let n=t;if(n==="stream")return Readable.toWeb(o.readableStreamBody);let i=[];for await(let p of o.readableStreamBody)i.push(Buffer.isBuffer(p)?p:Buffer.from(p));let a=Buffer.concat(i);switch(n){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new x("Invalid return type")}}catch(r){throw r.statusCode===404?new G(e):r}}async putObject(e,t,r){await this.ensureClient();let o=this.containerClient.getBlockBlobClient(e),n=t;await o.upload(n,n.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new x("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new x("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var Tr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new x("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new x("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=f.resolve(this.options.directory),r=e?f.join(t,e):t;if(!await m.exists(r))return [];let n=[];return await this.listFilesRecursively(r,t,n),n}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=f.join(this.options.directory,e);if(!await m.exists(r))throw new G(e);switch(t){case "raw":return await m.readFile(r);case "text":return await m.readFile(r,{encoding:"utf8"});case "stream":return await m.streamFile(r);default:throw new x("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let o=f.join(this.options.directory,e),n=f.join(o,"..");await m.mkdir(n,{recursive:true}),await m.writeFile(o,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=f.join(this.options.directory,e);await m.exists(t)&&await m.unlink(t);}async listFilesRecursively(e,t,r){let o=await m.stat(e);if(o.isFile){let i=e.replace(t,"").replace(/^\//,"");r.push(i);return}if(!o.isDirectory)return;let n=await this.readDirectory(e);for(let i of n){let a=f.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(H(),Mt));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let o of Deno.readDir(e))r.push(o.name);return r}default:throw new x("Unsupported runtime")}}async ensureDirectoryExists(){await m.exists(this.options.directory)||(await m.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true);}};var Cr=class{options;constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),!this.options.cloudfrontOptions)throw new x("getDownloadUrl requires CloudFront configuration");let{domainName:r,keyPairId:o,privateKey:n}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:o,privateKey:n,dateLessThan:a})}async getUploadUrl(e,t=3600){await this.ensureClient();let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async listObjects(e){await this.ensureClient();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(o=>o.Key).filter(Boolean)??[]}async getObject(e,t="raw"){await this.ensureClient();let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let o=await this.s3Client.send(r);if(!o.Body)throw new G(e);switch(t){case "raw":return await o.Body.transformToByteArray();case "text":return await o.Body.transformToString();case "stream":return o.Body.transformToWebStream();default:throw new x("Invalid return type")}}catch(o){throw o.name==="NoSuchKey"?new G(e):o}}async putObject(e,t,r){await this.ensureClient();let o=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(o);}async deleteObject(e){await this.ensureClient();let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default).catch(()=>{throw new x("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default).catch(()=>{throw new x("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default).catch(()=>{throw new x("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var Or=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,o])=>[r,o]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var Pr=class{};var jr=s=>(e,t)=>(r,o,n)=>{let i={scope:e,handler:t,manager:s};if(typeof o>"u"){let p=v.get(r.prototype,"__class__");return p||(p={policies:[]}),p.policies||(p.policies=[]),p.policies.push(i),v.set(r.prototype,"__class__",p),r}let a=v.get(r,o);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),v.set(r,o,a),n};var Er=class{providers;constructor(e){this.providers=e;}createDecorator(){return jr(this)}canAccess(e,t,...r){let o=this.providers[e];if(!o)throw new x(`Policy provider for ${String(e)} not found`);return o[t](...r)}};var Dl=C;
438
- export{ao as ARG_SYMBOL,Rr as AzureBlobStorageProvider,Ht as BaseCron,Dt as BaseMqtt,Pr as BasePlugin,Ft as BaseQueue,Ue as BullMQPubSub,O as Command,bt as CommandRegistry,be as CronService,z as GraphQL,Tr as LocalStorageProvider,$e as MqttService,Qe as PGBossPubSub,Er as PolicyManager,ee as QueueManager,Ge as QueueService,Q as Request,W as Response,Cr as S3StorageProvider,ze as SQSPubSub,xr as Server,Or as Storage,ae as VALIDATION_ERROR_SYMBOL,A as arg,Rt as asyncLocalStorage,qe as asyncStorage,Zr as baseCommands,Pe as commandRegistry,Gt as compression,So as controller,Zt as cookie,Wt as cors,rr as createExpressAdapter,jr as createPolicyDecorator,Vs as cron,Ls as defineLoggerConfig,Yn as defineQueueConfiguration,To as del,ds as expressHandler,ke as expressMiddleware,ir as fileParser,T as flag,Po as get,xt as getContentType,rt as hash,ar as helmet,cr as json,lr as log,y as logger,ur as methodOverride,Do as middleware,Ye as mountExpressRouter,Bn as mqtt,Mo as patch,ko as post,Gn as publish,No as put,Te as queue,mr as rateLimiter,Dl as router,Yo as serialize,Qt as serveStatic,hr as session,Gs as setCronGlobalErrorHandler,Fn as setMqttGlobalErrorHandler,yr as timeout,vr as trustProxy,br as urlencoded,rn as validate};//# sourceMappingURL=index.js.map
454
+ `}function gr(s,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,o;for(;(o=r.exec(s))!==null;){let n=o[1],i={type:"string"};e&&e.shape&&e.shape[n]&&(i=be(e.shape[n])||{type:"string"}),t.push({name:n,in:"path",required:true,schema:i});}return t}var vr=s=>async(e,t,r)=>{e.timeout=false;let o=setTimeout(()=>{e.timeout=true;},s.ms);try{await r();}finally{clearTimeout(o);}};var wr=s=>{let e=s?.header??"x-forwarded-for",t=s?.trust??true,r=s?.hop??"first";return async(o,n,i)=>{if(!t)return i();let a=o.headers.get(e);if(a&&typeof a=="string"){let p=a.split(",").map(c=>c.trim()).filter(Boolean);p.length&&(o.ip=r==="first"?p[0]:p[p.length-1]);}return i()}};var br=1024*1024,Sr=s=>{let t={limit:xe(s?.limit,br)??br,extended:s?.extended??false,charset:s?.charset??"utf8",allowEmpty:s?.allowEmpty??true,parameterLimit:s?.parameterLimit??1e3};return async(r,o,n)=>{if(!(r.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return n();try{await Os(r,t),await n();}catch(a){if(a instanceof Error&&a.message.includes("limit")){o.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw a}}};async function Os(s,e){let t=s.rawBody;if(t.byteLength>e.limit)throw new Error(`Body size ${t.byteLength} exceeds limit ${e.limit}`);let o=new TextDecoder(e.charset).decode(t),n=Ps(o,e);s.body=n;}function Ps(s,e){let t={},r=new URLSearchParams(s);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[o,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?js(t,o,n):t[o]=n);return t}function js(s,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let o=e.match(/\[([^\]]*)\]/g);if(!o){r.includes(e)||(s[e]=t);return}let n=s,i=e.split("[")[0];if(r.includes(i))return;for(let p=0;p<o.length-1;p++){let c=o[p].slice(1,-1);if(r.includes(c))return;if(n[i]||(n[i]={}),c===""){Array.isArray(n[i])||(n[i]=[]),n=n[i];continue}n[i][c]||(n[i][c]={}),n=n[i][c];}let a=o[o.length-1].slice(1,-1);if(!r.includes(a)){if(a===""){Array.isArray(n)||(n=[]),n.push(t);return}n[a]=t;}}var Pt=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),o=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),n=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:o,iterations:this.ITERATIONS,hash:"SHA-256"},n,this.KEY_LENGTH),a=this.encodeBase64(o),p=this.encodeBase64(new Uint8Array(i));return `${a}:${p}`}async compare(e,t){if(!e||!t)return false;try{let o=new TextEncoder().encode(t),n=e.split(":");if(n.length!==2)throw new Error("Invalid hash format");let[i,a]=n,p=this.decodeBase64(i),c=this.decodeBase64(a),l=await crypto.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveBits"]),d=await crypto.subtle.deriveBits({name:"PBKDF2",salt:p,iterations:this.ITERATIONS,hash:"SHA-256"},l,this.KEY_LENGTH),f=new Uint8Array(d);if(f.length!==c.length)return !1;let m=0;for(let g=0;g<f.length;g++)m|=f[g]^c[g];return m===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let o=0;o<r;o++)t+=String.fromCharCode(e[o]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,o=new Uint8Array(r);for(let n=0;n<r;n++)o[n]=t.charCodeAt(n);return o}},st=new Pt;var ot=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new K,this.ensureGraphQLHandler=qe(this.graphql);}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...o}=e??{};this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(n,i)=>{let a=new URL(n.url),p=O.find(n.method,a.pathname);if(G.enrichRequest(n),n.params=p?.params??{},n.query=Object.fromEntries(a.searchParams.entries()),n.ip=n.headers.get("x-forwarded-for")?.split(",")[0]??i.requestIP(n)?.address,await t?.call(this,n,i),this.graphql.isEnabled&&a.pathname.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let d=await this.ensureGraphQLHandler();if(d)return d.fetch(n,{server:i})}if(r&&n.headers.get("upgrade")==="websocket"&&i.upgrade(n,{data:{}}))return;let c=await se(p?.middleware??[],p?.handler??((d,f)=>{f.notFound({...M(new _(d.url,d.method))});}),n);return c.headers["Content-Type"]==="application/json"?Response.json(c.getBody(),{status:c.responseStatus,headers:c.headers}):new Response(c.getBody(),{status:c.responseStatus,headers:c.headers})},...r?{websocket:r}:{},...o}),this.url=this.runtimeServer.url.toString();}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.stop();}};var nt=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new K,this.ensureGraphQLHandler=qe(this.graphql);}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{};this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(o,n)=>{let i=new URL(o.url),a=O.find(o.method,i.pathname);if(G.enrichRequest(o),o.params=a?.params??{},o.query=Object.fromEntries(i.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.remoteAddr?.hostname,await t?.(o,n))return new Response(null,{status:426});if(this.graphql.isEnabled&&i.pathname.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let d=await this.ensureGraphQLHandler();if(d)return d.fetch(o,{info:n})}if(o.headers.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let{socket:d,response:f}=Deno.upgradeWebSocket(o);return this.tapOptions?.deno?.websocket?.open&&(d.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(d)),this.tapOptions?.deno?.websocket?.message&&(d.onmessage=m=>{this.tapOptions?.deno?.websocket?.message?.(d,m.data);}),this.tapOptions?.deno?.websocket?.close&&(d.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(d)),f}let c=await se(a?.middleware??[],a?.handler??((d,f)=>{f.notFound({...M(new _(d.url,d.method))});}),o);return c.headers["Content-Type"]==="application/json"?Response.json(c.getBody(),{status:c.responseStatus,headers:c.headers}):new Response(c.getBody(),{status:c.responseStatus,headers:c.headers})},...r}),this.url=`http://${this.host}:${this.port}`;}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.shutdown();}};async function ks(s,e){let t=s.getReader();try{for(;;){let{done:r,value:o}=await t.read();if(r){e.end();break}e.write(o);}}catch(r){e.destroy(r);}}var it=class{port;host;url;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new K,this.ensureGraphQLHandler=qe(this.graphql);let t=this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http";this.url=`${t}://${this.host}:${this.port}`,this.runtimeServer=this.createServer(async(r,o)=>{if(this.tapOptions&&this.tapOptions.node){let g=this.tapOptions.node;await g?.(r);}if(this.graphql.isEnabled&&r.url?.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let g=await this.ensureGraphQLHandler();if(g){g(r,o);return}}let n=O.find(r.method,r.url),i={};for(let g of Object.keys(r.headers)){if(g.startsWith(":"))continue;let S=r.headers[g];S!==void 0&&(i[g]=Array.isArray(S)?S.join(", "):S);}let a=new G(`${this.url}${r.url}`,{method:r.method,body:oe(r.method)?await this.readRequestBody(r):void 0,headers:i}),p=r.headers["x-forwarded-for"];Array.isArray(p)&&(p=p[0]),a.ip=p??r.socket.remoteAddress;let[c,l=""]=r.url?.split("?",2)??[];a.query=Object.fromEntries(new URLSearchParams(l)),a.params=n?.params??{};let d=new Y;d.nodeResponse=o;let f=await se(n?.middleware??[],n?.handler??((g,S)=>{S.notFound({...M(new _(g.url,g.method))});}),a,d);if(o.headersSent||o.writableEnded)return;let m=f.getBody();if(m instanceof ReadableStream){ks(m,o);return}m instanceof Buffer||m instanceof Uint8Array||typeof m=="string"?m=m:f.headers["Content-Type"]==="application/json"&&typeof m!="string"?m=JSON.stringify(m):m=String(m),o.writeHead(f.responseStatus,f.headers),o.end(m);});}listen(){this.runtimeServer.listen(this.port,this.host);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}async readRequestBody(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>o.push(Buffer.from(n))),e.on("error",r),e.on("end",()=>t(Buffer.concat(o).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return createServer(e);if(this.nodeHttpClient==="http2")return createServer$1(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return createServer$2(this.httpsOptions,e)}};var at=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new ot(e);if(e?.runtime==="node")return new it(e);if(e?.runtime==="deno")return new nt(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};F();var xr=["isListening","url","port","host","routes","embed","constructor","get","post","put","patch","delete","getNodeServer","getBunServer","getDenoServer","use","setErrorHandler","listen","close","tapOptions","startUpOptions","tmpDir","logger","getMockServer","useExpress","expressMiddleware","mountExpressRouter","setNotFoundHandler","setGlobalCronErrorHandler","startRegisteredCrons","bootstrap","handleNotFound","registerNotFoundRoutes","importControllers","applyPlugins"];var Rr=class{isListening;isProduction;graphql;router=O;wasInitialized;serverConnector;globalMiddlewares=[];serverOptions;controllerImportBlacklistedPaths=["node_modules"];notFoundHandler;nativeEnv=new Ee;httpsOptions;constructor(e){this.wasInitialized=false,this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:e?.port??Number(this.nativeEnv.get("PORT"))??80,host:e?.host??this.nativeEnv.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,useBodyParser:e?.useBodyParser??true,graphql:e?.graphql??void 0},e?.ajvInstance&&B.setGlobalInstance(e.ajvInstance),this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.nativeEnv.get("NODE_ENV")==="production",this.graphql=new K(this.serverOptions.graphql),this.serverConnector=new at({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:R.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.httpsOptions,graphql:this.graphql}),this.serverOptions.useBodyParser&&this.use(Gt());}get url(){return this.serverConnector.url}get port(){return this.serverConnector.port}get host(){return this.serverConnector.host}get routes(){return O.getRoutes()||[]}async hash(e){return st.hash(e)}async compareHash(e,t){return st.compare(e,t)}getEnvironment(){return this.nativeEnv.getEnvironment()}tmpDir(...e){return h.join("tmp",...e)}async mkdir(e,t){await u.mkdir(e,t);}get(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);O.addOrUpdate("GET",e,o,n,i);}post(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);O.addOrUpdate("POST",e,o,n,i);}patch(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);O.addOrUpdate("PATCH",e,o,n,i);}put(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);O.addOrUpdate("PUT",e,o,n,i);}delete(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);O.addOrUpdate("DELETE",e,o,n,i);}options(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);O.addOrUpdate("OPTIONS",e,o,n,i);}head(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);O.addOrUpdate("HEAD",e,o,n,i);}group(e,t,r){this.router.group(e,t,r);}getNodeServer(){if(R.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.serverConnector.getServer("node")}getBunServer(){if(R.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.serverConnector.getServer("bun")}getDenoServer(){if(R.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.serverConnector.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(xr.includes(e))throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property.`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){switch(R.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${R.type}`)}}on(e,t){switch(R.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${R.type}, only node, bun and deno are supported`)}}once(e,t){switch(R.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${R.type}, only node, bun and deno are supported`)}}use(...e){this.globalMiddlewares.push(...e);}useExpress(e,t){sr(this).use(e,t);}expressMiddleware(e){return $e(e)}mountExpressRouter(e,t){Xe(e,t);}setErrorHandler(e){this.globalMiddlewares.unshift(async(t,r,o)=>{try{await o();}catch(n){await e?.(t,r,o,n);}});}setNotFoundHandler(e){this.notFoundHandler=e?.bind(this);}listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");this.bootstrap().then(()=>{this.serverConnector.listen(),this.isListening=true,this.serverOptions.swagger&&yr(this.serverOptions.swagger),e?.({port:this.port,host:this.host,url:this.url});});}async close(){await this.serverConnector.close(),this.isListening=false;}async getMockServer(e){return await this.bootstrap(e),new Ye(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns,r=await Promise.all(t.map(async o=>glob(o,{absolute:true,cwd:k.getCwd()}))).then(o=>o.flat());r=r.flat(),r=r.filter(o=>!this.controllerImportBlacklistedPaths.some(n=>o.includes(n))),v.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async o=>{v.debug(`Importing controller ${o}`),await import(o).catch(n=>{v.error(`Error importing controller ${o}: ${n}`);});}));}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return {middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "cors":this.use(Jt(r));break;case "json":this.use(lr(r));break;case "static":this.use(zt(r));break;case "fileParser":this.use(ar(r));break;case "helmet":this.use(pr(r));break;case "cookie":this.use(Zt(r));break;case "methodOverride":this.use(mr(r));break;case "compression":this.use(Kt(r));break;case "log":this.use(ur(r));break;case "rateLimiter":let{keyOptions:o,storageOptions:n}=r;this.use(hr(o,n));break;case "urlencoded":this.use(Sr(r));break;case "trustProxy":this.use(wr(r));break;case "timeout":this.use(vr(r));break;case "session":this.use(fr(r));break;case "asyncLocalStorage":this.use(Tt(r));break;default:v.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.wasInitialized||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.registerNotFoundRoutes(),this.globalMiddlewares.length&&O.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares),this.wasInitialized=true);}handleNotFound=(e,t)=>{if(this.notFoundHandler){this.notFoundHandler(e,t);return}let r=new URL(e.url).pathname,o=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"],n=[];for(let a of o){if(a===e.method.toUpperCase())continue;let p=O.find(a,r);p&&p.handler!==this.handleNotFound&&n.push(a);}if(n.length){t.setHeader("Allow",n.join(", "));let a=new Ae(r,e.method);t.methodNotAllowed({...M(a)});return}let i=new _(r,e.method);t.notFound({...M(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)O.addOrUpdate(t,"*",[],this.handleNotFound,{excludeFromSwagger:true});}};var V=class extends T{constructor(e){super(`File not found: ${e}`);}};var Tr=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),o=new Date(Date.now()-300*1e3),n=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:o,expiresOn:n},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),o=new Date(Date.now()-300*1e3),n=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:o,expiresOn:n},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let o of this.containerClient.listBlobsFlat({prefix:r}))t.push(o.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let o=await this.containerClient.getBlockBlobClient(e).download();if(!o.readableStreamBody)throw new V(e);let n=t;if(n==="stream")return Readable.toWeb(o.readableStreamBody);let i=[];for await(let p of o.readableStreamBody)i.push(Buffer.isBuffer(p)?p:Buffer.from(p));let a=Buffer.concat(i);switch(n){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new T("Invalid return type")}}catch(r){throw r.statusCode===404?new V(e):r}}async putObject(e,t,r){await this.ensureClient();let o=this.containerClient.getBlockBlobClient(e),n=t;await o.upload(n,n.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new T("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new T("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var Cr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new T("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new T("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=h.resolve(this.options.directory),r=e?h.join(t,e):t;if(!await u.exists(r))return [];let n=[];return await this.listFilesRecursively(r,t,n),n}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=h.join(this.options.directory,e);if(!await u.exists(r))throw new V(e);switch(t){case "raw":return await u.readFile(r);case "text":return await u.readFile(r,{encoding:"utf8"});case "stream":return await u.streamFile(r);default:throw new T("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let o=h.join(this.options.directory,e),n=h.join(o,"..");await u.mkdir(n,{recursive:true}),await u.writeFile(o,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=h.join(this.options.directory,e);await u.exists(t)&&await u.unlink(t);}async listFilesRecursively(e,t,r){let o=await u.stat(e);if(o.isFile){let i=e.replace(t,"").replace(/^\//,"");r.push(i);return}if(!o.isDirectory)return;let n=await this.readDirectory(e);for(let i of n){let a=h.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(F(),Mt));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let o of Deno.readDir(e))r.push(o.name);return r}default:throw new T("Unsupported runtime")}}async ensureDirectoryExists(){await u.exists(this.options.directory)||(await u.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true);}};var Or=class{options;constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),!this.options.cloudfrontOptions)throw new T("getDownloadUrl requires CloudFront configuration");let{domainName:r,keyPairId:o,privateKey:n}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:o,privateKey:n,dateLessThan:a})}async getUploadUrl(e,t=3600){await this.ensureClient();let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async listObjects(e){await this.ensureClient();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(o=>o.Key).filter(Boolean)??[]}async getObject(e,t="raw"){await this.ensureClient();let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let o=await this.s3Client.send(r);if(!o.Body)throw new V(e);switch(t){case "raw":return await o.Body.transformToByteArray();case "text":return await o.Body.transformToString();case "stream":return o.Body.transformToWebStream();default:throw new T("Invalid return type")}}catch(o){throw o.name==="NoSuchKey"?new V(e):o}}async putObject(e,t,r){await this.ensureClient();let o=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(o);}async deleteObject(e){await this.ensureClient();let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default).catch(()=>{throw new T("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default).catch(()=>{throw new T("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default).catch(()=>{throw new T("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var Pr=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,o])=>[r,o]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var jr=class{};var Er=s=>(e,t)=>(r,o,n)=>{let i={scope:e,handler:t,manager:s};if(typeof o>"u"){let p=w.get(r.prototype,"__class__");return p||(p={policies:[]}),p.policies||(p.policies=[]),p.policies.push(i),w.set(r.prototype,"__class__",p),r}let a=w.get(r,o);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),w.set(r,o,a),n};var Ar=class{providers;constructor(e){this.providers=e;}createDecorator(){return Er(this)}canAccess(e,t,...r){let o=this.providers[e];if(!o)throw new T(`Policy provider for ${String(e)} not found`);return o[t](...r)}};var Zd=O;
455
+ export{po as ARG_SYMBOL,Tr as AzureBlobStorageProvider,Nt as BaseCron,Ft as BaseMqtt,jr as BasePlugin,Bt as BaseQueue,Qe as BullMQPubSub,P as Command,St as CommandRegistry,Se as CronService,K as GraphQL,Cr as LocalStorageProvider,He as MqttService,ze as PGBossPubSub,Ar as PolicyManager,te as QueueManager,Ke as QueueService,G as Request,Y as Response,Or as S3StorageProvider,Ge as SQSPubSub,Rr as Server,Pr as Storage,ae as VALIDATION_ERROR_SYMBOL,q as arg,Tt as asyncLocalStorage,ke as asyncStorage,Wr as baseCommands,je as commandRegistry,Kt as compression,xo as controller,Zt as cookie,Jt as cors,sr as createExpressAdapter,Er as createPolicyDecorator,Ws as cron,Ds as defineLoggerConfig,Xn as defineQueueConfiguration,Co as del,us as expressHandler,$e as expressMiddleware,ar as fileParser,x as flag,jo as get,Rt as getContentType,st as hash,pr as helmet,lr as json,ur as log,v as logger,mr as methodOverride,Fo as middleware,Xe as mountExpressRouter,In as mqtt,Mo as patch,$o as post,Kn as publish,_o as put,Ce as queue,hr as rateLimiter,Zd as router,Xo as serialize,zt as serveStatic,fr as session,Ks as setCronGlobalErrorHandler,Bn as setMqttGlobalErrorHandler,vr as timeout,wr as trustProxy,Sr as urlencoded,sn as validate};//# sourceMappingURL=index.js.map
439
456
  //# sourceMappingURL=index.js.map