@andrewcaires/api 5.2.2 → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -0
- package/dist/index.cjs.js +2 -2
- package/dist/index.d.ts +327 -6
- 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.0
|
|
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(),description:e.string().empty(""),state:e.boolean().parse().empty(!0)})),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(),description:e.string().empty(),state:e.boolean().parse().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 h,Get as g,Query as m,Controller as y,Post as E,Validate as f,Body as _,App as S,Middleware as A,Delete as O,Put as T,Params as I,All as P,Options as b,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 K,isArray as B,isValidationShape as q,Validation as U,getConstructor as V,noop as Y,clamp as $,merge as W,clone as z,forEachAsync as G,upperCamelCase as J,uniqueArray as Q,forEachSeries as X,sleep as Z,EventEmitter as ee,isDef as te,uniqueID as ie}from"@andrewcaires/utils.js";import{WebSocketServer as re}from"ws";import{Sequelize as ne,Hooks as oe,Column as se,Association as ae,Database as de,ModelName as le,Version as ue,Model as ce,Index as pe,DefaultValue as ve,Op as he,Where as ge}from"@andrewcaires/sequelize";import{config as me}from"dotenv";import{metadata as ye,Trait as Ee,Singleton as fe}from"@andrewcaires/decorator";import{Store as _e}from"express-session";import Se from"jsonwebtoken";import{hashSync as Ae,verify as Oe}from"@node-rs/argon2";import{existsSync as Te,statSync as Ie,readdirSync as Pe,mkdirSync as be,lstatSync as we,rmSync as Me}from"fs";import{join as xe}from"path";function Ce(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 Re(e,t){return function(i,r){t(i,r,e)}}function je(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function De(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 Ne;"function"==typeof SuppressedError&&SuppressedError,me({quiet:!0});class Env extends M{}Ne=Env,Env.BASE_NAME=Ne.getString("BASE_NAME",""),Env.CONSOLE_ERROR=Ne.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=Ne.getString("DATABASE_URI","",!0),Env.DATABASE_LOG=Ne.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=Ne.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=Ne.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=Ne.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CROSS=Ne.getString("HTTP_CROSS",""),Env.HTTP_TLS_CA=Ne.getFile("HTTP_TLS_CA"),Env.HTTP_TLS_CRT=Ne.getFile("HTTP_TLS_CRT"),Env.HTTP_TLS_KEY=Ne.getFile("HTTP_TLS_KEY"),Env.MODEL_LIMIT=Ne.getInt("MODEL_LIMIT",10),Env.MODEL_LIMIT_MAX=Ne.getInt("MODEL_LIMIT_MAX",100),Env.MCP_ALLOWED_ORIGINS=Ne.getString("MCP_ALLOWED_ORIGINS",""),Env.MCP_RATE_LIMIT_MAX=Ne.getInt("MCP_RATE_LIMIT_MAX",120),Env.MCP_RATE_LIMIT_WINDOW=Ne.getMs("MCP_RATE_LIMIT_WINDOW","1m"),Env.MCP_SESSION_TTL=Ne.getMs("MCP_SESSION_TTL","30m"),Env.PASSWORD_ALGORITHM=Ne.getInt("PASSWORD_ALGORITHM",2),Env.PASSWORD_MEMORY_COST=Ne.getInt("PASSWORD_MEMORY_COST",4096),Env.PASSWORD_PARALLELISM=Ne.getInt("PASSWORD_PARALLELISM",1),Env.PASSWORD_PEPPER=Ne.getString("PASSWORD_PEPPER",""),Env.PASSWORD_TIME_COST=Ne.getInt("PASSWORD_TIME_COST",3),Env.SLEEP_AUTH=Ne.getMs("SLEEP_AUTH","2s"),Env.SLEEP_FORGOT=Ne.getMs("SLEEP_FORGOT","5s"),Env.SLEEP_REGISTRY=Ne.getMs("SLEEP_REGISTRY","5s"),Env.TOKEN_CRT=Ne.getFile("TOKEN_CRT"),Env.TOKEN_KEY=Ne.getFile("TOKEN_KEY"),Env.TOKEN_TTL=Ne.getMs("TOKEN_TTL","1d"),Env.TOKEN_TYPE=Ne.getString("TOKEN_TYPE","bearer"),Env.API_BODYPARSER_STRICT=Ne.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=Ne.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=Ne.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=Ne.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_PORT=Ne.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=Ne.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_HYBRID=Ne.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=Ne.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=Ne.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=Ne.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=Ne.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=Ne.getString("API_KEY_HEADER","x-api-key"),Env.API_SESSION_NAME=Ne.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=Ne.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=Ne.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=Ne.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=Ne.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_TOKEN_FORGOT=Ne.getMs("API_TOKEN_FORGOT","1d"),Env.API_TOKEN_HEADER=Ne.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_RENEW=Ne.getMs("API_TOKEN_RENEW","1d"),Env.API_USER_HISTORY=Ne.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=Ne.getBool("API_WEBSOCKET_START",!1);const Le=new ne({uri:Env.DATABASE_URI,logging:!!Env.DATABASE_LOG&&(e=>x.console(C.Magenta,"sql",e)),prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE});var He,ke,Fe;!function(e){e.CREATE="CREATE",e.DELETE="DELETE",e.UPDATE="UPDATE"}(He||(He={})),function(e){e.INFO="info",e.WARN="warn",e.ERROR="error"}(ke||(ke={})),function(e){e.ACTIVE="active",e.PENDING="pending",e.DISABLED="disabled",e.LOCKED="locked",e.ARCHIVED="archived"}(Fe||(Fe={}));const Ke=i=>r=>(n,o,s)=>{e(e=>De(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)},Be=Ke("create"),qe=Ke("delete"),Ue=Ke("read"),Ve=Ke("update"),Ye=(...i)=>(r,n,o)=>{e(e=>De(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)},$e=(...i)=>(r,n,o)=>{e(e=>De(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)},We=()=>(i,r,n)=>{e(e=>De(void 0,void 0,void 0,function*(){yield(e=>De(void 0,void 0,void 0,function*(){var i,r,n,o;if(e.req.auth&&e.req.user)return e.next();const{[Env.API_KEY_HEADER]:s,[Env.API_TOKEN_HEADER]:a,"user-agent":d}=e.getHeaders(),l=e.getQuery(Env.API_KEY_HEADER),u=(null===(i=s||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=a||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:h,userService:g}=e.app,{auth:m,user:y}=null!==(o=yield(u?h.key(u.toString()):h.user(v)).catch(t=>{e.error(t)}))&&void 0!==o?o:{};if(!m||!y)return;if(!u&&m.user_agent&&m.user_agent!=d)return e.error(new t("Invalid token"));e.req.auth=m,e.req.user=y;const{groups:E,permissions:f}=yield g.getGroupsPermissions(y.id);e.req.groups=E,e.req.permissions=f,e.next()}))(e)}))(i,r,n)},ze=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),Ge=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)}),Je=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.groups)&&void 0!==i?i:[]}),Qe=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)}),Xe=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.permissions)&&void 0!==i?i:[]}),Ze=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.user}),et={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,ServerError:-32e3,InvalidSession:-32001};class McpError extends r{constructor(e,t=et.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,et.ParseError,400,t)}}class McpInvalidRequestError extends McpError{constructor(e="Invalid Request",t){super(e,et.InvalidRequest,400,t)}}class McpMethodNotFoundError extends McpError{constructor(e){super(`Method not found: ${e}`,et.MethodNotFound,200)}}class McpInvalidParamsError extends McpError{constructor(e="Invalid params",t){super(e,et.InvalidParams,200,t)}}class McpInternalError extends McpError{constructor(e="Internal error",t){super(e,et.InternalError,200,t)}}class McpServerError extends McpError{constructor(e="Server error",t){super(e,et.ServerError,500,t)}}class McpInvalidSessionError extends McpError{constructor(e="Invalid MCP session",t=404){super(e,et.InvalidSession,t)}}class McpToolNotFoundError extends McpError{constructor(e){super("Tool not found",et.InvalidParams,200,{toolName:e})}}const tt=e=>k(e)||F(e),it=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),rt=(e,t)=>({jsonrpc:"2.0",id:e,error:Object.assign({code:t.code,message:t.message},void 0!==t.data?{data:t.data}:{})}),nt=(e,t,i,r)=>({jsonrpc:"2.0",id:e,error:Object.assign({code:t,message:i},void 0!==r?{data:r}:{})}),ot=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&&!tt(e.id))throw new McpInvalidRequestError("Invalid id");return e},st=["2025-11-25","2025-06-18"],at=st[0],dt="MCP-Protocol-Version",lt="MCP-Session-Id",ut=["POST","DELETE","OPTIONS"],ct=ut.join(", "),pt=e=>{if(!(e instanceof SyntaxError))return!1;const t=e;return"entity.parse.failed"===t.type||400===t.status||400===t.statusCode},vt=e=>{if(pt(e))return{status:400,body:rt(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 De(this,void 0,void 0,function*(){var t;const i=this.validateOrigin(e);if(i)return i;let r=null;try{const i=ot(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:it(e,{})})),e);if("tools/list"===i.method)return this.validateObjectParams(i.params),this.withTransportHeaders(this.withInitializedSession(i.id,e,e=>({status:200,body:it(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(`${lt} 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:{[lt]:o.sessionId,[dt]:o.protocolVersion},body:it(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 De(this,void 0,void 0,function*(){return this.withInitializedSession(e,i,(e,i)=>De(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:it(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(!tt(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(`${lt} 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 ${dt} header`)}negotiateProtocolVersion(e){if(!H(e)||!k(e.protocolVersion))throw new McpInvalidParamsError("params.protocolVersion is required");return st.includes(e.protocolVersion)?e.protocolVersion:at}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:ct,"Access-Control-Allow-Methods":ct,"Access-Control-Allow-Headers":`Content-Type, Accept, ${lt}, ${dt}`},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:rt(e,t)};const i=new McpServerError;return{status:i.status,body:rt(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:K(),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 ht=Symbol.for("@andrewcaires/api:mcp:tool"),gt=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(gt(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 De(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)&&B(e.content)}normalizeMcpValidation(e,t="object"){if(q(e)){const t=U.object(e).parse();return{schema:t.toSchema(),validation:t}}const i="object"===t?U.object({}).parse():U.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 mt=e=>(gt(e),(t,i)=>{yt(i)?i.addInitializer(function(){Et(this.constructor,i.name,e)}):Et(t,i,e)}),yt=e=>"object"==typeof e&&null!==e&&"kind"in e&&"method"===e.kind&&"name"in e&&"addInitializer"in e,Et=(e,t,i)=>{const r=ye(ht,e,[]),n=Object.assign(Object.assign({},i),{propertyKey:t});r.some(e=>e.propertyKey===n.propertyKey&&e.name===n.name)||r.push(n)},ft=(e,t,i)=>{var r,o,s,a,d,l,u,c,p,v,h;const g=i.ctx instanceof n?i.ctx:null,m=null!==(r=null==g?void 0:g.id)&&void 0!==r?r:null,y=null!==(d=null!==(a=null===(s=null===(o=null==g?void 0:g.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:m,user_id:y};return g?Object.assign(Object.assign({},E),{full_url:null!==(c=g.getUrl())&&void 0!==c?c:"",ip_address:null!==(p=g.getIp())&&void 0!==p?p:"",user_agent:null!==(h=null===(v=g.req)||void 0===v?void 0:v.headers["user-agent"])&&void 0!==h?h:""}):E},_t=e=>{const t=V(e),i=t.primaryKeyAttribute;return{model:t,record_id:i?e.getDataValue(i):null}},St={afterCreate:(e,t)=>De(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=_t(e);yield Ct.create(Object.assign(Object.assign({},ft(He.CREATE,i,t)),{record:r,currently:e.toJSON()})).catch(x.catch)}),afterUpdate:(e,t)=>De(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=_t(e),n={},o={},s=e.changed();s&&s.length&&s.forEach(t=>{n[t]=e.getDataValue(t),o[t]=e.previous(t)}),yield Ct.create(Object.assign(Object.assign({},ft(He.UPDATE,i,t)),{record:r,currently:n,previously:o})).catch(x.catch)}),afterDestroy:(e,t)=>De(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=_t(e);yield Ct.create(Object.assign(Object.assign({},ft(He.DELETE,i,t)),{record:r,currently:e.toJSON()})).catch(x.catch)})},At=e=>(D(e)&&(e=Env.DATABASE_AUDIT),oe(e?St:{}));let Ot=class RegisterModel extends ce{};Ce([se.Id(7),je("design:type",String)],Ot.prototype,"id",void 0),Ce([se.String(),je("design:type",String)],Ot.prototype,"secret",void 0),Ce([se.FullDate(),je("design:type",Number)],Ot.prototype,"expired_at",void 0),Ce([se.Boolean(),je("design:type",Boolean)],Ot.prototype,"active",void 0),Ce([se.CreatedAt(),je("design:type",Date)],Ot.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],Ot.prototype,"updated_at",void 0),Ce([se.DeletedAt(),je("design:type",Object)],Ot.prototype,"deleted_at",void 0),Ce([ae.BelongsTo(()=>xt),je("design:type",String)],Ot.prototype,"user_id",void 0),Ot=Ce([de(Le),le("register"),ue("5.2.0")],Ot);let Tt=class UserAuthModel extends ce{};Ce([se.Id(7),je("design:type",String)],Tt.prototype,"id",void 0),Ce([se.String(),je("design:type",String)],Tt.prototype,"secret",void 0),Ce([se.String(),je("design:type",String)],Tt.prototype,"ip_address",void 0),Ce([se.String(),je("design:type",String)],Tt.prototype,"user_agent",void 0),Ce([se.FullDate(),je("design:type",Object)],Tt.prototype,"revoked_at",void 0),Ce([se.CreatedAt(),je("design:type",Date)],Tt.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],Tt.prototype,"updated_at",void 0),Ce([se.DeletedAt(),je("design:type",Object)],Tt.prototype,"deleted_at",void 0),Ce([ae.BelongsTo(()=>xt),je("design:type",String)],Tt.prototype,"user_id",void 0),Tt=Ce([de(Le),le("users_auth"),ue("5.2.0")],Tt);let It=class PermissionModel extends ce{};Ce([se.Id(7),je("design:type",String)],It.prototype,"id",void 0),Ce([se.String(),pe(),je("design:type",String)],It.prototype,"name",void 0),Ce([se.Text(),je("design:type",String)],It.prototype,"description",void 0),Ce([se.Boolean(),je("design:type",Boolean)],It.prototype,"active",void 0),Ce([se.CreatedAt(),je("design:type",Date)],It.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],It.prototype,"updated_at",void 0),Ce([se.DeletedAt(),je("design:type",Object)],It.prototype,"deleted_at",void 0),Ce([ae.HasMany(()=>Pt),je("design:type",Array)],It.prototype,"groups_permissions",void 0),It=Ce([de(Le),le("permission"),At(),ue("5.2.1")],It);let Pt=class GroupPermissionModel extends ce{};Ce([se.Id(7),je("design:type",String)],Pt.prototype,"id",void 0),Ce([se.CreatedAt(),je("design:type",Date)],Pt.prototype,"created_at",void 0),Ce([ae.BelongsTo(()=>bt),je("design:type",String)],Pt.prototype,"group_id",void 0),Ce([ae.BelongsTo(()=>It),je("design:type",String)],Pt.prototype,"permission_id",void 0),Pt=Ce([de(Le),le("groups_permissions"),At(),ue("5.2.0")],Pt);let bt=class GroupModel extends ce{};Ce([se.Id(7),je("design:type",String)],bt.prototype,"id",void 0),Ce([se.String(),pe(),je("design:type",String)],bt.prototype,"name",void 0),Ce([se.Text(),je("design:type",String)],bt.prototype,"description",void 0),Ce([se.Boolean(),je("design:type",Boolean)],bt.prototype,"active",void 0),Ce([se.CreatedAt(),je("design:type",Date)],bt.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],bt.prototype,"updated_at",void 0),Ce([se.DeletedAt(),je("design:type",Object)],bt.prototype,"deleted_at",void 0),Ce([ae.HasMany(()=>wt),je("design:type",Array)],bt.prototype,"users_groups",void 0),Ce([ae.HasMany(()=>Pt),je("design:type",Array)],bt.prototype,"groups_Permission",void 0),bt=Ce([de(Le),le("group"),At(),ue("5.2.1")],bt);let wt=class UserGroupModel extends ce{};Ce([se.Id(7),je("design:type",String)],wt.prototype,"id",void 0),Ce([se.CreatedAt(),je("design:type",Date)],wt.prototype,"created_at",void 0),Ce([ae.BelongsTo(()=>bt),je("design:type",String)],wt.prototype,"group_id",void 0),Ce([ae.BelongsTo(()=>xt),je("design:type",String)],wt.prototype,"user_id",void 0),wt=Ce([de(Le),le("users_groups"),At(),ue("5.2.0")],wt);let Mt=class UserPasswordModel extends ce{};Ce([se.Id(7),je("design:type",String)],Mt.prototype,"id",void 0),Ce([se.String(),je("design:type",String)],Mt.prototype,"hash",void 0),Ce([se.FullDate(),je("design:type",Object)],Mt.prototype,"revoked_at",void 0),Ce([se.CreatedAt(),je("design:type",Date)],Mt.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],Mt.prototype,"updated_at",void 0),Ce([se.DeletedAt(),je("design:type",Object)],Mt.prototype,"deleted_at",void 0),Ce([ae.BelongsTo(()=>xt),je("design:type",String)],Mt.prototype,"user_id",void 0),Mt=Ce([de(Le),le("users_password"),At(),ue("5.2.0")],Mt);let xt=class UserModel extends ce{};Ce([se.Id(7),je("design:type",String)],xt.prototype,"id",void 0),Ce([se.String(),je("design:type",String)],xt.prototype,"name",void 0),Ce([se.String(),je("design:type",String)],xt.prototype,"username",void 0),Ce([se.String(),je("design:type",String)],xt.prototype,"email",void 0),Ce([se.Text(),je("design:type",String)],xt.prototype,"notes",void 0),Ce([se.Enum(Fe),ve(Fe.ACTIVE),je("design:type",String)],xt.prototype,"status",void 0),Ce([se.Json(),ve(()=>({})),je("design:type",Object)],xt.prototype,"metadata",void 0),Ce([se.CreatedAt(),je("design:type",Date)],xt.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],xt.prototype,"updated_at",void 0),Ce([se.DeletedAt(),je("design:type",Object)],xt.prototype,"deleted_at",void 0),Ce([ae.HasMany(()=>Ct),je("design:type",Array)],xt.prototype,"audits",void 0),Ce([ae.HasMany(()=>Tt),je("design:type",Array)],xt.prototype,"users_auths",void 0),Ce([ae.HasMany(()=>Ot),je("design:type",Array)],xt.prototype,"registers",void 0),Ce([ae.HasMany(()=>wt),je("design:type",Array)],xt.prototype,"users_groups",void 0),Ce([ae.HasMany(()=>Mt),je("design:type",Array)],xt.prototype,"users_passwords",void 0),xt=Ce([de(Le),le("user"),At(),ue("5.2.0")],xt);let Ct=class AuditModel extends ce{};Ce([se.Id(7),je("design:type",String)],Ct.prototype,"id",void 0),Ce([se.Enum(He),je("design:type",String)],Ct.prototype,"type",void 0),Ce([se.String(),je("design:type",String)],Ct.prototype,"model",void 0),Ce([se.String(),je("design:type",String)],Ct.prototype,"record",void 0),Ce([se.Json(),je("design:type",Object)],Ct.prototype,"currently",void 0),Ce([se.Json(),je("design:type",Object)],Ct.prototype,"previously",void 0),Ce([se.String(36),je("design:type",String)],Ct.prototype,"request_id",void 0),Ce([se.Text(),je("design:type",String)],Ct.prototype,"full_url",void 0),Ce([se.String(),je("design:type",String)],Ct.prototype,"ip_address",void 0),Ce([se.Text(),je("design:type",String)],Ct.prototype,"user_agent",void 0),Ce([se.String(),je("design:type",String)],Ct.prototype,"source",void 0),Ce([se.FullDate(),je("design:type",Object)],Ct.prototype,"reverted_at",void 0),Ce([se.CreatedAt(),je("design:type",Date)],Ct.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],Ct.prototype,"updated_at",void 0),Ce([se.DeletedAt(),je("design:type",Object)],Ct.prototype,"deleted_at",void 0),Ce([ae.BelongsTo(()=>xt),je("design:type",String)],Ct.prototype,"user_id",void 0),Ct=Ce([de(Le),le("audit"),ue("5.2.0")],Ct);let Rt=class ConfigModel extends ce{};Ce([se.Id(7),je("design:type",String)],Rt.prototype,"id",void 0),Ce([se.String(),je("design:type",String)],Rt.prototype,"key",void 0),Ce([se.Text(),je("design:type",String)],Rt.prototype,"value",void 0),Ce([se.CreatedAt(),je("design:type",Date)],Rt.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],Rt.prototype,"updated_at",void 0),Rt=Ce([de(Le),le("configs"),ue("5.2.0")],Rt);let jt=class ForgotModel extends ce{};Ce([se.Id(7),je("design:type",String)],jt.prototype,"id",void 0),Ce([se.String(),je("design:type",String)],jt.prototype,"secret",void 0),Ce([se.FullDate(),je("design:type",Number)],jt.prototype,"expired_at",void 0),Ce([se.Boolean(),je("design:type",Boolean)],jt.prototype,"active",void 0),Ce([se.CreatedAt(),je("design:type",Date)],jt.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],jt.prototype,"updated_at",void 0),Ce([se.DeletedAt(),je("design:type",Object)],jt.prototype,"deleted_at",void 0),Ce([ae.BelongsTo(()=>xt),je("design:type",String)],jt.prototype,"user_id",void 0),jt=Ce([de(Le),le("forgot"),ue("5.2.0")],jt);let Dt=class LogModel extends ce{};Ce([se.Id(7),je("design:type",String)],Dt.prototype,"id",void 0),Ce([se.Enum(ke),ve(ke.INFO),je("design:type",String)],Dt.prototype,"level",void 0),Ce([se.Text(),je("design:type",String)],Dt.prototype,"message",void 0),Ce([se.String(),je("design:type",String)],Dt.prototype,"source",void 0),Ce([se.CreatedAt(),je("design:type",Date)],Dt.prototype,"created_at",void 0),Dt=Ce([de(Le),le("log"),ue("5.2.0")],Dt);let Nt=class MigrationModel extends ce{};Ce([se.Id(7),je("design:type",String)],Nt.prototype,"id",void 0),Ce([se.String(),je("design:type",String)],Nt.prototype,"model",void 0),Ce([se.String(),je("design:type",String)],Nt.prototype,"version",void 0),Ce([se.CreatedAt(),je("design:type",Date)],Nt.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],Nt.prototype,"updated_at",void 0),Nt=Ce([de(Le),le("migration"),ue("5.2.0")],Nt);let Lt=class SessionModel extends ce{};Ce([se.Id(7),je("design:type",String)],Lt.prototype,"id",void 0),Ce([se.Json(),je("design:type",Object)],Lt.prototype,"data",void 0),Ce([se.FullDate(),je("design:type",Date)],Lt.prototype,"expired_at",void 0),Ce([se.CreatedAt(),je("design:type",Date)],Lt.prototype,"created_at",void 0),Ce([se.UpdatedAt(),je("design:type",Date)],Lt.prototype,"updated_at",void 0),Lt=Ce([de(Le),le("session"),ue("5.2.0")],Lt);class Log{static error(e,t,i){return De(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,i)})}static info(e,t,i){return De(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,i)})}static warn(e,t,i){return De(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,i)})}static writeRaw(e,t,i,r){return De(this,void 0,void 0,function*(){var n;r&&x.console(null!==(n=this.colors[e])&&void 0!==n?n:C.White,e,t),Le&&(yield Dt.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 De(this,void 0,void 0,function*(){var t;const i=null!==(t=yield Rt.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 De(this,void 0,void 0,function*(){return((yield Rt.destroy({where:{key:e}}).catch(this.error))||0)>0})}static get(e){return De(this,arguments,void 0,function*(e,t=""){const[i]=(yield Rt.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return i?i.value:t})}static set(e,t){return De(this,void 0,void 0,function*(){const[i,r]=(yield Rt.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 _e{constructor(){super(),this.all=e=>De(this,void 0,void 0,function*(){e=e||Y;const t=yield Lt.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=>De(this,void 0,void 0,function*(){yield Lt.destroy().catch(x.catch),e&&e()}),this.destroy=(e,t)=>De(this,void 0,void 0,function*(){yield Lt.destroy({where:{id:e}}).catch(x.catch),t&&t()}),this.expired=()=>De(this,void 0,void 0,function*(){yield Lt.destroy({where:{expired_at:{[he.lt]:new Date}}}).catch(x.catch)}),this.get=(e,t)=>De(this,void 0,void 0,function*(){t=t||Y;const i=yield Lt.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=>De(this,void 0,void 0,function*(){e&&e(null,(yield Lt.count().catch(x.catch))||0)}),this.set=(e,t,i)=>De(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 Lt.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 Ht=class Service{};Ht=Ce([Ee(Loggable)],Ht);let kt=class AuthService extends Ht{constructor(){super(...arguments),this.userAttributes={exclude:["username","notes","deleted_at"]}}create(e){return De(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new o("TOKEN_KEY not found");const{id:t}=e,i=K(),r=yield Tt.create({secret:i,user_id:t}).catch(this.error);if(!r)throw new s;return{auth:r,token:Se.sign({id:t,secret:i},Env.TOKEN_KEY,this.options())}})}destroy(e){return De(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return De(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.API_TOKEN_RENEW/1e3);if(!i)throw new t("Invalid token");const{id:r,secret:n}=i;if(r&&n){const e=yield xt.findOne({where:{id:r,status:Fe.ACTIVE}}).catch(this.error);if(e){const t=yield Tt.findOne({where:{secret:n,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:Se.sign({id:r,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t("Invalid token")})}user(e){return De(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 xt.findOne({attributes:this.userAttributes,where:{id:r,status:Fe.ACTIVE}}).catch(this.error);if(e){const t=yield Tt.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 De(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:Se.verify(e,Env.TOKEN_CRT,{clockTolerance:i})}}catch(e){throw new t("Invalid token")}})}key(e){return De(this,void 0,void 0,function*(){if(!e)throw new t("Invalid token");const i=yield xt.findOne({attributes:this.userAttributes,where:{token:e,status:Fe.ACTIVE}}).catch(this.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield Tt.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")})}};kt=Ce([fe()],kt);class ModelService extends Ht{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=ge.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 De(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 De(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 De(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(B(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 De(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 De(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 h=W({},u);h.attributes=this.getAttributes(null!==(i=null==h?void 0:h.attributes)&&void 0!==i?i:[]),c&&this.applySelect(s,h);const g=yield this.model.findOne(Object.assign(Object.assign({},h),{where:{[he.and]:Object.assign({[p]:v},null!==(r=null==h?void 0:h.where)&&void 0!==r?r:{})}})).catch(this.error);return g?(null==s||s.prepare(d.OK,n?yield n(g):g.toJSON()),g):(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 De(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=>De(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=J(e.replace(/_/g," ")," ");yield It.findOrCreate({where:{key:r},defaults:Object.assign({name:`${n} ${J(i," ")}`,key:r,tags:n},t)})}))})}update(e){return De(this,void 0,void 0,function*(){var t,i,r,n,o;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),[h]=null!==(o=yield this.model.update(Object.assign({},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:{})),Object.assign(Object.assign(Object.assign({},v),{where:{[he.and]:Object.assign({[c]:p},null!==(n=null==v?void 0:v.where)&&void 0!==n?n:{})},individualHooks:!0}),{ctx:s})).catch(this.error))&&void 0!==o?o:[];return h?(null==s||s.success("OK"),!0):(null==s||s.success("Record not changed"),!1)})}}let Ft=class UserService extends Ht{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 De(this,void 0,void 0,function*(){yield Mt.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 Mt.create({hash:r,user_id:e},Object.assign({},{ctx:i})).catch(this.error)})}findAllPermission(e){return De(this,void 0,void 0,function*(){var t;return null!==(t=yield It.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 De(this,void 0,void 0,function*(){var t;return(null!==(t=yield bt.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 De(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:Q(t),permissions:Q(i)}})}getPermissions(e){return De(this,void 0,void 0,function*(){return(yield this.findAllPermission(e)).map(e=>e.name)})}};Ft=Ce([fe()],Ft);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.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 De(this,void 0,void 0,function*(){yield Le.sync(),yield this.migrations(Le),yield X(this.controllers,e=>De(this,void 0,void 0,function*(){N(e.sync)&&(yield e.sync(this))})),this.authService=new kt,this.userService=new Ft,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new re({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>De(this,void 0,void 0,function*(){t.url||(t.url=""),e.on("close",()=>{}),yield Z(2e3)})))})}migrations(e){return De(this,void 0,void 0,function*(){const t=[];yield X(Object.keys(e.models),i=>De(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 Nt.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 X(t,e=>De(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}let Kt=class BaseController extends ee{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 De(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 De(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=J(e.replace(/_/g," ")," ");yield X(this.permissions,i=>De(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield It.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${J(i," ")}`,active:!0}})}))})}};Ce([Re(0,c()),Re(1,p("user-agent")),Re(2,v()),je("design:type",Function),je("design:paramtypes",[n,String,Object]),je("design:returntype",Promise)],Kt.prototype,"session",null),Kt=Ce([Ee(Loggable)],Kt);let Bt=class ModelController extends Kt{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"],this.search=[]}countAll(e){return De(this,void 0,void 0,function*(){return yield this.service.countAll(e)})}create(e){return De(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return De(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return De(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return De(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}include(e,t){return this.service.include(e,t)}sync(){return De(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=J(e.replace(/_/g," ")," ");yield X(this.permissions,i=>De(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield It.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 De(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}};Bt=Ce([h(Kt)],Bt);let qt=class AuditsController extends Bt{constructor(){super(...arguments),this.model=Ct,this.permissions=["read"]}all(e,t,i){return De(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 De(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};Ce([g(),We(),Ue(),Re(0,c()),Re(1,m("type")),Re(2,m("table")),je("design:type",Function),je("design:paramtypes",[n,String,String]),je("design:returntype",Promise)],qt.prototype,"all",null),Ce([g("/:id"),We(),Ue(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],qt.prototype,"get",null),qt=Ce([y("/audits"),h(Bt)],qt);let Ut=class AuthController extends Kt{constructor(){super(...arguments),this.authService=new kt}login(e,i,r,n,o,s){return De(this,void 0,void 0,function*(){var a;yield Z(Env.SLEEP_AUTH);const d=yield xt.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 Mt.findOne({where:{revoked_at:null,user_id:d.id}}).catch(this.error);if(n+=Env.PASSWORD_PEPPER,!l||!(yield Oe(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 Ot.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!=Fe.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 De(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 De(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 De(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}))})}};Ce([E("/login"),f(e=>({username:e.string().min(3),password:e.string().min(5),remember:e.boolean().parse().default(!1)})),Re(0,c()),Re(1,p("user-agent")),Re(2,_("username")),Re(3,_("password")),Re(4,_("remember")),Re(5,S()),je("design:type",Function),je("design:paramtypes",[n,String,String,String,Boolean,Application]),je("design:returntype",Promise)],Ut.prototype,"login",null),Ce([g("/logout"),We(),Re(0,c()),Re(1,ze()),Re(2,Ze()),Re(3,S()),je("design:type",Function),je("design:paramtypes",[n,Tt,xt,Application]),je("design:returntype",Promise)],Ut.prototype,"logout",null),Ce([E("/renew"),f(e=>({token:e.string()})),Re(0,c()),Re(1,p("user-agent")),Re(2,_("token")),Re(3,S()),je("design:type",Function),je("design:paramtypes",[n,String,String,Application]),je("design:returntype",Promise)],Ut.prototype,"renew",null),Ce([g(),g("/me"),We(),Re(0,c()),Re(1,Ze()),je("design:type",Function),je("design:paramtypes",[n,xt]),je("design:returntype",Promise)],Ut.prototype,"user",null),Ut=Ce([y("/auth"),h(Kt)],Ut);let Vt=class CrudController extends Bt{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 De(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return De(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}rows(e){return De(this,void 0,void 0,function*(){yield this.countAll(this.CrudArgumentsCountAll(e))})}del(e){return De(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return De(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return De(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validate(e,t){var i,r;const n=U.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){return De(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 De(this,void 0,void 0,function*(){const t=this.CrudValidateUpdate();if(t==this._crud)return e.error(new s);yield this.validate(e,t)})}};Ce([E(),We(),Be(),A("validateCreate"),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Vt.prototype,"add",null),Ce([g(),We(),Ue(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Vt.prototype,"all",null),Ce([g("/count"),We(),Ue(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Vt.prototype,"rows",null),Ce([O("/:id"),We(),qe(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Vt.prototype,"del",null),Ce([g("/:id"),We(),Ue(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Vt.prototype,"get",null),Ce([T("/:id"),We(),Ve(),A("validateUpdate"),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Vt.prototype,"set",null),Ce([Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Vt.prototype,"validateCreate",null),Ce([Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Vt.prototype,"validateUpdate",null),Vt=Ce([h(Bt)],Vt);let Yt=class FilesController extends Kt{constructor(){super(...arguments),this.directory=Env.API_HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return De(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=xe(this.directory,t);if(!Te(i)||!Ie(i).isDirectory())return e.error(new o);let r;return r=Pe(i),r=r.map(e=>this.info(xe(i,e))),r=r.filter(te),Object.assign(Object.assign({},this.info(i)),{files:r})})}info(e){if(!Te(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 De(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=J(e.replace(/_/g," ")," ");yield X(this.permissions,i=>De(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield It.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${J(i," ")}`,active:!0}})}))})}};Ce([g("/path"),g("/path/*path"),We(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Yt.prototype,"files",null),Yt=Ce([y("/files"),h(Kt)],Yt);let $t=class ForgotController extends Kt{check(e,t){return De(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.error(new o);i.secret=ie(),yield i.save(),e.json({token:i.secret})})}forgot(e,t,i){return De(this,void 0,void 0,function*(){yield Z(Env.SLEEP_FORGOT);const r=t,n=yield xt.findOne({where:{[he.or]:[{email:r},{username:t}]}}).catch(this.error);if(!n)return e.error(new o);const s=ie(),a=Date.now()+6e4*Env.API_TOKEN_FORGOT,d=yield jt.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 De(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 De(this,void 0,void 0,function*(){return yield jt.findOne({where:{token:e,active:!0},include:[{association:"users",required:!0}]}).catch(this.error)})}};Ce([g("/check"),f(e=>({token:e.string()})),Re(0,c()),Re(1,_("token")),je("design:type",Function),je("design:paramtypes",[n,String]),je("design:returntype",Promise)],$t.prototype,"check",null),Ce([E(),f(e=>({username:e.string().min(4)})),Re(0,c()),Re(1,_("username")),Re(2,S()),je("design:type",Function),je("design:paramtypes",[n,String,Application]),je("design:returntype",Promise)],$t.prototype,"forgot",null),Ce([E("/reset"),f(e=>({token:e.string(),password:e.string().min(5)})),Re(0,c()),Re(1,_("token")),Re(2,_("password")),Re(3,S()),je("design:type",Function),je("design:paramtypes",[n,String,String,Application]),je("design:returntype",Promise)],$t.prototype,"reset",null),$t=Ce([y("/forgot"),h(Kt)],$t);let Wt=class GroupsController extends Vt{constructor(){super(...arguments),this.model=bt,this.schemaCreate={name:U.string(),description:U.string().default(""),active:U.boolean().parse()},this.schemaUpdate={description:U.string().optional(),active:U.boolean().parse().optional()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}};Wt=Ce([y("/groups"),h(Vt)],Wt);let zt=class GroupsPermissionsController extends Bt{constructor(){super(...arguments),this.model=Pt,this.permissions=[]}all(e,t){return De(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 De(this,void 0,void 0,function*(){const r=yield bt.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new o);const n=r.id,s=[];yield X(Q(i),t=>De(this,void 0,void 0,function*(){var i;if(!(yield It.count({where:{id:t}})))return;const[r]=null!==(i=yield Pt.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 Pt.destroy(Object.assign({where:{group_id:n,permission_id:{[he.notIn]:s}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Ce([g("/:id/permissions"),We(),Ue("groups"),Re(0,c()),Re(1,I("id")),je("design:type",Function),je("design:paramtypes",[n,String]),je("design:returntype",Promise)],zt.prototype,"all",null),Ce([T("/:id/permissions"),We(),Ve("groups"),f(e=>({permissions:e.array(e.string().uuid())})),Re(0,c()),Re(1,I("id")),Re(2,_("permissions")),je("design:type",Function),je("design:paramtypes",[n,String,Array]),je("design:returntype",Promise)],zt.prototype,"set",null),zt=Ce([y("/groups"),h(Bt)],zt);let Gt=class HealthController{ping(e){return De(this,void 0,void 0,function*(){e.json({status:"ok",timestamp:Date.now(),uptime:process.uptime()})})}};Ce([P("/"),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Gt.prototype,"ping",null),Gt=Ce([y("/health")],Gt);let Jt=class LogsController extends Bt{constructor(){super(...arguments),this.model=Dt,this.permissions=["read"]}all(e){return De(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{order:[["created_at","DESC"]]}})})}};Ce([g(),We(),Ue(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Jt.prototype,"all",null),Jt=Ce([y("/logs"),h(Bt)],Jt);let Qt=class McpController extends Kt{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=>De(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 De(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",ct),t.status(405).end()}),this.discoverMcpTools(e.controllers).forEach(e=>this.tools.register(e))))})}options(e){return De(this,void 0,void 0,function*(){this.respond(e,this.handler.options(this.request(e)))})}post(e){return De(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 De(this,void 0,void 0,function*(){this.respond(e,this.handler.delete(this.request(e)))})}getMcpToolMetadata(e){const t=ye(ht,e,[]);return t.length||"function"==typeof e?t:ye(ht,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 gt(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:rt(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()}};Ce([b(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Qt.prototype,"options",null),Ce([E(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Qt.prototype,"post",null),Ce([O(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],Qt.prototype,"delete",null),Qt=Ce([y("/mcp"),h(Kt)],Qt);let Xt=class PermissionsController extends Vt{constructor(){super(...arguments),this.model=It,this.schemaCreate={name:U.string(),description:U.string().default(""),active:U.boolean().parse()},this.schemaUpdate={description:U.string().optional(),active:U.boolean().parse().optional()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}};Xt=Ce([y("/permissions"),h(Vt)],Xt);let Zt=class RegisterController extends Kt{register(e,t,i){return De(this,void 0,void 0,function*(){yield Z(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 xt.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 xt.create({name:r,email:o,username:u,password:c,avatar:"",date:n,description:"",status:Fe.PENDING}).catch(this.error);if(!p)return e.error(new s);const v=yield Ot.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 De(this,void 0,void 0,function*(){const r=yield Ot.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=Fe.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 De(this,void 0,void 0,function*(){const r=t,n=yield Ot.findOne({where:{active:!0},include:[{model:xt,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 De(this,void 0,void 0,function*(){const e=K();return(yield Ot.count({where:{token:e}}))?this.getId():e})}};Ce([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)})),Re(0,c()),Re(1,_()),Re(2,S()),je("design:type",Function),je("design:paramtypes",[n,Object,Application]),je("design:returntype",Promise)],Zt.prototype,"register",null),Ce([E("/confirm"),f(e=>({token:e.string()})),Re(0,c()),Re(1,_("token")),Re(2,S()),je("design:type",Function),je("design:paramtypes",[n,String,Application]),je("design:returntype",Promise)],Zt.prototype,"confirm",null),Ce([E("/send"),f(e=>({username:e.string().min(4)})),Re(0,c()),Re(1,_("username")),Re(2,S()),je("design:type",Function),je("design:paramtypes",[n,String,Application]),je("design:returntype",Promise)],Zt.prototype,"send",null),Zt=Ce([y("/register"),h(Kt)],Zt);let ei=class SetupController extends Kt{constructor(){super(...arguments),this.userService=new Ft}setup(e){return De(this,void 0,void 0,function*(){var t;if(yield xt.count())return e.error(new o("Endpoint Not Found"));const i=yield xt.create({name:"Admin",username:"admin",email:"admin@localhost.com",notes:"",status:Fe.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 bt.create({name:"root",description:"Root",active:!0},Object.assign({},{ctx:e}));yield wt.create({user_id:i.id,group_id:r.id},Object.assign({},{ctx:e})),yield bt.create({name:"admin",description:"Admin",active:!0},Object.assign({},{ctx:e})),yield bt.create({name:"user",description:"User",active:!0},Object.assign({},{ctx:e}));const n=null!==(t=yield It.findAll({where:{active:!0}}).catch(this.error))&&void 0!==t?t:[];yield X(n,t=>De(this,void 0,void 0,function*(){yield Pt.create({group_id:r.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}};Ce([g(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],ei.prototype,"setup",null),ei=Ce([y("/setup"),h(Kt)],ei);let ti=class TestController extends Kt{json(e){return De(this,void 0,void 0,function*(){e.json({ok:!0,message:"hello",timestamp:Date.now()})})}sum(e,t){return De(this,void 0,void 0,function*(){const{a:t,b:i}=e;return{value:t+i}})}multiply(e,t){return De(this,void 0,void 0,function*(){const{a:t,b:i}=e;return{value:t*i}})}average(e,t){return De(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 De(this,void 0,void 0,function*(){const t=e.text;return{length:t.length,normalized:t.trim()}})}validationNumber(e,t){return De(this,void 0,void 0,function*(){return{doubled:2*e.value}})}validationBoolean(e,t){return De(this,void 0,void 0,function*(){return{active:e.active}})}validationArray(e,t){return De(this,void 0,void 0,function*(){return{count:e.tags.length}})}validationObject(e,t){return De(this,void 0,void 0,function*(){const t=e.profile;return{summary:{name:t.name,adult:t.age>=18}}})}validationEnum(e,t){return De(this,void 0,void 0,function*(){return{status:e.status}})}validationDate(e,t){return De(this,void 0,void 0,function*(){const t=e.date;return{iso:t.toISOString(),timestamp:t.getTime()}})}validationOptional(e,t){return De(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 De(this,void 0,void 0,function*(){return{name:e.name,limit:e.limit}})}validationParse(e,t){return De(this,void 0,void 0,function*(){return{active:e.active,amount:e.amount}})}validationNested(e,t){return De(this,void 0,void 0,function*(){const t=e.payload;return{userId:t.user.id,scoreCount:t.scores.length}})}};Ce([g(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],ti.prototype,"json",null),Ce([mt({name:"sum",title:"Somar numeros",description:"Soma dois numeros.",input:{a:U.number().description("valor a"),b:U.number().description("valor b")},output:{value:U.number().description("resultado da soma de a + b")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"sum",null),Ce([mt({name:"multiply",title:"Multiplicar numeros",description:"Multiplica dois numeros.",input:{a:U.number().description("valor a"),b:U.number().description("valor b")},output:{value:U.number().description("resultado da multiplicação de a * b")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"multiply",null),Ce([mt({name:"average",title:"Calcular media",description:"Calcula a media de uma lista de numeros.",input:{values:U.array(U.number().description("numero usado no calculo da media")).min(1).max(10).description("lista de numeros para calcular a media")},output:{value:U.number().description("media calculada"),count:U.number().description("quantidade de numeros usados")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"average",null),Ce([mt({name:"validation.string",title:"Validacao de string",description:"Exemplo de validacao de texto com tamanho minimo e maximo.",input:{text:U.string().min(5).max(50).description("Texto entre 5 e 50 caracteres.")},output:{length:U.number().description("Quantidade de caracteres do texto."),normalized:U.string().description("Texto normalizado sem espacos nas pontas.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationString",null),Ce([mt({name:"validation.number",title:"Validacao de number",description:"Exemplo de validacao numerica com minimo e maximo.",input:{value:U.number().min(0).max(100).description("Numero entre 0 e 100.")},output:{doubled:U.number().description("Numero multiplicado por dois.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationNumber",null),Ce([mt({name:"validation.boolean",title:"Validacao de boolean",description:"Exemplo de validacao de booleano sem parse implicito.",input:{active:U.boolean().description("Indica se o registro esta ativo.")},output:{active:U.boolean().description("Booleano validado.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationBoolean",null),Ce([mt({name:"validation.array",title:"Validacao de array",description:"Exemplo de validacao de array com limites e item tipado.",input:{tags:U.array(U.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:U.number().description("Quantidade de tags recebidas.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationArray",null),Ce([mt({name:"validation.object",title:"Validacao de object",description:"Exemplo de validacao de objeto simples.",input:{profile:U.object({name:U.string().min(2).max(60).description("Nome do perfil."),age:U.number().min(0).max(120).description("Idade do perfil."),nickname:U.string().empty().max(30).description("Apelido opcional do perfil.")}).description("Objeto de perfil.")},output:{summary:U.object({name:U.string().description("Nome validado."),adult:U.boolean().description("Indica se a idade e maior ou igual a 18.")}).description("Resumo do perfil.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationObject",null),Ce([mt({name:"validation.enum",title:"Validacao de enum",description:"Exemplo de validacao de lista fechada de valores.",input:{status:U.enum(["draft","active","archived"]).description("Status permitido.")},output:{status:U.string().description("Status validado.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationEnum",null),Ce([mt({name:"validation.date",title:"Validacao de date",description:"Exemplo de validacao e parse de data.",input:{date:U.date().parse().description("Data em formato aceito pelo Date.")},output:{iso:U.string().description("Data em ISO string."),timestamp:U.number().description("Data em timestamp Unix em milissegundos.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationDate",null),Ce([mt({name:"validation.optional",title:"Validacao de campo opcional",description:"Exemplo de campo opcional aceitando ausencia.",input:{name:U.string().min(2).description("Nome obrigatorio."),nickname:U.string().empty().max(30).description("Apelido opcional.")},output:{name:U.string().description("Nome validado."),hasNickname:U.boolean().description("Indica se apelido foi enviado."),nickname:U.string().empty().description("Apelido validado quando enviado.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationOptional",null),Ce([mt({name:"validation.defaults",title:"Validacao de valores padrao",description:"Exemplo de campos opcionais com valores padrao.",input:{name:U.string().default("guest").description("Nome opcional com valor padrao."),limit:U.number().parse().default(10).min(1).max(100).description("Limite opcional com valor padrao.")},output:{name:U.string().description("Nome final."),limit:U.number().description("Limite final.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationDefaults",null),Ce([mt({name:"validation.parse",title:"Validacao com parse",description:"Exemplo de parse de boolean e number antes da validacao final.",input:{active:U.boolean().parse().default(!1).description("Booleano aceitando valores parseaveis."),amount:U.number().parse().min(1).max(1e3).description("Numero aceitando string numerica.")},output:{active:U.boolean().description("Booleano parseado."),amount:U.number().description("Numero parseado.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationParse",null),Ce([mt({name:"validation.nested",title:"Validacao de objeto aninhado",description:"Exemplo de objeto aninhado com array interno.",input:{payload:U.object({user:U.object({id:U.string().min(3).max(30).description("Identificador do usuario."),email:U.string().email().description("Email do usuario.")}).description("Usuario do payload."),scores:U.array(U.number().min(0).max(100).description("Pontuacao individual.")).min(1).max(3).description("Pontuacoes do usuario.")}).description("Payload aninhado.")},output:{userId:U.string().description("Identificador validado."),scoreCount:U.number().description("Quantidade de pontuacoes.")}}),je("design:type",Function),je("design:paramtypes",[Object,Object]),je("design:returntype",Promise)],ti.prototype,"validationNested",null),ti=Ce([y("/test"),h(Kt)],ti);let ii=class UsersController extends Bt{constructor(){super(),this.model=xt,this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&Te(Env.API_HTTP_PUBLIC)&&!Te(this.path)&&be(this.path)}avatar(e,t){return De(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 xt.findOne({where:{user_id:t.id}}).catch(this.error);if(!i)return we(o).isFile()&&Me(o),e.error(new s);const r=this.path+"/"+i.metadata.avatar_url;if(Te(r)&&we(r).isFile()&&Me(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 De(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 De(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return De(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}rows(e){return De(this,void 0,void 0,function*(){yield this.countAll({ctx:e})})}del(e,t,i){return De(this,void 0,void 0,function*(){if(i.id==t)return e.error(new o);yield this.delete({ctx:e})})}get(e){return De(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return De(this,void 0,void 0,function*(){yield this.update({ctx:e})})}};Ce([E("/avatar"),We(),w({file:{count:1,path:`${Env.API_HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),Re(0,c()),Re(1,Ze()),je("design:type",Function),je("design:paramtypes",[n,xt]),je("design:returntype",Promise)],ii.prototype,"avatar",null),Ce([E(),We(),Be(),f(e=>({name:e.string(),email:e.string().email(),username:e.string().min(3),notes:e.string().default(""),status:e.enum(["active","pending","disabled","locked","archived"]).default("active")})),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],ii.prototype,"add",null),Ce([g(),We(),Ue(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],ii.prototype,"all",null),Ce([g("/count"),We(),Ue(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],ii.prototype,"rows",null),Ce([O("/:id"),We(),qe(),Re(0,c()),Re(1,I("id")),Re(2,Ze()),je("design:type",Function),je("design:paramtypes",[n,String,xt]),je("design:returntype",Promise)],ii.prototype,"del",null),Ce([g("/:id"),We(),Ue(),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],ii.prototype,"get",null),Ce([T("/:id"),We(),Ve(),f(e=>({name:e.string().optional(),email:e.string().email().optional(),username:e.string().min(3).optional(),notes:e.string().optional(),status:e.enum(["active","pending","disabled","locked","archived"]).optional()})),Re(0,c()),je("design:type",Function),je("design:paramtypes",[n]),je("design:returntype",Promise)],ii.prototype,"set",null),ii=Ce([y("/users"),h(Bt),je("design:paramtypes",[])],ii);let ri=class UsersGroupsController extends Bt{constructor(){super(...arguments),this.model=wt,this.permissions=[]}all(e,t){return De(this,void 0,void 0,function*(){if(!(yield xt.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 De(this,void 0,void 0,function*(){const r=yield xt.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new o("User Not Found"));const n=r.id,s=[];yield X(Q(i),t=>De(this,void 0,void 0,function*(){var i;if(!(yield bt.count({where:{id:t}})))return;const[r]=null!==(i=yield wt.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 wt.destroy(Object.assign({where:{user_id:n,group_id:{[he.notIn]:s}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Ce([g("/:id/groups"),We(),Ue("users"),Re(0,c()),Re(1,I("id")),je("design:type",Function),je("design:paramtypes",[n,String]),je("design:returntype",Promise)],ri.prototype,"all",null),Ce([T("/:id/groups"),We(),Ve("users"),f(e=>({groups:e.array(e.string().uuid())})),Re(0,c()),Re(1,I("id")),Re(2,_("groups")),je("design:type",Function),je("design:paramtypes",[n,String,Array]),je("design:returntype",Promise)],ri.prototype,"set",null),ri=Ce([y("/users"),h(Bt)],ri);export{Application,At as Audit,Ct as AuditModel,He as AuditTypes,qt as AuditsController,Ut as AuthController,kt as AuthService,Kt as BaseController,Be as CanCreate,qe as CanDelete,Ue as CanRead,Ve as CanUpdate,Config,Rt as ConfigModel,Vt as CrudController,Env,Yt as FilesController,$t as ForgotController,jt as ForgotModel,bt as GroupModel,Pt as GroupPermissionModel,Wt as GroupsController,zt as GroupsPermissionsController,Ye as HasGroups,$e as HasPermissions,Gt as HealthController,We as IsAuthenticated,Log,Dt as LogModel,Loggable,ke as Loglevels,Jt as LogsController,at as MCP_DEFAULT_PROTOCOL_VERSION,ct as MCP_HTTP_ALLOW,ut as MCP_HTTP_ALLOWED_METHODS,dt as MCP_PROTOCOL_VERSION_HEADER,lt as MCP_SESSION_ID_HEADER,st as MCP_SUPPORTED_PROTOCOL_VERSIONS,ht as MCP_TOOL_METADATA,Qt as McpController,McpError,et as McpErrorCode,McpHttpHandler,McpInternalError,McpInvalidParamsError,McpInvalidRequestError,McpInvalidSessionError,McpMethodNotFoundError,McpParseError,McpRateLimiter,McpServerError,McpSessionStore,mt as McpTool,McpToolNotFoundError,McpToolRegistry,Nt as MigrationModel,Bt as ModelController,ModelService,It as PermissionModel,Xt as PermissionsController,Zt as RegisterController,Ot as RegisterModel,ze as ReqAuth,Ge as ReqGroup,Je as ReqGroups,Qe as ReqPermission,Xe as ReqPermissions,Ze as ReqUser,Ht as Service,Lt as SessionModel,SessionStore,ei as SetupController,ti as TestController,Tt as UserAuthModel,wt as UserGroupModel,xt as UserModel,Mt as UserPasswordModel,Ft as UserService,Fe as UserStatus,ii as UsersController,ri as UsersGroupsController,gt as assertValidMcpToolDefinition,Ke as canFactory,pt as isJsonParseError,tt as isJsonRpcId,vt as jsonParseErrorResponse,rt as jsonRpcError,nt as jsonRpcErrorFromCode,it as jsonRpcResult,ot as parseJsonRpcRequest,Le as sequelize};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrewcaires/api",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.3.0",
|
|
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.
|
|
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.1",
|
|
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.0"
|
|
80
81
|
}
|
|
81
82
|
}
|