@elysiumjs/core 0.5.0 → 0.5.1

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