@andrewcaires/api 4.2.0 → 4.2.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/api v4.2.0
2
+ * @andrewcaires/api v4.2.1
3
3
  * Simple api for small applications using express, jsonwebtoken, sequelize and websocket
4
- * (c) 2024 Andrew Caires
4
+ * (c) 2025 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- "use strict";var e=require("@andrewcaires/express"),t=require("@andrewcaires/sequelize"),r=require("@andrewcaires/node"),o=require("dotenv"),i=require("@andrewcaires/utils.js"),s=require("sequelize"),n=require("ws"),d=require("fs"),a=require("express-session"),p=require("jsonwebtoken"),l=require("path");function u(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 c(e,t){return function(r,o){t(r,o,e)}}function g(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function y(e,t,r,o){return new(r||(r=Promise))((function(i,s){function n(e){try{a(o.next(e))}catch(e){s(e)}}function d(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,d)}a((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const x=e=>{var t,r,o,i,s,n,d,a,p;return{audit_client:null!==(t=e.ip())&&void 0!==t?t:"0.0.0.0",audit_href:(null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.protocol)+"://"+(null===(o=null==e?void 0:e.req)||void 0===o?void 0:o.get("host"))+(null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.originalUrl),audit_user_agent:null!==(n=null===(s=e.req)||void 0===s?void 0:s.headers["user-agent"])&&void 0!==n?n:"",audit_user_id:null!==(p=null===(a=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.user)||void 0===a?void 0:a.id)&&void 0!==p?p:null}},h=e.parameterFactory((({ctx:e})=>x(e))),v=e.parameterFactory((({ctx:e})=>e.req.auth)),m=e.parameterFactory((({ctx:e})=>e.req.user));class _{static migrations(e){return r.Metadata(_.MIGRATE,e,{version:""})}}_.MIGRATE=Symbol();const A=e=>t=>{_.migrations(t).version=e};o.config();class O extends r.Env{}O.API_CONSOLE_ERROR=O.getBool("API_CONSOLE_ERROR",!1),O.API_DB_DATABASE=O.getString("API_DB_DATABASE",""),O.API_DB_HOST=O.getString("API_DB_HOST","127.0.0.1"),O.API_DB_PASSWORD=O.getString("API_DB_PASSWORD",""),O.API_DB_PORT=O.getInt("API_DB_PORT",3306),O.API_DB_TYPE=O.getString("API_DB_TYPE",""),O.API_DB_USERNAME=O.getString("API_DB_USERNAME","root"),O.API_DB_LOG=O.getBool("API_DB_LOG",!1),O.API_DB_AUDIT=O.getBool("API_DB_AUDIT",!0),O.API_DB_PREFIX=O.getString("API_DB_PREFIX",""),O.API_DB_TIMEZONE=O.getString("API_DB_TIMEZONE","+00:00"),O.API_HTTP_CRT=O.getString("API_HTTP_CRT",""),O.API_HTTP_KEY=O.getString("API_HTTP_KEY",""),O.API_HTTP_PORT=O.getInt("API_HTTP_PORT",3e3),O.API_HTTP_PUBLIC=O.getString("API_HTTP_PUBLIC",""),O.API_HTTP_CROSS=O.getBool("API_HTTP_CROSS",!1),O.API_HTTP_HYBRID=O.getBool("API_HTTP_HYBRID",!1),O.API_HTTP_NOTFOUND=O.getString("API_HTTP_NOTFOUND",""),O.API_HTTP_PATH=O.getString("API_HTTP_PATH","/api"),O.API_HTTP_REDIRECT=O.getString("API_HTTP_REDIRECT",""),O.API_KEY_HASH=O.getString("API_KEY_HASH",""),O.API_KEY_HEADER=O.getString("API_KEY_HEADER","api_key"),O.API_MODEL_LIMIT=O.getInt("API_MODEL_LIMIT",10),O.API_MODEL_LIMIT_MAX=O.getInt("API_MODEL_LIMIT_MAX",500),O.API_SLEEP_AUTH=O.getMs("API_SLEEP_AUTH","2s"),O.API_SLEEP_FORGOT=O.getMs("API_SLEEP_FORGOT","5s"),O.API_SLEEP_REGISTRY=O.getMs("API_SLEEP_REGISTRY","5s"),O.API_SESSION_NAME=O.getString("API_SESSION_NAME","session.id"),O.API_SESSION_LIFETIME=O.getMs("API_SESSION_LIFETIME","1d"),O.API_SESSION_SECRET=O.getString("API_SESSION_SECRET","yoursecret"),O.API_TOKEN_CRT=O.getString("API_TOKEN_CRT",""),O.API_TOKEN_KEY=O.getString("API_TOKEN_KEY",""),O.API_TOKEN_FORGOT=O.getMs("API_TOKEN_LIFETIME","1d"),O.API_TOKEN_HEADER=O.getString("API_TOKEN_HEADER","authorization"),O.API_TOKEN_LIFETIME=O.getMs("API_TOKEN_LIFETIME","1d"),O.API_TOKEN_RENEW=O.getMs("API_TOKEN_RENEW","1d"),O.API_UPLOAD_COUNT=O.getInt("API_UPLOAD_COUNT",1),O.API_UPLOAD_FIELD=O.getString("API_UPLOAD_FIELD","upload"),O.API_UPLOAD_SIZE=O.getInt("API_UPLOAD_SIZE",2),O.API_UPLOAD_TEMP=O.getString("API_UPLOAD_TEMP","./temp"),O.API_USER_HISTORY=O.getBool("API_USER_HISTORY",!0),O.API_WEBSOCKET_START=O.getBool("API_WEBSOCKET_START",!1);const C=new t.Connection({type:O.API_DB_TYPE,database:O.API_DB_DATABASE,username:O.API_DB_USERNAME,password:O.API_DB_PASSWORD,hostname:O.API_DB_HOST,hostport:O.API_DB_PORT,logging:O.API_DB_LOG,prefix:O.API_DB_PREFIX,timezone:O.API_DB_TIMEZONE});class P extends t.Model{constructor(){super(...arguments),this._version=""}}const S=(e,t,r)=>{var o,i,s,n,d;return{type:e,model:null!==(o=null==t?void 0:t.getTableName())&&void 0!==o?o:null,client:null!==(i=null==r?void 0:r.audit_client)&&void 0!==i?i:null,href:null!==(s=null==r?void 0:r.audit_href)&&void 0!==s?s:null,user_agent:null!==(n=null==r?void 0:r.audit_user_agent)&&void 0!==n?n:null,user_id:null!==(d=null==r?void 0:r.audit_user_id)&&void 0!==d?d:null,state:!0}},E={afterCreate:(e,t)=>y(void 0,void 0,void 0,(function*(){var r;if(!O.API_DB_AUDIT)return;const o=i.isObject(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null;yield exports.Audit.create(Object.assign(Object.assign({},S("CREATE",o,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(i.noop)})),afterUpdate:(e,t)=>y(void 0,void 0,void 0,(function*(){var r;if(!O.API_DB_AUDIT)return;const o=i.isObject(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null,n={},d=e.changed();d&&d.forEach((t=>n[t]=e.getDataValue(t))),yield exports.Audit.create(Object.assign(Object.assign({},S("UPDATE",o,t)),{record:s?e.getDataValue(s):null,data:n,previously:e.previous()})).catch(i.noop)})),afterDestroy:(e,t)=>y(void 0,void 0,void 0,(function*(){var r;if(!O.API_DB_AUDIT)return;const o=i.isObject(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null;yield exports.Audit.create(Object.assign(Object.assign({},S("DELETE",o,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(i.noop)}))};exports.Auth=class extends P{},u([t.Id(),g("design:type",Number)],exports.Auth.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Auth.prototype,"secret",void 0),u([t.FullDate(),g("design:type",Date)],exports.Auth.prototype,"logout",void 0),u([t.String(),g("design:type",t.String)],exports.Auth.prototype,"user_agent",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Auth.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Auth.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Auth.prototype,"deleted_at",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Auth.prototype,"user_id",void 0),exports.Auth=u([t.Database(C),t.ModelName("auth"),A("4.2.0")],exports.Auth),exports.Register=class extends P{},u([t.Id(),g("design:type",Number)],exports.Register.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Register.prototype,"token",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.Register.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Register.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Register.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Register.prototype,"deleted_at",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Register.prototype,"user_id",void 0),exports.Register=u([t.Database(C),t.ModelName("register"),A("4.2.0")],exports.Register),exports.Group=class extends P{},u([t.Id(),g("design:type",Number)],exports.Group.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Group.prototype,"name",void 0),u([t.Text(),g("design:type",t.String)],exports.Group.prototype,"description",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.Group.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Group.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Group.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Group.prototype,"deleted_at",void 0),u([t.HasMany((()=>exports.UserGroup),"group_id"),g("design:type",Array)],exports.Group.prototype,"groups_routes",void 0),u([t.HasMany((()=>exports.UserGroup),"group_id"),g("design:type",Array)],exports.Group.prototype,"users_groups",void 0),exports.Group=u([t.Database(C),t.ModelName("group"),t.Hooks(E),A("4.2.0")],exports.Group),exports.UserGroup=class extends P{},u([t.CreatedAt,g("design:type",Date)],exports.UserGroup.prototype,"created_at",void 0),u([t.BelongsTo((()=>exports.Group)),g("design:type",Number)],exports.UserGroup.prototype,"group_id",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.UserGroup.prototype,"user_id",void 0),exports.UserGroup=u([t.Database(C),t.ModelName("users_groups"),t.Hooks(E),A("4.2.0")],exports.UserGroup),exports.UserHistory=class extends P{},u([t.String(),g("design:type",t.String)],exports.UserHistory.prototype,"password",void 0),u([t.CreatedAt,g("design:type",Date)],exports.UserHistory.prototype,"created_at",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.UserHistory.prototype,"user_id",void 0),exports.UserHistory=u([t.Database(C),t.ModelName("users_histories"),A("4.2.0")],exports.UserHistory),exports.User=class extends P{},u([t.Id(),g("design:type",Number)],exports.User.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"name",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"email",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"username",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"password",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"salt",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"token",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"avatar",void 0),u([t.DateOnly(),g("design:type",t.String)],exports.User.prototype,"date",void 0),u([t.Text(),g("design:type",t.String)],exports.User.prototype,"description",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.User.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.User.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.User.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.User.prototype,"deleted_at",void 0),u([t.HasMany((()=>exports.Audit),"user_id"),g("design:type",Array)],exports.User.prototype,"audits",void 0),u([t.HasMany((()=>exports.Auth),"user_id"),g("design:type",Array)],exports.User.prototype,"auths",void 0),u([t.HasMany((()=>exports.Register),"user_id"),g("design:type",Array)],exports.User.prototype,"registers",void 0),u([t.HasMany((()=>exports.UserGroup),"user_id"),g("design:type",Array)],exports.User.prototype,"users_groups",void 0),u([t.HasMany((()=>exports.UserHistory),"user_id"),g("design:type",Array)],exports.User.prototype,"users_histories",void 0),exports.User=u([t.Database(C),t.ModelName("user"),t.DefaultScope({attributes:{exclude:["password","salt","token"]}}),t.Scopes({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),t.Hooks(E),A("4.2.0")],exports.User),exports.Audit=class extends P{},u([t.Id(),g("design:type",Number)],exports.Audit.prototype,"id",void 0),u([t.Enum("CREATE","DELETE","UPDATE"),g("design:type",t.String)],exports.Audit.prototype,"type",void 0),u([t.String(),g("design:type",t.String)],exports.Audit.prototype,"model",void 0),u([t.String(),g("design:type",t.String)],exports.Audit.prototype,"record",void 0),u([t.Json(),g("design:type",Object)],exports.Audit.prototype,"data",void 0),u([t.Json(),g("design:type",Object)],exports.Audit.prototype,"previously",void 0),u([t.String(),g("design:type",t.String)],exports.Audit.prototype,"client",void 0),u([t.Text(),g("design:type",t.String)],exports.Audit.prototype,"href",void 0),u([t.String(),g("design:type",t.String)],exports.Audit.prototype,"user_agent",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.Audit.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Audit.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Audit.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Audit.prototype,"deleted_at",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Audit.prototype,"user_id",void 0),exports.Audit=u([t.Database(C),t.ModelName("audit"),A("4.2.0")],exports.Audit),exports.Configs=class extends P{},u([t.String(),g("design:type",t.String)],exports.Configs.prototype,"key",void 0),u([t.String(),g("design:type",t.String)],exports.Configs.prototype,"value",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Configs.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Configs.prototype,"updated_at",void 0),exports.Configs=u([t.Database(C),t.ModelName("configs"),t.Hooks(E),A("4.2.0")],exports.Configs),exports.Forgot=class extends P{},u([t.Id(),g("design:type",Number)],exports.Forgot.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Forgot.prototype,"token",void 0),u([t.BigInt(),g("design:type",Number)],exports.Forgot.prototype,"timestamp",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.Forgot.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Forgot.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Forgot.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Forgot.prototype,"deleted_at",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Forgot.prototype,"user_id",void 0),exports.Forgot=u([t.Database(C),t.ModelName("forgot"),A("4.2.0")],exports.Forgot),exports.Permission=class extends P{},u([t.Id(),g("design:type",Number)],exports.Permission.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Permission.prototype,"name",void 0),u([t.String(),t.Unique(!0),g("design:type",t.String)],exports.Permission.prototype,"route",void 0),u([t.Text(),g("design:type",t.String)],exports.Permission.prototype,"description",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.Permission.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Permission.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Permission.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Permission.prototype,"deleted_at",void 0),u([t.HasMany((()=>exports.GroupPermission),"permission_id"),g("design:type",Array)],exports.Permission.prototype,"groups_permissions",void 0),exports.Permission=u([t.Database(C),t.ModelName("permission"),t.Hooks(E),A("4.2.0")],exports.Permission),exports.GroupPermission=class extends P{},u([t.CreatedAt,g("design:type",Date)],exports.GroupPermission.prototype,"created_at",void 0),u([t.BelongsTo((()=>exports.Group)),g("design:type",Number)],exports.GroupPermission.prototype,"group_id",void 0),u([t.BelongsTo((()=>exports.Permission)),g("design:type",Number)],exports.GroupPermission.prototype,"permission_id",void 0),exports.GroupPermission=u([t.Database(C),t.ModelName("groups_permissions"),t.Hooks(E),A("4.2.0")],exports.GroupPermission),exports.Log=class extends P{},u([t.Id(),g("design:type",Number)],exports.Log.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Log.prototype,"type",void 0),u([t.String(),g("design:type",t.String)],exports.Log.prototype,"source",void 0),u([t.Text(),g("design:type",t.String)],exports.Log.prototype,"message",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Log.prototype,"created_at",void 0),exports.Log=u([t.Database(C),t.ModelName("log"),A("4.2.0")],exports.Log),exports.Migration=class extends P{},u([t.String(),g("design:type",t.String)],exports.Migration.prototype,"model",void 0),u([t.String(),g("design:type",t.String)],exports.Migration.prototype,"version",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Migration.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Migration.prototype,"updated_at",void 0),exports.Migration=u([t.Database(C),t.ModelName("migration"),A("4.2.0")],exports.Migration),exports.Session=class extends P{},u([t.String(),g("design:type",t.String)],exports.Session.prototype,"session",void 0),u([t.Text(),g("design:type",t.String)],exports.Session.prototype,"json",void 0),u([t.BigInt(),g("design:type",Number)],exports.Session.prototype,"expired",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Session.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Session.prototype,"updated_at",void 0),exports.Session=u([t.Database(C),t.ModelName("session"),A("4.2.0")],exports.Session);class f{static write(e,t,o){return y(this,void 0,void 0,(function*(){yield f.writeRaw(r.LogColor.White,"",e,t,o)}))}static error(e,t,o){return y(this,void 0,void 0,(function*(){yield f.writeRaw(r.LogColor.Red,"error",e,t,o)}))}static info(e,t,o){return y(this,void 0,void 0,(function*(){yield f.writeRaw(r.LogColor.Cyan,"info",e,t,o)}))}static success(e,t,o){return y(this,void 0,void 0,(function*(){yield f.writeRaw(r.LogColor.Green,"success",e,t,o)}))}static warning(e,t,o){return y(this,void 0,void 0,(function*(){yield f.writeRaw(r.LogColor.Yellow,"warning",e,t,o)}))}static writeRaw(e,t,o,i,s){return y(this,void 0,void 0,(function*(){s&&r.Log.console(e,t,o),C&&(yield exports.Log.create({type:t,source:i,message:o}).catch((()=>null)))}))}}const I=e=>d.existsSync(e)?d.readFileSync(e):void 0,R={http:I(O.API_HTTP_CRT),token:I(O.API_TOKEN_CRT)},T={http:I(O.API_HTTP_KEY),token:I(O.API_TOKEN_KEY)};class D extends a.Store{constructor(){super(),this.all=e=>y(this,void 0,void 0,(function*(){e=e||i.noop;const t=yield exports.Session.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=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy().catch(i.noop),e&&e()})),this.destroy=(e,t)=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy({where:{session:e}}).catch(i.noop),t&&t()})),this.expired=()=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy({where:{expired:{[s.Op.lt]:Date.now()}}}).catch(i.noop)})),this.get=(e,t)=>y(this,void 0,void 0,(function*(){t=t||i.noop;const r=yield exports.Session.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(i.noop),void t(null)}t(null,e)}else t(null)})),this.length=e=>y(this,void 0,void 0,(function*(){e&&e(null,(yield exports.Session.count().catch(i.noop))||0)})),this.set=(e,t,r)=>y(this,void 0,void 0,(function*(){r=r||i.noop;const o=Date.now()+O.API_SESSION_LIFETIME,s=JSON.stringify(t),[n,d]=(yield exports.Session.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:o}}).catch(i.noop))||[];n&&(d||(n.json=s,n.expired=o,yield n.save().catch(i.noop))),r()})),this.loop=i.loop(this.expired,3e4),this.loop.start()}}class w{static create(e){return y(this,void 0,void 0,(function*(){if(!T.token)return{error:"KEY NOT FOUND"};const{id:t}=e,r=i.uuidv4(),o=yield exports.Auth.create({secret:r,user_id:t}).catch(w.error);if(!o)return{error:"INTERNAL SERVER ERROR"};return{auth:o,token:p.sign({id:t,secret:r},T.token,w.options())}}))}static destroy(e){return y(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){f.error(e.message,"api.token",O.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:O.API_TOKEN_LIFETIME+"ms"}}static renew(e){return y(this,void 0,void 0,(function*(){if(!T.token)return{error:"KEY NOT FOUND"};const{error:t,decode:r}=w.verify(e,O.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield exports.User.findOne({where:{id:e,state:!0}}).catch(w.error);if(r){const o=yield exports.Auth.findOne({where:{secret:t,user_id:r.id}}).catch(w.error);if(o&&!o.logout){o.secret=i.uuidv4(),yield o.save().catch(w.error);return{auth:o,token:p.sign({id:e,secret:o.secret},T.token,w.options())}}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}}))}static user(e,t,r){return y(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const o=yield exports.User.findOne({where:{token:t,state:!0}}).catch(w.error);if(o){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield exports.Auth.findOrCreate({where:{secret:t,user_id:o.id},defaults:{secret:t,user_id:o.id}}).catch(w.error))||[];if(r)return{auth:r,user:o}}return{error:"ACCESS DENIED"}}const{error:o,decode:i}=w.verify(t);if(o)return{error:o};if(i){const{id:e,secret:t}=i;if(e&&t){const r=yield exports.User.findOne({where:{id:e,state:!0}}).catch(w.error);if(r){const e=yield exports.Auth.findOne({where:{secret:t,user_id:r.id}}).catch(w.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}}))}static verify(e,t){if(!R.token)return{error:"CERT NOT FOUND"};if(!e||e.split(".").length<3)return{error:"INVALID TOKEN"};try{return{decode:p.verify(e,R.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class b extends e.Application{constructor(e){super(e,{cert:R.http,cross:O.API_HTTP_CROSS,hybrid:O.API_HTTP_HYBRID,key:T.http,notfound:O.API_HTTP_NOTFOUND,path:O.API_HTTP_PATH,port:O.API_HTTP_PORT,public:O.API_HTTP_PUBLIC,redirect:O.API_HTTP_REDIRECT,session:{store:new D,name:O.API_SESSION_NAME,secret:O.API_SESSION_SECRET,cookie:{maxAge:O.API_SESSION_LIFETIME},genid:i.uuidv4}}),this.hash=new r.Hash(O.API_KEY_HASH)}error(e,t){f.error(e.message,t,O.API_CONSOLE_ERROR)}log(e,t){f.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return y(this,void 0,void 0,(function*(){yield C.sync(),yield this.migrations(C),yield e.listen.call(this),O.API_WEBSOCKET_START&&this.server&&(this._webSocket=new n.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(O.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>y(this,void 0,void 0,(function*(){t.url||(t.url="");const r=t.url.length<=1?"":t.url.replace(/\//g,".");let o;e.on("message",(i=>y(this,void 0,void 0,(function*(){if(o)try{const s=JSON.parse(i);this.emit("ws.message"+r,{data:s,message:i,req:t,user:o,ws:e})}catch(s){this.emit("ws.message"+r,{erro:s,message:i,req:t,user:o,ws:e})}else{const{user:s}=yield w.user("",i.toString(),this);s&&(o=s,this.emit("ws.connection"+r,{req:t,user:o,ws:e}))}o||e.close()})))),e.on("close",(()=>{o&&this.emit("ws.close"+r,{user:o,ws:e})})),yield i.sleep(2e3),o||e.close()})))))}))}migrations(e){return y(this,void 0,void 0,(function*(){const r=[];yield i.forEachSeries(Object.keys(e.models),(t=>y(this,void 0,void 0,(function*(){var o;const i=e.models[t],{version:s}=_.migrations(i);if(!s)return;const[n,d]=null!==(o=yield exports.Migration.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),r.push(i))})))),r.length&&(yield t.migrate(e,r))}))}websocket(){return this._webSocket}}class N extends i.EventEmitter{auth(e,t,r,o,i){return y(this,void 0,void 0,(function*(){const{auth:s,error:n,user:d}=yield w.user(t,r,i);return n?e.error(n):s&&d?s.user_agent&&s.user_agent!=o?e.error("INVALID TOKEN"):(e.req.auth=s,e.req.user=d,void e.next()):e.error("INTERNAL SERVER ERROR")}))}create(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".create",r)}))}delete(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".delete",r)}))}error(e){f.error(e.message,"api.controller",O.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return y(this,void 0,void 0,(function*(){if(r){const o=yield this.permissions(r,{route:t});if(o&&o.length>0)return e.next()}e.unauthorized("ACCESS DENIED")}))}permissions(e,t){return y(this,void 0,void 0,(function*(){return yield exports.Permission.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:exports.GroupPermission,required:!0,include:[{model:exports.Group,required:!0,where:{state:!0},include:[{model:exports.UserGroup,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error)}))}read(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}session(e,t,r){return y(this,void 0,void 0,(function*(){r.auth&&r.user&&(r.user_agent?r.user_agent!=t&&r.regenerate(i.noop):(r.user_agent=t,r.save(i.noop))),e.next()}))}upload(t,r){r.path||(r.path=O.API_UPLOAD_TEMP),r.size||(r.size=O.API_UPLOAD_SIZE),r.field||(r.field=O.API_UPLOAD_FIELD),e.Upload.middleware(t,r)}update(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".update",r)}))}validation(e,t){return y(this,void 0,void 0,(function*(){const{error:r,value:o}=yield i.Validation.object(t).parse().validateAsync(e.req.body);if(r)return e.validation(r);e.req.body=o,e.next()}))}}u([c(0,e.Ctx()),c(1,e.Headers(O.API_KEY_HEADER)),c(2,e.Headers(O.API_TOKEN_HEADER)),c(3,e.Headers("user-agent")),c(4,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,String,b]),g("design:returntype",Promise)],N.prototype,"auth",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],N.prototype,"create",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],N.prototype,"delete",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],N.prototype,"permission",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],N.prototype,"read",null),u([c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Session()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object]),g("design:returntype",Promise)],N.prototype,"session",null),u([c(0,e.Ctx()),c(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",void 0)],N.prototype,"upload",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],N.prototype,"update",null),u([c(0,e.Ctx()),c(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",Promise)],N.prototype,"validation",null),exports.ModelController=class extends N{constructor(){super(...arguments),this._attributes=[]}_add(t){return y(this,arguments,void 0,(function*({ctx:t,options:r,body:o}){const i=yield this.model().create(Object.assign(Object.assign({},t.req.body),o||{}),Object.assign(Object.assign({},r||{}),x(t))).catch(this.error);if(i){const r=this.key();return t.prepare(e.Status.OK,{[r]:i.getDataValue(r)}),i}t.error("INTERNAL SERVER ERROR")}))}_all(r){return y(this,arguments,void 0,(function*({ctx:r,options:o,callback:n,scope:d,advanced:a,unlimited:p}){var l,u,c;const g=this.scope(d),y=Object.assign({},o||{}),{limit:x,offset:h,asc:v,desc:m,search:_,where:A}=r.req.query;if(i.isUndefined(y.limit)){const e=i.clamp(i.isString(x)?parseInt(x)||0:O.API_MODEL_LIMIT,-1,O.API_MODEL_LIMIT_MAX);y.limit=e>0?e:p?void 0:O.API_MODEL_LIMIT}if(i.isString(h)){const e=h&&parseInt(h)||0;y.offset=e>0?e:void 0}const C=this.attributes(null!==(l=null==y?void 0:y.attributes)&&void 0!==l?l:[]),P=[],S=e=>C.indexOf(e)>=0;if(i.isString(v)&&v.length&&P.push(...v.split(";").filter(S).map((e=>[e,"ASC"]))),i.isString(m)&&m.length&&P.push(...m.split(";").filter(S).map((e=>[e,"DESC"]))),P.length&&(y.order=P),y.where=Object.assign({},y.where||{}),i.isString(A)&&(i.isUndefined(a)||a)){const e=t.Where.parse(C,A);if(!i.isUndefined(e.error))return r.validation(e.error.join(", ")),{count:0,records:[]};y.where=Object.assign(Object.assign({},y.where),null!==(u=e.value)&&void 0!==u?u:{})}else{const e=[];C.forEach((t=>{i.isString(_)&&_.length&&e.push({[t]:{[s.Op.like]:`%${_}%`}})})),e.length&&(y.where=Object.assign(Object.assign({},y.where),{[s.Op.or]:[...e]}))}const E=g.count(Object.assign(Object.assign({},y),{distinct:!!y.include,col:this._attributes.length?this._attributes[0]:void 0})).catch(this.error),f=g.findAll(y).catch(this.error);yield Promise.allSettled([E,f]);const I=null!==(c=yield E)&&void 0!==c?c:0;let R=yield f;const T={count:I};return R?(R=n?yield n(R):R,(i.isNumber(null==o?void 0:o.limit)||0==I)&&(T.count=R.length),r.prepare(e.Status.OK,Object.assign(Object.assign({},T),{records:R})),Object.assign(Object.assign({},T),{records:R})):(r.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},T),{records:[]}))}))}_del(e){return y(this,arguments,void 0,(function*({ctx:e,options:t}){const r=this.key(),{[r]:o}=e.req.params;if(!o)return e.error("INTERNAL SERVER ERROR"),0;const i=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:o}),individualHooks:!0}),x(e))).catch(this.error);return i?(e.success("OK"),i):(e.notFound("RECORD NOT FOUND"),0)}))}_get(t){return y(this,arguments,void 0,(function*({ctx:t,options:r,callback:o,scope:i}){const s=this.key(),{[s]:n}=t.req.params,d=yield this.scope(i).findOne(Object.assign(Object.assign({},r||{}),{where:Object.assign(Object.assign({},(r||{}).where),{[s]:n})})).catch(this.error);return d?(t.prepare(e.Status.OK,o?yield o(d):d.toJSON()),d):null===d?t.notFound("RECORD NOT FOUND"):void t.error("INTERNAL SERVER ERROR")}))}_set(e){return y(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){var o;const i=this.key(),{[i]:s}=e.req.params,[n]=null!==(o=yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:s}),individualHooks:!0}),x(e))).catch(this.error))&&void 0!==o?o:[];return n?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)}))}attributes(e){if(0==this._attributes.length&&(this._attributes=Object.keys(this.model().getAttributes())),i.isArray(e))return e.map((e=>i.isString(e)&&-1!=this._attributes.indexOf(e)?e:void 0)).filter(i.isString);const{exclude:t,include:r}=e,o=i.isUndefined(r)?this._attributes:r.map((e=>i.isString(e)&&-1!=this._attributes.indexOf(e)?e:void 0)).filter(i.isString),s=null!=t?t:[];return s.length?o.filter((e=>-1==s.indexOf(e)?e:void 0)).filter(i.isString):o}error(e){e.sql?f.error(e.message+"\n"+e.sql,"api.controller.sql",O.API_CONSOLE_ERROR):super.error(e)}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}},exports.ModelController=u([e.Extends(N)],exports.ModelController),exports.AuditsController=class extends exports.ModelController{model(){return exports.Audit}all(e,t,r){return y(this,void 0,void 0,(function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this._all({ctx:e,options:{attributes:{exclude:["data","previously"]},where:o,order:[["created_at","DESC"]]}})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}},u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("table")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=u([e.Controller("/audits"),e.Extends(exports.ModelController)],exports.AuditsController),exports.AuthController=class extends N{login(e,t,o,n,d){return y(this,void 0,void 0,(function*(){var a;yield i.sleep(O.API_SLEEP_AUTH);const p=yield exports.User.scope("password").findOne({where:{[s.Op.or]:[{email:o},{username:o}]}}).catch(this.error);if(n+=null!==(a=null==p?void 0:p.salt)&&void 0!==a?a:"",!p||p.password!=r.sha256(n))return e.notFound("INVALID USERNAME OR PASSWORD"),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const l=yield exports.Register.findOne({where:{state:!0,user_id:p.id}}).catch(this.error);if(l)return e.error("ACTIVATION REQUIRED"),d.emit("auth.activation",{ctx:e,register:l,user:p}),void this.emit("auth.activation",{ctx:e,register:l,user:p});if(!p.state)return e.notFound("INVALID USERNAME OR PASSWORD"),d.emit("auth.failure",{ctx:e,user:p}),void this.emit("auth.failure",{ctx:e,user:p});const{auth:u,error:c,token:g}=yield w.create(p);return c?(e.error(c),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):u&&g?(u.user_agent=t,yield u.save().catch(this.error),e.json({token:g}),d.emit("auth.login",{auth:u,ctx:e,user:p}),void this.emit("auth.login",{auth:u,ctx:e,user:p})):(e.error("INTERNAL SERVER ERROR"),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,o){return y(this,void 0,void 0,(function*(){if(yield w.destroy(t))return e.success("OK"),o.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("ACCESS DENIED")}))}renew(e,t,r,o){return y(this,void 0,void 0,(function*(){const{auth:i,error:s,token:n}=yield w.renew(r);return s?e.error(s):i?(i.user_agent=t,yield i.save().catch(this.error),e.json({token:n}),o.emit("auth.renew",{auth:i,ctx:e}),void this.emit("auth.renew",{auth:i,ctx:e})):e.error("INTERNAL SERVER ERROR")}))}user(e,t){return y(this,void 0,void 0,(function*(){const r=yield this.permissions(t);if(!r)return e.error("INTERNAL SERVER ERROR");e.json(Object.assign(Object.assign({},i.denied(["username","date","description","state","created_at","updated_at","deleted_at"],t.toJSON())),{permissions:r.map((e=>e.route))}))}))}},u([e.Post("/login"),e.Middleware("validation",{username:i.Validation.string().min(3).required(),password:i.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("username")),c(3,e.Body("password")),c(4,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,String,b]),g("design:returntype",Promise)],exports.AuthController.prototype,"login",null),u([e.Get("/logout"),e.Middleware("auth"),c(0,e.Ctx()),c(1,v()),c(2,m()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.Auth,exports.User,b]),g("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),u([e.Post("/renew"),e.Middleware("validation",{token:i.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("token")),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,b]),g("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),u([e.Get(),e.Middleware("auth"),c(0,e.Ctx()),c(1,m()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=u([e.Controller("/auth"),e.Extends(N)],exports.AuthController),exports.FilesController=class extends N{directory(){return O.API_HTTP_PUBLIC||"./"}files(e){return y(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const r=l.join(this.directory(),t);if(!d.existsSync(r)||!d.statSync(r).isDirectory())return e.notFound("RECORD NOT FOUND");let o=[];return o=d.readdirSync(r),o=o.map((e=>this.info(l.join(r,e)))),o=o.filter(i.isDef),Object.assign(Object.assign({},this.info(r)),{files:o})}))}access(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!d.existsSync(e))return null;const t=d.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"}},u([e.Get("/path/?*"),e.Middleware("auth"),e.Middleware("access","list"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.FilesController.prototype,"files",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=u([e.Controller("/files"),e.Extends(N)],exports.FilesController),exports.ForgotController=class extends N{check(e,t){return y(this,void 0,void 0,(function*(){const r=yield this.find(t);if(!r||!r.user)return e.notFound("RECORD NOT FOUND");r.token=i.uniqueID(),yield r.save(),e.json({token:r.token})}))}forgot(e,t,r){return y(this,void 0,void 0,(function*(){yield i.sleep(O.API_SLEEP_FORGOT);const o=t,n=yield exports.User.findOne({where:{[s.Op.or]:[{email:o},{username:t}]}}).catch(this.error);if(!n)return e.notFound("RECORD NOT FOUND");const d=i.uniqueID(),a=Date.now()+6e4*O.API_TOKEN_FORGOT,p=yield exports.Forgot.create({token:d,timestamp:a,state:!0,user_id:n.id});e.success("OK"),r.emit("forgot.send",{ctx:e,forgot:p,user:n}),this.emit("forgot.send",{ctx:e,forgot:p,user:n})}))}reset(e,t,o,i){return y(this,void 0,void 0,(function*(){const s=yield this.find(t);if(!s)return e.notFound("RECORD NOT FOUND");s.state=!1,yield s.save().catch(this.error),s.user.password=r.sha256(o),yield s.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:s.user}),this.emit("forgot.reset",{ctx:e,user:s.user})}))}find(e){return y(this,void 0,void 0,(function*(){return yield exports.Forgot.findOne({where:{token:e,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error)}))}},u([e.Get("/check"),e.Middleware("validation",{token:i.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),u([e.Post(),e.Middleware("validation",{username:i.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,b]),g("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),u([e.Post("/reset"),e.Middleware("validation",{token:i.Validation.string().required(),password:i.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.Body("password")),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,b]),g("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=u([e.Controller("/forgot"),e.Extends(N)],exports.ForgotController),exports.CrudController=class extends exports.ModelController{constructor(){super(...arguments),this._crud={}}add(e){return y(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}CrudCreate(){return this._crud}del(e){return y(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return y(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}CrudUpdate(){return this._crud}validationAdd(e){return y(this,void 0,void 0,(function*(){const t=this.CrudCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)}))}validationSet(e){return y(this,void 0,void 0,(function*(){const t=this.CrudUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)}))}},u([e.Post(),e.Middleware("auth"),e.Middleware("create"),e.Middleware("validationAdd"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("delete"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"get",null),u([e.Put("/:id"),e.Middleware("auth"),e.Middleware("update"),e.Middleware("validationSet"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"set",null),u([c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationAdd",null),u([c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationSet",null),exports.CrudController=u([e.Extends(exports.ModelController)],exports.CrudController),exports.GroupsController=class extends exports.CrudController{model(){return exports.Group}CrudCreate(){return{name:i.Validation.string().required(),description:i.Validation.string().empty(""),state:i.Validation.boolean().parse().required()}}CrudUpdate(){return{name:i.Validation.string().empty(),description:i.Validation.string().empty(),state:i.Validation.boolean().parse().empty()}}},exports.GroupsController=u([e.Controller("/groups"),e.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsPermissionsController=class extends exports.ModelController{model(){return exports.GroupPermission}all(e,t){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{group_id:t},include:[{model:exports.Permission,required:!0}]},callback:e=>e.map((e=>e.permission))})}))}set(e,t,r,o){return y(this,void 0,void 0,(function*(){const s=yield exports.Group.findByPk(t,{attributes:["id"]}).catch(this.error);if(s){const t=s.id;if(yield exports.GroupPermission.destroy(Object.assign({where:{group_id:t},individualHooks:!0},o)),r){let e=0;yield i.sleep(1e3);for(let i=0;i<r.length;i++)e=yield exports.Permission.count({where:{id:r[i]}}),e&&(yield exports.GroupPermission.create({group_id:t,permission_id:r[i]},Object.assign({},o)))}return e.success("OK")}if(i.isNull(s))return e.notFound("RECORD NOT FOUND");e.error("INTERNAL SERVER ERROR")}))}},u([e.Get("/:id/permissions"),e.Middleware("auth"),e.Middleware("read","groups"),c(0,e.Ctx()),c(1,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"all",null),u([e.Put("/:id/permissions"),e.Middleware("auth"),e.Middleware("update","groups"),e.Middleware("validation",{permissions:i.Validation.array(i.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("permissions")),c(3,h()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array,Object]),g("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"set",null),exports.GroupsPermissionsController=u([e.Controller("/groups"),e.Extends(exports.ModelController)],exports.GroupsPermissionsController),exports.LogsController=class extends exports.ModelController{model(){return exports.Log}all(e,t,r){return y(this,void 0,void 0,(function*(){const o={};t&&(o.type=t),r&&(o.source=r),yield this._all({ctx:e,options:{where:o,order:[["created_at","DESC"]]}})}))}},u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("source")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=u([e.Controller("/logs"),e.Extends(exports.ModelController)],exports.LogsController),exports.PermissionsController=class extends exports.CrudController{model(){return exports.Permission}CrudCreate(){return{name:i.Validation.string().required(),route:i.Validation.string().required(),description:i.Validation.string().empty(""),state:i.Validation.boolean().parse().required()}}CrudUpdate(){return{name:i.Validation.string().empty(),route:i.Validation.string().empty(),description:i.Validation.string().empty(),state:i.Validation.boolean().parse().empty()}}},exports.PermissionsController=u([e.Controller("/permissions"),e.Extends(exports.CrudController)],exports.PermissionsController),exports.RegisterController=class extends N{register(e,t,o){return y(this,void 0,void 0,(function*(){yield i.sleep(O.API_SLEEP_REGISTRY);const{name:n,date:d,email:a,username:p,password:l,confirm:u}=t,c=p||a,g=r.sha256(l);if(yield exports.User.count({where:{[s.Op.or]:[{email:a},{username:c}]}}).catch(this.error))return e.validation("INVALID EMAIL OR USERNAME");if(g!=r.sha256(u))return e.error("INVALID PASSWORD");const y=yield exports.User.create({name:n,email:a,username:c,password:g,avatar:"",date:d,description:"",state:!1}).catch(this.error);if(!y)return e.error("INTERNAL SERVER ERROR");const x=yield exports.Register.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("INTERNAL SERVER ERROR");e.success("OK"),o.emit("register.user",{ctx:e,register:x,user:y}),this.emit("register.user",{ctx:e,register:x,user:y})}))}confirm(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield exports.Register.findOne({where:{token:t,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error);if(!o)return e.notFound("RECORD NOT FOUND");o.state=!1,yield o.save().catch(this.error),o.user.state=!0,yield o.user.save().catch(this.error),e.success("OK"),r.emit("register.confirm",{ctx:e,register:o,user:o.user}),this.emit("register.confirm",{ctx:e,register:o,user:o.user})}))}send(e,t,r){return y(this,void 0,void 0,(function*(){const o=t,i=yield exports.Register.findOne({where:{state:!0},include:[{model:exports.User,required:!0,where:{[s.Op.or]:[{email:o},{username:t}]}}]}).catch(this.error);if(!i)return e.notFound("RECORD NOT FOUND");e.success("OK"),r.emit("register.send",{ctx:e,register:i,user:i.user}),this.emit("register.send",{ctx:e,register:i,user:i.user})}))}getId(){return y(this,void 0,void 0,(function*(){const e=i.uuidv4();return(yield exports.Register.count({where:{token:e}}))?this.getId():e}))}},u([e.Post(),e.Middleware("validation",{name:i.Validation.string().required(),date:i.Validation.date().required(),email:i.Validation.string().email().required(),username:i.Validation.string().min(4).empty(),password:i.Validation.string().min(5).required(),confirm:i.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body()),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,Object,b]),g("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),u([e.Post("/confirm"),e.Middleware("validation",{token:i.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,b]),g("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),u([e.Post("/send"),e.Middleware("validation",{username:i.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,b]),g("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=u([e.Controller("/register"),e.Extends(N)],exports.RegisterController),exports.SetupController=class extends N{setup(e,t){return y(this,void 0,void 0,(function*(){if(0==(yield exports.User.count())){const e=i.uniqueID(),o=yield exports.User.create({name:"Admin",email:"admin@localhost",username:"admin",password:r.sha256("admin"+e),salt:e,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},t)),s={description:"API CORE",state:!0},n=yield exports.Group.create(Object.assign({name:"Admin"},s),Object.assign({},t));yield exports.UserGroup.create({user_id:o.id,group_id:n.id},Object.assign({},t));const d=["Users","Groups","Permissions"],a=["Create","Read","Update","Delete"];yield i.forEachSeries(d,(e=>y(this,void 0,void 0,(function*(){yield i.forEachSeries(a,(r=>y(this,void 0,void 0,(function*(){const o=yield exports.Permission.create(Object.assign({name:`${e} ${r}`,route:`${e.toLowerCase()}.${r.toLowerCase()}`},s),Object.assign({},t));yield exports.GroupPermission.create({group_id:n.id,permission_id:o.id},Object.assign({},t))}))))}))));const p=["Delete","List","Read","Rename","Upload","Write"];yield i.forEachSeries(p,(e=>y(this,void 0,void 0,(function*(){const r=yield exports.Permission.create(Object.assign({name:`Files ${e}`,route:`files.${e.toLowerCase()}`},s),Object.assign({},t));yield exports.GroupPermission.create({group_id:n.id,permission_id:r.id},Object.assign({},t))}))));const l=["Audits","Logs"];yield i.forEachSeries(l,(e=>y(this,void 0,void 0,(function*(){const r=yield exports.Permission.create(Object.assign({name:`${e} Read`,route:`${e.toLowerCase()}.read`},s),Object.assign({},t));yield exports.GroupPermission.create({group_id:n.id,permission_id:r.id},Object.assign({},t))}))))}e.success("OK")}))}},u([e.Get(),c(0,e.Ctx()),c(1,h()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=u([e.Controller("/setup"),e.Extends(N)],exports.SetupController),exports.UsersController=class extends exports.ModelController{model(){return exports.User}constructor(){super(),this.path=O.API_HTTP_PUBLIC+"/avatar",O.API_HTTP_PUBLIC&&d.existsSync(O.API_HTTP_PUBLIC)&&!d.existsSync(this.path)&&d.mkdirSync(this.path)}avatar(e,t,r,o){return y(this,void 0,void 0,(function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.path+"/"+r.avatar;if(d.existsSync(t)&&d.lstatSync(t).isFile()&&d.rmSync(t),r.avatar=i,yield r.save(Object.assign({},o)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")}))}avatar_delete(e,t,r){return y(this,void 0,void 0,(function*(){const o=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},r)).catch(this.error))&&d.existsSync(o)&&d.rmSync(o),e.success("OK")}))}password(e,t,o,s,n){return y(this,void 0,void 0,(function*(){var d;if(O.API_USER_HISTORY){if(yield exports.UserHistory.count({where:{password:r.sha256(o+s.id)}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED")}const a=yield this.scope("password").findOne({where:{id:s.id,state:!0}}).catch(this.error);return t+=null!==(d=null==a?void 0:a.salt)&&void 0!==d?d:"",a&&a.password==r.sha256(t)?(a.salt=i.uniqueID(),a.password=r.sha256(o+a.salt),(yield a.save(Object.assign({},n)).catch(this.error))?e.success("OK"):void e.success("RECORD NOT CHANGED")):e.error("INVALID PASSWORD")}))}token(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(o)return e.json({token:r.hash.decrypt(o.token)});e.notFound("RECORD NOT FOUND")}))}token_get(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(o)return e.json({token:r.hash.decrypt(o.token)});e.notFound("RECORD NOT FOUND")}))}token_delete(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(o)return o.token="",yield o.save(Object.assign({},r)).catch(this.error),e.success("OK");e.notFound("RECORD NOT FOUND")}))}token_renew(e,t,r,o){return y(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(i){const t=yield this.token_new();return i.token=o.hash.encrypt(t),yield i.save(Object.assign({},r)).catch(this.error),e.json({token:t})}e.notFound("RECORD NOT FOUND")}))}token_new(){return y(this,void 0,void 0,(function*(){var e;const t=i.uuidv4();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t}))}add(e,t){return y(this,void 0,void 0,(function*(){const o=i.uniqueID(),s=yield this._add({ctx:e,body:{password:r.sha256(t+o),salt:o}});O.API_USER_HISTORY&&s&&(yield exports.UserHistory.create({password:r.sha256(t+s.id),user_id:s.id}))}))}all(e){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{attributes:{exclude:["password","salt","token"]}}})}))}del(e,t,r){return y(this,void 0,void 0,(function*(){if(r.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this._del({ctx:e})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t,o){return y(this,void 0,void 0,(function*(){if(O.API_USER_HISTORY&&o){const i=r.sha256(o+t);if(yield exports.UserHistory.count({where:{password:i}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED");yield exports.UserHistory.create({password:i,user_id:t}).catch(this.error)}const s=o?i.uniqueID():"";yield this._set({ctx:e,body:o?{password:r.sha256(o+s),salt:s}:{}})}))}},u([e.Post("/avatar"),e.Middleware("auth"),e.Middleware("upload",(e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32}))),c(0,e.Ctx()),c(1,e.Files()),c(2,m()),c(3,h()),g("design:type",Function),g("design:paramtypes",[e.Context,Array,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),u([e.Delete("/avatar"),e.Middleware("auth"),c(0,e.Ctx()),c(1,m()),c(2,h()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar_delete",null),u([e.Post("/password"),e.Middleware("auth"),e.Middleware("validation",{oldPassword:i.Validation.string().min(5).required(),newPassword:i.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("oldPassword")),c(2,e.Body("newPassword")),c(3,m()),c(4,h()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"password",null),u([e.Get("/token"),e.Middleware("auth"),c(0,e.Ctx()),c(1,m()),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,b]),g("design:returntype",Promise)],exports.UsersController.prototype,"token",null),u([e.Get("/token/:id"),e.Middleware("auth"),e.Middleware("create"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,b]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_get",null),u([e.Delete("/token/:id"),e.Middleware("auth"),e.Middleware("delete"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,h()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_delete",null),u([e.Get("/token/renew/:id"),e.Middleware("auth"),e.Middleware("update"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,h()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object,b]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_renew",null),u([e.Post(),e.Middleware("auth"),e.Middleware("create"),e.Middleware("validation",{name:i.Validation.string().required(),email:i.Validation.string().email().required(),username:i.Validation.string().min(4).required(),password:i.Validation.string().min(5).required(),description:i.Validation.string().empty(""),state:i.Validation.boolean().parse().required()}),c(0,e.Ctx()),c(1,e.Body("password")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.UsersController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("delete"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],exports.UsersController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.UsersController.prototype,"get",null),u([e.Put("/:id"),e.Middleware("auth"),e.Middleware("update"),e.Middleware("validation",{name:i.Validation.string().empty(),email:i.Validation.string().email().empty(),username:i.Validation.string().min(4).empty(),password:i.Validation.string().min(5).empty().filter(""),description:i.Validation.string().empty(),state:i.Validation.boolean().parse().empty()}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("password")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=u([e.Controller("/users"),e.Extends(exports.ModelController),g("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ModelController{model(){return exports.UserGroup}groups(e,t){return y(this,void 0,void 0,(function*(){yield this.all(e,t.id.toString())}))}all(e,t){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{user_id:t},include:[{model:exports.Group,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,r,o){return y(this,void 0,void 0,(function*(){const s=yield exports.User.findByPk(t,{attributes:["id"]}).catch(this.error);if(s){if(yield exports.UserGroup.destroy(Object.assign({where:{user_id:s.id},individualHooks:!0},o)),r){let e=0;yield i.sleep(1e3);for(let t=0;t<r.length;t++)e=yield exports.Group.count({where:{id:r[t]}}),e&&(yield exports.UserGroup.create({user_id:s.id,group_id:r[t]},Object.assign({},o)))}return e.success("OK")}if(i.isNull(s))return e.notFound("RECORD NOT FOUND");e.error("INTERNAL SERVER ERROR")}))}},u([e.Get("/groups"),e.Middleware("auth"),e.Middleware("read","users"),c(0,e.Ctx()),c(1,m()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"groups",null),u([e.Get("/:id/groups"),e.Middleware("auth"),e.Middleware("read","users"),c(0,e.Ctx()),c(1,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),u([e.Put("/:id/groups"),e.Middleware("auth"),e.Middleware("update","users"),e.Middleware("validation",{groups:i.Validation.array(i.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("groups")),c(3,h()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array,Object]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=u([e.Controller("/users"),e.Extends(exports.ModelController)],exports.UsersGroupsController);class U{static all(){return y(this,void 0,void 0,(function*(){const e=yield exports.Configs.findAll().catch(U.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e,t){return y(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.Configs.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:o})).catch(U.error))||0)>0}))}static error(e){f.error(e.message,"api.config",O.API_CONSOLE_ERROR)}static get(e){return y(this,arguments,void 0,(function*(e,t=""){const[r]=(yield exports.Configs.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(U.error))||[];return r?r.value:t}))}static set(e,t,r){return y(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.Configs.findOrCreate(Object.assign({where:{key:e}},{user_id:i})).catch(U.error))||[];s&&(s.value=t,yield s.save().catch(U.error))}))}}exports.Application=b,exports.Config=U,exports.ControllerBase=N,exports.Env=O,exports.Logs=f,exports.Metadata=_,exports.Migrate=A,exports.Model=P,exports.ReqAudit=h,exports.ReqAuth=v,exports.ReqUser=m,exports.Store=D,exports.Token=w,exports.audit=x,exports.crt=R,exports.database=C,exports.hooks=E,exports.key=T;
7
+ "use strict";var e=require("@andrewcaires/express"),t=require("@andrewcaires/sequelize"),r=require("@andrewcaires/node"),o=require("dotenv"),i=require("@andrewcaires/utils.js"),s=require("sequelize"),n=require("ws"),d=require("fs"),a=require("express-session"),p=require("jsonwebtoken"),l=require("path");function u(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 c(e,t){return function(r,o){t(r,o,e)}}function g(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function y(e,t,r,o){return new(r||(r=Promise))((function(i,s){function n(e){try{a(o.next(e))}catch(e){s(e)}}function d(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,d)}a((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const x=e=>{var t,r,o,i,s,n,d,a,p;return{audit_client:null!==(t=e.ip())&&void 0!==t?t:"0.0.0.0",audit_href:(null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.protocol)+"://"+(null===(o=null==e?void 0:e.req)||void 0===o?void 0:o.get("host"))+(null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.originalUrl),audit_user_agent:null!==(n=null===(s=e.req)||void 0===s?void 0:s.headers["user-agent"])&&void 0!==n?n:"",audit_user_id:null!==(p=null===(a=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.user)||void 0===a?void 0:a.id)&&void 0!==p?p:null}},h=e.parameterFactory((({ctx:e})=>x(e))),v=e.parameterFactory((({ctx:e})=>e.req.auth)),m=e.parameterFactory((({ctx:e})=>e.req.user));class _{static migrations(e){return r.Metadata(_.MIGRATE,e,{version:""})}}_.MIGRATE=Symbol();const A=e=>t=>{_.migrations(t).version=e};o.config();class O extends r.Env{}O.API_CONSOLE_ERROR=O.getBool("API_CONSOLE_ERROR",!1),O.API_DB_DATABASE=O.getString("API_DB_DATABASE",""),O.API_DB_HOST=O.getString("API_DB_HOST","127.0.0.1"),O.API_DB_PASSWORD=O.getString("API_DB_PASSWORD",""),O.API_DB_PORT=O.getInt("API_DB_PORT",3306),O.API_DB_TYPE=O.getString("API_DB_TYPE",""),O.API_DB_USERNAME=O.getString("API_DB_USERNAME","root"),O.API_DB_LOG=O.getBool("API_DB_LOG",!1),O.API_DB_AUDIT=O.getBool("API_DB_AUDIT",!0),O.API_DB_PREFIX=O.getString("API_DB_PREFIX",""),O.API_DB_TIMEZONE=O.getString("API_DB_TIMEZONE","+00:00"),O.API_HTTP_CRT=O.getString("API_HTTP_CRT",""),O.API_HTTP_KEY=O.getString("API_HTTP_KEY",""),O.API_HTTP_PORT=O.getInt("API_HTTP_PORT",3e3),O.API_HTTP_PUBLIC=O.getString("API_HTTP_PUBLIC",""),O.API_HTTP_CROSS=O.getBool("API_HTTP_CROSS",!1),O.API_HTTP_HYBRID=O.getBool("API_HTTP_HYBRID",!1),O.API_HTTP_NOTFOUND=O.getString("API_HTTP_NOTFOUND",""),O.API_HTTP_PATH=O.getString("API_HTTP_PATH","/api"),O.API_HTTP_REDIRECT=O.getString("API_HTTP_REDIRECT",""),O.API_KEY_HASH=O.getString("API_KEY_HASH",""),O.API_KEY_HEADER=O.getString("API_KEY_HEADER","api_key"),O.API_MODEL_LIMIT=O.getInt("API_MODEL_LIMIT",10),O.API_MODEL_LIMIT_MAX=O.getInt("API_MODEL_LIMIT_MAX",500),O.API_SLEEP_AUTH=O.getMs("API_SLEEP_AUTH","2s"),O.API_SLEEP_FORGOT=O.getMs("API_SLEEP_FORGOT","5s"),O.API_SLEEP_REGISTRY=O.getMs("API_SLEEP_REGISTRY","5s"),O.API_SESSION_NAME=O.getString("API_SESSION_NAME","session.id"),O.API_SESSION_LIFETIME=O.getMs("API_SESSION_LIFETIME","1d"),O.API_SESSION_SECRET=O.getString("API_SESSION_SECRET","yoursecret"),O.API_TOKEN_CRT=O.getString("API_TOKEN_CRT",""),O.API_TOKEN_KEY=O.getString("API_TOKEN_KEY",""),O.API_TOKEN_FORGOT=O.getMs("API_TOKEN_LIFETIME","1d"),O.API_TOKEN_HEADER=O.getString("API_TOKEN_HEADER","authorization"),O.API_TOKEN_LIFETIME=O.getMs("API_TOKEN_LIFETIME","1d"),O.API_TOKEN_RENEW=O.getMs("API_TOKEN_RENEW","1d"),O.API_UPLOAD_COUNT=O.getInt("API_UPLOAD_COUNT",1),O.API_UPLOAD_FIELD=O.getString("API_UPLOAD_FIELD","upload"),O.API_UPLOAD_SIZE=O.getInt("API_UPLOAD_SIZE",2),O.API_UPLOAD_TEMP=O.getString("API_UPLOAD_TEMP","./temp"),O.API_USER_HISTORY=O.getBool("API_USER_HISTORY",!0),O.API_WEBSOCKET_START=O.getBool("API_WEBSOCKET_START",!1);const C=new t.Connection({type:O.API_DB_TYPE,database:O.API_DB_DATABASE,username:O.API_DB_USERNAME,password:O.API_DB_PASSWORD,hostname:O.API_DB_HOST,hostport:O.API_DB_PORT,logging:O.API_DB_LOG,prefix:O.API_DB_PREFIX,timezone:O.API_DB_TIMEZONE});class P extends t.Model{constructor(){super(...arguments),this._version=""}}const S=(e,t,r)=>{var o,i,s,n,d;return{type:e,model:null!==(o=null==t?void 0:t.getTableName())&&void 0!==o?o:null,client:null!==(i=null==r?void 0:r.audit_client)&&void 0!==i?i:null,href:null!==(s=null==r?void 0:r.audit_href)&&void 0!==s?s:null,user_agent:null!==(n=null==r?void 0:r.audit_user_agent)&&void 0!==n?n:null,user_id:null!==(d=null==r?void 0:r.audit_user_id)&&void 0!==d?d:null,state:!0}},E={afterCreate:(e,t)=>y(void 0,void 0,void 0,(function*(){var r;if(!O.API_DB_AUDIT)return;const o=i.isObject(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null;yield exports.Audit.create(Object.assign(Object.assign({},S("CREATE",o,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(i.noop)})),afterUpdate:(e,t)=>y(void 0,void 0,void 0,(function*(){var r;if(!O.API_DB_AUDIT)return;const o=i.isObject(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null,n={},d=e.changed();d&&d.forEach((t=>n[t]=e.getDataValue(t))),yield exports.Audit.create(Object.assign(Object.assign({},S("UPDATE",o,t)),{record:s?e.getDataValue(s):null,data:n,previously:e.previous()})).catch(i.noop)})),afterDestroy:(e,t)=>y(void 0,void 0,void 0,(function*(){var r;if(!O.API_DB_AUDIT)return;const o=i.isObject(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null;yield exports.Audit.create(Object.assign(Object.assign({},S("DELETE",o,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(i.noop)}))};exports.Auth=class extends P{},u([t.Id(),g("design:type",Number)],exports.Auth.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Auth.prototype,"secret",void 0),u([t.FullDate(),g("design:type",Date)],exports.Auth.prototype,"logout",void 0),u([t.String(),g("design:type",t.String)],exports.Auth.prototype,"user_agent",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Auth.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Auth.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Auth.prototype,"deleted_at",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Auth.prototype,"user_id",void 0),exports.Auth=u([t.Database(C),t.ModelName("auth"),A("4.2.0")],exports.Auth),exports.Register=class extends P{},u([t.Id(),g("design:type",Number)],exports.Register.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Register.prototype,"token",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.Register.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Register.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Register.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Register.prototype,"deleted_at",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Register.prototype,"user_id",void 0),exports.Register=u([t.Database(C),t.ModelName("register"),A("4.2.0")],exports.Register),exports.Group=class extends P{},u([t.Id(),g("design:type",Number)],exports.Group.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Group.prototype,"name",void 0),u([t.Text(),g("design:type",t.String)],exports.Group.prototype,"description",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.Group.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Group.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Group.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Group.prototype,"deleted_at",void 0),u([t.HasMany((()=>exports.UserGroup),"group_id"),g("design:type",Array)],exports.Group.prototype,"groups_routes",void 0),u([t.HasMany((()=>exports.UserGroup),"group_id"),g("design:type",Array)],exports.Group.prototype,"users_groups",void 0),exports.Group=u([t.Database(C),t.ModelName("group"),t.Hooks(E),A("4.2.0")],exports.Group),exports.UserGroup=class extends P{},u([t.CreatedAt,g("design:type",Date)],exports.UserGroup.prototype,"created_at",void 0),u([t.BelongsTo((()=>exports.Group)),g("design:type",Number)],exports.UserGroup.prototype,"group_id",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.UserGroup.prototype,"user_id",void 0),exports.UserGroup=u([t.Database(C),t.ModelName("users_groups"),t.Hooks(E),A("4.2.0")],exports.UserGroup),exports.UserHistory=class extends P{},u([t.String(),g("design:type",t.String)],exports.UserHistory.prototype,"password",void 0),u([t.CreatedAt,g("design:type",Date)],exports.UserHistory.prototype,"created_at",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.UserHistory.prototype,"user_id",void 0),exports.UserHistory=u([t.Database(C),t.ModelName("users_histories"),A("4.2.0")],exports.UserHistory),exports.User=class extends P{},u([t.Id(),g("design:type",Number)],exports.User.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"name",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"email",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"username",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"password",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"salt",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"token",void 0),u([t.String(),g("design:type",t.String)],exports.User.prototype,"avatar",void 0),u([t.DateOnly(),g("design:type",t.String)],exports.User.prototype,"date",void 0),u([t.Text(),g("design:type",t.String)],exports.User.prototype,"description",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.User.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.User.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.User.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.User.prototype,"deleted_at",void 0),u([t.HasMany((()=>exports.Audit),"user_id"),g("design:type",Array)],exports.User.prototype,"audits",void 0),u([t.HasMany((()=>exports.Auth),"user_id"),g("design:type",Array)],exports.User.prototype,"auths",void 0),u([t.HasMany((()=>exports.Register),"user_id"),g("design:type",Array)],exports.User.prototype,"registers",void 0),u([t.HasMany((()=>exports.UserGroup),"user_id"),g("design:type",Array)],exports.User.prototype,"users_groups",void 0),u([t.HasMany((()=>exports.UserHistory),"user_id"),g("design:type",Array)],exports.User.prototype,"users_histories",void 0),exports.User=u([t.Database(C),t.ModelName("user"),t.DefaultScope({attributes:{exclude:["password","salt","token"]}}),t.Scopes({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),t.Hooks(E),A("4.2.0")],exports.User),exports.Audit=class extends P{},u([t.Id(),g("design:type",Number)],exports.Audit.prototype,"id",void 0),u([t.Enum("CREATE","DELETE","UPDATE"),g("design:type",t.String)],exports.Audit.prototype,"type",void 0),u([t.String(),g("design:type",t.String)],exports.Audit.prototype,"model",void 0),u([t.String(),g("design:type",t.String)],exports.Audit.prototype,"record",void 0),u([t.Json(),g("design:type",Object)],exports.Audit.prototype,"data",void 0),u([t.Json(),g("design:type",Object)],exports.Audit.prototype,"previously",void 0),u([t.String(),g("design:type",t.String)],exports.Audit.prototype,"client",void 0),u([t.Text(),g("design:type",t.String)],exports.Audit.prototype,"href",void 0),u([t.String(),g("design:type",t.String)],exports.Audit.prototype,"user_agent",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.Audit.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Audit.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Audit.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Audit.prototype,"deleted_at",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Audit.prototype,"user_id",void 0),exports.Audit=u([t.Database(C),t.ModelName("audit"),A("4.2.0")],exports.Audit),exports.Configs=class extends P{},u([t.String(),g("design:type",t.String)],exports.Configs.prototype,"key",void 0),u([t.String(),g("design:type",t.String)],exports.Configs.prototype,"value",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Configs.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Configs.prototype,"updated_at",void 0),exports.Configs=u([t.Database(C),t.ModelName("configs"),t.Hooks(E),A("4.2.0")],exports.Configs),exports.Forgot=class extends P{},u([t.Id(),g("design:type",Number)],exports.Forgot.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Forgot.prototype,"token",void 0),u([t.BigInt(),g("design:type",Number)],exports.Forgot.prototype,"timestamp",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.Forgot.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Forgot.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Forgot.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Forgot.prototype,"deleted_at",void 0),u([t.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Forgot.prototype,"user_id",void 0),exports.Forgot=u([t.Database(C),t.ModelName("forgot"),A("4.2.0")],exports.Forgot),exports.Permission=class extends P{},u([t.Id(),g("design:type",Number)],exports.Permission.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Permission.prototype,"name",void 0),u([t.String(),t.Unique(!0),g("design:type",t.String)],exports.Permission.prototype,"route",void 0),u([t.Text(),g("design:type",t.String)],exports.Permission.prototype,"description",void 0),u([t.Boolean(),g("design:type",t.Boolean)],exports.Permission.prototype,"state",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Permission.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Permission.prototype,"updated_at",void 0),u([t.DeletedAt,g("design:type",Object)],exports.Permission.prototype,"deleted_at",void 0),u([t.HasMany((()=>exports.GroupPermission),"permission_id"),g("design:type",Array)],exports.Permission.prototype,"groups_permissions",void 0),exports.Permission=u([t.Database(C),t.ModelName("permission"),t.Hooks(E),A("4.2.0")],exports.Permission),exports.GroupPermission=class extends P{},u([t.CreatedAt,g("design:type",Date)],exports.GroupPermission.prototype,"created_at",void 0),u([t.BelongsTo((()=>exports.Group)),g("design:type",Number)],exports.GroupPermission.prototype,"group_id",void 0),u([t.BelongsTo((()=>exports.Permission)),g("design:type",Number)],exports.GroupPermission.prototype,"permission_id",void 0),exports.GroupPermission=u([t.Database(C),t.ModelName("groups_permissions"),t.Hooks(E),A("4.2.0")],exports.GroupPermission),exports.Log=class extends P{},u([t.Id(),g("design:type",Number)],exports.Log.prototype,"id",void 0),u([t.String(),g("design:type",t.String)],exports.Log.prototype,"type",void 0),u([t.String(),g("design:type",t.String)],exports.Log.prototype,"source",void 0),u([t.Text(),g("design:type",t.String)],exports.Log.prototype,"message",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Log.prototype,"created_at",void 0),exports.Log=u([t.Database(C),t.ModelName("log"),A("4.2.0")],exports.Log),exports.Migration=class extends P{},u([t.String(),g("design:type",t.String)],exports.Migration.prototype,"model",void 0),u([t.String(),g("design:type",t.String)],exports.Migration.prototype,"version",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Migration.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Migration.prototype,"updated_at",void 0),exports.Migration=u([t.Database(C),t.ModelName("migration"),A("4.2.0")],exports.Migration),exports.Session=class extends P{},u([t.String(),g("design:type",t.String)],exports.Session.prototype,"session",void 0),u([t.Text(),g("design:type",t.String)],exports.Session.prototype,"json",void 0),u([t.BigInt(),g("design:type",Number)],exports.Session.prototype,"expired",void 0),u([t.CreatedAt,g("design:type",Date)],exports.Session.prototype,"created_at",void 0),u([t.UpdatedAt,g("design:type",Date)],exports.Session.prototype,"updated_at",void 0),exports.Session=u([t.Database(C),t.ModelName("session"),A("4.2.0")],exports.Session);class f{static write(e,t,o){return y(this,void 0,void 0,(function*(){yield f.writeRaw(r.LogColor.White,"",e,t,o)}))}static error(e,t,o){return y(this,void 0,void 0,(function*(){yield f.writeRaw(r.LogColor.Red,"error",e,t,o)}))}static info(e,t,o){return y(this,void 0,void 0,(function*(){yield f.writeRaw(r.LogColor.Cyan,"info",e,t,o)}))}static success(e,t,o){return y(this,void 0,void 0,(function*(){yield f.writeRaw(r.LogColor.Green,"success",e,t,o)}))}static warning(e,t,o){return y(this,void 0,void 0,(function*(){yield f.writeRaw(r.LogColor.Yellow,"warning",e,t,o)}))}static writeRaw(e,t,o,i,s){return y(this,void 0,void 0,(function*(){s&&r.Log.console(e,t,o),C&&(yield exports.Log.create({type:t,source:i,message:o}).catch((()=>null)))}))}}const I=e=>d.existsSync(e)?d.readFileSync(e):void 0,R={http:I(O.API_HTTP_CRT),token:I(O.API_TOKEN_CRT)},T={http:I(O.API_HTTP_KEY),token:I(O.API_TOKEN_KEY)};class D extends a.Store{constructor(){super(),this.all=e=>y(this,void 0,void 0,(function*(){e=e||i.noop;const t=yield exports.Session.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=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy().catch(i.noop),e&&e()})),this.destroy=(e,t)=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy({where:{session:e}}).catch(i.noop),t&&t()})),this.expired=()=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy({where:{expired:{[s.Op.lt]:Date.now()}}}).catch(i.noop)})),this.get=(e,t)=>y(this,void 0,void 0,(function*(){t=t||i.noop;const r=yield exports.Session.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(i.noop),void t(null)}t(null,e)}else t(null)})),this.length=e=>y(this,void 0,void 0,(function*(){e&&e(null,(yield exports.Session.count().catch(i.noop))||0)})),this.set=(e,t,r)=>y(this,void 0,void 0,(function*(){r=r||i.noop;const o=Date.now()+O.API_SESSION_LIFETIME,s=JSON.stringify(t),[n,d]=(yield exports.Session.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:o}}).catch(i.noop))||[];n&&(d||(n.json=s,n.expired=o,yield n.save().catch(i.noop))),r()})),this.loop=i.loop(this.expired,3e4),this.loop.start()}}class w{static create(e){return y(this,void 0,void 0,(function*(){if(!T.token)return{error:"KEY NOT FOUND"};const{id:t}=e,r=i.uuidv4(),o=yield exports.Auth.create({secret:r,user_id:t}).catch(w.error);if(!o)return{error:"INTERNAL SERVER ERROR"};return{auth:o,token:p.sign({id:t,secret:r},T.token,w.options())}}))}static destroy(e){return y(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){f.error(e.message,"api.token",O.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:O.API_TOKEN_LIFETIME+"ms"}}static renew(e){return y(this,void 0,void 0,(function*(){if(!T.token)return{error:"KEY NOT FOUND"};const{error:t,decode:r}=w.verify(e,O.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield exports.User.findOne({where:{id:e,state:!0}}).catch(w.error);if(r){const o=yield exports.Auth.findOne({where:{secret:t,user_id:r.id}}).catch(w.error);if(o&&!o.logout){o.secret=i.uuidv4(),yield o.save().catch(w.error);return{auth:o,token:p.sign({id:e,secret:o.secret},T.token,w.options())}}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}}))}static user(e,t,r){return y(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const o=yield exports.User.findOne({where:{token:t,state:!0}}).catch(w.error);if(o){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield exports.Auth.findOrCreate({where:{secret:t,user_id:o.id},defaults:{secret:t,user_id:o.id}}).catch(w.error))||[];if(r)return{auth:r,user:o}}return{error:"ACCESS DENIED"}}const{error:o,decode:i}=w.verify(t);if(o)return{error:o};if(i){const{id:e,secret:t}=i;if(e&&t){const r=yield exports.User.findOne({where:{id:e,state:!0}}).catch(w.error);if(r){const e=yield exports.Auth.findOne({where:{secret:t,user_id:r.id}}).catch(w.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}}))}static verify(e,t){if(!R.token)return{error:"CERT NOT FOUND"};if(!e||e.split(".").length<3)return{error:"INVALID TOKEN"};try{return{decode:p.verify(e,R.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class b extends e.Application{constructor(e){super(e,{cert:R.http,cross:O.API_HTTP_CROSS,hybrid:O.API_HTTP_HYBRID,key:T.http,notfound:O.API_HTTP_NOTFOUND,path:O.API_HTTP_PATH,port:O.API_HTTP_PORT,public:O.API_HTTP_PUBLIC,redirect:O.API_HTTP_REDIRECT,session:{store:new D,name:O.API_SESSION_NAME,secret:O.API_SESSION_SECRET,cookie:{maxAge:O.API_SESSION_LIFETIME},genid:i.uuidv4}}),this.hash=new r.Hash(O.API_KEY_HASH)}error(e,t){f.error(e.message,t,O.API_CONSOLE_ERROR)}log(e,t){f.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return y(this,void 0,void 0,(function*(){yield C.sync(),yield this.migrations(C),yield e.listen.call(this),O.API_WEBSOCKET_START&&this.server&&(this._webSocket=new n.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(O.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>y(this,void 0,void 0,(function*(){t.url||(t.url="");const r=t.url.length<=1?"":t.url.replace(/\//g,".");let o;e.on("message",(i=>y(this,void 0,void 0,(function*(){if(o)try{const s=JSON.parse(i);this.emit("ws.message"+r,{data:s,message:i,req:t,user:o,ws:e})}catch(s){this.emit("ws.message"+r,{erro:s,message:i,req:t,user:o,ws:e})}else{const{user:s}=yield w.user("",i.toString(),this);s&&(o=s,this.emit("ws.connection"+r,{req:t,user:o,ws:e}))}o||e.close()})))),e.on("close",(()=>{o&&this.emit("ws.close"+r,{user:o,ws:e})})),yield i.sleep(2e3),o||e.close()})))))}))}migrations(e){return y(this,void 0,void 0,(function*(){const r=[];yield i.forEachSeries(Object.keys(e.models),(t=>y(this,void 0,void 0,(function*(){var o;const i=e.models[t],{version:s}=_.migrations(i);if(!s)return;const[n,d]=null!==(o=yield exports.Migration.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),r.push(i))})))),r.length&&(yield t.migrate(e,r))}))}websocket(){return this._webSocket}}class N extends i.EventEmitter{auth(e,t,r,o,i){return y(this,void 0,void 0,(function*(){const{auth:s,error:n,user:d}=yield w.user(t,r,i);return n?e.error(n):s&&d?s.user_agent&&s.user_agent!=o?e.error("INVALID TOKEN"):(e.req.auth=s,e.req.user=d,void e.next()):e.error("INTERNAL SERVER ERROR")}))}create(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".create",r)}))}delete(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".delete",r)}))}error(e){f.error(e.message,"api.controller",O.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return y(this,void 0,void 0,(function*(){if(r){const o=yield this.permissions(r,{route:t});if(o&&o.length>0)return e.next()}e.unauthorized("ACCESS DENIED")}))}permissions(e,t){return y(this,void 0,void 0,(function*(){return yield exports.Permission.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:exports.GroupPermission,required:!0,include:[{model:exports.Group,required:!0,where:{state:!0},include:[{model:exports.UserGroup,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error)}))}read(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}session(e,t,r){return y(this,void 0,void 0,(function*(){r.auth&&r.user&&(r.user_agent?r.user_agent!=t&&r.regenerate(i.noop):(r.user_agent=t,r.save(i.noop))),e.next()}))}upload(t,r){r.path||(r.path=O.API_UPLOAD_TEMP),r.size||(r.size=O.API_UPLOAD_SIZE),r.field||(r.field=O.API_UPLOAD_FIELD),e.Upload.middleware(t,r)}update(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".update",r)}))}validation(e,t){return y(this,void 0,void 0,(function*(){const{error:r,value:o}=yield i.Validation.object(t).parse().validateAsync(e.req.body);if(r)return e.validation(r);e.req.body=o,e.next()}))}}u([c(0,e.Ctx()),c(1,e.Headers(O.API_KEY_HEADER)),c(2,e.Headers(O.API_TOKEN_HEADER)),c(3,e.Headers("user-agent")),c(4,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,String,b]),g("design:returntype",Promise)],N.prototype,"auth",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],N.prototype,"create",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],N.prototype,"delete",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],N.prototype,"permission",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],N.prototype,"read",null),u([c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Session()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object]),g("design:returntype",Promise)],N.prototype,"session",null),u([c(0,e.Ctx()),c(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",void 0)],N.prototype,"upload",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],N.prototype,"update",null),u([c(0,e.Ctx()),c(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",Promise)],N.prototype,"validation",null),exports.ModelController=class extends N{constructor(){super(...arguments),this._attributes=[]}_add(t){return y(this,arguments,void 0,(function*({ctx:t,options:r,body:o}){const i=yield this.model().create(Object.assign(Object.assign({},t.req.body),o||{}),Object.assign(Object.assign({},r||{}),x(t))).catch(this.error);if(i){const r=this.key();return t.prepare(e.Status.OK,{[r]:i.getDataValue(r)}),i}t.error("INTERNAL SERVER ERROR")}))}_all(r){return y(this,arguments,void 0,(function*({ctx:r,options:o,callback:n,scope:d,advanced:a,attributes:p,unlimited:l}){var u,c,g;const y=this.scope(d),x=Object.assign({},o||{}),{limit:h,offset:v,asc:m,desc:_,search:A,where:C}=r.req.query;if(i.isUndefined(x.limit)){const e=i.clamp(i.isString(h)?parseInt(h)||0:O.API_MODEL_LIMIT,-1,O.API_MODEL_LIMIT_MAX);x.limit=e>0?e:l?void 0:O.API_MODEL_LIMIT}if(i.isString(v)){const e=v&&parseInt(v)||0;x.offset=e>0?e:void 0}p=null!=p?p:this.attributes(null!==(u=null==x?void 0:x.attributes)&&void 0!==u?u:[]);const P=[],S=e=>p.indexOf(e)>=0;if(i.isString(m)&&m.length&&P.push(...m.split(";").filter(S).map((e=>[e,"ASC"]))),i.isString(_)&&_.length&&P.push(..._.split(";").filter(S).map((e=>[e,"DESC"]))),P.length&&(x.order=P),x.where=Object.assign({},x.where||{}),i.isString(C)&&(null==a||a)){const e=t.Where.parse(p,C);if(!i.isUndefined(e.error))return r.validation(e.error.join(", ")),{count:0,records:[]};x.where=Object.assign(Object.assign({},x.where),null!==(c=e.value)&&void 0!==c?c:{})}else{const e=[];p.forEach((t=>{i.isString(A)&&A.length&&e.push({[t]:{[s.Op.like]:`%${A}%`}})})),e.length&&(x.where=Object.assign(Object.assign({},x.where),{[s.Op.or]:[...e]}))}const E=y.count(Object.assign(Object.assign({},x),{distinct:!!x.include,col:this._attributes.length?this._attributes[0]:void 0})).catch(this.error),f=y.findAll(x).catch(this.error);yield Promise.allSettled([E,f]);const I=null!==(g=yield E)&&void 0!==g?g:0;let R=yield f;const T={count:I};return R?(R=n?yield n(R):R,(i.isNumber(null==o?void 0:o.limit)||0==I)&&(T.count=R.length),r.prepare(e.Status.OK,Object.assign(Object.assign({},T),{records:R})),Object.assign(Object.assign({},T),{records:R})):(r.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},T),{records:[]}))}))}_del(e){return y(this,arguments,void 0,(function*({ctx:e,options:t}){const r=this.key(),{[r]:o}=e.req.params;if(!o)return e.error("INTERNAL SERVER ERROR"),0;const i=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:o}),individualHooks:!0}),x(e))).catch(this.error);return i?(e.success("OK"),i):(e.notFound("RECORD NOT FOUND"),0)}))}_get(t){return y(this,arguments,void 0,(function*({ctx:t,options:r,callback:o,scope:i}){const s=this.key(),{[s]:n}=t.req.params,d=yield this.scope(i).findOne(Object.assign(Object.assign({},r||{}),{where:Object.assign(Object.assign({},(r||{}).where),{[s]:n})})).catch(this.error);return d?(t.prepare(e.Status.OK,o?yield o(d):d.toJSON()),d):null===d?t.notFound("RECORD NOT FOUND"):void t.error("INTERNAL SERVER ERROR")}))}_set(e){return y(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){var o;const i=this.key(),{[i]:s}=e.req.params,[n]=null!==(o=yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:s}),individualHooks:!0}),x(e))).catch(this.error))&&void 0!==o?o:[];return n?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)}))}attributes(e){if(0==this._attributes.length&&(this._attributes=Object.keys(this.model().getAttributes())),i.isArray(e))return e.map((e=>i.isString(e)&&-1!=this._attributes.indexOf(e)?e:void 0)).filter(i.isString);const{exclude:t,include:r}=e,o=i.isUndefined(r)?this._attributes:r.map((e=>i.isString(e)&&-1!=this._attributes.indexOf(e)?e:void 0)).filter(i.isString),s=null!=t?t:[];return s.length?o.filter((e=>-1==s.indexOf(e)?e:void 0)).filter(i.isString):o}error(e){e.sql?f.error(e.message+"\n"+e.sql,"api.controller.sql",O.API_CONSOLE_ERROR):super.error(e)}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}},exports.ModelController=u([e.Extends(N)],exports.ModelController),exports.AuditsController=class extends exports.ModelController{model(){return exports.Audit}all(e,t,r){return y(this,void 0,void 0,(function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this._all({ctx:e,options:{attributes:{exclude:["data","previously"]},where:o,order:[["created_at","DESC"]]}})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}},u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("table")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=u([e.Controller("/audits"),e.Extends(exports.ModelController)],exports.AuditsController),exports.AuthController=class extends N{login(e,t,o,n,d){return y(this,void 0,void 0,(function*(){var a;yield i.sleep(O.API_SLEEP_AUTH);const p=yield exports.User.scope("password").findOne({where:{[s.Op.or]:[{email:o},{username:o}]}}).catch(this.error);if(n+=null!==(a=null==p?void 0:p.salt)&&void 0!==a?a:"",!p||p.password!=r.sha256(n))return e.notFound("INVALID USERNAME OR PASSWORD"),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const l=yield exports.Register.findOne({where:{state:!0,user_id:p.id}}).catch(this.error);if(l)return e.error("ACTIVATION REQUIRED"),d.emit("auth.activation",{ctx:e,register:l,user:p}),void this.emit("auth.activation",{ctx:e,register:l,user:p});if(!p.state)return e.notFound("INVALID USERNAME OR PASSWORD"),d.emit("auth.failure",{ctx:e,user:p}),void this.emit("auth.failure",{ctx:e,user:p});const{auth:u,error:c,token:g}=yield w.create(p);return c?(e.error(c),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):u&&g?(u.user_agent=t,yield u.save().catch(this.error),e.json({token:g}),d.emit("auth.login",{auth:u,ctx:e,user:p}),void this.emit("auth.login",{auth:u,ctx:e,user:p})):(e.error("INTERNAL SERVER ERROR"),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,o){return y(this,void 0,void 0,(function*(){if(yield w.destroy(t))return e.success("OK"),o.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("ACCESS DENIED")}))}renew(e,t,r,o){return y(this,void 0,void 0,(function*(){const{auth:i,error:s,token:n}=yield w.renew(r);return s?e.error(s):i?(i.user_agent=t,yield i.save().catch(this.error),e.json({token:n}),o.emit("auth.renew",{auth:i,ctx:e}),void this.emit("auth.renew",{auth:i,ctx:e})):e.error("INTERNAL SERVER ERROR")}))}user(e,t){return y(this,void 0,void 0,(function*(){const r=yield this.permissions(t);if(!r)return e.error("INTERNAL SERVER ERROR");e.json(Object.assign(Object.assign({},i.denied(["username","date","description","state","created_at","updated_at","deleted_at"],t.toJSON())),{permissions:r.map((e=>e.route))}))}))}},u([e.Post("/login"),e.Middleware("validation",{username:i.Validation.string().min(3).required(),password:i.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("username")),c(3,e.Body("password")),c(4,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,String,b]),g("design:returntype",Promise)],exports.AuthController.prototype,"login",null),u([e.Get("/logout"),e.Middleware("auth"),c(0,e.Ctx()),c(1,v()),c(2,m()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.Auth,exports.User,b]),g("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),u([e.Post("/renew"),e.Middleware("validation",{token:i.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("token")),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,b]),g("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),u([e.Get(),e.Middleware("auth"),c(0,e.Ctx()),c(1,m()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=u([e.Controller("/auth"),e.Extends(N)],exports.AuthController),exports.FilesController=class extends N{directory(){return O.API_HTTP_PUBLIC||"./"}files(e){return y(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const r=l.join(this.directory(),t);if(!d.existsSync(r)||!d.statSync(r).isDirectory())return e.notFound("RECORD NOT FOUND");let o=[];return o=d.readdirSync(r),o=o.map((e=>this.info(l.join(r,e)))),o=o.filter(i.isDef),Object.assign(Object.assign({},this.info(r)),{files:o})}))}access(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!d.existsSync(e))return null;const t=d.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"}},u([e.Get("/path/?*"),e.Middleware("auth"),e.Middleware("access","list"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.FilesController.prototype,"files",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=u([e.Controller("/files"),e.Extends(N)],exports.FilesController),exports.ForgotController=class extends N{check(e,t){return y(this,void 0,void 0,(function*(){const r=yield this.find(t);if(!r||!r.user)return e.notFound("RECORD NOT FOUND");r.token=i.uniqueID(),yield r.save(),e.json({token:r.token})}))}forgot(e,t,r){return y(this,void 0,void 0,(function*(){yield i.sleep(O.API_SLEEP_FORGOT);const o=t,n=yield exports.User.findOne({where:{[s.Op.or]:[{email:o},{username:t}]}}).catch(this.error);if(!n)return e.notFound("RECORD NOT FOUND");const d=i.uniqueID(),a=Date.now()+6e4*O.API_TOKEN_FORGOT,p=yield exports.Forgot.create({token:d,timestamp:a,state:!0,user_id:n.id});e.success("OK"),r.emit("forgot.send",{ctx:e,forgot:p,user:n}),this.emit("forgot.send",{ctx:e,forgot:p,user:n})}))}reset(e,t,o,i){return y(this,void 0,void 0,(function*(){const s=yield this.find(t);if(!s)return e.notFound("RECORD NOT FOUND");s.state=!1,yield s.save().catch(this.error),s.user.password=r.sha256(o),yield s.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:s.user}),this.emit("forgot.reset",{ctx:e,user:s.user})}))}find(e){return y(this,void 0,void 0,(function*(){return yield exports.Forgot.findOne({where:{token:e,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error)}))}},u([e.Get("/check"),e.Middleware("validation",{token:i.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),u([e.Post(),e.Middleware("validation",{username:i.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,b]),g("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),u([e.Post("/reset"),e.Middleware("validation",{token:i.Validation.string().required(),password:i.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.Body("password")),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,b]),g("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=u([e.Controller("/forgot"),e.Extends(N)],exports.ForgotController),exports.CrudController=class extends exports.ModelController{constructor(){super(...arguments),this._crud={}}add(e){return y(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}CrudCreate(){return this._crud}del(e){return y(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return y(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}CrudUpdate(){return this._crud}validationAdd(e){return y(this,void 0,void 0,(function*(){const t=this.CrudCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)}))}validationSet(e){return y(this,void 0,void 0,(function*(){const t=this.CrudUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)}))}},u([e.Post(),e.Middleware("auth"),e.Middleware("create"),e.Middleware("validationAdd"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("delete"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"get",null),u([e.Put("/:id"),e.Middleware("auth"),e.Middleware("update"),e.Middleware("validationSet"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"set",null),u([c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationAdd",null),u([c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationSet",null),exports.CrudController=u([e.Extends(exports.ModelController)],exports.CrudController),exports.GroupsController=class extends exports.CrudController{model(){return exports.Group}CrudCreate(){return{name:i.Validation.string().required(),description:i.Validation.string().empty(""),state:i.Validation.boolean().parse().required()}}CrudUpdate(){return{name:i.Validation.string().empty(),description:i.Validation.string().empty(),state:i.Validation.boolean().parse().empty()}}},exports.GroupsController=u([e.Controller("/groups"),e.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsPermissionsController=class extends exports.ModelController{model(){return exports.GroupPermission}all(e,t){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{group_id:t},include:[{model:exports.Permission,required:!0}]},callback:e=>e.map((e=>e.permission))})}))}set(e,t,r,o){return y(this,void 0,void 0,(function*(){const s=yield exports.Group.findByPk(t,{attributes:["id"]}).catch(this.error);if(s){const t=s.id;if(yield exports.GroupPermission.destroy(Object.assign({where:{group_id:t},individualHooks:!0},o)),r){let e=0;yield i.sleep(1e3);for(let i=0;i<r.length;i++)e=yield exports.Permission.count({where:{id:r[i]}}),e&&(yield exports.GroupPermission.create({group_id:t,permission_id:r[i]},Object.assign({},o)))}return e.success("OK")}if(i.isNull(s))return e.notFound("RECORD NOT FOUND");e.error("INTERNAL SERVER ERROR")}))}},u([e.Get("/:id/permissions"),e.Middleware("auth"),e.Middleware("read","groups"),c(0,e.Ctx()),c(1,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"all",null),u([e.Put("/:id/permissions"),e.Middleware("auth"),e.Middleware("update","groups"),e.Middleware("validation",{permissions:i.Validation.array(i.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("permissions")),c(3,h()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array,Object]),g("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"set",null),exports.GroupsPermissionsController=u([e.Controller("/groups"),e.Extends(exports.ModelController)],exports.GroupsPermissionsController),exports.LogsController=class extends exports.ModelController{model(){return exports.Log}all(e,t,r){return y(this,void 0,void 0,(function*(){const o={};t&&(o.type=t),r&&(o.source=r),yield this._all({ctx:e,options:{where:o,order:[["created_at","DESC"]]}})}))}},u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("source")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=u([e.Controller("/logs"),e.Extends(exports.ModelController)],exports.LogsController),exports.PermissionsController=class extends exports.CrudController{model(){return exports.Permission}CrudCreate(){return{name:i.Validation.string().required(),route:i.Validation.string().required(),description:i.Validation.string().empty(""),state:i.Validation.boolean().parse().required()}}CrudUpdate(){return{name:i.Validation.string().empty(),route:i.Validation.string().empty(),description:i.Validation.string().empty(),state:i.Validation.boolean().parse().empty()}}},exports.PermissionsController=u([e.Controller("/permissions"),e.Extends(exports.CrudController)],exports.PermissionsController),exports.RegisterController=class extends N{register(e,t,o){return y(this,void 0,void 0,(function*(){yield i.sleep(O.API_SLEEP_REGISTRY);const{name:n,date:d,email:a,username:p,password:l,confirm:u}=t,c=p||a,g=r.sha256(l);if(yield exports.User.count({where:{[s.Op.or]:[{email:a},{username:c}]}}).catch(this.error))return e.validation("INVALID EMAIL OR USERNAME");if(g!=r.sha256(u))return e.error("INVALID PASSWORD");const y=yield exports.User.create({name:n,email:a,username:c,password:g,avatar:"",date:d,description:"",state:!1}).catch(this.error);if(!y)return e.error("INTERNAL SERVER ERROR");const x=yield exports.Register.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("INTERNAL SERVER ERROR");e.success("OK"),o.emit("register.user",{ctx:e,register:x,user:y}),this.emit("register.user",{ctx:e,register:x,user:y})}))}confirm(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield exports.Register.findOne({where:{token:t,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error);if(!o)return e.notFound("RECORD NOT FOUND");o.state=!1,yield o.save().catch(this.error),o.user.state=!0,yield o.user.save().catch(this.error),e.success("OK"),r.emit("register.confirm",{ctx:e,register:o,user:o.user}),this.emit("register.confirm",{ctx:e,register:o,user:o.user})}))}send(e,t,r){return y(this,void 0,void 0,(function*(){const o=t,i=yield exports.Register.findOne({where:{state:!0},include:[{model:exports.User,required:!0,where:{[s.Op.or]:[{email:o},{username:t}]}}]}).catch(this.error);if(!i)return e.notFound("RECORD NOT FOUND");e.success("OK"),r.emit("register.send",{ctx:e,register:i,user:i.user}),this.emit("register.send",{ctx:e,register:i,user:i.user})}))}getId(){return y(this,void 0,void 0,(function*(){const e=i.uuidv4();return(yield exports.Register.count({where:{token:e}}))?this.getId():e}))}},u([e.Post(),e.Middleware("validation",{name:i.Validation.string().required(),date:i.Validation.date().required(),email:i.Validation.string().email().required(),username:i.Validation.string().min(4).empty(),password:i.Validation.string().min(5).required(),confirm:i.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body()),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,Object,b]),g("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),u([e.Post("/confirm"),e.Middleware("validation",{token:i.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,b]),g("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),u([e.Post("/send"),e.Middleware("validation",{username:i.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,b]),g("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=u([e.Controller("/register"),e.Extends(N)],exports.RegisterController),exports.SetupController=class extends N{setup(e,t){return y(this,void 0,void 0,(function*(){if(0==(yield exports.User.count())){const e=i.uniqueID(),o=yield exports.User.create({name:"Admin",email:"admin@localhost",username:"admin",password:r.sha256("admin"+e),salt:e,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},t)),s={description:"API CORE",state:!0},n=yield exports.Group.create(Object.assign({name:"Admin"},s),Object.assign({},t));yield exports.UserGroup.create({user_id:o.id,group_id:n.id},Object.assign({},t));const d=["Users","Groups","Permissions"],a=["Create","Read","Update","Delete"];yield i.forEachSeries(d,(e=>y(this,void 0,void 0,(function*(){yield i.forEachSeries(a,(r=>y(this,void 0,void 0,(function*(){const o=yield exports.Permission.create(Object.assign({name:`${e} ${r}`,route:`${e.toLowerCase()}.${r.toLowerCase()}`},s),Object.assign({},t));yield exports.GroupPermission.create({group_id:n.id,permission_id:o.id},Object.assign({},t))}))))}))));const p=["Delete","List","Read","Rename","Upload","Write"];yield i.forEachSeries(p,(e=>y(this,void 0,void 0,(function*(){const r=yield exports.Permission.create(Object.assign({name:`Files ${e}`,route:`files.${e.toLowerCase()}`},s),Object.assign({},t));yield exports.GroupPermission.create({group_id:n.id,permission_id:r.id},Object.assign({},t))}))));const l=["Audits","Logs"];yield i.forEachSeries(l,(e=>y(this,void 0,void 0,(function*(){const r=yield exports.Permission.create(Object.assign({name:`${e} Read`,route:`${e.toLowerCase()}.read`},s),Object.assign({},t));yield exports.GroupPermission.create({group_id:n.id,permission_id:r.id},Object.assign({},t))}))))}e.success("OK")}))}},u([e.Get(),c(0,e.Ctx()),c(1,h()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=u([e.Controller("/setup"),e.Extends(N)],exports.SetupController),exports.UsersController=class extends exports.ModelController{model(){return exports.User}constructor(){super(),this.path=O.API_HTTP_PUBLIC+"/avatar",O.API_HTTP_PUBLIC&&d.existsSync(O.API_HTTP_PUBLIC)&&!d.existsSync(this.path)&&d.mkdirSync(this.path)}avatar(e,t,r,o){return y(this,void 0,void 0,(function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.path+"/"+r.avatar;if(d.existsSync(t)&&d.lstatSync(t).isFile()&&d.rmSync(t),r.avatar=i,yield r.save(Object.assign({},o)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")}))}avatar_delete(e,t,r){return y(this,void 0,void 0,(function*(){const o=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},r)).catch(this.error))&&d.existsSync(o)&&d.rmSync(o),e.success("OK")}))}password(e,t,o,s,n){return y(this,void 0,void 0,(function*(){var d;if(O.API_USER_HISTORY){if(yield exports.UserHistory.count({where:{password:r.sha256(o+s.id)}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED")}const a=yield this.scope("password").findOne({where:{id:s.id,state:!0}}).catch(this.error);return t+=null!==(d=null==a?void 0:a.salt)&&void 0!==d?d:"",a&&a.password==r.sha256(t)?(a.salt=i.uniqueID(),a.password=r.sha256(o+a.salt),(yield a.save(Object.assign({},n)).catch(this.error))?e.success("OK"):void e.success("RECORD NOT CHANGED")):e.error("INVALID PASSWORD")}))}token(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(o)return e.json({token:r.hash.decrypt(o.token)});e.notFound("RECORD NOT FOUND")}))}token_get(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(o)return e.json({token:r.hash.decrypt(o.token)});e.notFound("RECORD NOT FOUND")}))}token_delete(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(o)return o.token="",yield o.save(Object.assign({},r)).catch(this.error),e.success("OK");e.notFound("RECORD NOT FOUND")}))}token_renew(e,t,r,o){return y(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(i){const t=yield this.token_new();return i.token=o.hash.encrypt(t),yield i.save(Object.assign({},r)).catch(this.error),e.json({token:t})}e.notFound("RECORD NOT FOUND")}))}token_new(){return y(this,void 0,void 0,(function*(){var e;const t=i.uuidv4();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t}))}add(e,t){return y(this,void 0,void 0,(function*(){const o=i.uniqueID(),s=yield this._add({ctx:e,body:{password:r.sha256(t+o),salt:o}});O.API_USER_HISTORY&&s&&(yield exports.UserHistory.create({password:r.sha256(t+s.id),user_id:s.id}))}))}all(e){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{attributes:{exclude:["password","salt","token"]}}})}))}del(e,t,r){return y(this,void 0,void 0,(function*(){if(r.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this._del({ctx:e})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t,o){return y(this,void 0,void 0,(function*(){if(O.API_USER_HISTORY&&o){const i=r.sha256(o+t);if(yield exports.UserHistory.count({where:{password:i}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED");yield exports.UserHistory.create({password:i,user_id:t}).catch(this.error)}const s=o?i.uniqueID():"";yield this._set({ctx:e,body:o?{password:r.sha256(o+s),salt:s}:{}})}))}},u([e.Post("/avatar"),e.Middleware("auth"),e.Middleware("upload",(e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32}))),c(0,e.Ctx()),c(1,e.Files()),c(2,m()),c(3,h()),g("design:type",Function),g("design:paramtypes",[e.Context,Array,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),u([e.Delete("/avatar"),e.Middleware("auth"),c(0,e.Ctx()),c(1,m()),c(2,h()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar_delete",null),u([e.Post("/password"),e.Middleware("auth"),e.Middleware("validation",{oldPassword:i.Validation.string().min(5).required(),newPassword:i.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("oldPassword")),c(2,e.Body("newPassword")),c(3,m()),c(4,h()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"password",null),u([e.Get("/token"),e.Middleware("auth"),c(0,e.Ctx()),c(1,m()),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,b]),g("design:returntype",Promise)],exports.UsersController.prototype,"token",null),u([e.Get("/token/:id"),e.Middleware("auth"),e.Middleware("create"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,b]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_get",null),u([e.Delete("/token/:id"),e.Middleware("auth"),e.Middleware("delete"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,h()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_delete",null),u([e.Get("/token/renew/:id"),e.Middleware("auth"),e.Middleware("update"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,h()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object,b]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_renew",null),u([e.Post(),e.Middleware("auth"),e.Middleware("create"),e.Middleware("validation",{name:i.Validation.string().required(),email:i.Validation.string().email().required(),username:i.Validation.string().min(4).required(),password:i.Validation.string().min(5).required(),description:i.Validation.string().empty(""),state:i.Validation.boolean().parse().required()}),c(0,e.Ctx()),c(1,e.Body("password")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.UsersController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("delete"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,m()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],exports.UsersController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.UsersController.prototype,"get",null),u([e.Put("/:id"),e.Middleware("auth"),e.Middleware("update"),e.Middleware("validation",{name:i.Validation.string().empty(),email:i.Validation.string().email().empty(),username:i.Validation.string().min(4).empty(),password:i.Validation.string().min(5).empty().filter(""),description:i.Validation.string().empty(),state:i.Validation.boolean().parse().empty()}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("password")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=u([e.Controller("/users"),e.Extends(exports.ModelController),g("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ModelController{model(){return exports.UserGroup}groups(e,t){return y(this,void 0,void 0,(function*(){yield this.all(e,t.id.toString())}))}all(e,t){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{user_id:t},include:[{model:exports.Group,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,r,o){return y(this,void 0,void 0,(function*(){const s=yield exports.User.findByPk(t,{attributes:["id"]}).catch(this.error);if(s){if(yield exports.UserGroup.destroy(Object.assign({where:{user_id:s.id},individualHooks:!0},o)),r){let e=0;yield i.sleep(1e3);for(let t=0;t<r.length;t++)e=yield exports.Group.count({where:{id:r[t]}}),e&&(yield exports.UserGroup.create({user_id:s.id,group_id:r[t]},Object.assign({},o)))}return e.success("OK")}if(i.isNull(s))return e.notFound("RECORD NOT FOUND");e.error("INTERNAL SERVER ERROR")}))}},u([e.Get("/groups"),e.Middleware("auth"),e.Middleware("read","users"),c(0,e.Ctx()),c(1,m()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"groups",null),u([e.Get("/:id/groups"),e.Middleware("auth"),e.Middleware("read","users"),c(0,e.Ctx()),c(1,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),u([e.Put("/:id/groups"),e.Middleware("auth"),e.Middleware("update","users"),e.Middleware("validation",{groups:i.Validation.array(i.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("groups")),c(3,h()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array,Object]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=u([e.Controller("/users"),e.Extends(exports.ModelController)],exports.UsersGroupsController);class U{static all(){return y(this,void 0,void 0,(function*(){const e=yield exports.Configs.findAll().catch(U.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e,t){return y(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.Configs.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:o})).catch(U.error))||0)>0}))}static error(e){f.error(e.message,"api.config",O.API_CONSOLE_ERROR)}static get(e){return y(this,arguments,void 0,(function*(e,t=""){const[r]=(yield exports.Configs.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(U.error))||[];return r?r.value:t}))}static set(e,t,r){return y(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.Configs.findOrCreate(Object.assign({where:{key:e}},{user_id:i})).catch(U.error))||[];s&&(s.value=t,yield s.save().catch(U.error))}))}}exports.Application=b,exports.Config=U,exports.ControllerBase=N,exports.Env=O,exports.Logs=f,exports.Metadata=_,exports.Migrate=A,exports.Model=P,exports.ReqAudit=h,exports.ReqAuth=v,exports.ReqUser=m,exports.Store=D,exports.Token=w,exports.audit=x,exports.crt=R,exports.database=C,exports.hooks=E,exports.key=T;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/api v4.2.0
2
+ * @andrewcaires/api v4.2.1
3
3
  * Simple api for small applications using express, jsonwebtoken, sequelize and websocket
4
- * (c) 2024 Andrew Caires
4
+ * (c) 2025 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
7
  import { Context, Application as Application$1, IStore, IUpload, IFile } from '@andrewcaires/express';
@@ -182,6 +182,7 @@ interface ArgumentsModelAll<M extends Model$2<M>> {
182
182
  callback?: CallbackModelAll<M>;
183
183
  scope?: string;
184
184
  advanced?: boolean;
185
+ attributes?: Array<string>;
185
186
  unlimited?: boolean;
186
187
  }
187
188
 
@@ -260,7 +261,7 @@ declare abstract class ControllerBase extends EventEmitter {
260
261
  declare abstract class ModelController<M extends Model$2<M>> extends ControllerBase {
261
262
  private _attributes;
262
263
  protected _add({ ctx, options, body }: ArgumentsModelAdd<M>): Promise<M | void>;
263
- protected _all({ ctx, options, callback, scope, advanced, unlimited }: ArgumentsModelAll<M>): Promise<ResultModelAll<M>>;
264
+ protected _all({ ctx, options, callback, scope, advanced, attributes, unlimited }: ArgumentsModelAll<M>): Promise<ResultModelAll<M>>;
264
265
  protected _del({ ctx, options }: ArgumentsModelDel<M>): Promise<number>;
265
266
  protected _get({ ctx, options, callback, scope }: ArgumentsModelGet<M>): Promise<M | void>;
266
267
  protected _set({ ctx, options, body }: ArgumentsModelSet<M>): Promise<boolean>;
package/dist/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/api v4.2.0
2
+ * @andrewcaires/api v4.2.1
3
3
  * Simple api for small applications using express, jsonwebtoken, sequelize and websocket
4
- * (c) 2024 Andrew Caires
4
+ * (c) 2025 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- import{parameterFactory as e,Application as t,Ctx as i,Headers as r,App as s,Argument as n,Session as o,Upload as d,Context as a,Extends as u,Status as p,Get as c,Middleware as l,Query as y,Controller as g,Post as h,Body as v,Delete as _,Put as m,Params as O,Files as f}from"@andrewcaires/express";import{Connection as E,Model as P,Id as I,String as A,FullDate as R,CreatedAt as S,UpdatedAt as T,DeletedAt as D,BelongsTo as b,Database as N,ModelName as w,Boolean as j,Text as x,HasMany as F,Hooks as k,DateOnly as L,DefaultScope as C,Scopes as U,Enum as H,Json as K,BigInt as q,Unique as B,migrate as M,Where as V}from"@andrewcaires/sequelize";import{Metadata as Y,Env as G,LogColor as W,Log as z,Hash as $,sha256 as J}from"@andrewcaires/node";import{config as X}from"dotenv";import{isObject as Z,noop as Q,loop as ee,uuidv4 as te,sleep as ie,forEachSeries as re,EventEmitter as se,Validation as ne,isArray as oe,isString as de,isUndefined as ae,clamp as ue,isNumber as pe,denied as ce,isDef as le,uniqueID as ye,isNull as ge}from"@andrewcaires/utils.js";import{Op as he}from"sequelize";import{WebSocketServer as ve}from"ws";import{existsSync as _e,readFileSync as me,statSync as Oe,readdirSync as fe,mkdirSync as Ee,lstatSync as Pe,rmSync as Ie}from"fs";import{Store as Ae}from"express-session";import Re from"jsonwebtoken";import{join as Se}from"path";function Te(e,t,i,r){var s,n=arguments.length,o=n<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--)(s=e[d])&&(o=(n<3?s(o):n>3?s(t,i,o):s(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}function De(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 Ne(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{a(r.next(e))}catch(e){n(e)}}function d(e){try{a(r.throw(e))}catch(e){n(e)}}function a(e){var t;e.done?s(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())}))}"function"==typeof SuppressedError&&SuppressedError;const we=e=>{var t,i,r,s,n,o,d,a,u;return{audit_client:null!==(t=e.ip())&&void 0!==t?t:"0.0.0.0",audit_href:(null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.protocol)+"://"+(null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.get("host"))+(null===(s=null==e?void 0:e.req)||void 0===s?void 0:s.originalUrl),audit_user_agent:null!==(o=null===(n=e.req)||void 0===n?void 0:n.headers["user-agent"])&&void 0!==o?o:"",audit_user_id:null!==(u=null===(a=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.user)||void 0===a?void 0:a.id)&&void 0!==u?u:null}},je=e((({ctx:e})=>we(e))),xe=e((({ctx:e})=>e.req.auth)),Fe=e((({ctx:e})=>e.req.user));class ke{static migrations(e){return Y(ke.MIGRATE,e,{version:""})}}ke.MIGRATE=Symbol();const Le=e=>t=>{ke.migrations(t).version=e};X();class Ce extends G{}Ce.API_CONSOLE_ERROR=Ce.getBool("API_CONSOLE_ERROR",!1),Ce.API_DB_DATABASE=Ce.getString("API_DB_DATABASE",""),Ce.API_DB_HOST=Ce.getString("API_DB_HOST","127.0.0.1"),Ce.API_DB_PASSWORD=Ce.getString("API_DB_PASSWORD",""),Ce.API_DB_PORT=Ce.getInt("API_DB_PORT",3306),Ce.API_DB_TYPE=Ce.getString("API_DB_TYPE",""),Ce.API_DB_USERNAME=Ce.getString("API_DB_USERNAME","root"),Ce.API_DB_LOG=Ce.getBool("API_DB_LOG",!1),Ce.API_DB_AUDIT=Ce.getBool("API_DB_AUDIT",!0),Ce.API_DB_PREFIX=Ce.getString("API_DB_PREFIX",""),Ce.API_DB_TIMEZONE=Ce.getString("API_DB_TIMEZONE","+00:00"),Ce.API_HTTP_CRT=Ce.getString("API_HTTP_CRT",""),Ce.API_HTTP_KEY=Ce.getString("API_HTTP_KEY",""),Ce.API_HTTP_PORT=Ce.getInt("API_HTTP_PORT",3e3),Ce.API_HTTP_PUBLIC=Ce.getString("API_HTTP_PUBLIC",""),Ce.API_HTTP_CROSS=Ce.getBool("API_HTTP_CROSS",!1),Ce.API_HTTP_HYBRID=Ce.getBool("API_HTTP_HYBRID",!1),Ce.API_HTTP_NOTFOUND=Ce.getString("API_HTTP_NOTFOUND",""),Ce.API_HTTP_PATH=Ce.getString("API_HTTP_PATH","/api"),Ce.API_HTTP_REDIRECT=Ce.getString("API_HTTP_REDIRECT",""),Ce.API_KEY_HASH=Ce.getString("API_KEY_HASH",""),Ce.API_KEY_HEADER=Ce.getString("API_KEY_HEADER","api_key"),Ce.API_MODEL_LIMIT=Ce.getInt("API_MODEL_LIMIT",10),Ce.API_MODEL_LIMIT_MAX=Ce.getInt("API_MODEL_LIMIT_MAX",500),Ce.API_SLEEP_AUTH=Ce.getMs("API_SLEEP_AUTH","2s"),Ce.API_SLEEP_FORGOT=Ce.getMs("API_SLEEP_FORGOT","5s"),Ce.API_SLEEP_REGISTRY=Ce.getMs("API_SLEEP_REGISTRY","5s"),Ce.API_SESSION_NAME=Ce.getString("API_SESSION_NAME","session.id"),Ce.API_SESSION_LIFETIME=Ce.getMs("API_SESSION_LIFETIME","1d"),Ce.API_SESSION_SECRET=Ce.getString("API_SESSION_SECRET","yoursecret"),Ce.API_TOKEN_CRT=Ce.getString("API_TOKEN_CRT",""),Ce.API_TOKEN_KEY=Ce.getString("API_TOKEN_KEY",""),Ce.API_TOKEN_FORGOT=Ce.getMs("API_TOKEN_LIFETIME","1d"),Ce.API_TOKEN_HEADER=Ce.getString("API_TOKEN_HEADER","authorization"),Ce.API_TOKEN_LIFETIME=Ce.getMs("API_TOKEN_LIFETIME","1d"),Ce.API_TOKEN_RENEW=Ce.getMs("API_TOKEN_RENEW","1d"),Ce.API_UPLOAD_COUNT=Ce.getInt("API_UPLOAD_COUNT",1),Ce.API_UPLOAD_FIELD=Ce.getString("API_UPLOAD_FIELD","upload"),Ce.API_UPLOAD_SIZE=Ce.getInt("API_UPLOAD_SIZE",2),Ce.API_UPLOAD_TEMP=Ce.getString("API_UPLOAD_TEMP","./temp"),Ce.API_USER_HISTORY=Ce.getBool("API_USER_HISTORY",!0),Ce.API_WEBSOCKET_START=Ce.getBool("API_WEBSOCKET_START",!1);const Ue=new E({type:Ce.API_DB_TYPE,database:Ce.API_DB_DATABASE,username:Ce.API_DB_USERNAME,password:Ce.API_DB_PASSWORD,hostname:Ce.API_DB_HOST,hostport:Ce.API_DB_PORT,logging:Ce.API_DB_LOG,prefix:Ce.API_DB_PREFIX,timezone:Ce.API_DB_TIMEZONE});class He extends P{constructor(){super(...arguments),this._version=""}}const Ke=(e,t,i)=>{var r,s,n,o,d;return{type:e,model:null!==(r=null==t?void 0:t.getTableName())&&void 0!==r?r:null,client:null!==(s=null==i?void 0:i.audit_client)&&void 0!==s?s:null,href:null!==(n=null==i?void 0:i.audit_href)&&void 0!==n?n:null,user_agent:null!==(o=null==i?void 0:i.audit_user_agent)&&void 0!==o?o:null,user_id:null!==(d=null==i?void 0:i.audit_user_id)&&void 0!==d?d:null,state:!0}},qe={afterCreate:(e,t)=>Ne(void 0,void 0,void 0,(function*(){var i;if(!Ce.API_DB_AUDIT)return;const r=Z(e)?e.constructor:null,s=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null;yield ze.create(Object.assign(Object.assign({},Ke("CREATE",r,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(Q)})),afterUpdate:(e,t)=>Ne(void 0,void 0,void 0,(function*(){var i;if(!Ce.API_DB_AUDIT)return;const r=Z(e)?e.constructor:null,s=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null,n={},o=e.changed();o&&o.forEach((t=>n[t]=e.getDataValue(t))),yield ze.create(Object.assign(Object.assign({},Ke("UPDATE",r,t)),{record:s?e.getDataValue(s):null,data:n,previously:e.previous()})).catch(Q)})),afterDestroy:(e,t)=>Ne(void 0,void 0,void 0,(function*(){var i;if(!Ce.API_DB_AUDIT)return;const r=Z(e)?e.constructor:null,s=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null;yield ze.create(Object.assign(Object.assign({},Ke("DELETE",r,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(Q)}))};let Be=class extends He{};Te([I(),be("design:type",Number)],Be.prototype,"id",void 0),Te([A(),be("design:type",A)],Be.prototype,"secret",void 0),Te([R(),be("design:type",Date)],Be.prototype,"logout",void 0),Te([A(),be("design:type",A)],Be.prototype,"user_agent",void 0),Te([S,be("design:type",Date)],Be.prototype,"created_at",void 0),Te([T,be("design:type",Date)],Be.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],Be.prototype,"deleted_at",void 0),Te([b((()=>We)),be("design:type",Number)],Be.prototype,"user_id",void 0),Be=Te([N(Ue),w("auth"),Le("4.2.0")],Be);let Me=class extends He{};Te([I(),be("design:type",Number)],Me.prototype,"id",void 0),Te([A(),be("design:type",A)],Me.prototype,"token",void 0),Te([j(),be("design:type",j)],Me.prototype,"state",void 0),Te([S,be("design:type",Date)],Me.prototype,"created_at",void 0),Te([T,be("design:type",Date)],Me.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],Me.prototype,"deleted_at",void 0),Te([b((()=>We)),be("design:type",Number)],Me.prototype,"user_id",void 0),Me=Te([N(Ue),w("register"),Le("4.2.0")],Me);let Ve=class extends He{};Te([I(),be("design:type",Number)],Ve.prototype,"id",void 0),Te([A(),be("design:type",A)],Ve.prototype,"name",void 0),Te([x(),be("design:type",A)],Ve.prototype,"description",void 0),Te([j(),be("design:type",j)],Ve.prototype,"state",void 0),Te([S,be("design:type",Date)],Ve.prototype,"created_at",void 0),Te([T,be("design:type",Date)],Ve.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],Ve.prototype,"deleted_at",void 0),Te([F((()=>Ye),"group_id"),be("design:type",Array)],Ve.prototype,"groups_routes",void 0),Te([F((()=>Ye),"group_id"),be("design:type",Array)],Ve.prototype,"users_groups",void 0),Ve=Te([N(Ue),w("group"),k(qe),Le("4.2.0")],Ve);let Ye=class extends He{};Te([S,be("design:type",Date)],Ye.prototype,"created_at",void 0),Te([b((()=>Ve)),be("design:type",Number)],Ye.prototype,"group_id",void 0),Te([b((()=>We)),be("design:type",Number)],Ye.prototype,"user_id",void 0),Ye=Te([N(Ue),w("users_groups"),k(qe),Le("4.2.0")],Ye);let Ge=class extends He{};Te([A(),be("design:type",A)],Ge.prototype,"password",void 0),Te([S,be("design:type",Date)],Ge.prototype,"created_at",void 0),Te([b((()=>We)),be("design:type",Number)],Ge.prototype,"user_id",void 0),Ge=Te([N(Ue),w("users_histories"),Le("4.2.0")],Ge);let We=class extends He{};Te([I(),be("design:type",Number)],We.prototype,"id",void 0),Te([A(),be("design:type",A)],We.prototype,"name",void 0),Te([A(),be("design:type",A)],We.prototype,"email",void 0),Te([A(),be("design:type",A)],We.prototype,"username",void 0),Te([A(),be("design:type",A)],We.prototype,"password",void 0),Te([A(),be("design:type",A)],We.prototype,"salt",void 0),Te([A(),be("design:type",A)],We.prototype,"token",void 0),Te([A(),be("design:type",A)],We.prototype,"avatar",void 0),Te([L(),be("design:type",A)],We.prototype,"date",void 0),Te([x(),be("design:type",A)],We.prototype,"description",void 0),Te([j(),be("design:type",j)],We.prototype,"state",void 0),Te([S,be("design:type",Date)],We.prototype,"created_at",void 0),Te([T,be("design:type",Date)],We.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],We.prototype,"deleted_at",void 0),Te([F((()=>ze),"user_id"),be("design:type",Array)],We.prototype,"audits",void 0),Te([F((()=>Be),"user_id"),be("design:type",Array)],We.prototype,"auths",void 0),Te([F((()=>Me),"user_id"),be("design:type",Array)],We.prototype,"registers",void 0),Te([F((()=>Ye),"user_id"),be("design:type",Array)],We.prototype,"users_groups",void 0),Te([F((()=>Ge),"user_id"),be("design:type",Array)],We.prototype,"users_histories",void 0),We=Te([N(Ue),w("user"),C({attributes:{exclude:["password","salt","token"]}}),U({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),k(qe),Le("4.2.0")],We);let ze=class extends He{};Te([I(),be("design:type",Number)],ze.prototype,"id",void 0),Te([H("CREATE","DELETE","UPDATE"),be("design:type",A)],ze.prototype,"type",void 0),Te([A(),be("design:type",A)],ze.prototype,"model",void 0),Te([A(),be("design:type",A)],ze.prototype,"record",void 0),Te([K(),be("design:type",Object)],ze.prototype,"data",void 0),Te([K(),be("design:type",Object)],ze.prototype,"previously",void 0),Te([A(),be("design:type",A)],ze.prototype,"client",void 0),Te([x(),be("design:type",A)],ze.prototype,"href",void 0),Te([A(),be("design:type",A)],ze.prototype,"user_agent",void 0),Te([j(),be("design:type",j)],ze.prototype,"state",void 0),Te([S,be("design:type",Date)],ze.prototype,"created_at",void 0),Te([T,be("design:type",Date)],ze.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],ze.prototype,"deleted_at",void 0),Te([b((()=>We)),be("design:type",Number)],ze.prototype,"user_id",void 0),ze=Te([N(Ue),w("audit"),Le("4.2.0")],ze);let $e=class extends He{};Te([A(),be("design:type",A)],$e.prototype,"key",void 0),Te([A(),be("design:type",A)],$e.prototype,"value",void 0),Te([S,be("design:type",Date)],$e.prototype,"created_at",void 0),Te([T,be("design:type",Date)],$e.prototype,"updated_at",void 0),$e=Te([N(Ue),w("configs"),k(qe),Le("4.2.0")],$e);let Je=class extends He{};Te([I(),be("design:type",Number)],Je.prototype,"id",void 0),Te([A(),be("design:type",A)],Je.prototype,"token",void 0),Te([q(),be("design:type",Number)],Je.prototype,"timestamp",void 0),Te([j(),be("design:type",j)],Je.prototype,"state",void 0),Te([S,be("design:type",Date)],Je.prototype,"created_at",void 0),Te([T,be("design:type",Date)],Je.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],Je.prototype,"deleted_at",void 0),Te([b((()=>We)),be("design:type",Number)],Je.prototype,"user_id",void 0),Je=Te([N(Ue),w("forgot"),Le("4.2.0")],Je);let Xe=class extends He{};Te([I(),be("design:type",Number)],Xe.prototype,"id",void 0),Te([A(),be("design:type",A)],Xe.prototype,"name",void 0),Te([A(),B(!0),be("design:type",A)],Xe.prototype,"route",void 0),Te([x(),be("design:type",A)],Xe.prototype,"description",void 0),Te([j(),be("design:type",j)],Xe.prototype,"state",void 0),Te([S,be("design:type",Date)],Xe.prototype,"created_at",void 0),Te([T,be("design:type",Date)],Xe.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],Xe.prototype,"deleted_at",void 0),Te([F((()=>Ze),"permission_id"),be("design:type",Array)],Xe.prototype,"groups_permissions",void 0),Xe=Te([N(Ue),w("permission"),k(qe),Le("4.2.0")],Xe);let Ze=class extends He{};Te([S,be("design:type",Date)],Ze.prototype,"created_at",void 0),Te([b((()=>Ve)),be("design:type",Number)],Ze.prototype,"group_id",void 0),Te([b((()=>Xe)),be("design:type",Number)],Ze.prototype,"permission_id",void 0),Ze=Te([N(Ue),w("groups_permissions"),k(qe),Le("4.2.0")],Ze);let Qe=class extends He{};Te([I(),be("design:type",Number)],Qe.prototype,"id",void 0),Te([A(),be("design:type",A)],Qe.prototype,"type",void 0),Te([A(),be("design:type",A)],Qe.prototype,"source",void 0),Te([x(),be("design:type",A)],Qe.prototype,"message",void 0),Te([S,be("design:type",Date)],Qe.prototype,"created_at",void 0),Qe=Te([N(Ue),w("log"),Le("4.2.0")],Qe);let et=class extends He{};Te([A(),be("design:type",A)],et.prototype,"model",void 0),Te([A(),be("design:type",A)],et.prototype,"version",void 0),Te([S,be("design:type",Date)],et.prototype,"created_at",void 0),Te([T,be("design:type",Date)],et.prototype,"updated_at",void 0),et=Te([N(Ue),w("migration"),Le("4.2.0")],et);let tt=class extends He{};Te([A(),be("design:type",A)],tt.prototype,"session",void 0),Te([x(),be("design:type",A)],tt.prototype,"json",void 0),Te([q(),be("design:type",Number)],tt.prototype,"expired",void 0),Te([S,be("design:type",Date)],tt.prototype,"created_at",void 0),Te([T,be("design:type",Date)],tt.prototype,"updated_at",void 0),tt=Te([N(Ue),w("session"),Le("4.2.0")],tt);class it{static write(e,t,i){return Ne(this,void 0,void 0,(function*(){yield it.writeRaw(W.White,"",e,t,i)}))}static error(e,t,i){return Ne(this,void 0,void 0,(function*(){yield it.writeRaw(W.Red,"error",e,t,i)}))}static info(e,t,i){return Ne(this,void 0,void 0,(function*(){yield it.writeRaw(W.Cyan,"info",e,t,i)}))}static success(e,t,i){return Ne(this,void 0,void 0,(function*(){yield it.writeRaw(W.Green,"success",e,t,i)}))}static warning(e,t,i){return Ne(this,void 0,void 0,(function*(){yield it.writeRaw(W.Yellow,"warning",e,t,i)}))}static writeRaw(e,t,i,r,s){return Ne(this,void 0,void 0,(function*(){s&&z.console(e,t,i),Ue&&(yield Qe.create({type:t,source:r,message:i}).catch((()=>null)))}))}}const rt=e=>_e(e)?me(e):void 0,st={http:rt(Ce.API_HTTP_CRT),token:rt(Ce.API_TOKEN_CRT)},nt={http:rt(Ce.API_HTTP_KEY),token:rt(Ce.API_TOKEN_KEY)};class ot extends Ae{constructor(){super(),this.all=e=>Ne(this,void 0,void 0,(function*(){e=e||Q;const t=yield tt.findAll({attributes:["session"],where:{expired:{[he.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>Ne(this,void 0,void 0,(function*(){yield tt.destroy().catch(Q),e&&e()})),this.destroy=(e,t)=>Ne(this,void 0,void 0,(function*(){yield tt.destroy({where:{session:e}}).catch(Q),t&&t()})),this.expired=()=>Ne(this,void 0,void 0,(function*(){yield tt.destroy({where:{expired:{[he.lt]:Date.now()}}}).catch(Q)})),this.get=(e,t)=>Ne(this,void 0,void 0,(function*(){t=t||Q;const i=yield tt.findOne({where:{session:e,expired:{[he.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(Q),void t(null)}t(null,e)}else t(null)})),this.length=e=>Ne(this,void 0,void 0,(function*(){e&&e(null,(yield tt.count().catch(Q))||0)})),this.set=(e,t,i)=>Ne(this,void 0,void 0,(function*(){i=i||Q;const r=Date.now()+Ce.API_SESSION_LIFETIME,s=JSON.stringify(t),[n,o]=(yield tt.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:r}}).catch(Q))||[];n&&(o||(n.json=s,n.expired=r,yield n.save().catch(Q))),i()})),this.loop=ee(this.expired,3e4),this.loop.start()}}class dt{static create(e){return Ne(this,void 0,void 0,(function*(){if(!nt.token)return{error:"KEY NOT FOUND"};const{id:t}=e,i=te(),r=yield Be.create({secret:i,user_id:t}).catch(dt.error);if(!r)return{error:"INTERNAL SERVER ERROR"};return{auth:r,token:Re.sign({id:t,secret:i},nt.token,dt.options())}}))}static destroy(e){return Ne(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){it.error(e.message,"api.token",Ce.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:Ce.API_TOKEN_LIFETIME+"ms"}}static renew(e){return Ne(this,void 0,void 0,(function*(){if(!nt.token)return{error:"KEY NOT FOUND"};const{error:t,decode:i}=dt.verify(e,Ce.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(i){const{id:e,secret:t}=i;if(e&&t){const i=yield We.findOne({where:{id:e,state:!0}}).catch(dt.error);if(i){const r=yield Be.findOne({where:{secret:t,user_id:i.id}}).catch(dt.error);if(r&&!r.logout){r.secret=te(),yield r.save().catch(dt.error);return{auth:r,token:Re.sign({id:e,secret:r.secret},nt.token,dt.options())}}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}}))}static user(e,t,i){return Ne(this,void 0,void 0,(function*(){if(e){t=i.hash.encrypt(e);const r=yield We.findOne({where:{token:t,state:!0}}).catch(dt.error);if(r){const t=e.replace(/(-[\w]{4})/g,"-****"),[i]=(yield Be.findOrCreate({where:{secret:t,user_id:r.id},defaults:{secret:t,user_id:r.id}}).catch(dt.error))||[];if(i)return{auth:i,user:r}}return{error:"ACCESS DENIED"}}const{error:r,decode:s}=dt.verify(t);if(r)return{error:r};if(s){const{id:e,secret:t}=s;if(e&&t){const i=yield We.findOne({where:{id:e,state:!0}}).catch(dt.error);if(i){const e=yield Be.findOne({where:{secret:t,user_id:i.id}}).catch(dt.error);if(e&&!e.logout)return{auth:e,user:i}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}}))}static verify(e,t){if(!st.token)return{error:"CERT NOT FOUND"};if(!e||e.split(".").length<3)return{error:"INVALID TOKEN"};try{return{decode:Re.verify(e,st.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class at extends t{constructor(e){super(e,{cert:st.http,cross:Ce.API_HTTP_CROSS,hybrid:Ce.API_HTTP_HYBRID,key:nt.http,notfound:Ce.API_HTTP_NOTFOUND,path:Ce.API_HTTP_PATH,port:Ce.API_HTTP_PORT,public:Ce.API_HTTP_PUBLIC,redirect:Ce.API_HTTP_REDIRECT,session:{store:new ot,name:Ce.API_SESSION_NAME,secret:Ce.API_SESSION_SECRET,cookie:{maxAge:Ce.API_SESSION_LIFETIME},genid:te}}),this.hash=new $(Ce.API_KEY_HASH)}error(e,t){it.error(e.message,t,Ce.API_CONSOLE_ERROR)}log(e,t){it.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return Ne(this,void 0,void 0,(function*(){yield Ue.sync(),yield this.migrations(Ue),yield e.listen.call(this),Ce.API_WEBSOCKET_START&&this.server&&(this._webSocket=new ve({server:this.server,verifyClient:(e,t)=>t(Ce.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>Ne(this,void 0,void 0,(function*(){t.url||(t.url="");const i=t.url.length<=1?"":t.url.replace(/\//g,".");let r;e.on("message",(s=>Ne(this,void 0,void 0,(function*(){if(r)try{const n=JSON.parse(s);this.emit("ws.message"+i,{data:n,message:s,req:t,user:r,ws:e})}catch(n){this.emit("ws.message"+i,{erro:n,message:s,req:t,user:r,ws:e})}else{const{user:n}=yield dt.user("",s.toString(),this);n&&(r=n,this.emit("ws.connection"+i,{req:t,user:r,ws:e}))}r||e.close()})))),e.on("close",(()=>{r&&this.emit("ws.close"+i,{user:r,ws:e})})),yield ie(2e3),r||e.close()})))))}))}migrations(e){return Ne(this,void 0,void 0,(function*(){const t=[];yield re(Object.keys(e.models),(i=>Ne(this,void 0,void 0,(function*(){var r;const s=e.models[i],{version:n}=ke.migrations(s);if(!n)return;const[o,d]=null!==(r=yield et.findOrCreate({where:{model:s.tableName},defaults:{model:s.tableName,version:""}}).catch(this.error))&&void 0!==r?r:[];o&&(d||o.version!=n)&&(o.version=n,yield o.save().catch(this.error),t.push(s))})))),t.length&&(yield M(e,t))}))}websocket(){return this._webSocket}}class ut extends se{auth(e,t,i,r,s){return Ne(this,void 0,void 0,(function*(){const{auth:n,error:o,user:d}=yield dt.user(t,i,s);return o?e.error(o):n&&d?n.user_agent&&n.user_agent!=r?e.error("INVALID TOKEN"):(e.req.auth=n,e.req.user=d,void e.next()):e.error("INTERNAL SERVER ERROR")}))}create(e,t,i){return Ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".create",i)}))}delete(e,t,i){return Ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".delete",i)}))}error(e){it.error(e.message,"api.controller",Ce.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,i){return Ne(this,void 0,void 0,(function*(){if(i){const r=yield this.permissions(i,{route:t});if(r&&r.length>0)return e.next()}e.unauthorized("ACCESS DENIED")}))}permissions(e,t){return Ne(this,void 0,void 0,(function*(){return yield Xe.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:Ze,required:!0,include:[{model:Ve,required:!0,where:{state:!0},include:[{model:Ye,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error)}))}read(e,t,i){return Ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",i)}))}session(e,t,i){return Ne(this,void 0,void 0,(function*(){i.auth&&i.user&&(i.user_agent?i.user_agent!=t&&i.regenerate(Q):(i.user_agent=t,i.save(Q))),e.next()}))}upload(e,t){t.path||(t.path=Ce.API_UPLOAD_TEMP),t.size||(t.size=Ce.API_UPLOAD_SIZE),t.field||(t.field=Ce.API_UPLOAD_FIELD),d.middleware(e,t)}update(e,t,i){return Ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".update",i)}))}validation(e,t){return Ne(this,void 0,void 0,(function*(){const{error:i,value:r}=yield ne.object(t).parse().validateAsync(e.req.body);if(i)return e.validation(i);e.req.body=r,e.next()}))}}Te([De(0,i()),De(1,r(Ce.API_KEY_HEADER)),De(2,r(Ce.API_TOKEN_HEADER)),De(3,r("user-agent")),De(4,s()),be("design:type",Function),be("design:paramtypes",[a,String,String,String,at]),be("design:returntype",Promise)],ut.prototype,"auth",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],ut.prototype,"create",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],ut.prototype,"delete",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],ut.prototype,"permission",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],ut.prototype,"read",null),Te([De(0,i()),De(1,r("user-agent")),De(2,o()),be("design:type",Function),be("design:paramtypes",[a,String,Object]),be("design:returntype",Promise)],ut.prototype,"session",null),Te([De(0,i()),De(1,n()),be("design:type",Function),be("design:paramtypes",[a,Object]),be("design:returntype",void 0)],ut.prototype,"upload",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],ut.prototype,"update",null),Te([De(0,i()),De(1,n()),be("design:type",Function),be("design:paramtypes",[a,Object]),be("design:returntype",Promise)],ut.prototype,"validation",null);let pt=class extends ut{constructor(){super(...arguments),this._attributes=[]}_add(e){return Ne(this,arguments,void 0,(function*({ctx:e,options:t,body:i}){const r=yield this.model().create(Object.assign(Object.assign({},e.req.body),i||{}),Object.assign(Object.assign({},t||{}),we(e))).catch(this.error);if(r){const t=this.key();return e.prepare(p.OK,{[t]:r.getDataValue(t)}),r}e.error("INTERNAL SERVER ERROR")}))}_all(e){return Ne(this,arguments,void 0,(function*({ctx:e,options:t,callback:i,scope:r,advanced:s,unlimited:n}){var o,d,a;const u=this.scope(r),c=Object.assign({},t||{}),{limit:l,offset:y,asc:g,desc:h,search:v,where:_}=e.req.query;if(ae(c.limit)){const e=ue(de(l)?parseInt(l)||0:Ce.API_MODEL_LIMIT,-1,Ce.API_MODEL_LIMIT_MAX);c.limit=e>0?e:n?void 0:Ce.API_MODEL_LIMIT}if(de(y)){const e=y&&parseInt(y)||0;c.offset=e>0?e:void 0}const m=this.attributes(null!==(o=null==c?void 0:c.attributes)&&void 0!==o?o:[]),O=[],f=e=>m.indexOf(e)>=0;if(de(g)&&g.length&&O.push(...g.split(";").filter(f).map((e=>[e,"ASC"]))),de(h)&&h.length&&O.push(...h.split(";").filter(f).map((e=>[e,"DESC"]))),O.length&&(c.order=O),c.where=Object.assign({},c.where||{}),de(_)&&(ae(s)||s)){const t=V.parse(m,_);if(!ae(t.error))return e.validation(t.error.join(", ")),{count:0,records:[]};c.where=Object.assign(Object.assign({},c.where),null!==(d=t.value)&&void 0!==d?d:{})}else{const e=[];m.forEach((t=>{de(v)&&v.length&&e.push({[t]:{[he.like]:`%${v}%`}})})),e.length&&(c.where=Object.assign(Object.assign({},c.where),{[he.or]:[...e]}))}const E=u.count(Object.assign(Object.assign({},c),{distinct:!!c.include,col:this._attributes.length?this._attributes[0]:void 0})).catch(this.error),P=u.findAll(c).catch(this.error);yield Promise.allSettled([E,P]);const I=null!==(a=yield E)&&void 0!==a?a:0;let A=yield P;const R={count:I};return A?(A=i?yield i(A):A,(pe(null==t?void 0:t.limit)||0==I)&&(R.count=A.length),e.prepare(p.OK,Object.assign(Object.assign({},R),{records:A})),Object.assign(Object.assign({},R),{records:A})):(e.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},R),{records:[]}))}))}_del(e){return Ne(this,arguments,void 0,(function*({ctx:e,options:t}){const i=this.key(),{[i]:r}=e.req.params;if(!r)return e.error("INTERNAL SERVER ERROR"),0;const s=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:r}),individualHooks:!0}),we(e))).catch(this.error);return s?(e.success("OK"),s):(e.notFound("RECORD NOT FOUND"),0)}))}_get(e){return Ne(this,arguments,void 0,(function*({ctx:e,options:t,callback:i,scope:r}){const s=this.key(),{[s]:n}=e.req.params,o=yield this.scope(r).findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[s]:n})})).catch(this.error);return o?(e.prepare(p.OK,i?yield i(o):o.toJSON()),o):null===o?e.notFound("RECORD NOT FOUND"):void e.error("INTERNAL SERVER ERROR")}))}_set(e){return Ne(this,arguments,void 0,(function*({ctx:e,options:t,body:i}){var r;const s=this.key(),{[s]:n}=e.req.params,[o]=null!==(r=yield this.model().update(Object.assign(Object.assign({},e.req.body),i||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[s]:n}),individualHooks:!0}),we(e))).catch(this.error))&&void 0!==r?r:[];return o?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)}))}attributes(e){if(0==this._attributes.length&&(this._attributes=Object.keys(this.model().getAttributes())),oe(e))return e.map((e=>de(e)&&-1!=this._attributes.indexOf(e)?e:void 0)).filter(de);const{exclude:t,include:i}=e,r=ae(i)?this._attributes:i.map((e=>de(e)&&-1!=this._attributes.indexOf(e)?e:void 0)).filter(de),s=null!=t?t:[];return s.length?r.filter((e=>-1==s.indexOf(e)?e:void 0)).filter(de):r}error(e){e.sql?it.error(e.message+"\n"+e.sql,"api.controller.sql",Ce.API_CONSOLE_ERROR):super.error(e)}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}};pt=Te([u(ut)],pt);let ct=class extends pt{model(){return ze}all(e,t,i){return Ne(this,void 0,void 0,(function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this._all({ctx:e,options:{attributes:{exclude:["data","previously"]},where:r,order:[["created_at","DESC"]]}})}))}get(e){return Ne(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}};Te([c(),l("auth"),l("read"),De(0,i()),De(1,y("type")),De(2,y("table")),be("design:type",Function),be("design:paramtypes",[a,String,String]),be("design:returntype",Promise)],ct.prototype,"all",null),Te([c("/:id"),l("auth"),l("read"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ct.prototype,"get",null),ct=Te([g("/audits"),u(pt)],ct);let lt=class extends ut{login(e,t,i,r,s){return Ne(this,void 0,void 0,(function*(){var n;yield ie(Ce.API_SLEEP_AUTH);const o=yield We.scope("password").findOne({where:{[he.or]:[{email:i},{username:i}]}}).catch(this.error);if(r+=null!==(n=null==o?void 0:o.salt)&&void 0!==n?n:"",!o||o.password!=J(r))return e.notFound("INVALID USERNAME OR PASSWORD"),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const d=yield Me.findOne({where:{state:!0,user_id:o.id}}).catch(this.error);if(d)return e.error("ACTIVATION REQUIRED"),s.emit("auth.activation",{ctx:e,register:d,user:o}),void this.emit("auth.activation",{ctx:e,register:d,user:o});if(!o.state)return e.notFound("INVALID USERNAME OR PASSWORD"),s.emit("auth.failure",{ctx:e,user:o}),void this.emit("auth.failure",{ctx:e,user:o});const{auth:a,error:u,token:p}=yield dt.create(o);return u?(e.error(u),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):a&&p?(a.user_agent=t,yield a.save().catch(this.error),e.json({token:p}),s.emit("auth.login",{auth:a,ctx:e,user:o}),void this.emit("auth.login",{auth:a,ctx:e,user:o})):(e.error("INTERNAL SERVER ERROR"),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,i,r){return Ne(this,void 0,void 0,(function*(){if(yield dt.destroy(t))return e.success("OK"),r.emit("auth.logout",{auth:t,ctx:e,user:i}),void this.emit("auth.logout",{auth:t,ctx:e,user:i});e.unauthorized("ACCESS DENIED")}))}renew(e,t,i,r){return Ne(this,void 0,void 0,(function*(){const{auth:s,error:n,token:o}=yield dt.renew(i);return n?e.error(n):s?(s.user_agent=t,yield s.save().catch(this.error),e.json({token:o}),r.emit("auth.renew",{auth:s,ctx:e}),void this.emit("auth.renew",{auth:s,ctx:e})):e.error("INTERNAL SERVER ERROR")}))}user(e,t){return Ne(this,void 0,void 0,(function*(){const i=yield this.permissions(t);if(!i)return e.error("INTERNAL SERVER ERROR");e.json(Object.assign(Object.assign({},ce(["username","date","description","state","created_at","updated_at","deleted_at"],t.toJSON())),{permissions:i.map((e=>e.route))}))}))}};Te([h("/login"),l("validation",{username:ne.string().min(3).required(),password:ne.string().min(5).required()}),De(0,i()),De(1,r("user-agent")),De(2,v("username")),De(3,v("password")),De(4,s()),be("design:type",Function),be("design:paramtypes",[a,String,String,String,at]),be("design:returntype",Promise)],lt.prototype,"login",null),Te([c("/logout"),l("auth"),De(0,i()),De(1,xe()),De(2,Fe()),De(3,s()),be("design:type",Function),be("design:paramtypes",[a,Be,We,at]),be("design:returntype",Promise)],lt.prototype,"logout",null),Te([h("/renew"),l("validation",{token:ne.string().required()}),De(0,i()),De(1,r("user-agent")),De(2,v("token")),De(3,s()),be("design:type",Function),be("design:paramtypes",[a,String,String,at]),be("design:returntype",Promise)],lt.prototype,"renew",null),Te([c(),l("auth"),De(0,i()),De(1,Fe()),be("design:type",Function),be("design:paramtypes",[a,We]),be("design:returntype",Promise)],lt.prototype,"user",null),lt=Te([g("/auth"),u(ut)],lt);let yt=class extends ut{directory(){return Ce.API_HTTP_PUBLIC||"./"}files(e){return Ne(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=Se(this.directory(),t);if(!_e(i)||!Oe(i).isDirectory())return e.notFound("RECORD NOT FOUND");let r=[];return r=fe(i),r=r.map((e=>this.info(Se(i,e)))),r=r.filter(le),Object.assign(Object.assign({},this.info(i)),{files:r})}))}access(e,t,i){return Ne(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,i)}))}info(e){if(!_e(e))return null;const t=Oe(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"}};Te([c("/path/?*"),l("auth"),l("access","list"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],yt.prototype,"files",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],yt.prototype,"access",null),yt=Te([g("/files"),u(ut)],yt);let gt=class extends ut{check(e,t){return Ne(this,void 0,void 0,(function*(){const i=yield this.find(t);if(!i||!i.user)return e.notFound("RECORD NOT FOUND");i.token=ye(),yield i.save(),e.json({token:i.token})}))}forgot(e,t,i){return Ne(this,void 0,void 0,(function*(){yield ie(Ce.API_SLEEP_FORGOT);const r=t,s=yield We.findOne({where:{[he.or]:[{email:r},{username:t}]}}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");const n=ye(),o=Date.now()+6e4*Ce.API_TOKEN_FORGOT,d=yield Je.create({token:n,timestamp:o,state:!0,user_id:s.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:d,user:s}),this.emit("forgot.send",{ctx:e,forgot:d,user:s})}))}reset(e,t,i,r){return Ne(this,void 0,void 0,(function*(){const s=yield this.find(t);if(!s)return e.notFound("RECORD NOT FOUND");s.state=!1,yield s.save().catch(this.error),s.user.password=J(i),yield s.user.save().catch(this.error),e.success("OK"),r.emit("forgot.reset",{ctx:e,user:s.user}),this.emit("forgot.reset",{ctx:e,user:s.user})}))}find(e){return Ne(this,void 0,void 0,(function*(){return yield Je.findOne({where:{token:e,state:!0},include:[{model:We,required:!0}]}).catch(this.error)}))}};Te([c("/check"),l("validation",{token:ne.string().required()}),De(0,i()),De(1,v("token")),be("design:type",Function),be("design:paramtypes",[a,String]),be("design:returntype",Promise)],gt.prototype,"check",null),Te([h(),l("validation",{username:ne.string().min(4).required()}),De(0,i()),De(1,v("username")),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,String,at]),be("design:returntype",Promise)],gt.prototype,"forgot",null),Te([h("/reset"),l("validation",{token:ne.string().required(),password:ne.string().min(5).required()}),De(0,i()),De(1,v("token")),De(2,v("password")),De(3,s()),be("design:type",Function),be("design:paramtypes",[a,String,String,at]),be("design:returntype",Promise)],gt.prototype,"reset",null),gt=Te([g("/forgot"),u(ut)],gt);let ht=class extends pt{constructor(){super(...arguments),this._crud={}}add(e){return Ne(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return Ne(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}CrudCreate(){return this._crud}del(e){return Ne(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return Ne(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return Ne(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}CrudUpdate(){return this._crud}validationAdd(e){return Ne(this,void 0,void 0,(function*(){const t=this.CrudCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)}))}validationSet(e){return Ne(this,void 0,void 0,(function*(){const t=this.CrudUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)}))}};Te([h(),l("auth"),l("create"),l("validationAdd"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"add",null),Te([c(),l("auth"),l("read"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"all",null),Te([_("/:id"),l("auth"),l("delete"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"del",null),Te([c("/:id"),l("auth"),l("read"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"get",null),Te([m("/:id"),l("auth"),l("update"),l("validationSet"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"set",null),Te([De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"validationAdd",null),Te([De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"validationSet",null),ht=Te([u(pt)],ht);let vt=class extends ht{model(){return Ve}CrudCreate(){return{name:ne.string().required(),description:ne.string().empty(""),state:ne.boolean().parse().required()}}CrudUpdate(){return{name:ne.string().empty(),description:ne.string().empty(),state:ne.boolean().parse().empty()}}};vt=Te([g("/groups"),u(ht)],vt);let _t=class extends pt{model(){return Ze}all(e,t){return Ne(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{group_id:t},include:[{model:Xe,required:!0}]},callback:e=>e.map((e=>e.permission))})}))}set(e,t,i,r){return Ne(this,void 0,void 0,(function*(){const s=yield Ve.findByPk(t,{attributes:["id"]}).catch(this.error);if(s){const t=s.id;if(yield Ze.destroy(Object.assign({where:{group_id:t},individualHooks:!0},r)),i){let e=0;yield ie(1e3);for(let s=0;s<i.length;s++)e=yield Xe.count({where:{id:i[s]}}),e&&(yield Ze.create({group_id:t,permission_id:i[s]},Object.assign({},r)))}return e.success("OK")}if(ge(s))return e.notFound("RECORD NOT FOUND");e.error("INTERNAL SERVER ERROR")}))}};Te([c("/:id/permissions"),l("auth"),l("read","groups"),De(0,i()),De(1,O("id")),be("design:type",Function),be("design:paramtypes",[a,String]),be("design:returntype",Promise)],_t.prototype,"all",null),Te([m("/:id/permissions"),l("auth"),l("update","groups"),l("validation",{permissions:ne.array(ne.number().parse())}),De(0,i()),De(1,O("id")),De(2,v("permissions")),De(3,je()),be("design:type",Function),be("design:paramtypes",[a,String,Array,Object]),be("design:returntype",Promise)],_t.prototype,"set",null),_t=Te([g("/groups"),u(pt)],_t);let mt=class extends pt{model(){return Qe}all(e,t,i){return Ne(this,void 0,void 0,(function*(){const r={};t&&(r.type=t),i&&(r.source=i),yield this._all({ctx:e,options:{where:r,order:[["created_at","DESC"]]}})}))}};Te([c(),l("auth"),l("read"),De(0,i()),De(1,y("type")),De(2,y("source")),be("design:type",Function),be("design:paramtypes",[a,String,String]),be("design:returntype",Promise)],mt.prototype,"all",null),mt=Te([g("/logs"),u(pt)],mt);let Ot=class extends ht{model(){return Xe}CrudCreate(){return{name:ne.string().required(),route:ne.string().required(),description:ne.string().empty(""),state:ne.boolean().parse().required()}}CrudUpdate(){return{name:ne.string().empty(),route:ne.string().empty(),description:ne.string().empty(),state:ne.boolean().parse().empty()}}};Ot=Te([g("/permissions"),u(ht)],Ot);let ft=class extends ut{register(e,t,i){return Ne(this,void 0,void 0,(function*(){yield ie(Ce.API_SLEEP_REGISTRY);const{name:r,date:s,email:n,username:o,password:d,confirm:a}=t,u=o||n,p=J(d);if(yield We.count({where:{[he.or]:[{email:n},{username:u}]}}).catch(this.error))return e.validation("INVALID EMAIL OR USERNAME");if(p!=J(a))return e.error("INVALID PASSWORD");const c=yield We.create({name:r,email:n,username:u,password:p,avatar:"",date:s,description:"",state:!1}).catch(this.error);if(!c)return e.error("INTERNAL SERVER ERROR");const l=yield Me.create({token:yield this.getId(),user_id:c.id,state:!0}).catch(this.error);if(!l)return yield c.destroy().catch(this.error),e.error("INTERNAL SERVER ERROR");e.success("OK"),i.emit("register.user",{ctx:e,register:l,user:c}),this.emit("register.user",{ctx:e,register:l,user:c})}))}confirm(e,t,i){return Ne(this,void 0,void 0,(function*(){const r=yield Me.findOne({where:{token:t,state:!0},include:[{model:We,required:!0}]}).catch(this.error);if(!r)return e.notFound("RECORD NOT FOUND");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 Ne(this,void 0,void 0,(function*(){const r=t,s=yield Me.findOne({where:{state:!0},include:[{model:We,required:!0,where:{[he.or]:[{email:r},{username:t}]}}]}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");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 Ne(this,void 0,void 0,(function*(){const e=te();return(yield Me.count({where:{token:e}}))?this.getId():e}))}};Te([h(),l("validation",{name:ne.string().required(),date:ne.date().required(),email:ne.string().email().required(),username:ne.string().min(4).empty(),password:ne.string().min(5).required(),confirm:ne.string().min(5).required()}),De(0,i()),De(1,v()),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,Object,at]),be("design:returntype",Promise)],ft.prototype,"register",null),Te([h("/confirm"),l("validation",{token:ne.string().required()}),De(0,i()),De(1,v("token")),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,String,at]),be("design:returntype",Promise)],ft.prototype,"confirm",null),Te([h("/send"),l("validation",{username:ne.string().min(4).required()}),De(0,i()),De(1,v("username")),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,String,at]),be("design:returntype",Promise)],ft.prototype,"send",null),ft=Te([g("/register"),u(ut)],ft);let Et=class extends ut{setup(e,t){return Ne(this,void 0,void 0,(function*(){if(0==(yield We.count())){const e=ye(),i=yield We.create({name:"Admin",email:"admin@localhost",username:"admin",password:J("admin"+e),salt:e,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},t)),r={description:"API CORE",state:!0},s=yield Ve.create(Object.assign({name:"Admin"},r),Object.assign({},t));yield Ye.create({user_id:i.id,group_id:s.id},Object.assign({},t));const n=["Users","Groups","Permissions"],o=["Create","Read","Update","Delete"];yield re(n,(e=>Ne(this,void 0,void 0,(function*(){yield re(o,(i=>Ne(this,void 0,void 0,(function*(){const n=yield Xe.create(Object.assign({name:`${e} ${i}`,route:`${e.toLowerCase()}.${i.toLowerCase()}`},r),Object.assign({},t));yield Ze.create({group_id:s.id,permission_id:n.id},Object.assign({},t))}))))}))));const d=["Delete","List","Read","Rename","Upload","Write"];yield re(d,(e=>Ne(this,void 0,void 0,(function*(){const i=yield Xe.create(Object.assign({name:`Files ${e}`,route:`files.${e.toLowerCase()}`},r),Object.assign({},t));yield Ze.create({group_id:s.id,permission_id:i.id},Object.assign({},t))}))));const a=["Audits","Logs"];yield re(a,(e=>Ne(this,void 0,void 0,(function*(){const i=yield Xe.create(Object.assign({name:`${e} Read`,route:`${e.toLowerCase()}.read`},r),Object.assign({},t));yield Ze.create({group_id:s.id,permission_id:i.id},Object.assign({},t))}))))}e.success("OK")}))}};Te([c(),De(0,i()),De(1,je()),be("design:type",Function),be("design:paramtypes",[a,Object]),be("design:returntype",Promise)],Et.prototype,"setup",null),Et=Te([g("/setup"),u(ut)],Et);let Pt=class extends pt{model(){return We}constructor(){super(),this.path=Ce.API_HTTP_PUBLIC+"/avatar",Ce.API_HTTP_PUBLIC&&_e(Ce.API_HTTP_PUBLIC)&&!_e(this.path)&&Ee(this.path)}avatar(e,t,i,r){return Ne(this,void 0,void 0,(function*(){if(t.length){const s=t[0].filename||"";if(s){const t=this.path+"/"+i.avatar;if(_e(t)&&Pe(t).isFile()&&Ie(t),i.avatar=s,yield i.save(Object.assign({},r)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")}))}avatar_delete(e,t,i){return Ne(this,void 0,void 0,(function*(){const r=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},i)).catch(this.error))&&_e(r)&&Ie(r),e.success("OK")}))}password(e,t,i,r,s){return Ne(this,void 0,void 0,(function*(){var n;if(Ce.API_USER_HISTORY){if(yield Ge.count({where:{password:J(i+r.id)}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED")}const o=yield this.scope("password").findOne({where:{id:r.id,state:!0}}).catch(this.error);return t+=null!==(n=null==o?void 0:o.salt)&&void 0!==n?n:"",o&&o.password==J(t)?(o.salt=ye(),o.password=J(i+o.salt),(yield o.save(Object.assign({},s)).catch(this.error))?e.success("OK"):void e.success("RECORD NOT CHANGED")):e.error("INVALID PASSWORD")}))}token(e,t,i){return Ne(this,void 0,void 0,(function*(){const r=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(r)return e.json({token:i.hash.decrypt(r.token)});e.notFound("RECORD NOT FOUND")}))}token_get(e,t,i){return Ne(this,void 0,void 0,(function*(){const r=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(r)return e.json({token:i.hash.decrypt(r.token)});e.notFound("RECORD NOT FOUND")}))}token_delete(e,t,i){return Ne(this,void 0,void 0,(function*(){const r=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(r)return r.token="",yield r.save(Object.assign({},i)).catch(this.error),e.success("OK");e.notFound("RECORD NOT FOUND")}))}token_renew(e,t,i,r){return Ne(this,void 0,void 0,(function*(){const s=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(s){const t=yield this.token_new();return s.token=r.hash.encrypt(t),yield s.save(Object.assign({},i)).catch(this.error),e.json({token:t})}e.notFound("RECORD NOT FOUND")}))}token_new(){return Ne(this,void 0,void 0,(function*(){var e;const t=te();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t}))}add(e,t){return Ne(this,void 0,void 0,(function*(){const i=ye(),r=yield this._add({ctx:e,body:{password:J(t+i),salt:i}});Ce.API_USER_HISTORY&&r&&(yield Ge.create({password:J(t+r.id),user_id:r.id}))}))}all(e){return Ne(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{attributes:{exclude:["password","salt","token"]}}})}))}del(e,t,i){return Ne(this,void 0,void 0,(function*(){if(i.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this._del({ctx:e})}))}get(e){return Ne(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t,i){return Ne(this,void 0,void 0,(function*(){if(Ce.API_USER_HISTORY&&i){const r=J(i+t);if(yield Ge.count({where:{password:r}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED");yield Ge.create({password:r,user_id:t}).catch(this.error)}const r=i?ye():"";yield this._set({ctx:e,body:i?{password:J(i+r),salt:r}:{}})}))}};Te([h("/avatar"),l("auth"),l("upload",(e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32}))),De(0,i()),De(1,f()),De(2,Fe()),De(3,je()),be("design:type",Function),be("design:paramtypes",[a,Array,We,Object]),be("design:returntype",Promise)],Pt.prototype,"avatar",null),Te([_("/avatar"),l("auth"),De(0,i()),De(1,Fe()),De(2,je()),be("design:type",Function),be("design:paramtypes",[a,We,Object]),be("design:returntype",Promise)],Pt.prototype,"avatar_delete",null),Te([h("/password"),l("auth"),l("validation",{oldPassword:ne.string().min(5).required(),newPassword:ne.string().min(5).required()}),De(0,i()),De(1,v("oldPassword")),De(2,v("newPassword")),De(3,Fe()),De(4,je()),be("design:type",Function),be("design:paramtypes",[a,String,String,We,Object]),be("design:returntype",Promise)],Pt.prototype,"password",null),Te([c("/token"),l("auth"),De(0,i()),De(1,Fe()),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,We,at]),be("design:returntype",Promise)],Pt.prototype,"token",null),Te([c("/token/:id"),l("auth"),l("create"),De(0,i()),De(1,O("id")),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,String,at]),be("design:returntype",Promise)],Pt.prototype,"token_get",null),Te([_("/token/:id"),l("auth"),l("delete"),De(0,i()),De(1,O("id")),De(2,je()),be("design:type",Function),be("design:paramtypes",[a,String,Object]),be("design:returntype",Promise)],Pt.prototype,"token_delete",null),Te([c("/token/renew/:id"),l("auth"),l("update"),De(0,i()),De(1,O("id")),De(2,je()),De(3,s()),be("design:type",Function),be("design:paramtypes",[a,String,Object,at]),be("design:returntype",Promise)],Pt.prototype,"token_renew",null),Te([h(),l("auth"),l("create"),l("validation",{name:ne.string().required(),email:ne.string().email().required(),username:ne.string().min(4).required(),password:ne.string().min(5).required(),description:ne.string().empty(""),state:ne.boolean().parse().required()}),De(0,i()),De(1,v("password")),be("design:type",Function),be("design:paramtypes",[a,String]),be("design:returntype",Promise)],Pt.prototype,"add",null),Te([c(),l("auth"),l("read"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],Pt.prototype,"all",null),Te([_("/:id"),l("auth"),l("delete"),De(0,i()),De(1,O("id")),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],Pt.prototype,"del",null),Te([c("/:id"),l("auth"),l("read"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],Pt.prototype,"get",null),Te([m("/:id"),l("auth"),l("update"),l("validation",{name:ne.string().empty(),email:ne.string().email().empty(),username:ne.string().min(4).empty(),password:ne.string().min(5).empty().filter(""),description:ne.string().empty(),state:ne.boolean().parse().empty()}),De(0,i()),De(1,O("id")),De(2,v("password")),be("design:type",Function),be("design:paramtypes",[a,String,String]),be("design:returntype",Promise)],Pt.prototype,"set",null),Pt=Te([g("/users"),u(pt),be("design:paramtypes",[])],Pt);let It=class extends pt{model(){return Ye}groups(e,t){return Ne(this,void 0,void 0,(function*(){yield this.all(e,t.id.toString())}))}all(e,t){return Ne(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{user_id:t},include:[{model:Ve,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,i,r){return Ne(this,void 0,void 0,(function*(){const s=yield We.findByPk(t,{attributes:["id"]}).catch(this.error);if(s){if(yield Ye.destroy(Object.assign({where:{user_id:s.id},individualHooks:!0},r)),i){let e=0;yield ie(1e3);for(let t=0;t<i.length;t++)e=yield Ve.count({where:{id:i[t]}}),e&&(yield Ye.create({user_id:s.id,group_id:i[t]},Object.assign({},r)))}return e.success("OK")}if(ge(s))return e.notFound("RECORD NOT FOUND");e.error("INTERNAL SERVER ERROR")}))}};Te([c("/groups"),l("auth"),l("read","users"),De(0,i()),De(1,Fe()),be("design:type",Function),be("design:paramtypes",[a,We]),be("design:returntype",Promise)],It.prototype,"groups",null),Te([c("/:id/groups"),l("auth"),l("read","users"),De(0,i()),De(1,O("id")),be("design:type",Function),be("design:paramtypes",[a,String]),be("design:returntype",Promise)],It.prototype,"all",null),Te([m("/:id/groups"),l("auth"),l("update","users"),l("validation",{groups:ne.array(ne.number().parse())}),De(0,i()),De(1,O("id")),De(2,v("groups")),De(3,je()),be("design:type",Function),be("design:paramtypes",[a,String,Array,Object]),be("design:returntype",Promise)],It.prototype,"set",null),It=Te([g("/users"),u(pt)],It);class At{static all(){return Ne(this,void 0,void 0,(function*(){const e=yield $e.findAll().catch(At.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e,t){return Ne(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 $e.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:r})).catch(At.error))||0)>0}))}static error(e){it.error(e.message,"api.config",Ce.API_CONSOLE_ERROR)}static get(e){return Ne(this,arguments,void 0,(function*(e,t=""){const[i]=(yield $e.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(At.error))||[];return i?i.value:t}))}static set(e,t,i){return Ne(this,void 0,void 0,(function*(){var r;const s=null!==(r=null==i?void 0:i.id)&&void 0!==r?r:null,[n]=(yield $e.findOrCreate(Object.assign({where:{key:e}},{user_id:s})).catch(At.error))||[];n&&(n.value=t,yield n.save().catch(At.error))}))}}export{at as Application,ze as Audit,ct as AuditsController,Be as Auth,lt as AuthController,At as Config,$e as Configs,ut as ControllerBase,ht as CrudController,Ce as Env,yt as FilesController,Je as Forgot,gt as ForgotController,Ve as Group,Ze as GroupPermission,vt as GroupsController,_t as GroupsPermissionsController,Qe as Log,it as Logs,mt as LogsController,ke as Metadata,Le as Migrate,et as Migration,He as Model,pt as ModelController,Xe as Permission,Ot as PermissionsController,Me as Register,ft as RegisterController,je as ReqAudit,xe as ReqAuth,Fe as ReqUser,tt as Session,Et as SetupController,ot as Store,dt as Token,We as User,Ye as UserGroup,Ge as UserHistory,Pt as UsersController,It as UsersGroupsController,we as audit,st as crt,Ue as database,qe as hooks,nt as key};
7
+ import{parameterFactory as e,Application as t,Ctx as i,Headers as r,App as s,Argument as n,Session as o,Upload as d,Context as a,Extends as u,Status as p,Get as c,Middleware as l,Query as y,Controller as g,Post as h,Body as v,Delete as _,Put as m,Params as O,Files as f}from"@andrewcaires/express";import{Connection as E,Model as P,Id as I,String as A,FullDate as R,CreatedAt as S,UpdatedAt as T,DeletedAt as D,BelongsTo as b,Database as N,ModelName as w,Boolean as j,Text as x,HasMany as F,Hooks as k,DateOnly as L,DefaultScope as C,Scopes as U,Enum as H,Json as K,BigInt as q,Unique as B,migrate as M,Where as V}from"@andrewcaires/sequelize";import{Metadata as Y,Env as G,LogColor as W,Log as z,Hash as $,sha256 as J}from"@andrewcaires/node";import{config as X}from"dotenv";import{isObject as Z,noop as Q,loop as ee,uuidv4 as te,sleep as ie,forEachSeries as re,EventEmitter as se,Validation as ne,isArray as oe,isString as de,isUndefined as ae,clamp as ue,isNumber as pe,denied as ce,isDef as le,uniqueID as ye,isNull as ge}from"@andrewcaires/utils.js";import{Op as he}from"sequelize";import{WebSocketServer as ve}from"ws";import{existsSync as _e,readFileSync as me,statSync as Oe,readdirSync as fe,mkdirSync as Ee,lstatSync as Pe,rmSync as Ie}from"fs";import{Store as Ae}from"express-session";import Re from"jsonwebtoken";import{join as Se}from"path";function Te(e,t,i,r){var s,n=arguments.length,o=n<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--)(s=e[d])&&(o=(n<3?s(o):n>3?s(t,i,o):s(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}function De(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 Ne(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{a(r.next(e))}catch(e){n(e)}}function d(e){try{a(r.throw(e))}catch(e){n(e)}}function a(e){var t;e.done?s(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())}))}"function"==typeof SuppressedError&&SuppressedError;const we=e=>{var t,i,r,s,n,o,d,a,u;return{audit_client:null!==(t=e.ip())&&void 0!==t?t:"0.0.0.0",audit_href:(null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.protocol)+"://"+(null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.get("host"))+(null===(s=null==e?void 0:e.req)||void 0===s?void 0:s.originalUrl),audit_user_agent:null!==(o=null===(n=e.req)||void 0===n?void 0:n.headers["user-agent"])&&void 0!==o?o:"",audit_user_id:null!==(u=null===(a=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.user)||void 0===a?void 0:a.id)&&void 0!==u?u:null}},je=e((({ctx:e})=>we(e))),xe=e((({ctx:e})=>e.req.auth)),Fe=e((({ctx:e})=>e.req.user));class ke{static migrations(e){return Y(ke.MIGRATE,e,{version:""})}}ke.MIGRATE=Symbol();const Le=e=>t=>{ke.migrations(t).version=e};X();class Ce extends G{}Ce.API_CONSOLE_ERROR=Ce.getBool("API_CONSOLE_ERROR",!1),Ce.API_DB_DATABASE=Ce.getString("API_DB_DATABASE",""),Ce.API_DB_HOST=Ce.getString("API_DB_HOST","127.0.0.1"),Ce.API_DB_PASSWORD=Ce.getString("API_DB_PASSWORD",""),Ce.API_DB_PORT=Ce.getInt("API_DB_PORT",3306),Ce.API_DB_TYPE=Ce.getString("API_DB_TYPE",""),Ce.API_DB_USERNAME=Ce.getString("API_DB_USERNAME","root"),Ce.API_DB_LOG=Ce.getBool("API_DB_LOG",!1),Ce.API_DB_AUDIT=Ce.getBool("API_DB_AUDIT",!0),Ce.API_DB_PREFIX=Ce.getString("API_DB_PREFIX",""),Ce.API_DB_TIMEZONE=Ce.getString("API_DB_TIMEZONE","+00:00"),Ce.API_HTTP_CRT=Ce.getString("API_HTTP_CRT",""),Ce.API_HTTP_KEY=Ce.getString("API_HTTP_KEY",""),Ce.API_HTTP_PORT=Ce.getInt("API_HTTP_PORT",3e3),Ce.API_HTTP_PUBLIC=Ce.getString("API_HTTP_PUBLIC",""),Ce.API_HTTP_CROSS=Ce.getBool("API_HTTP_CROSS",!1),Ce.API_HTTP_HYBRID=Ce.getBool("API_HTTP_HYBRID",!1),Ce.API_HTTP_NOTFOUND=Ce.getString("API_HTTP_NOTFOUND",""),Ce.API_HTTP_PATH=Ce.getString("API_HTTP_PATH","/api"),Ce.API_HTTP_REDIRECT=Ce.getString("API_HTTP_REDIRECT",""),Ce.API_KEY_HASH=Ce.getString("API_KEY_HASH",""),Ce.API_KEY_HEADER=Ce.getString("API_KEY_HEADER","api_key"),Ce.API_MODEL_LIMIT=Ce.getInt("API_MODEL_LIMIT",10),Ce.API_MODEL_LIMIT_MAX=Ce.getInt("API_MODEL_LIMIT_MAX",500),Ce.API_SLEEP_AUTH=Ce.getMs("API_SLEEP_AUTH","2s"),Ce.API_SLEEP_FORGOT=Ce.getMs("API_SLEEP_FORGOT","5s"),Ce.API_SLEEP_REGISTRY=Ce.getMs("API_SLEEP_REGISTRY","5s"),Ce.API_SESSION_NAME=Ce.getString("API_SESSION_NAME","session.id"),Ce.API_SESSION_LIFETIME=Ce.getMs("API_SESSION_LIFETIME","1d"),Ce.API_SESSION_SECRET=Ce.getString("API_SESSION_SECRET","yoursecret"),Ce.API_TOKEN_CRT=Ce.getString("API_TOKEN_CRT",""),Ce.API_TOKEN_KEY=Ce.getString("API_TOKEN_KEY",""),Ce.API_TOKEN_FORGOT=Ce.getMs("API_TOKEN_LIFETIME","1d"),Ce.API_TOKEN_HEADER=Ce.getString("API_TOKEN_HEADER","authorization"),Ce.API_TOKEN_LIFETIME=Ce.getMs("API_TOKEN_LIFETIME","1d"),Ce.API_TOKEN_RENEW=Ce.getMs("API_TOKEN_RENEW","1d"),Ce.API_UPLOAD_COUNT=Ce.getInt("API_UPLOAD_COUNT",1),Ce.API_UPLOAD_FIELD=Ce.getString("API_UPLOAD_FIELD","upload"),Ce.API_UPLOAD_SIZE=Ce.getInt("API_UPLOAD_SIZE",2),Ce.API_UPLOAD_TEMP=Ce.getString("API_UPLOAD_TEMP","./temp"),Ce.API_USER_HISTORY=Ce.getBool("API_USER_HISTORY",!0),Ce.API_WEBSOCKET_START=Ce.getBool("API_WEBSOCKET_START",!1);const Ue=new E({type:Ce.API_DB_TYPE,database:Ce.API_DB_DATABASE,username:Ce.API_DB_USERNAME,password:Ce.API_DB_PASSWORD,hostname:Ce.API_DB_HOST,hostport:Ce.API_DB_PORT,logging:Ce.API_DB_LOG,prefix:Ce.API_DB_PREFIX,timezone:Ce.API_DB_TIMEZONE});class He extends P{constructor(){super(...arguments),this._version=""}}const Ke=(e,t,i)=>{var r,s,n,o,d;return{type:e,model:null!==(r=null==t?void 0:t.getTableName())&&void 0!==r?r:null,client:null!==(s=null==i?void 0:i.audit_client)&&void 0!==s?s:null,href:null!==(n=null==i?void 0:i.audit_href)&&void 0!==n?n:null,user_agent:null!==(o=null==i?void 0:i.audit_user_agent)&&void 0!==o?o:null,user_id:null!==(d=null==i?void 0:i.audit_user_id)&&void 0!==d?d:null,state:!0}},qe={afterCreate:(e,t)=>Ne(void 0,void 0,void 0,(function*(){var i;if(!Ce.API_DB_AUDIT)return;const r=Z(e)?e.constructor:null,s=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null;yield ze.create(Object.assign(Object.assign({},Ke("CREATE",r,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(Q)})),afterUpdate:(e,t)=>Ne(void 0,void 0,void 0,(function*(){var i;if(!Ce.API_DB_AUDIT)return;const r=Z(e)?e.constructor:null,s=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null,n={},o=e.changed();o&&o.forEach((t=>n[t]=e.getDataValue(t))),yield ze.create(Object.assign(Object.assign({},Ke("UPDATE",r,t)),{record:s?e.getDataValue(s):null,data:n,previously:e.previous()})).catch(Q)})),afterDestroy:(e,t)=>Ne(void 0,void 0,void 0,(function*(){var i;if(!Ce.API_DB_AUDIT)return;const r=Z(e)?e.constructor:null,s=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null;yield ze.create(Object.assign(Object.assign({},Ke("DELETE",r,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(Q)}))};let Be=class extends He{};Te([I(),be("design:type",Number)],Be.prototype,"id",void 0),Te([A(),be("design:type",A)],Be.prototype,"secret",void 0),Te([R(),be("design:type",Date)],Be.prototype,"logout",void 0),Te([A(),be("design:type",A)],Be.prototype,"user_agent",void 0),Te([S,be("design:type",Date)],Be.prototype,"created_at",void 0),Te([T,be("design:type",Date)],Be.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],Be.prototype,"deleted_at",void 0),Te([b((()=>We)),be("design:type",Number)],Be.prototype,"user_id",void 0),Be=Te([N(Ue),w("auth"),Le("4.2.0")],Be);let Me=class extends He{};Te([I(),be("design:type",Number)],Me.prototype,"id",void 0),Te([A(),be("design:type",A)],Me.prototype,"token",void 0),Te([j(),be("design:type",j)],Me.prototype,"state",void 0),Te([S,be("design:type",Date)],Me.prototype,"created_at",void 0),Te([T,be("design:type",Date)],Me.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],Me.prototype,"deleted_at",void 0),Te([b((()=>We)),be("design:type",Number)],Me.prototype,"user_id",void 0),Me=Te([N(Ue),w("register"),Le("4.2.0")],Me);let Ve=class extends He{};Te([I(),be("design:type",Number)],Ve.prototype,"id",void 0),Te([A(),be("design:type",A)],Ve.prototype,"name",void 0),Te([x(),be("design:type",A)],Ve.prototype,"description",void 0),Te([j(),be("design:type",j)],Ve.prototype,"state",void 0),Te([S,be("design:type",Date)],Ve.prototype,"created_at",void 0),Te([T,be("design:type",Date)],Ve.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],Ve.prototype,"deleted_at",void 0),Te([F((()=>Ye),"group_id"),be("design:type",Array)],Ve.prototype,"groups_routes",void 0),Te([F((()=>Ye),"group_id"),be("design:type",Array)],Ve.prototype,"users_groups",void 0),Ve=Te([N(Ue),w("group"),k(qe),Le("4.2.0")],Ve);let Ye=class extends He{};Te([S,be("design:type",Date)],Ye.prototype,"created_at",void 0),Te([b((()=>Ve)),be("design:type",Number)],Ye.prototype,"group_id",void 0),Te([b((()=>We)),be("design:type",Number)],Ye.prototype,"user_id",void 0),Ye=Te([N(Ue),w("users_groups"),k(qe),Le("4.2.0")],Ye);let Ge=class extends He{};Te([A(),be("design:type",A)],Ge.prototype,"password",void 0),Te([S,be("design:type",Date)],Ge.prototype,"created_at",void 0),Te([b((()=>We)),be("design:type",Number)],Ge.prototype,"user_id",void 0),Ge=Te([N(Ue),w("users_histories"),Le("4.2.0")],Ge);let We=class extends He{};Te([I(),be("design:type",Number)],We.prototype,"id",void 0),Te([A(),be("design:type",A)],We.prototype,"name",void 0),Te([A(),be("design:type",A)],We.prototype,"email",void 0),Te([A(),be("design:type",A)],We.prototype,"username",void 0),Te([A(),be("design:type",A)],We.prototype,"password",void 0),Te([A(),be("design:type",A)],We.prototype,"salt",void 0),Te([A(),be("design:type",A)],We.prototype,"token",void 0),Te([A(),be("design:type",A)],We.prototype,"avatar",void 0),Te([L(),be("design:type",A)],We.prototype,"date",void 0),Te([x(),be("design:type",A)],We.prototype,"description",void 0),Te([j(),be("design:type",j)],We.prototype,"state",void 0),Te([S,be("design:type",Date)],We.prototype,"created_at",void 0),Te([T,be("design:type",Date)],We.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],We.prototype,"deleted_at",void 0),Te([F((()=>ze),"user_id"),be("design:type",Array)],We.prototype,"audits",void 0),Te([F((()=>Be),"user_id"),be("design:type",Array)],We.prototype,"auths",void 0),Te([F((()=>Me),"user_id"),be("design:type",Array)],We.prototype,"registers",void 0),Te([F((()=>Ye),"user_id"),be("design:type",Array)],We.prototype,"users_groups",void 0),Te([F((()=>Ge),"user_id"),be("design:type",Array)],We.prototype,"users_histories",void 0),We=Te([N(Ue),w("user"),C({attributes:{exclude:["password","salt","token"]}}),U({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),k(qe),Le("4.2.0")],We);let ze=class extends He{};Te([I(),be("design:type",Number)],ze.prototype,"id",void 0),Te([H("CREATE","DELETE","UPDATE"),be("design:type",A)],ze.prototype,"type",void 0),Te([A(),be("design:type",A)],ze.prototype,"model",void 0),Te([A(),be("design:type",A)],ze.prototype,"record",void 0),Te([K(),be("design:type",Object)],ze.prototype,"data",void 0),Te([K(),be("design:type",Object)],ze.prototype,"previously",void 0),Te([A(),be("design:type",A)],ze.prototype,"client",void 0),Te([x(),be("design:type",A)],ze.prototype,"href",void 0),Te([A(),be("design:type",A)],ze.prototype,"user_agent",void 0),Te([j(),be("design:type",j)],ze.prototype,"state",void 0),Te([S,be("design:type",Date)],ze.prototype,"created_at",void 0),Te([T,be("design:type",Date)],ze.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],ze.prototype,"deleted_at",void 0),Te([b((()=>We)),be("design:type",Number)],ze.prototype,"user_id",void 0),ze=Te([N(Ue),w("audit"),Le("4.2.0")],ze);let $e=class extends He{};Te([A(),be("design:type",A)],$e.prototype,"key",void 0),Te([A(),be("design:type",A)],$e.prototype,"value",void 0),Te([S,be("design:type",Date)],$e.prototype,"created_at",void 0),Te([T,be("design:type",Date)],$e.prototype,"updated_at",void 0),$e=Te([N(Ue),w("configs"),k(qe),Le("4.2.0")],$e);let Je=class extends He{};Te([I(),be("design:type",Number)],Je.prototype,"id",void 0),Te([A(),be("design:type",A)],Je.prototype,"token",void 0),Te([q(),be("design:type",Number)],Je.prototype,"timestamp",void 0),Te([j(),be("design:type",j)],Je.prototype,"state",void 0),Te([S,be("design:type",Date)],Je.prototype,"created_at",void 0),Te([T,be("design:type",Date)],Je.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],Je.prototype,"deleted_at",void 0),Te([b((()=>We)),be("design:type",Number)],Je.prototype,"user_id",void 0),Je=Te([N(Ue),w("forgot"),Le("4.2.0")],Je);let Xe=class extends He{};Te([I(),be("design:type",Number)],Xe.prototype,"id",void 0),Te([A(),be("design:type",A)],Xe.prototype,"name",void 0),Te([A(),B(!0),be("design:type",A)],Xe.prototype,"route",void 0),Te([x(),be("design:type",A)],Xe.prototype,"description",void 0),Te([j(),be("design:type",j)],Xe.prototype,"state",void 0),Te([S,be("design:type",Date)],Xe.prototype,"created_at",void 0),Te([T,be("design:type",Date)],Xe.prototype,"updated_at",void 0),Te([D,be("design:type",Object)],Xe.prototype,"deleted_at",void 0),Te([F((()=>Ze),"permission_id"),be("design:type",Array)],Xe.prototype,"groups_permissions",void 0),Xe=Te([N(Ue),w("permission"),k(qe),Le("4.2.0")],Xe);let Ze=class extends He{};Te([S,be("design:type",Date)],Ze.prototype,"created_at",void 0),Te([b((()=>Ve)),be("design:type",Number)],Ze.prototype,"group_id",void 0),Te([b((()=>Xe)),be("design:type",Number)],Ze.prototype,"permission_id",void 0),Ze=Te([N(Ue),w("groups_permissions"),k(qe),Le("4.2.0")],Ze);let Qe=class extends He{};Te([I(),be("design:type",Number)],Qe.prototype,"id",void 0),Te([A(),be("design:type",A)],Qe.prototype,"type",void 0),Te([A(),be("design:type",A)],Qe.prototype,"source",void 0),Te([x(),be("design:type",A)],Qe.prototype,"message",void 0),Te([S,be("design:type",Date)],Qe.prototype,"created_at",void 0),Qe=Te([N(Ue),w("log"),Le("4.2.0")],Qe);let et=class extends He{};Te([A(),be("design:type",A)],et.prototype,"model",void 0),Te([A(),be("design:type",A)],et.prototype,"version",void 0),Te([S,be("design:type",Date)],et.prototype,"created_at",void 0),Te([T,be("design:type",Date)],et.prototype,"updated_at",void 0),et=Te([N(Ue),w("migration"),Le("4.2.0")],et);let tt=class extends He{};Te([A(),be("design:type",A)],tt.prototype,"session",void 0),Te([x(),be("design:type",A)],tt.prototype,"json",void 0),Te([q(),be("design:type",Number)],tt.prototype,"expired",void 0),Te([S,be("design:type",Date)],tt.prototype,"created_at",void 0),Te([T,be("design:type",Date)],tt.prototype,"updated_at",void 0),tt=Te([N(Ue),w("session"),Le("4.2.0")],tt);class it{static write(e,t,i){return Ne(this,void 0,void 0,(function*(){yield it.writeRaw(W.White,"",e,t,i)}))}static error(e,t,i){return Ne(this,void 0,void 0,(function*(){yield it.writeRaw(W.Red,"error",e,t,i)}))}static info(e,t,i){return Ne(this,void 0,void 0,(function*(){yield it.writeRaw(W.Cyan,"info",e,t,i)}))}static success(e,t,i){return Ne(this,void 0,void 0,(function*(){yield it.writeRaw(W.Green,"success",e,t,i)}))}static warning(e,t,i){return Ne(this,void 0,void 0,(function*(){yield it.writeRaw(W.Yellow,"warning",e,t,i)}))}static writeRaw(e,t,i,r,s){return Ne(this,void 0,void 0,(function*(){s&&z.console(e,t,i),Ue&&(yield Qe.create({type:t,source:r,message:i}).catch((()=>null)))}))}}const rt=e=>_e(e)?me(e):void 0,st={http:rt(Ce.API_HTTP_CRT),token:rt(Ce.API_TOKEN_CRT)},nt={http:rt(Ce.API_HTTP_KEY),token:rt(Ce.API_TOKEN_KEY)};class ot extends Ae{constructor(){super(),this.all=e=>Ne(this,void 0,void 0,(function*(){e=e||Q;const t=yield tt.findAll({attributes:["session"],where:{expired:{[he.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>Ne(this,void 0,void 0,(function*(){yield tt.destroy().catch(Q),e&&e()})),this.destroy=(e,t)=>Ne(this,void 0,void 0,(function*(){yield tt.destroy({where:{session:e}}).catch(Q),t&&t()})),this.expired=()=>Ne(this,void 0,void 0,(function*(){yield tt.destroy({where:{expired:{[he.lt]:Date.now()}}}).catch(Q)})),this.get=(e,t)=>Ne(this,void 0,void 0,(function*(){t=t||Q;const i=yield tt.findOne({where:{session:e,expired:{[he.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(Q),void t(null)}t(null,e)}else t(null)})),this.length=e=>Ne(this,void 0,void 0,(function*(){e&&e(null,(yield tt.count().catch(Q))||0)})),this.set=(e,t,i)=>Ne(this,void 0,void 0,(function*(){i=i||Q;const r=Date.now()+Ce.API_SESSION_LIFETIME,s=JSON.stringify(t),[n,o]=(yield tt.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:r}}).catch(Q))||[];n&&(o||(n.json=s,n.expired=r,yield n.save().catch(Q))),i()})),this.loop=ee(this.expired,3e4),this.loop.start()}}class dt{static create(e){return Ne(this,void 0,void 0,(function*(){if(!nt.token)return{error:"KEY NOT FOUND"};const{id:t}=e,i=te(),r=yield Be.create({secret:i,user_id:t}).catch(dt.error);if(!r)return{error:"INTERNAL SERVER ERROR"};return{auth:r,token:Re.sign({id:t,secret:i},nt.token,dt.options())}}))}static destroy(e){return Ne(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){it.error(e.message,"api.token",Ce.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:Ce.API_TOKEN_LIFETIME+"ms"}}static renew(e){return Ne(this,void 0,void 0,(function*(){if(!nt.token)return{error:"KEY NOT FOUND"};const{error:t,decode:i}=dt.verify(e,Ce.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(i){const{id:e,secret:t}=i;if(e&&t){const i=yield We.findOne({where:{id:e,state:!0}}).catch(dt.error);if(i){const r=yield Be.findOne({where:{secret:t,user_id:i.id}}).catch(dt.error);if(r&&!r.logout){r.secret=te(),yield r.save().catch(dt.error);return{auth:r,token:Re.sign({id:e,secret:r.secret},nt.token,dt.options())}}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}}))}static user(e,t,i){return Ne(this,void 0,void 0,(function*(){if(e){t=i.hash.encrypt(e);const r=yield We.findOne({where:{token:t,state:!0}}).catch(dt.error);if(r){const t=e.replace(/(-[\w]{4})/g,"-****"),[i]=(yield Be.findOrCreate({where:{secret:t,user_id:r.id},defaults:{secret:t,user_id:r.id}}).catch(dt.error))||[];if(i)return{auth:i,user:r}}return{error:"ACCESS DENIED"}}const{error:r,decode:s}=dt.verify(t);if(r)return{error:r};if(s){const{id:e,secret:t}=s;if(e&&t){const i=yield We.findOne({where:{id:e,state:!0}}).catch(dt.error);if(i){const e=yield Be.findOne({where:{secret:t,user_id:i.id}}).catch(dt.error);if(e&&!e.logout)return{auth:e,user:i}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}}))}static verify(e,t){if(!st.token)return{error:"CERT NOT FOUND"};if(!e||e.split(".").length<3)return{error:"INVALID TOKEN"};try{return{decode:Re.verify(e,st.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class at extends t{constructor(e){super(e,{cert:st.http,cross:Ce.API_HTTP_CROSS,hybrid:Ce.API_HTTP_HYBRID,key:nt.http,notfound:Ce.API_HTTP_NOTFOUND,path:Ce.API_HTTP_PATH,port:Ce.API_HTTP_PORT,public:Ce.API_HTTP_PUBLIC,redirect:Ce.API_HTTP_REDIRECT,session:{store:new ot,name:Ce.API_SESSION_NAME,secret:Ce.API_SESSION_SECRET,cookie:{maxAge:Ce.API_SESSION_LIFETIME},genid:te}}),this.hash=new $(Ce.API_KEY_HASH)}error(e,t){it.error(e.message,t,Ce.API_CONSOLE_ERROR)}log(e,t){it.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return Ne(this,void 0,void 0,(function*(){yield Ue.sync(),yield this.migrations(Ue),yield e.listen.call(this),Ce.API_WEBSOCKET_START&&this.server&&(this._webSocket=new ve({server:this.server,verifyClient:(e,t)=>t(Ce.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>Ne(this,void 0,void 0,(function*(){t.url||(t.url="");const i=t.url.length<=1?"":t.url.replace(/\//g,".");let r;e.on("message",(s=>Ne(this,void 0,void 0,(function*(){if(r)try{const n=JSON.parse(s);this.emit("ws.message"+i,{data:n,message:s,req:t,user:r,ws:e})}catch(n){this.emit("ws.message"+i,{erro:n,message:s,req:t,user:r,ws:e})}else{const{user:n}=yield dt.user("",s.toString(),this);n&&(r=n,this.emit("ws.connection"+i,{req:t,user:r,ws:e}))}r||e.close()})))),e.on("close",(()=>{r&&this.emit("ws.close"+i,{user:r,ws:e})})),yield ie(2e3),r||e.close()})))))}))}migrations(e){return Ne(this,void 0,void 0,(function*(){const t=[];yield re(Object.keys(e.models),(i=>Ne(this,void 0,void 0,(function*(){var r;const s=e.models[i],{version:n}=ke.migrations(s);if(!n)return;const[o,d]=null!==(r=yield et.findOrCreate({where:{model:s.tableName},defaults:{model:s.tableName,version:""}}).catch(this.error))&&void 0!==r?r:[];o&&(d||o.version!=n)&&(o.version=n,yield o.save().catch(this.error),t.push(s))})))),t.length&&(yield M(e,t))}))}websocket(){return this._webSocket}}class ut extends se{auth(e,t,i,r,s){return Ne(this,void 0,void 0,(function*(){const{auth:n,error:o,user:d}=yield dt.user(t,i,s);return o?e.error(o):n&&d?n.user_agent&&n.user_agent!=r?e.error("INVALID TOKEN"):(e.req.auth=n,e.req.user=d,void e.next()):e.error("INTERNAL SERVER ERROR")}))}create(e,t,i){return Ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".create",i)}))}delete(e,t,i){return Ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".delete",i)}))}error(e){it.error(e.message,"api.controller",Ce.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,i){return Ne(this,void 0,void 0,(function*(){if(i){const r=yield this.permissions(i,{route:t});if(r&&r.length>0)return e.next()}e.unauthorized("ACCESS DENIED")}))}permissions(e,t){return Ne(this,void 0,void 0,(function*(){return yield Xe.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:Ze,required:!0,include:[{model:Ve,required:!0,where:{state:!0},include:[{model:Ye,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error)}))}read(e,t,i){return Ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",i)}))}session(e,t,i){return Ne(this,void 0,void 0,(function*(){i.auth&&i.user&&(i.user_agent?i.user_agent!=t&&i.regenerate(Q):(i.user_agent=t,i.save(Q))),e.next()}))}upload(e,t){t.path||(t.path=Ce.API_UPLOAD_TEMP),t.size||(t.size=Ce.API_UPLOAD_SIZE),t.field||(t.field=Ce.API_UPLOAD_FIELD),d.middleware(e,t)}update(e,t,i){return Ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".update",i)}))}validation(e,t){return Ne(this,void 0,void 0,(function*(){const{error:i,value:r}=yield ne.object(t).parse().validateAsync(e.req.body);if(i)return e.validation(i);e.req.body=r,e.next()}))}}Te([De(0,i()),De(1,r(Ce.API_KEY_HEADER)),De(2,r(Ce.API_TOKEN_HEADER)),De(3,r("user-agent")),De(4,s()),be("design:type",Function),be("design:paramtypes",[a,String,String,String,at]),be("design:returntype",Promise)],ut.prototype,"auth",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],ut.prototype,"create",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],ut.prototype,"delete",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],ut.prototype,"permission",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],ut.prototype,"read",null),Te([De(0,i()),De(1,r("user-agent")),De(2,o()),be("design:type",Function),be("design:paramtypes",[a,String,Object]),be("design:returntype",Promise)],ut.prototype,"session",null),Te([De(0,i()),De(1,n()),be("design:type",Function),be("design:paramtypes",[a,Object]),be("design:returntype",void 0)],ut.prototype,"upload",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],ut.prototype,"update",null),Te([De(0,i()),De(1,n()),be("design:type",Function),be("design:paramtypes",[a,Object]),be("design:returntype",Promise)],ut.prototype,"validation",null);let pt=class extends ut{constructor(){super(...arguments),this._attributes=[]}_add(e){return Ne(this,arguments,void 0,(function*({ctx:e,options:t,body:i}){const r=yield this.model().create(Object.assign(Object.assign({},e.req.body),i||{}),Object.assign(Object.assign({},t||{}),we(e))).catch(this.error);if(r){const t=this.key();return e.prepare(p.OK,{[t]:r.getDataValue(t)}),r}e.error("INTERNAL SERVER ERROR")}))}_all(e){return Ne(this,arguments,void 0,(function*({ctx:e,options:t,callback:i,scope:r,advanced:s,attributes:n,unlimited:o}){var d,a,u;const c=this.scope(r),l=Object.assign({},t||{}),{limit:y,offset:g,asc:h,desc:v,search:_,where:m}=e.req.query;if(ae(l.limit)){const e=ue(de(y)?parseInt(y)||0:Ce.API_MODEL_LIMIT,-1,Ce.API_MODEL_LIMIT_MAX);l.limit=e>0?e:o?void 0:Ce.API_MODEL_LIMIT}if(de(g)){const e=g&&parseInt(g)||0;l.offset=e>0?e:void 0}n=null!=n?n:this.attributes(null!==(d=null==l?void 0:l.attributes)&&void 0!==d?d:[]);const O=[],f=e=>n.indexOf(e)>=0;if(de(h)&&h.length&&O.push(...h.split(";").filter(f).map((e=>[e,"ASC"]))),de(v)&&v.length&&O.push(...v.split(";").filter(f).map((e=>[e,"DESC"]))),O.length&&(l.order=O),l.where=Object.assign({},l.where||{}),de(m)&&(null==s||s)){const t=V.parse(n,m);if(!ae(t.error))return e.validation(t.error.join(", ")),{count:0,records:[]};l.where=Object.assign(Object.assign({},l.where),null!==(a=t.value)&&void 0!==a?a:{})}else{const e=[];n.forEach((t=>{de(_)&&_.length&&e.push({[t]:{[he.like]:`%${_}%`}})})),e.length&&(l.where=Object.assign(Object.assign({},l.where),{[he.or]:[...e]}))}const E=c.count(Object.assign(Object.assign({},l),{distinct:!!l.include,col:this._attributes.length?this._attributes[0]:void 0})).catch(this.error),P=c.findAll(l).catch(this.error);yield Promise.allSettled([E,P]);const I=null!==(u=yield E)&&void 0!==u?u:0;let A=yield P;const R={count:I};return A?(A=i?yield i(A):A,(pe(null==t?void 0:t.limit)||0==I)&&(R.count=A.length),e.prepare(p.OK,Object.assign(Object.assign({},R),{records:A})),Object.assign(Object.assign({},R),{records:A})):(e.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},R),{records:[]}))}))}_del(e){return Ne(this,arguments,void 0,(function*({ctx:e,options:t}){const i=this.key(),{[i]:r}=e.req.params;if(!r)return e.error("INTERNAL SERVER ERROR"),0;const s=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:r}),individualHooks:!0}),we(e))).catch(this.error);return s?(e.success("OK"),s):(e.notFound("RECORD NOT FOUND"),0)}))}_get(e){return Ne(this,arguments,void 0,(function*({ctx:e,options:t,callback:i,scope:r}){const s=this.key(),{[s]:n}=e.req.params,o=yield this.scope(r).findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[s]:n})})).catch(this.error);return o?(e.prepare(p.OK,i?yield i(o):o.toJSON()),o):null===o?e.notFound("RECORD NOT FOUND"):void e.error("INTERNAL SERVER ERROR")}))}_set(e){return Ne(this,arguments,void 0,(function*({ctx:e,options:t,body:i}){var r;const s=this.key(),{[s]:n}=e.req.params,[o]=null!==(r=yield this.model().update(Object.assign(Object.assign({},e.req.body),i||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[s]:n}),individualHooks:!0}),we(e))).catch(this.error))&&void 0!==r?r:[];return o?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)}))}attributes(e){if(0==this._attributes.length&&(this._attributes=Object.keys(this.model().getAttributes())),oe(e))return e.map((e=>de(e)&&-1!=this._attributes.indexOf(e)?e:void 0)).filter(de);const{exclude:t,include:i}=e,r=ae(i)?this._attributes:i.map((e=>de(e)&&-1!=this._attributes.indexOf(e)?e:void 0)).filter(de),s=null!=t?t:[];return s.length?r.filter((e=>-1==s.indexOf(e)?e:void 0)).filter(de):r}error(e){e.sql?it.error(e.message+"\n"+e.sql,"api.controller.sql",Ce.API_CONSOLE_ERROR):super.error(e)}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}};pt=Te([u(ut)],pt);let ct=class extends pt{model(){return ze}all(e,t,i){return Ne(this,void 0,void 0,(function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this._all({ctx:e,options:{attributes:{exclude:["data","previously"]},where:r,order:[["created_at","DESC"]]}})}))}get(e){return Ne(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}};Te([c(),l("auth"),l("read"),De(0,i()),De(1,y("type")),De(2,y("table")),be("design:type",Function),be("design:paramtypes",[a,String,String]),be("design:returntype",Promise)],ct.prototype,"all",null),Te([c("/:id"),l("auth"),l("read"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ct.prototype,"get",null),ct=Te([g("/audits"),u(pt)],ct);let lt=class extends ut{login(e,t,i,r,s){return Ne(this,void 0,void 0,(function*(){var n;yield ie(Ce.API_SLEEP_AUTH);const o=yield We.scope("password").findOne({where:{[he.or]:[{email:i},{username:i}]}}).catch(this.error);if(r+=null!==(n=null==o?void 0:o.salt)&&void 0!==n?n:"",!o||o.password!=J(r))return e.notFound("INVALID USERNAME OR PASSWORD"),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const d=yield Me.findOne({where:{state:!0,user_id:o.id}}).catch(this.error);if(d)return e.error("ACTIVATION REQUIRED"),s.emit("auth.activation",{ctx:e,register:d,user:o}),void this.emit("auth.activation",{ctx:e,register:d,user:o});if(!o.state)return e.notFound("INVALID USERNAME OR PASSWORD"),s.emit("auth.failure",{ctx:e,user:o}),void this.emit("auth.failure",{ctx:e,user:o});const{auth:a,error:u,token:p}=yield dt.create(o);return u?(e.error(u),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):a&&p?(a.user_agent=t,yield a.save().catch(this.error),e.json({token:p}),s.emit("auth.login",{auth:a,ctx:e,user:o}),void this.emit("auth.login",{auth:a,ctx:e,user:o})):(e.error("INTERNAL SERVER ERROR"),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,i,r){return Ne(this,void 0,void 0,(function*(){if(yield dt.destroy(t))return e.success("OK"),r.emit("auth.logout",{auth:t,ctx:e,user:i}),void this.emit("auth.logout",{auth:t,ctx:e,user:i});e.unauthorized("ACCESS DENIED")}))}renew(e,t,i,r){return Ne(this,void 0,void 0,(function*(){const{auth:s,error:n,token:o}=yield dt.renew(i);return n?e.error(n):s?(s.user_agent=t,yield s.save().catch(this.error),e.json({token:o}),r.emit("auth.renew",{auth:s,ctx:e}),void this.emit("auth.renew",{auth:s,ctx:e})):e.error("INTERNAL SERVER ERROR")}))}user(e,t){return Ne(this,void 0,void 0,(function*(){const i=yield this.permissions(t);if(!i)return e.error("INTERNAL SERVER ERROR");e.json(Object.assign(Object.assign({},ce(["username","date","description","state","created_at","updated_at","deleted_at"],t.toJSON())),{permissions:i.map((e=>e.route))}))}))}};Te([h("/login"),l("validation",{username:ne.string().min(3).required(),password:ne.string().min(5).required()}),De(0,i()),De(1,r("user-agent")),De(2,v("username")),De(3,v("password")),De(4,s()),be("design:type",Function),be("design:paramtypes",[a,String,String,String,at]),be("design:returntype",Promise)],lt.prototype,"login",null),Te([c("/logout"),l("auth"),De(0,i()),De(1,xe()),De(2,Fe()),De(3,s()),be("design:type",Function),be("design:paramtypes",[a,Be,We,at]),be("design:returntype",Promise)],lt.prototype,"logout",null),Te([h("/renew"),l("validation",{token:ne.string().required()}),De(0,i()),De(1,r("user-agent")),De(2,v("token")),De(3,s()),be("design:type",Function),be("design:paramtypes",[a,String,String,at]),be("design:returntype",Promise)],lt.prototype,"renew",null),Te([c(),l("auth"),De(0,i()),De(1,Fe()),be("design:type",Function),be("design:paramtypes",[a,We]),be("design:returntype",Promise)],lt.prototype,"user",null),lt=Te([g("/auth"),u(ut)],lt);let yt=class extends ut{directory(){return Ce.API_HTTP_PUBLIC||"./"}files(e){return Ne(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=Se(this.directory(),t);if(!_e(i)||!Oe(i).isDirectory())return e.notFound("RECORD NOT FOUND");let r=[];return r=fe(i),r=r.map((e=>this.info(Se(i,e)))),r=r.filter(le),Object.assign(Object.assign({},this.info(i)),{files:r})}))}access(e,t,i){return Ne(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,i)}))}info(e){if(!_e(e))return null;const t=Oe(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"}};Te([c("/path/?*"),l("auth"),l("access","list"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],yt.prototype,"files",null),Te([De(0,i()),De(1,n()),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],yt.prototype,"access",null),yt=Te([g("/files"),u(ut)],yt);let gt=class extends ut{check(e,t){return Ne(this,void 0,void 0,(function*(){const i=yield this.find(t);if(!i||!i.user)return e.notFound("RECORD NOT FOUND");i.token=ye(),yield i.save(),e.json({token:i.token})}))}forgot(e,t,i){return Ne(this,void 0,void 0,(function*(){yield ie(Ce.API_SLEEP_FORGOT);const r=t,s=yield We.findOne({where:{[he.or]:[{email:r},{username:t}]}}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");const n=ye(),o=Date.now()+6e4*Ce.API_TOKEN_FORGOT,d=yield Je.create({token:n,timestamp:o,state:!0,user_id:s.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:d,user:s}),this.emit("forgot.send",{ctx:e,forgot:d,user:s})}))}reset(e,t,i,r){return Ne(this,void 0,void 0,(function*(){const s=yield this.find(t);if(!s)return e.notFound("RECORD NOT FOUND");s.state=!1,yield s.save().catch(this.error),s.user.password=J(i),yield s.user.save().catch(this.error),e.success("OK"),r.emit("forgot.reset",{ctx:e,user:s.user}),this.emit("forgot.reset",{ctx:e,user:s.user})}))}find(e){return Ne(this,void 0,void 0,(function*(){return yield Je.findOne({where:{token:e,state:!0},include:[{model:We,required:!0}]}).catch(this.error)}))}};Te([c("/check"),l("validation",{token:ne.string().required()}),De(0,i()),De(1,v("token")),be("design:type",Function),be("design:paramtypes",[a,String]),be("design:returntype",Promise)],gt.prototype,"check",null),Te([h(),l("validation",{username:ne.string().min(4).required()}),De(0,i()),De(1,v("username")),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,String,at]),be("design:returntype",Promise)],gt.prototype,"forgot",null),Te([h("/reset"),l("validation",{token:ne.string().required(),password:ne.string().min(5).required()}),De(0,i()),De(1,v("token")),De(2,v("password")),De(3,s()),be("design:type",Function),be("design:paramtypes",[a,String,String,at]),be("design:returntype",Promise)],gt.prototype,"reset",null),gt=Te([g("/forgot"),u(ut)],gt);let ht=class extends pt{constructor(){super(...arguments),this._crud={}}add(e){return Ne(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return Ne(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}CrudCreate(){return this._crud}del(e){return Ne(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return Ne(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return Ne(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}CrudUpdate(){return this._crud}validationAdd(e){return Ne(this,void 0,void 0,(function*(){const t=this.CrudCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)}))}validationSet(e){return Ne(this,void 0,void 0,(function*(){const t=this.CrudUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)}))}};Te([h(),l("auth"),l("create"),l("validationAdd"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"add",null),Te([c(),l("auth"),l("read"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"all",null),Te([_("/:id"),l("auth"),l("delete"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"del",null),Te([c("/:id"),l("auth"),l("read"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"get",null),Te([m("/:id"),l("auth"),l("update"),l("validationSet"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"set",null),Te([De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"validationAdd",null),Te([De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],ht.prototype,"validationSet",null),ht=Te([u(pt)],ht);let vt=class extends ht{model(){return Ve}CrudCreate(){return{name:ne.string().required(),description:ne.string().empty(""),state:ne.boolean().parse().required()}}CrudUpdate(){return{name:ne.string().empty(),description:ne.string().empty(),state:ne.boolean().parse().empty()}}};vt=Te([g("/groups"),u(ht)],vt);let _t=class extends pt{model(){return Ze}all(e,t){return Ne(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{group_id:t},include:[{model:Xe,required:!0}]},callback:e=>e.map((e=>e.permission))})}))}set(e,t,i,r){return Ne(this,void 0,void 0,(function*(){const s=yield Ve.findByPk(t,{attributes:["id"]}).catch(this.error);if(s){const t=s.id;if(yield Ze.destroy(Object.assign({where:{group_id:t},individualHooks:!0},r)),i){let e=0;yield ie(1e3);for(let s=0;s<i.length;s++)e=yield Xe.count({where:{id:i[s]}}),e&&(yield Ze.create({group_id:t,permission_id:i[s]},Object.assign({},r)))}return e.success("OK")}if(ge(s))return e.notFound("RECORD NOT FOUND");e.error("INTERNAL SERVER ERROR")}))}};Te([c("/:id/permissions"),l("auth"),l("read","groups"),De(0,i()),De(1,O("id")),be("design:type",Function),be("design:paramtypes",[a,String]),be("design:returntype",Promise)],_t.prototype,"all",null),Te([m("/:id/permissions"),l("auth"),l("update","groups"),l("validation",{permissions:ne.array(ne.number().parse())}),De(0,i()),De(1,O("id")),De(2,v("permissions")),De(3,je()),be("design:type",Function),be("design:paramtypes",[a,String,Array,Object]),be("design:returntype",Promise)],_t.prototype,"set",null),_t=Te([g("/groups"),u(pt)],_t);let mt=class extends pt{model(){return Qe}all(e,t,i){return Ne(this,void 0,void 0,(function*(){const r={};t&&(r.type=t),i&&(r.source=i),yield this._all({ctx:e,options:{where:r,order:[["created_at","DESC"]]}})}))}};Te([c(),l("auth"),l("read"),De(0,i()),De(1,y("type")),De(2,y("source")),be("design:type",Function),be("design:paramtypes",[a,String,String]),be("design:returntype",Promise)],mt.prototype,"all",null),mt=Te([g("/logs"),u(pt)],mt);let Ot=class extends ht{model(){return Xe}CrudCreate(){return{name:ne.string().required(),route:ne.string().required(),description:ne.string().empty(""),state:ne.boolean().parse().required()}}CrudUpdate(){return{name:ne.string().empty(),route:ne.string().empty(),description:ne.string().empty(),state:ne.boolean().parse().empty()}}};Ot=Te([g("/permissions"),u(ht)],Ot);let ft=class extends ut{register(e,t,i){return Ne(this,void 0,void 0,(function*(){yield ie(Ce.API_SLEEP_REGISTRY);const{name:r,date:s,email:n,username:o,password:d,confirm:a}=t,u=o||n,p=J(d);if(yield We.count({where:{[he.or]:[{email:n},{username:u}]}}).catch(this.error))return e.validation("INVALID EMAIL OR USERNAME");if(p!=J(a))return e.error("INVALID PASSWORD");const c=yield We.create({name:r,email:n,username:u,password:p,avatar:"",date:s,description:"",state:!1}).catch(this.error);if(!c)return e.error("INTERNAL SERVER ERROR");const l=yield Me.create({token:yield this.getId(),user_id:c.id,state:!0}).catch(this.error);if(!l)return yield c.destroy().catch(this.error),e.error("INTERNAL SERVER ERROR");e.success("OK"),i.emit("register.user",{ctx:e,register:l,user:c}),this.emit("register.user",{ctx:e,register:l,user:c})}))}confirm(e,t,i){return Ne(this,void 0,void 0,(function*(){const r=yield Me.findOne({where:{token:t,state:!0},include:[{model:We,required:!0}]}).catch(this.error);if(!r)return e.notFound("RECORD NOT FOUND");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 Ne(this,void 0,void 0,(function*(){const r=t,s=yield Me.findOne({where:{state:!0},include:[{model:We,required:!0,where:{[he.or]:[{email:r},{username:t}]}}]}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");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 Ne(this,void 0,void 0,(function*(){const e=te();return(yield Me.count({where:{token:e}}))?this.getId():e}))}};Te([h(),l("validation",{name:ne.string().required(),date:ne.date().required(),email:ne.string().email().required(),username:ne.string().min(4).empty(),password:ne.string().min(5).required(),confirm:ne.string().min(5).required()}),De(0,i()),De(1,v()),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,Object,at]),be("design:returntype",Promise)],ft.prototype,"register",null),Te([h("/confirm"),l("validation",{token:ne.string().required()}),De(0,i()),De(1,v("token")),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,String,at]),be("design:returntype",Promise)],ft.prototype,"confirm",null),Te([h("/send"),l("validation",{username:ne.string().min(4).required()}),De(0,i()),De(1,v("username")),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,String,at]),be("design:returntype",Promise)],ft.prototype,"send",null),ft=Te([g("/register"),u(ut)],ft);let Et=class extends ut{setup(e,t){return Ne(this,void 0,void 0,(function*(){if(0==(yield We.count())){const e=ye(),i=yield We.create({name:"Admin",email:"admin@localhost",username:"admin",password:J("admin"+e),salt:e,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},t)),r={description:"API CORE",state:!0},s=yield Ve.create(Object.assign({name:"Admin"},r),Object.assign({},t));yield Ye.create({user_id:i.id,group_id:s.id},Object.assign({},t));const n=["Users","Groups","Permissions"],o=["Create","Read","Update","Delete"];yield re(n,(e=>Ne(this,void 0,void 0,(function*(){yield re(o,(i=>Ne(this,void 0,void 0,(function*(){const n=yield Xe.create(Object.assign({name:`${e} ${i}`,route:`${e.toLowerCase()}.${i.toLowerCase()}`},r),Object.assign({},t));yield Ze.create({group_id:s.id,permission_id:n.id},Object.assign({},t))}))))}))));const d=["Delete","List","Read","Rename","Upload","Write"];yield re(d,(e=>Ne(this,void 0,void 0,(function*(){const i=yield Xe.create(Object.assign({name:`Files ${e}`,route:`files.${e.toLowerCase()}`},r),Object.assign({},t));yield Ze.create({group_id:s.id,permission_id:i.id},Object.assign({},t))}))));const a=["Audits","Logs"];yield re(a,(e=>Ne(this,void 0,void 0,(function*(){const i=yield Xe.create(Object.assign({name:`${e} Read`,route:`${e.toLowerCase()}.read`},r),Object.assign({},t));yield Ze.create({group_id:s.id,permission_id:i.id},Object.assign({},t))}))))}e.success("OK")}))}};Te([c(),De(0,i()),De(1,je()),be("design:type",Function),be("design:paramtypes",[a,Object]),be("design:returntype",Promise)],Et.prototype,"setup",null),Et=Te([g("/setup"),u(ut)],Et);let Pt=class extends pt{model(){return We}constructor(){super(),this.path=Ce.API_HTTP_PUBLIC+"/avatar",Ce.API_HTTP_PUBLIC&&_e(Ce.API_HTTP_PUBLIC)&&!_e(this.path)&&Ee(this.path)}avatar(e,t,i,r){return Ne(this,void 0,void 0,(function*(){if(t.length){const s=t[0].filename||"";if(s){const t=this.path+"/"+i.avatar;if(_e(t)&&Pe(t).isFile()&&Ie(t),i.avatar=s,yield i.save(Object.assign({},r)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")}))}avatar_delete(e,t,i){return Ne(this,void 0,void 0,(function*(){const r=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},i)).catch(this.error))&&_e(r)&&Ie(r),e.success("OK")}))}password(e,t,i,r,s){return Ne(this,void 0,void 0,(function*(){var n;if(Ce.API_USER_HISTORY){if(yield Ge.count({where:{password:J(i+r.id)}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED")}const o=yield this.scope("password").findOne({where:{id:r.id,state:!0}}).catch(this.error);return t+=null!==(n=null==o?void 0:o.salt)&&void 0!==n?n:"",o&&o.password==J(t)?(o.salt=ye(),o.password=J(i+o.salt),(yield o.save(Object.assign({},s)).catch(this.error))?e.success("OK"):void e.success("RECORD NOT CHANGED")):e.error("INVALID PASSWORD")}))}token(e,t,i){return Ne(this,void 0,void 0,(function*(){const r=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(r)return e.json({token:i.hash.decrypt(r.token)});e.notFound("RECORD NOT FOUND")}))}token_get(e,t,i){return Ne(this,void 0,void 0,(function*(){const r=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(r)return e.json({token:i.hash.decrypt(r.token)});e.notFound("RECORD NOT FOUND")}))}token_delete(e,t,i){return Ne(this,void 0,void 0,(function*(){const r=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(r)return r.token="",yield r.save(Object.assign({},i)).catch(this.error),e.success("OK");e.notFound("RECORD NOT FOUND")}))}token_renew(e,t,i,r){return Ne(this,void 0,void 0,(function*(){const s=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(s){const t=yield this.token_new();return s.token=r.hash.encrypt(t),yield s.save(Object.assign({},i)).catch(this.error),e.json({token:t})}e.notFound("RECORD NOT FOUND")}))}token_new(){return Ne(this,void 0,void 0,(function*(){var e;const t=te();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t}))}add(e,t){return Ne(this,void 0,void 0,(function*(){const i=ye(),r=yield this._add({ctx:e,body:{password:J(t+i),salt:i}});Ce.API_USER_HISTORY&&r&&(yield Ge.create({password:J(t+r.id),user_id:r.id}))}))}all(e){return Ne(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{attributes:{exclude:["password","salt","token"]}}})}))}del(e,t,i){return Ne(this,void 0,void 0,(function*(){if(i.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this._del({ctx:e})}))}get(e){return Ne(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t,i){return Ne(this,void 0,void 0,(function*(){if(Ce.API_USER_HISTORY&&i){const r=J(i+t);if(yield Ge.count({where:{password:r}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED");yield Ge.create({password:r,user_id:t}).catch(this.error)}const r=i?ye():"";yield this._set({ctx:e,body:i?{password:J(i+r),salt:r}:{}})}))}};Te([h("/avatar"),l("auth"),l("upload",(e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32}))),De(0,i()),De(1,f()),De(2,Fe()),De(3,je()),be("design:type",Function),be("design:paramtypes",[a,Array,We,Object]),be("design:returntype",Promise)],Pt.prototype,"avatar",null),Te([_("/avatar"),l("auth"),De(0,i()),De(1,Fe()),De(2,je()),be("design:type",Function),be("design:paramtypes",[a,We,Object]),be("design:returntype",Promise)],Pt.prototype,"avatar_delete",null),Te([h("/password"),l("auth"),l("validation",{oldPassword:ne.string().min(5).required(),newPassword:ne.string().min(5).required()}),De(0,i()),De(1,v("oldPassword")),De(2,v("newPassword")),De(3,Fe()),De(4,je()),be("design:type",Function),be("design:paramtypes",[a,String,String,We,Object]),be("design:returntype",Promise)],Pt.prototype,"password",null),Te([c("/token"),l("auth"),De(0,i()),De(1,Fe()),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,We,at]),be("design:returntype",Promise)],Pt.prototype,"token",null),Te([c("/token/:id"),l("auth"),l("create"),De(0,i()),De(1,O("id")),De(2,s()),be("design:type",Function),be("design:paramtypes",[a,String,at]),be("design:returntype",Promise)],Pt.prototype,"token_get",null),Te([_("/token/:id"),l("auth"),l("delete"),De(0,i()),De(1,O("id")),De(2,je()),be("design:type",Function),be("design:paramtypes",[a,String,Object]),be("design:returntype",Promise)],Pt.prototype,"token_delete",null),Te([c("/token/renew/:id"),l("auth"),l("update"),De(0,i()),De(1,O("id")),De(2,je()),De(3,s()),be("design:type",Function),be("design:paramtypes",[a,String,Object,at]),be("design:returntype",Promise)],Pt.prototype,"token_renew",null),Te([h(),l("auth"),l("create"),l("validation",{name:ne.string().required(),email:ne.string().email().required(),username:ne.string().min(4).required(),password:ne.string().min(5).required(),description:ne.string().empty(""),state:ne.boolean().parse().required()}),De(0,i()),De(1,v("password")),be("design:type",Function),be("design:paramtypes",[a,String]),be("design:returntype",Promise)],Pt.prototype,"add",null),Te([c(),l("auth"),l("read"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],Pt.prototype,"all",null),Te([_("/:id"),l("auth"),l("delete"),De(0,i()),De(1,O("id")),De(2,Fe()),be("design:type",Function),be("design:paramtypes",[a,String,We]),be("design:returntype",Promise)],Pt.prototype,"del",null),Te([c("/:id"),l("auth"),l("read"),De(0,i()),be("design:type",Function),be("design:paramtypes",[a]),be("design:returntype",Promise)],Pt.prototype,"get",null),Te([m("/:id"),l("auth"),l("update"),l("validation",{name:ne.string().empty(),email:ne.string().email().empty(),username:ne.string().min(4).empty(),password:ne.string().min(5).empty().filter(""),description:ne.string().empty(),state:ne.boolean().parse().empty()}),De(0,i()),De(1,O("id")),De(2,v("password")),be("design:type",Function),be("design:paramtypes",[a,String,String]),be("design:returntype",Promise)],Pt.prototype,"set",null),Pt=Te([g("/users"),u(pt),be("design:paramtypes",[])],Pt);let It=class extends pt{model(){return Ye}groups(e,t){return Ne(this,void 0,void 0,(function*(){yield this.all(e,t.id.toString())}))}all(e,t){return Ne(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{user_id:t},include:[{model:Ve,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,i,r){return Ne(this,void 0,void 0,(function*(){const s=yield We.findByPk(t,{attributes:["id"]}).catch(this.error);if(s){if(yield Ye.destroy(Object.assign({where:{user_id:s.id},individualHooks:!0},r)),i){let e=0;yield ie(1e3);for(let t=0;t<i.length;t++)e=yield Ve.count({where:{id:i[t]}}),e&&(yield Ye.create({user_id:s.id,group_id:i[t]},Object.assign({},r)))}return e.success("OK")}if(ge(s))return e.notFound("RECORD NOT FOUND");e.error("INTERNAL SERVER ERROR")}))}};Te([c("/groups"),l("auth"),l("read","users"),De(0,i()),De(1,Fe()),be("design:type",Function),be("design:paramtypes",[a,We]),be("design:returntype",Promise)],It.prototype,"groups",null),Te([c("/:id/groups"),l("auth"),l("read","users"),De(0,i()),De(1,O("id")),be("design:type",Function),be("design:paramtypes",[a,String]),be("design:returntype",Promise)],It.prototype,"all",null),Te([m("/:id/groups"),l("auth"),l("update","users"),l("validation",{groups:ne.array(ne.number().parse())}),De(0,i()),De(1,O("id")),De(2,v("groups")),De(3,je()),be("design:type",Function),be("design:paramtypes",[a,String,Array,Object]),be("design:returntype",Promise)],It.prototype,"set",null),It=Te([g("/users"),u(pt)],It);class At{static all(){return Ne(this,void 0,void 0,(function*(){const e=yield $e.findAll().catch(At.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e,t){return Ne(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 $e.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:r})).catch(At.error))||0)>0}))}static error(e){it.error(e.message,"api.config",Ce.API_CONSOLE_ERROR)}static get(e){return Ne(this,arguments,void 0,(function*(e,t=""){const[i]=(yield $e.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(At.error))||[];return i?i.value:t}))}static set(e,t,i){return Ne(this,void 0,void 0,(function*(){var r;const s=null!==(r=null==i?void 0:i.id)&&void 0!==r?r:null,[n]=(yield $e.findOrCreate(Object.assign({where:{key:e}},{user_id:s})).catch(At.error))||[];n&&(n.value=t,yield n.save().catch(At.error))}))}}export{at as Application,ze as Audit,ct as AuditsController,Be as Auth,lt as AuthController,At as Config,$e as Configs,ut as ControllerBase,ht as CrudController,Ce as Env,yt as FilesController,Je as Forgot,gt as ForgotController,Ve as Group,Ze as GroupPermission,vt as GroupsController,_t as GroupsPermissionsController,Qe as Log,it as Logs,mt as LogsController,ke as Metadata,Le as Migrate,et as Migration,He as Model,pt as ModelController,Xe as Permission,Ot as PermissionsController,Me as Register,ft as RegisterController,je as ReqAudit,xe as ReqAuth,Fe as ReqUser,tt as Session,Et as SetupController,ot as Store,dt as Token,We as User,Ye as UserGroup,Ge as UserHistory,Pt as UsersController,It as UsersGroupsController,we as audit,st as crt,Ue as database,qe as hooks,nt as key};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrewcaires/api",
3
- "version": "4.2.0",
3
+ "version": "4.2.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",
@@ -51,26 +51,26 @@
51
51
  "@andrewcaires/sequelize": "^1.2.0",
52
52
  "@andrewcaires/utils.js": "^0.4.2",
53
53
  "cors": "^2.8.5",
54
- "dotenv": "^16.4.5",
54
+ "dotenv": "^16.4.7",
55
55
  "express-session": "^1.18.1",
56
56
  "jsonwebtoken": "^9.0.2",
57
57
  "tsx": "^4.19.2",
58
58
  "ws": "^8.18.0"
59
59
  },
60
60
  "devDependencies": {
61
- "@rollup/plugin-commonjs": "^28.0.1",
61
+ "@rollup/plugin-commonjs": "^28.0.2",
62
62
  "@rollup/plugin-terser": "^0.4.4",
63
- "@rollup/plugin-typescript": "^12.1.1",
63
+ "@rollup/plugin-typescript": "^12.1.2",
64
64
  "@types/cors": "^2.8.17",
65
- "@types/express-session": "^1.18.0",
65
+ "@types/express-session": "^1.18.1",
66
66
  "@types/jsonwebtoken": "^9.0.7",
67
- "@types/node": "^22.9.1",
67
+ "@types/node": "^22.10.5",
68
68
  "@types/ws": "^8.5.13",
69
- "eslint": "^9.15.0",
69
+ "eslint": "^9.17.0",
70
70
  "mariadb": "^3.4.0",
71
- "rollup": "^4.27.3",
71
+ "rollup": "^4.29.1",
72
72
  "rollup-plugin-dts": "^6.1.1",
73
73
  "tslib": "^2.8.1",
74
- "typescript-eslint": "^8.15.0"
74
+ "typescript-eslint": "^8.19.0"
75
75
  }
76
76
  }