@elysiumjs/core 0.6.0 → 0.7.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.
- package/dist/app.d.ts +0 -14
- package/dist/index.d.ts +0 -7
- package/dist/index.js +9 -9
- package/dist/redis.d.ts +0 -84
- package/dist/websocket.d.ts +2 -2
- package/package.json +43 -44
- package/.turbo/turbo-build.log +0 -8
- package/dist/cache.d.ts +0 -113
- package/dist/database.d.ts +0 -112
- package/dist/model.d.ts +0 -2413
- package/dist/repository.d.ts +0 -175
- package/dist/tenancy.d.ts +0 -244
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 { DatabaseConnectionProps } from './database';
|
|
4
3
|
import type { Route } from './http';
|
|
5
4
|
import type { ModuleClass } from './module';
|
|
6
5
|
import type { RedisConnectionProps } from './redis';
|
|
@@ -49,19 +48,6 @@ export type AppProps = {
|
|
|
49
48
|
* The list of modules provided the app.
|
|
50
49
|
*/
|
|
51
50
|
modules?: ModuleClass[];
|
|
52
|
-
/**
|
|
53
|
-
* The database configuration for the app.
|
|
54
|
-
*/
|
|
55
|
-
database?: {
|
|
56
|
-
/**
|
|
57
|
-
* The default connection name.
|
|
58
|
-
*/
|
|
59
|
-
default: string;
|
|
60
|
-
/**
|
|
61
|
-
* The list of connections.
|
|
62
|
-
*/
|
|
63
|
-
connections: Record<string, DatabaseConnectionProps>;
|
|
64
|
-
};
|
|
65
51
|
/**
|
|
66
52
|
* The redis configuration for the app.
|
|
67
53
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import type { SingletonBase } from 'elysia';
|
|
2
2
|
export { type Elysia, type TSchema, type Static, t } from 'elysia';
|
|
3
3
|
export { type AppContext, type ElysiumPlugin, Application } from './app';
|
|
4
|
-
export { Cache } from './cache';
|
|
5
4
|
export { type CommandArgumentProps, type CommandClass, Command, CommandArgumentType } from './command';
|
|
6
5
|
export { ConsoleFormat, InteractsWithConsole } from './console';
|
|
7
|
-
export { Database } from './database';
|
|
8
6
|
export { Env } from './env';
|
|
9
7
|
export { type EventData, type EventHandler, Event } from './event';
|
|
10
8
|
export { type LoggerInterface, ConsoleLogger } from './logger';
|
|
@@ -12,13 +10,8 @@ export { type Context, type Route, HttpControllerScope, Http } from './http';
|
|
|
12
10
|
export { Job } from './job';
|
|
13
11
|
export { Middleware } from './middleware';
|
|
14
12
|
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';
|
|
19
13
|
export { type ModuleClass, Module } from './module';
|
|
20
14
|
export { Redis } from './redis';
|
|
21
|
-
export { type IdType, type RepositoryInterface, type RepositoryClass, Repository } from './repository';
|
|
22
15
|
export { ServiceScope, Service } from './service';
|
|
23
16
|
export { type WampRegistrationOptions, type WampSubscriptionOptions, type WampProps, type WampRegistrationHandlerArgs, type WampSubscriptionHandlerArgs, type WampRegistrationHandler, type WampSubscriptionHandler, Wamp } from './wamp';
|
|
24
17
|
export { type WS, type WSError, Websocket } from './websocket';
|
package/dist/index.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
2
|
+
var cQ=Object.defineProperty;var mQ=(Q,X)=>{for(var $ in X)cQ(Q,$,{get:X[$],enumerable:!0,configurable:!0,set:(z)=>X[$]=()=>z})};var QQ=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);import*as HQ from"readline";import{isEmpty as uQ,omit as iQ}from"radash";class S{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 $=Q.name||"Error",
|
|
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",z=Q.message||"An error occurred",Y=Q.stack||"";if(X)this.title(X);else this.newLine();if(this.write(this.format(`${$}: ${z}`,1)),Q.stack)this.write(this.format("Stack Trace:",9)),this.write(this.format(Y.split(`
|
|
5
5
|
`).map((U)=>` ${U}`).join(`
|
|
6
|
-
`),8));let
|
|
6
|
+
`),8));let Z=iQ(Q,["name","message","stack"]);if(!uQ(Z))this.write(this.format("Additional Information:",9)),Object.keys(Z).forEach((U)=>{let L=Q[U];this.write(` ${U}: ${JSON.stringify(L)}`)});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]),z={};for(let U of $){let L=X?.[U];if(L?.width){z[U]=L.width;continue}let K=(L?.header||String(U)).length,G=Math.max(...Q.map((D)=>{let W=D[U];if(L?.format)return L.format(W).length;return String(W===null||W===void 0?"":W).length}));z[U]=Math.max(K,G)}let Y="",Z="";for(let U of $){let K=X?.[U]?.header||String(U),G=z[U];Y+=`| ${K.padEnd(G)} `,Z+=`| ${"-".repeat(G)} `}Y+="|",Z+="|",this.write(Y),this.write(Z);for(let U of Q){let L="";for(let K of $){let G=X?.[K],D=z[K],W=U[K],P;if(G?.format)P=G.format(W);else P=String(W===null||W===void 0?"":W);L+=`| ${P.padEnd(D)} `}L+="|",this.write(L)}this.newLine()}format(Q,...X){return`${X.map((z)=>nQ[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 $=HQ.createInterface({input:process.stdin,output:process.stdout}),z=X?` (default: ${X})`:"";return new Promise((Y)=>{$.question(`${Q}${z}: `,(Z)=>{$.close(),Y(Z||X||"")})})}async promptPassword(Q){let X=HQ.createInterface({input:process.stdin,output:process.stdout});return process.stdin.setRawMode?.(!0),new Promise(($)=>{let z="";process.stdout.write(`${Q}: `),process.stdin.on("data",(Y)=>{let Z=Y.toString();if(Z==="\r"||Z===`
|
|
7
7
|
`){process.stdout.write(`
|
|
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
|
|
8
|
+
`),process.stdin.setRawMode?.(!1),process.stdin.removeAllListeners("data"),X.close(),$(z);return}if(Z==="\b"||Z==="\x7F"){if(z.length>0)z=z.slice(0,-1),process.stdout.write("\b \b");return}z+=Z,process.stdout.write("*")})})}async confirm(Q,X=!1){let $=X?"Y/n":"y/N",z=await this.prompt(`${Q} [${$}]`);if(!z)return X;return z.toLowerCase()==="y"||z.toLowerCase()==="yes"}async select(Q,X,$=0){if(X.length===0)throw Error("No options provided for selection");this.write(Q),X.forEach((Z,U)=>{let L=U===$;this.write(` ${U+1}. ${Z}${L?" (default)":""}`)});let z=await this.prompt("Enter your choice (number)");if(!z)return X[$];let Y=parseInt(z,10)-1;if(isNaN(Y)||Y<0||Y>=X.length)return this.warning(`Invalid selection. Using default: ${X[$]}`),X[$];return X[Y]}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 ZQ,nQ;var n=QQ(()=>{((_)=>{_[_.BLACK=0]="BLACK";_[_.RED=1]="RED";_[_.GREEN=2]="GREEN";_[_.YELLOW=3]="YELLOW";_[_.BLUE=4]="BLUE";_[_.MAGENTA=5]="MAGENTA";_[_.CYAN=6]="CYAN";_[_.WHITE=7]="WHITE";_[_.GRAY=8]="GRAY";_[_.BOLD=9]="BOLD";_[_.UNDERLINE=10]="UNDERLINE";_[_.ITALIC=11]="ITALIC";_[_.INVERSE=12]="INVERSE"})(ZQ||={});nQ={[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 XQ,isPrimitive as oQ}from"radash";function m(Q,...X){if(!X.length)return Q;let $=X.shift();if($===void 0)return Q;if(XQ(Q)&&XQ($))for(let z in $)if(XQ($[z])){if(!Q[z])Object.assign(Q,{[z]:$[z]})}else if(Array.isArray($[z])){if(!Array.isArray(Q[z]))Q[z]=[];if($[z].length>0&&!XQ($[z][0]))Q[z]=[...new Set([...Q[z],...$[z]])];else $[z].forEach((Y,Z)=>{if(XQ(Y)&&Q[z][Z])Q[z][Z]=m(Q[z][Z],Y);else if(!Q[z].includes(Y))Q[z].push(Y)})}else if(oQ($[z]))Q[z]??=$[z];else m(Q[z],$[z]);return m(Q,...X)}var H,p=()=>new Promise((Q)=>process.nextTick(Q));var y=QQ(()=>{((f)=>(f.app=Symbol("elysium:Application"),f.controller=Symbol("elysium:Controller"),f.middlewares=Symbol("elysium:MiddlewaresList"),f.services=Symbol("elysium:ServicesList"),f.websocket=Symbol("elysium:WebSocket"),f.wamp=Symbol("elysium:Wamp"),f.http=Symbol("elysium:Http"),f.job=Symbol("elysium:Job"),f.arg=Symbol("elysium:CommandArguments"),f.elysiaPlugin=Symbol("elysium:ElysiaPlugin"),f.middlewareGuards=Symbol("elysium:MiddlewareGuards")))(H||={})});import{isString as o}from"radash";var JQ,aQ=(Q)=>{return typeof Q==="function"&&Q.prototype&&Q.prototype.constructor===Q},FQ,WQ=(Q)=>{return typeof Q==="object"&&Q!==null&&FQ in Q},h,B;var v=QQ(()=>{y();(($)=>{$[$.SINGLETON=0]="SINGLETON";$[$.FACTORY=1]="FACTORY"})(JQ||={});FQ=Symbol("lazy"),h=new Map;((E)=>{E.register=(P)=>{return function(_){let O=P?.name??_.name,j=P?.scope??0;if(B.exists(O))console.error(`A service with the name ${O} has already been registered.`),process.exit(1);let k=()=>B.make(_);if(j===0){let R=k();h.set(O,{scope:j,factory(){return R}})}else h.set(O,{scope:j,factory:k})}},E.inject=(P)=>{return function(_,O,j){let k=Reflect.getMetadata(H.services,_,O)??[],R=Reflect.getMetadata("design:paramtypes",_,O)??[],V=o(P)?P:P?.name??R[j].name;k.push({name:V,index:j}),Reflect.defineMetadata(H.services,k,_,O)}},E.get=(P)=>{let _=o(P)?P:P.name;if(E.exists(_)){let O=h.get(_);if(WQ(O)){let j=O.resolver();return h.set(_,{scope:0,factory:()=>j}),j}return O.factory()}return null},E.registerLazy=(P,_)=>{if(h.has(P)&&!WQ(h.get(P)))throw Error(`Service ${P} already registered`);h.set(P,{[FQ]:!0,resolver:_})},E.make=(P)=>{let _=Reflect.getMetadata(H.services,P)??[],O=[];return _.forEach((j)=>{let k=E.get(j.name);if(k===null)console.error(`Cannot inject service ${j.name}. No service was registered with the name: ${j.name}`),process.exit(1);O[j.index]=k}),new P(...O)},E.bind=(P,_)=>{let O=E.make(P);return E.instance(_??P.name,O)};function U(P,_){let O=o(P)?P:_??P.name;if(E.exists(O))console.error(`A service with the name ${O} has already been registered.`),process.exit(1);let j=()=>{return aQ(P)?E.make(P):_()};return h.set(O,{scope:1,factory:j}),j()}E.factory=U,E.instance=(P,_)=>{let O=o(P)?P:P.name;if(E.exists(O))console.error(`A service with the name ${O} has already been registered.`),process.exit(1);return h.set(O,{scope:0,factory(){return _}}),_},E.remove=(P)=>{let _=o(P)?P:P.name;h.delete(_)},E.exists=(P)=>{let _=o(P)?P:P.name;return h.has(_)},E.clear=()=>{h.clear()},E.keys=(P)=>{let _="^"+P.replace(/[-[\]{}()+.,\\^$|#\s]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$",O=new RegExp(_);return Array.from(h.keys()).filter((j)=>O.test(j))}})(B||={})});import"reflect-metadata";import{assign as XX,uid as $X}from"radash";var EQ;var IQ=QQ(()=>{n();v();y();EQ=class EQ extends S{#Q;#X;#$="pending";#z;static register(Q={}){return function(X){Q=XX({name:X.name,queue:"default"},Q);let $=`job.${Q.name}`;B.instance($,X),Reflect.defineMetadata(H.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.#z=Q instanceof Error?Q:Error(String(Q)),this.#$!=="cancelled")this.#$="failed";this.#X=new Date,this.trace(this.#z)}}cancel(){this.#$="cancelled"}generateJobId(){return`job_${Date.now()}_${$X(8)}`}}});var fQ={};mQ(fQ,{WorkerPool:()=>GQ,Worker:()=>OQ});import{uid as zX}from"radash";var TQ,OQ,GQ;var RQ=QQ(()=>{n();v();y();TQ=globalThis.Worker;OQ=class OQ extends S{#Q;queues=new Map;defaultQueueName="default";static spawn(Q,X=["default"],$){let z=new this;z.debug(`Worker ${z.id} starting with queues: ${X.join(", ")}`);for(let Y of X)z.createQueue({name:Y,concurrency:$?.concurrency??1,maxRetries:$?.maxRetries??5,retryDelay:$?.retryDelay??5000,pauseOnError:$?.pauseOnError??!1});return Q.addEventListener("message",async(Y)=>{let{type:Z="job:process",jobId:U,job:L,args:K,queue:G="default"}=Y.data;switch(Z){case"job:cancel":let D=z.cancelJob(U,G);Q.postMessage({type:"job:canceled",jobId:U,queue:G,success:D,count:D?1:0});break;case"job:cancelAll":let W=z.cancelAllJobs(G);Q.postMessage({type:"jobs:canceled",queue:G,count:W});break;case"job:process":z.debug(`Worker ${z.id} received job ${L} for queue ${G}`);try{let P=B.get(L);if(!P)throw z.error(`Job class ${L} not found`),Error(`Job class ${L} not found`);let _=new P(...K||[]);z.addJob(_,G),Q.postMessage({type:"job:received",jobId:_.id,queue:G})}catch(P){z.trace({...P,...$??{}},`Error while adding job '${L}' to queue '${G}' with worker ${z.id}`),Q.postMessage({type:"job:error",jobName:L,error:P.message})}break}}),Q.addEventListener("error",(Y)=>{z.trace({...Y.error,filename:Y.filename},`Worker ${z.id} error:`)}),Q.addEventListener("unhandledrejection",(Y)=>{z.trace(Y,`Worker ${z.id} unhandled rejection:`)}),Q.postMessage({type:"worker:ready",id:z.id,queues:X}),z}constructor(){super();this.#Q=zX(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 z={job:Q,retries:0,queueName:X};if($.jobs.push(z),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 z=$.jobs.length;$.jobs=[],this.info(`Cleared ${z} 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(z){if(this.error(`Unexpected error processing job ${$.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,$]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[z]of this.queues.entries())if(this.cancelJobInQueue(Q,z)){$=!0;break}return $}}cancelJobInQueue(Q,X){let $=this.queues.get(X);if(!$)return!1;let z=$.jobs.findIndex((Y)=>Y.job.id===Q);if(z>=0)return $.jobs[z].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((z)=>{z.job.cancel()}),this.info(`Canceled ${X} jobs in queue '${Q}'`)}else for(let[$,z]of this.queues.entries()){let Y=z.jobs.length;z.jobs.forEach((Z)=>{Z.job.cancel()}),X+=Y,this.info(`Canceled ${Y} jobs in queue '${$}'`)}return X}};GQ=class GQ extends S{workers=[];currentWorkerIndex=0;queueWorkerMap=new Map;static instance=new GQ;constructor(){super()}async init(){}async addWorker(Q=[]){let X;if(Bun.main.endsWith(".js"))X=new TQ("./index.js",{argv:["work",...Q.map((z)=>`--queue=${z}`)]});else{let z=await Array.fromAsync(new Bun.Glob("./src/**/*.job.ts").scan());X=new TQ("./index.ts",{preload:z,argv:["work",...Q.map((Y)=>`--queue=${Y}`)]})}X.addEventListener("error",(z)=>{this.trace({message:"An error occurred inside a worker process",stack:z.message,name:"WorkerError"}),this.removeWorker(X),this.addWorker(Q)}),X.addEventListener("messageerror",(z)=>{this.error(`Worker message error: ${z}`)}),X.addEventListener("message",(z)=>{if(z.data.type==="worker:ready")this.debug(`Worker ${z.data.id} ready with queues: ${z.data.queues.join(", ")}`);else if(z.data.type==="job:received")this.debug(`Job ${z.data.jobId} received by worker for queue ${z.data.queue}`);else if(z.data.type==="job:error")this.error(`Error processing job ${z.data.jobName}: ${z.data.error}`);else this.debug(`Worker message: ${JSON.stringify(z.data)}`)}),this.workers.push(X);for(let z of Q){if(!this.queueWorkerMap.has(z))this.queueWorkerMap.set(z,[]);this.queueWorkerMap.get(z).push(X)}}removeWorker(Q){let X=Q??this.workers.pop();if(!X)return;X.terminate();for(let[$,z]of this.queueWorkerMap.entries())this.queueWorkerMap.set($,z.filter((Y)=>Y!==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(H.job,Q))throw Error(`Job ${Q.name} is not marked with @job() decorator`);let{name:$,queue:z="default"}=Reflect.getMetadata(H.job,Q),Y=this.queueWorkerMap.get(z)||this.workers;if(Y.length===0)throw Error(`No workers available for queue '${z}'`);let Z=this.currentWorkerIndex%Y.length;Y[Z].postMessage({job:$,args:X,queue:z}),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 c0}from"elysia";n();import{AsyncLocalStorage as YX}from"async_hooks";import{parseArgs as ZX}from"util";import{swagger as UX}from"@elysiajs/swagger";import{Value as $Q}from"@sinclair/typebox/value";import{Elysia as _X}from"elysia";import{first as GX}from"radash";var UQ=new Map,DQ=(Q)=>{for(let[X,$]of Object.entries(Q))UQ.set(X,$)},AQ;((s)=>(s.get=(z,Y)=>{return UQ.get(z)??Y},s.exists=(z)=>{return UQ.has(z)},s.clear=()=>{UQ.clear()}))(AQ||={});import{EventEmitter as sQ}from"events";import{isString as KQ}from"radash";class x extends sQ{static instance=new x;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 w;((l)=>{l.emit=(U,L,K=null)=>{x.instance.emitEvent(U,L,K)};function X(U,L){if(KQ(U))x.instance.on(U,L);else return function(K,G,D){let W=async function(_){try{await D.value(_)}catch(O){x.instance.emitError(O)}};if(U.prepend??!1)x.instance.prependListener(U.event,W);else x.instance.on(U.event,W)}}l.on=X;function $(U,L){if(KQ(U))x.instance.once(U,L);else return function(K,G,D){let W=async function(_){try{await D.value(_)}catch(O){x.instance.emitError(O)}};if(U.prepend??!1)x.instance.prependOnceListener(U.event,W);else x.instance.once(U.event,W)}}l.once=$,l.off=(U)=>{x.instance.removeAllListeners(U)},l.clear=()=>{x.instance.removeAllListeners()},l.listen=(U)=>{if(U.mode==="on")return X(U);else if(U.mode==="once")return $(U);return function(L,K,G){console.error("Unknown mode provided to @listen. Use either 'on' or 'once'.")}}})(w||={});v();y();var g=(Q,X,$)=>{return c.context.run(new Map([["tenant",X.tenant],["http:context",X]]),async()=>{for(let z of Q)try{let Y=await z[$](X);if(Y!==void 0)return Y}catch(Y){throw Y}})},a=(Q,X)=>{let $=Q.map((z)=>B.make(z));X.onRequest((z)=>{return g($,z,"onRequest")}),X.onTransform((z)=>{return g($,z,"onTransform")}),X.onBeforeHandle((z)=>{return g($,z,"onBeforeHandle")}),X.onAfterHandle((z)=>{return g($,z,"onAfterHandle")}),X.onAfterResponse((z)=>{return g($,z,"onAfterResponse")})};class _Q{static register(...Q){return function(X,$,z){if($===void 0&&z===void 0){let Y=Reflect.getMetadata(H.middlewares,X)??[];Y.push(...Q),Reflect.defineMetadata(H.middlewares,Y,X)}else{let Y=Reflect.getMetadata(H.middlewares,X,$)??[];Y.push(...Q),Reflect.defineMetadata(H.middlewares,Y,X,$)}}}static guards(Q){class X extends this{}return Reflect.defineMetadata(H.middlewareGuards,Q,X),X}get logger(){return B.get("logger").child({middleware:this.constructor.name})}get guards(){return Reflect.getMetadata(H.middlewareGuards,this.constructor)??[]}onRequest(Q){}onTransform(Q){}onAfterHandle(Q){}onBeforeHandle(Q){}onAfterResponse(Q){}}v();import{omit as tQ}from"radash";var t;((b)=>{let Q=(U)=>{return`redis.connection.${U}`};b.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))},b.registerConnection=(U,L)=>{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(L.url,tQ(L,["url"])))},b.connectionExists=(U)=>{return B.exists(Q(U))},b.getDefaultConnection=()=>{return b.getConnection("default")},b.setDefaultConnection=(U)=>{let L=Q("default");return B.remove(L),B.instance(L,b.getConnection(U))}})(t||={});v();y();import{Elysia as rQ}from"elysia";import{omit as eQ}from"radash";import QX from"wampy";v();y();class jQ extends WebSocket{protocols;constructor(Q,X){super(Q,X);this.protocols=X}get protocol(){return this.protocols?.[0]??"wamp.2.json"}}var u;((N)=>{let Q=(G)=>{return`wamp.connection.${G}`};N.getConnection=(G)=>{if(!B.exists(Q(G)))console.error(`No WAMP connection with name ${G} found. Please make sure to register the connection before using it.`),process.exit(1);return B.get(Q(G))},N.registerConnection=(G,D)=>{if(B.exists(Q(G)))console.error(`A WAMP connection with name ${G} already exists. Please ensure to register a new connection before overwriting it.`),process.exit(1);let W=new QX(D.url,{ws:jQ,...eQ(D,["url"]),onError(){D.onError?.(),w.emit("elysium:error",Error(`An error occurred in WAMP connection ${G}`))}}),P=D.maxRetries??5,_=D.retryInterval??5000,O=0,j=async()=>{try{await W.connect()}catch(k){if(console.error(`Failed to connect to WAMP server (attempt ${O+1}/${P}):`,k),O<P)O++,setTimeout(j,_);else console.error(`Max retry attempts (${P}) reached. Giving up.`),w.emit("elysium:error",Error(`Failed to establish WAMP connection ${G} after ${P} attempts`))}};return j(),B.instance(Q(G),W)},N.connectionExists=(G)=>{return B.exists(Q(G))},N.getDefaultConnection=()=>{return N.getConnection("default")},N.setDefaultConnection=(G)=>{let D=Q("default");return B.remove(D),B.instance(D,N.getConnection(G))},N.controller=(G)=>{return function(D){async function W(){console.log(`Registering Wamp controller for connection ${G.connection} using ${D.name}`),await p();let P=B.make(D),_=Reflect.getMetadata(H.wamp,D)??{},O=u.getConnection(G.connection??"default"),j=new rQ;return j.onStart(async(k)=>{let R=_.registrations??[],V=_.subscriptions??[];for(let M of R)O.register(M.topic,M.handler.bind(P),M.options).then((T)=>{console.log(`Registered ${M.topic} with id ${T.registrationId}`)});for(let M of V)O.subscribe(M.topic,M.handler.bind(P),M.options).then((T)=>{console.log(`Subscribed ${M.topic} with id ${T.subscriptionId}`)})}),j}Reflect.defineMetadata(H.elysiaPlugin,W,D)}},N.register=(G,D)=>{return function(W,P,_){let O=Reflect.getMetadata(H.wamp,W.constructor)??{};O.registrations??=[],O.registrations.push({topic:G,options:D,handler:_.value}),Reflect.defineMetadata(H.wamp,O,W.constructor)}},N.subscribe=(G,D)=>{return function(W,P,_){let O=Reflect.getMetadata(H.wamp,W.constructor)??{};O.subscriptions??=[],O.subscriptions.push({topic:G,options:D,handler:_.value}),Reflect.defineMetadata(H.wamp,O,W.constructor)}}})(u||={});class c extends S{#Q;#X;_appContextStorage=new YX;static get instance(){return B.get("elysium.app")}static get context(){return c.instance._appContextStorage}static register(Q={}){return function(X){let $,z=Object.getPrototypeOf(X);while(z&&z!==Object.prototype){let Z=Reflect.getMetadata(H.app,z);if(Z){$=Z;break}z=Object.getPrototypeOf(z)}if($)Q=m($,Q);let Y=Reflect.getMetadata(H.app,X);if(Y)Q=m(Y,Q);Q=m({modules:[],swagger:!1},Q),Reflect.defineMetadata(H.app,Q,X)}}constructor(){super();let{env:Q,debug:X}=Reflect.getMetadata(H.app,this.constructor)??{};if(this.#X=X??!1,Q){let Y=$Q.Convert(Q,$Q.Clone(Bun.env));if(this.#X&&!$Q.Check(Q,Y)){let Z=$Q.Errors(Q,Y).First();this.trace(Z,"Invalid environment configuration")}DQ($Q.Clean(Q,Y))}else DQ(Bun.env);B.instance("elysium.app",this);let{redis:$,wamp:z}=Reflect.getMetadata(H.app,this.constructor);if($){for(let Y in $.connections)t.registerConnection(Y,$.connections[Y]);if(t.connectionExists($.default))t.setDefaultConnection($.default)}if(z){for(let Y in z.connections)u.registerConnection(Y,z.connections[Y]);if(u.connectionExists(z.default))u.setDefaultConnection(z.default)}this.run().then(()=>w.emit("elysium:app:launched",this,this)).catch((Y)=>{w.emit("elysium:error",Y),this.trace(Y,"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 Y=this.getCommands().find((Z)=>Z.command===$);if(Y){let Z=B.make(Y);return this.write(await Z.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(H.app,this.constructor)?.[Q]??null}async commandExec(Q,X){let z=this.getCommands().find((Y)=>Y.command===Q);if(!z)return console.error(`Command ${Q} not found`),this.commandList(),process.exit(1);try{let Y=B.make(z);if(await Y.init(...X))await Y.run();else{let U=await Y.help();this.write(U)}return process.exit(0)}catch(Y){return console.error(Y.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}=ZX({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(() => (RQ(),fQ)),z=X.queue.map((Z)=>Z.split(",")).reduce((Z,U)=>Z.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(Y.id,2)} started with queues: ${z.map((Z)=>this.format(Z,6)).join(", ")}`)}async commandServe(){let{server:Q,modules:X,swagger:$,plugins:z}=Reflect.getMetadata(H.app,this.constructor);if(this.#Q=new _X(Q).onRequest((Z)=>{if(this.isDebug)console.log(Z.request.method,Z.request.url)}),w.emit("elysium:server:before-init",this,this),this.#Q.resolve({as:"global"},({request:Z})=>({tenant:Z.headers.get("x-tenant-id")??"public"})),$)this.#Q.use(UX($));if(z&&z.length>0){this.debug("Registering plugins...");for(let Z of z)this.#Q.use(await Z(this))}this.#Q.onError({as:"global"},async(Z)=>{if(await this.onError(Z)){w.emit("elysium:error",Z),this.trace({name:"HttpError",message:"Unexpected error while handling HTTP request",stack:Z.error.stack,...Z.error});let U={};if(typeof Z.code==="number")return Z.error.response;else switch(Z.code){case"VALIDATION":{U={scope:Z.error.type,code:Z.error.message};break}case"INTERNAL_SERVER_ERROR":{U={message:Z.error.message};break}}return{type:Z.code,data:U}}}).onStart(async(Z)=>{await this.onStart(Z),w.emit("elysium:server:start",Z,this)}).onStop(async(Z)=>{await this.onStop(Z),w.emit("elysium:server:stop",Z,this),this._appContextStorage.disable()});let Y=Reflect.getMetadata(H.middlewares,this.constructor)??[];a(Y,this.#Q);for(let Z of X){let U=Reflect.getMetadata(H.elysiaPlugin,Z);if(U===void 0)return console.error(`Invalid module class ${Z.name} registered in app ${this.constructor.name}. Ensure that you used the @module() decorator on the module.`),process.exit(1);let L=B.bind(Z);await L.beforeRegister(),this.#Q.use(await U(L)),await L.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 X=this.getCommands().reduce(($,z)=>{let Y=GX(z.command.split(":")),Z=$.get(Y)??[];return Z.push(z),$.set(Y,Z),$},new Map);for(let[$,z]of X){this.section(this.format($,4));for(let Y of z)this.commandDescription(Y.command,"",Y.description)}}commandDescription(Q,X,$,z=S.SPACE_WIDTH){X=X.length===0?" ":` ${X} `,this.write(` ${this.format(Q,6)}${X}${"\u2219".repeat(z-Q.length-X.length)} ${$}`)}}n();v();y();import{isArray as LX,trim as PX}from"radash";var kQ;((Z)=>{Z.STRING="string";Z.NUMBER="number";Z.BOOLEAN="boolean";Z.ENUM="enum";Z.ARRAY="array"})(kQ||={});class CQ extends S{static command="command";static description="Command description";static dev=!1;static register(Q={}){return function(X){let $=X,Y=`elysium.command.${Q.name??$.command}`;if(B.exists(Y))return X;return B.instance(Y,X),X}}static arg(Q={}){return function(X,$){let z=Reflect.getMetadata(H.arg,X.constructor)??[],Y=Reflect.getMetadata("design:type",X,$),Z=Q.type;if(!Z&&Y){if(Y===Array){if(Z="array",!Q.arrayType)Q={...Q,arrayType:"string"}}else if(Y.constructor!==Object)switch(Y.name.toLowerCase()){case"number":Z="number";break;case"boolean":Z="boolean";break;case"string":Z="string";break;default:Z=void 0}else if(Object.values(Y).length>0){if(Z="enum",!Q.enum)Q={...Q,enum:Object.values(Y)}}}z.push({name:Q.name??$,description:Q.description,required:Q.required??!1,default:Q.default,type:Z,enum:Q.enum,arrayType:Q.arrayType,propertyKey:$}),Reflect.defineMetadata(H.arg,z,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 z=this.getArguments();for(let Y of z)if(X[Y.name]!==void 0)this[Y.propertyKey]=X[Y.name];return!0}getArguments(){return Reflect.getMetadata(H.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 $ of X){let
|
|
13
|
+
`;for(let $ of X){let z=this.format($.required?"(required)":"(optional)",1,9),Y=$.default!==void 0?this.format(`[default: ${$.default}]`,8,11):"",Z="";if($.type==="array")Z=`<array of ${$.arrayType||"string"}s>`;else if($.type)Z=`<${$.type}>`;let U=$.enum?` [${$.enum.join("|")}]`:"";if(Q+=` ${this.format(`--${$.name}`,6)} ${Z}${U} ${z} ${Y}
|
|
14
14
|
`,$.description)Q+=` ${$.description}
|
|
15
15
|
|
|
16
16
|
`}}else Q+=`This command has no arguments.
|
|
17
|
-
`;return
|
|
18
|
-
`)}validateArgs(Q){let X=[],$=[],
|
|
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};
|
|
17
|
+
`;return PX(Q,`
|
|
18
|
+
`)}validateArgs(Q){let X=[],$=[],z=this.getArguments();if(Object.keys(Q).includes("help"))return{valid:!0,missing:[]};for(let Y of z){if(Y.required&&(Q[Y.name]===void 0||Q[Y.name]===null)){X.push(Y.name);continue}if(Q[Y.name]===void 0)continue;if(Y.type==="enum"&&Y.enum&&!Y.enum.includes(Q[Y.name]))$.push(`${Y.name} (must be one of: ${Y.enum.join(", ")})`);if(Y.type==="array"&&Y.arrayType==="enum"&&Y.enum){let Z=Q[Y.name].filter((U)=>!Y.enum.includes(U));if(Z.length>0)$.push(`${Y.name} (contains invalid values: ${Z.join(", ")}. Must be one of: ${Y.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 z=0;z<Q.length;z++){let Y=Q[z];if(Y.startsWith("--")){let Z=Y.slice(2);if(z+1<Q.length&&!Q[z+1].startsWith("--"))X[Z]=Q[z+1],z++;else X[Z]=!0}}for(let z of $){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 Z=X[z.name].toLowerCase();X[z.name]=Z==="true"||Z==="1"||Z==="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((L)=>L.trim());if(z.arrayType)X[z.name]=U.map((L)=>{switch(z.arrayType){case"number":return Number(L);case"boolean":return L.toLowerCase()==="true"||L.toLowerCase()==="1"||L.toLowerCase()==="yes";case"enum":return L;default:return L}});else X[z.name]=U;break;case"string":default:break}}return X}progress(Q,X="Processing"){return new NQ(Q,X)}spinner(Q="Processing",X,$){return new wQ(Q,X,$)}inferType(Q){if(Q===void 0)return"string";switch(typeof Q){case"number":return"number";case"boolean":return"boolean";default:return LX(Q)?"array":"string"}}}class NQ extends S{#Q=!1;#X=0;#$=0;#z="";#Y=0;constructor(Q=0,X="Processing"){super();this.#X=Q,this.#z=X,this.#Q=!0,this.#$=0,this.#Y=Date.now(),this.update(0)}update(Q=1,X){if(!this.#Q)return;if(this.#$+=Q,X)this.#z=X;let $=Math.min(100,Math.floor(this.#$/this.#X*100)),Y=(Date.now()-this.#Y)/1000,Z=0,U=0,L="";if(this.#$>0)Z=Y/this.#$*this.#X,U=Math.max(0,Z-Y),L=` | ${this.formatTime(Y)} elapsed | ${this.formatTime(U)} remaining`;let K=30,G=Math.floor($/100*K),D=K-G,W="["+"=".repeat(G)+(D>0?">":"")+" ".repeat(Math.max(0,D-(D>0?1:0)))+"]",P=`${this.#z}: ${W} ${$}% (${this.#$}/${this.#X})${L}`;if(this.clearLine(),this.write(P,!1),this.#$>=this.#X)this.complete()}complete(Q){if(!this.#Q)return;this.#$=this.#X;let $=(Date.now()-this.#Y)/1000;if(this.clearLine(),Q)this.write(`${Q} (completed in ${this.formatTime($)})`);else this.write(`${this.#z} 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 wQ extends S{#Q=!1;#X="";#$=0;#z=null;#Y=0;#Z=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];#U=80;constructor(Q="Processing",X,$){super();if(this.#X=Q,X)this.#Z=X;if($)this.#U=$;if(this.#Q)return;this.#Q=!0,this.#$=Date.now(),this.#Y=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.#$)/1000;this.clearLine();let Y=this.formatTime(z);if(Q)this[X?"success":"error"](`${Q} (${Y})`);else this[X?"success":"error"](`${this.#X} completed in ${Y}`);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.#$)/1000}render(){if(!this.#Q)return;let Q=this.getElapsedTime(),X=this.#Z[this.#Y];this.#Y=(this.#Y+1)%this.#Z.length,this.clearLine(),this.write(`${X} ${this.#X} (${this.formatTime(Q)})`,!1)}}n();class BQ{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 BQ({...this.context,...Q})}}import{Elysia as HX,sse as DX,t as SQ}from"elysia";import{assign as OX,isEmpty as LQ,objectify as RX}from"radash";v();y();var BX=(Q)=>{let X=Reflect.getMetadata("http:body",Q.target,Q.propertyKey),$=Reflect.getMetadata("http:params",Q.target,Q.propertyKey)??[],z=Reflect.getMetadata("http:query",Q.target,Q.propertyKey),Y=Reflect.getMetadata("http:rawContext",Q.target,Q.propertyKey),Z=Reflect.getMetadata("http:customDecorators",Q.target,Q.propertyKey)??[],U=Reflect.getMetadata(H.middlewares,Q.target,Q.propertyKey)??[],L=Reflect.getMetadata(H.services,Q.target,Q.propertyKey)??[],{path:K,method:G,handler:D,target:W,response:P,operationId:_,description:O,transactional:j}=Q,k=Reflect.getMetadata(H.http,W.constructor)??[];k.push({path:K,method:G,body:X,params:$,query:z,customDecorators:Z,rawContext:Y,handler:D,middlewares:U,response:P,operationId:_,description:O,services:L,transactional:j}),Reflect.defineMetadata(H.http,k,W.constructor)},xQ;(($)=>{$[$.SERVER=0]="SERVER";$[$.REQUEST=1]="REQUEST"})(xQ||={});var hQ;((A)=>(A.controller=(R={path:"/"})=>{return function(V){async function M(){console.log(`Registering HTTP controller for ${R.path} using ${V.name}`),await p(),R=OX({path:"/",scope:0,tags:[]},R);let T=new HX({prefix:R.path,name:V.name}),d=(()=>{if(R.scope===0)return()=>{let J=B.make(V);return()=>J};else if(R.scope===1)return()=>()=>B.make(V);else throw Error(`Invalid scope for controller: ${V.name}`)})();T.resolve({as:"local"},()=>({controller:d()}));let r=Reflect.getMetadata("http:onRequest",V)??{};if(r.handler)T.onRequest((J)=>{let i=d()();return r.handler.call(i,J)});let vQ=Reflect.getMetadata(H.middlewares,V)??[];a(vQ,T);let gQ=Reflect.getMetadata(H.http,V)??[];for(let J of gQ){let i=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(!LQ(J.params))for(let C of J.params)F[C.index]=I.params[C.slug];if(!LQ(J.customDecorators))for(let C of J.customDecorators)F[C.index]=await C.handler(I);if(!LQ(J.services))for(let C of J.services)F[C.index]=B.get(C.name);return F},dQ=J.handler.constructor.name.includes("GeneratorFunction"),VQ=J.method==="elysium:SSE",lQ=J.transactional??R.transactional??!1,PQ=J.body&&J.body.schema===void 0&&J.body.validator!==void 0;J.method=VQ?"GET":J.method;let pQ=()=>{let I=(F)=>{if(lQ)return function(...C){return B.get("db.connection.default").transaction((YQ)=>{return c.context.run(new Map([["tenant",F.tenant],["http:context",F],["db:tx",YQ]]),()=>{try{return J.handler.call(F.controller(),...C)}catch(e){throw YQ.rollback(),e}})})};return function(...C){return c.context.run(new Map([["tenant",F.tenant],["http:context",F]]),()=>J.handler.call(F.controller(),...C))}};if(dQ)return async function*(F){let C=I(F),YQ=await i(F);try{for await(let e of C(...YQ))yield e}catch(e){yield e}};if(VQ)return async function*(F){let C=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 DX(await C(...await i(F))),await Bun.sleep(10)};if(PQ)return async function(F){if(await J.body.validator.validate(F))return await I(F)(...await i(F));throw F.status(400,"Invalid request body")};return async function(F){return await I(F)(...await i(F))}},MQ=RX(J.params??[],(I)=>I.slug,(I)=>I.schema),zQ=J.middlewares.map((I)=>B.make(I));T.route(J.method,J.path,pQ(),{config:{},async transform(I){if(PQ&&!await J.body.validator.authorize(I))throw I.status(401,"Unauthorized");return g(zQ,I,"onTransform")},beforeHandle(I){return g(zQ,I,"onBeforeHandle")},afterHandle(I){return g(zQ,I,"onAfterHandle")},afterResponse(I){return g(zQ,I,"onAfterResponse")},detail:{tags:R.tags,description:J.description,operationId:J.operationId},body:PQ?J.body?.validator?.schema:J.body?.schema,response:J.response,params:LQ(MQ)?void 0:SQ.Object(MQ)})}return T}Reflect.defineMetadata(H.elysiaPlugin,M,V)}},A.sse=(R={})=>{let{path:V="/",...M}=R;return A.custom({method:"elysium:SSE",path:V,...M})},A.get=(R={})=>{let{path:V="/",...M}=R;return A.custom({method:"GET",path:V,...M})},A.post=(R={})=>{let{path:V="/",...M}=R;return A.custom({method:"POST",path:V,...M})},A.put=(R={})=>{let{path:V="/",...M}=R;return A.custom({method:"PUT",path:V,...M})},A.del=(R={})=>{let{path:V="/",...M}=R;return A.custom({method:"DELETE",path:V,...M})},A.patch=(R={})=>{let{path:V="/",...M}=R;return A.custom({method:"PATCH",path:V,...M})},A.head=(R={})=>{let{path:V="/",...M}=R??{};return A.custom({method:"HEAD",path:V,...M})},A.options=(R={})=>{let{path:V="/",...M}=R;return A.custom({method:"OPTIONS",path:V,...M})},A.trace=(R={})=>{let{path:V="/",...M}=R;return A.custom({method:"TRACE",path:V,...M})},A.custom=({path:R="/",...V})=>{return function(M,T,d){process.nextTick(()=>{BX({path:R,handler:d.value,target:M,propertyKey:T,...V})})}},A.onRequest=()=>{return function(R,V,M){let T=Reflect.getMetadata("http:onRequest",R.constructor)??{};T.handler=M.value,Reflect.defineMetadata("http:onRequest",T,R.constructor)}},A.context=()=>{return function(R,V,M){Reflect.defineMetadata("http:rawContext",{index:M},R,V)}},A.param=(R,V)=>{return function(M,T,d){let r=Reflect.getMetadata("http:params",M,T)??[];r.push({slug:R,schema:V??SQ.String(),index:d}),Reflect.defineMetadata("http:params",r,M,T)}},A.query=(R)=>{return function(V,M,T){Reflect.defineMetadata("http:query",{schema:R,index:T},V,M)}},A.body=(R)=>{return function(V,M,T){if(typeof R==="function")Reflect.defineMetadata("http:body",{validator:R,index:T},V,M);else Reflect.defineMetadata("http:body",{schema:R,index:T},V,M)}},A.decorate=(R)=>{return()=>{return function(V,M,T){let d=Reflect.getMetadata("http:customDecorators",V,M)??[];d.push({handler:R,index:T}),Reflect.defineMetadata("http:customDecorators",d,V,M)}}}))(hQ||={});IQ();class bQ extends _Q{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{Elysia as VX}from"elysia";import{assign as MX}from"radash";y();class qQ{static register(Q={}){return function(X){async function $(z){console.log(`Registering module ${X.name}`),await p();let Y=MX({controllers:[]},Q),Z=new VX({name:X.name,prefix:Q.prefix});Z.resolve({as:"local"},()=>({module:z}));let U=Reflect.getMetadata(H.middlewares,X)??[];a(U,Z);for(let L of Y.controllers){let K=Reflect.getMetadata(H.elysiaPlugin,L);if(K===void 0)console.error(`Invalid controller class ${L.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 Z.use(await K())}return Z}Reflect.defineMetadata(H.elysiaPlugin,$,X)}}beforeRegister(){return Promise.resolve()}afterRegister(){return Promise.resolve()}}v();import{Elysia as AX}from"elysia";v();y();var yQ;((q)=>(q.controller=(U)=>{return function(L){async function K(){console.log(`Registering Websocket route for ${U.path} using ${L.name}`),await p();let G=B.make(L),D=Reflect.getMetadata(H.websocket,L)??{},W=D.open?.bind(G),P=D.close?.bind(G),_=D.message?.bind(G),O=D.drain?.bind(G),j=D.error?.bind(G)??((R)=>w.emit("elysium:error",R.error)),k=new AX;return k.ws(U.path,{open:W,close:P,message:_,drain:O,error:j,body:D.body,...U.options}),k}Reflect.defineMetadata(H.elysiaPlugin,K,L)}},q.onOpen=()=>{return function(U,L,K){let G=Reflect.getMetadata(H.websocket,U.constructor)??{};G.open=K.value,Reflect.defineMetadata(H.websocket,G,U.constructor)}},q.onClose=()=>{return function(U,L,K){let G=Reflect.getMetadata(H.websocket,U.constructor)??{};G.close=K.value,Reflect.defineMetadata(H.websocket,G,U.constructor)}},q.onMessage=(U)=>{return function(L,K,G){let D=Reflect.getMetadata(H.websocket,L.constructor)??{};D.message=G.value,D.body=U,Reflect.defineMetadata(H.websocket,D,L.constructor)}},q.onDrain=()=>{return function(U,L,K){let G=Reflect.getMetadata(H.websocket,U.constructor)??{};G.drain=K.value,Reflect.defineMetadata(H.websocket,G,U.constructor)}},q.onError=()=>{return function(U,L,K){let G=Reflect.getMetadata(H.websocket,U.constructor)??{};G.error=K.value,Reflect.defineMetadata(H.websocket,G,U.constructor)}}))(yQ||={});RQ();export{c0 as t,GQ as WorkerPool,OQ as Worker,yQ as Websocket,u as Wamp,JQ as ServiceScope,B as Service,bQ as RequestLoggerMiddleware,t as Redis,qQ as Module,_Q as Middleware,EQ as Job,S as InteractsWithConsole,xQ as HttpControllerScope,hQ as Http,w as Event,AQ as Env,BQ as ConsoleLogger,ZQ as ConsoleFormat,kQ as CommandArgumentType,CQ as Command,c as Application};
|
package/dist/redis.d.ts
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
import type { KeyvStoreAdapter } from 'cacheable';
|
|
2
|
-
import type { KeyvEntry, StoredData } from 'keyv';
|
|
3
|
-
import { EventEmitter } from 'node:events';
|
|
4
1
|
/**
|
|
5
2
|
* Properties used to create a new redis connection.
|
|
6
3
|
* @author Axel Nana <axel.nana@workbud.com>
|
|
@@ -8,87 +5,6 @@ import { EventEmitter } from 'node:events';
|
|
|
8
5
|
export type RedisConnectionProps = Bun.RedisOptions & {
|
|
9
6
|
url: string;
|
|
10
7
|
};
|
|
11
|
-
/**
|
|
12
|
-
* Keyv adapter for redis. This adapter is based on the Bun's Redis client.
|
|
13
|
-
* @author Axel Nana <axel.nana@workbud.com>
|
|
14
|
-
*/
|
|
15
|
-
export declare class KeyvRedis extends EventEmitter implements KeyvStoreAdapter {
|
|
16
|
-
#private;
|
|
17
|
-
constructor(props: {
|
|
18
|
-
/**
|
|
19
|
-
* The Redis connection to use.
|
|
20
|
-
*/
|
|
21
|
-
connection: string;
|
|
22
|
-
/**
|
|
23
|
-
* Namespace for the connection.
|
|
24
|
-
*/
|
|
25
|
-
namespace?: string;
|
|
26
|
-
/**
|
|
27
|
-
* Separator to use between namespace and key.
|
|
28
|
-
*/
|
|
29
|
-
keyPrefixSeparator?: string;
|
|
30
|
-
/**
|
|
31
|
-
* Number of keys to delete in a single batch.
|
|
32
|
-
*/
|
|
33
|
-
clearBatchSize?: number;
|
|
34
|
-
/**
|
|
35
|
-
* Enable Unlink instead of using Del for clearing keys. This is more performant but may not be supported by all Redis versions.
|
|
36
|
-
*/
|
|
37
|
-
useUnlink?: boolean;
|
|
38
|
-
/**
|
|
39
|
-
* Whether to allow clearing all keys when no namespace is set.
|
|
40
|
-
* If set to true and no namespace is set, iterate() will return all keys.
|
|
41
|
-
* Defaults to `false`.
|
|
42
|
-
*/
|
|
43
|
-
noNamespaceAffectsAll?: boolean;
|
|
44
|
-
});
|
|
45
|
-
get client(): Bun.RedisClient;
|
|
46
|
-
/**
|
|
47
|
-
* Get the options for the adapter.
|
|
48
|
-
*/
|
|
49
|
-
get opts(): {
|
|
50
|
-
namespace: string | undefined;
|
|
51
|
-
keyPrefixSeparator: string;
|
|
52
|
-
clearBatchSize: number;
|
|
53
|
-
noNamespaceAffectsAll: boolean;
|
|
54
|
-
dialect: string;
|
|
55
|
-
url: string;
|
|
56
|
-
};
|
|
57
|
-
/**
|
|
58
|
-
* Gets the namespace for the adapter. If undefined, it will not use a namespace including keyPrefixing.
|
|
59
|
-
* @default undefined
|
|
60
|
-
*/
|
|
61
|
-
get namespace(): string | undefined;
|
|
62
|
-
/**
|
|
63
|
-
* Sets the namespace for the adapter. If undefined, it will not use a namespace including keyPrefixing.
|
|
64
|
-
*/
|
|
65
|
-
set namespace(value: string | undefined);
|
|
66
|
-
get<Value>(key: string): Promise<StoredData<Value> | undefined>;
|
|
67
|
-
set(key: string, value: any, ttl?: number): Promise<void>;
|
|
68
|
-
setMany(values: Array<KeyvEntry>): Promise<void>;
|
|
69
|
-
delete(key: string): Promise<boolean>;
|
|
70
|
-
clear(): Promise<void>;
|
|
71
|
-
has(key: string): Promise<boolean>;
|
|
72
|
-
hasMany(keys: string[]): Promise<boolean[]>;
|
|
73
|
-
getMany<Value>(keys: string[]): Promise<Array<StoredData<Value | undefined>>>;
|
|
74
|
-
disconnect(): Promise<void>;
|
|
75
|
-
deleteMany(keys: string[]): Promise<boolean>;
|
|
76
|
-
iterator<Value>(namespace?: string): AsyncGenerator<Array<string | Awaited<Value> | undefined>, void>;
|
|
77
|
-
/**
|
|
78
|
-
* Helper function to create a key with a namespace.
|
|
79
|
-
* @param key The key to prefix.
|
|
80
|
-
* @param namespace The namespace to prefix the key with.
|
|
81
|
-
* @returns The key with the namespace such as 'namespace::key'.
|
|
82
|
-
*/
|
|
83
|
-
createKeyPrefix(key: string, namespace?: string): string;
|
|
84
|
-
/**
|
|
85
|
-
* Helper function to remove the namespace from a key.
|
|
86
|
-
* @param key The key to remove the namespace from.
|
|
87
|
-
* @param namespace The namespace to remove from the key.
|
|
88
|
-
* @returns The key without the namespace.
|
|
89
|
-
*/
|
|
90
|
-
getKeyWithoutPrefix(key: string, namespace?: string): string;
|
|
91
|
-
}
|
|
92
8
|
export declare namespace Redis {
|
|
93
9
|
/**
|
|
94
10
|
* Retrieves the client for a redis connection.
|
package/dist/websocket.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type { Route } from './http';
|
|
|
6
6
|
* Properties required when declaring a websocket controller using the `@websocket()` decorator.
|
|
7
7
|
* @author Axel Nana <axel.nana@workbud.com>
|
|
8
8
|
*/
|
|
9
|
-
export type WebsocketProps = {
|
|
9
|
+
export type WebsocketProps<TWebsocketData = any> = {
|
|
10
10
|
/**
|
|
11
11
|
* The path of the websocket route.
|
|
12
12
|
*/
|
|
@@ -14,7 +14,7 @@ export type WebsocketProps = {
|
|
|
14
14
|
/**
|
|
15
15
|
* The options for the websocket server.
|
|
16
16
|
*/
|
|
17
|
-
options?: ConditionalPick<Bun.WebSocketHandler
|
|
17
|
+
options?: ConditionalPick<Bun.WebSocketHandler<TWebsocketData>, Primitive | JsonObject>;
|
|
18
18
|
};
|
|
19
19
|
/**
|
|
20
20
|
* The websocket connection instance.
|
package/package.json
CHANGED
|
@@ -1,46 +1,45 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
]
|
|
2
|
+
"name": "@elysiumjs/core",
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"description": "A super-charged web framework for Bun, built on top of ElysiaJS.",
|
|
6
|
+
"private": false,
|
|
7
|
+
"author": "Workbud Technologies Inc.",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/workbud/elysium"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/workbud/elysium",
|
|
13
|
+
"scripts": {
|
|
14
|
+
"format": "prettier --write \"./src/**/*.ts\"",
|
|
15
|
+
"clean": "rimraf dist",
|
|
16
|
+
"build:js": "bun build ./src/index.ts --outdir ./dist --target bun --packages external --root ./src --minify",
|
|
17
|
+
"build:ts": "tsc",
|
|
18
|
+
"build": "bun run clean && bun run build:js && bun run build:ts",
|
|
19
|
+
"typecheck": "tsc --noEmit",
|
|
20
|
+
"prepublishOnly": "bun run build"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"elysium",
|
|
24
|
+
"framework",
|
|
25
|
+
"web",
|
|
26
|
+
"api",
|
|
27
|
+
"typescript"
|
|
28
|
+
],
|
|
29
|
+
"module": "dist/index.js",
|
|
30
|
+
"type": "module",
|
|
31
|
+
"types": "dist/index.d.ts",
|
|
32
|
+
"sideEffects": [
|
|
33
|
+
"./src/index.ts"
|
|
34
|
+
],
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@elysiajs/swagger": "^1.3.1",
|
|
37
|
+
"elysia": "^1.4.9",
|
|
38
|
+
"radash": "^12.1.1",
|
|
39
|
+
"reflect-metadata": "^0.2.2",
|
|
40
|
+
"wampy": "^7.2.0"
|
|
41
|
+
},
|
|
42
|
+
"trustedDependencies": [
|
|
43
|
+
"es5-ext"
|
|
44
|
+
]
|
|
46
45
|
}
|
package/.turbo/turbo-build.log
DELETED