@andrewcaires/api 5.2.3 → 5.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -0
- package/dist/index.cjs.js +2 -2
- package/dist/index.d.ts +394 -22
- package/dist/index.esm.js +2 -2
- package/package.json +14 -13
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v5.
|
|
2
|
+
* @andrewcaires/api v5.3.1
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2026 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
import{Use as e,UnauthorizedError as t,parameterFactory as i,Context as r,NotFoundError as n,InternalServerError as s,ValidationError as o,StatusCodes as d,BadRequestError as a,Application as l,Ctx as u,Headers as c,Session as p,Extends as v,Get as g,Query as y,Controller as h,Post as m,Validate as E,Body as _,App as f,Middleware as A,Delete as S,Put as O,Params as T,All as P,Upload as I}from"@andrewcaires/express";import{Env as w,Log as b,LogColor as C,Hash as R,sha256 as D}from"@andrewcaires/node";import{isUndefined as x,isFunction as L,includesArray as N,getConstructor as M,noop as k,uuidv7 as K,isString as j,clamp as B,merge as F,isArray as H,clone as U,forEachAsync as q,upperCamelCase as Y,uniqueArray as $,forEachSeries as W,sleep as G,EventEmitter as V,Validation as z,isDef as J,uniqueID as Q}from"@andrewcaires/utils.js";import{WebSocketServer as X}from"ws";import{Sequelize as Z,Hooks as ee,Column as te,Association as ie,Database as re,ModelName as ne,Version as se,Model as oe,Index as de,DefaultValue as ae,Op as le,Where as ue}from"@andrewcaires/sequelize";import{config as ce}from"dotenv";import{Store as pe}from"express-session";import{Trait as ve,Singleton as ge}from"@andrewcaires/decorator";import ye from"jsonwebtoken";import{hashSync as he,verify as me}from"@node-rs/argon2";import{existsSync as Ee,statSync as _e,readdirSync as fe,mkdirSync as Ae,lstatSync as Se,rmSync as Oe}from"fs";import{join as Te}from"path";function Pe(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var d=e.length-1;d>=0;d--)(n=e[d])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o}function Ie(e,t){return function(i,r){t(i,r,e)}}function we(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function be(e,t,i,r){return new(i||(i=Promise))(function(n,s){function o(e){try{a(r.next(e))}catch(e){s(e)}}function d(e){try{a(r.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,d)}a((r=r.apply(e,t||[])).next())})}var Ce;"function"==typeof SuppressedError&&SuppressedError,ce({quiet:!0});class Env extends w{}Ce=Env,Env.BASE_NAME=Ce.getString("BASE_NAME",""),Env.CONSOLE_ERROR=Ce.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=Ce.getString("DATABASE_URI","",!0),Env.DATABASE_LOG=Ce.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=Ce.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=Ce.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=Ce.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CROSS=Ce.getString("HTTP_CROSS",""),Env.HTTP_TLS_CA=Ce.getFile("HTTP_TLS_CA"),Env.HTTP_TLS_CRT=Ce.getFile("HTTP_TLS_CRT"),Env.HTTP_TLS_KEY=Ce.getFile("HTTP_TLS_KEY"),Env.MODEL_LIMIT=Ce.getInt("MODEL_LIMIT",10),Env.MODEL_LIMIT_MAX=Ce.getInt("MODEL_LIMIT_MAX",100),Env.PASSWORD_ALGORITHM=Ce.getInt("PASSWORD_ALGORITHM",2),Env.PASSWORD_MEMORY_COST=Ce.getInt("PASSWORD_MEMORY_COST",4096),Env.PASSWORD_PARALLELISM=Ce.getInt("PASSWORD_PARALLELISM",1),Env.PASSWORD_PEPPER=Ce.getString("PASSWORD_PEPPER",""),Env.PASSWORD_TIME_COST=Ce.getInt("PASSWORD_TIME_COST",3),Env.SLEEP_AUTH=Ce.getMs("SLEEP_AUTH","2s"),Env.SLEEP_FORGOT=Ce.getMs("SLEEP_FORGOT","5s"),Env.SLEEP_REGISTRY=Ce.getMs("SLEEP_REGISTRY","5s"),Env.TOKEN_CRT=Ce.getFile("TOKEN_CRT"),Env.TOKEN_KEY=Ce.getFile("TOKEN_KEY"),Env.TOKEN_TTL=Ce.getMs("TOKEN_TTL","1d"),Env.TOKEN_TYPE=Ce.getString("TOKEN_TYPE","bearer"),Env.API_BODYPARSER_STRICT=Ce.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=Ce.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=Ce.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=Ce.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_PORT=Ce.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=Ce.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_HYBRID=Ce.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=Ce.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=Ce.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=Ce.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=Ce.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=Ce.getString("API_KEY_HEADER","x-api-key"),Env.API_SESSION_NAME=Ce.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=Ce.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=Ce.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=Ce.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=Ce.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_TOKEN_FORGOT=Ce.getMs("API_TOKEN_FORGOT","1d"),Env.API_TOKEN_HEADER=Ce.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_RENEW=Ce.getMs("API_TOKEN_RENEW","1d"),Env.API_USER_HISTORY=Ce.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=Ce.getBool("API_WEBSOCKET_START",!1);const Re=new Z({uri:Env.DATABASE_URI,logging:!!Env.DATABASE_LOG&&(e=>b.console(C.Magenta,"sql",e)),prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE});var De,xe,Le;!function(e){e.CREATE="CREATE",e.DELETE="DELETE",e.UPDATE="UPDATE"}(De||(De={})),function(e){e.INFO="info",e.WARN="warn",e.ERROR="error"}(xe||(xe={})),function(e){e.ACTIVE="active",e.PENDING="pending",e.DISABLED="disabled",e.LOCKED="locked",e.ARCHIVED="archived"}(Le||(Le={}));const Ne=i=>r=>(n,s,o)=>{e(e=>be(void 0,void 0,void 0,function*(){var n;x(r)&&(r=L(e.controller.name)?e.controller.name():null===(n=e.controller.constructor)||void 0===n?void 0:n.name);const{permissions:s=[]}=e.req;if(s.includes(`${r}.${i}`))return e.next();e.error(new t("Access Denied"))}))(n,s,o)},Me=Ne("create"),ke=Ne("delete"),Ke=Ne("read"),je=Ne("update"),Be=(...i)=>(r,n,s)=>{e(e=>be(void 0,void 0,void 0,function*(){const{groups:r=[]}=e.req;if(N(i,r))return e.next();e.error(new t("Access Denied"))}))(r,n,s)},Fe=(...i)=>(r,n,s)=>{e(e=>be(void 0,void 0,void 0,function*(){const{permissions:r}=e.req;if(N(i,null!=r?r:[]))return e.next();e.error(new t("Access Denied"))}))(r,n,s)},He=()=>(i,r,n)=>{e(e=>be(void 0,void 0,void 0,function*(){yield(e=>be(void 0,void 0,void 0,function*(){var i,r,n,s;if(e.req.auth&&e.req.user)return e.next();const{[Env.API_KEY_HEADER]:o,[Env.API_TOKEN_HEADER]:d,"user-agent":a}=e.getHeaders(),l=e.getQuery(Env.API_KEY_HEADER),u=(null===(i=o||l)||void 0===i?void 0:i.toString())||"";let c=e.getCookie(Env.API_TOKEN_COOKIE);c=`${Env.TOKEN_TYPE} ${c}`;const[p,v]=null!==(n=null===(r=d||c)||void 0===r?void 0:r.split(" "))&&void 0!==n?n:["",""];if(!(u||v&&p.toLowerCase()==Env.TOKEN_TYPE))return e.error(new t("Invalid token"));const{authService:g,userService:y}=e.app,{auth:h,user:m}=null!==(s=yield(u?g.key(u.toString()):g.user(v)).catch(t=>{e.error(t)}))&&void 0!==s?s:{};if(!h||!m)return;if(!u&&h.user_agent&&h.user_agent!=a)return e.error(new t("Invalid token"));e.req.auth=h,e.req.user=m;const{groups:E,permissions:_}=yield y.getGroupsPermissions(m.id);e.req.groups=E,e.req.permissions=_,e.next()}))(e)}))(i,r,n)},Ue=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),qe=i(({ctx:e,key:t})=>{var i,r;return(null!==(r=null===(i=e.req)||void 0===i?void 0:i.groups)&&void 0!==r?r:[]).includes(t)}),Ye=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.groups)&&void 0!==i?i:[]}),$e=i(({ctx:e,key:t})=>{var i,r;return(null!==(r=null===(i=e.req)||void 0===i?void 0:i.permissions)&&void 0!==r?r:[]).includes(t)}),We=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.permissions)&&void 0!==i?i:[]}),Ge=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.user}),Ve=(e,t,i)=>{var n,s,o,d,a,l,u,c,p,v,g;const y=i.ctx instanceof r?i.ctx:null,h=null!==(n=null==y?void 0:y.id)&&void 0!==n?n:null,m=null!==(a=null!==(d=null===(o=null===(s=null==y?void 0:y.req)||void 0===s?void 0:s.user)||void 0===o?void 0:o.id)&&void 0!==d?d:i.user_id)&&void 0!==a?a:null,E={type:e,model:null!==(l=null==t?void 0:t.getTableName())&&void 0!==l?l:null,source:null!==(u=Env.BASE_NAME)&&void 0!==u?u:"",request_id:h,user_id:m};return y?Object.assign(Object.assign({},E),{full_url:null!==(c=y.getUrl())&&void 0!==c?c:"",ip_address:null!==(p=y.getIp())&&void 0!==p?p:"",user_agent:null!==(g=null===(v=y.req)||void 0===v?void 0:v.headers["user-agent"])&&void 0!==g?g:""}):E},ze=e=>{const t=M(e),i=t.primaryKeyAttribute;return{model:t,record_id:i?e.getDataValue(i):null}},Je={afterCreate:(e,t)=>be(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=ze(e);yield ot.create(Object.assign(Object.assign({},Ve(De.CREATE,i,t)),{record:r,currently:e.toJSON()})).catch(b.catch)}),afterUpdate:(e,t)=>be(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=ze(e),n={},s={},o=e.changed();o&&o.length&&o.forEach(t=>{n[t]=e.getDataValue(t),s[t]=e.previous(t)}),yield ot.create(Object.assign(Object.assign({},Ve(De.UPDATE,i,t)),{record:r,currently:n,previously:s})).catch(b.catch)}),afterDestroy:(e,t)=>be(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=ze(e);yield ot.create(Object.assign(Object.assign({},Ve(De.DELETE,i,t)),{record:r,currently:e.toJSON()})).catch(b.catch)})},Qe=e=>(x(e)&&(e=Env.DATABASE_AUDIT),ee(e?Je:{}));let Xe=class RegisterModel extends oe{};Pe([te.Id(7),we("design:type",String)],Xe.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],Xe.prototype,"secret",void 0),Pe([te.FullDate(),we("design:type",Number)],Xe.prototype,"expired_at",void 0),Pe([te.Boolean(),we("design:type",Boolean)],Xe.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],Xe.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],Xe.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],Xe.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],Xe.prototype,"user_id",void 0),Xe=Pe([re(Re),ne("register"),se("5.2.0")],Xe);let Ze=class UserAuthModel extends oe{};Pe([te.Id(7),we("design:type",String)],Ze.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],Ze.prototype,"secret",void 0),Pe([te.String(),we("design:type",String)],Ze.prototype,"ip_address",void 0),Pe([te.String(),we("design:type",String)],Ze.prototype,"user_agent",void 0),Pe([te.FullDate(),we("design:type",Object)],Ze.prototype,"revoked_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],Ze.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],Ze.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],Ze.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],Ze.prototype,"user_id",void 0),Ze=Pe([re(Re),ne("users_auth"),se("5.2.0")],Ze);let et=class PermissionModel extends oe{};Pe([te.Id(7),we("design:type",String)],et.prototype,"id",void 0),Pe([te.String(),de(),we("design:type",String)],et.prototype,"name",void 0),Pe([te.Text(),we("design:type",String)],et.prototype,"description",void 0),Pe([te.Boolean(),we("design:type",Boolean)],et.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],et.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],et.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],et.prototype,"deleted_at",void 0),Pe([ie.HasMany(()=>tt),we("design:type",Array)],et.prototype,"groups_permissions",void 0),et=Pe([re(Re),ne("permission"),Qe(),se("5.2.1")],et);let tt=class GroupPermissionModel extends oe{};Pe([te.Id(7),we("design:type",String)],tt.prototype,"id",void 0),Pe([te.CreatedAt(),we("design:type",Date)],tt.prototype,"created_at",void 0),Pe([ie.BelongsTo(()=>it),we("design:type",String)],tt.prototype,"group_id",void 0),Pe([ie.BelongsTo(()=>et),we("design:type",String)],tt.prototype,"permission_id",void 0),tt=Pe([re(Re),ne("groups_permissions"),Qe(),se("5.2.0")],tt);let it=class GroupModel extends oe{};Pe([te.Id(7),we("design:type",String)],it.prototype,"id",void 0),Pe([te.String(),de(),we("design:type",String)],it.prototype,"name",void 0),Pe([te.Text(),we("design:type",String)],it.prototype,"description",void 0),Pe([te.Boolean(),we("design:type",Boolean)],it.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],it.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],it.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],it.prototype,"deleted_at",void 0),Pe([ie.HasMany(()=>rt),we("design:type",Array)],it.prototype,"users_groups",void 0),Pe([ie.HasMany(()=>tt),we("design:type",Array)],it.prototype,"groups_Permission",void 0),it=Pe([re(Re),ne("group"),Qe(),se("5.2.1")],it);let rt=class UserGroupModel extends oe{};Pe([te.Id(7),we("design:type",String)],rt.prototype,"id",void 0),Pe([te.CreatedAt(),we("design:type",Date)],rt.prototype,"created_at",void 0),Pe([ie.BelongsTo(()=>it),we("design:type",String)],rt.prototype,"group_id",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],rt.prototype,"user_id",void 0),rt=Pe([re(Re),ne("users_groups"),Qe(),se("5.2.0")],rt);let nt=class UserPasswordModel extends oe{};Pe([te.Id(7),we("design:type",String)],nt.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],nt.prototype,"hash",void 0),Pe([te.FullDate(),we("design:type",Object)],nt.prototype,"revoked_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],nt.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],nt.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],nt.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],nt.prototype,"user_id",void 0),nt=Pe([re(Re),ne("users_password"),Qe(),se("5.2.0")],nt);let st=class UserModel extends oe{};Pe([te.Id(7),we("design:type",String)],st.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],st.prototype,"name",void 0),Pe([te.String(),we("design:type",String)],st.prototype,"username",void 0),Pe([te.String(),we("design:type",String)],st.prototype,"email",void 0),Pe([te.Text(),we("design:type",String)],st.prototype,"notes",void 0),Pe([te.Enum(Le),ae(Le.ACTIVE),we("design:type",String)],st.prototype,"status",void 0),Pe([te.Json(),ae(()=>({})),we("design:type",Object)],st.prototype,"metadata",void 0),Pe([te.CreatedAt(),we("design:type",Date)],st.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],st.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],st.prototype,"deleted_at",void 0),Pe([ie.HasMany(()=>ot),we("design:type",Array)],st.prototype,"audits",void 0),Pe([ie.HasMany(()=>Ze),we("design:type",Array)],st.prototype,"users_auths",void 0),Pe([ie.HasMany(()=>Xe),we("design:type",Array)],st.prototype,"registers",void 0),Pe([ie.HasMany(()=>rt),we("design:type",Array)],st.prototype,"users_groups",void 0),Pe([ie.HasMany(()=>nt),we("design:type",Array)],st.prototype,"users_passwords",void 0),st=Pe([re(Re),ne("user"),Qe(),se("5.2.0")],st);let ot=class AuditModel extends oe{};Pe([te.Id(7),we("design:type",String)],ot.prototype,"id",void 0),Pe([te.Enum(De),we("design:type",String)],ot.prototype,"type",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"model",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"record",void 0),Pe([te.Json(),we("design:type",Object)],ot.prototype,"currently",void 0),Pe([te.Json(),we("design:type",Object)],ot.prototype,"previously",void 0),Pe([te.String(36),we("design:type",String)],ot.prototype,"request_id",void 0),Pe([te.Text(),we("design:type",String)],ot.prototype,"full_url",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"ip_address",void 0),Pe([te.Text(),we("design:type",String)],ot.prototype,"user_agent",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"source",void 0),Pe([te.FullDate(),we("design:type",Object)],ot.prototype,"reverted_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],ot.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],ot.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],ot.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],ot.prototype,"user_id",void 0),ot=Pe([re(Re),ne("audit"),se("5.2.0")],ot);let dt=class ConfigModel extends oe{};Pe([te.Id(7),we("design:type",String)],dt.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],dt.prototype,"key",void 0),Pe([te.Text(),we("design:type",String)],dt.prototype,"value",void 0),Pe([te.CreatedAt(),we("design:type",Date)],dt.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],dt.prototype,"updated_at",void 0),dt=Pe([re(Re),ne("configs"),se("5.2.0")],dt);let at=class ForgotModel extends oe{};Pe([te.Id(7),we("design:type",String)],at.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],at.prototype,"secret",void 0),Pe([te.FullDate(),we("design:type",Number)],at.prototype,"expired_at",void 0),Pe([te.Boolean(),we("design:type",Boolean)],at.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],at.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],at.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],at.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],at.prototype,"user_id",void 0),at=Pe([re(Re),ne("forgot"),se("5.2.0")],at);let lt=class LogModel extends oe{};Pe([te.Id(7),we("design:type",String)],lt.prototype,"id",void 0),Pe([te.Enum(xe),ae(xe.INFO),we("design:type",String)],lt.prototype,"level",void 0),Pe([te.Text(),we("design:type",String)],lt.prototype,"message",void 0),Pe([te.String(),we("design:type",String)],lt.prototype,"source",void 0),Pe([te.CreatedAt(),we("design:type",Date)],lt.prototype,"created_at",void 0),lt=Pe([re(Re),ne("log"),se("5.2.0")],lt);let ut=class MigrationModel extends oe{};Pe([te.Id(7),we("design:type",String)],ut.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],ut.prototype,"model",void 0),Pe([te.String(),we("design:type",String)],ut.prototype,"version",void 0),Pe([te.CreatedAt(),we("design:type",Date)],ut.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],ut.prototype,"updated_at",void 0),ut=Pe([re(Re),ne("migration"),se("5.2.0")],ut);let ct=class SessionModel extends oe{};Pe([te.Id(7),we("design:type",String)],ct.prototype,"id",void 0),Pe([te.Json(),we("design:type",Object)],ct.prototype,"data",void 0),Pe([te.FullDate(),we("design:type",Date)],ct.prototype,"expired_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],ct.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],ct.prototype,"updated_at",void 0),ct=Pe([re(Re),ne("session"),se("5.2.0")],ct);class Log{static error(e,t,i){return be(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,i)})}static info(e,t,i){return be(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,i)})}static warn(e,t,i){return be(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,i)})}static writeRaw(e,t,i,r){return be(this,void 0,void 0,function*(){var n;r&&b.console(null!==(n=this.colors[e])&&void 0!==n?n:C.White,e,t),Re&&(yield lt.create({level:e,message:t,source:null!=i?i:""}).catch(b.catch))})}}Log.colors={error:C.Red,info:C.Cyan,warn:C.Yellow};class Loggable{get log(){return e=>Loggable.logInfo(this,e)}static get log(){return e=>this.logInfo(this,e)}get error(){return e=>Loggable.logError(this,e)}static get error(){return e=>this.logError(this,e)}static logError(e,t){var i,r;Log.error(null!==(r=null!==(i=null==t?void 0:t.message)&&void 0!==i?i:t)&&void 0!==r?r:"",this.source(e),Env.CONSOLE_ERROR)}static logInfo(e,t){Log.info(null!=t?t:"",this.source(e),Env.CONSOLE_ERROR)}static source(e){var t,i,r;const n=null!==(r=null!==(i=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)&&void 0!==i?i:null==e?void 0:e.name)&&void 0!==r?r:"null";return Env.BASE_NAME?`${Env.BASE_NAME}.${n}`:n}}class Config extends Loggable{static all(e){return be(this,void 0,void 0,function*(){var t;const i=null!==(t=yield dt.findAll({where:(null==e?void 0:e.length)?{key:{[le.in]:e}}:{}}).catch(this.error))&&void 0!==t?t:[];return Object.fromEntries(i.map(e=>[e.key,e.value]))})}static del(e){return be(this,void 0,void 0,function*(){return((yield dt.destroy({where:{key:e}}).catch(this.error))||0)>0})}static get(e){return be(this,arguments,void 0,function*(e,t=""){const[i]=(yield dt.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return i?i.value:t})}static set(e,t){return be(this,void 0,void 0,function*(){const[i,r]=(yield dt.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];i&&!r&&(i.value=t,yield i.save().catch(this.error))})}}class SessionStore extends pe{constructor(){super(),this.all=e=>be(this,void 0,void 0,function*(){e=e||k;const t=yield ct.findAll({attributes:["id","expired_at"],where:{expired_at:{[le.gte]:new Date}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.id)),e()}),this.clear=e=>be(this,void 0,void 0,function*(){yield ct.destroy().catch(b.catch),e&&e()}),this.destroy=(e,t)=>be(this,void 0,void 0,function*(){yield ct.destroy({where:{id:e}}).catch(b.catch),t&&t()}),this.expired=()=>be(this,void 0,void 0,function*(){yield ct.destroy({where:{expired_at:{[le.lt]:new Date}}}).catch(b.catch)}),this.get=(e,t)=>be(this,void 0,void 0,function*(){t=t||k;const i=yield ct.findOne({where:{id:e,expired_at:{[le.gte]:new Date}}}).catch(e=>(t(e),null));if(i){if(i.data.cookie){if(new Date(i.data.cookie.expires).getTime()<=Date.now())return yield i.destroy().catch(b.catch),void t(null)}t(null,i.data)}else t(null)}),this.length=e=>be(this,void 0,void 0,function*(){e&&e(null,(yield ct.count().catch(b.catch))||0)}),this.set=(e,t,i)=>be(this,void 0,void 0,function*(){i=i||k;const r=new Date;r.setTime(r.getTime()+Env.API_SESSION_LIFETIME);const[n,s]=(yield ct.findOrCreate({where:{id:e},defaults:{id:e,data:t,expired_at:r}}).catch(b.catch))||[];n?(s||(n.data=t,n.expired_at=r,yield n.save().catch(b.catch)),i()):i()}),setInterval(this.expired,6e4)}}let pt=class Service{};pt=Pe([ve(Loggable)],pt);let vt=class AuthService extends pt{constructor(){super(...arguments),this.userAttributes={exclude:["username","notes","deleted_at"]}}create(e){return be(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new n("TOKEN_KEY not found");const{id:t}=e,i=K(),r=yield Ze.create({secret:i,user_id:t}).catch(this.error);if(!r)throw new s;return{auth:r,token:ye.sign({id:t,secret:i},Env.TOKEN_KEY,this.options())}})}destroy(e){return be(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return be(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new n("TOKEN_KEY not found");const{decode:i}=yield this.verify(e,Env.API_TOKEN_RENEW/1e3);if(!i)throw new t("Invalid token");const{id:r,secret:s}=i;if(r&&s){const e=yield st.findOne({where:{id:r,status:Le.ACTIVE}}).catch(this.error);if(e){const t=yield Ze.findOne({where:{secret:s,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at){t.secret=K(),yield t.save().catch(this.error);return{auth:t,token:ye.sign({id:r,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t("Invalid token")})}user(e){return be(this,void 0,void 0,function*(){const{decode:i}=yield this.verify(e);if(!i)throw new t("Invalid token");const{id:r,secret:n}=i;if(r&&n){const e=yield st.findOne({attributes:this.userAttributes,where:{id:r,status:Le.ACTIVE}}).catch(this.error);if(e){const t=yield Ze.findOne({where:{secret:n,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at)return{auth:t,user:e}}}throw new t("Invalid token")})}options(){return{algorithm:"RS256",expiresIn:`${Env.TOKEN_TTL}ms`}}verify(e,i){return be(this,void 0,void 0,function*(){if(!Env.TOKEN_CRT)throw new n("TOKEN_CRT not found");if(!e||e.split(".").length<3)throw new t("Invalid token");try{return{decode:ye.verify(e,Env.TOKEN_CRT,{clockTolerance:i})}}catch(e){throw new t("Invalid token")}})}key(e){return be(this,void 0,void 0,function*(){if(!e)throw new t("Invalid token");const i=yield st.findOne({attributes:this.userAttributes,where:{token:e,status:Le.ACTIVE}}).catch(this.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield Ze.findOrCreate({where:{secret:t,user_id:i.id},defaults:{secret:t,user_id:i.id}}).catch(this.error))||[];if(r)return r.revoked_at&&(r.revoked_at=null,yield r.save().catch(this.error)),{auth:r,user:i}}throw new t("Invalid token")})}};vt=Pe([ge()],vt);class ModelService extends pt{constructor(e,t){var i,r;super(),this.attributes=[],this.permissions=[],this.search=[],this.model=e,(null==t?void 0:t.permissions)&&(this.permissions=t.permissions);const n=Object.keys(e.getAttributes());this.attributes=this.filterAttributes(n,null!==(i=null==t?void 0:t.attributes)&&void 0!==i?i:[]),this.search=this.filterAttributes(n,null!==(r=null==t?void 0:t.search)&&void 0!==r?r:this.attributes)}applySelect(e,t,i){if(!t)return;const r=null==e?void 0:e.getQuery(i?`${i}_select`:"select"),n=t.attributes,s=e=>n.includes(e);t.attributes=[],j(r)&&r.length&&t.attributes.push(...r.split(/\s*,\s*/g).filter(s)),t.attributes.length||(t.attributes=n)}applyOrders(e,t){if(!t)return;const i=null==e?void 0:e.getQuery("asc"),r=null==e?void 0:e.getQuery("desc"),n=[],s=t.attributes,o=e=>s.includes(e);j(i)&&i.length&&n.push(...i.split(/\s*,\s*/g).filter(o).map(e=>[e,"ASC"])),j(r)&&r.length&&n.push(...r.split(/\s*,\s*/g).filter(o).map(e=>[e,"DESC"])),n.length&&(t.order=n)}applyPagination(e,t){if(!t)return;const i=null==e?void 0:e.getQuery("limit"),r=null==e?void 0:e.getQuery("offset");x(t.limit)&&(t.limit=Env.MODEL_LIMIT,j(i)&&(t.limit=parseInt(i)||0),t.limit=B(t.limit,-1,Env.MODEL_LIMIT_MAX)),t.limit<0&&(t.limit=void 0),j(r)&&(t.offset=parseInt(r)||0,t.offset<0&&(t.offset=void 0))}applySearch(e,t){var i;if(!t)return;const r=null==e?void 0:e.getQuery("search");r&&j(r)&&(t.where=Object.assign(Object.assign({},null!==(i=t.where)&&void 0!==i?i:{}),{[le.or]:this.search.map(e=>({[e]:{[le.substring]:r}}))}))}applyWhere(e,t,i){var r,n;if(!t)return null;const s=null==e?void 0:e.getQuery(i?`${i}_where`:"where");if(!j(s))return null;const d=t.attributes,a=ue.parse(d,s);return x(a.error)?(t.where=Object.assign(Object.assign({},null!==(r=t.where)&&void 0!==r?r:{}),null!==(n=a.value)&&void 0!==n?n:{}),null):new o(a.error.join(", "))}countAll(e){return be(this,void 0,void 0,function*(){var t,i;const{ctx:r,options:n={}}=e,s=F({},n);s.attributes=this.getAttributes(null!==(t=null==s?void 0:s.attributes)&&void 0!==t?t:[]),this.applySearch(r,s);const o=this.applyWhere(r,s);if(o)return null==r||r.error(o),0;this.applySelect(r,s);const a=null!==(i=yield this.model.count(Object.assign(Object.assign({},s),{distinct:!!s.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error))&&void 0!==i?i:0;return null==r||r.prepare(d.OK,{count:a}),a})}create(e){return be(this,void 0,void 0,function*(){var t,i;const{body:r={},ctx:n,options:o={}}=e,a=F({},o),l=yield this.model.create(Object.assign({},F({},null!==(i=null===(t=null==n?void 0:n.req)||void 0===t?void 0:t.body)&&void 0!==i?i:{},r)),Object.assign(Object.assign({},a),{ctx:n})).catch(this.error);if(!l)return null==n||n.error(new s),null;const{primaryKeyAttribute:u}=this.model;return null==n||n.prepare(d.OK,{[u]:l.getDataValue(u)}),l})}delete(e){return be(this,void 0,void 0,function*(){var t,i;const{ctx:r,id:s,options:o={}}=e,{primaryKeyAttribute:d}=this.model,l=null!==(t=null==r?void 0:r.getParam(d))&&void 0!==t?t:s;if(x(l))return null==r||r.error(new a),0;const u=F({},o),c=yield this.model.destroy(Object.assign(Object.assign(Object.assign({},u),{where:{[le.and]:Object.assign({[d]:l},null!==(i=null==u?void 0:u.where)&&void 0!==i?i:{})},individualHooks:!0}),{ctx:r})).catch(this.error);return c?(null==r||r.success("OK"),c):(null==r||r.error(new n),0)})}filterAttributes(e,t){if(H(t))return t.length?t.filter(t=>j(t)&&e.includes(t)):e;const{exclude:i,include:r}=t,n=x(r)?e:r.filter(t=>j(t)&&e.includes(t)),s=null!=i?i:[];return s.length?n.filter(e=>!s.includes(e)):n}findAll(e){return be(this,void 0,void 0,function*(){var t,i;const{ctx:r,callback:n,options:s={},query:o=!0}=e,a=F({},s);if(a.attributes=this.getAttributes(null!==(t=null==a?void 0:a.attributes)&&void 0!==t?t:[]),o&&this.applySelect(r,a),this.applyOrders(r,a),this.applyPagination(r,a),(null!==(i=null==a?void 0:a.limit)&&void 0!==i?i:0)>Env.MODEL_LIMIT_MAX&&(a.limit=Env.MODEL_LIMIT_MAX),this.applySearch(r,a),o){const e=this.applyWhere(r,a);if(e)return null==r||r.error(e),{count:0,records:[]}}const[l,u]=yield Promise.all([this.model.count(Object.assign(Object.assign({},a),{distinct:!!a.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error).then(e=>null!=e?e:0),this.model.findAll(a).catch(this.error).then(e=>null!=e?e:[])]),c={count:l,records:n?yield n(u):u};return null==r||r.prepare(d.OK,c),c})}findOne(e){return be(this,void 0,void 0,function*(){var t,i,r;const{callback:s,ctx:o,id:l,options:u={},query:c=!0}=e,{primaryKeyAttribute:p}=this.model,v=null!==(t=null==o?void 0:o.getParam(p))&&void 0!==t?t:l;if(x(v))return null==o||o.error(new a),null;const g=F({},u);g.attributes=this.getAttributes(null!==(i=null==g?void 0:g.attributes)&&void 0!==i?i:[]),c&&this.applySelect(o,g);const y=yield this.model.findOne(Object.assign(Object.assign({},g),{where:{[le.and]:Object.assign({[p]:v},null!==(r=null==g?void 0:g.where)&&void 0!==r?r:{})}})).catch(this.error);return y?(null==o||o.prepare(d.OK,s?yield s(y):y.toJSON()),y):(null==o||o.error(new n),null)})}getAttributes(e){return this.filterAttributes(this.attributes,e)}include(e,t){var i;const r=U(t),{ctx:n}=null!=t?t:{};r.attributes=this.filterAttributes(Object.keys(e.getAttributes()),null!==(i=r.attributes)&&void 0!==i?i:[]),this.applySearch(n,r);const s=this.applyWhere(n,r,t.name);return s?(null==n||n.error(s),null):(this.applySelect(n,r,t.name),Object.assign({model:e},r))}name(){return this.model.tableName}sync(){return be(this,void 0,void 0,function*(){if(!this.permissions.length)return;const e=this.name().toLowerCase(),t={description:"",active:!0};yield q(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=Y(e.replace(/_/g," ")," ");yield et.findOrCreate({where:{key:r},defaults:Object.assign({name:`${n} ${Y(i," ")}`,key:r,tags:n},t)})}))})}update(e){return be(this,void 0,void 0,function*(){var t,i,r,n,s;const{ctx:o,body:d,id:l,options:u={}}=e,{primaryKeyAttribute:c}=this.model,p=null!==(t=null==o?void 0:o.getParam(c))&&void 0!==t?t:l;if(x(p))return null==o||o.error(new a),!1;const v=F({},u),[g]=null!==(s=yield this.model.update(Object.assign({},F({},null!==(r=null===(i=null==o?void 0:o.req)||void 0===i?void 0:i.body)&&void 0!==r?r:{},null!=d?d:{})),Object.assign(Object.assign(Object.assign({},v),{where:{[le.and]:Object.assign({[c]:p},null!==(n=null==v?void 0:v.where)&&void 0!==n?n:{})},individualHooks:!0}),{ctx:o})).catch(this.error))&&void 0!==s?s:[];return g?(null==o||o.success("OK"),!0):(null==o||o.success("Record not changed"),!1)})}}let gt=class UserService extends pt{constructor(){super(...arguments),this.hashOptions={algorithm:Env.PASSWORD_ALGORITHM,memoryCost:Env.PASSWORD_MEMORY_COST,parallelism:Env.PASSWORD_PARALLELISM,timeCost:Env.PASSWORD_TIME_COST}}createPassword(e,t,i){return be(this,void 0,void 0,function*(){yield nt.update({revoked_at:new Date},{where:{revoked_at:null,user_id:e}}).catch(this.error);const r=he(t+Env.PASSWORD_PEPPER,this.hashOptions);yield nt.create({hash:r,user_id:e},Object.assign({},{ctx:i})).catch(this.error)})}findAllPermission(e){return be(this,void 0,void 0,function*(){var t;return null!==(t=yield et.findAll({attributes:["name"],where:{active:!0},include:[{association:"groups_permissions",required:!0,include:[{association:"group",required:!0,attributes:["id","name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:{user_id:e}}]}]}]}).catch(this.error))&&void 0!==t?t:[]})}getGroups(e){return be(this,void 0,void 0,function*(){var t;return(null!==(t=yield it.findAll({attributes:["name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:{user_id:e}}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.name)})}getGroupsPermissions(e){return be(this,void 0,void 0,function*(){const t=[],i=[];return(yield this.findAllPermission(e)).forEach(e=>{i.push(e.name),e.groups_permissions.forEach(e=>t.push(e.group.name))}),{groups:$(t),permissions:$(i)}})}getPermissions(e){return be(this,void 0,void 0,function*(){return(yield this.findAllPermission(e)).map(e=>e.name)})}};gt=Pe([ge()],gt);class Application extends l{constructor(e,t){super(e,F({},{cross:!!Env.HTTP_CROSS&&("*"===Env.HTTP_CROSS||{origin:Env.HTTP_CROSS.split(",")}),hybrid:Env.API_HTTP_HYBRID,json:{strict:Env.API_BODYPARSER_STRICT,inflate:Env.API_BODYPARSER_INFLATE,limit:Env.API_BODYPARSER_LIMIT,type:Env.API_BODYPARSER_TYPE},notfound:Env.API_HTTP_NOTFOUND,path:Env.API_HTTP_PATH,port:Env.API_HTTP_PORT,public:Env.API_HTTP_PUBLIC,redirect:Env.API_HTTP_REDIRECT,session:{store:new SessionStore,name:Env.API_SESSION_NAME,secret:Env.API_SESSION_SECRET,cookie:{maxAge:Env.API_SESSION_LIFETIME},genid:K},tls:{ca:Env.HTTP_TLS_CA,cert:Env.HTTP_TLS_CRT,key:Env.HTTP_TLS_KEY}},null!=t?t:{})),this.hash=new R(Env.API_KEY_HASH)}error(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.error(e.message,t,Env.CONSOLE_ERROR)}log(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return be(this,void 0,void 0,function*(){yield Re.sync(),yield this.migrations(Re),yield W(this.controllers,e=>be(this,void 0,void 0,function*(){L(e.sync)&&(yield e.sync(this))})),this.authService=new vt,this.userService=new gt,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new X({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>be(this,void 0,void 0,function*(){t.url||(t.url=""),e.on("close",()=>{}),yield G(2e3)})))})}migrations(e){return be(this,void 0,void 0,function*(){const t=[];yield W(Object.keys(e.models),i=>be(this,void 0,void 0,function*(){var r;const n=e.models[i],s=n.version();if(!s)return;const[o,d]=null!==(r=yield ut.findOrCreate({where:{model:n.tableName},defaults:{model:n.tableName,version:""}}).catch(this.error))&&void 0!==r?r:[];o&&(d||o.version!=s)&&(o.version=s,yield o.save().catch(this.error),t.push(n))})),yield W(t,e=>be(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}let yt=class BaseController extends V{constructor(){super(...arguments),this.permissions=[]}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}session(e,t,i){return be(this,void 0,void 0,function*(){i.auth&&i.user&&(i.user_agent?i.user_agent!=t&&i.regenerate(k):(i.user_agent=t,i.save(k))),e.next()})}sync(){return be(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=Y(e.replace(/_/g," ")," ");yield W(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield et.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${Y(i," ")}`,active:!0}})}))})}};Pe([Ie(0,u()),Ie(1,c("user-agent")),Ie(2,p()),we("design:type",Function),we("design:paramtypes",[r,String,Object]),we("design:returntype",Promise)],yt.prototype,"session",null),yt=Pe([ve(Loggable)],yt);let ht=class ModelController extends yt{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"],this.search=[]}countAll(e){return be(this,void 0,void 0,function*(){return yield this.service.countAll(e)})}create(e){return be(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return be(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return be(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return be(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}include(e,t){return this.service.include(e,t)}sync(){return be(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=Y(e.replace(/_/g," ")," ");yield W(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield et.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${Y(i," ")}`,active:!0}})})),this.service=new ModelService(this.model,{attributes:this.attributes.length?this.attributes:void 0,search:this.search.length?this.search:void 0})})}update(e){return be(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}};ht=Pe([v(yt)],ht);let mt=class AuditsController extends ht{constructor(){super(...arguments),this.model=ot,this.permissions=["read"]}all(e,t,i){return be(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this.findAll({ctx:e,options:{attributes:{exclude:["currently","previously"]},where:r,order:[["created_at","DESC"]]}})})}get(e){return be(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};Pe([g(),He(),Ke(),Ie(0,u()),Ie(1,y("type")),Ie(2,y("table")),we("design:type",Function),we("design:paramtypes",[r,String,String]),we("design:returntype",Promise)],mt.prototype,"all",null),Pe([g("/:id"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],mt.prototype,"get",null),mt=Pe([h("/audits"),v(ht)],mt);let Et=class AuthController extends yt{constructor(){super(...arguments),this.authService=new vt}login(e,i,r,n,s,o){return be(this,void 0,void 0,function*(){var d;yield G(Env.SLEEP_AUTH);const a=yield st.findOne({where:{[le.or]:[{email:r},{username:r}]}}).catch(this.error);if(!a)return e.error(new t("Invalid credentials")),o.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const l=yield nt.findOne({where:{revoked_at:null,user_id:a.id}}).catch(this.error);if(n+=Env.PASSWORD_PEPPER,!l||!(yield me(l.hash,n).catch(k)))return e.error(new t("Invalid credentials")),o.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const u=yield Xe.findOne({where:{active:!0,user_id:a.id}}).catch(this.error);if(u)return e.error(new t("Activation Required")),o.emit("auth.activation",{ctx:e,register:u,user:a}),void this.emit("auth.activation",{ctx:e,register:u,user:a});if(a.status!=Le.ACTIVE)return e.error(new t("Invalid credentials")),o.emit("auth.failure",{ctx:e,user:a}),void this.emit("auth.failure",{ctx:e,user:a});const{auth:c,token:p}=null!==(d=yield this.authService.create(a).catch(t=>{e.error(t),o.emit("auth.failure",{ctx:e}),this.emit("auth.failure",{ctx:e})}))&&void 0!==d?d:{};c&&p&&(c.user_agent=i,c.ip_address=e.getIp(),yield c.save().catch(this.error),Env.API_TOKEN_COOKIE_SET&&e.setCookie(Env.API_TOKEN_COOKIE,p,{maxAge:s?Env.TOKEN_TTL:void 0}),e.json({token:p}),o.emit("auth.login",{ctx:e,auth:c,user:a}),this.emit("auth.login",{ctx:e,auth:c,user:a}))})}logout(e,i,r,n){return be(this,void 0,void 0,function*(){if(yield this.authService.destroy(i))return Env.API_TOKEN_COOKIE_SET&&e.clearCookie(Env.API_TOKEN_COOKIE),e.success("OK"),n.emit("auth.logout",{auth:i,ctx:e,user:r}),void this.emit("auth.logout",{auth:i,ctx:e,user:r});e.error(new t("Access Denied"))})}renew(e,t,i,r){return be(this,void 0,void 0,function*(){var n;const{auth:s,token:o}=null!==(n=yield this.authService.renew(i).catch(t=>{e.error(t)}))&&void 0!==n?n:{};s&&o&&(s.user_agent=t,yield s.save().catch(this.error),e.json({token:o}),r.emit("auth.renew",{auth:s,ctx:e}),this.emit("auth.renew",{auth:s,ctx:e}))})}user(e,t){return be(this,void 0,void 0,function*(){const{groups:i,permissions:r,profile:n}=e.req;if(!i||!r)return e.error(new s);e.json(Object.assign(Object.assign({},t.toJSON()),{groups:i,permissions:r,profile:n}))})}};Pe([m("/login"),E(e=>({username:e.string().min(3).required(),password:e.string().min(5).required(),remember:e.boolean().parse().empty(!1)})),Ie(0,u()),Ie(1,c("user-agent")),Ie(2,_("username")),Ie(3,_("password")),Ie(4,_("remember")),Ie(5,f()),we("design:type",Function),we("design:paramtypes",[r,String,String,String,Boolean,Application]),we("design:returntype",Promise)],Et.prototype,"login",null),Pe([g("/logout"),He(),Ie(0,u()),Ie(1,Ue()),Ie(2,Ge()),Ie(3,f()),we("design:type",Function),we("design:paramtypes",[r,Ze,st,Application]),we("design:returntype",Promise)],Et.prototype,"logout",null),Pe([m("/renew"),E(e=>({token:e.string().required()})),Ie(0,u()),Ie(1,c("user-agent")),Ie(2,_("token")),Ie(3,f()),we("design:type",Function),we("design:paramtypes",[r,String,String,Application]),we("design:returntype",Promise)],Et.prototype,"renew",null),Pe([g(),g("/me"),He(),Ie(0,u()),Ie(1,Ge()),we("design:type",Function),we("design:paramtypes",[r,st]),we("design:returntype",Promise)],Et.prototype,"user",null),Et=Pe([h("/auth"),v(yt)],Et);let _t=class CrudController extends ht{constructor(){super(...arguments),this._crud={}}CrudArgumentsCountAll(e){return{ctx:e}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidateCreate(){return this._crud}CrudValidateUpdate(){return this._crud}add(e){return be(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return be(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}rows(e){return be(this,void 0,void 0,function*(){yield this.countAll(this.CrudArgumentsCountAll(e))})}del(e){return be(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return be(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return be(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validate(e,t){return be(this,void 0,void 0,function*(){var i,r;const n=z.object(t).parse(),{error:s,message:d,value:a}=yield n.validateAsync(null!==(r=null===(i=e.req)||void 0===i?void 0:i.body)&&void 0!==r?r:{});if(s)return e.error(new o(null!=d?d:s));e.req.body=a,e.next()})}validateCreate(e){return be(this,void 0,void 0,function*(){const t=this.CrudValidateCreate();if(t==this._crud)return e.error(new s);yield this.validate(e,t)})}validateUpdate(e){return be(this,void 0,void 0,function*(){const t=this.CrudValidateUpdate();if(t==this._crud)return e.error(new s);yield this.validate(e,t)})}};Pe([m(),He(),Me(),A("validateCreate"),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"add",null),Pe([g(),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"all",null),Pe([g("/count"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"rows",null),Pe([S("/:id"),He(),ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"del",null),Pe([g("/:id"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"get",null),Pe([O("/:id"),He(),je(),A("validateUpdate"),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"set",null),Pe([Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"validateCreate",null),Pe([Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"validateUpdate",null),_t=Pe([v(ht)],_t);let ft=class FilesController extends yt{constructor(){super(...arguments),this.directory=Env.API_HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return be(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=Te(this.directory,t);if(!Ee(i)||!_e(i).isDirectory())return e.error(new n);let r;return r=fe(i),r=r.map(e=>this.info(Te(i,e))),r=r.filter(J),Object.assign(Object.assign({},this.info(i)),{files:r})})}info(e){if(!Ee(e))return null;const t=_e(e),i=e.split("/").pop();e=e.replace(this.directory,"/").replace(/^\/\//,"/");const r=t.isDirectory();return{name:i,path:e.replace(/^\/\//,"/"),size:t.size,extension:r?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:r,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return be(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=Y(e.replace(/_/g," ")," ");yield W(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield et.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${Y(i," ")}`,active:!0}})}))})}};Pe([g("/path"),g("/path/*path"),He(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],ft.prototype,"files",null),ft=Pe([h("/files"),v(yt)],ft);let At=class ForgotController extends yt{check(e,t){return be(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.error(new n);i.secret=Q(),yield i.save(),e.json({token:i.secret})})}forgot(e,t,i){return be(this,void 0,void 0,function*(){yield G(Env.SLEEP_FORGOT);const r=t,s=yield st.findOne({where:{[le.or]:[{email:r},{username:t}]}}).catch(this.error);if(!s)return e.error(new n);const o=Q(),d=Date.now()+6e4*Env.API_TOKEN_FORGOT,a=yield at.create({token:o,timestamp:d,active:!0,user_id:s.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:a,user:s}),this.emit("forgot.send",{ctx:e,forgot:a,user:s})})}reset(e,t,i,r){return be(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i)return e.error(new n);i.active=!1,yield i.save().catch(this.error),yield i.user.save().catch(this.error),e.success("OK"),r.emit("forgot.reset",{ctx:e,user:i.user}),this.emit("forgot.reset",{ctx:e,user:i.user})})}find(e){return be(this,void 0,void 0,function*(){return yield at.findOne({where:{token:e,active:!0},include:[{association:"users",required:!0}]}).catch(this.error)})}};Pe([g("/check"),E(e=>({token:e.string().required()})),Ie(0,u()),Ie(1,_("token")),we("design:type",Function),we("design:paramtypes",[r,String]),we("design:returntype",Promise)],At.prototype,"check",null),Pe([m(),E(e=>({username:e.string().min(4).required()})),Ie(0,u()),Ie(1,_("username")),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,String,Application]),we("design:returntype",Promise)],At.prototype,"forgot",null),Pe([m("/reset"),E(e=>({token:e.string().required(),password:e.string().min(5).required()})),Ie(0,u()),Ie(1,_("token")),Ie(2,_("password")),Ie(3,f()),we("design:type",Function),we("design:paramtypes",[r,String,String,Application]),we("design:returntype",Promise)],At.prototype,"reset",null),At=Pe([h("/forgot"),v(yt)],At);let St=class GroupsController extends _t{constructor(){super(...arguments),this.model=it,this.schemaCreate={name:z.string().required(),description:z.string().empty(""),active:z.boolean().parse().required()},this.schemaUpdate={description:z.string().empty(),active:z.boolean().parse().empty()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}};St=Pe([h("/groups"),v(_t)],St);let Ot=class GroupsPermissionsController extends ht{constructor(){super(...arguments),this.model=tt,this.permissions=[]}all(e,t){return be(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{association:"permission"}]},callback:e=>e.map(e=>e.permission),query:!1})})}set(e,t,i){return be(this,void 0,void 0,function*(){const r=yield it.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new n);const s=r.id,o=[];yield W($(i),t=>be(this,void 0,void 0,function*(){var i;if(!(yield et.count({where:{id:t}})))return;const[r]=null!==(i=yield tt.findOrCreate(Object.assign({where:{group_id:s,permission_id:t},defaults:{group_id:s,permission_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];r&&o.push(t)})),yield tt.destroy(Object.assign({where:{group_id:s,permission_id:{[le.notIn]:o}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Pe([g("/:id/permissions"),He(),Ke("groups"),Ie(0,u()),Ie(1,T("id")),we("design:type",Function),we("design:paramtypes",[r,String]),we("design:returntype",Promise)],Ot.prototype,"all",null),Pe([O("/:id/permissions"),He(),je("groups"),E(e=>({permissions:e.array(e.string())})),Ie(0,u()),Ie(1,T("id")),Ie(2,_("permissions")),we("design:type",Function),we("design:paramtypes",[r,String,Array]),we("design:returntype",Promise)],Ot.prototype,"set",null),Ot=Pe([h("/groups"),v(ht)],Ot);let Tt=class HealthController{ping(e){return be(this,void 0,void 0,function*(){e.json({status:"ok",timestamp:Date.now(),uptime:process.uptime()})})}};Pe([P("/"),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Tt.prototype,"ping",null),Tt=Pe([h("/health")],Tt);let Pt=class LogsController extends ht{constructor(){super(...arguments),this.model=lt,this.permissions=["read"]}all(e){return be(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{order:[["created_at","DESC"]]}})})}};Pe([g(),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Pt.prototype,"all",null),Pt=Pe([h("/logs"),v(ht)],Pt);let It=class PermissionsController extends _t{constructor(){super(...arguments),this.model=et,this.schemaCreate={name:z.string().required(),description:z.string().empty(""),active:z.boolean().parse().required()},this.schemaUpdate={description:z.string().empty(),active:z.boolean().parse().empty()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}};It=Pe([h("/permissions"),v(_t)],It);let wt=class RegisterController extends yt{register(e,t,i){return be(this,void 0,void 0,function*(){yield G(Env.SLEEP_REGISTRY);const{name:r,date:n,email:o,username:d,password:a,confirm:l}=t,u=d||o,c=D(a);if(yield st.count({where:{[le.or]:[{email:o},{username:u}]}}).catch(this.error))return e.error("INVALID EMAIL OR USERNAME");if(c!=D(l))return e.error("INVALID PASSWORD");const p=yield st.create({name:r,email:o,username:u,password:c,avatar:"",date:n,description:"",status:Le.PENDING}).catch(this.error);if(!p)return e.error(new s);const v=yield Xe.create({token:yield this.getId(),active:!0,user_id:p.id}).catch(this.error);if(!v)return yield p.destroy().catch(this.error),e.error(new s);e.success("OK"),i.emit("register.user",{ctx:e,register:v,user:p}),this.emit("register.user",{ctx:e,register:v,user:p})})}confirm(e,t,i){return be(this,void 0,void 0,function*(){const r=yield Xe.findOne({where:{token:t,active:!0},include:[{association:"users",required:!0}]}).catch(this.error);if(!r)return e.error(new n);r.active=!1,yield r.save().catch(this.error),r.user.status=Le.ACTIVE,yield r.user.save().catch(this.error),e.success("OK"),i.emit("register.confirm",{ctx:e,register:r,user:r.user}),this.emit("register.confirm",{ctx:e,register:r,user:r.user})})}send(e,t,i){return be(this,void 0,void 0,function*(){const r=t,s=yield Xe.findOne({where:{active:!0},include:[{model:st,required:!0,where:{[le.or]:[{email:r},{username:t}]}}]}).catch(this.error);if(!s)return e.error(new n);e.success("OK"),i.emit("register.send",{ctx:e,register:s,user:s.user}),this.emit("register.send",{ctx:e,register:s,user:s.user})})}getId(){return be(this,void 0,void 0,function*(){const e=K();return(yield Xe.count({where:{token:e}}))?this.getId():e})}};Pe([m(),E(e=>({name:e.string().required(),date:e.date().required(),email:e.string().email().required(),username:e.string().min(4).empty(),password:e.string().min(5).required(),confirm:e.string().min(5).required()})),Ie(0,u()),Ie(1,_()),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,Object,Application]),we("design:returntype",Promise)],wt.prototype,"register",null),Pe([m("/confirm"),E(e=>({token:e.string().required()})),Ie(0,u()),Ie(1,_("token")),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,String,Application]),we("design:returntype",Promise)],wt.prototype,"confirm",null),Pe([m("/send"),E(e=>({username:e.string().min(4).required()})),Ie(0,u()),Ie(1,_("username")),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,String,Application]),we("design:returntype",Promise)],wt.prototype,"send",null),wt=Pe([h("/register"),v(yt)],wt);let bt=class SetupController extends yt{constructor(){super(...arguments),this.userService=new gt}setup(e){return be(this,void 0,void 0,function*(){var t;if(yield st.count())return e.error(new n("Endpoint Not Found"));const i=yield st.create({name:"Admin",username:"admin",email:"admin@localhost.com",notes:"",status:Le.ACTIVE},Object.assign({},{ctx:e})).catch(this.error);if(!i)return e.error(new s);yield this.userService.createPassword(i.id,"admin",e);const r=yield it.create({name:"root",description:"Root",active:!0},Object.assign({},{ctx:e}));yield rt.create({user_id:i.id,group_id:r.id},Object.assign({},{ctx:e})),yield it.create({name:"admin",description:"Admin",active:!0},Object.assign({},{ctx:e})),yield it.create({name:"user",description:"User",active:!0},Object.assign({},{ctx:e}));const o=null!==(t=yield et.findAll({where:{active:!0}}).catch(this.error))&&void 0!==t?t:[];yield W(o,t=>be(this,void 0,void 0,function*(){yield tt.create({group_id:r.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}};Pe([g(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],bt.prototype,"setup",null),bt=Pe([h("/setup"),v(yt)],bt);let Ct=class UsersController extends ht{constructor(){super(),this.model=st,this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&Ee(Env.API_HTTP_PUBLIC)&&!Ee(this.path)&&Ae(this.path)}avatar(e,t){return be(this,void 0,void 0,function*(){var i;const r=e.getFiles();if(r.file&&r.file.length){const{filename:n,path:o}=null!==(i=r.file[0])&&void 0!==i?i:{};if(n){const i=yield st.findOne({where:{user_id:t.id}}).catch(this.error);if(!i)return Se(o).isFile()&&Oe(o),e.error(new s);const r=this.path+"/"+i.metadata.avatar_url;if(Ee(r)&&Se(r).isFile()&&Oe(r),i.changed("metadata",!0),i.metadata.avatar_url=n,yield i.save(Object.assign({},{ctx:e})).catch(this.error))return e.success("OK")}}e.success("Record not Changed")})}token_new(){return be(this,void 0,void 0,function*(){var e;const t=K();return(null!==(e=yield this.model.count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(e){return be(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return be(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}rows(e){return be(this,void 0,void 0,function*(){yield this.countAll({ctx:e})})}del(e,t,i){return be(this,void 0,void 0,function*(){if(i.id==t)return e.error(new n);yield this.delete({ctx:e})})}get(e){return be(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return be(this,void 0,void 0,function*(){yield this.update({ctx:e})})}};Pe([m("/avatar"),He(),I({file:{count:1,path:`${Env.API_HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),Ie(0,u()),Ie(1,Ge()),we("design:type",Function),we("design:paramtypes",[r,st]),we("design:returntype",Promise)],Ct.prototype,"avatar",null),Pe([m(),He(),Me(),E(e=>({name:e.string().required(),email:e.string().email().required(),username:e.string().min(3).required(),notes:e.string().empty(""),status:e.enum(["active","pending","disabled","locked","archived"]).empty("active")})),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"add",null),Pe([g(),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"all",null),Pe([g("/count"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"rows",null),Pe([S("/:id"),He(),ke(),Ie(0,u()),Ie(1,T("id")),Ie(2,Ge()),we("design:type",Function),we("design:paramtypes",[r,String,st]),we("design:returntype",Promise)],Ct.prototype,"del",null),Pe([g("/:id"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"get",null),Pe([O("/:id"),He(),je(),E(e=>({name:e.string().empty(),email:e.string().email().empty(),username:e.string().min(3).empty(),notes:e.string().empty(),status:e.enum(["active","pending","disabled","locked","archived"]).empty()})),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"set",null),Ct=Pe([h("/users"),v(ht),we("design:paramtypes",[])],Ct);let Rt=class UsersGroupsController extends ht{constructor(){super(...arguments),this.model=rt,this.permissions=[]}all(e,t){return be(this,void 0,void 0,function*(){if(!(yield st.findByPk(t,{attributes:["id"]}).catch(this.error)))return e.error(new n("User Not Found"));yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{association:"group"}]},callback:e=>e.map(e=>e.group),query:!1})})}set(e,t,i){return be(this,void 0,void 0,function*(){const r=yield st.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new n("User Not Found"));const s=r.id,o=[];yield W($(i),t=>be(this,void 0,void 0,function*(){var i;if(!(yield it.count({where:{id:t}})))return;const[r]=null!==(i=yield rt.findOrCreate(Object.assign({where:{user_id:s,group_id:t},defaults:{user_id:s,group_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];r&&o.push(t)})),yield rt.destroy(Object.assign({where:{user_id:s,group_id:{[le.notIn]:o}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Pe([g("/:id/groups"),He(),Ke("users"),Ie(0,u()),Ie(1,T("id")),we("design:type",Function),we("design:paramtypes",[r,String]),we("design:returntype",Promise)],Rt.prototype,"all",null),Pe([O("/:id/groups"),He(),je("users"),E(e=>({groups:e.array(e.string())})),Ie(0,u()),Ie(1,T("id")),Ie(2,_("groups")),we("design:type",Function),we("design:paramtypes",[r,String,Array]),we("design:returntype",Promise)],Rt.prototype,"set",null),Rt=Pe([h("/users"),v(ht)],Rt);export{Application,Qe as Audit,ot as AuditModel,De as AuditTypes,mt as AuditsController,Et as AuthController,vt as AuthService,yt as BaseController,Me as CanCreate,ke as CanDelete,Ke as CanRead,je as CanUpdate,Config,dt as ConfigModel,_t as CrudController,Env,ft as FilesController,At as ForgotController,at as ForgotModel,it as GroupModel,tt as GroupPermissionModel,St as GroupsController,Ot as GroupsPermissionsController,Be as HasGroups,Fe as HasPermissions,Tt as HealthController,He as IsAuthenticated,Log,lt as LogModel,Loggable,xe as Loglevels,Pt as LogsController,ut as MigrationModel,ht as ModelController,ModelService,et as PermissionModel,It as PermissionsController,wt as RegisterController,Xe as RegisterModel,Ue as ReqAuth,qe as ReqGroup,Ye as ReqGroups,$e as ReqPermission,We as ReqPermissions,Ge as ReqUser,pt as Service,ct as SessionModel,SessionStore,bt as SetupController,Ze as UserAuthModel,rt as UserGroupModel,st as UserModel,nt as UserPasswordModel,gt as UserService,Le as UserStatus,Ct as UsersController,Rt as UsersGroupsController,Ne as canFactory,Re as sequelize};
|
|
7
|
+
import{Use as e,UnauthorizedError as t,parameterFactory as i,ResponseError as r,Context as n,NotFoundError as o,InternalServerError as s,ValidationError as a,StatusCodes as d,BadRequestError as l,Application as u,Ctx as c,Headers as p,Session as v,Extends as g,Get as h,Query as y,Controller as m,Post as E,Validate as f,Body as _,App as S,Middleware as O,Delete as A,Put as T,Params as b,All as I,Options as P,Upload as w}from"@andrewcaires/express";import{Env as M,Log as x,LogColor as C,Hash as R,sha256 as j}from"@andrewcaires/node";import{isUndefined as D,isFunction as N,includesArray as L,isPlainObject as H,isString as k,isNumber as F,uuidv7 as B,isArray as K,isValidationShape as q,Validation as V,getConstructor as U,noop as Y,clamp as $,merge as W,clone as z,forEachAsync as G,upperCamelCase as J,uniqueArray as Q,isNull as X,forEachSeries as Z,sleep as ee,EventEmitter as te,isDef as ie,uniqueID as re}from"@andrewcaires/utils.js";import{WebSocketServer as ne}from"ws";import{Sequelize as oe,Hooks as se,Column as ae,Association as de,Database as le,ModelName as ue,Version as ce,Model as pe,Index as ve,DefaultValue as ge,Op as he,Where as ye}from"@andrewcaires/sequelize";import{config as me}from"dotenv";import{metadata as Ee,Trait as fe,Singleton as _e}from"@andrewcaires/decorator";import{Store as Se}from"express-session";import Oe from"jsonwebtoken";import{hashSync as Ae,verify as Te}from"@node-rs/argon2";import{existsSync as be,statSync as Ie,readdirSync as Pe,mkdirSync as we,lstatSync as Me,rmSync as xe}from"fs";import{join as Ce}from"path";function Re(e,t,i,r){var n,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,i,s):n(t,i))||s);return o>3&&s&&Object.defineProperty(t,i,s),s}function je(e,t){return function(i,r){t(i,r,e)}}function De(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function Ne(e,t,i,r){return new(i||(i=Promise))(function(n,o){function s(e){try{d(r.next(e))}catch(e){o(e)}}function a(e){try{d(r.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,a)}d((r=r.apply(e,t||[])).next())})}var Le;"function"==typeof SuppressedError&&SuppressedError,me({quiet:!0});class Env extends M{}Le=Env,Env.BASE_NAME=Le.getString("BASE_NAME",""),Env.CONSOLE_ERROR=Le.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=Le.getString("DATABASE_URI","",!0),Env.DATABASE_LOG=Le.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=Le.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=Le.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=Le.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CROSS=Le.getString("HTTP_CROSS",""),Env.HTTP_PORT=Le.getInt("HTTP_PORT",Le.getInt("PORT",3e3)),Env.HTTP_PUBLIC=Le.getString("HTTP_PUBLIC",""),Env.HTTP_TLS_CA=Le.getFile("HTTP_TLS_CA"),Env.HTTP_TLS_CRT=Le.getFile("HTTP_TLS_CRT"),Env.HTTP_TLS_KEY=Le.getFile("HTTP_TLS_KEY"),Env.KEY_HEADER=Le.getString("KEY_HEADER","x-api-key"),Env.MODEL_LIMIT=Le.getInt("MODEL_LIMIT",10),Env.MODEL_LIMIT_MAX=Le.getInt("MODEL_LIMIT_MAX",100),Env.MCP_ALLOWED_ORIGINS=Le.getString("MCP_ALLOWED_ORIGINS",""),Env.MCP_RATE_LIMIT_MAX=Le.getInt("MCP_RATE_LIMIT_MAX",120),Env.MCP_RATE_LIMIT_WINDOW=Le.getMs("MCP_RATE_LIMIT_WINDOW","1m"),Env.MCP_SESSION_TTL=Le.getMs("MCP_SESSION_TTL","30m"),Env.PASSWORD_ALGORITHM=Le.getInt("PASSWORD_ALGORITHM",2),Env.PASSWORD_MEMORY_COST=Le.getInt("PASSWORD_MEMORY_COST",4096),Env.PASSWORD_PARALLELISM=Le.getInt("PASSWORD_PARALLELISM",1),Env.PASSWORD_PEPPER=Le.getString("PASSWORD_PEPPER",""),Env.PASSWORD_TIME_COST=Le.getInt("PASSWORD_TIME_COST",3),Env.SLEEP_AUTH=Le.getMs("SLEEP_AUTH","2s"),Env.SLEEP_FORGOT=Le.getMs("SLEEP_FORGOT","5s"),Env.SLEEP_REGISTRY=Le.getMs("SLEEP_REGISTRY","5s"),Env.TENANT_HEADER=Le.getString("TENANT_HEADER","x-tenant-id"),Env.TOKEN_CRT=Le.getFile("TOKEN_CRT"),Env.TOKEN_HEADER=Le.getString("TOKEN_HEADER","authorization"),Env.TOKEN_KEY=Le.getFile("TOKEN_KEY"),Env.TOKEN_TTL=Le.getMs("TOKEN_TTL","1d"),Env.TOKEN_TTL_FORGOT=Le.getMs("TOKEN_TTL_FORGOT","1d"),Env.TOKEN_TTL_RENEW=Le.getMs("TOKEN_TTL_RENEW","1d"),Env.TOKEN_TYPE=Le.getString("TOKEN_TYPE","bearer"),Env.API_BODYPARSER_STRICT=Le.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=Le.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=Le.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=Le.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_HYBRID=Le.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=Le.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=Le.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=Le.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=Le.getString("API_KEY_HASH",""),Env.API_SESSION_NAME=Le.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=Le.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=Le.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=Le.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=Le.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_USER_HISTORY=Le.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=Le.getBool("API_WEBSOCKET_START",!1);const He=new oe({uri:Env.DATABASE_URI,logging:!!Env.DATABASE_LOG&&(e=>x.console(C.Magenta,"sql",e)),prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE});var ke,Fe,Be,Ke,qe;!function(e){e.CREATE="CREATE",e.DELETE="DELETE",e.UPDATE="UPDATE"}(ke||(ke={})),function(e){e.SYSTEM="system",e.TENANT="tenant"}(Fe||(Fe={})),function(e){e.INFO="info",e.WARN="warn",e.ERROR="error"}(Be||(Be={})),function(e){e.ACTIVE="active",e.PENDING="pending",e.SUSPENDED="suspended",e.DISABLED="disabled",e.ARCHIVED="archived"}(Ke||(Ke={})),function(e){e.ACTIVE="active",e.PENDING="pending",e.DISABLED="disabled",e.LOCKED="locked",e.ARCHIVED="archived"}(qe||(qe={}));const Ve=i=>r=>(n,o,s)=>{e(e=>Ne(void 0,void 0,void 0,function*(){var n;D(r)&&(r=N(e.controller.name)?e.controller.name():null===(n=e.controller.constructor)||void 0===n?void 0:n.name);const{permissions:o=[]}=e.req;if(o.includes(`${r}.${i}`))return e.next();e.error(new t("Access Denied"))}))(n,o,s)},Ue=Ve("create"),Ye=Ve("delete"),$e=Ve("read"),We=Ve("update"),ze=(...i)=>(r,n,o)=>{e(e=>Ne(void 0,void 0,void 0,function*(){const{groups:r=[]}=e.req;if(L(i,r))return e.next();e.error(new t("Access Denied"))}))(r,n,o)},Ge=(...i)=>(r,n,o)=>{e(e=>Ne(void 0,void 0,void 0,function*(){const{permissions:r}=e.req;if(L(i,null!=r?r:[]))return e.next();e.error(new t("Access Denied"))}))(r,n,o)},Je=()=>(i,r,n)=>{e(e=>Ne(void 0,void 0,void 0,function*(){yield(e=>Ne(void 0,void 0,void 0,function*(){var i,r,n,o;if(e.req.auth&&e.req.user)return e.next();const{[Env.KEY_HEADER]:s,[Env.TOKEN_HEADER]:a,[Env.TENANT_HEADER]:d,"user-agent":l}=e.getHeaders(),u=e.getQuery(Env.KEY_HEADER),c=(null===(i=s||u)||void 0===i?void 0:i.toString())||"";let p=e.getCookie(Env.API_TOKEN_COOKIE);p=`${Env.TOKEN_TYPE} ${p}`;const[v,g]=null!==(n=null===(r=a||p)||void 0===r?void 0:r.split(" "))&&void 0!==n?n:["",""];if(!(c||g&&v.toLowerCase()==Env.TOKEN_TYPE))return e.error(new t("Invalid token"));const{authService:h,userService:y}=e.app,{auth:m,user:E}=null!==(o=yield(c?h.key(c.toString()):h.user(g)).catch(t=>{e.error(t)}))&&void 0!==o?o:{};if(!m||!E)return;if(!c&&m.user_agent&&m.user_agent!=l)return e.error(new t("Invalid token"));e.req.auth=m,e.req.user=E;const f=d||null,_=yield y.getTenants(E.id);if(f&&!_.find(e=>e.id==f))return e.error(new t("Invalid token"));const S=y.getGroups(E.id,f),O=y.getPermissions(E.id,f),[A,T]=yield Promise.all([S,O]);e.req.groups=A,e.req.permissions=T,e.req.tenants=_,e.next()}))(e)}))(i,r,n)},Qe=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),Xe=i(({ctx:e,key:t})=>{var i,r;return(null!==(r=null===(i=e.req)||void 0===i?void 0:i.groups)&&void 0!==r?r:[]).includes(t)}),Ze=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.groups)&&void 0!==i?i:[]}),et=i(({ctx:e,key:t})=>{var i,r;return(null!==(r=null===(i=e.req)||void 0===i?void 0:i.permissions)&&void 0!==r?r:[]).includes(t)}),tt=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.permissions)&&void 0!==i?i:[]}),it=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.user}),rt={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,ServerError:-32e3,InvalidSession:-32001};class McpError extends r{constructor(e,t=rt.ServerError,i=200,r){super(e,i),this.code=t,this.data=r,this.name=this.constructor.name}}class McpParseError extends McpError{constructor(e="Parse error",t){super(e,rt.ParseError,400,t)}}class McpInvalidRequestError extends McpError{constructor(e="Invalid Request",t){super(e,rt.InvalidRequest,400,t)}}class McpMethodNotFoundError extends McpError{constructor(e){super(`Method not found: ${e}`,rt.MethodNotFound,200)}}class McpInvalidParamsError extends McpError{constructor(e="Invalid params",t){super(e,rt.InvalidParams,200,t)}}class McpInternalError extends McpError{constructor(e="Internal error",t){super(e,rt.InternalError,200,t)}}class McpServerError extends McpError{constructor(e="Server error",t){super(e,rt.ServerError,500,t)}}class McpInvalidSessionError extends McpError{constructor(e="Invalid MCP session",t=404){super(e,rt.InvalidSession,t)}}class McpToolNotFoundError extends McpError{constructor(e){super("Tool not found",rt.InvalidParams,200,{toolName:e})}}const nt=e=>k(e)||F(e),ot=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),st=(e,t)=>({jsonrpc:"2.0",id:e,error:Object.assign({code:t.code,message:t.message},void 0!==t.data?{data:t.data}:{})}),at=(e,t,i,r)=>({jsonrpc:"2.0",id:e,error:Object.assign({code:t,message:i},void 0!==r?{data:r}:{})}),dt=e=>{if(!H(e))throw new McpInvalidRequestError("Invalid Request");if("2.0"!==e.jsonrpc)throw new McpInvalidRequestError("Invalid JSON-RPC version");if(!k(e.method))throw new McpInvalidRequestError("Invalid method");if(void 0!==e.id&&!nt(e.id))throw new McpInvalidRequestError("Invalid id");return e},lt=["2025-11-25","2025-06-18"],ut=lt[0],ct="MCP-Protocol-Version",pt="MCP-Session-Id",vt=["POST","DELETE","OPTIONS"],gt=vt.join(", "),ht=e=>{if(!(e instanceof SyntaxError))return!1;const t=e;return"entity.parse.failed"===t.type||400===t.status||400===t.statusCode},yt=e=>{if(ht(e))return{status:400,body:st(null,new McpParseError("Parse error",{message:e.message}))}};class McpHttpHandler{constructor(e){var t,i,r;this.sessions=e.sessions,this.tools=e.tools,this.allowedOrigins=null!==(t=e.allowedOrigins)&&void 0!==t?t:[],this.logger=e.logger,this.serverName=null!==(i=e.serverName)&&void 0!==i?i:"andrewcaires-api-mcp",this.serverVersion=null!==(r=e.serverVersion)&&void 0!==r?r:"1.0.0"}post(e){return Ne(this,void 0,void 0,function*(){var t;const i=this.validateOrigin(e);if(i)return i;let r=null;try{const i=dt(e.body);if(r=null!==(t=i.id)&&void 0!==t?t:null,"initialize"===i.method)return this.withTransportHeaders(this.initialize(i.id,i.params,e),e);if("notifications/initialized"===i.method)return this.withTransportHeaders(this.initialized(i.id,i.params,e),e);if("ping"===i.method)return this.validateObjectParams(i.params),this.withTransportHeaders(this.withSession(i.id,e,e=>({status:200,body:ot(e,{})})),e);if("tools/list"===i.method)return this.validateObjectParams(i.params),this.withTransportHeaders(this.withInitializedSession(i.id,e,e=>({status:200,body:ot(e,{tools:this.tools.list()})})),e);if("tools/call"===i.method)return this.withTransportHeaders(yield this.callTool(i.id,i.params,e),e);if(void 0===i.id)return this.withTransportHeaders({status:202},e);throw new McpMethodNotFoundError(i.method)}catch(t){return this.withTransportHeaders(this.errorResponse(r,t),e)}})}delete(e){const t=this.validateOrigin(e);if(t)return t;const i=this.getSessionHeader(e);if(!i)return this.withTransportHeaders(this.errorResponse(null,new McpInvalidSessionError(`${pt} header is required`,400)),e);const r=this.sessions.get(i);if(!r)return this.withTransportHeaders(this.errorResponse(null,new McpInvalidSessionError),e);try{this.validateProtocolHeader(e,r.protocolVersion)}catch(t){return this.withTransportHeaders(this.errorResponse(null,t),e)}return this.sessions.delete(i),this.withTransportHeaders({status:204},e)}get(e){const t=this.validateOrigin(e);return t||this.withTransportHeaders({status:405},e)}options(e){const t=this.validateOrigin(e);return t||this.withTransportHeaders({status:204},e)}initialize(e,t,i){const r=this.requireRequestId({jsonrpc:"2.0",id:e,method:"initialize",params:t}),n=this.negotiateProtocolVersion(t),o=this.sessions.create(n,i.context);return{status:200,headers:{[pt]:o.sessionId,[ct]:o.protocolVersion},body:ot(r,{protocolVersion:o.protocolVersion,capabilities:{tools:{listChanged:!1}},serverInfo:{name:this.serverName,version:this.serverVersion}})}}initialized(e,t,i){if(void 0!==e)throw new McpInvalidRequestError("notifications/initialized must not include id");this.validateObjectParams(t);const r=this.requireSession(i);return this.validateProtocolHeader(i,r.protocolVersion),this.sessions.markInitialized(r.sessionId),{status:202}}callTool(e,t,i){return Ne(this,void 0,void 0,function*(){return this.withInitializedSession(e,i,(e,i)=>Ne(this,void 0,void 0,function*(){var r;const n=this.parseToolCallParams(t),o=Date.now();let s,a=!1;try{const t=yield this.tools.call(n.name,n.arguments,i);return a=!t.isError,s=t.isError?"Tool execution failed":void 0,{status:200,body:ot(e,t)}}catch(e){if(e instanceof McpError)throw s=e.message,e;throw s="Internal error",e}finally{null===(r=this.logger)||void 0===r||r.toolCall(Object.assign({sessionId:i.sessionId,userId:i.userId,toolName:n.name,durationMs:Date.now()-o,success:a},s?{error:s}:{}))}}))})}requireRequestId(e){if(!nt(e.id))throw new McpInvalidRequestError("Request id is required");return e.id}withSession(e,t,i){const r=this.requireRequestId({jsonrpc:"2.0",id:e,method:"session"}),n=this.requireSession(t);return this.validateProtocolHeader(t,n.protocolVersion),i(r,n)}withInitializedSession(e,t,i){return this.withSession(e,t,(e,t)=>{if(!t.initialized)throw new McpInvalidRequestError("Session not initialized");return i(e,t)})}requireSession(e){const t=this.getSessionHeader(e);if(!t)throw new McpInvalidSessionError(`${pt} header is required`,400);return this.sessions.require(t)}validateProtocolHeader(e,t){const i=this.getHeader(e,"mcp-protocol-version");if(i&&i!==t)throw new McpInvalidRequestError(`Invalid ${ct} header`)}negotiateProtocolVersion(e){if(!H(e)||!k(e.protocolVersion))throw new McpInvalidParamsError("params.protocolVersion is required");return lt.includes(e.protocolVersion)?e.protocolVersion:ut}parseToolCallParams(e){if(!H(e)||!k(e.name))throw new McpInvalidParamsError("params.name is required");return{name:e.name,arguments:e.arguments}}validateObjectParams(e){if(void 0!==e&&!H(e))throw new McpInvalidParamsError("params must be an object")}validateOrigin(e){if(this.getHeader(e,"origin")&&!this.getAllowedOrigin(e))return{status:403}}withTransportHeaders(e,t){var i;return Object.assign(Object.assign({},e),{headers:Object.assign(Object.assign({},this.transportHeaders(t)),null!==(i=e.headers)&&void 0!==i?i:{})})}transportHeaders(e){const t={Allow:gt,"Access-Control-Allow-Methods":gt,"Access-Control-Allow-Headers":`Content-Type, Accept, ${pt}, ${ct}`},i=this.getAllowedOrigin(e);return i&&(t["Access-Control-Allow-Origin"]=i),t}getAllowedOrigin(e){const t=this.getHeader(e,"origin");if(!t)return;if(this.allowedOrigins.includes("*"))return"*";if(this.allowedOrigins.includes(t))return t;const i=this.getHeader(e,"host");if(!this.allowedOrigins.length&&i)try{if(new URL(t).host===i)return t}catch(e){return}}getSessionHeader(e){return this.getHeader(e,"mcp-session-id")}getHeader(e,t){var i;return null===(i=Object.entries(e.headers).find(([e])=>e.toLowerCase()===t))||void 0===i?void 0:i[1]}errorResponse(e,t){if(t instanceof McpError)return{status:t.status,body:st(e,t)};const i=new McpServerError;return{status:i.status,body:st(e,i)}}}class McpRateLimiter{constructor(e=120,t=6e4,i=()=>Date.now()){this.entries=new Map,this.max=e,this.windowMs=t,this.now=i}consume(e){if(this.max<=0)return!0;const t=this.now(),i=this.entries.get(e);return!i||i.resetAt<=t?(this.entries.set(e,{count:1,resetAt:t+this.windowMs}),!0):(i.count++,i.count<=this.max)}}class McpSessionStore{constructor(e=18e5,t=()=>Date.now()){this.sessions=new Map,this.ttl=e,this.now=t}create(e,t){this.cleanup();const i=this.now(),r=Object.assign(Object.assign({},t),{sessionId:B(),createdAt:i,expiresAt:i+this.ttl,protocolVersion:e,initialized:!1});return this.sessions.set(r.sessionId,r),r}get(e){this.cleanup();const t=this.sessions.get(e);if(t){if(!this.isExpired(t))return t;this.sessions.delete(e)}}require(e){const t=this.get(e);if(!t)throw new McpInvalidSessionError;return t}markInitialized(e){const t=this.require(e);return t.initialized=!0,t}delete(e){return this.cleanup(),this.sessions.delete(e)}cleanup(){const e=this.now();for(const[t,i]of this.sessions)i.expiresAt<=e&&this.sessions.delete(t)}size(){return this.cleanup(),this.sessions.size}isExpired(e){return e.expiresAt<=this.now()}}const mt=Symbol.for("@andrewcaires/api:mcp:tool"),Et=e=>{if(!k(e.name)||!e.name.trim())throw new Error("MCP tool name is required");if(!k(e.title)||!e.title.trim())throw new Error(`MCP tool "${e.name}" title is required`);if(!k(e.description)||!e.description.trim())throw new Error(`MCP tool "${e.name}" description is required`);if(D(e.input))throw new Error(`MCP tool "${e.name}" input must be declared`)};class McpToolRegistry{constructor(e=[]){this.tools=new Map,e.forEach(e=>this.register(e))}register(e){var t,i;if(Et(e),this.tools.has(e.name))throw new Error(`Duplicate MCP tool name: ${e.name}`);const r=this.normalizeMcpValidation(null!==(t=e.input)&&void 0!==t?t:{},"object"),n=e.output?this.normalizeMcpValidation(null!==(i=e.output)&&void 0!==i?i:{},"any"):void 0;this.tools.set(e.name,{inputSchema:r.schema,inputValidation:r.validation,outputSchema:null==n?void 0:n.schema,outputValidation:null==n?void 0:n.validation,tool:e})}list(){return Array.from(this.tools.values()).map(({tool:e})=>{var t,i,r,n;return Object.assign({name:e.name,title:e.title,description:e.description,inputSchema:null!==(i=null===(t=this.tools.get(e.name))||void 0===t?void 0:t.inputSchema)&&void 0!==i?i:{}},(null===(r=this.tools.get(e.name))||void 0===r?void 0:r.outputSchema)?{outputSchema:null===(n=this.tools.get(e.name))||void 0===n?void 0:n.outputSchema}:{})})}call(e,t,i){return Ne(this,void 0,void 0,function*(){var r;const n=this.tools.get(e);if(!n)throw new McpToolNotFoundError(e);const o=null!=t?t:{};if(!H(o))return this.toolInputValidationError(["arguments must be an object"]);const s={session:i,auth:i.auth,groups:i.groups,permissions:i.permissions,profile:i.profile,user:i.user,userId:i.userId};let a=o;const d=this.validateAdditionalProperties(n.inputSchema,o);if(d.length)return this.toolInputValidationError(d);if(n.inputValidation){const e=n.inputValidation.validate(o,s);if(e.error)return this.toolInputValidationError([e.error]);a=null!==(r=e.value)&&void 0!==r?r:{}}try{const e=yield n.tool.run(a,s);if(!n.outputValidation&&this.isCallToolResult(e))return e;let t=e;if(n.outputValidation){const i=n.outputValidation.validate(e,s);if(i.error)return this.outputValidationError();t=i.value}return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}catch(e){return{isError:!0,content:[{type:"text",text:"Tool execution failed."}]}}})}isCallToolResult(e){return H(e)&&K(e.content)}normalizeMcpValidation(e,t="object"){if(q(e)){const t=V.object(e).parse();return{schema:t.toSchema(),validation:t}}const i="object"===t?V.object({}).parse():V.any();return{schema:i.toSchema(),validation:i}}outputValidationError(){return{isError:!0,content:[{type:"text",text:"Tool output validation failed."}]}}toolInputValidationError(e){return{isError:!0,content:[{type:"text",text:"Invalid tool arguments."}],structuredContent:{errors:e}}}validateAdditionalProperties(e,t){if("object"!==e.type||!1!==e.additionalProperties||!H(e.properties))return[];const i=Object.keys(e.properties);return Object.keys(t).filter(e=>!i.includes(e)).map(e=>`additional property "${e}" is not allowed`)}}const ft=e=>(Et(e),(t,i)=>{_t(i)?i.addInitializer(function(){St(this.constructor,i.name,e)}):St(t,i,e)}),_t=e=>"object"==typeof e&&null!==e&&"kind"in e&&"method"===e.kind&&"name"in e&&"addInitializer"in e,St=(e,t,i)=>{const r=Ee(mt,e,[]),n=Object.assign(Object.assign({},i),{propertyKey:t});r.some(e=>e.propertyKey===n.propertyKey&&e.name===n.name)||r.push(n)},Ot=(e,t,i)=>{var r,o,s,a,d,l,u,c,p,v,g;const h=i.ctx instanceof n?i.ctx:null,y=null!==(r=null==h?void 0:h.id)&&void 0!==r?r:null,m=null!==(d=null!==(a=null===(s=null===(o=null==h?void 0:h.req)||void 0===o?void 0:o.user)||void 0===s?void 0:s.id)&&void 0!==a?a:i.user_id)&&void 0!==d?d:null,E={type:e,model:null!==(l=null==t?void 0:t.getTableName())&&void 0!==l?l:null,source:null!==(u=Env.BASE_NAME)&&void 0!==u?u:"",request_id:y,user_id:m};return h?Object.assign(Object.assign({},E),{full_url:null!==(c=h.getUrl())&&void 0!==c?c:"",ip_address:null!==(p=h.getIp())&&void 0!==p?p:"",user_agent:null!==(g=null===(v=h.req)||void 0===v?void 0:v.headers["user-agent"])&&void 0!==g?g:""}):E},At=e=>{const t=U(e),i=t.primaryKeyAttribute;return{model:t,record_id:i?e.getDataValue(i):null}},Tt={afterCreate:(e,t)=>Ne(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=At(e);yield Lt.create(Object.assign(Object.assign({},Ot(ke.CREATE,i,t)),{record:r,currently:e.toJSON()})).catch(x.catch)}),afterUpdate:(e,t)=>Ne(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=At(e),n={},o={},s=e.changed();s&&s.length&&s.forEach(t=>{n[t]=e.getDataValue(t),o[t]=e.previous(t)}),yield Lt.create(Object.assign(Object.assign({},Ot(ke.UPDATE,i,t)),{record:r,currently:n,previously:o})).catch(x.catch)}),afterDestroy:(e,t)=>Ne(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=At(e);yield Lt.create(Object.assign(Object.assign({},Ot(ke.DELETE,i,t)),{record:r,currently:e.toJSON()})).catch(x.catch)})},bt=e=>(D(e)&&(e=Env.DATABASE_AUDIT),se(e?Tt:{}));let It=class RegisterModel extends pe{};Re([ae.Id(7),De("design:type",String)],It.prototype,"id",void 0),Re([ae.String(),De("design:type",String)],It.prototype,"secret",void 0),Re([ae.FullDate(),De("design:type",Number)],It.prototype,"expired_at",void 0),Re([ae.Boolean(),De("design:type",Boolean)],It.prototype,"active",void 0),Re([ae.CreatedAt(),De("design:type",Date)],It.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],It.prototype,"updated_at",void 0),Re([ae.DeletedAt(),De("design:type",Object)],It.prototype,"deleted_at",void 0),Re([de.BelongsTo(()=>Nt),De("design:type",String)],It.prototype,"user_id",void 0),It=Re([le(He),ue("register"),ce("5.3.1")],It);let Pt=class UserAuthModel extends pe{};Re([ae.Id(7),De("design:type",String)],Pt.prototype,"id",void 0),Re([ae.String(),De("design:type",String)],Pt.prototype,"secret",void 0),Re([ae.String(),De("design:type",String)],Pt.prototype,"ip_address",void 0),Re([ae.String(),De("design:type",String)],Pt.prototype,"user_agent",void 0),Re([ae.FullDate(),De("design:type",Object)],Pt.prototype,"revoked_at",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Pt.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],Pt.prototype,"updated_at",void 0),Re([ae.DeletedAt(),De("design:type",Object)],Pt.prototype,"deleted_at",void 0),Re([de.BelongsTo(()=>Nt),De("design:type",String)],Pt.prototype,"user_id",void 0),Pt=Re([le(He),ue("users_auth"),ce("5.3.1")],Pt);let wt=class PermissionModel extends pe{};Re([ae.Id(7),De("design:type",String)],wt.prototype,"id",void 0),Re([ae.String(),ve(),De("design:type",String)],wt.prototype,"name",void 0),Re([ae.Text(),De("design:type",String)],wt.prototype,"description",void 0),Re([ae.Boolean(),De("design:type",Boolean)],wt.prototype,"active",void 0),Re([ae.Json(),ge(()=>({})),De("design:type",Object)],wt.prototype,"metadata",void 0),Re([ae.CreatedAt(),De("design:type",Date)],wt.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],wt.prototype,"updated_at",void 0),Re([ae.DeletedAt(),De("design:type",Object)],wt.prototype,"deleted_at",void 0),Re([de.HasMany(()=>Mt),De("design:type",Array)],wt.prototype,"groups_permissions",void 0),wt=Re([le(He),ue("permission"),bt(),ce("5.3.1")],wt);let Mt=class GroupPermissionModel extends pe{};Re([ae.Id(7),De("design:type",String)],Mt.prototype,"id",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Mt.prototype,"created_at",void 0),Re([de.BelongsTo(()=>xt),De("design:type",String)],Mt.prototype,"group_id",void 0),Re([de.BelongsTo(()=>wt),De("design:type",String)],Mt.prototype,"permission_id",void 0),Mt=Re([le(He),ue("groups_permissions"),bt(),ce("5.3.1")],Mt);let xt=class GroupModel extends pe{};Re([ae.Id(7),De("design:type",String)],xt.prototype,"id",void 0),Re([ae.String(),ve(),De("design:type",String)],xt.prototype,"name",void 0),Re([ae.Text(),De("design:type",String)],xt.prototype,"description",void 0),Re([ae.Enum(Fe),ge(Fe.SYSTEM),De("design:type",String)],xt.prototype,"type",void 0),Re([ae.Boolean(),De("design:type",Boolean)],xt.prototype,"active",void 0),Re([ae.Json(),ge(()=>({})),De("design:type",Object)],xt.prototype,"metadata",void 0),Re([ae.CreatedAt(),De("design:type",Date)],xt.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],xt.prototype,"updated_at",void 0),Re([ae.DeletedAt(),De("design:type",Object)],xt.prototype,"deleted_at",void 0),Re([de.HasMany(()=>jt),De("design:type",Array)],xt.prototype,"users_groups",void 0),Re([de.HasMany(()=>Mt),De("design:type",Array)],xt.prototype,"groups_Permission",void 0),xt=Re([le(He),ue("group"),bt(),ce("5.3.1")],xt);let Ct=class UserTenantModel extends pe{};Re([ae.Id(7),De("design:type",String)],Ct.prototype,"id",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Ct.prototype,"created_at",void 0),Re([de.BelongsTo(()=>Rt),De("design:type",String)],Ct.prototype,"tenant_id",void 0),Re([de.BelongsTo(()=>Nt),De("design:type",String)],Ct.prototype,"user_id",void 0),Ct=Re([le(He),ue("users_tenants"),bt(),ce("5.3.1")],Ct);let Rt=class TenantModel extends pe{};Re([ae.Id(7),De("design:type",String)],Rt.prototype,"id",void 0),Re([ae.String(),De("design:type",String)],Rt.prototype,"name",void 0),Re([ae.Enum(Ke),ge(Ke.ACTIVE),De("design:type",String)],Rt.prototype,"status",void 0),Re([ae.Json(),ge(()=>({})),De("design:type",Object)],Rt.prototype,"metadata",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Rt.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],Rt.prototype,"updated_at",void 0),Re([ae.DeletedAt(),De("design:type",Object)],Rt.prototype,"deleted_at",void 0),Re([de.HasMany(()=>Ct),De("design:type",Array)],Rt.prototype,"users_tenants",void 0),Rt=Re([le(He),ue("tenant"),bt(),ce("5.3.1")],Rt);let jt=class UserGroupModel extends pe{};Re([ae.Id(7),De("design:type",String)],jt.prototype,"id",void 0),Re([ae.CreatedAt(),De("design:type",Date)],jt.prototype,"created_at",void 0),Re([de.BelongsTo(()=>xt),De("design:type",String)],jt.prototype,"group_id",void 0),Re([de.BelongsTo(()=>Nt),De("design:type",String)],jt.prototype,"user_id",void 0),Re([de.BelongsTo(()=>Rt),De("design:type",String)],jt.prototype,"tenant_id",void 0),jt=Re([le(He),ue("users_groups"),bt(),ce("5.3.1")],jt);let Dt=class UserPasswordModel extends pe{};Re([ae.Id(7),De("design:type",String)],Dt.prototype,"id",void 0),Re([ae.String(),De("design:type",String)],Dt.prototype,"hash",void 0),Re([ae.FullDate(),De("design:type",Object)],Dt.prototype,"revoked_at",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Dt.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],Dt.prototype,"updated_at",void 0),Re([ae.DeletedAt(),De("design:type",Object)],Dt.prototype,"deleted_at",void 0),Re([de.BelongsTo(()=>Nt),De("design:type",String)],Dt.prototype,"user_id",void 0),Dt=Re([le(He),ue("users_password"),bt(),ce("5.3.1")],Dt);let Nt=class UserModel extends pe{};Re([ae.Id(7),De("design:type",String)],Nt.prototype,"id",void 0),Re([ae.String(),De("design:type",String)],Nt.prototype,"name",void 0),Re([ae.String(),De("design:type",String)],Nt.prototype,"username",void 0),Re([ae.String(),De("design:type",String)],Nt.prototype,"email",void 0),Re([ae.Text(),De("design:type",String)],Nt.prototype,"notes",void 0),Re([ae.Enum(qe),ge(qe.ACTIVE),De("design:type",String)],Nt.prototype,"status",void 0),Re([ae.Json(),ge(()=>({})),De("design:type",Object)],Nt.prototype,"metadata",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Nt.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],Nt.prototype,"updated_at",void 0),Re([ae.DeletedAt(),De("design:type",Object)],Nt.prototype,"deleted_at",void 0),Re([de.HasMany(()=>Lt),De("design:type",Array)],Nt.prototype,"audits",void 0),Re([de.HasMany(()=>Pt),De("design:type",Array)],Nt.prototype,"users_auths",void 0),Re([de.HasMany(()=>It),De("design:type",Array)],Nt.prototype,"registers",void 0),Re([de.HasMany(()=>jt),De("design:type",Array)],Nt.prototype,"users_groups",void 0),Re([de.HasMany(()=>Dt),De("design:type",Array)],Nt.prototype,"users_passwords",void 0),Re([de.HasMany(()=>Ct),De("design:type",Array)],Nt.prototype,"users_tenants",void 0),Nt=Re([le(He),ue("user"),bt(),ce("5.3.1")],Nt);let Lt=class AuditModel extends pe{};Re([ae.Id(7),De("design:type",String)],Lt.prototype,"id",void 0),Re([ae.Enum(ke),De("design:type",String)],Lt.prototype,"type",void 0),Re([ae.String(),De("design:type",String)],Lt.prototype,"model",void 0),Re([ae.String(),De("design:type",String)],Lt.prototype,"record",void 0),Re([ae.Json(),De("design:type",Object)],Lt.prototype,"currently",void 0),Re([ae.Json(),De("design:type",Object)],Lt.prototype,"previously",void 0),Re([ae.String(36),De("design:type",String)],Lt.prototype,"request_id",void 0),Re([ae.Text(),De("design:type",String)],Lt.prototype,"full_url",void 0),Re([ae.String(),De("design:type",String)],Lt.prototype,"ip_address",void 0),Re([ae.Text(),De("design:type",String)],Lt.prototype,"user_agent",void 0),Re([ae.String(),De("design:type",String)],Lt.prototype,"source",void 0),Re([ae.FullDate(),De("design:type",Object)],Lt.prototype,"reverted_at",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Lt.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],Lt.prototype,"updated_at",void 0),Re([ae.DeletedAt(),De("design:type",Object)],Lt.prototype,"deleted_at",void 0),Re([de.BelongsTo(()=>Nt),De("design:type",String)],Lt.prototype,"user_id",void 0),Lt=Re([le(He),ue("audit"),ce("5.3.1")],Lt);let Ht=class ConfigModel extends pe{};Re([ae.Id(7),De("design:type",String)],Ht.prototype,"id",void 0),Re([ae.String(),De("design:type",String)],Ht.prototype,"key",void 0),Re([ae.Text(),De("design:type",String)],Ht.prototype,"value",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Ht.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],Ht.prototype,"updated_at",void 0),Ht=Re([le(He),ue("configs"),ce("5.3.1")],Ht);let kt=class ForgotModel extends pe{};Re([ae.Id(7),De("design:type",String)],kt.prototype,"id",void 0),Re([ae.String(),De("design:type",String)],kt.prototype,"secret",void 0),Re([ae.FullDate(),De("design:type",Number)],kt.prototype,"expired_at",void 0),Re([ae.Boolean(),De("design:type",Boolean)],kt.prototype,"active",void 0),Re([ae.CreatedAt(),De("design:type",Date)],kt.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],kt.prototype,"updated_at",void 0),Re([ae.DeletedAt(),De("design:type",Object)],kt.prototype,"deleted_at",void 0),Re([de.BelongsTo(()=>Nt),De("design:type",String)],kt.prototype,"user_id",void 0),kt=Re([le(He),ue("forgot"),ce("5.3.1")],kt);let Ft=class LogModel extends pe{};Re([ae.Id(7),De("design:type",String)],Ft.prototype,"id",void 0),Re([ae.Enum(Be),ge(Be.INFO),De("design:type",String)],Ft.prototype,"level",void 0),Re([ae.Text(),De("design:type",String)],Ft.prototype,"message",void 0),Re([ae.String(),De("design:type",String)],Ft.prototype,"source",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Ft.prototype,"created_at",void 0),Ft=Re([le(He),ue("log"),ce("5.3.1")],Ft);let Bt=class MigrationModel extends pe{};Re([ae.Id(7),De("design:type",String)],Bt.prototype,"id",void 0),Re([ae.String(),De("design:type",String)],Bt.prototype,"model",void 0),Re([ae.String(),De("design:type",String)],Bt.prototype,"version",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Bt.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],Bt.prototype,"updated_at",void 0),Bt=Re([le(He),ue("migration"),ce("5.3.1")],Bt);let Kt=class SessionModel extends pe{};Re([ae.Id(7),De("design:type",String)],Kt.prototype,"id",void 0),Re([ae.Json(),De("design:type",Object)],Kt.prototype,"data",void 0),Re([ae.FullDate(),De("design:type",Date)],Kt.prototype,"expired_at",void 0),Re([ae.CreatedAt(),De("design:type",Date)],Kt.prototype,"created_at",void 0),Re([ae.UpdatedAt(),De("design:type",Date)],Kt.prototype,"updated_at",void 0),Kt=Re([le(He),ue("session"),ce("5.3.1")],Kt);class Log{static error(e,t,i){return Ne(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,i)})}static info(e,t,i){return Ne(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,i)})}static warn(e,t,i){return Ne(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,i)})}static writeRaw(e,t,i,r){return Ne(this,void 0,void 0,function*(){var n;r&&x.console(null!==(n=this.colors[e])&&void 0!==n?n:C.White,e,t),He&&(yield Ft.create({level:e,message:t,source:null!=i?i:""}).catch(x.catch))})}}Log.colors={error:C.Red,info:C.Cyan,warn:C.Yellow};class Loggable{get log(){return e=>Loggable.logInfo(this,e)}static get log(){return e=>this.logInfo(this,e)}get error(){return e=>Loggable.logError(this,e)}static get error(){return e=>this.logError(this,e)}static logError(e,t){var i,r;Log.error(null!==(r=null!==(i=null==t?void 0:t.message)&&void 0!==i?i:t)&&void 0!==r?r:"",this.source(e),Env.CONSOLE_ERROR)}static logInfo(e,t){Log.info(null!=t?t:"",this.source(e),Env.CONSOLE_ERROR)}static source(e){var t,i,r;const n=null!==(r=null!==(i=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)&&void 0!==i?i:null==e?void 0:e.name)&&void 0!==r?r:"null";return Env.BASE_NAME?`${Env.BASE_NAME}.${n}`:n}}class Config extends Loggable{static all(e){return Ne(this,void 0,void 0,function*(){var t;const i=null!==(t=yield Ht.findAll({where:(null==e?void 0:e.length)?{key:{[he.in]:e}}:{}}).catch(this.error))&&void 0!==t?t:[];return Object.fromEntries(i.map(e=>[e.key,e.value]))})}static del(e){return Ne(this,void 0,void 0,function*(){return((yield Ht.destroy({where:{key:e}}).catch(this.error))||0)>0})}static get(e){return Ne(this,arguments,void 0,function*(e,t=""){const[i]=(yield Ht.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return i?i.value:t})}static set(e,t){return Ne(this,void 0,void 0,function*(){const[i,r]=(yield Ht.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];i&&!r&&(i.value=t,yield i.save().catch(this.error))})}}class SessionStore extends Se{constructor(){super(),this.all=e=>Ne(this,void 0,void 0,function*(){e=e||Y;const t=yield Kt.findAll({attributes:["id","expired_at"],where:{expired_at:{[he.gte]:new Date}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.id)),e()}),this.clear=e=>Ne(this,void 0,void 0,function*(){yield Kt.destroy().catch(x.catch),e&&e()}),this.destroy=(e,t)=>Ne(this,void 0,void 0,function*(){yield Kt.destroy({where:{id:e}}).catch(x.catch),t&&t()}),this.expired=()=>Ne(this,void 0,void 0,function*(){yield Kt.destroy({where:{expired_at:{[he.lt]:new Date}}}).catch(x.catch)}),this.get=(e,t)=>Ne(this,void 0,void 0,function*(){t=t||Y;const i=yield Kt.findOne({where:{id:e,expired_at:{[he.gte]:new Date}}}).catch(e=>(t(e),null));if(i){if(i.data.cookie){if(new Date(i.data.cookie.expires).getTime()<=Date.now())return yield i.destroy().catch(x.catch),void t(null)}t(null,i.data)}else t(null)}),this.length=e=>Ne(this,void 0,void 0,function*(){e&&e(null,(yield Kt.count().catch(x.catch))||0)}),this.set=(e,t,i)=>Ne(this,void 0,void 0,function*(){i=i||Y;const r=new Date;r.setTime(r.getTime()+Env.API_SESSION_LIFETIME);const[n,o]=(yield Kt.findOrCreate({where:{id:e},defaults:{id:e,data:t,expired_at:r}}).catch(x.catch))||[];n?(o||(n.data=t,n.expired_at=r,yield n.save().catch(x.catch)),i()):i()}),setInterval(this.expired,6e4)}}let qt=class Service{};qt=Re([fe(Loggable)],qt);let Vt=class AuthService extends qt{constructor(){super(...arguments),this.userAttributes={exclude:["username","notes","deleted_at"]}}create(e){return Ne(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new o("TOKEN_KEY not found");const{id:t}=e,i=B(),r=yield Pt.create({secret:i,user_id:t}).catch(this.error);if(!r)throw new s;return{auth:r,token:Oe.sign({id:t,secret:i},Env.TOKEN_KEY,this.options())}})}destroy(e){return Ne(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return Ne(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new o("TOKEN_KEY not found");const{decode:i}=yield this.verify(e,Env.TOKEN_TTL_RENEW/1e3);if(!i)throw new t("Invalid token");const{id:r,secret:n}=i;if(r&&n){const e=yield Nt.findOne({where:{id:r,status:qe.ACTIVE}}).catch(this.error);if(e){const t=yield Pt.findOne({where:{secret:n,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at){t.secret=B(),yield t.save().catch(this.error);return{auth:t,token:Oe.sign({id:r,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t("Invalid token")})}user(e){return Ne(this,void 0,void 0,function*(){const{decode:i}=yield this.verify(e);if(!i)throw new t("Invalid token");const{id:r,secret:n}=i;if(r&&n){const e=yield Nt.findOne({attributes:this.userAttributes,where:{id:r,status:qe.ACTIVE}}).catch(this.error);if(e){const t=yield Pt.findOne({where:{secret:n,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at)return{auth:t,user:e}}}throw new t("Invalid token")})}options(){return{algorithm:"RS256",expiresIn:`${Env.TOKEN_TTL}ms`}}verify(e,i){return Ne(this,void 0,void 0,function*(){if(!Env.TOKEN_CRT)throw new o("TOKEN_CRT not found");if(!e||e.split(".").length<3)throw new t("Invalid token");try{return{decode:Oe.verify(e,Env.TOKEN_CRT,{clockTolerance:i})}}catch(e){throw new t("Invalid token")}})}key(e){return Ne(this,void 0,void 0,function*(){if(!e)throw new t("Invalid token");const i=yield Nt.findOne({attributes:this.userAttributes,where:{token:e,status:qe.ACTIVE}}).catch(this.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield Pt.findOrCreate({where:{secret:t,user_id:i.id},defaults:{secret:t,user_id:i.id}}).catch(this.error))||[];if(r)return r.revoked_at&&(r.revoked_at=null,yield r.save().catch(this.error)),{auth:r,user:i}}throw new t("Invalid token")})}};Vt=Re([_e()],Vt);class ModelService extends qt{constructor(e,t){var i,r;super(),this.attributes=[],this.permissions=[],this.search=[],this.model=e,(null==t?void 0:t.permissions)&&(this.permissions=t.permissions);const n=Object.keys(e.getAttributes());this.attributes=this.filterAttributes(n,null!==(i=null==t?void 0:t.attributes)&&void 0!==i?i:[]),this.search=this.filterAttributes(n,null!==(r=null==t?void 0:t.search)&&void 0!==r?r:this.attributes)}applySelect(e,t,i){if(!t)return;const r=null==e?void 0:e.getQuery(i?`${i}_select`:"select"),n=t.attributes,o=e=>n.includes(e);t.attributes=[],k(r)&&r.length&&t.attributes.push(...r.split(/\s*,\s*/g).filter(o)),t.attributes.length||(t.attributes=n)}applyOrders(e,t){if(!t)return;const i=null==e?void 0:e.getQuery("asc"),r=null==e?void 0:e.getQuery("desc"),n=[],o=t.attributes,s=e=>o.includes(e);k(i)&&i.length&&n.push(...i.split(/\s*,\s*/g).filter(s).map(e=>[e,"ASC"])),k(r)&&r.length&&n.push(...r.split(/\s*,\s*/g).filter(s).map(e=>[e,"DESC"])),n.length&&(t.order=n)}applyPagination(e,t){if(!t)return;const i=null==e?void 0:e.getQuery("limit"),r=null==e?void 0:e.getQuery("offset");D(t.limit)&&(t.limit=Env.MODEL_LIMIT,k(i)&&(t.limit=parseInt(i)||0),t.limit=$(t.limit,-1,Env.MODEL_LIMIT_MAX)),t.limit<0&&(t.limit=void 0),k(r)&&(t.offset=parseInt(r)||0,t.offset<0&&(t.offset=void 0))}applySearch(e,t){var i;if(!t)return;const r=null==e?void 0:e.getQuery("search");r&&k(r)&&(t.where=Object.assign(Object.assign({},null!==(i=t.where)&&void 0!==i?i:{}),{[he.or]:this.search.map(e=>({[e]:{[he.substring]:r}}))}))}applyWhere(e,t,i){var r,n;if(!t)return null;const o=null==e?void 0:e.getQuery(i?`${i}_where`:"where");if(!k(o))return null;const s=t.attributes,d=ye.parse(s,o);return D(d.error)?(t.where=Object.assign(Object.assign({},null!==(r=t.where)&&void 0!==r?r:{}),null!==(n=d.value)&&void 0!==n?n:{}),null):new a(d.error.join(", "))}countAll(e){return Ne(this,void 0,void 0,function*(){var t,i;const{ctx:r,options:n={}}=e,o=W({},n);o.attributes=this.getAttributes(null!==(t=null==o?void 0:o.attributes)&&void 0!==t?t:[]),this.applySearch(r,o);const s=this.applyWhere(r,o);if(s)return null==r||r.error(s),0;this.applySelect(r,o);const a=null!==(i=yield this.model.count(Object.assign(Object.assign({},o),{distinct:!!o.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error))&&void 0!==i?i:0;return null==r||r.prepare(d.OK,{count:a}),a})}create(e){return Ne(this,void 0,void 0,function*(){var t,i;const{body:r={},ctx:n,options:o={}}=e,a=W({},o),l=yield this.model.create(Object.assign({},W({},null!==(i=null===(t=null==n?void 0:n.req)||void 0===t?void 0:t.body)&&void 0!==i?i:{},r)),Object.assign(Object.assign({},a),{ctx:n})).catch(this.error);if(!l)return null==n||n.error(new s),null;const{primaryKeyAttribute:u}=this.model;return null==n||n.prepare(d.OK,{[u]:l.getDataValue(u)}),l})}delete(e){return Ne(this,void 0,void 0,function*(){var t,i;const{ctx:r,id:n,options:s={}}=e,{primaryKeyAttribute:a}=this.model,d=null!==(t=null==r?void 0:r.getParam(a))&&void 0!==t?t:n;if(D(d))return null==r||r.error(new l),0;const u=W({},s),c=yield this.model.destroy(Object.assign(Object.assign(Object.assign({},u),{where:{[he.and]:Object.assign({[a]:d},null!==(i=null==u?void 0:u.where)&&void 0!==i?i:{})},individualHooks:!0}),{ctx:r})).catch(this.error);return c?(null==r||r.success("OK"),c):(null==r||r.error(new o),0)})}filterAttributes(e,t){if(K(t))return t.length?t.filter(t=>k(t)&&e.includes(t)):e;const{exclude:i,include:r}=t,n=D(r)?e:r.filter(t=>k(t)&&e.includes(t)),o=null!=i?i:[];return o.length?n.filter(e=>!o.includes(e)):n}findAll(e){return Ne(this,void 0,void 0,function*(){var t,i;const{ctx:r,callback:n,options:o={},query:s=!0}=e,a=W({},o);if(a.attributes=this.getAttributes(null!==(t=null==a?void 0:a.attributes)&&void 0!==t?t:[]),s&&this.applySelect(r,a),this.applyOrders(r,a),this.applyPagination(r,a),(null!==(i=null==a?void 0:a.limit)&&void 0!==i?i:0)>Env.MODEL_LIMIT_MAX&&(a.limit=Env.MODEL_LIMIT_MAX),this.applySearch(r,a),s){const e=this.applyWhere(r,a);if(e)return null==r||r.error(e),{count:0,records:[]}}const[l,u]=yield Promise.all([this.model.count(Object.assign(Object.assign({},a),{distinct:!!a.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error).then(e=>null!=e?e:0),this.model.findAll(a).catch(this.error).then(e=>null!=e?e:[])]),c={count:l,records:n?yield n(u):u};return null==r||r.prepare(d.OK,c),c})}findOne(e){return Ne(this,void 0,void 0,function*(){var t,i,r;const{callback:n,ctx:s,id:a,options:u={},query:c=!0}=e,{primaryKeyAttribute:p}=this.model,v=null!==(t=null==s?void 0:s.getParam(p))&&void 0!==t?t:a;if(D(v))return null==s||s.error(new l),null;const g=W({},u);g.attributes=this.getAttributes(null!==(i=null==g?void 0:g.attributes)&&void 0!==i?i:[]),c&&this.applySelect(s,g);const h=yield this.model.findOne(Object.assign(Object.assign({},g),{where:{[he.and]:Object.assign({[p]:v},null!==(r=null==g?void 0:g.where)&&void 0!==r?r:{})}})).catch(this.error);return h?(null==s||s.prepare(d.OK,n?yield n(h):h.toJSON()),h):(null==s||s.error(new o),null)})}getAttributes(e){return this.filterAttributes(this.attributes,e)}include(e,t){var i;const r=z(t),{ctx:n}=null!=t?t:{};r.attributes=this.filterAttributes(Object.keys(e.getAttributes()),null!==(i=r.attributes)&&void 0!==i?i:[]),this.applySearch(n,r);const o=this.applyWhere(n,r,t.name);return o?(null==n||n.error(o),null):(this.applySelect(n,r,t.name),Object.assign({model:e},r))}name(){return this.model.tableName}sync(){return Ne(this,void 0,void 0,function*(){if(!this.permissions.length)return;const e=this.name().toLowerCase(),t={description:"",active:!0};yield G(this.permissions,i=>Ne(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=J(e.replace(/_/g," ")," ");yield wt.findOrCreate({where:{key:r},defaults:Object.assign({name:`${n} ${J(i," ")}`,key:r,tags:n},t)})}))})}update(e){return Ne(this,void 0,void 0,function*(){var t,i,r,n;const{ctx:s,body:a,id:d,options:u={}}=e,{primaryKeyAttribute:c}=this.model,p=null!==(t=null==s?void 0:s.getParam(c))&&void 0!==t?t:d;if(D(p))return null==s||s.error(new l),!1;const v=W({},u),g=W({},null!==(r=null===(i=null==s?void 0:s.req)||void 0===i?void 0:i.body)&&void 0!==r?r:{},null!=a?a:{}),h=yield this.model.findOne(Object.assign(Object.assign({},v),{attributes:this.getAttributes([c,...Object.keys(g)]),where:{[he.and]:Object.assign({[c]:p},null!==(n=null==v?void 0:v.where)&&void 0!==n?n:{})}})).catch(this.error);return h?(h.set(g),h.changed()?(null==s||s.success("OK"),yield h.save(Object.assign({},{ctx:s})).catch(this.error),!0):(null==s||s.success("Record not changed"),!1)):(null==s||s.error(new o),!1)})}}let Ut=class UserService extends qt{constructor(){super(...arguments),this.hashOptions={algorithm:Env.PASSWORD_ALGORITHM,memoryCost:Env.PASSWORD_MEMORY_COST,parallelism:Env.PASSWORD_PARALLELISM,timeCost:Env.PASSWORD_TIME_COST}}createPassword(e,t,i){return Ne(this,void 0,void 0,function*(){yield Dt.update({revoked_at:new Date},{where:{revoked_at:null,user_id:e}}).catch(this.error);const r=Ae(t+Env.PASSWORD_PEPPER,this.hashOptions);yield Dt.create({hash:r,user_id:e},Object.assign({},{ctx:i})).catch(this.error)})}getGroups(e,t){return Ne(this,void 0,void 0,function*(){var i;return Q((null!==(i=yield xt.findAll({attributes:["name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:Object.assign({user_id:e},t||X(t)?{tenant_id:t}:{})}]}).catch(this.error))&&void 0!==i?i:[]).map(e=>e.name))})}getPermissions(e,t){return Ne(this,void 0,void 0,function*(){var i;return(null!==(i=yield wt.findAll({attributes:["name"],where:{active:!0},include:[{association:"groups_permissions",required:!0,include:[{association:"group",required:!0,attributes:["id","name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:Object.assign({user_id:e},t||X(t)?{tenant_id:t}:{})}]}]}]}).catch(this.error))&&void 0!==i?i:[]).map(e=>e.name)})}getTenants(e){return Ne(this,void 0,void 0,function*(){var t;return(null!==(t=yield Rt.findAll({attributes:["id","name"],where:{status:Ke.ACTIVE},include:[{association:"users_tenants",required:!0,where:{user_id:e}}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>({id:e.id,name:e.name}))})}};Ut=Re([_e()],Ut);class Application extends u{constructor(e,t){super(e,W({},{cross:!!Env.HTTP_CROSS&&("*"===Env.HTTP_CROSS||{origin:Env.HTTP_CROSS.split(",")}),hybrid:Env.API_HTTP_HYBRID,json:{strict:Env.API_BODYPARSER_STRICT,inflate:Env.API_BODYPARSER_INFLATE,limit:Env.API_BODYPARSER_LIMIT,type:Env.API_BODYPARSER_TYPE},notfound:Env.API_HTTP_NOTFOUND,path:Env.API_HTTP_PATH,port:Env.HTTP_PORT,public:Env.HTTP_PUBLIC,redirect:Env.API_HTTP_REDIRECT,session:{store:new SessionStore,name:Env.API_SESSION_NAME,secret:Env.API_SESSION_SECRET,cookie:{maxAge:Env.API_SESSION_LIFETIME},genid:B},tls:{ca:Env.HTTP_TLS_CA,cert:Env.HTTP_TLS_CRT,key:Env.HTTP_TLS_KEY}},null!=t?t:{})),this.hash=new R(Env.API_KEY_HASH)}error(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.error(e.message,t,Env.CONSOLE_ERROR)}log(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return Ne(this,void 0,void 0,function*(){yield He.sync(),yield this.migrations(He),yield Z(this.controllers,e=>Ne(this,void 0,void 0,function*(){N(e.sync)&&(yield e.sync(this))})),this.authService=new Vt,this.userService=new Ut,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new ne({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>Ne(this,void 0,void 0,function*(){t.url||(t.url=""),e.on("close",()=>{}),yield ee(2e3)})))})}migrations(e){return Ne(this,void 0,void 0,function*(){const t=[];yield Z(Object.keys(e.models),i=>Ne(this,void 0,void 0,function*(){var r;const n=e.models[i],o=n.version();if(!o)return;const[s,a]=null!==(r=yield Bt.findOrCreate({where:{model:n.tableName},defaults:{model:n.tableName,version:""}}).catch(this.error))&&void 0!==r?r:[];s&&(a||s.version!=o)&&(s.version=o,yield s.save().catch(this.error),t.push(n))})),yield Z(t,e=>Ne(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}let Yt=class BaseController extends te{constructor(){super(...arguments),this.permissions=[]}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}session(e,t,i){return Ne(this,void 0,void 0,function*(){i.auth&&i.user&&(i.user_agent?i.user_agent!=t&&i.regenerate(Y):(i.user_agent=t,i.save(Y))),e.next()})}sync(){return Ne(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=J(e.replace(/_/g," ")," ");yield Z(this.permissions,i=>Ne(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield wt.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${J(i," ")}`,active:!0}})}))})}};Re([je(0,c()),je(1,p("user-agent")),je(2,v()),De("design:type",Function),De("design:paramtypes",[n,String,Object]),De("design:returntype",Promise)],Yt.prototype,"session",null),Yt=Re([fe(Loggable)],Yt);let $t=class ModelController extends Yt{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"],this.search=[]}countAll(e){return Ne(this,void 0,void 0,function*(){return yield this.service.countAll(e)})}create(e){return Ne(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return Ne(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return Ne(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return Ne(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}include(e,t){return this.service.include(e,t)}sync(){return Ne(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=J(e.replace(/_/g," ")," ");yield Z(this.permissions,i=>Ne(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield wt.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${J(i," ")}`,active:!0}})})),this.service=new ModelService(this.model,{attributes:this.attributes.length?this.attributes:void 0,search:this.search.length?this.search:void 0})})}update(e){return Ne(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}};$t=Re([g(Yt)],$t);let Wt=class AuditsController extends $t{constructor(){super(...arguments),this.model=Lt,this.permissions=["read"]}all(e,t,i){return Ne(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this.findAll({ctx:e,options:{attributes:{exclude:["currently","previously"]},where:r,order:[["created_at","DESC"]]}})})}get(e){return Ne(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};Re([h(),Je(),$e(),je(0,c()),je(1,y("type")),je(2,y("table")),De("design:type",Function),De("design:paramtypes",[n,String,String]),De("design:returntype",Promise)],Wt.prototype,"all",null),Re([h("/:id"),Je(),$e(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],Wt.prototype,"get",null),Wt=Re([m("/audits"),g($t)],Wt);let zt=class AuthController extends Yt{constructor(){super(...arguments),this.authService=new Vt}login(e,i,r,n,o,s){return Ne(this,void 0,void 0,function*(){var a;yield ee(Env.SLEEP_AUTH);const d=yield Nt.findOne({where:{[he.or]:[{email:r},{username:r}]}}).catch(this.error);if(!d)return e.error(new t("Invalid credentials")),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const l=yield Dt.findOne({where:{revoked_at:null,user_id:d.id}}).catch(this.error);if(n+=Env.PASSWORD_PEPPER,!l||!(yield Te(l.hash,n).catch(Y)))return e.error(new t("Invalid credentials")),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const u=yield It.findOne({where:{active:!0,user_id:d.id}}).catch(this.error);if(u)return e.error(new t("Activation Required")),s.emit("auth.activation",{ctx:e,register:u,user:d}),void this.emit("auth.activation",{ctx:e,register:u,user:d});if(d.status!=qe.ACTIVE)return e.error(new t("Invalid credentials")),s.emit("auth.failure",{ctx:e,user:d}),void this.emit("auth.failure",{ctx:e,user:d});const{auth:c,token:p}=null!==(a=yield this.authService.create(d).catch(t=>{e.error(t),s.emit("auth.failure",{ctx:e}),this.emit("auth.failure",{ctx:e})}))&&void 0!==a?a:{};c&&p&&(c.user_agent=i,c.ip_address=e.getIp(),yield c.save().catch(this.error),Env.API_TOKEN_COOKIE_SET&&e.setCookie(Env.API_TOKEN_COOKIE,p,{maxAge:o?Env.TOKEN_TTL:void 0}),e.json({token:p}),s.emit("auth.login",{ctx:e,auth:c,user:d}),this.emit("auth.login",{ctx:e,auth:c,user:d}))})}logout(e,i,r,n){return Ne(this,void 0,void 0,function*(){if(yield this.authService.destroy(i))return Env.API_TOKEN_COOKIE_SET&&e.clearCookie(Env.API_TOKEN_COOKIE),e.success("OK"),n.emit("auth.logout",{auth:i,ctx:e,user:r}),void this.emit("auth.logout",{auth:i,ctx:e,user:r});e.error(new t("Access Denied"))})}renew(e,t,i,r){return Ne(this,void 0,void 0,function*(){var n;const{auth:o,token:s}=null!==(n=yield this.authService.renew(i).catch(t=>{e.error(t)}))&&void 0!==n?n:{};o&&s&&(o.user_agent=t,yield o.save().catch(this.error),e.json({token:s}),r.emit("auth.renew",{auth:o,ctx:e}),this.emit("auth.renew",{auth:o,ctx:e}))})}user(e,t){return Ne(this,void 0,void 0,function*(){const{groups:i,permissions:r,profile:n,tenants:o}=e.req;if(!(i&&r&&n&&o))return e.error(new s);e.json(Object.assign(Object.assign({},t.toJSON()),{groups:i,permissions:r,profile:n,tenants:o}))})}};Re([E("/login"),f(e=>({username:e.string().min(3),password:e.string().min(5),remember:e.boolean().parse().default(!1)})),je(0,c()),je(1,p("user-agent")),je(2,_("username")),je(3,_("password")),je(4,_("remember")),je(5,S()),De("design:type",Function),De("design:paramtypes",[n,String,String,String,Boolean,Application]),De("design:returntype",Promise)],zt.prototype,"login",null),Re([h("/logout"),Je(),je(0,c()),je(1,Qe()),je(2,it()),je(3,S()),De("design:type",Function),De("design:paramtypes",[n,Pt,Nt,Application]),De("design:returntype",Promise)],zt.prototype,"logout",null),Re([E("/renew"),f(e=>({token:e.string()})),je(0,c()),je(1,p("user-agent")),je(2,_("token")),je(3,S()),De("design:type",Function),De("design:paramtypes",[n,String,String,Application]),De("design:returntype",Promise)],zt.prototype,"renew",null),Re([h(),h("/me"),Je(),je(0,c()),je(1,it()),De("design:type",Function),De("design:paramtypes",[n,Nt]),De("design:returntype",Promise)],zt.prototype,"user",null),zt=Re([m("/auth"),g(Yt)],zt);let Gt=class CrudController extends $t{constructor(){super(...arguments),this._crud={}}CrudArgumentsCountAll(e){return{ctx:e}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidateCreate(){return this._crud}CrudValidateUpdate(){return this._crud}add(e){return Ne(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return Ne(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}rows(e){return Ne(this,void 0,void 0,function*(){yield this.countAll(this.CrudArgumentsCountAll(e))})}del(e){return Ne(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return Ne(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return Ne(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validate(e,t){var i,r;const n=V.object(t).parse().validate(null!==(r=null===(i=e.req)||void 0===i?void 0:i.body)&&void 0!==r?r:{});if(n.error)return e.error(new a(n.message||n.error));e.req.body=n.value,e.next()}validateCreate(e){const t=this.CrudValidateCreate();if(t==this._crud)return e.error(new s);this.validate(e,t)}validateUpdate(e){const t=this.CrudValidateUpdate();if(t==this._crud)return e.error(new s);this.validate(e,t)}};Re([E(),Je(),Ue(),O("validateCreate"),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],Gt.prototype,"add",null),Re([h(),Je(),$e(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],Gt.prototype,"all",null),Re([h("/count"),Je(),$e(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],Gt.prototype,"rows",null),Re([A("/:id"),Je(),Ye(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],Gt.prototype,"del",null),Re([h("/:id"),Je(),$e(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],Gt.prototype,"get",null),Re([T("/:id"),Je(),We(),O("validateUpdate"),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],Gt.prototype,"set",null),Re([je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",void 0)],Gt.prototype,"validateCreate",null),Re([je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",void 0)],Gt.prototype,"validateUpdate",null),Gt=Re([g($t)],Gt);let Jt=class FilesController extends Yt{constructor(){super(...arguments),this.directory=Env.HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return Ne(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=Ce(this.directory,t);if(!be(i)||!Ie(i).isDirectory())return e.error(new o);let r;return r=Pe(i),r=r.map(e=>this.info(Ce(i,e))),r=r.filter(ie),Object.assign(Object.assign({},this.info(i)),{files:r})})}info(e){if(!be(e))return null;const t=Ie(e),i=e.split("/").pop();e=e.replace(this.directory,"/").replace(/^\/\//,"/");const r=t.isDirectory();return{name:i,path:e.replace(/^\/\//,"/"),size:t.size,extension:r?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:r,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return Ne(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=J(e.replace(/_/g," ")," ");yield Z(this.permissions,i=>Ne(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield wt.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${J(i," ")}`,active:!0}})}))})}};Re([h("/path"),h("/path/*path"),Je(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],Jt.prototype,"files",null),Jt=Re([m("/files"),g(Yt)],Jt);let Qt=class ForgotController extends Yt{check(e,t){return Ne(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.error(new o);i.secret=re(),yield i.save(),e.json({token:i.secret})})}forgot(e,t,i){return Ne(this,void 0,void 0,function*(){yield ee(Env.SLEEP_FORGOT);const r=t,n=yield Nt.findOne({where:{[he.or]:[{email:r},{username:t}]}}).catch(this.error);if(!n)return e.error(new o);const s=re(),a=Date.now()+6e4*Env.TOKEN_TTL_FORGOT,d=yield kt.create({token:s,timestamp:a,active:!0,user_id:n.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:d,user:n}),this.emit("forgot.send",{ctx:e,forgot:d,user:n})})}reset(e,t,i,r){return Ne(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i)return e.error(new o);i.active=!1,yield i.save().catch(this.error),yield i.user.save().catch(this.error),e.success("OK"),r.emit("forgot.reset",{ctx:e,user:i.user}),this.emit("forgot.reset",{ctx:e,user:i.user})})}find(e){return Ne(this,void 0,void 0,function*(){return yield kt.findOne({where:{token:e,active:!0},include:[{association:"users",required:!0}]}).catch(this.error)})}};Re([h("/check"),f(e=>({token:e.string()})),je(0,c()),je(1,_("token")),De("design:type",Function),De("design:paramtypes",[n,String]),De("design:returntype",Promise)],Qt.prototype,"check",null),Re([E(),f(e=>({username:e.string().min(4)})),je(0,c()),je(1,_("username")),je(2,S()),De("design:type",Function),De("design:paramtypes",[n,String,Application]),De("design:returntype",Promise)],Qt.prototype,"forgot",null),Re([E("/reset"),f(e=>({token:e.string(),password:e.string().min(5)})),je(0,c()),je(1,_("token")),je(2,_("password")),je(3,S()),De("design:type",Function),De("design:paramtypes",[n,String,String,Application]),De("design:returntype",Promise)],Qt.prototype,"reset",null),Qt=Re([m("/forgot"),g(Yt)],Qt);let Xt=class GroupsController extends Gt{constructor(){super(...arguments),this.model=xt,this.schemaCreate={name:V.string(),description:V.string().default(""),type:V.enum(Object.keys(Fe)).default(Fe.SYSTEM),active:V.boolean().parse(),metadata:V.object().parse().default({})},this.schemaUpdate={description:V.string().optional(),type:V.enum(Object.keys(Fe)).optional(),active:V.boolean().parse().optional(),metadata:V.object().parse().optional()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}};Xt=Re([m("/groups"),g(Gt)],Xt);let Zt=class GroupsPermissionsController extends $t{constructor(){super(...arguments),this.model=Mt,this.permissions=[]}all(e,t){return Ne(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{association:"permission"}]},callback:e=>e.map(e=>e.permission),query:!1})})}set(e,t,i){return Ne(this,void 0,void 0,function*(){const r=yield xt.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new o);const n=r.id,s=[];yield Z(Q(i),t=>Ne(this,void 0,void 0,function*(){var i;if(!(yield wt.count({where:{id:t}})))return;const[r]=null!==(i=yield Mt.findOrCreate(Object.assign({where:{group_id:n,permission_id:t},defaults:{group_id:n,permission_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];r&&s.push(t)})),yield Mt.destroy(Object.assign({where:{group_id:n,permission_id:{[he.notIn]:s}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Re([h("/:id/permissions"),Je(),$e("groups"),je(0,c()),je(1,b("id")),De("design:type",Function),De("design:paramtypes",[n,String]),De("design:returntype",Promise)],Zt.prototype,"all",null),Re([T("/:id/permissions"),Je(),We("groups"),f(e=>({permissions:e.array(e.string().uuid())})),je(0,c()),je(1,b("id")),je(2,_("permissions")),De("design:type",Function),De("design:paramtypes",[n,String,Array]),De("design:returntype",Promise)],Zt.prototype,"set",null),Zt=Re([m("/groups"),g($t)],Zt);let ei=class HealthController{ping(e){return Ne(this,void 0,void 0,function*(){e.json({status:"ok",timestamp:Date.now(),uptime:process.uptime()})})}};Re([I("/"),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],ei.prototype,"ping",null),ei=Re([m("/health")],ei);let ti=class LogsController extends $t{constructor(){super(...arguments),this.model=Ft,this.permissions=["read"]}all(e){return Ne(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}};Re([h(),Je(),$e(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],ti.prototype,"all",null),ti=Re([m("/logs"),g($t)],ti);let ii=class McpController extends Yt{constructor(){super(...arguments),this.tools=new McpToolRegistry,this.toolsRegistered=!1,this.handler=new McpHttpHandler({sessions:new McpSessionStore(Env.MCP_SESSION_TTL),tools:this.tools,allowedOrigins:Env.MCP_ALLOWED_ORIGINS?Env.MCP_ALLOWED_ORIGINS.split(",").map(e=>e.trim()).filter(Boolean):[],logger:{toolCall:e=>Ne(this,void 0,void 0,function*(){yield Log.info(JSON.stringify(e),"mcp")})}}),this.rateLimiter=new McpRateLimiter(Env.MCP_RATE_LIMIT_MAX,Env.MCP_RATE_LIMIT_WINDOW)}sync(e){const t=Object.create(null,{sync:{get:()=>super.sync}});return Ne(this,void 0,void 0,function*(){yield t.sync.call(this),this.toolsRegistered||(this.toolsRegistered=!0,e&&(e.instance.use((e,t,i,r)=>{if(!this.isMcpEndpoint(t))return r(e);const n=this.jsonParseErrorResponse(e);if(!n)return r(e);i.status(n.status).json(n.body)}),e.instance.use((e,t,i)=>{if(!this.isMcpEndpoint(e)||!["GET","HEAD"].includes(e.method))return i();t.setHeader("Allow",gt),t.status(405).end()}),this.discoverMcpTools(e.controllers).forEach(e=>this.tools.register(e))))})}options(e){return Ne(this,void 0,void 0,function*(){this.respond(e,this.handler.options(this.request(e)))})}post(e){return Ne(this,void 0,void 0,function*(){this.rateLimiter.consume(e.getIp()||"unknown")?this.respond(e,yield this.handler.post(this.request(e))):e.res.status(429).end()})}delete(e){return Ne(this,void 0,void 0,function*(){this.respond(e,this.handler.delete(this.request(e)))})}getMcpToolMetadata(e){const t=Ee(mt,e,[]);return t.length||"function"==typeof e?t:Ee(mt,Object.getPrototypeOf(e),[])}discoverMcpTools(e){const t=[];for(const i of e)for(const e of this.getMcpToolMetadata(i))t.push(this.createMcpToolFromMetadata(i,e));return t}createMcpToolFromMetadata(e,t){const i=e[t.propertyKey];if(!N(i))throw new Error(`MCP tool "${t.name}" handler was not found`);return Et(t),Object.assign(Object.assign(Object.assign({name:t.name,title:t.title,description:t.description},void 0!==t.input?{input:t.input}:{}),void 0!==t.output?{output:t.output}:{}),{run:(t,r)=>i.call(e,t,r)})}request(e){const t=e.req.user;return{body:e.getBody(),headers:e.getHeaders(),ip:e.getIp(),context:{auth:e.req.auth,groups:e.req.groups,permissions:e.req.permissions,profile:e.req.profile,user:t,userId:null==t?void 0:t.id}}}isJsonParseError(e){if(!(e instanceof SyntaxError))return!1;const t=e;return"entity.parse.failed"===t.type||400===t.status||400===t.statusCode}isMcpEndpoint(e){const t=(e.originalUrl||e.url).split("?")[0].replace(/\/+$/g,"")||"/";return t===`${(Env.API_HTTP_PATH||"/").replace(/\/+$/g,"")||""}/mcp`.replace(/\/+/g,"/")||"/mcp"===t}jsonParseErrorResponse(e){if(this.isJsonParseError(e))return{status:400,body:st(null,new McpParseError("Parse error",{message:e.message}))}}respond(e,t){var i;for(const[r,n]of Object.entries(null!==(i=t.headers)&&void 0!==i?i:{}))e.res.setHeader(r,n);void 0!==t.body?e.res.status(t.status).json(t.body):e.res.status(t.status).end()}};Re([P(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],ii.prototype,"options",null),Re([E(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],ii.prototype,"post",null),Re([A(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],ii.prototype,"delete",null),ii=Re([m("/mcp"),g(Yt)],ii);let ri=class PermissionsController extends Gt{constructor(){super(...arguments),this.model=wt,this.schemaCreate={name:V.string(),description:V.string().default(""),active:V.boolean().parse(),metadata:V.object().parse().default({})},this.schemaUpdate={description:V.string().optional(),active:V.boolean().parse().optional(),metadata:V.object().parse().optional()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}};ri=Re([m("/permissions"),g(Gt)],ri);let ni=class RegisterController extends Yt{register(e,t,i){return Ne(this,void 0,void 0,function*(){yield ee(Env.SLEEP_REGISTRY);const{name:r,date:n,email:o,username:a,password:d,confirm:l}=t,u=a||o,c=j(d);if(yield Nt.count({where:{[he.or]:[{email:o},{username:u}]}}).catch(this.error))return e.error("INVALID EMAIL OR USERNAME");if(c!=j(l))return e.error("INVALID PASSWORD");const p=yield Nt.create({name:r,email:o,username:u,password:c,avatar:"",date:n,description:"",status:qe.PENDING}).catch(this.error);if(!p)return e.error(new s);const v=yield It.create({token:yield this.getId(),active:!0,user_id:p.id}).catch(this.error);if(!v)return yield p.destroy().catch(this.error),e.error(new s);e.success("OK"),i.emit("register.user",{ctx:e,register:v,user:p}),this.emit("register.user",{ctx:e,register:v,user:p})})}confirm(e,t,i){return Ne(this,void 0,void 0,function*(){const r=yield It.findOne({where:{token:t,active:!0},include:[{association:"users",required:!0}]}).catch(this.error);if(!r)return e.error(new o);r.active=!1,yield r.save().catch(this.error),r.user.status=qe.ACTIVE,yield r.user.save().catch(this.error),e.success("OK"),i.emit("register.confirm",{ctx:e,register:r,user:r.user}),this.emit("register.confirm",{ctx:e,register:r,user:r.user})})}send(e,t,i){return Ne(this,void 0,void 0,function*(){const r=t,n=yield It.findOne({where:{active:!0},include:[{model:Nt,required:!0,where:{[he.or]:[{email:r},{username:t}]}}]}).catch(this.error);if(!n)return e.error(new o);e.success("OK"),i.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})})}getId(){return Ne(this,void 0,void 0,function*(){const e=B();return(yield It.count({where:{token:e}}))?this.getId():e})}};Re([E(),f(e=>({name:e.string(),date:e.date(),email:e.string().email(),username:e.string().min(4).default(e.ref("email")),password:e.string().min(5),confirm:e.string().min(5)})),je(0,c()),je(1,_()),je(2,S()),De("design:type",Function),De("design:paramtypes",[n,Object,Application]),De("design:returntype",Promise)],ni.prototype,"register",null),Re([E("/confirm"),f(e=>({token:e.string()})),je(0,c()),je(1,_("token")),je(2,S()),De("design:type",Function),De("design:paramtypes",[n,String,Application]),De("design:returntype",Promise)],ni.prototype,"confirm",null),Re([E("/send"),f(e=>({username:e.string().min(4)})),je(0,c()),je(1,_("username")),je(2,S()),De("design:type",Function),De("design:paramtypes",[n,String,Application]),De("design:returntype",Promise)],ni.prototype,"send",null),ni=Re([m("/register"),g(Yt)],ni);let oi=class SetupController extends Yt{constructor(){super(...arguments),this.userService=new Ut}setup(e){return Ne(this,void 0,void 0,function*(){var t;if(yield Nt.count())return e.error(new o("Endpoint Not Found"));const i=yield Nt.create({name:"Admin",username:"admin",email:"admin@localhost.com",notes:"",status:qe.ACTIVE},Object.assign({},{ctx:e})).catch(this.error);if(!i)return e.error(new s);yield this.userService.createPassword(i.id,"admin",e);const r=yield xt.create({name:"root",description:"Root",active:!0},Object.assign({},{ctx:e}));yield jt.create({user_id:i.id,group_id:r.id},Object.assign({},{ctx:e})),yield xt.create({name:"admin",description:"Admin",active:!0},Object.assign({},{ctx:e})),yield xt.create({name:"user",description:"User",active:!0},Object.assign({},{ctx:e}));const n=null!==(t=yield wt.findAll({where:{active:!0}}).catch(this.error))&&void 0!==t?t:[];yield Z(n,t=>Ne(this,void 0,void 0,function*(){yield Mt.create({group_id:r.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}};Re([h(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],oi.prototype,"setup",null),oi=Re([m("/setup"),g(Yt)],oi);let si=class TestController extends Yt{json(e){return Ne(this,void 0,void 0,function*(){e.json({ok:!0,message:"hello",timestamp:Date.now()})})}sum(e,t){return Ne(this,void 0,void 0,function*(){const{a:t,b:i}=e;return{value:t+i}})}multiply(e,t){return Ne(this,void 0,void 0,function*(){const{a:t,b:i}=e;return{value:t*i}})}average(e,t){return Ne(this,void 0,void 0,function*(){const t=e.values;return{value:t.reduce((e,t)=>e+t,0)/t.length,count:t.length}})}validationString(e,t){return Ne(this,void 0,void 0,function*(){const t=e.text;return{length:t.length,normalized:t.trim()}})}validationNumber(e,t){return Ne(this,void 0,void 0,function*(){return{doubled:2*e.value}})}validationBoolean(e,t){return Ne(this,void 0,void 0,function*(){return{active:e.active}})}validationArray(e,t){return Ne(this,void 0,void 0,function*(){return{count:e.tags.length}})}validationObject(e,t){return Ne(this,void 0,void 0,function*(){const t=e.profile;return{summary:{name:t.name,adult:t.age>=18}}})}validationEnum(e,t){return Ne(this,void 0,void 0,function*(){return{status:e.status}})}validationDate(e,t){return Ne(this,void 0,void 0,function*(){const t=e.date;return{iso:t.toISOString(),timestamp:t.getTime()}})}validationOptional(e,t){return Ne(this,void 0,void 0,function*(){const t=e.nickname;return Object.assign({name:e.name,hasNickname:Boolean(t)},t?{nickname:t}:{})})}validationDefaults(e,t){return Ne(this,void 0,void 0,function*(){return{name:e.name,limit:e.limit}})}validationParse(e,t){return Ne(this,void 0,void 0,function*(){return{active:e.active,amount:e.amount}})}validationNested(e,t){return Ne(this,void 0,void 0,function*(){const t=e.payload;return{userId:t.user.id,scoreCount:t.scores.length}})}};Re([h(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],si.prototype,"json",null),Re([ft({name:"sum",title:"Somar numeros",description:"Soma dois numeros.",input:{a:V.number().description("valor a"),b:V.number().description("valor b")},output:{value:V.number().description("resultado da soma de a + b")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"sum",null),Re([ft({name:"multiply",title:"Multiplicar numeros",description:"Multiplica dois numeros.",input:{a:V.number().description("valor a"),b:V.number().description("valor b")},output:{value:V.number().description("resultado da multiplicação de a * b")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"multiply",null),Re([ft({name:"average",title:"Calcular media",description:"Calcula a media de uma lista de numeros.",input:{values:V.array(V.number().description("numero usado no calculo da media")).min(1).max(10).description("lista de numeros para calcular a media")},output:{value:V.number().description("media calculada"),count:V.number().description("quantidade de numeros usados")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"average",null),Re([ft({name:"validation.string",title:"Validacao de string",description:"Exemplo de validacao de texto com tamanho minimo e maximo.",input:{text:V.string().min(5).max(50).description("Texto entre 5 e 50 caracteres.")},output:{length:V.number().description("Quantidade de caracteres do texto."),normalized:V.string().description("Texto normalizado sem espacos nas pontas.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationString",null),Re([ft({name:"validation.number",title:"Validacao de number",description:"Exemplo de validacao numerica com minimo e maximo.",input:{value:V.number().min(0).max(100).description("Numero entre 0 e 100.")},output:{doubled:V.number().description("Numero multiplicado por dois.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationNumber",null),Re([ft({name:"validation.boolean",title:"Validacao de boolean",description:"Exemplo de validacao de booleano sem parse implicito.",input:{active:V.boolean().description("Indica se o registro esta ativo.")},output:{active:V.boolean().description("Booleano validado.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationBoolean",null),Re([ft({name:"validation.array",title:"Validacao de array",description:"Exemplo de validacao de array com limites e item tipado.",input:{tags:V.array(V.string().min(2).max(20).description("Tag entre 2 e 20 caracteres.")).min(1).max(5).description("Lista de tags entre 1 e 5 itens.")},output:{count:V.number().description("Quantidade de tags recebidas.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationArray",null),Re([ft({name:"validation.object",title:"Validacao de object",description:"Exemplo de validacao de objeto simples.",input:{profile:V.object({name:V.string().min(2).max(60).description("Nome do perfil."),age:V.number().min(0).max(120).description("Idade do perfil."),nickname:V.string().empty().max(30).description("Apelido opcional do perfil.")}).description("Objeto de perfil.")},output:{summary:V.object({name:V.string().description("Nome validado."),adult:V.boolean().description("Indica se a idade e maior ou igual a 18.")}).description("Resumo do perfil.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationObject",null),Re([ft({name:"validation.enum",title:"Validacao de enum",description:"Exemplo de validacao de lista fechada de valores.",input:{status:V.enum(["draft","active","archived"]).description("Status permitido.")},output:{status:V.string().description("Status validado.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationEnum",null),Re([ft({name:"validation.date",title:"Validacao de date",description:"Exemplo de validacao e parse de data.",input:{date:V.date().parse().description("Data em formato aceito pelo Date.")},output:{iso:V.string().description("Data em ISO string."),timestamp:V.number().description("Data em timestamp Unix em milissegundos.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationDate",null),Re([ft({name:"validation.optional",title:"Validacao de campo opcional",description:"Exemplo de campo opcional aceitando ausencia.",input:{name:V.string().min(2).description("Nome obrigatorio."),nickname:V.string().empty().max(30).description("Apelido opcional.")},output:{name:V.string().description("Nome validado."),hasNickname:V.boolean().description("Indica se apelido foi enviado."),nickname:V.string().empty().description("Apelido validado quando enviado.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationOptional",null),Re([ft({name:"validation.defaults",title:"Validacao de valores padrao",description:"Exemplo de campos opcionais com valores padrao.",input:{name:V.string().default("guest").description("Nome opcional com valor padrao."),limit:V.number().parse().default(10).min(1).max(100).description("Limite opcional com valor padrao.")},output:{name:V.string().description("Nome final."),limit:V.number().description("Limite final.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationDefaults",null),Re([ft({name:"validation.parse",title:"Validacao com parse",description:"Exemplo de parse de boolean e number antes da validacao final.",input:{active:V.boolean().parse().default(!1).description("Booleano aceitando valores parseaveis."),amount:V.number().parse().min(1).max(1e3).description("Numero aceitando string numerica.")},output:{active:V.boolean().description("Booleano parseado."),amount:V.number().description("Numero parseado.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationParse",null),Re([ft({name:"validation.nested",title:"Validacao de objeto aninhado",description:"Exemplo de objeto aninhado com array interno.",input:{payload:V.object({user:V.object({id:V.string().min(3).max(30).description("Identificador do usuario."),email:V.string().email().description("Email do usuario.")}).description("Usuario do payload."),scores:V.array(V.number().min(0).max(100).description("Pontuacao individual.")).min(1).max(3).description("Pontuacoes do usuario.")}).description("Payload aninhado.")},output:{userId:V.string().description("Identificador validado."),scoreCount:V.number().description("Quantidade de pontuacoes.")}}),De("design:type",Function),De("design:paramtypes",[Object,Object]),De("design:returntype",Promise)],si.prototype,"validationNested",null),si=Re([m("/test"),g(Yt)],si);let ai=class UsersController extends $t{constructor(){super(),this.model=Nt,this.path=Env.HTTP_PUBLIC+"/avatar",Env.HTTP_PUBLIC&&be(Env.HTTP_PUBLIC)&&!be(this.path)&&we(this.path)}avatar(e,t){return Ne(this,void 0,void 0,function*(){var i;const r=e.getFiles();if(r.file&&r.file.length){const{filename:n,path:o}=null!==(i=r.file[0])&&void 0!==i?i:{};if(n){const i=yield Nt.findOne({where:{id:t.id}}).catch(this.error);if(!i)return Me(o).isFile()&&xe(o),e.error(new s);const r=this.path+"/"+i.metadata.avatar_url;if(be(r)&&Me(r).isFile()&&xe(r),i.changed("metadata",!0),i.metadata.avatar_url=n,yield i.save(Object.assign({},{ctx:e})).catch(this.error))return e.success("OK")}}e.success("Record not Changed")})}token_new(){return Ne(this,void 0,void 0,function*(){var e;const t=B();return(null!==(e=yield this.model.count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(e){return Ne(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return Ne(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}rows(e){return Ne(this,void 0,void 0,function*(){yield this.countAll({ctx:e})})}del(e,t,i){return Ne(this,void 0,void 0,function*(){if(i.id==t)return e.error(new o);yield this.delete({ctx:e})})}get(e){return Ne(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return Ne(this,void 0,void 0,function*(){yield this.update({ctx:e})})}};Re([E("/avatar"),Je(),w({file:{count:1,path:`${Env.HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),je(0,c()),je(1,it()),De("design:type",Function),De("design:paramtypes",[n,Nt]),De("design:returntype",Promise)],ai.prototype,"avatar",null),Re([E(),Je(),Ue(),f(e=>({name:e.string(),email:e.string().email(),username:e.string().min(3),notes:e.string().default(""),status:e.enum(Object.keys(qe)).default(qe.ACTIVE),metadata:e.object().parse().default({})})),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],ai.prototype,"add",null),Re([h(),Je(),$e(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],ai.prototype,"all",null),Re([h("/count"),Je(),$e(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],ai.prototype,"rows",null),Re([A("/:id"),Je(),Ye(),je(0,c()),je(1,b("id")),je(2,it()),De("design:type",Function),De("design:paramtypes",[n,String,Nt]),De("design:returntype",Promise)],ai.prototype,"del",null),Re([h("/:id"),Je(),$e(),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],ai.prototype,"get",null),Re([T("/:id"),Je(),We(),f(e=>({name:e.string().optional(),email:e.string().email().optional(),username:e.string().min(3).optional(),notes:e.string().optional(),status:e.enum(Object.keys(qe)).optional(),metadata:e.object().parse().optional()})),je(0,c()),De("design:type",Function),De("design:paramtypes",[n]),De("design:returntype",Promise)],ai.prototype,"set",null),ai=Re([m("/users"),g($t),De("design:paramtypes",[])],ai);let di=class UsersGroupsController extends $t{constructor(){super(...arguments),this.model=jt,this.permissions=[]}all(e,t){return Ne(this,void 0,void 0,function*(){if(!(yield Nt.findByPk(t,{attributes:["id"]}).catch(this.error)))return e.error(new o("User Not Found"));yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{association:"group"}]},callback:e=>e.map(e=>e.group),query:!1})})}set(e,t,i){return Ne(this,void 0,void 0,function*(){const r=yield Nt.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new o("User Not Found"));const n=r.id,s=[];yield Z(Q(i),t=>Ne(this,void 0,void 0,function*(){var i;if(!(yield xt.count({where:{id:t}})))return;const[r]=null!==(i=yield jt.findOrCreate(Object.assign({where:{user_id:n,group_id:t},defaults:{user_id:n,group_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];r&&s.push(t)})),yield jt.destroy(Object.assign({where:{user_id:n,group_id:{[he.notIn]:s}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Re([h("/:id/groups"),Je(),$e("users"),je(0,c()),je(1,b("id")),De("design:type",Function),De("design:paramtypes",[n,String]),De("design:returntype",Promise)],di.prototype,"all",null),Re([T("/:id/groups"),Je(),We("users"),f(e=>({groups:e.array(e.string().uuid())})),je(0,c()),je(1,b("id")),je(2,_("groups")),De("design:type",Function),De("design:paramtypes",[n,String,Array]),De("design:returntype",Promise)],di.prototype,"set",null),di=Re([m("/users"),g($t)],di);export{Application,bt as Audit,Lt as AuditModel,ke as AuditTypes,Wt as AuditsController,zt as AuthController,Vt as AuthService,Yt as BaseController,Ue as CanCreate,Ye as CanDelete,$e as CanRead,We as CanUpdate,Config,Ht as ConfigModel,Gt as CrudController,Env,Jt as FilesController,Qt as ForgotController,kt as ForgotModel,xt as GroupModel,Mt as GroupPermissionModel,Fe as GroupTypes,Xt as GroupsController,Zt as GroupsPermissionsController,ze as HasGroups,Ge as HasPermissions,ei as HealthController,Je as IsAuthenticated,Log,Be as LogLevels,Ft as LogModel,Loggable,ti as LogsController,ut as MCP_DEFAULT_PROTOCOL_VERSION,gt as MCP_HTTP_ALLOW,vt as MCP_HTTP_ALLOWED_METHODS,ct as MCP_PROTOCOL_VERSION_HEADER,pt as MCP_SESSION_ID_HEADER,lt as MCP_SUPPORTED_PROTOCOL_VERSIONS,mt as MCP_TOOL_METADATA,ii as McpController,McpError,rt as McpErrorCode,McpHttpHandler,McpInternalError,McpInvalidParamsError,McpInvalidRequestError,McpInvalidSessionError,McpMethodNotFoundError,McpParseError,McpRateLimiter,McpServerError,McpSessionStore,ft as McpTool,McpToolNotFoundError,McpToolRegistry,Bt as MigrationModel,$t as ModelController,ModelService,wt as PermissionModel,ri as PermissionsController,ni as RegisterController,It as RegisterModel,Qe as ReqAuth,Xe as ReqGroup,Ze as ReqGroups,et as ReqPermission,tt as ReqPermissions,it as ReqUser,qt as Service,Kt as SessionModel,SessionStore,oi as SetupController,Rt as TenantModel,Ke as TenantStatus,si as TestController,Pt as UserAuthModel,jt as UserGroupModel,Nt as UserModel,Dt as UserPasswordModel,Ut as UserService,qe as UserStatus,Ct as UserTenantModel,ai as UsersController,di as UsersGroupsController,Et as assertValidMcpToolDefinition,Ve as canFactory,ht as isJsonParseError,nt as isJsonRpcId,yt as jsonParseErrorResponse,st as jsonRpcError,at as jsonRpcErrorFromCode,ot as jsonRpcResult,dt as parseJsonRpcRequest,He as sequelize};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrewcaires/api",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.3.1",
|
|
4
4
|
"description": "Simple api for small applications using express, jsonwebtoken, sequelize and websocket",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs.js",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
],
|
|
21
21
|
"scripts": {
|
|
22
22
|
"dev": "tsx-dev --watch --clear ./src/dev.ts",
|
|
23
|
+
"test": "node --import tsx --test test/**/*.test.ts",
|
|
23
24
|
"build": "npm run lint && rollup --bundleConfigAsCjs -c rollup.config.js",
|
|
24
25
|
"lint": "eslint \"src/**/*.{ts,tsx,js,jsx}\" --max-warnings=0"
|
|
25
26
|
},
|
|
@@ -47,35 +48,35 @@
|
|
|
47
48
|
},
|
|
48
49
|
"homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
|
|
49
50
|
"dependencies": {
|
|
50
|
-
"@andrewcaires/decorator": "^1.
|
|
51
|
-
"@andrewcaires/express": "^2.
|
|
52
|
-
"@andrewcaires/node": "^1.
|
|
53
|
-
"@andrewcaires/sequelize": "^3.2.
|
|
54
|
-
"@andrewcaires/utils.js": "^0.4
|
|
51
|
+
"@andrewcaires/decorator": "^1.2.0",
|
|
52
|
+
"@andrewcaires/express": "^2.4.0",
|
|
53
|
+
"@andrewcaires/node": "^1.4.0",
|
|
54
|
+
"@andrewcaires/sequelize": "^3.2.2",
|
|
55
|
+
"@andrewcaires/utils.js": "^0.5.4",
|
|
55
56
|
"@node-rs/argon2": "^2.0.2",
|
|
56
57
|
"cors": "^2.8.6",
|
|
57
58
|
"dotenv": "^17.4.2",
|
|
58
59
|
"express-session": "^1.19.0",
|
|
59
60
|
"jsonwebtoken": "^9.0.3",
|
|
60
61
|
"sequelize": "^6.37.8",
|
|
61
|
-
"tsx": "^4.
|
|
62
|
-
"ws": "^8.
|
|
62
|
+
"tsx": "^4.22.4",
|
|
63
|
+
"ws": "^8.21.0"
|
|
63
64
|
},
|
|
64
65
|
"devDependencies": {
|
|
65
66
|
"@eslint/js": "^10.0.1",
|
|
66
|
-
"@rollup/plugin-commonjs": "^29.0.
|
|
67
|
+
"@rollup/plugin-commonjs": "^29.0.3",
|
|
67
68
|
"@rollup/plugin-terser": "^1.0.0",
|
|
68
69
|
"@rollup/plugin-typescript": "^12.3.0",
|
|
69
70
|
"@types/cors": "^2.8.19",
|
|
70
71
|
"@types/express-session": "^1.19.0",
|
|
71
72
|
"@types/jsonwebtoken": "^9.0.10",
|
|
72
|
-
"@types/node": "^25.
|
|
73
|
+
"@types/node": "^25.9.1",
|
|
73
74
|
"@types/ws": "^8.18.1",
|
|
74
|
-
"eslint": "^10.
|
|
75
|
+
"eslint": "^10.4.1",
|
|
75
76
|
"mariadb": "^3.5.2",
|
|
76
|
-
"rollup": "^4.
|
|
77
|
+
"rollup": "^4.61.0",
|
|
77
78
|
"rollup-plugin-dts": "^6.4.1",
|
|
78
79
|
"tslib": "^2.8.1",
|
|
79
|
-
"typescript-eslint": "^8.
|
|
80
|
+
"typescript-eslint": "^8.60.1"
|
|
80
81
|
}
|
|
81
82
|
}
|