@elysiumjs/core 0.5.1 → 0.5.2

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/dist/env.d.ts CHANGED
@@ -1,8 +1,4 @@
1
- /**
2
- * The type for all registered environment variables.
3
- * @author Axel Nana <axel.nana@workbud.com>
4
- */
5
- export type AppEnv = Record<string, unknown>;
1
+ import type { AppEnv } from '.';
6
2
  /**
7
3
  * Initializes the environment variables.
8
4
  * @author Axel Nana <axel.nana@workbud.com>
package/dist/http.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import type { Context as ElysiaContext, Handler, HTTPMethod, SingletonBase, TSchema } from 'elysia';
1
+ import type { Context as ElysiaContext, Handler, HTTPMethod, TSchema } from 'elysia';
2
2
  import type { Class, MergeDeep } from 'type-fest';
3
+ import type { AppHttpContext } from '.';
3
4
  import type { Module } from './module';
4
5
  import { Elysia } from 'elysia';
5
6
  /**
@@ -30,12 +31,6 @@ export type ValidatorClass<T extends TSchema = TSchema> = {
30
31
  */
31
32
  validate(ctx: Context<T['static']>): Promise<boolean>;
32
33
  };
33
- /**
34
- * The type for the context of the application.
35
- * @author Axel Nana <axel.nana@workbud.com>
36
- */
37
- export interface AppHttpContext extends SingletonBase {
38
- }
39
34
  /**
40
35
  * Metadata for the HTTP context.
41
36
  * @author Axel Nana <axel.nana@workbud.com>
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { SingletonBase } from 'elysia';
1
2
  import './macros';
2
3
  export { type Elysia, type TSchema, type Static, t } from 'elysia';
3
4
  export { type AppContext, type ElysiumPlugin, Application } from './app';
@@ -18,3 +19,14 @@ export { ServiceScope, Service } from './service';
18
19
  export { type WampRegistrationOptions, type WampSubscriptionOptions, type WampProps, type WampRegistrationHandlerArgs, type WampSubscriptionHandlerArgs, type WampRegistrationHandler, type WampSubscriptionHandler, Wamp } from './wamp';
19
20
  export { type WS, type WSError, Websocket } from './websocket';
20
21
  export { type QueueOptions, WorkerPool, Worker } from './worker';
22
+ /**
23
+ * The type for the context of the application.
24
+ * @author Axel Nana <axel.nana@workbud.com>
25
+ */
26
+ export interface AppHttpContext extends SingletonBase {
27
+ }
28
+ /**
29
+ * The type for all registered environment variables.
30
+ * @author Axel Nana <axel.nana@workbud.com>
31
+ */
32
+ export type AppEnv = Record<string, unknown>;
package/dist/index.js CHANGED
@@ -1,19 +1,19 @@
1
1
  // @bun
2
- var Z0=Object.defineProperty;var $0=(L,Y)=>{for(var Q in Y)Z0(L,Q,{get:Y[Q],enumerable:!0,configurable:!0,set:(X)=>Y[Q]=()=>X})};var $2=(L,Y)=>()=>(L&&(Y=L(L=0)),Y);import*as D2 from"readline";import{isEmpty as U0,omit as _0}from"radash";class k{static SPACE_WIDTH=60;write(L,Y=!0,Q=process.stdout){Q.write(L+(Y?`
2
+ var $X=Object.defineProperty;var _X=(Q,X)=>{for(var Y in X)$X(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:(Z)=>X[Y]=()=>Z})};var _Q=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);import*as WQ from"readline";import{isEmpty as UX,omit as GX}from"radash";class k{static SPACE_WIDTH=60;write(Q,X=!0,Y=process.stdout){Y.write(Q+(X?`
3
3
  `:""))}newLine(){this.write(`
4
- `,!1)}info(L){this.write(`${this.format("\u2139",4)} ${L}`)}success(L){this.write(`${this.format("\u2714",2)} ${L}`)}warning(L){this.write(`${this.format("\u26A0",3)} ${L}`)}error(L){this.write(`${this.format("\u2716",1)} ${L}`,!0,process.stderr)}debug(L){if(process.env.DEBUG)this.write(`\uD83D\uDD0D ${L}`)}trace(L,Y){if(!L)return;let Q=L.name||"Error",X=L.message||"An error occurred",Z=L.stack||"";if(Y)this.title(Y);else this.newLine();if(this.write(this.format(`${Q}: ${X}`,1)),L.stack)this.write(this.format("Stack Trace:",9)),this.write(this.format(Z.split(`
4
+ `,!1)}info(Q){this.write(`${this.format("\u2139",4)} ${Q}`)}success(Q){this.write(`${this.format("\u2714",2)} ${Q}`)}warning(Q){this.write(`${this.format("\u26A0",3)} ${Q}`)}error(Q){this.write(`${this.format("\u2716",1)} ${Q}`,!0,process.stderr)}debug(Q){if(process.env.DEBUG)this.write(`\uD83D\uDD0D ${Q}`)}trace(Q,X){if(!Q)return;let Y=Q.name||"Error",Z=Q.message||"An error occurred",$=Q.stack||"";if(X)this.title(X);else this.newLine();if(this.write(this.format(`${Y}: ${Z}`,1)),Q.stack)this.write(this.format("Stack Trace:",9)),this.write(this.format($.split(`
5
5
  `).map((U)=>` ${U}`).join(`
6
- `),8));let $=_0(L,["name","message","stack"]);if(!U0($))this.write(this.format("Additional Information:",9)),Object.keys($).forEach((U)=>{let _=L[U];this.write(` ${U}: ${JSON.stringify(_)}`)});this.newLine()}title(L){this.newLine(),this.write(this.format(L,9,10)),this.newLine()}section(L){this.newLine(),this.write(`\x1B[1m${L}\x1B[0m`)}table(L,Y){if(L.length===0){this.info("No data to display");return}let Q=Object.keys(Y||L[0]),X={};for(let U of Q){let _=Y?.[U];if(_?.width){X[U]=_.width;continue}let V=(_?.header||String(U)).length,H=Math.max(...L.map((G)=>{let R=G[U];if(_?.format)return _.format(R).length;return String(R===null||R===void 0?"":R).length}));X[U]=Math.max(V,H)}let Z="",$="";for(let U of Q){let V=Y?.[U]?.header||String(U),H=X[U];Z+=`| ${V.padEnd(H)} `,$+=`| ${"-".repeat(H)} `}Z+="|",$+="|",this.write(Z),this.write($);for(let U of L){let _="";for(let V of Q){let H=Y?.[V],G=X[V],R=U[V],W;if(H?.format)W=H.format(R);else W=String(R===null||R===void 0?"":R);_+=`| ${W.padEnd(G)} `}_+="|",this.write(_)}this.newLine()}format(L,...Y){return`${Y.map((X)=>G0[X]).join("")}${L}\x1B[0m`}bold(L){return this.format(L,9)}italic(L){return this.format(L,11)}underline(L){return this.format(L,10)}clear(){process.stdout.write("\x1Bc")}moveCursor(L,Y){process.stdout.moveCursor(L,Y)}clearLine(){process.stdout.clearLine(0),process.stdout.cursorTo(0)}async prompt(L,Y){let Q=D2.createInterface({input:process.stdin,output:process.stdout}),X=Y?` (default: ${Y})`:"";return new Promise((Z)=>{Q.question(`${L}${X}: `,($)=>{Q.close(),Z($||Y||"")})})}async promptPassword(L){let Y=D2.createInterface({input:process.stdin,output:process.stdout});return process.stdin.setRawMode?.(!0),new Promise((Q)=>{let X="";process.stdout.write(`${L}: `),process.stdin.on("data",(Z)=>{let $=Z.toString();if($==="\r"||$===`
6
+ `),8));let _=GX(Q,["name","message","stack"]);if(!UX(_))this.write(this.format("Additional Information:",9)),Object.keys(_).forEach((U)=>{let G=Q[U];this.write(` ${U}: ${JSON.stringify(G)}`)});this.newLine()}title(Q){this.newLine(),this.write(this.format(Q,9,10)),this.newLine()}section(Q){this.newLine(),this.write(`\x1B[1m${Q}\x1B[0m`)}table(Q,X){if(Q.length===0){this.info("No data to display");return}let Y=Object.keys(X||Q[0]),Z={};for(let U of Y){let G=X?.[U];if(G?.width){Z[U]=G.width;continue}let M=(G?.header||String(U)).length,H=Math.max(...Q.map((L)=>{let z=L[U];if(G?.format)return G.format(z).length;return String(z===null||z===void 0?"":z).length}));Z[U]=Math.max(M,H)}let $="",_="";for(let U of Y){let M=X?.[U]?.header||String(U),H=Z[U];$+=`| ${M.padEnd(H)} `,_+=`| ${"-".repeat(H)} `}$+="|",_+="|",this.write($),this.write(_);for(let U of Q){let G="";for(let M of Y){let H=X?.[M],L=Z[M],z=U[M],R;if(H?.format)R=H.format(z);else R=String(z===null||z===void 0?"":z);G+=`| ${R.padEnd(L)} `}G+="|",this.write(G)}this.newLine()}format(Q,...X){return`${X.map((Z)=>LX[Z]).join("")}${Q}\x1B[0m`}bold(Q){return this.format(Q,9)}italic(Q){return this.format(Q,11)}underline(Q){return this.format(Q,10)}clear(){process.stdout.write("\x1Bc")}moveCursor(Q,X){process.stdout.moveCursor(Q,X)}clearLine(){process.stdout.clearLine(0),process.stdout.cursorTo(0)}async prompt(Q,X){let Y=WQ.createInterface({input:process.stdin,output:process.stdout}),Z=X?` (default: ${X})`:"";return new Promise(($)=>{Y.question(`${Q}${Z}: `,(_)=>{Y.close(),$(_||X||"")})})}async promptPassword(Q){let X=WQ.createInterface({input:process.stdin,output:process.stdout});return process.stdin.setRawMode?.(!0),new Promise((Y)=>{let Z="";process.stdout.write(`${Q}: `),process.stdin.on("data",($)=>{let _=$.toString();if(_==="\r"||_===`
7
7
  `){process.stdout.write(`
8
- `),process.stdin.setRawMode?.(!1),process.stdin.removeAllListeners("data"),Y.close(),Q(X);return}if($==="\b"||$==="\x7F"){if(X.length>0)X=X.slice(0,-1),process.stdout.write("\b \b");return}X+=$,process.stdout.write("*")})})}async confirm(L,Y=!1){let Q=Y?"Y/n":"y/N",X=await this.prompt(`${L} [${Q}]`);if(!X)return Y;return X.toLowerCase()==="y"||X.toLowerCase()==="yes"}async select(L,Y,Q=0){if(Y.length===0)throw new Error("No options provided for selection");this.write(L),Y.forEach(($,U)=>{let _=U===Q;this.write(` ${U+1}. ${$}${_?" (default)":""}`)});let X=await this.prompt("Enter your choice (number)");if(!X)return Y[Q];let Z=parseInt(X,10)-1;if(isNaN(Z)||Z<0||Z>=Y.length)return this.warning(`Invalid selection. Using default: ${Y[Q]}`),Y[Q];return Y[Z]}formatTime(L){if(L<60)return`${L.toFixed(1)}s`;if(L<3600)return`${Math.floor(L/60)}m ${Math.floor(L%60)}s`;return`${Math.floor(L/3600)}h ${Math.floor(L%3600/60)}m`}}var O2,G0;var e=$2(()=>{((P)=>{P[P.BLACK=0]="BLACK";P[P.RED=1]="RED";P[P.GREEN=2]="GREEN";P[P.YELLOW=3]="YELLOW";P[P.BLUE=4]="BLUE";P[P.MAGENTA=5]="MAGENTA";P[P.CYAN=6]="CYAN";P[P.WHITE=7]="WHITE";P[P.GRAY=8]="GRAY";P[P.BOLD=9]="BOLD";P[P.UNDERLINE=10]="UNDERLINE";P[P.ITALIC=11]="ITALIC";P[P.INVERSE=12]="INVERSE"})(O2||={});G0={[0]:Bun.color("black","ansi")||Bun.color("black","ansi-256")||"",[1]:Bun.color("red","ansi")||Bun.color("red","ansi-256")||"",[2]:Bun.color("green","ansi")||Bun.color("green","ansi-256")||"",[3]:Bun.color("yellow","ansi")||Bun.color("yellow","ansi-256")||"",[4]:Bun.color("blue","ansi")||Bun.color("blue","ansi-256")||"",[5]:Bun.color("magenta","ansi")||Bun.color("magenta","ansi-256")||"",[6]:Bun.color("cyan","ansi")||Bun.color("cyan","ansi-256")||"",[7]:Bun.color("white","ansi")||Bun.color("white","ansi-256")||"",[8]:Bun.color("gray","ansi")||Bun.color("gray","ansi-256")||"",[9]:"\x1B[1m",[10]:"\x1B[4m",[11]:"\x1B[3m",[12]:"\x1B[7m"}});import{isObject as U2,isPrimitive as O0}from"radash";function o(L,...Y){if(!Y.length)return L;let Q=Y.shift();if(Q===void 0)return L;if(U2(L)&&U2(Q))for(let X in Q)if(U2(Q[X])){if(!L[X])Object.assign(L,{[X]:Q[X]})}else if(Array.isArray(Q[X])){if(!Array.isArray(L[X]))L[X]=[];if(Q[X].length>0&&!U2(Q[X][0]))L[X]=[...new Set([...L[X],...Q[X]])];else Q[X].forEach((Z,$)=>{if(U2(Z)&&L[X][$])L[X][$]=o(L[X][$],Z);else if(!L[X].includes(Z))L[X].push(Z)})}else if(O0(Q[X]))L[X]??=Q[X];else o(L[X],Q[X]);return o(L,...Y)}var O,n=()=>new Promise((L)=>process.nextTick(L));var g=$2(()=>{((T)=>(T.app=Symbol("elysium:Application"),T.controller=Symbol("elysium:Controller"),T.middlewares=Symbol("elysium:MiddlewaresList"),T.services=Symbol("elysium:ServicesList"),T.websocket=Symbol("elysium:WebSocket"),T.wamp=Symbol("elysium:Wamp"),T.http=Symbol("elysium:Http"),T.job=Symbol("elysium:Job"),T.arg=Symbol("elysium:CommandArguments"),T.elysiaPlugin=Symbol("elysium:ElysiaPlugin"),T.middlewareGuards=Symbol("elysium:MiddlewareGuards")))(O||={})});import{isString as L2}from"radash";var N2,P0=(L)=>{return typeof L==="function"&&L.prototype&&L.prototype.constructor===L},s,z;var d=$2(()=>{g();((Q)=>{Q[Q.SINGLETON=0]="SINGLETON";Q[Q.FACTORY=1]="FACTORY"})(N2||={});s=new Map;((E)=>{E.register=(G)=>{return function(R){let W=G?.name??R.name,P=G?.scope??0;if(z.exists(W))console.error(`A service with the name ${W} has already been registered.`),process.exit(1);let K=()=>z.make(R);if(P===0){let C=K();s.set(W,{scope:P,factory(){return C}})}else s.set(W,{scope:P,factory:K})}},E.inject=(G)=>{return function(R,W,P){let K=Reflect.getMetadata(O.services,R,W)??[],C=Reflect.getMetadata("design:paramtypes",R,W)??[],y=L2(G)?G:G?.name??C[P].name;K.push({name:y,index:P}),Reflect.defineMetadata(O.services,K,R,W)}},E.get=(G)=>{let R=L2(G)?G:G.name;if(E.exists(R))return s.get(R).factory();return null},E.make=(G)=>{let R=Reflect.getMetadata(O.services,G)??[],W=[];return R.forEach((P)=>{let K=E.get(P.name);if(K===null)console.error(`Cannot inject service ${P.name}. No service was registered with the name: ${P.name}`),process.exit(1);W[P.index]=K}),new G(...W)},E.bind=(G,R)=>{let W=E.make(G);return E.instance(R??G.name,W)};function $(G,R){let W=L2(G)?G:R??G.name;if(E.exists(W))console.error(`A service with the name ${W} has already been registered.`),process.exit(1);let P=()=>{return P0(G)?E.make(G):R()};return s.set(W,{scope:1,factory:P}),P()}E.factory=$,E.instance=(G,R)=>{let W=L2(G)?G:G.name;if(E.exists(W))console.error(`A service with the name ${W} has already been registered.`),process.exit(1);return s.set(W,{scope:0,factory(){return R}}),R},E.remove=(G)=>{let R=L2(G)?G:G.name;s.delete(R)},E.exists=(G)=>{let R=L2(G)?G:G.name;return s.has(R)},E.clear=()=>{s.clear()}})(z||={})});import"reflect-metadata";import{assign as K0,uid as j0}from"radash";var d2;var j2=$2(()=>{e();d();g();d2=class d2 extends k{#L;#Y;#Q="pending";#X;static register(L={}){return function(Y){L=K0({name:Y.name,queue:"default"},L);let Q=`job.${L.name}`;z.instance(Q,Y),Reflect.defineMetadata(O.job,{name:Q,queue:L.queue},Y)}}id;createdAt;get startedAt(){return this.#L}get completedAt(){return this.#Y}get status(){return this.#Q}constructor(L){super();this.id=L||this.generateJobId(),this.createdAt=new Date}async run(){try{this.#Q="running",this.#L=new Date,this.debug(`Job ${this.id} started at ${this.#L.toISOString()}`),await this.execute(),this.#Q="completed",this.#Y=new Date,this.debug(`Job ${this.id} completed at ${this.#Y.toISOString()}`)}catch(L){if(this.#X=L instanceof Error?L:new Error(String(L)),this.#Q!=="cancelled")this.#Q="failed";this.#Y=new Date,this.trace(this.#X)}}cancel(){this.#Q="cancelled"}generateJobId(){return`job_${Date.now()}_${j0(8)}`}}});var l2={};$0(l2,{WorkerPool:()=>R2,Worker:()=>F2});import{uid as F0}from"radash";var p2,F2,R2;var E2=$2(()=>{e();j2();d();g();p2=globalThis.Worker;F2=class F2 extends k{#L;queues=new Map;defaultQueueName="default";static spawn(L,Y=["default"],Q){let X=new this;X.debug(`Worker ${X.id} starting with queues: ${Y.join(", ")}`);for(let Z of Y)X.createQueue({name:Z,concurrency:Q?.concurrency??1,maxRetries:Q?.maxRetries??5,retryDelay:Q?.retryDelay??5000,pauseOnError:Q?.pauseOnError??!1});return L.addEventListener("message",async(Z)=>{let{type:$="job:process",jobId:U,job:_,args:V,queue:H="default"}=Z.data;switch($){case"job:cancel":let G=X.cancelJob(U,H);L.postMessage({type:"job:canceled",jobId:U,queue:H,success:G,count:G?1:0});break;case"job:cancelAll":let R=X.cancelAllJobs(H);L.postMessage({type:"jobs:canceled",queue:H,count:R});break;case"job:process":X.debug(`Worker ${X.id} received job ${_} for queue ${H}`);try{let W=z.get(_);if(!W)throw X.error(`Job class ${_} not found`),new Error(`Job class ${_} not found`);let P=new W(...V||[]);X.addJob(P,H),L.postMessage({type:"job:received",jobId:P.id,queue:H})}catch(W){X.trace({...W,...Q??{}},`Error while adding job '${_}' to queue '${H}' with worker ${X.id}`),L.postMessage({type:"job:error",jobName:_,error:W.message})}break}}),L.addEventListener("error",(Z)=>{X.trace({...Z.error,filename:Z.filename},`Worker ${X.id} error:`)}),L.addEventListener("unhandledrejection",(Z)=>{X.trace(Z,`Worker ${X.id} unhandled rejection:`)}),L.postMessage({type:"worker:ready",id:X.id,queues:Y}),X}constructor(){super();this.#L=F0(24),this.createQueue({name:this.defaultQueueName})}get id(){return this.#L}createQueue(L){if(this.queues.has(L.name))return this.debug(`Queue with name '${L.name}' already exists`),this;let Y={options:{...L,concurrency:L.concurrency||1,maxRetries:L.maxRetries||0,retryDelay:L.retryDelay||1000,pauseOnError:L.pauseOnError||!1},jobs:[],processing:0,paused:!1,draining:!1};return this.queues.set(L.name,Y),this.debug(`Created queue '${L.name}'`),this}addJob(L,Y=this.defaultQueueName){let Q=this.queues.get(Y);if(!Q)return this.error(`Queue '${Y}' does not exist`),this;if(Q.draining)return this.warning(`Queue '${Y}' is draining, job ${L.id} will not be added`),this;let X={job:L,retries:0,queueName:Y};if(Q.jobs.push(X),this.debug(`Added job ${L.id} to queue '${Y}'`),!Q.paused&&Q.processing<Q.options.concurrency)this.processNextJob(Y);return this}pause(L){if(L){let Y=this.queues.get(L);if(Y)Y.paused=!0,this.info(`Paused queue '${L}'`)}else for(let[Y]of this.queues.entries())this.pause(Y);return this}resume(L){if(L){let Y=this.queues.get(L);if(Y)Y.paused=!1,this.info(`Resumed queue '${L}'`),this.processQueueJobs(L)}else for(let[Y]of this.queues.entries())this.resume(Y);return this}drain(L){if(L){let Y=this.queues.get(L);if(Y)Y.draining=!0,this.info(`Draining queue '${L}'`)}else for(let[Y]of this.queues.entries())this.drain(Y);return this}clear(L){if(L){let Y=this.queues.get(L);if(Y){let Q=Y.jobs.length;Y.jobs=[],this.info(`Cleared ${Q} jobs from queue '${L}'`)}}else for(let[Y,Q]of this.queues.entries()){let X=Q.jobs.length;Q.jobs=[],this.info(`Cleared ${X} jobs from queue '${Y}'`)}return this}size(L=this.defaultQueueName){let Y=this.queues.get(L);if(!Y)throw new Error(`Queue '${L}' does not exist`);return Y.jobs.length}totalSize(){let L=0;for(let Y of this.queues.values())L+=Y.jobs.length;return L}async processNextJob(L){let Y=this.queues.get(L);if(!Y||Y.paused||Y.processing>=Y.options.concurrency)return;let Q=Y.jobs.shift();if(!Q)return;if(Q.job.status==="cancelled"){this.info(`Skipping cancelled job ${Q.job.id}`),Y.processing--,this.processQueueJobs(L);return}Y.processing++;try{if(this.debug(`Processing job ${Q.job.id} from queue '${L}'`),await Q.job.run(),Q.job.status==="failed"){if(Q.retries<Y.options.maxRetries)Q.retries++,this.warning(`Job ${Q.job.id} failed, retrying (${Q.retries}/${Y.options.maxRetries})`),setTimeout(()=>{if(Q.job.status!=="cancelled")Y.jobs.push(Q),this.processQueueJobs(L);else this.info(`Skipping cancelled job ${Q.job.id} during retry delay`)},Y.options.retryDelay);else if(this.error(`Job ${Q.job.id} failed after ${Q.retries} retries`),Y.options.pauseOnError)this.pause(L),this.warning(`Queue '${L}' paused due to job failure`)}else if(Q.job.status==="completed")this.success(`Job ${Q.job.id} completed successfully`);else this.info(`Job ${Q.job.id} cancelled while running`)}catch(X){if(this.error(`Unexpected error processing job ${Q.job.id}: ${X}`),Y.options.pauseOnError)this.pause(L),this.warning(`Queue '${L}' paused due to unexpected error`)}finally{Y.processing--,this.processQueueJobs(L)}}processQueueJobs(L){let Y=this.queues.get(L);if(!Y||Y.paused)return;while(Y.jobs.length>0&&Y.processing<Y.options.concurrency)this.processNextJob(L)}getStats(){let L={};for(let[Y,Q]of this.queues.entries())L[Y]={waiting:Q.jobs.length,processing:Q.processing,paused:Q.paused,draining:Q.draining};return L}cancelJob(L,Y){if(Y)return this.cancelJobInQueue(L,Y);else{let Q=!1;for(let[X]of this.queues.entries())if(this.cancelJobInQueue(L,X)){Q=!0;break}return Q}}cancelJobInQueue(L,Y){let Q=this.queues.get(Y);if(!Q)return!1;let X=Q.jobs.findIndex((Z)=>Z.job.id===L);if(X>=0)return Q.jobs[X].job.cancel(),this.info(`Canceled job ${L} in queue '${Y}'`),!0;return!1}cancelAllJobs(L){let Y=0;if(L){let Q=this.queues.get(L);if(Q)Y=Q.jobs.length,Q.jobs.forEach((X)=>{X.job.cancel()}),this.info(`Canceled ${Y} jobs in queue '${L}'`)}else for(let[Q,X]of this.queues.entries()){let Z=X.jobs.length;X.jobs.forEach(($)=>{$.job.cancel()}),Y+=Z,this.info(`Canceled ${Z} jobs in queue '${Q}'`)}return Y}};R2=class R2 extends k{workers=[];currentWorkerIndex=0;queueWorkerMap=new Map;static instance=new R2;constructor(){super()}async init(){}async addWorker(L=[]){let Y;if(ELYSIUM_BUILD)Y=new p2("./index.js",{argv:["work",...L.map((Q)=>`--queue=${Q}`)]});else{let Q=await Array.fromAsync(new Bun.Glob("./src/**/*.job.ts").scan());Y=new p2("./index.ts",{preload:Q,argv:["work",...L.map((X)=>`--queue=${X}`)]})}Y.addEventListener("error",(Q)=>{this.trace({message:"An error occurred inside a worker process",stack:Q.message,name:"WorkerError"}),this.removeWorker(Y),this.addWorker(L)}),Y.addEventListener("messageerror",(Q)=>{this.error(`Worker message error: ${Q}`)}),Y.addEventListener("message",(Q)=>{if(Q.data.type==="worker:ready")this.debug(`Worker ${Q.data.id} ready with queues: ${Q.data.queues.join(", ")}`);else if(Q.data.type==="job:received")this.debug(`Job ${Q.data.jobId} received by worker for queue ${Q.data.queue}`);else if(Q.data.type==="job:error")this.error(`Error processing job ${Q.data.jobName}: ${Q.data.error}`);else this.debug(`Worker message: ${JSON.stringify(Q.data)}`)}),this.workers.push(Y);for(let Q of L){if(!this.queueWorkerMap.has(Q))this.queueWorkerMap.set(Q,[]);this.queueWorkerMap.get(Q).push(Y)}}removeWorker(L){let Y=L??this.workers.pop();if(!Y)return;Y.terminate();for(let[Q,X]of this.queueWorkerMap.entries())this.queueWorkerMap.set(Q,X.filter((Z)=>Z!==Y));if(L)this.workers=this.workers.filter((Q)=>Q!==Y)}terminate(){while(this.workers.length>0)this.removeWorker();this.queueWorkerMap.clear()}runJob(L,...Y){if(!Reflect.hasMetadata(O.job,L))throw new Error(`Job ${L.name} is not marked with @job() decorator`);let{name:Q,queue:X="default"}=Reflect.getMetadata(O.job,L),Z=this.queueWorkerMap.get(X)||this.workers;if(Z.length===0)throw new Error(`No workers available for queue '${X}'`);let $=this.currentWorkerIndex%Z.length;Z[$].postMessage({job:Q,args:Y,queue:X}),this.currentWorkerIndex=(this.currentWorkerIndex+1)%this.workers.length}cancelJob(L,Y){for(let Q of this.workers)Q.postMessage({type:"job:cancel",jobId:L,queue:Y});return this.workers.length>0}cancelAllJobs(L){for(let Y of this.workers)Y.postMessage({type:"job:cancelAll",queue:L});return this.workers.length>0}}});global.ELYSIUM_BUILD=typeof ELYSIUM_BUILD!=="undefined";import{t as vY}from"elysia";e();import{AsyncLocalStorage as E0}from"async_hooks";import{parseArgs as I0}from"util";import{swagger as T0}from"@elysiajs/swagger";import{Value as _2}from"@sinclair/typebox/value";import{Elysia as x0}from"elysia";import{first as f0}from"radash";import{getTableName as q2,is as h2,Table as b2}from"drizzle-orm";import{drizzle as V0}from"drizzle-orm/bun-sql";import{Cache as M0}from"drizzle-orm/cache/core";import{createCache as S2}from"cache-manager";import{KeyvCacheableMemory as z0}from"cacheable";import{Keyv as C2}from"keyv";import{alphabetical as B0}from"radash";import{EventEmitter as R0}from"events";import{omit as W0}from"radash";import{EventEmitter as H0}from"events";import{isString as w2}from"radash";class q extends H0{static instance=new q;constructor(){super();this.on("error",(L)=>this.emitError(L))}emitError(L){this.emit("elysium:error",{data:L,source:null})}emitEvent(L,Y,Q=null){this.emit(L,{data:Y,source:Q})}}var f;((m)=>{m.emit=(U,_,V=null)=>{q.instance.emitEvent(U,_,V)};function Y(U,_){if(w2(U))q.instance.on(U,_);else return function(V,H,G){let R=async function(P){try{await G.value(P)}catch(K){q.instance.emitError(K)}};if(U.prepend??!1)q.instance.prependListener(U.event,R);else q.instance.on(U.event,R)}}m.on=Y;function Q(U,_){if(w2(U))q.instance.once(U,_);else return function(V,H,G){let R=async function(P){try{await G.value(P)}catch(K){q.instance.emitError(K)}};if(U.prepend??!1)q.instance.prependOnceListener(U.event,R);else q.instance.once(U.event,R)}}m.once=Q,m.off=(U)=>{q.instance.removeAllListeners(U)},m.clear=()=>{q.instance.removeAllListeners()},m.listen=(U)=>{if(U.mode==="on")return Y(U);else if(U.mode==="once")return Q(U);return function(_,V,H){console.error("Unknown mode provided to @listen. Use either 'on' or 'once'.")}}})(f||={});d();class J2 extends R0{#L;#Y;#Q="::";#X=1000;#Z=!0;#$=!1;#U;constructor(L){super();f.once("elysium:app:launched",()=>{this.#L=r.getConnection(L.connection)}),this.#U=L.connection,this.#Y=L.namespace,this.#Q=L.keyPrefixSeparator??"::",this.#X=L.clearBatchSize??1000,this.#Z=L.useUnlink??!0,this.#$=L.noNamespaceAffectsAll??!1,this.on("error",(Y)=>{f.emit("elysium:error",Y)})}get client(){return this.#L}get opts(){return{namespace:this.#Y,keyPrefixSeparator:this.#Q,clearBatchSize:this.#X,noNamespaceAffectsAll:this.#$,dialect:"redis",url:this.#U}}get namespace(){return this.#Y}set namespace(L){this.#Y=L}async get(L){L=this.createKeyPrefix(L,this.#Y);let Y=await this.client.get(L);return Y===null?void 0:Y}async set(L,Y,Q){if(L=this.createKeyPrefix(L,this.#Y),Q)await this.client.set(L,Y,"PX",Q);else await this.client.set(L,Y)}async setMany(L){let Y=[];for(let{key:Q,value:X,ttl:Z}of L){let $=this.createKeyPrefix(Q,this.#Y);if(Z)Y.push(this.client.set($,X,"PX",Z));else Y.push(this.client.set($,X))}await Promise.all(Y)}async delete(L){return L=this.createKeyPrefix(L,this.#Y),await(this.#Z?this.client.send("UNLINK",[L]):this.client.del(L))>0}async clear(){try{if(!this.#Y&&this.#$){await this.client.send("FLUSHDB",[]);return}let L="0",Y=this.#X,Q=this.#Y?`${this.#Y}${this.#Q}*`:"*",X=[];do{let Z=await this.client.send("SCAN",[L,"MATCH",Q,"COUNT",Y.toString(),"TYPE","string"]),[$,U]=Z;if(L=$.toString(),U.length===0)continue;if(!this.#Y)U=U.filter((_)=>!_.includes(this.#Q));X.push(U.map((_)=>this.client.del(_)))}while(L!=="0");await Promise.all(X)}catch(L){this.emit("error",L)}}async has(L){return L=this.createKeyPrefix(L,this.#Y),this.client.exists(L)}async hasMany(L){let Y=[];for(let Q of L){let X=this.createKeyPrefix(Q,this.#Y);Y.push(this.client.exists(X))}return Promise.all(Y)}async getMany(L){if(L.length===0)return[];return L=L.map((Q)=>this.createKeyPrefix(Q,this.#Y)),await this.client.mget(...L)}async disconnect(){this.client.close()}async deleteMany(L){let Y=!1,Q=[];for(let Z of L){let $=this.createKeyPrefix(Z,this.#Y);if(this.#Z)Q.push(this.client.send("UNLINK",[$]));else Q.push(this.client.del($))}let X=await Promise.all(Q);for(let Z of X)if(typeof Z==="number"&&Z>0)Y=!0;return Y}async*iterator(L){let Y=L?`${L}${this.#Q}*`:"*",Q="0";do{let X=await this.client.send("SCAN",[Q,"MATCH",Y,"TYPE","string"]),[Z,$]=X;if(Q=Z.toString(),!L&&!this.#$)$=$.filter((U)=>!U.includes(this.#Q));if($.length>0){let U=await this.client.mget(...$);for(let _ of $.keys()){let V=this.getKeyWithoutPrefix($[_],L),H=U[_];yield[V,H]}}}while(Q!=="0")}createKeyPrefix(L,Y){return Y?`${Y}${this.#Q}${L}`:L}getKeyWithoutPrefix(L,Y){return Y?L.replace(`${Y}${this.#Q}`,""):L}}var r;((h)=>{let L=(U)=>{return`redis.connection.${U}`};h.getConnection=(U)=>{if(!z.exists(L(U)))console.error(`No Redis connection with name ${U} found. Please make sure to register the connection before using it.`),process.exit(1);return z.get(L(U))},h.registerConnection=(U,_)=>{if(z.exists(L(U)))console.error(`A Redis connection with the name ${U} has already been registered.`),process.exit(1);return z.instance(L(U),new Bun.RedisClient(_.url,W0(_,["url"])))},h.connectionExists=(U)=>{return z.exists(L(U))},h.getDefaultConnection=()=>{return h.getConnection("default")},h.setDefaultConnection=(U)=>{let _=L("default");return z.remove(_),z.instance(_,h.getConnection(U))}})(r||={});var k2=(L)=>{let Y=S2({stores:[new C2({store:L,namespace:"cache"})]}),Q=new Map;return{...Y,tags(...X){let Z=`cache__${B0(X,(U)=>U).join("__")}`,$=Q.get(Z);if(!$)$=S2({stores:[new C2({store:L,namespace:Z})]}),Q.set(Z,$);return $}}};class p{static#L;static#Y;static weak=Object.seal({map:new WeakMap,get(L){if(!this.map.has(L))this.map.set(L,{});return this.map.get(L)},del(L){this.map.delete(L)}});static get redis(){if(!p.#L)p.#L=k2(new J2({connection:"cache"}));return p.#L}static get memory(){if(!p.#Y)p.#Y=k2(new z0({ttl:60000,lruSize:5000}));return p.#Y}}d();class A2 extends M0{cacheStrategy;globalTtl;#L;usedTablesPerKey={};constructor(L="explicit",Y=1,Q="redis"){super();this.cacheStrategy=L;this.globalTtl=Y;this.#L=p[Q].tags("database")}strategy(){return this.cacheStrategy}async get(L){return await this.#L.get(L)??void 0}async put(L,Y,Q,X,Z){await this.#L.set(L,Y,(Z?.ex??this.globalTtl)*1000);for(let $ of Q){let U=this.usedTablesPerKey[$];if(U===void 0)this.usedTablesPerKey[$]=[L];else U.push(L)}}async onMutate(L){let Y=L.tags?Array.isArray(L.tags)?L.tags:[L.tags]:[],Q=L.tables?Array.isArray(L.tables)?L.tables:[L.tables]:[],X=new Set;for(let Z of Q){let $=h2(Z,b2)?q2(Z):Z,U=this.usedTablesPerKey[$]??[];for(let _ of U)X.add(_)}if(X.size>0||Y.length>0){await this.#L.mdel(Y),await this.#L.mdel([...X]);for(let Z of Q){let $=h2(Z,b2)?q2(Z):Z;this.usedTablesPerKey[$]=[]}}}}var l;((b)=>{let L=(U)=>{return`db.connection.${U}`};b.getConnection=(U)=>{if(!z.exists(L(U)))console.error(`No connection with name ${U} found. Please make sure to register the connection before using it.`),process.exit(1);return z.get(L(U))},b.registerConnection=(U,_)=>{if(z.exists(L(U)))console.error(`A connection with the name ${U} has already been registered.`),process.exit(1);return z.instance(L(U),V0({..._,cache:_.cache===void 0?void 0:_.cache===!0?new A2:_.cache.enabled?new A2(_.cache.strategy,_.cache.ttl,_.cache.storage):void 0}))},b.connectionExists=(U)=>{return z.exists(L(U))},b.getDefaultConnection=()=>{return b.getConnection("default")},b.setDefaultConnection=(U)=>{let _=L("default");return z.remove(_),z.instance(_,b.getConnection(U))}})(l||={});var P2=new Map,K2=(L)=>{for(let[Y,Q]of Object.entries(L))P2.set(Y,Q)},v2;((Y2)=>(Y2.get=(X,Z)=>{return P2.get(X)??Z},Y2.exists=(X)=>{return P2.has(X)},Y2.clear=()=>{P2.clear()}))(v2||={});d();g();var u=(L,Y,Q)=>{return N.context.run(new Map([["tenant",Y.tenant],["http:context",Y]]),async()=>{for(let X of L)try{let Z=await X[Q](Y);if(Z!==void 0)return Z}catch(Z){throw Z}})},Q2=(L,Y)=>{let Q=L.map((X)=>z.make(X));Y.onRequest((X)=>{return u(Q,X,"onRequest")}),Y.onTransform((X)=>{return u(Q,X,"onTransform")}),Y.onBeforeHandle((X)=>{return u(Q,X,"onBeforeHandle")}),Y.onAfterHandle((X)=>{return u(Q,X,"onAfterHandle")}),Y.onAfterResponse((X)=>{return u(Q,X,"onAfterResponse")})};class y2{static register(...L){return function(Y,Q,X){if(Q===void 0&&X===void 0){let Z=Reflect.getMetadata(O.middlewares,Y)??[];Z.push(...L),Reflect.defineMetadata(O.middlewares,Z,Y)}else{let Z=Reflect.getMetadata(O.middlewares,Y,Q)??[];Z.push(...L),Reflect.defineMetadata(O.middlewares,Z,Y,Q)}}}static guards(L){class Y extends this{}return Reflect.defineMetadata(O.middlewareGuards,L,Y),Y}get guards(){return Reflect.getMetadata(O.middlewareGuards,this.constructor)??[]}onRequest(L){}onTransform(L){}onAfterHandle(L){}onBeforeHandle(L){}onAfterResponse(L){}}d();g();import{Elysia as D0}from"elysia";import{omit as J0}from"radash";import A0 from"wampy";d();g();class g2 extends WebSocket{protocols;constructor(L,Y){super(L,Y);this.protocols=Y}get protocol(){return this.protocols?.[0]??"wamp.2.json"}}var t;((w)=>{let L=(H)=>{return`wamp.connection.${H}`};w.getConnection=(H)=>{if(!z.exists(L(H)))console.error(`No WAMP connection with name ${H} found. Please make sure to register the connection before using it.`),process.exit(1);return z.get(L(H))},w.registerConnection=(H,G)=>{if(z.exists(L(H)))console.error(`A WAMP connection with name ${H} already exists. Please ensure to register a new connection before overwriting it.`),process.exit(1);let R=new A0(G.url,{ws:g2,...J0(G,["url"]),onError(){G.onError?.(),f.emit("elysium:error",new Error(`An error occurred in WAMP connection ${H}`))}}),W=G.maxRetries??5,P=G.retryInterval??5000,K=0,C=async()=>{try{await R.connect()}catch(y){if(console.error(`Failed to connect to WAMP server (attempt ${K+1}/${W}):`,y),K<W)K++,setTimeout(C,P);else console.error(`Max retry attempts (${W}) reached. Giving up.`),f.emit("elysium:error",new Error(`Failed to establish WAMP connection ${H} after ${W} attempts`))}};return C(),z.instance(L(H),R)},w.connectionExists=(H)=>{return z.exists(L(H))},w.getDefaultConnection=()=>{return w.getConnection("default")},w.setDefaultConnection=(H)=>{let G=L("default");return z.remove(G),z.instance(G,w.getConnection(H))},w.controller=(H)=>{return function(G){async function R(){console.log(`Registering Wamp controller for connection ${H.connection} using ${G.name}`),await n();let W=z.make(G),P=Reflect.getMetadata(O.wamp,G)??{},K=t.getConnection(H.connection??"default"),C=new D0;return C.onStart(async(y)=>{let B=P.registrations??[],D=P.subscriptions??[];for(let M of B)K.register(M.topic,M.handler.bind(W),M.options).then((I)=>{console.log(`Registered ${M.topic} with id ${I.registrationId}`)});for(let M of D)K.subscribe(M.topic,M.handler.bind(W),M.options).then((I)=>{console.log(`Subscribed ${M.topic} with id ${I.subscriptionId}`)})}),C}Reflect.defineMetadata(O.elysiaPlugin,R,G)}},w.register=(H,G)=>{return function(R,W,P){let K=Reflect.getMetadata(O.wamp,R.constructor)??{};K.registrations??=[],K.registrations.push({topic:H,options:G,handler:P.value}),Reflect.defineMetadata(O.wamp,K,R.constructor)}},w.subscribe=(H,G)=>{return function(R,W,P){let K=Reflect.getMetadata(O.wamp,R.constructor)??{};K.subscriptions??=[],K.subscriptions.push({topic:H,options:G,handler:P.value}),Reflect.defineMetadata(O.wamp,K,R.constructor)}}})(t||={});class N extends k{#L;#Y;_appContextStorage=new E0;static get instance(){return z.get("elysium.app")}static get context(){return N.instance._appContextStorage}static register(L={}){return function(Y){let Q,X=Object.getPrototypeOf(Y);while(X&&X!==Object.prototype){let $=Reflect.getMetadata(O.app,X);if($){Q=$;break}X=Object.getPrototypeOf(X)}if(Q)L=o(Q,L);let Z=Reflect.getMetadata(O.app,Y);if(Z)L=o(Z,L);L=o({modules:[],swagger:!1},L),Reflect.defineMetadata(O.app,L,Y)}}constructor(){super();let{env:L,debug:Y}=Reflect.getMetadata(O.app,this.constructor)??{};if(this.#Y=Y??!1,L){let $=_2.Convert(L,_2.Clone(Bun.env));if(this.#Y&&!_2.Check(L,$)){let U=_2.Errors(L,$).First();this.trace(U,"Invalid environment configuration")}K2(_2.Clean(L,$))}else K2(Bun.env);z.instance("elysium.app",this);let{database:Q,redis:X,wamp:Z}=Reflect.getMetadata(O.app,this.constructor);if(X){for(let $ in X.connections)r.registerConnection($,X.connections[$]);if(r.connectionExists(X.default))r.setDefaultConnection(X.default)}if(Q){for(let $ in Q.connections)l.registerConnection($,Q.connections[$]);if(l.connectionExists(Q.default))l.setDefaultConnection(Q.default)}if(Z){for(let $ in Z.connections)t.registerConnection($,Z.connections[$]);if(t.connectionExists(Z.default))t.setDefaultConnection(Z.default)}this.run().then(()=>f.emit("elysium:app:launched",this,this)).catch(($)=>{f.emit("elysium:error",$),this.trace($,"An error occurred while launching the application"),process.exit(1)})}get elysia(){return this.#L}get isDebug(){return this.#Y}set isDebug(L){this.#Y=L}async onError(L){return!0}async onStart(L){}async onStop(L){}async run(){let L=process.argv.slice(2),Y=L[0];if(!Y)this.commandDescribe();else{let{commands:Q}=Reflect.getMetadata(O.app,this.constructor);switch(Y){case"serve":return this.commandServe();case"work":return this.commandWork(L.slice(1));case"help":{let X=L[1];if(X){let Z=Q?.find(($)=>$.command===X);if(Z){let $=z.make(Z);return this.write(await $.help()),process.exit(0)}console.error(`Command <${X}> not found.`)}else console.error("No command provided. Usage: styx help <command>");this.commandList();break}case"list":{this.write(this.bold("Available commands:")),this.commandList();break}default:{let X=L.slice(1);return this.commandExec(Y,X)}}}return process.exit(0)}getConfig(L){return Reflect.getMetadata(O.app,this.constructor)?.[L]??null}async commandExec(L,Y){let{commands:Q}=Reflect.getMetadata(O.app,this.constructor),X=Q?.find((Z)=>Z.command===L);if(!X)return console.error(`Command ${L} not found`),this.commandList(),process.exit(1);try{let Z=z.make(X);if(await Z.init(...Y))await Z.run();else{let U=await Z.help();this.write(U)}return process.exit(0)}catch(Z){return console.error(Z.message),process.exit(1)}}async commandWork(L){this.info("Starting worker process...");let{values:Y}=I0({args:L,options:{queue:{type:"string",multiple:!0,default:["default"],short:"q"},concurrency:{type:"string",default:"1",short:"c"},["max-retries"]:{type:"string",default:"5",short:"r"},["retry-delay"]:{type:"string",default:"5000",short:"d"},["pause-on-error"]:{type:"boolean",default:!1,short:"p"}}}),{Worker:Q}=await Promise.resolve().then(() => (E2(),l2)),X=Y.queue.map(($)=>$.split(",")).reduce(($,U)=>$.concat(U),[]),Z=Q.spawn(self,X,{concurrency:parseInt(Y.concurrency,10),maxRetries:parseInt(Y["max-retries"],10),retryDelay:parseInt(Y["retry-delay"],10),pauseOnError:Y["pause-on-error"]});this.success(`Worker process ${this.format(Z.id,2)} started with queues: ${X.map(($)=>this.format($,6)).join(", ")}`)}async commandServe(){let{server:L,modules:Y,swagger:Q,plugins:X}=Reflect.getMetadata(O.app,this.constructor);if(this.#L=new x0(L).onRequest(($)=>{if(this.isDebug)console.log($.request.method,$.request.url)}),f.emit("elysium:server:before-init",this,this),this.#L.resolve({as:"global"},({request:$})=>({tenant:$.headers.get("x-tenant-id")??"public"})),Q)this.#L.use(T0(Q));if(X&&X.length>0){this.debug("Registering plugins...");for(let $ of X)this.#L.use(await $(this))}this.#L.onError({as:"global"},async($)=>{if(await this.onError($)){f.emit("elysium:error",$),this.trace({name:"HttpError",message:"Unexpected error while handling HTTP request",stack:$.error.stack,...$.error});let U={};if(typeof $.code==="number")return $.error.response;else switch($.code){case"VALIDATION":{U={scope:$.error.type,code:$.error.message};break}case"INTERNAL_SERVER_ERROR":{U={message:$.error.message};break}}return{type:$.code,data:U}}}).onStart(async($)=>{await this.onStart($),f.emit("elysium:server:start",$,this)}).onStop(async($)=>{await this.onStop($),f.emit("elysium:server:stop",$,this),this._appContextStorage.disable()});let Z=Reflect.getMetadata(O.middlewares,this.constructor)??[];Q2(Z,this.#L);for(let $ of Y){let U=Reflect.getMetadata(O.elysiaPlugin,$);if(U===void 0)return console.error(`Invalid module class ${$.name} registered in app ${this.constructor.name}. Ensure that you used the @module() decorator on the module.`),process.exit(1);let _=z.bind($);await _.beforeRegister(),this.#L.use(await U(_)),await _.afterRegister()}f.emit("elysium:server:after-init",this,this),this.#L.listen(L?.port??(parseInt(process.env.PORT,10)||3000)),process.on("SIGINT",()=>{this.#L.stop().then(()=>process.exit(0))})}commandDescribe(){this.section(`${this.bold("Usage:")} ${this.format("styx",5)} <command> [options]`),this.section(this.bold("Core Commands:")),this.newLine(),this.commandDescription("serve","","Starts the server."),this.commandDescription("help","<command>","Displays help for a command."),this.commandDescription("list","","List all available application commands."),this.section(this.bold("Application Commands:")),this.commandList()}commandList(){let{commands:L}=Reflect.getMetadata(O.app,this.constructor),Y=(L??[]).reduce((Q,X)=>{let Z=f0(X.command.split(":")),$=Q.get(Z)??[];return $.push(X),Q.set(Z,$),Q},new Map);for(let[Q,X]of Y){this.section(this.format(Q,4));for(let Z of X)this.commandDescription(Z.command,"",Z.description)}}commandDescription(L,Y,Q,X=k.SPACE_WIDTH){Y=Y.length===0?" ":` ${Y} `,this.write(` ${this.format(L,6)}${Y}${"\u2219".repeat(X-L.length-Y.length)} ${Q}`)}}e();g();import{isArray as w0,trim as N0}from"radash";var u2;(($)=>{$.STRING="string";$.NUMBER="number";$.BOOLEAN="boolean";$.ENUM="enum";$.ARRAY="array"})(u2||={});class i2 extends k{static command="command";static description="Command description";static arg(L={}){return function(Y,Q){let X=Reflect.getMetadata(O.arg,Y.constructor)??[],Z=Reflect.getMetadata("design:type",Y,Q),$=L.type;if(!$&&Z){if(Z===Array){if($="array",!L.arrayType)L={...L,arrayType:"string"}}else if(Z.constructor!==Object)switch(Z.name.toLowerCase()){case"number":$="number";break;case"boolean":$="boolean";break;case"string":$="string";break;default:$=void 0}else if(Object.values(Z).length>0){if($="enum",!L.enum)L={...L,enum:Object.values(Z)}}}X.push({name:L.name??Q,description:L.description,required:L.required??!1,default:L.default,type:$,enum:L.enum,arrayType:L.arrayType,propertyKey:Q}),Reflect.defineMetadata(O.arg,X,Y.constructor)}}async init(...L){let Y=this.processArgs(L),Q=this.validateArgs(Y);if(!Q.valid){if(Q.missing.length>0)console.error(`Missing required arguments: ${Q.missing.join(", ")}
9
- `);return!1}if(Object.keys(Y).includes("help"))return!1;let X=this.getArguments();for(let Z of X)if(Y[Z.name]!==void 0)this[Z.propertyKey]=Y[Z.name];return!0}getArguments(){return Reflect.getMetadata(O.arg,this.constructor)||[]}async help(){let L=`${this.bold("Command:")} ${this.format(this.constructor.command,5)}
10
- `;L+=`${this.bold("Description:")} ${this.constructor.description}
8
+ `),process.stdin.setRawMode?.(!1),process.stdin.removeAllListeners("data"),X.close(),Y(Z);return}if(_==="\b"||_==="\x7F"){if(Z.length>0)Z=Z.slice(0,-1),process.stdout.write("\b \b");return}Z+=_,process.stdout.write("*")})})}async confirm(Q,X=!1){let Y=X?"Y/n":"y/N",Z=await this.prompt(`${Q} [${Y}]`);if(!Z)return X;return Z.toLowerCase()==="y"||Z.toLowerCase()==="yes"}async select(Q,X,Y=0){if(X.length===0)throw new Error("No options provided for selection");this.write(Q),X.forEach((_,U)=>{let G=U===Y;this.write(` ${U+1}. ${_}${G?" (default)":""}`)});let Z=await this.prompt("Enter your choice (number)");if(!Z)return X[Y];let $=parseInt(Z,10)-1;if(isNaN($)||$<0||$>=X.length)return this.warning(`Invalid selection. Using default: ${X[Y]}`),X[Y];return X[$]}formatTime(Q){if(Q<60)return`${Q.toFixed(1)}s`;if(Q<3600)return`${Math.floor(Q/60)}m ${Math.floor(Q%60)}s`;return`${Math.floor(Q/3600)}h ${Math.floor(Q%3600/60)}m`}}var OQ,LX;var e=_Q(()=>{((P)=>{P[P.BLACK=0]="BLACK";P[P.RED=1]="RED";P[P.GREEN=2]="GREEN";P[P.YELLOW=3]="YELLOW";P[P.BLUE=4]="BLUE";P[P.MAGENTA=5]="MAGENTA";P[P.CYAN=6]="CYAN";P[P.WHITE=7]="WHITE";P[P.GRAY=8]="GRAY";P[P.BOLD=9]="BOLD";P[P.UNDERLINE=10]="UNDERLINE";P[P.ITALIC=11]="ITALIC";P[P.INVERSE=12]="INVERSE"})(OQ||={});LX={[0]:Bun.color("black","ansi")||Bun.color("black","ansi-256")||"",[1]:Bun.color("red","ansi")||Bun.color("red","ansi-256")||"",[2]:Bun.color("green","ansi")||Bun.color("green","ansi-256")||"",[3]:Bun.color("yellow","ansi")||Bun.color("yellow","ansi-256")||"",[4]:Bun.color("blue","ansi")||Bun.color("blue","ansi-256")||"",[5]:Bun.color("magenta","ansi")||Bun.color("magenta","ansi-256")||"",[6]:Bun.color("cyan","ansi")||Bun.color("cyan","ansi-256")||"",[7]:Bun.color("white","ansi")||Bun.color("white","ansi-256")||"",[8]:Bun.color("gray","ansi")||Bun.color("gray","ansi-256")||"",[9]:"\x1B[1m",[10]:"\x1B[4m",[11]:"\x1B[3m",[12]:"\x1B[7m"}});import{isObject as UQ,isPrimitive as OX}from"radash";function o(Q,...X){if(!X.length)return Q;let Y=X.shift();if(Y===void 0)return Q;if(UQ(Q)&&UQ(Y))for(let Z in Y)if(UQ(Y[Z])){if(!Q[Z])Object.assign(Q,{[Z]:Y[Z]})}else if(Array.isArray(Y[Z])){if(!Array.isArray(Q[Z]))Q[Z]=[];if(Y[Z].length>0&&!UQ(Y[Z][0]))Q[Z]=[...new Set([...Q[Z],...Y[Z]])];else Y[Z].forEach(($,_)=>{if(UQ($)&&Q[Z][_])Q[Z][_]=o(Q[Z][_],$);else if(!Q[Z].includes($))Q[Z].push($)})}else if(OX(Y[Z]))Q[Z]??=Y[Z];else o(Q[Z],Y[Z]);return o(Q,...X)}var O,n=()=>new Promise((Q)=>process.nextTick(Q));var g=_Q(()=>{((T)=>(T.app=Symbol("elysium:Application"),T.controller=Symbol("elysium:Controller"),T.middlewares=Symbol("elysium:MiddlewaresList"),T.services=Symbol("elysium:ServicesList"),T.websocket=Symbol("elysium:WebSocket"),T.wamp=Symbol("elysium:Wamp"),T.http=Symbol("elysium:Http"),T.job=Symbol("elysium:Job"),T.arg=Symbol("elysium:CommandArguments"),T.elysiaPlugin=Symbol("elysium:ElysiaPlugin"),T.middlewareGuards=Symbol("elysium:MiddlewareGuards")))(O||={})});import{isString as QQ}from"radash";var NQ,PX=(Q)=>{return typeof Q==="function"&&Q.prototype&&Q.prototype.constructor===Q},s,B;var d=_Q(()=>{g();((Y)=>{Y[Y.SINGLETON=0]="SINGLETON";Y[Y.FACTORY=1]="FACTORY"})(NQ||={});s=new Map;((E)=>{E.register=(L)=>{return function(z){let R=L?.name??z.name,P=L?.scope??0;if(B.exists(R))console.error(`A service with the name ${R} has already been registered.`),process.exit(1);let j=()=>B.make(z);if(P===0){let C=j();s.set(R,{scope:P,factory(){return C}})}else s.set(R,{scope:P,factory:j})}},E.inject=(L)=>{return function(z,R,P){let j=Reflect.getMetadata(O.services,z,R)??[],C=Reflect.getMetadata("design:paramtypes",z,R)??[],y=QQ(L)?L:L?.name??C[P].name;j.push({name:y,index:P}),Reflect.defineMetadata(O.services,j,z,R)}},E.get=(L)=>{let z=QQ(L)?L:L.name;if(E.exists(z))return s.get(z).factory();return null},E.make=(L)=>{let z=Reflect.getMetadata(O.services,L)??[],R=[];return z.forEach((P)=>{let j=E.get(P.name);if(j===null)console.error(`Cannot inject service ${P.name}. No service was registered with the name: ${P.name}`),process.exit(1);R[P.index]=j}),new L(...R)},E.bind=(L,z)=>{let R=E.make(L);return E.instance(z??L.name,R)};function _(L,z){let R=QQ(L)?L:z??L.name;if(E.exists(R))console.error(`A service with the name ${R} has already been registered.`),process.exit(1);let P=()=>{return PX(L)?E.make(L):z()};return s.set(R,{scope:1,factory:P}),P()}E.factory=_,E.instance=(L,z)=>{let R=QQ(L)?L:L.name;if(E.exists(R))console.error(`A service with the name ${R} has already been registered.`),process.exit(1);return s.set(R,{scope:0,factory(){return z}}),z},E.remove=(L)=>{let z=QQ(L)?L:L.name;s.delete(z)},E.exists=(L)=>{let z=QQ(L)?L:L.name;return s.has(z)},E.clear=()=>{s.clear()}})(B||={})});import"reflect-metadata";import{assign as jX,uid as FX}from"radash";var dQ;var FQ=_Q(()=>{e();d();g();dQ=class dQ extends k{#Q;#X;#Y="pending";#Z;static register(Q={}){return function(X){Q=jX({name:X.name,queue:"default"},Q);let Y=`job.${Q.name}`;B.instance(Y,X),Reflect.defineMetadata(O.job,{name:Y,queue:Q.queue},X)}}id;createdAt;get startedAt(){return this.#Q}get completedAt(){return this.#X}get status(){return this.#Y}constructor(Q){super();this.id=Q||this.generateJobId(),this.createdAt=new Date}async run(){try{this.#Y="running",this.#Q=new Date,this.debug(`Job ${this.id} started at ${this.#Q.toISOString()}`),await this.execute(),this.#Y="completed",this.#X=new Date,this.debug(`Job ${this.id} completed at ${this.#X.toISOString()}`)}catch(Q){if(this.#Z=Q instanceof Error?Q:new Error(String(Q)),this.#Y!=="cancelled")this.#Y="failed";this.#X=new Date,this.trace(this.#Z)}}cancel(){this.#Y="cancelled"}generateJobId(){return`job_${Date.now()}_${FX(8)}`}}});var pQ={};_X(pQ,{WorkerPool:()=>zQ,Worker:()=>AQ});import{uid as AX}from"radash";var lQ,AQ,zQ;var EQ=_Q(()=>{e();FQ();d();g();lQ=globalThis.Worker;AQ=class AQ extends k{#Q;queues=new Map;defaultQueueName="default";static spawn(Q,X=["default"],Y){let Z=new this;Z.debug(`Worker ${Z.id} starting with queues: ${X.join(", ")}`);for(let $ of X)Z.createQueue({name:$,concurrency:Y?.concurrency??1,maxRetries:Y?.maxRetries??5,retryDelay:Y?.retryDelay??5000,pauseOnError:Y?.pauseOnError??!1});return Q.addEventListener("message",async($)=>{let{type:_="job:process",jobId:U,job:G,args:M,queue:H="default"}=$.data;switch(_){case"job:cancel":let L=Z.cancelJob(U,H);Q.postMessage({type:"job:canceled",jobId:U,queue:H,success:L,count:L?1:0});break;case"job:cancelAll":let z=Z.cancelAllJobs(H);Q.postMessage({type:"jobs:canceled",queue:H,count:z});break;case"job:process":Z.debug(`Worker ${Z.id} received job ${G} for queue ${H}`);try{let R=B.get(G);if(!R)throw Z.error(`Job class ${G} not found`),new Error(`Job class ${G} not found`);let P=new R(...M||[]);Z.addJob(P,H),Q.postMessage({type:"job:received",jobId:P.id,queue:H})}catch(R){Z.trace({...R,...Y??{}},`Error while adding job '${G}' to queue '${H}' with worker ${Z.id}`),Q.postMessage({type:"job:error",jobName:G,error:R.message})}break}}),Q.addEventListener("error",($)=>{Z.trace({...$.error,filename:$.filename},`Worker ${Z.id} error:`)}),Q.addEventListener("unhandledrejection",($)=>{Z.trace($,`Worker ${Z.id} unhandled rejection:`)}),Q.postMessage({type:"worker:ready",id:Z.id,queues:X}),Z}constructor(){super();this.#Q=AX(24),this.createQueue({name:this.defaultQueueName})}get id(){return this.#Q}createQueue(Q){if(this.queues.has(Q.name))return this.debug(`Queue with name '${Q.name}' already exists`),this;let X={options:{...Q,concurrency:Q.concurrency||1,maxRetries:Q.maxRetries||0,retryDelay:Q.retryDelay||1000,pauseOnError:Q.pauseOnError||!1},jobs:[],processing:0,paused:!1,draining:!1};return this.queues.set(Q.name,X),this.debug(`Created queue '${Q.name}'`),this}addJob(Q,X=this.defaultQueueName){let Y=this.queues.get(X);if(!Y)return this.error(`Queue '${X}' does not exist`),this;if(Y.draining)return this.warning(`Queue '${X}' is draining, job ${Q.id} will not be added`),this;let Z={job:Q,retries:0,queueName:X};if(Y.jobs.push(Z),this.debug(`Added job ${Q.id} to queue '${X}'`),!Y.paused&&Y.processing<Y.options.concurrency)this.processNextJob(X);return this}pause(Q){if(Q){let X=this.queues.get(Q);if(X)X.paused=!0,this.info(`Paused queue '${Q}'`)}else for(let[X]of this.queues.entries())this.pause(X);return this}resume(Q){if(Q){let X=this.queues.get(Q);if(X)X.paused=!1,this.info(`Resumed queue '${Q}'`),this.processQueueJobs(Q)}else for(let[X]of this.queues.entries())this.resume(X);return this}drain(Q){if(Q){let X=this.queues.get(Q);if(X)X.draining=!0,this.info(`Draining queue '${Q}'`)}else for(let[X]of this.queues.entries())this.drain(X);return this}clear(Q){if(Q){let X=this.queues.get(Q);if(X){let Y=X.jobs.length;X.jobs=[],this.info(`Cleared ${Y} jobs from queue '${Q}'`)}}else for(let[X,Y]of this.queues.entries()){let Z=Y.jobs.length;Y.jobs=[],this.info(`Cleared ${Z} jobs from queue '${X}'`)}return this}size(Q=this.defaultQueueName){let X=this.queues.get(Q);if(!X)throw new Error(`Queue '${Q}' does not exist`);return X.jobs.length}totalSize(){let Q=0;for(let X of this.queues.values())Q+=X.jobs.length;return Q}async processNextJob(Q){let X=this.queues.get(Q);if(!X||X.paused||X.processing>=X.options.concurrency)return;let Y=X.jobs.shift();if(!Y)return;if(Y.job.status==="cancelled"){this.info(`Skipping cancelled job ${Y.job.id}`),X.processing--,this.processQueueJobs(Q);return}X.processing++;try{if(this.debug(`Processing job ${Y.job.id} from queue '${Q}'`),await Y.job.run(),Y.job.status==="failed"){if(Y.retries<X.options.maxRetries)Y.retries++,this.warning(`Job ${Y.job.id} failed, retrying (${Y.retries}/${X.options.maxRetries})`),setTimeout(()=>{if(Y.job.status!=="cancelled")X.jobs.push(Y),this.processQueueJobs(Q);else this.info(`Skipping cancelled job ${Y.job.id} during retry delay`)},X.options.retryDelay);else if(this.error(`Job ${Y.job.id} failed after ${Y.retries} retries`),X.options.pauseOnError)this.pause(Q),this.warning(`Queue '${Q}' paused due to job failure`)}else if(Y.job.status==="completed")this.success(`Job ${Y.job.id} completed successfully`);else this.info(`Job ${Y.job.id} cancelled while running`)}catch(Z){if(this.error(`Unexpected error processing job ${Y.job.id}: ${Z}`),X.options.pauseOnError)this.pause(Q),this.warning(`Queue '${Q}' paused due to unexpected error`)}finally{X.processing--,this.processQueueJobs(Q)}}processQueueJobs(Q){let X=this.queues.get(Q);if(!X||X.paused)return;while(X.jobs.length>0&&X.processing<X.options.concurrency)this.processNextJob(Q)}getStats(){let Q={};for(let[X,Y]of this.queues.entries())Q[X]={waiting:Y.jobs.length,processing:Y.processing,paused:Y.paused,draining:Y.draining};return Q}cancelJob(Q,X){if(X)return this.cancelJobInQueue(Q,X);else{let Y=!1;for(let[Z]of this.queues.entries())if(this.cancelJobInQueue(Q,Z)){Y=!0;break}return Y}}cancelJobInQueue(Q,X){let Y=this.queues.get(X);if(!Y)return!1;let Z=Y.jobs.findIndex(($)=>$.job.id===Q);if(Z>=0)return Y.jobs[Z].job.cancel(),this.info(`Canceled job ${Q} in queue '${X}'`),!0;return!1}cancelAllJobs(Q){let X=0;if(Q){let Y=this.queues.get(Q);if(Y)X=Y.jobs.length,Y.jobs.forEach((Z)=>{Z.job.cancel()}),this.info(`Canceled ${X} jobs in queue '${Q}'`)}else for(let[Y,Z]of this.queues.entries()){let $=Z.jobs.length;Z.jobs.forEach((_)=>{_.job.cancel()}),X+=$,this.info(`Canceled ${$} jobs in queue '${Y}'`)}return X}};zQ=class zQ extends k{workers=[];currentWorkerIndex=0;queueWorkerMap=new Map;static instance=new zQ;constructor(){super()}async init(){}async addWorker(Q=[]){let X;if(ELYSIUM_BUILD)X=new lQ("./index.js",{argv:["work",...Q.map((Y)=>`--queue=${Y}`)]});else{let Y=await Array.fromAsync(new Bun.Glob("./src/**/*.job.ts").scan());X=new lQ("./index.ts",{preload:Y,argv:["work",...Q.map((Z)=>`--queue=${Z}`)]})}X.addEventListener("error",(Y)=>{this.trace({message:"An error occurred inside a worker process",stack:Y.message,name:"WorkerError"}),this.removeWorker(X),this.addWorker(Q)}),X.addEventListener("messageerror",(Y)=>{this.error(`Worker message error: ${Y}`)}),X.addEventListener("message",(Y)=>{if(Y.data.type==="worker:ready")this.debug(`Worker ${Y.data.id} ready with queues: ${Y.data.queues.join(", ")}`);else if(Y.data.type==="job:received")this.debug(`Job ${Y.data.jobId} received by worker for queue ${Y.data.queue}`);else if(Y.data.type==="job:error")this.error(`Error processing job ${Y.data.jobName}: ${Y.data.error}`);else this.debug(`Worker message: ${JSON.stringify(Y.data)}`)}),this.workers.push(X);for(let Y of Q){if(!this.queueWorkerMap.has(Y))this.queueWorkerMap.set(Y,[]);this.queueWorkerMap.get(Y).push(X)}}removeWorker(Q){let X=Q??this.workers.pop();if(!X)return;X.terminate();for(let[Y,Z]of this.queueWorkerMap.entries())this.queueWorkerMap.set(Y,Z.filter(($)=>$!==X));if(Q)this.workers=this.workers.filter((Y)=>Y!==X)}terminate(){while(this.workers.length>0)this.removeWorker();this.queueWorkerMap.clear()}runJob(Q,...X){if(!Reflect.hasMetadata(O.job,Q))throw new Error(`Job ${Q.name} is not marked with @job() decorator`);let{name:Y,queue:Z="default"}=Reflect.getMetadata(O.job,Q),$=this.queueWorkerMap.get(Z)||this.workers;if($.length===0)throw new Error(`No workers available for queue '${Z}'`);let _=this.currentWorkerIndex%$.length;$[_].postMessage({job:Y,args:X,queue:Z}),this.currentWorkerIndex=(this.currentWorkerIndex+1)%this.workers.length}cancelJob(Q,X){for(let Y of this.workers)Y.postMessage({type:"job:cancel",jobId:Q,queue:X});return this.workers.length>0}cancelAllJobs(Q){for(let X of this.workers)X.postMessage({type:"job:cancelAll",queue:Q});return this.workers.length>0}}});global.ELYSIUM_BUILD=typeof ELYSIUM_BUILD!=="undefined";import{t as vZ}from"elysia";e();import{AsyncLocalStorage as EX}from"async_hooks";import{parseArgs as IX}from"util";import{swagger as TX}from"@elysiajs/swagger";import{Value as GQ}from"@sinclair/typebox/value";import{Elysia as xX}from"elysia";import{first as wX}from"radash";import{getTableName as qQ,is as hQ,Table as bQ}from"drizzle-orm";import{drizzle as MX}from"drizzle-orm/bun-sql";import{Cache as JX}from"drizzle-orm/cache/core";import{createCache as SQ}from"cache-manager";import{KeyvCacheableMemory as BX}from"cacheable";import{Keyv as CQ}from"keyv";import{alphabetical as VX}from"radash";import{EventEmitter as zX}from"events";import{omit as RX}from"radash";import{EventEmitter as HX}from"events";import{isString as fQ}from"radash";class q extends HX{static instance=new q;constructor(){super();this.on("error",(Q)=>this.emitError(Q))}emitError(Q){this.emit("elysium:error",{data:Q,source:null})}emitEvent(Q,X,Y=null){this.emit(Q,{data:X,source:Y})}}var w;((m)=>{m.emit=(U,G,M=null)=>{q.instance.emitEvent(U,G,M)};function X(U,G){if(fQ(U))q.instance.on(U,G);else return function(M,H,L){let z=async function(P){try{await L.value(P)}catch(j){q.instance.emitError(j)}};if(U.prepend??!1)q.instance.prependListener(U.event,z);else q.instance.on(U.event,z)}}m.on=X;function Y(U,G){if(fQ(U))q.instance.once(U,G);else return function(M,H,L){let z=async function(P){try{await L.value(P)}catch(j){q.instance.emitError(j)}};if(U.prepend??!1)q.instance.prependOnceListener(U.event,z);else q.instance.once(U.event,z)}}m.once=Y,m.off=(U)=>{q.instance.removeAllListeners(U)},m.clear=()=>{q.instance.removeAllListeners()},m.listen=(U)=>{if(U.mode==="on")return X(U);else if(U.mode==="once")return Y(U);return function(G,M,H){console.error("Unknown mode provided to @listen. Use either 'on' or 'once'.")}}})(w||={});d();class DQ extends zX{#Q;#X;#Y="::";#Z=1000;#$=!0;#_=!1;#U;constructor(Q){super();w.once("elysium:app:launched",()=>{this.#Q=r.getConnection(Q.connection)}),this.#U=Q.connection,this.#X=Q.namespace,this.#Y=Q.keyPrefixSeparator??"::",this.#Z=Q.clearBatchSize??1000,this.#$=Q.useUnlink??!0,this.#_=Q.noNamespaceAffectsAll??!1,this.on("error",(X)=>{w.emit("elysium:error",X)})}get client(){return this.#Q}get opts(){return{namespace:this.#X,keyPrefixSeparator:this.#Y,clearBatchSize:this.#Z,noNamespaceAffectsAll:this.#_,dialect:"redis",url:this.#U}}get namespace(){return this.#X}set namespace(Q){this.#X=Q}async get(Q){Q=this.createKeyPrefix(Q,this.#X);let X=await this.client.get(Q);return X===null?void 0:X}async set(Q,X,Y){if(Q=this.createKeyPrefix(Q,this.#X),Y)await this.client.set(Q,X,"PX",Y);else await this.client.set(Q,X)}async setMany(Q){let X=[];for(let{key:Y,value:Z,ttl:$}of Q){let _=this.createKeyPrefix(Y,this.#X);if($)X.push(this.client.set(_,Z,"PX",$));else X.push(this.client.set(_,Z))}await Promise.all(X)}async delete(Q){return Q=this.createKeyPrefix(Q,this.#X),await(this.#$?this.client.send("UNLINK",[Q]):this.client.del(Q))>0}async clear(){try{if(!this.#X&&this.#_){await this.client.send("FLUSHDB",[]);return}let Q="0",X=this.#Z,Y=this.#X?`${this.#X}${this.#Y}*`:"*",Z=[];do{let $=await this.client.send("SCAN",[Q,"MATCH",Y,"COUNT",X.toString(),"TYPE","string"]),[_,U]=$;if(Q=_.toString(),U.length===0)continue;if(!this.#X)U=U.filter((G)=>!G.includes(this.#Y));Z.push(U.map((G)=>this.client.del(G)))}while(Q!=="0");await Promise.all(Z)}catch(Q){this.emit("error",Q)}}async has(Q){return Q=this.createKeyPrefix(Q,this.#X),this.client.exists(Q)}async hasMany(Q){let X=[];for(let Y of Q){let Z=this.createKeyPrefix(Y,this.#X);X.push(this.client.exists(Z))}return Promise.all(X)}async getMany(Q){if(Q.length===0)return[];return Q=Q.map((Y)=>this.createKeyPrefix(Y,this.#X)),await this.client.mget(...Q)}async disconnect(){this.client.close()}async deleteMany(Q){let X=!1,Y=[];for(let $ of Q){let _=this.createKeyPrefix($,this.#X);if(this.#$)Y.push(this.client.send("UNLINK",[_]));else Y.push(this.client.del(_))}let Z=await Promise.all(Y);for(let $ of Z)if(typeof $==="number"&&$>0)X=!0;return X}async*iterator(Q){let X=Q?`${Q}${this.#Y}*`:"*",Y="0";do{let Z=await this.client.send("SCAN",[Y,"MATCH",X,"TYPE","string"]),[$,_]=Z;if(Y=$.toString(),!Q&&!this.#_)_=_.filter((U)=>!U.includes(this.#Y));if(_.length>0){let U=await this.client.mget(..._);for(let G of _.keys()){let M=this.getKeyWithoutPrefix(_[G],Q),H=U[G];yield[M,H]}}}while(Y!=="0")}createKeyPrefix(Q,X){return X?`${X}${this.#Y}${Q}`:Q}getKeyWithoutPrefix(Q,X){return X?Q.replace(`${X}${this.#Y}`,""):Q}}var r;((h)=>{let Q=(U)=>{return`redis.connection.${U}`};h.getConnection=(U)=>{if(!B.exists(Q(U)))console.error(`No Redis connection with name ${U} found. Please make sure to register the connection before using it.`),process.exit(1);return B.get(Q(U))},h.registerConnection=(U,G)=>{if(B.exists(Q(U)))console.error(`A Redis connection with the name ${U} has already been registered.`),process.exit(1);return B.instance(Q(U),new Bun.RedisClient(G.url,RX(G,["url"])))},h.connectionExists=(U)=>{return B.exists(Q(U))},h.getDefaultConnection=()=>{return h.getConnection("default")},h.setDefaultConnection=(U)=>{let G=Q("default");return B.remove(G),B.instance(G,h.getConnection(U))}})(r||={});var kQ=(Q)=>{let X=SQ({stores:[new CQ({store:Q,namespace:"cache"})]}),Y=new Map;return{...X,tags(...Z){let $=`cache__${VX(Z,(U)=>U).join("__")}`,_=Y.get($);if(!_)_=SQ({stores:[new CQ({store:Q,namespace:$})]}),Y.set($,_);return _}}};class l{static#Q;static#X;static weak=Object.seal({map:new WeakMap,get(Q){if(!this.map.has(Q))this.map.set(Q,{});return this.map.get(Q)},del(Q){this.map.delete(Q)}});static get redis(){if(!l.#Q)l.#Q=kQ(new DQ({connection:"cache"}));return l.#Q}static get memory(){if(!l.#X)l.#X=kQ(new BX({ttl:60000,lruSize:5000}));return l.#X}}d();class KQ extends JX{cacheStrategy;globalTtl;#Q;usedTablesPerKey={};constructor(Q="explicit",X=1,Y="redis"){super();this.cacheStrategy=Q;this.globalTtl=X;this.#Q=l[Y].tags("database")}strategy(){return this.cacheStrategy}async get(Q){return await this.#Q.get(Q)??void 0}async put(Q,X,Y,Z,$){await this.#Q.set(Q,X,($?.ex??this.globalTtl)*1000);for(let _ of Y){let U=this.usedTablesPerKey[_];if(U===void 0)this.usedTablesPerKey[_]=[Q];else U.push(Q)}}async onMutate(Q){let X=Q.tags?Array.isArray(Q.tags)?Q.tags:[Q.tags]:[],Y=Q.tables?Array.isArray(Q.tables)?Q.tables:[Q.tables]:[],Z=new Set;for(let $ of Y){let _=hQ($,bQ)?qQ($):$,U=this.usedTablesPerKey[_]??[];for(let G of U)Z.add(G)}if(Z.size>0||X.length>0){await this.#Q.mdel(X),await this.#Q.mdel([...Z]);for(let $ of Y){let _=hQ($,bQ)?qQ($):$;this.usedTablesPerKey[_]=[]}}}}var p;((b)=>{let Q=(U)=>{return`db.connection.${U}`};b.getConnection=(U)=>{if(!B.exists(Q(U)))console.error(`No connection with name ${U} found. Please make sure to register the connection before using it.`),process.exit(1);return B.get(Q(U))},b.registerConnection=(U,G)=>{if(B.exists(Q(U)))console.error(`A connection with the name ${U} has already been registered.`),process.exit(1);return B.instance(Q(U),MX({...G,cache:G.cache===void 0?void 0:G.cache===!0?new KQ:G.cache.enabled?new KQ(G.cache.strategy,G.cache.ttl,G.cache.storage):void 0}))},b.connectionExists=(U)=>{return B.exists(Q(U))},b.getDefaultConnection=()=>{return b.getConnection("default")},b.setDefaultConnection=(U)=>{let G=Q("default");return B.remove(G),B.instance(G,b.getConnection(U))}})(p||={});var PQ=new Map,jQ=(Q)=>{for(let[X,Y]of Object.entries(Q))PQ.set(X,Y)},vQ;((XQ)=>(XQ.get=(Z,$)=>{return PQ.get(Z)??$},XQ.exists=(Z)=>{return PQ.has(Z)},XQ.clear=()=>{PQ.clear()}))(vQ||={});d();g();var u=(Q,X,Y)=>{return N.context.run(new Map([["tenant",X.tenant],["http:context",X]]),async()=>{for(let Z of Q)try{let $=await Z[Y](X);if($!==void 0)return $}catch($){throw $}})},YQ=(Q,X)=>{let Y=Q.map((Z)=>B.make(Z));X.onRequest((Z)=>{return u(Y,Z,"onRequest")}),X.onTransform((Z)=>{return u(Y,Z,"onTransform")}),X.onBeforeHandle((Z)=>{return u(Y,Z,"onBeforeHandle")}),X.onAfterHandle((Z)=>{return u(Y,Z,"onAfterHandle")}),X.onAfterResponse((Z)=>{return u(Y,Z,"onAfterResponse")})};class yQ{static register(...Q){return function(X,Y,Z){if(Y===void 0&&Z===void 0){let $=Reflect.getMetadata(O.middlewares,X)??[];$.push(...Q),Reflect.defineMetadata(O.middlewares,$,X)}else{let $=Reflect.getMetadata(O.middlewares,X,Y)??[];$.push(...Q),Reflect.defineMetadata(O.middlewares,$,X,Y)}}}static guards(Q){class X extends this{}return Reflect.defineMetadata(O.middlewareGuards,Q,X),X}get guards(){return Reflect.getMetadata(O.middlewareGuards,this.constructor)??[]}onRequest(Q){}onTransform(Q){}onAfterHandle(Q){}onBeforeHandle(Q){}onAfterResponse(Q){}}d();g();import{Elysia as WX}from"elysia";import{omit as DX}from"radash";import KX from"wampy";d();g();class gQ extends WebSocket{protocols;constructor(Q,X){super(Q,X);this.protocols=X}get protocol(){return this.protocols?.[0]??"wamp.2.json"}}var t;((f)=>{let Q=(H)=>{return`wamp.connection.${H}`};f.getConnection=(H)=>{if(!B.exists(Q(H)))console.error(`No WAMP connection with name ${H} found. Please make sure to register the connection before using it.`),process.exit(1);return B.get(Q(H))},f.registerConnection=(H,L)=>{if(B.exists(Q(H)))console.error(`A WAMP connection with name ${H} already exists. Please ensure to register a new connection before overwriting it.`),process.exit(1);let z=new KX(L.url,{ws:gQ,...DX(L,["url"]),onError(){L.onError?.(),w.emit("elysium:error",new Error(`An error occurred in WAMP connection ${H}`))}}),R=L.maxRetries??5,P=L.retryInterval??5000,j=0,C=async()=>{try{await z.connect()}catch(y){if(console.error(`Failed to connect to WAMP server (attempt ${j+1}/${R}):`,y),j<R)j++,setTimeout(C,P);else console.error(`Max retry attempts (${R}) reached. Giving up.`),w.emit("elysium:error",new Error(`Failed to establish WAMP connection ${H} after ${R} attempts`))}};return C(),B.instance(Q(H),z)},f.connectionExists=(H)=>{return B.exists(Q(H))},f.getDefaultConnection=()=>{return f.getConnection("default")},f.setDefaultConnection=(H)=>{let L=Q("default");return B.remove(L),B.instance(L,f.getConnection(H))},f.controller=(H)=>{return function(L){async function z(){console.log(`Registering Wamp controller for connection ${H.connection} using ${L.name}`),await n();let R=B.make(L),P=Reflect.getMetadata(O.wamp,L)??{},j=t.getConnection(H.connection??"default"),C=new WX;return C.onStart(async(y)=>{let V=P.registrations??[],W=P.subscriptions??[];for(let J of V)j.register(J.topic,J.handler.bind(R),J.options).then((I)=>{console.log(`Registered ${J.topic} with id ${I.registrationId}`)});for(let J of W)j.subscribe(J.topic,J.handler.bind(R),J.options).then((I)=>{console.log(`Subscribed ${J.topic} with id ${I.subscriptionId}`)})}),C}Reflect.defineMetadata(O.elysiaPlugin,z,L)}},f.register=(H,L)=>{return function(z,R,P){let j=Reflect.getMetadata(O.wamp,z.constructor)??{};j.registrations??=[],j.registrations.push({topic:H,options:L,handler:P.value}),Reflect.defineMetadata(O.wamp,j,z.constructor)}},f.subscribe=(H,L)=>{return function(z,R,P){let j=Reflect.getMetadata(O.wamp,z.constructor)??{};j.subscriptions??=[],j.subscriptions.push({topic:H,options:L,handler:P.value}),Reflect.defineMetadata(O.wamp,j,z.constructor)}}})(t||={});class N extends k{#Q;#X;_appContextStorage=new EX;static get instance(){return B.get("elysium.app")}static get context(){return N.instance._appContextStorage}static register(Q={}){return function(X){let Y,Z=Object.getPrototypeOf(X);while(Z&&Z!==Object.prototype){let _=Reflect.getMetadata(O.app,Z);if(_){Y=_;break}Z=Object.getPrototypeOf(Z)}if(Y)Q=o(Y,Q);let $=Reflect.getMetadata(O.app,X);if($)Q=o($,Q);Q=o({modules:[],swagger:!1},Q),Reflect.defineMetadata(O.app,Q,X)}}constructor(){super();let{env:Q,debug:X}=Reflect.getMetadata(O.app,this.constructor)??{};if(this.#X=X??!1,Q){let _=GQ.Convert(Q,GQ.Clone(Bun.env));if(this.#X&&!GQ.Check(Q,_)){let U=GQ.Errors(Q,_).First();this.trace(U,"Invalid environment configuration")}jQ(GQ.Clean(Q,_))}else jQ(Bun.env);B.instance("elysium.app",this);let{database:Y,redis:Z,wamp:$}=Reflect.getMetadata(O.app,this.constructor);if(Z){for(let _ in Z.connections)r.registerConnection(_,Z.connections[_]);if(r.connectionExists(Z.default))r.setDefaultConnection(Z.default)}if(Y){for(let _ in Y.connections)p.registerConnection(_,Y.connections[_]);if(p.connectionExists(Y.default))p.setDefaultConnection(Y.default)}if($){for(let _ in $.connections)t.registerConnection(_,$.connections[_]);if(t.connectionExists($.default))t.setDefaultConnection($.default)}this.run().then(()=>w.emit("elysium:app:launched",this,this)).catch((_)=>{w.emit("elysium:error",_),this.trace(_,"An error occurred while launching the application"),process.exit(1)})}get elysia(){return this.#Q}get isDebug(){return this.#X}set isDebug(Q){this.#X=Q}async onError(Q){return!0}async onStart(Q){}async onStop(Q){}async run(){let Q=process.argv.slice(2),X=Q[0];if(!X)this.commandDescribe();else{let{commands:Y}=Reflect.getMetadata(O.app,this.constructor);switch(X){case"serve":return this.commandServe();case"work":return this.commandWork(Q.slice(1));case"help":{let Z=Q[1];if(Z){let $=Y?.find((_)=>_.command===Z);if($){let _=B.make($);return this.write(await _.help()),process.exit(0)}console.error(`Command <${Z}> not found.`)}else console.error("No command provided. Usage: styx help <command>");this.commandList();break}case"list":{this.write(this.bold("Available commands:")),this.commandList();break}default:{let Z=Q.slice(1);return this.commandExec(X,Z)}}}return process.exit(0)}getConfig(Q){return Reflect.getMetadata(O.app,this.constructor)?.[Q]??null}async commandExec(Q,X){let{commands:Y}=Reflect.getMetadata(O.app,this.constructor),Z=Y?.find(($)=>$.command===Q);if(!Z)return console.error(`Command ${Q} not found`),this.commandList(),process.exit(1);try{let $=B.make(Z);if(await $.init(...X))await $.run();else{let U=await $.help();this.write(U)}return process.exit(0)}catch($){return console.error($.message),process.exit(1)}}async commandWork(Q){this.info("Starting worker process...");let{values:X}=IX({args:Q,options:{queue:{type:"string",multiple:!0,default:["default"],short:"q"},concurrency:{type:"string",default:"1",short:"c"},["max-retries"]:{type:"string",default:"5",short:"r"},["retry-delay"]:{type:"string",default:"5000",short:"d"},["pause-on-error"]:{type:"boolean",default:!1,short:"p"}}}),{Worker:Y}=await Promise.resolve().then(() => (EQ(),pQ)),Z=X.queue.map((_)=>_.split(",")).reduce((_,U)=>_.concat(U),[]),$=Y.spawn(self,Z,{concurrency:parseInt(X.concurrency,10),maxRetries:parseInt(X["max-retries"],10),retryDelay:parseInt(X["retry-delay"],10),pauseOnError:X["pause-on-error"]});this.success(`Worker process ${this.format($.id,2)} started with queues: ${Z.map((_)=>this.format(_,6)).join(", ")}`)}async commandServe(){let{server:Q,modules:X,swagger:Y,plugins:Z}=Reflect.getMetadata(O.app,this.constructor);if(this.#Q=new xX(Q).onRequest((_)=>{if(this.isDebug)console.log(_.request.method,_.request.url)}),w.emit("elysium:server:before-init",this,this),this.#Q.resolve({as:"global"},({request:_})=>({tenant:_.headers.get("x-tenant-id")??"public"})),Y)this.#Q.use(TX(Y));if(Z&&Z.length>0){this.debug("Registering plugins...");for(let _ of Z)this.#Q.use(await _(this))}this.#Q.onError({as:"global"},async(_)=>{if(await this.onError(_)){w.emit("elysium:error",_),this.trace({name:"HttpError",message:"Unexpected error while handling HTTP request",stack:_.error.stack,..._.error});let U={};if(typeof _.code==="number")return _.error.response;else switch(_.code){case"VALIDATION":{U={scope:_.error.type,code:_.error.message};break}case"INTERNAL_SERVER_ERROR":{U={message:_.error.message};break}}return{type:_.code,data:U}}}).onStart(async(_)=>{await this.onStart(_),w.emit("elysium:server:start",_,this)}).onStop(async(_)=>{await this.onStop(_),w.emit("elysium:server:stop",_,this),this._appContextStorage.disable()});let $=Reflect.getMetadata(O.middlewares,this.constructor)??[];YQ($,this.#Q);for(let _ of X){let U=Reflect.getMetadata(O.elysiaPlugin,_);if(U===void 0)return console.error(`Invalid module class ${_.name} registered in app ${this.constructor.name}. Ensure that you used the @module() decorator on the module.`),process.exit(1);let G=B.bind(_);await G.beforeRegister(),this.#Q.use(await U(G)),await G.afterRegister()}w.emit("elysium:server:after-init",this,this),this.#Q.listen(Q?.port??(parseInt(process.env.PORT,10)||3000)),process.on("SIGINT",()=>{this.#Q.stop().then(()=>process.exit(0))})}commandDescribe(){this.section(`${this.bold("Usage:")} ${this.format("styx",5)} <command> [options]`),this.section(this.bold("Core Commands:")),this.newLine(),this.commandDescription("serve","","Starts the server."),this.commandDescription("help","<command>","Displays help for a command."),this.commandDescription("list","","List all available application commands."),this.section(this.bold("Application Commands:")),this.commandList()}commandList(){let{commands:Q}=Reflect.getMetadata(O.app,this.constructor),X=(Q??[]).reduce((Y,Z)=>{let $=wX(Z.command.split(":")),_=Y.get($)??[];return _.push(Z),Y.set($,_),Y},new Map);for(let[Y,Z]of X){this.section(this.format(Y,4));for(let $ of Z)this.commandDescription($.command,"",$.description)}}commandDescription(Q,X,Y,Z=k.SPACE_WIDTH){X=X.length===0?" ":` ${X} `,this.write(` ${this.format(Q,6)}${X}${"\u2219".repeat(Z-Q.length-X.length)} ${Y}`)}}e();g();import{isArray as fX,trim as NX}from"radash";var uQ;((_)=>{_.STRING="string";_.NUMBER="number";_.BOOLEAN="boolean";_.ENUM="enum";_.ARRAY="array"})(uQ||={});class cQ extends k{static command="command";static description="Command description";static arg(Q={}){return function(X,Y){let Z=Reflect.getMetadata(O.arg,X.constructor)??[],$=Reflect.getMetadata("design:type",X,Y),_=Q.type;if(!_&&$){if($===Array){if(_="array",!Q.arrayType)Q={...Q,arrayType:"string"}}else if($.constructor!==Object)switch($.name.toLowerCase()){case"number":_="number";break;case"boolean":_="boolean";break;case"string":_="string";break;default:_=void 0}else if(Object.values($).length>0){if(_="enum",!Q.enum)Q={...Q,enum:Object.values($)}}}Z.push({name:Q.name??Y,description:Q.description,required:Q.required??!1,default:Q.default,type:_,enum:Q.enum,arrayType:Q.arrayType,propertyKey:Y}),Reflect.defineMetadata(O.arg,Z,X.constructor)}}async init(...Q){let X=this.processArgs(Q),Y=this.validateArgs(X);if(!Y.valid){if(Y.missing.length>0)console.error(`Missing required arguments: ${Y.missing.join(", ")}
9
+ `);return!1}if(Object.keys(X).includes("help"))return!1;let Z=this.getArguments();for(let $ of Z)if(X[$.name]!==void 0)this[$.propertyKey]=X[$.name];return!0}getArguments(){return Reflect.getMetadata(O.arg,this.constructor)||[]}async help(){let Q=`${this.bold("Command:")} ${this.format(this.constructor.command,5)}
10
+ `;Q+=`${this.bold("Description:")} ${this.constructor.description}
11
11
 
12
- `;let Y=this.getArguments();if(Y.length>0){L+=`${this.bold("Arguments:")}
13
- `;for(let Q of Y){let X=this.format(Q.required?"(required)":"(optional)",1,9),Z=Q.default!==void 0?this.format(`[default: ${Q.default}]`,8,11):"",$="";if(Q.type==="array")$=`<array of ${Q.arrayType||"string"}s>`;else if(Q.type)$=`<${Q.type}>`;let U=Q.enum?` [${Q.enum.join("|")}]`:"";if(L+=` ${this.format(`--${Q.name}`,6)} ${$}${U} ${X} ${Z}
14
- `,Q.description)L+=` ${Q.description}
12
+ `;let X=this.getArguments();if(X.length>0){Q+=`${this.bold("Arguments:")}
13
+ `;for(let Y of X){let Z=this.format(Y.required?"(required)":"(optional)",1,9),$=Y.default!==void 0?this.format(`[default: ${Y.default}]`,8,11):"",_="";if(Y.type==="array")_=`<array of ${Y.arrayType||"string"}s>`;else if(Y.type)_=`<${Y.type}>`;let U=Y.enum?` [${Y.enum.join("|")}]`:"";if(Q+=` ${this.format(`--${Y.name}`,6)} ${_}${U} ${Z} ${$}
14
+ `,Y.description)Q+=` ${Y.description}
15
15
 
16
- `}}else L+=`This command has no arguments.
17
- `;return N0(L,`
18
- `)}validateArgs(L){let Y=[],Q=[],X=this.getArguments();if(Object.keys(L).includes("help"))return{valid:!0,missing:[]};for(let Z of X){if(Z.required&&(L[Z.name]===void 0||L[Z.name]===null)){Y.push(Z.name);continue}if(L[Z.name]===void 0)continue;if(Z.type==="enum"&&Z.enum&&!Z.enum.includes(L[Z.name]))Q.push(`${Z.name} (must be one of: ${Z.enum.join(", ")})`);if(Z.type==="array"&&Z.arrayType==="enum"&&Z.enum){let $=L[Z.name].filter((U)=>!Z.enum.includes(U));if($.length>0)Q.push(`${Z.name} (contains invalid values: ${$.join(", ")}. Must be one of: ${Z.enum.join(", ")})`)}}if(Q.length>0)console.error(`Invalid argument values: ${Q.join(", ")}
19
- `);return{valid:Y.length===0&&Q.length===0,missing:Y}}processArgs(L){let Y={},Q=this.getArguments();for(let X=0;X<L.length;X++){let Z=L[X];if(Z.startsWith("--")){let $=Z.slice(2);if(X+1<L.length&&!L[X+1].startsWith("--"))Y[$]=L[X+1],X++;else Y[$]=!0}}for(let X of Q){if(Y[X.name]===void 0&&X.default!==void 0){Y[X.name]=X.default;continue}if(Y[X.name]===void 0)continue;if(typeof Y[X.name]==="string")switch(X.type||this.inferType(X.default)){case"number":Y[X.name]=Number(Y[X.name]);break;case"boolean":let $=Y[X.name].toLowerCase();Y[X.name]=$==="true"||$==="1"||$==="yes";break;case"enum":if(X.enum&&X.enum.length>0&&typeof X.enum[0]==="number")Y[X.name]=Number(Y[X.name]);break;case"array":let U=Y[X.name].split(",").map((_)=>_.trim());if(X.arrayType)Y[X.name]=U.map((_)=>{switch(X.arrayType){case"number":return Number(_);case"boolean":return _.toLowerCase()==="true"||_.toLowerCase()==="1"||_.toLowerCase()==="yes";case"enum":return _;default:return _}});else Y[X.name]=U;break;case"string":default:break}}return Y}progress(L,Y="Processing"){return new c2(L,Y)}spinner(L="Processing",Y,Q){return new m2(L,Y,Q)}inferType(L){if(L===void 0)return"string";switch(typeof L){case"number":return"number";case"boolean":return"boolean";default:return w0(L)?"array":"string"}}}class c2 extends k{#L=!1;#Y=0;#Q=0;#X="";#Z=0;constructor(L=0,Y="Processing"){super();this.#Y=L,this.#X=Y,this.#L=!0,this.#Q=0,this.#Z=Date.now(),this.update(0)}update(L=1,Y){if(!this.#L)return;if(this.#Q+=L,Y)this.#X=Y;let Q=Math.min(100,Math.floor(this.#Q/this.#Y*100)),Z=(Date.now()-this.#Z)/1000,$=0,U=0,_="";if(this.#Q>0)$=Z/this.#Q*this.#Y,U=Math.max(0,$-Z),_=` | ${this.formatTime(Z)} elapsed | ${this.formatTime(U)} remaining`;let V=30,H=Math.floor(Q/100*V),G=V-H,R="["+"=".repeat(H)+(G>0?">":"")+" ".repeat(Math.max(0,G-(G>0?1:0)))+"]",W=`${this.#X}: ${R} ${Q}% (${this.#Q}/${this.#Y})${_}`;if(this.clearLine(),this.write(W,!1),this.#Q>=this.#Y)this.complete()}complete(L){if(!this.#L)return;this.#Q=this.#Y;let Q=(Date.now()-this.#Z)/1000;if(this.clearLine(),L)this.write(`${L} (completed in ${this.formatTime(Q)})`);else this.write(`${this.#X} completed in ${this.formatTime(Q)}`);this.#L=!1}pause(L){if(!this.#L)return;this.newLine(),this.write(L),this.update(0)}isActive(){return this.#L}getCurrent(){return this.#Q}getTotal(){return this.#Y}getPercentage(){return Math.min(100,Math.floor(this.#Q/this.#Y*100))}}class m2 extends k{#L=!1;#Y="";#Q=0;#X=null;#Z=0;#$=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];#U=80;constructor(L="Processing",Y,Q){super();if(this.#Y=L,Y)this.#$=Y;if(Q)this.#U=Q;if(this.#L)return;this.#L=!0,this.#Q=Date.now(),this.#Z=0,this.#X=setInterval(()=>{this.render()},this.#U),this.render()}update(L){if(!this.#L)return;this.#Y=L}complete(L,Y=!0){if(!this.#L)return;if(this.#X)clearInterval(this.#X),this.#X=null;let X=(Date.now()-this.#Q)/1000;this.clearLine();let Z=this.formatTime(X);if(L)this[Y?"success":"error"](`${L} (${Z})`);else this[Y?"success":"error"](`${this.#Y} completed in ${Z}`);this.#L=!1}fail(L){this.complete(L,!1)}pause(L){if(!this.#L)return;if(this.#X)clearInterval(this.#X),this.#X=null;this.clearLine(),this.write(L),this.#X=setInterval(()=>{this.render()},this.#U)}isActive(){return this.#L}getElapsedTime(){return(Date.now()-this.#Q)/1000}render(){if(!this.#L)return;let L=this.getElapsedTime(),Y=this.#$[this.#Z];this.#Z=(this.#Z+1)%this.#$.length,this.clearLine(),this.write(`${Y} ${this.#Y} (${this.formatTime(L)})`,!1)}}e();import{Elysia as S0,sse as C0,t as n2}from"elysia";import{assign as k0,isEmpty as W2,objectify as q0}from"radash";d();g();var h0=(L)=>{let Y=Reflect.getMetadata("http:body",L.target,L.propertyKey),Q=Reflect.getMetadata("http:params",L.target,L.propertyKey)??[],X=Reflect.getMetadata("http:query",L.target,L.propertyKey),Z=Reflect.getMetadata("http:rawContext",L.target,L.propertyKey),$=Reflect.getMetadata("http:customDecorators",L.target,L.propertyKey)??[],U=Reflect.getMetadata(O.middlewares,L.target,L.propertyKey)??[],_=Reflect.getMetadata(O.services,L.target,L.propertyKey)??[],{path:V,method:H,handler:G,target:R,response:W,operationId:P,description:K,transactional:C}=L,y=Reflect.getMetadata(O.http,R.constructor)??[];y.push({path:V,method:H,body:Y,params:Q,query:X,customDecorators:$,rawContext:Z,handler:G,middlewares:U,response:W,operationId:P,description:K,services:_,transactional:C}),Reflect.defineMetadata(O.http,y,R.constructor)},s2;((Q)=>{Q[Q.SERVER=0]="SERVER";Q[Q.REQUEST=1]="REQUEST"})(s2||={});var o2;((J)=>(J.controller=(B={path:"/"})=>{return function(D){async function M(){console.log(`Registering HTTP controller for ${B.path} using ${D.name}`),await n(),B=k0({path:"/",scope:0,tags:[]},B);let I=new S0({prefix:B.path,name:D.name}),i=(()=>{if(B.scope===0)return()=>{let A=z.make(D);return()=>A};else if(B.scope===1)return()=>()=>z.make(D);else throw new Error(`Invalid scope for controller: ${D.name}`)})();I.resolve({as:"local"},()=>({controller:i()}));let X2=Reflect.getMetadata("http:onRequest",D)??{};if(X2.handler)I.onRequest((A)=>{let a=i()();return X2.handler.call(a,A)});let e2=Reflect.getMetadata(O.middlewares,D)??[];Q2(e2,I);let L0=Reflect.getMetadata(O.http,D)??[];for(let A of L0){let a=async(F)=>{let j=[];if(A.rawContext)j[A.rawContext.index]=F;if(A.body)j[A.body.index]=F.body;if(A.query)j[A.query.index]=F.query;if(!W2(A.params))for(let x of A.params)j[x.index]=F.params[x.slug];if(!W2(A.customDecorators))for(let x of A.customDecorators)j[x.index]=await x.handler(F);if(!W2(A.services))for(let x of A.services)j[x.index]=z.get(x.name);return j},Y0=A.handler.constructor.name.includes("GeneratorFunction"),x2=A.method==="elysium:SSE",Q0=A.transactional??B.transactional??!1,M2=A.body&&A.body.schema===void 0&&A.body.validator!==void 0;A.method=x2?"GET":A.method;let X0=()=>{let F=(j)=>{if(Q0)return function(...x){return l.getDefaultConnection().transaction((H2)=>{return N.context.run(new Map([["tenant",j.tenant],["http:context",j],["db:tx",H2]]),()=>{try{return A.handler.call(j.controller(),...x)}catch(Z2){throw H2.rollback(),Z2}})})};return function(...x){return N.context.run(new Map([["tenant",j.tenant],["http:context",j]]),()=>A.handler.call(j.controller(),...x))}};if(Y0)return async function*(j){let x=F(j),H2=await a(j);try{for await(let Z2 of x(...H2))yield Z2}catch(Z2){yield Z2}};if(x2)return async function*(j){let x=F(j);j.set.headers["content-type"]="text/event-stream",j.set.headers["cache-control"]="no-cache",j.set.headers.connection="keep-alive";while(!0)yield C0(await x(...await a(j))),await Bun.sleep(10)};if(M2)return async function(j){if(await A.body.validator.validate(j))return await F(j)(...await a(j));throw j.status(400,"Invalid request body")};return async function(j){return await F(j)(...await a(j))}},f2=q0(A.params??[],(F)=>F.slug,(F)=>F.schema),G2=A.middlewares.map((F)=>z.make(F));I.route(A.method,A.path,X0(),{config:{},async transform(F){if(M2&&!await A.body.validator.authorize(F))throw F.status(401,"Unauthorized");return u(G2,F,"onTransform")},beforeHandle(F){return u(G2,F,"onBeforeHandle")},afterHandle(F){return u(G2,F,"onAfterHandle")},afterResponse(F){return u(G2,F,"onAfterResponse")},detail:{tags:B.tags,description:A.description,operationId:A.operationId},body:M2?A.body?.validator?.schema:A.body?.schema,response:A.response,params:W2(f2)?void 0:n2.Object(f2)})}return I}Reflect.defineMetadata(O.elysiaPlugin,M,D)}},J.sse=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"elysium:SSE",path:D,...M})},J.get=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"GET",path:D,...M})},J.post=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"POST",path:D,...M})},J.put=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"PUT",path:D,...M})},J.del=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"DELETE",path:D,...M})},J.patch=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"PATCH",path:D,...M})},J.head=(B={})=>{let{path:D="/",...M}=B??{};return J.custom({method:"HEAD",path:D,...M})},J.options=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"OPTIONS",path:D,...M})},J.trace=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"TRACE",path:D,...M})},J.custom=({path:B="/",...D})=>{return function(M,I,i){process.nextTick(()=>{h0({path:B,handler:i.value,target:M,propertyKey:I,...D})})}},J.onRequest=()=>{return function(B,D,M){let I=Reflect.getMetadata("http:onRequest",B.constructor)??{};I.handler=M.value,Reflect.defineMetadata("http:onRequest",I,B.constructor)}},J.context=()=>{return function(B,D,M){Reflect.defineMetadata("http:rawContext",{index:M},B,D)}},J.param=(B,D)=>{return function(M,I,i){let X2=Reflect.getMetadata("http:params",M,I)??[];X2.push({slug:B,schema:D??n2.String(),index:i}),Reflect.defineMetadata("http:params",X2,M,I)}},J.query=(B)=>{return function(D,M,I){Reflect.defineMetadata("http:query",{schema:B,index:I},D,M)}},J.body=(B)=>{return function(D,M,I){if(typeof B==="function")Reflect.defineMetadata("http:body",{validator:B,index:I},D,M);else Reflect.defineMetadata("http:body",{schema:B,index:I},D,M)}},J.decorate=(B)=>{return()=>{return function(D,M,I){let i=Reflect.getMetadata("http:customDecorators",D,M)??[];i.push({handler:B,index:I}),Reflect.defineMetadata("http:customDecorators",i,D,M)}}}))(o2||={});j2();import{getTableConfig as b0,pgSchema as v0,pgTable as r2}from"drizzle-orm/pg-core";import{t as S}from"elysia";var I2=(L,{mode:Y="select"}={})=>{let{columns:Q}=b0(L);if(Q===void 0)return S.Object({});let X={};for(let Z of Q){if(["create","update"].includes(Y)&&Z.primary)continue;if(X[Z.name]=y0(Z),!Z.notNull)X[Z.name]=S.Nullable(X[Z.name]);if(Y==="update"||Z.hasDefault||!Z.notNull)X[Z.name]=S.Optional(X[Z.name])}return S.Object(X)},y0=(L)=>{let Y=(()=>{switch(L.dataType){case"string":return S.String({format:L.columnType==="PgUUID"?"uuid":void 0});case"number":return S.Number();case"boolean":return S.Boolean();case"array":return S.Array(S.Any());case"json":return S.Object({});case"date":case"localDate":case"localDateTime":return S.String({format:L.dataType==="date"?"date":"date-time"});case"bigint":return S.BigInt();case"buffer":return S.File();default:return S.Never()}})();if(!L.notNull)Y=S.Optional(Y);else Y=S.Required(Y);return Y},g0=(L,Y,Q)=>{let X=r2(L,Y,Q);class Z{static $inferSelect=X.$inferSelect;static $inferInsert=X.$inferInsert;static $inferUpdate=X.$inferInsert;static get table(){if(!N.instance||!N.context.getStore)return X;if(this.supportTenancy){let $=B2.getCurrentTenant()??"public";return B2.wrapTenant($,this)}return X}static tableName=L;static columns=Y;static extraConfig=Q;static insertSchema=I2(X,{mode:"create"});static updateSchema=I2(X,{mode:"update"});static selectSchema=I2(X,{mode:"select"});static supportTenancy=!1}return Z},T2=new Map,z2=new Map,B2;((c)=>{let L=($)=>{return z2.get($)??c.registerTenant($)};c.getCurrentTenant=()=>{return N.context.getStore()?.get("tenant")??null},c.wrapTenant=($,U)=>{if($==="public")return r2(U.tableName,U.columns);let _=`${$}.${U.tableName}`;if(T2.has(_))return T2.get(_);let H=L($).table(U.tableName,U.columns);return T2.set(_,H),H},c.registerTenant=($)=>{if(z2.has($))return z2.get($);let U=v0($);return z2.set($,U),U},c.withTenant=($,U)=>{let _=N.context.getStore(),V=new Map(_);return V.set("tenant",$),N.context.run(V,U)}})(B2||={});import{Elysia as d0}from"elysia";import{assign as p0}from"radash";g();class t2{static register(L={}){return function(Y){async function Q(X){console.log(`Registering module ${Y.name}`),await n();let Z=p0({controllers:[]},L),$=new d0({name:Y.name,prefix:L.prefix});$.resolve({as:"local"},()=>({module:X}));let U=Reflect.getMetadata(O.middlewares,Y)??[];Q2(U,$);for(let _ of Z.controllers){let V=Reflect.getMetadata(O.elysiaPlugin,_);if(V===void 0)console.error(`Invalid controller class ${_.name} registered in module ${Y.name}. Ensure that you either used the @Http.controller(), the @Websocket.controller(), or the @Wamp.controller() decorators on the class.`),process.exit(1);else $.use(await V())}return $}Reflect.defineMetadata(O.elysiaPlugin,Q,Y)}}beforeRegister(){return Promise.resolve()}afterRegister(){return Promise.resolve()}}import{eq as V2}from"drizzle-orm";var l0=(L)=>{class Y{static Model=L;static connection="default";get db(){let Q=this.constructor.connection,X=null;if(Q==="default")X=N.context.getStore()?.get("db:tx")??null;return X??l.getConnection(Q)}async all(){return await this.db.select().from(L.table)}async paginate(Q,X=1){let Z=await this.db.$count(L.table),$=Math.max(X-1,0)*Q;return{page:X,total:Z,data:await this.db.select().from(L.table).offset($).limit(Q)}}async find(Q){let[X]=await this.db.select().from(L.table).where(V2(L.table.id,Q));return X??null}async findBy(Q,X){let[Z]=await this.db.select().from(L.table).where(V2(L.table[Q],X));return Z??null}async insert(Q){let[X]=await this.db.insert(L.table).values(Q).returning();return X}async update(Q,X){let[Z]=await this.db.update(L.table).set(X).where(V2(L.table.id,Q)).returning();return Z}async updateAll(Q){return await this.db.update(L.table).set(Q).returning()}async delete(Q){let[X]=await this.db.delete(L.table).where(V2(L.table.id,Q)).returning();return X}async deleteAll(){return await this.db.delete(L.table).returning()}}return Y};d();import{Elysia as u0}from"elysia";d();g();var a2;((v)=>(v.controller=(U)=>{return function(_){async function V(){console.log(`Registering Websocket route for ${U.path} using ${_.name}`),await n();let H=z.make(_),G=Reflect.getMetadata(O.websocket,_)??{},R=G.open?.bind(H),W=G.close?.bind(H),P=G.message?.bind(H),K=G.drain?.bind(H),C=G.error?.bind(H)??((B)=>f.emit("elysium:error",B.error)),y=new u0;return y.ws(U.path,{open:R,close:W,message:P,drain:K,error:C,body:G.body,...U.options}),y}Reflect.defineMetadata(O.elysiaPlugin,V,_)}},v.onOpen=()=>{return function(U,_,V){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.open=V.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onClose=()=>{return function(U,_,V){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.close=V.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onMessage=(U)=>{return function(_,V,H){let G=Reflect.getMetadata(O.websocket,_.constructor)??{};G.message=H.value,G.body=U,Reflect.defineMetadata(O.websocket,G,_.constructor)}},v.onDrain=()=>{return function(U,_,V){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.drain=V.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onError=()=>{return function(U,_,V){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.error=V.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}}))(a2||={});E2();export{vY as t,R2 as WorkerPool,F2 as Worker,a2 as Websocket,t as Wamp,B2 as Tenancy,N2 as ServiceScope,z as Service,l0 as Repository,r as Redis,t2 as Module,g0 as Model,y2 as Middleware,d2 as Job,k as InteractsWithConsole,s2 as HttpControllerScope,o2 as Http,f as Event,v2 as Env,l as Database,O2 as ConsoleFormat,u2 as CommandArgumentType,i2 as Command,p as Cache,N as Application};
16
+ `}}else Q+=`This command has no arguments.
17
+ `;return NX(Q,`
18
+ `)}validateArgs(Q){let X=[],Y=[],Z=this.getArguments();if(Object.keys(Q).includes("help"))return{valid:!0,missing:[]};for(let $ of Z){if($.required&&(Q[$.name]===void 0||Q[$.name]===null)){X.push($.name);continue}if(Q[$.name]===void 0)continue;if($.type==="enum"&&$.enum&&!$.enum.includes(Q[$.name]))Y.push(`${$.name} (must be one of: ${$.enum.join(", ")})`);if($.type==="array"&&$.arrayType==="enum"&&$.enum){let _=Q[$.name].filter((U)=>!$.enum.includes(U));if(_.length>0)Y.push(`${$.name} (contains invalid values: ${_.join(", ")}. Must be one of: ${$.enum.join(", ")})`)}}if(Y.length>0)console.error(`Invalid argument values: ${Y.join(", ")}
19
+ `);return{valid:X.length===0&&Y.length===0,missing:X}}processArgs(Q){let X={},Y=this.getArguments();for(let Z=0;Z<Q.length;Z++){let $=Q[Z];if($.startsWith("--")){let _=$.slice(2);if(Z+1<Q.length&&!Q[Z+1].startsWith("--"))X[_]=Q[Z+1],Z++;else X[_]=!0}}for(let Z of Y){if(X[Z.name]===void 0&&Z.default!==void 0){X[Z.name]=Z.default;continue}if(X[Z.name]===void 0)continue;if(typeof X[Z.name]==="string")switch(Z.type||this.inferType(Z.default)){case"number":X[Z.name]=Number(X[Z.name]);break;case"boolean":let _=X[Z.name].toLowerCase();X[Z.name]=_==="true"||_==="1"||_==="yes";break;case"enum":if(Z.enum&&Z.enum.length>0&&typeof Z.enum[0]==="number")X[Z.name]=Number(X[Z.name]);break;case"array":let U=X[Z.name].split(",").map((G)=>G.trim());if(Z.arrayType)X[Z.name]=U.map((G)=>{switch(Z.arrayType){case"number":return Number(G);case"boolean":return G.toLowerCase()==="true"||G.toLowerCase()==="1"||G.toLowerCase()==="yes";case"enum":return G;default:return G}});else X[Z.name]=U;break;case"string":default:break}}return X}progress(Q,X="Processing"){return new iQ(Q,X)}spinner(Q="Processing",X,Y){return new mQ(Q,X,Y)}inferType(Q){if(Q===void 0)return"string";switch(typeof Q){case"number":return"number";case"boolean":return"boolean";default:return fX(Q)?"array":"string"}}}class iQ extends k{#Q=!1;#X=0;#Y=0;#Z="";#$=0;constructor(Q=0,X="Processing"){super();this.#X=Q,this.#Z=X,this.#Q=!0,this.#Y=0,this.#$=Date.now(),this.update(0)}update(Q=1,X){if(!this.#Q)return;if(this.#Y+=Q,X)this.#Z=X;let Y=Math.min(100,Math.floor(this.#Y/this.#X*100)),$=(Date.now()-this.#$)/1000,_=0,U=0,G="";if(this.#Y>0)_=$/this.#Y*this.#X,U=Math.max(0,_-$),G=` | ${this.formatTime($)} elapsed | ${this.formatTime(U)} remaining`;let M=30,H=Math.floor(Y/100*M),L=M-H,z="["+"=".repeat(H)+(L>0?">":"")+" ".repeat(Math.max(0,L-(L>0?1:0)))+"]",R=`${this.#Z}: ${z} ${Y}% (${this.#Y}/${this.#X})${G}`;if(this.clearLine(),this.write(R,!1),this.#Y>=this.#X)this.complete()}complete(Q){if(!this.#Q)return;this.#Y=this.#X;let Y=(Date.now()-this.#$)/1000;if(this.clearLine(),Q)this.write(`${Q} (completed in ${this.formatTime(Y)})`);else this.write(`${this.#Z} completed in ${this.formatTime(Y)}`);this.#Q=!1}pause(Q){if(!this.#Q)return;this.newLine(),this.write(Q),this.update(0)}isActive(){return this.#Q}getCurrent(){return this.#Y}getTotal(){return this.#X}getPercentage(){return Math.min(100,Math.floor(this.#Y/this.#X*100))}}class mQ extends k{#Q=!1;#X="";#Y=0;#Z=null;#$=0;#_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];#U=80;constructor(Q="Processing",X,Y){super();if(this.#X=Q,X)this.#_=X;if(Y)this.#U=Y;if(this.#Q)return;this.#Q=!0,this.#Y=Date.now(),this.#$=0,this.#Z=setInterval(()=>{this.render()},this.#U),this.render()}update(Q){if(!this.#Q)return;this.#X=Q}complete(Q,X=!0){if(!this.#Q)return;if(this.#Z)clearInterval(this.#Z),this.#Z=null;let Z=(Date.now()-this.#Y)/1000;this.clearLine();let $=this.formatTime(Z);if(Q)this[X?"success":"error"](`${Q} (${$})`);else this[X?"success":"error"](`${this.#X} completed in ${$}`);this.#Q=!1}fail(Q){this.complete(Q,!1)}pause(Q){if(!this.#Q)return;if(this.#Z)clearInterval(this.#Z),this.#Z=null;this.clearLine(),this.write(Q),this.#Z=setInterval(()=>{this.render()},this.#U)}isActive(){return this.#Q}getElapsedTime(){return(Date.now()-this.#Y)/1000}render(){if(!this.#Q)return;let Q=this.getElapsedTime(),X=this.#_[this.#$];this.#$=(this.#$+1)%this.#_.length,this.clearLine(),this.write(`${X} ${this.#X} (${this.formatTime(Q)})`,!1)}}e();import{Elysia as SX,sse as CX,t as nQ}from"elysia";import{assign as kX,isEmpty as RQ,objectify as qX}from"radash";d();g();var hX=(Q)=>{let X=Reflect.getMetadata("http:body",Q.target,Q.propertyKey),Y=Reflect.getMetadata("http:params",Q.target,Q.propertyKey)??[],Z=Reflect.getMetadata("http:query",Q.target,Q.propertyKey),$=Reflect.getMetadata("http:rawContext",Q.target,Q.propertyKey),_=Reflect.getMetadata("http:customDecorators",Q.target,Q.propertyKey)??[],U=Reflect.getMetadata(O.middlewares,Q.target,Q.propertyKey)??[],G=Reflect.getMetadata(O.services,Q.target,Q.propertyKey)??[],{path:M,method:H,handler:L,target:z,response:R,operationId:P,description:j,transactional:C}=Q,y=Reflect.getMetadata(O.http,z.constructor)??[];y.push({path:M,method:H,body:X,params:Y,query:Z,customDecorators:_,rawContext:$,handler:L,middlewares:U,response:R,operationId:P,description:j,services:G,transactional:C}),Reflect.defineMetadata(O.http,y,z.constructor)},sQ;((Y)=>{Y[Y.SERVER=0]="SERVER";Y[Y.REQUEST=1]="REQUEST"})(sQ||={});var oQ;((D)=>(D.controller=(V={path:"/"})=>{return function(W){async function J(){console.log(`Registering HTTP controller for ${V.path} using ${W.name}`),await n(),V=kX({path:"/",scope:0,tags:[]},V);let I=new SX({prefix:V.path,name:W.name}),c=(()=>{if(V.scope===0)return()=>{let K=B.make(W);return()=>K};else if(V.scope===1)return()=>()=>B.make(W);else throw new Error(`Invalid scope for controller: ${W.name}`)})();I.resolve({as:"local"},()=>({controller:c()}));let ZQ=Reflect.getMetadata("http:onRequest",W)??{};if(ZQ.handler)I.onRequest((K)=>{let a=c()();return ZQ.handler.call(a,K)});let eQ=Reflect.getMetadata(O.middlewares,W)??[];YQ(eQ,I);let QX=Reflect.getMetadata(O.http,W)??[];for(let K of QX){let a=async(A)=>{let F=[];if(K.rawContext)F[K.rawContext.index]=A;if(K.body)F[K.body.index]=A.body;if(K.query)F[K.query.index]=A.query;if(!RQ(K.params))for(let x of K.params)F[x.index]=A.params[x.slug];if(!RQ(K.customDecorators))for(let x of K.customDecorators)F[x.index]=await x.handler(A);if(!RQ(K.services))for(let x of K.services)F[x.index]=B.get(x.name);return F},XX=K.handler.constructor.name.includes("GeneratorFunction"),xQ=K.method==="elysium:SSE",YX=K.transactional??V.transactional??!1,JQ=K.body&&K.body.schema===void 0&&K.body.validator!==void 0;K.method=xQ?"GET":K.method;let ZX=()=>{let A=(F)=>{if(YX)return function(...x){return p.getDefaultConnection().transaction((HQ)=>{return N.context.run(new Map([["tenant",F.tenant],["http:context",F],["db:tx",HQ]]),()=>{try{return K.handler.call(F.controller(),...x)}catch($Q){throw HQ.rollback(),$Q}})})};return function(...x){return N.context.run(new Map([["tenant",F.tenant],["http:context",F]]),()=>K.handler.call(F.controller(),...x))}};if(XX)return async function*(F){let x=A(F),HQ=await a(F);try{for await(let $Q of x(...HQ))yield $Q}catch($Q){yield $Q}};if(xQ)return async function*(F){let x=A(F);F.set.headers["content-type"]="text/event-stream",F.set.headers["cache-control"]="no-cache",F.set.headers.connection="keep-alive";while(!0)yield CX(await x(...await a(F))),await Bun.sleep(10)};if(JQ)return async function(F){if(await K.body.validator.validate(F))return await A(F)(...await a(F));throw F.status(400,"Invalid request body")};return async function(F){return await A(F)(...await a(F))}},wQ=qX(K.params??[],(A)=>A.slug,(A)=>A.schema),LQ=K.middlewares.map((A)=>B.make(A));I.route(K.method,K.path,ZX(),{config:{},async transform(A){if(JQ&&!await K.body.validator.authorize(A))throw A.status(401,"Unauthorized");return u(LQ,A,"onTransform")},beforeHandle(A){return u(LQ,A,"onBeforeHandle")},afterHandle(A){return u(LQ,A,"onAfterHandle")},afterResponse(A){return u(LQ,A,"onAfterResponse")},detail:{tags:V.tags,description:K.description,operationId:K.operationId},body:JQ?K.body?.validator?.schema:K.body?.schema,response:K.response,params:RQ(wQ)?void 0:nQ.Object(wQ)})}return I}Reflect.defineMetadata(O.elysiaPlugin,J,W)}},D.sse=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"elysium:SSE",path:W,...J})},D.get=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"GET",path:W,...J})},D.post=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"POST",path:W,...J})},D.put=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"PUT",path:W,...J})},D.del=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"DELETE",path:W,...J})},D.patch=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"PATCH",path:W,...J})},D.head=(V={})=>{let{path:W="/",...J}=V??{};return D.custom({method:"HEAD",path:W,...J})},D.options=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"OPTIONS",path:W,...J})},D.trace=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"TRACE",path:W,...J})},D.custom=({path:V="/",...W})=>{return function(J,I,c){process.nextTick(()=>{hX({path:V,handler:c.value,target:J,propertyKey:I,...W})})}},D.onRequest=()=>{return function(V,W,J){let I=Reflect.getMetadata("http:onRequest",V.constructor)??{};I.handler=J.value,Reflect.defineMetadata("http:onRequest",I,V.constructor)}},D.context=()=>{return function(V,W,J){Reflect.defineMetadata("http:rawContext",{index:J},V,W)}},D.param=(V,W)=>{return function(J,I,c){let ZQ=Reflect.getMetadata("http:params",J,I)??[];ZQ.push({slug:V,schema:W??nQ.String(),index:c}),Reflect.defineMetadata("http:params",ZQ,J,I)}},D.query=(V)=>{return function(W,J,I){Reflect.defineMetadata("http:query",{schema:V,index:I},W,J)}},D.body=(V)=>{return function(W,J,I){if(typeof V==="function")Reflect.defineMetadata("http:body",{validator:V,index:I},W,J);else Reflect.defineMetadata("http:body",{schema:V,index:I},W,J)}},D.decorate=(V)=>{return()=>{return function(W,J,I){let c=Reflect.getMetadata("http:customDecorators",W,J)??[];c.push({handler:V,index:I}),Reflect.defineMetadata("http:customDecorators",c,W,J)}}}))(oQ||={});FQ();import{getTableConfig as bX,pgSchema as vX,pgTable as rQ}from"drizzle-orm/pg-core";import{t as S}from"elysia";var IQ=(Q,{mode:X="select"}={})=>{let{columns:Y}=bX(Q);if(Y===void 0)return S.Object({});let Z={};for(let $ of Y){if(["create","update"].includes(X)&&$.primary)continue;if(Z[$.name]=yX($),!$.notNull)Z[$.name]=S.Nullable(Z[$.name]);if(X==="update"||$.hasDefault||!$.notNull)Z[$.name]=S.Optional(Z[$.name])}return S.Object(Z)},yX=(Q)=>{let X=(()=>{switch(Q.dataType){case"string":return S.String({format:Q.columnType==="PgUUID"?"uuid":void 0});case"number":return S.Number();case"boolean":return S.Boolean();case"array":return S.Array(S.Any());case"json":return S.Object({});case"date":case"localDate":case"localDateTime":return S.String({format:Q.dataType==="date"?"date":"date-time"});case"bigint":return S.BigInt();case"buffer":return S.File();default:return S.Never()}})();if(!Q.notNull)X=S.Optional(X);else X=S.Required(X);return X},gX=(Q,X,Y)=>{let Z=rQ(Q,X,Y);class ${static $inferSelect=Z.$inferSelect;static $inferInsert=Z.$inferInsert;static $inferUpdate=Z.$inferInsert;static get table(){if(!N.instance||!N.context.getStore)return Z;if(this.supportTenancy){let _=VQ.getCurrentTenant()??"public";return VQ.wrapTenant(_,this)}return Z}static tableName=Q;static columns=X;static extraConfig=Y;static insertSchema=IQ(Z,{mode:"create"});static updateSchema=IQ(Z,{mode:"update"});static selectSchema=IQ(Z,{mode:"select"});static supportTenancy=!1}return $},TQ=new Map,BQ=new Map,VQ;((i)=>{let Q=(_)=>{return BQ.get(_)??i.registerTenant(_)};i.getCurrentTenant=()=>{return N.context.getStore()?.get("tenant")??null},i.wrapTenant=(_,U)=>{if(_==="public")return rQ(U.tableName,U.columns);let G=`${_}.${U.tableName}`;if(TQ.has(G))return TQ.get(G);let H=Q(_).table(U.tableName,U.columns);return TQ.set(G,H),H},i.registerTenant=(_)=>{if(BQ.has(_))return BQ.get(_);let U=vX(_);return BQ.set(_,U),U},i.withTenant=(_,U)=>{let G=N.context.getStore(),M=new Map(G);return M.set("tenant",_),N.context.run(M,U)}})(VQ||={});import{Elysia as dX}from"elysia";import{assign as lX}from"radash";g();class tQ{static register(Q={}){return function(X){async function Y(Z){console.log(`Registering module ${X.name}`),await n();let $=lX({controllers:[]},Q),_=new dX({name:X.name,prefix:Q.prefix});_.resolve({as:"local"},()=>({module:Z}));let U=Reflect.getMetadata(O.middlewares,X)??[];YQ(U,_);for(let G of $.controllers){let M=Reflect.getMetadata(O.elysiaPlugin,G);if(M===void 0)console.error(`Invalid controller class ${G.name} registered in module ${X.name}. Ensure that you either used the @Http.controller(), the @Websocket.controller(), or the @Wamp.controller() decorators on the class.`),process.exit(1);else _.use(await M())}return _}Reflect.defineMetadata(O.elysiaPlugin,Y,X)}}beforeRegister(){return Promise.resolve()}afterRegister(){return Promise.resolve()}}import{eq as MQ}from"drizzle-orm";var pX=(Q)=>{class X{static Model=Q;static connection="default";get db(){let Y=this.constructor.connection,Z=null;if(Y==="default")Z=N.context.getStore()?.get("db:tx")??null;return Z??p.getConnection(Y)}async all(){return await this.db.select().from(Q.table)}async paginate(Y,Z=1){let $=await this.db.$count(Q.table),_=Math.max(Z-1,0)*Y;return{page:Z,total:$,data:await this.db.select().from(Q.table).offset(_).limit(Y)}}async find(Y){let[Z]=await this.db.select().from(Q.table).where(MQ(Q.table.id,Y));return Z??null}async findBy(Y,Z){let[$]=await this.db.select().from(Q.table).where(MQ(Q.table[Y],Z));return $??null}async insert(Y){let[Z]=await this.db.insert(Q.table).values(Y).returning();return Z}async update(Y,Z){let[$]=await this.db.update(Q.table).set(Z).where(MQ(Q.table.id,Y)).returning();return $}async updateAll(Y){return await this.db.update(Q.table).set(Y).returning()}async delete(Y){let[Z]=await this.db.delete(Q.table).where(MQ(Q.table.id,Y)).returning();return Z}async deleteAll(){return await this.db.delete(Q.table).returning()}}return X};d();import{Elysia as uX}from"elysia";d();g();var aQ;((v)=>(v.controller=(U)=>{return function(G){async function M(){console.log(`Registering Websocket route for ${U.path} using ${G.name}`),await n();let H=B.make(G),L=Reflect.getMetadata(O.websocket,G)??{},z=L.open?.bind(H),R=L.close?.bind(H),P=L.message?.bind(H),j=L.drain?.bind(H),C=L.error?.bind(H)??((V)=>w.emit("elysium:error",V.error)),y=new uX;return y.ws(U.path,{open:z,close:R,message:P,drain:j,error:C,body:L.body,...U.options}),y}Reflect.defineMetadata(O.elysiaPlugin,M,G)}},v.onOpen=()=>{return function(U,G,M){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.open=M.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onClose=()=>{return function(U,G,M){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.close=M.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onMessage=(U)=>{return function(G,M,H){let L=Reflect.getMetadata(O.websocket,G.constructor)??{};L.message=H.value,L.body=U,Reflect.defineMetadata(O.websocket,L,G.constructor)}},v.onDrain=()=>{return function(U,G,M){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.drain=M.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onError=()=>{return function(U,G,M){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.error=M.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}}))(aQ||={});EQ();export{vZ as t,zQ as WorkerPool,AQ as Worker,aQ as Websocket,t as Wamp,VQ as Tenancy,NQ as ServiceScope,B as Service,pX as Repository,r as Redis,tQ as Module,gX as Model,yQ as Middleware,dQ as Job,k as InteractsWithConsole,sQ as HttpControllerScope,oQ as Http,w as Event,vQ as Env,p as Database,OQ as ConsoleFormat,uQ as CommandArgumentType,cQ as Command,l as Cache,N as Application};
package/dist/module.d.ts CHANGED
@@ -9,6 +9,10 @@ export type ModuleProps = {
9
9
  * The list of controllers provided by the module.
10
10
  */
11
11
  controllers?: Class<any>[];
12
+ /**
13
+ * The list of jobs provided by the module.
14
+ */
15
+ jobs?: Class<any>[];
12
16
  /**
13
17
  * The base path for all the controllers registered by this module.
14
18
  * This value will be prefixed to each controllers path.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elysiumjs/core",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "license": "Apache-2.0",
5
5
  "description": "A super-charged web framework for Bun, built on top of ElysiaJS.",
6
6
  "private": false,