@elysiumjs/core 0.5.0 → 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/app.d.ts CHANGED
@@ -166,6 +166,7 @@ export declare abstract class Application extends InteractsWithConsole {
166
166
  * @param argv The command line arguments.
167
167
  */
168
168
  private commandExec;
169
+ private commandWork;
169
170
  /**
170
171
  * Starts the server on the specified port.
171
172
  */
@@ -177,4 +178,3 @@ export declare abstract class Application extends InteractsWithConsole {
177
178
  private commandList;
178
179
  private commandDescription;
179
180
  }
180
- //# sourceMappingURL=app.d.ts.map
package/dist/cache.d.ts CHANGED
@@ -111,4 +111,3 @@ export declare abstract class Cache {
111
111
  */
112
112
  static get memory(): CacheInterface;
113
113
  }
114
- //# sourceMappingURL=cache.d.ts.map
package/dist/command.d.ts CHANGED
@@ -270,4 +270,3 @@ export declare class CommandSpinner extends InteractsWithConsole {
270
270
  private render;
271
271
  }
272
272
  export {};
273
- //# sourceMappingURL=command.d.ts.map
package/dist/console.d.ts CHANGED
@@ -164,4 +164,3 @@ export declare class InteractsWithConsole {
164
164
  */
165
165
  protected formatTime(seconds: number): string;
166
166
  }
167
- //# sourceMappingURL=console.d.ts.map
@@ -110,4 +110,3 @@ export declare namespace Database {
110
110
  */
111
111
  const setDefaultConnection: (name: string) => DatabaseConnection;
112
112
  }
113
- //# sourceMappingURL=database.d.ts.map
package/dist/env.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AppEnv } from '@elysiumjs/core';
1
+ import type { AppEnv } from '.';
2
2
  /**
3
3
  * Initializes the environment variables.
4
4
  * @author Axel Nana <axel.nana@workbud.com>
@@ -27,4 +27,3 @@ export declare namespace Env {
27
27
  */
28
28
  const clear: () => void;
29
29
  }
30
- //# sourceMappingURL=env.d.ts.map
package/dist/event.d.ts CHANGED
@@ -91,4 +91,3 @@ export declare namespace Event {
91
91
  */
92
92
  const listen: (options: ListenProps) => MethodDecorator;
93
93
  }
94
- //# sourceMappingURL=event.d.ts.map
package/dist/http.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import type { AppHttpContext } from '@elysiumjs/core';
2
1
  import type { Context as ElysiaContext, Handler, HTTPMethod, TSchema } from 'elysia';
3
2
  import type { Class, MergeDeep } from 'type-fest';
3
+ import type { AppHttpContext } from '.';
4
4
  import type { Module } from './module';
5
5
  import { Elysia } from 'elysia';
6
6
  /**
@@ -239,4 +239,3 @@ export declare namespace Http {
239
239
  */
240
240
  const decorate: (handler: Handler) => (() => ParameterDecorator);
241
241
  }
242
- //# sourceMappingURL=http.d.ts.map
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,4 +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';
21
- //# sourceMappingURL=index.d.ts.map
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,24 +1,19 @@
1
1
  // @bun
2
- global.ELYSIUM_BUILD=typeof ELYSIUM_BUILD!=="undefined";import{t as F0}from"elysia";import{AsyncLocalStorage as R2}from"async_hooks";import{swagger as W2}from"@elysiajs/swagger";import{Value as UL}from"@sinclair/typebox/value";import{Elysia as P2}from"elysia";import{first as z2}from"radash";import*as WL from"readline";import{isEmpty as rL,omit as tL}from"radash";var ZL;((R)=>{R[R.BLACK=0]="BLACK";R[R.RED=1]="RED";R[R.GREEN=2]="GREEN";R[R.YELLOW=3]="YELLOW";R[R.BLUE=4]="BLUE";R[R.MAGENTA=5]="MAGENTA";R[R.CYAN=6]="CYAN";R[R.WHITE=7]="WHITE";R[R.GRAY=8]="GRAY";R[R.BOLD=9]="BOLD";R[R.UNDERLINE=10]="UNDERLINE";R[R.ITALIC=11]="ITALIC";R[R.INVERSE=12]="INVERSE"})(ZL||={});var aL={[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"};class k{static SPACE_WIDTH=60;write(L,Y=!0,U=process.stdout){U.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 U=L.name||"Error",Q=L.message||"An error occurred",X=L.stack||"";if(Y)this.title(Y);else this.newLine();if(this.write(this.format(`${U}: ${Q}`,1)),L.stack)this.write(this.format("Stack Trace:",9)),this.write(this.format(X.split(`
5
- `).map((_)=>` ${_}`).join(`
6
- `),8));let Z=tL(L,["name","message","stack"]);if(!rL(Z))this.write(this.format("Additional Information:",9)),Object.keys(Z).forEach((_)=>{let $=L[_];this.write(` ${_}: ${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 U=Object.keys(Y||L[0]),Q={};for(let _ of U){let $=Y?.[_];if($?.width){Q[_]=$.width;continue}let D=($?.header||String(_)).length,H=Math.max(...L.map((G)=>{let W=G[_];if($?.format)return $.format(W).length;return String(W===null||W===void 0?"":W).length}));Q[_]=Math.max(D,H)}let X="",Z="";for(let _ of U){let D=Y?.[_]?.header||String(_),H=Q[_];X+=`| ${D.padEnd(H)} `,Z+=`| ${"-".repeat(H)} `}X+="|",Z+="|",this.write(X),this.write(Z);for(let _ of L){let $="";for(let D of U){let H=Y?.[D],G=Q[D],W=_[D],P;if(H?.format)P=H.format(W);else P=String(W===null||W===void 0?"":W);$+=`| ${P.padEnd(G)} `}$+="|",this.write($)}this.newLine()}format(L,...Y){return`${Y.map((Q)=>aL[Q]).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 U=WL.createInterface({input:process.stdin,output:process.stdout}),Q=Y?` (default: ${Y})`:"";return new Promise((X)=>{U.question(`${L}${Q}: `,(Z)=>{U.close(),X(Z||Y||"")})})}async promptPassword(L){let Y=WL.createInterface({input:process.stdin,output:process.stdout});return process.stdin.setRawMode?.(!0),new Promise((U)=>{let Q="";process.stdout.write(`${L}: `),process.stdin.on("data",(X)=>{let Z=X.toString();if(Z==="\r"||Z===`
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
+ `).map((U)=>` ${U}`).join(`
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(),U(Q);return}if(Z==="\b"||Z==="\x7F"){if(Q.length>0)Q=Q.slice(0,-1),process.stdout.write("\b \b");return}Q+=Z,process.stdout.write("*")})})}async confirm(L,Y=!1){let U=Y?"Y/n":"y/N",Q=await this.prompt(`${L} [${U}]`);if(!Q)return Y;return Q.toLowerCase()==="y"||Q.toLowerCase()==="yes"}async select(L,Y,U=0){if(Y.length===0)throw new Error("No options provided for selection");this.write(L),Y.forEach((Z,_)=>{let $=_===U;this.write(` ${_+1}. ${Z}${$?" (default)":""}`)});let Q=await this.prompt("Enter your choice (number)");if(!Q)return Y[U];let X=parseInt(Q,10)-1;if(isNaN(X)||X<0||X>=Y.length)return this.warning(`Invalid selection. Using default: ${Y[U]}`),Y[U];return Y[X]}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`}}import{getTableName as TL,is as fL,Table as xL}from"drizzle-orm";import{drizzle as _2}from"drizzle-orm/bun-sql";import{Cache as $2}from"drizzle-orm/cache/core";import{createCache as EL}from"cache-manager";import{KeyvCacheableMemory as X2}from"cacheable";import{Keyv as FL}from"keyv";import{alphabetical as Z2}from"radash";import{EventEmitter as U2}from"events";import{omit as Q2}from"radash";import{EventEmitter as eL}from"events";import{isString as IL}from"radash";class h extends eL{static instance=new h;constructor(){super();this.on("error",(L)=>this.emitError(L))}emitError(L){this.emit("elysium:error",{data:L,source:null})}emitEvent(L,Y,U=null){this.emit(L,{data:Y,source:U})}}var x;((u)=>{u.emit=(_,$,D=null)=>{h.instance.emitEvent(_,$,D)};function Y(_,$){if(IL(_))h.instance.on(_,$);else return function(D,H,G){let W=async function(R){try{await G.value(R)}catch(I){h.instance.emitError(I)}};if(_.prepend??!1)h.instance.prependListener(_.event,W);else h.instance.on(_.event,W)}}u.on=Y;function U(_,$){if(IL(_))h.instance.once(_,$);else return function(D,H,G){let W=async function(R){try{await G.value(R)}catch(I){h.instance.emitError(I)}};if(_.prepend??!1)h.instance.prependOnceListener(_.event,W);else h.instance.once(_.event,W)}}u.once=U,u.off=(_)=>{h.instance.removeAllListeners(_)},u.clear=()=>{h.instance.removeAllListeners()},u.listen=(_)=>{if(_.mode==="on")return Y(_);else if(_.mode==="once")return U(_);return function($,D,H){console.error("Unknown mode provided to @listen. Use either 'on' or 'once'.")}}})(x||={});import{isString as a}from"radash";import{isObject as YL,isPrimitive as L2}from"radash";var O;((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||={});var c=()=>new Promise((L)=>process.nextTick(L));function n(L,...Y){if(!Y.length)return L;let U=Y.shift();if(U===void 0)return L;if(YL(L)&&YL(U))for(let Q in U)if(YL(U[Q])){if(!L[Q])Object.assign(L,{[Q]:U[Q]})}else if(Array.isArray(U[Q])){if(!Array.isArray(L[Q]))L[Q]=[];if(U[Q].length>0&&!YL(U[Q][0]))L[Q]=[...new Set([...L[Q],...U[Q]])];else U[Q].forEach((X,Z)=>{if(YL(X)&&L[Q][Z])L[Q][Z]=n(L[Q][Z],X);else if(!L[Q].includes(X))L[Q].push(X)})}else if(L2(U[Q]))L[Q]??=U[Q];else n(L[Q],U[Q]);return n(L,...Y)}var KL;((U)=>{U[U.SINGLETON=0]="SINGLETON";U[U.FACTORY=1]="FACTORY"})(KL||={});var Y2=(L)=>{return typeof L==="function"&&L.prototype&&L.prototype.constructor===L},m=new Map,z;((j)=>{j.register=(G)=>{return function(W){let P=G?.name??W.name,R=G?.scope??0;if(z.exists(P))console.error(`A service with the name ${P} has already been registered.`),process.exit(1);let I=()=>z.make(W);if(R===0){let C=I();m.set(P,{scope:R,factory(){return C}})}else m.set(P,{scope:R,factory:I})}},j.inject=(G)=>{return function(W,P,R){let I=Reflect.getMetadata(O.services,W,P)??[],C=Reflect.getMetadata("design:paramtypes",W,P)??[],y=a(G)?G:G?.name??C[R].name;I.push({name:y,index:R}),Reflect.defineMetadata(O.services,I,W,P)}},j.get=(G)=>{let W=a(G)?G:G.name;if(j.exists(W))return m.get(W).factory();return null},j.make=(G)=>{let W=Reflect.getMetadata(O.services,G)??[],P=[];return W.forEach((R)=>{let I=j.get(R.name);if(I===null)console.error(`Cannot inject service ${R.name}. No service was registered with the name: ${R.name}`),process.exit(1);P[R.index]=I}),new G(...P)},j.bind=(G,W)=>{let P=j.make(G);return j.instance(W??G.name,P)};function Z(G,W){let P=a(G)?G:W??G.name;if(j.exists(P))console.error(`A service with the name ${P} has already been registered.`),process.exit(1);let R=()=>{return Y2(G)?j.make(G):W()};return m.set(P,{scope:1,factory:R}),R()}j.factory=Z,j.instance=(G,W)=>{let P=a(G)?G:G.name;if(j.exists(P))console.error(`A service with the name ${P} has already been registered.`),process.exit(1);return m.set(P,{scope:0,factory(){return W}}),W},j.remove=(G)=>{let W=a(G)?G:G.name;m.delete(W)},j.exists=(G)=>{let W=a(G)?G:G.name;return m.has(W)},j.clear=()=>{m.clear()}})(z||={});class PL extends U2{#L;#Y;#U="::";#Q=1000;#X=!0;#Z=!1;#_;constructor(L){super();x.once("elysium:app:launched",()=>{this.#L=s.getConnection(L.connection)}),this.#_=L.connection,this.#Y=L.namespace,this.#U=L.keyPrefixSeparator??"::",this.#Q=L.clearBatchSize??1000,this.#X=L.useUnlink??!0,this.#Z=L.noNamespaceAffectsAll??!1,this.on("error",(Y)=>{x.emit("elysium:error",Y)})}get client(){return this.#L}get opts(){return{namespace:this.#Y,keyPrefixSeparator:this.#U,clearBatchSize:this.#Q,noNamespaceAffectsAll:this.#Z,dialect:"redis",url:this.#_}}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,U){if(L=this.createKeyPrefix(L,this.#Y),U)await this.client.set(L,Y,"PX",U);else await this.client.set(L,Y)}async setMany(L){let Y=[];for(let{key:U,value:Q,ttl:X}of L){let Z=this.createKeyPrefix(U,this.#Y);if(X)Y.push(this.client.set(Z,Q,"PX",X));else Y.push(this.client.set(Z,Q))}await Promise.all(Y)}async delete(L){return L=this.createKeyPrefix(L,this.#Y),await(this.#X?this.client.send("UNLINK",[L]):this.client.del(L))>0}async clear(){try{if(!this.#Y&&this.#Z){await this.client.send("FLUSHDB",[]);return}let L="0",Y=this.#Q,U=this.#Y?`${this.#Y}${this.#U}*`:"*",Q=[];do{let X=await this.client.send("SCAN",[L,"MATCH",U,"COUNT",Y.toString(),"TYPE","string"]),[Z,_]=X;if(L=Z.toString(),_.length===0)continue;if(!this.#Y)_=_.filter(($)=>!$.includes(this.#U));Q.push(_.map(($)=>this.client.del($)))}while(L!=="0");await Promise.all(Q)}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 U of L){let Q=this.createKeyPrefix(U,this.#Y);Y.push(this.client.exists(Q))}return Promise.all(Y)}async getMany(L){if(L.length===0)return[];return L=L.map((U)=>this.createKeyPrefix(U,this.#Y)),await this.client.mget(...L)}async disconnect(){this.client.close()}async deleteMany(L){let Y=!1,U=[];for(let X of L){let Z=this.createKeyPrefix(X,this.#Y);if(this.#X)U.push(this.client.send("UNLINK",[Z]));else U.push(this.client.del(Z))}let Q=await Promise.all(U);for(let X of Q)if(typeof X==="number"&&X>0)Y=!0;return Y}async*iterator(L){let Y=L?`${L}${this.#U}*`:"*",U="0";do{let Q=await this.client.send("SCAN",[U,"MATCH",Y,"TYPE","string"]),[X,Z]=Q;if(U=X.toString(),!L&&!this.#Z)Z=Z.filter((_)=>!_.includes(this.#U));if(Z.length>0){let _=await this.client.mget(...Z);for(let $ of Z.keys()){let D=this.getKeyWithoutPrefix(Z[$],L),H=_[$];yield[D,H]}}}while(U!=="0")}createKeyPrefix(L,Y){return Y?`${Y}${this.#U}${L}`:L}getKeyWithoutPrefix(L,Y){return Y?L.replace(`${Y}${this.#U}`,""):L}}var s;((q)=>{let L=(_)=>{return`redis.connection.${_}`};q.getConnection=(_)=>{if(!z.exists(L(_)))console.error(`No Redis connection with name ${_} found. Please make sure to register the connection before using it.`),process.exit(1);return z.get(L(_))},q.registerConnection=(_,$)=>{if(z.exists(L(_)))console.error(`A Redis connection with the name ${_} has already been registered.`),process.exit(1);return z.instance(L(_),new Bun.RedisClient($.url,Q2($,["url"])))},q.connectionExists=(_)=>{return z.exists(L(_))},q.getDefaultConnection=()=>{return q.getConnection("default")},q.setDefaultConnection=(_)=>{let $=L("default");return z.remove($),z.instance($,q.getConnection(_))}})(s||={});var jL=(L)=>{let Y=EL({stores:[new FL({store:L,namespace:"cache"})]}),U=new Map;return{...Y,tags(...Q){let X=`cache__${Z2(Q,(_)=>_).join("__")}`,Z=U.get(X);if(!Z)Z=EL({stores:[new FL({store:L,namespace:X})]}),U.set(X,Z);return Z}}};class g{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(!g.#L)g.#L=jL(new PL({connection:"cache"}));return g.#L}static get memory(){if(!g.#Y)g.#Y=jL(new X2({ttl:60000,lruSize:5000}));return g.#Y}}class zL extends $2{cacheStrategy;globalTtl;#L;usedTablesPerKey={};constructor(L="explicit",Y=1,U="redis"){super();this.cacheStrategy=L;this.globalTtl=Y;this.#L=g[U].tags("database")}strategy(){return this.cacheStrategy}async get(L){return await this.#L.get(L)??void 0}async put(L,Y,U,Q,X){await this.#L.set(L,Y,(X?.ex??this.globalTtl)*1000);for(let Z of U){let _=this.usedTablesPerKey[Z];if(_===void 0)this.usedTablesPerKey[Z]=[L];else _.push(L)}}async onMutate(L){let Y=L.tags?Array.isArray(L.tags)?L.tags:[L.tags]:[],U=L.tables?Array.isArray(L.tables)?L.tables:[L.tables]:[],Q=new Set;for(let X of U){let Z=fL(X,xL)?TL(X):X,_=this.usedTablesPerKey[Z]??[];for(let $ of _)Q.add($)}if(Q.size>0||Y.length>0){await this.#L.mdel(Y),await this.#L.mdel([...Q]);for(let X of U){let Z=fL(X,xL)?TL(X):X;this.usedTablesPerKey[Z]=[]}}}}var d;((b)=>{let L=(_)=>{return`db.connection.${_}`};b.getConnection=(_)=>{if(!z.exists(L(_)))console.error(`No connection with name ${_} found. Please make sure to register the connection before using it.`),process.exit(1);return z.get(L(_))},b.registerConnection=(_,$)=>{if(z.exists(L(_)))console.error(`A connection with the name ${_} has already been registered.`),process.exit(1);return z.instance(L(_),_2({...$,cache:$.cache===void 0?void 0:$.cache===!0?new zL:$.cache.enabled?new zL($.cache.strategy,$.cache.ttl,$.cache.storage):void 0}))},b.connectionExists=(_)=>{return z.exists(L(_))},b.getDefaultConnection=()=>{return b.getConnection("default")},b.setDefaultConnection=(_)=>{let $=L("default");return z.remove($),z.instance($,b.getConnection(_))}})(d||={});var _L=new Map,BL=(L)=>{for(let[Y,U]of Object.entries(L))_L.set(Y,U)},wL;((e)=>(e.get=(Q,X)=>{return _L.get(Q)??X},e.exists=(Q)=>{return _L.has(Q)},e.clear=()=>{_L.clear()}))(wL||={});var l=(L,Y,U)=>{return S.context.run(new Map([["tenant",Y.tenant],["http:context",Y]]),async()=>{for(let Q of L)try{let X=await Q[U](Y);if(X!==void 0)return X}catch(X){throw X}})},LL=(L,Y)=>{let U=L.map((Q)=>z.make(Q));Y.onRequest((Q)=>{return l(U,Q,"onRequest")}),Y.onTransform((Q)=>{return l(U,Q,"onTransform")}),Y.onBeforeHandle((Q)=>{return l(U,Q,"onBeforeHandle")}),Y.onAfterHandle((Q)=>{return l(U,Q,"onAfterHandle")}),Y.onAfterResponse((Q)=>{return l(U,Q,"onAfterResponse")})};class SL{static register(...L){return function(Y,U,Q){if(U===void 0&&Q===void 0){let X=Reflect.getMetadata(O.middlewares,Y)??[];X.push(...L),Reflect.defineMetadata(O.middlewares,X,Y)}else{let X=Reflect.getMetadata(O.middlewares,Y,U)??[];X.push(...L),Reflect.defineMetadata(O.middlewares,X,Y,U)}}}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){}}import{Elysia as G2}from"elysia";import{omit as H2}from"radash";import O2 from"wampy";class NL extends WebSocket{protocols;constructor(L,Y){super(L,Y);this.protocols=Y}get protocol(){return this.protocols?.[0]??"wamp.2.json"}}var o;((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 W=new O2(G.url,{ws:NL,...H2(G,["url"]),onError(){G.onError?.(),x.emit("elysium:error",new Error(`An error occurred in WAMP connection ${H}`))}}),P=G.maxRetries??5,R=G.retryInterval??5000,I=0,C=async()=>{try{await W.connect()}catch(y){if(console.error(`Failed to connect to WAMP server (attempt ${I+1}/${P}):`,y),I<P)I++,setTimeout(C,R);else console.error(`Max retry attempts (${P}) reached. Giving up.`),x.emit("elysium:error",new Error(`Failed to establish WAMP connection ${H} after ${P} attempts`))}};return C(),z.instance(L(H),W)},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 W(){console.log(`Registering Wamp controller for connection ${H.connection} using ${G.name}`),await c();let P=z.make(G),R=Reflect.getMetadata(O.wamp,G)??{},I=o.getConnection(H.connection??"default"),C=new G2;return C.onStart(async(y)=>{let B=R.registrations??[],V=R.subscriptions??[];for(let M of B)I.register(M.topic,M.handler.bind(P),M.options).then((F)=>{console.log(`Registered ${M.topic} with id ${F.registrationId}`)});for(let M of V)I.subscribe(M.topic,M.handler.bind(P),M.options).then((F)=>{console.log(`Subscribed ${M.topic} with id ${F.subscriptionId}`)})}),C}Reflect.defineMetadata(O.elysiaPlugin,W,G)}},w.register=(H,G)=>{return function(W,P,R){let I=Reflect.getMetadata(O.wamp,W.constructor)??{};I.registrations??=[],I.registrations.push({topic:H,options:G,handler:R.value}),Reflect.defineMetadata(O.wamp,I,W.constructor)}},w.subscribe=(H,G)=>{return function(W,P,R){let I=Reflect.getMetadata(O.wamp,W.constructor)??{};I.subscriptions??=[],I.subscriptions.push({topic:H,options:G,handler:R.value}),Reflect.defineMetadata(O.wamp,I,W.constructor)}}})(o||={});class S extends k{#L;#Y;_appContextStorage=new R2;static get instance(){return z.get("elysium.app")}static get context(){return S.instance._appContextStorage}static register(L={}){return function(Y){let U,Q=Object.getPrototypeOf(Y);while(Q&&Q!==Object.prototype){let Z=Reflect.getMetadata(O.app,Q);if(Z){U=Z;break}Q=Object.getPrototypeOf(Q)}if(U)L=n(U,L);let X=Reflect.getMetadata(O.app,Y);if(X)L=n(X,L);L=n({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 Z=UL.Convert(L,UL.Clone(Bun.env));if(this.#Y&&!UL.Check(L,Z)){let _=UL.Errors(L,Z).First();this.trace(_,"Invalid environment configuration")}BL(UL.Clean(L,Z))}else BL(Bun.env);z.instance("elysium.app",this);let{database:U,redis:Q,wamp:X}=Reflect.getMetadata(O.app,this.constructor);if(Q){for(let Z in Q.connections)s.registerConnection(Z,Q.connections[Z]);if(s.connectionExists(Q.default))s.setDefaultConnection(Q.default)}if(U){for(let Z in U.connections)d.registerConnection(Z,U.connections[Z]);if(d.connectionExists(U.default))d.setDefaultConnection(U.default)}if(X){for(let Z in X.connections)o.registerConnection(Z,X.connections[Z]);if(o.connectionExists(X.default))o.setDefaultConnection(X.default)}this.run().then(()=>x.emit("elysium:app:launched",this,this)).catch((Z)=>{x.emit("elysium:error",Z),this.trace(Z,"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:U}=Reflect.getMetadata(O.app,this.constructor);switch(Y){case"serve":return this.commandServe();case"help":{let Q=L[1];if(Q){let X=U?.find((Z)=>Z.command===Q);if(X){let Z=z.make(X);return this.write(await Z.help()),process.exit(0)}console.error(`Command <${Q}> 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 Q=L.slice(1);return this.commandExec(Y,Q)}}}return process.exit(0)}getConfig(L){return Reflect.getMetadata(O.app,this.constructor)?.[L]??null}async commandExec(L,Y){let{commands:U}=Reflect.getMetadata(O.app,this.constructor),Q=U?.find((X)=>X.command===L);if(!Q)return console.error(`Command ${L} not found`),this.commandList(),process.exit(1);try{let X=z.make(Q);if(await X.init(...Y))await X.run();else{let _=await X.help();this.write(_)}return process.exit(0)}catch(X){return console.error(X.message),process.exit(1)}}async commandServe(){let{server:L,modules:Y,swagger:U,plugins:Q}=Reflect.getMetadata(O.app,this.constructor);if(this.#L=new P2(L).onRequest((Z)=>{if(this.isDebug)console.log(Z.request.method,Z.request.url)}),x.emit("elysium:server:before-init",this,this),this.#L.resolve({as:"global"},({request:Z})=>({tenant:Z.headers.get("x-tenant-id")??"public"})),U)this.#L.use(W2(U));if(Q&&Q.length>0){this.debug("Registering plugins...");for(let Z of Q)this.#L.use(await Z(this))}this.#L.onError({as:"global"},async(Z)=>{if(await this.onError(Z)){x.emit("elysium:error",Z),this.trace({name:"HttpError",message:"Unexpected error while handling HTTP request",stack:Z.error.stack,...Z.error});let _={};if(typeof Z.code==="number")return Z.error.response;else switch(Z.code){case"VALIDATION":{_={scope:Z.error.type,code:Z.error.message};break}case"INTERNAL_SERVER_ERROR":{_={message:Z.error.message};break}}return{type:Z.code,data:_}}}).onStart(async(Z)=>{await this.onStart(Z),x.emit("elysium:server:start",Z,this)}).onStop(async(Z)=>{await this.onStop(Z),x.emit("elysium:server:stop",Z,this),this._appContextStorage.disable()});let X=Reflect.getMetadata(O.middlewares,this.constructor)??[];LL(X,this.#L);for(let Z of Y){let _=Reflect.getMetadata(O.elysiaPlugin,Z);if(_===void 0)return console.error(`Invalid module class ${Z.name} registered in app ${this.constructor.name}. Ensure that you used the @module() decorator on the module.`),process.exit(1);let $=z.bind(Z);await $.beforeRegister(),this.#L.use(await _($)),await $.afterRegister()}x.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((U,Q)=>{let X=z2(Q.command.split(":")),Z=U.get(X)??[];return Z.push(Q),U.set(X,Z),U},new Map);for(let[U,Q]of Y){this.section(this.format(U,4));for(let X of Q)this.commandDescription(X.command,"",X.description)}}commandDescription(L,Y,U,Q=k.SPACE_WIDTH){Y=Y.length===0?" ":` ${Y} `,this.write(` ${this.format(L,6)}${Y}${"\u2219".repeat(Q-L.length-Y.length)} ${U}`)}}import{isArray as B2,trim as D2}from"radash";var CL;((Z)=>{Z.STRING="string";Z.NUMBER="number";Z.BOOLEAN="boolean";Z.ENUM="enum";Z.ARRAY="array"})(CL||={});class kL extends k{static command="command";static description="Command description";static arg(L={}){return function(Y,U){let Q=Reflect.getMetadata(O.arg,Y.constructor)??[],X=Reflect.getMetadata("design:type",Y,U),Z=L.type;if(!Z&&X){if(X===Array){if(Z="array",!L.arrayType)L={...L,arrayType:"string"}}else if(X.constructor!==Object)switch(X.name.toLowerCase()){case"number":Z="number";break;case"boolean":Z="boolean";break;case"string":Z="string";break;default:Z=void 0}else if(Object.values(X).length>0){if(Z="enum",!L.enum)L={...L,enum:Object.values(X)}}}Q.push({name:L.name??U,description:L.description,required:L.required??!1,default:L.default,type:Z,enum:L.enum,arrayType:L.arrayType,propertyKey:U}),Reflect.defineMetadata(O.arg,Q,Y.constructor)}}async init(...L){let Y=this.processArgs(L),U=this.validateArgs(Y);if(!U.valid){if(U.missing.length>0)console.error(`Missing required arguments: ${U.missing.join(", ")}
9
- `);return!1}if(Object.keys(Y).includes("help"))return!1;let Q=this.getArguments();for(let X of Q)if(Y[X.name]!==void 0)this[X.propertyKey]=Y[X.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 U of Y){let Q=this.format(U.required?"(required)":"(optional)",1,9),X=U.default!==void 0?this.format(`[default: ${U.default}]`,8,11):"",Z="";if(U.type==="array")Z=`<array of ${U.arrayType||"string"}s>`;else if(U.type)Z=`<${U.type}>`;let _=U.enum?` [${U.enum.join("|")}]`:"";if(L+=` ${this.format(`--${U.name}`,6)} ${Z}${_} ${Q} ${X}
14
- `,U.description)L+=` ${U.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 D2(L,`
18
- `)}validateArgs(L){let Y=[],U=[],Q=this.getArguments();if(Object.keys(L).includes("help"))return{valid:!0,missing:[]};for(let X of Q){if(X.required&&(L[X.name]===void 0||L[X.name]===null)){Y.push(X.name);continue}if(L[X.name]===void 0)continue;if(X.type==="enum"&&X.enum&&!X.enum.includes(L[X.name]))U.push(`${X.name} (must be one of: ${X.enum.join(", ")})`);if(X.type==="array"&&X.arrayType==="enum"&&X.enum){let Z=L[X.name].filter((_)=>!X.enum.includes(_));if(Z.length>0)U.push(`${X.name} (contains invalid values: ${Z.join(", ")}. Must be one of: ${X.enum.join(", ")})`)}}if(U.length>0)console.error(`Invalid argument values: ${U.join(", ")}
19
- `);return{valid:Y.length===0&&U.length===0,missing:Y}}processArgs(L){let Y={},U=this.getArguments();for(let Q=0;Q<L.length;Q++){let X=L[Q];if(X.startsWith("--")){let Z=X.slice(2);if(Q+1<L.length&&!L[Q+1].startsWith("--"))Y[Z]=L[Q+1],Q++;else Y[Z]=!0}}for(let Q of U){if(Y[Q.name]===void 0&&Q.default!==void 0){Y[Q.name]=Q.default;continue}if(Y[Q.name]===void 0)continue;if(typeof Y[Q.name]==="string")switch(Q.type||this.inferType(Q.default)){case"number":Y[Q.name]=Number(Y[Q.name]);break;case"boolean":let Z=Y[Q.name].toLowerCase();Y[Q.name]=Z==="true"||Z==="1"||Z==="yes";break;case"enum":if(Q.enum&&Q.enum.length>0&&typeof Q.enum[0]==="number")Y[Q.name]=Number(Y[Q.name]);break;case"array":let _=Y[Q.name].split(",").map(($)=>$.trim());if(Q.arrayType)Y[Q.name]=_.map(($)=>{switch(Q.arrayType){case"number":return Number($);case"boolean":return $.toLowerCase()==="true"||$.toLowerCase()==="1"||$.toLowerCase()==="yes";case"enum":return $;default:return $}});else Y[Q.name]=_;break;case"string":default:break}}return Y}progress(L,Y="Processing"){return new hL(L,Y)}spinner(L="Processing",Y,U){return new qL(L,Y,U)}inferType(L){if(L===void 0)return"string";switch(typeof L){case"number":return"number";case"boolean":return"boolean";default:return B2(L)?"array":"string"}}}class hL extends k{#L=!1;#Y=0;#U=0;#Q="";#X=0;constructor(L=0,Y="Processing"){super();this.#Y=L,this.#Q=Y,this.#L=!0,this.#U=0,this.#X=Date.now(),this.update(0)}update(L=1,Y){if(!this.#L)return;if(this.#U+=L,Y)this.#Q=Y;let U=Math.min(100,Math.floor(this.#U/this.#Y*100)),X=(Date.now()-this.#X)/1000,Z=0,_=0,$="";if(this.#U>0)Z=X/this.#U*this.#Y,_=Math.max(0,Z-X),$=` | ${this.formatTime(X)} elapsed | ${this.formatTime(_)} remaining`;let D=30,H=Math.floor(U/100*D),G=D-H,W="["+"=".repeat(H)+(G>0?">":"")+" ".repeat(Math.max(0,G-(G>0?1:0)))+"]",P=`${this.#Q}: ${W} ${U}% (${this.#U}/${this.#Y})${$}`;if(this.clearLine(),this.write(P,!1),this.#U>=this.#Y)this.complete()}complete(L){if(!this.#L)return;this.#U=this.#Y;let U=(Date.now()-this.#X)/1000;if(this.clearLine(),L)this.write(`${L} (completed in ${this.formatTime(U)})`);else this.write(`${this.#Q} completed in ${this.formatTime(U)}`);this.#L=!1}pause(L){if(!this.#L)return;this.newLine(),this.write(L),this.update(0)}isActive(){return this.#L}getCurrent(){return this.#U}getTotal(){return this.#Y}getPercentage(){return Math.min(100,Math.floor(this.#U/this.#Y*100))}}class qL extends k{#L=!1;#Y="";#U=0;#Q=null;#X=0;#Z=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];#_=80;constructor(L="Processing",Y,U){super();if(this.#Y=L,Y)this.#Z=Y;if(U)this.#_=U;if(this.#L)return;this.#L=!0,this.#U=Date.now(),this.#X=0,this.#Q=setInterval(()=>{this.render()},this.#_),this.render()}update(L){if(!this.#L)return;this.#Y=L}complete(L,Y=!0){if(!this.#L)return;if(this.#Q)clearInterval(this.#Q),this.#Q=null;let Q=(Date.now()-this.#U)/1000;this.clearLine();let X=this.formatTime(Q);if(L)this[Y?"success":"error"](`${L} (${X})`);else this[Y?"success":"error"](`${this.#Y} completed in ${X}`);this.#L=!1}fail(L){this.complete(L,!1)}pause(L){if(!this.#L)return;if(this.#Q)clearInterval(this.#Q),this.#Q=null;this.clearLine(),this.write(L),this.#Q=setInterval(()=>{this.render()},this.#_)}isActive(){return this.#L}getElapsedTime(){return(Date.now()-this.#U)/1000}render(){if(!this.#L)return;let L=this.getElapsedTime(),Y=this.#Z[this.#X];this.#X=(this.#X+1)%this.#Z.length,this.clearLine(),this.write(`${Y} ${this.#Y} (${this.formatTime(L)})`,!1)}}import{Elysia as M2,t as bL}from"elysia";import{assign as V2,isEmpty as $L,objectify as A2}from"radash";var J2=(L)=>{let Y=Reflect.getMetadata("http:body",L.target,L.propertyKey),U=Reflect.getMetadata("http:params",L.target,L.propertyKey)??[],Q=Reflect.getMetadata("http:query",L.target,L.propertyKey),X=Reflect.getMetadata("http:rawContext",L.target,L.propertyKey),Z=Reflect.getMetadata("http:customDecorators",L.target,L.propertyKey)??[],_=Reflect.getMetadata(O.middlewares,L.target,L.propertyKey)??[],$=Reflect.getMetadata(O.services,L.target,L.propertyKey)??[],{path:D,method:H,handler:G,target:W,response:P,operationId:R,description:I,transactional:C}=L,y=Reflect.getMetadata(O.http,W.constructor)??[];y.push({path:D,method:H,body:Y,params:U,query:Q,customDecorators:Z,rawContext:X,handler:G,middlewares:_,response:P,operationId:R,description:I,services:$,transactional:C}),Reflect.defineMetadata(O.http,y,W.constructor)},vL;((U)=>{U[U.SERVER=0]="SERVER";U[U.REQUEST=1]="REQUEST"})(vL||={});var yL;((A)=>(A.controller=(B={path:"/"})=>{return function(V){async function M(){console.log(`Registering HTTP controller for ${B.path} using ${V.name}`),await c(),B=V2({path:"/",scope:0,tags:[]},B);let F=new M2({prefix:B.path,name:V.name});if(B.scope===0){let J=z.make(V);F.resolve({as:"local"},()=>({controller:()=>J}))}else if(B.scope===1)F.resolve({as:"local"},()=>({controller:()=>z.make(V)}));let p=Reflect.getMetadata("http:onRequest",V)??{};if(p.handler)F.onRequest((J)=>{let r=J.controller();return p.handler.call(r,J)});let QL=Reflect.getMetadata(O.middlewares,V)??[];LL(QL,F);let cL=Reflect.getMetadata(O.http,V)??[];for(let J of cL){let r=async(E)=>{let K=[];if(J.rawContext)K[J.rawContext.index]=E;if(J.body)K[J.body.index]=E.body;if(J.query)K[J.query.index]=E.query;if(!$L(J.params))for(let f of J.params)K[f.index]=E.params[f.slug];if(!$L(J.customDecorators))for(let f of J.customDecorators)K[f.index]=await f.handler(E);if(!$L(J.services))for(let f of J.services)K[f.index]=z.get(f.name);return K},mL=J.handler.constructor.name.includes("GeneratorFunction"),AL=J.method==="elysium:SSE",nL=J.transactional??B.transactional??!1,RL=J.body&&J.body.schema===void 0&&J.body.validator!==void 0;J.method=AL?"GET":J.method;let sL=()=>{let E=(K)=>{if(nL)return function(...f){return d.getDefaultConnection().transaction((t)=>{return S.context.run(new Map([["tenant",K.tenant],["http:context",K],["db:tx",t]]),()=>{try{return J.handler.call(K.controller(),...f)}catch(oL){throw t.rollback(),oL}})})};return function(...f){return S.context.run(new Map([["tenant",K.tenant],["http:context",K]]),()=>J.handler.call(K.controller(),...f))}};if(mL)return async function*(K){let f=E(K);try{for await(let t of f(...await r(K)))yield t}catch(t){yield t}};if(AL)return async function*(K){let f=E(K);K.set.headers["Content-Type"]="text/event-stream",K.set.headers["Cache-Control"]="no-cache",K.set.headers.Connection="keep-alive";while(!0)yield`data: ${await f(...await r(K))}
20
-
21
- `,await Bun.sleep(1)};if(RL)return async function(K){if(await J.body.validator.validate(K))return await E(K)(...await r(K));throw K.status(400,"Invalid request body")};return async function(K){return await E(K)(...await r(K))}},JL=A2(J.params??[],(E)=>E.slug,(E)=>E.schema),XL=J.middlewares.map((E)=>z.make(E));F.route(J.method,J.path,sL(),{config:{},async transform(E){if(RL&&!await J.body.validator.authorize(E))throw E.status(401,"Unauthorized");return l(XL,E,"onTransform")},beforeHandle(E){return l(XL,E,"onBeforeHandle")},afterHandle(E){return l(XL,E,"onAfterHandle")},afterResponse(E){return l(XL,E,"onAfterResponse")},detail:{tags:B.tags,description:J.description,operationId:J.operationId},body:RL?J.body?.validator?.schema:J.body?.schema,response:J.response,params:$L(JL)?void 0:bL.Object(JL)})}return F}Reflect.defineMetadata(O.elysiaPlugin,M,V)}},A.sse=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"elysium:SSE",path:V,...M})},A.get=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"GET",path:V,...M})},A.post=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"POST",path:V,...M})},A.put=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"PUT",path:V,...M})},A.del=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"DELETE",path:V,...M})},A.patch=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"PATCH",path:V,...M})},A.head=(B={})=>{let{path:V="/",...M}=B??{};return A.custom({method:"HEAD",path:V,...M})},A.options=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"OPTIONS",path:V,...M})},A.trace=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"TRACE",path:V,...M})},A.custom=({path:B="/",...V})=>{return function(M,F,p){process.nextTick(()=>{J2({path:B,handler:p.value,target:M,propertyKey:F,...V})})}},A.onRequest=()=>{return function(B,V,M){let F=Reflect.getMetadata("http:onRequest",B.constructor)??{};F.handler=M.value,Reflect.defineMetadata("http:onRequest",F,B.constructor)}},A.context=()=>{return function(B,V,M){Reflect.defineMetadata("http:rawContext",{index:M},B,V)}},A.param=(B,V)=>{return function(M,F,p){let QL=Reflect.getMetadata("http:params",M,F)??[];QL.push({slug:B,schema:V??bL.String(),index:p}),Reflect.defineMetadata("http:params",QL,M,F)}},A.query=(B)=>{return function(V,M,F){Reflect.defineMetadata("http:query",{schema:B,index:F},V,M)}},A.body=(B)=>{return function(V,M,F){if(typeof B==="function")Reflect.defineMetadata("http:body",{validator:B,index:F},V,M);else Reflect.defineMetadata("http:body",{schema:B,index:F},V,M)}},A.decorate=(B)=>{return()=>{return function(V,M,F){let p=Reflect.getMetadata("http:customDecorators",V,M)??[];p.push({handler:B,index:F}),Reflect.defineMetadata("http:customDecorators",p,V,M)}}}))(yL||={});import"reflect-metadata";import{assign as I2,uid as K2}from"radash";class gL extends k{#L;#Y;#U="pending";#Q;static register(L={}){return function(Y){L=I2({name:Y.name,queue:"default"},L);let U=`job.${L.name}`;z.instance(U,Y),Reflect.defineMetadata(O.job,{name:U,queue:L.queue},Y)}}id;createdAt;get startedAt(){return this.#L}get completedAt(){return this.#Y}get status(){return this.#U}constructor(L){super();this.id=L||this.generateJobId(),this.createdAt=new Date}async run(){try{this.#U="running",this.#L=new Date,this.debug(`Job ${this.id} started at ${this.#L.toISOString()}`),await this.execute(),this.#U="completed",this.#Y=new Date,this.debug(`Job ${this.id} completed at ${this.#Y.toISOString()}`)}catch(L){if(this.#Q=L instanceof Error?L:new Error(String(L)),this.#U!=="cancelled")this.#U="failed";this.#Y=new Date,this.trace(this.#Q)}}cancel(){this.#U="cancelled"}generateJobId(){return`job_${Date.now()}_${K2(8)}`}}import{getTableConfig as E2,pgSchema as F2,pgTable as dL}from"drizzle-orm/pg-core";import{t as N}from"elysia";var DL=(L,{mode:Y="select"}={})=>{let{columns:U}=E2(L);if(U===void 0)return N.Object({});let Q={};for(let X of U){if(["create","update"].includes(Y)&&X.primary)continue;if(Q[X.name]=j2(X),!X.notNull)Q[X.name]=N.Nullable(Q[X.name]);if(Y==="update"||X.hasDefault||!X.notNull)Q[X.name]=N.Optional(Q[X.name])}return N.Object(Q)},j2=(L)=>{let Y=(()=>{switch(L.dataType){case"string":return N.String({format:L.columnType==="PgUUID"?"uuid":void 0});case"number":return N.Number();case"boolean":return N.Boolean();case"array":return N.Array(N.Any());case"json":return N.Object({});case"date":case"localDate":case"localDateTime":return N.String({format:L.dataType==="date"?"date":"date-time"});case"bigint":return N.BigInt();case"buffer":return N.File();default:return N.Never()}})();if(!L.notNull)Y=N.Optional(Y);else Y=N.Required(Y);return Y},T2=(L,Y,U)=>{let Q=dL(L,Y,U);class X{static $inferSelect=Q.$inferSelect;static $inferInsert=Q.$inferInsert;static $inferUpdate=Q.$inferInsert;static get table(){if(!S.instance||!S.context.getStore)return Q;if(this.supportTenancy){let Z=HL.getCurrentTenant()??"public";return HL.wrapTenant(Z,this)}return Q}static tableName=L;static columns=Y;static extraConfig=U;static insertSchema=DL(Q,{mode:"create"});static updateSchema=DL(Q,{mode:"update"});static selectSchema=DL(Q,{mode:"select"});static supportTenancy=!1}return X},ML=new Map,GL=new Map,HL;((i)=>{let L=(Z)=>{return GL.get(Z)??i.registerTenant(Z)};i.getCurrentTenant=()=>{return S.context.getStore()?.get("tenant")??null},i.wrapTenant=(Z,_)=>{if(Z==="public")return dL(_.tableName,_.columns);let $=`${Z}.${_.tableName}`;if(ML.has($))return ML.get($);let H=L(Z).table(_.tableName,_.columns);return ML.set($,H),H},i.registerTenant=(Z)=>{if(GL.has(Z))return GL.get(Z);let _=F2(Z);return GL.set(Z,_),_},i.withTenant=(Z,_)=>{let $=S.context.getStore(),D=new Map($);return D.set("tenant",Z),S.context.run(D,_)}})(HL||={});import{Elysia as f2}from"elysia";import{assign as x2}from"radash";class lL{static register(L={}){return function(Y){async function U(Q){console.log(`Registering module ${Y.name}`),await c();let X=x2({controllers:[]},L),Z=new f2({name:Y.name,prefix:L.prefix});Z.resolve({as:"local"},()=>({module:Q}));let _=Reflect.getMetadata(O.middlewares,Y)??[];LL(_,Z);for(let $ of X.controllers){let D=Reflect.getMetadata(O.elysiaPlugin,$);if(D===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 Z.use(await D())}return Z}Reflect.defineMetadata(O.elysiaPlugin,U,Y)}}beforeRegister(){return Promise.resolve()}afterRegister(){return Promise.resolve()}}import{eq as OL}from"drizzle-orm";var w2=(L)=>{class Y{static Model=L;static connection="default";get db(){let U=this.constructor.connection,Q=null;if(U==="default")Q=S.context.getStore()?.get("db:tx")??null;return Q??d.getConnection(U)}async all(){return await this.db.select().from(L.table)}async paginate(U,Q=1){let X=await this.db.$count(L.table),Z=Math.max(Q-1,0)*U;return{page:Q,total:X,data:await this.db.select().from(L.table).offset(Z).limit(U)}}async find(U){let[Q]=await this.db.select().from(L.table).where(OL(L.table.id,U));return Q??null}async findBy(U,Q){let[X]=await this.db.select().from(L.table).where(OL(L.table[U],Q));return X??null}async insert(U){let[Q]=await this.db.insert(L.table).values(U).returning();return Q}async update(U,Q){let[X]=await this.db.update(L.table).set(Q).where(OL(L.table.id,U)).returning();return X}async updateAll(U){return await this.db.update(L.table).set(U).returning()}async delete(U){let[Q]=await this.db.delete(L.table).where(OL(L.table.id,U)).returning();return Q}async deleteAll(){return await this.db.delete(L.table).returning()}}return Y};import{Elysia as S2}from"elysia";var pL;((v)=>(v.controller=(_)=>{return function($){async function D(){console.log(`Registering Websocket route for ${_.path} using ${$.name}`),await c();let H=z.make($),G=Reflect.getMetadata(O.websocket,$)??{},W=G.open?.bind(H),P=G.close?.bind(H),R=G.message?.bind(H),I=G.drain?.bind(H),C=G.error?.bind(H)??((B)=>x.emit("elysium:error",B.error)),y=new S2;return y.ws(_.path,{open:W,close:P,message:R,drain:I,error:C,body:G.body,..._.options}),y}Reflect.defineMetadata(O.elysiaPlugin,D,$)}},v.onOpen=()=>{return function(_,$,D){let H=Reflect.getMetadata(O.websocket,_.constructor)??{};H.open=D.value,Reflect.defineMetadata(O.websocket,H,_.constructor)}},v.onClose=()=>{return function(_,$,D){let H=Reflect.getMetadata(O.websocket,_.constructor)??{};H.close=D.value,Reflect.defineMetadata(O.websocket,H,_.constructor)}},v.onMessage=(_)=>{return function($,D,H){let G=Reflect.getMetadata(O.websocket,$.constructor)??{};G.message=H.value,G.body=_,Reflect.defineMetadata(O.websocket,G,$.constructor)}},v.onDrain=()=>{return function(_,$,D){let H=Reflect.getMetadata(O.websocket,_.constructor)??{};H.drain=D.value,Reflect.defineMetadata(O.websocket,H,_.constructor)}},v.onError=()=>{return function(_,$,D){let H=Reflect.getMetadata(O.websocket,_.constructor)??{};H.error=D.value,Reflect.defineMetadata(O.websocket,H,_.constructor)}}))(pL||={});import{uid as N2}from"radash";var iL=globalThis.Worker;class uL extends k{#L;queues=new Map;defaultQueueName="default";static spawn(L,Y=["default"],U){let Q=new this;Q.debug(`Worker ${Q.id} starting with queues: ${Y.join(", ")}`);for(let X of Y)Q.createQueue({name:X,concurrency:U?.concurrency??1,maxRetries:U?.maxRetries??5,retryDelay:U?.retryDelay??5000,pauseOnError:U?.pauseOnError??!1});return L.addEventListener("message",async(X)=>{let{type:Z="job:process",jobId:_,job:$,args:D,queue:H="default"}=X.data;switch(Z){case"job:cancel":let G=Q.cancelJob(_,H);L.postMessage({type:"job:canceled",jobId:_,queue:H,success:G,count:G?1:0});break;case"job:cancelAll":let W=Q.cancelAllJobs(H);L.postMessage({type:"jobs:canceled",queue:H,count:W});break;case"job:process":Q.debug(`Worker ${Q.id} received job ${$} for queue ${H}`);try{let P=z.get($);if(!P)throw Q.error(`Job class ${$} not found`),new Error(`Job class ${$} not found`);let R=new P(...D||[]);Q.addJob(R,H),L.postMessage({type:"job:received",jobId:R.id,queue:H})}catch(P){Q.trace({...P,...U??{}},`Error while adding job '${$}' to queue '${H}' with worker ${Q.id}`),L.postMessage({type:"job:error",jobName:$,error:P.message})}break}}),L.addEventListener("error",(X)=>{Q.trace({...X.error,filename:X.filename},`Worker ${Q.id} error:`)}),L.addEventListener("unhandledrejection",(X)=>{Q.trace(X,`Worker ${Q.id} unhandled rejection:`)}),L.postMessage({type:"worker:ready",id:Q.id,queues:Y}),Q}constructor(){super();this.#L=N2(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 U=this.queues.get(Y);if(!U)return this.error(`Queue '${Y}' does not exist`),this;if(U.draining)return this.warning(`Queue '${Y}' is draining, job ${L.id} will not be added`),this;let Q={job:L,retries:0,queueName:Y};if(U.jobs.push(Q),this.debug(`Added job ${L.id} to queue '${Y}'`),!U.paused&&U.processing<U.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 U=Y.jobs.length;Y.jobs=[],this.info(`Cleared ${U} jobs from queue '${L}'`)}}else for(let[Y,U]of this.queues.entries()){let Q=U.jobs.length;U.jobs=[],this.info(`Cleared ${Q} 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 U=Y.jobs.shift();if(!U)return;if(U.job.status==="cancelled"){this.info(`Skipping cancelled job ${U.job.id}`),Y.processing--,this.processQueueJobs(L);return}Y.processing++;try{if(this.debug(`Processing job ${U.job.id} from queue '${L}'`),await U.job.run(),U.job.status==="failed"){if(U.retries<Y.options.maxRetries)U.retries++,this.warning(`Job ${U.job.id} failed, retrying (${U.retries}/${Y.options.maxRetries})`),setTimeout(()=>{if(U.job.status!=="cancelled")Y.jobs.push(U),this.processQueueJobs(L);else this.info(`Skipping cancelled job ${U.job.id} during retry delay`)},Y.options.retryDelay);else if(this.error(`Job ${U.job.id} failed after ${U.retries} retries`),Y.options.pauseOnError)this.pause(L),this.warning(`Queue '${L}' paused due to job failure`)}else if(U.job.status==="completed")this.success(`Job ${U.job.id} completed successfully`);else this.info(`Job ${U.job.id} cancelled while running`)}catch(Q){if(this.error(`Unexpected error processing job ${U.job.id}: ${Q}`),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,U]of this.queues.entries())L[Y]={waiting:U.jobs.length,processing:U.processing,paused:U.paused,draining:U.draining};return L}cancelJob(L,Y){if(Y)return this.cancelJobInQueue(L,Y);else{let U=!1;for(let[Q]of this.queues.entries())if(this.cancelJobInQueue(L,Q)){U=!0;break}return U}}cancelJobInQueue(L,Y){let U=this.queues.get(Y);if(!U)return!1;let Q=U.jobs.findIndex((X)=>X.job.id===L);if(Q>=0)return U.jobs[Q].job.cancel(),this.info(`Canceled job ${L} in queue '${Y}'`),!0;return!1}cancelAllJobs(L){let Y=0;if(L){let U=this.queues.get(L);if(U)Y=U.jobs.length,U.jobs.forEach((Q)=>{Q.job.cancel()}),this.info(`Canceled ${Y} jobs in queue '${L}'`)}else for(let[U,Q]of this.queues.entries()){let X=Q.jobs.length;Q.jobs.forEach((Z)=>{Z.job.cancel()}),Y+=X,this.info(`Canceled ${X} jobs in queue '${U}'`)}return Y}}class VL extends k{workers=[];currentWorkerIndex=0;queueWorkerMap=new Map;static instance=new VL;constructor(){super()}async init(){}async addWorker(L=[]){let Y;if(ELYSIUM_BUILD)Y=new iL("./index.js",{argv:["work",...L.map((U)=>`--queue=${U}`)]});else{let U=await Array.fromAsync(new Bun.Glob("./src/**/*.job.ts").scan());Y=new iL("./index.ts",{preload:U,argv:["work",...L.map((Q)=>`--queue=${Q}`)]})}Y.addEventListener("error",(U)=>{this.trace({message:"An error occurred inside a worker process",stack:U.message,name:"WorkerError"}),this.removeWorker(Y),this.addWorker(L)}),Y.addEventListener("messageerror",(U)=>{this.error(`Worker message error: ${U}`)}),Y.addEventListener("message",(U)=>{if(U.data.type==="worker:ready")this.debug(`Worker ${U.data.id} ready with queues: ${U.data.queues.join(", ")}`);else if(U.data.type==="job:received")this.debug(`Job ${U.data.jobId} received by worker for queue ${U.data.queue}`);else if(U.data.type==="job:error")this.error(`Error processing job ${U.data.jobName}: ${U.data.error}`);else this.debug(`Worker message: ${JSON.stringify(U.data)}`)}),this.workers.push(Y);for(let U of L){if(!this.queueWorkerMap.has(U))this.queueWorkerMap.set(U,[]);this.queueWorkerMap.get(U).push(Y)}}removeWorker(L){let Y=L??this.workers.pop();if(!Y)return;Y.terminate();for(let[U,Q]of this.queueWorkerMap.entries())this.queueWorkerMap.set(U,Q.filter((X)=>X!==Y));if(L)this.workers=this.workers.filter((U)=>U!==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:U,queue:Q="default"}=Reflect.getMetadata(O.job,L),X=this.queueWorkerMap.get(Q)||this.workers;if(X.length===0)throw new Error(`No workers available for queue '${Q}'`);let Z=this.currentWorkerIndex%X.length;X[Z].postMessage({job:U,args:Y,queue:Q}),this.currentWorkerIndex=(this.currentWorkerIndex+1)%this.workers.length}cancelJob(L,Y){for(let U of this.workers)U.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}}export{F0 as t,VL as WorkerPool,uL as Worker,pL as Websocket,o as Wamp,HL as Tenancy,KL as ServiceScope,z as Service,w2 as Repository,s as Redis,lL as Module,T2 as Model,SL as Middleware,gL as Job,k as InteractsWithConsole,vL as HttpControllerScope,yL as Http,x as Event,wL as Env,d as Database,ZL as ConsoleFormat,CL as CommandArgumentType,kL as Command,g as Cache,S as Application};
22
-
23
- //# debugId=14632E349B4BAC5C64756E2164756E21
24
- //# sourceMappingURL=index.js.map
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/job.d.ts CHANGED
@@ -103,4 +103,3 @@ export declare enum JobStatus {
103
103
  */
104
104
  CANCELLED = "cancelled"
105
105
  }
106
- //# sourceMappingURL=job.d.ts.map
package/dist/macros.d.ts CHANGED
@@ -1,2 +1,8 @@
1
+ declare global {
2
+ /**
3
+ * A macro indicating if the code is running from a build.
4
+ * @author Axel Nana <axel.nana@workbud.com>
5
+ */
6
+ var ELYSIUM_BUILD: boolean;
7
+ }
1
8
  export {};
2
- //# sourceMappingURL=macros.d.ts.map
@@ -67,4 +67,3 @@ export declare abstract class Middleware<TGuards extends string[] = []> {
67
67
  */
68
68
  onAfterResponse(_ctx: Context): any;
69
69
  }
70
- //# sourceMappingURL=middleware.d.ts.map
package/dist/model.d.ts CHANGED
@@ -4800,4 +4800,3 @@ export declare namespace Tenancy {
4800
4800
  */
4801
4801
  const withTenant: <TReturn>(tenant: string, callback: () => TReturn) => TReturn;
4802
4802
  }
4803
- //# sourceMappingURL=model.d.ts.map
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.
@@ -42,4 +46,3 @@ export declare abstract class Module {
42
46
  */
43
47
  afterRegister(): Promise<void>;
44
48
  }
45
- //# sourceMappingURL=module.d.ts.map
package/dist/redis.d.ts CHANGED
@@ -131,4 +131,3 @@ export declare namespace Redis {
131
131
  */
132
132
  const setDefaultConnection: (name: string) => Bun.RedisClient;
133
133
  }
134
- //# sourceMappingURL=redis.d.ts.map
@@ -161,4 +161,3 @@ export declare const Repository: <TModel extends ModelClass<TTableName, TColumns
161
161
  */
162
162
  readonly connection: string;
163
163
  };
164
- //# sourceMappingURL=repository.d.ts.map
package/dist/service.d.ts CHANGED
@@ -129,4 +129,3 @@ export declare namespace Service {
129
129
  const clear: () => void;
130
130
  }
131
131
  export {};
132
- //# sourceMappingURL=service.d.ts.map
package/dist/utils.d.ts CHANGED
@@ -23,4 +23,3 @@ export type ElysiaPlugin = () => Promise<Elysia>;
23
23
  * @returns The merged object (same reference as target)
24
24
  */
25
25
  export declare function deepMerge<T extends Record<string, any | any[]>>(target: T, ...sources: T[]): T;
26
- //# sourceMappingURL=utils.d.ts.map
package/dist/wamp.d.ts CHANGED
@@ -270,4 +270,3 @@ export declare namespace Wamp {
270
270
  */
271
271
  const subscribe: (topic: string, options?: WampSubscriptionOptions) => MethodDecorator;
272
272
  }
273
- //# sourceMappingURL=wamp.d.ts.map
@@ -89,4 +89,3 @@ export declare namespace Websocket {
89
89
  */
90
90
  const onError: () => MethodDecorator;
91
91
  }
92
- //# sourceMappingURL=websocket.d.ts.map
package/dist/worker.d.ts CHANGED
@@ -217,4 +217,3 @@ export declare class WorkerPool extends InteractsWithConsole {
217
217
  cancelAllJobs(queue?: string): boolean;
218
218
  }
219
219
  export {};
220
- //# sourceMappingURL=worker.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elysiumjs/core",
3
- "version": "0.5.0",
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,
@@ -13,7 +13,7 @@
13
13
  "scripts": {
14
14
  "format": "prettier --write \"./src/**/*.ts\"",
15
15
  "clean": "rimraf dist",
16
- "build:js": "bun build ./src/index.ts --outdir ./dist --target bun --packages external --root ./src --minify --sourcemap",
16
+ "build:js": "bun build ./src/index.ts --outdir ./dist --target bun --packages external --root ./src --minify",
17
17
  "build:ts": "tsc",
18
18
  "build": "bun run clean && bun run build:js && bun run build:ts",
19
19
  "prepublishOnly": "bun run build"
@@ -32,7 +32,7 @@
32
32
  "@elysiajs/swagger": "^1.3.0",
33
33
  "cache-manager": "^6.4.3",
34
34
  "cacheable": "^1.9.0",
35
- "drizzle-orm": "0.43.1-4aa795a",
35
+ "drizzle-orm": "^0.44.2",
36
36
  "elysia": "latest",
37
37
  "radash": "^12.1.0",
38
38
  "reflect-metadata": "^0.2.2",
package/tsconfig.json CHANGED
@@ -25,7 +25,7 @@
25
25
  "outDir": "dist",
26
26
  "declaration": true,
27
27
  "emitDeclarationOnly": true,
28
- "declarationMap": true,
28
+ "declarationMap": false,
29
29
  "declarationDir": "dist",
30
30
  "rootDir": "src",
31
31
  // Bundler mode