@andrewcaires/api 4.3.3 → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +2 -2
- package/dist/index.d.ts +139 -138
- package/dist/index.esm.js +2 -2
- package/package.json +8 -8
package/dist/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v4.
|
|
2
|
+
* @andrewcaires/api v4.4.0
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
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 h=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}},x=e.parameterFactory(({ctx:e})=>h(e)),m=e.parameterFactory(({ctx:e})=>e.req.auth),A=e.parameterFactory(({ctx:e})=>e.req.user);class v{static migrations(e){return r.Metadata(v.MIGRATE,e,{version:""})}}v.MIGRATE=Symbol("MIGRATE");const _=e=>t=>{v.migrations(t).version=e};o.config({quiet:!0});class E extends r.Env{}E.API_BASE_NAME=E.getString("API_BASE_NAME",""),E.API_BODYPARSER_STRICT=E.getBool("API_BODYPARSER_STRICT",!0),E.API_BODYPARSER_INFLATE=E.getBool("API_BODYPARSER_INFLATE",!0),E.API_BODYPARSER_LIMIT=E.getString("API_BODYPARSER_LIMIT","10mb"),E.API_BODYPARSER_TYPE=E.getString("API_BODYPARSER_TYPE","json"),E.API_CONSOLE_ERROR=E.getBool("API_CONSOLE_ERROR",!1),E.API_DB_DATABASE=E.getString("API_DB_DATABASE",""),E.API_DB_HOST=E.getString("API_DB_HOST","127.0.0.1"),E.API_DB_PASSWORD=E.getString("API_DB_PASSWORD",""),E.API_DB_PORT=E.getInt("API_DB_PORT",3306),E.API_DB_TYPE=E.getString("API_DB_TYPE",""),E.API_DB_USERNAME=E.getString("API_DB_USERNAME","root"),E.API_DB_LOG=E.getBool("API_DB_LOG",!1),E.API_DB_AUDIT=E.getBool("API_DB_AUDIT",!0),E.API_DB_PREFIX=E.getString("API_DB_PREFIX",""),E.API_DB_TIMEZONE=E.getString("API_DB_TIMEZONE","+00:00"),E.API_HTTP_CRT=E.getString("API_HTTP_CRT",""),E.API_HTTP_KEY=E.getString("API_HTTP_KEY",""),E.API_HTTP_PORT=E.getInt("API_HTTP_PORT",3e3),E.API_HTTP_PUBLIC=E.getString("API_HTTP_PUBLIC",""),E.API_HTTP_CROSS=E.getBool("API_HTTP_CROSS",!1),E.API_HTTP_HYBRID=E.getBool("API_HTTP_HYBRID",!1),E.API_HTTP_NOTFOUND=E.getString("API_HTTP_NOTFOUND",""),E.API_HTTP_PATH=E.getString("API_HTTP_PATH","/api"),E.API_HTTP_REDIRECT=E.getString("API_HTTP_REDIRECT",""),E.API_KEY_HASH=E.getString("API_KEY_HASH",""),E.API_KEY_HEADER=E.getString("API_KEY_HEADER","x-api-key"),E.API_MODEL_LIMIT=E.getInt("API_MODEL_LIMIT",10),E.API_MODEL_LIMIT_MAX=E.getInt("API_MODEL_LIMIT_MAX",500),E.API_SLEEP_AUTH=E.getMs("API_SLEEP_AUTH","2s"),E.API_SLEEP_FORGOT=E.getMs("API_SLEEP_FORGOT","5s"),E.API_SLEEP_REGISTRY=E.getMs("API_SLEEP_REGISTRY","5s"),E.API_SESSION_NAME=E.getString("API_SESSION_NAME","session.id"),E.API_SESSION_LIFETIME=E.getMs("API_SESSION_LIFETIME","1d"),E.API_SESSION_SECRET=E.getString("API_SESSION_SECRET","yoursecret"),E.API_TOKEN_CRT=E.getString("API_TOKEN_CRT",""),E.API_TOKEN_KEY=E.getString("API_TOKEN_KEY",""),E.API_TOKEN_FORGOT=E.getMs("API_TOKEN_LIFETIME","1d"),E.API_TOKEN_HEADER=E.getString("API_TOKEN_HEADER","authorization"),E.API_TOKEN_HEADER_KEY=E.getString("API_TOKEN_HEADER","bearer"),E.API_TOKEN_LIFETIME=E.getMs("API_TOKEN_LIFETIME","1d"),E.API_TOKEN_RENEW=E.getMs("API_TOKEN_RENEW","1d"),E.API_UPLOAD_COUNT=E.getInt("API_UPLOAD_COUNT",1),E.API_UPLOAD_FIELD=E.getString("API_UPLOAD_FIELD","upload"),E.API_UPLOAD_SIZE=E.getInt("API_UPLOAD_SIZE",2),E.API_UPLOAD_TEMP=E.getString("API_UPLOAD_TEMP","./temp"),E.API_USER_HISTORY=E.getBool("API_USER_HISTORY",!0),E.API_WEBSOCKET_START=E.getBool("API_WEBSOCKET_START",!1);const S=new t.Connection({type:E.API_DB_TYPE,database:E.API_DB_DATABASE,username:E.API_DB_USERNAME,password:E.API_DB_PASSWORD,hostname:E.API_DB_HOST,hostport:E.API_DB_PORT,logging:E.API_DB_LOG,prefix:E.API_DB_PREFIX,timezone:E.API_DB_TIMEZONE});class P extends t.Model{constructor(){super(...arguments),this._version=""}}const C=(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}},O={afterCreate:(e,t)=>y(void 0,void 0,void 0,function*(){var r;if(!E.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({},C("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(!E.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({},C("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(!E.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({},C("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(S),t.ModelName("auth"),_("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(S),t.ModelName("register"),_("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(S),t.ModelName("group"),t.Hooks(O),_("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(S),t.ModelName("users_groups"),t.Hooks(O),_("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(S),t.ModelName("users_histories"),_("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(S),t.ModelName("user"),t.DefaultScope({attributes:{exclude:["password","salt","token"]}}),t.Scopes({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),t.Hooks(O),_("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(S),t.ModelName("audit"),_("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(S),t.ModelName("configs"),t.Hooks(O),_("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(S),t.ModelName("forgot"),_("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.String(),g("design:type",t.String)],exports.Permission.prototype,"tag",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(S),t.ModelName("permission"),t.Hooks(O),_("4.3.1")],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(S),t.ModelName("groups_permissions"),t.Hooks(O),_("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(S),t.ModelName("log"),_("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(S),t.ModelName("migration"),_("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(S),t.ModelName("session"),_("4.2.0")],exports.Session);class I{static write(e,t,o){return y(this,void 0,void 0,function*(){yield I.writeRaw(r.LogColor.White,"",e,t,o)})}static error(e,t,o){return y(this,void 0,void 0,function*(){yield I.writeRaw(r.LogColor.Red,"error",e,t,o)})}static info(e,t,o){return y(this,void 0,void 0,function*(){yield I.writeRaw(r.LogColor.Cyan,"info",e,t,o)})}static success(e,t,o){return y(this,void 0,void 0,function*(){yield I.writeRaw(r.LogColor.Green,"success",e,t,o)})}static warning(e,t,o){return y(this,void 0,void 0,function*(){yield I.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),S&&(yield exports.Log.create({type:t,source:i,message:o}).catch(()=>null))})}}const f=e=>d.existsSync(e)?d.readFileSync(e):void 0,R={http:f(E.API_HTTP_CRT),token:f(E.API_TOKEN_CRT)},T={http:f(E.API_HTTP_KEY),token:f(E.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)}return void t(null,e)}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()+E.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){let t="token";E.API_BASE_NAME&&(t=`${E.API_BASE_NAME}.${t}`),I.error(e.message,t,E.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:`${E.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,E.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 N extends e.Application{constructor(e){super(e,{cert:R.http,cross:E.API_HTTP_CROSS,hybrid:E.API_HTTP_HYBRID,json:{strict:E.API_BODYPARSER_STRICT,inflate:E.API_BODYPARSER_INFLATE,limit:E.API_BODYPARSER_LIMIT,type:E.API_BODYPARSER_TYPE},key:T.http,notfound:E.API_HTTP_NOTFOUND,path:E.API_HTTP_PATH,port:E.API_HTTP_PORT,public:E.API_HTTP_PUBLIC,redirect:E.API_HTTP_REDIRECT,session:{store:new D,name:E.API_SESSION_NAME,secret:E.API_SESSION_SECRET,cookie:{maxAge:E.API_SESSION_LIFETIME},genid:i.uuidv4}}),this.hash=new r.Hash(E.API_KEY_HASH)}error(e,t){E.API_BASE_NAME&&(t=t?`${E.API_BASE_NAME}.${t}`:E.API_BASE_NAME),I.error(e.message,t,E.API_CONSOLE_ERROR)}log(e,t){E.API_BASE_NAME&&(t=t?`${E.API_BASE_NAME}.${t}`:E.API_BASE_NAME),I.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return y(this,void 0,void 0,function*(){yield S.sync(),yield this.migrations(S),yield i.forEachSeries(this.controllers,e=>y(this,void 0,void 0,function*(){i.isFunction(e.sync)&&(yield e.sync(this))})),yield e.listen.call(this),E.API_WEBSOCKET_START&&this.server&&(this._webSocket=new n.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(E.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}=v.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 U extends i.EventEmitter{auth(e,t,r,o,i){return y(this,void 0,void 0,function*(){var s;const[n,d]=null!==(s=null==r?void 0:r.split(" "))&&void 0!==s?s:["",""];if(!d||n.toLowerCase()!=E.API_TOKEN_HEADER_KEY)return e.error("INVALID TOKEN");const{auth:a,error:p,user:l}=yield w.user(t,d,i);return p?e.error(p):a&&l?a.user_agent&&a.user_agent!=o?e.error("INVALID TOKEN"):(e.req.auth=a,e.req.user=l,void e.next()):e.error("INTERNAL SERVER ERROR")})}canCreate(e,t,r){return y(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".create",r)})}canDelete(e,t,r){return y(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".delete",r)})}canRead(e,t,r){return y(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".read",r)})}canUpdate(e,t,r){return y(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".update",r)})}error(e){let t="controller_base";E.API_BASE_NAME&&(t=`${E.API_BASE_NAME}.${t}`),I.error(e.message,t,E.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return y(this,void 0,void 0,function*(){if(r){if((yield this.permissions(r,{route:t})).length>0)return e.next()}e.unauthorized("ACCESS DENIED")})}permissions(e,t){return y(this,void 0,void 0,function*(){var r;return null!==(r=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))&&void 0!==r?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()})}sync(){return y(this,void 0,void 0,function*(){})}upload(t,r){r.path||(r.path=E.API_UPLOAD_TEMP),r.size||(r.size=E.API_UPLOAD_SIZE),r.field||(r.field=E.API_UPLOAD_FIELD),e.Upload.middleware(t,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(E.API_KEY_HEADER)),c(2,e.Headers(E.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,N]),g("design:returntype",Promise)],U.prototype,"auth",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,A()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],U.prototype,"canCreate",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,A()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],U.prototype,"canDelete",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,A()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],U.prototype,"canRead",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,A()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],U.prototype,"canUpdate",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,A()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],U.prototype,"permission",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)],U.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)],U.prototype,"upload",null),u([c(0,e.Ctx()),c(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",Promise)],U.prototype,"validation",null);class b{}var M,F,B,L;b.ATTRIBUTES=Symbol("ATTRIBUTES"),b.PERMISSIONS=Symbol("PERMISSIONS"),exports.ModelController=class extends U{constructor(){super(...arguments),this[M]=[],this[F]=["create","read","update","delete"]}attributes(e){if(0==this[b.ATTRIBUTES].length&&(this[b.ATTRIBUTES]=Object.keys(this.model().getAttributes())),i.isArray(e))return e.length?e.map(e=>i.isString(e)&&-1!=this[b.ATTRIBUTES].indexOf(e)?e:void 0).filter(i.isString):this[b.ATTRIBUTES];const{exclude:t,include:r}=e,o=i.isUndefined(r)?this[b.ATTRIBUTES]:r.map(e=>i.isString(e)&&-1!=this[b.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}create(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||{}),h(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")})}delete(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}),h(e))).catch(this.error);return i?(e.success("OK"),i):(e.notFound("RECORD NOT FOUND"),0)})}error(e){let t="controller_model";E.API_BASE_NAME&&(t=`${E.API_BASE_NAME}.${t}`),(null==e?void 0:e.sql)?I.error((null==e?void 0:e.message)+"\n"+(null==e?void 0:e.sql),t,E.API_CONSOLE_ERROR):super.error(e)}findAll(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),h=Object.assign({},o||{}),{limit:x,offset:m,asc:A,desc:v,search:_,where:S}=r.req.query;if(i.isUndefined(h.limit)){const e=i.clamp(i.isString(x)?parseInt(x)||0:E.API_MODEL_LIMIT,-1,E.API_MODEL_LIMIT_MAX);h.limit=e>0?e:l?void 0:E.API_MODEL_LIMIT}if(i.isNumber(h.limit)&&(h.limit=h.limit>0?h.limit:void 0),i.isString(m)){const e=m&&parseInt(m)||0;h.offset=e>0?e:void 0}p=null!=p?p:this.attributes(null!==(u=null==h?void 0:h.attributes)&&void 0!==u?u:[]);const P=[],C=e=>p.indexOf(e)>=0;if(i.isString(A)&&A.length&&P.push(...A.split(";").filter(C).map(e=>[e,"ASC"])),i.isString(v)&&v.length&&P.push(...v.split(";").filter(C).map(e=>[e,"DESC"])),P.length&&(h.order=P),h.where=Object.assign({},h.where||{}),i.isString(S)&&(null==a||a)){const e=t.Where.parse(p,S);if(!i.isUndefined(e.error))return r.validation(e.error.join(", ")),{count:0,records:[]};h.where=Object.assign(Object.assign({},h.where),null!==(c=e.value)&&void 0!==c?c:{})}else{const e=[];p.forEach(t=>{i.isString(_)&&_.length&&e.push({[t]:{[s.Op.like]:`%${_}%`}})}),e.length&&(h.where=Object.assign(Object.assign({},h.where),{[s.Op.or]:[...e]}))}const O=y.count(Object.assign(Object.assign({},h),{distinct:!!h.include,col:this[b.ATTRIBUTES].length?this[b.ATTRIBUTES][0]:void 0})).catch(this.error),I=y.findAll(h).catch(this.error);yield Promise.allSettled([O,I]);const f=null!==(g=yield O)&&void 0!==g?g:0;let R=yield I;const T={count:f};return R?(R=n?yield n(R):R,(i.isNumber(null==o?void 0:o.limit)||0==f)&&(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:[]}))})}findOne(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")})}sync(){return y(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield i.forEachSeries(this[b.PERMISSIONS],r=>y(this,void 0,void 0,function*(){const o=`${e}.${r}`,s=i.upperCamelCase(e.replace(/_/g," ")," ");yield exports.Permission.findOrCreate({where:{route:o},defaults:Object.assign({name:`${s} ${i.upperCamelCase(r," ")}`,route:o,tag:s},t)})}))})}update(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}),h(e))).catch(this.error))&&void 0!==o?o:[];return n?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)})}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}},M=b.ATTRIBUTES,F=b.PERMISSIONS,exports.ModelController=u([e.Extends(U)],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.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:o,order:[["created_at","DESC"]]},unlimited:!0})})}get(e){return y(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}},u([e.Get(),e.Middleware("auth"),e.Middleware("canRead"),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("canRead"),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 U{login(e,t,o,n,d){return y(this,void 0,void 0,function*(){var a;yield i.sleep(E.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,N]),g("design:returntype",Promise)],exports.AuthController.prototype,"login",null),u([e.Get("/logout"),e.Middleware("auth"),c(0,e.Ctx()),c(1,m()),c(2,A()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.Auth,exports.User,N]),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,N]),g("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),u([e.Get(),e.Middleware("auth"),c(0,e.Ctx()),c(1,A()),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(U)],exports.AuthController),exports.FilesController=class extends U{constructor(){super(...arguments),this[B]=["delete","download","edit","list","read","rename","upload","write"]}directory(){return E.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"}sync(){return y(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=i.upperCamelCase(e.replace(/_/g," ")," "),r={description:"",state:!0};yield i.forEachSeries(this[b.PERMISSIONS],o=>y(this,void 0,void 0,function*(){const s=`${e}.${o}`;yield exports.Permission.findOrCreate({where:{route:s},defaults:Object.assign({name:`${t} ${i.upperCamelCase(o," ")}`,route:s,tag:t},r)})}))})}},B=b.PERMISSIONS,u([e.Get("/path"),e.Get("/path/*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,A()),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(U)],exports.FilesController),exports.ForgotController=class extends U{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(E.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*E.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,N]),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,N]),g("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=u([e.Controller("/forgot"),e.Extends(U)],exports.ForgotController),exports.CrudController=class extends exports.ModelController{constructor(){super(...arguments),this._crud={}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return y(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return y(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}del(e){return y(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return y(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return y(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return y(this,void 0,void 0,function*(){const t=this.CrudValidationCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}validationUpdate(e){return y(this,void 0,void 0,function*(){const t=this.CrudValidationUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}},u([e.Post(),e.Middleware("auth"),e.Middleware("canCreate"),e.Middleware("validationCreate"),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("canRead"),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("canDelete"),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("canRead"),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("canUpdate"),e.Middleware("validationUpdate"),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,"validationCreate",null),u([c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationUpdate",null),exports.CrudController=u([e.Extends(exports.ModelController)],exports.CrudController),exports.GroupsController=class extends exports.CrudController{constructor(){super(...arguments),this.schemaCreate={name:i.Validation.string().required(),description:i.Validation.string().empty(""),state:i.Validation.boolean().parse().required()},this.schemaUpdate={name:i.Validation.string().empty(),description:i.Validation.string().empty(),state:i.Validation.boolean().parse().empty()}}model(){return exports.Group}CrudArgumentsFindAll(e){return{ctx:e,unlimited:!0}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},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.findAll({ctx:e,options:{where:{group_id:t},include:[{model:exports.Permission,required:!0}]},unlimited:!0,callback:e=>e.map(e=>e.permission)})})}me(e,t){return y(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}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)return e.notFound("RECORD NOT FOUND");const n=s.id;if(yield exports.GroupPermission.destroy(Object.assign({where:{group_id:n},individualHooks:!0},o)),r){let e=0;yield i.sleep(1e3);for(let t=0;t<r.length;t++)e=yield exports.Permission.count({where:{id:r[t]}}),e&&(yield exports.GroupPermission.create({group_id:n,permission_id:r[t]},Object.assign({},o)))}e.success("OK")})}},u([e.Get("/:id/permissions"),e.Middleware("auth"),e.Middleware("canRead","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.Get("/permissions"),e.Middleware("auth"),e.Middleware("canRead","users"),c(0,e.Ctx()),c(1,A()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"me",null),u([e.Put("/:id/permissions"),e.Middleware("auth"),e.Middleware("canUpdate","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,x()),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{constructor(){super(...arguments),this[L]=["read"]}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.findAll({ctx:e,options:{where:o,order:[["created_at","DESC"]]},unlimited:!0})})}},L=b.PERMISSIONS,u([e.Get(),e.Middleware("auth"),e.Middleware("canRead"),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{constructor(){super(...arguments),this.schemaCreate={name:i.Validation.string().required(),route:i.Validation.string().required(),tag:i.Validation.string().required(),description:i.Validation.string().empty(""),state:i.Validation.boolean().parse().required()},this.schemaUpdate={name:i.Validation.string().empty(),route:i.Validation.string().empty(),tag:i.Validation.string().empty(),description:i.Validation.string().empty(),state:i.Validation.boolean().parse().empty()}}model(){return exports.Permission}CrudArgumentsFindAll(e){return{ctx:e,unlimited:!0}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.PermissionsController=u([e.Controller("/permissions"),e.Extends(exports.CrudController)],exports.PermissionsController),exports.RegisterController=class extends U{register(e,t,o){return y(this,void 0,void 0,function*(){yield i.sleep(E.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 h=yield exports.Register.create({token:yield this.getId(),user_id:y.id,state:!0}).catch(this.error);if(!h)return yield y.destroy().catch(this.error),e.error("INTERNAL SERVER ERROR");e.success("OK"),o.emit("register.user",{ctx:e,register:h,user:y}),this.emit("register.user",{ctx:e,register:h,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,N]),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,N]),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,N]),g("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=u([e.Controller("/register"),e.Extends(U)],exports.RegisterController),exports.SetupController=class extends U{setup(e,t){return y(this,void 0,void 0,function*(){var o;if(yield exports.User.count())return e.success("OK");const s=i.uniqueID(),n=yield exports.User.create({name:"Admin",email:"admin@localhost",username:"admin",password:r.sha256("admin"+s),salt:s,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},t)),d=yield exports.Group.create(Object.assign({name:"Admin"},{description:"API CORE",state:!0}),Object.assign({},t));yield exports.UserGroup.create({user_id:n.id,group_id:d.id},Object.assign({},t));const a=null!==(o=yield exports.Permission.findAll({where:{state:!0}}).catch(this.error))&&void 0!==o?o:[];yield i.forEachSeries(a,e=>y(this,void 0,void 0,function*(){yield exports.GroupPermission.create({group_id:d.id,permission_id:e.id},Object.assign({},t))})),e.success("OK")})}},u([e.Get(),c(0,e.Ctx()),c(1,x()),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(U)],exports.SetupController),exports.UsersController=class extends exports.ModelController{model(){return exports.User}constructor(){super(),this.path=E.API_HTTP_PUBLIC+"/avatar",E.API_HTTP_PUBLIC&&d.existsSync(E.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_del(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(E.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_del(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_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_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.create({ctx:e,body:{password:r.sha256(t+o),salt:o}});E.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.findAll({ctx:e,options:{attributes:{exclude:["password","salt","token"]}},unlimited:!0})})}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.delete({ctx:e})})}get(e){return y(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e,t,o){return y(this,void 0,void 0,function*(){if(E.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.update({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,A()),c(3,x()),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,A()),c(2,x()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar_del",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(),confirmPassword:i.Validation.string().equal(i.Validation.ref("newPassword"))}),c(0,e.Ctx()),c(1,e.Body("oldPassword")),c(2,e.Body("newPassword")),c(3,A()),c(4,x()),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,A()),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,N]),g("design:returntype",Promise)],exports.UsersController.prototype,"token",null),u([e.Delete("/token/:id"),e.Middleware("auth"),e.Middleware("canDelete"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,x()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_del",null),u([e.Get("/token/:id"),e.Middleware("auth"),e.Middleware("canCreate"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,N]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_get",null),u([e.Get("/token/renew/:id"),e.Middleware("auth"),e.Middleware("canUpdate"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,x()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object,N]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_renew",null),u([e.Post(),e.Middleware("auth"),e.Middleware("canCreate"),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("canRead"),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("canDelete"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,A()),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("canRead"),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("canUpdate"),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}all(e,t){return y(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:exports.Group,required:!0}]},unlimited:!0,callback:e=>e.map(e=>e.group)})})}me(e,t){return y(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}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)return e.notFound("RECORD NOT FOUND");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)))}e.success("OK")})}},u([e.Get("/:id/groups"),e.Middleware("auth"),e.Middleware("canRead","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.Get("/groups"),e.Middleware("auth"),e.Middleware("canRead","users"),c(0,e.Ctx()),c(1,A()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"me",null),u([e.Put("/:id/groups"),e.Middleware("auth"),e.Middleware("canUpdate","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,x()),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 k{static all(){return y(this,void 0,void 0,function*(){const e=yield exports.Configs.findAll().catch(k.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(k.error))||0)>0})}static error(e){let t="config";E.API_BASE_NAME&&(t=`${E.API_BASE_NAME}.${t}`),I.error(e.message,t,E.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(k.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(k.error))||[];s&&(s.value=t,yield s.save().catch(k.error))})}}exports.Application=N,exports.Config=k,exports.ControllerBase=U,exports.ControllerKeys=b,exports.Env=E,exports.Logs=I,exports.Metadata=v,exports.Migrate=_,exports.Model=P,exports.ReqAudit=x,exports.ReqAuth=m,exports.ReqUser=A,exports.Store=D,exports.Token=w,exports.audit=h,exports.crt=R,exports.database=S,exports.hooks=O,exports.key=T;
|
|
7
|
+
"use strict";var e=require("@andrewcaires/node"),t=require("dotenv"),r=require("@andrewcaires/utils.js"),o=require("@andrewcaires/express"),i=require("@andrewcaires/sequelize"),s=require("jsonwebtoken"),n=require("fs"),d=require("ws"),a=require("express-session"),p=require("sequelize"),l=require("path");t.config({quiet:!0});class u extends e.Env{}u.API_BASE_NAME=u.getString("API_BASE_NAME",""),u.API_BODYPARSER_STRICT=u.getBool("API_BODYPARSER_STRICT",!0),u.API_BODYPARSER_INFLATE=u.getBool("API_BODYPARSER_INFLATE",!0),u.API_BODYPARSER_LIMIT=u.getString("API_BODYPARSER_LIMIT","10mb"),u.API_BODYPARSER_TYPE=u.getString("API_BODYPARSER_TYPE","json"),u.API_CONSOLE_ERROR=u.getBool("API_CONSOLE_ERROR",!1),u.API_DB_DATABASE=u.getString("API_DB_DATABASE",""),u.API_DB_HOST=u.getString("API_DB_HOST","127.0.0.1"),u.API_DB_PASSWORD=u.getString("API_DB_PASSWORD",""),u.API_DB_PORT=u.getInt("API_DB_PORT",3306),u.API_DB_TYPE=u.getString("API_DB_TYPE",""),u.API_DB_USERNAME=u.getString("API_DB_USERNAME","root"),u.API_DB_LOG=u.getBool("API_DB_LOG",!1),u.API_DB_AUDIT=u.getBool("API_DB_AUDIT",!0),u.API_DB_PREFIX=u.getString("API_DB_PREFIX",""),u.API_DB_TIMEZONE=u.getString("API_DB_TIMEZONE","+00:00"),u.API_HTTP_CRT=u.getString("API_HTTP_CRT",""),u.API_HTTP_KEY=u.getString("API_HTTP_KEY",""),u.API_HTTP_PORT=u.getInt("API_HTTP_PORT",3e3),u.API_HTTP_PUBLIC=u.getString("API_HTTP_PUBLIC",""),u.API_HTTP_CROSS=u.getBool("API_HTTP_CROSS",!1),u.API_HTTP_HYBRID=u.getBool("API_HTTP_HYBRID",!1),u.API_HTTP_NOTFOUND=u.getString("API_HTTP_NOTFOUND",""),u.API_HTTP_PATH=u.getString("API_HTTP_PATH","/api"),u.API_HTTP_REDIRECT=u.getString("API_HTTP_REDIRECT",""),u.API_KEY_HASH=u.getString("API_KEY_HASH",""),u.API_KEY_HEADER=u.getString("API_KEY_HEADER","x-api-key"),u.API_MODEL_LIMIT=u.getInt("API_MODEL_LIMIT",10),u.API_MODEL_LIMIT_MAX=u.getInt("API_MODEL_LIMIT_MAX",500),u.API_SLEEP_AUTH=u.getMs("API_SLEEP_AUTH","2s"),u.API_SLEEP_FORGOT=u.getMs("API_SLEEP_FORGOT","5s"),u.API_SLEEP_REGISTRY=u.getMs("API_SLEEP_REGISTRY","5s"),u.API_SESSION_NAME=u.getString("API_SESSION_NAME","session.id"),u.API_SESSION_LIFETIME=u.getMs("API_SESSION_LIFETIME","1d"),u.API_SESSION_SECRET=u.getString("API_SESSION_SECRET","yoursecret"),u.API_TOKEN_CRT=u.getString("API_TOKEN_CRT",""),u.API_TOKEN_KEY=u.getString("API_TOKEN_KEY",""),u.API_TOKEN_FORGOT=u.getMs("API_TOKEN_LIFETIME","1d"),u.API_TOKEN_HEADER=u.getString("API_TOKEN_HEADER","authorization"),u.API_TOKEN_HEADER_KEY=u.getString("API_TOKEN_HEADER","bearer"),u.API_TOKEN_LIFETIME=u.getMs("API_TOKEN_LIFETIME","1d"),u.API_TOKEN_RENEW=u.getMs("API_TOKEN_RENEW","1d"),u.API_UPLOAD_COUNT=u.getInt("API_UPLOAD_COUNT",1),u.API_UPLOAD_FIELD=u.getString("API_UPLOAD_FIELD","upload"),u.API_UPLOAD_SIZE=u.getInt("API_UPLOAD_SIZE",2),u.API_UPLOAD_TEMP=u.getString("API_UPLOAD_TEMP","./temp"),u.API_USER_HISTORY=u.getBool("API_USER_HISTORY",!0),u.API_WEBSOCKET_START=u.getBool("API_WEBSOCKET_START",!1);class c extends r.EventEmitter{}function g(e,t,r,o){var i,s=arguments.length,n=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,o);else for(var d=e.length-1;d>=0;d--)(i=e[d])&&(n=(s<3?i(n):s>3?i(t,r,n):i(t,r))||n);return s>3&&n&&Object.defineProperty(t,r,n),n}function y(e,t){return function(r,o){t(r,o,e)}}function h(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function x(e,t,r,o){return new(r||(r=Promise))(function(i,s){function n(e){try{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())})}c.ATTRIBUTES=Symbol("ATTRIBUTES"),c.PERMISSIONS=Symbol("PERMISSIONS"),"function"==typeof SuppressedError&&SuppressedError;const m=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}},v=o.parameterFactory(({ctx:e})=>m(e)),A=o.parameterFactory(({ctx:e})=>e.req.auth),_=o.parameterFactory(({ctx:e})=>e.req.user),S=e=>t=>{E.migrations(t).version=e};class E{static migrations(t){return e.Metadata(E.MIGRATE,t,{version:""})}}E.MIGRATE=Symbol("MIGRATE");class P extends i.Model{static error(t){e.Log.error(t.message)}}const C=new i.Connection({type:u.API_DB_TYPE,database:u.API_DB_DATABASE,username:u.API_DB_USERNAME,password:u.API_DB_PASSWORD,hostname:u.API_DB_HOST,hostport:u.API_DB_PORT,logging:u.API_DB_LOG,prefix:u.API_DB_PREFIX,timezone:u.API_DB_TIMEZONE}),O=(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}},I={afterCreate:(e,t)=>x(void 0,void 0,void 0,function*(){var o;if(!u.API_DB_AUDIT)return;const i=r.isObject(e)?e.constructor:null,s=null!==(o=null==i?void 0:i.primaryKeyAttribute)&&void 0!==o?o:null;yield exports.Audit.create(Object.assign(Object.assign({},O("CREATE",i,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(r.noop)}),afterUpdate:(e,t)=>x(void 0,void 0,void 0,function*(){var o;if(!u.API_DB_AUDIT)return;const i=r.isObject(e)?e.constructor:null,s=null!==(o=null==i?void 0:i.primaryKeyAttribute)&&void 0!==o?o:null,n={},d=e.changed();d&&d.forEach(t=>n[t]=e.getDataValue(t)),yield exports.Audit.create(Object.assign(Object.assign({},O("UPDATE",i,t)),{record:s?e.getDataValue(s):null,data:n,previously:e.previous()})).catch(r.noop)}),afterDestroy:(e,t)=>x(void 0,void 0,void 0,function*(){var o;if(!u.API_DB_AUDIT)return;const i=r.isObject(e)?e.constructor:null,s=null!==(o=null==i?void 0:i.primaryKeyAttribute)&&void 0!==o?o:null;yield exports.Audit.create(Object.assign(Object.assign({},O("DELETE",i,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(r.noop)})};var f;exports.Auth=class extends P{},g([i.Id(),h("design:type",Number)],exports.Auth.prototype,"id",void 0),g([i.String(),h("design:type",i.String)],exports.Auth.prototype,"secret",void 0),g([i.FullDate(),h("design:type",Object)],exports.Auth.prototype,"logout",void 0),g([i.String(),h("design:type",i.String)],exports.Auth.prototype,"user_agent",void 0),g([i.CreatedAt,h("design:type",Date)],exports.Auth.prototype,"created_at",void 0),g([i.UpdatedAt,h("design:type",Date)],exports.Auth.prototype,"updated_at",void 0),g([i.DeletedAt,h("design:type",Object)],exports.Auth.prototype,"deleted_at",void 0),g([i.BelongsTo(()=>exports.User),h("design:type",Number)],exports.Auth.prototype,"user_id",void 0),exports.Auth=g([i.Database(C),i.ModelName("auth"),S("4.2.0")],exports.Auth),exports.Register=class extends P{},g([i.Id(),h("design:type",Number)],exports.Register.prototype,"id",void 0),g([i.String(),h("design:type",i.String)],exports.Register.prototype,"token",void 0),g([i.Boolean(),h("design:type",i.Boolean)],exports.Register.prototype,"state",void 0),g([i.CreatedAt,h("design:type",Date)],exports.Register.prototype,"created_at",void 0),g([i.UpdatedAt,h("design:type",Date)],exports.Register.prototype,"updated_at",void 0),g([i.DeletedAt,h("design:type",Object)],exports.Register.prototype,"deleted_at",void 0),g([i.BelongsTo(()=>exports.User),h("design:type",Number)],exports.Register.prototype,"user_id",void 0),exports.Register=g([i.Database(C),i.ModelName("register"),S("4.2.0")],exports.Register),exports.Group=class extends P{},g([i.Id(),h("design:type",Number)],exports.Group.prototype,"id",void 0),g([i.String(),h("design:type",i.String)],exports.Group.prototype,"name",void 0),g([i.Text(),h("design:type",i.String)],exports.Group.prototype,"description",void 0),g([i.Boolean(),h("design:type",i.Boolean)],exports.Group.prototype,"state",void 0),g([i.CreatedAt,h("design:type",Date)],exports.Group.prototype,"created_at",void 0),g([i.UpdatedAt,h("design:type",Date)],exports.Group.prototype,"updated_at",void 0),g([i.DeletedAt,h("design:type",Object)],exports.Group.prototype,"deleted_at",void 0),g([i.HasMany(()=>exports.UserGroup,"group_id"),h("design:type",Array)],exports.Group.prototype,"groups_routes",void 0),g([i.HasMany(()=>exports.UserGroup,"group_id"),h("design:type",Array)],exports.Group.prototype,"users_groups",void 0),exports.Group=g([i.Database(C),i.ModelName("group"),i.Hooks(I),S("4.2.0")],exports.Group),exports.UserGroup=class extends P{},g([i.CreatedAt,h("design:type",Date)],exports.UserGroup.prototype,"created_at",void 0),g([i.BelongsTo(()=>exports.Group),h("design:type",Number)],exports.UserGroup.prototype,"group_id",void 0),g([i.BelongsTo(()=>exports.User),h("design:type",Number)],exports.UserGroup.prototype,"user_id",void 0),exports.UserGroup=g([i.Database(C),i.ModelName("users_groups"),i.Hooks(I),S("4.2.0")],exports.UserGroup),exports.UserHistory=class extends P{},g([i.String(),h("design:type",i.String)],exports.UserHistory.prototype,"password",void 0),g([i.CreatedAt,h("design:type",Date)],exports.UserHistory.prototype,"created_at",void 0),g([i.BelongsTo(()=>exports.User),h("design:type",Number)],exports.UserHistory.prototype,"user_id",void 0),exports.UserHistory=g([i.Database(C),i.ModelName("users_histories"),S("4.2.0")],exports.UserHistory),exports.User=class extends P{},g([i.Id(),h("design:type",Number)],exports.User.prototype,"id",void 0),g([i.String(),h("design:type",i.String)],exports.User.prototype,"name",void 0),g([i.String(),h("design:type",i.String)],exports.User.prototype,"email",void 0),g([i.String(),h("design:type",i.String)],exports.User.prototype,"username",void 0),g([i.String(),h("design:type",i.String)],exports.User.prototype,"password",void 0),g([i.String(),h("design:type",i.String)],exports.User.prototype,"salt",void 0),g([i.String(),h("design:type",i.String)],exports.User.prototype,"token",void 0),g([i.String(),h("design:type",i.String)],exports.User.prototype,"avatar",void 0),g([i.DateOnly(),h("design:type",i.String)],exports.User.prototype,"date",void 0),g([i.Text(),h("design:type",i.String)],exports.User.prototype,"description",void 0),g([i.Boolean(),h("design:type",i.Boolean)],exports.User.prototype,"state",void 0),g([i.CreatedAt,h("design:type",Date)],exports.User.prototype,"created_at",void 0),g([i.UpdatedAt,h("design:type",Date)],exports.User.prototype,"updated_at",void 0),g([i.DeletedAt,h("design:type",Object)],exports.User.prototype,"deleted_at",void 0),g([i.HasMany(()=>exports.Audit,"user_id"),h("design:type",Array)],exports.User.prototype,"audits",void 0),g([i.HasMany(()=>exports.Auth,"user_id"),h("design:type",Array)],exports.User.prototype,"auths",void 0),g([i.HasMany(()=>exports.Register,"user_id"),h("design:type",Array)],exports.User.prototype,"registers",void 0),g([i.HasMany(()=>exports.UserGroup,"user_id"),h("design:type",Array)],exports.User.prototype,"users_groups",void 0),g([i.HasMany(()=>exports.UserHistory,"user_id"),h("design:type",Array)],exports.User.prototype,"users_histories",void 0),exports.User=g([i.Database(C),i.ModelName("user"),i.DefaultScope({attributes:{exclude:["password","salt","token"]}}),i.Scopes({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),i.Hooks(I),S("4.2.0")],exports.User),exports.Audit=class extends P{},g([i.Id(),h("design:type",Number)],exports.Audit.prototype,"id",void 0),g([i.Enum("CREATE","DELETE","UPDATE"),h("design:type",i.String)],exports.Audit.prototype,"type",void 0),g([i.String(),h("design:type",i.String)],exports.Audit.prototype,"model",void 0),g([i.String(),h("design:type",i.String)],exports.Audit.prototype,"record",void 0),g([i.Json(),h("design:type",Object)],exports.Audit.prototype,"data",void 0),g([i.Json(),h("design:type",Object)],exports.Audit.prototype,"previously",void 0),g([i.String(),h("design:type",i.String)],exports.Audit.prototype,"client",void 0),g([i.Text(),h("design:type",i.String)],exports.Audit.prototype,"href",void 0),g([i.String(),h("design:type",i.String)],exports.Audit.prototype,"user_agent",void 0),g([i.Boolean(),h("design:type",i.Boolean)],exports.Audit.prototype,"state",void 0),g([i.CreatedAt,h("design:type",Date)],exports.Audit.prototype,"created_at",void 0),g([i.UpdatedAt,h("design:type",Date)],exports.Audit.prototype,"updated_at",void 0),g([i.DeletedAt,h("design:type",Object)],exports.Audit.prototype,"deleted_at",void 0),g([i.BelongsTo(()=>exports.User),h("design:type",Number)],exports.Audit.prototype,"user_id",void 0),exports.Audit=g([i.Database(C),i.ModelName("audit"),S("4.2.0")],exports.Audit),exports.Config=class extends P{static all(){return x(this,void 0,void 0,function*(){const e=yield this.findAll().catch(this.error),t={};return e&&e.forEach(e=>t[e.key]=e.value),t})}static del(e,t){return x(this,void 0,void 0,function*(){var r;const o=null!==(r=null==t?void 0:t.id)&&void 0!==r?r:null;return((yield this.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:o})).catch(this.error))||0)>0})}static get(e){return x(this,arguments,void 0,function*(e,t=""){const[r]=(yield this.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return r?r.value:t})}static set(e,t,r){return x(this,void 0,void 0,function*(){var o;const i=null!==(o=null==r?void 0:r.id)&&void 0!==o?o:null,[s]=(yield this.findOrCreate(Object.assign({where:{key:e}},{user_id:i})).catch(this.error))||[];s&&(s.value=t,yield s.save().catch(this.error))})}},g([i.String(),h("design:type",i.String)],exports.Config.prototype,"key",void 0),g([i.String(),h("design:type",i.String)],exports.Config.prototype,"value",void 0),g([i.CreatedAt,h("design:type",Date)],exports.Config.prototype,"created_at",void 0),g([i.UpdatedAt,h("design:type",Date)],exports.Config.prototype,"updated_at",void 0),exports.Config=g([i.Database(C),i.ModelName("configs"),i.Hooks(I),S("4.2.0")],exports.Config),exports.Forgot=class extends P{},g([i.Id(),h("design:type",Number)],exports.Forgot.prototype,"id",void 0),g([i.String(),h("design:type",i.String)],exports.Forgot.prototype,"token",void 0),g([i.BigInt(),h("design:type",Number)],exports.Forgot.prototype,"timestamp",void 0),g([i.Boolean(),h("design:type",i.Boolean)],exports.Forgot.prototype,"state",void 0),g([i.CreatedAt,h("design:type",Date)],exports.Forgot.prototype,"created_at",void 0),g([i.UpdatedAt,h("design:type",Date)],exports.Forgot.prototype,"updated_at",void 0),g([i.DeletedAt,h("design:type",Object)],exports.Forgot.prototype,"deleted_at",void 0),g([i.BelongsTo(()=>exports.User),h("design:type",Number)],exports.Forgot.prototype,"user_id",void 0),exports.Forgot=g([i.Database(C),i.ModelName("forgot"),S("4.2.0")],exports.Forgot),exports.Permission=class extends P{},g([i.Id(),h("design:type",Number)],exports.Permission.prototype,"id",void 0),g([i.String(),h("design:type",i.String)],exports.Permission.prototype,"name",void 0),g([i.String(),i.Unique(!0),h("design:type",i.String)],exports.Permission.prototype,"route",void 0),g([i.String(),h("design:type",i.String)],exports.Permission.prototype,"tag",void 0),g([i.Text(),h("design:type",i.String)],exports.Permission.prototype,"description",void 0),g([i.Boolean(),h("design:type",i.Boolean)],exports.Permission.prototype,"state",void 0),g([i.CreatedAt,h("design:type",Date)],exports.Permission.prototype,"created_at",void 0),g([i.UpdatedAt,h("design:type",Date)],exports.Permission.prototype,"updated_at",void 0),g([i.DeletedAt,h("design:type",Object)],exports.Permission.prototype,"deleted_at",void 0),g([i.HasMany(()=>exports.GroupPermission,"permission_id"),h("design:type",Array)],exports.Permission.prototype,"groups_permissions",void 0),exports.Permission=g([i.Database(C),i.ModelName("permission"),i.Hooks(I),S("4.3.1")],exports.Permission),exports.GroupPermission=class extends P{},g([i.CreatedAt,h("design:type",Date)],exports.GroupPermission.prototype,"created_at",void 0),g([i.BelongsTo(()=>exports.Group),h("design:type",Number)],exports.GroupPermission.prototype,"group_id",void 0),g([i.BelongsTo(()=>exports.Permission),h("design:type",Number)],exports.GroupPermission.prototype,"permission_id",void 0),exports.GroupPermission=g([i.Database(C),i.ModelName("groups_permissions"),i.Hooks(I),S("4.2.0")],exports.GroupPermission),exports.Log=f=class extends P{static write(t,r,o){return x(this,void 0,void 0,function*(){yield this.writeRaw(e.LogColor.White,"",t,r,o)})}static error(t,r,o){return x(this,void 0,void 0,function*(){yield this.writeRaw(e.LogColor.Red,"error",t,r,o)})}static info(t,r,o){return x(this,void 0,void 0,function*(){yield this.writeRaw(e.LogColor.Cyan,"info",t,r,o)})}static success(t,r,o){return x(this,void 0,void 0,function*(){yield this.writeRaw(e.LogColor.Green,"success",t,r,o)})}static warning(t,r,o){return x(this,void 0,void 0,function*(){yield this.writeRaw(e.LogColor.Yellow,"warning",t,r,o)})}static writeRaw(t,r,o,i,s){return x(this,void 0,void 0,function*(){s&&e.Log.console(t,r,o),C&&(yield f.create({type:r,source:i,message:o}).catch(this.error))})}},g([i.Id(),h("design:type",Number)],exports.Log.prototype,"id",void 0),g([i.String(),h("design:type",i.String)],exports.Log.prototype,"type",void 0),g([i.String(),h("design:type",i.String)],exports.Log.prototype,"source",void 0),g([i.Text(),h("design:type",i.String)],exports.Log.prototype,"message",void 0),g([i.CreatedAt,h("design:type",Date)],exports.Log.prototype,"created_at",void 0),exports.Log=f=g([i.Database(C),i.ModelName("log"),S("4.2.0")],exports.Log),exports.Migration=class extends P{},g([i.String(),h("design:type",i.String)],exports.Migration.prototype,"model",void 0),g([i.String(),h("design:type",i.String)],exports.Migration.prototype,"version",void 0),g([i.CreatedAt,h("design:type",Date)],exports.Migration.prototype,"created_at",void 0),g([i.UpdatedAt,h("design:type",Date)],exports.Migration.prototype,"updated_at",void 0),exports.Migration=g([i.Database(C),i.ModelName("migration"),S("4.2.0")],exports.Migration),exports.Session=class extends P{},g([i.String(),h("design:type",i.String)],exports.Session.prototype,"session",void 0),g([i.Text(),h("design:type",i.String)],exports.Session.prototype,"json",void 0),g([i.BigInt(),h("design:type",Number)],exports.Session.prototype,"expired",void 0),g([i.CreatedAt,h("design:type",Date)],exports.Session.prototype,"created_at",void 0),g([i.UpdatedAt,h("design:type",Date)],exports.Session.prototype,"updated_at",void 0),exports.Session=g([i.Database(C),i.ModelName("session"),S("4.2.0")],exports.Session);class R{static error(e){let t="token";u.API_BASE_NAME&&(t=`${u.API_BASE_NAME}.${t}`),exports.Log.error(e.message,t,u.API_CONSOLE_ERROR)}}class T extends R{static user(e,t){return x(this,void 0,void 0,function*(){if(!e)return{error:"INVALID TOKEN"};const r=t.hash.encrypt(e),o=yield exports.User.findOne({where:{token:r,state:!0}}).catch(this.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(this.error))||[];if(r)return r.logout&&(r.logout=null,yield r.save().catch(this.error)),{auth:r,user:o}}return{error:"ACCESS DENIED"}})}}const D=e=>n.existsSync(e)?n.readFileSync(e):void 0,w={http:D(u.API_HTTP_CRT),token:D(u.API_TOKEN_CRT)},N={http:D(u.API_HTTP_KEY),token:D(u.API_TOKEN_KEY)};class U extends R{static options(){return{algorithm:"RS256",expiresIn:`${u.API_TOKEN_LIFETIME}ms`}}static create(e){return x(this,void 0,void 0,function*(){if(!N.token)return{error:"KEY NOT FOUND"};const{id:t}=e,o=r.uuidv4(),i=yield exports.Auth.create({secret:o,user_id:t}).catch(this.error);if(!i)return{error:"INTERNAL SERVER ERROR"};return{auth:i,token:s.sign({id:t,secret:o},N.token,this.options())}})}static destroy(e){return x(this,void 0,void 0,function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)})}static renew(e){return x(this,void 0,void 0,function*(){if(!N.token)return{error:"KEY NOT FOUND"};const{error:t,decode:o}=this.verify(e,u.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(o){const{id:e,secret:t}=o;if(e&&t){const o=yield exports.User.findOne({where:{id:e,state:!0}}).catch(this.error);if(o){const i=yield exports.Auth.findOne({where:{secret:t,user_id:o.id}}).catch(this.error);if(i&&!i.logout){i.secret=r.uuidv4(),yield i.save().catch(this.error);return{auth:i,token:s.sign({id:e,secret:i.secret},N.token,this.options())}}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static user(e){return x(this,void 0,void 0,function*(){const{error:t,decode:r}=this.verify(e);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(this.error);if(r){const e=yield exports.Auth.findOne({where:{secret:t,user_id:r.id}}).catch(this.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static verify(e,t){if(!w.token)return{error:"CERT NOT FOUND"};if(!e||e.split(".").length<3)return{error:"INVALID TOKEN"};try{return{decode:s.verify(e,w.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class b extends a.Store{constructor(){super(),this.all=e=>x(this,void 0,void 0,function*(){e=e||r.noop;const t=yield exports.Session.findAll({attributes:["session"],where:{expired:{[p.Op.gte]:Date.now()}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.session)),e()}),this.clear=e=>x(this,void 0,void 0,function*(){yield exports.Session.destroy().catch(r.noop),e&&e()}),this.destroy=(e,t)=>x(this,void 0,void 0,function*(){yield exports.Session.destroy({where:{session:e}}).catch(r.noop),t&&t()}),this.expired=()=>x(this,void 0,void 0,function*(){yield exports.Session.destroy({where:{expired:{[p.Op.lt]:Date.now()}}}).catch(r.noop)}),this.get=(e,t)=>x(this,void 0,void 0,function*(){t=t||r.noop;const o=yield exports.Session.findOne({where:{session:e,expired:{[p.Op.gte]:Date.now()}}}).catch(e=>(t(e),null));if(o){const e=JSON.parse(o.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield o.destroy().catch(r.noop),void t(null)}return void t(null,e)}t(null)}),this.length=e=>x(this,void 0,void 0,function*(){e&&e(null,(yield exports.Session.count().catch(r.noop))||0)}),this.set=(e,t,o)=>x(this,void 0,void 0,function*(){o=o||r.noop;const i=Date.now()+u.API_SESSION_LIFETIME,s=JSON.stringify(t),[n,d]=(yield exports.Session.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:i}}).catch(r.noop))||[];n&&(d||(n.json=s,n.expired=i,yield n.save().catch(r.noop))),o()}),this.loop=r.loop(this.expired,3e4),this.loop.start()}}class M extends o.Application{constructor(t){super(t,{cert:w.http,cross:u.API_HTTP_CROSS,hybrid:u.API_HTTP_HYBRID,json:{strict:u.API_BODYPARSER_STRICT,inflate:u.API_BODYPARSER_INFLATE,limit:u.API_BODYPARSER_LIMIT,type:u.API_BODYPARSER_TYPE},key:N.http,notfound:u.API_HTTP_NOTFOUND,path:u.API_HTTP_PATH,port:u.API_HTTP_PORT,public:u.API_HTTP_PUBLIC,redirect:u.API_HTTP_REDIRECT,session:{store:new b,name:u.API_SESSION_NAME,secret:u.API_SESSION_SECRET,cookie:{maxAge:u.API_SESSION_LIFETIME},genid:r.uuidv4}}),this.hash=new e.Hash(u.API_KEY_HASH)}error(e,t){u.API_BASE_NAME&&(t=t?`${u.API_BASE_NAME}.${t}`:u.API_BASE_NAME),exports.Log.error(e.message,t,u.API_CONSOLE_ERROR)}log(e,t){u.API_BASE_NAME&&(t=t?`${u.API_BASE_NAME}.${t}`:u.API_BASE_NAME),exports.Log.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return x(this,void 0,void 0,function*(){yield C.sync(),yield this.migrations(C),yield r.forEachSeries(this.controllers,e=>x(this,void 0,void 0,function*(){r.isFunction(e.sync)&&(yield e.sync(this))})),yield e.listen.call(this),u.API_WEBSOCKET_START&&this.server&&(this._webSocket=new d.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(u.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>x(this,void 0,void 0,function*(){t.url||(t.url="");const o=t.url.length<=1?"":t.url.replace(/\//g,".");let i;e.on("message",r=>x(this,void 0,void 0,function*(){if(i)try{const s=JSON.parse(r);this.emit("ws.message"+o,{data:s,message:r,req:t,user:i,ws:e})}catch(s){this.emit("ws.message"+o,{erro:s,message:r,req:t,user:i,ws:e})}else{const{user:s}=yield U.user(r.toString());s&&(i=s,this.emit("ws.connection"+o,{req:t,user:i,ws:e}))}i||e.close()})),e.on("close",()=>{i&&this.emit("ws.close"+o,{user:i,ws:e})}),yield r.sleep(2e3),i||e.close()})))})}migrations(e){return x(this,void 0,void 0,function*(){const t=[];yield r.forEachSeries(Object.keys(e.models),r=>x(this,void 0,void 0,function*(){var o;const i=e.models[r],{version:s}=E.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),t.push(i))})),t.length&&(yield i.migrate(e,t))})}websocket(){return this._webSocket}}var F,B,L,k,j;class H extends c{constructor(){super(...arguments),this[F]=[]}auth(e,t,r,o,i,s){return x(this,void 0,void 0,function*(){var n;t=null!=t?t:o;const[d,a]=null!==(n=null==r?void 0:r.split(" "))&&void 0!==n?n:["",""];if(!(t||a&&d.toLowerCase()==u.API_TOKEN_HEADER_KEY))return e.error("INVALID TOKEN");const{auth:p,error:l,user:c}=yield t?T.user(t,s):U.user(a);return l?e.error(l):p&&c?!t&&p.user_agent&&p.user_agent!=i?e.error("INVALID TOKEN"):(e.req.auth=p,e.req.user=c,void e.next()):e.error("INTERNAL SERVER ERROR")})}canCreate(e,t,r){return x(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".create",r)})}canDelete(e,t,r){return x(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".delete",r)})}canRead(e,t,r){return x(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".read",r)})}canUpdate(e,t,r){return x(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".update",r)})}error(e){let t="controller_base";u.API_BASE_NAME&&(t=`${u.API_BASE_NAME}.${t}`),exports.Log.error(e.message,t,u.API_CONSOLE_ERROR)}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}permission(e,t,r){return x(this,void 0,void 0,function*(){if(r){if((yield this.permissions(r,{route:t})).length>0)return e.next()}e.unauthorized("ACCESS DENIED")})}permissions(e,t){return x(this,void 0,void 0,function*(){var r;return null!==(r=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))&&void 0!==r?r:[]})}session(e,t,o){return x(this,void 0,void 0,function*(){o.auth&&o.user&&(o.user_agent?o.user_agent!=t&&o.regenerate(r.noop):(o.user_agent=t,o.save(r.noop))),e.next()})}sync(){return x(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield r.forEachSeries(this[c.PERMISSIONS],o=>x(this,void 0,void 0,function*(){const i=`${e}.${o}`,s=r.upperCamelCase(e.replace(/_/g," ")," ");yield exports.Permission.findOrCreate({where:{route:i},defaults:Object.assign({name:`${s} ${r.upperCamelCase(o," ")}`,route:i,tag:s},t)})}))})}upload(e,t){t.path||(t.path=u.API_UPLOAD_TEMP),t.size||(t.size=u.API_UPLOAD_SIZE),t.field||(t.field=u.API_UPLOAD_FIELD),o.Upload.middleware(e,t)}validation(e,t){return x(this,void 0,void 0,function*(){const{error:o,value:i}=yield r.Validation.object(t).parse().validateAsync(e.req.body);if(o)return e.validation(o);e.req.body=i,e.next()})}}F=c.PERMISSIONS,g([y(0,o.Ctx()),y(1,o.Headers(u.API_KEY_HEADER)),y(2,o.Headers(u.API_TOKEN_HEADER)),y(3,o.Query(u.API_KEY_HEADER)),y(4,o.Headers("user-agent")),y(5,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,String,String,String,String,M]),h("design:returntype",Promise)],H.prototype,"auth",null),g([y(0,o.Ctx()),y(1,o.Argument()),y(2,_()),h("design:type",Function),h("design:paramtypes",[o.Context,String,exports.User]),h("design:returntype",Promise)],H.prototype,"canCreate",null),g([y(0,o.Ctx()),y(1,o.Argument()),y(2,_()),h("design:type",Function),h("design:paramtypes",[o.Context,String,exports.User]),h("design:returntype",Promise)],H.prototype,"canDelete",null),g([y(0,o.Ctx()),y(1,o.Argument()),y(2,_()),h("design:type",Function),h("design:paramtypes",[o.Context,String,exports.User]),h("design:returntype",Promise)],H.prototype,"canRead",null),g([y(0,o.Ctx()),y(1,o.Argument()),y(2,_()),h("design:type",Function),h("design:paramtypes",[o.Context,String,exports.User]),h("design:returntype",Promise)],H.prototype,"canUpdate",null),g([y(0,o.Ctx()),y(1,o.Argument()),y(2,_()),h("design:type",Function),h("design:paramtypes",[o.Context,String,exports.User]),h("design:returntype",Promise)],H.prototype,"permission",null),g([y(0,o.Ctx()),y(1,o.Headers("user-agent")),y(2,o.Session()),h("design:type",Function),h("design:paramtypes",[o.Context,String,Object]),h("design:returntype",Promise)],H.prototype,"session",null),g([y(0,o.Ctx()),y(1,o.Argument()),h("design:type",Function),h("design:paramtypes",[o.Context,Object]),h("design:returntype",void 0)],H.prototype,"upload",null),g([y(0,o.Ctx()),y(1,o.Argument()),h("design:type",Function),h("design:paramtypes",[o.Context,Object]),h("design:returntype",Promise)],H.prototype,"validation",null),exports.ControllerModel=class extends H{constructor(){super(...arguments),this[B]=[],this[L]=["create","read","update","delete"]}attributes(e){if(0==this[H.ATTRIBUTES].length&&(this[H.ATTRIBUTES]=Object.keys(this.model().getAttributes())),r.isArray(e))return e.length?e.map(e=>r.isString(e)&&-1!=this[H.ATTRIBUTES].indexOf(e)?e:void 0).filter(r.isString):this[H.ATTRIBUTES];const{exclude:t,include:o}=e,i=r.isUndefined(o)?this[H.ATTRIBUTES]:o.map(e=>r.isString(e)&&-1!=this[H.ATTRIBUTES].indexOf(e)?e:void 0).filter(r.isString),s=null!=t?t:[];return s.length?i.filter(e=>-1==s.indexOf(e)?e:void 0).filter(r.isString):i}create(e){return x(this,arguments,void 0,function*({ctx:e,options:t,body:r}){const i=yield this.model().create(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign({},t||{}),m(e))).catch(this.error);if(i){const t=this.key();return e.prepare(o.Status.OK,{[t]:i.getDataValue(t)}),i}e.error("INTERNAL SERVER ERROR")})}delete(e){return x(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}),m(e))).catch(this.error);return i?(e.success("OK"),i):(e.notFound("RECORD NOT FOUND"),0)})}error(e){let t="controller_model";u.API_BASE_NAME&&(t=`${u.API_BASE_NAME}.${t}`),(null==e?void 0:e.sql)?exports.Log.error((null==e?void 0:e.message)+"\n"+(null==e?void 0:e.sql),t,u.API_CONSOLE_ERROR):super.error(e)}findAll(e){return x(this,arguments,void 0,function*({ctx:e,options:t,callback:s,scope:n,advanced:d,attributes:a,unlimited:l}){var c,g,y;const h=this.scope(n),x=Object.assign({},t||{}),{limit:m,offset:v,asc:A,desc:_,search:S,where:E}=e.req.query;if(r.isUndefined(x.limit)){const e=r.clamp(r.isString(m)?parseInt(m)||0:u.API_MODEL_LIMIT,-1,u.API_MODEL_LIMIT_MAX);x.limit=e>0?e:l?void 0:u.API_MODEL_LIMIT}if(r.isNumber(x.limit)&&(x.limit=x.limit>0?x.limit:void 0),r.isString(v)){const e=v&&parseInt(v)||0;x.offset=e>0?e:void 0}a=null!=a?a:this.attributes(null!==(c=null==x?void 0:x.attributes)&&void 0!==c?c:[]);const P=[],C=e=>a.indexOf(e)>=0;if(r.isString(A)&&A.length&&P.push(...A.split(";").filter(C).map(e=>[e,"ASC"])),r.isString(_)&&_.length&&P.push(..._.split(";").filter(C).map(e=>[e,"DESC"])),P.length&&(x.order=P),x.where=Object.assign({},x.where||{}),r.isString(E)&&(null==d||d)){const t=i.Where.parse(a,E);if(!r.isUndefined(t.error))return e.validation(t.error.join(", ")),{count:0,records:[]};x.where=Object.assign(Object.assign({},x.where),null!==(g=t.value)&&void 0!==g?g:{})}else{const e=[];a.forEach(t=>{r.isString(S)&&S.length&&e.push({[t]:{[p.Op.like]:`%${S}%`}})}),e.length&&(x.where=Object.assign(Object.assign({},x.where),{[p.Op.or]:[...e]}))}const O=h.count(Object.assign(Object.assign({},x),{distinct:!!x.include,col:this[H.ATTRIBUTES].length?this[H.ATTRIBUTES][0]:void 0})).catch(this.error),I=h.findAll(x).catch(this.error);yield Promise.allSettled([O,I]);const f=null!==(y=yield O)&&void 0!==y?y:0;let R=yield I;const T={count:f};return R?(R=s?yield s(R):R,(r.isNumber(null==t?void 0:t.limit)||0==f)&&(T.count=R.length),e.prepare(o.Status.OK,Object.assign(Object.assign({},T),{records:R})),Object.assign(Object.assign({},T),{records:R})):(e.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},T),{records:[]}))})}findOne(e){return x(this,arguments,void 0,function*({ctx:e,options:t,callback:r,scope:i}){const s=this.key(),{[s]:n}=e.req.params,d=yield this.scope(i).findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[s]:n})})).catch(this.error);return d?(e.prepare(o.Status.OK,r?yield r(d):d.toJSON()),d):null===d?e.notFound("RECORD NOT FOUND"):void e.error("INTERNAL SERVER ERROR")})}sync(){return x(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield r.forEachSeries(this[H.PERMISSIONS],o=>x(this,void 0,void 0,function*(){const i=`${e}.${o}`,s=r.upperCamelCase(e.replace(/_/g," ")," ");yield exports.Permission.findOrCreate({where:{route:i},defaults:Object.assign({name:`${s} ${r.upperCamelCase(o," ")}`,route:i,tag:s},t)})}))})}update(e){return x(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}),m(e))).catch(this.error))&&void 0!==o?o:[];return n?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)})}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}},B=H.ATTRIBUTES,L=H.PERMISSIONS,exports.ControllerModel=g([o.Extends(H)],exports.ControllerModel),exports.ControllerCrud=class extends exports.ControllerModel{constructor(){super(...arguments),this._crud={}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return x(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return x(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}del(e){return x(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return x(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return x(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return x(this,void 0,void 0,function*(){const t=this.CrudValidationCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}validationUpdate(e){return x(this,void 0,void 0,function*(){const t=this.CrudValidationUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}},g([o.Post(),o.Middleware("auth"),o.Middleware("canCreate"),o.Middleware("validationCreate"),y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.ControllerCrud.prototype,"add",null),g([o.Get(),o.Middleware("auth"),o.Middleware("canRead"),y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.ControllerCrud.prototype,"all",null),g([o.Delete("/:id"),o.Middleware("auth"),o.Middleware("canDelete"),y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.ControllerCrud.prototype,"del",null),g([o.Get("/:id"),o.Middleware("auth"),o.Middleware("canRead"),y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.ControllerCrud.prototype,"get",null),g([o.Put("/:id"),o.Middleware("auth"),o.Middleware("canUpdate"),o.Middleware("validationUpdate"),y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.ControllerCrud.prototype,"set",null),g([y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.ControllerCrud.prototype,"validationCreate",null),g([y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.ControllerCrud.prototype,"validationUpdate",null),exports.ControllerCrud=g([o.Extends(exports.ControllerModel)],exports.ControllerCrud),exports.AuditsController=class extends exports.ControllerModel{model(){return exports.Audit}all(e,t,r){return x(this,void 0,void 0,function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:o,order:[["created_at","DESC"]]},unlimited:!0})})}get(e){return x(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}},g([o.Get(),o.Middleware("auth"),o.Middleware("canRead"),y(0,o.Ctx()),y(1,o.Query("type")),y(2,o.Query("table")),h("design:type",Function),h("design:paramtypes",[o.Context,String,String]),h("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),g([o.Get("/:id"),o.Middleware("auth"),o.Middleware("canRead"),y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=g([o.Controller("/audits"),o.Extends(exports.ControllerModel)],exports.AuditsController),exports.AuthController=class extends H{login(t,o,i,s,n){return x(this,void 0,void 0,function*(){var d;yield r.sleep(u.API_SLEEP_AUTH);const a=yield exports.User.scope("password").findOne({where:{[p.Op.or]:[{email:i},{username:i}]}}).catch(this.error);if(s+=null!==(d=null==a?void 0:a.salt)&&void 0!==d?d:"",!a||a.password!=e.sha256(s))return t.notFound("INVALID USERNAME OR PASSWORD"),n.emit("auth.failure",{ctx:t}),void this.emit("auth.failure",{ctx:t});const l=yield exports.Register.findOne({where:{state:!0,user_id:a.id}}).catch(this.error);if(l)return t.error("ACTIVATION REQUIRED"),n.emit("auth.activation",{ctx:t,register:l,user:a}),void this.emit("auth.activation",{ctx:t,register:l,user:a});if(!a.state)return t.notFound("INVALID USERNAME OR PASSWORD"),n.emit("auth.failure",{ctx:t,user:a}),void this.emit("auth.failure",{ctx:t,user:a});const{auth:c,error:g,token:y}=yield U.create(a);return g?(t.error(g),n.emit("auth.failure",{ctx:t}),void this.emit("auth.failure",{ctx:t})):c&&y?(c.user_agent=o,yield c.save().catch(this.error),t.json({token:y}),n.emit("auth.login",{auth:c,ctx:t,user:a}),void this.emit("auth.login",{auth:c,ctx:t,user:a})):(t.error("INTERNAL SERVER ERROR"),n.emit("auth.failure",{ctx:t}),void this.emit("auth.failure",{ctx:t}))})}logout(e,t,r,o){return x(this,void 0,void 0,function*(){if(yield U.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 x(this,void 0,void 0,function*(){const{auth:i,error:s,token:n}=yield U.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 x(this,void 0,void 0,function*(){const o=yield this.permissions(t);if(!o)return e.error("INTERNAL SERVER ERROR");e.json(Object.assign(Object.assign({},r.denied(["username","date","description","state","created_at","updated_at","deleted_at"],t.toJSON())),{permissions:o.map(e=>e.route)}))})}},g([o.Post("/login"),o.Middleware("validation",{username:r.Validation.string().min(3).required(),password:r.Validation.string().min(5).required()}),y(0,o.Ctx()),y(1,o.Headers("user-agent")),y(2,o.Body("username")),y(3,o.Body("password")),y(4,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,String,String,String,M]),h("design:returntype",Promise)],exports.AuthController.prototype,"login",null),g([o.Get("/logout"),o.Middleware("auth"),y(0,o.Ctx()),y(1,A()),y(2,_()),y(3,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,exports.Auth,exports.User,M]),h("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),g([o.Post("/renew"),o.Middleware("validation",{token:r.Validation.string().required()}),y(0,o.Ctx()),y(1,o.Headers("user-agent")),y(2,o.Body("token")),y(3,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,String,String,M]),h("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),g([o.Get(),o.Middleware("auth"),y(0,o.Ctx()),y(1,_()),h("design:type",Function),h("design:paramtypes",[o.Context,exports.User]),h("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=g([o.Controller("/auth"),o.Extends(H)],exports.AuthController),exports.FilesController=class extends H{constructor(){super(...arguments),this[k]=["delete","download","edit","list","read","rename","upload","write"]}directory(){return u.API_HTTP_PUBLIC||"./"}files(e){return x(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const o=l.join(this.directory(),t);if(!n.existsSync(o)||!n.statSync(o).isDirectory())return e.notFound("RECORD NOT FOUND");let i=[];return i=n.readdirSync(o),i=i.map(e=>this.info(l.join(o,e))),i=i.filter(r.isDef),Object.assign(Object.assign({},this.info(o)),{files:i})})}access(e,t,r){return x(this,void 0,void 0,function*(){yield this.permission(e,this.name()+"."+t,r)})}info(e){if(!n.existsSync(e))return null;const t=n.statSync(e),r=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const o=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:o?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:o,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return x(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=r.upperCamelCase(e.replace(/_/g," ")," "),o={description:"",state:!0};yield r.forEachSeries(this[H.PERMISSIONS],i=>x(this,void 0,void 0,function*(){const s=`${e}.${i}`;yield exports.Permission.findOrCreate({where:{route:s},defaults:Object.assign({name:`${t} ${r.upperCamelCase(i," ")}`,route:s,tag:t},o)})}))})}},k=H.PERMISSIONS,g([o.Get("/path"),o.Get("/path/*path"),o.Middleware("auth"),o.Middleware("access","list"),y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.FilesController.prototype,"files",null),g([y(0,o.Ctx()),y(1,o.Argument()),y(2,_()),h("design:type",Function),h("design:paramtypes",[o.Context,String,exports.User]),h("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=g([o.Controller("/files"),o.Extends(H)],exports.FilesController),exports.ForgotController=class extends H{check(e,t){return x(this,void 0,void 0,function*(){const o=yield this.find(t);if(!o||!o.user)return e.notFound("RECORD NOT FOUND");o.token=r.uniqueID(),yield o.save(),e.json({token:o.token})})}forgot(e,t,o){return x(this,void 0,void 0,function*(){yield r.sleep(u.API_SLEEP_FORGOT);const i=t,s=yield exports.User.findOne({where:{[p.Op.or]:[{email:i},{username:t}]}}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");const n=r.uniqueID(),d=Date.now()+6e4*u.API_TOKEN_FORGOT,a=yield exports.Forgot.create({token:n,timestamp:d,state:!0,user_id:s.id});e.success("OK"),o.emit("forgot.send",{ctx:e,forgot:a,user:s}),this.emit("forgot.send",{ctx:e,forgot:a,user:s})})}reset(t,r,o,i){return x(this,void 0,void 0,function*(){const s=yield this.find(r);if(!s)return t.notFound("RECORD NOT FOUND");s.state=!1,yield s.save().catch(this.error),s.user.password=e.sha256(o),yield s.user.save().catch(this.error),t.success("OK"),i.emit("forgot.reset",{ctx:t,user:s.user}),this.emit("forgot.reset",{ctx:t,user:s.user})})}find(e){return x(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)})}},g([o.Get("/check"),o.Middleware("validation",{token:r.Validation.string().required()}),y(0,o.Ctx()),y(1,o.Body("token")),h("design:type",Function),h("design:paramtypes",[o.Context,String]),h("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),g([o.Post(),o.Middleware("validation",{username:r.Validation.string().min(4).required()}),y(0,o.Ctx()),y(1,o.Body("username")),y(2,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,String,M]),h("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),g([o.Post("/reset"),o.Middleware("validation",{token:r.Validation.string().required(),password:r.Validation.string().min(5).required()}),y(0,o.Ctx()),y(1,o.Body("token")),y(2,o.Body("password")),y(3,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,String,String,M]),h("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=g([o.Controller("/forgot"),o.Extends(H)],exports.ForgotController),exports.GroupsController=class extends exports.ControllerCrud{constructor(){super(...arguments),this.schemaCreate={name:r.Validation.string().required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()},this.schemaUpdate={name:r.Validation.string().empty(),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}}model(){return exports.Group}CrudArgumentsFindAll(e){return{ctx:e,unlimited:!0}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.GroupsController=g([o.Controller("/groups"),o.Extends(exports.ControllerCrud)],exports.GroupsController),exports.GroupsPermissionsController=class extends exports.ControllerModel{model(){return exports.GroupPermission}all(e,t){return x(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:exports.Permission,required:!0}]},unlimited:!0,callback:e=>e.map(e=>e.permission)})})}me(e,t){return x(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,o,i){return x(this,void 0,void 0,function*(){const s=yield exports.Group.findByPk(t,{attributes:["id"]}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");const n=s.id;if(yield exports.GroupPermission.destroy(Object.assign({where:{group_id:n},individualHooks:!0},i)),o){let e=0;yield r.sleep(1e3);for(let t=0;t<o.length;t++)e=yield exports.Permission.count({where:{id:o[t]}}),e&&(yield exports.GroupPermission.create({group_id:n,permission_id:o[t]},Object.assign({},i)))}e.success("OK")})}},g([o.Get("/:id/permissions"),o.Middleware("auth"),o.Middleware("canRead","groups"),y(0,o.Ctx()),y(1,o.Params("id")),h("design:type",Function),h("design:paramtypes",[o.Context,String]),h("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"all",null),g([o.Get("/permissions"),o.Middleware("auth"),o.Middleware("canRead","users"),y(0,o.Ctx()),y(1,_()),h("design:type",Function),h("design:paramtypes",[o.Context,exports.User]),h("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"me",null),g([o.Put("/:id/permissions"),o.Middleware("auth"),o.Middleware("canUpdate","groups"),o.Middleware("validation",{permissions:r.Validation.array(r.Validation.number().parse())}),y(0,o.Ctx()),y(1,o.Params("id")),y(2,o.Body("permissions")),y(3,v()),h("design:type",Function),h("design:paramtypes",[o.Context,String,Array,Object]),h("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"set",null),exports.GroupsPermissionsController=g([o.Controller("/groups"),o.Extends(exports.ControllerModel)],exports.GroupsPermissionsController),exports.LogsController=class extends exports.ControllerModel{constructor(){super(...arguments),this[j]=["read"]}model(){return exports.Log}all(e,t,r){return x(this,void 0,void 0,function*(){const o={};t&&(o.type=t),r&&(o.source=r),yield this.findAll({ctx:e,options:{where:o,order:[["created_at","DESC"]]},unlimited:!0})})}},j=exports.ControllerModel.PERMISSIONS,g([o.Get(),o.Middleware("auth"),o.Middleware("canRead"),y(0,o.Ctx()),y(1,o.Query("type")),y(2,o.Query("source")),h("design:type",Function),h("design:paramtypes",[o.Context,String,String]),h("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=g([o.Controller("/logs"),o.Extends(exports.ControllerModel)],exports.LogsController),exports.PermissionsController=class extends exports.ControllerCrud{constructor(){super(...arguments),this.schemaCreate={name:r.Validation.string().required(),route:r.Validation.string().required(),tag:r.Validation.string().required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()},this.schemaUpdate={name:r.Validation.string().empty(),route:r.Validation.string().empty(),tag:r.Validation.string().empty(),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}}model(){return exports.Permission}CrudArgumentsFindAll(e){return{ctx:e,unlimited:!0}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.PermissionsController=g([o.Controller("/permissions"),o.Extends(exports.ControllerCrud)],exports.PermissionsController),exports.RegisterController=class extends H{register(t,o,i){return x(this,void 0,void 0,function*(){yield r.sleep(u.API_SLEEP_REGISTRY);const{name:s,date:n,email:d,username:a,password:l,confirm:c}=o,g=a||d,y=e.sha256(l);if(yield exports.User.count({where:{[p.Op.or]:[{email:d},{username:g}]}}).catch(this.error))return t.validation("INVALID EMAIL OR USERNAME");if(y!=e.sha256(c))return t.error("INVALID PASSWORD");const h=yield exports.User.create({name:s,email:d,username:g,password:y,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!h)return t.error("INTERNAL SERVER ERROR");const x=yield exports.Register.create({token:yield this.getId(),user_id:h.id,state:!0}).catch(this.error);if(!x)return yield h.destroy().catch(this.error),t.error("INTERNAL SERVER ERROR");t.success("OK"),i.emit("register.user",{ctx:t,register:x,user:h}),this.emit("register.user",{ctx:t,register:x,user:h})})}confirm(e,t,r){return x(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 x(this,void 0,void 0,function*(){const o=t,i=yield exports.Register.findOne({where:{state:!0},include:[{model:exports.User,required:!0,where:{[p.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 x(this,void 0,void 0,function*(){const e=r.uuidv4();return(yield exports.Register.count({where:{token:e}}))?this.getId():e})}},g([o.Post(),o.Middleware("validation",{name:r.Validation.string().required(),date:r.Validation.date().required(),email:r.Validation.string().email().required(),username:r.Validation.string().min(4).empty(),password:r.Validation.string().min(5).required(),confirm:r.Validation.string().min(5).required()}),y(0,o.Ctx()),y(1,o.Body()),y(2,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,Object,M]),h("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),g([o.Post("/confirm"),o.Middleware("validation",{token:r.Validation.string().required()}),y(0,o.Ctx()),y(1,o.Body("token")),y(2,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,String,M]),h("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),g([o.Post("/send"),o.Middleware("validation",{username:r.Validation.string().min(4).required()}),y(0,o.Ctx()),y(1,o.Body("username")),y(2,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,String,M]),h("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=g([o.Controller("/register"),o.Extends(H)],exports.RegisterController),exports.SetupController=class extends H{setup(t,o){return x(this,void 0,void 0,function*(){var i;if(yield exports.User.count())return t.success("OK");const s=r.uniqueID(),n=yield exports.User.create({name:"Admin",email:"admin@localhost",username:"admin",password:e.sha256("admin"+s),salt:s,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},o)),d=yield exports.Group.create(Object.assign({name:"Admin"},{description:"API CORE",state:!0}),Object.assign({},o));yield exports.UserGroup.create({user_id:n.id,group_id:d.id},Object.assign({},o));const a=null!==(i=yield exports.Permission.findAll({where:{state:!0}}).catch(this.error))&&void 0!==i?i:[];yield r.forEachSeries(a,e=>x(this,void 0,void 0,function*(){yield exports.GroupPermission.create({group_id:d.id,permission_id:e.id},Object.assign({},o))})),t.success("OK")})}},g([o.Get(),y(0,o.Ctx()),y(1,v()),h("design:type",Function),h("design:paramtypes",[o.Context,Object]),h("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=g([o.Controller("/setup"),o.Extends(H)],exports.SetupController),exports.UsersController=class extends exports.ControllerModel{model(){return exports.User}constructor(){super(),this.path=u.API_HTTP_PUBLIC+"/avatar",u.API_HTTP_PUBLIC&&n.existsSync(u.API_HTTP_PUBLIC)&&!n.existsSync(this.path)&&n.mkdirSync(this.path)}avatar(e,t,r,o){return x(this,void 0,void 0,function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.path+"/"+r.avatar;if(n.existsSync(t)&&n.lstatSync(t).isFile()&&n.rmSync(t),r.avatar=i,yield r.save(Object.assign({},o)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")})}avatar_del(e,t,r){return x(this,void 0,void 0,function*(){const o=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},r)).catch(this.error))&&n.existsSync(o)&&n.rmSync(o),e.success("OK")})}password(t,o,i,s,n){return x(this,void 0,void 0,function*(){var d;if(u.API_USER_HISTORY){if(yield exports.UserHistory.count({where:{password:e.sha256(i+s.id)}}).catch(this.error))return t.error("PASSWORD PREVIOUSLY REGISTERED")}const a=yield this.scope("password").findOne({where:{id:s.id,state:!0}}).catch(this.error);return o+=null!==(d=null==a?void 0:a.salt)&&void 0!==d?d:"",a&&a.password==e.sha256(o)?(a.salt=r.uniqueID(),a.password=e.sha256(i+a.salt),(yield a.save(Object.assign({},n)).catch(this.error))?t.success("OK"):void t.success("RECORD NOT CHANGED")):t.error("INVALID PASSWORD")})}token(e,t,r){return x(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_del(e,t,r){return x(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_get(e,t,r){return x(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_renew(e,t,r,o){return x(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 x(this,void 0,void 0,function*(){var e;const t=r.uuidv4();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(t,o){return x(this,void 0,void 0,function*(){const i=r.uniqueID(),s=yield this.create({ctx:t,body:{password:e.sha256(o+i),salt:i}});u.API_USER_HISTORY&&s&&(yield exports.UserHistory.create({password:e.sha256(o+s.id),user_id:s.id}))})}all(e){return x(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{attributes:{exclude:["password","salt","token"]}},unlimited:!0})})}del(e,t,r){return x(this,void 0,void 0,function*(){if(r.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this.delete({ctx:e})})}get(e){return x(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(t,o,i){return x(this,void 0,void 0,function*(){if(u.API_USER_HISTORY&&i){const r=e.sha256(i+o);if(yield exports.UserHistory.count({where:{password:r}}).catch(this.error))return t.error("PASSWORD PREVIOUSLY REGISTERED");yield exports.UserHistory.create({password:r,user_id:o}).catch(this.error)}const s=i?r.uniqueID():"";yield this.update({ctx:t,body:i?{password:e.sha256(i+s),salt:s}:{}})})}},g([o.Post("/avatar"),o.Middleware("auth"),o.Middleware("upload",e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32})),y(0,o.Ctx()),y(1,o.Files()),y(2,_()),y(3,v()),h("design:type",Function),h("design:paramtypes",[o.Context,Array,exports.User,Object]),h("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),g([o.Delete("/avatar"),o.Middleware("auth"),y(0,o.Ctx()),y(1,_()),y(2,v()),h("design:type",Function),h("design:paramtypes",[o.Context,exports.User,Object]),h("design:returntype",Promise)],exports.UsersController.prototype,"avatar_del",null),g([o.Post("/password"),o.Middleware("auth"),o.Middleware("validation",{oldPassword:r.Validation.string().min(5).required(),newPassword:r.Validation.string().min(5).required(),confirmPassword:r.Validation.string().equal(r.Validation.ref("newPassword"))}),y(0,o.Ctx()),y(1,o.Body("oldPassword")),y(2,o.Body("newPassword")),y(3,_()),y(4,v()),h("design:type",Function),h("design:paramtypes",[o.Context,String,String,exports.User,Object]),h("design:returntype",Promise)],exports.UsersController.prototype,"password",null),g([o.Get("/token"),o.Middleware("auth"),y(0,o.Ctx()),y(1,_()),y(2,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,exports.User,M]),h("design:returntype",Promise)],exports.UsersController.prototype,"token",null),g([o.Delete("/token/:id"),o.Middleware("auth"),o.Middleware("canDelete"),y(0,o.Ctx()),y(1,o.Params("id")),y(2,v()),h("design:type",Function),h("design:paramtypes",[o.Context,String,Object]),h("design:returntype",Promise)],exports.UsersController.prototype,"token_del",null),g([o.Get("/token/:id"),o.Middleware("auth"),o.Middleware("canCreate"),y(0,o.Ctx()),y(1,o.Params("id")),y(2,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,String,M]),h("design:returntype",Promise)],exports.UsersController.prototype,"token_get",null),g([o.Get("/token/renew/:id"),o.Middleware("auth"),o.Middleware("canUpdate"),y(0,o.Ctx()),y(1,o.Params("id")),y(2,v()),y(3,o.App()),h("design:type",Function),h("design:paramtypes",[o.Context,String,Object,M]),h("design:returntype",Promise)],exports.UsersController.prototype,"token_renew",null),g([o.Post(),o.Middleware("auth"),o.Middleware("canCreate"),o.Middleware("validation",{name:r.Validation.string().required(),email:r.Validation.string().email().required(),username:r.Validation.string().min(4).required(),password:r.Validation.string().min(5).required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()}),y(0,o.Ctx()),y(1,o.Body("password")),h("design:type",Function),h("design:paramtypes",[o.Context,String]),h("design:returntype",Promise)],exports.UsersController.prototype,"add",null),g([o.Get(),o.Middleware("auth"),o.Middleware("canRead"),y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"all",null),g([o.Delete("/:id"),o.Middleware("auth"),o.Middleware("canDelete"),y(0,o.Ctx()),y(1,o.Params("id")),y(2,_()),h("design:type",Function),h("design:paramtypes",[o.Context,String,exports.User]),h("design:returntype",Promise)],exports.UsersController.prototype,"del",null),g([o.Get("/:id"),o.Middleware("auth"),o.Middleware("canRead"),y(0,o.Ctx()),h("design:type",Function),h("design:paramtypes",[o.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"get",null),g([o.Put("/:id"),o.Middleware("auth"),o.Middleware("canUpdate"),o.Middleware("validation",{name:r.Validation.string().empty(),email:r.Validation.string().email().empty(),username:r.Validation.string().min(4).empty(),password:r.Validation.string().min(5).empty().filter(""),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}),y(0,o.Ctx()),y(1,o.Params("id")),y(2,o.Body("password")),h("design:type",Function),h("design:paramtypes",[o.Context,String,String]),h("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=g([o.Controller("/users"),o.Extends(exports.ControllerModel),h("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ControllerModel{model(){return exports.UserGroup}all(e,t){return x(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:exports.Group,required:!0}]},unlimited:!0,callback:e=>e.map(e=>e.group)})})}me(e,t){return x(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,o,i){return x(this,void 0,void 0,function*(){const s=yield exports.User.findByPk(t,{attributes:["id"]}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");if(yield exports.UserGroup.destroy(Object.assign({where:{user_id:s.id},individualHooks:!0},i)),o){let e=0;yield r.sleep(1e3);for(let t=0;t<o.length;t++)e=yield exports.Group.count({where:{id:o[t]}}),e&&(yield exports.UserGroup.create({user_id:s.id,group_id:o[t]},Object.assign({},i)))}e.success("OK")})}},g([o.Get("/:id/groups"),o.Middleware("auth"),o.Middleware("canRead","users"),y(0,o.Ctx()),y(1,o.Params("id")),h("design:type",Function),h("design:paramtypes",[o.Context,String]),h("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),g([o.Get("/groups"),o.Middleware("auth"),o.Middleware("canRead","users"),y(0,o.Ctx()),y(1,_()),h("design:type",Function),h("design:paramtypes",[o.Context,exports.User]),h("design:returntype",Promise)],exports.UsersGroupsController.prototype,"me",null),g([o.Put("/:id/groups"),o.Middleware("auth"),o.Middleware("canUpdate","users"),o.Middleware("validation",{groups:r.Validation.array(r.Validation.number().parse())}),y(0,o.Ctx()),y(1,o.Params("id")),y(2,o.Body("groups")),y(3,v()),h("design:type",Function),h("design:paramtypes",[o.Context,String,Array,Object]),h("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=g([o.Controller("/users"),o.Extends(exports.ControllerModel)],exports.UsersGroupsController),exports.Application=M,exports.AuthBase=R,exports.AuthKey=T,exports.AuthToken=U,exports.Controller=c,exports.ControllerBase=H,exports.Env=u,exports.Metadata=E,exports.Migrate=S,exports.Model=P,exports.ReqAudit=v,exports.ReqAuth=A,exports.ReqUser=_,exports.Store=b,exports.audit=m,exports.crt=w,exports.database=C,exports.hooks=I,exports.key=N;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,25 +1,83 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v4.
|
|
2
|
+
* @andrewcaires/api v4.4.0
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2025 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
+
import { Env as Env$1, Hash } from '@andrewcaires/node';
|
|
8
|
+
import { EventEmitter, TypeObjectAny, TypeObjectString, TypeObject, ValidationBase, TypeCallbackFunction } from '@andrewcaires/utils.js';
|
|
7
9
|
import { Application as Application$1, Context, IStore, IUpload, IFile } from '@andrewcaires/express';
|
|
8
|
-
import { TypeObjectAny, EventEmitter, TypeObject, ValidationBase, TypeObjectString, TypeCallbackFunction } from '@andrewcaires/utils.js';
|
|
9
|
-
import { Model as Model$1, Connection } from '@andrewcaires/sequelize';
|
|
10
10
|
import { WhereOptions, Model as Model$2, CreateOptions, Attributes, FindOptions, UpdateOptions, FindAttributeOptions, ModelStatic } from 'sequelize';
|
|
11
|
-
import {
|
|
11
|
+
import { Model as Model$1, Connection } from '@andrewcaires/sequelize';
|
|
12
12
|
import { WebSocketServer } from 'ws';
|
|
13
13
|
import { Store as Store$1, SessionData } from 'express-session';
|
|
14
14
|
|
|
15
|
+
declare class Env extends Env$1 {
|
|
16
|
+
static readonly API_BASE_NAME: string;
|
|
17
|
+
static readonly API_BODYPARSER_STRICT: boolean;
|
|
18
|
+
static readonly API_BODYPARSER_INFLATE: boolean;
|
|
19
|
+
static readonly API_BODYPARSER_LIMIT: string;
|
|
20
|
+
static readonly API_BODYPARSER_TYPE: string;
|
|
21
|
+
static readonly API_CONSOLE_ERROR: boolean;
|
|
22
|
+
static readonly API_DB_DATABASE: string;
|
|
23
|
+
static readonly API_DB_HOST: string;
|
|
24
|
+
static readonly API_DB_PASSWORD: string;
|
|
25
|
+
static readonly API_DB_PORT: number;
|
|
26
|
+
static readonly API_DB_TYPE: string;
|
|
27
|
+
static readonly API_DB_USERNAME: string;
|
|
28
|
+
static readonly API_DB_LOG: boolean;
|
|
29
|
+
static readonly API_DB_AUDIT: boolean;
|
|
30
|
+
static readonly API_DB_PREFIX: string;
|
|
31
|
+
static readonly API_DB_TIMEZONE: string;
|
|
32
|
+
static readonly API_HTTP_CRT: string;
|
|
33
|
+
static readonly API_HTTP_KEY: string;
|
|
34
|
+
static readonly API_HTTP_PORT: number;
|
|
35
|
+
static readonly API_HTTP_PUBLIC: string;
|
|
36
|
+
static readonly API_HTTP_CROSS: boolean;
|
|
37
|
+
static readonly API_HTTP_HYBRID: boolean;
|
|
38
|
+
static readonly API_HTTP_NOTFOUND: string;
|
|
39
|
+
static readonly API_HTTP_PATH: string;
|
|
40
|
+
static readonly API_HTTP_REDIRECT: string;
|
|
41
|
+
static readonly API_KEY_HASH: string;
|
|
42
|
+
static readonly API_KEY_HEADER: string;
|
|
43
|
+
static readonly API_MODEL_LIMIT: number;
|
|
44
|
+
static readonly API_MODEL_LIMIT_MAX: number;
|
|
45
|
+
static readonly API_SLEEP_AUTH: number;
|
|
46
|
+
static readonly API_SLEEP_FORGOT: number;
|
|
47
|
+
static readonly API_SLEEP_REGISTRY: number;
|
|
48
|
+
static readonly API_SESSION_NAME: string;
|
|
49
|
+
static readonly API_SESSION_LIFETIME: number;
|
|
50
|
+
static readonly API_SESSION_SECRET: string;
|
|
51
|
+
static readonly API_TOKEN_CRT: string;
|
|
52
|
+
static readonly API_TOKEN_KEY: string;
|
|
53
|
+
static readonly API_TOKEN_FORGOT: number;
|
|
54
|
+
static readonly API_TOKEN_HEADER: string;
|
|
55
|
+
static readonly API_TOKEN_HEADER_KEY: string;
|
|
56
|
+
static readonly API_TOKEN_LIFETIME: number;
|
|
57
|
+
static readonly API_TOKEN_RENEW: number;
|
|
58
|
+
static readonly API_UPLOAD_COUNT: number;
|
|
59
|
+
static readonly API_UPLOAD_FIELD: string;
|
|
60
|
+
static readonly API_UPLOAD_SIZE: number;
|
|
61
|
+
static readonly API_UPLOAD_TEMP: string;
|
|
62
|
+
static readonly API_USER_HISTORY: boolean;
|
|
63
|
+
static readonly API_WEBSOCKET_START: boolean;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
declare abstract class Controller extends EventEmitter {
|
|
67
|
+
static readonly ATTRIBUTES: unique symbol;
|
|
68
|
+
static readonly PERMISSIONS: unique symbol;
|
|
69
|
+
}
|
|
70
|
+
|
|
15
71
|
declare class Model extends Model$1 {
|
|
16
|
-
|
|
72
|
+
protected static error(error: any): void;
|
|
17
73
|
}
|
|
18
74
|
|
|
75
|
+
declare const database: Connection;
|
|
76
|
+
|
|
19
77
|
declare class Auth extends Model {
|
|
20
78
|
id: number;
|
|
21
79
|
secret: string;
|
|
22
|
-
logout: Date;
|
|
80
|
+
logout: Date | null;
|
|
23
81
|
user_agent: string;
|
|
24
82
|
created_at: Date;
|
|
25
83
|
updated_at: Date;
|
|
@@ -127,11 +185,15 @@ declare class Audit extends Model {
|
|
|
127
185
|
user: User;
|
|
128
186
|
}
|
|
129
187
|
|
|
130
|
-
declare class
|
|
188
|
+
declare class Config extends Model {
|
|
131
189
|
key: string;
|
|
132
190
|
value: string;
|
|
133
191
|
created_at: Date;
|
|
134
192
|
updated_at: Date;
|
|
193
|
+
static all(): Promise<TypeObjectString>;
|
|
194
|
+
static del(key: string, user?: User): Promise<boolean>;
|
|
195
|
+
static get(key: string, value?: string): Promise<string>;
|
|
196
|
+
static set(key: string, value: string, user?: User): Promise<void>;
|
|
135
197
|
}
|
|
136
198
|
|
|
137
199
|
declare class Forgot extends Model {
|
|
@@ -152,6 +214,12 @@ declare class Log extends Model {
|
|
|
152
214
|
source: string;
|
|
153
215
|
message: string;
|
|
154
216
|
created_at: Date;
|
|
217
|
+
static write(message: string, source?: string, show?: boolean): Promise<void>;
|
|
218
|
+
static error(message: string, source?: string, show?: boolean): Promise<void>;
|
|
219
|
+
static info(message: string, source?: string, show?: boolean): Promise<void>;
|
|
220
|
+
static success(message: string, source?: string, show?: boolean): Promise<void>;
|
|
221
|
+
static warning(message: string, source?: string, show?: boolean): Promise<void>;
|
|
222
|
+
private static writeRaw;
|
|
155
223
|
}
|
|
156
224
|
|
|
157
225
|
declare class Migration extends Model {
|
|
@@ -172,7 +240,7 @@ declare class Session extends Model {
|
|
|
172
240
|
declare class Application extends Application$1 {
|
|
173
241
|
readonly hash: Hash;
|
|
174
242
|
private _webSocket?;
|
|
175
|
-
constructor(controllers: Array<
|
|
243
|
+
constructor(controllers: Array<Controller>);
|
|
176
244
|
error(error: any, source?: string): void;
|
|
177
245
|
log(message: string, source?: string): void;
|
|
178
246
|
listen(): Promise<void>;
|
|
@@ -180,8 +248,9 @@ declare class Application extends Application$1 {
|
|
|
180
248
|
websocket(): WebSocketServer | undefined;
|
|
181
249
|
}
|
|
182
250
|
|
|
183
|
-
declare abstract class ControllerBase extends
|
|
184
|
-
|
|
251
|
+
declare abstract class ControllerBase extends Controller {
|
|
252
|
+
protected [Controller.PERMISSIONS]: Array<string>;
|
|
253
|
+
auth(ctx: Context, key_header: string, token_header: string, key_query: string, user_agent: string, app: Application): Promise<void>;
|
|
185
254
|
canCreate(ctx: Context, name: string, user: User): Promise<void>;
|
|
186
255
|
canDelete(ctx: Context, name: string, user: User): Promise<void>;
|
|
187
256
|
canRead(ctx: Context, name: string, user: User): Promise<void>;
|
|
@@ -196,11 +265,6 @@ declare abstract class ControllerBase extends EventEmitter {
|
|
|
196
265
|
validation(ctx: Context, options: TypeObject<ValidationBase>): Promise<void>;
|
|
197
266
|
}
|
|
198
267
|
|
|
199
|
-
declare class ControllerKeys {
|
|
200
|
-
static readonly ATTRIBUTES: unique symbol;
|
|
201
|
-
static readonly PERMISSIONS: unique symbol;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
268
|
interface ArgumentsModel<M extends Model$2<M>> {
|
|
205
269
|
ctx: Context;
|
|
206
270
|
}
|
|
@@ -238,6 +302,15 @@ interface ArgumentsModelUpdate<M extends Model$2<M>> extends ArgumentsModel<M> {
|
|
|
238
302
|
body?: TypeObjectAny;
|
|
239
303
|
}
|
|
240
304
|
|
|
305
|
+
interface IAuthParameters {
|
|
306
|
+
auth?: Auth;
|
|
307
|
+
decode?: TypeObjectAny;
|
|
308
|
+
error?: string;
|
|
309
|
+
forgot?: Forgot;
|
|
310
|
+
token?: string;
|
|
311
|
+
user?: User;
|
|
312
|
+
}
|
|
313
|
+
|
|
241
314
|
interface IDatabaseOptions {
|
|
242
315
|
database: string;
|
|
243
316
|
username: string;
|
|
@@ -250,38 +323,47 @@ interface IMigrate {
|
|
|
250
323
|
version: string;
|
|
251
324
|
}
|
|
252
325
|
|
|
253
|
-
interface ITokenParameters {
|
|
254
|
-
auth?: Auth;
|
|
255
|
-
decode?: TypeObjectAny;
|
|
256
|
-
error?: string;
|
|
257
|
-
forgot?: Forgot;
|
|
258
|
-
token?: string;
|
|
259
|
-
user?: User;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
326
|
interface ResultModelAll<M extends Model$2<M>> {
|
|
263
327
|
count: number;
|
|
264
328
|
records: Array<M>;
|
|
265
329
|
}
|
|
266
330
|
|
|
267
|
-
declare abstract class
|
|
268
|
-
|
|
269
|
-
protected [
|
|
331
|
+
declare abstract class ControllerModel<M extends Model$2<M>> extends ControllerBase {
|
|
332
|
+
protected [ControllerBase.ATTRIBUTES]: Array<string>;
|
|
333
|
+
protected [ControllerBase.PERMISSIONS]: Array<string>;
|
|
270
334
|
protected attributes(options: FindAttributeOptions): Array<string>;
|
|
271
335
|
protected create({ ctx, options, body }: ArgumentsModelCreate<M>): Promise<M | void>;
|
|
272
336
|
protected delete({ ctx, options }: ArgumentsModelDelete<M>): Promise<number>;
|
|
273
337
|
error(error: any): void;
|
|
274
338
|
protected findAll({ ctx, options, callback, scope, advanced, attributes, unlimited }: ArgumentsModelFindAll<M>): Promise<ResultModelAll<M>>;
|
|
275
339
|
protected findOne({ ctx, options, callback, scope }: ArgumentsModelFindOne<M>): Promise<M | void>;
|
|
340
|
+
abstract model(): ModelStatic<M>;
|
|
276
341
|
sync(): Promise<void>;
|
|
277
342
|
protected update({ ctx, options, body }: ArgumentsModelUpdate<M>): Promise<boolean>;
|
|
278
343
|
key(): string;
|
|
279
|
-
abstract model(): ModelStatic<M>;
|
|
280
344
|
name(): string;
|
|
281
345
|
scope(name?: string): ModelStatic<M>;
|
|
282
346
|
}
|
|
283
347
|
|
|
284
|
-
declare class
|
|
348
|
+
declare abstract class ControllerCrud<M extends Model$2<M>> extends ControllerModel<M> {
|
|
349
|
+
private _crud;
|
|
350
|
+
CrudArgumentsCreate(ctx: Context): ArgumentsModelUpdate<M>;
|
|
351
|
+
CrudArgumentsFindAll(ctx: Context): ArgumentsModelFindAll<M>;
|
|
352
|
+
CrudArgumentsFindOne(ctx: Context): ArgumentsModelFindOne<M>;
|
|
353
|
+
CrudArgumentsDelete(ctx: Context): ArgumentsModelDelete<M>;
|
|
354
|
+
CrudArgumentsUpdate(ctx: Context): ArgumentsModelUpdate<M>;
|
|
355
|
+
CrudValidationCreate(): TypeObject<ValidationBase>;
|
|
356
|
+
CrudValidationUpdate(): TypeObject<ValidationBase>;
|
|
357
|
+
protected add(ctx: Context): Promise<void>;
|
|
358
|
+
protected all(ctx: Context): Promise<void>;
|
|
359
|
+
protected del(ctx: Context): Promise<void>;
|
|
360
|
+
protected get(ctx: Context): Promise<void>;
|
|
361
|
+
protected set(ctx: Context): Promise<void>;
|
|
362
|
+
protected validationCreate(ctx: Context): Promise<void>;
|
|
363
|
+
protected validationUpdate(ctx: Context): Promise<void>;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
declare class AuditsController extends ControllerModel<Audit> {
|
|
285
367
|
model(): typeof Audit;
|
|
286
368
|
protected all(ctx: Context, type: string, table: string): Promise<void>;
|
|
287
369
|
protected get(ctx: Context): Promise<void>;
|
|
@@ -295,7 +377,7 @@ declare class AuthController extends ControllerBase {
|
|
|
295
377
|
}
|
|
296
378
|
|
|
297
379
|
declare class FilesController extends ControllerBase {
|
|
298
|
-
protected [
|
|
380
|
+
protected [ControllerBase.PERMISSIONS]: Array<string>;
|
|
299
381
|
directory(): string;
|
|
300
382
|
protected files(ctx: Context): Promise<TypeObjectAny | void>;
|
|
301
383
|
protected access(ctx: Context, name: string, user: User): Promise<void>;
|
|
@@ -311,25 +393,7 @@ declare class ForgotController extends ControllerBase {
|
|
|
311
393
|
private find;
|
|
312
394
|
}
|
|
313
395
|
|
|
314
|
-
declare
|
|
315
|
-
private _crud;
|
|
316
|
-
CrudArgumentsCreate(ctx: Context): ArgumentsModelUpdate<M>;
|
|
317
|
-
CrudArgumentsFindAll(ctx: Context): ArgumentsModelFindAll<M>;
|
|
318
|
-
CrudArgumentsFindOne(ctx: Context): ArgumentsModelFindOne<M>;
|
|
319
|
-
CrudArgumentsDelete(ctx: Context): ArgumentsModelDelete<M>;
|
|
320
|
-
CrudArgumentsUpdate(ctx: Context): ArgumentsModelUpdate<M>;
|
|
321
|
-
CrudValidationCreate(): TypeObject<ValidationBase>;
|
|
322
|
-
CrudValidationUpdate(): TypeObject<ValidationBase>;
|
|
323
|
-
protected add(ctx: Context): Promise<void>;
|
|
324
|
-
protected all(ctx: Context): Promise<void>;
|
|
325
|
-
protected del(ctx: Context): Promise<void>;
|
|
326
|
-
protected get(ctx: Context): Promise<void>;
|
|
327
|
-
protected set(ctx: Context): Promise<void>;
|
|
328
|
-
protected validationCreate(ctx: Context): Promise<void>;
|
|
329
|
-
protected validationUpdate(ctx: Context): Promise<void>;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
declare class GroupsController extends CrudController<Group> {
|
|
396
|
+
declare class GroupsController extends ControllerCrud<Group> {
|
|
333
397
|
private schemaCreate;
|
|
334
398
|
private schemaUpdate;
|
|
335
399
|
model(): typeof Group;
|
|
@@ -338,20 +402,20 @@ declare class GroupsController extends CrudController<Group> {
|
|
|
338
402
|
CrudValidationUpdate(): TypeObject<ValidationBase>;
|
|
339
403
|
}
|
|
340
404
|
|
|
341
|
-
declare class GroupsPermissionsController extends
|
|
405
|
+
declare class GroupsPermissionsController extends ControllerModel<GroupPermission> {
|
|
342
406
|
model(): typeof GroupPermission;
|
|
343
407
|
protected all(ctx: Context, group_id: string): Promise<void>;
|
|
344
408
|
protected me(ctx: Context, user: User): Promise<void>;
|
|
345
409
|
protected set(ctx: Context, id: string, permissions: Array<number>, audit: TypeObjectAny): Promise<void>;
|
|
346
410
|
}
|
|
347
411
|
|
|
348
|
-
declare class LogsController extends
|
|
349
|
-
protected [
|
|
412
|
+
declare class LogsController extends ControllerModel<Log> {
|
|
413
|
+
protected [ControllerModel.PERMISSIONS]: Array<string>;
|
|
350
414
|
model(): typeof Log;
|
|
351
415
|
protected all(ctx: Context, type: string, source: string): Promise<void>;
|
|
352
416
|
}
|
|
353
417
|
|
|
354
|
-
declare class PermissionsController extends
|
|
418
|
+
declare class PermissionsController extends ControllerCrud<Permission> {
|
|
355
419
|
private schemaCreate;
|
|
356
420
|
private schemaUpdate;
|
|
357
421
|
model(): typeof Permission;
|
|
@@ -371,7 +435,7 @@ declare class SetupController extends ControllerBase {
|
|
|
371
435
|
protected setup(ctx: Context, audit: TypeObjectAny): Promise<void>;
|
|
372
436
|
}
|
|
373
437
|
|
|
374
|
-
declare class UsersController extends
|
|
438
|
+
declare class UsersController extends ControllerModel<User> {
|
|
375
439
|
path: string;
|
|
376
440
|
model(): typeof User;
|
|
377
441
|
constructor();
|
|
@@ -390,7 +454,7 @@ declare class UsersController extends ModelController<User> {
|
|
|
390
454
|
protected set(ctx: Context, id: string, password: string): Promise<void>;
|
|
391
455
|
}
|
|
392
456
|
|
|
393
|
-
declare class UsersGroupsController extends
|
|
457
|
+
declare class UsersGroupsController extends ControllerModel<UserGroup> {
|
|
394
458
|
model(): typeof UserGroup;
|
|
395
459
|
protected all(ctx: Context, user_id: string): Promise<void>;
|
|
396
460
|
protected me(ctx: Context, user: User): Promise<void>;
|
|
@@ -414,89 +478,36 @@ declare global {
|
|
|
414
478
|
|
|
415
479
|
declare const Migrate: (version: string) => ClassDecorator;
|
|
416
480
|
|
|
417
|
-
declare
|
|
481
|
+
declare class Metadata {
|
|
482
|
+
static readonly MIGRATE: unique symbol;
|
|
483
|
+
static migrations(target: any): IMigrate;
|
|
484
|
+
}
|
|
418
485
|
|
|
419
|
-
declare class
|
|
420
|
-
static
|
|
421
|
-
static del(key: string, user?: User): Promise<boolean>;
|
|
422
|
-
private static error;
|
|
423
|
-
static get(key: string, value?: string): Promise<string>;
|
|
424
|
-
static set(key: string, value: string, user?: User): Promise<void>;
|
|
486
|
+
declare class AuthBase {
|
|
487
|
+
protected static error(error: any): void;
|
|
425
488
|
}
|
|
426
489
|
|
|
427
|
-
declare
|
|
490
|
+
declare class AuthKey extends AuthBase {
|
|
491
|
+
static user(key: string, app: Application): Promise<IAuthParameters>;
|
|
492
|
+
}
|
|
428
493
|
|
|
429
|
-
declare class
|
|
430
|
-
static
|
|
431
|
-
static
|
|
432
|
-
static
|
|
433
|
-
static
|
|
434
|
-
static
|
|
435
|
-
static
|
|
436
|
-
static readonly API_DB_DATABASE: string;
|
|
437
|
-
static readonly API_DB_HOST: string;
|
|
438
|
-
static readonly API_DB_PASSWORD: string;
|
|
439
|
-
static readonly API_DB_PORT: number;
|
|
440
|
-
static readonly API_DB_TYPE: string;
|
|
441
|
-
static readonly API_DB_USERNAME: string;
|
|
442
|
-
static readonly API_DB_LOG: boolean;
|
|
443
|
-
static readonly API_DB_AUDIT: boolean;
|
|
444
|
-
static readonly API_DB_PREFIX: string;
|
|
445
|
-
static readonly API_DB_TIMEZONE: string;
|
|
446
|
-
static readonly API_HTTP_CRT: string;
|
|
447
|
-
static readonly API_HTTP_KEY: string;
|
|
448
|
-
static readonly API_HTTP_PORT: number;
|
|
449
|
-
static readonly API_HTTP_PUBLIC: string;
|
|
450
|
-
static readonly API_HTTP_CROSS: boolean;
|
|
451
|
-
static readonly API_HTTP_HYBRID: boolean;
|
|
452
|
-
static readonly API_HTTP_NOTFOUND: string;
|
|
453
|
-
static readonly API_HTTP_PATH: string;
|
|
454
|
-
static readonly API_HTTP_REDIRECT: string;
|
|
455
|
-
static readonly API_KEY_HASH: string;
|
|
456
|
-
static readonly API_KEY_HEADER: string;
|
|
457
|
-
static readonly API_MODEL_LIMIT: number;
|
|
458
|
-
static readonly API_MODEL_LIMIT_MAX: number;
|
|
459
|
-
static readonly API_SLEEP_AUTH: number;
|
|
460
|
-
static readonly API_SLEEP_FORGOT: number;
|
|
461
|
-
static readonly API_SLEEP_REGISTRY: number;
|
|
462
|
-
static readonly API_SESSION_NAME: string;
|
|
463
|
-
static readonly API_SESSION_LIFETIME: number;
|
|
464
|
-
static readonly API_SESSION_SECRET: string;
|
|
465
|
-
static readonly API_TOKEN_CRT: string;
|
|
466
|
-
static readonly API_TOKEN_KEY: string;
|
|
467
|
-
static readonly API_TOKEN_FORGOT: number;
|
|
468
|
-
static readonly API_TOKEN_HEADER: string;
|
|
469
|
-
static readonly API_TOKEN_HEADER_KEY: string;
|
|
470
|
-
static readonly API_TOKEN_LIFETIME: number;
|
|
471
|
-
static readonly API_TOKEN_RENEW: number;
|
|
472
|
-
static readonly API_UPLOAD_COUNT: number;
|
|
473
|
-
static readonly API_UPLOAD_FIELD: string;
|
|
474
|
-
static readonly API_UPLOAD_SIZE: number;
|
|
475
|
-
static readonly API_UPLOAD_TEMP: string;
|
|
476
|
-
static readonly API_USER_HISTORY: boolean;
|
|
477
|
-
static readonly API_WEBSOCKET_START: boolean;
|
|
494
|
+
declare class AuthToken extends AuthBase {
|
|
495
|
+
private static options;
|
|
496
|
+
static create(user: User): Promise<IAuthParameters>;
|
|
497
|
+
static destroy(auth?: Auth): Promise<boolean>;
|
|
498
|
+
static renew(token: string): Promise<IAuthParameters>;
|
|
499
|
+
static user(token: string): Promise<IAuthParameters>;
|
|
500
|
+
private static verify;
|
|
478
501
|
}
|
|
479
502
|
|
|
503
|
+
declare const audit: (ctx: Context) => TypeObjectAny;
|
|
504
|
+
|
|
480
505
|
declare const hooks: {
|
|
481
506
|
afterCreate: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
482
507
|
afterUpdate: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
483
508
|
afterDestroy: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
484
509
|
};
|
|
485
510
|
|
|
486
|
-
declare class Logs {
|
|
487
|
-
static write(message: string, source?: string, show?: boolean): Promise<void>;
|
|
488
|
-
static error(message: string, source?: string, show?: boolean): Promise<void>;
|
|
489
|
-
static info(message: string, source?: string, show?: boolean): Promise<void>;
|
|
490
|
-
static success(message: string, source?: string, show?: boolean): Promise<void>;
|
|
491
|
-
static warning(message: string, source?: string, show?: boolean): Promise<void>;
|
|
492
|
-
private static writeRaw;
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
declare class Metadata {
|
|
496
|
-
static readonly MIGRATE: unique symbol;
|
|
497
|
-
static migrations(target: any): IMigrate;
|
|
498
|
-
}
|
|
499
|
-
|
|
500
511
|
declare const crt: {
|
|
501
512
|
http: Buffer<ArrayBufferLike> | undefined;
|
|
502
513
|
token: Buffer<ArrayBufferLike> | undefined;
|
|
@@ -518,15 +529,5 @@ declare class Store extends Store$1 {
|
|
|
518
529
|
set: (session_id: any, session: SessionData, callback: TypeCallbackFunction) => Promise<void>;
|
|
519
530
|
}
|
|
520
531
|
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
static destroy(auth?: Auth): Promise<boolean>;
|
|
524
|
-
private static error;
|
|
525
|
-
private static options;
|
|
526
|
-
static renew(token: string): Promise<ITokenParameters>;
|
|
527
|
-
static user(key: string, token: string, app: Application): Promise<ITokenParameters>;
|
|
528
|
-
private static verify;
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
export { Application, Audit, AuditsController, Auth, AuthController, Config, Configs, ControllerBase, ControllerKeys, CrudController, Env, FilesController, Forgot, ForgotController, Group, GroupPermission, GroupsController, GroupsPermissionsController, Log, Logs, LogsController, Metadata, Migrate, Migration, Model, ModelController, Permission, PermissionsController, Register, RegisterController, ReqAudit, ReqAuth, ReqUser, Session, SetupController, Store, Token, User, UserGroup, UserHistory, UsersController, UsersGroupsController, audit, crt, database, hooks, key };
|
|
532
|
-
export type { ArgumentsModel, ArgumentsModelCreate, ArgumentsModelDelete, ArgumentsModelFindAll, ArgumentsModelFindOne, ArgumentsModelUpdate, CallbackModelAll, CallbackModelGet, IDatabaseOptions, IMigrate, ITokenParameters, ResultModelAll };
|
|
532
|
+
export { Application, Audit, AuditsController, Auth, AuthBase, AuthController, AuthKey, AuthToken, Config, Controller, ControllerBase, ControllerCrud, ControllerModel, Env, FilesController, Forgot, ForgotController, Group, GroupPermission, GroupsController, GroupsPermissionsController, Log, LogsController, Metadata, Migrate, Migration, Model, Permission, PermissionsController, Register, RegisterController, ReqAudit, ReqAuth, ReqUser, Session, SetupController, Store, User, UserGroup, UserHistory, UsersController, UsersGroupsController, audit, crt, database, hooks, key };
|
|
533
|
+
export type { ArgumentsModel, ArgumentsModelCreate, ArgumentsModelDelete, ArgumentsModelFindAll, ArgumentsModelFindOne, ArgumentsModelUpdate, CallbackModelAll, CallbackModelGet, IAuthParameters, IDatabaseOptions, IMigrate, ResultModelAll };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v4.
|
|
2
|
+
* @andrewcaires/api v4.4.0
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
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 n,Context as s,Argument as o,Session as d,Upload 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 E,Files as A}from"@andrewcaires/express";import{Connection as O,Model as I,Id as P,String as f,FullDate as R,CreatedAt as S,UpdatedAt as T,DeletedAt as D,BelongsTo as N,Database as b,ModelName as w,Boolean as C,Text as F,HasMany as x,Hooks as j,DateOnly as k,DefaultScope as L,Scopes as B,Enum as U,Json as M,BigInt as H,Unique as K,migrate as q,Where as Y}from"@andrewcaires/sequelize";import{Metadata as V,Env as $,LogColor as G,Log as W,Hash as z,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,forEachSeries as ie,isFunction as re,sleep as ne,EventEmitter as se,Validation as oe,isArray as de,isString as ae,isUndefined as ue,clamp as pe,isNumber as ce,upperCamelCase as le,denied as ye,isDef as ge,uniqueID as he}from"@andrewcaires/utils.js";import{Op as ve}from"sequelize";import{WebSocketServer as _e}from"ws";import{readFileSync as me,existsSync as Ee,statSync as Ae,readdirSync as Oe,mkdirSync as Ie,lstatSync as Pe,rmSync as fe}from"fs";import{Store as Re}from"express-session";import Se from"jsonwebtoken";import{join as Te}from"path";function De(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var d=e.length-1;d>=0;d--)(n=e[d])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o}function Ne(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 we(e,t,i,r){return new(i||(i=Promise))(function(n,s){function o(e){try{a(r.next(e))}catch(e){s(e)}}function d(e){try{a(r.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,d)}a((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const Ce=e=>{var t,i,r,n,s,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===(n=null==e?void 0:e.req)||void 0===n?void 0:n.originalUrl),audit_user_agent:null!==(o=null===(s=e.req)||void 0===s?void 0:s.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}},Fe=e(({ctx:e})=>Ce(e)),xe=e(({ctx:e})=>e.req.auth),je=e(({ctx:e})=>e.req.user);class ke{static migrations(e){return V(ke.MIGRATE,e,{version:""})}}ke.MIGRATE=Symbol("MIGRATE");const Le=e=>t=>{ke.migrations(t).version=e};X({quiet:!0});class Be extends ${}Be.API_BASE_NAME=Be.getString("API_BASE_NAME",""),Be.API_BODYPARSER_STRICT=Be.getBool("API_BODYPARSER_STRICT",!0),Be.API_BODYPARSER_INFLATE=Be.getBool("API_BODYPARSER_INFLATE",!0),Be.API_BODYPARSER_LIMIT=Be.getString("API_BODYPARSER_LIMIT","10mb"),Be.API_BODYPARSER_TYPE=Be.getString("API_BODYPARSER_TYPE","json"),Be.API_CONSOLE_ERROR=Be.getBool("API_CONSOLE_ERROR",!1),Be.API_DB_DATABASE=Be.getString("API_DB_DATABASE",""),Be.API_DB_HOST=Be.getString("API_DB_HOST","127.0.0.1"),Be.API_DB_PASSWORD=Be.getString("API_DB_PASSWORD",""),Be.API_DB_PORT=Be.getInt("API_DB_PORT",3306),Be.API_DB_TYPE=Be.getString("API_DB_TYPE",""),Be.API_DB_USERNAME=Be.getString("API_DB_USERNAME","root"),Be.API_DB_LOG=Be.getBool("API_DB_LOG",!1),Be.API_DB_AUDIT=Be.getBool("API_DB_AUDIT",!0),Be.API_DB_PREFIX=Be.getString("API_DB_PREFIX",""),Be.API_DB_TIMEZONE=Be.getString("API_DB_TIMEZONE","+00:00"),Be.API_HTTP_CRT=Be.getString("API_HTTP_CRT",""),Be.API_HTTP_KEY=Be.getString("API_HTTP_KEY",""),Be.API_HTTP_PORT=Be.getInt("API_HTTP_PORT",3e3),Be.API_HTTP_PUBLIC=Be.getString("API_HTTP_PUBLIC",""),Be.API_HTTP_CROSS=Be.getBool("API_HTTP_CROSS",!1),Be.API_HTTP_HYBRID=Be.getBool("API_HTTP_HYBRID",!1),Be.API_HTTP_NOTFOUND=Be.getString("API_HTTP_NOTFOUND",""),Be.API_HTTP_PATH=Be.getString("API_HTTP_PATH","/api"),Be.API_HTTP_REDIRECT=Be.getString("API_HTTP_REDIRECT",""),Be.API_KEY_HASH=Be.getString("API_KEY_HASH",""),Be.API_KEY_HEADER=Be.getString("API_KEY_HEADER","x-api-key"),Be.API_MODEL_LIMIT=Be.getInt("API_MODEL_LIMIT",10),Be.API_MODEL_LIMIT_MAX=Be.getInt("API_MODEL_LIMIT_MAX",500),Be.API_SLEEP_AUTH=Be.getMs("API_SLEEP_AUTH","2s"),Be.API_SLEEP_FORGOT=Be.getMs("API_SLEEP_FORGOT","5s"),Be.API_SLEEP_REGISTRY=Be.getMs("API_SLEEP_REGISTRY","5s"),Be.API_SESSION_NAME=Be.getString("API_SESSION_NAME","session.id"),Be.API_SESSION_LIFETIME=Be.getMs("API_SESSION_LIFETIME","1d"),Be.API_SESSION_SECRET=Be.getString("API_SESSION_SECRET","yoursecret"),Be.API_TOKEN_CRT=Be.getString("API_TOKEN_CRT",""),Be.API_TOKEN_KEY=Be.getString("API_TOKEN_KEY",""),Be.API_TOKEN_FORGOT=Be.getMs("API_TOKEN_LIFETIME","1d"),Be.API_TOKEN_HEADER=Be.getString("API_TOKEN_HEADER","authorization"),Be.API_TOKEN_HEADER_KEY=Be.getString("API_TOKEN_HEADER","bearer"),Be.API_TOKEN_LIFETIME=Be.getMs("API_TOKEN_LIFETIME","1d"),Be.API_TOKEN_RENEW=Be.getMs("API_TOKEN_RENEW","1d"),Be.API_UPLOAD_COUNT=Be.getInt("API_UPLOAD_COUNT",1),Be.API_UPLOAD_FIELD=Be.getString("API_UPLOAD_FIELD","upload"),Be.API_UPLOAD_SIZE=Be.getInt("API_UPLOAD_SIZE",2),Be.API_UPLOAD_TEMP=Be.getString("API_UPLOAD_TEMP","./temp"),Be.API_USER_HISTORY=Be.getBool("API_USER_HISTORY",!0),Be.API_WEBSOCKET_START=Be.getBool("API_WEBSOCKET_START",!1);const Ue=new O({type:Be.API_DB_TYPE,database:Be.API_DB_DATABASE,username:Be.API_DB_USERNAME,password:Be.API_DB_PASSWORD,hostname:Be.API_DB_HOST,hostport:Be.API_DB_PORT,logging:Be.API_DB_LOG,prefix:Be.API_DB_PREFIX,timezone:Be.API_DB_TIMEZONE});class Me extends I{constructor(){super(...arguments),this._version=""}}const He=(e,t,i)=>{var r,n,s,o,d;return{type:e,model:null!==(r=null==t?void 0:t.getTableName())&&void 0!==r?r:null,client:null!==(n=null==i?void 0:i.audit_client)&&void 0!==n?n:null,href:null!==(s=null==i?void 0:i.audit_href)&&void 0!==s?s: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}},Ke={afterCreate:(e,t)=>we(void 0,void 0,void 0,function*(){var i;if(!Be.API_DB_AUDIT)return;const r=Z(e)?e.constructor:null,n=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null;yield ze.create(Object.assign(Object.assign({},He("CREATE",r,t)),{record:n?e.getDataValue(n):null,data:e.toJSON()})).catch(Q)}),afterUpdate:(e,t)=>we(void 0,void 0,void 0,function*(){var i;if(!Be.API_DB_AUDIT)return;const r=Z(e)?e.constructor:null,n=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null,s={},o=e.changed();o&&o.forEach(t=>s[t]=e.getDataValue(t)),yield ze.create(Object.assign(Object.assign({},He("UPDATE",r,t)),{record:n?e.getDataValue(n):null,data:s,previously:e.previous()})).catch(Q)}),afterDestroy:(e,t)=>we(void 0,void 0,void 0,function*(){var i;if(!Be.API_DB_AUDIT)return;const r=Z(e)?e.constructor:null,n=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null;yield ze.create(Object.assign(Object.assign({},He("DELETE",r,t)),{record:n?e.getDataValue(n):null,data:e.toJSON()})).catch(Q)})};let qe=class extends Me{};De([P(),be("design:type",Number)],qe.prototype,"id",void 0),De([f(),be("design:type",f)],qe.prototype,"secret",void 0),De([R(),be("design:type",Date)],qe.prototype,"logout",void 0),De([f(),be("design:type",f)],qe.prototype,"user_agent",void 0),De([S,be("design:type",Date)],qe.prototype,"created_at",void 0),De([T,be("design:type",Date)],qe.prototype,"updated_at",void 0),De([D,be("design:type",Object)],qe.prototype,"deleted_at",void 0),De([N(()=>We),be("design:type",Number)],qe.prototype,"user_id",void 0),qe=De([b(Ue),w("auth"),Le("4.2.0")],qe);let Ye=class extends Me{};De([P(),be("design:type",Number)],Ye.prototype,"id",void 0),De([f(),be("design:type",f)],Ye.prototype,"token",void 0),De([C(),be("design:type",C)],Ye.prototype,"state",void 0),De([S,be("design:type",Date)],Ye.prototype,"created_at",void 0),De([T,be("design:type",Date)],Ye.prototype,"updated_at",void 0),De([D,be("design:type",Object)],Ye.prototype,"deleted_at",void 0),De([N(()=>We),be("design:type",Number)],Ye.prototype,"user_id",void 0),Ye=De([b(Ue),w("register"),Le("4.2.0")],Ye);let Ve=class extends Me{};De([P(),be("design:type",Number)],Ve.prototype,"id",void 0),De([f(),be("design:type",f)],Ve.prototype,"name",void 0),De([F(),be("design:type",f)],Ve.prototype,"description",void 0),De([C(),be("design:type",C)],Ve.prototype,"state",void 0),De([S,be("design:type",Date)],Ve.prototype,"created_at",void 0),De([T,be("design:type",Date)],Ve.prototype,"updated_at",void 0),De([D,be("design:type",Object)],Ve.prototype,"deleted_at",void 0),De([x(()=>$e,"group_id"),be("design:type",Array)],Ve.prototype,"groups_routes",void 0),De([x(()=>$e,"group_id"),be("design:type",Array)],Ve.prototype,"users_groups",void 0),Ve=De([b(Ue),w("group"),j(Ke),Le("4.2.0")],Ve);let $e=class extends Me{};De([S,be("design:type",Date)],$e.prototype,"created_at",void 0),De([N(()=>Ve),be("design:type",Number)],$e.prototype,"group_id",void 0),De([N(()=>We),be("design:type",Number)],$e.prototype,"user_id",void 0),$e=De([b(Ue),w("users_groups"),j(Ke),Le("4.2.0")],$e);let Ge=class extends Me{};De([f(),be("design:type",f)],Ge.prototype,"password",void 0),De([S,be("design:type",Date)],Ge.prototype,"created_at",void 0),De([N(()=>We),be("design:type",Number)],Ge.prototype,"user_id",void 0),Ge=De([b(Ue),w("users_histories"),Le("4.2.0")],Ge);let We=class extends Me{};De([P(),be("design:type",Number)],We.prototype,"id",void 0),De([f(),be("design:type",f)],We.prototype,"name",void 0),De([f(),be("design:type",f)],We.prototype,"email",void 0),De([f(),be("design:type",f)],We.prototype,"username",void 0),De([f(),be("design:type",f)],We.prototype,"password",void 0),De([f(),be("design:type",f)],We.prototype,"salt",void 0),De([f(),be("design:type",f)],We.prototype,"token",void 0),De([f(),be("design:type",f)],We.prototype,"avatar",void 0),De([k(),be("design:type",f)],We.prototype,"date",void 0),De([F(),be("design:type",f)],We.prototype,"description",void 0),De([C(),be("design:type",C)],We.prototype,"state",void 0),De([S,be("design:type",Date)],We.prototype,"created_at",void 0),De([T,be("design:type",Date)],We.prototype,"updated_at",void 0),De([D,be("design:type",Object)],We.prototype,"deleted_at",void 0),De([x(()=>ze,"user_id"),be("design:type",Array)],We.prototype,"audits",void 0),De([x(()=>qe,"user_id"),be("design:type",Array)],We.prototype,"auths",void 0),De([x(()=>Ye,"user_id"),be("design:type",Array)],We.prototype,"registers",void 0),De([x(()=>$e,"user_id"),be("design:type",Array)],We.prototype,"users_groups",void 0),De([x(()=>Ge,"user_id"),be("design:type",Array)],We.prototype,"users_histories",void 0),We=De([b(Ue),w("user"),L({attributes:{exclude:["password","salt","token"]}}),B({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),j(Ke),Le("4.2.0")],We);let ze=class extends Me{};De([P(),be("design:type",Number)],ze.prototype,"id",void 0),De([U("CREATE","DELETE","UPDATE"),be("design:type",f)],ze.prototype,"type",void 0),De([f(),be("design:type",f)],ze.prototype,"model",void 0),De([f(),be("design:type",f)],ze.prototype,"record",void 0),De([M(),be("design:type",Object)],ze.prototype,"data",void 0),De([M(),be("design:type",Object)],ze.prototype,"previously",void 0),De([f(),be("design:type",f)],ze.prototype,"client",void 0),De([F(),be("design:type",f)],ze.prototype,"href",void 0),De([f(),be("design:type",f)],ze.prototype,"user_agent",void 0),De([C(),be("design:type",C)],ze.prototype,"state",void 0),De([S,be("design:type",Date)],ze.prototype,"created_at",void 0),De([T,be("design:type",Date)],ze.prototype,"updated_at",void 0),De([D,be("design:type",Object)],ze.prototype,"deleted_at",void 0),De([N(()=>We),be("design:type",Number)],ze.prototype,"user_id",void 0),ze=De([b(Ue),w("audit"),Le("4.2.0")],ze);let Je=class extends Me{};De([f(),be("design:type",f)],Je.prototype,"key",void 0),De([f(),be("design:type",f)],Je.prototype,"value",void 0),De([S,be("design:type",Date)],Je.prototype,"created_at",void 0),De([T,be("design:type",Date)],Je.prototype,"updated_at",void 0),Je=De([b(Ue),w("configs"),j(Ke),Le("4.2.0")],Je);let Xe=class extends Me{};De([P(),be("design:type",Number)],Xe.prototype,"id",void 0),De([f(),be("design:type",f)],Xe.prototype,"token",void 0),De([H(),be("design:type",Number)],Xe.prototype,"timestamp",void 0),De([C(),be("design:type",C)],Xe.prototype,"state",void 0),De([S,be("design:type",Date)],Xe.prototype,"created_at",void 0),De([T,be("design:type",Date)],Xe.prototype,"updated_at",void 0),De([D,be("design:type",Object)],Xe.prototype,"deleted_at",void 0),De([N(()=>We),be("design:type",Number)],Xe.prototype,"user_id",void 0),Xe=De([b(Ue),w("forgot"),Le("4.2.0")],Xe);let Ze=class extends Me{};De([P(),be("design:type",Number)],Ze.prototype,"id",void 0),De([f(),be("design:type",f)],Ze.prototype,"name",void 0),De([f(),K(!0),be("design:type",f)],Ze.prototype,"route",void 0),De([f(),be("design:type",f)],Ze.prototype,"tag",void 0),De([F(),be("design:type",f)],Ze.prototype,"description",void 0),De([C(),be("design:type",C)],Ze.prototype,"state",void 0),De([S,be("design:type",Date)],Ze.prototype,"created_at",void 0),De([T,be("design:type",Date)],Ze.prototype,"updated_at",void 0),De([D,be("design:type",Object)],Ze.prototype,"deleted_at",void 0),De([x(()=>Qe,"permission_id"),be("design:type",Array)],Ze.prototype,"groups_permissions",void 0),Ze=De([b(Ue),w("permission"),j(Ke),Le("4.3.1")],Ze);let Qe=class extends Me{};De([S,be("design:type",Date)],Qe.prototype,"created_at",void 0),De([N(()=>Ve),be("design:type",Number)],Qe.prototype,"group_id",void 0),De([N(()=>Ze),be("design:type",Number)],Qe.prototype,"permission_id",void 0),Qe=De([b(Ue),w("groups_permissions"),j(Ke),Le("4.2.0")],Qe);let et=class extends Me{};De([P(),be("design:type",Number)],et.prototype,"id",void 0),De([f(),be("design:type",f)],et.prototype,"type",void 0),De([f(),be("design:type",f)],et.prototype,"source",void 0),De([F(),be("design:type",f)],et.prototype,"message",void 0),De([S,be("design:type",Date)],et.prototype,"created_at",void 0),et=De([b(Ue),w("log"),Le("4.2.0")],et);let tt=class extends Me{};De([f(),be("design:type",f)],tt.prototype,"model",void 0),De([f(),be("design:type",f)],tt.prototype,"version",void 0),De([S,be("design:type",Date)],tt.prototype,"created_at",void 0),De([T,be("design:type",Date)],tt.prototype,"updated_at",void 0),tt=De([b(Ue),w("migration"),Le("4.2.0")],tt);let it=class extends Me{};De([f(),be("design:type",f)],it.prototype,"session",void 0),De([F(),be("design:type",f)],it.prototype,"json",void 0),De([H(),be("design:type",Number)],it.prototype,"expired",void 0),De([S,be("design:type",Date)],it.prototype,"created_at",void 0),De([T,be("design:type",Date)],it.prototype,"updated_at",void 0),it=De([b(Ue),w("session"),Le("4.2.0")],it);class rt{static write(e,t,i){return we(this,void 0,void 0,function*(){yield rt.writeRaw(G.White,"",e,t,i)})}static error(e,t,i){return we(this,void 0,void 0,function*(){yield rt.writeRaw(G.Red,"error",e,t,i)})}static info(e,t,i){return we(this,void 0,void 0,function*(){yield rt.writeRaw(G.Cyan,"info",e,t,i)})}static success(e,t,i){return we(this,void 0,void 0,function*(){yield rt.writeRaw(G.Green,"success",e,t,i)})}static warning(e,t,i){return we(this,void 0,void 0,function*(){yield rt.writeRaw(G.Yellow,"warning",e,t,i)})}static writeRaw(e,t,i,r,n){return we(this,void 0,void 0,function*(){n&&W.console(e,t,i),Ue&&(yield et.create({type:t,source:r,message:i}).catch(()=>null))})}}const nt=e=>Ee(e)?me(e):void 0,st={http:nt(Be.API_HTTP_CRT),token:nt(Be.API_TOKEN_CRT)},ot={http:nt(Be.API_HTTP_KEY),token:nt(Be.API_TOKEN_KEY)};class dt extends Re{constructor(){super(),this.all=e=>we(this,void 0,void 0,function*(){e=e||Q;const t=yield it.findAll({attributes:["session"],where:{expired:{[ve.gte]:Date.now()}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.session)),e()}),this.clear=e=>we(this,void 0,void 0,function*(){yield it.destroy().catch(Q),e&&e()}),this.destroy=(e,t)=>we(this,void 0,void 0,function*(){yield it.destroy({where:{session:e}}).catch(Q),t&&t()}),this.expired=()=>we(this,void 0,void 0,function*(){yield it.destroy({where:{expired:{[ve.lt]:Date.now()}}}).catch(Q)}),this.get=(e,t)=>we(this,void 0,void 0,function*(){t=t||Q;const i=yield it.findOne({where:{session:e,expired:{[ve.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)}return void t(null,e)}t(null)}),this.length=e=>we(this,void 0,void 0,function*(){e&&e(null,(yield it.count().catch(Q))||0)}),this.set=(e,t,i)=>we(this,void 0,void 0,function*(){i=i||Q;const r=Date.now()+Be.API_SESSION_LIFETIME,n=JSON.stringify(t),[s,o]=(yield it.findOrCreate({where:{session:e},defaults:{session:e,json:n,expired:r}}).catch(Q))||[];s&&(o||(s.json=n,s.expired=r,yield s.save().catch(Q))),i()}),this.loop=ee(this.expired,3e4),this.loop.start()}}class at{static create(e){return we(this,void 0,void 0,function*(){if(!ot.token)return{error:"KEY NOT FOUND"};const{id:t}=e,i=te(),r=yield qe.create({secret:i,user_id:t}).catch(at.error);if(!r)return{error:"INTERNAL SERVER ERROR"};return{auth:r,token:Se.sign({id:t,secret:i},ot.token,at.options())}})}static destroy(e){return we(this,void 0,void 0,function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)})}static error(e){let t="token";Be.API_BASE_NAME&&(t=`${Be.API_BASE_NAME}.${t}`),rt.error(e.message,t,Be.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:`${Be.API_TOKEN_LIFETIME}ms`}}static renew(e){return we(this,void 0,void 0,function*(){if(!ot.token)return{error:"KEY NOT FOUND"};const{error:t,decode:i}=at.verify(e,Be.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(at.error);if(i){const r=yield qe.findOne({where:{secret:t,user_id:i.id}}).catch(at.error);if(r&&!r.logout){r.secret=te(),yield r.save().catch(at.error);return{auth:r,token:Se.sign({id:e,secret:r.secret},ot.token,at.options())}}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static user(e,t,i){return we(this,void 0,void 0,function*(){if(e){t=i.hash.encrypt(e);const r=yield We.findOne({where:{token:t,state:!0}}).catch(at.error);if(r){const t=e.replace(/(-[\w]{4})/g,"-****"),[i]=(yield qe.findOrCreate({where:{secret:t,user_id:r.id},defaults:{secret:t,user_id:r.id}}).catch(at.error))||[];if(i)return{auth:i,user:r}}return{error:"ACCESS DENIED"}}const{error:r,decode:n}=at.verify(t);if(r)return{error:r};if(n){const{id:e,secret:t}=n;if(e&&t){const i=yield We.findOne({where:{id:e,state:!0}}).catch(at.error);if(i){const e=yield qe.findOne({where:{secret:t,user_id:i.id}}).catch(at.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:Se.verify(e,st.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class ut extends t{constructor(e){super(e,{cert:st.http,cross:Be.API_HTTP_CROSS,hybrid:Be.API_HTTP_HYBRID,json:{strict:Be.API_BODYPARSER_STRICT,inflate:Be.API_BODYPARSER_INFLATE,limit:Be.API_BODYPARSER_LIMIT,type:Be.API_BODYPARSER_TYPE},key:ot.http,notfound:Be.API_HTTP_NOTFOUND,path:Be.API_HTTP_PATH,port:Be.API_HTTP_PORT,public:Be.API_HTTP_PUBLIC,redirect:Be.API_HTTP_REDIRECT,session:{store:new dt,name:Be.API_SESSION_NAME,secret:Be.API_SESSION_SECRET,cookie:{maxAge:Be.API_SESSION_LIFETIME},genid:te}}),this.hash=new z(Be.API_KEY_HASH)}error(e,t){Be.API_BASE_NAME&&(t=t?`${Be.API_BASE_NAME}.${t}`:Be.API_BASE_NAME),rt.error(e.message,t,Be.API_CONSOLE_ERROR)}log(e,t){Be.API_BASE_NAME&&(t=t?`${Be.API_BASE_NAME}.${t}`:Be.API_BASE_NAME),rt.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return we(this,void 0,void 0,function*(){yield Ue.sync(),yield this.migrations(Ue),yield ie(this.controllers,e=>we(this,void 0,void 0,function*(){re(e.sync)&&(yield e.sync(this))})),yield e.listen.call(this),Be.API_WEBSOCKET_START&&this.server&&(this._webSocket=new _e({server:this.server,verifyClient:(e,t)=>t(Be.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>we(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",n=>we(this,void 0,void 0,function*(){if(r)try{const s=JSON.parse(n);this.emit("ws.message"+i,{data:s,message:n,req:t,user:r,ws:e})}catch(s){this.emit("ws.message"+i,{erro:s,message:n,req:t,user:r,ws:e})}else{const{user:s}=yield at.user("",n.toString(),this);s&&(r=s,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 ne(2e3),r||e.close()})))})}migrations(e){return we(this,void 0,void 0,function*(){const t=[];yield ie(Object.keys(e.models),i=>we(this,void 0,void 0,function*(){var r;const n=e.models[i],{version:s}=ke.migrations(n);if(!s)return;const[o,d]=null!==(r=yield tt.findOrCreate({where:{model:n.tableName},defaults:{model:n.tableName,version:""}}).catch(this.error))&&void 0!==r?r:[];o&&(d||o.version!=s)&&(o.version=s,yield o.save().catch(this.error),t.push(n))})),t.length&&(yield q(e,t))})}websocket(){return this._webSocket}}class pt extends se{auth(e,t,i,r,n){return we(this,void 0,void 0,function*(){var s;const[o,d]=null!==(s=null==i?void 0:i.split(" "))&&void 0!==s?s:["",""];if(!d||o.toLowerCase()!=Be.API_TOKEN_HEADER_KEY)return e.error("INVALID TOKEN");const{auth:a,error:u,user:p}=yield at.user(t,d,n);return u?e.error(u):a&&p?a.user_agent&&a.user_agent!=r?e.error("INVALID TOKEN"):(e.req.auth=a,e.req.user=p,void e.next()):e.error("INTERNAL SERVER ERROR")})}canCreate(e,t,i){return we(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".create",i)})}canDelete(e,t,i){return we(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".delete",i)})}canRead(e,t,i){return we(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".read",i)})}canUpdate(e,t,i){return we(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".update",i)})}error(e){let t="controller_base";Be.API_BASE_NAME&&(t=`${Be.API_BASE_NAME}.${t}`),rt.error(e.message,t,Be.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,i){return we(this,void 0,void 0,function*(){if(i){if((yield this.permissions(i,{route:t})).length>0)return e.next()}e.unauthorized("ACCESS DENIED")})}permissions(e,t){return we(this,void 0,void 0,function*(){var i;return null!==(i=yield Ze.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:Qe,required:!0,include:[{model:Ve,required:!0,where:{state:!0},include:[{model:$e,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error))&&void 0!==i?i:[]})}session(e,t,i){return we(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()})}sync(){return we(this,void 0,void 0,function*(){})}upload(e,t){t.path||(t.path=Be.API_UPLOAD_TEMP),t.size||(t.size=Be.API_UPLOAD_SIZE),t.field||(t.field=Be.API_UPLOAD_FIELD),a.middleware(e,t)}validation(e,t){return we(this,void 0,void 0,function*(){const{error:i,value:r}=yield oe.object(t).parse().validateAsync(e.req.body);if(i)return e.validation(i);e.req.body=r,e.next()})}}De([Ne(0,i()),Ne(1,r(Be.API_KEY_HEADER)),Ne(2,r(Be.API_TOKEN_HEADER)),Ne(3,r("user-agent")),Ne(4,n()),be("design:type",Function),be("design:paramtypes",[s,String,String,String,ut]),be("design:returntype",Promise)],pt.prototype,"auth",null),De([Ne(0,i()),Ne(1,o()),Ne(2,je()),be("design:type",Function),be("design:paramtypes",[s,String,We]),be("design:returntype",Promise)],pt.prototype,"canCreate",null),De([Ne(0,i()),Ne(1,o()),Ne(2,je()),be("design:type",Function),be("design:paramtypes",[s,String,We]),be("design:returntype",Promise)],pt.prototype,"canDelete",null),De([Ne(0,i()),Ne(1,o()),Ne(2,je()),be("design:type",Function),be("design:paramtypes",[s,String,We]),be("design:returntype",Promise)],pt.prototype,"canRead",null),De([Ne(0,i()),Ne(1,o()),Ne(2,je()),be("design:type",Function),be("design:paramtypes",[s,String,We]),be("design:returntype",Promise)],pt.prototype,"canUpdate",null),De([Ne(0,i()),Ne(1,o()),Ne(2,je()),be("design:type",Function),be("design:paramtypes",[s,String,We]),be("design:returntype",Promise)],pt.prototype,"permission",null),De([Ne(0,i()),Ne(1,r("user-agent")),Ne(2,d()),be("design:type",Function),be("design:paramtypes",[s,String,Object]),be("design:returntype",Promise)],pt.prototype,"session",null),De([Ne(0,i()),Ne(1,o()),be("design:type",Function),be("design:paramtypes",[s,Object]),be("design:returntype",void 0)],pt.prototype,"upload",null),De([Ne(0,i()),Ne(1,o()),be("design:type",Function),be("design:paramtypes",[s,Object]),be("design:returntype",Promise)],pt.prototype,"validation",null);class ct{}var lt,yt;ct.ATTRIBUTES=Symbol("ATTRIBUTES"),ct.PERMISSIONS=Symbol("PERMISSIONS");let gt=class extends pt{constructor(){super(...arguments),this[lt]=[],this[yt]=["create","read","update","delete"]}attributes(e){if(0==this[ct.ATTRIBUTES].length&&(this[ct.ATTRIBUTES]=Object.keys(this.model().getAttributes())),de(e))return e.length?e.map(e=>ae(e)&&-1!=this[ct.ATTRIBUTES].indexOf(e)?e:void 0).filter(ae):this[ct.ATTRIBUTES];const{exclude:t,include:i}=e,r=ue(i)?this[ct.ATTRIBUTES]:i.map(e=>ae(e)&&-1!=this[ct.ATTRIBUTES].indexOf(e)?e:void 0).filter(ae),n=null!=t?t:[];return n.length?r.filter(e=>-1==n.indexOf(e)?e:void 0).filter(ae):r}create(e){return we(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||{}),Ce(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")})}delete(e){return we(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 n=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:r}),individualHooks:!0}),Ce(e))).catch(this.error);return n?(e.success("OK"),n):(e.notFound("RECORD NOT FOUND"),0)})}error(e){let t="controller_model";Be.API_BASE_NAME&&(t=`${Be.API_BASE_NAME}.${t}`),(null==e?void 0:e.sql)?rt.error((null==e?void 0:e.message)+"\n"+(null==e?void 0:e.sql),t,Be.API_CONSOLE_ERROR):super.error(e)}findAll(e){return we(this,arguments,void 0,function*({ctx:e,options:t,callback:i,scope:r,advanced:n,attributes:s,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(ue(l.limit)){const e=pe(ae(y)?parseInt(y)||0:Be.API_MODEL_LIMIT,-1,Be.API_MODEL_LIMIT_MAX);l.limit=e>0?e:o?void 0:Be.API_MODEL_LIMIT}if(ce(l.limit)&&(l.limit=l.limit>0?l.limit:void 0),ae(g)){const e=g&&parseInt(g)||0;l.offset=e>0?e:void 0}s=null!=s?s:this.attributes(null!==(d=null==l?void 0:l.attributes)&&void 0!==d?d:[]);const E=[],A=e=>s.indexOf(e)>=0;if(ae(h)&&h.length&&E.push(...h.split(";").filter(A).map(e=>[e,"ASC"])),ae(v)&&v.length&&E.push(...v.split(";").filter(A).map(e=>[e,"DESC"])),E.length&&(l.order=E),l.where=Object.assign({},l.where||{}),ae(m)&&(null==n||n)){const t=Y.parse(s,m);if(!ue(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=[];s.forEach(t=>{ae(_)&&_.length&&e.push({[t]:{[ve.like]:`%${_}%`}})}),e.length&&(l.where=Object.assign(Object.assign({},l.where),{[ve.or]:[...e]}))}const O=c.count(Object.assign(Object.assign({},l),{distinct:!!l.include,col:this[ct.ATTRIBUTES].length?this[ct.ATTRIBUTES][0]:void 0})).catch(this.error),I=c.findAll(l).catch(this.error);yield Promise.allSettled([O,I]);const P=null!==(u=yield O)&&void 0!==u?u:0;let f=yield I;const R={count:P};return f?(f=i?yield i(f):f,(ce(null==t?void 0:t.limit)||0==P)&&(R.count=f.length),e.prepare(p.OK,Object.assign(Object.assign({},R),{records:f})),Object.assign(Object.assign({},R),{records:f})):(e.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},R),{records:[]}))})}findOne(e){return we(this,arguments,void 0,function*({ctx:e,options:t,callback:i,scope:r}){const n=this.key(),{[n]:s}=e.req.params,o=yield this.scope(r).findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[n]:s})})).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")})}sync(){return we(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield ie(this[ct.PERMISSIONS],i=>we(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=le(e.replace(/_/g," ")," ");yield Ze.findOrCreate({where:{route:r},defaults:Object.assign({name:`${n} ${le(i," ")}`,route:r,tag:n},t)})}))})}update(e){return we(this,arguments,void 0,function*({ctx:e,options:t,body:i}){var r;const n=this.key(),{[n]:s}=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),{[n]:s}),individualHooks:!0}),Ce(e))).catch(this.error))&&void 0!==r?r:[];return o?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)})}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}};lt=ct.ATTRIBUTES,yt=ct.PERMISSIONS,gt=De([u(pt)],gt);let ht=class extends gt{model(){return ze}all(e,t,i){return we(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:r,order:[["created_at","DESC"]]},unlimited:!0})})}get(e){return we(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};De([c(),l("auth"),l("canRead"),Ne(0,i()),Ne(1,y("type")),Ne(2,y("table")),be("design:type",Function),be("design:paramtypes",[s,String,String]),be("design:returntype",Promise)],ht.prototype,"all",null),De([c("/:id"),l("auth"),l("canRead"),Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],ht.prototype,"get",null),ht=De([g("/audits"),u(gt)],ht);let vt=class extends pt{login(e,t,i,r,n){return we(this,void 0,void 0,function*(){var s;yield ne(Be.API_SLEEP_AUTH);const o=yield We.scope("password").findOne({where:{[ve.or]:[{email:i},{username:i}]}}).catch(this.error);if(r+=null!==(s=null==o?void 0:o.salt)&&void 0!==s?s:"",!o||o.password!=J(r))return e.notFound("INVALID USERNAME OR PASSWORD"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const d=yield Ye.findOne({where:{state:!0,user_id:o.id}}).catch(this.error);if(d)return e.error("ACTIVATION REQUIRED"),n.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"),n.emit("auth.failure",{ctx:e,user:o}),void this.emit("auth.failure",{ctx:e,user:o});const{auth:a,error:u,token:p}=yield at.create(o);return u?(e.error(u),n.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}),n.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"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))})}logout(e,t,i,r){return we(this,void 0,void 0,function*(){if(yield at.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 we(this,void 0,void 0,function*(){const{auth:n,error:s,token:o}=yield at.renew(i);return s?e.error(s):n?(n.user_agent=t,yield n.save().catch(this.error),e.json({token:o}),r.emit("auth.renew",{auth:n,ctx:e}),void this.emit("auth.renew",{auth:n,ctx:e})):e.error("INTERNAL SERVER ERROR")})}user(e,t){return we(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({},ye(["username","date","description","state","created_at","updated_at","deleted_at"],t.toJSON())),{permissions:i.map(e=>e.route)}))})}};var _t;De([h("/login"),l("validation",{username:oe.string().min(3).required(),password:oe.string().min(5).required()}),Ne(0,i()),Ne(1,r("user-agent")),Ne(2,v("username")),Ne(3,v("password")),Ne(4,n()),be("design:type",Function),be("design:paramtypes",[s,String,String,String,ut]),be("design:returntype",Promise)],vt.prototype,"login",null),De([c("/logout"),l("auth"),Ne(0,i()),Ne(1,xe()),Ne(2,je()),Ne(3,n()),be("design:type",Function),be("design:paramtypes",[s,qe,We,ut]),be("design:returntype",Promise)],vt.prototype,"logout",null),De([h("/renew"),l("validation",{token:oe.string().required()}),Ne(0,i()),Ne(1,r("user-agent")),Ne(2,v("token")),Ne(3,n()),be("design:type",Function),be("design:paramtypes",[s,String,String,ut]),be("design:returntype",Promise)],vt.prototype,"renew",null),De([c(),l("auth"),Ne(0,i()),Ne(1,je()),be("design:type",Function),be("design:paramtypes",[s,We]),be("design:returntype",Promise)],vt.prototype,"user",null),vt=De([g("/auth"),u(pt)],vt);let mt=class extends pt{constructor(){super(...arguments),this[_t]=["delete","download","edit","list","read","rename","upload","write"]}directory(){return Be.API_HTTP_PUBLIC||"./"}files(e){return we(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=Te(this.directory(),t);if(!Ee(i)||!Ae(i).isDirectory())return e.notFound("RECORD NOT FOUND");let r=[];return r=Oe(i),r=r.map(e=>this.info(Te(i,e))),r=r.filter(ge),Object.assign(Object.assign({},this.info(i)),{files:r})})}access(e,t,i){return we(this,void 0,void 0,function*(){yield this.permission(e,this.name()+"."+t,i)})}info(e){if(!Ee(e))return null;const t=Ae(e),i=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const r=t.isDirectory();return{name:i,path:e.replace(/^\/\//,"/"),size:t.size,extension:r?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:r,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return we(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=le(e.replace(/_/g," ")," "),i={description:"",state:!0};yield ie(this[ct.PERMISSIONS],r=>we(this,void 0,void 0,function*(){const n=`${e}.${r}`;yield Ze.findOrCreate({where:{route:n},defaults:Object.assign({name:`${t} ${le(r," ")}`,route:n,tag:t},i)})}))})}};_t=ct.PERMISSIONS,De([c("/path"),c("/path/*path"),l("auth"),l("access","list"),Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],mt.prototype,"files",null),De([Ne(0,i()),Ne(1,o()),Ne(2,je()),be("design:type",Function),be("design:paramtypes",[s,String,We]),be("design:returntype",Promise)],mt.prototype,"access",null),mt=De([g("/files"),u(pt)],mt);let Et=class extends pt{check(e,t){return we(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.notFound("RECORD NOT FOUND");i.token=he(),yield i.save(),e.json({token:i.token})})}forgot(e,t,i){return we(this,void 0,void 0,function*(){yield ne(Be.API_SLEEP_FORGOT);const r=t,n=yield We.findOne({where:{[ve.or]:[{email:r},{username:t}]}}).catch(this.error);if(!n)return e.notFound("RECORD NOT FOUND");const s=he(),o=Date.now()+6e4*Be.API_TOKEN_FORGOT,d=yield Xe.create({token:s,timestamp:o,state:!0,user_id:n.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:d,user:n}),this.emit("forgot.send",{ctx:e,forgot:d,user:n})})}reset(e,t,i,r){return we(this,void 0,void 0,function*(){const n=yield this.find(t);if(!n)return e.notFound("RECORD NOT FOUND");n.state=!1,yield n.save().catch(this.error),n.user.password=J(i),yield n.user.save().catch(this.error),e.success("OK"),r.emit("forgot.reset",{ctx:e,user:n.user}),this.emit("forgot.reset",{ctx:e,user:n.user})})}find(e){return we(this,void 0,void 0,function*(){return yield Xe.findOne({where:{token:e,state:!0},include:[{model:We,required:!0}]}).catch(this.error)})}};De([c("/check"),l("validation",{token:oe.string().required()}),Ne(0,i()),Ne(1,v("token")),be("design:type",Function),be("design:paramtypes",[s,String]),be("design:returntype",Promise)],Et.prototype,"check",null),De([h(),l("validation",{username:oe.string().min(4).required()}),Ne(0,i()),Ne(1,v("username")),Ne(2,n()),be("design:type",Function),be("design:paramtypes",[s,String,ut]),be("design:returntype",Promise)],Et.prototype,"forgot",null),De([h("/reset"),l("validation",{token:oe.string().required(),password:oe.string().min(5).required()}),Ne(0,i()),Ne(1,v("token")),Ne(2,v("password")),Ne(3,n()),be("design:type",Function),be("design:paramtypes",[s,String,String,ut]),be("design:returntype",Promise)],Et.prototype,"reset",null),Et=De([g("/forgot"),u(pt)],Et);let At=class extends gt{constructor(){super(...arguments),this._crud={}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return we(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return we(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}del(e){return we(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return we(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return we(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return we(this,void 0,void 0,function*(){const t=this.CrudValidationCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}validationUpdate(e){return we(this,void 0,void 0,function*(){const t=this.CrudValidationUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}};De([h(),l("auth"),l("canCreate"),l("validationCreate"),Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],At.prototype,"add",null),De([c(),l("auth"),l("canRead"),Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],At.prototype,"all",null),De([_("/:id"),l("auth"),l("canDelete"),Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],At.prototype,"del",null),De([c("/:id"),l("auth"),l("canRead"),Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],At.prototype,"get",null),De([m("/:id"),l("auth"),l("canUpdate"),l("validationUpdate"),Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],At.prototype,"set",null),De([Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],At.prototype,"validationCreate",null),De([Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],At.prototype,"validationUpdate",null),At=De([u(gt)],At);let Ot=class extends At{constructor(){super(...arguments),this.schemaCreate={name:oe.string().required(),description:oe.string().empty(""),state:oe.boolean().parse().required()},this.schemaUpdate={name:oe.string().empty(),description:oe.string().empty(),state:oe.boolean().parse().empty()}}model(){return Ve}CrudArgumentsFindAll(e){return{ctx:e,unlimited:!0}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};Ot=De([g("/groups"),u(At)],Ot);let It=class extends gt{model(){return Qe}all(e,t){return we(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:Ze,required:!0}]},unlimited:!0,callback:e=>e.map(e=>e.permission)})})}me(e,t){return we(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,i,r){return we(this,void 0,void 0,function*(){const n=yield Ve.findByPk(t,{attributes:["id"]}).catch(this.error);if(!n)return e.notFound("RECORD NOT FOUND");const s=n.id;if(yield Qe.destroy(Object.assign({where:{group_id:s},individualHooks:!0},r)),i){let e=0;yield ne(1e3);for(let t=0;t<i.length;t++)e=yield Ze.count({where:{id:i[t]}}),e&&(yield Qe.create({group_id:s,permission_id:i[t]},Object.assign({},r)))}e.success("OK")})}};var Pt;De([c("/:id/permissions"),l("auth"),l("canRead","groups"),Ne(0,i()),Ne(1,E("id")),be("design:type",Function),be("design:paramtypes",[s,String]),be("design:returntype",Promise)],It.prototype,"all",null),De([c("/permissions"),l("auth"),l("canRead","users"),Ne(0,i()),Ne(1,je()),be("design:type",Function),be("design:paramtypes",[s,We]),be("design:returntype",Promise)],It.prototype,"me",null),De([m("/:id/permissions"),l("auth"),l("canUpdate","groups"),l("validation",{permissions:oe.array(oe.number().parse())}),Ne(0,i()),Ne(1,E("id")),Ne(2,v("permissions")),Ne(3,Fe()),be("design:type",Function),be("design:paramtypes",[s,String,Array,Object]),be("design:returntype",Promise)],It.prototype,"set",null),It=De([g("/groups"),u(gt)],It);let ft=class extends gt{constructor(){super(...arguments),this[Pt]=["read"]}model(){return et}all(e,t,i){return we(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.source=i),yield this.findAll({ctx:e,options:{where:r,order:[["created_at","DESC"]]},unlimited:!0})})}};Pt=ct.PERMISSIONS,De([c(),l("auth"),l("canRead"),Ne(0,i()),Ne(1,y("type")),Ne(2,y("source")),be("design:type",Function),be("design:paramtypes",[s,String,String]),be("design:returntype",Promise)],ft.prototype,"all",null),ft=De([g("/logs"),u(gt)],ft);let Rt=class extends At{constructor(){super(...arguments),this.schemaCreate={name:oe.string().required(),route:oe.string().required(),tag:oe.string().required(),description:oe.string().empty(""),state:oe.boolean().parse().required()},this.schemaUpdate={name:oe.string().empty(),route:oe.string().empty(),tag:oe.string().empty(),description:oe.string().empty(),state:oe.boolean().parse().empty()}}model(){return Ze}CrudArgumentsFindAll(e){return{ctx:e,unlimited:!0}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};Rt=De([g("/permissions"),u(At)],Rt);let St=class extends pt{register(e,t,i){return we(this,void 0,void 0,function*(){yield ne(Be.API_SLEEP_REGISTRY);const{name:r,date:n,email:s,username:o,password:d,confirm:a}=t,u=o||s,p=J(d);if(yield We.count({where:{[ve.or]:[{email:s},{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:s,username:u,password:p,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!c)return e.error("INTERNAL SERVER ERROR");const l=yield Ye.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 we(this,void 0,void 0,function*(){const r=yield Ye.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 we(this,void 0,void 0,function*(){const r=t,n=yield Ye.findOne({where:{state:!0},include:[{model:We,required:!0,where:{[ve.or]:[{email:r},{username:t}]}}]}).catch(this.error);if(!n)return e.notFound("RECORD NOT FOUND");e.success("OK"),i.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})})}getId(){return we(this,void 0,void 0,function*(){const e=te();return(yield Ye.count({where:{token:e}}))?this.getId():e})}};De([h(),l("validation",{name:oe.string().required(),date:oe.date().required(),email:oe.string().email().required(),username:oe.string().min(4).empty(),password:oe.string().min(5).required(),confirm:oe.string().min(5).required()}),Ne(0,i()),Ne(1,v()),Ne(2,n()),be("design:type",Function),be("design:paramtypes",[s,Object,ut]),be("design:returntype",Promise)],St.prototype,"register",null),De([h("/confirm"),l("validation",{token:oe.string().required()}),Ne(0,i()),Ne(1,v("token")),Ne(2,n()),be("design:type",Function),be("design:paramtypes",[s,String,ut]),be("design:returntype",Promise)],St.prototype,"confirm",null),De([h("/send"),l("validation",{username:oe.string().min(4).required()}),Ne(0,i()),Ne(1,v("username")),Ne(2,n()),be("design:type",Function),be("design:paramtypes",[s,String,ut]),be("design:returntype",Promise)],St.prototype,"send",null),St=De([g("/register"),u(pt)],St);let Tt=class extends pt{setup(e,t){return we(this,void 0,void 0,function*(){var i;if(yield We.count())return e.success("OK");const r=he(),n=yield We.create({name:"Admin",email:"admin@localhost",username:"admin",password:J("admin"+r),salt:r,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},t)),s=yield Ve.create(Object.assign({name:"Admin"},{description:"API CORE",state:!0}),Object.assign({},t));yield $e.create({user_id:n.id,group_id:s.id},Object.assign({},t));const o=null!==(i=yield Ze.findAll({where:{state:!0}}).catch(this.error))&&void 0!==i?i:[];yield ie(o,e=>we(this,void 0,void 0,function*(){yield Qe.create({group_id:s.id,permission_id:e.id},Object.assign({},t))})),e.success("OK")})}};De([c(),Ne(0,i()),Ne(1,Fe()),be("design:type",Function),be("design:paramtypes",[s,Object]),be("design:returntype",Promise)],Tt.prototype,"setup",null),Tt=De([g("/setup"),u(pt)],Tt);let Dt=class extends gt{model(){return We}constructor(){super(),this.path=Be.API_HTTP_PUBLIC+"/avatar",Be.API_HTTP_PUBLIC&&Ee(Be.API_HTTP_PUBLIC)&&!Ee(this.path)&&Ie(this.path)}avatar(e,t,i,r){return we(this,void 0,void 0,function*(){if(t.length){const n=t[0].filename||"";if(n){const t=this.path+"/"+i.avatar;if(Ee(t)&&Pe(t).isFile()&&fe(t),i.avatar=n,yield i.save(Object.assign({},r)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")})}avatar_del(e,t,i){return we(this,void 0,void 0,function*(){const r=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},i)).catch(this.error))&&Ee(r)&&fe(r),e.success("OK")})}password(e,t,i,r,n){return we(this,void 0,void 0,function*(){var s;if(Be.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!==(s=null==o?void 0:o.salt)&&void 0!==s?s:"",o&&o.password==J(t)?(o.salt=he(),o.password=J(i+o.salt),(yield o.save(Object.assign({},n)).catch(this.error))?e.success("OK"):void e.success("RECORD NOT CHANGED")):e.error("INVALID PASSWORD")})}token(e,t,i){return we(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_del(e,t,i){return we(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_get(e,t,i){return we(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_renew(e,t,i,r){return we(this,void 0,void 0,function*(){const n=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(n){const t=yield this.token_new();return n.token=r.hash.encrypt(t),yield n.save(Object.assign({},i)).catch(this.error),e.json({token:t})}e.notFound("RECORD NOT FOUND")})}token_new(){return we(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 we(this,void 0,void 0,function*(){const i=he(),r=yield this.create({ctx:e,body:{password:J(t+i),salt:i}});Be.API_USER_HISTORY&&r&&(yield Ge.create({password:J(t+r.id),user_id:r.id}))})}all(e){return we(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{attributes:{exclude:["password","salt","token"]}},unlimited:!0})})}del(e,t,i){return we(this,void 0,void 0,function*(){if(i.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this.delete({ctx:e})})}get(e){return we(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e,t,i){return we(this,void 0,void 0,function*(){if(Be.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?he():"";yield this.update({ctx:e,body:i?{password:J(i+r),salt:r}:{}})})}};De([h("/avatar"),l("auth"),l("upload",e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32})),Ne(0,i()),Ne(1,A()),Ne(2,je()),Ne(3,Fe()),be("design:type",Function),be("design:paramtypes",[s,Array,We,Object]),be("design:returntype",Promise)],Dt.prototype,"avatar",null),De([_("/avatar"),l("auth"),Ne(0,i()),Ne(1,je()),Ne(2,Fe()),be("design:type",Function),be("design:paramtypes",[s,We,Object]),be("design:returntype",Promise)],Dt.prototype,"avatar_del",null),De([h("/password"),l("auth"),l("validation",{oldPassword:oe.string().min(5).required(),newPassword:oe.string().min(5).required(),confirmPassword:oe.string().equal(oe.ref("newPassword"))}),Ne(0,i()),Ne(1,v("oldPassword")),Ne(2,v("newPassword")),Ne(3,je()),Ne(4,Fe()),be("design:type",Function),be("design:paramtypes",[s,String,String,We,Object]),be("design:returntype",Promise)],Dt.prototype,"password",null),De([c("/token"),l("auth"),Ne(0,i()),Ne(1,je()),Ne(2,n()),be("design:type",Function),be("design:paramtypes",[s,We,ut]),be("design:returntype",Promise)],Dt.prototype,"token",null),De([_("/token/:id"),l("auth"),l("canDelete"),Ne(0,i()),Ne(1,E("id")),Ne(2,Fe()),be("design:type",Function),be("design:paramtypes",[s,String,Object]),be("design:returntype",Promise)],Dt.prototype,"token_del",null),De([c("/token/:id"),l("auth"),l("canCreate"),Ne(0,i()),Ne(1,E("id")),Ne(2,n()),be("design:type",Function),be("design:paramtypes",[s,String,ut]),be("design:returntype",Promise)],Dt.prototype,"token_get",null),De([c("/token/renew/:id"),l("auth"),l("canUpdate"),Ne(0,i()),Ne(1,E("id")),Ne(2,Fe()),Ne(3,n()),be("design:type",Function),be("design:paramtypes",[s,String,Object,ut]),be("design:returntype",Promise)],Dt.prototype,"token_renew",null),De([h(),l("auth"),l("canCreate"),l("validation",{name:oe.string().required(),email:oe.string().email().required(),username:oe.string().min(4).required(),password:oe.string().min(5).required(),description:oe.string().empty(""),state:oe.boolean().parse().required()}),Ne(0,i()),Ne(1,v("password")),be("design:type",Function),be("design:paramtypes",[s,String]),be("design:returntype",Promise)],Dt.prototype,"add",null),De([c(),l("auth"),l("canRead"),Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],Dt.prototype,"all",null),De([_("/:id"),l("auth"),l("canDelete"),Ne(0,i()),Ne(1,E("id")),Ne(2,je()),be("design:type",Function),be("design:paramtypes",[s,String,We]),be("design:returntype",Promise)],Dt.prototype,"del",null),De([c("/:id"),l("auth"),l("canRead"),Ne(0,i()),be("design:type",Function),be("design:paramtypes",[s]),be("design:returntype",Promise)],Dt.prototype,"get",null),De([m("/:id"),l("auth"),l("canUpdate"),l("validation",{name:oe.string().empty(),email:oe.string().email().empty(),username:oe.string().min(4).empty(),password:oe.string().min(5).empty().filter(""),description:oe.string().empty(),state:oe.boolean().parse().empty()}),Ne(0,i()),Ne(1,E("id")),Ne(2,v("password")),be("design:type",Function),be("design:paramtypes",[s,String,String]),be("design:returntype",Promise)],Dt.prototype,"set",null),Dt=De([g("/users"),u(gt),be("design:paramtypes",[])],Dt);let Nt=class extends gt{model(){return $e}all(e,t){return we(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:Ve,required:!0}]},unlimited:!0,callback:e=>e.map(e=>e.group)})})}me(e,t){return we(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,i,r){return we(this,void 0,void 0,function*(){const n=yield We.findByPk(t,{attributes:["id"]}).catch(this.error);if(!n)return e.notFound("RECORD NOT FOUND");if(yield $e.destroy(Object.assign({where:{user_id:n.id},individualHooks:!0},r)),i){let e=0;yield ne(1e3);for(let t=0;t<i.length;t++)e=yield Ve.count({where:{id:i[t]}}),e&&(yield $e.create({user_id:n.id,group_id:i[t]},Object.assign({},r)))}e.success("OK")})}};De([c("/:id/groups"),l("auth"),l("canRead","users"),Ne(0,i()),Ne(1,E("id")),be("design:type",Function),be("design:paramtypes",[s,String]),be("design:returntype",Promise)],Nt.prototype,"all",null),De([c("/groups"),l("auth"),l("canRead","users"),Ne(0,i()),Ne(1,je()),be("design:type",Function),be("design:paramtypes",[s,We]),be("design:returntype",Promise)],Nt.prototype,"me",null),De([m("/:id/groups"),l("auth"),l("canUpdate","users"),l("validation",{groups:oe.array(oe.number().parse())}),Ne(0,i()),Ne(1,E("id")),Ne(2,v("groups")),Ne(3,Fe()),be("design:type",Function),be("design:paramtypes",[s,String,Array,Object]),be("design:returntype",Promise)],Nt.prototype,"set",null),Nt=De([g("/users"),u(gt)],Nt);class bt{static all(){return we(this,void 0,void 0,function*(){const e=yield Je.findAll().catch(bt.error),t={};return e&&e.forEach(e=>t[e.key]=e.value),t})}static del(e,t){return we(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 Je.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:r})).catch(bt.error))||0)>0})}static error(e){let t="config";Be.API_BASE_NAME&&(t=`${Be.API_BASE_NAME}.${t}`),rt.error(e.message,t,Be.API_CONSOLE_ERROR)}static get(e){return we(this,arguments,void 0,function*(e,t=""){const[i]=(yield Je.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(bt.error))||[];return i?i.value:t})}static set(e,t,i){return we(this,void 0,void 0,function*(){var r;const n=null!==(r=null==i?void 0:i.id)&&void 0!==r?r:null,[s]=(yield Je.findOrCreate(Object.assign({where:{key:e}},{user_id:n})).catch(bt.error))||[];s&&(s.value=t,yield s.save().catch(bt.error))})}}export{ut as Application,ze as Audit,ht as AuditsController,qe as Auth,vt as AuthController,bt as Config,Je as Configs,pt as ControllerBase,ct as ControllerKeys,At as CrudController,Be as Env,mt as FilesController,Xe as Forgot,Et as ForgotController,Ve as Group,Qe as GroupPermission,Ot as GroupsController,It as GroupsPermissionsController,et as Log,rt as Logs,ft as LogsController,ke as Metadata,Le as Migrate,tt as Migration,Me as Model,gt as ModelController,Ze as Permission,Rt as PermissionsController,Ye as Register,St as RegisterController,Fe as ReqAudit,xe as ReqAuth,je as ReqUser,it as Session,Tt as SetupController,dt as Store,at as Token,We as User,$e as UserGroup,Ge as UserHistory,Dt as UsersController,Nt as UsersGroupsController,Ce as audit,st as crt,Ue as database,Ke as hooks,ot as key};
|
|
7
|
+
import{Env as e,Metadata as t,Log as i,LogColor as r,Hash as s,sha256 as n}from"@andrewcaires/node";import{config as o}from"dotenv";import{EventEmitter as d,isObject as a,noop as u,uuidv4 as c,loop as p,forEachSeries as l,isFunction as y,sleep as g,upperCamelCase as h,Validation as v,isArray as _,isString as m,isUndefined as E,clamp as A,isNumber as O,denied as I,isDef as f,uniqueID as P}from"@andrewcaires/utils.js";import{parameterFactory as R,Application as S,Ctx as T,Headers as D,Query as N,App as b,Context as w,Argument as C,Session as x,Upload as F,Extends as j,Status as k,Post as L,Middleware as U,Get as B,Delete as M,Put as H,Controller as K,Body as q,Params as Y,Files as V}from"@andrewcaires/express";import{Model as $,Connection as G,Id as W,String as z,FullDate as J,CreatedAt as Z,UpdatedAt as X,DeletedAt as Q,BelongsTo as ee,Database as te,ModelName as ie,Boolean as re,Text as se,HasMany as ne,Hooks as oe,DateOnly as de,DefaultScope as ae,Scopes as ue,Enum as ce,Json as pe,BigInt as le,Unique as ye,migrate as ge,Where as he}from"@andrewcaires/sequelize";import ve from"jsonwebtoken";import{readFileSync as _e,existsSync as me,statSync as Ee,readdirSync as Ae,mkdirSync as Oe,lstatSync as Ie,rmSync as fe}from"fs";import{WebSocketServer as Pe}from"ws";import{Store as Re}from"express-session";import{Op as Se}from"sequelize";import{join as Te}from"path";o({quiet:!0});class De extends e{}De.API_BASE_NAME=De.getString("API_BASE_NAME",""),De.API_BODYPARSER_STRICT=De.getBool("API_BODYPARSER_STRICT",!0),De.API_BODYPARSER_INFLATE=De.getBool("API_BODYPARSER_INFLATE",!0),De.API_BODYPARSER_LIMIT=De.getString("API_BODYPARSER_LIMIT","10mb"),De.API_BODYPARSER_TYPE=De.getString("API_BODYPARSER_TYPE","json"),De.API_CONSOLE_ERROR=De.getBool("API_CONSOLE_ERROR",!1),De.API_DB_DATABASE=De.getString("API_DB_DATABASE",""),De.API_DB_HOST=De.getString("API_DB_HOST","127.0.0.1"),De.API_DB_PASSWORD=De.getString("API_DB_PASSWORD",""),De.API_DB_PORT=De.getInt("API_DB_PORT",3306),De.API_DB_TYPE=De.getString("API_DB_TYPE",""),De.API_DB_USERNAME=De.getString("API_DB_USERNAME","root"),De.API_DB_LOG=De.getBool("API_DB_LOG",!1),De.API_DB_AUDIT=De.getBool("API_DB_AUDIT",!0),De.API_DB_PREFIX=De.getString("API_DB_PREFIX",""),De.API_DB_TIMEZONE=De.getString("API_DB_TIMEZONE","+00:00"),De.API_HTTP_CRT=De.getString("API_HTTP_CRT",""),De.API_HTTP_KEY=De.getString("API_HTTP_KEY",""),De.API_HTTP_PORT=De.getInt("API_HTTP_PORT",3e3),De.API_HTTP_PUBLIC=De.getString("API_HTTP_PUBLIC",""),De.API_HTTP_CROSS=De.getBool("API_HTTP_CROSS",!1),De.API_HTTP_HYBRID=De.getBool("API_HTTP_HYBRID",!1),De.API_HTTP_NOTFOUND=De.getString("API_HTTP_NOTFOUND",""),De.API_HTTP_PATH=De.getString("API_HTTP_PATH","/api"),De.API_HTTP_REDIRECT=De.getString("API_HTTP_REDIRECT",""),De.API_KEY_HASH=De.getString("API_KEY_HASH",""),De.API_KEY_HEADER=De.getString("API_KEY_HEADER","x-api-key"),De.API_MODEL_LIMIT=De.getInt("API_MODEL_LIMIT",10),De.API_MODEL_LIMIT_MAX=De.getInt("API_MODEL_LIMIT_MAX",500),De.API_SLEEP_AUTH=De.getMs("API_SLEEP_AUTH","2s"),De.API_SLEEP_FORGOT=De.getMs("API_SLEEP_FORGOT","5s"),De.API_SLEEP_REGISTRY=De.getMs("API_SLEEP_REGISTRY","5s"),De.API_SESSION_NAME=De.getString("API_SESSION_NAME","session.id"),De.API_SESSION_LIFETIME=De.getMs("API_SESSION_LIFETIME","1d"),De.API_SESSION_SECRET=De.getString("API_SESSION_SECRET","yoursecret"),De.API_TOKEN_CRT=De.getString("API_TOKEN_CRT",""),De.API_TOKEN_KEY=De.getString("API_TOKEN_KEY",""),De.API_TOKEN_FORGOT=De.getMs("API_TOKEN_LIFETIME","1d"),De.API_TOKEN_HEADER=De.getString("API_TOKEN_HEADER","authorization"),De.API_TOKEN_HEADER_KEY=De.getString("API_TOKEN_HEADER","bearer"),De.API_TOKEN_LIFETIME=De.getMs("API_TOKEN_LIFETIME","1d"),De.API_TOKEN_RENEW=De.getMs("API_TOKEN_RENEW","1d"),De.API_UPLOAD_COUNT=De.getInt("API_UPLOAD_COUNT",1),De.API_UPLOAD_FIELD=De.getString("API_UPLOAD_FIELD","upload"),De.API_UPLOAD_SIZE=De.getInt("API_UPLOAD_SIZE",2),De.API_UPLOAD_TEMP=De.getString("API_UPLOAD_TEMP","./temp"),De.API_USER_HISTORY=De.getBool("API_USER_HISTORY",!0),De.API_WEBSOCKET_START=De.getBool("API_WEBSOCKET_START",!1);class Ne extends d{}function be(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 we(e,t){return function(i,r){t(i,r,e)}}function Ce(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function xe(e,t,i,r){return new(i||(i=Promise))(function(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())})}Ne.ATTRIBUTES=Symbol("ATTRIBUTES"),Ne.PERMISSIONS=Symbol("PERMISSIONS"),"function"==typeof SuppressedError&&SuppressedError;const Fe=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=R(({ctx:e})=>Fe(e)),ke=R(({ctx:e})=>e.req.auth),Le=R(({ctx:e})=>e.req.user),Ue=e=>t=>{Be.migrations(t).version=e};class Be{static migrations(e){return t(Be.MIGRATE,e,{version:""})}}Be.MIGRATE=Symbol("MIGRATE");class Me extends ${static error(e){i.error(e.message)}}const He=new G({type:De.API_DB_TYPE,database:De.API_DB_DATABASE,username:De.API_DB_USERNAME,password:De.API_DB_PASSWORD,hostname:De.API_DB_HOST,hostport:De.API_DB_PORT,logging:De.API_DB_LOG,prefix:De.API_DB_PREFIX,timezone:De.API_DB_TIMEZONE}),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)=>xe(void 0,void 0,void 0,function*(){var i;if(!De.API_DB_AUDIT)return;const r=a(e)?e.constructor:null,s=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null;yield Je.create(Object.assign(Object.assign({},Ke("CREATE",r,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(u)}),afterUpdate:(e,t)=>xe(void 0,void 0,void 0,function*(){var i;if(!De.API_DB_AUDIT)return;const r=a(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 Je.create(Object.assign(Object.assign({},Ke("UPDATE",r,t)),{record:s?e.getDataValue(s):null,data:n,previously:e.previous()})).catch(u)}),afterDestroy:(e,t)=>xe(void 0,void 0,void 0,function*(){var i;if(!De.API_DB_AUDIT)return;const r=a(e)?e.constructor:null,s=null!==(i=null==r?void 0:r.primaryKeyAttribute)&&void 0!==i?i:null;yield Je.create(Object.assign(Object.assign({},Ke("DELETE",r,t)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(u)})};let Ye=class extends Me{};be([W(),Ce("design:type",Number)],Ye.prototype,"id",void 0),be([z(),Ce("design:type",z)],Ye.prototype,"secret",void 0),be([J(),Ce("design:type",Object)],Ye.prototype,"logout",void 0),be([z(),Ce("design:type",z)],Ye.prototype,"user_agent",void 0),be([Z,Ce("design:type",Date)],Ye.prototype,"created_at",void 0),be([X,Ce("design:type",Date)],Ye.prototype,"updated_at",void 0),be([Q,Ce("design:type",Object)],Ye.prototype,"deleted_at",void 0),be([ee(()=>ze),Ce("design:type",Number)],Ye.prototype,"user_id",void 0),Ye=be([te(He),ie("auth"),Ue("4.2.0")],Ye);let Ve=class extends Me{};be([W(),Ce("design:type",Number)],Ve.prototype,"id",void 0),be([z(),Ce("design:type",z)],Ve.prototype,"token",void 0),be([re(),Ce("design:type",re)],Ve.prototype,"state",void 0),be([Z,Ce("design:type",Date)],Ve.prototype,"created_at",void 0),be([X,Ce("design:type",Date)],Ve.prototype,"updated_at",void 0),be([Q,Ce("design:type",Object)],Ve.prototype,"deleted_at",void 0),be([ee(()=>ze),Ce("design:type",Number)],Ve.prototype,"user_id",void 0),Ve=be([te(He),ie("register"),Ue("4.2.0")],Ve);let $e=class extends Me{};be([W(),Ce("design:type",Number)],$e.prototype,"id",void 0),be([z(),Ce("design:type",z)],$e.prototype,"name",void 0),be([se(),Ce("design:type",z)],$e.prototype,"description",void 0),be([re(),Ce("design:type",re)],$e.prototype,"state",void 0),be([Z,Ce("design:type",Date)],$e.prototype,"created_at",void 0),be([X,Ce("design:type",Date)],$e.prototype,"updated_at",void 0),be([Q,Ce("design:type",Object)],$e.prototype,"deleted_at",void 0),be([ne(()=>Ge,"group_id"),Ce("design:type",Array)],$e.prototype,"groups_routes",void 0),be([ne(()=>Ge,"group_id"),Ce("design:type",Array)],$e.prototype,"users_groups",void 0),$e=be([te(He),ie("group"),oe(qe),Ue("4.2.0")],$e);let Ge=class extends Me{};be([Z,Ce("design:type",Date)],Ge.prototype,"created_at",void 0),be([ee(()=>$e),Ce("design:type",Number)],Ge.prototype,"group_id",void 0),be([ee(()=>ze),Ce("design:type",Number)],Ge.prototype,"user_id",void 0),Ge=be([te(He),ie("users_groups"),oe(qe),Ue("4.2.0")],Ge);let We=class extends Me{};be([z(),Ce("design:type",z)],We.prototype,"password",void 0),be([Z,Ce("design:type",Date)],We.prototype,"created_at",void 0),be([ee(()=>ze),Ce("design:type",Number)],We.prototype,"user_id",void 0),We=be([te(He),ie("users_histories"),Ue("4.2.0")],We);let ze=class extends Me{};be([W(),Ce("design:type",Number)],ze.prototype,"id",void 0),be([z(),Ce("design:type",z)],ze.prototype,"name",void 0),be([z(),Ce("design:type",z)],ze.prototype,"email",void 0),be([z(),Ce("design:type",z)],ze.prototype,"username",void 0),be([z(),Ce("design:type",z)],ze.prototype,"password",void 0),be([z(),Ce("design:type",z)],ze.prototype,"salt",void 0),be([z(),Ce("design:type",z)],ze.prototype,"token",void 0),be([z(),Ce("design:type",z)],ze.prototype,"avatar",void 0),be([de(),Ce("design:type",z)],ze.prototype,"date",void 0),be([se(),Ce("design:type",z)],ze.prototype,"description",void 0),be([re(),Ce("design:type",re)],ze.prototype,"state",void 0),be([Z,Ce("design:type",Date)],ze.prototype,"created_at",void 0),be([X,Ce("design:type",Date)],ze.prototype,"updated_at",void 0),be([Q,Ce("design:type",Object)],ze.prototype,"deleted_at",void 0),be([ne(()=>Je,"user_id"),Ce("design:type",Array)],ze.prototype,"audits",void 0),be([ne(()=>Ye,"user_id"),Ce("design:type",Array)],ze.prototype,"auths",void 0),be([ne(()=>Ve,"user_id"),Ce("design:type",Array)],ze.prototype,"registers",void 0),be([ne(()=>Ge,"user_id"),Ce("design:type",Array)],ze.prototype,"users_groups",void 0),be([ne(()=>We,"user_id"),Ce("design:type",Array)],ze.prototype,"users_histories",void 0),ze=be([te(He),ie("user"),ae({attributes:{exclude:["password","salt","token"]}}),ue({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),oe(qe),Ue("4.2.0")],ze);let Je=class extends Me{};be([W(),Ce("design:type",Number)],Je.prototype,"id",void 0),be([ce("CREATE","DELETE","UPDATE"),Ce("design:type",z)],Je.prototype,"type",void 0),be([z(),Ce("design:type",z)],Je.prototype,"model",void 0),be([z(),Ce("design:type",z)],Je.prototype,"record",void 0),be([pe(),Ce("design:type",Object)],Je.prototype,"data",void 0),be([pe(),Ce("design:type",Object)],Je.prototype,"previously",void 0),be([z(),Ce("design:type",z)],Je.prototype,"client",void 0),be([se(),Ce("design:type",z)],Je.prototype,"href",void 0),be([z(),Ce("design:type",z)],Je.prototype,"user_agent",void 0),be([re(),Ce("design:type",re)],Je.prototype,"state",void 0),be([Z,Ce("design:type",Date)],Je.prototype,"created_at",void 0),be([X,Ce("design:type",Date)],Je.prototype,"updated_at",void 0),be([Q,Ce("design:type",Object)],Je.prototype,"deleted_at",void 0),be([ee(()=>ze),Ce("design:type",Number)],Je.prototype,"user_id",void 0),Je=be([te(He),ie("audit"),Ue("4.2.0")],Je);let Ze=class extends Me{static all(){return xe(this,void 0,void 0,function*(){const e=yield this.findAll().catch(this.error),t={};return e&&e.forEach(e=>t[e.key]=e.value),t})}static del(e,t){return xe(this,void 0,void 0,function*(){var i;const r=null!==(i=null==t?void 0:t.id)&&void 0!==i?i:null;return((yield this.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:r})).catch(this.error))||0)>0})}static get(e){return xe(this,arguments,void 0,function*(e,t=""){const[i]=(yield this.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return i?i.value:t})}static set(e,t,i){return xe(this,void 0,void 0,function*(){var r;const s=null!==(r=null==i?void 0:i.id)&&void 0!==r?r:null,[n]=(yield this.findOrCreate(Object.assign({where:{key:e}},{user_id:s})).catch(this.error))||[];n&&(n.value=t,yield n.save().catch(this.error))})}};be([z(),Ce("design:type",z)],Ze.prototype,"key",void 0),be([z(),Ce("design:type",z)],Ze.prototype,"value",void 0),be([Z,Ce("design:type",Date)],Ze.prototype,"created_at",void 0),be([X,Ce("design:type",Date)],Ze.prototype,"updated_at",void 0),Ze=be([te(He),ie("configs"),oe(qe),Ue("4.2.0")],Ze);let Xe=class extends Me{};be([W(),Ce("design:type",Number)],Xe.prototype,"id",void 0),be([z(),Ce("design:type",z)],Xe.prototype,"token",void 0),be([le(),Ce("design:type",Number)],Xe.prototype,"timestamp",void 0),be([re(),Ce("design:type",re)],Xe.prototype,"state",void 0),be([Z,Ce("design:type",Date)],Xe.prototype,"created_at",void 0),be([X,Ce("design:type",Date)],Xe.prototype,"updated_at",void 0),be([Q,Ce("design:type",Object)],Xe.prototype,"deleted_at",void 0),be([ee(()=>ze),Ce("design:type",Number)],Xe.prototype,"user_id",void 0),Xe=be([te(He),ie("forgot"),Ue("4.2.0")],Xe);let Qe=class extends Me{};be([W(),Ce("design:type",Number)],Qe.prototype,"id",void 0),be([z(),Ce("design:type",z)],Qe.prototype,"name",void 0),be([z(),ye(!0),Ce("design:type",z)],Qe.prototype,"route",void 0),be([z(),Ce("design:type",z)],Qe.prototype,"tag",void 0),be([se(),Ce("design:type",z)],Qe.prototype,"description",void 0),be([re(),Ce("design:type",re)],Qe.prototype,"state",void 0),be([Z,Ce("design:type",Date)],Qe.prototype,"created_at",void 0),be([X,Ce("design:type",Date)],Qe.prototype,"updated_at",void 0),be([Q,Ce("design:type",Object)],Qe.prototype,"deleted_at",void 0),be([ne(()=>et,"permission_id"),Ce("design:type",Array)],Qe.prototype,"groups_permissions",void 0),Qe=be([te(He),ie("permission"),oe(qe),Ue("4.3.1")],Qe);let et=class extends Me{};var tt;be([Z,Ce("design:type",Date)],et.prototype,"created_at",void 0),be([ee(()=>$e),Ce("design:type",Number)],et.prototype,"group_id",void 0),be([ee(()=>Qe),Ce("design:type",Number)],et.prototype,"permission_id",void 0),et=be([te(He),ie("groups_permissions"),oe(qe),Ue("4.2.0")],et);let it=tt=class extends Me{static write(e,t,i){return xe(this,void 0,void 0,function*(){yield this.writeRaw(r.White,"",e,t,i)})}static error(e,t,i){return xe(this,void 0,void 0,function*(){yield this.writeRaw(r.Red,"error",e,t,i)})}static info(e,t,i){return xe(this,void 0,void 0,function*(){yield this.writeRaw(r.Cyan,"info",e,t,i)})}static success(e,t,i){return xe(this,void 0,void 0,function*(){yield this.writeRaw(r.Green,"success",e,t,i)})}static warning(e,t,i){return xe(this,void 0,void 0,function*(){yield this.writeRaw(r.Yellow,"warning",e,t,i)})}static writeRaw(e,t,r,s,n){return xe(this,void 0,void 0,function*(){n&&i.console(e,t,r),He&&(yield tt.create({type:t,source:s,message:r}).catch(this.error))})}};be([W(),Ce("design:type",Number)],it.prototype,"id",void 0),be([z(),Ce("design:type",z)],it.prototype,"type",void 0),be([z(),Ce("design:type",z)],it.prototype,"source",void 0),be([se(),Ce("design:type",z)],it.prototype,"message",void 0),be([Z,Ce("design:type",Date)],it.prototype,"created_at",void 0),it=tt=be([te(He),ie("log"),Ue("4.2.0")],it);let rt=class extends Me{};be([z(),Ce("design:type",z)],rt.prototype,"model",void 0),be([z(),Ce("design:type",z)],rt.prototype,"version",void 0),be([Z,Ce("design:type",Date)],rt.prototype,"created_at",void 0),be([X,Ce("design:type",Date)],rt.prototype,"updated_at",void 0),rt=be([te(He),ie("migration"),Ue("4.2.0")],rt);let st=class extends Me{};be([z(),Ce("design:type",z)],st.prototype,"session",void 0),be([se(),Ce("design:type",z)],st.prototype,"json",void 0),be([le(),Ce("design:type",Number)],st.prototype,"expired",void 0),be([Z,Ce("design:type",Date)],st.prototype,"created_at",void 0),be([X,Ce("design:type",Date)],st.prototype,"updated_at",void 0),st=be([te(He),ie("session"),Ue("4.2.0")],st);class nt{static error(e){let t="token";De.API_BASE_NAME&&(t=`${De.API_BASE_NAME}.${t}`),it.error(e.message,t,De.API_CONSOLE_ERROR)}}class ot extends nt{static user(e,t){return xe(this,void 0,void 0,function*(){if(!e)return{error:"INVALID TOKEN"};const i=t.hash.encrypt(e),r=yield ze.findOne({where:{token:i,state:!0}}).catch(this.error);if(r){const t=e.replace(/(-[\w]{4})/g,"-****"),[i]=(yield Ye.findOrCreate({where:{secret:t,user_id:r.id},defaults:{secret:t,user_id:r.id}}).catch(this.error))||[];if(i)return i.logout&&(i.logout=null,yield i.save().catch(this.error)),{auth:i,user:r}}return{error:"ACCESS DENIED"}})}}const dt=e=>me(e)?_e(e):void 0,at={http:dt(De.API_HTTP_CRT),token:dt(De.API_TOKEN_CRT)},ut={http:dt(De.API_HTTP_KEY),token:dt(De.API_TOKEN_KEY)};class ct extends nt{static options(){return{algorithm:"RS256",expiresIn:`${De.API_TOKEN_LIFETIME}ms`}}static create(e){return xe(this,void 0,void 0,function*(){if(!ut.token)return{error:"KEY NOT FOUND"};const{id:t}=e,i=c(),r=yield Ye.create({secret:i,user_id:t}).catch(this.error);if(!r)return{error:"INTERNAL SERVER ERROR"};return{auth:r,token:ve.sign({id:t,secret:i},ut.token,this.options())}})}static destroy(e){return xe(this,void 0,void 0,function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)})}static renew(e){return xe(this,void 0,void 0,function*(){if(!ut.token)return{error:"KEY NOT FOUND"};const{error:t,decode:i}=this.verify(e,De.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(i){const{id:e,secret:t}=i;if(e&&t){const i=yield ze.findOne({where:{id:e,state:!0}}).catch(this.error);if(i){const r=yield Ye.findOne({where:{secret:t,user_id:i.id}}).catch(this.error);if(r&&!r.logout){r.secret=c(),yield r.save().catch(this.error);return{auth:r,token:ve.sign({id:e,secret:r.secret},ut.token,this.options())}}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static user(e){return xe(this,void 0,void 0,function*(){const{error:t,decode:i}=this.verify(e);if(t)return{error:t};if(i){const{id:e,secret:t}=i;if(e&&t){const i=yield ze.findOne({where:{id:e,state:!0}}).catch(this.error);if(i){const e=yield Ye.findOne({where:{secret:t,user_id:i.id}}).catch(this.error);if(e&&!e.logout)return{auth:e,user:i}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static verify(e,t){if(!at.token)return{error:"CERT NOT FOUND"};if(!e||e.split(".").length<3)return{error:"INVALID TOKEN"};try{return{decode:ve.verify(e,at.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class pt extends Re{constructor(){super(),this.all=e=>xe(this,void 0,void 0,function*(){e=e||u;const t=yield st.findAll({attributes:["session"],where:{expired:{[Se.gte]:Date.now()}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.session)),e()}),this.clear=e=>xe(this,void 0,void 0,function*(){yield st.destroy().catch(u),e&&e()}),this.destroy=(e,t)=>xe(this,void 0,void 0,function*(){yield st.destroy({where:{session:e}}).catch(u),t&&t()}),this.expired=()=>xe(this,void 0,void 0,function*(){yield st.destroy({where:{expired:{[Se.lt]:Date.now()}}}).catch(u)}),this.get=(e,t)=>xe(this,void 0,void 0,function*(){t=t||u;const i=yield st.findOne({where:{session:e,expired:{[Se.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(u),void t(null)}return void t(null,e)}t(null)}),this.length=e=>xe(this,void 0,void 0,function*(){e&&e(null,(yield st.count().catch(u))||0)}),this.set=(e,t,i)=>xe(this,void 0,void 0,function*(){i=i||u;const r=Date.now()+De.API_SESSION_LIFETIME,s=JSON.stringify(t),[n,o]=(yield st.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:r}}).catch(u))||[];n&&(o||(n.json=s,n.expired=r,yield n.save().catch(u))),i()}),this.loop=p(this.expired,3e4),this.loop.start()}}class lt extends S{constructor(e){super(e,{cert:at.http,cross:De.API_HTTP_CROSS,hybrid:De.API_HTTP_HYBRID,json:{strict:De.API_BODYPARSER_STRICT,inflate:De.API_BODYPARSER_INFLATE,limit:De.API_BODYPARSER_LIMIT,type:De.API_BODYPARSER_TYPE},key:ut.http,notfound:De.API_HTTP_NOTFOUND,path:De.API_HTTP_PATH,port:De.API_HTTP_PORT,public:De.API_HTTP_PUBLIC,redirect:De.API_HTTP_REDIRECT,session:{store:new pt,name:De.API_SESSION_NAME,secret:De.API_SESSION_SECRET,cookie:{maxAge:De.API_SESSION_LIFETIME},genid:c}}),this.hash=new s(De.API_KEY_HASH)}error(e,t){De.API_BASE_NAME&&(t=t?`${De.API_BASE_NAME}.${t}`:De.API_BASE_NAME),it.error(e.message,t,De.API_CONSOLE_ERROR)}log(e,t){De.API_BASE_NAME&&(t=t?`${De.API_BASE_NAME}.${t}`:De.API_BASE_NAME),it.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return xe(this,void 0,void 0,function*(){yield He.sync(),yield this.migrations(He),yield l(this.controllers,e=>xe(this,void 0,void 0,function*(){y(e.sync)&&(yield e.sync(this))})),yield e.listen.call(this),De.API_WEBSOCKET_START&&this.server&&(this._webSocket=new Pe({server:this.server,verifyClient:(e,t)=>t(De.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>xe(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=>xe(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 ct.user(s.toString());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 g(2e3),r||e.close()})))})}migrations(e){return xe(this,void 0,void 0,function*(){const t=[];yield l(Object.keys(e.models),i=>xe(this,void 0,void 0,function*(){var r;const s=e.models[i],{version:n}=Be.migrations(s);if(!n)return;const[o,d]=null!==(r=yield rt.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 ge(e,t))})}websocket(){return this._webSocket}}var yt,gt,ht;class vt extends Ne{constructor(){super(...arguments),this[yt]=[]}auth(e,t,i,r,s,n){return xe(this,void 0,void 0,function*(){var o;t=null!=t?t:r;const[d,a]=null!==(o=null==i?void 0:i.split(" "))&&void 0!==o?o:["",""];if(!(t||a&&d.toLowerCase()==De.API_TOKEN_HEADER_KEY))return e.error("INVALID TOKEN");const{auth:u,error:c,user:p}=yield t?ot.user(t,n):ct.user(a);return c?e.error(c):u&&p?!t&&u.user_agent&&u.user_agent!=s?e.error("INVALID TOKEN"):(e.req.auth=u,e.req.user=p,void e.next()):e.error("INTERNAL SERVER ERROR")})}canCreate(e,t,i){return xe(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".create",i)})}canDelete(e,t,i){return xe(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".delete",i)})}canRead(e,t,i){return xe(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".read",i)})}canUpdate(e,t,i){return xe(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".update",i)})}error(e){let t="controller_base";De.API_BASE_NAME&&(t=`${De.API_BASE_NAME}.${t}`),it.error(e.message,t,De.API_CONSOLE_ERROR)}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}permission(e,t,i){return xe(this,void 0,void 0,function*(){if(i){if((yield this.permissions(i,{route:t})).length>0)return e.next()}e.unauthorized("ACCESS DENIED")})}permissions(e,t){return xe(this,void 0,void 0,function*(){var i;return null!==(i=yield Qe.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:et,required:!0,include:[{model:$e,required:!0,where:{state:!0},include:[{model:Ge,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error))&&void 0!==i?i:[]})}session(e,t,i){return xe(this,void 0,void 0,function*(){i.auth&&i.user&&(i.user_agent?i.user_agent!=t&&i.regenerate(u):(i.user_agent=t,i.save(u))),e.next()})}sync(){return xe(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield l(this[Ne.PERMISSIONS],i=>xe(this,void 0,void 0,function*(){const r=`${e}.${i}`,s=h(e.replace(/_/g," ")," ");yield Qe.findOrCreate({where:{route:r},defaults:Object.assign({name:`${s} ${h(i," ")}`,route:r,tag:s},t)})}))})}upload(e,t){t.path||(t.path=De.API_UPLOAD_TEMP),t.size||(t.size=De.API_UPLOAD_SIZE),t.field||(t.field=De.API_UPLOAD_FIELD),F.middleware(e,t)}validation(e,t){return xe(this,void 0,void 0,function*(){const{error:i,value:r}=yield v.object(t).parse().validateAsync(e.req.body);if(i)return e.validation(i);e.req.body=r,e.next()})}}yt=Ne.PERMISSIONS,be([we(0,T()),we(1,D(De.API_KEY_HEADER)),we(2,D(De.API_TOKEN_HEADER)),we(3,N(De.API_KEY_HEADER)),we(4,D("user-agent")),we(5,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,String,String,String,lt]),Ce("design:returntype",Promise)],vt.prototype,"auth",null),be([we(0,T()),we(1,C()),we(2,Le()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,ze]),Ce("design:returntype",Promise)],vt.prototype,"canCreate",null),be([we(0,T()),we(1,C()),we(2,Le()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,ze]),Ce("design:returntype",Promise)],vt.prototype,"canDelete",null),be([we(0,T()),we(1,C()),we(2,Le()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,ze]),Ce("design:returntype",Promise)],vt.prototype,"canRead",null),be([we(0,T()),we(1,C()),we(2,Le()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,ze]),Ce("design:returntype",Promise)],vt.prototype,"canUpdate",null),be([we(0,T()),we(1,C()),we(2,Le()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,ze]),Ce("design:returntype",Promise)],vt.prototype,"permission",null),be([we(0,T()),we(1,D("user-agent")),we(2,x()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,Object]),Ce("design:returntype",Promise)],vt.prototype,"session",null),be([we(0,T()),we(1,C()),Ce("design:type",Function),Ce("design:paramtypes",[w,Object]),Ce("design:returntype",void 0)],vt.prototype,"upload",null),be([we(0,T()),we(1,C()),Ce("design:type",Function),Ce("design:paramtypes",[w,Object]),Ce("design:returntype",Promise)],vt.prototype,"validation",null);let _t=class extends vt{constructor(){super(...arguments),this[gt]=[],this[ht]=["create","read","update","delete"]}attributes(e){if(0==this[vt.ATTRIBUTES].length&&(this[vt.ATTRIBUTES]=Object.keys(this.model().getAttributes())),_(e))return e.length?e.map(e=>m(e)&&-1!=this[vt.ATTRIBUTES].indexOf(e)?e:void 0).filter(m):this[vt.ATTRIBUTES];const{exclude:t,include:i}=e,r=E(i)?this[vt.ATTRIBUTES]:i.map(e=>m(e)&&-1!=this[vt.ATTRIBUTES].indexOf(e)?e:void 0).filter(m),s=null!=t?t:[];return s.length?r.filter(e=>-1==s.indexOf(e)?e:void 0).filter(m):r}create(e){return xe(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||{}),Fe(e))).catch(this.error);if(r){const t=this.key();return e.prepare(k.OK,{[t]:r.getDataValue(t)}),r}e.error("INTERNAL SERVER ERROR")})}delete(e){return xe(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}),Fe(e))).catch(this.error);return s?(e.success("OK"),s):(e.notFound("RECORD NOT FOUND"),0)})}error(e){let t="controller_model";De.API_BASE_NAME&&(t=`${De.API_BASE_NAME}.${t}`),(null==e?void 0:e.sql)?it.error((null==e?void 0:e.message)+"\n"+(null==e?void 0:e.sql),t,De.API_CONSOLE_ERROR):super.error(e)}findAll(e){return xe(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),p=Object.assign({},t||{}),{limit:l,offset:y,asc:g,desc:h,search:v,where:_}=e.req.query;if(E(p.limit)){const e=A(m(l)?parseInt(l)||0:De.API_MODEL_LIMIT,-1,De.API_MODEL_LIMIT_MAX);p.limit=e>0?e:o?void 0:De.API_MODEL_LIMIT}if(O(p.limit)&&(p.limit=p.limit>0?p.limit:void 0),m(y)){const e=y&&parseInt(y)||0;p.offset=e>0?e:void 0}n=null!=n?n:this.attributes(null!==(d=null==p?void 0:p.attributes)&&void 0!==d?d:[]);const I=[],f=e=>n.indexOf(e)>=0;if(m(g)&&g.length&&I.push(...g.split(";").filter(f).map(e=>[e,"ASC"])),m(h)&&h.length&&I.push(...h.split(";").filter(f).map(e=>[e,"DESC"])),I.length&&(p.order=I),p.where=Object.assign({},p.where||{}),m(_)&&(null==s||s)){const t=he.parse(n,_);if(!E(t.error))return e.validation(t.error.join(", ")),{count:0,records:[]};p.where=Object.assign(Object.assign({},p.where),null!==(a=t.value)&&void 0!==a?a:{})}else{const e=[];n.forEach(t=>{m(v)&&v.length&&e.push({[t]:{[Se.like]:`%${v}%`}})}),e.length&&(p.where=Object.assign(Object.assign({},p.where),{[Se.or]:[...e]}))}const P=c.count(Object.assign(Object.assign({},p),{distinct:!!p.include,col:this[vt.ATTRIBUTES].length?this[vt.ATTRIBUTES][0]:void 0})).catch(this.error),R=c.findAll(p).catch(this.error);yield Promise.allSettled([P,R]);const S=null!==(u=yield P)&&void 0!==u?u:0;let T=yield R;const D={count:S};return T?(T=i?yield i(T):T,(O(null==t?void 0:t.limit)||0==S)&&(D.count=T.length),e.prepare(k.OK,Object.assign(Object.assign({},D),{records:T})),Object.assign(Object.assign({},D),{records:T})):(e.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},D),{records:[]}))})}findOne(e){return xe(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(k.OK,i?yield i(o):o.toJSON()),o):null===o?e.notFound("RECORD NOT FOUND"):void e.error("INTERNAL SERVER ERROR")})}sync(){return xe(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield l(this[vt.PERMISSIONS],i=>xe(this,void 0,void 0,function*(){const r=`${e}.${i}`,s=h(e.replace(/_/g," ")," ");yield Qe.findOrCreate({where:{route:r},defaults:Object.assign({name:`${s} ${h(i," ")}`,route:r,tag:s},t)})}))})}update(e){return xe(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}),Fe(e))).catch(this.error))&&void 0!==r?r:[];return o?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)})}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}};gt=vt.ATTRIBUTES,ht=vt.PERMISSIONS,_t=be([j(vt)],_t);let mt=class extends _t{constructor(){super(...arguments),this._crud={}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return xe(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return xe(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}del(e){return xe(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return xe(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return xe(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return xe(this,void 0,void 0,function*(){const t=this.CrudValidationCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}validationUpdate(e){return xe(this,void 0,void 0,function*(){const t=this.CrudValidationUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}};be([L(),U("auth"),U("canCreate"),U("validationCreate"),we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],mt.prototype,"add",null),be([B(),U("auth"),U("canRead"),we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],mt.prototype,"all",null),be([M("/:id"),U("auth"),U("canDelete"),we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],mt.prototype,"del",null),be([B("/:id"),U("auth"),U("canRead"),we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],mt.prototype,"get",null),be([H("/:id"),U("auth"),U("canUpdate"),U("validationUpdate"),we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],mt.prototype,"set",null),be([we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],mt.prototype,"validationCreate",null),be([we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],mt.prototype,"validationUpdate",null),mt=be([j(_t)],mt);let Et=class extends _t{model(){return Je}all(e,t,i){return xe(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:r,order:[["created_at","DESC"]]},unlimited:!0})})}get(e){return xe(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};be([B(),U("auth"),U("canRead"),we(0,T()),we(1,N("type")),we(2,N("table")),Ce("design:type",Function),Ce("design:paramtypes",[w,String,String]),Ce("design:returntype",Promise)],Et.prototype,"all",null),be([B("/:id"),U("auth"),U("canRead"),we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],Et.prototype,"get",null),Et=be([K("/audits"),j(_t)],Et);let At=class extends vt{login(e,t,i,r,s){return xe(this,void 0,void 0,function*(){var o;yield g(De.API_SLEEP_AUTH);const d=yield ze.scope("password").findOne({where:{[Se.or]:[{email:i},{username:i}]}}).catch(this.error);if(r+=null!==(o=null==d?void 0:d.salt)&&void 0!==o?o:"",!d||d.password!=n(r))return e.notFound("INVALID USERNAME OR PASSWORD"),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const a=yield Ve.findOne({where:{state:!0,user_id:d.id}}).catch(this.error);if(a)return e.error("ACTIVATION REQUIRED"),s.emit("auth.activation",{ctx:e,register:a,user:d}),void this.emit("auth.activation",{ctx:e,register:a,user:d});if(!d.state)return e.notFound("INVALID USERNAME OR PASSWORD"),s.emit("auth.failure",{ctx:e,user:d}),void this.emit("auth.failure",{ctx:e,user:d});const{auth:u,error:c,token:p}=yield ct.create(d);return c?(e.error(c),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):u&&p?(u.user_agent=t,yield u.save().catch(this.error),e.json({token:p}),s.emit("auth.login",{auth:u,ctx:e,user:d}),void this.emit("auth.login",{auth:u,ctx:e,user:d})):(e.error("INTERNAL SERVER ERROR"),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))})}logout(e,t,i,r){return xe(this,void 0,void 0,function*(){if(yield ct.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 xe(this,void 0,void 0,function*(){const{auth:s,error:n,token:o}=yield ct.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 xe(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({},I(["username","date","description","state","created_at","updated_at","deleted_at"],t.toJSON())),{permissions:i.map(e=>e.route)}))})}};var Ot;be([L("/login"),U("validation",{username:v.string().min(3).required(),password:v.string().min(5).required()}),we(0,T()),we(1,D("user-agent")),we(2,q("username")),we(3,q("password")),we(4,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,String,String,lt]),Ce("design:returntype",Promise)],At.prototype,"login",null),be([B("/logout"),U("auth"),we(0,T()),we(1,ke()),we(2,Le()),we(3,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,Ye,ze,lt]),Ce("design:returntype",Promise)],At.prototype,"logout",null),be([L("/renew"),U("validation",{token:v.string().required()}),we(0,T()),we(1,D("user-agent")),we(2,q("token")),we(3,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,String,lt]),Ce("design:returntype",Promise)],At.prototype,"renew",null),be([B(),U("auth"),we(0,T()),we(1,Le()),Ce("design:type",Function),Ce("design:paramtypes",[w,ze]),Ce("design:returntype",Promise)],At.prototype,"user",null),At=be([K("/auth"),j(vt)],At);let It=class extends vt{constructor(){super(...arguments),this[Ot]=["delete","download","edit","list","read","rename","upload","write"]}directory(){return De.API_HTTP_PUBLIC||"./"}files(e){return xe(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=Te(this.directory(),t);if(!me(i)||!Ee(i).isDirectory())return e.notFound("RECORD NOT FOUND");let r=[];return r=Ae(i),r=r.map(e=>this.info(Te(i,e))),r=r.filter(f),Object.assign(Object.assign({},this.info(i)),{files:r})})}access(e,t,i){return xe(this,void 0,void 0,function*(){yield this.permission(e,this.name()+"."+t,i)})}info(e){if(!me(e))return null;const t=Ee(e),i=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const r=t.isDirectory();return{name:i,path:e.replace(/^\/\//,"/"),size:t.size,extension:r?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:r,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return xe(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=h(e.replace(/_/g," ")," "),i={description:"",state:!0};yield l(this[vt.PERMISSIONS],r=>xe(this,void 0,void 0,function*(){const s=`${e}.${r}`;yield Qe.findOrCreate({where:{route:s},defaults:Object.assign({name:`${t} ${h(r," ")}`,route:s,tag:t},i)})}))})}};Ot=vt.PERMISSIONS,be([B("/path"),B("/path/*path"),U("auth"),U("access","list"),we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],It.prototype,"files",null),be([we(0,T()),we(1,C()),we(2,Le()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,ze]),Ce("design:returntype",Promise)],It.prototype,"access",null),It=be([K("/files"),j(vt)],It);let ft=class extends vt{check(e,t){return xe(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.notFound("RECORD NOT FOUND");i.token=P(),yield i.save(),e.json({token:i.token})})}forgot(e,t,i){return xe(this,void 0,void 0,function*(){yield g(De.API_SLEEP_FORGOT);const r=t,s=yield ze.findOne({where:{[Se.or]:[{email:r},{username:t}]}}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");const n=P(),o=Date.now()+6e4*De.API_TOKEN_FORGOT,d=yield Xe.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 xe(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=n(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 xe(this,void 0,void 0,function*(){return yield Xe.findOne({where:{token:e,state:!0},include:[{model:ze,required:!0}]}).catch(this.error)})}};be([B("/check"),U("validation",{token:v.string().required()}),we(0,T()),we(1,q("token")),Ce("design:type",Function),Ce("design:paramtypes",[w,String]),Ce("design:returntype",Promise)],ft.prototype,"check",null),be([L(),U("validation",{username:v.string().min(4).required()}),we(0,T()),we(1,q("username")),we(2,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,lt]),Ce("design:returntype",Promise)],ft.prototype,"forgot",null),be([L("/reset"),U("validation",{token:v.string().required(),password:v.string().min(5).required()}),we(0,T()),we(1,q("token")),we(2,q("password")),we(3,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,String,lt]),Ce("design:returntype",Promise)],ft.prototype,"reset",null),ft=be([K("/forgot"),j(vt)],ft);let Pt=class extends mt{constructor(){super(...arguments),this.schemaCreate={name:v.string().required(),description:v.string().empty(""),state:v.boolean().parse().required()},this.schemaUpdate={name:v.string().empty(),description:v.string().empty(),state:v.boolean().parse().empty()}}model(){return $e}CrudArgumentsFindAll(e){return{ctx:e,unlimited:!0}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};Pt=be([K("/groups"),j(mt)],Pt);let Rt=class extends _t{model(){return et}all(e,t){return xe(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:Qe,required:!0}]},unlimited:!0,callback:e=>e.map(e=>e.permission)})})}me(e,t){return xe(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,i,r){return xe(this,void 0,void 0,function*(){const s=yield $e.findByPk(t,{attributes:["id"]}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");const n=s.id;if(yield et.destroy(Object.assign({where:{group_id:n},individualHooks:!0},r)),i){let e=0;yield g(1e3);for(let t=0;t<i.length;t++)e=yield Qe.count({where:{id:i[t]}}),e&&(yield et.create({group_id:n,permission_id:i[t]},Object.assign({},r)))}e.success("OK")})}};var St;be([B("/:id/permissions"),U("auth"),U("canRead","groups"),we(0,T()),we(1,Y("id")),Ce("design:type",Function),Ce("design:paramtypes",[w,String]),Ce("design:returntype",Promise)],Rt.prototype,"all",null),be([B("/permissions"),U("auth"),U("canRead","users"),we(0,T()),we(1,Le()),Ce("design:type",Function),Ce("design:paramtypes",[w,ze]),Ce("design:returntype",Promise)],Rt.prototype,"me",null),be([H("/:id/permissions"),U("auth"),U("canUpdate","groups"),U("validation",{permissions:v.array(v.number().parse())}),we(0,T()),we(1,Y("id")),we(2,q("permissions")),we(3,je()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,Array,Object]),Ce("design:returntype",Promise)],Rt.prototype,"set",null),Rt=be([K("/groups"),j(_t)],Rt);let Tt=class extends _t{constructor(){super(...arguments),this[St]=["read"]}model(){return it}all(e,t,i){return xe(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.source=i),yield this.findAll({ctx:e,options:{where:r,order:[["created_at","DESC"]]},unlimited:!0})})}};St=_t.PERMISSIONS,be([B(),U("auth"),U("canRead"),we(0,T()),we(1,N("type")),we(2,N("source")),Ce("design:type",Function),Ce("design:paramtypes",[w,String,String]),Ce("design:returntype",Promise)],Tt.prototype,"all",null),Tt=be([K("/logs"),j(_t)],Tt);let Dt=class extends mt{constructor(){super(...arguments),this.schemaCreate={name:v.string().required(),route:v.string().required(),tag:v.string().required(),description:v.string().empty(""),state:v.boolean().parse().required()},this.schemaUpdate={name:v.string().empty(),route:v.string().empty(),tag:v.string().empty(),description:v.string().empty(),state:v.boolean().parse().empty()}}model(){return Qe}CrudArgumentsFindAll(e){return{ctx:e,unlimited:!0}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};Dt=be([K("/permissions"),j(mt)],Dt);let Nt=class extends vt{register(e,t,i){return xe(this,void 0,void 0,function*(){yield g(De.API_SLEEP_REGISTRY);const{name:r,date:s,email:o,username:d,password:a,confirm:u}=t,c=d||o,p=n(a);if(yield ze.count({where:{[Se.or]:[{email:o},{username:c}]}}).catch(this.error))return e.validation("INVALID EMAIL OR USERNAME");if(p!=n(u))return e.error("INVALID PASSWORD");const l=yield ze.create({name:r,email:o,username:c,password:p,avatar:"",date:s,description:"",state:!1}).catch(this.error);if(!l)return e.error("INTERNAL SERVER ERROR");const y=yield Ve.create({token:yield this.getId(),user_id:l.id,state:!0}).catch(this.error);if(!y)return yield l.destroy().catch(this.error),e.error("INTERNAL SERVER ERROR");e.success("OK"),i.emit("register.user",{ctx:e,register:y,user:l}),this.emit("register.user",{ctx:e,register:y,user:l})})}confirm(e,t,i){return xe(this,void 0,void 0,function*(){const r=yield Ve.findOne({where:{token:t,state:!0},include:[{model:ze,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 xe(this,void 0,void 0,function*(){const r=t,s=yield Ve.findOne({where:{state:!0},include:[{model:ze,required:!0,where:{[Se.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 xe(this,void 0,void 0,function*(){const e=c();return(yield Ve.count({where:{token:e}}))?this.getId():e})}};be([L(),U("validation",{name:v.string().required(),date:v.date().required(),email:v.string().email().required(),username:v.string().min(4).empty(),password:v.string().min(5).required(),confirm:v.string().min(5).required()}),we(0,T()),we(1,q()),we(2,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,Object,lt]),Ce("design:returntype",Promise)],Nt.prototype,"register",null),be([L("/confirm"),U("validation",{token:v.string().required()}),we(0,T()),we(1,q("token")),we(2,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,lt]),Ce("design:returntype",Promise)],Nt.prototype,"confirm",null),be([L("/send"),U("validation",{username:v.string().min(4).required()}),we(0,T()),we(1,q("username")),we(2,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,lt]),Ce("design:returntype",Promise)],Nt.prototype,"send",null),Nt=be([K("/register"),j(vt)],Nt);let bt=class extends vt{setup(e,t){return xe(this,void 0,void 0,function*(){var i;if(yield ze.count())return e.success("OK");const r=P(),s=yield ze.create({name:"Admin",email:"admin@localhost",username:"admin",password:n("admin"+r),salt:r,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},t)),o=yield $e.create(Object.assign({name:"Admin"},{description:"API CORE",state:!0}),Object.assign({},t));yield Ge.create({user_id:s.id,group_id:o.id},Object.assign({},t));const d=null!==(i=yield Qe.findAll({where:{state:!0}}).catch(this.error))&&void 0!==i?i:[];yield l(d,e=>xe(this,void 0,void 0,function*(){yield et.create({group_id:o.id,permission_id:e.id},Object.assign({},t))})),e.success("OK")})}};be([B(),we(0,T()),we(1,je()),Ce("design:type",Function),Ce("design:paramtypes",[w,Object]),Ce("design:returntype",Promise)],bt.prototype,"setup",null),bt=be([K("/setup"),j(vt)],bt);let wt=class extends _t{model(){return ze}constructor(){super(),this.path=De.API_HTTP_PUBLIC+"/avatar",De.API_HTTP_PUBLIC&&me(De.API_HTTP_PUBLIC)&&!me(this.path)&&Oe(this.path)}avatar(e,t,i,r){return xe(this,void 0,void 0,function*(){if(t.length){const s=t[0].filename||"";if(s){const t=this.path+"/"+i.avatar;if(me(t)&&Ie(t).isFile()&&fe(t),i.avatar=s,yield i.save(Object.assign({},r)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")})}avatar_del(e,t,i){return xe(this,void 0,void 0,function*(){const r=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},i)).catch(this.error))&&me(r)&&fe(r),e.success("OK")})}password(e,t,i,r,s){return xe(this,void 0,void 0,function*(){var o;if(De.API_USER_HISTORY){if(yield We.count({where:{password:n(i+r.id)}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED")}const d=yield this.scope("password").findOne({where:{id:r.id,state:!0}}).catch(this.error);return t+=null!==(o=null==d?void 0:d.salt)&&void 0!==o?o:"",d&&d.password==n(t)?(d.salt=P(),d.password=n(i+d.salt),(yield d.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 xe(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_del(e,t,i){return xe(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_get(e,t,i){return xe(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_renew(e,t,i,r){return xe(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 xe(this,void 0,void 0,function*(){var e;const t=c();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 xe(this,void 0,void 0,function*(){const i=P(),r=yield this.create({ctx:e,body:{password:n(t+i),salt:i}});De.API_USER_HISTORY&&r&&(yield We.create({password:n(t+r.id),user_id:r.id}))})}all(e){return xe(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{attributes:{exclude:["password","salt","token"]}},unlimited:!0})})}del(e,t,i){return xe(this,void 0,void 0,function*(){if(i.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this.delete({ctx:e})})}get(e){return xe(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e,t,i){return xe(this,void 0,void 0,function*(){if(De.API_USER_HISTORY&&i){const r=n(i+t);if(yield We.count({where:{password:r}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED");yield We.create({password:r,user_id:t}).catch(this.error)}const r=i?P():"";yield this.update({ctx:e,body:i?{password:n(i+r),salt:r}:{}})})}};be([L("/avatar"),U("auth"),U("upload",e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32})),we(0,T()),we(1,V()),we(2,Le()),we(3,je()),Ce("design:type",Function),Ce("design:paramtypes",[w,Array,ze,Object]),Ce("design:returntype",Promise)],wt.prototype,"avatar",null),be([M("/avatar"),U("auth"),we(0,T()),we(1,Le()),we(2,je()),Ce("design:type",Function),Ce("design:paramtypes",[w,ze,Object]),Ce("design:returntype",Promise)],wt.prototype,"avatar_del",null),be([L("/password"),U("auth"),U("validation",{oldPassword:v.string().min(5).required(),newPassword:v.string().min(5).required(),confirmPassword:v.string().equal(v.ref("newPassword"))}),we(0,T()),we(1,q("oldPassword")),we(2,q("newPassword")),we(3,Le()),we(4,je()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,String,ze,Object]),Ce("design:returntype",Promise)],wt.prototype,"password",null),be([B("/token"),U("auth"),we(0,T()),we(1,Le()),we(2,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,ze,lt]),Ce("design:returntype",Promise)],wt.prototype,"token",null),be([M("/token/:id"),U("auth"),U("canDelete"),we(0,T()),we(1,Y("id")),we(2,je()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,Object]),Ce("design:returntype",Promise)],wt.prototype,"token_del",null),be([B("/token/:id"),U("auth"),U("canCreate"),we(0,T()),we(1,Y("id")),we(2,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,lt]),Ce("design:returntype",Promise)],wt.prototype,"token_get",null),be([B("/token/renew/:id"),U("auth"),U("canUpdate"),we(0,T()),we(1,Y("id")),we(2,je()),we(3,b()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,Object,lt]),Ce("design:returntype",Promise)],wt.prototype,"token_renew",null),be([L(),U("auth"),U("canCreate"),U("validation",{name:v.string().required(),email:v.string().email().required(),username:v.string().min(4).required(),password:v.string().min(5).required(),description:v.string().empty(""),state:v.boolean().parse().required()}),we(0,T()),we(1,q("password")),Ce("design:type",Function),Ce("design:paramtypes",[w,String]),Ce("design:returntype",Promise)],wt.prototype,"add",null),be([B(),U("auth"),U("canRead"),we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],wt.prototype,"all",null),be([M("/:id"),U("auth"),U("canDelete"),we(0,T()),we(1,Y("id")),we(2,Le()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,ze]),Ce("design:returntype",Promise)],wt.prototype,"del",null),be([B("/:id"),U("auth"),U("canRead"),we(0,T()),Ce("design:type",Function),Ce("design:paramtypes",[w]),Ce("design:returntype",Promise)],wt.prototype,"get",null),be([H("/:id"),U("auth"),U("canUpdate"),U("validation",{name:v.string().empty(),email:v.string().email().empty(),username:v.string().min(4).empty(),password:v.string().min(5).empty().filter(""),description:v.string().empty(),state:v.boolean().parse().empty()}),we(0,T()),we(1,Y("id")),we(2,q("password")),Ce("design:type",Function),Ce("design:paramtypes",[w,String,String]),Ce("design:returntype",Promise)],wt.prototype,"set",null),wt=be([K("/users"),j(_t),Ce("design:paramtypes",[])],wt);let Ct=class extends _t{model(){return Ge}all(e,t){return xe(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:$e,required:!0}]},unlimited:!0,callback:e=>e.map(e=>e.group)})})}me(e,t){return xe(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,i,r){return xe(this,void 0,void 0,function*(){const s=yield ze.findByPk(t,{attributes:["id"]}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");if(yield Ge.destroy(Object.assign({where:{user_id:s.id},individualHooks:!0},r)),i){let e=0;yield g(1e3);for(let t=0;t<i.length;t++)e=yield $e.count({where:{id:i[t]}}),e&&(yield Ge.create({user_id:s.id,group_id:i[t]},Object.assign({},r)))}e.success("OK")})}};be([B("/:id/groups"),U("auth"),U("canRead","users"),we(0,T()),we(1,Y("id")),Ce("design:type",Function),Ce("design:paramtypes",[w,String]),Ce("design:returntype",Promise)],Ct.prototype,"all",null),be([B("/groups"),U("auth"),U("canRead","users"),we(0,T()),we(1,Le()),Ce("design:type",Function),Ce("design:paramtypes",[w,ze]),Ce("design:returntype",Promise)],Ct.prototype,"me",null),be([H("/:id/groups"),U("auth"),U("canUpdate","users"),U("validation",{groups:v.array(v.number().parse())}),we(0,T()),we(1,Y("id")),we(2,q("groups")),we(3,je()),Ce("design:type",Function),Ce("design:paramtypes",[w,String,Array,Object]),Ce("design:returntype",Promise)],Ct.prototype,"set",null),Ct=be([K("/users"),j(_t)],Ct);export{lt as Application,Je as Audit,Et as AuditsController,Ye as Auth,nt as AuthBase,At as AuthController,ot as AuthKey,ct as AuthToken,Ze as Config,Ne as Controller,vt as ControllerBase,mt as ControllerCrud,_t as ControllerModel,De as Env,It as FilesController,Xe as Forgot,ft as ForgotController,$e as Group,et as GroupPermission,Pt as GroupsController,Rt as GroupsPermissionsController,it as Log,Tt as LogsController,Be as Metadata,Ue as Migrate,rt as Migration,Me as Model,Qe as Permission,Dt as PermissionsController,Ve as Register,Nt as RegisterController,je as ReqAudit,ke as ReqAuth,Le as ReqUser,st as Session,bt as SetupController,pt as Store,ze as User,Ge as UserGroup,We as UserHistory,wt as UsersController,Ct as UsersGroupsController,Fe as audit,at as crt,He as database,qe as hooks,ut as key};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrewcaires/api",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.4.0",
|
|
4
4
|
"description": "Simple api for small applications using express, jsonwebtoken, sequelize and websocket",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs.js",
|
|
@@ -47,12 +47,12 @@
|
|
|
47
47
|
"homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"@andrewcaires/express": "^1.2.6",
|
|
50
|
-
"@andrewcaires/node": "^1.2.
|
|
50
|
+
"@andrewcaires/node": "^1.2.6",
|
|
51
51
|
"@andrewcaires/sequelize": "^1.2.2",
|
|
52
52
|
"@andrewcaires/utils.js": "^0.4.9",
|
|
53
53
|
"cors": "^2.8.5",
|
|
54
54
|
"dotenv": "^17.2.0",
|
|
55
|
-
"express-session": "^1.18.
|
|
55
|
+
"express-session": "^1.18.2",
|
|
56
56
|
"jsonwebtoken": "^9.0.2",
|
|
57
57
|
"tsx": "^4.20.3",
|
|
58
58
|
"ws": "^8.18.3"
|
|
@@ -64,13 +64,13 @@
|
|
|
64
64
|
"@types/cors": "^2.8.19",
|
|
65
65
|
"@types/express-session": "^1.18.2",
|
|
66
66
|
"@types/jsonwebtoken": "^9.0.10",
|
|
67
|
-
"@types/node": "^24.0
|
|
67
|
+
"@types/node": "^24.1.0",
|
|
68
68
|
"@types/ws": "^8.18.1",
|
|
69
|
-
"eslint": "^9.
|
|
70
|
-
"mariadb": "^3.4.
|
|
71
|
-
"rollup": "^4.
|
|
69
|
+
"eslint": "^9.31.0",
|
|
70
|
+
"mariadb": "^3.4.5",
|
|
71
|
+
"rollup": "^4.45.1",
|
|
72
72
|
"rollup-plugin-dts": "^6.2.1",
|
|
73
73
|
"tslib": "^2.8.1",
|
|
74
|
-
"typescript-eslint": "^8.
|
|
74
|
+
"typescript-eslint": "^8.38.0"
|
|
75
75
|
}
|
|
76
76
|
}
|