@elysiumjs/core 0.5.3 → 0.6.0

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.
@@ -0,0 +1,8 @@
1
+ $ bun run clean && bun run build:js && bun run build:ts
2
+ $ rimraf dist
3
+ $ bun build ./src/index.ts --outdir ./dist --target bun --packages external --root ./src --minify
4
+ Bundled 23 modules in 6ms
5
+
6
+ index.js 54.86 KB (entry point)
7
+
8
+ $ tsc
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # @elysiumjs/core
2
+
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Extract tenancy module with multi-tenant support (strict, simple, and custom modes).
8
+ - Enhance dependency injection with lazy registration.
9
+ - Add new base abstractions for commands, middlewares, and repositories.
10
+ - Add built-in `ConsoleLogger` and `RequestLoggerMiddleware`.
11
+ - Remove usage of `ELYSIUM_BUILD` macro.
package/dist/app.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import type { ElysiaSwaggerConfig } from '@elysiajs/swagger';
2
2
  import type { AnyElysia, ElysiaConfig, ErrorContext, TSchema } from 'elysia';
3
- import type { CommandClass } from './command';
4
3
  import type { DatabaseConnectionProps } from './database';
5
4
  import type { Route } from './http';
6
5
  import type { ModuleClass } from './module';
@@ -50,10 +49,6 @@ export type AppProps = {
50
49
  * The list of modules provided the app.
51
50
  */
52
51
  modules?: ModuleClass[];
53
- /**
54
- * The list of CLI commands provided the app.
55
- */
56
- commands?: CommandClass[];
57
52
  /**
58
53
  * The database configuration for the app.
59
54
  */
@@ -166,6 +161,14 @@ export declare abstract class Application extends InteractsWithConsole {
166
161
  * @param argv The command line arguments.
167
162
  */
168
163
  private commandExec;
164
+ /**
165
+ * Discovers all registered commands from the service container.
166
+ * Commands are registered via `@Command.register()` and stored with the
167
+ * `elysium.command.*` service name pattern.
168
+ *
169
+ * @returns An array of all discovered command classes, filtered by build mode.
170
+ */
171
+ private getCommands;
169
172
  private commandWork;
170
173
  /**
171
174
  * Starts the server on the specified port.
package/dist/cache.d.ts CHANGED
@@ -9,20 +9,20 @@ export interface CacheInterface {
9
9
  *
10
10
  * @param key The key of the cached data.
11
11
  */
12
- get<T>(key: string): Promise<T | null>;
12
+ get<T>(key: string): Promise<T | undefined>;
13
13
  /**
14
14
  * Retrieves the cached data for a given list of keys.
15
15
  * @typeParam T The type of the cached data.
16
16
  *
17
17
  * @param keys The list of cached data keys.
18
18
  */
19
- mget<T>(keys: string[]): Promise<Array<T | null>>;
19
+ mget<T>(keys: string[]): Promise<Array<T | undefined>>;
20
20
  /**
21
21
  * Gets the TTL of the cached data with the given key.
22
22
  * @param key The key of the cached data.
23
- * @returns The TTL of the cached data, or `null` if the data does not exist.
23
+ * @returns The TTL of the cached data, or `undefined` if the data does not exist.
24
24
  */
25
- ttl(key: string): Promise<number | null>;
25
+ ttl(key: string): Promise<number | undefined>;
26
26
  /**
27
27
  * Caches data under the given key and an optional TTL.
28
28
  * @typeParam T The type of the data to cache.
package/dist/command.d.ts CHANGED
@@ -77,7 +77,7 @@ type CommandArgumentMetadata = CommandArgumentProps & {
77
77
  * Type for a command class.
78
78
  * @author Axel Nana <axel.nana@workbud.com>
79
79
  */
80
- export type CommandClass = Class<Command> & {
80
+ export type CommandClass<T extends Command = Command> = Class<T> & {
81
81
  /**
82
82
  * The name of the command.
83
83
  */
@@ -86,6 +86,10 @@ export type CommandClass = Class<Command> & {
86
86
  * The description of the command.
87
87
  */
88
88
  readonly description: string;
89
+ /**
90
+ * Whether the command is only available in development mode.
91
+ */
92
+ readonly dev: boolean;
89
93
  };
90
94
  /**
91
95
  * Base class for commands.
@@ -108,6 +112,22 @@ export declare abstract class Command extends InteractsWithConsole {
108
112
  * This is displayed when displaying help messages for the command.
109
113
  */
110
114
  static readonly description: string;
115
+ /**
116
+ * Whether the command is only available in development mode.
117
+ * When set to `true`, the command will not be available in production builds.
118
+ */
119
+ static readonly dev: boolean;
120
+ /**
121
+ * Registers a command in the service container for autodiscovery.
122
+ *
123
+ * Commands registered with this decorator will be automatically discovered
124
+ * and made available in the CLI without needing to be listed explicitly.
125
+ *
126
+ * @param options Optional registration options.
127
+ */
128
+ static register(options?: {
129
+ name?: string;
130
+ }): ClassDecorator;
111
131
  /**
112
132
  * Decorator for registering a command argument.
113
133
  * @author Axel Nana <axel.nana@workbud.com>
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { SingletonBase } from 'elysia';
2
- import './macros';
3
2
  export { type Elysia, type TSchema, type Static, t } from 'elysia';
4
3
  export { type AppContext, type ElysiumPlugin, Application } from './app';
5
4
  export { Cache } from './cache';
@@ -8,10 +7,15 @@ export { ConsoleFormat, InteractsWithConsole } from './console';
8
7
  export { Database } from './database';
9
8
  export { Env } from './env';
10
9
  export { type EventData, type EventHandler, Event } from './event';
10
+ export { type LoggerInterface, ConsoleLogger } from './logger';
11
11
  export { type Context, type Route, HttpControllerScope, Http } from './http';
12
12
  export { Job } from './job';
13
13
  export { Middleware } from './middleware';
14
- export { type ModelClass, Model, Tenancy } from './model';
14
+ export { RequestLoggerMiddleware } from './middlewares/request-logger.middleware';
15
+ export { type ModelClass, Model } from './model';
16
+ export * as Tenancy from './tenancy';
17
+ export { TenantMiddleware, SimpleTenantMiddleware, StrictTenantMiddleware } from './tenancy';
18
+ export type { TenancyConfig, TenancyMode, ModelTenancyConfig } from './tenancy';
15
19
  export { type ModuleClass, Module } from './module';
16
20
  export { Redis } from './redis';
17
21
  export { type IdType, type RepositoryInterface, type RepositoryClass, Repository } from './repository';
package/dist/index.js CHANGED
@@ -1,19 +1,19 @@
1
1
  // @bun
2
- var $X=Object.defineProperty;var _X=(Q,X)=>{for(var Y in X)$X(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:(Z)=>X[Y]=()=>Z})};var _Q=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);import*as WQ from"readline";import{isEmpty as UX,omit as GX}from"radash";class k{static SPACE_WIDTH=60;write(Q,X=!0,Y=process.stdout){Y.write(Q+(X?`
2
+ var JX=Object.defineProperty;var hQ=(Q,X)=>{for(var $ in X)JX(Q,$,{get:X[$],enumerable:!0,configurable:!0,set:(Y)=>X[$]=()=>Y})};var _Q=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);import*as KQ from"readline";import{isEmpty as WX,omit as DX}from"radash";class q{static SPACE_WIDTH=60;write(Q,X=!0,$=process.stdout){$.write(Q+(X?`
3
3
  `:""))}newLine(){this.write(`
4
- `,!1)}info(Q){this.write(`${this.format("\u2139",4)} ${Q}`)}success(Q){this.write(`${this.format("\u2714",2)} ${Q}`)}warning(Q){this.write(`${this.format("\u26A0",3)} ${Q}`)}error(Q){this.write(`${this.format("\u2716",1)} ${Q}`,!0,process.stderr)}debug(Q){if(process.env.DEBUG)this.write(`\uD83D\uDD0D ${Q}`)}trace(Q,X){if(!Q)return;let Y=Q.name||"Error",Z=Q.message||"An error occurred",$=Q.stack||"";if(X)this.title(X);else this.newLine();if(this.write(this.format(`${Y}: ${Z}`,1)),Q.stack)this.write(this.format("Stack Trace:",9)),this.write(this.format($.split(`
4
+ `,!1)}info(Q){this.write(`${this.format("\u2139",4)} ${Q}`)}success(Q){this.write(`${this.format("\u2714",2)} ${Q}`)}warning(Q){this.write(`${this.format("\u26A0",3)} ${Q}`)}error(Q){this.write(`${this.format("\u2716",1)} ${Q}`,!0,process.stderr)}debug(Q){if(process.env.DEBUG)this.write(`\uD83D\uDD0D ${Q}`)}trace(Q,X){if(!Q)return;let $=Q.name||"Error",Y=Q.message||"An error occurred",Z=Q.stack||"";if(X)this.title(X);else this.newLine();if(this.write(this.format(`${$}: ${Y}`,1)),Q.stack)this.write(this.format("Stack Trace:",9)),this.write(this.format(Z.split(`
5
5
  `).map((U)=>` ${U}`).join(`
6
- `),8));let _=GX(Q,["name","message","stack"]);if(!UX(_))this.write(this.format("Additional Information:",9)),Object.keys(_).forEach((U)=>{let G=Q[U];this.write(` ${U}: ${JSON.stringify(G)}`)});this.newLine()}title(Q){this.newLine(),this.write(this.format(Q,9,10)),this.newLine()}section(Q){this.newLine(),this.write(`\x1B[1m${Q}\x1B[0m`)}table(Q,X){if(Q.length===0){this.info("No data to display");return}let Y=Object.keys(X||Q[0]),Z={};for(let U of Y){let G=X?.[U];if(G?.width){Z[U]=G.width;continue}let M=(G?.header||String(U)).length,H=Math.max(...Q.map((L)=>{let z=L[U];if(G?.format)return G.format(z).length;return String(z===null||z===void 0?"":z).length}));Z[U]=Math.max(M,H)}let $="",_="";for(let U of Y){let M=X?.[U]?.header||String(U),H=Z[U];$+=`| ${M.padEnd(H)} `,_+=`| ${"-".repeat(H)} `}$+="|",_+="|",this.write($),this.write(_);for(let U of Q){let G="";for(let M of Y){let H=X?.[M],L=Z[M],z=U[M],R;if(H?.format)R=H.format(z);else R=String(z===null||z===void 0?"":z);G+=`| ${R.padEnd(L)} `}G+="|",this.write(G)}this.newLine()}format(Q,...X){return`${X.map((Z)=>LX[Z]).join("")}${Q}\x1B[0m`}bold(Q){return this.format(Q,9)}italic(Q){return this.format(Q,11)}underline(Q){return this.format(Q,10)}clear(){process.stdout.write("\x1Bc")}moveCursor(Q,X){process.stdout.moveCursor(Q,X)}clearLine(){process.stdout.clearLine(0),process.stdout.cursorTo(0)}async prompt(Q,X){let Y=WQ.createInterface({input:process.stdin,output:process.stdout}),Z=X?` (default: ${X})`:"";return new Promise(($)=>{Y.question(`${Q}${Z}: `,(_)=>{Y.close(),$(_||X||"")})})}async promptPassword(Q){let X=WQ.createInterface({input:process.stdin,output:process.stdout});return process.stdin.setRawMode?.(!0),new Promise((Y)=>{let Z="";process.stdout.write(`${Q}: `),process.stdin.on("data",($)=>{let _=$.toString();if(_==="\r"||_===`
6
+ `),8));let G=DX(Q,["name","message","stack"]);if(!WX(G))this.write(this.format("Additional Information:",9)),Object.keys(G).forEach((U)=>{let _=Q[U];this.write(` ${U}: ${JSON.stringify(_)}`)});this.newLine()}title(Q){this.newLine(),this.write(this.format(Q,9,10)),this.newLine()}section(Q){this.newLine(),this.write(`\x1B[1m${Q}\x1B[0m`)}table(Q,X){if(Q.length===0){this.info("No data to display");return}let $=Object.keys(X||Q[0]),Y={};for(let U of $){let _=X?.[U];if(_?.width){Y[U]=_.width;continue}let M=(_?.header||String(U)).length,H=Math.max(...Q.map((z)=>{let K=z[U];if(_?.format)return _.format(K).length;return String(K===null||K===void 0?"":K).length}));Y[U]=Math.max(M,H)}let Z="",G="";for(let U of $){let M=X?.[U]?.header||String(U),H=Y[U];Z+=`| ${M.padEnd(H)} `,G+=`| ${"-".repeat(H)} `}Z+="|",G+="|",this.write(Z),this.write(G);for(let U of Q){let _="";for(let M of $){let H=X?.[M],z=Y[M],K=U[M],O;if(H?.format)O=H.format(K);else O=String(K===null||K===void 0?"":K);_+=`| ${O.padEnd(z)} `}_+="|",this.write(_)}this.newLine()}format(Q,...X){return`${X.map((Y)=>MX[Y]).join("")}${Q}\x1B[0m`}bold(Q){return this.format(Q,9)}italic(Q){return this.format(Q,11)}underline(Q){return this.format(Q,10)}clear(){process.stdout.write("\x1Bc")}moveCursor(Q,X){process.stdout.moveCursor(Q,X)}clearLine(){process.stdout.clearLine(0),process.stdout.cursorTo(0)}async prompt(Q,X){let $=KQ.createInterface({input:process.stdin,output:process.stdout}),Y=X?` (default: ${X})`:"";return new Promise((Z)=>{$.question(`${Q}${Y}: `,(G)=>{$.close(),Z(G||X||"")})})}async promptPassword(Q){let X=KQ.createInterface({input:process.stdin,output:process.stdout});return process.stdin.setRawMode?.(!0),new Promise(($)=>{let Y="";process.stdout.write(`${Q}: `),process.stdin.on("data",(Z)=>{let G=Z.toString();if(G==="\r"||G===`
7
7
  `){process.stdout.write(`
8
- `),process.stdin.setRawMode?.(!1),process.stdin.removeAllListeners("data"),X.close(),Y(Z);return}if(_==="\b"||_==="\x7F"){if(Z.length>0)Z=Z.slice(0,-1),process.stdout.write("\b \b");return}Z+=_,process.stdout.write("*")})})}async confirm(Q,X=!1){let Y=X?"Y/n":"y/N",Z=await this.prompt(`${Q} [${Y}]`);if(!Z)return X;return Z.toLowerCase()==="y"||Z.toLowerCase()==="yes"}async select(Q,X,Y=0){if(X.length===0)throw new Error("No options provided for selection");this.write(Q),X.forEach((_,U)=>{let G=U===Y;this.write(` ${U+1}. ${_}${G?" (default)":""}`)});let Z=await this.prompt("Enter your choice (number)");if(!Z)return X[Y];let $=parseInt(Z,10)-1;if(isNaN($)||$<0||$>=X.length)return this.warning(`Invalid selection. Using default: ${X[Y]}`),X[Y];return X[$]}formatTime(Q){if(Q<60)return`${Q.toFixed(1)}s`;if(Q<3600)return`${Math.floor(Q/60)}m ${Math.floor(Q%60)}s`;return`${Math.floor(Q/3600)}h ${Math.floor(Q%3600/60)}m`}}var OQ,LX;var e=_Q(()=>{((P)=>{P[P.BLACK=0]="BLACK";P[P.RED=1]="RED";P[P.GREEN=2]="GREEN";P[P.YELLOW=3]="YELLOW";P[P.BLUE=4]="BLUE";P[P.MAGENTA=5]="MAGENTA";P[P.CYAN=6]="CYAN";P[P.WHITE=7]="WHITE";P[P.GRAY=8]="GRAY";P[P.BOLD=9]="BOLD";P[P.UNDERLINE=10]="UNDERLINE";P[P.ITALIC=11]="ITALIC";P[P.INVERSE=12]="INVERSE"})(OQ||={});LX={[0]:Bun.color("black","ansi")||Bun.color("black","ansi-256")||"",[1]:Bun.color("red","ansi")||Bun.color("red","ansi-256")||"",[2]:Bun.color("green","ansi")||Bun.color("green","ansi-256")||"",[3]:Bun.color("yellow","ansi")||Bun.color("yellow","ansi-256")||"",[4]:Bun.color("blue","ansi")||Bun.color("blue","ansi-256")||"",[5]:Bun.color("magenta","ansi")||Bun.color("magenta","ansi-256")||"",[6]:Bun.color("cyan","ansi")||Bun.color("cyan","ansi-256")||"",[7]:Bun.color("white","ansi")||Bun.color("white","ansi-256")||"",[8]:Bun.color("gray","ansi")||Bun.color("gray","ansi-256")||"",[9]:"\x1B[1m",[10]:"\x1B[4m",[11]:"\x1B[3m",[12]:"\x1B[7m"}});import{isObject as UQ,isPrimitive as OX}from"radash";function o(Q,...X){if(!X.length)return Q;let Y=X.shift();if(Y===void 0)return Q;if(UQ(Q)&&UQ(Y))for(let Z in Y)if(UQ(Y[Z])){if(!Q[Z])Object.assign(Q,{[Z]:Y[Z]})}else if(Array.isArray(Y[Z])){if(!Array.isArray(Q[Z]))Q[Z]=[];if(Y[Z].length>0&&!UQ(Y[Z][0]))Q[Z]=[...new Set([...Q[Z],...Y[Z]])];else Y[Z].forEach(($,_)=>{if(UQ($)&&Q[Z][_])Q[Z][_]=o(Q[Z][_],$);else if(!Q[Z].includes($))Q[Z].push($)})}else if(OX(Y[Z]))Q[Z]??=Y[Z];else o(Q[Z],Y[Z]);return o(Q,...X)}var O,n=()=>new Promise((Q)=>process.nextTick(Q));var g=_Q(()=>{((T)=>(T.app=Symbol("elysium:Application"),T.controller=Symbol("elysium:Controller"),T.middlewares=Symbol("elysium:MiddlewaresList"),T.services=Symbol("elysium:ServicesList"),T.websocket=Symbol("elysium:WebSocket"),T.wamp=Symbol("elysium:Wamp"),T.http=Symbol("elysium:Http"),T.job=Symbol("elysium:Job"),T.arg=Symbol("elysium:CommandArguments"),T.elysiaPlugin=Symbol("elysium:ElysiaPlugin"),T.middlewareGuards=Symbol("elysium:MiddlewareGuards")))(O||={})});import{isString as QQ}from"radash";var NQ,PX=(Q)=>{return typeof Q==="function"&&Q.prototype&&Q.prototype.constructor===Q},s,B;var d=_Q(()=>{g();((Y)=>{Y[Y.SINGLETON=0]="SINGLETON";Y[Y.FACTORY=1]="FACTORY"})(NQ||={});s=new Map;((E)=>{E.register=(L)=>{return function(z){let R=L?.name??z.name,P=L?.scope??0;if(B.exists(R))console.error(`A service with the name ${R} has already been registered.`),process.exit(1);let j=()=>B.make(z);if(P===0){let C=j();s.set(R,{scope:P,factory(){return C}})}else s.set(R,{scope:P,factory:j})}},E.inject=(L)=>{return function(z,R,P){let j=Reflect.getMetadata(O.services,z,R)??[],C=Reflect.getMetadata("design:paramtypes",z,R)??[],y=QQ(L)?L:L?.name??C[P].name;j.push({name:y,index:P}),Reflect.defineMetadata(O.services,j,z,R)}},E.get=(L)=>{let z=QQ(L)?L:L.name;if(E.exists(z))return s.get(z).factory();return null},E.make=(L)=>{let z=Reflect.getMetadata(O.services,L)??[],R=[];return z.forEach((P)=>{let j=E.get(P.name);if(j===null)console.error(`Cannot inject service ${P.name}. No service was registered with the name: ${P.name}`),process.exit(1);R[P.index]=j}),new L(...R)},E.bind=(L,z)=>{let R=E.make(L);return E.instance(z??L.name,R)};function _(L,z){let R=QQ(L)?L:z??L.name;if(E.exists(R))console.error(`A service with the name ${R} has already been registered.`),process.exit(1);let P=()=>{return PX(L)?E.make(L):z()};return s.set(R,{scope:1,factory:P}),P()}E.factory=_,E.instance=(L,z)=>{let R=QQ(L)?L:L.name;if(E.exists(R))console.error(`A service with the name ${R} has already been registered.`),process.exit(1);return s.set(R,{scope:0,factory(){return z}}),z},E.remove=(L)=>{let z=QQ(L)?L:L.name;s.delete(z)},E.exists=(L)=>{let z=QQ(L)?L:L.name;return s.has(z)},E.clear=()=>{s.clear()}})(B||={})});import"reflect-metadata";import{assign as jX,uid as FX}from"radash";var dQ;var FQ=_Q(()=>{e();d();g();dQ=class dQ extends k{#Q;#X;#Y="pending";#Z;static register(Q={}){return function(X){Q=jX({name:X.name,queue:"default"},Q);let Y=`job.${Q.name}`;B.instance(Y,X),Reflect.defineMetadata(O.job,{name:Y,queue:Q.queue},X)}}id;createdAt;get startedAt(){return this.#Q}get completedAt(){return this.#X}get status(){return this.#Y}constructor(Q){super();this.id=Q||this.generateJobId(),this.createdAt=new Date}async run(){try{this.#Y="running",this.#Q=new Date,this.debug(`Job ${this.id} started at ${this.#Q.toISOString()}`),await this.execute(),this.#Y="completed",this.#X=new Date,this.debug(`Job ${this.id} completed at ${this.#X.toISOString()}`)}catch(Q){if(this.#Z=Q instanceof Error?Q:new Error(String(Q)),this.#Y!=="cancelled")this.#Y="failed";this.#X=new Date,this.trace(this.#Z)}}cancel(){this.#Y="cancelled"}generateJobId(){return`job_${Date.now()}_${FX(8)}`}}});var pQ={};_X(pQ,{WorkerPool:()=>zQ,Worker:()=>AQ});import{uid as AX}from"radash";var lQ,AQ,zQ;var EQ=_Q(()=>{e();FQ();d();g();lQ=globalThis.Worker;AQ=class AQ extends k{#Q;queues=new Map;defaultQueueName="default";static spawn(Q,X=["default"],Y){let Z=new this;Z.debug(`Worker ${Z.id} starting with queues: ${X.join(", ")}`);for(let $ of X)Z.createQueue({name:$,concurrency:Y?.concurrency??1,maxRetries:Y?.maxRetries??5,retryDelay:Y?.retryDelay??5000,pauseOnError:Y?.pauseOnError??!1});return Q.addEventListener("message",async($)=>{let{type:_="job:process",jobId:U,job:G,args:M,queue:H="default"}=$.data;switch(_){case"job:cancel":let L=Z.cancelJob(U,H);Q.postMessage({type:"job:canceled",jobId:U,queue:H,success:L,count:L?1:0});break;case"job:cancelAll":let z=Z.cancelAllJobs(H);Q.postMessage({type:"jobs:canceled",queue:H,count:z});break;case"job:process":Z.debug(`Worker ${Z.id} received job ${G} for queue ${H}`);try{let R=B.get(G);if(!R)throw Z.error(`Job class ${G} not found`),new Error(`Job class ${G} not found`);let P=new R(...M||[]);Z.addJob(P,H),Q.postMessage({type:"job:received",jobId:P.id,queue:H})}catch(R){Z.trace({...R,...Y??{}},`Error while adding job '${G}' to queue '${H}' with worker ${Z.id}`),Q.postMessage({type:"job:error",jobName:G,error:R.message})}break}}),Q.addEventListener("error",($)=>{Z.trace({...$.error,filename:$.filename},`Worker ${Z.id} error:`)}),Q.addEventListener("unhandledrejection",($)=>{Z.trace($,`Worker ${Z.id} unhandled rejection:`)}),Q.postMessage({type:"worker:ready",id:Z.id,queues:X}),Z}constructor(){super();this.#Q=AX(24),this.createQueue({name:this.defaultQueueName})}get id(){return this.#Q}createQueue(Q){if(this.queues.has(Q.name))return this.debug(`Queue with name '${Q.name}' already exists`),this;let X={options:{...Q,concurrency:Q.concurrency||1,maxRetries:Q.maxRetries||0,retryDelay:Q.retryDelay||1000,pauseOnError:Q.pauseOnError||!1},jobs:[],processing:0,paused:!1,draining:!1};return this.queues.set(Q.name,X),this.debug(`Created queue '${Q.name}'`),this}addJob(Q,X=this.defaultQueueName){let Y=this.queues.get(X);if(!Y)return this.error(`Queue '${X}' does not exist`),this;if(Y.draining)return this.warning(`Queue '${X}' is draining, job ${Q.id} will not be added`),this;let Z={job:Q,retries:0,queueName:X};if(Y.jobs.push(Z),this.debug(`Added job ${Q.id} to queue '${X}'`),!Y.paused&&Y.processing<Y.options.concurrency)this.processNextJob(X);return this}pause(Q){if(Q){let X=this.queues.get(Q);if(X)X.paused=!0,this.info(`Paused queue '${Q}'`)}else for(let[X]of this.queues.entries())this.pause(X);return this}resume(Q){if(Q){let X=this.queues.get(Q);if(X)X.paused=!1,this.info(`Resumed queue '${Q}'`),this.processQueueJobs(Q)}else for(let[X]of this.queues.entries())this.resume(X);return this}drain(Q){if(Q){let X=this.queues.get(Q);if(X)X.draining=!0,this.info(`Draining queue '${Q}'`)}else for(let[X]of this.queues.entries())this.drain(X);return this}clear(Q){if(Q){let X=this.queues.get(Q);if(X){let Y=X.jobs.length;X.jobs=[],this.info(`Cleared ${Y} jobs from queue '${Q}'`)}}else for(let[X,Y]of this.queues.entries()){let Z=Y.jobs.length;Y.jobs=[],this.info(`Cleared ${Z} jobs from queue '${X}'`)}return this}size(Q=this.defaultQueueName){let X=this.queues.get(Q);if(!X)throw new Error(`Queue '${Q}' does not exist`);return X.jobs.length}totalSize(){let Q=0;for(let X of this.queues.values())Q+=X.jobs.length;return Q}async processNextJob(Q){let X=this.queues.get(Q);if(!X||X.paused||X.processing>=X.options.concurrency)return;let Y=X.jobs.shift();if(!Y)return;if(Y.job.status==="cancelled"){this.info(`Skipping cancelled job ${Y.job.id}`),X.processing--,this.processQueueJobs(Q);return}X.processing++;try{if(this.debug(`Processing job ${Y.job.id} from queue '${Q}'`),await Y.job.run(),Y.job.status==="failed"){if(Y.retries<X.options.maxRetries)Y.retries++,this.warning(`Job ${Y.job.id} failed, retrying (${Y.retries}/${X.options.maxRetries})`),setTimeout(()=>{if(Y.job.status!=="cancelled")X.jobs.push(Y),this.processQueueJobs(Q);else this.info(`Skipping cancelled job ${Y.job.id} during retry delay`)},X.options.retryDelay);else if(this.error(`Job ${Y.job.id} failed after ${Y.retries} retries`),X.options.pauseOnError)this.pause(Q),this.warning(`Queue '${Q}' paused due to job failure`)}else if(Y.job.status==="completed")this.success(`Job ${Y.job.id} completed successfully`);else this.info(`Job ${Y.job.id} cancelled while running`)}catch(Z){if(this.error(`Unexpected error processing job ${Y.job.id}: ${Z}`),X.options.pauseOnError)this.pause(Q),this.warning(`Queue '${Q}' paused due to unexpected error`)}finally{X.processing--,this.processQueueJobs(Q)}}processQueueJobs(Q){let X=this.queues.get(Q);if(!X||X.paused)return;while(X.jobs.length>0&&X.processing<X.options.concurrency)this.processNextJob(Q)}getStats(){let Q={};for(let[X,Y]of this.queues.entries())Q[X]={waiting:Y.jobs.length,processing:Y.processing,paused:Y.paused,draining:Y.draining};return Q}cancelJob(Q,X){if(X)return this.cancelJobInQueue(Q,X);else{let Y=!1;for(let[Z]of this.queues.entries())if(this.cancelJobInQueue(Q,Z)){Y=!0;break}return Y}}cancelJobInQueue(Q,X){let Y=this.queues.get(X);if(!Y)return!1;let Z=Y.jobs.findIndex(($)=>$.job.id===Q);if(Z>=0)return Y.jobs[Z].job.cancel(),this.info(`Canceled job ${Q} in queue '${X}'`),!0;return!1}cancelAllJobs(Q){let X=0;if(Q){let Y=this.queues.get(Q);if(Y)X=Y.jobs.length,Y.jobs.forEach((Z)=>{Z.job.cancel()}),this.info(`Canceled ${X} jobs in queue '${Q}'`)}else for(let[Y,Z]of this.queues.entries()){let $=Z.jobs.length;Z.jobs.forEach((_)=>{_.job.cancel()}),X+=$,this.info(`Canceled ${$} jobs in queue '${Y}'`)}return X}};zQ=class zQ extends k{workers=[];currentWorkerIndex=0;queueWorkerMap=new Map;static instance=new zQ;constructor(){super()}async init(){}async addWorker(Q=[]){let X;if(ELYSIUM_BUILD)X=new lQ("./index.js",{argv:["work",...Q.map((Y)=>`--queue=${Y}`)]});else{let Y=await Array.fromAsync(new Bun.Glob("./src/**/*.job.ts").scan());X=new lQ("./index.ts",{preload:Y,argv:["work",...Q.map((Z)=>`--queue=${Z}`)]})}X.addEventListener("error",(Y)=>{this.trace({message:"An error occurred inside a worker process",stack:Y.message,name:"WorkerError"}),this.removeWorker(X),this.addWorker(Q)}),X.addEventListener("messageerror",(Y)=>{this.error(`Worker message error: ${Y}`)}),X.addEventListener("message",(Y)=>{if(Y.data.type==="worker:ready")this.debug(`Worker ${Y.data.id} ready with queues: ${Y.data.queues.join(", ")}`);else if(Y.data.type==="job:received")this.debug(`Job ${Y.data.jobId} received by worker for queue ${Y.data.queue}`);else if(Y.data.type==="job:error")this.error(`Error processing job ${Y.data.jobName}: ${Y.data.error}`);else this.debug(`Worker message: ${JSON.stringify(Y.data)}`)}),this.workers.push(X);for(let Y of Q){if(!this.queueWorkerMap.has(Y))this.queueWorkerMap.set(Y,[]);this.queueWorkerMap.get(Y).push(X)}}removeWorker(Q){let X=Q??this.workers.pop();if(!X)return;X.terminate();for(let[Y,Z]of this.queueWorkerMap.entries())this.queueWorkerMap.set(Y,Z.filter(($)=>$!==X));if(Q)this.workers=this.workers.filter((Y)=>Y!==X)}terminate(){while(this.workers.length>0)this.removeWorker();this.queueWorkerMap.clear()}runJob(Q,...X){if(!Reflect.hasMetadata(O.job,Q))throw new Error(`Job ${Q.name} is not marked with @job() decorator`);let{name:Y,queue:Z="default"}=Reflect.getMetadata(O.job,Q),$=this.queueWorkerMap.get(Z)||this.workers;if($.length===0)throw new Error(`No workers available for queue '${Z}'`);let _=this.currentWorkerIndex%$.length;$[_].postMessage({job:Y,args:X,queue:Z}),this.currentWorkerIndex=(this.currentWorkerIndex+1)%this.workers.length}cancelJob(Q,X){for(let Y of this.workers)Y.postMessage({type:"job:cancel",jobId:Q,queue:X});return this.workers.length>0}cancelAllJobs(Q){for(let X of this.workers)X.postMessage({type:"job:cancelAll",queue:Q});return this.workers.length>0}}});global.ELYSIUM_BUILD=typeof ELYSIUM_BUILD!=="undefined";import{t as vZ}from"elysia";e();import{AsyncLocalStorage as EX}from"async_hooks";import{parseArgs as IX}from"util";import{swagger as TX}from"@elysiajs/swagger";import{Value as GQ}from"@sinclair/typebox/value";import{Elysia as xX}from"elysia";import{first as wX}from"radash";import{getTableName as qQ,is as hQ,Table as bQ}from"drizzle-orm";import{drizzle as MX}from"drizzle-orm/bun-sql";import{Cache as JX}from"drizzle-orm/cache/core";import{createCache as SQ}from"cache-manager";import{KeyvCacheableMemory as BX}from"cacheable";import{Keyv as CQ}from"keyv";import{alphabetical as VX}from"radash";import{EventEmitter as zX}from"events";import{omit as RX}from"radash";import{EventEmitter as HX}from"events";import{isString as fQ}from"radash";class q extends HX{static instance=new q;constructor(){super();this.on("error",(Q)=>this.emitError(Q))}emitError(Q){this.emit("elysium:error",{data:Q,source:null})}emitEvent(Q,X,Y=null){this.emit(Q,{data:X,source:Y})}}var w;((m)=>{m.emit=(U,G,M=null)=>{q.instance.emitEvent(U,G,M)};function X(U,G){if(fQ(U))q.instance.on(U,G);else return function(M,H,L){let z=async function(P){try{await L.value(P)}catch(j){q.instance.emitError(j)}};if(U.prepend??!1)q.instance.prependListener(U.event,z);else q.instance.on(U.event,z)}}m.on=X;function Y(U,G){if(fQ(U))q.instance.once(U,G);else return function(M,H,L){let z=async function(P){try{await L.value(P)}catch(j){q.instance.emitError(j)}};if(U.prepend??!1)q.instance.prependOnceListener(U.event,z);else q.instance.once(U.event,z)}}m.once=Y,m.off=(U)=>{q.instance.removeAllListeners(U)},m.clear=()=>{q.instance.removeAllListeners()},m.listen=(U)=>{if(U.mode==="on")return X(U);else if(U.mode==="once")return Y(U);return function(G,M,H){console.error("Unknown mode provided to @listen. Use either 'on' or 'once'.")}}})(w||={});d();class DQ extends zX{#Q;#X;#Y="::";#Z=1000;#$=!0;#_=!1;#U;constructor(Q){super();w.once("elysium:app:launched",()=>{this.#Q=r.getConnection(Q.connection)}),this.#U=Q.connection,this.#X=Q.namespace,this.#Y=Q.keyPrefixSeparator??"::",this.#Z=Q.clearBatchSize??1000,this.#$=Q.useUnlink??!0,this.#_=Q.noNamespaceAffectsAll??!1,this.on("error",(X)=>{w.emit("elysium:error",X)})}get client(){return this.#Q}get opts(){return{namespace:this.#X,keyPrefixSeparator:this.#Y,clearBatchSize:this.#Z,noNamespaceAffectsAll:this.#_,dialect:"redis",url:this.#U}}get namespace(){return this.#X}set namespace(Q){this.#X=Q}async get(Q){Q=this.createKeyPrefix(Q,this.#X);let X=await this.client.get(Q);return X===null?void 0:X}async set(Q,X,Y){if(Q=this.createKeyPrefix(Q,this.#X),Y)await this.client.set(Q,X,"PX",Y);else await this.client.set(Q,X)}async setMany(Q){let X=[];for(let{key:Y,value:Z,ttl:$}of Q){let _=this.createKeyPrefix(Y,this.#X);if($)X.push(this.client.set(_,Z,"PX",$));else X.push(this.client.set(_,Z))}await Promise.all(X)}async delete(Q){return Q=this.createKeyPrefix(Q,this.#X),await(this.#$?this.client.send("UNLINK",[Q]):this.client.del(Q))>0}async clear(){try{if(!this.#X&&this.#_){await this.client.send("FLUSHDB",[]);return}let Q="0",X=this.#Z,Y=this.#X?`${this.#X}${this.#Y}*`:"*",Z=[];do{let $=await this.client.send("SCAN",[Q,"MATCH",Y,"COUNT",X.toString(),"TYPE","string"]),[_,U]=$;if(Q=_.toString(),U.length===0)continue;if(!this.#X)U=U.filter((G)=>!G.includes(this.#Y));Z.push(U.map((G)=>this.client.del(G)))}while(Q!=="0");await Promise.all(Z)}catch(Q){this.emit("error",Q)}}async has(Q){return Q=this.createKeyPrefix(Q,this.#X),this.client.exists(Q)}async hasMany(Q){let X=[];for(let Y of Q){let Z=this.createKeyPrefix(Y,this.#X);X.push(this.client.exists(Z))}return Promise.all(X)}async getMany(Q){if(Q.length===0)return[];return Q=Q.map((Y)=>this.createKeyPrefix(Y,this.#X)),await this.client.mget(...Q)}async disconnect(){this.client.close()}async deleteMany(Q){let X=!1,Y=[];for(let $ of Q){let _=this.createKeyPrefix($,this.#X);if(this.#$)Y.push(this.client.send("UNLINK",[_]));else Y.push(this.client.del(_))}let Z=await Promise.all(Y);for(let $ of Z)if(typeof $==="number"&&$>0)X=!0;return X}async*iterator(Q){let X=Q?`${Q}${this.#Y}*`:"*",Y="0";do{let Z=await this.client.send("SCAN",[Y,"MATCH",X,"TYPE","string"]),[$,_]=Z;if(Y=$.toString(),!Q&&!this.#_)_=_.filter((U)=>!U.includes(this.#Y));if(_.length>0){let U=await this.client.mget(..._);for(let G of _.keys()){let M=this.getKeyWithoutPrefix(_[G],Q),H=U[G];yield[M,H]}}}while(Y!=="0")}createKeyPrefix(Q,X){return X?`${X}${this.#Y}${Q}`:Q}getKeyWithoutPrefix(Q,X){return X?Q.replace(`${X}${this.#Y}`,""):Q}}var r;((h)=>{let Q=(U)=>{return`redis.connection.${U}`};h.getConnection=(U)=>{if(!B.exists(Q(U)))console.error(`No Redis connection with name ${U} found. Please make sure to register the connection before using it.`),process.exit(1);return B.get(Q(U))},h.registerConnection=(U,G)=>{if(B.exists(Q(U)))console.error(`A Redis connection with the name ${U} has already been registered.`),process.exit(1);return B.instance(Q(U),new Bun.RedisClient(G.url,RX(G,["url"])))},h.connectionExists=(U)=>{return B.exists(Q(U))},h.getDefaultConnection=()=>{return h.getConnection("default")},h.setDefaultConnection=(U)=>{let G=Q("default");return B.remove(G),B.instance(G,h.getConnection(U))}})(r||={});var kQ=(Q)=>{let X=SQ({stores:[new CQ({store:Q,namespace:"cache"})]}),Y=new Map;return{...X,tags(...Z){let $=`cache__${VX(Z,(U)=>U).join("__")}`,_=Y.get($);if(!_)_=SQ({stores:[new CQ({store:Q,namespace:$})]}),Y.set($,_);return _}}};class l{static#Q;static#X;static weak=Object.seal({map:new WeakMap,get(Q){if(!this.map.has(Q))this.map.set(Q,{});return this.map.get(Q)},del(Q){this.map.delete(Q)}});static get redis(){if(!l.#Q)l.#Q=kQ(new DQ({connection:"cache"}));return l.#Q}static get memory(){if(!l.#X)l.#X=kQ(new BX({ttl:60000,lruSize:5000}));return l.#X}}d();class KQ extends JX{cacheStrategy;globalTtl;#Q;usedTablesPerKey={};constructor(Q="explicit",X=1,Y="redis"){super();this.cacheStrategy=Q;this.globalTtl=X;this.#Q=l[Y].tags("database")}strategy(){return this.cacheStrategy}async get(Q){return await this.#Q.get(Q)??void 0}async put(Q,X,Y,Z,$){await this.#Q.set(Q,X,($?.ex??this.globalTtl)*1000);for(let _ of Y){let U=this.usedTablesPerKey[_];if(U===void 0)this.usedTablesPerKey[_]=[Q];else U.push(Q)}}async onMutate(Q){let X=Q.tags?Array.isArray(Q.tags)?Q.tags:[Q.tags]:[],Y=Q.tables?Array.isArray(Q.tables)?Q.tables:[Q.tables]:[],Z=new Set;for(let $ of Y){let _=hQ($,bQ)?qQ($):$,U=this.usedTablesPerKey[_]??[];for(let G of U)Z.add(G)}if(Z.size>0||X.length>0){await this.#Q.mdel(X),await this.#Q.mdel([...Z]);for(let $ of Y){let _=hQ($,bQ)?qQ($):$;this.usedTablesPerKey[_]=[]}}}}var p;((b)=>{let Q=(U)=>{return`db.connection.${U}`};b.getConnection=(U)=>{if(!B.exists(Q(U)))console.error(`No connection with name ${U} found. Please make sure to register the connection before using it.`),process.exit(1);return B.get(Q(U))},b.registerConnection=(U,G)=>{if(B.exists(Q(U)))console.error(`A connection with the name ${U} has already been registered.`),process.exit(1);return B.instance(Q(U),MX({...G,cache:G.cache===void 0?void 0:G.cache===!0?new KQ:G.cache.enabled?new KQ(G.cache.strategy,G.cache.ttl,G.cache.storage):void 0}))},b.connectionExists=(U)=>{return B.exists(Q(U))},b.getDefaultConnection=()=>{return b.getConnection("default")},b.setDefaultConnection=(U)=>{let G=Q("default");return B.remove(G),B.instance(G,b.getConnection(U))}})(p||={});var PQ=new Map,jQ=(Q)=>{for(let[X,Y]of Object.entries(Q))PQ.set(X,Y)},vQ;((XQ)=>(XQ.get=(Z,$)=>{return PQ.get(Z)??$},XQ.exists=(Z)=>{return PQ.has(Z)},XQ.clear=()=>{PQ.clear()}))(vQ||={});d();g();var u=(Q,X,Y)=>{return N.context.run(new Map([["tenant",X.tenant],["http:context",X]]),async()=>{for(let Z of Q)try{let $=await Z[Y](X);if($!==void 0)return $}catch($){throw $}})},YQ=(Q,X)=>{let Y=Q.map((Z)=>B.make(Z));X.onRequest((Z)=>{return u(Y,Z,"onRequest")}),X.onTransform((Z)=>{return u(Y,Z,"onTransform")}),X.onBeforeHandle((Z)=>{return u(Y,Z,"onBeforeHandle")}),X.onAfterHandle((Z)=>{return u(Y,Z,"onAfterHandle")}),X.onAfterResponse((Z)=>{return u(Y,Z,"onAfterResponse")})};class yQ{static register(...Q){return function(X,Y,Z){if(Y===void 0&&Z===void 0){let $=Reflect.getMetadata(O.middlewares,X)??[];$.push(...Q),Reflect.defineMetadata(O.middlewares,$,X)}else{let $=Reflect.getMetadata(O.middlewares,X,Y)??[];$.push(...Q),Reflect.defineMetadata(O.middlewares,$,X,Y)}}}static guards(Q){class X extends this{}return Reflect.defineMetadata(O.middlewareGuards,Q,X),X}get guards(){return Reflect.getMetadata(O.middlewareGuards,this.constructor)??[]}onRequest(Q){}onTransform(Q){}onAfterHandle(Q){}onBeforeHandle(Q){}onAfterResponse(Q){}}d();g();import{Elysia as WX}from"elysia";import{omit as DX}from"radash";import KX from"wampy";d();g();class gQ extends WebSocket{protocols;constructor(Q,X){super(Q,X);this.protocols=X}get protocol(){return this.protocols?.[0]??"wamp.2.json"}}var t;((f)=>{let Q=(H)=>{return`wamp.connection.${H}`};f.getConnection=(H)=>{if(!B.exists(Q(H)))console.error(`No WAMP connection with name ${H} found. Please make sure to register the connection before using it.`),process.exit(1);return B.get(Q(H))},f.registerConnection=(H,L)=>{if(B.exists(Q(H)))console.error(`A WAMP connection with name ${H} already exists. Please ensure to register a new connection before overwriting it.`),process.exit(1);let z=new KX(L.url,{ws:gQ,...DX(L,["url"]),onError(){L.onError?.(),w.emit("elysium:error",new Error(`An error occurred in WAMP connection ${H}`))}}),R=L.maxRetries??5,P=L.retryInterval??5000,j=0,C=async()=>{try{await z.connect()}catch(y){if(console.error(`Failed to connect to WAMP server (attempt ${j+1}/${R}):`,y),j<R)j++,setTimeout(C,P);else console.error(`Max retry attempts (${R}) reached. Giving up.`),w.emit("elysium:error",new Error(`Failed to establish WAMP connection ${H} after ${R} attempts`))}};return C(),B.instance(Q(H),z)},f.connectionExists=(H)=>{return B.exists(Q(H))},f.getDefaultConnection=()=>{return f.getConnection("default")},f.setDefaultConnection=(H)=>{let L=Q("default");return B.remove(L),B.instance(L,f.getConnection(H))},f.controller=(H)=>{return function(L){async function z(){console.log(`Registering Wamp controller for connection ${H.connection} using ${L.name}`),await n();let R=B.make(L),P=Reflect.getMetadata(O.wamp,L)??{},j=t.getConnection(H.connection??"default"),C=new WX;return C.onStart(async(y)=>{let V=P.registrations??[],W=P.subscriptions??[];for(let J of V)j.register(J.topic,J.handler.bind(R),J.options).then((I)=>{console.log(`Registered ${J.topic} with id ${I.registrationId}`)});for(let J of W)j.subscribe(J.topic,J.handler.bind(R),J.options).then((I)=>{console.log(`Subscribed ${J.topic} with id ${I.subscriptionId}`)})}),C}Reflect.defineMetadata(O.elysiaPlugin,z,L)}},f.register=(H,L)=>{return function(z,R,P){let j=Reflect.getMetadata(O.wamp,z.constructor)??{};j.registrations??=[],j.registrations.push({topic:H,options:L,handler:P.value}),Reflect.defineMetadata(O.wamp,j,z.constructor)}},f.subscribe=(H,L)=>{return function(z,R,P){let j=Reflect.getMetadata(O.wamp,z.constructor)??{};j.subscriptions??=[],j.subscriptions.push({topic:H,options:L,handler:P.value}),Reflect.defineMetadata(O.wamp,j,z.constructor)}}})(t||={});class N extends k{#Q;#X;_appContextStorage=new EX;static get instance(){return B.get("elysium.app")}static get context(){return N.instance._appContextStorage}static register(Q={}){return function(X){let Y,Z=Object.getPrototypeOf(X);while(Z&&Z!==Object.prototype){let _=Reflect.getMetadata(O.app,Z);if(_){Y=_;break}Z=Object.getPrototypeOf(Z)}if(Y)Q=o(Y,Q);let $=Reflect.getMetadata(O.app,X);if($)Q=o($,Q);Q=o({modules:[],swagger:!1},Q),Reflect.defineMetadata(O.app,Q,X)}}constructor(){super();let{env:Q,debug:X}=Reflect.getMetadata(O.app,this.constructor)??{};if(this.#X=X??!1,Q){let _=GQ.Convert(Q,GQ.Clone(Bun.env));if(this.#X&&!GQ.Check(Q,_)){let U=GQ.Errors(Q,_).First();this.trace(U,"Invalid environment configuration")}jQ(GQ.Clean(Q,_))}else jQ(Bun.env);B.instance("elysium.app",this);let{database:Y,redis:Z,wamp:$}=Reflect.getMetadata(O.app,this.constructor);if(Z){for(let _ in Z.connections)r.registerConnection(_,Z.connections[_]);if(r.connectionExists(Z.default))r.setDefaultConnection(Z.default)}if(Y){for(let _ in Y.connections)p.registerConnection(_,Y.connections[_]);if(p.connectionExists(Y.default))p.setDefaultConnection(Y.default)}if($){for(let _ in $.connections)t.registerConnection(_,$.connections[_]);if(t.connectionExists($.default))t.setDefaultConnection($.default)}this.run().then(()=>w.emit("elysium:app:launched",this,this)).catch((_)=>{w.emit("elysium:error",_),this.trace(_,"An error occurred while launching the application"),process.exit(1)})}get elysia(){return this.#Q}get isDebug(){return this.#X}set isDebug(Q){this.#X=Q}async onError(Q){return!0}async onStart(Q){}async onStop(Q){}async run(){let Q=process.argv.slice(2),X=Q[0];if(!X)this.commandDescribe();else{let{commands:Y}=Reflect.getMetadata(O.app,this.constructor);switch(X){case"serve":return this.commandServe();case"work":return this.commandWork(Q.slice(1));case"help":{let Z=Q[1];if(Z){let $=Y?.find((_)=>_.command===Z);if($){let _=B.make($);return this.write(await _.help()),process.exit(0)}console.error(`Command <${Z}> not found.`)}else console.error("No command provided. Usage: styx help <command>");this.commandList();break}case"list":{this.write(this.bold("Available commands:")),this.commandList();break}default:{let Z=Q.slice(1);return this.commandExec(X,Z)}}}return process.exit(0)}getConfig(Q){return Reflect.getMetadata(O.app,this.constructor)?.[Q]??null}async commandExec(Q,X){let{commands:Y}=Reflect.getMetadata(O.app,this.constructor),Z=Y?.find(($)=>$.command===Q);if(!Z)return console.error(`Command ${Q} not found`),this.commandList(),process.exit(1);try{let $=B.make(Z);if(await $.init(...X))await $.run();else{let U=await $.help();this.write(U)}return process.exit(0)}catch($){return console.error($.message),process.exit(1)}}async commandWork(Q){this.info("Starting worker process...");let{values:X}=IX({args:Q,options:{queue:{type:"string",multiple:!0,default:["default"],short:"q"},concurrency:{type:"string",default:"1",short:"c"},["max-retries"]:{type:"string",default:"5",short:"r"},["retry-delay"]:{type:"string",default:"5000",short:"d"},["pause-on-error"]:{type:"boolean",default:!1,short:"p"}}}),{Worker:Y}=await Promise.resolve().then(() => (EQ(),pQ)),Z=X.queue.map((_)=>_.split(",")).reduce((_,U)=>_.concat(U),[]),$=Y.spawn(self,Z,{concurrency:parseInt(X.concurrency,10),maxRetries:parseInt(X["max-retries"],10),retryDelay:parseInt(X["retry-delay"],10),pauseOnError:X["pause-on-error"]});this.success(`Worker process ${this.format($.id,2)} started with queues: ${Z.map((_)=>this.format(_,6)).join(", ")}`)}async commandServe(){let{server:Q,modules:X,swagger:Y,plugins:Z}=Reflect.getMetadata(O.app,this.constructor);if(this.#Q=new xX(Q).onRequest((_)=>{if(this.isDebug)console.log(_.request.method,_.request.url)}),w.emit("elysium:server:before-init",this,this),this.#Q.resolve({as:"global"},({request:_})=>({tenant:_.headers.get("x-tenant-id")??"public"})),Y)this.#Q.use(TX(Y));if(Z&&Z.length>0){this.debug("Registering plugins...");for(let _ of Z)this.#Q.use(await _(this))}this.#Q.onError({as:"global"},async(_)=>{if(await this.onError(_)){w.emit("elysium:error",_),this.trace({name:"HttpError",message:"Unexpected error while handling HTTP request",stack:_.error.stack,..._.error});let U={};if(typeof _.code==="number")return _.error.response;else switch(_.code){case"VALIDATION":{U={scope:_.error.type,code:_.error.message};break}case"INTERNAL_SERVER_ERROR":{U={message:_.error.message};break}}return{type:_.code,data:U}}}).onStart(async(_)=>{await this.onStart(_),w.emit("elysium:server:start",_,this)}).onStop(async(_)=>{await this.onStop(_),w.emit("elysium:server:stop",_,this),this._appContextStorage.disable()});let $=Reflect.getMetadata(O.middlewares,this.constructor)??[];YQ($,this.#Q);for(let _ of X){let U=Reflect.getMetadata(O.elysiaPlugin,_);if(U===void 0)return console.error(`Invalid module class ${_.name} registered in app ${this.constructor.name}. Ensure that you used the @module() decorator on the module.`),process.exit(1);let G=B.bind(_);await G.beforeRegister(),this.#Q.use(await U(G)),await G.afterRegister()}w.emit("elysium:server:after-init",this,this),this.#Q.listen(Q?.port??(parseInt(process.env.PORT,10)||3000)),process.on("SIGINT",()=>{this.#Q.stop().then(()=>process.exit(0))})}commandDescribe(){this.section(`${this.bold("Usage:")} ${this.format("styx",5)} <command> [options]`),this.section(this.bold("Core Commands:")),this.newLine(),this.commandDescription("serve","","Starts the server."),this.commandDescription("help","<command>","Displays help for a command."),this.commandDescription("list","","List all available application commands."),this.section(this.bold("Application Commands:")),this.commandList()}commandList(){let{commands:Q}=Reflect.getMetadata(O.app,this.constructor),X=(Q??[]).reduce((Y,Z)=>{let $=wX(Z.command.split(":")),_=Y.get($)??[];return _.push(Z),Y.set($,_),Y},new Map);for(let[Y,Z]of X){this.section(this.format(Y,4));for(let $ of Z)this.commandDescription($.command,"",$.description)}}commandDescription(Q,X,Y,Z=k.SPACE_WIDTH){X=X.length===0?" ":` ${X} `,this.write(` ${this.format(Q,6)}${X}${"\u2219".repeat(Z-Q.length-X.length)} ${Y}`)}}e();g();import{isArray as fX,trim as NX}from"radash";var uQ;((_)=>{_.STRING="string";_.NUMBER="number";_.BOOLEAN="boolean";_.ENUM="enum";_.ARRAY="array"})(uQ||={});class cQ extends k{static command="command";static description="Command description";static arg(Q={}){return function(X,Y){let Z=Reflect.getMetadata(O.arg,X.constructor)??[],$=Reflect.getMetadata("design:type",X,Y),_=Q.type;if(!_&&$){if($===Array){if(_="array",!Q.arrayType)Q={...Q,arrayType:"string"}}else if($.constructor!==Object)switch($.name.toLowerCase()){case"number":_="number";break;case"boolean":_="boolean";break;case"string":_="string";break;default:_=void 0}else if(Object.values($).length>0){if(_="enum",!Q.enum)Q={...Q,enum:Object.values($)}}}Z.push({name:Q.name??Y,description:Q.description,required:Q.required??!1,default:Q.default,type:_,enum:Q.enum,arrayType:Q.arrayType,propertyKey:Y}),Reflect.defineMetadata(O.arg,Z,X.constructor)}}async init(...Q){let X=this.processArgs(Q),Y=this.validateArgs(X);if(!Y.valid){if(Y.missing.length>0)console.error(`Missing required arguments: ${Y.missing.join(", ")}
9
- `);return!1}if(Object.keys(X).includes("help"))return!1;let Z=this.getArguments();for(let $ of Z)if(X[$.name]!==void 0)this[$.propertyKey]=X[$.name];return!0}getArguments(){return Reflect.getMetadata(O.arg,this.constructor)||[]}async help(){let Q=`${this.bold("Command:")} ${this.format(this.constructor.command,5)}
8
+ `),process.stdin.setRawMode?.(!1),process.stdin.removeAllListeners("data"),X.close(),$(Y);return}if(G==="\b"||G==="\x7F"){if(Y.length>0)Y=Y.slice(0,-1),process.stdout.write("\b \b");return}Y+=G,process.stdout.write("*")})})}async confirm(Q,X=!1){let $=X?"Y/n":"y/N",Y=await this.prompt(`${Q} [${$}]`);if(!Y)return X;return Y.toLowerCase()==="y"||Y.toLowerCase()==="yes"}async select(Q,X,$=0){if(X.length===0)throw Error("No options provided for selection");this.write(Q),X.forEach((G,U)=>{let _=U===$;this.write(` ${U+1}. ${G}${_?" (default)":""}`)});let Y=await this.prompt("Enter your choice (number)");if(!Y)return X[$];let Z=parseInt(Y,10)-1;if(isNaN(Z)||Z<0||Z>=X.length)return this.warning(`Invalid selection. Using default: ${X[$]}`),X[$];return X[Z]}formatTime(Q){if(Q<60)return`${Q.toFixed(1)}s`;if(Q<3600)return`${Math.floor(Q/60)}m ${Math.floor(Q%60)}s`;return`${Math.floor(Q/3600)}h ${Math.floor(Q%3600/60)}m`}}var VQ,MX;var QQ=_Q(()=>{((L)=>{L[L.BLACK=0]="BLACK";L[L.RED=1]="RED";L[L.GREEN=2]="GREEN";L[L.YELLOW=3]="YELLOW";L[L.BLUE=4]="BLUE";L[L.MAGENTA=5]="MAGENTA";L[L.CYAN=6]="CYAN";L[L.WHITE=7]="WHITE";L[L.GRAY=8]="GRAY";L[L.BOLD=9]="BOLD";L[L.UNDERLINE=10]="UNDERLINE";L[L.ITALIC=11]="ITALIC";L[L.INVERSE=12]="INVERSE"})(VQ||={});MX={[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 LQ,isPrimitive as jX}from"radash";function s(Q,...X){if(!X.length)return Q;let $=X.shift();if($===void 0)return Q;if(LQ(Q)&&LQ($))for(let Y in $)if(LQ($[Y])){if(!Q[Y])Object.assign(Q,{[Y]:$[Y]})}else if(Array.isArray($[Y])){if(!Array.isArray(Q[Y]))Q[Y]=[];if($[Y].length>0&&!LQ($[Y][0]))Q[Y]=[...new Set([...Q[Y],...$[Y]])];else $[Y].forEach((Z,G)=>{if(LQ(Z)&&Q[Y][G])Q[Y][G]=s(Q[Y][G],Z);else if(!Q[Y].includes(Z))Q[Y].push(Z)})}else if(jX($[Y]))Q[Y]??=$[Y];else s(Q[Y],$[Y]);return s(Q,...X)}var P,n=()=>new Promise((Q)=>process.nextTick(Q));var p=_Q(()=>{((w)=>(w.app=Symbol("elysium:Application"),w.controller=Symbol("elysium:Controller"),w.middlewares=Symbol("elysium:MiddlewaresList"),w.services=Symbol("elysium:ServicesList"),w.websocket=Symbol("elysium:WebSocket"),w.wamp=Symbol("elysium:Wamp"),w.http=Symbol("elysium:Http"),w.job=Symbol("elysium:Job"),w.arg=Symbol("elysium:CommandArguments"),w.elysiaPlugin=Symbol("elysium:ElysiaPlugin"),w.middlewareGuards=Symbol("elysium:MiddlewareGuards")))(P||={})});import{isString as XQ}from"radash";var yQ,FX=(Q)=>{return typeof Q==="function"&&Q.prototype&&Q.prototype.constructor===Q},gQ,vQ=(Q)=>{return typeof Q==="object"&&Q!==null&&gQ in Q},v,B;var y=_Q(()=>{p();(($)=>{$[$.SINGLETON=0]="SINGLETON";$[$.FACTORY=1]="FACTORY"})(yQ||={});gQ=Symbol("lazy"),v=new Map;((E)=>{E.register=(O)=>{return function(L){let V=O?.name??L.name,A=O?.scope??0;if(B.exists(V))console.error(`A service with the name ${V} has already been registered.`),process.exit(1);let C=()=>B.make(L);if(A===0){let R=C();v.set(V,{scope:A,factory(){return R}})}else v.set(V,{scope:A,factory:C})}},E.inject=(O)=>{return function(L,V,A){let C=Reflect.getMetadata(P.services,L,V)??[],R=Reflect.getMetadata("design:paramtypes",L,V)??[],J=XQ(O)?O:O?.name??R[A].name;C.push({name:J,index:A}),Reflect.defineMetadata(P.services,C,L,V)}},E.get=(O)=>{let L=XQ(O)?O:O.name;if(E.exists(L)){let V=v.get(L);if(vQ(V)){let A=V.resolver();return v.set(L,{scope:0,factory:()=>A}),A}return V.factory()}return null},E.registerLazy=(O,L)=>{if(v.has(O)&&!vQ(v.get(O)))throw Error(`Service ${O} already registered`);v.set(O,{[gQ]:!0,resolver:L})},E.make=(O)=>{let L=Reflect.getMetadata(P.services,O)??[],V=[];return L.forEach((A)=>{let C=E.get(A.name);if(C===null)console.error(`Cannot inject service ${A.name}. No service was registered with the name: ${A.name}`),process.exit(1);V[A.index]=C}),new O(...V)},E.bind=(O,L)=>{let V=E.make(O);return E.instance(L??O.name,V)};function U(O,L){let V=XQ(O)?O:L??O.name;if(E.exists(V))console.error(`A service with the name ${V} has already been registered.`),process.exit(1);let A=()=>{return FX(O)?E.make(O):L()};return v.set(V,{scope:1,factory:A}),A()}E.factory=U,E.instance=(O,L)=>{let V=XQ(O)?O:O.name;if(E.exists(V))console.error(`A service with the name ${V} has already been registered.`),process.exit(1);return v.set(V,{scope:0,factory(){return L}}),L},E.remove=(O)=>{let L=XQ(O)?O:O.name;v.delete(L)},E.exists=(O)=>{let L=XQ(O)?O:O.name;return v.has(L)},E.clear=()=>{v.clear()},E.keys=(O)=>{let L="^"+O.replace(/[-[\]{}()+.,\\^$|#\s]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$",V=new RegExp(L);return Array.from(v.keys()).filter((A)=>V.test(A))}})(B||={})});import"reflect-metadata";import{assign as xX,uid as kX}from"radash";var sQ;var oQ=_Q(()=>{QQ();y();p();sQ=class sQ extends q{#Q;#X;#$="pending";#Y;static register(Q={}){return function(X){Q=xX({name:X.name,queue:"default"},Q);let $=`job.${Q.name}`;B.instance($,X),Reflect.defineMetadata(P.job,{name:$,queue:Q.queue},X)}}id;createdAt;get startedAt(){return this.#Q}get completedAt(){return this.#X}get status(){return this.#$}constructor(Q){super();this.id=Q||this.generateJobId(),this.createdAt=new Date}async run(){try{this.#$="running",this.#Q=new Date,this.debug(`Job ${this.id} started at ${this.#Q.toISOString()}`),await this.execute(),this.#$="completed",this.#X=new Date,this.debug(`Job ${this.id} completed at ${this.#X.toISOString()}`)}catch(Q){if(this.#Y=Q instanceof Error?Q:Error(String(Q)),this.#$!=="cancelled")this.#$="failed";this.#X=new Date,this.trace(this.#Y)}}cancel(){this.#$="cancelled"}generateJobId(){return`job_${Date.now()}_${kX(8)}`}}});var tQ={};hQ(tQ,{WorkerPool:()=>JQ,Worker:()=>EQ});import{uid as qX}from"radash";var rQ,EQ,JQ;var IQ=_Q(()=>{QQ();y();p();rQ=globalThis.Worker;EQ=class EQ extends q{#Q;queues=new Map;defaultQueueName="default";static spawn(Q,X=["default"],$){let Y=new this;Y.debug(`Worker ${Y.id} starting with queues: ${X.join(", ")}`);for(let Z of X)Y.createQueue({name:Z,concurrency:$?.concurrency??1,maxRetries:$?.maxRetries??5,retryDelay:$?.retryDelay??5000,pauseOnError:$?.pauseOnError??!1});return Q.addEventListener("message",async(Z)=>{let{type:G="job:process",jobId:U,job:_,args:M,queue:H="default"}=Z.data;switch(G){case"job:cancel":let z=Y.cancelJob(U,H);Q.postMessage({type:"job:canceled",jobId:U,queue:H,success:z,count:z?1:0});break;case"job:cancelAll":let K=Y.cancelAllJobs(H);Q.postMessage({type:"jobs:canceled",queue:H,count:K});break;case"job:process":Y.debug(`Worker ${Y.id} received job ${_} for queue ${H}`);try{let O=B.get(_);if(!O)throw Y.error(`Job class ${_} not found`),Error(`Job class ${_} not found`);let L=new O(...M||[]);Y.addJob(L,H),Q.postMessage({type:"job:received",jobId:L.id,queue:H})}catch(O){Y.trace({...O,...$??{}},`Error while adding job '${_}' to queue '${H}' with worker ${Y.id}`),Q.postMessage({type:"job:error",jobName:_,error:O.message})}break}}),Q.addEventListener("error",(Z)=>{Y.trace({...Z.error,filename:Z.filename},`Worker ${Y.id} error:`)}),Q.addEventListener("unhandledrejection",(Z)=>{Y.trace(Z,`Worker ${Y.id} unhandled rejection:`)}),Q.postMessage({type:"worker:ready",id:Y.id,queues:X}),Y}constructor(){super();this.#Q=qX(24),this.createQueue({name:this.defaultQueueName})}get id(){return this.#Q}createQueue(Q){if(this.queues.has(Q.name))return this.debug(`Queue with name '${Q.name}' already exists`),this;let X={options:{...Q,concurrency:Q.concurrency||1,maxRetries:Q.maxRetries||0,retryDelay:Q.retryDelay||1000,pauseOnError:Q.pauseOnError||!1},jobs:[],processing:0,paused:!1,draining:!1};return this.queues.set(Q.name,X),this.debug(`Created queue '${Q.name}'`),this}addJob(Q,X=this.defaultQueueName){let $=this.queues.get(X);if(!$)return this.error(`Queue '${X}' does not exist`),this;if($.draining)return this.warning(`Queue '${X}' is draining, job ${Q.id} will not be added`),this;let Y={job:Q,retries:0,queueName:X};if($.jobs.push(Y),this.debug(`Added job ${Q.id} to queue '${X}'`),!$.paused&&$.processing<$.options.concurrency)this.processNextJob(X);return this}pause(Q){if(Q){let X=this.queues.get(Q);if(X)X.paused=!0,this.info(`Paused queue '${Q}'`)}else for(let[X]of this.queues.entries())this.pause(X);return this}resume(Q){if(Q){let X=this.queues.get(Q);if(X)X.paused=!1,this.info(`Resumed queue '${Q}'`),this.processQueueJobs(Q)}else for(let[X]of this.queues.entries())this.resume(X);return this}drain(Q){if(Q){let X=this.queues.get(Q);if(X)X.draining=!0,this.info(`Draining queue '${Q}'`)}else for(let[X]of this.queues.entries())this.drain(X);return this}clear(Q){if(Q){let X=this.queues.get(Q);if(X){let $=X.jobs.length;X.jobs=[],this.info(`Cleared ${$} jobs from queue '${Q}'`)}}else for(let[X,$]of this.queues.entries()){let Y=$.jobs.length;$.jobs=[],this.info(`Cleared ${Y} jobs from queue '${X}'`)}return this}size(Q=this.defaultQueueName){let X=this.queues.get(Q);if(!X)throw Error(`Queue '${Q}' does not exist`);return X.jobs.length}totalSize(){let Q=0;for(let X of this.queues.values())Q+=X.jobs.length;return Q}async processNextJob(Q){let X=this.queues.get(Q);if(!X||X.paused||X.processing>=X.options.concurrency)return;let $=X.jobs.shift();if(!$)return;if($.job.status==="cancelled"){this.info(`Skipping cancelled job ${$.job.id}`),X.processing--,this.processQueueJobs(Q);return}X.processing++;try{if(this.debug(`Processing job ${$.job.id} from queue '${Q}'`),await $.job.run(),$.job.status==="failed"){if($.retries<X.options.maxRetries)$.retries++,this.warning(`Job ${$.job.id} failed, retrying (${$.retries}/${X.options.maxRetries})`),setTimeout(()=>{if($.job.status!=="cancelled")X.jobs.push($),this.processQueueJobs(Q);else this.info(`Skipping cancelled job ${$.job.id} during retry delay`)},X.options.retryDelay);else if(this.error(`Job ${$.job.id} failed after ${$.retries} retries`),X.options.pauseOnError)this.pause(Q),this.warning(`Queue '${Q}' paused due to job failure`)}else if($.job.status==="completed")this.success(`Job ${$.job.id} completed successfully`);else this.info(`Job ${$.job.id} cancelled while running`)}catch(Y){if(this.error(`Unexpected error processing job ${$.job.id}: ${Y}`),X.options.pauseOnError)this.pause(Q),this.warning(`Queue '${Q}' paused due to unexpected error`)}finally{X.processing--,this.processQueueJobs(Q)}}processQueueJobs(Q){let X=this.queues.get(Q);if(!X||X.paused)return;while(X.jobs.length>0&&X.processing<X.options.concurrency)this.processNextJob(Q)}getStats(){let Q={};for(let[X,$]of this.queues.entries())Q[X]={waiting:$.jobs.length,processing:$.processing,paused:$.paused,draining:$.draining};return Q}cancelJob(Q,X){if(X)return this.cancelJobInQueue(Q,X);else{let $=!1;for(let[Y]of this.queues.entries())if(this.cancelJobInQueue(Q,Y)){$=!0;break}return $}}cancelJobInQueue(Q,X){let $=this.queues.get(X);if(!$)return!1;let Y=$.jobs.findIndex((Z)=>Z.job.id===Q);if(Y>=0)return $.jobs[Y].job.cancel(),this.info(`Canceled job ${Q} in queue '${X}'`),!0;return!1}cancelAllJobs(Q){let X=0;if(Q){let $=this.queues.get(Q);if($)X=$.jobs.length,$.jobs.forEach((Y)=>{Y.job.cancel()}),this.info(`Canceled ${X} jobs in queue '${Q}'`)}else for(let[$,Y]of this.queues.entries()){let Z=Y.jobs.length;Y.jobs.forEach((G)=>{G.job.cancel()}),X+=Z,this.info(`Canceled ${Z} jobs in queue '${$}'`)}return X}};JQ=class JQ extends q{workers=[];currentWorkerIndex=0;queueWorkerMap=new Map;static instance=new JQ;constructor(){super()}async init(){}async addWorker(Q=[]){let X;if(Bun.main.endsWith(".js"))X=new rQ("./index.js",{argv:["work",...Q.map((Y)=>`--queue=${Y}`)]});else{let Y=await Array.fromAsync(new Bun.Glob("./src/**/*.job.ts").scan());X=new rQ("./index.ts",{preload:Y,argv:["work",...Q.map((Z)=>`--queue=${Z}`)]})}X.addEventListener("error",(Y)=>{this.trace({message:"An error occurred inside a worker process",stack:Y.message,name:"WorkerError"}),this.removeWorker(X),this.addWorker(Q)}),X.addEventListener("messageerror",(Y)=>{this.error(`Worker message error: ${Y}`)}),X.addEventListener("message",(Y)=>{if(Y.data.type==="worker:ready")this.debug(`Worker ${Y.data.id} ready with queues: ${Y.data.queues.join(", ")}`);else if(Y.data.type==="job:received")this.debug(`Job ${Y.data.jobId} received by worker for queue ${Y.data.queue}`);else if(Y.data.type==="job:error")this.error(`Error processing job ${Y.data.jobName}: ${Y.data.error}`);else this.debug(`Worker message: ${JSON.stringify(Y.data)}`)}),this.workers.push(X);for(let Y of Q){if(!this.queueWorkerMap.has(Y))this.queueWorkerMap.set(Y,[]);this.queueWorkerMap.get(Y).push(X)}}removeWorker(Q){let X=Q??this.workers.pop();if(!X)return;X.terminate();for(let[$,Y]of this.queueWorkerMap.entries())this.queueWorkerMap.set($,Y.filter((Z)=>Z!==X));if(Q)this.workers=this.workers.filter(($)=>$!==X)}terminate(){while(this.workers.length>0)this.removeWorker();this.queueWorkerMap.clear()}runJob(Q,...X){if(!Reflect.hasMetadata(P.job,Q))throw Error(`Job ${Q.name} is not marked with @job() decorator`);let{name:$,queue:Y="default"}=Reflect.getMetadata(P.job,Q),Z=this.queueWorkerMap.get(Y)||this.workers;if(Z.length===0)throw Error(`No workers available for queue '${Y}'`);let G=this.currentWorkerIndex%Z.length;Z[G].postMessage({job:$,args:X,queue:Y}),this.currentWorkerIndex=(this.currentWorkerIndex+1)%this.workers.length}cancelJob(Q,X){for(let $ of this.workers)$.postMessage({type:"job:cancel",jobId:Q,queue:X});return this.workers.length>0}cancelAllJobs(Q){for(let X of this.workers)X.postMessage({type:"job:cancelAll",queue:Q});return this.workers.length>0}}});import{t as P2}from"elysia";QQ();import{AsyncLocalStorage as hX}from"async_hooks";import{parseArgs as bX}from"util";import{swagger as vX}from"@elysiajs/swagger";import{Value as HQ}from"@sinclair/typebox/value";import{Elysia as yX}from"elysia";import{first as gX}from"radash";import{getTableName as uQ,is as mQ,Table as iQ}from"drizzle-orm";import{drizzle as wX}from"drizzle-orm/bun-sql";import{Cache as fX}from"drizzle-orm/cache/core";import{createCache as dQ}from"cache-manager";import{KeyvCacheableMemory as IX}from"cacheable";import{Keyv as lQ}from"keyv";import{alphabetical as TX}from"radash";import{EventEmitter as AX}from"events";import{omit as EX}from"radash";import{EventEmitter as KX}from"events";import{isString as bQ}from"radash";class b extends KX{static instance=new b;constructor(){super();this.on("error",(Q)=>this.emitError(Q))}emitError(Q){this.emit("elysium:error",{data:Q,source:null})}emitEvent(Q,X,$=null){this.emit(Q,{data:X,source:$})}}var N;((c)=>{c.emit=(U,_,M=null)=>{b.instance.emitEvent(U,_,M)};function X(U,_){if(bQ(U))b.instance.on(U,_);else return function(M,H,z){let K=async function(L){try{await z.value(L)}catch(V){b.instance.emitError(V)}};if(U.prepend??!1)b.instance.prependListener(U.event,K);else b.instance.on(U.event,K)}}c.on=X;function $(U,_){if(bQ(U))b.instance.once(U,_);else return function(M,H,z){let K=async function(L){try{await z.value(L)}catch(V){b.instance.emitError(V)}};if(U.prepend??!1)b.instance.prependOnceListener(U.event,K);else b.instance.once(U.event,K)}}c.once=$,c.off=(U)=>{b.instance.removeAllListeners(U)},c.clear=()=>{b.instance.removeAllListeners()},c.listen=(U)=>{if(U.mode==="on")return X(U);else if(U.mode==="once")return $(U);return function(_,M,H){console.error("Unknown mode provided to @listen. Use either 'on' or 'once'.")}}})(N||={});y();class jQ extends AX{#Q;#X;#$="::";#Y=1000;#Z=!0;#G=!1;#U;constructor(Q){super();N.once("elysium:app:launched",()=>{this.#Q=o.getConnection(Q.connection)}),this.#U=Q.connection,this.#X=Q.namespace,this.#$=Q.keyPrefixSeparator??"::",this.#Y=Q.clearBatchSize??1000,this.#Z=Q.useUnlink??!0,this.#G=Q.noNamespaceAffectsAll??!1,this.on("error",(X)=>{N.emit("elysium:error",X)})}get client(){return this.#Q}get opts(){return{namespace:this.#X,keyPrefixSeparator:this.#$,clearBatchSize:this.#Y,noNamespaceAffectsAll:this.#G,dialect:"redis",url:this.#U}}get namespace(){return this.#X}set namespace(Q){this.#X=Q}async get(Q){Q=this.createKeyPrefix(Q,this.#X);let X=await this.client.get(Q);return X===null?void 0:X}async set(Q,X,$){if(Q=this.createKeyPrefix(Q,this.#X),$)await this.client.set(Q,X,"PX",$);else await this.client.set(Q,X)}async setMany(Q){let X=[];for(let{key:$,value:Y,ttl:Z}of Q){let G=this.createKeyPrefix($,this.#X);if(Z)X.push(this.client.set(G,Y,"PX",Z));else X.push(this.client.set(G,Y))}await Promise.all(X)}async delete(Q){return Q=this.createKeyPrefix(Q,this.#X),await(this.#Z?this.client.send("UNLINK",[Q]):this.client.del(Q))>0}async clear(){try{if(!this.#X&&this.#G){await this.client.send("FLUSHDB",[]);return}let Q="0",X=this.#Y,$=this.#X?`${this.#X}${this.#$}*`:"*",Y=[];do{let Z=await this.client.send("SCAN",[Q,"MATCH",$,"COUNT",X.toString(),"TYPE","string"]),[G,U]=Z;if(Q=G.toString(),U.length===0)continue;if(!this.#X)U=U.filter((_)=>!_.includes(this.#$));Y.push(U.map((_)=>this.client.del(_)))}while(Q!=="0");await Promise.all(Y)}catch(Q){this.emit("error",Q)}}async has(Q){return Q=this.createKeyPrefix(Q,this.#X),this.client.exists(Q)}async hasMany(Q){let X=[];for(let $ of Q){let Y=this.createKeyPrefix($,this.#X);X.push(this.client.exists(Y))}return Promise.all(X)}async getMany(Q){if(Q.length===0)return[];return Q=Q.map(($)=>this.createKeyPrefix($,this.#X)),await this.client.mget(...Q)}async disconnect(){this.client.close()}async deleteMany(Q){let X=!1,$=[];for(let Z of Q){let G=this.createKeyPrefix(Z,this.#X);if(this.#Z)$.push(this.client.send("UNLINK",[G]));else $.push(this.client.del(G))}let Y=await Promise.all($);for(let Z of Y)if(typeof Z==="number"&&Z>0)X=!0;return X}async*iterator(Q){let X=Q?`${Q}${this.#$}*`:"*",$="0";do{let Y=await this.client.send("SCAN",[$,"MATCH",X,"TYPE","string"]),[Z,G]=Y;if($=Z.toString(),!Q&&!this.#G)G=G.filter((U)=>!U.includes(this.#$));if(G.length>0){let U=await this.client.mget(...G);for(let _ of G.keys()){let M=this.getKeyWithoutPrefix(G[_],Q),H=U[_];yield[M,H]}}}while($!=="0")}createKeyPrefix(Q,X){return X?`${X}${this.#$}${Q}`:Q}getKeyWithoutPrefix(Q,X){return X?Q.replace(`${X}${this.#$}`,""):Q}}var o;((g)=>{let Q=(U)=>{return`redis.connection.${U}`};g.getConnection=(U)=>{if(!B.exists(Q(U)))console.error(`No Redis connection with name ${U} found. Please make sure to register the connection before using it.`),process.exit(1);return B.get(Q(U))},g.registerConnection=(U,_)=>{if(B.exists(Q(U)))console.error(`A Redis connection with the name ${U} has already been registered.`),process.exit(1);return B.instance(Q(U),new Bun.RedisClient(_.url,EX(_,["url"])))},g.connectionExists=(U)=>{return B.exists(Q(U))},g.getDefaultConnection=()=>{return g.getConnection("default")},g.setDefaultConnection=(U)=>{let _=Q("default");return B.remove(_),B.instance(_,g.getConnection(U))}})(o||={});var pQ=(Q)=>{let X=dQ({stores:[new lQ({store:Q,namespace:"cache"})]}),$=new Map;return{...X,tags(...Y){let Z=`cache__${TX(Y,(U)=>U).join("__")}`,G=$.get(Z);if(!G)G=dQ({stores:[new lQ({store:Q,namespace:Z})]}),$.set(Z,G);return G}}};class u{static#Q;static#X;static weak=Object.seal({map:new WeakMap,get(Q){if(!this.map.has(Q))this.map.set(Q,{});return this.map.get(Q)},del(Q){this.map.delete(Q)}});static get redis(){if(!u.#Q)u.#Q=pQ(new jQ({connection:"cache"}));return u.#Q}static get memory(){if(!u.#X)u.#X=pQ(new IX({ttl:60000,lruSize:5000}));return u.#X}}y();class FQ extends fX{cacheStrategy;globalTtl;#Q;usedTablesPerKey={};constructor(Q="explicit",X=1,$="redis"){super();this.cacheStrategy=Q;this.globalTtl=X;this.#Q=u[$].tags("database")}strategy(){return this.cacheStrategy}async get(Q){return await this.#Q.get(Q)??void 0}async put(Q,X,$,Y,Z){await this.#Q.set(Q,X,(Z?.ex??this.globalTtl)*1000);for(let G of $){let U=this.usedTablesPerKey[G];if(U===void 0)this.usedTablesPerKey[G]=[Q];else U.push(Q)}}async onMutate(Q){let X=Q.tags?Array.isArray(Q.tags)?Q.tags:[Q.tags]:[],$=Q.tables?Array.isArray(Q.tables)?Q.tables:[Q.tables]:[],Y=new Set;for(let Z of $){let G=mQ(Z,iQ)?uQ(Z):Z,U=this.usedTablesPerKey[G]??[];for(let _ of U)Y.add(_)}if(Y.size>0||X.length>0){await this.#Q.mdel(X),await this.#Q.mdel([...Y]);for(let Z of $){let G=mQ(Z,iQ)?uQ(Z):Z;this.usedTablesPerKey[G]=[]}}}}var h;((d)=>{let Q=(U)=>{return`db.connection.${U}`};d.getConnection=(U)=>{if(!B.exists(Q(U)))console.error(`No connection with name ${U} found. Please make sure to register the connection before using it.`),process.exit(1);return B.get(Q(U))},d.registerConnection=(U,_)=>{if(B.exists(Q(U)))console.error(`A connection with the name ${U} has already been registered.`),process.exit(1);return B.instance(Q(U),wX({..._,cache:_.cache===void 0?void 0:_.cache===!0?new FQ:_.cache.enabled?new FQ(_.cache.strategy,_.cache.ttl,_.cache.storage):void 0}))},d.connectionExists=(U)=>{return B.exists(Q(U))},d.getDefaultConnection=()=>{return d.getConnection("default")},d.setDefaultConnection=(U)=>{let _=Q("default");return B.remove(_),B.instance(_,d.getConnection(U))}})(h||={});var RQ=new Map,AQ=(Q)=>{for(let[X,$]of Object.entries(Q))RQ.set(X,$)},cQ;(($Q)=>($Q.get=(Y,Z)=>{return RQ.get(Y)??Z},$Q.exists=(Y)=>{return RQ.has(Y)},$Q.clear=()=>{RQ.clear()}))(cQ||={});y();p();var m=(Q,X,$)=>{return f.context.run(new Map([["tenant",X.tenant],["http:context",X]]),async()=>{for(let Y of Q)try{let Z=await Y[$](X);if(Z!==void 0)return Z}catch(Z){throw Z}})},YQ=(Q,X)=>{let $=Q.map((Y)=>B.make(Y));X.onRequest((Y)=>{return m($,Y,"onRequest")}),X.onTransform((Y)=>{return m($,Y,"onTransform")}),X.onBeforeHandle((Y)=>{return m($,Y,"onBeforeHandle")}),X.onAfterHandle((Y)=>{return m($,Y,"onAfterHandle")}),X.onAfterResponse((Y)=>{return m($,Y,"onAfterResponse")})};class ZQ{static register(...Q){return function(X,$,Y){if($===void 0&&Y===void 0){let Z=Reflect.getMetadata(P.middlewares,X)??[];Z.push(...Q),Reflect.defineMetadata(P.middlewares,Z,X)}else{let Z=Reflect.getMetadata(P.middlewares,X,$)??[];Z.push(...Q),Reflect.defineMetadata(P.middlewares,Z,X,$)}}}static guards(Q){class X extends this{}return Reflect.defineMetadata(P.middlewareGuards,Q,X),X}get logger(){return B.get("logger").child({middleware:this.constructor.name})}get guards(){return Reflect.getMetadata(P.middlewareGuards,this.constructor)??[]}onRequest(Q){}onTransform(Q){}onAfterHandle(Q){}onBeforeHandle(Q){}onAfterResponse(Q){}}y();p();import{Elysia as CX}from"elysia";import{omit as SX}from"radash";import NX from"wampy";y();p();class nQ extends WebSocket{protocols;constructor(Q,X){super(Q,X);this.protocols=X}get protocol(){return this.protocols?.[0]??"wamp.2.json"}}var r;((x)=>{let Q=(H)=>{return`wamp.connection.${H}`};x.getConnection=(H)=>{if(!B.exists(Q(H)))console.error(`No WAMP connection with name ${H} found. Please make sure to register the connection before using it.`),process.exit(1);return B.get(Q(H))},x.registerConnection=(H,z)=>{if(B.exists(Q(H)))console.error(`A WAMP connection with name ${H} already exists. Please ensure to register a new connection before overwriting it.`),process.exit(1);let K=new NX(z.url,{ws:nQ,...SX(z,["url"]),onError(){z.onError?.(),N.emit("elysium:error",Error(`An error occurred in WAMP connection ${H}`))}}),O=z.maxRetries??5,L=z.retryInterval??5000,V=0,A=async()=>{try{await K.connect()}catch(C){if(console.error(`Failed to connect to WAMP server (attempt ${V+1}/${O}):`,C),V<O)V++,setTimeout(A,L);else console.error(`Max retry attempts (${O}) reached. Giving up.`),N.emit("elysium:error",Error(`Failed to establish WAMP connection ${H} after ${O} attempts`))}};return A(),B.instance(Q(H),K)},x.connectionExists=(H)=>{return B.exists(Q(H))},x.getDefaultConnection=()=>{return x.getConnection("default")},x.setDefaultConnection=(H)=>{let z=Q("default");return B.remove(z),B.instance(z,x.getConnection(H))},x.controller=(H)=>{return function(z){async function K(){console.log(`Registering Wamp controller for connection ${H.connection} using ${z.name}`),await n();let O=B.make(z),L=Reflect.getMetadata(P.wamp,z)??{},V=r.getConnection(H.connection??"default"),A=new CX;return A.onStart(async(C)=>{let R=L.registrations??[],J=L.subscriptions??[];for(let W of R)V.register(W.topic,W.handler.bind(O),W.options).then((T)=>{console.log(`Registered ${W.topic} with id ${T.registrationId}`)});for(let W of J)V.subscribe(W.topic,W.handler.bind(O),W.options).then((T)=>{console.log(`Subscribed ${W.topic} with id ${T.subscriptionId}`)})}),A}Reflect.defineMetadata(P.elysiaPlugin,K,z)}},x.register=(H,z)=>{return function(K,O,L){let V=Reflect.getMetadata(P.wamp,K.constructor)??{};V.registrations??=[],V.registrations.push({topic:H,options:z,handler:L.value}),Reflect.defineMetadata(P.wamp,V,K.constructor)}},x.subscribe=(H,z)=>{return function(K,O,L){let V=Reflect.getMetadata(P.wamp,K.constructor)??{};V.subscriptions??=[],V.subscriptions.push({topic:H,options:z,handler:L.value}),Reflect.defineMetadata(P.wamp,V,K.constructor)}}})(r||={});class f extends q{#Q;#X;_appContextStorage=new hX;static get instance(){return B.get("elysium.app")}static get context(){return f.instance._appContextStorage}static register(Q={}){return function(X){let $,Y=Object.getPrototypeOf(X);while(Y&&Y!==Object.prototype){let G=Reflect.getMetadata(P.app,Y);if(G){$=G;break}Y=Object.getPrototypeOf(Y)}if($)Q=s($,Q);let Z=Reflect.getMetadata(P.app,X);if(Z)Q=s(Z,Q);Q=s({modules:[],swagger:!1},Q),Reflect.defineMetadata(P.app,Q,X)}}constructor(){super();let{env:Q,debug:X}=Reflect.getMetadata(P.app,this.constructor)??{};if(this.#X=X??!1,Q){let G=HQ.Convert(Q,HQ.Clone(Bun.env));if(this.#X&&!HQ.Check(Q,G)){let U=HQ.Errors(Q,G).First();this.trace(U,"Invalid environment configuration")}AQ(HQ.Clean(Q,G))}else AQ(Bun.env);B.instance("elysium.app",this);let{database:$,redis:Y,wamp:Z}=Reflect.getMetadata(P.app,this.constructor);if(Y){for(let G in Y.connections)o.registerConnection(G,Y.connections[G]);if(o.connectionExists(Y.default))o.setDefaultConnection(Y.default)}if($){for(let G in $.connections)h.registerConnection(G,$.connections[G]);if(h.connectionExists($.default))h.setDefaultConnection($.default)}if(Z){for(let G in Z.connections)r.registerConnection(G,Z.connections[G]);if(r.connectionExists(Z.default))r.setDefaultConnection(Z.default)}this.run().then(()=>N.emit("elysium:app:launched",this,this)).catch((G)=>{N.emit("elysium:error",G),this.trace(G,"An error occurred while launching the application"),process.exit(1)})}get elysia(){return this.#Q}get isDebug(){return this.#X}set isDebug(Q){this.#X=Q}async onError(Q){return!0}async onStart(Q){}async onStop(Q){}async run(){let Q=process.argv.slice(2),X=Q[0];if(!X)this.commandDescribe();else switch(X){case"serve":return this.commandServe();case"work":return this.commandWork(Q.slice(1));case"help":{let $=Q[1];if($){let Z=this.getCommands().find((G)=>G.command===$);if(Z){let G=B.make(Z);return this.write(await G.help()),process.exit(0)}console.error(`Command <${$}> 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.slice(1);return this.commandExec(X,$)}}return process.exit(0)}getConfig(Q){return Reflect.getMetadata(P.app,this.constructor)?.[Q]??null}async commandExec(Q,X){let Y=this.getCommands().find((Z)=>Z.command===Q);if(!Y)return console.error(`Command ${Q} not found`),this.commandList(),process.exit(1);try{let Z=B.make(Y);if(await Z.init(...X))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)}}getCommands(){return B.keys("elysium.command.*").map(($)=>B.get($)).filter(($)=>$!==null).filter(($)=>Bun.env.NODE_ENV==="production"?!$.dev:!0)}async commandWork(Q){this.info("Starting worker process...");let{values:X}=bX({args:Q,options:{queue:{type:"string",multiple:!0,default:["default"],short:"q"},concurrency:{type:"string",default:"1",short:"c"},["max-retries"]:{type:"string",default:"5",short:"r"},["retry-delay"]:{type:"string",default:"5000",short:"d"},["pause-on-error"]:{type:"boolean",default:!1,short:"p"}}}),{Worker:$}=await Promise.resolve().then(() => (IQ(),tQ)),Y=X.queue.map((G)=>G.split(",")).reduce((G,U)=>G.concat(U),[]),Z=$.spawn(self,Y,{concurrency:parseInt(X.concurrency,10),maxRetries:parseInt(X["max-retries"],10),retryDelay:parseInt(X["retry-delay"],10),pauseOnError:X["pause-on-error"]});this.success(`Worker process ${this.format(Z.id,2)} started with queues: ${Y.map((G)=>this.format(G,6)).join(", ")}`)}async commandServe(){let{server:Q,modules:X,swagger:$,plugins:Y}=Reflect.getMetadata(P.app,this.constructor);if(this.#Q=new yX(Q).onRequest((G)=>{if(this.isDebug)console.log(G.request.method,G.request.url)}),N.emit("elysium:server:before-init",this,this),this.#Q.resolve({as:"global"},({request:G})=>({tenant:G.headers.get("x-tenant-id")??"public"})),$)this.#Q.use(vX($));if(Y&&Y.length>0){this.debug("Registering plugins...");for(let G of Y)this.#Q.use(await G(this))}this.#Q.onError({as:"global"},async(G)=>{if(await this.onError(G)){N.emit("elysium:error",G),this.trace({name:"HttpError",message:"Unexpected error while handling HTTP request",stack:G.error.stack,...G.error});let U={};if(typeof G.code==="number")return G.error.response;else switch(G.code){case"VALIDATION":{U={scope:G.error.type,code:G.error.message};break}case"INTERNAL_SERVER_ERROR":{U={message:G.error.message};break}}return{type:G.code,data:U}}}).onStart(async(G)=>{await this.onStart(G),N.emit("elysium:server:start",G,this)}).onStop(async(G)=>{await this.onStop(G),N.emit("elysium:server:stop",G,this),this._appContextStorage.disable()});let Z=Reflect.getMetadata(P.middlewares,this.constructor)??[];YQ(Z,this.#Q);for(let G of X){let U=Reflect.getMetadata(P.elysiaPlugin,G);if(U===void 0)return console.error(`Invalid module class ${G.name} registered in app ${this.constructor.name}. Ensure that you used the @module() decorator on the module.`),process.exit(1);let _=B.bind(G);await _.beforeRegister(),this.#Q.use(await U(_)),await _.afterRegister()}N.emit("elysium:server:after-init",this,this),this.#Q.listen(Q?.port??(parseInt(process.env.PORT,10)||3000)),process.on("SIGINT",()=>{this.#Q.stop().then(()=>process.exit(0))})}commandDescribe(){this.section(`${this.bold("Usage:")} ${this.format("styx",5)} <command> [options]`),this.section(this.bold("Core Commands:")),this.newLine(),this.commandDescription("serve","","Starts the server."),this.commandDescription("help","<command>","Displays help for a command."),this.commandDescription("list","","List all available application commands."),this.section(this.bold("Application Commands:")),this.commandList()}commandList(){let X=this.getCommands().reduce(($,Y)=>{let Z=gX(Y.command.split(":")),G=$.get(Z)??[];return G.push(Y),$.set(Z,G),$},new Map);for(let[$,Y]of X){this.section(this.format($,4));for(let Z of Y)this.commandDescription(Z.command,"",Z.description)}}commandDescription(Q,X,$,Y=q.SPACE_WIDTH){X=X.length===0?" ":` ${X} `,this.write(` ${this.format(Q,6)}${X}${"\u2219".repeat(Y-Q.length-X.length)} ${$}`)}}QQ();y();p();import{isArray as dX,trim as lX}from"radash";var aQ;((G)=>{G.STRING="string";G.NUMBER="number";G.BOOLEAN="boolean";G.ENUM="enum";G.ARRAY="array"})(aQ||={});class eQ extends q{static command="command";static description="Command description";static dev=!1;static register(Q={}){return function(X){let $=X,Z=`elysium.command.${Q.name??$.command}`;if(B.exists(Z))return X;return B.instance(Z,X),X}}static arg(Q={}){return function(X,$){let Y=Reflect.getMetadata(P.arg,X.constructor)??[],Z=Reflect.getMetadata("design:type",X,$),G=Q.type;if(!G&&Z){if(Z===Array){if(G="array",!Q.arrayType)Q={...Q,arrayType:"string"}}else if(Z.constructor!==Object)switch(Z.name.toLowerCase()){case"number":G="number";break;case"boolean":G="boolean";break;case"string":G="string";break;default:G=void 0}else if(Object.values(Z).length>0){if(G="enum",!Q.enum)Q={...Q,enum:Object.values(Z)}}}Y.push({name:Q.name??$,description:Q.description,required:Q.required??!1,default:Q.default,type:G,enum:Q.enum,arrayType:Q.arrayType,propertyKey:$}),Reflect.defineMetadata(P.arg,Y,X.constructor)}}async init(...Q){let X=this.processArgs(Q),$=this.validateArgs(X);if(!$.valid){if($.missing.length>0)console.error(`Missing required arguments: ${$.missing.join(", ")}
9
+ `);return!1}if(Object.keys(X).includes("help"))return!1;let Y=this.getArguments();for(let Z of Y)if(X[Z.name]!==void 0)this[Z.propertyKey]=X[Z.name];return!0}getArguments(){return Reflect.getMetadata(P.arg,this.constructor)||[]}async help(){let Q=`${this.bold("Command:")} ${this.format(this.constructor.command,5)}
10
10
  `;Q+=`${this.bold("Description:")} ${this.constructor.description}
11
11
 
12
12
  `;let X=this.getArguments();if(X.length>0){Q+=`${this.bold("Arguments:")}
13
- `;for(let Y of X){let Z=this.format(Y.required?"(required)":"(optional)",1,9),$=Y.default!==void 0?this.format(`[default: ${Y.default}]`,8,11):"",_="";if(Y.type==="array")_=`<array of ${Y.arrayType||"string"}s>`;else if(Y.type)_=`<${Y.type}>`;let U=Y.enum?` [${Y.enum.join("|")}]`:"";if(Q+=` ${this.format(`--${Y.name}`,6)} ${_}${U} ${Z} ${$}
14
- `,Y.description)Q+=` ${Y.description}
13
+ `;for(let $ of X){let Y=this.format($.required?"(required)":"(optional)",1,9),Z=$.default!==void 0?this.format(`[default: ${$.default}]`,8,11):"",G="";if($.type==="array")G=`<array of ${$.arrayType||"string"}s>`;else if($.type)G=`<${$.type}>`;let U=$.enum?` [${$.enum.join("|")}]`:"";if(Q+=` ${this.format(`--${$.name}`,6)} ${G}${U} ${Y} ${Z}
14
+ `,$.description)Q+=` ${$.description}
15
15
 
16
16
  `}}else Q+=`This command has no arguments.
17
- `;return NX(Q,`
18
- `)}validateArgs(Q){let X=[],Y=[],Z=this.getArguments();if(Object.keys(Q).includes("help"))return{valid:!0,missing:[]};for(let $ of Z){if($.required&&(Q[$.name]===void 0||Q[$.name]===null)){X.push($.name);continue}if(Q[$.name]===void 0)continue;if($.type==="enum"&&$.enum&&!$.enum.includes(Q[$.name]))Y.push(`${$.name} (must be one of: ${$.enum.join(", ")})`);if($.type==="array"&&$.arrayType==="enum"&&$.enum){let _=Q[$.name].filter((U)=>!$.enum.includes(U));if(_.length>0)Y.push(`${$.name} (contains invalid values: ${_.join(", ")}. Must be one of: ${$.enum.join(", ")})`)}}if(Y.length>0)console.error(`Invalid argument values: ${Y.join(", ")}
19
- `);return{valid:X.length===0&&Y.length===0,missing:X}}processArgs(Q){let X={},Y=this.getArguments();for(let Z=0;Z<Q.length;Z++){let $=Q[Z];if($.startsWith("--")){let _=$.slice(2);if(Z+1<Q.length&&!Q[Z+1].startsWith("--"))X[_]=Q[Z+1],Z++;else X[_]=!0}}for(let Z of Y){if(X[Z.name]===void 0&&Z.default!==void 0){X[Z.name]=Z.default;continue}if(X[Z.name]===void 0)continue;if(typeof X[Z.name]==="string")switch(Z.type||this.inferType(Z.default)){case"number":X[Z.name]=Number(X[Z.name]);break;case"boolean":let _=X[Z.name].toLowerCase();X[Z.name]=_==="true"||_==="1"||_==="yes";break;case"enum":if(Z.enum&&Z.enum.length>0&&typeof Z.enum[0]==="number")X[Z.name]=Number(X[Z.name]);break;case"array":let U=X[Z.name].split(",").map((G)=>G.trim());if(Z.arrayType)X[Z.name]=U.map((G)=>{switch(Z.arrayType){case"number":return Number(G);case"boolean":return G.toLowerCase()==="true"||G.toLowerCase()==="1"||G.toLowerCase()==="yes";case"enum":return G;default:return G}});else X[Z.name]=U;break;case"string":default:break}}return X}progress(Q,X="Processing"){return new iQ(Q,X)}spinner(Q="Processing",X,Y){return new mQ(Q,X,Y)}inferType(Q){if(Q===void 0)return"string";switch(typeof Q){case"number":return"number";case"boolean":return"boolean";default:return fX(Q)?"array":"string"}}}class iQ extends k{#Q=!1;#X=0;#Y=0;#Z="";#$=0;constructor(Q=0,X="Processing"){super();this.#X=Q,this.#Z=X,this.#Q=!0,this.#Y=0,this.#$=Date.now(),this.update(0)}update(Q=1,X){if(!this.#Q)return;if(this.#Y+=Q,X)this.#Z=X;let Y=Math.min(100,Math.floor(this.#Y/this.#X*100)),$=(Date.now()-this.#$)/1000,_=0,U=0,G="";if(this.#Y>0)_=$/this.#Y*this.#X,U=Math.max(0,_-$),G=` | ${this.formatTime($)} elapsed | ${this.formatTime(U)} remaining`;let M=30,H=Math.floor(Y/100*M),L=M-H,z="["+"=".repeat(H)+(L>0?">":"")+" ".repeat(Math.max(0,L-(L>0?1:0)))+"]",R=`${this.#Z}: ${z} ${Y}% (${this.#Y}/${this.#X})${G}`;if(this.clearLine(),this.write(R,!1),this.#Y>=this.#X)this.complete()}complete(Q){if(!this.#Q)return;this.#Y=this.#X;let Y=(Date.now()-this.#$)/1000;if(this.clearLine(),Q)this.write(`${Q} (completed in ${this.formatTime(Y)})`);else this.write(`${this.#Z} completed in ${this.formatTime(Y)}`);this.#Q=!1}pause(Q){if(!this.#Q)return;this.newLine(),this.write(Q),this.update(0)}isActive(){return this.#Q}getCurrent(){return this.#Y}getTotal(){return this.#X}getPercentage(){return Math.min(100,Math.floor(this.#Y/this.#X*100))}}class mQ extends k{#Q=!1;#X="";#Y=0;#Z=null;#$=0;#_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];#U=80;constructor(Q="Processing",X,Y){super();if(this.#X=Q,X)this.#_=X;if(Y)this.#U=Y;if(this.#Q)return;this.#Q=!0,this.#Y=Date.now(),this.#$=0,this.#Z=setInterval(()=>{this.render()},this.#U),this.render()}update(Q){if(!this.#Q)return;this.#X=Q}complete(Q,X=!0){if(!this.#Q)return;if(this.#Z)clearInterval(this.#Z),this.#Z=null;let Z=(Date.now()-this.#Y)/1000;this.clearLine();let $=this.formatTime(Z);if(Q)this[X?"success":"error"](`${Q} (${$})`);else this[X?"success":"error"](`${this.#X} completed in ${$}`);this.#Q=!1}fail(Q){this.complete(Q,!1)}pause(Q){if(!this.#Q)return;if(this.#Z)clearInterval(this.#Z),this.#Z=null;this.clearLine(),this.write(Q),this.#Z=setInterval(()=>{this.render()},this.#U)}isActive(){return this.#Q}getElapsedTime(){return(Date.now()-this.#Y)/1000}render(){if(!this.#Q)return;let Q=this.getElapsedTime(),X=this.#_[this.#$];this.#$=(this.#$+1)%this.#_.length,this.clearLine(),this.write(`${X} ${this.#X} (${this.formatTime(Q)})`,!1)}}e();import{Elysia as SX,sse as CX,t as nQ}from"elysia";import{assign as kX,isEmpty as RQ,objectify as qX}from"radash";d();g();var hX=(Q)=>{let X=Reflect.getMetadata("http:body",Q.target,Q.propertyKey),Y=Reflect.getMetadata("http:params",Q.target,Q.propertyKey)??[],Z=Reflect.getMetadata("http:query",Q.target,Q.propertyKey),$=Reflect.getMetadata("http:rawContext",Q.target,Q.propertyKey),_=Reflect.getMetadata("http:customDecorators",Q.target,Q.propertyKey)??[],U=Reflect.getMetadata(O.middlewares,Q.target,Q.propertyKey)??[],G=Reflect.getMetadata(O.services,Q.target,Q.propertyKey)??[],{path:M,method:H,handler:L,target:z,response:R,operationId:P,description:j,transactional:C}=Q,y=Reflect.getMetadata(O.http,z.constructor)??[];y.push({path:M,method:H,body:X,params:Y,query:Z,customDecorators:_,rawContext:$,handler:L,middlewares:U,response:R,operationId:P,description:j,services:G,transactional:C}),Reflect.defineMetadata(O.http,y,z.constructor)},sQ;((Y)=>{Y[Y.SERVER=0]="SERVER";Y[Y.REQUEST=1]="REQUEST"})(sQ||={});var oQ;((D)=>(D.controller=(V={path:"/"})=>{return function(W){async function J(){console.log(`Registering HTTP controller for ${V.path} using ${W.name}`),await n(),V=kX({path:"/",scope:0,tags:[]},V);let I=new SX({prefix:V.path,name:W.name}),c=(()=>{if(V.scope===0)return()=>{let K=B.make(W);return()=>K};else if(V.scope===1)return()=>()=>B.make(W);else throw new Error(`Invalid scope for controller: ${W.name}`)})();I.resolve({as:"local"},()=>({controller:c()}));let ZQ=Reflect.getMetadata("http:onRequest",W)??{};if(ZQ.handler)I.onRequest((K)=>{let a=c()();return ZQ.handler.call(a,K)});let eQ=Reflect.getMetadata(O.middlewares,W)??[];YQ(eQ,I);let QX=Reflect.getMetadata(O.http,W)??[];for(let K of QX){let a=async(A)=>{let F=[];if(K.rawContext)F[K.rawContext.index]=A;if(K.body)F[K.body.index]=A.body;if(K.query)F[K.query.index]=A.query;if(!RQ(K.params))for(let x of K.params)F[x.index]=A.params[x.slug];if(!RQ(K.customDecorators))for(let x of K.customDecorators)F[x.index]=await x.handler(A);if(!RQ(K.services))for(let x of K.services)F[x.index]=B.get(x.name);return F},XX=K.handler.constructor.name.includes("GeneratorFunction"),xQ=K.method==="elysium:SSE",YX=K.transactional??V.transactional??!1,JQ=K.body&&K.body.schema===void 0&&K.body.validator!==void 0;K.method=xQ?"GET":K.method;let ZX=()=>{let A=(F)=>{if(YX)return function(...x){return p.getDefaultConnection().transaction((HQ)=>{return N.context.run(new Map([["tenant",F.tenant],["http:context",F],["db:tx",HQ]]),()=>{try{return K.handler.call(F.controller(),...x)}catch($Q){throw HQ.rollback(),$Q}})})};return function(...x){return N.context.run(new Map([["tenant",F.tenant],["http:context",F]]),()=>K.handler.call(F.controller(),...x))}};if(XX)return async function*(F){let x=A(F),HQ=await a(F);try{for await(let $Q of x(...HQ))yield $Q}catch($Q){yield $Q}};if(xQ)return async function*(F){let x=A(F);F.set.headers["content-type"]="text/event-stream",F.set.headers["cache-control"]="no-cache",F.set.headers.connection="keep-alive";while(!0)yield CX(await x(...await a(F))),await Bun.sleep(10)};if(JQ)return async function(F){if(await K.body.validator.validate(F))return await A(F)(...await a(F));throw F.status(400,"Invalid request body")};return async function(F){return await A(F)(...await a(F))}},wQ=qX(K.params??[],(A)=>A.slug,(A)=>A.schema),LQ=K.middlewares.map((A)=>B.make(A));I.route(K.method,K.path,ZX(),{config:{},async transform(A){if(JQ&&!await K.body.validator.authorize(A))throw A.status(401,"Unauthorized");return u(LQ,A,"onTransform")},beforeHandle(A){return u(LQ,A,"onBeforeHandle")},afterHandle(A){return u(LQ,A,"onAfterHandle")},afterResponse(A){return u(LQ,A,"onAfterResponse")},detail:{tags:V.tags,description:K.description,operationId:K.operationId},body:JQ?K.body?.validator?.schema:K.body?.schema,response:K.response,params:RQ(wQ)?void 0:nQ.Object(wQ)})}return I}Reflect.defineMetadata(O.elysiaPlugin,J,W)}},D.sse=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"elysium:SSE",path:W,...J})},D.get=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"GET",path:W,...J})},D.post=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"POST",path:W,...J})},D.put=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"PUT",path:W,...J})},D.del=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"DELETE",path:W,...J})},D.patch=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"PATCH",path:W,...J})},D.head=(V={})=>{let{path:W="/",...J}=V??{};return D.custom({method:"HEAD",path:W,...J})},D.options=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"OPTIONS",path:W,...J})},D.trace=(V={})=>{let{path:W="/",...J}=V;return D.custom({method:"TRACE",path:W,...J})},D.custom=({path:V="/",...W})=>{return function(J,I,c){process.nextTick(()=>{hX({path:V,handler:c.value,target:J,propertyKey:I,...W})})}},D.onRequest=()=>{return function(V,W,J){let I=Reflect.getMetadata("http:onRequest",V.constructor)??{};I.handler=J.value,Reflect.defineMetadata("http:onRequest",I,V.constructor)}},D.context=()=>{return function(V,W,J){Reflect.defineMetadata("http:rawContext",{index:J},V,W)}},D.param=(V,W)=>{return function(J,I,c){let ZQ=Reflect.getMetadata("http:params",J,I)??[];ZQ.push({slug:V,schema:W??nQ.String(),index:c}),Reflect.defineMetadata("http:params",ZQ,J,I)}},D.query=(V)=>{return function(W,J,I){Reflect.defineMetadata("http:query",{schema:V,index:I},W,J)}},D.body=(V)=>{return function(W,J,I){if(typeof V==="function")Reflect.defineMetadata("http:body",{validator:V,index:I},W,J);else Reflect.defineMetadata("http:body",{schema:V,index:I},W,J)}},D.decorate=(V)=>{return()=>{return function(W,J,I){let c=Reflect.getMetadata("http:customDecorators",W,J)??[];c.push({handler:V,index:I}),Reflect.defineMetadata("http:customDecorators",c,W,J)}}}))(oQ||={});FQ();import{getTableConfig as bX,pgSchema as vX,pgTable as rQ}from"drizzle-orm/pg-core";import{t as S}from"elysia";var IQ=(Q,{mode:X="select"}={})=>{let{columns:Y}=bX(Q);if(Y===void 0)return S.Object({});let Z={};for(let $ of Y){if(["create","update"].includes(X)&&$.primary)continue;if(Z[$.name]=yX($),!$.notNull)Z[$.name]=S.Nullable(Z[$.name]);if(X==="update"||$.hasDefault||!$.notNull)Z[$.name]=S.Optional(Z[$.name])}return S.Object(Z)},yX=(Q)=>{let X=(()=>{switch(Q.dataType){case"string":return S.String({format:Q.columnType==="PgUUID"?"uuid":void 0});case"number":return S.Number();case"boolean":return S.Boolean();case"array":return S.Array(S.Any());case"json":return S.Object({});case"date":case"localDate":case"localDateTime":return S.String({format:Q.dataType==="date"?"date":"date-time"});case"bigint":return S.BigInt();case"buffer":return S.File();default:return S.Never()}})();if(!Q.notNull)X=S.Optional(X);else X=S.Required(X);return X},gX=(Q,X,Y)=>{let Z=rQ(Q,X,Y);class ${static $inferSelect=Z.$inferSelect;static $inferInsert=Z.$inferInsert;static $inferUpdate=Z.$inferInsert;static get table(){if(!N.instance||!N.context.getStore)return Z;if(this.supportTenancy){let _=VQ.getCurrentTenant()??"public";return VQ.wrapTenant(_,this)}return Z}static tableName=Q;static columns=X;static extraConfig=Y;static insertSchema=IQ(Z,{mode:"create"});static updateSchema=IQ(Z,{mode:"update"});static selectSchema=IQ(Z,{mode:"select"});static supportTenancy=!1}return $},TQ=new Map,BQ=new Map,VQ;((i)=>{let Q=(_)=>{return BQ.get(_)??i.registerTenant(_)};i.getCurrentTenant=()=>{return N.context.getStore()?.get("tenant")??null},i.wrapTenant=(_,U)=>{if(_==="public")return rQ(U.tableName,U.columns);let G=`${_}.${U.tableName}`;if(TQ.has(G))return TQ.get(G);let H=Q(_).table(U.tableName,U.columns);return TQ.set(G,H),H},i.registerTenant=(_)=>{if(BQ.has(_))return BQ.get(_);let U=vX(_);return BQ.set(_,U),U},i.withTenant=(_,U)=>{let G=N.context.getStore(),M=new Map(G);return M.set("tenant",_),N.context.run(M,U)}})(VQ||={});import{Elysia as dX}from"elysia";import{assign as lX}from"radash";g();class tQ{static register(Q={}){return function(X){async function Y(Z){console.log(`Registering module ${X.name}`),await n();let $=lX({controllers:[]},Q),_=new dX({name:X.name,prefix:Q.prefix});_.resolve({as:"local"},()=>({module:Z}));let U=Reflect.getMetadata(O.middlewares,X)??[];YQ(U,_);for(let G of $.controllers){let M=Reflect.getMetadata(O.elysiaPlugin,G);if(M===void 0)console.error(`Invalid controller class ${G.name} registered in module ${X.name}. Ensure that you either used the @Http.controller(), the @Websocket.controller(), or the @Wamp.controller() decorators on the class.`),process.exit(1);else _.use(await M())}return _}Reflect.defineMetadata(O.elysiaPlugin,Y,X)}}beforeRegister(){return Promise.resolve()}afterRegister(){return Promise.resolve()}}import{eq as MQ}from"drizzle-orm";var pX=(Q)=>{class X{static Model=Q;static connection="default";get db(){let Y=this.constructor.connection,Z=null;if(Y==="default")Z=N.context.getStore()?.get("db:tx")??null;return Z??p.getConnection(Y)}async all(){return await this.db.select().from(Q.table)}async paginate(Y,Z=1){let $=await this.db.$count(Q.table),_=Math.max(Z-1,0)*Y;return{page:Z,total:$,data:await this.db.select().from(Q.table).offset(_).limit(Y)}}async find(Y){let[Z]=await this.db.select().from(Q.table).where(MQ(Q.table.id,Y));return Z??null}async findBy(Y,Z){let[$]=await this.db.select().from(Q.table).where(MQ(Q.table[Y],Z));return $??null}async insert(Y){let[Z]=await this.db.insert(Q.table).values(Y).returning();return Z}async update(Y,Z){let[$]=await this.db.update(Q.table).set(Z).where(MQ(Q.table.id,Y)).returning();return $}async updateAll(Y){return await this.db.update(Q.table).set(Y).returning()}async delete(Y){let[Z]=await this.db.delete(Q.table).where(MQ(Q.table.id,Y)).returning();return Z}async deleteAll(){return await this.db.delete(Q.table).returning()}}return X};d();import{Elysia as uX}from"elysia";d();g();var aQ;((v)=>(v.controller=(U)=>{return function(G){async function M(){console.log(`Registering Websocket route for ${U.path} using ${G.name}`),await n();let H=B.make(G),L=Reflect.getMetadata(O.websocket,G)??{},z=L.open?.bind(H),R=L.close?.bind(H),P=L.message?.bind(H),j=L.drain?.bind(H),C=L.error?.bind(H)??((V)=>w.emit("elysium:error",V.error)),y=new uX;return y.ws(U.path,{open:z,close:R,message:P,drain:j,error:C,body:L.body,...U.options}),y}Reflect.defineMetadata(O.elysiaPlugin,M,G)}},v.onOpen=()=>{return function(U,G,M){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.open=M.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onClose=()=>{return function(U,G,M){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.close=M.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onMessage=(U)=>{return function(G,M,H){let L=Reflect.getMetadata(O.websocket,G.constructor)??{};L.message=H.value,L.body=U,Reflect.defineMetadata(O.websocket,L,G.constructor)}},v.onDrain=()=>{return function(U,G,M){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.drain=M.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onError=()=>{return function(U,G,M){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.error=M.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}}))(aQ||={});EQ();export{vZ as t,zQ as WorkerPool,AQ as Worker,aQ as Websocket,t as Wamp,VQ as Tenancy,NQ as ServiceScope,B as Service,pX as Repository,r as Redis,tQ as Module,gX as Model,yQ as Middleware,dQ as Job,k as InteractsWithConsole,sQ as HttpControllerScope,oQ as Http,w as Event,vQ as Env,p as Database,OQ as ConsoleFormat,uQ as CommandArgumentType,cQ as Command,l as Cache,N as Application};
17
+ `;return lX(Q,`
18
+ `)}validateArgs(Q){let X=[],$=[],Y=this.getArguments();if(Object.keys(Q).includes("help"))return{valid:!0,missing:[]};for(let Z of Y){if(Z.required&&(Q[Z.name]===void 0||Q[Z.name]===null)){X.push(Z.name);continue}if(Q[Z.name]===void 0)continue;if(Z.type==="enum"&&Z.enum&&!Z.enum.includes(Q[Z.name]))$.push(`${Z.name} (must be one of: ${Z.enum.join(", ")})`);if(Z.type==="array"&&Z.arrayType==="enum"&&Z.enum){let G=Q[Z.name].filter((U)=>!Z.enum.includes(U));if(G.length>0)$.push(`${Z.name} (contains invalid values: ${G.join(", ")}. Must be one of: ${Z.enum.join(", ")})`)}}if($.length>0)console.error(`Invalid argument values: ${$.join(", ")}
19
+ `);return{valid:X.length===0&&$.length===0,missing:X}}processArgs(Q){let X={},$=this.getArguments();for(let Y=0;Y<Q.length;Y++){let Z=Q[Y];if(Z.startsWith("--")){let G=Z.slice(2);if(Y+1<Q.length&&!Q[Y+1].startsWith("--"))X[G]=Q[Y+1],Y++;else X[G]=!0}}for(let Y of $){if(X[Y.name]===void 0&&Y.default!==void 0){X[Y.name]=Y.default;continue}if(X[Y.name]===void 0)continue;if(typeof X[Y.name]==="string")switch(Y.type||this.inferType(Y.default)){case"number":X[Y.name]=Number(X[Y.name]);break;case"boolean":let G=X[Y.name].toLowerCase();X[Y.name]=G==="true"||G==="1"||G==="yes";break;case"enum":if(Y.enum&&Y.enum.length>0&&typeof Y.enum[0]==="number")X[Y.name]=Number(X[Y.name]);break;case"array":let U=X[Y.name].split(",").map((_)=>_.trim());if(Y.arrayType)X[Y.name]=U.map((_)=>{switch(Y.arrayType){case"number":return Number(_);case"boolean":return _.toLowerCase()==="true"||_.toLowerCase()==="1"||_.toLowerCase()==="yes";case"enum":return _;default:return _}});else X[Y.name]=U;break;case"string":default:break}}return X}progress(Q,X="Processing"){return new QX(Q,X)}spinner(Q="Processing",X,$){return new XX(Q,X,$)}inferType(Q){if(Q===void 0)return"string";switch(typeof Q){case"number":return"number";case"boolean":return"boolean";default:return dX(Q)?"array":"string"}}}class QX extends q{#Q=!1;#X=0;#$=0;#Y="";#Z=0;constructor(Q=0,X="Processing"){super();this.#X=Q,this.#Y=X,this.#Q=!0,this.#$=0,this.#Z=Date.now(),this.update(0)}update(Q=1,X){if(!this.#Q)return;if(this.#$+=Q,X)this.#Y=X;let $=Math.min(100,Math.floor(this.#$/this.#X*100)),Z=(Date.now()-this.#Z)/1000,G=0,U=0,_="";if(this.#$>0)G=Z/this.#$*this.#X,U=Math.max(0,G-Z),_=` | ${this.formatTime(Z)} elapsed | ${this.formatTime(U)} remaining`;let M=30,H=Math.floor($/100*M),z=M-H,K="["+"=".repeat(H)+(z>0?">":"")+" ".repeat(Math.max(0,z-(z>0?1:0)))+"]",O=`${this.#Y}: ${K} ${$}% (${this.#$}/${this.#X})${_}`;if(this.clearLine(),this.write(O,!1),this.#$>=this.#X)this.complete()}complete(Q){if(!this.#Q)return;this.#$=this.#X;let $=(Date.now()-this.#Z)/1000;if(this.clearLine(),Q)this.write(`${Q} (completed in ${this.formatTime($)})`);else this.write(`${this.#Y} completed in ${this.formatTime($)}`);this.#Q=!1}pause(Q){if(!this.#Q)return;this.newLine(),this.write(Q),this.update(0)}isActive(){return this.#Q}getCurrent(){return this.#$}getTotal(){return this.#X}getPercentage(){return Math.min(100,Math.floor(this.#$/this.#X*100))}}class XX extends q{#Q=!1;#X="";#$=0;#Y=null;#Z=0;#G=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];#U=80;constructor(Q="Processing",X,$){super();if(this.#X=Q,X)this.#G=X;if($)this.#U=$;if(this.#Q)return;this.#Q=!0,this.#$=Date.now(),this.#Z=0,this.#Y=setInterval(()=>{this.render()},this.#U),this.render()}update(Q){if(!this.#Q)return;this.#X=Q}complete(Q,X=!0){if(!this.#Q)return;if(this.#Y)clearInterval(this.#Y),this.#Y=null;let Y=(Date.now()-this.#$)/1000;this.clearLine();let Z=this.formatTime(Y);if(Q)this[X?"success":"error"](`${Q} (${Z})`);else this[X?"success":"error"](`${this.#X} completed in ${Z}`);this.#Q=!1}fail(Q){this.complete(Q,!1)}pause(Q){if(!this.#Q)return;if(this.#Y)clearInterval(this.#Y),this.#Y=null;this.clearLine(),this.write(Q),this.#Y=setInterval(()=>{this.render()},this.#U)}isActive(){return this.#Q}getElapsedTime(){return(Date.now()-this.#$)/1000}render(){if(!this.#Q)return;let Q=this.getElapsedTime(),X=this.#G[this.#Z];this.#Z=(this.#Z+1)%this.#G.length,this.clearLine(),this.write(`${X} ${this.#X} (${this.formatTime(Q)})`,!1)}}QQ();class TQ{context;constructor(Q={}){this.context=Q}trace(Q,X){console.debug(`[TRACE] ${Q}`,{...this.context,...X})}debug(Q,X){console.debug(`[DEBUG] ${Q}`,{...this.context,...X})}info(Q,X){console.info(`[INFO] ${Q}`,{...this.context,...X})}warn(Q,X){console.warn(`[WARN] ${Q}`,{...this.context,...X})}error(Q,X){console.error(`[ERROR] ${Q}`,{...this.context,...X})}fatal(Q,X){console.error(`[FATAL] ${Q}`,{...this.context,...X})}child(Q){return new TQ({...this.context,...Q})}}import{Elysia as pX,sse as uX,t as $X}from"elysia";import{assign as mX,isEmpty as WQ,objectify as iX}from"radash";y();p();var cX=(Q)=>{let X=Reflect.getMetadata("http:body",Q.target,Q.propertyKey),$=Reflect.getMetadata("http:params",Q.target,Q.propertyKey)??[],Y=Reflect.getMetadata("http:query",Q.target,Q.propertyKey),Z=Reflect.getMetadata("http:rawContext",Q.target,Q.propertyKey),G=Reflect.getMetadata("http:customDecorators",Q.target,Q.propertyKey)??[],U=Reflect.getMetadata(P.middlewares,Q.target,Q.propertyKey)??[],_=Reflect.getMetadata(P.services,Q.target,Q.propertyKey)??[],{path:M,method:H,handler:z,target:K,response:O,operationId:L,description:V,transactional:A}=Q,C=Reflect.getMetadata(P.http,K.constructor)??[];C.push({path:M,method:H,body:X,params:$,query:Y,customDecorators:G,rawContext:Z,handler:z,middlewares:U,response:O,operationId:L,description:V,services:_,transactional:A}),Reflect.defineMetadata(P.http,C,K.constructor)},YX;(($)=>{$[$.SERVER=0]="SERVER";$[$.REQUEST=1]="REQUEST"})(YX||={});var ZX;((D)=>(D.controller=(R={path:"/"})=>{return function(J){async function W(){console.log(`Registering HTTP controller for ${R.path} using ${J.name}`),await n(),R=mX({path:"/",scope:0,tags:[]},R);let T=new pX({prefix:R.path,name:J.name}),i=(()=>{if(R.scope===0)return()=>{let j=B.make(J);return()=>j};else if(R.scope===1)return()=>()=>B.make(J);else throw Error(`Invalid scope for controller: ${J.name}`)})();T.resolve({as:"local"},()=>({controller:i()}));let GQ=Reflect.getMetadata("http:onRequest",J)??{};if(GQ.handler)T.onRequest((j)=>{let e=i()();return GQ.handler.call(e,j)});let PX=Reflect.getMetadata(P.middlewares,J)??[];YQ(PX,T);let zX=Reflect.getMetadata(P.http,J)??[];for(let j of zX){let e=async(I)=>{let F=[];if(j.rawContext)F[j.rawContext.index]=I;if(j.body)F[j.body.index]=I.body;if(j.query)F[j.query.index]=I.query;if(!WQ(j.params))for(let S of j.params)F[S.index]=I.params[S.slug];if(!WQ(j.customDecorators))for(let S of j.customDecorators)F[S.index]=await S.handler(I);if(!WQ(j.services))for(let S of j.services)F[S.index]=B.get(S.name);return F},BX=j.handler.constructor.name.includes("GeneratorFunction"),kQ=j.method==="elysium:SSE",VX=j.transactional??R.transactional??!1,MQ=j.body&&j.body.schema===void 0&&j.body.validator!==void 0;j.method=kQ?"GET":j.method;let RX=()=>{let I=(F)=>{if(VX)return function(...S){return h.getDefaultConnection().transaction((BQ)=>{return f.context.run(new Map([["tenant",F.tenant],["http:context",F],["db:tx",BQ]]),()=>{try{return j.handler.call(F.controller(),...S)}catch(UQ){throw BQ.rollback(),UQ}})})};return function(...S){return f.context.run(new Map([["tenant",F.tenant],["http:context",F]]),()=>j.handler.call(F.controller(),...S))}};if(BX)return async function*(F){let S=I(F),BQ=await e(F);try{for await(let UQ of S(...BQ))yield UQ}catch(UQ){yield UQ}};if(kQ)return async function*(F){let S=I(F);F.set.headers["content-type"]="text/event-stream",F.set.headers["cache-control"]="no-cache",F.set.headers.connection="keep-alive";while(!0)yield uX(await S(...await e(F))),await Bun.sleep(10)};if(MQ)return async function(F){if(await j.body.validator.validate(F))return await I(F)(...await e(F));throw F.status(400,"Invalid request body")};return async function(F){return await I(F)(...await e(F))}},qQ=iX(j.params??[],(I)=>I.slug,(I)=>I.schema),zQ=j.middlewares.map((I)=>B.make(I));T.route(j.method,j.path,RX(),{config:{},async transform(I){if(MQ&&!await j.body.validator.authorize(I))throw I.status(401,"Unauthorized");return m(zQ,I,"onTransform")},beforeHandle(I){return m(zQ,I,"onBeforeHandle")},afterHandle(I){return m(zQ,I,"onAfterHandle")},afterResponse(I){return m(zQ,I,"onAfterResponse")},detail:{tags:R.tags,description:j.description,operationId:j.operationId},body:MQ?j.body?.validator?.schema:j.body?.schema,response:j.response,params:WQ(qQ)?void 0:$X.Object(qQ)})}return T}Reflect.defineMetadata(P.elysiaPlugin,W,J)}},D.sse=(R={})=>{let{path:J="/",...W}=R;return D.custom({method:"elysium:SSE",path:J,...W})},D.get=(R={})=>{let{path:J="/",...W}=R;return D.custom({method:"GET",path:J,...W})},D.post=(R={})=>{let{path:J="/",...W}=R;return D.custom({method:"POST",path:J,...W})},D.put=(R={})=>{let{path:J="/",...W}=R;return D.custom({method:"PUT",path:J,...W})},D.del=(R={})=>{let{path:J="/",...W}=R;return D.custom({method:"DELETE",path:J,...W})},D.patch=(R={})=>{let{path:J="/",...W}=R;return D.custom({method:"PATCH",path:J,...W})},D.head=(R={})=>{let{path:J="/",...W}=R??{};return D.custom({method:"HEAD",path:J,...W})},D.options=(R={})=>{let{path:J="/",...W}=R;return D.custom({method:"OPTIONS",path:J,...W})},D.trace=(R={})=>{let{path:J="/",...W}=R;return D.custom({method:"TRACE",path:J,...W})},D.custom=({path:R="/",...J})=>{return function(W,T,i){process.nextTick(()=>{cX({path:R,handler:i.value,target:W,propertyKey:T,...J})})}},D.onRequest=()=>{return function(R,J,W){let T=Reflect.getMetadata("http:onRequest",R.constructor)??{};T.handler=W.value,Reflect.defineMetadata("http:onRequest",T,R.constructor)}},D.context=()=>{return function(R,J,W){Reflect.defineMetadata("http:rawContext",{index:W},R,J)}},D.param=(R,J)=>{return function(W,T,i){let GQ=Reflect.getMetadata("http:params",W,T)??[];GQ.push({slug:R,schema:J??$X.String(),index:i}),Reflect.defineMetadata("http:params",GQ,W,T)}},D.query=(R)=>{return function(J,W,T){Reflect.defineMetadata("http:query",{schema:R,index:T},J,W)}},D.body=(R)=>{return function(J,W,T){if(typeof R==="function")Reflect.defineMetadata("http:body",{validator:R,index:T},J,W);else Reflect.defineMetadata("http:body",{schema:R,index:T},J,W)}},D.decorate=(R)=>{return()=>{return function(J,W,T){let i=Reflect.getMetadata("http:customDecorators",J,W)??[];i.push({handler:R,index:T}),Reflect.defineMetadata("http:customDecorators",i,J,W)}}}))(ZX||={});oQ();class GX extends ZQ{async onRequest(Q){Q.__requestStartTime=Date.now(),this.logger.info("Incoming request",{method:Q.request.method,path:new URL(Q.request.url).pathname})}async onAfterResponse(Q){let X=Date.now()-(Q.__requestStartTime??0);this.logger.info("Request completed",{method:Q.request.method,path:new URL(Q.request.url).pathname,duration:`${X}ms`})}}import{getTableConfig as Y0,pgTable as Z0}from"drizzle-orm/pg-core";import{t as k}from"elysia";var LX={};hQ(LX,{wrapTenantSchema:()=>CQ,withTenant:()=>aX,withRLS:()=>eX,setConnectionTenant:()=>Q0,registerTenantSchema:()=>_X,getTenantSchema:()=>UX,getSessionTenant:()=>X0,getCurrentTenant:()=>fQ,getConfig:()=>tX,createRLSPolicy:()=>$0,configure:()=>rX,TenantMiddleware:()=>OQ,StrictTenantMiddleware:()=>NQ,SimpleTenantMiddleware:()=>SQ});import{sql as t}from"drizzle-orm";import{pgPolicy as nX,pgSchema as sX,pgTable as oX}from"drizzle-orm/pg-core";var a={mode:"schema"},wQ=new Map,DQ=new Map,rX=(Q)=>{a=Q},tX=()=>a,fQ=()=>{if(!f.instance||!f.context.getStore)return null;return f.context.getStore()?.get("tenant")??null},aX=(Q,X)=>{let $=f.context.getStore(),Y=new Map($);return Y.set("tenant",Q),f.context.run(Y,X)},UX=(Q)=>{return DQ.get(Q)??_X(Q)},_X=(Q)=>{if(DQ.has(Q))return DQ.get(Q);let X=sX(Q);return DQ.set(Q,X),X},CQ=(Q,X,$)=>{if(Q==="public")return oX(X,$);let Y=`${Q}.${X}`;if(wQ.has(Y))return wQ.get(Y);let G=UX(Q).table(X,$);return wQ.set(Y,G),G},eX=async(Q,X,$="default")=>{let Y=h.getConnection($),Z=a.rls?.sessionVariable??"app.current_tenant",G=Q??"public";return Y.transaction(async(U)=>{return await U.execute(t`SELECT set_config(${Z}, ${G}, true)`),X(U)})},Q0=async(Q,X="default")=>{let $=h.getConnection(X),Y=a.rls?.sessionVariable??"app.current_tenant",Z=Q??"public";await $.execute(t`SELECT set_config(${Y}, ${Z}, false)`)},X0=async(Q="default")=>{let X=h.getConnection(Q),$=a.rls?.sessionVariable??"app.current_tenant";return(await X.execute(t`SELECT current_setting(${$}, true) as tenant`))?.rows?.[0]?.tenant??null},$0=(Q,X,$)=>{let Y=a.rls?.sessionVariable??"app.current_tenant",Z=X??a.rls?.defaultColumn??"tenant_id",G=$??`${Q}_tenant_isolation`;return nX(G,{for:"all",to:"public",using:t`${t.identifier(Z)} = current_setting(${Y}, true)::text`,withCheck:t`${t.identifier(Z)} = current_setting(${Y}, true)::text`})};class OQ extends ZQ{header="x-tenant-id";allowPublic=!0;connectionName="default";async validateTenant(Q){return!0}async onTenantResolved(Q,X){}onTenantError(Q,X){if(Q==="missing")throw Error("Tenant ID required");else throw Error("Invalid tenant")}async onRequest(Q){let X=Q.request.headers.get(this.header);if(!X||X==="public"){if(this.allowPublic){Q.tenant="public";return}return this.onTenantError("missing",Q)}if(!await this.validateTenant(X))return this.onTenantError("invalid",Q);Q.tenant=X,await this.onTenantResolved(X,Q)}}class SQ extends OQ{}class NQ extends OQ{allowPublic=!1}var xQ=(Q,{mode:X="select"}={})=>{let{columns:$}=Y0(Q);if($===void 0)return k.Object({});let Y={};for(let Z of $){if(["create","update"].includes(X)&&Z.primary)continue;if(Y[Z.name]=G0(Z),!Z.notNull)Y[Z.name]=k.Nullable(Y[Z.name]);if(X==="update"||Z.hasDefault||!Z.notNull)Y[Z.name]=k.Optional(Y[Z.name])}return k.Object(Y)},G0=(Q)=>{let X=(()=>{switch(Q.dataType){case"string":return k.String({format:Q.columnType==="PgUUID"?"uuid":void 0});case"number":return k.Number();case"boolean":return k.Boolean();case"array":return k.Array(k.Any());case"json":return k.Object({});case"date":case"localDate":case"localDateTime":return k.Transform(k.String({format:Q.dataType==="date"?"date":"date-time"})).Decode(($)=>new Date($)).Encode(($)=>$.toISOString());case"bigint":return k.BigInt();case"buffer":return k.File();default:return k.Never()}})();if(!Q.notNull)X=k.Optional(X);else X=k.Required(X);return X},U0=(Q,X,$)=>{let Y=Z0(Q,X,$);class Z{static $inferSelect=Y.$inferSelect;static $inferInsert=Y.$inferInsert;static $inferUpdate=Y.$inferInsert;static get table(){if(!f.instance||!f.context.getStore)return Y;if(this.supportTenancy){let G=fQ()??"public";return CQ(G,this.tableName,this.columns)}return Y}static tableName=Q;static columns=X;static extraConfig=$;static insertSchema=xQ(Y,{mode:"create"});static updateSchema=xQ(Y,{mode:"update"});static selectSchema=xQ(Y,{mode:"select"});static supportTenancy=!1}return Z};import{Elysia as _0}from"elysia";import{assign as L0}from"radash";p();class HX{static register(Q={}){return function(X){async function $(Y){console.log(`Registering module ${X.name}`),await n();let Z=L0({controllers:[]},Q),G=new _0({name:X.name,prefix:Q.prefix});G.resolve({as:"local"},()=>({module:Y}));let U=Reflect.getMetadata(P.middlewares,X)??[];YQ(U,G);for(let _ of Z.controllers){let M=Reflect.getMetadata(P.elysiaPlugin,_);if(M===void 0)console.error(`Invalid controller class ${_.name} registered in module ${X.name}. Ensure that you either used the @Http.controller(), the @Websocket.controller(), or the @Wamp.controller() decorators on the class.`),process.exit(1);else G.use(await M())}return G}Reflect.defineMetadata(P.elysiaPlugin,$,X)}}beforeRegister(){return Promise.resolve()}afterRegister(){return Promise.resolve()}}import{eq as PQ}from"drizzle-orm";var H0=(Q)=>{class X{static Model=Q;static connection="default";get db(){let $=this.constructor.connection,Y=null;if($==="default")Y=f.context.getStore()?.get("db:tx")??null;return Y??h.getConnection($)}async all(){return await this.db.select().from(Q.table)}async paginate($,Y=1){let Z=await this.db.$count(Q.table),G=Math.max(Y-1,0)*$;return{page:Y,total:Z,data:await this.db.select().from(Q.table).offset(G).limit($)}}async find($){let[Y]=await this.db.select().from(Q.table).where(PQ(Q.table.id,$));return Y??null}async findBy($,Y){let[Z]=await this.db.select().from(Q.table).where(PQ(Q.table[$],Y));return Z??null}async insert($){let[Y]=await this.db.insert(Q.table).values($).returning();return Y}async update($,Y){let[Z]=await this.db.update(Q.table).set(Y).where(PQ(Q.table.id,$)).returning();return Z}async updateAll($){return await this.db.update(Q.table).set($).returning()}async delete($){let[Y]=await this.db.delete(Q.table).where(PQ(Q.table.id,$)).returning();return Y}async deleteAll(){return await this.db.delete(Q.table).returning()}async exists($){return await this.db.$count(Q.table,PQ(Q.table.id,$))>0}}return X};y();import{Elysia as O0}from"elysia";y();p();var OX;((l)=>(l.controller=(U)=>{return function(_){async function M(){console.log(`Registering Websocket route for ${U.path} using ${_.name}`),await n();let H=B.make(_),z=Reflect.getMetadata(P.websocket,_)??{},K=z.open?.bind(H),O=z.close?.bind(H),L=z.message?.bind(H),V=z.drain?.bind(H),A=z.error?.bind(H)??((R)=>N.emit("elysium:error",R.error)),C=new O0;return C.ws(U.path,{open:K,close:O,message:L,drain:V,error:A,body:z.body,...U.options}),C}Reflect.defineMetadata(P.elysiaPlugin,M,_)}},l.onOpen=()=>{return function(U,_,M){let H=Reflect.getMetadata(P.websocket,U.constructor)??{};H.open=M.value,Reflect.defineMetadata(P.websocket,H,U.constructor)}},l.onClose=()=>{return function(U,_,M){let H=Reflect.getMetadata(P.websocket,U.constructor)??{};H.close=M.value,Reflect.defineMetadata(P.websocket,H,U.constructor)}},l.onMessage=(U)=>{return function(_,M,H){let z=Reflect.getMetadata(P.websocket,_.constructor)??{};z.message=H.value,z.body=U,Reflect.defineMetadata(P.websocket,z,_.constructor)}},l.onDrain=()=>{return function(U,_,M){let H=Reflect.getMetadata(P.websocket,U.constructor)??{};H.drain=M.value,Reflect.defineMetadata(P.websocket,H,U.constructor)}},l.onError=()=>{return function(U,_,M){let H=Reflect.getMetadata(P.websocket,U.constructor)??{};H.error=M.value,Reflect.defineMetadata(P.websocket,H,U.constructor)}}))(OX||={});IQ();export{P2 as t,JQ as WorkerPool,EQ as Worker,OX as Websocket,r as Wamp,OQ as TenantMiddleware,LX as Tenancy,NQ as StrictTenantMiddleware,SQ as SimpleTenantMiddleware,yQ as ServiceScope,B as Service,GX as RequestLoggerMiddleware,H0 as Repository,o as Redis,HX as Module,U0 as Model,ZQ as Middleware,sQ as Job,q as InteractsWithConsole,YX as HttpControllerScope,ZX as Http,N as Event,cQ as Env,h as Database,TQ as ConsoleLogger,VQ as ConsoleFormat,aQ as CommandArgumentType,eQ as Command,u as Cache,f as Application};
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Interface for structured application logging.
3
+ *
4
+ * This is distinct from `InteractsWithConsole` (Styx):
5
+ * - `LoggerInterface`: structured application logging (machine-parseable, sent to transports)
6
+ * - `InteractsWithConsole`: CLI user output (colors, spinners, formatted for humans)
7
+ *
8
+ * @author Axel Nana <axel.nana@workbud.com>
9
+ */
10
+ export interface LoggerInterface {
11
+ trace(msg: string, ctx?: Record<string, unknown>): void;
12
+ debug(msg: string, ctx?: Record<string, unknown>): void;
13
+ info(msg: string, ctx?: Record<string, unknown>): void;
14
+ warn(msg: string, ctx?: Record<string, unknown>): void;
15
+ error(msg: string, ctx?: Record<string, unknown>): void;
16
+ fatal(msg: string, ctx?: Record<string, unknown>): void;
17
+ child(ctx: Record<string, unknown>): LoggerInterface;
18
+ }
19
+ /**
20
+ * Default logger implementation using console.* APIs.
21
+ * Used as fallback when @elysiumjs/hermes is not installed.
22
+ *
23
+ * @author Axel Nana <axel.nana@workbud.com>
24
+ */
25
+ export declare class ConsoleLogger implements LoggerInterface {
26
+ private context;
27
+ constructor(context?: Record<string, unknown>);
28
+ trace(msg: string, ctx?: Record<string, unknown>): void;
29
+ debug(msg: string, ctx?: Record<string, unknown>): void;
30
+ info(msg: string, ctx?: Record<string, unknown>): void;
31
+ warn(msg: string, ctx?: Record<string, unknown>): void;
32
+ error(msg: string, ctx?: Record<string, unknown>): void;
33
+ fatal(msg: string, ctx?: Record<string, unknown>): void;
34
+ child(ctx: Record<string, unknown>): LoggerInterface;
35
+ }
@@ -1,6 +1,7 @@
1
1
  import type { AnyElysia } from 'elysia';
2
2
  import type { Class } from 'type-fest';
3
3
  import type { Context } from './http';
4
+ import type { LoggerInterface } from './logger';
4
5
  /**
5
6
  * Execute a chain of middlewares, stopping on the first return or throw.
6
7
  * @author Axel Nana <axel.nana@workbud.com>
@@ -35,6 +36,12 @@ export declare abstract class Middleware<TGuards extends string[] = []> {
35
36
  * @returns A middleware class decorated with guards.
36
37
  */
37
38
  static guards(guards: string[]): Class<Middleware>;
39
+ /**
40
+ * Structured application logger resolved from the service container.
41
+ * Returns a child logger with the middleware class name in context.
42
+ * @author Axel Nana <axel.nana@workbud.com>
43
+ */
44
+ protected get logger(): LoggerInterface;
38
45
  /**
39
46
  * Gets the list of guards for the middleware.
40
47
  */
@@ -0,0 +1,15 @@
1
+ import type { Context } from '../http';
2
+ import { Middleware } from '../middleware';
3
+ /**
4
+ * Middleware that logs incoming HTTP requests and their completion time.
5
+ *
6
+ * Uses `this.logger` which is resolved from the service container.
7
+ * If Hermes is installed, structured JSON logs are produced; otherwise,
8
+ * the fallback `ConsoleLogger` is used.
9
+ *
10
+ * @author Axel Nana <axel.nana@workbud.com>
11
+ */
12
+ export declare class RequestLoggerMiddleware extends Middleware {
13
+ onRequest(ctx: Context): Promise<void>;
14
+ onAfterResponse(ctx: Context): Promise<void>;
15
+ }