@andrewcaires/api 5.0.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +2 -2
- package/dist/index.d.ts +175 -91
- package/dist/index.esm.js +2 -2
- package/package.json +9 -9
package/dist/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v5.0.
|
|
2
|
+
* @andrewcaires/api v5.0.1
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2026 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
"use strict";var e,t=require("@andrewcaires/express"),r=require("@andrewcaires/node"),o=require("@andrewcaires/utils.js"),i=require("ws"),s=require("@andrewcaires/sequelize"),n=require("dotenv"),d=require("bcrypt"),l=require("express-session"),a=require("@andrewcaires/decorator"),p=require("jsonwebtoken"),u=require("fs"),c=require("path");function g(e,t,r,o){var i,s=arguments.length,n=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,o);else for(var d=e.length-1;d>=0;d--)(i=e[d])&&(n=(s<3?i(n):s>3?i(t,r,n):i(t,r))||n);return s>3&&n&&Object.defineProperty(t,r,n),n}function v(e,t){return function(r,o){t(r,o,e)}}function y(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function x(e,t,r,o){return new(r||(r=Promise))(function(i,s){function n(e){try{l(o.next(e))}catch(e){s(e)}}function d(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(n,d)}l((o=o.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError,n.config({quiet:!0});class Env extends r.Env{}e=Env,Env.BASE_NAME=e.getString("BASE_NAME",""),Env.CONSOLE_ERROR=e.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=e.getString("DATABASE_URI",""),Env.DATABASE_LOG=e.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=e.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=e.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=e.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CRT=e.getFile("HTTP_CRT"),Env.HTTP_KEY=e.getFile("HTTP_KEY"),Env.TOKEN_CRT=e.getFile("TOKEN_CRT"),Env.TOKEN_KEY=e.getFile("TOKEN_KEY"),Env.API_BODYPARSER_STRICT=e.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=e.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=e.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=e.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_PORT=e.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=e.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_CROSS=e.getBool("API_HTTP_CROSS",!1),Env.API_HTTP_HYBRID=e.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=e.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=e.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=e.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=e.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=e.getString("API_KEY_HEADER","x-api-key"),Env.API_MODEL_LIMIT=e.getInt("API_MODEL_LIMIT",10),Env.API_MODEL_LIMIT_MAX=e.getInt("API_MODEL_LIMIT_MAX",500),Env.API_SLEEP_AUTH=e.getMs("API_SLEEP_AUTH","2s"),Env.API_SLEEP_FORGOT=e.getMs("API_SLEEP_FORGOT","5s"),Env.API_SLEEP_REGISTRY=e.getMs("API_SLEEP_REGISTRY","5s"),Env.API_SESSION_NAME=e.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=e.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=e.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=e.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=e.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_TOKEN_FORGOT=e.getMs("API_TOKEN_FORGOT","1d"),Env.API_TOKEN_HEADER=e.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_HEADER_KEY=e.getString("API_TOKEN_HEADER","bearer"),Env.API_TOKEN_LIFETIME=e.getMs("API_TOKEN_LIFETIME","1d"),Env.API_TOKEN_RENEW=e.getMs("API_TOKEN_RENEW","1d"),Env.API_USER_HISTORY=e.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=e.getBool("API_WEBSOCKET_START",!1);const h=new s.Sequelize({uri:Env.DATABASE_URI,logging:Env.DATABASE_LOG,prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE}),m=e=>r=>(i,s,n)=>{t.Use(i=>x(void 0,void 0,void 0,function*(){var s;let n=null!=r?r:"";o.isUndefined(r)&&(n=o.isFunction(i.controller.name)?i.controller.name():null===(s=i.controller.constructor)||void 0===s?void 0:s.name);const{permissions:d}=i.req;if((null!=d?d:[]).includes(`${n}.${e}`))return i.next();i.error(new t.UnauthorizedError("Access Denied"))}))(i,s,n)},C=m("create"),E=m("delete"),A=m("read"),M=m("update"),_=()=>(e,r,o)=>{t.Use(e=>x(void 0,void 0,void 0,function*(){yield(e=>x(void 0,void 0,void 0,function*(){var r,o,i,s;if(e.req.auth&&e.req.user)return e.next();const{[Env.API_KEY_HEADER]:n,[Env.API_TOKEN_HEADER]:d,"user-agent":l}=e.getHeaders(),a=e.getQuery(Env.API_KEY_HEADER),p=(null===(r=n||a)||void 0===r?void 0:r.toString())||"";let u=e.getCookie(Env.API_TOKEN_COOKIE);u=`${Env.API_TOKEN_HEADER_KEY} ${u}`;const[c,g]=null!==(i=null===(o=d||u)||void 0===o?void 0:o.split(" "))&&void 0!==i?i:["",""];if(!(p||g&&c.toLowerCase()==Env.API_TOKEN_HEADER_KEY))return e.error(new t.UnauthorizedError("Invalid token"));const{authService:v,userService:y}=e.app,{auth:x,user:h}=null!==(s=yield(p?v.key(p.toString()):v.user(g)).catch(t=>{e.error(t)}))&&void 0!==s?s:{};if(x&&h){if(!p&&x.user_agent&&x.user_agent!=l)return e.error(new t.UnauthorizedError("Invalid token"));e.req.auth=x,e.req.user=h,e.req.groups=yield y.getGroups(h.id),e.req.permissions=yield y.getPermissions(h.id),e.req.profile=yield y.getProfile(h.id),e.next()}}))(e)}))(e,r,o)},f=t.parameterFactory(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),S=t.parameterFactory(({ctx:e,key:t})=>{var r,o;return(null!==(o=null===(r=e.req)||void 0===r?void 0:r.groups)&&void 0!==o?o:[]).includes(t)}),P=t.parameterFactory(({ctx:e})=>{var t,r;return null!==(r=null===(t=e.req)||void 0===t?void 0:t.groups)&&void 0!==r?r:[]}),O=t.parameterFactory(({ctx:e,key:t})=>{var r,o;return(null!==(o=null===(r=e.req)||void 0===r?void 0:r.permissions)&&void 0!==o?o:[]).includes(t)}),I=t.parameterFactory(({ctx:e})=>{var t,r;return null!==(r=null===(t=e.req)||void 0===t?void 0:t.permissions)&&void 0!==r?r:[]}),U=t.parameterFactory(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.user}),T=(e,r,o)=>{var i,s,n,d,l,a,p,u,c;const g=o.ctx instanceof t.Context?o.ctx:null,v=null!==(d=null!==(n=null===(s=null===(i=null==g?void 0:g.req)||void 0===i?void 0:i.user)||void 0===s?void 0:s.id)&&void 0!==n?n:o.user_id)&&void 0!==d?d:null,y={type:e,model:null!==(l=null==r?void 0:r.getTableName())&&void 0!==l?l:null,state:!0,user_id:v};return g?Object.assign(Object.assign({},y),{full_url:null!==(a=null==g?void 0:g.getUrl())&&void 0!==a?a:"",ip_address:null!==(p=null==g?void 0:g.getIp())&&void 0!==p?p:"",user_agent:null!==(c=null===(u=null==g?void 0:g.req)||void 0===u?void 0:u.headers["user-agent"])&&void 0!==c?c:""}):y},w={afterCreate:(e,t)=>x(void 0,void 0,void 0,function*(){const i=o.getConstructor(e),{primaryKeyAttribute:s}=null!=i?i:{};yield exports.AuditModel.create(Object.assign(Object.assign({},T("CREATE",i,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(r.Log.catch)}),afterUpdate:(e,t)=>x(void 0,void 0,void 0,function*(){const i=o.getConstructor(e),{primaryKeyAttribute:s}=null!=i?i:{},n={},d=e.changed();d&&d.forEach(t=>n[t]=e.getDataValue(t)),yield exports.AuditModel.create(Object.assign(Object.assign({},T("UPDATE",i,t)),{record:s?e.getDataValue(s):null,data:n,previously:e.previous()})).catch(r.Log.catch)}),afterDestroy:(e,t)=>x(void 0,void 0,void 0,function*(){const i=o.getConstructor(e),{primaryKeyAttribute:s}=null!=i?i:{};yield exports.AuditModel.create(Object.assign(Object.assign({},T("DELETE",i,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(r.Log.catch)})},b=e=>(o.isUndefined(e)&&(e=Env.DATABASE_AUDIT),s.Hooks(e?w:{}));exports.RegisterModel=class RegisterModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.RegisterModel.prototype,"id",void 0),g([s.Column.String(),y("design:type",String)],exports.RegisterModel.prototype,"secret",void 0),g([s.Column.FullDate(),y("design:type",Number)],exports.RegisterModel.prototype,"expired_at",void 0),g([s.Column.Boolean(),y("design:type",Boolean)],exports.RegisterModel.prototype,"state",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.RegisterModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.RegisterModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),y("design:type",Object)],exports.RegisterModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.RegisterModel.prototype,"user_id",void 0),exports.RegisterModel=g([s.Database(h),s.ModelName("register"),s.Version("5.0.0")],exports.RegisterModel),exports.UserAuthModel=class UserAuthModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.UserAuthModel.prototype,"id",void 0),g([s.Column.String(),y("design:type",String)],exports.UserAuthModel.prototype,"secret",void 0),g([s.Column.String(),y("design:type",String)],exports.UserAuthModel.prototype,"ip_address",void 0),g([s.Column.String(),y("design:type",String)],exports.UserAuthModel.prototype,"user_agent",void 0),g([s.Column.FullDate(),y("design:type",Object)],exports.UserAuthModel.prototype,"revoked_at",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.UserAuthModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.UserAuthModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),y("design:type",Object)],exports.UserAuthModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.UserAuthModel.prototype,"user_id",void 0),exports.UserAuthModel=g([s.Database(h),s.ModelName("users_auth"),s.Version("5.0.0")],exports.UserAuthModel),exports.PermissionModel=class PermissionModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.PermissionModel.prototype,"id",void 0),g([s.Column.String(),y("design:type",String)],exports.PermissionModel.prototype,"name",void 0),g([s.Column.String(),s.Unique(!0),y("design:type",String)],exports.PermissionModel.prototype,"key",void 0),g([s.Column.String(),y("design:type",String)],exports.PermissionModel.prototype,"tag",void 0),g([s.Column.Text(),y("design:type",String)],exports.PermissionModel.prototype,"description",void 0),g([s.Column.Boolean(),y("design:type",Boolean)],exports.PermissionModel.prototype,"state",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.PermissionModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.PermissionModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),y("design:type",Object)],exports.PermissionModel.prototype,"deleted_at",void 0),g([s.HasMany(()=>exports.GroupPermissionModel,"permission_id"),y("design:type",Array)],exports.PermissionModel.prototype,"groups_permissions",void 0),exports.PermissionModel=g([s.Database(h),s.ModelName("permission"),b(),s.Version("5.0.0")],exports.PermissionModel),exports.GroupPermissionModel=class GroupPermissionModel extends s.Model{},g([s.Column.CreatedAt(),y("design:type",Date)],exports.GroupPermissionModel.prototype,"created_at",void 0),g([s.Association.BelongsTo(()=>exports.GroupModel),y("design:type",String)],exports.GroupPermissionModel.prototype,"group_id",void 0),g([s.Association.BelongsTo(()=>exports.PermissionModel),y("design:type",String)],exports.GroupPermissionModel.prototype,"permission_id",void 0),exports.GroupPermissionModel=g([s.Database(h),s.ModelName("groups_permissions"),b(),s.Version("5.0.0")],exports.GroupPermissionModel),exports.GroupModel=class GroupModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.GroupModel.prototype,"id",void 0),g([s.Column.String(),y("design:type",String)],exports.GroupModel.prototype,"name",void 0),g([s.Column.String(),y("design:type",String)],exports.GroupModel.prototype,"key",void 0),g([s.Column.Text(),y("design:type",String)],exports.GroupModel.prototype,"description",void 0),g([s.Column.Boolean(),y("design:type",Boolean)],exports.GroupModel.prototype,"state",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.GroupModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.GroupModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),y("design:type",Object)],exports.GroupModel.prototype,"deleted_at",void 0),g([s.Association.HasMany(()=>exports.UserGroupModel,"group_id"),y("design:type",Array)],exports.GroupModel.prototype,"users_groups",void 0),g([s.Association.HasMany(()=>exports.GroupPermissionModel,"group_id"),y("design:type",Array)],exports.GroupModel.prototype,"groups_Permission",void 0),exports.GroupModel=g([s.Database(h),s.ModelName("group"),b(),s.Version("5.0.0")],exports.GroupModel),exports.UserGroupModel=class UserGroupModel extends s.Model{},g([s.Column.CreatedAt(),y("design:type",Date)],exports.UserGroupModel.prototype,"created_at",void 0),g([s.Association.BelongsTo(()=>exports.GroupModel),y("design:type",String)],exports.UserGroupModel.prototype,"group_id",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.UserGroupModel.prototype,"user_id",void 0),exports.UserGroupModel=g([s.Database(h),s.ModelName("users_groups"),b(),s.Version("5.0.0")],exports.UserGroupModel),exports.UserPasswordModel=class UserPasswordModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.UserPasswordModel.prototype,"id",void 0),g([s.Column.String(),s.Value(e=>d.hashSync(e.value,12)),y("design:type",String)],exports.UserPasswordModel.prototype,"value",void 0),g([s.Column.Boolean(),y("design:type",Boolean)],exports.UserPasswordModel.prototype,"state",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.UserPasswordModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.UserPasswordModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),y("design:type",Object)],exports.UserPasswordModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.UserPasswordModel.prototype,"user_id",void 0),exports.UserPasswordModel=g([s.Database(h),s.ModelName("users_password"),b(),s.Version("5.0.0")],exports.UserPasswordModel),exports.UserModel=class UserModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.UserModel.prototype,"id",void 0),g([s.Column.String(),y("design:type",String)],exports.UserModel.prototype,"name",void 0),g([s.Column.String(),y("design:type",String)],exports.UserModel.prototype,"email",void 0),g([s.Column.String(),y("design:type",String)],exports.UserModel.prototype,"username",void 0),g([s.Column.Text(),y("design:type",String)],exports.UserModel.prototype,"description",void 0),g([s.Column.Boolean(),y("design:type",Boolean)],exports.UserModel.prototype,"state",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.UserModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.UserModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),y("design:type",Object)],exports.UserModel.prototype,"deleted_at",void 0),g([s.Association.HasMany(()=>exports.AuditModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"audits",void 0),g([s.Association.HasMany(()=>exports.UserAuthModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"users_auths",void 0),g([s.Association.HasMany(()=>exports.RegisterModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"registers",void 0),g([s.Association.HasMany(()=>exports.UserGroupModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"users_groups",void 0),g([s.Association.HasMany(()=>exports.UserPasswordModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"users_passwords",void 0),exports.UserModel=g([s.Database(h),s.ModelName("user"),b(),s.Version("5.0.0")],exports.UserModel),exports.AuditModel=class AuditModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.AuditModel.prototype,"id",void 0),g([s.Column.Enum("CREATE","DELETE","UPDATE"),y("design:type",String)],exports.AuditModel.prototype,"type",void 0),g([s.Column.String(),y("design:type",String)],exports.AuditModel.prototype,"model",void 0),g([s.Column.String(),y("design:type",String)],exports.AuditModel.prototype,"record",void 0),g([s.Column.Json(),y("design:type",Object)],exports.AuditModel.prototype,"data",void 0),g([s.Column.Json(),y("design:type",Object)],exports.AuditModel.prototype,"previously",void 0),g([s.Column.Text(),y("design:type",String)],exports.AuditModel.prototype,"full_url",void 0),g([s.Column.String(),y("design:type",String)],exports.AuditModel.prototype,"ip_address",void 0),g([s.Column.String(),y("design:type",String)],exports.AuditModel.prototype,"user_agent",void 0),g([s.Column.Boolean(),y("design:type",Boolean)],exports.AuditModel.prototype,"state",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.AuditModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.AuditModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),y("design:type",Object)],exports.AuditModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.AuditModel.prototype,"user_id",void 0),exports.AuditModel=g([s.Database(h),s.ModelName("audit"),s.Version("5.0.0")],exports.AuditModel),exports.ConfigModel=class ConfigModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.ConfigModel.prototype,"id",void 0),g([s.Column.String(),y("design:type",String)],exports.ConfigModel.prototype,"key",void 0),g([s.Column.String(),y("design:type",String)],exports.ConfigModel.prototype,"value",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.ConfigModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.ConfigModel.prototype,"updated_at",void 0),exports.ConfigModel=g([s.Database(h),s.ModelName("configs"),s.Version("5.0.0")],exports.ConfigModel),exports.ForgotModel=class ForgotModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.ForgotModel.prototype,"id",void 0),g([s.Column.String(),y("design:type",String)],exports.ForgotModel.prototype,"secret",void 0),g([s.Column.FullDate(),y("design:type",Number)],exports.ForgotModel.prototype,"expired_at",void 0),g([s.Column.Boolean(),y("design:type",Boolean)],exports.ForgotModel.prototype,"state",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.ForgotModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.ForgotModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),y("design:type",Object)],exports.ForgotModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.ForgotModel.prototype,"user_id",void 0),exports.ForgotModel=g([s.Database(h),s.ModelName("forgot"),s.Version("5.0.0")],exports.ForgotModel),exports.LogModel=class LogModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.LogModel.prototype,"id",void 0),g([s.Column.Enum("info","warn","error"),s.DefaultValue("info"),y("design:type",String)],exports.LogModel.prototype,"level",void 0),g([s.Column.Text(),y("design:type",String)],exports.LogModel.prototype,"message",void 0),g([s.Column.String(),y("design:type",String)],exports.LogModel.prototype,"source",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.LogModel.prototype,"created_at",void 0),exports.LogModel=g([s.Database(h),s.ModelName("log"),s.Version("5.0.0")],exports.LogModel),exports.MigrationModel=class MigrationModel extends s.Model{},g([s.Column.String(),y("design:type",String)],exports.MigrationModel.prototype,"model",void 0),g([s.Column.String(),y("design:type",String)],exports.MigrationModel.prototype,"version",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.MigrationModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.MigrationModel.prototype,"updated_at",void 0),exports.MigrationModel=g([s.Database(h),s.ModelName("migration"),s.Version("5.0.0")],exports.MigrationModel),exports.SessionModel=class SessionModel extends s.Model{},g([s.Column.String(),y("design:type",String)],exports.SessionModel.prototype,"session",void 0),g([s.Column.Text(),y("design:type",String)],exports.SessionModel.prototype,"json",void 0),g([s.Column.BigInt(),y("design:type",Number)],exports.SessionModel.prototype,"expired",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.SessionModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.SessionModel.prototype,"updated_at",void 0),exports.SessionModel=g([s.Database(h),s.ModelName("session"),s.Version("5.0.0")],exports.SessionModel),exports.UserMetadataModel=class UserMetadataModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.UserMetadataModel.prototype,"id",void 0),g([s.Column.String(),y("design:type",String)],exports.UserMetadataModel.prototype,"key",void 0),g([s.Column.Text("medium"),y("design:type",String)],exports.UserMetadataModel.prototype,"value",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.UserMetadataModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.UserMetadataModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),y("design:type",Object)],exports.UserMetadataModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.UserMetadataModel.prototype,"user_id",void 0),exports.UserMetadataModel=g([s.Database(h),s.ModelName("users_metadata"),b(),s.Version("5.0.0")],exports.UserMetadataModel),exports.UserProfileModel=class UserProfileModel extends s.Model{},g([s.Column.UUID(7),y("design:type",String)],exports.UserProfileModel.prototype,"id",void 0),g([s.Column.String(),y("design:type",String)],exports.UserProfileModel.prototype,"key",void 0),g([s.Column.Text("medium"),y("design:type",String)],exports.UserProfileModel.prototype,"value",void 0),g([s.Column.CreatedAt(),y("design:type",Date)],exports.UserProfileModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),y("design:type",Date)],exports.UserProfileModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),y("design:type",Object)],exports.UserProfileModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.UserProfileModel.prototype,"user_id",void 0),exports.UserProfileModel=g([s.Database(h),s.ModelName("users_profile"),b(),s.Version("5.0.0")],exports.UserProfileModel);class Log{static error(e,t,r){return x(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,r)})}static info(e,t,r){return x(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,r)})}static warn(e,t,r){return x(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,r)})}static writeRaw(e,t,o,i){return x(this,void 0,void 0,function*(){var s;i&&r.Log.console(null!==(s=this.colors[e])&&void 0!==s?s:r.LogColor.White,e,t),h&&(yield exports.LogModel.create({level:e,message:t,source:null!=o?o:""}).catch(r.Log.catch))})}}Log.colors={error:r.LogColor.Red,info:r.LogColor.Cyan,warn:r.LogColor.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 r,o;Log.error(null!==(o=null!==(r=null==t?void 0:t.message)&&void 0!==r?r:t)&&void 0!==o?o:"",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,r,o;const i=null!==(o=null!==(r=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)&&void 0!==r?r:null==e?void 0:e.name)&&void 0!==o?o:"null";return Env.BASE_NAME?`${Env.BASE_NAME}.${i}`:i}}class SessionStore extends l.Store{constructor(){super(),this.all=e=>x(this,void 0,void 0,function*(){e=e||o.noop;const t=yield exports.SessionModel.findAll({attributes:["session"],where:{expired:{[s.Op.gte]:Date.now()}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.session)),e()}),this.clear=e=>x(this,void 0,void 0,function*(){yield exports.SessionModel.destroy().catch(o.noop),e&&e()}),this.destroy=(e,t)=>x(this,void 0,void 0,function*(){yield exports.SessionModel.destroy({where:{session:e}}).catch(o.noop),t&&t()}),this.expired=()=>x(this,void 0,void 0,function*(){yield exports.SessionModel.destroy({where:{expired:{[s.Op.lt]:Date.now()}}}).catch(o.noop)}),this.get=(e,t)=>x(this,void 0,void 0,function*(){t=t||o.noop;const r=yield exports.SessionModel.findOne({where:{session:e,expired:{[s.Op.gte]:Date.now()}}}).catch(e=>(t(e),null));if(r){const e=JSON.parse(r.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield r.destroy().catch(o.noop),void t(null)}return void t(null,e)}t(null)}),this.length=e=>x(this,void 0,void 0,function*(){e&&e(null,(yield exports.SessionModel.count().catch(o.noop))||0)}),this.set=(e,t,r)=>x(this,void 0,void 0,function*(){r=r||o.noop;const i=Date.now()+Env.API_SESSION_LIFETIME,s=JSON.stringify(t),[n,d]=(yield exports.SessionModel.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:i}}).catch(o.noop))||[];n&&(d||(n.json=s,n.expired=i,yield n.save().catch(o.noop))),r()}),this.loop=o.loop(this.expired,3e4),this.loop.start()}}exports.Service=class Service{},exports.Service=g([a.Trait(Loggable)],exports.Service),exports.AuthService=class AuthService extends exports.Service{create(e){return x(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new t.NotFoundError("TOKEN_KEY not found");const{id:r}=e,i=o.uuidv7(),s=yield exports.UserAuthModel.create({secret:i,user_id:r}).catch(this.error);if(!s)throw new t.InternalServerError;return{auth:s,token:p.sign({id:r,secret:i},Env.TOKEN_KEY,this.options())}})}destroy(e){return x(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return x(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new t.NotFoundError("TOKEN_KEY not found");const{decode:r}=yield this.verify(e,Env.API_TOKEN_RENEW/1e3);if(!r)throw new t.UnauthorizedError("Invalid token");const{id:i,secret:s}=r;if(i&&s){const e=yield exports.UserModel.findOne({where:{id:i,state:!0}}).catch(this.error);if(e){const t=yield exports.UserAuthModel.findOne({where:{secret:s,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at){t.secret=o.uuidv7(),yield t.save().catch(this.error);return{auth:t,token:p.sign({id:i,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t.UnauthorizedError("Invalid token")})}user(e){return x(this,void 0,void 0,function*(){const{decode:r}=yield this.verify(e);if(!r)throw new t.UnauthorizedError("Invalid token");const{id:o,secret:i}=r;if(o&&i){const e=yield exports.UserModel.findOne({where:{id:o,state:!0}}).catch(this.error);if(e){const t=yield exports.UserAuthModel.findOne({where:{secret:i,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at)return{auth:t,user:e}}}throw new t.UnauthorizedError("Invalid token")})}options(){return{algorithm:"RS256",expiresIn:`${Env.API_TOKEN_LIFETIME}ms`}}verify(e,r){return x(this,void 0,void 0,function*(){if(!Env.TOKEN_CRT)throw new t.NotFoundError("TOKEN_CRT not found");if(!e||e.split(".").length<3)throw new t.UnauthorizedError("Invalid token");try{return{decode:p.verify(e,Env.TOKEN_CRT,{clockTolerance:r})}}catch(e){throw new t.UnauthorizedError("Invalid token")}})}key(e){return x(this,void 0,void 0,function*(){if(!e)throw new t.UnauthorizedError("Invalid token");const r=yield exports.UserModel.findOne({where:{token:e,state:!0}}).catch(this.error);if(r){const t=e.replace(/(-[\w]{4})/g,"-****"),[o]=(yield exports.UserAuthModel.findOrCreate({where:{secret:t,user_id:r.id},defaults:{secret:t,user_id:r.id}}).catch(this.error))||[];if(o)return o.revoked_at&&(o.revoked_at=null,yield o.save().catch(this.error)),{auth:o,user:r}}throw new t.UnauthorizedError("Invalid token")})}},exports.AuthService=g([a.Singleton()],exports.AuthService);class ModelService extends exports.Service{constructor(e,t){super(),this.attributes=[],this.filter=[],this.model=e,t&&(this.filter=t)}create(e){return x(this,arguments,void 0,function*({ctx:e,options:r,body:i}){var s,n;const d=Object.assign({},r||{}),l=yield this.model.create(Object.assign({},o.merge({},null!==(n=null===(s=null==e?void 0:e.req)||void 0===s?void 0:s.body)&&void 0!==n?n:{},null!=i?i:{})),Object.assign(Object.assign({},d),{ctx:e})).catch(this.error);if(l){const{primaryKeyAttribute:r}=this.model;return null==e||e.prepare(t.Status.OK,{[r]:l.getDataValue(r)}),l}return null==e||e.error(new t.InternalServerError),null})}delete(e){return x(this,arguments,void 0,function*({ctx:e,options:r,id:o}){var i,s,n;const d=Object.assign({},r||{}),{primaryKeyAttribute:l}=this.model,{[l]:a}=null!==(s=null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.params)&&void 0!==s?s:{[l]:null!=o?o:0};if(!a)return null==e||e.error(new t.InternalServerError),0;const p=yield this.model.destroy(Object.assign(Object.assign(Object.assign({},d),{where:Object.assign(Object.assign({},null!==(n=d.where)&&void 0!==n?n:{}),{[l]:a}),individualHooks:!0}),{ctx:e})).catch(this.error);return p?(null==e||e.success("OK"),p):(null==e||e.error(new t.NotFoundError),0)})}filterAttributes(e,t){if(o.isArray(t))return t.length?t.map(t=>o.isString(t)&&-1!=e.indexOf(t)?t:void 0).filter(o.isString):e;const{exclude:r,include:i}=t,s=o.isUndefined(i)?e:i.map(t=>o.isString(t)&&-1!=e.indexOf(t)?t:void 0).filter(o.isString),n=null!=r?r:[];return n.length?s.filter(e=>-1==n.indexOf(e)):s}findAll(e){return x(this,arguments,void 0,function*({ctx:e,options:r,callback:i,advanced:n,limited:d}){var l,a,p,u,c,g,v;const y=Object.assign({},r||{}),{attributes:x,limit:h,offset:m,asc:C,desc:E,search:A,where:M}=null!==(a=null===(l=null==e?void 0:e.req)||void 0===l?void 0:l.query)&&void 0!==a?a:{};if(o.isUndefined(y.limit)){let e=Env.API_MODEL_LIMIT;o.isString(h)&&(e=parseInt(h)||0),e=o.clamp(e,-1,Env.API_MODEL_LIMIT_MAX),y.limit=e>0?e:d?Env.API_MODEL_LIMIT:void 0}if(o.isNumber(y.limit)&&(y.limit=y.limit>0?y.limit:void 0),o.isString(m)){const e=parseInt(m)||0;y.offset=e>0?e:void 0}const _=this.getAttributes(null!==(p=null==y?void 0:y.attributes)&&void 0!==p?p:[]),f=e=>_.indexOf(e)>=0;y.attributes=[],o.isString(x)&&x.length&&y.attributes.push(...x.split(";").filter(f)),y.attributes.length||(y.attributes=_);const S=[];if(o.isString(C)&&C.length&&S.push(...C.split(";").filter(f).map(e=>[e,"ASC"])),o.isString(E)&&E.length&&S.push(...E.split(";").filter(f).map(e=>[e,"DESC"])),S.length&&(y.order=S),y.where=Object.assign({},y.where||{}),o.isString(M)&&(null==n||n)){const r=s.Where.parse(_,M);if(!o.isUndefined(r.error))return null==e||e.error(new t.ValidationError(r.error.join(", "))),{count:0,records:[]};y.where=Object.assign(Object.assign({},y.where),null!==(u=r.value)&&void 0!==u?u:{})}else{const e=[];_.forEach(t=>{o.isString(A)&&A.length&&e.push({[t]:{[s.Op.like]:`%${A}%`}})}),e.length&&(y.where=Object.assign(Object.assign({},y.where),{[s.Op.or]:[...e]}))}const P=this.model.count(Object.assign(Object.assign({},y),{distinct:!!y.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error),O=this.model.findAll(y).catch(this.error);yield Promise.allSettled([P,O]);const I=null!==(c=yield P)&&void 0!==c?c:0;let U=null!==(g=yield O)&&void 0!==g?g:[];const T={count:I};return U?(U=i?yield i(U):U,(o.isNumber(null==r?void 0:r.limit)||0==I)&&(T.count=null!==(v=null==U?void 0:U.length)&&void 0!==v?v:0),null==e||e.prepare(t.Status.OK,Object.assign(Object.assign({},T),{records:U})),Object.assign(Object.assign({},T),{records:U})):(null==e||e.error(new t.InternalServerError),Object.assign(Object.assign({},T),{records:[]}))})}findOne(e){return x(this,arguments,void 0,function*({ctx:e,options:r,callback:i}){var s,n,d,l,a;const p=Object.assign({},r||{}),{primaryKeyAttribute:u}=this.model,{[u]:c}=null!==(s=null==e?void 0:e.req.params)&&void 0!==s?s:{},g=this.getAttributes(null!==(n=null==p?void 0:p.attributes)&&void 0!==n?n:[]),v=e=>g.indexOf(e)>=0,{attributes:y}=null!==(l=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.query)&&void 0!==l?l:{};o.isString(y)&&(p.attributes=y.split(";").filter(v));const x=yield this.model.findOne(Object.assign(Object.assign({},p),{where:Object.assign(Object.assign({},null!==(a=null==p?void 0:p.where)&&void 0!==a?a:{}),{[u]:c})})).catch(this.error);return x?(null==e||e.prepare(t.Status.OK,i?yield i(x):x.toJSON()),x):x?(null==e||e.error(new t.InternalServerError),null):(null==e||e.error(new t.NotFoundError),null)})}getAttributes(e){return 0==this.attributes.length&&(this.attributes=this.filterAttributes(Object.keys(this.model.getAttributes()),this.filter)),this.filterAttributes(this.attributes,e)}update(e){return x(this,arguments,void 0,function*({ctx:e,options:t,body:r,id:i}){var s,n,d,l,a,p;const u=Object.assign({},t||{}),{primaryKeyAttribute:c}=this.model,{[c]:g}=null!==(n=null===(s=null==e?void 0:e.req)||void 0===s?void 0:s.params)&&void 0!==n?n:{[c]:null!=i?i:0},[v]=null!==(p=yield this.model.update(Object.assign({},o.merge({},null!==(l=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.body)&&void 0!==l?l:{},null!=r?r:{})),Object.assign(Object.assign(Object.assign({},u),{where:Object.assign(Object.assign({},null!==(a=null==u?void 0:u.where)&&void 0!==a?a:{}),{[c]:g}),individualHooks:!0}),{ctx:e})).catch(this.error))&&void 0!==p?p:[];return v?(null==e||e.success("OK"),!0):(null==e||e.success("Record not changed"),!1)})}name(){return this.model.tableName}}exports.UserService=class UserService extends exports.Service{getMetadata(e){return x(this,void 0,void 0,function*(){var t;return Object.fromEntries((null!==(t=yield exports.UserMetadataModel.findAll({where:{user_id:e}}).catch(this.error))&&void 0!==t?t:[]).map(e=>[e.key,e.value]))})}getProfile(e){return x(this,void 0,void 0,function*(){var t;return Object.fromEntries((null!==(t=yield exports.UserProfileModel.findAll({where:{user_id:e}}).catch(this.error))&&void 0!==t?t:[]).map(e=>[e.key,e.value]))})}getGroups(e){return x(this,void 0,void 0,function*(){var t;return(null!==(t=yield exports.GroupModel.findAll({attributes:["key"],where:{state:!0},include:[{model:exports.UserGroupModel,required:!0,where:{user_id:e}}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.key)})}getPermissions(e){return x(this,void 0,void 0,function*(){var t;return(null!==(t=yield exports.PermissionModel.findAll({attributes:["key"],where:{state:!0},include:[{model:exports.GroupPermissionModel,required:!0,include:[{model:exports.GroupModel,required:!0,attributes:["id"],where:{state:!0},include:[{model:exports.UserGroupModel,required:!0,where:{user_id:e}}]}]}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.key)})}},exports.UserService=g([a.Singleton()],exports.UserService);class Application extends t.Application{constructor(e,t){super(e,o.merge({},{cert:Env.HTTP_CRT,cross:Env.API_HTTP_CROSS,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},key:Env.HTTP_KEY,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:o.uuidv7}},null!=t?t:{})),this.hash=new r.Hash(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 x(this,void 0,void 0,function*(){yield h.sync(),yield this.migrations(h),yield o.forEachSeries(this.controllers,e=>x(this,void 0,void 0,function*(){o.isFunction(e.sync)&&(yield e.sync(this))})),this.authService=new exports.AuthService,this.userService=new exports.UserService,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new i.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>x(this,void 0,void 0,function*(){t.url||(t.url=""),!(t.url.length<=1)&&t.url.replace(/\//g,"."),e.on("close",()=>{}),yield o.sleep(2e3),e.close()})))})}migrations(e){return x(this,void 0,void 0,function*(){const t=[];yield o.forEachSeries(Object.keys(e.models),r=>x(this,void 0,void 0,function*(){var o;const i=e.models[r],s=i.version();if(!s)return;const[n,d]=null!==(o=yield exports.MigrationModel.findOrCreate({where:{model:i.tableName},defaults:{model:i.tableName,version:""}}).catch(this.error))&&void 0!==o?o:[];n&&(d||n.version!=s)&&(n.version=s,yield n.save().catch(this.error),t.push(i))})),yield o.forEachSeries(t,e=>x(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}exports.BaseController=class BaseController extends o.EventEmitter{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,r){return x(this,void 0,void 0,function*(){r.auth&&r.user&&(r.user_agent?r.user_agent!=t&&r.regenerate(o.noop):(r.user_agent=t,r.save(o.noop))),e.next()})}sync(){return x(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield o.forEachSeries(this.permissions,r=>x(this,void 0,void 0,function*(){const i=`${e}.${r}`,s=o.upperCamelCase(e.replace(/_/g," ")," ");yield exports.PermissionModel.findOrCreate({where:{key:i},defaults:Object.assign({name:`${s} ${o.upperCamelCase(r," ")}`,key:i,tag:s},t)})}))})}},g([v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Session()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Object]),y("design:returntype",Promise)],exports.BaseController.prototype,"session",null),exports.BaseController=g([a.Trait(Loggable)],exports.BaseController),exports.ModelController=class ModelController extends exports.BaseController{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"]}create(e){return x(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return x(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return x(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return x(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}sync(){return x(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield o.forEachSeries(this.permissions,r=>x(this,void 0,void 0,function*(){const i=`${e}.${r}`,s=o.upperCamelCase(e.replace(/_/g," ")," ");yield exports.PermissionModel.findOrCreate({where:{key:i},defaults:Object.assign({name:`${s} ${o.upperCamelCase(r," ")}`,key:i,tag:s},t)})})),this.service=new ModelService(this.model)})}update(e){return x(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}},exports.ModelController=g([t.Extends(exports.BaseController)],exports.ModelController),exports.AuditsController=class AuditsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.AuditModel}all(e,t,r){return x(this,void 0,void 0,function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:o,order:[["created_at","DESC"]]},limited:!0})})}get(e){return x(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}},g([t.Get(),_(),A(),v(0,t.Ctx()),v(1,t.Query("type")),v(2,t.Query("table")),y("design:type",Function),y("design:paramtypes",[t.Context,String,String]),y("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),g([t.Get("/:id"),_(),A(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=g([t.Controller("/audits"),t.Extends(exports.ModelController)],exports.AuditsController),exports.AuthController=class AuthController extends exports.BaseController{constructor(e){super(),this.authService=e}login(e,r,i,n,l,a){return x(this,void 0,void 0,function*(){var p;yield o.sleep(Env.API_SLEEP_AUTH);const u=yield exports.UserModel.findOne({where:{[s.Op.or]:[{email:i},{username:i}]}}).catch(this.error);if(!u)return e.error(new t.UnauthorizedError("Invalid credentials")),a.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const c=yield exports.UserPasswordModel.findOne({where:{user_id:u.id,state:!0}}).catch(this.error);if(!c||!d.compareSync(n,c.value))return e.error(new t.UnauthorizedError("Invalid credentials")),a.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const g=yield exports.RegisterModel.findOne({where:{state:!0,user_id:u.id}}).catch(this.error);if(g)return e.error("ACTIVATION REQUIRED"),a.emit("auth.activation",{ctx:e,register:g,user:u}),void this.emit("auth.activation",{ctx:e,register:g,user:u});if(!u.state)return e.error(new t.UnauthorizedError("Invalid credentials")),a.emit("auth.failure",{ctx:e,user:u}),void this.emit("auth.failure",{ctx:e,user:u});const{auth:v,token:y}=null!==(p=yield this.authService.create(u).catch(t=>{e.error(t),a.emit("auth.failure",{ctx:e}),this.emit("auth.failure",{ctx:e})}))&&void 0!==p?p:{};v&&y&&(v.user_agent=r,v.ip_address=e.getIp(),yield v.save().catch(this.error),Env.API_TOKEN_COOKIE_SET&&e.cookie(Env.API_TOKEN_COOKIE,y,{maxAge:l?Env.API_TOKEN_LIFETIME:void 0}),e.json({token:y}),a.emit("auth.login",{ctx:e,auth:v,user:u}),this.emit("auth.login",{ctx:e,auth:v,user:u}))})}logout(e,r,o,i){return x(this,void 0,void 0,function*(){if(yield this.authService.destroy(r))return e.success("OK"),i.emit("auth.logout",{auth:r,ctx:e,user:o}),void this.emit("auth.logout",{auth:r,ctx:e,user:o});e.error(new t.UnauthorizedError("Access Denied"))})}renew(e,t,r,o){return x(this,void 0,void 0,function*(){var i;const{auth:s,token:n}=null!==(i=yield this.authService.renew(r).catch(t=>{e.error(t)}))&&void 0!==i?i:{};s&&n&&(s.user_agent=t,yield s.save().catch(this.error),e.json({token:n}),o.emit("auth.renew",{auth:s,ctx:e}),this.emit("auth.renew",{auth:s,ctx:e}))})}user(e,r){return x(this,void 0,void 0,function*(){const{groups:i,permissions:s,profile:n}=e.req;if(!i||!s)return e.error(new t.InternalServerError);e.json(Object.assign(Object.assign({},o.denied(["username","description"],r.toJSON())),{groups:i,permissions:s,profile:n}))})}},g([t.Post("/login"),t.Validate(e=>({username:e.string().min(3).required(),password:e.string().min(5).required(),remember:e.boolean().parse().empty(!1)})),v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Body("username")),v(3,t.Body("password")),v(4,t.Body("remember")),v(5,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,String,Boolean,Application]),y("design:returntype",Promise)],exports.AuthController.prototype,"login",null),g([t.Get("/logout"),_(),v(0,t.Ctx()),v(1,f()),v(2,U()),v(3,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.UserAuthModel,exports.UserModel,Application]),y("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),g([t.Post("/renew"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Body("token")),v(3,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,Application]),y("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),g([t.Get(),_(),v(0,t.Ctx()),v(1,U()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.UserModel]),y("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=g([t.Controller("/auth"),t.Extends(exports.BaseController),v(0,a.Inject(exports.AuthService)),y("design:paramtypes",[exports.AuthService])],exports.AuthController),exports.CrudController=class CrudController extends exports.ModelController{constructor(){super(...arguments),this._crud={}}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}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return x(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return x(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}del(e){return x(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return x(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return x(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return x(this,void 0,void 0,function*(){if(this.CrudValidationCreate()==this._crud)return e.error(new t.InternalServerError)})}validationUpdate(e){return x(this,void 0,void 0,function*(){if(this.CrudValidationUpdate()==this._crud)return e.error(new t.InternalServerError)})}},g([t.Post(),_(),C(),t.Middleware("validationCreate"),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"add",null),g([t.Get(),_(),A(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"all",null),g([t.Delete("/:id"),_(),E(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"del",null),g([t.Get("/:id"),_(),A(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"get",null),g([t.Put("/:id"),_(),M(),t.Middleware("validationUpdate"),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"set",null),g([v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"validationCreate",null),g([v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"validationUpdate",null),exports.CrudController=g([t.Extends(exports.ModelController)],exports.CrudController),exports.FilesController=class FilesController extends exports.BaseController{constructor(){super(...arguments),this.directory=Env.API_HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return x(this,void 0,void 0,function*(){let{path:r}=e.req;r=r.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=c.join(this.directory,r);if(!u.existsSync(i)||!u.statSync(i).isDirectory())return e.error(new t.NotFoundError);let s=[];return s=u.readdirSync(i),s=s.map(e=>this.info(c.join(i,e))),s=s.filter(o.isDef),Object.assign(Object.assign({},this.info(i)),{files:s})})}info(e){if(!u.existsSync(e))return null;const t=u.statSync(e),r=e.split("/").pop();e=e.replace(this.directory,"/").replace(/^\/\//,"/");const o=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:o?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:o,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return x(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=o.upperCamelCase(e.replace(/_/g," ")," "),r={description:"",state:!0};yield o.forEachSeries(this.permissions,i=>x(this,void 0,void 0,function*(){const s=`${e}.${i}`;yield exports.PermissionModel.findOrCreate({where:{key:s},defaults:Object.assign({name:`${t} ${o.upperCamelCase(i," ")}`,key:s,tag:t},r)})}))})}},g([t.Get("/path"),t.Get("/path/*path"),_(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.FilesController.prototype,"files",null),exports.FilesController=g([t.Controller("/files"),t.Extends(exports.BaseController)],exports.FilesController),exports.ForgotController=class ForgotController extends exports.BaseController{check(e,r){return x(this,void 0,void 0,function*(){const i=yield this.find(r);if(!i||!i.user)return e.error(new t.NotFoundError);i.secret=o.uniqueID(),yield i.save(),e.json({token:i.secret})})}forgot(e,r,i){return x(this,void 0,void 0,function*(){yield o.sleep(Env.API_SLEEP_FORGOT);const n=r,d=yield exports.UserModel.findOne({where:{[s.Op.or]:[{email:n},{username:r}]}}).catch(this.error);if(!d)return e.error(new t.NotFoundError);const l=o.uniqueID(),a=Date.now()+6e4*Env.API_TOKEN_FORGOT,p=yield exports.ForgotModel.create({token:l,timestamp:a,state:!0,user_id:d.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:p,user:d}),this.emit("forgot.send",{ctx:e,forgot:p,user:d})})}reset(e,r,o,i){return x(this,void 0,void 0,function*(){const o=yield this.find(r);if(!o)return e.error(new t.NotFoundError);o.state=!1,yield o.save().catch(this.error),yield o.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:o.user}),this.emit("forgot.reset",{ctx:e,user:o.user})})}find(e){return x(this,void 0,void 0,function*(){return yield exports.ForgotModel.findOne({where:{token:e,state:!0},include:[{model:exports.UserModel,required:!0}]}).catch(this.error)})}},g([t.Get("/check"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Body("token")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),g([t.Post(),t.Validate(e=>({username:e.string().min(4).required()})),v(0,t.Ctx()),v(1,t.Body("username")),v(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Application]),y("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),g([t.Post("/reset"),t.Validate(e=>({token:e.string().required(),password:e.string().min(5).required()})),v(0,t.Ctx()),v(1,t.Body("token")),v(2,t.Body("password")),v(3,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,Application]),y("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=g([t.Controller("/forgot"),t.Extends(exports.BaseController)],exports.ForgotController),exports.GroupsController=class GroupsController extends exports.CrudController{constructor(){super(...arguments),this.model=exports.GroupModel,this.schemaCreate={name:o.Validation.string().required(),description:o.Validation.string().empty(""),state:o.Validation.boolean().parse().required()},this.schemaUpdate={name:o.Validation.string().empty(),description:o.Validation.string().empty(),state:o.Validation.boolean().parse().empty()}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.GroupsController=g([t.Controller("/groups"),t.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsPermissionsController=class GroupsPermissionsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.GroupPermissionModel}all(e,t){return x(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:exports.PermissionModel,required:!0}]},callback:e=>e.map(e=>e.permission)})})}me(e,t){return x(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,r,i){return x(this,void 0,void 0,function*(){const n=yield exports.GroupModel.findByPk(r,{attributes:["id"]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);const d=n.id,l=[];yield o.forEachSeries(i,t=>x(this,void 0,void 0,function*(){var r;if(!(yield exports.PermissionModel.count({where:{id:t}})))return;const[o]=null!==(r=yield exports.GroupPermissionModel.findOrCreate(Object.assign({where:{group_id:d,permission_id:t},defaults:{group_id:d,permission_id:t}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];o&&l.push(t)})),yield exports.GroupPermissionModel.destroy(Object.assign({where:{group_id:d,permission_id:{[s.Op.notIn]:l}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}},g([t.Get("/:id/permissions"),_(),A("groups"),v(0,t.Ctx()),v(1,t.Params("id")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"all",null),g([t.Get("/permissions"),_(),A("users"),v(0,t.Ctx()),v(1,U()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.UserModel]),y("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"me",null),g([t.Put("/:id/permissions"),_(),M("groups"),t.Validate(e=>({permissions:e.array(e.string())})),v(0,t.Ctx()),v(1,t.Params("id")),v(2,t.Body("permissions")),y("design:type",Function),y("design:paramtypes",[t.Context,String,Array]),y("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"set",null),exports.GroupsPermissionsController=g([t.Controller("/groups"),t.Extends(exports.ModelController)],exports.GroupsPermissionsController),exports.LogsController=class LogsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.LogModel,this.permissions=["read"]}all(e){return x(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{order:[["created_at","DESC"]]},limited:!0})})}},g([t.Get(),_(),A(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=g([t.Controller("/logs"),t.Extends(exports.ModelController)],exports.LogsController),exports.PermissionsController=class PermissionsController extends exports.CrudController{constructor(){super(...arguments),this.model=exports.PermissionModel,this.schemaCreate={name:o.Validation.string().required(),key:o.Validation.string().required(),tag:o.Validation.string().required(),description:o.Validation.string().empty(""),state:o.Validation.boolean().parse().required()},this.schemaUpdate={name:o.Validation.string().empty(),key:o.Validation.string().empty(),tag:o.Validation.string().empty(),description:o.Validation.string().empty(),state:o.Validation.boolean().parse().empty()}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.PermissionsController=g([t.Controller("/permissions"),t.Extends(exports.CrudController)],exports.PermissionsController),exports.RegisterController=class RegisterController extends exports.BaseController{register(e,i,n){return x(this,void 0,void 0,function*(){yield o.sleep(Env.API_SLEEP_REGISTRY);const{name:d,date:l,email:a,username:p,password:u,confirm:c}=i,g=p||a,v=r.sha256(u);if(yield exports.UserModel.count({where:{[s.Op.or]:[{email:a},{username:g}]}}).catch(this.error))return e.error("INVALID EMAIL OR USERNAME");if(v!=r.sha256(c))return e.error("INVALID PASSWORD");const y=yield exports.UserModel.create({name:d,email:a,username:g,password:v,avatar:"",date:l,description:"",state:!1}).catch(this.error);if(!y)return e.error(new t.InternalServerError);const x=yield exports.RegisterModel.create({token:yield this.getId(),user_id:y.id,state:!0}).catch(this.error);if(!x)return yield y.destroy().catch(this.error),e.error(new t.InternalServerError);e.success("OK"),n.emit("register.user",{ctx:e,register:x,user:y}),this.emit("register.user",{ctx:e,register:x,user:y})})}confirm(e,r,o){return x(this,void 0,void 0,function*(){const i=yield exports.RegisterModel.findOne({where:{token:r,state:!0},include:[{model:exports.UserModel,required:!0}]}).catch(this.error);if(!i)return e.error(new t.NotFoundError);i.state=!1,yield i.save().catch(this.error),i.user.state=!0,yield i.user.save().catch(this.error),e.success("OK"),o.emit("register.confirm",{ctx:e,register:i,user:i.user}),this.emit("register.confirm",{ctx:e,register:i,user:i.user})})}send(e,r,o){return x(this,void 0,void 0,function*(){const i=r,n=yield exports.RegisterModel.findOne({where:{state:!0},include:[{model:exports.UserModel,required:!0,where:{[s.Op.or]:[{email:i},{username:r}]}}]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);e.success("OK"),o.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})})}getId(){return x(this,void 0,void 0,function*(){const e=o.uuidv7();return(yield exports.RegisterModel.count({where:{token:e}}))?this.getId():e})}},g([t.Post(),t.Validate(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()})),v(0,t.Ctx()),v(1,t.Body()),v(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,Object,Application]),y("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),g([t.Post("/confirm"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Body("token")),v(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Application]),y("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),g([t.Post("/send"),t.Validate(e=>({username:e.string().min(4).required()})),v(0,t.Ctx()),v(1,t.Body("username")),v(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Application]),y("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=g([t.Controller("/register"),t.Extends(exports.BaseController)],exports.RegisterController),exports.SetupController=class SetupController extends exports.BaseController{setup(e){return x(this,void 0,void 0,function*(){var t;if(yield exports.UserModel.count())return e.success("OK");const i=o.uniqueID(),s=yield exports.UserModel.create({name:"Admin",email:"admin@localhost",username:"admin",password:r.sha256("admin"+i),salt:i,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},{ctx:e}));yield exports.UserPasswordModel.create({value:"admin",state:!0,user_id:s.id});const n=yield exports.GroupModel.create(Object.assign({name:"Admin"},{description:"API CORE",state:!0}),Object.assign({},{ctx:e}));yield exports.UserGroupModel.create({user_id:s.id,group_id:n.id},Object.assign({},{ctx:e}));const d=null!==(t=yield exports.PermissionModel.findAll({where:{state:!0}}).catch(this.error))&&void 0!==t?t:[];yield o.forEachSeries(d,t=>x(this,void 0,void 0,function*(){yield exports.GroupPermissionModel.create({group_id:n.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}},g([t.Get(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=g([t.Controller("/setup"),t.Extends(exports.BaseController)],exports.SetupController),exports.UsersController=class UsersController extends exports.ModelController{constructor(){super(),this.model=exports.UserModel,this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&u.existsSync(Env.API_HTTP_PUBLIC)&&!u.existsSync(this.path)&&u.mkdirSync(this.path)}avatar(e,r){return x(this,void 0,void 0,function*(){var o,i;const s=e.getFiles();if(s.file&&s.file.length){const{filename:n,path:d}=null!==(o=s.file[0])&&void 0!==o?o:{};if(n){const[o]=null!==(i=yield exports.UserProfileModel.findOrCreate(Object.assign({where:{key:"avatar",user_id:r.id},defaults:{key:"avatar",user_id:r.id}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];if(!o)return u.lstatSync(d).isFile()&&u.rmSync(d),e.error(new t.InternalServerError);const s=this.path+"/"+o.value;if(u.existsSync(s)&&u.lstatSync(s).isFile()&&u.rmSync(s),o.value=n,yield o.save(Object.assign({},{ctx:e})).catch(this.error))return e.success("OK")}}e.success("Record not Changed")})}token_new(){return x(this,void 0,void 0,function*(){var e;const t=o.uuidv7();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 x(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return x(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}del(e,r,o){return x(this,void 0,void 0,function*(){if(o.id.toString()==r)return e.error(new t.NotFoundError);yield this.delete({ctx:e})})}get(e){return x(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return x(this,void 0,void 0,function*(){yield this.update({ctx:e})})}},g([t.Post("/avatar"),_(),t.Upload({file:{count:1,path:`${Env.API_HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),v(0,t.Ctx()),v(1,U()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.UserModel]),y("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),g([t.Post(),_(),C(),t.Validate(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)})),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"add",null),g([t.Get(),_(),A(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"all",null),g([t.Delete("/:id"),_(),E(),v(0,t.Ctx()),v(1,t.Params("id")),v(2,U()),y("design:type",Function),y("design:paramtypes",[t.Context,String,exports.UserModel]),y("design:returntype",Promise)],exports.UsersController.prototype,"del",null),g([t.Get("/:id"),_(),A(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"get",null),g([t.Put("/:id"),_(),M(),t.Validate(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()})),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=g([t.Controller("/users"),t.Extends(exports.ModelController),y("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class UsersGroupsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.UserGroupModel}all(e,t){return x(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:exports.GroupModel,required:!0}]},callback:e=>e.map(e=>e.group)})})}me(e,t){return x(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,r,i){return x(this,void 0,void 0,function*(){const n=yield exports.UserModel.findByPk(r,{attributes:["id"]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);const d=n.id,l=[];yield o.forEachSeries(i,t=>x(this,void 0,void 0,function*(){var r;if(!(yield exports.GroupModel.count({where:{id:t}})))return;const[o]=null!==(r=yield exports.UserGroupModel.findOrCreate(Object.assign({where:{user_id:d,group_id:t},defaults:{user_id:d,group_id:t}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];o&&l.push(t)})),yield exports.UserGroupModel.destroy(Object.assign({where:{user_id:d,group_id:{[s.Op.notIn]:l}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}},g([t.Get("/:id/groups"),_(),A("users"),v(0,t.Ctx()),v(1,t.Params("id")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),g([t.Get("/groups"),_(),A("users"),v(0,t.Ctx()),v(1,U()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.UserModel]),y("design:returntype",Promise)],exports.UsersGroupsController.prototype,"me",null),g([t.Put("/:id/groups"),_(),M("users"),t.Validate(e=>({groups:e.array(e.string())})),v(0,t.Ctx()),v(1,t.Params("id")),v(2,t.Body("groups")),y("design:type",Function),y("design:paramtypes",[t.Context,String,Array]),y("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=g([t.Controller("/users"),t.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=Application,exports.Audit=b,exports.CanCreate=C,exports.CanDelete=E,exports.CanRead=A,exports.CanUpdate=M,exports.Config=class Config extends Loggable{static all(){return x(this,void 0,void 0,function*(){const e=yield exports.ConfigModel.findAll().catch(this.error),t={};return e&&e.forEach(e=>t[e.key]=e.value),t})}static del(e,t){return x(this,void 0,void 0,function*(){var r;const o=null!==(r=null==t?void 0:t.id)&&void 0!==r?r:null;return((yield exports.ConfigModel.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:o})).catch(this.error))||0)>0})}static get(e){return x(this,arguments,void 0,function*(e,t=""){const[r]=(yield exports.ConfigModel.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return r?r.value:t})}static set(e,t,r){return x(this,void 0,void 0,function*(){var o;const i=null!==(o=null==r?void 0:r.id)&&void 0!==o?o:null,[s]=(yield exports.ConfigModel.findOrCreate(Object.assign({where:{key:e}},{user_id:i})).catch(this.error))||[];s&&(s.value=t,yield s.save().catch(this.error))})}},exports.Env=Env,exports.HasGroups=(...e)=>(r,i,s)=>{t.Use(r=>x(void 0,void 0,void 0,function*(){const{groups:i}=r.req;if(o.includesArray(e,null!=i?i:[]))return r.next();r.error(new t.UnauthorizedError("Access Denied"))}))(r,i,s)},exports.HasPermissions=(...e)=>(r,i,s)=>{t.Use(r=>x(void 0,void 0,void 0,function*(){const{permissions:i}=r.req;if(o.includesArray(e,null!=i?i:[]))return r.next();r.error(new t.UnauthorizedError("Access Denied"))}))(r,i,s)},exports.IsAuthenticated=_,exports.Log=Log,exports.Loggable=Loggable,exports.ModelService=ModelService,exports.ReqAuth=f,exports.ReqGroup=S,exports.ReqGroups=P,exports.ReqPermission=O,exports.ReqPermissions=I,exports.ReqUser=U,exports.SessionStore=SessionStore,exports.canFactory=m,exports.sequelize=h;
|
|
7
|
+
"use strict";var e,t=require("@andrewcaires/express"),r=require("@andrewcaires/node"),o=require("@andrewcaires/utils.js"),s=require("ws"),i=require("@andrewcaires/sequelize"),n=require("dotenv"),d=require("bcrypt"),l=require("express-session"),a=require("jsonwebtoken"),p=require("@andrewcaires/decorator"),u=require("fs"),c=require("path");function g(e,t,r,o){var s,i=arguments.length,n=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,o);else for(var d=e.length-1;d>=0;d--)(s=e[d])&&(n=(i<3?s(n):i>3?s(t,r,n):s(t,r))||n);return i>3&&n&&Object.defineProperty(t,r,n),n}function v(e,t){return function(r,o){t(r,o,e)}}function y(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function h(e,t,r,o){return new(r||(r=Promise))(function(s,i){function n(e){try{l(o.next(e))}catch(e){i(e)}}function d(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(n,d)}l((o=o.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError,n.config({quiet:!0});class Env extends r.Env{}e=Env,Env.BASE_NAME=e.getString("BASE_NAME",""),Env.CONSOLE_ERROR=e.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=e.getString("DATABASE_URI","",!0),Env.DATABASE_LOG=e.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=e.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=e.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=e.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CRT=e.getFile("HTTP_CRT"),Env.HTTP_KEY=e.getFile("HTTP_KEY"),Env.SLEEP_AUTH=e.getMs("SLEEP_AUTH","2s"),Env.SLEEP_FORGOT=e.getMs("SLEEP_FORGOT","5s"),Env.SLEEP_REGISTRY=e.getMs("SLEEP_REGISTRY","5s"),Env.TOKEN_CRT=e.getFile("TOKEN_CRT"),Env.TOKEN_KEY=e.getFile("TOKEN_KEY"),Env.TOKEN_TTL=e.getMs("TOKEN_TTL","1d"),Env.API_BODYPARSER_STRICT=e.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=e.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=e.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=e.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_PORT=e.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=e.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_CROSS=e.getBool("API_HTTP_CROSS",!1),Env.API_HTTP_HYBRID=e.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=e.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=e.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=e.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=e.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=e.getString("API_KEY_HEADER","x-api-key"),Env.API_MODEL_LIMIT=e.getInt("API_MODEL_LIMIT",10),Env.API_MODEL_LIMIT_MAX=e.getInt("API_MODEL_LIMIT_MAX",500),Env.API_SESSION_NAME=e.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=e.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=e.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=e.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=e.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_TOKEN_FORGOT=e.getMs("API_TOKEN_FORGOT","1d"),Env.API_TOKEN_HEADER=e.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_HEADER_KEY=e.getString("API_TOKEN_HEADER","bearer"),Env.API_TOKEN_RENEW=e.getMs("API_TOKEN_RENEW","1d"),Env.API_USER_HISTORY=e.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=e.getBool("API_WEBSOCKET_START",!1);const x=new i.Sequelize({uri:Env.DATABASE_URI,logging:!!Env.DATABASE_LOG&&(e=>r.Log.console(r.LogColor.Magenta,"sql",e)),prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE}),m=e=>r=>(s,i,n)=>{t.Use(s=>h(void 0,void 0,void 0,function*(){var i;let n=null!=r?r:"";o.isUndefined(r)&&(n=o.isFunction(s.controller.name)?s.controller.name():null===(i=s.controller.constructor)||void 0===i?void 0:i.name);const{permissions:d}=s.req;if((null!=d?d:[]).includes(`${n}.${e}`))return s.next();s.error(new t.UnauthorizedError("Access Denied"))}))(s,i,n)},C=m("create"),E=m("delete"),f=m("read"),A=m("update"),M=()=>(e,r,o)=>{t.Use(e=>h(void 0,void 0,void 0,function*(){yield(e=>h(void 0,void 0,void 0,function*(){var r,o,s,i;if(e.req.auth&&e.req.user)return e.next();const{[Env.API_KEY_HEADER]:n,[Env.API_TOKEN_HEADER]:d,"user-agent":l}=e.getHeaders(),a=e.getQuery(Env.API_KEY_HEADER),p=(null===(r=n||a)||void 0===r?void 0:r.toString())||"";let u=e.getCookie(Env.API_TOKEN_COOKIE);u=`${Env.API_TOKEN_HEADER_KEY} ${u}`;const[c,g]=null!==(s=null===(o=d||u)||void 0===o?void 0:o.split(" "))&&void 0!==s?s:["",""];if(!(p||g&&c.toLowerCase()==Env.API_TOKEN_HEADER_KEY))return e.error(new t.UnauthorizedError("Invalid token"));const{authService:v,userService:y}=e.app,{auth:h,user:x}=null!==(i=yield(p?v.key(p.toString()):v.user(g)).catch(t=>{e.error(t)}))&&void 0!==i?i:{};if(h&&x){if(!p&&h.user_agent&&h.user_agent!=l)return e.error(new t.UnauthorizedError("Invalid token"));e.req.auth=h,e.req.user=x,e.req.groups=yield y.getGroups(x.id),e.req.permissions=yield y.getPermissions(x.id),e.req.profile=yield y.getProfile(x.id),e.next()}}))(e)}))(e,r,o)},_=t.parameterFactory(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),S=t.parameterFactory(({ctx:e,key:t})=>{var r,o;return(null!==(o=null===(r=e.req)||void 0===r?void 0:r.groups)&&void 0!==o?o:[]).includes(t)}),P=t.parameterFactory(({ctx:e})=>{var t,r;return null!==(r=null===(t=e.req)||void 0===t?void 0:t.groups)&&void 0!==r?r:[]}),O=t.parameterFactory(({ctx:e,key:t})=>{var r,o;return(null!==(o=null===(r=e.req)||void 0===r?void 0:r.permissions)&&void 0!==o?o:[]).includes(t)}),U=t.parameterFactory(({ctx:e})=>{var t,r;return null!==(r=null===(t=e.req)||void 0===t?void 0:t.permissions)&&void 0!==r?r:[]}),T=t.parameterFactory(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.user}),I=(e,r,o)=>{var s,i,n,d,l,a,p,u,c,g;const v=o.ctx instanceof t.Context?o.ctx:null,y=null!==(d=null!==(n=null===(i=null===(s=null==v?void 0:v.req)||void 0===s?void 0:s.user)||void 0===i?void 0:i.id)&&void 0!==n?n:o.user_id)&&void 0!==d?d:null,h={type:e,model:null!==(l=null==r?void 0:r.getTableName())&&void 0!==l?l:null,app_name:null!==(a=Env.BASE_NAME)&&void 0!==a?a:"",state:!0,user_id:y};return v?Object.assign(Object.assign({},h),{full_url:null!==(p=null==v?void 0:v.getUrl())&&void 0!==p?p:"",ip_address:null!==(u=null==v?void 0:v.getIp())&&void 0!==u?u:"",user_agent:null!==(g=null===(c=null==v?void 0:v.req)||void 0===c?void 0:c.headers["user-agent"])&&void 0!==g?g:""}):h},b={afterCreate:(e,t)=>h(void 0,void 0,void 0,function*(){const s=o.getConstructor(e),{primaryKeyAttribute:i}=null!=s?s:{};yield exports.AuditModel.create(Object.assign(Object.assign({},I("CREATE",s,t)),{record:i?e.getDataValue(i):null,data:e.toJSON()})).catch(r.Log.catch)}),afterUpdate:(e,t)=>h(void 0,void 0,void 0,function*(){const s=o.getConstructor(e),{primaryKeyAttribute:i}=null!=s?s:{},n={},d=e.changed();d&&d.forEach(t=>n[t]=e.getDataValue(t)),yield exports.AuditModel.create(Object.assign(Object.assign({},I("UPDATE",s,t)),{record:i?e.getDataValue(i):null,data:n,previously:e.previous()})).catch(r.Log.catch)}),afterDestroy:(e,t)=>h(void 0,void 0,void 0,function*(){const s=o.getConstructor(e),{primaryKeyAttribute:i}=null!=s?s:{};yield exports.AuditModel.create(Object.assign(Object.assign({},I("DELETE",s,t)),{record:i?e.getDataValue(i):null,data:e.toJSON()})).catch(r.Log.catch)})},w=e=>(o.isUndefined(e)&&(e=Env.DATABASE_AUDIT),i.Hooks(e?b:{}));exports.RegisterModel=class RegisterModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.RegisterModel.prototype,"id",void 0),g([i.Column.String(),y("design:type",String)],exports.RegisterModel.prototype,"secret",void 0),g([i.Column.FullDate(),y("design:type",Number)],exports.RegisterModel.prototype,"expired_at",void 0),g([i.Column.Boolean(),y("design:type",Boolean)],exports.RegisterModel.prototype,"state",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.RegisterModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.RegisterModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),y("design:type",Object)],exports.RegisterModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.RegisterModel.prototype,"user_id",void 0),exports.RegisterModel=g([i.Database(x),i.ModelName("register"),i.Version("5.0.0")],exports.RegisterModel),exports.UserAuthModel=class UserAuthModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.UserAuthModel.prototype,"id",void 0),g([i.Column.String(),y("design:type",String)],exports.UserAuthModel.prototype,"secret",void 0),g([i.Column.String(),y("design:type",String)],exports.UserAuthModel.prototype,"ip_address",void 0),g([i.Column.String(),y("design:type",String)],exports.UserAuthModel.prototype,"user_agent",void 0),g([i.Column.FullDate(),y("design:type",Object)],exports.UserAuthModel.prototype,"revoked_at",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.UserAuthModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.UserAuthModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),y("design:type",Object)],exports.UserAuthModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.UserAuthModel.prototype,"user_id",void 0),exports.UserAuthModel=g([i.Database(x),i.ModelName("users_auth"),i.Version("5.0.0")],exports.UserAuthModel),exports.PermissionModel=class PermissionModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.PermissionModel.prototype,"id",void 0),g([i.Column.String(),y("design:type",String)],exports.PermissionModel.prototype,"name",void 0),g([i.Column.String(),i.Unique(!0),y("design:type",String)],exports.PermissionModel.prototype,"key",void 0),g([i.Column.String(),y("design:type",String)],exports.PermissionModel.prototype,"tags",void 0),g([i.Column.Text(),y("design:type",String)],exports.PermissionModel.prototype,"description",void 0),g([i.Column.Boolean(),y("design:type",Boolean)],exports.PermissionModel.prototype,"state",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.PermissionModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.PermissionModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),y("design:type",Object)],exports.PermissionModel.prototype,"deleted_at",void 0),g([i.HasMany(()=>exports.GroupPermissionModel,"permission_id"),y("design:type",Array)],exports.PermissionModel.prototype,"groups_permissions",void 0),exports.PermissionModel=g([i.Database(x),i.ModelName("permission"),w(),i.Version("5.0.1")],exports.PermissionModel),exports.GroupPermissionModel=class GroupPermissionModel extends i.Model{},g([i.Column.CreatedAt(),y("design:type",Date)],exports.GroupPermissionModel.prototype,"created_at",void 0),g([i.Association.BelongsTo(()=>exports.GroupModel),y("design:type",String)],exports.GroupPermissionModel.prototype,"group_id",void 0),g([i.Association.BelongsTo(()=>exports.PermissionModel),y("design:type",String)],exports.GroupPermissionModel.prototype,"permission_id",void 0),exports.GroupPermissionModel=g([i.Database(x),i.ModelName("groups_permissions"),w(),i.Version("5.0.0")],exports.GroupPermissionModel),exports.GroupModel=class GroupModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.GroupModel.prototype,"id",void 0),g([i.Column.String(),y("design:type",String)],exports.GroupModel.prototype,"name",void 0),g([i.Column.String(),y("design:type",String)],exports.GroupModel.prototype,"key",void 0),g([i.Column.String(),y("design:type",String)],exports.GroupModel.prototype,"tags",void 0),g([i.Column.Text(),y("design:type",String)],exports.GroupModel.prototype,"description",void 0),g([i.Column.Boolean(),y("design:type",Boolean)],exports.GroupModel.prototype,"state",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.GroupModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.GroupModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),y("design:type",Object)],exports.GroupModel.prototype,"deleted_at",void 0),g([i.Association.HasMany(()=>exports.UserGroupModel,"group_id"),y("design:type",Array)],exports.GroupModel.prototype,"users_groups",void 0),g([i.Association.HasMany(()=>exports.GroupPermissionModel,"group_id"),y("design:type",Array)],exports.GroupModel.prototype,"groups_Permission",void 0),exports.GroupModel=g([i.Database(x),i.ModelName("group"),w(),i.Version("5.0.1")],exports.GroupModel),exports.UserGroupModel=class UserGroupModel extends i.Model{},g([i.Column.CreatedAt(),y("design:type",Date)],exports.UserGroupModel.prototype,"created_at",void 0),g([i.Association.BelongsTo(()=>exports.GroupModel),y("design:type",String)],exports.UserGroupModel.prototype,"group_id",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.UserGroupModel.prototype,"user_id",void 0),exports.UserGroupModel=g([i.Database(x),i.ModelName("users_groups"),w(),i.Version("5.0.0")],exports.UserGroupModel),exports.UserPasswordModel=class UserPasswordModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.UserPasswordModel.prototype,"id",void 0),g([i.Column.String(),i.Value(e=>d.hashSync(e.value,12)),y("design:type",String)],exports.UserPasswordModel.prototype,"value",void 0),g([i.Column.Boolean(),y("design:type",Boolean)],exports.UserPasswordModel.prototype,"state",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.UserPasswordModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.UserPasswordModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),y("design:type",Object)],exports.UserPasswordModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.UserPasswordModel.prototype,"user_id",void 0),exports.UserPasswordModel=g([i.Database(x),i.ModelName("users_password"),w(),i.Version("5.0.0")],exports.UserPasswordModel),exports.UserProfileModel=class UserProfileModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.UserProfileModel.prototype,"id",void 0),g([i.Column.Json(),i.DefaultValue({}),y("design:type",Object)],exports.UserProfileModel.prototype,"data",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.UserProfileModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.UserProfileModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),y("design:type",Object)],exports.UserProfileModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.UserProfileModel.prototype,"user_id",void 0),exports.UserProfileModel=g([i.Database(x),i.ModelName("users_profile"),w(),i.Version("5.0.1")],exports.UserProfileModel),exports.UserModel=class UserModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.UserModel.prototype,"id",void 0),g([i.Column.String(),y("design:type",String)],exports.UserModel.prototype,"name",void 0),g([i.Column.String(),y("design:type",String)],exports.UserModel.prototype,"email",void 0),g([i.Column.String(),y("design:type",String)],exports.UserModel.prototype,"username",void 0),g([i.Column.Text(),y("design:type",String)],exports.UserModel.prototype,"description",void 0),g([i.Column.Boolean(),y("design:type",Boolean)],exports.UserModel.prototype,"state",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.UserModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.UserModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),y("design:type",Object)],exports.UserModel.prototype,"deleted_at",void 0),g([i.Association.HasMany(()=>exports.AuditModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"audits",void 0),g([i.Association.HasMany(()=>exports.UserAuthModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"users_auths",void 0),g([i.Association.HasMany(()=>exports.RegisterModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"registers",void 0),g([i.Association.HasMany(()=>exports.UserGroupModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"users_groups",void 0),g([i.Association.HasMany(()=>exports.UserPasswordModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"users_passwords",void 0),g([i.Association.HasMany(()=>exports.UserProfileModel,"user_id"),y("design:type",Array)],exports.UserModel.prototype,"users_profiles",void 0),exports.UserModel=g([i.Database(x),i.ModelName("user"),w(),i.Version("5.0.0")],exports.UserModel),exports.AuditModel=class AuditModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.AuditModel.prototype,"id",void 0),g([i.Column.Enum("CREATE","DELETE","UPDATE"),y("design:type",String)],exports.AuditModel.prototype,"type",void 0),g([i.Column.String(),y("design:type",String)],exports.AuditModel.prototype,"model",void 0),g([i.Column.String(),y("design:type",String)],exports.AuditModel.prototype,"record",void 0),g([i.Column.Json(),y("design:type",Object)],exports.AuditModel.prototype,"data",void 0),g([i.Column.Json(),y("design:type",Object)],exports.AuditModel.prototype,"previously",void 0),g([i.Column.Text(),y("design:type",String)],exports.AuditModel.prototype,"full_url",void 0),g([i.Column.String(),y("design:type",String)],exports.AuditModel.prototype,"ip_address",void 0),g([i.Column.String(),y("design:type",String)],exports.AuditModel.prototype,"user_agent",void 0),g([i.Column.String(),y("design:type",String)],exports.AuditModel.prototype,"app_name",void 0),g([i.Column.Boolean(),y("design:type",Boolean)],exports.AuditModel.prototype,"state",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.AuditModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.AuditModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),y("design:type",Object)],exports.AuditModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.AuditModel.prototype,"user_id",void 0),exports.AuditModel=g([i.Database(x),i.ModelName("audit"),i.Version("5.0.1")],exports.AuditModel),exports.ConfigModel=class ConfigModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.ConfigModel.prototype,"id",void 0),g([i.Column.String(),y("design:type",String)],exports.ConfigModel.prototype,"key",void 0),g([i.Column.String(),y("design:type",String)],exports.ConfigModel.prototype,"value",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.ConfigModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.ConfigModel.prototype,"updated_at",void 0),exports.ConfigModel=g([i.Database(x),i.ModelName("configs"),i.Version("5.0.0")],exports.ConfigModel),exports.ForgotModel=class ForgotModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.ForgotModel.prototype,"id",void 0),g([i.Column.String(),y("design:type",String)],exports.ForgotModel.prototype,"secret",void 0),g([i.Column.FullDate(),y("design:type",Number)],exports.ForgotModel.prototype,"expired_at",void 0),g([i.Column.Boolean(),y("design:type",Boolean)],exports.ForgotModel.prototype,"state",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.ForgotModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.ForgotModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),y("design:type",Object)],exports.ForgotModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.ForgotModel.prototype,"user_id",void 0),exports.ForgotModel=g([i.Database(x),i.ModelName("forgot"),i.Version("5.0.0")],exports.ForgotModel),exports.LogModel=class LogModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.LogModel.prototype,"id",void 0),g([i.Column.Enum("info","warn","error"),i.DefaultValue("info"),y("design:type",String)],exports.LogModel.prototype,"level",void 0),g([i.Column.Text(),y("design:type",String)],exports.LogModel.prototype,"message",void 0),g([i.Column.String(),y("design:type",String)],exports.LogModel.prototype,"source",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.LogModel.prototype,"created_at",void 0),exports.LogModel=g([i.Database(x),i.ModelName("log"),i.Version("5.0.0")],exports.LogModel),exports.MigrationModel=class MigrationModel extends i.Model{},g([i.Column.String(),y("design:type",String)],exports.MigrationModel.prototype,"model",void 0),g([i.Column.String(),y("design:type",String)],exports.MigrationModel.prototype,"version",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.MigrationModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.MigrationModel.prototype,"updated_at",void 0),exports.MigrationModel=g([i.Database(x),i.ModelName("migration"),i.Version("5.0.0")],exports.MigrationModel),exports.SessionModel=class SessionModel extends i.Model{},g([i.Column.String(),y("design:type",String)],exports.SessionModel.prototype,"session",void 0),g([i.Column.Text(),y("design:type",String)],exports.SessionModel.prototype,"json",void 0),g([i.Column.BigInt(),y("design:type",Number)],exports.SessionModel.prototype,"expired",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.SessionModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.SessionModel.prototype,"updated_at",void 0),exports.SessionModel=g([i.Database(x),i.ModelName("session"),i.Version("5.0.0")],exports.SessionModel),exports.UserMetadataModel=class UserMetadataModel extends i.Model{},g([i.Column.UUID(7),y("design:type",String)],exports.UserMetadataModel.prototype,"id",void 0),g([i.Column.Json(),i.DefaultValue({}),y("design:type",Object)],exports.UserMetadataModel.prototype,"data",void 0),g([i.Column.CreatedAt(),y("design:type",Date)],exports.UserMetadataModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),y("design:type",Date)],exports.UserMetadataModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),y("design:type",Object)],exports.UserMetadataModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),y("design:type",String)],exports.UserMetadataModel.prototype,"user_id",void 0),exports.UserMetadataModel=g([i.Database(x),i.ModelName("users_metadata"),w(),i.Version("5.0.1")],exports.UserMetadataModel);class Log{static error(e,t,r){return h(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,r)})}static info(e,t,r){return h(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,r)})}static warn(e,t,r){return h(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,r)})}static writeRaw(e,t,o,s){return h(this,void 0,void 0,function*(){var i;s&&r.Log.console(null!==(i=this.colors[e])&&void 0!==i?i:r.LogColor.White,e,t),x&&(yield exports.LogModel.create({level:e,message:t,source:null!=o?o:""}).catch(r.Log.catch))})}}Log.colors={error:r.LogColor.Red,info:r.LogColor.Cyan,warn:r.LogColor.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 r,o;Log.error(null!==(o=null!==(r=null==t?void 0:t.message)&&void 0!==r?r:t)&&void 0!==o?o:"",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,r,o;const s=null!==(o=null!==(r=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)&&void 0!==r?r:null==e?void 0:e.name)&&void 0!==o?o:"null";return Env.BASE_NAME?`${Env.BASE_NAME}.${s}`:s}}class SessionStore extends l.Store{constructor(){super(),this.all=e=>h(this,void 0,void 0,function*(){e=e||o.noop;const t=yield exports.SessionModel.findAll({attributes:["session"],where:{expired:{[i.Op.gte]:Date.now()}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.session)),e()}),this.clear=e=>h(this,void 0,void 0,function*(){yield exports.SessionModel.destroy().catch(o.noop),e&&e()}),this.destroy=(e,t)=>h(this,void 0,void 0,function*(){yield exports.SessionModel.destroy({where:{session:e}}).catch(o.noop),t&&t()}),this.expired=()=>h(this,void 0,void 0,function*(){yield exports.SessionModel.destroy({where:{expired:{[i.Op.lt]:Date.now()}}}).catch(o.noop)}),this.get=(e,t)=>h(this,void 0,void 0,function*(){t=t||o.noop;const r=yield exports.SessionModel.findOne({where:{session:e,expired:{[i.Op.gte]:Date.now()}}}).catch(e=>(t(e),null));if(r){const e=JSON.parse(r.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield r.destroy().catch(o.noop),void t(null)}return void t(null,e)}t(null)}),this.length=e=>h(this,void 0,void 0,function*(){e&&e(null,(yield exports.SessionModel.count().catch(o.noop))||0)}),this.set=(e,t,r)=>h(this,void 0,void 0,function*(){r=r||o.noop;const s=Date.now()+Env.API_SESSION_LIFETIME,i=JSON.stringify(t),[n,d]=(yield exports.SessionModel.findOrCreate({where:{session:e},defaults:{session:e,json:i,expired:s}}).catch(o.noop))||[];n&&(d||(n.json=i,n.expired=s,yield n.save().catch(o.noop))),r()}),this.loop=o.loop(this.expired,3e4),this.loop.start()}}exports.Service=class Service{},exports.Service=g([p.Trait(Loggable)],exports.Service);class AuthService extends exports.Service{create(e){return h(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new t.NotFoundError("TOKEN_KEY not found");const{id:r}=e,s=o.uuidv7(),i=yield exports.UserAuthModel.create({secret:s,user_id:r}).catch(this.error);if(!i)throw new t.InternalServerError;return{auth:i,token:a.sign({id:r,secret:s},Env.TOKEN_KEY,this.options())}})}destroy(e){return h(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return h(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new t.NotFoundError("TOKEN_KEY not found");const{decode:r}=yield this.verify(e,Env.API_TOKEN_RENEW/1e3);if(!r)throw new t.UnauthorizedError("Invalid token");const{id:s,secret:i}=r;if(s&&i){const e=yield exports.UserModel.findOne({where:{id:s,state:!0}}).catch(this.error);if(e){const t=yield exports.UserAuthModel.findOne({where:{secret:i,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at){t.secret=o.uuidv7(),yield t.save().catch(this.error);return{auth:t,token:a.sign({id:s,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t.UnauthorizedError("Invalid token")})}user(e){return h(this,void 0,void 0,function*(){const{decode:r}=yield this.verify(e);if(!r)throw new t.UnauthorizedError("Invalid token");const{id:o,secret:s}=r;if(o&&s){const e=yield exports.UserModel.findOne({where:{id:o,state:!0}}).catch(this.error);if(e){const t=yield exports.UserAuthModel.findOne({where:{secret:s,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at)return{auth:t,user:e}}}throw new t.UnauthorizedError("Invalid token")})}options(){return{algorithm:"RS256",expiresIn:`${Env.TOKEN_TTL}ms`}}verify(e,r){return h(this,void 0,void 0,function*(){if(!Env.TOKEN_CRT)throw new t.NotFoundError("TOKEN_CRT not found");if(!e||e.split(".").length<3)throw new t.UnauthorizedError("Invalid token");try{return{decode:a.verify(e,Env.TOKEN_CRT,{clockTolerance:r})}}catch(e){throw new t.UnauthorizedError("Invalid token")}})}key(e){return h(this,void 0,void 0,function*(){if(!e)throw new t.UnauthorizedError("Invalid token");const r=yield exports.UserModel.findOne({where:{token:e,state:!0}}).catch(this.error);if(r){const t=e.replace(/(-[\w]{4})/g,"-****"),[o]=(yield exports.UserAuthModel.findOrCreate({where:{secret:t,user_id:r.id},defaults:{secret:t,user_id:r.id}}).catch(this.error))||[];if(o)return o.revoked_at&&(o.revoked_at=null,yield o.save().catch(this.error)),{auth:o,user:r}}throw new t.UnauthorizedError("Invalid token")})}}class ModelService extends exports.Service{constructor(e,t){super(),this.attributes=[],this.filter=[],this.permissions=[],this.model=e,(null==t?void 0:t.attributes)&&(this.filter=t.attributes),(null==t?void 0:t.permissions)&&(this.filter=t.permissions)}countAll(e){return h(this,arguments,void 0,function*({ctx:e,options:r}){var s,n,d,l,a;const p=Object.assign({},r||{}),{search:u,where:c}=null!==(n=null===(s=null==e?void 0:e.req)||void 0===s?void 0:s.query)&&void 0!==n?n:{};p.attributes=[];const g=[];g.length&&(p.order=g),p.where=Object.assign({},p.where||{});const v=this.getAttributes(null!==(d=null==p?void 0:p.attributes)&&void 0!==d?d:[]);if(o.isString(c)){const r=i.Where.parse(v,c);if(!o.isUndefined(r.error))return null==e||e.error(new t.ValidationError(r.error.join(", "))),0;p.where=Object.assign(Object.assign({},p.where),null!==(l=r.value)&&void 0!==l?l:{})}else{const e=[];v.forEach(t=>{o.isString(u)&&u.length&&e.push({[t]:{[i.Op.like]:`%${u}%`}})}),e.length&&(p.where=Object.assign(Object.assign({},p.where),{[i.Op.or]:[...e]}))}const y=null!==(a=yield this.model.count(Object.assign(Object.assign({},p),{distinct:!!p.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error))&&void 0!==a?a:0;return null==e||e.prepare(t.Status.OK,{count:y}),y})}create(e){return h(this,arguments,void 0,function*({ctx:e,options:r,body:s}){var i,n;const d=Object.assign({},r||{}),l=yield this.model.create(Object.assign({},o.merge({},null!==(n=null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.body)&&void 0!==n?n:{},null!=s?s:{})),Object.assign(Object.assign({},d),{ctx:e})).catch(this.error);if(l){const{primaryKeyAttribute:r}=this.model;return null==e||e.prepare(t.Status.OK,{[r]:l.getDataValue(r)}),l}return null==e||e.error(new t.InternalServerError),null})}delete(e){return h(this,arguments,void 0,function*({ctx:e,options:r,id:o}){var s,i,n;const d=Object.assign({},r||{}),{primaryKeyAttribute:l}=this.model,{[l]:a}=null!==(i=null===(s=null==e?void 0:e.req)||void 0===s?void 0:s.params)&&void 0!==i?i:{[l]:null!=o?o:0};if(!a)return null==e||e.error(new t.InternalServerError),0;const p=yield this.model.destroy(Object.assign(Object.assign(Object.assign({},d),{where:Object.assign(Object.assign({},null!==(n=d.where)&&void 0!==n?n:{}),{[l]:a}),individualHooks:!0}),{ctx:e})).catch(this.error);return p?(null==e||e.success("OK"),p):(null==e||e.error(new t.NotFoundError),0)})}filterAttributes(e,t){if(o.isArray(t))return t.length?t.map(t=>o.isString(t)&&-1!=e.indexOf(t)?t:void 0).filter(o.isString):e;const{exclude:r,include:s}=t,i=o.isUndefined(s)?e:s.map(t=>o.isString(t)&&-1!=e.indexOf(t)?t:void 0).filter(o.isString),n=null!=r?r:[];return n.length?i.filter(e=>-1==n.indexOf(e)):i}findAll(e){return h(this,arguments,void 0,function*({ctx:e,options:r,callback:s,limited:n}){var d,l,a,p,u,c,g;const v=Object.assign({},r||{}),{limit:y,offset:h,asc:x,desc:m,search:C,select:E,where:f}=null!==(l=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.query)&&void 0!==l?l:{};if(o.isUndefined(v.limit)){let e=Env.API_MODEL_LIMIT;o.isString(y)&&(e=parseInt(y)||0),e=o.clamp(e,-1,Env.API_MODEL_LIMIT_MAX),v.limit=e>0?e:n?Env.API_MODEL_LIMIT:void 0}if(o.isNumber(v.limit)&&(v.limit=v.limit>0?v.limit:void 0),o.isString(h)){const e=parseInt(h)||0;v.offset=e>0?e:void 0}const A=this.getAttributes(null!==(a=null==v?void 0:v.attributes)&&void 0!==a?a:[]),M=e=>A.indexOf(e)>=0;v.attributes=[],o.isString(E)&&E.length&&v.attributes.push(...E.split(";").filter(M)),v.attributes.length||(v.attributes=A);const _=[];if(o.isString(x)&&x.length&&_.push(...x.split(";").filter(M).map(e=>[e,"ASC"])),o.isString(m)&&m.length&&_.push(...m.split(";").filter(M).map(e=>[e,"DESC"])),_.length&&(v.order=_),v.where=Object.assign({},v.where||{}),o.isString(f)){const r=i.Where.parse(A,f);if(!o.isUndefined(r.error))return null==e||e.error(new t.ValidationError(r.error.join(", "))),{count:0,records:[]};v.where=Object.assign(Object.assign({},v.where),null!==(p=r.value)&&void 0!==p?p:{})}else{const e=[];A.forEach(t=>{o.isString(C)&&C.length&&e.push({[t]:{[i.Op.like]:`%${C}%`}})}),e.length&&(v.where=Object.assign(Object.assign({},v.where),{[i.Op.or]:[...e]}))}const S=this.model.count(Object.assign(Object.assign({},v),{distinct:!!v.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error),P=this.model.findAll(v).catch(this.error);yield Promise.allSettled([S,P]);const O=null!==(u=yield S)&&void 0!==u?u:0;let U=null!==(c=yield P)&&void 0!==c?c:[];const T={count:O};return U?(U=s?yield s(U):U,(o.isNumber(null==r?void 0:r.limit)||0==O)&&(T.count=null!==(g=null==U?void 0:U.length)&&void 0!==g?g:0),null==e||e.prepare(t.Status.OK,Object.assign(Object.assign({},T),{records:U})),Object.assign(Object.assign({},T),{records:U})):(null==e||e.error(new t.InternalServerError),Object.assign(Object.assign({},T),{records:[]}))})}findOne(e){return h(this,arguments,void 0,function*({ctx:e,options:r,callback:s}){var i,n,d,l,a;const p=Object.assign({},r||{}),{primaryKeyAttribute:u}=this.model,{[u]:c}=null!==(i=null==e?void 0:e.req.params)&&void 0!==i?i:{},g=this.getAttributes(null!==(n=null==p?void 0:p.attributes)&&void 0!==n?n:[]),v=e=>g.indexOf(e)>=0,{select:y}=null!==(l=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.query)&&void 0!==l?l:{};o.isString(y)&&(p.attributes=y.split(";").filter(v));const h=yield this.model.findOne(Object.assign(Object.assign({},p),{where:Object.assign(Object.assign({},null!==(a=null==p?void 0:p.where)&&void 0!==a?a:{}),{[u]:c})})).catch(this.error);return h?(null==e||e.prepare(t.Status.OK,s?yield s(h):h.toJSON()),h):h?(null==e||e.error(new t.InternalServerError),null):(null==e||e.error(new t.NotFoundError),null)})}getAttributes(e){return 0==this.attributes.length&&(this.attributes=this.filterAttributes(Object.keys(this.model.getAttributes()),this.filter)),this.filterAttributes(this.attributes,e)}sync(){return h(this,void 0,void 0,function*(){if(!this.permissions.length)return;const e=this.name().toLowerCase(),t={description:"",state:!0};yield o.forEachSeries(this.permissions,r=>h(this,void 0,void 0,function*(){const s=`${e}.${r}`,i=o.upperCamelCase(e.replace(/_/g," ")," ");yield exports.PermissionModel.findOrCreate({where:{key:s},defaults:Object.assign({name:`${i} ${o.upperCamelCase(r," ")}`,key:s,tags:i},t)})}))})}update(e){return h(this,arguments,void 0,function*({ctx:e,options:t,body:r,id:s}){var i,n,d,l,a,p;const u=Object.assign({},t||{}),{primaryKeyAttribute:c}=this.model,{[c]:g}=null!==(n=null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.params)&&void 0!==n?n:{[c]:null!=s?s:0},[v]=null!==(p=yield this.model.update(Object.assign({},o.merge({},null!==(l=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.body)&&void 0!==l?l:{},null!=r?r:{})),Object.assign(Object.assign(Object.assign({},u),{where:Object.assign(Object.assign({},null!==(a=null==u?void 0:u.where)&&void 0!==a?a:{}),{[c]:g}),individualHooks:!0}),{ctx:e})).catch(this.error))&&void 0!==p?p:[];return v?(null==e||e.success("OK"),!0):(null==e||e.success("Record not changed"),!1)})}name(){return this.model.tableName}}class UserService extends exports.Service{getMetadata(e){return h(this,void 0,void 0,function*(){var t,r;const[o]=null!==(t=yield exports.UserMetadataModel.findOrCreate({where:{user_id:e},defaults:{user_id:e}}).catch(this.error))&&void 0!==t?t:[];return null!==(r=null==o?void 0:o.data)&&void 0!==r?r:{}})}getProfile(e){return h(this,void 0,void 0,function*(){var t,r;const[o]=null!==(t=yield exports.UserProfileModel.findOrCreate({where:{user_id:e},defaults:{user_id:e}}).catch(this.error))&&void 0!==t?t:[];return null!==(r=null==o?void 0:o.data)&&void 0!==r?r:{}})}getGroups(e){return h(this,void 0,void 0,function*(){var t;return(null!==(t=yield exports.GroupModel.findAll({attributes:["key"],where:{state:!0},include:[{model:exports.UserGroupModel,required:!0,where:{user_id:e}}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.key)})}getPermissions(e){return h(this,void 0,void 0,function*(){var t;return(null!==(t=yield exports.PermissionModel.findAll({attributes:["key"],where:{state:!0},include:[{model:exports.GroupPermissionModel,required:!0,include:[{model:exports.GroupModel,required:!0,attributes:["id"],where:{state:!0},include:[{model:exports.UserGroupModel,required:!0,where:{user_id:e}}]}]}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.key)})}}class Application extends t.Application{constructor(e,t){super(e,o.merge({},{cert:Env.HTTP_CRT,cross:Env.API_HTTP_CROSS,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},key:Env.HTTP_KEY,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:o.uuidv7}},null!=t?t:{})),this.hash=new r.Hash(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 h(this,void 0,void 0,function*(){yield x.sync(),yield this.migrations(x),yield o.forEachSeries(this.controllers,e=>h(this,void 0,void 0,function*(){o.isFunction(e.sync)&&(yield e.sync(this))})),this.authService=new AuthService,this.userService=new UserService,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new s.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>h(this,void 0,void 0,function*(){t.url||(t.url=""),e.on("close",()=>{}),yield o.sleep(2e3),e.close()})))})}migrations(e){return h(this,void 0,void 0,function*(){const t=[];yield o.forEachSeries(Object.keys(e.models),r=>h(this,void 0,void 0,function*(){var o;const s=e.models[r],i=s.version();if(!i)return;const[n,d]=null!==(o=yield exports.MigrationModel.findOrCreate({where:{model:s.tableName},defaults:{model:s.tableName,version:""}}).catch(this.error))&&void 0!==o?o:[];n&&(d||n.version!=i)&&(n.version=i,yield n.save().catch(this.error),t.push(s))})),yield o.forEachSeries(t,e=>h(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}exports.BaseController=class BaseController extends o.EventEmitter{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,r){return h(this,void 0,void 0,function*(){r.auth&&r.user&&(r.user_agent?r.user_agent!=t&&r.regenerate(o.noop):(r.user_agent=t,r.save(o.noop))),e.next()})}sync(){return h(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield o.forEachSeries(this.permissions,r=>h(this,void 0,void 0,function*(){const s=`${e}.${r}`,i=o.upperCamelCase(e.replace(/_/g," ")," ");yield exports.PermissionModel.findOrCreate({where:{key:s},defaults:Object.assign({name:`${i} ${o.upperCamelCase(r," ")}`,key:s,tags:i},t)})}))})}},g([v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Session()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Object]),y("design:returntype",Promise)],exports.BaseController.prototype,"session",null),exports.BaseController=g([p.Trait(Loggable)],exports.BaseController),exports.ModelController=class ModelController extends exports.BaseController{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"]}countAll(e){return h(this,void 0,void 0,function*(){return yield this.service.countAll(e)})}create(e){return h(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return h(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return h(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return h(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}sync(){return h(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield o.forEachSeries(this.permissions,r=>h(this,void 0,void 0,function*(){const s=`${e}.${r}`,i=o.upperCamelCase(e.replace(/_/g," ")," ");yield exports.PermissionModel.findOrCreate({where:{key:s},defaults:Object.assign({name:`${i} ${o.upperCamelCase(r," ")}`,key:s,tags:i},t)})})),this.service=new ModelService(this.model)})}update(e){return h(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}},exports.ModelController=g([t.Extends(exports.BaseController)],exports.ModelController),exports.AuditsController=class AuditsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.AuditModel,this.permissions=["read"]}all(e,t,r){return h(this,void 0,void 0,function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:o,order:[["created_at","DESC"]]},limited:!0})})}get(e){return h(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}},g([t.Get(),M(),f(),v(0,t.Ctx()),v(1,t.Query("type")),v(2,t.Query("table")),y("design:type",Function),y("design:paramtypes",[t.Context,String,String]),y("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),g([t.Get("/:id"),M(),f(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=g([t.Controller("/audits"),t.Extends(exports.ModelController)],exports.AuditsController),exports.AuthController=class AuthController extends exports.BaseController{constructor(e){super(),this.authService=e}login(e,r,s,n,l,a){return h(this,void 0,void 0,function*(){var p;yield o.sleep(Env.SLEEP_AUTH);const u=yield exports.UserModel.findOne({where:{[i.Op.or]:[{email:s},{username:s}]}}).catch(this.error);if(!u)return e.error(new t.UnauthorizedError("Invalid credentials")),a.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const c=yield exports.UserPasswordModel.findOne({where:{user_id:u.id,state:!0}}).catch(this.error);if(!c||!d.compareSync(n,c.value))return e.error(new t.UnauthorizedError("Invalid credentials")),a.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const g=yield exports.RegisterModel.findOne({where:{state:!0,user_id:u.id}}).catch(this.error);if(g)return e.error("ACTIVATION REQUIRED"),a.emit("auth.activation",{ctx:e,register:g,user:u}),void this.emit("auth.activation",{ctx:e,register:g,user:u});if(!u.state)return e.error(new t.UnauthorizedError("Invalid credentials")),a.emit("auth.failure",{ctx:e,user:u}),void this.emit("auth.failure",{ctx:e,user:u});const{auth:v,token:y}=null!==(p=yield this.authService.create(u).catch(t=>{e.error(t),a.emit("auth.failure",{ctx:e}),this.emit("auth.failure",{ctx:e})}))&&void 0!==p?p:{};v&&y&&(v.user_agent=r,v.ip_address=e.getIp(),yield v.save().catch(this.error),Env.API_TOKEN_COOKIE_SET&&e.cookie(Env.API_TOKEN_COOKIE,y,{maxAge:l?Env.TOKEN_TTL:void 0}),e.json({token:y}),a.emit("auth.login",{ctx:e,auth:v,user:u}),this.emit("auth.login",{ctx:e,auth:v,user:u}))})}logout(e,r,o,s){return h(this,void 0,void 0,function*(){if(yield this.authService.destroy(r))return e.success("OK"),s.emit("auth.logout",{auth:r,ctx:e,user:o}),void this.emit("auth.logout",{auth:r,ctx:e,user:o});e.error(new t.UnauthorizedError("Access Denied"))})}renew(e,t,r,o){return h(this,void 0,void 0,function*(){var s;const{auth:i,token:n}=null!==(s=yield this.authService.renew(r).catch(t=>{e.error(t)}))&&void 0!==s?s:{};i&&n&&(i.user_agent=t,yield i.save().catch(this.error),e.json({token:n}),o.emit("auth.renew",{auth:i,ctx:e}),this.emit("auth.renew",{auth:i,ctx:e}))})}user(e,r){return h(this,void 0,void 0,function*(){const{groups:s,permissions:i,profile:n}=e.req;if(!s||!i)return e.error(new t.InternalServerError);e.json(Object.assign(Object.assign({},o.denied(r.toJSON(),["username","description"])),{groups:s,permissions:i,profile:n}))})}},g([t.Post("/login"),t.Validate(e=>({username:e.string().min(3).required(),password:e.string().min(5).required(),remember:e.boolean().parse().empty(!1)})),v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Body("username")),v(3,t.Body("password")),v(4,t.Body("remember")),v(5,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,String,Boolean,Application]),y("design:returntype",Promise)],exports.AuthController.prototype,"login",null),g([t.Get("/logout"),M(),v(0,t.Ctx()),v(1,_()),v(2,T()),v(3,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.UserAuthModel,exports.UserModel,Application]),y("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),g([t.Post("/renew"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Body("token")),v(3,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,Application]),y("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),g([t.Get(),t.Get("/me"),M(),v(0,t.Ctx()),v(1,T()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.UserModel]),y("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=g([t.Controller("/auth"),t.Extends(exports.BaseController),v(0,p.Inject(AuthService)),y("design:paramtypes",[AuthService])],exports.AuthController),exports.CrudController=class CrudController extends exports.ModelController{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}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return h(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return h(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}number(e){return h(this,void 0,void 0,function*(){yield this.countAll(this.CrudArgumentsFindAll(e))})}del(e){return h(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return h(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return h(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return h(this,void 0,void 0,function*(){if(this.CrudValidationCreate()==this._crud)return e.error(new t.InternalServerError)})}validationUpdate(e){return h(this,void 0,void 0,function*(){if(this.CrudValidationUpdate()==this._crud)return e.error(new t.InternalServerError)})}},g([t.Post(),M(),C(),t.Middleware("validationCreate"),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"add",null),g([t.Get(),M(),f(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"all",null),g([t.Get("/count"),M(),f(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"number",null),g([t.Delete("/:id"),M(),E(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"del",null),g([t.Get("/:id"),M(),f(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"get",null),g([t.Put("/:id"),M(),A(),t.Middleware("validationUpdate"),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"set",null),g([v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"validationCreate",null),g([v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"validationUpdate",null),exports.CrudController=g([t.Extends(exports.ModelController)],exports.CrudController),exports.FilesController=class FilesController extends exports.BaseController{constructor(){super(...arguments),this.directory=Env.API_HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return h(this,void 0,void 0,function*(){let{path:r}=e.req;r=r.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const s=c.join(this.directory,r);if(!u.existsSync(s)||!u.statSync(s).isDirectory())return e.error(new t.NotFoundError);let i=[];return i=u.readdirSync(s),i=i.map(e=>this.info(c.join(s,e))),i=i.filter(o.isDef),Object.assign(Object.assign({},this.info(s)),{files:i})})}info(e){if(!u.existsSync(e))return null;const t=u.statSync(e),r=e.split("/").pop();e=e.replace(this.directory,"/").replace(/^\/\//,"/");const o=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:o?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:o,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return h(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=o.upperCamelCase(e.replace(/_/g," ")," "),r={description:"",state:!0};yield o.forEachSeries(this.permissions,s=>h(this,void 0,void 0,function*(){const i=`${e}.${s}`;yield exports.PermissionModel.findOrCreate({where:{key:i},defaults:Object.assign({name:`${t} ${o.upperCamelCase(s," ")}`,key:i,tags:t},r)})}))})}},g([t.Get("/path"),t.Get("/path/*path"),M(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.FilesController.prototype,"files",null),exports.FilesController=g([t.Controller("/files"),t.Extends(exports.BaseController)],exports.FilesController),exports.ForgotController=class ForgotController extends exports.BaseController{check(e,r){return h(this,void 0,void 0,function*(){const s=yield this.find(r);if(!s||!s.user)return e.error(new t.NotFoundError);s.secret=o.uniqueID(),yield s.save(),e.json({token:s.secret})})}forgot(e,r,s){return h(this,void 0,void 0,function*(){yield o.sleep(Env.SLEEP_FORGOT);const n=r,d=yield exports.UserModel.findOne({where:{[i.Op.or]:[{email:n},{username:r}]}}).catch(this.error);if(!d)return e.error(new t.NotFoundError);const l=o.uniqueID(),a=Date.now()+6e4*Env.API_TOKEN_FORGOT,p=yield exports.ForgotModel.create({token:l,timestamp:a,state:!0,user_id:d.id});e.success("OK"),s.emit("forgot.send",{ctx:e,forgot:p,user:d}),this.emit("forgot.send",{ctx:e,forgot:p,user:d})})}reset(e,r,o,s){return h(this,void 0,void 0,function*(){const o=yield this.find(r);if(!o)return e.error(new t.NotFoundError);o.state=!1,yield o.save().catch(this.error),yield o.user.save().catch(this.error),e.success("OK"),s.emit("forgot.reset",{ctx:e,user:o.user}),this.emit("forgot.reset",{ctx:e,user:o.user})})}find(e){return h(this,void 0,void 0,function*(){return yield exports.ForgotModel.findOne({where:{token:e,state:!0},include:[{model:exports.UserModel,required:!0}]}).catch(this.error)})}},g([t.Get("/check"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Body("token")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),g([t.Post(),t.Validate(e=>({username:e.string().min(4).required()})),v(0,t.Ctx()),v(1,t.Body("username")),v(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Application]),y("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),g([t.Post("/reset"),t.Validate(e=>({token:e.string().required(),password:e.string().min(5).required()})),v(0,t.Ctx()),v(1,t.Body("token")),v(2,t.Body("password")),v(3,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,Application]),y("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=g([t.Controller("/forgot"),t.Extends(exports.BaseController)],exports.ForgotController),exports.GroupsController=class GroupsController extends exports.CrudController{constructor(){super(...arguments),this.model=exports.GroupModel,this.schemaCreate={name:o.Validation.string().required(),key:o.Validation.string().required(),tags:o.Validation.string().empty(""),description:o.Validation.string().empty(""),state:o.Validation.boolean().parse().required()},this.schemaUpdate={name:o.Validation.string().empty(),tags:o.Validation.string().empty(),description:o.Validation.string().empty(),state:o.Validation.boolean().parse().empty()}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.GroupsController=g([t.Controller("/groups"),t.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsPermissionsController=class GroupsPermissionsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.GroupPermissionModel,this.permissions=[]}all(e,t){return h(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:exports.PermissionModel,required:!0}]},callback:e=>e.map(e=>e.permission)})})}set(e,r,s){return h(this,void 0,void 0,function*(){const n=yield exports.GroupModel.findByPk(r,{attributes:["id"]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);const d=n.id,l=[];yield o.forEachSeries(o.uniqueArray(s),t=>h(this,void 0,void 0,function*(){var r;if(!(yield exports.PermissionModel.count({where:{id:t}})))return;const[o]=null!==(r=yield exports.GroupPermissionModel.findOrCreate(Object.assign({where:{group_id:d,permission_id:t},defaults:{group_id:d,permission_id:t}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];o&&l.push(t)})),yield exports.GroupPermissionModel.destroy(Object.assign({where:{group_id:d,permission_id:{[i.Op.notIn]:l}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}},g([t.Get("/:id/permissions"),M(),f("groups"),v(0,t.Ctx()),v(1,t.Params("id")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"all",null),g([t.Put("/:id/permissions"),M(),A("groups"),t.Validate(e=>({permissions:e.array(e.string())})),v(0,t.Ctx()),v(1,t.Params("id")),v(2,t.Body("permissions")),y("design:type",Function),y("design:paramtypes",[t.Context,String,Array]),y("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"set",null),exports.GroupsPermissionsController=g([t.Controller("/groups"),t.Extends(exports.ModelController)],exports.GroupsPermissionsController),exports.LogsController=class LogsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.LogModel,this.permissions=["read"]}all(e){return h(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{order:[["created_at","DESC"]]},limited:!0})})}},g([t.Get(),M(),f(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=g([t.Controller("/logs"),t.Extends(exports.ModelController)],exports.LogsController),exports.PermissionsController=class PermissionsController extends exports.CrudController{constructor(){super(...arguments),this.model=exports.PermissionModel,this.schemaCreate={name:o.Validation.string().required(),key:o.Validation.string().required(),tags:o.Validation.string().empty(""),description:o.Validation.string().empty(""),state:o.Validation.boolean().parse().required()},this.schemaUpdate={name:o.Validation.string().empty(),tags:o.Validation.string().empty(),description:o.Validation.string().empty(),state:o.Validation.boolean().parse().empty()}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.PermissionsController=g([t.Controller("/permissions"),t.Extends(exports.CrudController)],exports.PermissionsController),exports.RegisterController=class RegisterController extends exports.BaseController{register(e,s,n){return h(this,void 0,void 0,function*(){yield o.sleep(Env.SLEEP_REGISTRY);const{name:d,date:l,email:a,username:p,password:u,confirm:c}=s,g=p||a,v=r.sha256(u);if(yield exports.UserModel.count({where:{[i.Op.or]:[{email:a},{username:g}]}}).catch(this.error))return e.error("INVALID EMAIL OR USERNAME");if(v!=r.sha256(c))return e.error("INVALID PASSWORD");const y=yield exports.UserModel.create({name:d,email:a,username:g,password:v,avatar:"",date:l,description:"",state:!1}).catch(this.error);if(!y)return e.error(new t.InternalServerError);const h=yield exports.RegisterModel.create({token:yield this.getId(),user_id:y.id,state:!0}).catch(this.error);if(!h)return yield y.destroy().catch(this.error),e.error(new t.InternalServerError);e.success("OK"),n.emit("register.user",{ctx:e,register:h,user:y}),this.emit("register.user",{ctx:e,register:h,user:y})})}confirm(e,r,o){return h(this,void 0,void 0,function*(){const s=yield exports.RegisterModel.findOne({where:{token:r,state:!0},include:[{model:exports.UserModel,required:!0}]}).catch(this.error);if(!s)return e.error(new t.NotFoundError);s.state=!1,yield s.save().catch(this.error),s.user.state=!0,yield s.user.save().catch(this.error),e.success("OK"),o.emit("register.confirm",{ctx:e,register:s,user:s.user}),this.emit("register.confirm",{ctx:e,register:s,user:s.user})})}send(e,r,o){return h(this,void 0,void 0,function*(){const s=r,n=yield exports.RegisterModel.findOne({where:{state:!0},include:[{model:exports.UserModel,required:!0,where:{[i.Op.or]:[{email:s},{username:r}]}}]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);e.success("OK"),o.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})})}getId(){return h(this,void 0,void 0,function*(){const e=o.uuidv7();return(yield exports.RegisterModel.count({where:{token:e}}))?this.getId():e})}},g([t.Post(),t.Validate(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()})),v(0,t.Ctx()),v(1,t.Body()),v(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,Object,Application]),y("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),g([t.Post("/confirm"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Body("token")),v(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Application]),y("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),g([t.Post("/send"),t.Validate(e=>({username:e.string().min(4).required()})),v(0,t.Ctx()),v(1,t.Body("username")),v(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Application]),y("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=g([t.Controller("/register"),t.Extends(exports.BaseController)],exports.RegisterController),exports.SetupController=class SetupController extends exports.BaseController{setup(e){return h(this,void 0,void 0,function*(){var t;if(yield exports.UserModel.count())return e.success("OK");const r=yield exports.UserModel.create({name:"Admin",email:"admin@localhost.com",username:"admin",description:"DEFAULT",state:!0},Object.assign({},{ctx:e}));yield exports.UserPasswordModel.create({value:"admin",state:!0,user_id:r.id});const s=yield exports.GroupModel.create(Object.assign({name:"Admin",key:"admin",tags:"Admin"},{description:"API CORE",state:!0}),Object.assign({},{ctx:e}));yield exports.UserGroupModel.create({user_id:r.id,group_id:s.id},Object.assign({},{ctx:e}));const i=null!==(t=yield exports.PermissionModel.findAll({where:{state:!0}}).catch(this.error))&&void 0!==t?t:[];yield o.forEachSeries(i,t=>h(this,void 0,void 0,function*(){yield exports.GroupPermissionModel.create({group_id:s.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}},g([t.Get(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=g([t.Controller("/setup"),t.Extends(exports.BaseController)],exports.SetupController),exports.UsersController=class UsersController extends exports.ModelController{constructor(){super(),this.model=exports.UserModel,this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&u.existsSync(Env.API_HTTP_PUBLIC)&&!u.existsSync(this.path)&&u.mkdirSync(this.path)}avatar(e,r){return h(this,void 0,void 0,function*(){var o,s;const i=e.getFiles();if(i.file&&i.file.length){const{filename:n,path:d}=null!==(o=i.file[0])&&void 0!==o?o:{};if(n){const[o]=null!==(s=yield exports.UserProfileModel.findOrCreate(Object.assign({where:{user_id:r.id},defaults:{user_id:r.id}},{ctx:e})).catch(this.error))&&void 0!==s?s:[];if(!o)return u.lstatSync(d).isFile()&&u.rmSync(d),e.error(new t.InternalServerError);const i=this.path+"/"+o.data.avatar;if(u.existsSync(i)&&u.lstatSync(i).isFile()&&u.rmSync(i),o.changed("data",!0),o.data.avatar=n,yield o.save(Object.assign({},{ctx:e})).catch(this.error))return e.success("OK")}}e.success("Record not Changed")})}token_new(){return h(this,void 0,void 0,function*(){var e;const t=o.uuidv7();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 h(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return h(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}number(e){return h(this,void 0,void 0,function*(){yield this.countAll({ctx:e})})}del(e,r,o){return h(this,void 0,void 0,function*(){if(o.id==r)return e.error(new t.NotFoundError);yield this.delete({ctx:e})})}get(e){return h(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return h(this,void 0,void 0,function*(){yield this.update({ctx:e})})}},g([t.Post("/avatar"),M(),t.Upload({file:{count:1,path:`${Env.API_HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),v(0,t.Ctx()),v(1,T()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.UserModel]),y("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),g([t.Post(),M(),C(),t.Validate(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)})),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"add",null),g([t.Get(),M(),f(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"all",null),g([t.Get("/count"),M(),f(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"number",null),g([t.Delete("/:id"),M(),E(),v(0,t.Ctx()),v(1,t.Params("id")),v(2,T()),y("design:type",Function),y("design:paramtypes",[t.Context,String,exports.UserModel]),y("design:returntype",Promise)],exports.UsersController.prototype,"del",null),g([t.Get("/:id"),M(),f(),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"get",null),g([t.Put("/:id"),M(),A(),t.Validate(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()})),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=g([t.Controller("/users"),t.Extends(exports.ModelController),y("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class UsersGroupsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.UserGroupModel,this.permissions=[]}all(e,t){return h(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:exports.GroupModel,required:!0}]},callback:e=>e.map(e=>e.group)})})}set(e,r,s){return h(this,void 0,void 0,function*(){const n=yield exports.UserModel.findByPk(r,{attributes:["id"]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);const d=n.id,l=[];yield o.forEachSeries(o.uniqueArray(s),t=>h(this,void 0,void 0,function*(){var r;if(!(yield exports.GroupModel.count({where:{id:t}})))return;const[o]=null!==(r=yield exports.UserGroupModel.findOrCreate(Object.assign({where:{user_id:d,group_id:t},defaults:{user_id:d,group_id:t}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];o&&l.push(t)})),yield exports.UserGroupModel.destroy(Object.assign({where:{user_id:d,group_id:{[i.Op.notIn]:l}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}},g([t.Get("/:id/groups"),M(),f("users"),v(0,t.Ctx()),v(1,t.Params("id")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),g([t.Put("/:id/groups"),M(),A("users"),t.Validate(e=>({groups:e.array(e.string())})),v(0,t.Ctx()),v(1,t.Params("id")),v(2,t.Body("groups")),y("design:type",Function),y("design:paramtypes",[t.Context,String,Array]),y("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=g([t.Controller("/users"),t.Extends(exports.ModelController)],exports.UsersGroupsController),exports.UsersProfilesController=class UsersProfilesController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.UserProfileModel,this.permissions=[]}all(e){return h(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}get(e,r){return h(this,void 0,void 0,function*(){var o;const[s]=null!==(o=yield exports.UserProfileModel.findOrCreate(Object.assign({where:{user_id:r},defaults:{user_id:r}},{ctx:e})).catch(this.error))&&void 0!==o?o:[];if(!s)return e.error(new t.NotFoundError);e.json(s.data)})}set(e,r,s){return h(this,void 0,void 0,function*(){var i;const n=yield exports.UserModel.findByPk(r,{attributes:["id"]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);const d=n.id,l=o.map(s,e=>String(e)),[a,p]=null!==(i=yield exports.UserProfileModel.findOrCreate(Object.assign({where:{user_id:d},defaults:{data:l,user_id:d}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];a&&!p&&(a.changed("data",!0),a.data=o.merge(a.data,l),yield a.save(Object.assign({},{ctx:e})).catch(this.error)),e.success("OK")})}},g([t.Get("/profiles"),M(),f("users"),v(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersProfilesController.prototype,"all",null),g([t.Get("/:id/profiles"),M(),f("users"),v(0,t.Ctx()),v(1,t.Params("id")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.UsersProfilesController.prototype,"get",null),g([t.Put("/:id/profiles"),M(),A("users"),v(0,t.Ctx()),v(1,t.Params("id")),v(2,t.Body()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Object]),y("design:returntype",Promise)],exports.UsersProfilesController.prototype,"set",null),exports.UsersProfilesController=g([t.Controller("/users"),t.Extends(exports.ModelController)],exports.UsersProfilesController),exports.Application=Application,exports.Audit=w,exports.AuthService=AuthService,exports.CanCreate=C,exports.CanDelete=E,exports.CanRead=f,exports.CanUpdate=A,exports.Config=class Config extends Loggable{static all(e){return h(this,void 0,void 0,function*(){var t;const r=null!==(t=yield exports.ConfigModel.findAll({where:(null==e?void 0:e.length)?{key:{[i.Op.in]:e}}:{}}).catch(this.error))&&void 0!==t?t:[];return Object.fromEntries(r.map(e=>[e.key,e.value]))})}static del(e){return h(this,void 0,void 0,function*(){return((yield exports.ConfigModel.destroy({where:{key:e}}).catch(this.error))||0)>0})}static get(e){return h(this,arguments,void 0,function*(e,t=""){const[r]=(yield exports.ConfigModel.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return r?r.value:t})}static set(e,t){return h(this,void 0,void 0,function*(){const[r,o]=(yield exports.ConfigModel.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];r&&!o&&(r.value=t,yield r.save().catch(this.error))})}},exports.Env=Env,exports.HasGroups=(...e)=>(r,s,i)=>{t.Use(r=>h(void 0,void 0,void 0,function*(){const{groups:s}=r.req;if(o.includesArray(e,null!=s?s:[]))return r.next();r.error(new t.UnauthorizedError("Access Denied"))}))(r,s,i)},exports.HasPermissions=(...e)=>(r,s,i)=>{t.Use(r=>h(void 0,void 0,void 0,function*(){const{permissions:s}=r.req;if(o.includesArray(e,null!=s?s:[]))return r.next();r.error(new t.UnauthorizedError("Access Denied"))}))(r,s,i)},exports.IsAuthenticated=M,exports.Log=Log,exports.Loggable=Loggable,exports.ModelService=ModelService,exports.ReqAuth=_,exports.ReqGroup=S,exports.ReqGroups=P,exports.ReqPermission=O,exports.ReqPermissions=U,exports.ReqUser=T,exports.SessionStore=SessionStore,exports.UserService=UserService,exports.canFactory=m,exports.sequelize=x;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v5.0.
|
|
2
|
+
* @andrewcaires/api v5.0.1
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2026 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
@@ -9,7 +9,7 @@ import { Hash, Env as Env$1 } from '@andrewcaires/node';
|
|
|
9
9
|
import { Model, Sequelize } from '@andrewcaires/sequelize';
|
|
10
10
|
import { TypeAnyObject, TypeObjectString, TypeAnyFunction, TypeAnyConstructor, EventEmitter, TypeObject, ValidationBase } from '@andrewcaires/utils.js';
|
|
11
11
|
import { WebSocketServer } from 'ws';
|
|
12
|
-
import { Model as Model$1,
|
|
12
|
+
import { Model as Model$1, FindOptions, Attributes, CreateOptions, UpdateOptions, FindAttributeOptions, ModelStatic } from 'sequelize';
|
|
13
13
|
import { Store, SessionData } from 'express-session';
|
|
14
14
|
|
|
15
15
|
declare class RegisterModel extends Model {
|
|
@@ -41,7 +41,7 @@ declare class PermissionModel extends Model {
|
|
|
41
41
|
readonly id: string;
|
|
42
42
|
name: string;
|
|
43
43
|
key: string;
|
|
44
|
-
|
|
44
|
+
tags: string;
|
|
45
45
|
description: string;
|
|
46
46
|
state: boolean;
|
|
47
47
|
readonly created_at: Date;
|
|
@@ -62,6 +62,7 @@ declare class GroupModel extends Model {
|
|
|
62
62
|
readonly id: string;
|
|
63
63
|
name: string;
|
|
64
64
|
key: string;
|
|
65
|
+
tags: string;
|
|
65
66
|
description: string;
|
|
66
67
|
state: boolean;
|
|
67
68
|
readonly created_at: Date;
|
|
@@ -90,6 +91,16 @@ declare class UserPasswordModel extends Model {
|
|
|
90
91
|
user: UserModel;
|
|
91
92
|
}
|
|
92
93
|
|
|
94
|
+
declare class UserProfileModel extends Model {
|
|
95
|
+
readonly id: string;
|
|
96
|
+
data: TypeAnyObject;
|
|
97
|
+
readonly created_at: Date;
|
|
98
|
+
readonly updated_at: Date;
|
|
99
|
+
readonly deleted_at: Date | null;
|
|
100
|
+
user_id: string;
|
|
101
|
+
user: UserModel;
|
|
102
|
+
}
|
|
103
|
+
|
|
93
104
|
declare class UserModel extends Model {
|
|
94
105
|
readonly id: string;
|
|
95
106
|
name: string;
|
|
@@ -105,6 +116,7 @@ declare class UserModel extends Model {
|
|
|
105
116
|
registers: Array<RegisterModel>;
|
|
106
117
|
users_groups: Array<UserGroupModel>;
|
|
107
118
|
users_passwords: Array<UserPasswordModel>;
|
|
119
|
+
users_profiles: Array<UserProfileModel>;
|
|
108
120
|
}
|
|
109
121
|
|
|
110
122
|
declare class AuditModel extends Model {
|
|
@@ -117,6 +129,7 @@ declare class AuditModel extends Model {
|
|
|
117
129
|
full_url: string;
|
|
118
130
|
ip_address: string;
|
|
119
131
|
user_agent: string;
|
|
132
|
+
app_name: string;
|
|
120
133
|
state: boolean;
|
|
121
134
|
readonly created_at: Date;
|
|
122
135
|
readonly updated_at: Date;
|
|
@@ -170,19 +183,7 @@ declare class SessionModel extends Model {
|
|
|
170
183
|
|
|
171
184
|
declare class UserMetadataModel extends Model {
|
|
172
185
|
readonly id: string;
|
|
173
|
-
|
|
174
|
-
value: string;
|
|
175
|
-
readonly created_at: Date;
|
|
176
|
-
readonly updated_at: Date;
|
|
177
|
-
readonly deleted_at: Date | null;
|
|
178
|
-
user_id: string;
|
|
179
|
-
user: UserModel;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
declare class UserProfileModel extends Model {
|
|
183
|
-
readonly id: string;
|
|
184
|
-
key: string;
|
|
185
|
-
value: string;
|
|
186
|
+
data: TypeAnyObject;
|
|
186
187
|
readonly created_at: Date;
|
|
187
188
|
readonly updated_at: Date;
|
|
188
189
|
readonly deleted_at: Date | null;
|
|
@@ -190,47 +191,6 @@ declare class UserProfileModel extends Model {
|
|
|
190
191
|
user: UserModel;
|
|
191
192
|
}
|
|
192
193
|
|
|
193
|
-
interface ArgumentsModel<M extends Model$1<M>> {
|
|
194
|
-
ctx?: Context;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
interface ArgumentsModelCreate<M extends Model$1<M>> extends ArgumentsModel<M> {
|
|
198
|
-
options?: CreateOptions<Attributes<M>>;
|
|
199
|
-
body?: TypeAnyObject;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
interface ArgumentsModelDelete<M extends Model$1<M>> extends ArgumentsModel<M> {
|
|
203
|
-
id?: string | number;
|
|
204
|
-
options?: FindOptions<Attributes<M>>;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
type CallbackModelFindAll<M> = (_records: Array<M>) => Array<any> | Promise<Array<any>>;
|
|
208
|
-
|
|
209
|
-
interface ArgumentsModelFindAll<M extends Model$1<any>> extends ArgumentsModel<M> {
|
|
210
|
-
options?: FindOptions<Attributes<M>>;
|
|
211
|
-
callback?: CallbackModelFindAll<M>;
|
|
212
|
-
advanced?: boolean;
|
|
213
|
-
limited?: boolean;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
type CallbackModelFindOne<M> = (_records: M) => any | Promise<any>;
|
|
217
|
-
|
|
218
|
-
interface ArgumentsModelFindOne<M extends Model$1<M>> extends ArgumentsModel<M> {
|
|
219
|
-
options?: FindOptions<Attributes<M>>;
|
|
220
|
-
callback?: CallbackModelFindOne<M>;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
interface ArgumentsModelUpdate<M extends Model$1<M>> extends ArgumentsModel<M> {
|
|
224
|
-
id?: string | number;
|
|
225
|
-
options?: UpdateOptions<Attributes<M>>;
|
|
226
|
-
body?: TypeAnyObject;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
interface ResultModelFindAll<M extends Model<M>> {
|
|
230
|
-
count: number;
|
|
231
|
-
records: Array<M>;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
194
|
interface IAuthParameters {
|
|
235
195
|
auth?: UserAuthModel;
|
|
236
196
|
decode?: TypeAnyObject;
|
|
@@ -239,6 +199,65 @@ interface IAuthParameters {
|
|
|
239
199
|
user?: UserModel;
|
|
240
200
|
}
|
|
241
201
|
|
|
202
|
+
interface AuthEvents {
|
|
203
|
+
"auth.activation": {
|
|
204
|
+
ctx: Context;
|
|
205
|
+
register: RegisterModel;
|
|
206
|
+
user: UserModel;
|
|
207
|
+
};
|
|
208
|
+
"auth.failure": {
|
|
209
|
+
ctx: Context;
|
|
210
|
+
user?: UserModel;
|
|
211
|
+
};
|
|
212
|
+
"auth.login": {
|
|
213
|
+
ctx: Context;
|
|
214
|
+
auth: UserAuthModel;
|
|
215
|
+
user: UserModel;
|
|
216
|
+
};
|
|
217
|
+
"auth.logout": {
|
|
218
|
+
ctx: Context;
|
|
219
|
+
auth: UserAuthModel;
|
|
220
|
+
user: UserModel;
|
|
221
|
+
};
|
|
222
|
+
"auth.renew": {
|
|
223
|
+
ctx: Context;
|
|
224
|
+
auth: UserAuthModel;
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
interface ForgotEvents {
|
|
229
|
+
"forgot.reset": {
|
|
230
|
+
ctx: Context;
|
|
231
|
+
user?: UserModel;
|
|
232
|
+
};
|
|
233
|
+
"forgot.send": {
|
|
234
|
+
ctx: Context;
|
|
235
|
+
forgot: ForgotModel;
|
|
236
|
+
user: UserModel;
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
interface RegisterEvents {
|
|
241
|
+
"register.confirm": {
|
|
242
|
+
ctx: Context;
|
|
243
|
+
register: RegisterModel;
|
|
244
|
+
user?: UserModel;
|
|
245
|
+
};
|
|
246
|
+
"register.send": {
|
|
247
|
+
ctx: Context;
|
|
248
|
+
register: RegisterModel;
|
|
249
|
+
user?: UserModel;
|
|
250
|
+
};
|
|
251
|
+
"register.user": {
|
|
252
|
+
ctx: Context;
|
|
253
|
+
register: RegisterModel;
|
|
254
|
+
user?: UserModel;
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
interface ApplicationEvents extends AuthEvents, ForgotEvents, RegisterEvents {
|
|
259
|
+
}
|
|
260
|
+
|
|
242
261
|
declare module "express-serve-static-core" {
|
|
243
262
|
interface Request {
|
|
244
263
|
auth?: UserAuthModel;
|
|
@@ -269,6 +288,55 @@ declare module "express-serve-static-core" {
|
|
|
269
288
|
}
|
|
270
289
|
}
|
|
271
290
|
|
|
291
|
+
interface ModelArgumentsBase<M extends Model$1<M>> {
|
|
292
|
+
ctx?: Context;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
interface ModelArgumentsCount<M extends Model$1<any>> extends ModelArgumentsBase<M> {
|
|
296
|
+
options?: FindOptions<Attributes<M>>;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
interface ModelArgumentsCreate<M extends Model$1<M>> extends ModelArgumentsBase<M> {
|
|
300
|
+
options?: CreateOptions<Attributes<M>>;
|
|
301
|
+
body?: TypeAnyObject;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
interface ModelArgumentsDelete<M extends Model$1<M>> extends ModelArgumentsBase<M> {
|
|
305
|
+
id?: string | number;
|
|
306
|
+
options?: FindOptions<Attributes<M>>;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
type ModelCallbackFindAll<M> = (_records: Array<M>) => Array<any> | Promise<Array<any>>;
|
|
310
|
+
|
|
311
|
+
interface ModelArgumentsFindAll<M extends Model$1<any>> extends ModelArgumentsBase<M> {
|
|
312
|
+
options?: FindOptions<Attributes<M>>;
|
|
313
|
+
callback?: ModelCallbackFindAll<M>;
|
|
314
|
+
limited?: boolean;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
type ModelCallbackFindOne<M> = (_records: M) => any | Promise<any>;
|
|
318
|
+
|
|
319
|
+
interface ModelArgumentsFindOne<M extends Model$1<M>> extends ModelArgumentsBase<M> {
|
|
320
|
+
options?: FindOptions<Attributes<M>>;
|
|
321
|
+
callback?: ModelCallbackFindOne<M>;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
interface ModelArgumentsUpdate<M extends Model$1<M>> extends ModelArgumentsBase<M> {
|
|
325
|
+
id?: string | number;
|
|
326
|
+
options?: UpdateOptions<Attributes<M>>;
|
|
327
|
+
body?: TypeAnyObject;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
interface ModelOptions {
|
|
331
|
+
attributes?: FindAttributeOptions;
|
|
332
|
+
permissions?: Array<string>;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
interface ModelResultFindAll<M extends Model<M>> {
|
|
336
|
+
count: number;
|
|
337
|
+
records: Array<M>;
|
|
338
|
+
}
|
|
339
|
+
|
|
272
340
|
declare class Loggable {
|
|
273
341
|
get log(): (message: string) => void;
|
|
274
342
|
static get log(): (message: string) => void;
|
|
@@ -280,10 +348,10 @@ declare class Loggable {
|
|
|
280
348
|
}
|
|
281
349
|
|
|
282
350
|
declare class Config extends Loggable {
|
|
283
|
-
static all(): Promise<TypeObjectString>;
|
|
284
|
-
static del(key: string
|
|
351
|
+
static all(keys?: Array<string>): Promise<TypeObjectString>;
|
|
352
|
+
static del(key: string): Promise<boolean>;
|
|
285
353
|
static get(key: string, value?: string): Promise<string>;
|
|
286
|
-
static set(key: string, value: string
|
|
354
|
+
static set(key: string, value: string): Promise<void>;
|
|
287
355
|
}
|
|
288
356
|
|
|
289
357
|
declare class Log {
|
|
@@ -325,14 +393,17 @@ declare class ModelService<M extends Model$1<any>> extends Service {
|
|
|
325
393
|
protected model: ModelStatic<M>;
|
|
326
394
|
protected attributes: Array<string>;
|
|
327
395
|
protected filter: FindAttributeOptions;
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
396
|
+
protected permissions: Array<string>;
|
|
397
|
+
constructor(model: ModelStatic<M>, options?: ModelOptions);
|
|
398
|
+
countAll({ ctx, options }: ModelArgumentsCount<M>): Promise<number>;
|
|
399
|
+
create({ ctx, options, body }: ModelArgumentsCreate<M>): Promise<M | null>;
|
|
400
|
+
delete({ ctx, options, id: _id }: ModelArgumentsDelete<M>): Promise<number>;
|
|
331
401
|
private filterAttributes;
|
|
332
|
-
findAll({ ctx, options, callback,
|
|
333
|
-
findOne({ ctx, options, callback }:
|
|
402
|
+
findAll({ ctx, options, callback, limited }: ModelArgumentsFindAll<M>): Promise<ModelResultFindAll<M>>;
|
|
403
|
+
findOne({ ctx, options, callback }: ModelArgumentsFindOne<M>): Promise<M | null>;
|
|
334
404
|
getAttributes(options: FindAttributeOptions): Array<string>;
|
|
335
|
-
|
|
405
|
+
sync(): Promise<void>;
|
|
406
|
+
update({ ctx, options, body, id: _id }: ModelArgumentsUpdate<M>): Promise<boolean>;
|
|
336
407
|
name(): string;
|
|
337
408
|
}
|
|
338
409
|
|
|
@@ -343,7 +414,7 @@ declare class UserService extends Service {
|
|
|
343
414
|
getPermissions(user_id: string): Promise<Array<string>>;
|
|
344
415
|
}
|
|
345
416
|
|
|
346
|
-
declare class Application extends Application$1 {
|
|
417
|
+
declare class Application<T extends TypeAnyObject = ApplicationEvents> extends Application$1<T> {
|
|
347
418
|
readonly hash: Hash;
|
|
348
419
|
authService: AuthService;
|
|
349
420
|
userService: UserService;
|
|
@@ -358,34 +429,36 @@ declare class Application extends Application$1 {
|
|
|
358
429
|
|
|
359
430
|
interface BaseController extends Loggable {
|
|
360
431
|
}
|
|
361
|
-
declare abstract class BaseController extends EventEmitter {
|
|
432
|
+
declare abstract class BaseController<T extends TypeAnyObject = TypeAnyObject> extends EventEmitter<T> {
|
|
362
433
|
protected readonly permissions: Array<string>;
|
|
363
434
|
name(): string;
|
|
364
435
|
session(ctx: Context, user_agent: string, store: IStore): Promise<void>;
|
|
365
436
|
sync(): Promise<void>;
|
|
366
437
|
}
|
|
367
438
|
|
|
368
|
-
declare abstract class ModelController<M extends Model$1<any
|
|
439
|
+
declare abstract class ModelController<M extends Model$1<any>, T extends TypeAnyObject = TypeAnyObject> extends BaseController<T> {
|
|
369
440
|
protected readonly attributes: Array<string>;
|
|
370
441
|
protected abstract readonly model: ModelStatic<M>;
|
|
371
442
|
protected readonly permissions: Array<string>;
|
|
372
443
|
private service;
|
|
373
|
-
protected
|
|
374
|
-
protected
|
|
375
|
-
protected
|
|
376
|
-
protected
|
|
444
|
+
protected countAll(options: ModelArgumentsCount<M>): Promise<number>;
|
|
445
|
+
protected create(options: ModelArgumentsCreate<M>): Promise<M | null>;
|
|
446
|
+
protected delete(options: ModelArgumentsDelete<M>): Promise<number>;
|
|
447
|
+
protected findAll(options: ModelArgumentsFindAll<M>): Promise<ModelResultFindAll<M>>;
|
|
448
|
+
protected findOne(options: ModelArgumentsFindOne<M>): Promise<M | null>;
|
|
377
449
|
sync(): Promise<void>;
|
|
378
|
-
protected update(options:
|
|
450
|
+
protected update(options: ModelArgumentsUpdate<M>): Promise<boolean>;
|
|
379
451
|
name(): string;
|
|
380
452
|
}
|
|
381
453
|
|
|
382
454
|
declare class AuditsController extends ModelController<AuditModel> {
|
|
383
455
|
protected readonly model: typeof AuditModel;
|
|
456
|
+
protected readonly permissions: string[];
|
|
384
457
|
protected all(ctx: Context, type: string, table: string): Promise<void>;
|
|
385
458
|
protected get(ctx: Context): Promise<void>;
|
|
386
459
|
}
|
|
387
460
|
|
|
388
|
-
declare class AuthController extends BaseController {
|
|
461
|
+
declare class AuthController extends BaseController<AuthEvents> {
|
|
389
462
|
protected readonly authService: AuthService;
|
|
390
463
|
constructor(authService: AuthService);
|
|
391
464
|
protected login(ctx: Context, user_agent: string, username: string, password: string, remember: boolean, app: Application): Promise<void>;
|
|
@@ -394,17 +467,19 @@ declare class AuthController extends BaseController {
|
|
|
394
467
|
protected user(ctx: Context, user: UserModel): Promise<void>;
|
|
395
468
|
}
|
|
396
469
|
|
|
397
|
-
declare abstract class CrudController<M extends Model$1<any
|
|
470
|
+
declare abstract class CrudController<M extends Model$1<any>, T extends TypeAnyObject = TypeAnyObject> extends ModelController<M, T> {
|
|
398
471
|
private _crud;
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
472
|
+
CrudArgumentscountAll(ctx: Context): ModelArgumentsUpdate<M>;
|
|
473
|
+
CrudArgumentsCreate(ctx: Context): ModelArgumentsUpdate<M>;
|
|
474
|
+
CrudArgumentsFindAll(ctx: Context): ModelArgumentsFindAll<M>;
|
|
475
|
+
CrudArgumentsFindOne(ctx: Context): ModelArgumentsFindOne<M>;
|
|
476
|
+
CrudArgumentsDelete(ctx: Context): ModelArgumentsDelete<M>;
|
|
477
|
+
CrudArgumentsUpdate(ctx: Context): ModelArgumentsUpdate<M>;
|
|
404
478
|
CrudValidationCreate(): TypeObject<ValidationBase>;
|
|
405
479
|
CrudValidationUpdate(): TypeObject<ValidationBase>;
|
|
406
480
|
protected add(ctx: Context): Promise<void>;
|
|
407
481
|
protected all(ctx: Context): Promise<void>;
|
|
482
|
+
protected number(ctx: Context): Promise<void>;
|
|
408
483
|
protected del(ctx: Context): Promise<void>;
|
|
409
484
|
protected get(ctx: Context): Promise<void>;
|
|
410
485
|
protected set(ctx: Context): Promise<void>;
|
|
@@ -421,7 +496,7 @@ declare class FilesController extends BaseController {
|
|
|
421
496
|
sync(): Promise<void>;
|
|
422
497
|
}
|
|
423
498
|
|
|
424
|
-
declare class ForgotController extends BaseController {
|
|
499
|
+
declare class ForgotController extends BaseController<ForgotEvents> {
|
|
425
500
|
protected check(ctx: Context, token: string): Promise<void>;
|
|
426
501
|
protected forgot(ctx: Context, username: string, app: Application): Promise<void>;
|
|
427
502
|
protected reset(ctx: Context, token: string, password: string, app: Application): Promise<void>;
|
|
@@ -438,8 +513,8 @@ declare class GroupsController extends CrudController<GroupModel> {
|
|
|
438
513
|
|
|
439
514
|
declare class GroupsPermissionsController extends ModelController<GroupPermissionModel> {
|
|
440
515
|
protected readonly model: typeof GroupPermissionModel;
|
|
516
|
+
protected readonly permissions: never[];
|
|
441
517
|
protected all(ctx: Context, group_id: string): Promise<void>;
|
|
442
|
-
protected me(ctx: Context, user: UserModel): Promise<void>;
|
|
443
518
|
protected set(ctx: Context, id: string, permissions: Array<string>): Promise<void>;
|
|
444
519
|
}
|
|
445
520
|
|
|
@@ -457,7 +532,7 @@ declare class PermissionsController extends CrudController<PermissionModel> {
|
|
|
457
532
|
CrudValidationUpdate(): TypeObject<ValidationBase>;
|
|
458
533
|
}
|
|
459
534
|
|
|
460
|
-
declare class RegisterController extends BaseController {
|
|
535
|
+
declare class RegisterController extends BaseController<RegisterEvents> {
|
|
461
536
|
protected register(ctx: Context, body: TypeAnyObject, app: Application): Promise<void>;
|
|
462
537
|
protected confirm(ctx: Context, token: string, app: Application): Promise<void>;
|
|
463
538
|
protected send(ctx: Context, username: string, app: Application): Promise<void>;
|
|
@@ -476,6 +551,7 @@ declare class UsersController extends ModelController<UserModel> {
|
|
|
476
551
|
private token_new;
|
|
477
552
|
protected add(ctx: Context): Promise<void>;
|
|
478
553
|
protected all(ctx: Context): Promise<void>;
|
|
554
|
+
protected number(ctx: Context): Promise<void>;
|
|
479
555
|
protected del(ctx: Context, id: string, user: UserModel): Promise<void>;
|
|
480
556
|
protected get(ctx: Context): Promise<void>;
|
|
481
557
|
protected set(ctx: Context): Promise<void>;
|
|
@@ -483,11 +559,19 @@ declare class UsersController extends ModelController<UserModel> {
|
|
|
483
559
|
|
|
484
560
|
declare class UsersGroupsController extends ModelController<UserGroupModel> {
|
|
485
561
|
protected readonly model: typeof UserGroupModel;
|
|
562
|
+
protected readonly permissions: never[];
|
|
486
563
|
protected all(ctx: Context, user_id: string): Promise<void>;
|
|
487
|
-
protected me(ctx: Context, user: UserModel): Promise<void>;
|
|
488
564
|
protected set(ctx: Context, id: string, groups: Array<string>): Promise<void>;
|
|
489
565
|
}
|
|
490
566
|
|
|
567
|
+
declare class UsersProfilesController extends ModelController<UserProfileModel> {
|
|
568
|
+
protected readonly model: typeof UserProfileModel;
|
|
569
|
+
protected readonly permissions: never[];
|
|
570
|
+
protected all(ctx: Context): Promise<void>;
|
|
571
|
+
protected get(ctx: Context, user_id: string): Promise<void>;
|
|
572
|
+
protected set(ctx: Context, id: string, body: TypeAnyObject): Promise<void>;
|
|
573
|
+
}
|
|
574
|
+
|
|
491
575
|
declare const sequelize: Sequelize;
|
|
492
576
|
|
|
493
577
|
declare const CanCreate: (name?: string) => MethodDecorator;
|
|
@@ -530,8 +614,12 @@ declare class Env extends Env$1 {
|
|
|
530
614
|
static readonly DATABASE_TIMEZONE: string;
|
|
531
615
|
static readonly HTTP_CRT: Buffer<ArrayBufferLike> | null;
|
|
532
616
|
static readonly HTTP_KEY: Buffer<ArrayBufferLike> | null;
|
|
617
|
+
static readonly SLEEP_AUTH: number;
|
|
618
|
+
static readonly SLEEP_FORGOT: number;
|
|
619
|
+
static readonly SLEEP_REGISTRY: number;
|
|
533
620
|
static readonly TOKEN_CRT: Buffer<ArrayBufferLike> | null;
|
|
534
621
|
static readonly TOKEN_KEY: Buffer<ArrayBufferLike> | null;
|
|
622
|
+
static readonly TOKEN_TTL: number;
|
|
535
623
|
static readonly API_BODYPARSER_STRICT: boolean;
|
|
536
624
|
static readonly API_BODYPARSER_INFLATE: boolean;
|
|
537
625
|
static readonly API_BODYPARSER_LIMIT: string;
|
|
@@ -547,9 +635,6 @@ declare class Env extends Env$1 {
|
|
|
547
635
|
static readonly API_KEY_HEADER: string;
|
|
548
636
|
static readonly API_MODEL_LIMIT: number;
|
|
549
637
|
static readonly API_MODEL_LIMIT_MAX: number;
|
|
550
|
-
static readonly API_SLEEP_AUTH: number;
|
|
551
|
-
static readonly API_SLEEP_FORGOT: number;
|
|
552
|
-
static readonly API_SLEEP_REGISTRY: number;
|
|
553
638
|
static readonly API_SESSION_NAME: string;
|
|
554
639
|
static readonly API_SESSION_LIFETIME: number;
|
|
555
640
|
static readonly API_SESSION_SECRET: string;
|
|
@@ -558,11 +643,10 @@ declare class Env extends Env$1 {
|
|
|
558
643
|
static readonly API_TOKEN_FORGOT: number;
|
|
559
644
|
static readonly API_TOKEN_HEADER: string;
|
|
560
645
|
static readonly API_TOKEN_HEADER_KEY: string;
|
|
561
|
-
static readonly API_TOKEN_LIFETIME: number;
|
|
562
646
|
static readonly API_TOKEN_RENEW: number;
|
|
563
647
|
static readonly API_USER_HISTORY: boolean;
|
|
564
648
|
static readonly API_WEBSOCKET_START: boolean;
|
|
565
649
|
}
|
|
566
650
|
|
|
567
|
-
export { Application, Audit, AuditModel, AuditsController, AuthController, AuthService, BaseController, CanCreate, CanDelete, CanRead, CanUpdate, Config, ConfigModel, CrudController, Env, FilesController, ForgotController, ForgotModel, GroupModel, GroupPermissionModel, GroupsController, GroupsPermissionsController, HasGroups, HasPermissions, IsAuthenticated, Log, LogModel, Loggable, LogsController, MigrationModel, ModelController, ModelService, PermissionModel, PermissionsController, RegisterController, RegisterModel, ReqAuth, ReqGroup, ReqGroups, ReqPermission, ReqPermissions, ReqUser, Service, SessionModel, SessionStore, SetupController, UserAuthModel, UserGroupModel, UserMetadataModel, UserModel, UserPasswordModel, UserProfileModel, UserService, UsersController, UsersGroupsController, canFactory, sequelize };
|
|
568
|
-
export type {
|
|
651
|
+
export { Application, Audit, AuditModel, AuditsController, AuthController, AuthService, BaseController, CanCreate, CanDelete, CanRead, CanUpdate, Config, ConfigModel, CrudController, Env, FilesController, ForgotController, ForgotModel, GroupModel, GroupPermissionModel, GroupsController, GroupsPermissionsController, HasGroups, HasPermissions, IsAuthenticated, Log, LogModel, Loggable, LogsController, MigrationModel, ModelController, ModelService, PermissionModel, PermissionsController, RegisterController, RegisterModel, ReqAuth, ReqGroup, ReqGroups, ReqPermission, ReqPermissions, ReqUser, Service, SessionModel, SessionStore, SetupController, UserAuthModel, UserGroupModel, UserMetadataModel, UserModel, UserPasswordModel, UserProfileModel, UserService, UsersController, UsersGroupsController, UsersProfilesController, canFactory, sequelize };
|
|
652
|
+
export type { ApplicationEvents, AuthEvents, ForgotEvents, IAuthParameters, ModelArgumentsBase, ModelArgumentsCount, ModelArgumentsCreate, ModelArgumentsDelete, ModelArgumentsFindAll, ModelArgumentsFindOne, ModelArgumentsUpdate, ModelCallbackFindAll, ModelCallbackFindOne, ModelOptions, ModelResultFindAll, RegisterEvents };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v5.0.
|
|
2
|
+
* @andrewcaires/api v5.0.1
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2026 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
import{Use as e,UnauthorizedError as t,parameterFactory as i,Context as r,NotFoundError as n,InternalServerError as o,Status as s,ValidationError as d,Application as a,Ctx as l,Headers as u,Session as p,Extends as c,Get as g,Query as v,Controller as y,Post as h,Validate as m,Body as _,App as E,Middleware as f,Delete as A,Put as S,Params as O,Upload as I}from"@andrewcaires/express";import{Env as T,Log as P,LogColor as w,Hash as b,sha256 as x}from"@andrewcaires/node";import{isUndefined as D,isFunction as C,includesArray as R,getConstructor as k,noop as j,loop as N,uuidv7 as B,merge as K,isArray as U,isString as M,clamp as L,isNumber as F,forEachSeries as H,sleep as q,EventEmitter as Y,upperCamelCase as $,denied as G,isDef as V,uniqueID as W,Validation as z}from"@andrewcaires/utils.js";import{WebSocketServer as J}from"ws";import{Sequelize as X,Hooks as Z,Column as Q,Association as ee,Database as te,ModelName as ie,Version as re,Model as ne,Unique as oe,HasMany as se,Value as de,DefaultValue as ae,Op as le,Where as ue}from"@andrewcaires/sequelize";import{config as pe}from"dotenv";import{hashSync as ce,compareSync as ge}from"bcrypt";import{Store as ve}from"express-session";import{Trait as ye,Singleton as he,Inject as me}from"@andrewcaires/decorator";import _e from"jsonwebtoken";import{existsSync as Ee,statSync as fe,readdirSync as Ae,mkdirSync as Se,lstatSync as Oe,rmSync as Ie}from"fs";import{join as Te}from"path";function Pe(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 d=e.length-1;d>=0;d--)(n=e[d])&&(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 we(e,t){return function(i,r){t(i,r,e)}}function be(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function xe(e,t,i,r){return new(i||(i=Promise))(function(n,o){function s(e){try{a(r.next(e))}catch(e){o(e)}}function d(e){try{a(r.throw(e))}catch(e){o(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(s,d)}a((r=r.apply(e,t||[])).next())})}var De;"function"==typeof SuppressedError&&SuppressedError,pe({quiet:!0});class Env extends T{}De=Env,Env.BASE_NAME=De.getString("BASE_NAME",""),Env.CONSOLE_ERROR=De.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=De.getString("DATABASE_URI",""),Env.DATABASE_LOG=De.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=De.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=De.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=De.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CRT=De.getFile("HTTP_CRT"),Env.HTTP_KEY=De.getFile("HTTP_KEY"),Env.TOKEN_CRT=De.getFile("TOKEN_CRT"),Env.TOKEN_KEY=De.getFile("TOKEN_KEY"),Env.API_BODYPARSER_STRICT=De.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=De.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=De.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=De.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_PORT=De.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=De.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_CROSS=De.getBool("API_HTTP_CROSS",!1),Env.API_HTTP_HYBRID=De.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=De.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=De.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=De.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=De.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=De.getString("API_KEY_HEADER","x-api-key"),Env.API_MODEL_LIMIT=De.getInt("API_MODEL_LIMIT",10),Env.API_MODEL_LIMIT_MAX=De.getInt("API_MODEL_LIMIT_MAX",500),Env.API_SLEEP_AUTH=De.getMs("API_SLEEP_AUTH","2s"),Env.API_SLEEP_FORGOT=De.getMs("API_SLEEP_FORGOT","5s"),Env.API_SLEEP_REGISTRY=De.getMs("API_SLEEP_REGISTRY","5s"),Env.API_SESSION_NAME=De.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=De.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=De.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=De.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=De.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_TOKEN_FORGOT=De.getMs("API_TOKEN_FORGOT","1d"),Env.API_TOKEN_HEADER=De.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_HEADER_KEY=De.getString("API_TOKEN_HEADER","bearer"),Env.API_TOKEN_LIFETIME=De.getMs("API_TOKEN_LIFETIME","1d"),Env.API_TOKEN_RENEW=De.getMs("API_TOKEN_RENEW","1d"),Env.API_USER_HISTORY=De.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=De.getBool("API_WEBSOCKET_START",!1);const Ce=new X({uri:Env.DATABASE_URI,logging:Env.DATABASE_LOG,prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE}),Re=i=>r=>(n,o,s)=>{e(e=>xe(void 0,void 0,void 0,function*(){var n;let o=null!=r?r:"";D(r)&&(o=C(e.controller.name)?e.controller.name():null===(n=e.controller.constructor)||void 0===n?void 0:n.name);const{permissions:s}=e.req;if((null!=s?s:[]).includes(`${o}.${i}`))return e.next();e.error(new t("Access Denied"))}))(n,o,s)},ke=Re("create"),je=Re("delete"),Ne=Re("read"),Be=Re("update"),Ke=(...i)=>(r,n,o)=>{e(e=>xe(void 0,void 0,void 0,function*(){const{groups:r}=e.req;if(R(i,null!=r?r:[]))return e.next();e.error(new t("Access Denied"))}))(r,n,o)},Ue=(...i)=>(r,n,o)=>{e(e=>xe(void 0,void 0,void 0,function*(){const{permissions:r}=e.req;if(R(i,null!=r?r:[]))return e.next();e.error(new t("Access Denied"))}))(r,n,o)},Me=()=>(i,r,n)=>{e(e=>xe(void 0,void 0,void 0,function*(){yield(e=>xe(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]:d,"user-agent":a}=e.getHeaders(),l=e.getQuery(Env.API_KEY_HEADER),u=(null===(i=s||l)||void 0===i?void 0:i.toString())||"";let p=e.getCookie(Env.API_TOKEN_COOKIE);p=`${Env.API_TOKEN_HEADER_KEY} ${p}`;const[c,g]=null!==(n=null===(r=d||p)||void 0===r?void 0:r.split(" "))&&void 0!==n?n:["",""];if(!(u||g&&c.toLowerCase()==Env.API_TOKEN_HEADER_KEY))return e.error(new t("Invalid token"));const{authService:v,userService:y}=e.app,{auth:h,user:m}=null!==(o=yield(u?v.key(u.toString()):v.user(g)).catch(t=>{e.error(t)}))&&void 0!==o?o:{};if(h&&m){if(!u&&h.user_agent&&h.user_agent!=a)return e.error(new t("Invalid token"));e.req.auth=h,e.req.user=m,e.req.groups=yield y.getGroups(m.id),e.req.permissions=yield y.getPermissions(m.id),e.req.profile=yield y.getProfile(m.id),e.next()}}))(e)}))(i,r,n)},Le=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),Fe=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)}),He=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)}),Ye=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.permissions)&&void 0!==i?i:[]}),$e=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.user}),Ge=(e,t,i)=>{var n,o,s,d,a,l,u,p,c;const g=i.ctx instanceof r?i.ctx:null,v=null!==(d=null!==(s=null===(o=null===(n=null==g?void 0:g.req)||void 0===n?void 0:n.user)||void 0===o?void 0:o.id)&&void 0!==s?s:i.user_id)&&void 0!==d?d:null,y={type:e,model:null!==(a=null==t?void 0:t.getTableName())&&void 0!==a?a:null,state:!0,user_id:v};return g?Object.assign(Object.assign({},y),{full_url:null!==(l=null==g?void 0:g.getUrl())&&void 0!==l?l:"",ip_address:null!==(u=null==g?void 0:g.getIp())&&void 0!==u?u:"",user_agent:null!==(c=null===(p=null==g?void 0:g.req)||void 0===p?void 0:p.headers["user-agent"])&&void 0!==c?c:""}):y},Ve={afterCreate:(e,t)=>xe(void 0,void 0,void 0,function*(){const i=k(e),{primaryKeyAttribute:r}=null!=i?i:{};yield rt.create(Object.assign(Object.assign({},Ge("CREATE",i,t)),{record:r?e.getDataValue(r):null,data:e.toJSON()})).catch(P.catch)}),afterUpdate:(e,t)=>xe(void 0,void 0,void 0,function*(){const i=k(e),{primaryKeyAttribute:r}=null!=i?i:{},n={},o=e.changed();o&&o.forEach(t=>n[t]=e.getDataValue(t)),yield rt.create(Object.assign(Object.assign({},Ge("UPDATE",i,t)),{record:r?e.getDataValue(r):null,data:n,previously:e.previous()})).catch(P.catch)}),afterDestroy:(e,t)=>xe(void 0,void 0,void 0,function*(){const i=k(e),{primaryKeyAttribute:r}=null!=i?i:{};yield rt.create(Object.assign(Object.assign({},Ge("DELETE",i,t)),{record:r?e.getDataValue(r):null,data:e.toJSON()})).catch(P.catch)})},We=e=>(D(e)&&(e=Env.DATABASE_AUDIT),Z(e?Ve:{}));let ze=class RegisterModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],ze.prototype,"id",void 0),Pe([Q.String(),be("design:type",String)],ze.prototype,"secret",void 0),Pe([Q.FullDate(),be("design:type",Number)],ze.prototype,"expired_at",void 0),Pe([Q.Boolean(),be("design:type",Boolean)],ze.prototype,"state",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],ze.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],ze.prototype,"updated_at",void 0),Pe([Q.DeletedAt(),be("design:type",Object)],ze.prototype,"deleted_at",void 0),Pe([ee.BelongsTo(()=>it),be("design:type",String)],ze.prototype,"user_id",void 0),ze=Pe([te(Ce),ie("register"),re("5.0.0")],ze);let Je=class UserAuthModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],Je.prototype,"id",void 0),Pe([Q.String(),be("design:type",String)],Je.prototype,"secret",void 0),Pe([Q.String(),be("design:type",String)],Je.prototype,"ip_address",void 0),Pe([Q.String(),be("design:type",String)],Je.prototype,"user_agent",void 0),Pe([Q.FullDate(),be("design:type",Object)],Je.prototype,"revoked_at",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],Je.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],Je.prototype,"updated_at",void 0),Pe([Q.DeletedAt(),be("design:type",Object)],Je.prototype,"deleted_at",void 0),Pe([ee.BelongsTo(()=>it),be("design:type",String)],Je.prototype,"user_id",void 0),Je=Pe([te(Ce),ie("users_auth"),re("5.0.0")],Je);let Xe=class PermissionModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],Xe.prototype,"id",void 0),Pe([Q.String(),be("design:type",String)],Xe.prototype,"name",void 0),Pe([Q.String(),oe(!0),be("design:type",String)],Xe.prototype,"key",void 0),Pe([Q.String(),be("design:type",String)],Xe.prototype,"tag",void 0),Pe([Q.Text(),be("design:type",String)],Xe.prototype,"description",void 0),Pe([Q.Boolean(),be("design:type",Boolean)],Xe.prototype,"state",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],Xe.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],Xe.prototype,"updated_at",void 0),Pe([Q.DeletedAt(),be("design:type",Object)],Xe.prototype,"deleted_at",void 0),Pe([se(()=>Ze,"permission_id"),be("design:type",Array)],Xe.prototype,"groups_permissions",void 0),Xe=Pe([te(Ce),ie("permission"),We(),re("5.0.0")],Xe);let Ze=class GroupPermissionModel extends ne{};Pe([Q.CreatedAt(),be("design:type",Date)],Ze.prototype,"created_at",void 0),Pe([ee.BelongsTo(()=>Qe),be("design:type",String)],Ze.prototype,"group_id",void 0),Pe([ee.BelongsTo(()=>Xe),be("design:type",String)],Ze.prototype,"permission_id",void 0),Ze=Pe([te(Ce),ie("groups_permissions"),We(),re("5.0.0")],Ze);let Qe=class GroupModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],Qe.prototype,"id",void 0),Pe([Q.String(),be("design:type",String)],Qe.prototype,"name",void 0),Pe([Q.String(),be("design:type",String)],Qe.prototype,"key",void 0),Pe([Q.Text(),be("design:type",String)],Qe.prototype,"description",void 0),Pe([Q.Boolean(),be("design:type",Boolean)],Qe.prototype,"state",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],Qe.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],Qe.prototype,"updated_at",void 0),Pe([Q.DeletedAt(),be("design:type",Object)],Qe.prototype,"deleted_at",void 0),Pe([ee.HasMany(()=>et,"group_id"),be("design:type",Array)],Qe.prototype,"users_groups",void 0),Pe([ee.HasMany(()=>Ze,"group_id"),be("design:type",Array)],Qe.prototype,"groups_Permission",void 0),Qe=Pe([te(Ce),ie("group"),We(),re("5.0.0")],Qe);let et=class UserGroupModel extends ne{};Pe([Q.CreatedAt(),be("design:type",Date)],et.prototype,"created_at",void 0),Pe([ee.BelongsTo(()=>Qe),be("design:type",String)],et.prototype,"group_id",void 0),Pe([ee.BelongsTo(()=>it),be("design:type",String)],et.prototype,"user_id",void 0),et=Pe([te(Ce),ie("users_groups"),We(),re("5.0.0")],et);let tt=class UserPasswordModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],tt.prototype,"id",void 0),Pe([Q.String(),de(e=>ce(e.value,12)),be("design:type",String)],tt.prototype,"value",void 0),Pe([Q.Boolean(),be("design:type",Boolean)],tt.prototype,"state",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],tt.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],tt.prototype,"updated_at",void 0),Pe([Q.DeletedAt(),be("design:type",Object)],tt.prototype,"deleted_at",void 0),Pe([ee.BelongsTo(()=>it),be("design:type",String)],tt.prototype,"user_id",void 0),tt=Pe([te(Ce),ie("users_password"),We(),re("5.0.0")],tt);let it=class UserModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],it.prototype,"id",void 0),Pe([Q.String(),be("design:type",String)],it.prototype,"name",void 0),Pe([Q.String(),be("design:type",String)],it.prototype,"email",void 0),Pe([Q.String(),be("design:type",String)],it.prototype,"username",void 0),Pe([Q.Text(),be("design:type",String)],it.prototype,"description",void 0),Pe([Q.Boolean(),be("design:type",Boolean)],it.prototype,"state",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],it.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],it.prototype,"updated_at",void 0),Pe([Q.DeletedAt(),be("design:type",Object)],it.prototype,"deleted_at",void 0),Pe([ee.HasMany(()=>rt,"user_id"),be("design:type",Array)],it.prototype,"audits",void 0),Pe([ee.HasMany(()=>Je,"user_id"),be("design:type",Array)],it.prototype,"users_auths",void 0),Pe([ee.HasMany(()=>ze,"user_id"),be("design:type",Array)],it.prototype,"registers",void 0),Pe([ee.HasMany(()=>et,"user_id"),be("design:type",Array)],it.prototype,"users_groups",void 0),Pe([ee.HasMany(()=>tt,"user_id"),be("design:type",Array)],it.prototype,"users_passwords",void 0),it=Pe([te(Ce),ie("user"),We(),re("5.0.0")],it);let rt=class AuditModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],rt.prototype,"id",void 0),Pe([Q.Enum("CREATE","DELETE","UPDATE"),be("design:type",String)],rt.prototype,"type",void 0),Pe([Q.String(),be("design:type",String)],rt.prototype,"model",void 0),Pe([Q.String(),be("design:type",String)],rt.prototype,"record",void 0),Pe([Q.Json(),be("design:type",Object)],rt.prototype,"data",void 0),Pe([Q.Json(),be("design:type",Object)],rt.prototype,"previously",void 0),Pe([Q.Text(),be("design:type",String)],rt.prototype,"full_url",void 0),Pe([Q.String(),be("design:type",String)],rt.prototype,"ip_address",void 0),Pe([Q.String(),be("design:type",String)],rt.prototype,"user_agent",void 0),Pe([Q.Boolean(),be("design:type",Boolean)],rt.prototype,"state",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],rt.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],rt.prototype,"updated_at",void 0),Pe([Q.DeletedAt(),be("design:type",Object)],rt.prototype,"deleted_at",void 0),Pe([ee.BelongsTo(()=>it),be("design:type",String)],rt.prototype,"user_id",void 0),rt=Pe([te(Ce),ie("audit"),re("5.0.0")],rt);let nt=class ConfigModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],nt.prototype,"id",void 0),Pe([Q.String(),be("design:type",String)],nt.prototype,"key",void 0),Pe([Q.String(),be("design:type",String)],nt.prototype,"value",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],nt.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],nt.prototype,"updated_at",void 0),nt=Pe([te(Ce),ie("configs"),re("5.0.0")],nt);let ot=class ForgotModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],ot.prototype,"id",void 0),Pe([Q.String(),be("design:type",String)],ot.prototype,"secret",void 0),Pe([Q.FullDate(),be("design:type",Number)],ot.prototype,"expired_at",void 0),Pe([Q.Boolean(),be("design:type",Boolean)],ot.prototype,"state",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],ot.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],ot.prototype,"updated_at",void 0),Pe([Q.DeletedAt(),be("design:type",Object)],ot.prototype,"deleted_at",void 0),Pe([ee.BelongsTo(()=>it),be("design:type",String)],ot.prototype,"user_id",void 0),ot=Pe([te(Ce),ie("forgot"),re("5.0.0")],ot);let st=class LogModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],st.prototype,"id",void 0),Pe([Q.Enum("info","warn","error"),ae("info"),be("design:type",String)],st.prototype,"level",void 0),Pe([Q.Text(),be("design:type",String)],st.prototype,"message",void 0),Pe([Q.String(),be("design:type",String)],st.prototype,"source",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],st.prototype,"created_at",void 0),st=Pe([te(Ce),ie("log"),re("5.0.0")],st);let dt=class MigrationModel extends ne{};Pe([Q.String(),be("design:type",String)],dt.prototype,"model",void 0),Pe([Q.String(),be("design:type",String)],dt.prototype,"version",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],dt.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],dt.prototype,"updated_at",void 0),dt=Pe([te(Ce),ie("migration"),re("5.0.0")],dt);let at=class SessionModel extends ne{};Pe([Q.String(),be("design:type",String)],at.prototype,"session",void 0),Pe([Q.Text(),be("design:type",String)],at.prototype,"json",void 0),Pe([Q.BigInt(),be("design:type",Number)],at.prototype,"expired",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],at.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],at.prototype,"updated_at",void 0),at=Pe([te(Ce),ie("session"),re("5.0.0")],at);let lt=class UserMetadataModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],lt.prototype,"id",void 0),Pe([Q.String(),be("design:type",String)],lt.prototype,"key",void 0),Pe([Q.Text("medium"),be("design:type",String)],lt.prototype,"value",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],lt.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],lt.prototype,"updated_at",void 0),Pe([Q.DeletedAt(),be("design:type",Object)],lt.prototype,"deleted_at",void 0),Pe([ee.BelongsTo(()=>it),be("design:type",String)],lt.prototype,"user_id",void 0),lt=Pe([te(Ce),ie("users_metadata"),We(),re("5.0.0")],lt);let ut=class UserProfileModel extends ne{};Pe([Q.UUID(7),be("design:type",String)],ut.prototype,"id",void 0),Pe([Q.String(),be("design:type",String)],ut.prototype,"key",void 0),Pe([Q.Text("medium"),be("design:type",String)],ut.prototype,"value",void 0),Pe([Q.CreatedAt(),be("design:type",Date)],ut.prototype,"created_at",void 0),Pe([Q.UpdatedAt(),be("design:type",Date)],ut.prototype,"updated_at",void 0),Pe([Q.DeletedAt(),be("design:type",Object)],ut.prototype,"deleted_at",void 0),Pe([ee.BelongsTo(()=>it),be("design:type",String)],ut.prototype,"user_id",void 0),ut=Pe([te(Ce),ie("users_profile"),We(),re("5.0.0")],ut);class Log{static error(e,t,i){return xe(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,i)})}static info(e,t,i){return xe(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,i)})}static warn(e,t,i){return xe(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,i)})}static writeRaw(e,t,i,r){return xe(this,void 0,void 0,function*(){var n;r&&P.console(null!==(n=this.colors[e])&&void 0!==n?n:w.White,e,t),Ce&&(yield st.create({level:e,message:t,source:null!=i?i:""}).catch(P.catch))})}}Log.colors={error:w.Red,info:w.Cyan,warn:w.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(){return xe(this,void 0,void 0,function*(){const e=yield nt.findAll().catch(this.error),t={};return e&&e.forEach(e=>t[e.key]=e.value),t})}static del(e,t){return xe(this,void 0,void 0,function*(){var i;const r=null!==(i=null==t?void 0:t.id)&&void 0!==i?i:null;return((yield nt.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:r})).catch(this.error))||0)>0})}static get(e){return xe(this,arguments,void 0,function*(e,t=""){const[i]=(yield nt.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return i?i.value:t})}static set(e,t,i){return xe(this,void 0,void 0,function*(){var r;const n=null!==(r=null==i?void 0:i.id)&&void 0!==r?r:null,[o]=(yield nt.findOrCreate(Object.assign({where:{key:e}},{user_id:n})).catch(this.error))||[];o&&(o.value=t,yield o.save().catch(this.error))})}}class SessionStore extends ve{constructor(){super(),this.all=e=>xe(this,void 0,void 0,function*(){e=e||j;const t=yield at.findAll({attributes:["session"],where:{expired:{[le.gte]:Date.now()}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.session)),e()}),this.clear=e=>xe(this,void 0,void 0,function*(){yield at.destroy().catch(j),e&&e()}),this.destroy=(e,t)=>xe(this,void 0,void 0,function*(){yield at.destroy({where:{session:e}}).catch(j),t&&t()}),this.expired=()=>xe(this,void 0,void 0,function*(){yield at.destroy({where:{expired:{[le.lt]:Date.now()}}}).catch(j)}),this.get=(e,t)=>xe(this,void 0,void 0,function*(){t=t||j;const i=yield at.findOne({where:{session:e,expired:{[le.gte]:Date.now()}}}).catch(e=>(t(e),null));if(i){const e=JSON.parse(i.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield i.destroy().catch(j),void t(null)}return void t(null,e)}t(null)}),this.length=e=>xe(this,void 0,void 0,function*(){e&&e(null,(yield at.count().catch(j))||0)}),this.set=(e,t,i)=>xe(this,void 0,void 0,function*(){i=i||j;const r=Date.now()+Env.API_SESSION_LIFETIME,n=JSON.stringify(t),[o,s]=(yield at.findOrCreate({where:{session:e},defaults:{session:e,json:n,expired:r}}).catch(j))||[];o&&(s||(o.json=n,o.expired=r,yield o.save().catch(j))),i()}),this.loop=N(this.expired,3e4),this.loop.start()}}let pt=class Service{};pt=Pe([ye(Loggable)],pt);let ct=class AuthService extends pt{create(e){return xe(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new n("TOKEN_KEY not found");const{id:t}=e,i=B(),r=yield Je.create({secret:i,user_id:t}).catch(this.error);if(!r)throw new o;return{auth:r,token:_e.sign({id:t,secret:i},Env.TOKEN_KEY,this.options())}})}destroy(e){return xe(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return xe(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:o}=i;if(r&&o){const e=yield it.findOne({where:{id:r,state:!0}}).catch(this.error);if(e){const t=yield Je.findOne({where:{secret:o,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at){t.secret=B(),yield t.save().catch(this.error);return{auth:t,token:_e.sign({id:r,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t("Invalid token")})}user(e){return xe(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 it.findOne({where:{id:r,state:!0}}).catch(this.error);if(e){const t=yield Je.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.API_TOKEN_LIFETIME}ms`}}verify(e,i){return xe(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:_e.verify(e,Env.TOKEN_CRT,{clockTolerance:i})}}catch(e){throw new t("Invalid token")}})}key(e){return xe(this,void 0,void 0,function*(){if(!e)throw new t("Invalid token");const i=yield it.findOne({where:{token:e,state:!0}}).catch(this.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield Je.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")})}};ct=Pe([he()],ct);class ModelService extends pt{constructor(e,t){super(),this.attributes=[],this.filter=[],this.model=e,t&&(this.filter=t)}create(e){return xe(this,arguments,void 0,function*({ctx:e,options:t,body:i}){var r,n;const d=Object.assign({},t||{}),a=yield this.model.create(Object.assign({},K({},null!==(n=null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.body)&&void 0!==n?n:{},null!=i?i:{})),Object.assign(Object.assign({},d),{ctx:e})).catch(this.error);if(a){const{primaryKeyAttribute:t}=this.model;return null==e||e.prepare(s.OK,{[t]:a.getDataValue(t)}),a}return null==e||e.error(new o),null})}delete(e){return xe(this,arguments,void 0,function*({ctx:e,options:t,id:i}){var r,s,d;const a=Object.assign({},t||{}),{primaryKeyAttribute:l}=this.model,{[l]:u}=null!==(s=null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.params)&&void 0!==s?s:{[l]:null!=i?i:0};if(!u)return null==e||e.error(new o),0;const p=yield this.model.destroy(Object.assign(Object.assign(Object.assign({},a),{where:Object.assign(Object.assign({},null!==(d=a.where)&&void 0!==d?d:{}),{[l]:u}),individualHooks:!0}),{ctx:e})).catch(this.error);return p?(null==e||e.success("OK"),p):(null==e||e.error(new n),0)})}filterAttributes(e,t){if(U(t))return t.length?t.map(t=>M(t)&&-1!=e.indexOf(t)?t:void 0).filter(M):e;const{exclude:i,include:r}=t,n=D(r)?e:r.map(t=>M(t)&&-1!=e.indexOf(t)?t:void 0).filter(M),o=null!=i?i:[];return o.length?n.filter(e=>-1==o.indexOf(e)):n}findAll(e){return xe(this,arguments,void 0,function*({ctx:e,options:t,callback:i,advanced:r,limited:n}){var a,l,u,p,c,g,v;const y=Object.assign({},t||{}),{attributes:h,limit:m,offset:_,asc:E,desc:f,search:A,where:S}=null!==(l=null===(a=null==e?void 0:e.req)||void 0===a?void 0:a.query)&&void 0!==l?l:{};if(D(y.limit)){let e=Env.API_MODEL_LIMIT;M(m)&&(e=parseInt(m)||0),e=L(e,-1,Env.API_MODEL_LIMIT_MAX),y.limit=e>0?e:n?Env.API_MODEL_LIMIT:void 0}if(F(y.limit)&&(y.limit=y.limit>0?y.limit:void 0),M(_)){const e=parseInt(_)||0;y.offset=e>0?e:void 0}const O=this.getAttributes(null!==(u=null==y?void 0:y.attributes)&&void 0!==u?u:[]),I=e=>O.indexOf(e)>=0;y.attributes=[],M(h)&&h.length&&y.attributes.push(...h.split(";").filter(I)),y.attributes.length||(y.attributes=O);const T=[];if(M(E)&&E.length&&T.push(...E.split(";").filter(I).map(e=>[e,"ASC"])),M(f)&&f.length&&T.push(...f.split(";").filter(I).map(e=>[e,"DESC"])),T.length&&(y.order=T),y.where=Object.assign({},y.where||{}),M(S)&&(null==r||r)){const t=ue.parse(O,S);if(!D(t.error))return null==e||e.error(new d(t.error.join(", "))),{count:0,records:[]};y.where=Object.assign(Object.assign({},y.where),null!==(p=t.value)&&void 0!==p?p:{})}else{const e=[];O.forEach(t=>{M(A)&&A.length&&e.push({[t]:{[le.like]:`%${A}%`}})}),e.length&&(y.where=Object.assign(Object.assign({},y.where),{[le.or]:[...e]}))}const P=this.model.count(Object.assign(Object.assign({},y),{distinct:!!y.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error),w=this.model.findAll(y).catch(this.error);yield Promise.allSettled([P,w]);const b=null!==(c=yield P)&&void 0!==c?c:0;let x=null!==(g=yield w)&&void 0!==g?g:[];const C={count:b};return x?(x=i?yield i(x):x,(F(null==t?void 0:t.limit)||0==b)&&(C.count=null!==(v=null==x?void 0:x.length)&&void 0!==v?v:0),null==e||e.prepare(s.OK,Object.assign(Object.assign({},C),{records:x})),Object.assign(Object.assign({},C),{records:x})):(null==e||e.error(new o),Object.assign(Object.assign({},C),{records:[]}))})}findOne(e){return xe(this,arguments,void 0,function*({ctx:e,options:t,callback:i}){var r,d,a,l,u;const p=Object.assign({},t||{}),{primaryKeyAttribute:c}=this.model,{[c]:g}=null!==(r=null==e?void 0:e.req.params)&&void 0!==r?r:{},v=this.getAttributes(null!==(d=null==p?void 0:p.attributes)&&void 0!==d?d:[]),y=e=>v.indexOf(e)>=0,{attributes:h}=null!==(l=null===(a=null==e?void 0:e.req)||void 0===a?void 0:a.query)&&void 0!==l?l:{};M(h)&&(p.attributes=h.split(";").filter(y));const m=yield this.model.findOne(Object.assign(Object.assign({},p),{where:Object.assign(Object.assign({},null!==(u=null==p?void 0:p.where)&&void 0!==u?u:{}),{[c]:g})})).catch(this.error);return m?(null==e||e.prepare(s.OK,i?yield i(m):m.toJSON()),m):m?(null==e||e.error(new o),null):(null==e||e.error(new n),null)})}getAttributes(e){return 0==this.attributes.length&&(this.attributes=this.filterAttributes(Object.keys(this.model.getAttributes()),this.filter)),this.filterAttributes(this.attributes,e)}update(e){return xe(this,arguments,void 0,function*({ctx:e,options:t,body:i,id:r}){var n,o,s,d,a,l;const u=Object.assign({},t||{}),{primaryKeyAttribute:p}=this.model,{[p]:c}=null!==(o=null===(n=null==e?void 0:e.req)||void 0===n?void 0:n.params)&&void 0!==o?o:{[p]:null!=r?r:0},[g]=null!==(l=yield this.model.update(Object.assign({},K({},null!==(d=null===(s=null==e?void 0:e.req)||void 0===s?void 0:s.body)&&void 0!==d?d:{},null!=i?i:{})),Object.assign(Object.assign(Object.assign({},u),{where:Object.assign(Object.assign({},null!==(a=null==u?void 0:u.where)&&void 0!==a?a:{}),{[p]:c}),individualHooks:!0}),{ctx:e})).catch(this.error))&&void 0!==l?l:[];return g?(null==e||e.success("OK"),!0):(null==e||e.success("Record not changed"),!1)})}name(){return this.model.tableName}}let gt=class UserService extends pt{getMetadata(e){return xe(this,void 0,void 0,function*(){var t;return Object.fromEntries((null!==(t=yield lt.findAll({where:{user_id:e}}).catch(this.error))&&void 0!==t?t:[]).map(e=>[e.key,e.value]))})}getProfile(e){return xe(this,void 0,void 0,function*(){var t;return Object.fromEntries((null!==(t=yield ut.findAll({where:{user_id:e}}).catch(this.error))&&void 0!==t?t:[]).map(e=>[e.key,e.value]))})}getGroups(e){return xe(this,void 0,void 0,function*(){var t;return(null!==(t=yield Qe.findAll({attributes:["key"],where:{state:!0},include:[{model:et,required:!0,where:{user_id:e}}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.key)})}getPermissions(e){return xe(this,void 0,void 0,function*(){var t;return(null!==(t=yield Xe.findAll({attributes:["key"],where:{state:!0},include:[{model:Ze,required:!0,include:[{model:Qe,required:!0,attributes:["id"],where:{state:!0},include:[{model:et,required:!0,where:{user_id:e}}]}]}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.key)})}};gt=Pe([he()],gt);class Application extends a{constructor(e,t){super(e,K({},{cert:Env.HTTP_CRT,cross:Env.API_HTTP_CROSS,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},key:Env.HTTP_KEY,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:B}},null!=t?t:{})),this.hash=new b(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 xe(this,void 0,void 0,function*(){yield Ce.sync(),yield this.migrations(Ce),yield H(this.controllers,e=>xe(this,void 0,void 0,function*(){C(e.sync)&&(yield e.sync(this))})),this.authService=new ct,this.userService=new gt,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new J({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>xe(this,void 0,void 0,function*(){t.url||(t.url=""),!(t.url.length<=1)&&t.url.replace(/\//g,"."),e.on("close",()=>{}),yield q(2e3),e.close()})))})}migrations(e){return xe(this,void 0,void 0,function*(){const t=[];yield H(Object.keys(e.models),i=>xe(this,void 0,void 0,function*(){var r;const n=e.models[i],o=n.version();if(!o)return;const[s,d]=null!==(r=yield dt.findOrCreate({where:{model:n.tableName},defaults:{model:n.tableName,version:""}}).catch(this.error))&&void 0!==r?r:[];s&&(d||s.version!=o)&&(s.version=o,yield s.save().catch(this.error),t.push(n))})),yield H(t,e=>xe(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}let vt=class BaseController extends Y{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 xe(this,void 0,void 0,function*(){i.auth&&i.user&&(i.user_agent?i.user_agent!=t&&i.regenerate(j):(i.user_agent=t,i.save(j))),e.next()})}sync(){return xe(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield H(this.permissions,i=>xe(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=$(e.replace(/_/g," ")," ");yield Xe.findOrCreate({where:{key:r},defaults:Object.assign({name:`${n} ${$(i," ")}`,key:r,tag:n},t)})}))})}};Pe([we(0,l()),we(1,u("user-agent")),we(2,p()),be("design:type",Function),be("design:paramtypes",[r,String,Object]),be("design:returntype",Promise)],vt.prototype,"session",null),vt=Pe([ye(Loggable)],vt);let yt=class ModelController extends vt{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"]}create(e){return xe(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return xe(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return xe(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return xe(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}sync(){return xe(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield H(this.permissions,i=>xe(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=$(e.replace(/_/g," ")," ");yield Xe.findOrCreate({where:{key:r},defaults:Object.assign({name:`${n} ${$(i," ")}`,key:r,tag:n},t)})})),this.service=new ModelService(this.model)})}update(e){return xe(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}};yt=Pe([c(vt)],yt);let ht=class AuditsController extends yt{constructor(){super(...arguments),this.model=rt}all(e,t,i){return xe(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:r,order:[["created_at","DESC"]]},limited:!0})})}get(e){return xe(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};Pe([g(),Me(),Ne(),we(0,l()),we(1,v("type")),we(2,v("table")),be("design:type",Function),be("design:paramtypes",[r,String,String]),be("design:returntype",Promise)],ht.prototype,"all",null),Pe([g("/:id"),Me(),Ne(),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],ht.prototype,"get",null),ht=Pe([y("/audits"),c(yt)],ht);let mt=class AuthController extends vt{constructor(e){super(),this.authService=e}login(e,i,r,n,o,s){return xe(this,void 0,void 0,function*(){var d;yield q(Env.API_SLEEP_AUTH);const a=yield it.findOne({where:{[le.or]:[{email:r},{username:r}]}}).catch(this.error);if(!a)return e.error(new t("Invalid credentials")),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const l=yield tt.findOne({where:{user_id:a.id,state:!0}}).catch(this.error);if(!l||!ge(n,l.value))return e.error(new t("Invalid credentials")),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const u=yield ze.findOne({where:{state:!0,user_id:a.id}}).catch(this.error);if(u)return e.error("ACTIVATION REQUIRED"),s.emit("auth.activation",{ctx:e,register:u,user:a}),void this.emit("auth.activation",{ctx:e,register:u,user:a});if(!a.state)return e.error(new t("Invalid credentials")),s.emit("auth.failure",{ctx:e,user:a}),void this.emit("auth.failure",{ctx:e,user:a});const{auth:p,token:c}=null!==(d=yield this.authService.create(a).catch(t=>{e.error(t),s.emit("auth.failure",{ctx:e}),this.emit("auth.failure",{ctx:e})}))&&void 0!==d?d:{};p&&c&&(p.user_agent=i,p.ip_address=e.getIp(),yield p.save().catch(this.error),Env.API_TOKEN_COOKIE_SET&&e.cookie(Env.API_TOKEN_COOKIE,c,{maxAge:o?Env.API_TOKEN_LIFETIME:void 0}),e.json({token:c}),s.emit("auth.login",{ctx:e,auth:p,user:a}),this.emit("auth.login",{ctx:e,auth:p,user:a}))})}logout(e,i,r,n){return xe(this,void 0,void 0,function*(){if(yield this.authService.destroy(i))return 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 xe(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 xe(this,void 0,void 0,function*(){const{groups:i,permissions:r,profile:n}=e.req;if(!i||!r)return e.error(new o);e.json(Object.assign(Object.assign({},G(["username","description"],t.toJSON())),{groups:i,permissions:r,profile:n}))})}};Pe([h("/login"),m(e=>({username:e.string().min(3).required(),password:e.string().min(5).required(),remember:e.boolean().parse().empty(!1)})),we(0,l()),we(1,u("user-agent")),we(2,_("username")),we(3,_("password")),we(4,_("remember")),we(5,E()),be("design:type",Function),be("design:paramtypes",[r,String,String,String,Boolean,Application]),be("design:returntype",Promise)],mt.prototype,"login",null),Pe([g("/logout"),Me(),we(0,l()),we(1,Le()),we(2,$e()),we(3,E()),be("design:type",Function),be("design:paramtypes",[r,Je,it,Application]),be("design:returntype",Promise)],mt.prototype,"logout",null),Pe([h("/renew"),m(e=>({token:e.string().required()})),we(0,l()),we(1,u("user-agent")),we(2,_("token")),we(3,E()),be("design:type",Function),be("design:paramtypes",[r,String,String,Application]),be("design:returntype",Promise)],mt.prototype,"renew",null),Pe([g(),Me(),we(0,l()),we(1,$e()),be("design:type",Function),be("design:paramtypes",[r,it]),be("design:returntype",Promise)],mt.prototype,"user",null),mt=Pe([y("/auth"),c(vt),we(0,me(ct)),be("design:paramtypes",[ct])],mt);let _t=class CrudController extends yt{constructor(){super(...arguments),this._crud={}}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}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return xe(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return xe(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}del(e){return xe(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return xe(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return xe(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return xe(this,void 0,void 0,function*(){if(this.CrudValidationCreate()==this._crud)return e.error(new o)})}validationUpdate(e){return xe(this,void 0,void 0,function*(){if(this.CrudValidationUpdate()==this._crud)return e.error(new o)})}};Pe([h(),Me(),ke(),f("validationCreate"),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],_t.prototype,"add",null),Pe([g(),Me(),Ne(),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],_t.prototype,"all",null),Pe([A("/:id"),Me(),je(),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],_t.prototype,"del",null),Pe([g("/:id"),Me(),Ne(),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],_t.prototype,"get",null),Pe([S("/:id"),Me(),Be(),f("validationUpdate"),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],_t.prototype,"set",null),Pe([we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],_t.prototype,"validationCreate",null),Pe([we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],_t.prototype,"validationUpdate",null),_t=Pe([c(yt)],_t);let Et=class FilesController extends vt{constructor(){super(...arguments),this.directory=Env.API_HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return xe(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)||!fe(i).isDirectory())return e.error(new n);let r=[];return r=Ae(i),r=r.map(e=>this.info(Te(i,e))),r=r.filter(V),Object.assign(Object.assign({},this.info(i)),{files:r})})}info(e){if(!Ee(e))return null;const t=fe(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 xe(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=$(e.replace(/_/g," ")," "),i={description:"",state:!0};yield H(this.permissions,r=>xe(this,void 0,void 0,function*(){const n=`${e}.${r}`;yield Xe.findOrCreate({where:{key:n},defaults:Object.assign({name:`${t} ${$(r," ")}`,key:n,tag:t},i)})}))})}};Pe([g("/path"),g("/path/*path"),Me(),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],Et.prototype,"files",null),Et=Pe([y("/files"),c(vt)],Et);let ft=class ForgotController extends vt{check(e,t){return xe(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.error(new n);i.secret=W(),yield i.save(),e.json({token:i.secret})})}forgot(e,t,i){return xe(this,void 0,void 0,function*(){yield q(Env.API_SLEEP_FORGOT);const r=t,o=yield it.findOne({where:{[le.or]:[{email:r},{username:t}]}}).catch(this.error);if(!o)return e.error(new n);const s=W(),d=Date.now()+6e4*Env.API_TOKEN_FORGOT,a=yield ot.create({token:s,timestamp:d,state:!0,user_id:o.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:a,user:o}),this.emit("forgot.send",{ctx:e,forgot:a,user:o})})}reset(e,t,i,r){return xe(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i)return e.error(new n);i.state=!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 xe(this,void 0,void 0,function*(){return yield ot.findOne({where:{token:e,state:!0},include:[{model:it,required:!0}]}).catch(this.error)})}};Pe([g("/check"),m(e=>({token:e.string().required()})),we(0,l()),we(1,_("token")),be("design:type",Function),be("design:paramtypes",[r,String]),be("design:returntype",Promise)],ft.prototype,"check",null),Pe([h(),m(e=>({username:e.string().min(4).required()})),we(0,l()),we(1,_("username")),we(2,E()),be("design:type",Function),be("design:paramtypes",[r,String,Application]),be("design:returntype",Promise)],ft.prototype,"forgot",null),Pe([h("/reset"),m(e=>({token:e.string().required(),password:e.string().min(5).required()})),we(0,l()),we(1,_("token")),we(2,_("password")),we(3,E()),be("design:type",Function),be("design:paramtypes",[r,String,String,Application]),be("design:returntype",Promise)],ft.prototype,"reset",null),ft=Pe([y("/forgot"),c(vt)],ft);let At=class GroupsController extends _t{constructor(){super(...arguments),this.model=Qe,this.schemaCreate={name:z.string().required(),description:z.string().empty(""),state:z.boolean().parse().required()},this.schemaUpdate={name:z.string().empty(),description:z.string().empty(),state:z.boolean().parse().empty()}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};At=Pe([y("/groups"),c(_t)],At);let St=class GroupsPermissionsController extends yt{constructor(){super(...arguments),this.model=Ze}all(e,t){return xe(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:Xe,required:!0}]},callback:e=>e.map(e=>e.permission)})})}me(e,t){return xe(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,i){return xe(this,void 0,void 0,function*(){const r=yield Qe.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new n);const o=r.id,s=[];yield H(i,t=>xe(this,void 0,void 0,function*(){var i;if(!(yield Xe.count({where:{id:t}})))return;const[r]=null!==(i=yield Ze.findOrCreate(Object.assign({where:{group_id:o,permission_id:t},defaults:{group_id:o,permission_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];r&&s.push(t)})),yield Ze.destroy(Object.assign({where:{group_id:o,permission_id:{[le.notIn]:s}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Pe([g("/:id/permissions"),Me(),Ne("groups"),we(0,l()),we(1,O("id")),be("design:type",Function),be("design:paramtypes",[r,String]),be("design:returntype",Promise)],St.prototype,"all",null),Pe([g("/permissions"),Me(),Ne("users"),we(0,l()),we(1,$e()),be("design:type",Function),be("design:paramtypes",[r,it]),be("design:returntype",Promise)],St.prototype,"me",null),Pe([S("/:id/permissions"),Me(),Be("groups"),m(e=>({permissions:e.array(e.string())})),we(0,l()),we(1,O("id")),we(2,_("permissions")),be("design:type",Function),be("design:paramtypes",[r,String,Array]),be("design:returntype",Promise)],St.prototype,"set",null),St=Pe([y("/groups"),c(yt)],St);let Ot=class LogsController extends yt{constructor(){super(...arguments),this.model=st,this.permissions=["read"]}all(e){return xe(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{order:[["created_at","DESC"]]},limited:!0})})}};Pe([g(),Me(),Ne(),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],Ot.prototype,"all",null),Ot=Pe([y("/logs"),c(yt)],Ot);let It=class PermissionsController extends _t{constructor(){super(...arguments),this.model=Xe,this.schemaCreate={name:z.string().required(),key:z.string().required(),tag:z.string().required(),description:z.string().empty(""),state:z.boolean().parse().required()},this.schemaUpdate={name:z.string().empty(),key:z.string().empty(),tag:z.string().empty(),description:z.string().empty(),state:z.boolean().parse().empty()}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};It=Pe([y("/permissions"),c(_t)],It);let Tt=class RegisterController extends vt{register(e,t,i){return xe(this,void 0,void 0,function*(){yield q(Env.API_SLEEP_REGISTRY);const{name:r,date:n,email:s,username:d,password:a,confirm:l}=t,u=d||s,p=x(a);if(yield it.count({where:{[le.or]:[{email:s},{username:u}]}}).catch(this.error))return e.error("INVALID EMAIL OR USERNAME");if(p!=x(l))return e.error("INVALID PASSWORD");const c=yield it.create({name:r,email:s,username:u,password:p,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!c)return e.error(new o);const g=yield ze.create({token:yield this.getId(),user_id:c.id,state:!0}).catch(this.error);if(!g)return yield c.destroy().catch(this.error),e.error(new o);e.success("OK"),i.emit("register.user",{ctx:e,register:g,user:c}),this.emit("register.user",{ctx:e,register:g,user:c})})}confirm(e,t,i){return xe(this,void 0,void 0,function*(){const r=yield ze.findOne({where:{token:t,state:!0},include:[{model:it,required:!0}]}).catch(this.error);if(!r)return e.error(new n);r.state=!1,yield r.save().catch(this.error),r.user.state=!0,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 xe(this,void 0,void 0,function*(){const r=t,o=yield ze.findOne({where:{state:!0},include:[{model:it,required:!0,where:{[le.or]:[{email:r},{username:t}]}}]}).catch(this.error);if(!o)return e.error(new n);e.success("OK"),i.emit("register.send",{ctx:e,register:o,user:o.user}),this.emit("register.send",{ctx:e,register:o,user:o.user})})}getId(){return xe(this,void 0,void 0,function*(){const e=B();return(yield ze.count({where:{token:e}}))?this.getId():e})}};Pe([h(),m(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()})),we(0,l()),we(1,_()),we(2,E()),be("design:type",Function),be("design:paramtypes",[r,Object,Application]),be("design:returntype",Promise)],Tt.prototype,"register",null),Pe([h("/confirm"),m(e=>({token:e.string().required()})),we(0,l()),we(1,_("token")),we(2,E()),be("design:type",Function),be("design:paramtypes",[r,String,Application]),be("design:returntype",Promise)],Tt.prototype,"confirm",null),Pe([h("/send"),m(e=>({username:e.string().min(4).required()})),we(0,l()),we(1,_("username")),we(2,E()),be("design:type",Function),be("design:paramtypes",[r,String,Application]),be("design:returntype",Promise)],Tt.prototype,"send",null),Tt=Pe([y("/register"),c(vt)],Tt);let Pt=class SetupController extends vt{setup(e){return xe(this,void 0,void 0,function*(){var t;if(yield it.count())return e.success("OK");const i=W(),r=yield it.create({name:"Admin",email:"admin@localhost",username:"admin",password:x("admin"+i),salt:i,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},{ctx:e}));yield tt.create({value:"admin",state:!0,user_id:r.id});const n=yield Qe.create(Object.assign({name:"Admin"},{description:"API CORE",state:!0}),Object.assign({},{ctx:e}));yield et.create({user_id:r.id,group_id:n.id},Object.assign({},{ctx:e}));const o=null!==(t=yield Xe.findAll({where:{state:!0}}).catch(this.error))&&void 0!==t?t:[];yield H(o,t=>xe(this,void 0,void 0,function*(){yield Ze.create({group_id:n.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}};Pe([g(),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],Pt.prototype,"setup",null),Pt=Pe([y("/setup"),c(vt)],Pt);let wt=class UsersController extends yt{constructor(){super(),this.model=it,this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&Ee(Env.API_HTTP_PUBLIC)&&!Ee(this.path)&&Se(this.path)}avatar(e,t){return xe(this,void 0,void 0,function*(){var i,r;const n=e.getFiles();if(n.file&&n.file.length){const{filename:s,path:d}=null!==(i=n.file[0])&&void 0!==i?i:{};if(s){const[i]=null!==(r=yield ut.findOrCreate(Object.assign({where:{key:"avatar",user_id:t.id},defaults:{key:"avatar",user_id:t.id}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];if(!i)return Oe(d).isFile()&&Ie(d),e.error(new o);const n=this.path+"/"+i.value;if(Ee(n)&&Oe(n).isFile()&&Ie(n),i.value=s,yield i.save(Object.assign({},{ctx:e})).catch(this.error))return e.success("OK")}}e.success("Record not Changed")})}token_new(){return xe(this,void 0,void 0,function*(){var e;const t=B();return(null!==(e=yield this.model.count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(e){return xe(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return xe(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}del(e,t,i){return xe(this,void 0,void 0,function*(){if(i.id.toString()==t)return e.error(new n);yield this.delete({ctx:e})})}get(e){return xe(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return xe(this,void 0,void 0,function*(){yield this.update({ctx:e})})}};Pe([h("/avatar"),Me(),I({file:{count:1,path:`${Env.API_HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),we(0,l()),we(1,$e()),be("design:type",Function),be("design:paramtypes",[r,it]),be("design:returntype",Promise)],wt.prototype,"avatar",null),Pe([h(),Me(),ke(),m(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)})),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],wt.prototype,"add",null),Pe([g(),Me(),Ne(),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],wt.prototype,"all",null),Pe([A("/:id"),Me(),je(),we(0,l()),we(1,O("id")),we(2,$e()),be("design:type",Function),be("design:paramtypes",[r,String,it]),be("design:returntype",Promise)],wt.prototype,"del",null),Pe([g("/:id"),Me(),Ne(),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],wt.prototype,"get",null),Pe([S("/:id"),Me(),Be(),m(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()})),we(0,l()),be("design:type",Function),be("design:paramtypes",[r]),be("design:returntype",Promise)],wt.prototype,"set",null),wt=Pe([y("/users"),c(yt),be("design:paramtypes",[])],wt);let bt=class UsersGroupsController extends yt{constructor(){super(...arguments),this.model=et}all(e,t){return xe(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:Qe,required:!0}]},callback:e=>e.map(e=>e.group)})})}me(e,t){return xe(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,i){return xe(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 o=r.id,s=[];yield H(i,t=>xe(this,void 0,void 0,function*(){var i;if(!(yield Qe.count({where:{id:t}})))return;const[r]=null!==(i=yield et.findOrCreate(Object.assign({where:{user_id:o,group_id:t},defaults:{user_id:o,group_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];r&&s.push(t)})),yield et.destroy(Object.assign({where:{user_id:o,group_id:{[le.notIn]:s}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Pe([g("/:id/groups"),Me(),Ne("users"),we(0,l()),we(1,O("id")),be("design:type",Function),be("design:paramtypes",[r,String]),be("design:returntype",Promise)],bt.prototype,"all",null),Pe([g("/groups"),Me(),Ne("users"),we(0,l()),we(1,$e()),be("design:type",Function),be("design:paramtypes",[r,it]),be("design:returntype",Promise)],bt.prototype,"me",null),Pe([S("/:id/groups"),Me(),Be("users"),m(e=>({groups:e.array(e.string())})),we(0,l()),we(1,O("id")),we(2,_("groups")),be("design:type",Function),be("design:paramtypes",[r,String,Array]),be("design:returntype",Promise)],bt.prototype,"set",null),bt=Pe([y("/users"),c(yt)],bt);export{Application,We as Audit,rt as AuditModel,ht as AuditsController,mt as AuthController,ct as AuthService,vt as BaseController,ke as CanCreate,je as CanDelete,Ne as CanRead,Be as CanUpdate,Config,nt as ConfigModel,_t as CrudController,Env,Et as FilesController,ft as ForgotController,ot as ForgotModel,Qe as GroupModel,Ze as GroupPermissionModel,At as GroupsController,St as GroupsPermissionsController,Ke as HasGroups,Ue as HasPermissions,Me as IsAuthenticated,Log,st as LogModel,Loggable,Ot as LogsController,dt as MigrationModel,yt as ModelController,ModelService,Xe as PermissionModel,It as PermissionsController,Tt as RegisterController,ze as RegisterModel,Le as ReqAuth,Fe as ReqGroup,He as ReqGroups,qe as ReqPermission,Ye as ReqPermissions,$e as ReqUser,pt as Service,at as SessionModel,SessionStore,Pt as SetupController,Je as UserAuthModel,et as UserGroupModel,lt as UserMetadataModel,it as UserModel,tt as UserPasswordModel,ut as UserProfileModel,gt as UserService,wt as UsersController,bt as UsersGroupsController,Re as canFactory,Ce as sequelize};
|
|
7
|
+
import{Use as e,UnauthorizedError as t,parameterFactory as i,Context as r,NotFoundError as n,InternalServerError as s,ValidationError as o,Status as d,Application as a,Ctx as l,Headers as u,Session as c,Extends as p,Get as g,Query as v,Controller as y,Post as h,Validate as m,Body as _,App as f,Middleware as E,Delete as A,Put as O,Params as S,Upload as T}from"@andrewcaires/express";import{Env as P,Log as I,LogColor as w,Hash as b,sha256 as x}from"@andrewcaires/node";import{isUndefined as C,isFunction as D,includesArray as R,getConstructor as j,noop as k,loop as N,uuidv7 as B,isString as K,merge as U,isArray as L,clamp as M,isNumber as F,forEachSeries as H,upperCamelCase as q,sleep as Y,EventEmitter as $,denied as G,isDef as V,uniqueID as J,Validation as W,uniqueArray as z,map as X}from"@andrewcaires/utils.js";import{WebSocketServer as Z}from"ws";import{Sequelize as Q,Hooks as ee,Column as te,Association as ie,Database as re,ModelName as ne,Version as se,Model as oe,Unique as de,HasMany as ae,Value as le,DefaultValue as ue,Op as ce,Where as pe}from"@andrewcaires/sequelize";import{config as ge}from"dotenv";import{hashSync as ve,compareSync as ye}from"bcrypt";import{Store as he}from"express-session";import me from"jsonwebtoken";import{Trait as _e,Inject as fe}from"@andrewcaires/decorator";import{existsSync as Ee,statSync as Ae,readdirSync as Oe,mkdirSync as Se,lstatSync as Te,rmSync as Pe}from"fs";import{join as Ie}from"path";function we(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 be(e,t){return function(i,r){t(i,r,e)}}function xe(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function Ce(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 De;"function"==typeof SuppressedError&&SuppressedError,ge({quiet:!0});class Env extends P{}De=Env,Env.BASE_NAME=De.getString("BASE_NAME",""),Env.CONSOLE_ERROR=De.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=De.getString("DATABASE_URI","",!0),Env.DATABASE_LOG=De.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=De.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=De.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=De.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CRT=De.getFile("HTTP_CRT"),Env.HTTP_KEY=De.getFile("HTTP_KEY"),Env.SLEEP_AUTH=De.getMs("SLEEP_AUTH","2s"),Env.SLEEP_FORGOT=De.getMs("SLEEP_FORGOT","5s"),Env.SLEEP_REGISTRY=De.getMs("SLEEP_REGISTRY","5s"),Env.TOKEN_CRT=De.getFile("TOKEN_CRT"),Env.TOKEN_KEY=De.getFile("TOKEN_KEY"),Env.TOKEN_TTL=De.getMs("TOKEN_TTL","1d"),Env.API_BODYPARSER_STRICT=De.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=De.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=De.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=De.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_PORT=De.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=De.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_CROSS=De.getBool("API_HTTP_CROSS",!1),Env.API_HTTP_HYBRID=De.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=De.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=De.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=De.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=De.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=De.getString("API_KEY_HEADER","x-api-key"),Env.API_MODEL_LIMIT=De.getInt("API_MODEL_LIMIT",10),Env.API_MODEL_LIMIT_MAX=De.getInt("API_MODEL_LIMIT_MAX",500),Env.API_SESSION_NAME=De.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=De.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=De.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=De.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=De.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_TOKEN_FORGOT=De.getMs("API_TOKEN_FORGOT","1d"),Env.API_TOKEN_HEADER=De.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_HEADER_KEY=De.getString("API_TOKEN_HEADER","bearer"),Env.API_TOKEN_RENEW=De.getMs("API_TOKEN_RENEW","1d"),Env.API_USER_HISTORY=De.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=De.getBool("API_WEBSOCKET_START",!1);const Re=new Q({uri:Env.DATABASE_URI,logging:!!Env.DATABASE_LOG&&(e=>I.console(w.Magenta,"sql",e)),prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE}),je=i=>r=>(n,s,o)=>{e(e=>Ce(void 0,void 0,void 0,function*(){var n;let s=null!=r?r:"";C(r)&&(s=D(e.controller.name)?e.controller.name():null===(n=e.controller.constructor)||void 0===n?void 0:n.name);const{permissions:o}=e.req;if((null!=o?o:[]).includes(`${s}.${i}`))return e.next();e.error(new t("Access Denied"))}))(n,s,o)},ke=je("create"),Ne=je("delete"),Be=je("read"),Ke=je("update"),Ue=(...i)=>(r,n,s)=>{e(e=>Ce(void 0,void 0,void 0,function*(){const{groups:r}=e.req;if(R(i,null!=r?r:[]))return e.next();e.error(new t("Access Denied"))}))(r,n,s)},Le=(...i)=>(r,n,s)=>{e(e=>Ce(void 0,void 0,void 0,function*(){const{permissions:r}=e.req;if(R(i,null!=r?r:[]))return e.next();e.error(new t("Access Denied"))}))(r,n,s)},Me=()=>(i,r,n)=>{e(e=>Ce(void 0,void 0,void 0,function*(){yield(e=>Ce(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.API_TOKEN_HEADER_KEY} ${c}`;const[p,g]=null!==(n=null===(r=d||c)||void 0===r?void 0:r.split(" "))&&void 0!==n?n:["",""];if(!(u||g&&p.toLowerCase()==Env.API_TOKEN_HEADER_KEY))return e.error(new t("Invalid token"));const{authService:v,userService:y}=e.app,{auth:h,user:m}=null!==(s=yield(u?v.key(u.toString()):v.user(g)).catch(t=>{e.error(t)}))&&void 0!==s?s:{};if(h&&m){if(!u&&h.user_agent&&h.user_agent!=a)return e.error(new t("Invalid token"));e.req.auth=h,e.req.user=m,e.req.groups=yield y.getGroups(m.id),e.req.permissions=yield y.getPermissions(m.id),e.req.profile=yield y.getProfile(m.id),e.next()}}))(e)}))(i,r,n)},Fe=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),He=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)}),qe=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.groups)&&void 0!==i?i:[]}),Ye=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)}),$e=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,g;const v=i.ctx instanceof r?i.ctx:null,y=null!==(d=null!==(o=null===(s=null===(n=null==v?void 0:v.req)||void 0===n?void 0:n.user)||void 0===s?void 0:s.id)&&void 0!==o?o:i.user_id)&&void 0!==d?d:null,h={type:e,model:null!==(a=null==t?void 0:t.getTableName())&&void 0!==a?a:null,app_name:null!==(l=Env.BASE_NAME)&&void 0!==l?l:"",state:!0,user_id:y};return v?Object.assign(Object.assign({},h),{full_url:null!==(u=null==v?void 0:v.getUrl())&&void 0!==u?u:"",ip_address:null!==(c=null==v?void 0:v.getIp())&&void 0!==c?c:"",user_agent:null!==(g=null===(p=null==v?void 0:v.req)||void 0===p?void 0:p.headers["user-agent"])&&void 0!==g?g:""}):h},Je={afterCreate:(e,t)=>Ce(void 0,void 0,void 0,function*(){const i=j(e),{primaryKeyAttribute:r}=null!=i?i:{};yield st.create(Object.assign(Object.assign({},Ve("CREATE",i,t)),{record:r?e.getDataValue(r):null,data:e.toJSON()})).catch(I.catch)}),afterUpdate:(e,t)=>Ce(void 0,void 0,void 0,function*(){const i=j(e),{primaryKeyAttribute:r}=null!=i?i:{},n={},s=e.changed();s&&s.forEach(t=>n[t]=e.getDataValue(t)),yield st.create(Object.assign(Object.assign({},Ve("UPDATE",i,t)),{record:r?e.getDataValue(r):null,data:n,previously:e.previous()})).catch(I.catch)}),afterDestroy:(e,t)=>Ce(void 0,void 0,void 0,function*(){const i=j(e),{primaryKeyAttribute:r}=null!=i?i:{};yield st.create(Object.assign(Object.assign({},Ve("DELETE",i,t)),{record:r?e.getDataValue(r):null,data:e.toJSON()})).catch(I.catch)})},We=e=>(C(e)&&(e=Env.DATABASE_AUDIT),ee(e?Je:{}));let ze=class RegisterModel extends oe{};we([te.UUID(7),xe("design:type",String)],ze.prototype,"id",void 0),we([te.String(),xe("design:type",String)],ze.prototype,"secret",void 0),we([te.FullDate(),xe("design:type",Number)],ze.prototype,"expired_at",void 0),we([te.Boolean(),xe("design:type",Boolean)],ze.prototype,"state",void 0),we([te.CreatedAt(),xe("design:type",Date)],ze.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],ze.prototype,"updated_at",void 0),we([te.DeletedAt(),xe("design:type",Object)],ze.prototype,"deleted_at",void 0),we([ie.BelongsTo(()=>nt),xe("design:type",String)],ze.prototype,"user_id",void 0),ze=we([re(Re),ne("register"),se("5.0.0")],ze);let Xe=class UserAuthModel extends oe{};we([te.UUID(7),xe("design:type",String)],Xe.prototype,"id",void 0),we([te.String(),xe("design:type",String)],Xe.prototype,"secret",void 0),we([te.String(),xe("design:type",String)],Xe.prototype,"ip_address",void 0),we([te.String(),xe("design:type",String)],Xe.prototype,"user_agent",void 0),we([te.FullDate(),xe("design:type",Object)],Xe.prototype,"revoked_at",void 0),we([te.CreatedAt(),xe("design:type",Date)],Xe.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],Xe.prototype,"updated_at",void 0),we([te.DeletedAt(),xe("design:type",Object)],Xe.prototype,"deleted_at",void 0),we([ie.BelongsTo(()=>nt),xe("design:type",String)],Xe.prototype,"user_id",void 0),Xe=we([re(Re),ne("users_auth"),se("5.0.0")],Xe);let Ze=class PermissionModel extends oe{};we([te.UUID(7),xe("design:type",String)],Ze.prototype,"id",void 0),we([te.String(),xe("design:type",String)],Ze.prototype,"name",void 0),we([te.String(),de(!0),xe("design:type",String)],Ze.prototype,"key",void 0),we([te.String(),xe("design:type",String)],Ze.prototype,"tags",void 0),we([te.Text(),xe("design:type",String)],Ze.prototype,"description",void 0),we([te.Boolean(),xe("design:type",Boolean)],Ze.prototype,"state",void 0),we([te.CreatedAt(),xe("design:type",Date)],Ze.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],Ze.prototype,"updated_at",void 0),we([te.DeletedAt(),xe("design:type",Object)],Ze.prototype,"deleted_at",void 0),we([ae(()=>Qe,"permission_id"),xe("design:type",Array)],Ze.prototype,"groups_permissions",void 0),Ze=we([re(Re),ne("permission"),We(),se("5.0.1")],Ze);let Qe=class GroupPermissionModel extends oe{};we([te.CreatedAt(),xe("design:type",Date)],Qe.prototype,"created_at",void 0),we([ie.BelongsTo(()=>et),xe("design:type",String)],Qe.prototype,"group_id",void 0),we([ie.BelongsTo(()=>Ze),xe("design:type",String)],Qe.prototype,"permission_id",void 0),Qe=we([re(Re),ne("groups_permissions"),We(),se("5.0.0")],Qe);let et=class GroupModel extends oe{};we([te.UUID(7),xe("design:type",String)],et.prototype,"id",void 0),we([te.String(),xe("design:type",String)],et.prototype,"name",void 0),we([te.String(),xe("design:type",String)],et.prototype,"key",void 0),we([te.String(),xe("design:type",String)],et.prototype,"tags",void 0),we([te.Text(),xe("design:type",String)],et.prototype,"description",void 0),we([te.Boolean(),xe("design:type",Boolean)],et.prototype,"state",void 0),we([te.CreatedAt(),xe("design:type",Date)],et.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],et.prototype,"updated_at",void 0),we([te.DeletedAt(),xe("design:type",Object)],et.prototype,"deleted_at",void 0),we([ie.HasMany(()=>tt,"group_id"),xe("design:type",Array)],et.prototype,"users_groups",void 0),we([ie.HasMany(()=>Qe,"group_id"),xe("design:type",Array)],et.prototype,"groups_Permission",void 0),et=we([re(Re),ne("group"),We(),se("5.0.1")],et);let tt=class UserGroupModel extends oe{};we([te.CreatedAt(),xe("design:type",Date)],tt.prototype,"created_at",void 0),we([ie.BelongsTo(()=>et),xe("design:type",String)],tt.prototype,"group_id",void 0),we([ie.BelongsTo(()=>nt),xe("design:type",String)],tt.prototype,"user_id",void 0),tt=we([re(Re),ne("users_groups"),We(),se("5.0.0")],tt);let it=class UserPasswordModel extends oe{};we([te.UUID(7),xe("design:type",String)],it.prototype,"id",void 0),we([te.String(),le(e=>ve(e.value,12)),xe("design:type",String)],it.prototype,"value",void 0),we([te.Boolean(),xe("design:type",Boolean)],it.prototype,"state",void 0),we([te.CreatedAt(),xe("design:type",Date)],it.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],it.prototype,"updated_at",void 0),we([te.DeletedAt(),xe("design:type",Object)],it.prototype,"deleted_at",void 0),we([ie.BelongsTo(()=>nt),xe("design:type",String)],it.prototype,"user_id",void 0),it=we([re(Re),ne("users_password"),We(),se("5.0.0")],it);let rt=class UserProfileModel extends oe{};we([te.UUID(7),xe("design:type",String)],rt.prototype,"id",void 0),we([te.Json(),ue({}),xe("design:type",Object)],rt.prototype,"data",void 0),we([te.CreatedAt(),xe("design:type",Date)],rt.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],rt.prototype,"updated_at",void 0),we([te.DeletedAt(),xe("design:type",Object)],rt.prototype,"deleted_at",void 0),we([ie.BelongsTo(()=>nt),xe("design:type",String)],rt.prototype,"user_id",void 0),rt=we([re(Re),ne("users_profile"),We(),se("5.0.1")],rt);let nt=class UserModel extends oe{};we([te.UUID(7),xe("design:type",String)],nt.prototype,"id",void 0),we([te.String(),xe("design:type",String)],nt.prototype,"name",void 0),we([te.String(),xe("design:type",String)],nt.prototype,"email",void 0),we([te.String(),xe("design:type",String)],nt.prototype,"username",void 0),we([te.Text(),xe("design:type",String)],nt.prototype,"description",void 0),we([te.Boolean(),xe("design:type",Boolean)],nt.prototype,"state",void 0),we([te.CreatedAt(),xe("design:type",Date)],nt.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],nt.prototype,"updated_at",void 0),we([te.DeletedAt(),xe("design:type",Object)],nt.prototype,"deleted_at",void 0),we([ie.HasMany(()=>st,"user_id"),xe("design:type",Array)],nt.prototype,"audits",void 0),we([ie.HasMany(()=>Xe,"user_id"),xe("design:type",Array)],nt.prototype,"users_auths",void 0),we([ie.HasMany(()=>ze,"user_id"),xe("design:type",Array)],nt.prototype,"registers",void 0),we([ie.HasMany(()=>tt,"user_id"),xe("design:type",Array)],nt.prototype,"users_groups",void 0),we([ie.HasMany(()=>it,"user_id"),xe("design:type",Array)],nt.prototype,"users_passwords",void 0),we([ie.HasMany(()=>rt,"user_id"),xe("design:type",Array)],nt.prototype,"users_profiles",void 0),nt=we([re(Re),ne("user"),We(),se("5.0.0")],nt);let st=class AuditModel extends oe{};we([te.UUID(7),xe("design:type",String)],st.prototype,"id",void 0),we([te.Enum("CREATE","DELETE","UPDATE"),xe("design:type",String)],st.prototype,"type",void 0),we([te.String(),xe("design:type",String)],st.prototype,"model",void 0),we([te.String(),xe("design:type",String)],st.prototype,"record",void 0),we([te.Json(),xe("design:type",Object)],st.prototype,"data",void 0),we([te.Json(),xe("design:type",Object)],st.prototype,"previously",void 0),we([te.Text(),xe("design:type",String)],st.prototype,"full_url",void 0),we([te.String(),xe("design:type",String)],st.prototype,"ip_address",void 0),we([te.String(),xe("design:type",String)],st.prototype,"user_agent",void 0),we([te.String(),xe("design:type",String)],st.prototype,"app_name",void 0),we([te.Boolean(),xe("design:type",Boolean)],st.prototype,"state",void 0),we([te.CreatedAt(),xe("design:type",Date)],st.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],st.prototype,"updated_at",void 0),we([te.DeletedAt(),xe("design:type",Object)],st.prototype,"deleted_at",void 0),we([ie.BelongsTo(()=>nt),xe("design:type",String)],st.prototype,"user_id",void 0),st=we([re(Re),ne("audit"),se("5.0.1")],st);let ot=class ConfigModel extends oe{};we([te.UUID(7),xe("design:type",String)],ot.prototype,"id",void 0),we([te.String(),xe("design:type",String)],ot.prototype,"key",void 0),we([te.String(),xe("design:type",String)],ot.prototype,"value",void 0),we([te.CreatedAt(),xe("design:type",Date)],ot.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],ot.prototype,"updated_at",void 0),ot=we([re(Re),ne("configs"),se("5.0.0")],ot);let dt=class ForgotModel extends oe{};we([te.UUID(7),xe("design:type",String)],dt.prototype,"id",void 0),we([te.String(),xe("design:type",String)],dt.prototype,"secret",void 0),we([te.FullDate(),xe("design:type",Number)],dt.prototype,"expired_at",void 0),we([te.Boolean(),xe("design:type",Boolean)],dt.prototype,"state",void 0),we([te.CreatedAt(),xe("design:type",Date)],dt.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],dt.prototype,"updated_at",void 0),we([te.DeletedAt(),xe("design:type",Object)],dt.prototype,"deleted_at",void 0),we([ie.BelongsTo(()=>nt),xe("design:type",String)],dt.prototype,"user_id",void 0),dt=we([re(Re),ne("forgot"),se("5.0.0")],dt);let at=class LogModel extends oe{};we([te.UUID(7),xe("design:type",String)],at.prototype,"id",void 0),we([te.Enum("info","warn","error"),ue("info"),xe("design:type",String)],at.prototype,"level",void 0),we([te.Text(),xe("design:type",String)],at.prototype,"message",void 0),we([te.String(),xe("design:type",String)],at.prototype,"source",void 0),we([te.CreatedAt(),xe("design:type",Date)],at.prototype,"created_at",void 0),at=we([re(Re),ne("log"),se("5.0.0")],at);let lt=class MigrationModel extends oe{};we([te.String(),xe("design:type",String)],lt.prototype,"model",void 0),we([te.String(),xe("design:type",String)],lt.prototype,"version",void 0),we([te.CreatedAt(),xe("design:type",Date)],lt.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],lt.prototype,"updated_at",void 0),lt=we([re(Re),ne("migration"),se("5.0.0")],lt);let ut=class SessionModel extends oe{};we([te.String(),xe("design:type",String)],ut.prototype,"session",void 0),we([te.Text(),xe("design:type",String)],ut.prototype,"json",void 0),we([te.BigInt(),xe("design:type",Number)],ut.prototype,"expired",void 0),we([te.CreatedAt(),xe("design:type",Date)],ut.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],ut.prototype,"updated_at",void 0),ut=we([re(Re),ne("session"),se("5.0.0")],ut);let ct=class UserMetadataModel extends oe{};we([te.UUID(7),xe("design:type",String)],ct.prototype,"id",void 0),we([te.Json(),ue({}),xe("design:type",Object)],ct.prototype,"data",void 0),we([te.CreatedAt(),xe("design:type",Date)],ct.prototype,"created_at",void 0),we([te.UpdatedAt(),xe("design:type",Date)],ct.prototype,"updated_at",void 0),we([te.DeletedAt(),xe("design:type",Object)],ct.prototype,"deleted_at",void 0),we([ie.BelongsTo(()=>nt),xe("design:type",String)],ct.prototype,"user_id",void 0),ct=we([re(Re),ne("users_metadata"),We(),se("5.0.1")],ct);class Log{static error(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,i)})}static info(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,i)})}static warn(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,i)})}static writeRaw(e,t,i,r){return Ce(this,void 0,void 0,function*(){var n;r&&I.console(null!==(n=this.colors[e])&&void 0!==n?n:w.White,e,t),Re&&(yield at.create({level:e,message:t,source:null!=i?i:""}).catch(I.catch))})}}Log.colors={error:w.Red,info:w.Cyan,warn:w.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 Ce(this,void 0,void 0,function*(){var t;const i=null!==(t=yield ot.findAll({where:(null==e?void 0:e.length)?{key:{[ce.in]:e}}:{}}).catch(this.error))&&void 0!==t?t:[];return Object.fromEntries(i.map(e=>[e.key,e.value]))})}static del(e){return Ce(this,void 0,void 0,function*(){return((yield ot.destroy({where:{key:e}}).catch(this.error))||0)>0})}static get(e){return Ce(this,arguments,void 0,function*(e,t=""){const[i]=(yield ot.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return i?i.value:t})}static set(e,t){return Ce(this,void 0,void 0,function*(){const[i,r]=(yield ot.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 he{constructor(){super(),this.all=e=>Ce(this,void 0,void 0,function*(){e=e||k;const t=yield ut.findAll({attributes:["session"],where:{expired:{[ce.gte]:Date.now()}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.session)),e()}),this.clear=e=>Ce(this,void 0,void 0,function*(){yield ut.destroy().catch(k),e&&e()}),this.destroy=(e,t)=>Ce(this,void 0,void 0,function*(){yield ut.destroy({where:{session:e}}).catch(k),t&&t()}),this.expired=()=>Ce(this,void 0,void 0,function*(){yield ut.destroy({where:{expired:{[ce.lt]:Date.now()}}}).catch(k)}),this.get=(e,t)=>Ce(this,void 0,void 0,function*(){t=t||k;const i=yield ut.findOne({where:{session:e,expired:{[ce.gte]:Date.now()}}}).catch(e=>(t(e),null));if(i){const e=JSON.parse(i.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield i.destroy().catch(k),void t(null)}return void t(null,e)}t(null)}),this.length=e=>Ce(this,void 0,void 0,function*(){e&&e(null,(yield ut.count().catch(k))||0)}),this.set=(e,t,i)=>Ce(this,void 0,void 0,function*(){i=i||k;const r=Date.now()+Env.API_SESSION_LIFETIME,n=JSON.stringify(t),[s,o]=(yield ut.findOrCreate({where:{session:e},defaults:{session:e,json:n,expired:r}}).catch(k))||[];s&&(o||(s.json=n,s.expired=r,yield s.save().catch(k))),i()}),this.loop=N(this.expired,3e4),this.loop.start()}}let pt=class Service{};pt=we([_e(Loggable)],pt);class AuthService extends pt{create(e){return Ce(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new n("TOKEN_KEY not found");const{id:t}=e,i=B(),r=yield Xe.create({secret:i,user_id:t}).catch(this.error);if(!r)throw new s;return{auth:r,token:me.sign({id:t,secret:i},Env.TOKEN_KEY,this.options())}})}destroy(e){return Ce(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return Ce(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 nt.findOne({where:{id:r,state:!0}}).catch(this.error);if(e){const t=yield Xe.findOne({where:{secret:s,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at){t.secret=B(),yield t.save().catch(this.error);return{auth:t,token:me.sign({id:r,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t("Invalid token")})}user(e){return Ce(this,void 0,void 0,function*(){const{decode:i}=yield this.verify(e);if(!i)throw new t("Invalid token");const{id:r,secret:n}=i;if(r&&n){const e=yield nt.findOne({where:{id:r,state:!0}}).catch(this.error);if(e){const t=yield Xe.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 Ce(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:me.verify(e,Env.TOKEN_CRT,{clockTolerance:i})}}catch(e){throw new t("Invalid token")}})}key(e){return Ce(this,void 0,void 0,function*(){if(!e)throw new t("Invalid token");const i=yield nt.findOne({where:{token:e,state:!0}}).catch(this.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield Xe.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")})}}class ModelService extends pt{constructor(e,t){super(),this.attributes=[],this.filter=[],this.permissions=[],this.model=e,(null==t?void 0:t.attributes)&&(this.filter=t.attributes),(null==t?void 0:t.permissions)&&(this.filter=t.permissions)}countAll(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t}){var i,r,n,s,a;const l=Object.assign({},t||{}),{search:u,where:c}=null!==(r=null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.query)&&void 0!==r?r:{};l.attributes=[];const p=[];p.length&&(l.order=p),l.where=Object.assign({},l.where||{});const g=this.getAttributes(null!==(n=null==l?void 0:l.attributes)&&void 0!==n?n:[]);if(K(c)){const t=pe.parse(g,c);if(!C(t.error))return null==e||e.error(new o(t.error.join(", "))),0;l.where=Object.assign(Object.assign({},l.where),null!==(s=t.value)&&void 0!==s?s:{})}else{const e=[];g.forEach(t=>{K(u)&&u.length&&e.push({[t]:{[ce.like]:`%${u}%`}})}),e.length&&(l.where=Object.assign(Object.assign({},l.where),{[ce.or]:[...e]}))}const v=null!==(a=yield this.model.count(Object.assign(Object.assign({},l),{distinct:!!l.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error))&&void 0!==a?a:0;return null==e||e.prepare(d.OK,{count:v}),v})}create(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t,body:i}){var r,n;const o=Object.assign({},t||{}),a=yield this.model.create(Object.assign({},U({},null!==(n=null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.body)&&void 0!==n?n:{},null!=i?i:{})),Object.assign(Object.assign({},o),{ctx:e})).catch(this.error);if(a){const{primaryKeyAttribute:t}=this.model;return null==e||e.prepare(d.OK,{[t]:a.getDataValue(t)}),a}return null==e||e.error(new s),null})}delete(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t,id:i}){var r,o,d;const a=Object.assign({},t||{}),{primaryKeyAttribute:l}=this.model,{[l]:u}=null!==(o=null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.params)&&void 0!==o?o:{[l]:null!=i?i:0};if(!u)return null==e||e.error(new s),0;const c=yield this.model.destroy(Object.assign(Object.assign(Object.assign({},a),{where:Object.assign(Object.assign({},null!==(d=a.where)&&void 0!==d?d:{}),{[l]:u}),individualHooks:!0}),{ctx:e})).catch(this.error);return c?(null==e||e.success("OK"),c):(null==e||e.error(new n),0)})}filterAttributes(e,t){if(L(t))return t.length?t.map(t=>K(t)&&-1!=e.indexOf(t)?t:void 0).filter(K):e;const{exclude:i,include:r}=t,n=C(r)?e:r.map(t=>K(t)&&-1!=e.indexOf(t)?t:void 0).filter(K),s=null!=i?i:[];return s.length?n.filter(e=>-1==s.indexOf(e)):n}findAll(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t,callback:i,limited:r}){var n,a,l,u,c,p,g;const v=Object.assign({},t||{}),{limit:y,offset:h,asc:m,desc:_,search:f,select:E,where:A}=null!==(a=null===(n=null==e?void 0:e.req)||void 0===n?void 0:n.query)&&void 0!==a?a:{};if(C(v.limit)){let e=Env.API_MODEL_LIMIT;K(y)&&(e=parseInt(y)||0),e=M(e,-1,Env.API_MODEL_LIMIT_MAX),v.limit=e>0?e:r?Env.API_MODEL_LIMIT:void 0}if(F(v.limit)&&(v.limit=v.limit>0?v.limit:void 0),K(h)){const e=parseInt(h)||0;v.offset=e>0?e:void 0}const O=this.getAttributes(null!==(l=null==v?void 0:v.attributes)&&void 0!==l?l:[]),S=e=>O.indexOf(e)>=0;v.attributes=[],K(E)&&E.length&&v.attributes.push(...E.split(";").filter(S)),v.attributes.length||(v.attributes=O);const T=[];if(K(m)&&m.length&&T.push(...m.split(";").filter(S).map(e=>[e,"ASC"])),K(_)&&_.length&&T.push(..._.split(";").filter(S).map(e=>[e,"DESC"])),T.length&&(v.order=T),v.where=Object.assign({},v.where||{}),K(A)){const t=pe.parse(O,A);if(!C(t.error))return null==e||e.error(new o(t.error.join(", "))),{count:0,records:[]};v.where=Object.assign(Object.assign({},v.where),null!==(u=t.value)&&void 0!==u?u:{})}else{const e=[];O.forEach(t=>{K(f)&&f.length&&e.push({[t]:{[ce.like]:`%${f}%`}})}),e.length&&(v.where=Object.assign(Object.assign({},v.where),{[ce.or]:[...e]}))}const P=this.model.count(Object.assign(Object.assign({},v),{distinct:!!v.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error),I=this.model.findAll(v).catch(this.error);yield Promise.allSettled([P,I]);const w=null!==(c=yield P)&&void 0!==c?c:0;let b=null!==(p=yield I)&&void 0!==p?p:[];const x={count:w};return b?(b=i?yield i(b):b,(F(null==t?void 0:t.limit)||0==w)&&(x.count=null!==(g=null==b?void 0:b.length)&&void 0!==g?g:0),null==e||e.prepare(d.OK,Object.assign(Object.assign({},x),{records:b})),Object.assign(Object.assign({},x),{records:b})):(null==e||e.error(new s),Object.assign(Object.assign({},x),{records:[]}))})}findOne(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t,callback:i}){var r,o,a,l,u;const c=Object.assign({},t||{}),{primaryKeyAttribute:p}=this.model,{[p]:g}=null!==(r=null==e?void 0:e.req.params)&&void 0!==r?r:{},v=this.getAttributes(null!==(o=null==c?void 0:c.attributes)&&void 0!==o?o:[]),y=e=>v.indexOf(e)>=0,{select:h}=null!==(l=null===(a=null==e?void 0:e.req)||void 0===a?void 0:a.query)&&void 0!==l?l:{};K(h)&&(c.attributes=h.split(";").filter(y));const m=yield this.model.findOne(Object.assign(Object.assign({},c),{where:Object.assign(Object.assign({},null!==(u=null==c?void 0:c.where)&&void 0!==u?u:{}),{[p]:g})})).catch(this.error);return m?(null==e||e.prepare(d.OK,i?yield i(m):m.toJSON()),m):m?(null==e||e.error(new s),null):(null==e||e.error(new n),null)})}getAttributes(e){return 0==this.attributes.length&&(this.attributes=this.filterAttributes(Object.keys(this.model.getAttributes()),this.filter)),this.filterAttributes(this.attributes,e)}sync(){return Ce(this,void 0,void 0,function*(){if(!this.permissions.length)return;const e=this.name().toLowerCase(),t={description:"",state:!0};yield H(this.permissions,i=>Ce(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=q(e.replace(/_/g," ")," ");yield Ze.findOrCreate({where:{key:r},defaults:Object.assign({name:`${n} ${q(i," ")}`,key:r,tags:n},t)})}))})}update(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t,body:i,id:r}){var n,s,o,d,a,l;const u=Object.assign({},t||{}),{primaryKeyAttribute:c}=this.model,{[c]:p}=null!==(s=null===(n=null==e?void 0:e.req)||void 0===n?void 0:n.params)&&void 0!==s?s:{[c]:null!=r?r:0},[g]=null!==(l=yield this.model.update(Object.assign({},U({},null!==(d=null===(o=null==e?void 0:e.req)||void 0===o?void 0:o.body)&&void 0!==d?d:{},null!=i?i:{})),Object.assign(Object.assign(Object.assign({},u),{where:Object.assign(Object.assign({},null!==(a=null==u?void 0:u.where)&&void 0!==a?a:{}),{[c]:p}),individualHooks:!0}),{ctx:e})).catch(this.error))&&void 0!==l?l:[];return g?(null==e||e.success("OK"),!0):(null==e||e.success("Record not changed"),!1)})}name(){return this.model.tableName}}class UserService extends pt{getMetadata(e){return Ce(this,void 0,void 0,function*(){var t,i;const[r]=null!==(t=yield ct.findOrCreate({where:{user_id:e},defaults:{user_id:e}}).catch(this.error))&&void 0!==t?t:[];return null!==(i=null==r?void 0:r.data)&&void 0!==i?i:{}})}getProfile(e){return Ce(this,void 0,void 0,function*(){var t,i;const[r]=null!==(t=yield rt.findOrCreate({where:{user_id:e},defaults:{user_id:e}}).catch(this.error))&&void 0!==t?t:[];return null!==(i=null==r?void 0:r.data)&&void 0!==i?i:{}})}getGroups(e){return Ce(this,void 0,void 0,function*(){var t;return(null!==(t=yield et.findAll({attributes:["key"],where:{state:!0},include:[{model:tt,required:!0,where:{user_id:e}}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.key)})}getPermissions(e){return Ce(this,void 0,void 0,function*(){var t;return(null!==(t=yield Ze.findAll({attributes:["key"],where:{state:!0},include:[{model:Qe,required:!0,include:[{model:et,required:!0,attributes:["id"],where:{state:!0},include:[{model:tt,required:!0,where:{user_id:e}}]}]}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.key)})}}class Application extends a{constructor(e,t){super(e,U({},{cert:Env.HTTP_CRT,cross:Env.API_HTTP_CROSS,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},key:Env.HTTP_KEY,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:B}},null!=t?t:{})),this.hash=new b(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 Ce(this,void 0,void 0,function*(){yield Re.sync(),yield this.migrations(Re),yield H(this.controllers,e=>Ce(this,void 0,void 0,function*(){D(e.sync)&&(yield e.sync(this))})),this.authService=new AuthService,this.userService=new UserService,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new Z({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>Ce(this,void 0,void 0,function*(){t.url||(t.url=""),e.on("close",()=>{}),yield Y(2e3),e.close()})))})}migrations(e){return Ce(this,void 0,void 0,function*(){const t=[];yield H(Object.keys(e.models),i=>Ce(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 lt.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 H(t,e=>Ce(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}let gt=class BaseController extends ${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 Ce(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 Ce(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield H(this.permissions,i=>Ce(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=q(e.replace(/_/g," ")," ");yield Ze.findOrCreate({where:{key:r},defaults:Object.assign({name:`${n} ${q(i," ")}`,key:r,tags:n},t)})}))})}};we([be(0,l()),be(1,u("user-agent")),be(2,c()),xe("design:type",Function),xe("design:paramtypes",[r,String,Object]),xe("design:returntype",Promise)],gt.prototype,"session",null),gt=we([_e(Loggable)],gt);let vt=class ModelController extends gt{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"]}countAll(e){return Ce(this,void 0,void 0,function*(){return yield this.service.countAll(e)})}create(e){return Ce(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return Ce(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return Ce(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return Ce(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}sync(){return Ce(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield H(this.permissions,i=>Ce(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=q(e.replace(/_/g," ")," ");yield Ze.findOrCreate({where:{key:r},defaults:Object.assign({name:`${n} ${q(i," ")}`,key:r,tags:n},t)})})),this.service=new ModelService(this.model)})}update(e){return Ce(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}};vt=we([p(gt)],vt);let yt=class AuditsController extends vt{constructor(){super(...arguments),this.model=st,this.permissions=["read"]}all(e,t,i){return Ce(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:r,order:[["created_at","DESC"]]},limited:!0})})}get(e){return Ce(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};we([g(),Me(),Be(),be(0,l()),be(1,v("type")),be(2,v("table")),xe("design:type",Function),xe("design:paramtypes",[r,String,String]),xe("design:returntype",Promise)],yt.prototype,"all",null),we([g("/:id"),Me(),Be(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],yt.prototype,"get",null),yt=we([y("/audits"),p(vt)],yt);let ht=class AuthController extends gt{constructor(e){super(),this.authService=e}login(e,i,r,n,s,o){return Ce(this,void 0,void 0,function*(){var d;yield Y(Env.SLEEP_AUTH);const a=yield nt.findOne({where:{[ce.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 it.findOne({where:{user_id:a.id,state:!0}}).catch(this.error);if(!l||!ye(n,l.value))return e.error(new t("Invalid credentials")),o.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const u=yield ze.findOne({where:{state:!0,user_id:a.id}}).catch(this.error);if(u)return e.error("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.state)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.cookie(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 Ce(this,void 0,void 0,function*(){if(yield this.authService.destroy(i))return 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 Ce(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 Ce(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({},G(t.toJSON(),["username","description"])),{groups:i,permissions:r,profile:n}))})}};we([h("/login"),m(e=>({username:e.string().min(3).required(),password:e.string().min(5).required(),remember:e.boolean().parse().empty(!1)})),be(0,l()),be(1,u("user-agent")),be(2,_("username")),be(3,_("password")),be(4,_("remember")),be(5,f()),xe("design:type",Function),xe("design:paramtypes",[r,String,String,String,Boolean,Application]),xe("design:returntype",Promise)],ht.prototype,"login",null),we([g("/logout"),Me(),be(0,l()),be(1,Fe()),be(2,Ge()),be(3,f()),xe("design:type",Function),xe("design:paramtypes",[r,Xe,nt,Application]),xe("design:returntype",Promise)],ht.prototype,"logout",null),we([h("/renew"),m(e=>({token:e.string().required()})),be(0,l()),be(1,u("user-agent")),be(2,_("token")),be(3,f()),xe("design:type",Function),xe("design:paramtypes",[r,String,String,Application]),xe("design:returntype",Promise)],ht.prototype,"renew",null),we([g(),g("/me"),Me(),be(0,l()),be(1,Ge()),xe("design:type",Function),xe("design:paramtypes",[r,nt]),xe("design:returntype",Promise)],ht.prototype,"user",null),ht=we([y("/auth"),p(gt),be(0,fe(AuthService)),xe("design:paramtypes",[AuthService])],ht);let mt=class CrudController extends vt{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}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return Ce(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return Ce(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}number(e){return Ce(this,void 0,void 0,function*(){yield this.countAll(this.CrudArgumentsFindAll(e))})}del(e){return Ce(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return Ce(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return Ce(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return Ce(this,void 0,void 0,function*(){if(this.CrudValidationCreate()==this._crud)return e.error(new s)})}validationUpdate(e){return Ce(this,void 0,void 0,function*(){if(this.CrudValidationUpdate()==this._crud)return e.error(new s)})}};we([h(),Me(),ke(),E("validationCreate"),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],mt.prototype,"add",null),we([g(),Me(),Be(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],mt.prototype,"all",null),we([g("/count"),Me(),Be(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],mt.prototype,"number",null),we([A("/:id"),Me(),Ne(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],mt.prototype,"del",null),we([g("/:id"),Me(),Be(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],mt.prototype,"get",null),we([O("/:id"),Me(),Ke(),E("validationUpdate"),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],mt.prototype,"set",null),we([be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],mt.prototype,"validationCreate",null),we([be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],mt.prototype,"validationUpdate",null),mt=we([p(vt)],mt);let _t=class FilesController extends gt{constructor(){super(...arguments),this.directory=Env.API_HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return Ce(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=Ie(this.directory,t);if(!Ee(i)||!Ae(i).isDirectory())return e.error(new n);let r=[];return r=Oe(i),r=r.map(e=>this.info(Ie(i,e))),r=r.filter(V),Object.assign(Object.assign({},this.info(i)),{files:r})})}info(e){if(!Ee(e))return null;const t=Ae(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 Ce(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=q(e.replace(/_/g," ")," "),i={description:"",state:!0};yield H(this.permissions,r=>Ce(this,void 0,void 0,function*(){const n=`${e}.${r}`;yield Ze.findOrCreate({where:{key:n},defaults:Object.assign({name:`${t} ${q(r," ")}`,key:n,tags:t},i)})}))})}};we([g("/path"),g("/path/*path"),Me(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],_t.prototype,"files",null),_t=we([y("/files"),p(gt)],_t);let ft=class ForgotController extends gt{check(e,t){return Ce(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.error(new n);i.secret=J(),yield i.save(),e.json({token:i.secret})})}forgot(e,t,i){return Ce(this,void 0,void 0,function*(){yield Y(Env.SLEEP_FORGOT);const r=t,s=yield nt.findOne({where:{[ce.or]:[{email:r},{username:t}]}}).catch(this.error);if(!s)return e.error(new n);const o=J(),d=Date.now()+6e4*Env.API_TOKEN_FORGOT,a=yield dt.create({token:o,timestamp:d,state:!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 Ce(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i)return e.error(new n);i.state=!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 Ce(this,void 0,void 0,function*(){return yield dt.findOne({where:{token:e,state:!0},include:[{model:nt,required:!0}]}).catch(this.error)})}};we([g("/check"),m(e=>({token:e.string().required()})),be(0,l()),be(1,_("token")),xe("design:type",Function),xe("design:paramtypes",[r,String]),xe("design:returntype",Promise)],ft.prototype,"check",null),we([h(),m(e=>({username:e.string().min(4).required()})),be(0,l()),be(1,_("username")),be(2,f()),xe("design:type",Function),xe("design:paramtypes",[r,String,Application]),xe("design:returntype",Promise)],ft.prototype,"forgot",null),we([h("/reset"),m(e=>({token:e.string().required(),password:e.string().min(5).required()})),be(0,l()),be(1,_("token")),be(2,_("password")),be(3,f()),xe("design:type",Function),xe("design:paramtypes",[r,String,String,Application]),xe("design:returntype",Promise)],ft.prototype,"reset",null),ft=we([y("/forgot"),p(gt)],ft);let Et=class GroupsController extends mt{constructor(){super(...arguments),this.model=et,this.schemaCreate={name:W.string().required(),key:W.string().required(),tags:W.string().empty(""),description:W.string().empty(""),state:W.boolean().parse().required()},this.schemaUpdate={name:W.string().empty(),tags:W.string().empty(),description:W.string().empty(),state:W.boolean().parse().empty()}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};Et=we([y("/groups"),p(mt)],Et);let At=class GroupsPermissionsController extends vt{constructor(){super(...arguments),this.model=Qe,this.permissions=[]}all(e,t){return Ce(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:Ze,required:!0}]},callback:e=>e.map(e=>e.permission)})})}set(e,t,i){return Ce(this,void 0,void 0,function*(){const r=yield et.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new n);const s=r.id,o=[];yield H(z(i),t=>Ce(this,void 0,void 0,function*(){var i;if(!(yield Ze.count({where:{id:t}})))return;const[r]=null!==(i=yield Qe.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 Qe.destroy(Object.assign({where:{group_id:s,permission_id:{[ce.notIn]:o}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};we([g("/:id/permissions"),Me(),Be("groups"),be(0,l()),be(1,S("id")),xe("design:type",Function),xe("design:paramtypes",[r,String]),xe("design:returntype",Promise)],At.prototype,"all",null),we([O("/:id/permissions"),Me(),Ke("groups"),m(e=>({permissions:e.array(e.string())})),be(0,l()),be(1,S("id")),be(2,_("permissions")),xe("design:type",Function),xe("design:paramtypes",[r,String,Array]),xe("design:returntype",Promise)],At.prototype,"set",null),At=we([y("/groups"),p(vt)],At);let Ot=class LogsController extends vt{constructor(){super(...arguments),this.model=at,this.permissions=["read"]}all(e){return Ce(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{order:[["created_at","DESC"]]},limited:!0})})}};we([g(),Me(),Be(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],Ot.prototype,"all",null),Ot=we([y("/logs"),p(vt)],Ot);let St=class PermissionsController extends mt{constructor(){super(...arguments),this.model=Ze,this.schemaCreate={name:W.string().required(),key:W.string().required(),tags:W.string().empty(""),description:W.string().empty(""),state:W.boolean().parse().required()},this.schemaUpdate={name:W.string().empty(),tags:W.string().empty(),description:W.string().empty(),state:W.boolean().parse().empty()}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};St=we([y("/permissions"),p(mt)],St);let Tt=class RegisterController extends gt{register(e,t,i){return Ce(this,void 0,void 0,function*(){yield Y(Env.SLEEP_REGISTRY);const{name:r,date:n,email:o,username:d,password:a,confirm:l}=t,u=d||o,c=x(a);if(yield nt.count({where:{[ce.or]:[{email:o},{username:u}]}}).catch(this.error))return e.error("INVALID EMAIL OR USERNAME");if(c!=x(l))return e.error("INVALID PASSWORD");const p=yield nt.create({name:r,email:o,username:u,password:c,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!p)return e.error(new s);const g=yield ze.create({token:yield this.getId(),user_id:p.id,state:!0}).catch(this.error);if(!g)return yield p.destroy().catch(this.error),e.error(new s);e.success("OK"),i.emit("register.user",{ctx:e,register:g,user:p}),this.emit("register.user",{ctx:e,register:g,user:p})})}confirm(e,t,i){return Ce(this,void 0,void 0,function*(){const r=yield ze.findOne({where:{token:t,state:!0},include:[{model:nt,required:!0}]}).catch(this.error);if(!r)return e.error(new n);r.state=!1,yield r.save().catch(this.error),r.user.state=!0,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 Ce(this,void 0,void 0,function*(){const r=t,s=yield ze.findOne({where:{state:!0},include:[{model:nt,required:!0,where:{[ce.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 Ce(this,void 0,void 0,function*(){const e=B();return(yield ze.count({where:{token:e}}))?this.getId():e})}};we([h(),m(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()})),be(0,l()),be(1,_()),be(2,f()),xe("design:type",Function),xe("design:paramtypes",[r,Object,Application]),xe("design:returntype",Promise)],Tt.prototype,"register",null),we([h("/confirm"),m(e=>({token:e.string().required()})),be(0,l()),be(1,_("token")),be(2,f()),xe("design:type",Function),xe("design:paramtypes",[r,String,Application]),xe("design:returntype",Promise)],Tt.prototype,"confirm",null),we([h("/send"),m(e=>({username:e.string().min(4).required()})),be(0,l()),be(1,_("username")),be(2,f()),xe("design:type",Function),xe("design:paramtypes",[r,String,Application]),xe("design:returntype",Promise)],Tt.prototype,"send",null),Tt=we([y("/register"),p(gt)],Tt);let Pt=class SetupController extends gt{setup(e){return Ce(this,void 0,void 0,function*(){var t;if(yield nt.count())return e.success("OK");const i=yield nt.create({name:"Admin",email:"admin@localhost.com",username:"admin",description:"DEFAULT",state:!0},Object.assign({},{ctx:e}));yield it.create({value:"admin",state:!0,user_id:i.id});const r=yield et.create(Object.assign({name:"Admin",key:"admin",tags:"Admin"},{description:"API CORE",state:!0}),Object.assign({},{ctx:e}));yield tt.create({user_id:i.id,group_id:r.id},Object.assign({},{ctx:e}));const n=null!==(t=yield Ze.findAll({where:{state:!0}}).catch(this.error))&&void 0!==t?t:[];yield H(n,t=>Ce(this,void 0,void 0,function*(){yield Qe.create({group_id:r.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}};we([g(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],Pt.prototype,"setup",null),Pt=we([y("/setup"),p(gt)],Pt);let It=class UsersController extends vt{constructor(){super(),this.model=nt,this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&Ee(Env.API_HTTP_PUBLIC)&&!Ee(this.path)&&Se(this.path)}avatar(e,t){return Ce(this,void 0,void 0,function*(){var i,r;const n=e.getFiles();if(n.file&&n.file.length){const{filename:o,path:d}=null!==(i=n.file[0])&&void 0!==i?i:{};if(o){const[i]=null!==(r=yield rt.findOrCreate(Object.assign({where:{user_id:t.id},defaults:{user_id:t.id}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];if(!i)return Te(d).isFile()&&Pe(d),e.error(new s);const n=this.path+"/"+i.data.avatar;if(Ee(n)&&Te(n).isFile()&&Pe(n),i.changed("data",!0),i.data.avatar=o,yield i.save(Object.assign({},{ctx:e})).catch(this.error))return e.success("OK")}}e.success("Record not Changed")})}token_new(){return Ce(this,void 0,void 0,function*(){var e;const t=B();return(null!==(e=yield this.model.count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(e){return Ce(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return Ce(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}number(e){return Ce(this,void 0,void 0,function*(){yield this.countAll({ctx:e})})}del(e,t,i){return Ce(this,void 0,void 0,function*(){if(i.id==t)return e.error(new n);yield this.delete({ctx:e})})}get(e){return Ce(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return Ce(this,void 0,void 0,function*(){yield this.update({ctx:e})})}};we([h("/avatar"),Me(),T({file:{count:1,path:`${Env.API_HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),be(0,l()),be(1,Ge()),xe("design:type",Function),xe("design:paramtypes",[r,nt]),xe("design:returntype",Promise)],It.prototype,"avatar",null),we([h(),Me(),ke(),m(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)})),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],It.prototype,"add",null),we([g(),Me(),Be(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],It.prototype,"all",null),we([g("/count"),Me(),Be(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],It.prototype,"number",null),we([A("/:id"),Me(),Ne(),be(0,l()),be(1,S("id")),be(2,Ge()),xe("design:type",Function),xe("design:paramtypes",[r,String,nt]),xe("design:returntype",Promise)],It.prototype,"del",null),we([g("/:id"),Me(),Be(),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],It.prototype,"get",null),we([O("/:id"),Me(),Ke(),m(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()})),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],It.prototype,"set",null),It=we([y("/users"),p(vt),xe("design:paramtypes",[])],It);let wt=class UsersGroupsController extends vt{constructor(){super(...arguments),this.model=tt,this.permissions=[]}all(e,t){return Ce(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:et,required:!0}]},callback:e=>e.map(e=>e.group)})})}set(e,t,i){return Ce(this,void 0,void 0,function*(){const r=yield nt.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new n);const s=r.id,o=[];yield H(z(i),t=>Ce(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:{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 tt.destroy(Object.assign({where:{user_id:s,group_id:{[ce.notIn]:o}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};we([g("/:id/groups"),Me(),Be("users"),be(0,l()),be(1,S("id")),xe("design:type",Function),xe("design:paramtypes",[r,String]),xe("design:returntype",Promise)],wt.prototype,"all",null),we([O("/:id/groups"),Me(),Ke("users"),m(e=>({groups:e.array(e.string())})),be(0,l()),be(1,S("id")),be(2,_("groups")),xe("design:type",Function),xe("design:paramtypes",[r,String,Array]),xe("design:returntype",Promise)],wt.prototype,"set",null),wt=we([y("/users"),p(vt)],wt);let bt=class UsersProfilesController extends vt{constructor(){super(...arguments),this.model=rt,this.permissions=[]}all(e){return Ce(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}get(e,t){return Ce(this,void 0,void 0,function*(){var i;const[r]=null!==(i=yield rt.findOrCreate(Object.assign({where:{user_id:t},defaults:{user_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];if(!r)return e.error(new n);e.json(r.data)})}set(e,t,i){return Ce(this,void 0,void 0,function*(){var r;const s=yield nt.findByPk(t,{attributes:["id"]}).catch(this.error);if(!s)return e.error(new n);const o=s.id,d=X(i,e=>String(e)),[a,l]=null!==(r=yield rt.findOrCreate(Object.assign({where:{user_id:o},defaults:{data:d,user_id:o}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];a&&!l&&(a.changed("data",!0),a.data=U(a.data,d),yield a.save(Object.assign({},{ctx:e})).catch(this.error)),e.success("OK")})}};we([g("/profiles"),Me(),Be("users"),be(0,l()),xe("design:type",Function),xe("design:paramtypes",[r]),xe("design:returntype",Promise)],bt.prototype,"all",null),we([g("/:id/profiles"),Me(),Be("users"),be(0,l()),be(1,S("id")),xe("design:type",Function),xe("design:paramtypes",[r,String]),xe("design:returntype",Promise)],bt.prototype,"get",null),we([O("/:id/profiles"),Me(),Ke("users"),be(0,l()),be(1,S("id")),be(2,_()),xe("design:type",Function),xe("design:paramtypes",[r,String,Object]),xe("design:returntype",Promise)],bt.prototype,"set",null),bt=we([y("/users"),p(vt)],bt);export{Application,We as Audit,st as AuditModel,yt as AuditsController,ht as AuthController,AuthService,gt as BaseController,ke as CanCreate,Ne as CanDelete,Be as CanRead,Ke as CanUpdate,Config,ot as ConfigModel,mt as CrudController,Env,_t as FilesController,ft as ForgotController,dt as ForgotModel,et as GroupModel,Qe as GroupPermissionModel,Et as GroupsController,At as GroupsPermissionsController,Ue as HasGroups,Le as HasPermissions,Me as IsAuthenticated,Log,at as LogModel,Loggable,Ot as LogsController,lt as MigrationModel,vt as ModelController,ModelService,Ze as PermissionModel,St as PermissionsController,Tt as RegisterController,ze as RegisterModel,Fe as ReqAuth,He as ReqGroup,qe as ReqGroups,Ye as ReqPermission,$e as ReqPermissions,Ge as ReqUser,pt as Service,ut as SessionModel,SessionStore,Pt as SetupController,Xe as UserAuthModel,tt as UserGroupModel,ct as UserMetadataModel,nt as UserModel,it as UserPasswordModel,rt as UserProfileModel,UserService,It as UsersController,wt as UsersGroupsController,bt as UsersProfilesController,je as canFactory,Re as sequelize};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrewcaires/api",
|
|
3
|
-
"version": "5.0.
|
|
3
|
+
"version": "5.0.1",
|
|
4
4
|
"description": "Simple api for small applications using express, jsonwebtoken, sequelize and websocket",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs.js",
|
|
@@ -47,13 +47,13 @@
|
|
|
47
47
|
"homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"@andrewcaires/decorator": "^1.1.1",
|
|
50
|
-
"@andrewcaires/express": "^2.0.
|
|
51
|
-
"@andrewcaires/node": "^1.
|
|
50
|
+
"@andrewcaires/express": "^2.0.5",
|
|
51
|
+
"@andrewcaires/node": "^1.3.1",
|
|
52
52
|
"@andrewcaires/sequelize": "^3.0.0",
|
|
53
|
-
"@andrewcaires/utils.js": "^0.4.
|
|
53
|
+
"@andrewcaires/utils.js": "^0.4.29",
|
|
54
54
|
"bcrypt": "^6.0.0",
|
|
55
55
|
"cors": "^2.8.6",
|
|
56
|
-
"dotenv": "^17.
|
|
56
|
+
"dotenv": "^17.3.1",
|
|
57
57
|
"express-session": "^1.19.0",
|
|
58
58
|
"jsonwebtoken": "^9.0.3",
|
|
59
59
|
"tsx": "^4.21.0",
|
|
@@ -67,13 +67,13 @@
|
|
|
67
67
|
"@types/cors": "^2.8.19",
|
|
68
68
|
"@types/express-session": "^1.18.2",
|
|
69
69
|
"@types/jsonwebtoken": "^9.0.10",
|
|
70
|
-
"@types/node": "^25.
|
|
70
|
+
"@types/node": "^25.2.3",
|
|
71
71
|
"@types/ws": "^8.18.1",
|
|
72
|
-
"eslint": "^
|
|
72
|
+
"eslint": "^10.0.0",
|
|
73
73
|
"mariadb": "^3.4.5",
|
|
74
|
-
"rollup": "^4.
|
|
74
|
+
"rollup": "^4.57.1",
|
|
75
75
|
"rollup-plugin-dts": "^6.3.0",
|
|
76
76
|
"tslib": "^2.8.1",
|
|
77
|
-
"typescript-eslint": "^8.
|
|
77
|
+
"typescript-eslint": "^8.56.0"
|
|
78
78
|
}
|
|
79
79
|
}
|