@clairejs/server 3.5.1 → 3.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,9 @@
1
1
  ## Change Log
2
2
 
3
- #### 3.5.1
3
+ #### 3.5.4
4
4
 
5
+ - fix aws get socket by id
6
+ - send error when close socket
5
7
  - remove constructor dependency of socket connection handler in socket managers
6
8
 
7
9
  #### 3.5.0
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- !function webpackUniversalModuleDefinition(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,(()=>(()=>{"use strict";var e={9025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FileOperation=void 0,function(e){e.GET="getObject",e.PUT="putObject",e.DELETE="deleteObject"}(t.FileOperation||(t.FileOperation={}))},4638:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractPrincipalResolver=void 0;t.AbstractPrincipalResolver=class AbstractPrincipalResolver{}},1820:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},137:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExitCode=t.INJECTED_TRANSACTION=void 0,t.INJECTED_TRANSACTION="__INJECTED_TRANSACTION__",t.ExitCode={SIGTERM_INTERUPTION:-1,SIGINT_INTERUPTION:-2,UNCAUGHT_EXCEPTION:-3,UNHANDLED_REJECTION:-4}},4435:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},4972:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEndpointId=void 0;t.getEndpointId=e=>`${e.httpMethod}:${e.mount}`},1870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3e3:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},120:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseAdapter=void 0;const o=n(2318);t.AbstractDatabaseAdapter=class AbstractDatabaseAdapter{constructor(){this.modelMetadata=[],this.models=[],this.modelConnections={}}init(){return i(this,void 0,void 0,(function*(){this.models=((0,o.getGlobalStore)().models||[]).slice(),this.modelMetadata=this.models.map((e=>(0,o.getObjectMetadata)(e))),this.modelConnections=this.modelMetadata.reduce(((e,t)=>Object.assign(e,{[t.id]:{connection:void 0}})),{})}))}exit(){}}},5549:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractQuery=void 0;const i=n(2318);t.AbstractQuery=class AbstractQuery{constructor(e){const t=(0,i.getObjectMetadata)(e);this.model=(0,i.getModelById)(t.id)||e,this.metadata=(0,i.getObjectMetadata)(this.model)}convertToLogicObjects(e,t){return e.map((e=>{let n=new this.model;return this.metadata.fields.filter((e=>!t||t.includes(e.name))).forEach((t=>{const i=e[t.name];void 0!==i&&(t.isBigInt?n[t.name]=Number(i):t.vectorProps?n[t.name]=JSON.parse(i):n[t.name]=i)})),n}))}convertToDataObjects(e,t){const n=Date.now();return e.map((e=>{let i=new this.model;for(const o of this.metadata.fields){let r=e[o.name];o.vectorProps?r=JSON.stringify(r):(o.modificationTimestamp||o.creationTimestamp&&!t)&&(r=n),i[o.name]=r}return i}))}}},9171:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseAdapter=void 0;const s=n(2318),a=n(496),d=n(4618),l=n(120),c=n(5549),u=n(7220),h=n(7048),getModelId=e=>{const t=(0,s.getObjectMetadata)(e);if(!t)throw s.ErrorBuilder.systemError(`Metadata for ${e.name} not found, check @Model decorator`);return t.id},p=["_and","_or"],f=[["_and",a.Op.and],["_or",a.Op.or],["_eq",a.Op.eq],["_neq",a.Op.ne],["_gt",a.Op.gt],["_lt",a.Op.lt],["_gte",a.Op.gte],["_lte",a.Op.lte],["_regex",a.Op.regexp],["_sub",a.Op.like],["_in",a.Op.in],["_nin",a.Op.notIn]],convertOp=e=>f.find((t=>t[0]===e))[1],safetifyColumn=(e,t)=>{const n=t===u.SqlProvider.MYSQL?"`":'"';return e.split(".").map((e=>`${n}${e}${n}`)).join(".")},getAggregatorColumn=(e,t)=>{const n=safetifyColumn(e.field,t);switch(e.fn){case"count":return`${!0===e.args?`COUNT(DISTINCT(${n}))`:`COUNT(${n})`}${t===u.SqlProvider.POSTGRES?"::int":""}`;case"sum":return`SUM(${n})`;case"avg":return`AVG(${n})`;case"min":return`MIN(${n})`;case"max":return`MAX(${n})`;case"join":return t===u.SqlProvider.POSTGRES?`string_agg(${n}, '${e.args}')`:`GROUP_CONCAT(${n} SEPARATOR '${e.args}')`;case"is":return n;default:throw s.ErrorBuilder.systemError(`Not supported agg function: ${e.fn}`)}};class Joiner{constructor(e){this.adapter=e,this.joinInfo=[],this.columnId=0}join(e,t,n,i){return this.joinInfo.push({rightModel:e,leftField:t,rightField:n,joinMode:i||"inner"}),this}where(e){return this.queryCondition=e,this}groupBy(e){return this.groupByFields=e,this}having(e){return this.havingCondition=e,this}getExecuteCondition(){const e=[],t=this.convertHavingCondition(this.havingCondition||{},e);return{conditions:{where:this.adapter.getQueryObjectFromQueryConditions(this.queryCondition,!0),transaction:this.adapter.transaction,include:this.joinInfo.map((e=>{const t=(0,s.getTableName)(e.rightModel);return{attributes:[],model:this.adapter.modelConnections[t].connection,duplicating:!1,required:"inner"===e.joinMode,right:"right"===e.joinMode,on:{[`$${e.leftField}$`]:{[convertOp("_eq")]:a.Sequelize.col(e.rightField)}}}})),group:this.groupByFields,attributes:this.adapter.sqlProvider===u.SqlProvider.POSTGRES?[]:e.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId])),having:t,raw:!0},collector:e}}countWithCondition(e){var t;return r(this,void 0,void 0,(function*(){e.offset=0,e.limit=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?1:0,e.attributes=[...this.adapter.sqlProvider===u.SqlProvider.MYSQL&&e.attributes||[],[this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.literal("(COUNT(*) OVER ())::int"):a.Sequelize.literal("COUNT(*)"),"count"]];const n=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?yield this.adapter.getCurrentConnection().findAll(e):yield this.adapter.getCurrentConnection().count(e);return(null===(t=n[0])||void 0===t?void 0:t.count)||0}))}count(){return r(this,void 0,void 0,(function*(){const{conditions:e}=this.getExecuteCondition();return this.countWithCondition(e)}))}rows(e,t){return r(this,void 0,void 0,(function*(){const{conditions:n,collector:i}=this.getExecuteCondition();n.attributes=[...n.attributes||[],...Object.keys(e).map((t=>[a.Sequelize.literal(getAggregatorColumn(e[t],this.adapter.sqlProvider)),t]))],n.limit=null==t?void 0:t.limit,n.offset=(null==t?void 0:t.limit)&&t.limit*((t.page||1)-1),(null==t?void 0:t.order)&&(n.order="random"===t.order?this.adapter.dbConnection.random():t.order);const o=yield this.adapter.getCurrentConnection().findAll(n);return{total:yield this.countWithCondition(Object.assign(Object.assign({},n),{attributes:i.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId]))})),records:o}}))}convertHavingOperation(e,t){const n=getAggregatorColumn(t[0],this.adapter.sqlProvider);return{columnId:"col__"+this.columnId++,sequelizeColumn:n,sequelizeOps:{[convertOp(e)]:t[1]}}}convertHavingCondition(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>{if(p.includes(n))return{[convertOp(n)]:e[n].map((e=>this.convertHavingCondition(e,t)))};{const i=this.convertHavingOperation(n,e[n]);return t.push(i),this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.where(a.Sequelize.literal(i.sequelizeColumn),i.sequelizeOps):{[i.columnId]:i.sequelizeOps}}}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class ModelAdapter extends c.AbstractQuery{constructor(e){super(e.model),this.dbConnection=e.dbConnection,this.modelConnections=e.modelConnections,this.transaction=e.transaction,this.sqlProvider=e.sqlProvider,this.logger=null==e?void 0:e.logger}getCurrentConnection(){const e=(0,s.getObjectMetadata)(this.model).id;return this.modelConnections[e].connection}resolveNestedIncludes(e){return e&&e.map((e=>({model:this.modelConnections[e.modelId].connection,where:this.getQueryObjectFromQueryConditions(e.queries)})))}join(e,t,n,i){const o=new Joiner(this);return o.join(e,t,n,i),o}count(e,t,n){return r(this,void 0,void 0,(function*(){const i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};return(null==t?void 0:t.distinct)&&Object.assign(i,{distinct:!0,col:t.distinct}),yield this.getCurrentConnection().count(i)}))}getById(e,t){return this.getOne({_eq:{id:e}},t)}getByIds(e,t){return this.getRecords({_in:{id:e}},t)}getOne(e,t){return r(this,void 0,void 0,(function*(){const n=yield this.getMany(e,{limit:1});return n.records.length?this.convertToLogicObjects(n.records,null==t?void 0:t.projection)[0]:void 0}))}getRecords(e,t,n){return r(this,void 0,void 0,(function*(){return(yield this.getMany(e,t,n)).records}))}getMany(e,t,n){return r(this,void 0,void 0,(function*(){let i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};if((null==t?void 0:t.order)&&Object.assign(i,{order:"random"===t.order?this.dbConnection.random():t.order}),(null==t?void 0:t.projection)&&Object.assign(i,{attributes:t.projection}),(null==t?void 0:t.limit)&&(i=Object.assign(i,{limit:t.limit}),t.page&&(i=Object.assign(i,{offset:t.limit*(t.page-1)}))),1!==(null==t?void 0:t.limit)||t.page){if(null==t?void 0:t.limit){const{count:e,rows:n}=yield this.getCurrentConnection().findAndCountAll(i);return{total:e,records:this.convertToLogicObjects(n,null==t?void 0:t.projection)}}{const e=yield this.getCurrentConnection().findAll(i);return{total:0,records:this.convertToLogicObjects(e,null==t?void 0:t.projection)}}}{const e=yield this.getCurrentConnection().findOne(i);return{total:0,records:e?this.convertToLogicObjects([e],t.projection):[]}}}))}createOne(e){return r(this,void 0,void 0,(function*(){return(yield this.createMany([e]))[0]}))}createMany(e){return r(this,void 0,void 0,(function*(){let t=yield this.getCurrentConnection().bulkCreate(this.convertToDataObjects(e),{transaction:this.transaction});return this.convertToLogicObjects(t)}))}updateOne(e){return r(this,void 0,void 0,(function*(){return yield this.getCurrentConnection().update(this.convertToDataObjects([e],!0)[0],{where:this.getQueryObjectFromQueryConditions({_eq:{id:e.id}}),transaction:this.transaction}),e}))}updateMany(e,t,n){return r(this,void 0,void 0,(function*(){if(n){const n=yield this.getRecords(e,{projection:["id"]});if(!n.length)return[];const i=n.map((e=>e.id));return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions({_in:{id:i}}),transaction:this.transaction}),i}return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}deleteOne(e){return r(this,void 0,void 0,(function*(){return yield this.deleteMany({_eq:{id:e.id}}),e}))}deleteMany(e,t){return r(this,void 0,void 0,(function*(){if(t){const t=yield this.getMany(e);if(!t.records.length)return[];const n=t.records.map((e=>e.id));return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions({_in:{id:n}}),transaction:this.transaction}),t.records}return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}rawQuery(...e){return r(this,void 0,void 0,(function*(){const t=e[0],n=e[1]||{};if("string"!=typeof t)throw s.ErrorBuilder.error(s.Errors.QUERY_ERROR,"First argument of raw sql expected to be string");return this.dbConnection.query(t,Object.assign({transaction:this.transaction,raw:!0},n))}))}mapToSequelizeOperator(e,t,n,i,o){const r=o?a.Sequelize.literal(safetifyColumn(n,e)):a.Sequelize.col(n);switch(t){case"_sub":switch(this.sqlProvider){case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_cs`)});default:return a.Sequelize.where(r,{[a.Op.like]:`%${i}%`})}case"_isub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(r,{[a.Op.iLike]:`%${i}%`});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_ci`)})}case"_usub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)}) COLLATE utf8mb4_0900_as_cs`)})}case"_iusub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.iLike]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_ai_ci`)})}case"_in":case"_nin":const o=i||[],s=o.filter((e=>null!==e)),d=s.length<o.length,l=convertOp(t);return d?a.Sequelize.or(a.Sequelize.where(r,{[a.Op.eq]:null}),...s.length?[a.Sequelize.where(e===u.SqlProvider.MYSQL?a.Sequelize.literal(`CAST(${safetifyColumn(n,e)} as BINARY)`):r,{[l]:s})]:[]):a.Sequelize.where(e===u.SqlProvider.MYSQL?a.Sequelize.literal(`CAST(${safetifyColumn(n,e)} as BINARY)`):r,{[l]:o});default:return a.Sequelize.where(r,{[convertOp(t)]:i})}}getQueryObjectFromQueryConditions(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>p.includes(n)?{[convertOp(n)]:e[n].map((e=>this.getQueryObjectFromQueryConditions(e)))}:{[convertOp("_and")]:Object.keys(e[n]).map((i=>this.mapToSequelizeOperator(this.sqlProvider,n,i,e[n][i],t)))}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class TransactionAdapter{constructor(e){this.modelAdapters={},this.transaction=e.transaction,this.dbConnection=e.dbConnection,this.logger=e.logger,this.modelConnections=e.modelConnections,this.sqlProvider=e.sqlProvider,this.transactionState=d.TransactionState.EXECUTING}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(this.modelAdapters,n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,transaction:this.transaction,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}commit(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.COMMITTED,this.transaction.commit()}))}rollback(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.ROLLED_BACK,this.transaction.rollback()}))}getState(){return this.transactionState}}let g=class DefaultSqlDatabaseAdapter extends l.AbstractDatabaseAdapter{constructor(e,t,n){super(),this.logger=n,this.modelAdapters={},this.sqlProvider=e,this.dbConnection=new a.Sequelize(`${e}://${t}`,{dialect:this.sqlProvider,logging:e=>this.logger.debug(e),define:{timestamps:!1}})}createTransaction(){return r(this,void 0,void 0,(function*(){let e=yield this.dbConnection.transaction();return new TransactionAdapter({transaction:e,dbConnection:this.dbConnection,logger:this.logger,modelConnections:this.modelConnections,sqlProvider:this.sqlProvider})}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});var t,n,i,o;return r(this,void 0,void 0,(function*(){yield e.init.call(this),null===(t=this.logger)||void 0===t||t.debug("Connecting to database"),yield this.dbConnection.authenticate(),null===(n=this.logger)||void 0===n||n.debug("Generating in-memory schema");for(const e of this.modelMetadata){const t=this.generateSchemaObject(e);this.modelConnections[e.id].connection=t}for(const e of this.modelMetadata){const t=this.modelConnections[e.id].connection,n=e.fields.filter((e=>e.fk));for(const o of n){const n=null===(i=o.fk)||void 0===i?void 0:i.dtoId;if(!n)throw s.ErrorBuilder.systemError(`FK model id not resolved for ${e.id}:${o.name}`);const r=this.modelConnections[n].connection;t.belongsTo(r,{foreignKey:o.name}),r.hasMany(t,{foreignKey:o.name})}}null===(o=this.logger)||void 0===o||o.debug("Database adapter init succeeded")}))}exit(){var e;return null===(e=this.logger)||void 0===e||e.debug("Closing connection to database"),this.dbConnection.close(),0}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}generateSchemaObject(e){let t={};const n=(0,h.getDirectFields)(e);for(const e of n){switch(t[e.name]={},e.dataType){case s.DataType.NUMBER:e.floating?t[e.name].type=a.DataTypes.FLOAT:e.isBigInt?t[e.name].type=a.DataTypes.BIGINT:t[e.name].type=a.DataTypes.INTEGER;break;case s.DataType.STRING:e.textLength?t[e.name].type=a.DataTypes.STRING(e.textLength):t[e.name].type=a.DataTypes.STRING;break;case s.DataType.BOOLEAN:t[e.name].type=a.DataTypes.BOOLEAN;break;case s.DataType.ARRAY:case s.DataType.OBJECT:t[e.name].type=a.DataTypes.TEXT}e.pk&&(t[e.name].primaryKey=!0,e.pk.isAutoIncrement&&(t[e.name].autoIncrement=!0)),void 0!==e.defaultValue&&(t[e.name].defaultValue=e.defaultValue),t[e.name].allowNull=!e.isRequired}return this.dbConnection.define(e.id,t,{tableName:e.id,freezeTableName:!0,name:{singular:e.id,plural:e.id}})}};g=i([(0,s.Initable)(),(0,s.Injectable)(),o("design:paramtypes",[String,String,s.AbstractLogger])],g),t.DefaultSqlDatabaseAdapter=g},1319:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},9461:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3757:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._is=t._join=t._max=t._min=t._avg=t._sum=t._count=void 0;t._count=(e,t)=>({fn:"count",field:e,args:t});t._sum=e=>({fn:"sum",field:e});t._avg=e=>({fn:"avg",field:e});t._min=e=>({fn:"min",field:e});t._max=e=>({fn:"max",field:e});t._join=(e,t)=>({fn:"join",field:e,args:t});t._is=e=>({fn:"is",field:e})},7220:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqlProvider=t.NoSqlProvider=void 0,function(e){e.MONGODB="mongodb",e.DYNAMODB="dynamodb"}(t.NoSqlProvider||(t.NoSqlProvider={})),function(e){e.MYSQL="mysql",e.POSTGRES="postgres"}(t.SqlProvider||(t.SqlProvider={}))},6793:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Transactional=void 0;const o=n(2318),r=n(137),s=n(873),a=n(4618);t.Transactional=e=>(t,n,d)=>{const l=(0,o.initObjectMetadata)(t);(0,o.initFieldMetadata)(t,n),l.transactional=!0;const c=d.value;d.value=function(...d){return i(this,void 0,void 0,(function*(){const i=this;let l,u,h;try{l=yield i.getCurrentTransaction()}catch(e){}switch(e){case s.TransactionLink.CREATE_NEW:u=!0,h=yield i.createTransaction();break;case s.TransactionLink.INHERIT_OR_CREATE:u=!l,h=l||(yield i.createTransaction());break;case s.TransactionLink.INHERIT_OR_THROW:if(u=!1,!l)throw o.ErrorBuilder.systemError(`No transaction to inherit when executing ${t.constructor.name}:${n}`);h=l}const p=Object.assign(Object.create(i),i),f=Object.keys(p).filter((e=>{var t,n;return(null===(t=p[e])||void 0===t?void 0:t.constructor)&&(null===(n=(0,o.getObjectMetadata)(p[e].constructor))||void 0===n?void 0:n.transactional)}));for(const e of f){const t=p[e],n=Object.assign(Object.create(t),t,{[r.INJECTED_TRANSACTION]:h});p[e]=n}try{Object.assign(p,{[r.INJECTED_TRANSACTION]:h});let e=yield c.call(p,...d);return h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.commit()),e}catch(e){throw h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.rollback()),e}}))},Object.defineProperty(d.value,"name",{value:n})}},5670:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseMigrator=void 0;t.AbstractDatabaseMigrator=class AbstractDatabaseMigrator{}},4963:function(e,t,n){var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseMigrator=void 0;const d=a(n(1017)),l=a(n(7147)),c=n(2081),u=n(2318),h=n(496),p=n(7220),f=n(7048),g=n(5670),uniqueGroupComparator=(e,t)=>!e.groupName&&!t.groupName&&e.fieldNames[0]===t.fieldNames[0]||!!e.groupName&&e.groupName===t.groupName;let v=i=class DefaultSqlDatabaseMigrator extends g.AbstractDatabaseMigrator{constructor(e,t,n,i){super(),this.cliPath=e,this.sqlProvider=t,this.connectionString=n,this.logger=i,this.cliPath=e,this.databaseURL=`${t}://${n}`,this.modelMetadata=((0,u.getGlobalStore)().models||[]).map((e=>(0,u.getObjectMetadata)(e)))}getUniqueConstraintGroups(e){const t=[],n=(0,f.getDirectFields)(e).filter((e=>!!e.unique));for(const e of n)if(e.unique.groupName){let n=t.find((t=>t.groupName===e.unique.groupName));n||(n={groupName:e.unique.groupName,fieldNames:[]},t.push(n)),n.fieldNames.push(e.name)}else t.push({fieldNames:[e.name]});return t}generateFieldPropertiesQuery(e){let t="{";if(e.pk&&(t+="primaryKey:true,",e.pk.isAutoIncrement&&(t+="autoIncrement:true,")),void 0!==e.defaultValue&&(t+=`defaultValue:${JSON.stringify(e.defaultValue)},`),t+=`allowNull:${e.isRequired?"false":"true"},`,void 0!==e.dataType)switch(e.dataType){case u.DataType.STRING:e.textLength?t+=`type:Sequelize.STRING(${e.textLength}),`:t+="type:Sequelize.TEXT,";break;case u.DataType.NUMBER:e.floating?t+="type:Sequelize.FLOAT,":e.isBigInt?t+="type:Sequelize.BIGINT,":t+="type:Sequelize.INTEGER,";break;case u.DataType.BOOLEAN:t+="type:Sequelize.BOOLEAN,";break;case u.DataType.ARRAY:case u.DataType.OBJECT:t+="type:Sequelize.TEXT,"}return t+="}",t}getUniqueConstraintUpDown(e,t){const n=`${e}_${t.groupName||t.fieldNames[0]}_un`;return[`queryInterface.addConstraint("${e}",{fields:${JSON.stringify(t.fieldNames)},type:"unique",name:"${n}","transaction":t})`,`queryInterface.removeConstraint("${e}","${n}",{"transaction":t})`]}getSqlCascadeAction(e){switch(e){case"delete":return"CASCADE";case"restrict":return"RESTRICT";case"nullify":return"SET NULL";default:return"RESTRICT"}}getForeignKeyConstraintUpDown(e,t,n){var i,o,r;if(!e)throw u.ErrorBuilder.systemError(`Refer table ${null===(i=n.fk)||void 0===i?void 0:i.dtoId} not found at ${t}:${n.name}`);const s=`${t}_${n.name}_fk`;return[`queryInterface.addConstraint("${t}",{fields:["${n.name}"],type:"foreign key",name:"${s}",references:{table:"${e.id}",field:"id"},onDelete:'${this.getSqlCascadeAction(null===(o=n.fk)||void 0===o?void 0:o.cascade)}',onUpdate:'${this.getSqlCascadeAction(null===(r=n.fk)||void 0===r?void 0:r.cascade)}',"transaction":t})`,`queryInterface.removeConstraint("${t}","${s}",{"transaction":t})`]}getAddColumnUpDown(e,t){return[`queryInterface.addColumn('${e}','${t.name}',${this.generateFieldPropertiesQuery(t)},{"transaction":t})`,`queryInterface.removeColumn('${e}','${t.name}',{"transaction":t})`]}generateCreateTableQuery(e){let t={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]},n="",i="";n+="{\n";for(const t of(0,f.getDirectFields)(e)){let e=this.generateFieldPropertiesQuery(t);n+=`${t.name}:${e},\n`}n+="}\n",i+='{charset:"utf8",transaction:t}',t.upTableAdd.push(`queryInterface.createTable("${e.id}",${n},{charset:"utf8",transaction:t})`),t.downTableRemove.push(`queryInterface.dropTable("${e.id}",{"transaction":t})`);const o=this.getUniqueConstraintGroups(e);for(const n of o){const[i,o]=this.getUniqueConstraintUpDown(e.id,n);t.upConstraintAdd.push(i),t.downConstraintRemove.push(o)}for(const n of(0,f.getDirectFields)(e))if(n.fk){let i=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=n.fk)||void 0===t?void 0:t.dtoId)}));const[o,r]=this.getForeignKeyConstraintUpDown(i,e.id,n);t.upConstraintAdd.push(o),t.downConstraintRemove.push(r)}return t}isBooleanDiff(e,t){return!!e&&!t||!!t&&!e}runProcess(e){return s(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{(0,c.exec)(e,{env:process.env},(e=>(e&&n(e),t())))}))}))}rollback(e){return s(this,void 0,void 0,(function*(){let t=d.default.join(e,"scripts");if(!l.default.existsSync)throw u.ErrorBuilder.systemError("Migration directory not found");this.logger.debug("Rolling back last migration"),yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${t} db:migrate:undo`),this.logger.debug("Rollback completed")}))}migrate(e){var t,n,o,r,a,c,g,v;return s(this,void 0,void 0,(function*(){let y=d.default.join(e,"metadata.json"),m=d.default.join(e,"scripts");l.default.existsSync(m)||(this.logger.debug("Migration directory not exists, creating empty folder"),l.default.mkdirSync(m,{recursive:!0})),l.default.existsSync(y)||(this.logger.debug("Migration metadata does not exist, creating one"),l.default.writeFileSync(y,JSON.stringify([]))),this.logger.debug("Parsing migration metadata file");let b=JSON.parse(String(l.default.readFileSync(y)));this.logger.debug("Calculating differences...");const C=this.modelMetadata.filter((e=>!b.find((t=>e.id===t.id)))),M=this.modelMetadata.filter((e=>b.find((t=>t.id===e.id)))).map((e=>e.id));let S=[];S.push(...C.map((e=>this.generateCreateTableQuery(e))));for(const e of M){const i=b.find((t=>t.id===e)),s=this.modelMetadata.find((t=>t.id===e));i.id!==s.id&&S.push({upTableAdd:[`queryInterface.query("ALTER TABLE ${i.id} RENAME TO ${s.id}",{"transaction":t})`],downTableRemove:[`queryInterface.query("ALTER TABLE ${s.id} RENAME TO ${i.id}",{"transaction":t})`],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]});let d={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]};const l=(0,f.getDirectFields)(i).filter((e=>!(0,f.getDirectFields)(s).find((t=>e.name===t.name))));for(const e of l){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableRemove.push(n),d.downTableAdd.push(t),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.dtoId)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintRemove.push(i),d.downConstraintAdd.push(n)}}const u=(0,f.getDirectFields)(s).filter((e=>!(0,f.getDirectFields)(i).find((t=>e.name===t.name))));for(const e of u){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableAdd.push(t),d.downTableRemove.push(n),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.dtoId)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintAdd.push(n),d.downConstraintRemove.push(i)}}const h=(0,f.getDirectFields)(s).filter((e=>(0,f.getDirectFields)(i).find((t=>e.name===t.name)))).map((e=>e.name));for(const e of h){const l=(0,f.getFieldByName)(i,e),u=(0,f.getFieldByName)(s,e);if((this.isBooleanDiff(l.floating,u.floating)||this.isBooleanDiff(l.isBigInt,u.isBigInt)||this.isBooleanDiff(l.isRequired,u.isRequired)||this.isBooleanDiff(null===(t=l.pk)||void 0===t?void 0:t.isAutoIncrement,null===(n=u.pk)||void 0===n?void 0:n.isAutoIncrement)||l.dataType!==u.dataType||l.textLength!==u.textLength||l.defaultValue!==u.defaultValue)&&(d.upTableAdd.push(`queryInterface.changeColumn("${s.id}","${u.name}",${this.generateFieldPropertiesQuery(u)},{"transaction":t})`),d.downTableRemove.push(`queryInterface.changeColumn("${s.id}","${l.name}",${this.generateFieldPropertiesQuery(l)},{"transaction":t})`)),(null===(o=l.fk)||void 0===o?void 0:o.dtoId)!==(null===(r=u.fk)||void 0===r?void 0:r.dtoId)||(null===(a=l.fk)||void 0===a?void 0:a.cascade)!==(null===(c=u.fk)||void 0===c?void 0:c.cascade)){if(null===(g=l.fk)||void 0===g?void 0:g.dtoId){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=l.fk)||void 0===t?void 0:t.dtoId)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,l);d.upTableAdd.push(n),d.downTableRemove.push(t)}if(null===(v=u.fk)||void 0===v?void 0:v.dtoId){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=u.fk)||void 0===t?void 0:t.dtoId)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,u);d.upTableAdd.push(t),d.downTableRemove.push(n)}}}const p=this.getUniqueConstraintGroups(i),y=this.getUniqueConstraintGroups(s),m=p.filter((e=>!!y.find((t=>uniqueGroupComparator(e,t))))),C=p.filter((e=>!m.find((t=>uniqueGroupComparator(e,t)))));for(const e of C){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintRemove.push(n),d.downConstraintAdd.push(t)}const M=y.filter((e=>!m.find((t=>uniqueGroupComparator(e,t)))));for(const e of M){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintAdd.push(t),d.downConstraintRemove.push(n)}for(const e of m){const t=p.find((t=>uniqueGroupComparator(t,e))),n=y.find((t=>uniqueGroupComparator(t,e)));if(t.fieldNames.length!==n.fieldNames.length||t.fieldNames.some((e=>!n.fieldNames.includes(e)))){const[e,i]=this.getUniqueConstraintUpDown(s.id,t),[o,r]=this.getUniqueConstraintUpDown(s.id,n);d.upConstraintRemove.push(i),d.upConstraintAdd.push(o),d.downConstraintRemove.push(r),d.downConstraintAdd.push(e)}}(d.upTableAdd.length||d.downTableRemove.length||d.upConstraintAdd.length||d.downConstraintRemove.length||d.upConstraintRemove.length||d.downConstraintAdd.length||d.upTableRemove.length||d.downTableAdd.length)&&S.push(d)}if(S.length){let e=`${Date.now()}-auto-migration.js`;const getTransactionalScript=e=>`const t = await queryInterface.sequelize.transaction({autoCommit: false}); \n try {\n ${e.reduce(((e,t)=>e+`await ${t};`),"")}\n await t.commit();\n } catch(err){\n await t.rollback(); \n throw(err);\n }`,migrationFunction=(e,t)=>s(this,void 0,void 0,(function*(){if(!e.up.length&&!e.down.length)return;let n=d.default.join(m,t),o=i.MIGRATION_TEMPLATE,r=new RegExp(i.COMMENT_BLOCK_REGEX_PATTERN),s=getTransactionalScript(e.up),a=getTransactionalScript(e.down);o=o.replace(r,s),o=o.replace(r,a),this.logger.debug("Writing to file",n),l.default.writeFileSync(n,o)}));throw yield migrationFunction({up:[...S.reduce(((e,t)=>e.concat(t.upConstraintRemove)),[]),...S.reduce(((e,t)=>e.concat(t.upTableRemove)),[]),...S.reduce(((e,t)=>e.concat(t.upTableAdd)),[]),...S.reduce(((e,t)=>e.concat(t.upConstraintAdd)),[])],down:[...S.reduce(((e,t)=>e.concat(t.downConstraintRemove)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downTableRemove)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downTableAdd)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downConstraintAdd)),[]).reverse()]},e),this.logger.debug("Updating metadata file"),l.default.writeFileSync(y,JSON.stringify(this.modelMetadata.map((e=>this.getLeanModelMetadata(e))))),u.ErrorBuilder.systemError(`Migration review needed: ${e}`)}this.logger.debug("No difference, running migration"),this.logger.debug("Create database if not exist");try{yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} db:create`)}catch(e){if(String(e).indexOf("already exists")<0)throw e}if(this.logger.debug("Running migration"),this.sqlProvider===p.SqlProvider.POSTGRES){this.logger.debug("Creating unaccent extension for postgres");const e=new h.Sequelize(this.databaseURL);yield e.query("CREATE EXTENSION IF NOT EXISTS unaccent;")}else if(this.sqlProvider===p.SqlProvider.MYSQL){this.logger.debug("Creating unaccent function for mysql");const e=new h.Sequelize(this.databaseURL,{dialectOptions:{multipleStatements:!0}}),t="ĂÂÀÁẢÃẠẰẮẲẴẶẦẤẨẪẬÔƠÒÓỎÕỌỒỐỔỖỘỜỚỞỠỢÈÉẺẼẸÊỀẾỂỄỆÙÚỦŨỤƯỪỨỬỮỰÌÍỈĨỊỲÝỶỸỴ",n="AAAAAAAAAAAAAAAAAOOOOOOOOOOOOOOOOOEEEEEEEEEEEUUUUUUUUUUUIIIIIYYYYY",i=`SET GLOBAL log_bin_trust_function_creators = 1; \nDROP FUNCTION IF EXISTS unaccent; \nCREATE FUNCTION unaccent( textvalue TEXT ) RETURNS TEXT \nBEGIN \nSET @textvalue = textvalue; \nSET @withaccents = 'ŠšŽžÄÅÆÇËÎÏÑÖØÛÜŸÞäåæçëîïñõöøûüÿþƒ${t}${t.toLowerCase()}'; \nSET @withoutaccents = 'SsZzAAACEIINOOUUYBaaaceiinooouuybf${n}${n.toLowerCase()}'; \nSET @count = LENGTH(@withaccents); \nWHILE @count > 0 DO \nSET @textvalue = REPLACE(@textvalue, SUBSTRING(@withaccents, @count, 1), SUBSTRING(@withoutaccents, @count, 1)); \nSET @count = @count - 1; \nEND WHILE; \nRETURN @textvalue; \nEND; \n`;yield e.query(i,{type:h.QueryTypes.RAW})}yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${m} db:migrate`),this.logger.debug("Migration finished")}))}remove(e,t){return Object.keys(e).filter((e=>!t.includes(e))).reduce(((t,n)=>Object.assign(t,{[n]:e[n]})),{})}getLeanModelMetadata(e){return{id:e.id,fields:(0,f.getDirectFields)(e).map((e=>Object.assign({},this.remove(e,["vectorProps","stateMachineTransition","serverValue","searchable","regex","rangeProps","modificationTimestamp","mimeProps","isTimestamp","isSymbol","isLabel","injecteeSuperClass","hasMany","elementDto","creationTimestamp"]))))}}};v.COMMENT_BLOCK_REGEX_PATTERN="/\\*(\\*(?!/)|[^*])*\\*\\/",v.MIGRATION_TEMPLATE="'use strict';\n module.exports = {\n up: async (queryInterface, Sequelize) => {\n /**\n */\n },\n \n down: async (queryInterface, Sequelize) => {\n /**\n */\n }\n };",v=i=o([(0,u.Injectable)(),r("design:paramtypes",[String,String,String,u.AbstractLogger])],v),t.DefaultSqlDatabaseMigrator=v},6042:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5616:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},873:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionLink=void 0,function(e){e.CREATE_NEW="create_new",e.INHERIT_OR_CREATE="inherit_or_create",e.INHERIT_OR_THROW="inherit_or_throw"}(t.TransactionLink||(t.TransactionLink={}))},4618:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionState=void 0,function(e){e.EXECUTING="executing",e.COMMITTED="commited",e.ROLLED_BACK="rolled_back"}(t.TransactionState||(t.TransactionState={}))},7048:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getDirectFields=t.getFieldByName=t.getTransactionFromContext=void 0;const i=n(2318),o=n(137);t.getTransactionFromContext=e=>{const t=e[o.INJECTED_TRANSACTION];if(!t)throw i.ErrorBuilder.systemError("Cannot get transaction from current context");return t};t.getFieldByName=(e,t)=>e.fields.find((e=>e.name===t));t.getDirectFields=e=>e.fields.filter((e=>!e.hasMany))},859:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpAuthorizationProvider=void 0;t.AbstractHttpAuthorizationProvider=class AbstractHttpAuthorizationProvider{}},2085:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRbacAuthProvider=void 0;const o=n(2318),r=n(859),s=n(4972);class AbstractRbacAuthProvider extends r.AbstractHttpAuthorizationProvider{constructor(e,t,n){super(),this.authDataResolver=e,this.principalResolver=t,this.logger=n}getPrincipalResolver(){return this.principalResolver}resolvePrincipal(e){return this.principalResolver.resolvePrincipal(this.authDataResolver(e))}authorize(e,t,n){return i(this,void 0,void 0,(function*(){if(n.endpointMetadata.openAccess)return;const i=yield this.getRbacCache();if(!i)throw o.ErrorBuilder.error(o.Errors.SYSTEM_ERROR,"Cannot read rbac cache");let r=[];if(e){const t=yield this.getRolesOfPrincipal(e);r=(i.roles||[]).filter((e=>!!t.find((t=>t===e.roleId))))}else r=(i.roles||[]).filter((e=>e.isAnonymousRole));if(!r.length)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,"No role attached");if(r.find((e=>e.isSuperRole)))return;const a=(i.rolePolicies||[]).filter((e=>!!r.find((t=>t.roleId===e.roleId)))),d=(i.policies||[]).filter((e=>!!a.find((t=>t.policyId===e.policyId)))),l=(i.policyPermissions||[]).filter((e=>!!d.find((t=>t.policyId===e.policyId)))),c=(i.policyPermissionConditions||[]).filter((e=>!!l.find((t=>t.id===e.policyPermissionId)))),u=l.filter((e=>e.permission===(0,s.getEndpointId)(n.endpoint)));if(!u.length)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,`Not permitted: ${(0,s.getEndpointId)(n.endpoint)}`);let h=!1;for(const e of u){const i=c.filter((t=>t.policyPermissionId===e.id));if(i.length){let e=!0;const r=(0,o.getServiceProvider)().getInjector(),s=(n.endpointMetadata.accessConditions||[]).map((e=>r.resolve(e)));yield r.initInstances();for(const n of i){const i=s.find((e=>e.getConditionMetadata().name===n.conditionName));if(!i)continue;const o=yield i.resolveConditionValue(t),r=JSON.parse(n.conditionValue);if(e=yield i.validate(o,r),!e){this.logger.debug("Condition check failed: condition, requested, permitted",n.conditionName,o,r);break}}h=e}else h=!0;if(h)break}if(!h)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,"Condition check failed")}))}}t.AbstractRbacAuthProvider=AbstractRbacAuthProvider},531:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.RedisRbacAuthProvider=void 0;const o=n(2085);class RedisRbacAuthProvider extends o.AbstractRbacAuthProvider{constructor(e,t,n,i,o,r,s,a=3e4){super(i,o,s),this.serviceId=e,this.rbacChannel=t,this.principalChannel=n,this.authDataResolver=i,this.principalResolver=o,this.cacheService=r,this.logger=s,this.redisDataRetentionDurationMs=a,this.lastRbacFetchTimestamp=0,this.principalCache={}}getRbacCache(){return i(this,void 0,void 0,(function*(){if(this.lastRbacFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.rbacChannel,this.serviceId);this.rbacCache=e,this.lastRbacFetchTimestamp=Date.now()}return this.rbacCache}))}getRolesOfPrincipal(e){return i(this,void 0,void 0,(function*(){const t=String(e.id);let n=this.principalCache[t];if(!n||n.lastFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.principalChannel,t),i=e?"string"==typeof e?JSON.parse(e):e:[];n={lastFetchTimestamp:Date.now(),roles:i},this.principalCache[t]=n}return n.roles}))}}t.RedisRbacAuthProvider=RedisRbacAuthProvider},7825:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SocketRbacAuthProvider=void 0;const s=n(2318),a=n(2085),d=n(4638);let l=class SocketRbacAuthProvider extends a.AbstractRbacAuthProvider{constructor(e,t,n,i,o,r){super(n,i,o),this.rbacCacheChannel=e,this.principalCacheChannel=t,this.authDataResolver=n,this.principalResolver=i,this.logger=o,this.socketProvider=r,this.idResolvers=[]}exit(){var e;null===(e=this.socket)||void 0===e||e.close()}init(){return r(this,void 0,void 0,(function*(){this.socket=yield this.socketProvider(),this.socket.onMessage(((e,t)=>{switch(t){case this.rbacCacheChannel:this.rbacCache=e;break;case this.principalCacheChannel:const{principalId:t,roleIds:n}=e,i=this.idResolvers.find((e=>e.principalId===t));if(i){for(const e of i.resolvers)e(n);i.resolvers=[]}}})),this.socket.joinChannels([this.rbacCacheChannel,this.principalCacheChannel])}))}getRbacCache(){return r(this,void 0,void 0,(function*(){return this.rbacCache}))}getRolesOfPrincipal(e){return r(this,void 0,void 0,(function*(){return new Promise((t=>{var n;let i=this.idResolvers.find((t=>t.principalId===e.id));i||(i={principalId:e.id,resolvers:[]},this.idResolvers.push(i)),i.resolvers.length||null===(n=this.socket)||void 0===n||n.send(e.id,this.principalCacheChannel),i.resolvers.push(t)}))}))}};l=i([(0,s.Initable)(),o("design:paramtypes",[String,String,Function,d.AbstractPrincipalResolver,s.AbstractLogger,Function])],l),t.SocketRbacAuthProvider=l},9837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},1532:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HttpRequest=void 0;const i=n(2318);t.HttpRequest=class HttpRequest{constructor(e,t){this.valueHolder={},this.method=e.method,this.pathName=e.pathName,this.headers=e.headers||{},this.hash=e.hash||"",this.params=e.params||{},(null==t?void 0:t.paramsValidationDto)&&(this.params=(0,i.validateData)(this.params,null==t?void 0:t.paramsValidationDto)),this.query=e.query||{},(null==t?void 0:t.queriesValidationDto)&&(this.query=(0,i.validateData)(this.jsonParsing(this.query,t.queriesValidationDto),t.queriesValidationDto)),this.body=e.body||{},t&&(t.httpMethod===i.HttpMethod.POST||t.httpMethod===i.HttpMethod.PUT)&&(null==t?void 0:t.bodyValidationDto)&&(this.body=(0,i.validateData)(this.body||{},t.bodyValidationDto))}jsonParsing(e,t){const n=Object.assign({},e);for(const o of t.fields)try{(void 0!==e[o.name]||o.isRequired)&&(n[o.name]=JSON.parse(e[o.name]))}catch(e){throw i.ErrorBuilder.error(i.Errors.VALIDATION_ERROR,`JSON parsing failed for field ${o.name}`)}return n}getAuthInfo(){return this.authInfo}setAuthInfo(e){this.authInfo=e}getHeaders(){return this.headers}getMethod(){return this.method}getHash(){return this.hash}getPathName(){return this.pathName}getValue(e){return this.valueHolder[e]}setValue(e,t){this.valueHolder[e]=t}getParams(){return this.params}getQuery(){return this.query}getBody(){return this.body}}},8903:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseBuilder=t.HttpResponse=void 0;class HttpResponse{constructor(){this.code=200,this.headers={},this.cookies={}}}t.HttpResponse=HttpResponse;class ResponseBuilder{constructor(){this.response=new HttpResponse}status(e){return this.response.code=e,this}header(e,t){return this.response.headers[e]=t,this}cookie(e,t){return this.response.headers[e]=t,this}get(){return this.response}static json(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/json",t}static html(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="text/html; charset=UTF-8",t}static binary(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/octet-stream",t}static success(){const e=new ResponseBuilder;return e.response.code=200,e.response}static notFound(e){const t=new ResponseBuilder;return t.response.code=404,t.response.value=e,t.response}static accessDenied(e){const t=new ResponseBuilder;return t.response.code=400,t.response.value=e,t.response}}t.ResponseBuilder=ResponseBuilder},6004:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=n(2318),r=n(7048);t.AbstractHttpController=class AbstractHttpController{constructor(e){this.databaseAdapter=e}createTransaction(){return i(this,void 0,void 0,(function*(){return this.databaseAdapter.createTransaction()}))}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,r.getTransactionFromContext)(this)}))}getEndpointMetadata(){const e=(0,o.getObjectMetadata)(this.constructor);return e?e.fields.filter((e=>{return!!(t=e).httpMethod||void 0!==t.openAccess||!!t.accessConditions;var t})).map((t=>Object.assign(Object.assign({},t),{permissionGroup:e.permissionGroup}))):[]}}},225:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpMiddleware=void 0;t.AbstractHttpMiddleware=class AbstractHttpMiddleware{}},767:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;const o=n(2318),r=n(4972),s=n(6004);t.AbstractHttpRequestHandler=class AbstractHttpRequestHandler{constructor(e,t){this.mountPoint=e,this.logger=t}resolverMountPoint(e,t){if(!e)return"";const n=[];return n.push(...t),n.reduce(((e,t)=>`${e}/${t}`),"").replace(/(\/)\/+/g,"$1")}getMountedEndpointInfo(){var e,t,n;return i(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const i=[],a=(0,o.getServiceProvider)().getInjector(),d=a.resolveMultiple(s.AbstractHttpController);yield a.initInstances();for(const e of d){const t=(0,o.getObjectMetadata)(e.constructor),n=e.getEndpointMetadata();for(const r of n){const n={mount:r.httpMethod===o.SocketMethod.MESSAGE?r.url:this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),httpMethod:r.httpMethod,controller:e,handlerFunctionName:r.name};i.push({endpointMetadata:r,endpoint:n})}}const l=[];for(const o of i){const i=l.find((e=>e.endpoint.mount===o.endpoint.mount&&e.endpoint.httpMethod===o.endpoint.httpMethod));i?null===(e=this.logger)||void 0===e||e.warn(`Implicit overriding endpoint: ${(0,r.getEndpointId)(i.endpoint)} of ${null===(t=i.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${i.endpoint.handlerFunctionName}`,`Ignore ${(0,r.getEndpointId)(o.endpoint)} of ${null===(n=o.endpoint.controller)||void 0===n?void 0:n.constructor.name}:${o.endpoint.handlerFunctionName}`):l.push(o)}this.mountedEndpointInfo=l}return this.mountedEndpointInfo}))}}},7282:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const a=n(2318),d=n(1071),l=n(1532),c=n(6793),u=n(873),h=n(2417),p=n(6004),f=n(859),g=n(8903),v=n(3198),y=n(4192);class CrudHttpController extends p.AbstractHttpController{constructor(e,t,n){super(n),this.model=e,this.crudRepository=t,this.databaseAdapter=n,this.modelMetadata=(0,a.getObjectMetadata)(e)}getMountedUrl(){return`/${this.model.name.toLowerCase()}`}static queryFieldDto(e){const t={id:"",fields:CrudHttpController.getRequestQueryFieldFromModel(e)},n={name:"fields",description:"Filter records by value of their fields."};return n.dataType=a.DataType.OBJECT,n.elementDto=t,n}static projectionFieldDto(e){const t={name:"projection",description:"Project the returning records to contain only certain fields. Omit to return all."};return t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.fields.map((e=>e.name)),allowDuplicated:!1,minLength:1,elementDataType:a.DataType.STRING},t}static getBodyDtoRecordClass(e,t,n){const i={id:"",fields:[]};let o=e.fields.filter((e=>!e.hasMany));o="get_response"===t||"query"===t?o:"create_response"===t?o.filter((e=>e.pk||e.serverValue)):"create_body"===t||"update_body"===t?o.filter((e=>{var t;return!e.serverValue&&!(null===(t=e.pk)||void 0===t?void 0:t.isAutoIncrement)||!!n&&!n.fields.find((t=>{var n;return(null===(n=t.hasMany)||void 0===n?void 0:n.column)===e.name}))})):[];const r=e.fields.filter((e=>!!e.hasMany));return i.fields.push(...o.map((e=>Object.assign(Object.assign({},e),{elementDto:e.elementDto&&("update_body"===t?(0,a.partialize)(e.elementDto):e.elementDto),isRequired:!("query"===t||"update_body"===t||"get_response"===t&&!n)&&e.isRequired}))),...r.map((n=>{var i;const o=CrudHttpController.getBodyDtoRecordClass(n.hasMany.relationDto,t,e);return{description:`All records of "${null===(i=n.hasMany)||void 0===i?void 0:i.relationDto.id}" table in this relationship.`,name:n.name,dataType:a.DataType.ARRAY,isRequired:"create_response"===t,vectorProps:{elementDataType:a.DataType.OBJECT,minLength:0},elementDto:Object.assign(Object.assign({},o),{fields:("create_body"===t||"update_body"===t?o.fields.filter((e=>{var t;return e.name!==(null===(t=n.hasMany)||void 0===t?void 0:t.column)})):o.fields).map((e=>"update_body"===t?Object.assign(Object.assign({},e),{isRequired:!1,allowNull:!0}):e))})}}))),i}static getRequestQueryFieldFromModel(e){return e.fields.map((e=>{const t={};if(t.name=e.name,t.description=e.description,t.isRequired=!1,e.pk||e.fk||e.isSymbol)t.dataType=a.DataType.ARRAY,t.vectorProps={elementDataType:e.dataType,allowDuplicated:!1,allowNull:e.allowNull,minLength:1};else if(e.hasMany){const n={id:"",fields:CrudHttpController.getRequestQueryFieldFromModel(e.hasMany.relationDto).filter((t=>{var n;return t.name!==(null===(n=e.hasMany)||void 0===n?void 0:n.column)})),relaxed:!0};t.dataType=a.DataType.OBJECT,t.elementDto=n}else if(e.enum)t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.enum,allowDuplicated:!1,minLength:1,elementDataType:e.dataType,allowNull:e.allowNull};else switch(e.dataType){case a.DataType.STRING:t.dataType=a.DataType.STRING;break;case a.DataType.NUMBER:t.dataType=a.DataType.OBJECT,t.elementDto=(0,a.getObjectMetadata)(a.RangeQueryDto)}return t}))}getAuthProvider(){return s(this,void 0,void 0,(function*(){if(void 0===this.authProvider){const e=(0,a.getServiceProvider)().getInjector();this.authProvider=e.resolveOptional(f.AbstractHttpAuthorizationProvider)||null,yield e.initInstances()}return this.authProvider}))}createManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.POST,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.createMany.name,e.displayName="createMany"+this.model.name,e.bodyValidationDto=CrudHttpController.getCreateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getCreateManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,y.DtoFieldValidation)(this.model,(e=>e.getBody().records))],e.params={0:{source:"raw"}},e}getManyEndpointMetadata(){const e={};return e.httpMethod=a.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queriesValidationDto=CrudHttpController.getGetManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getGetManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,y.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields])),(0,d.FilterModelFieldAccessCondition)(this.model,(e=>e.getQuery().projection)),v.MaximumQueryLimit],e.params={0:{source:"raw"}},e}updateManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.PUT,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.updateMany.name,e.displayName="update"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.bodyValidationDto=CrudHttpController.getUpdateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,d.FilterModelFieldAccessCondition)(this.model,(e=>{const t=e.getBody().update;return t?Object.keys((0,a.leanData)(t)):[]})),(0,y.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]),"dto_field_validation_query"),(0,y.DtoFieldValidation)(this.model,(e=>[e.getBody().update]),"dto_field_validation_body")],e.params={0:{source:"raw"}},e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.params={0:{source:"raw"}},e.accessConditions=[(0,y.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]))],e}static getCreateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records to be created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_body"),t.fields.push(n),t}static getCreateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records had just been created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_response"),t.fields.push(n),t}static getGetManyResponseValidator(e){const t={id:"",fields:[]},n={name:"total",description:"Number of records found, zero is returned if the request is not paged."};n.dataType=a.DataType.NUMBER,n.isRequired=!0,t.fields.push(n);const i={name:"records",description:"The found records. All records will be returned if the request is not paged."};return i.dataType=a.DataType.ARRAY,i.isRequired=!0,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},i.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(i),t}static getGetManyQueryValidator(e){const t={id:"",fields:[CrudHttpController.queryFieldDto(e)]},n={name:"search",description:"Filter records for their @Searchable denoted fields."};n.dataType=a.DataType.STRING,t.fields.push(n),t.fields.push(CrudHttpController.projectionFieldDto(e));const i={name:"order",description:"Sort the dataset before getting result by order given in the array. Field appears first in the array will be sorted first."};i.dataType=a.DataType.ARRAY,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:1};const o={id:"",fields:[]};o.fields.push(...e.fields.filter((e=>!e.hasMany)).map((e=>{const t={};return t.name=e.name,t.isRequired=!1,t.dataType=a.DataType.STRING,t.enum=["asc","desc"],t}))),i.elementDto=o,t.fields.push(i);const r={name:"limit",description:"Limit the number of returning result."};r.dataType=a.DataType.NUMBER,r.rangeProps={min:1},t.fields.push(r);const s={name:"page",description:"Page the returning result, default to 1 if ommited. Has no effect if limit is not set."};return s.dataType=a.DataType.NUMBER,s.rangeProps={min:1},t.fields.push(s),t}static getUpdateManyQueryValidator(e){const t={name:"returning",description:"Whether to return the affected records by this request."};return t.dataType=a.DataType.BOOLEAN,t.isRequired=!1,{id:"",fields:[t,CrudHttpController.queryFieldDto(e)]}}static getUpdateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"update",isRequired:!0,description:"The update data to apply to found records."};return n.dataType=a.DataType.OBJECT,n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"update_body"),t.fields.push(n),t}static getUpdateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"modified",description:"Array of affected records."};return n.dataType=a.DataType.ARRAY,n.vectorProps={minLength:0,elementDataType:a.DataType.OBJECT},n.elementDto=n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(n),t}getEndpointMetadata(){var e,t,n,i;let o=super.getEndpointMetadata();const r=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(a.HttpMethod.GET))?o=o.filter((e=>e.name!==CrudHttpController.prototype.getMany.name)):r.push(this.getManyEndpointMetadata()),(null===(t=this.modelMetadata.ignoreCrud)||void 0===t?void 0:t.includes(a.HttpMethod.POST))?o=o.filter((e=>e.name!==CrudHttpController.prototype.createMany.name)):r.push(this.createManyEndpoinMetadata()),(null===(n=this.modelMetadata.ignoreCrud)||void 0===n?void 0:n.includes(a.HttpMethod.PUT))?o=o.filter((e=>e.name!==CrudHttpController.prototype.updateMany.name)):r.push(this.updateManyEndpoinMetadata()),(null===(i=this.modelMetadata.ignoreCrud)||void 0===i?void 0:i.includes(a.HttpMethod.DEL))?o=o.filter((e=>e.name!==CrudHttpController.prototype.deleteMany.name)):r.push(this.deleteManyEndpoinMetadata());for(const e of r){const t=o.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name&&(!t.httpMethod||!t.url)));t>=0?o[t]=Object.assign(Object.assign(Object.assign({},e),o[t]),{accessConditions:[...e.accessConditions||[],...o[t].accessConditions||[]]}):o.push(e)}return o}createMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),i=n&&(yield n.resolvePrincipal(e)),o=yield this.crudRepository.createMany({principal:i,body:e.getBody(),tx:t});return g.ResponseBuilder.json(o).get()}))}getMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.crudRepository.getMany({queries:e.getQuery(),queryProvider:this.databaseAdapter});return g.ResponseBuilder.json(t).get()}))}updateMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),i=n&&(yield n.resolvePrincipal(e)),o=yield this.crudRepository.updateMany({principal:i,queries:e.getQuery(),body:e.getBody(),tx:t});return g.ResponseBuilder.json(o).get()}))}deleteMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.crudRepository.deleteMany({queries:e.getQuery(),tx:t});return g.ResponseBuilder.json({modified:n.modified.map((e=>e.id)).map((e=>({id:e})))}).get()}))}}i([(0,c.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Create records of this table."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[l.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),i([(0,h.AccessCondition)([]),(0,h.ApiDescription)("Get records of this table."),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[l.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),i([(0,c.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and update records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[l.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),i([(0,c.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and remove records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[l.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},5879:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultHttpRequestHandler=void 0;const a=n(2318),d=s(n(9215)),l=n(99),c=s(n(9103)),u=n(8903),h=n(1532),p=n(859),f=n(767),g=n(6721);let v=class DefaultHttpRequestHandler extends f.AbstractHttpRequestHandler{constructor(e,t){super("",e),this.logger=e,this.authorizationProvider=t}accessControl(e,t){return r(this,void 0,void 0,(function*(){if(e.endpointMetadata.httpMethod!==a.SocketMethod.MESSAGE){const n=yield this.authorizationProvider.resolvePrincipal(t);if(t.setAuthInfo(n),!e.endpointMetadata.openAccess&&(yield this.authorizationProvider.authorize(n,t,e),e.endpointMetadata.tfaRequired&&!(null==n?void 0:n.hasTfa)))throw a.ErrorBuilder.error(g.Errors.TFA_REQUIRED)}}))}handleRequest(e,t){return r(this,void 0,void 0,(function*(){yield this.accessControl(e,t);const n=Object.values(e.endpointMetadata.params||{}).map((e=>{switch(e.source){case"body":return t.getBody();case"params":return t.getParams();case"queries":return t.getQuery();case"headers":return t.getHeaders();case"raw":return t}})),i=yield e.endpoint.controller[e.endpointMetadata.name](...n);return e.endpointMetadata.responseValidationDto&&(i.value=(0,a.stripData)(i.value,e.endpointMetadata.responseValidationDto)),i}))}exit(){}handle(e){return r(this,void 0,void 0,(function*(){const t=e.method,n=(0,d.default)({url:e.fullPath});let i={};const o=(yield this.getMountedEndpointInfo()).find((e=>{const o=e.endpointMetadata.httpMethod===t&&(0,l.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname);return!!o&&(i=o,!0)}));if(!o)throw this.logger.debug(e),a.ErrorBuilder.error(g.Errors.NOT_FOUND,"Handler not found");const r=new h.HttpRequest({method:t,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:c.default.parse(decodeURIComponent(n.search||"")),params:i.params,body:e.body},o.endpointMetadata);let s;try{for(const e of this.getMiddleware())if(s=yield e.intercept(r),s)break;if(s||(s=yield this.handleRequest(o,r)),!(s&&s instanceof u.HttpResponse))throw a.ErrorBuilder.systemError(`Invalid response value returned ${o.endpoint.httpMethod}:${o.endpoint.mount}, required instance of ${u.HttpResponse.name}, found ${s?null==s?void 0:s.constructor.name:s}`)}catch(e){this.logger.error(e),s=u.ResponseBuilder.json({name:e.name,message:e.message}).status([g.Errors.ACCESS_DENIED,g.Errors.AUTHENTICATION_ERROR,g.Errors.SESSION_EXPIRED].includes(e.name)?401:[g.Errors.SYSTEM_ERROR,g.Errors.CANNOT_LOCK].includes(e.name)?500:400).get()}return s}))}getMiddleware(){return[]}};v=i([(0,a.Injectable)(),o("design:paramtypes",[a.AbstractLogger,p.AbstractHttpAuthorizationProvider])],v),t.DefaultHttpRequestHandler=v},2417:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CurrentUser=t.UriMapper=t.Raw=t.Socket=t.Headers=t.Queries=t.Params=t.Body=t.AccessCondition=t.TfaRequired=t.OpenAccess=t.ApiResponse=t.Get=t.Del=t.Put=t.Post=t.Endpoint=t.ApiDescription=t.Controller=void 0;const i=n(2318);t.Controller=e=>t=>{(0,i.getServiceProvider)().register(t,"singleton");(0,i.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup};t.ApiDescription=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).description=e};t.Endpoint=e=>(t,n)=>{const o=(0,i.initFieldMetadata)(t,n);o.httpMethod=e.method,o.url=e.url};t.Post=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.POST,url:e})(n,o);t.Put=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.PUT,url:e})(n,o);t.Del=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.DEL,url:e})(n,o);t.Get=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.GET,url:e})(n,o);t.ApiResponse=e=>(t,n,o)=>{const r=(0,i.initFieldMetadata)(t,n);e===String?r.responseValidationDto={id:"",primitiveType:i.DataType.STRING,fields:[]}:e===Number?r.responseValidationDto={id:"",primitiveType:i.DataType.NUMBER,fields:[]}:e===Boolean?r.responseValidationDto={id:"",primitiveType:i.DataType.BOOLEAN,fields:[]}:r.responseValidationDto=(0,i.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,i.initFieldMetadata)(e,t).openAccess=!0};t.TfaRequired=()=>(e,t)=>{(0,i.initFieldMetadata)(e,t).tfaRequired=!0};t.AccessCondition=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).accessConditions=e};const RequestDeco=e=>(t,n,o)=>{const r=(0,i.initFieldMetadata)(t,n),s=Reflect.getMetadata("design:paramtypes",t,n)||[];switch(e){case"body":r.bodyValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"params":r.paramsValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"queries":r.queriesValidationDto=(0,i.getObjectMetadata)(s[o])}r.params||(r.params={}),r.params[o]={source:e,diClass:s[o]}};t.Body=()=>RequestDeco("body");t.Params=()=>RequestDeco("params");t.Queries=()=>RequestDeco("queries");t.Headers=()=>RequestDeco("headers");t.Socket=()=>RequestDeco("socket");t.Raw=()=>RequestDeco("raw");t.UriMapper=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).uriMapper=e};t.CurrentUser=e=>(t,n)=>{const o=(0,i.initFieldMetadata)(t,n);o.userResolver=e,o.serverValue=!0}},6507:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},4839:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FileUploadHandler=void 0;const s=n(2318),a=n(8709),d=n(6507);let l=class FileUploadHandler extends d.AbstractFileUploadHandler{constructor(e){super(),this.fileService=e}moveFile(e,t){return r(this,void 0,void 0,(function*(){yield this.fileService.moveObject(e,t)}))}removeFile(e){return r(this,void 0,void 0,(function*(){yield this.fileService.removeObject(e)}))}resolvePublicUrl(e){return r(this,void 0,void 0,(function*(){return this.fileService.getAccessUrl(e,!0)}))}resolvePrivateUrl(e){return r(this,void 0,void 0,(function*(){return this.fileService.getAccessUrl(e,!1)}))}};l=i([(0,s.Injectable)(),o("design:paramtypes",[a.AbstractFileService])],l),t.FileUploadHandler=l},5232:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5048:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRepository=void 0;const o=n(2318);t.AbstractRepository=class AbstractRepository{constructor(e){this.model=e,this.modelMetadata=(0,o.getObjectMetadata)(this.model)}beforeCreating(e,t){return i(this,void 0,void 0,(function*(){for(const n of t)for(const t of this.modelMetadata.fields)t.userResolver&&e&&(n[t.name]=t.userResolver(e))}))}project(e,t){return t?e.map((e=>t.reduce(((t,n)=>Object.assign(t,{[n]:e[n]})),{}))):e}}},9073:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoRepository=t.MultipleMap=t.SingleMap=void 0;const o=n(2318),r=n(5048),s=n(3355);t.SingleMap=(e,t,n,i,o)=>({multiple:!1,modelClass:e,forwardOps:t,forwardMapping:e=>{const t=n(e[0]||{});return t&&[t]},rootMapping:e=>{const t=e&&e[0];return i(t)},nestedMapping:o});t.MultipleMap=(e,t,n,i,o)=>({multiple:!0,modelClass:e,forwardOps:t,forwardMapping:n,rootMapping:i,nestedMapping:o});class DtoRepository extends r.AbstractRepository{constructor(e,t){super(e),this.model=e,this.dissolver=t}getMapValue(e,t,n,r,s){return i(this,void 0,void 0,(function*(){for(const i of n){const n=yield t(i);let a=r?yield r(i,i.forwardMapping(n),n):i.forwardMapping(n);if(i.nestedMapping&&a)for(const n of a)yield this.getMapValue(e,t,i.nestedMapping(n),r,s);s&&(a=yield s(i,i.forwardMapping(n),n));const d=i.rootMapping(a);(0,o.deepMerge)(e,d)}}))}createMany({principal:e,body:t,tx:n}){return i(this,void 0,void 0,(function*(){const r=[];yield this.beforeCreating(e,t.records);for(const a of t.records)yield this.getMapValue(a,(e=>i(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(),queryProvider:n})).records}))),this.dissolver(a),((t,r,a)=>i(this,void 0,void 0,(function*(){if(!r)return[];const i=new s.ModelRepository(t.modelClass),d=t.forwardOps();if(t.multiple){yield i.deleteMany({ops:d,tx:n});return(yield i.createMany({principal:e,body:{records:r},tx:n})).records}{const s=r[0];if(!s)return[];if(0===a.length){return(yield i.createMany({principal:e,body:{records:r},tx:n})).records}if(1===a.length){const t=yield i.updateMany({principal:e,ops:d,body:{update:s},tx:n});return[Object.assign(Object.assign(Object.assign({},a[0]),s),t.modified[0])]}throw o.ErrorBuilder.validationError(`Found multiple record when creating ${t.modelClass.name}`)}})))),r.push(a);return{records:r}}))}updateMany({principal:e,queries:t,ops:n,body:r,tx:a}){var d;return i(this,void 0,void 0,(function*(){if(!(null===(d=null==t?void 0:t.fields)||void 0===d?void 0:d.id)||1!==t.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const l=Object.assign(Object.assign({},r.update),{id:t.fields.id[0]});yield this.beforeCreating(e,[l]),yield this.getMapValue(l,(e=>i(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(n),queryProvider:a})).records}))),this.dissolver(l),((t,o,r)=>i(this,void 0,void 0,(function*(){if(!o)return[];const i=new s.ModelRepository(t.modelClass),d=t.forwardOps(n);if(t.multiple){yield i.deleteMany({ops:d,tx:a});return(yield i.createMany({principal:e,body:{records:o},tx:a})).records}{const t=o[0];return t?0==r.length?[]:(r.length>1?(yield i.deleteMany({ops:d,tx:a}),yield i.createMany({principal:e,body:{records:[t]},tx:a})):yield i.updateMany({principal:e,ops:d,body:{update:t},tx:a}),r.map((e=>Object.assign(Object.assign({},e),t)))):[]}}))));let c=["id"];return t.returning&&(c=[...c,...Object.keys(r.update).filter((e=>void 0!==r.update[e]))]),{modified:l.id?this.project([l],c):[]}}))}getMany({queries:e,ops:t,queryProvider:n}){var r;return i(this,void 0,void 0,(function*(){if(!(null===(r=null==e?void 0:e.fields)||void 0===r?void 0:r.id)||1!==e.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>i(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),(e=>i(this,void 0,void 0,(function*(){const i=new s.ModelRepository(e.modelClass);return(yield i.getMany({ops:e.forwardOps(t),queryProvider:n})).records})))),a.id?{records:this.project([a],e.projection),total:1}:{records:[],total:0}}))}deleteMany({queries:e,ops:t,tx:n}){var r;return i(this,void 0,void 0,(function*(){if(!(null===(r=null==e?void 0:e.fields)||void 0===r?void 0:r.id)||1!==e.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>i(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),void 0,(o=>i(this,void 0,void 0,(function*(){const i=new s.ModelRepository(o.modelClass),r=o.forwardOps(t);return(yield i.deleteMany({queries:{returning:null==e?void 0:e.returning},ops:r,tx:n})).modified})))),{modified:a.id?[a]:[]}}))}}t.DtoRepository=DtoRepository},8023:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3355:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const o=n(2318),r=n(7048),s=n(6507),a=n(5048);class ModelRepository extends a.AbstractRepository{constructor(e){super(e),this.model=e}getNestedQueries(e){return this.modelMetadata.fields.filter((e=>e.hasMany)).filter((t=>(null==e?void 0:e.fields)&&e.fields[t.name])).map((t=>{const n=t.hasMany.relationDto,i=this.getRequestQueryConditionFromQuery(null==e?void 0:e.fields[t.name],Object.assign(Object.assign({},n),{fields:n.fields.filter((e=>{var t;return e.name!==(null===(t=e.hasMany)||void 0===t?void 0:t.column)}))}));return{modelId:t.hasMany.relationDto.id,queries:i.length?{_and:i}:{}}}))}getUploadHandler(){return i(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=(0,o.getServiceProvider)().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){var n;const i=[];for(const s of(0,r.getDirectFields)(t))if(e[s.name])if(s.pk||s.fk||s.isSymbol)i.push({_in:{[s.name]:e[s.name]}});else if(s.enum)i.push({_in:{[s.name]:e[s.name]}});else switch(s.dataType){case o.DataType.STRING:if(s.searchable){const t={[(null==s?void 0:s.searchable.caseSensitive)?(null==s?void 0:s.searchable.accentSensitive)?"_sub":"_usub":(null===(n=null==s?void 0:s.searchable)||void 0===n?void 0:n.accentSensitive)?"_isub":"_iusub"]:{[s.name]:e[s.name]}};i.push(t)}else i.push({_eq:{[s.name]:e[s.name]}});break;case o.DataType.NUMBER:const t=new o.RangeQueryDto;Object.assign(t,e[s.name]),t.min&&(t.minExclusive?i.push({_gt:{[s.name]:t.min}}):i.push({_gte:{[s.name]:t.min}})),t.max&&(t.maxExclusive?i.push({_lt:{[s.name]:t.max}}):i.push({_lte:{[s.name]:t.max}}))}return i}uriHandling(e,t){return i(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();if(!n)return;const i=t.use(this.model);for(const o of this.modelMetadata.fields)if(o.uriMapper)for(const r of e){const e=r[o.name];if(!e)continue;const s=yield o.uriMapper(t,r,e);s&&(yield n.moveFile(e,s),r[o.name]=s,yield i.updateOne(r))}}))}beforeReturning(e){var t;return i(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();for(const i of e)for(const e of this.modelMetadata.fields)if(e.uriMapper&&n){if(!i[e.name])continue;i[e.name]=(null===(t=e.mimeProps)||void 0===t?void 0:t.public)?yield n.resolvePublicUrl(i[e.name]):yield n.resolvePrivateUrl(i[e.name])}}))}createMany({principal:e,body:t,tx:n}){return i(this,void 0,void 0,(function*(){const i=t.records;if(!i.length)return{records:[]};const s=(0,r.getDirectFields)(this.modelMetadata),a=this.modelMetadata.fields.filter((e=>!!e.hasMany));t.records=i.map((e=>s.reduce(((t,n)=>Object.assign(t,void 0!==e[n.name]?{[n.name]:e[n.name]}:{})),{}))),yield this.beforeCreating(e,t.records);let d=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(d,n),yield this.beforeReturning(d);const l=this.modelMetadata.fields.filter((e=>e.pk||e.serverValue||e.mimeProps)).map((e=>e.name));d=this.project(d,l);for(const r of a){const s=d.map(((e,t)=>(i[t][r.name]||[]).map((t=>Object.assign(Object.assign({},t),{[r.hasMany.column]:e.id}))))).reduce(((e,t)=>e.concat(t)),[]);if(s.length){const i=new ModelRepository((0,o.getModelById)(r.hasMany.relationDto.id));t.records=s;const a=yield i.createMany({principal:e,body:t,tx:n});for(let e=0;e<a.records.length;e++)s[e]=Object.assign(Object.assign({},s[e]),a.records[e]);for(let e=0;e<d.length;e++){const t=[];for(let n=0;n<s.length;n++)s[n][r.hasMany.column]===d[e].id&&t.push(a.records[e]);d[e]=Object.assign(Object.assign({},d[e]),{[r.name]:t})}}}return{records:d}}))}updateMany({principal:e,ops:t,queries:n,body:s,tx:a}){return i(this,void 0,void 0,(function*(){const i=t||[],d=this.modelMetadata.fields.filter((e=>!!e.hasMany)),l=(0,r.getDirectFields)(this.modelMetadata).filter((e=>void 0!==s.update[e.name])),c=l.reduce(((e,t)=>Object.assign(e,{[t.name]:s.update[t.name]})),{});if(null==n?void 0:n.fields){const e=this.getRequestQueryConditionFromQuery(n.fields,this.modelMetadata);e.length&&i.push(...e)}const u=i.length?{_and:[...i]}:{},h=this.getNestedQueries(n);let p=[];if(h.length){const e=yield a.use(this.model).getMany(u,{projection:["id"]},h);p=e.records.map((e=>e.id)),p.length&&l.length&&(yield a.use(this.model).updateMany({_in:{id:p}},c,!1))}else if(l.length)p=yield a.use(this.model).updateMany(u,c,!0);else{const e=yield a.use(this.model).getMany(u,{projection:["id"]});p=e.records.map((e=>e.id))}let f=p.map((e=>Object.assign(Object.assign({},c),{id:e})));yield this.uriHandling(f,a),yield this.beforeReturning(f);for(const t of d){const n=s.update[t.name];if(void 0===n||!p.length)continue;if(p.length>1)throw o.ErrorBuilder.systemError(`Multiple records found while updating @HasMany field: ${t.name}`);const i=f.find((e=>e.id===p[0])),r=(0,o.getModelById)(t.hasMany.relationDto.id),d=a.use(r),l=(yield d.getRecords({_eq:{[t.hasMany.column]:i.id}})).map((e=>e.id)),c=n.map((e=>e.id)).filter((e=>!!e)),u=l.filter((e=>!c.includes(e))),h=n.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:i.id}))),g=n.filter((e=>!!e.id));yield d.deleteMany({_in:{id:u}});const v=new ModelRepository(r),y=yield v.createMany({principal:e,body:{records:h},tx:a}),m=h.map(((e,t)=>Object.assign(Object.assign({},e),y.records[t])));i[t.name]=m.concat(g)}let g=["id"];return(null==n?void 0:n.returning)&&(g=[...g,...Object.keys(s.update).filter((e=>void 0!==s.update[e]))]),{modified:this.project(f,g)}}))}getMany({queries:e,ops:t,queryProvider:n}){var r;return i(this,void 0,void 0,(function*(){const i=t||[];if((null==e?void 0:e.fields)&&i.push(...this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata)),null==e?void 0:e.search){const t=this.modelMetadata.fields.filter((e=>e.searchable)).map((t=>({_iusub:{[t.name]:e.search}})));t.length&&i.push({_or:t})}const s=yield n.use(this.model).getMany(i.length?{_and:i}:{},{limit:null==e?void 0:e.limit,page:null==e?void 0:e.page,projection:null==e?void 0:e.projection,order:null===(r=null==e?void 0:e.order)||void 0===r?void 0:r.map((e=>{const t=Object.keys(e).find((t=>!!e[t]));return[t,e[t]]}))},this.getNestedQueries(e)),a=s.records.map((e=>e.id));for(const t of this.modelMetadata.fields){if(!t.hasMany||(null==e?void 0:e.projection)&&!e.projection.includes(t.name))continue;const i=(0,o.getModelById)(t.hasMany.relationDto.id),r=new ModelRepository(i),d=a.length?yield r.getMany({queries:{fields:{[t.hasMany.column]:a}},queryProvider:n}):{records:[]};for(const e of s.records)e[t.name]=d.records.filter((n=>n[t.hasMany.column]===e.id))}return yield this.beforeReturning(s.records),{total:s.total,records:this.project(s.records,null==e?void 0:e.projection)}}))}deleteMany({queries:e,ops:t,tx:n}){return i(this,void 0,void 0,(function*(){let i=t||[];if(null==e?void 0:e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&i.push(...t)}const o=i.length?{_and:[...i,...t||[]]}:{},r=this.getNestedQueries(e);let s=[];if(r.length){const e=yield n.use(this.model).getRecords(o,{},r);yield n.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}}),s=e}else s=yield n.use(this.model).deleteMany(o,null==e?void 0:e.returning);return{modified:s}}))}}t.ModelRepository=ModelRepository},2255:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractAccessCondition=void 0;t.AbstractAccessCondition=class AbstractAccessCondition{}},4192:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoFieldValidation=void 0;const r=n(2318),s=n(2255);t.DtoFieldValidation=(e,t,n)=>{let a=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:n||"dto_field_condition",valueType:r.AccessConditionValueType.DTO,valueConstraint:JSON.stringify((0,r.getObjectMetadata)(e))}}validate(e,t){return o(this,void 0,void 0,(function*(){try{for(const n of e)(0,r.validateData)(n,t);return!0}catch(e){return!1}}))}};return a=i([(0,r.Register)()],a),a}},1071:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const r=n(2318),s=n(2255);t.FilterModelFieldAccessCondition=(e,t)=>{let n=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:"filter_model_field",valueType:r.AccessConditionValueType.CHOICES,valueConstraint:(0,r.getObjectMetadata)(e).fields.map((e=>e.name))}}validate(e,t){return o(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return n=i([(0,r.Register)()],n),n}},3198:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.MaximumQueryLimit=void 0;const r=n(2318),s=n(2255);let a=class MaximumQueryLimit extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){let t=e.getQuery().limit;return t&&(t=parseInt(t)),t||0}))}validate(e,t){return o(this,void 0,void 0,(function*(){return e>0&&e<=t}))}getConditionMetadata(){return{name:"maximum_query_limit",valueType:r.AccessConditionValueType.NUMBER,valueConstraint:JSON.stringify({min:1})}}};a=i([(0,r.Register)()],a),t.MaximumQueryLimit=a},341:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.QueryTypes=void 0,o(n(9025),t),o(n(4638),t),o(n(1820),t),o(n(1870),t),o(n(4972),t),o(n(8903),t),o(n(2417),t),o(n(1532),t),o(n(5879),t),o(n(6004),t),o(n(7282),t),o(n(4435),t),o(n(767),t),o(n(225),t),o(n(2255),t),o(n(1071),t),o(n(3198),t),o(n(4192),t),o(n(859),t),o(n(2085),t),o(n(531),t),o(n(7825),t),o(n(9837),t),o(n(3355),t),o(n(9073),t),o(n(8023),t),o(n(5048),t),o(n(5530),t),o(n(2841),t),o(n(7152),t),o(n(8577),t),o(n(2665),t),o(n(9990),t),o(n(6507),t),o(n(4839),t),o(n(5232),t),o(n(5572),t),o(n(889),t),o(n(5537),t),o(n(226),t),o(n(8836),t),o(n(9627),t),o(n(6721),t),o(n(204),t),o(n(7577),t),o(n(8709),t),o(n(6793),t),o(n(3e3),t),o(n(3643),t),o(n(5616),t),o(n(6042),t),o(n(873),t),o(n(1319),t),o(n(3757),t),o(n(7220),t),o(n(9461),t),o(n(120),t),o(n(9171),t),o(n(4963),t),o(n(5670),t),o(n(1556),t),o(n(2363),t),o(n(4683),t),o(n(3346),t),o(n(9527),t),o(n(3581),t),o(n(3376),t),o(n(8104),t),o(n(5033),t);var r=n(496);Object.defineProperty(t,"QueryTypes",{enumerable:!0,get:function(){return r.QueryTypes}})},4683:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobController=void 0;const i=n(2318);t.AbstractJobController=class AbstractJobController{getAllJobs(){const e=(0,i.getObjectMetadata)(this.constructor);return(null==e?void 0:e.jobs)||[]}}},3346:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobExecutor=void 0;const o=n(2318),r=n(4683);t.AbstractJobExecutor=class AbstractJobExecutor{constructor(){this._allJobs=null}init(){return i(this,void 0,void 0,(function*(){}))}getAllJobs(){return i(this,void 0,void 0,(function*(){if(!this._allJobs){const e=(0,o.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances(),this._allJobs=t.map((e=>e.getAllJobs().map((t=>({jobName:t.jobName,handlerFn:e[t.handlerName].bind(e)}))))).reduce(((e,t)=>e.concat(t)),[])}return this._allJobs}))}}},9527:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobScheduler=void 0;const o=n(2318),r=n(4683);t.AbstractJobScheduler=class AbstractJobScheduler{constructor(e){this.logger=e}schedule(){return i(this,void 0,void 0,(function*(){const e=(0,o.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances();const n=t.map((e=>e.getAllJobs())).reduce(((e,t)=>e.concat(t)),[]).filter((e=>e.interval||e.cron));for(const e of n)this.logger.debug(`Scheduling: ${e.jobName}, at: ${e.cron||e.interval}`),this.scheduleJob({jobName:e.jobName,cron:e.cron,interval:e.interval}),this.logger.debug(`Job scheduled: ${e.jobName}`)}))}}},3581:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobExecutor=void 0;const o=n(3346);class AwsJobExecutor extends o.AbstractJobExecutor{constructor(e){super(),this.logger=e}executeJob(e,t){return i(this,void 0,void 0,(function*(){(yield this.getAllJobs()).find((t=>t.jobName===e.jobName))?e.interval||e.cron:this.logger.error(`Job not found: ${e.jobName}`)}))}}t.AwsJobExecutor=AwsJobExecutor},3376:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobScheduler=void 0;const i=n(9527);class AwsJobScheduler extends i.AbstractJobScheduler{scheduleJob(e){}}t.AwsJobScheduler=AwsJobScheduler},8104:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalJobExecutor=void 0;const o=n(3346);class LocalJobExecutor extends o.AbstractJobExecutor{constructor(e){super(),this.logger=e}executeJob(e,t){return i(this,void 0,void 0,(function*(){const t=(yield this.getAllJobs()).find((t=>t.jobName===e.jobName));t?yield t.handlerFn(e):this.logger.error(`Job not found: ${e.jobName}`)}))}}t.LocalJobExecutor=LocalJobExecutor},5033:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalJobScheduler=void 0;const a=n(2318),d=s(n(8311)),l=s(n(1495)),c=s(n(9896)),u=n(3346),h=n(9527);let p=class LocalJobScheduler extends h.AbstractJobScheduler{constructor(e,t,n,i,o,r=3e4){super(e),this.logger=e,this.jobExecutor=t,this.redisServerUrl=n,this.lockMutexKey=i,this.holdMutexKey=o,this.keyRetentionDurationSecond=r,this.intervals=[]}init(){return r(this,void 0,void 0,(function*(){this.logger.debug("LocalJobScheduler init")}))}exit(){var e;this.mutexHoldInterval&&clearInterval(this.mutexHoldInterval),null===(e=this.redisClient)||void 0===e||e.quit();for(const e of this.intervals)clearInterval(e);this.logger.debug("LocalJobScheduler exit")}extendMutexKey(){return r(this,void 0,void 0,(function*(){this.redisClient&&(yield this.redisClient.setex(this.holdMutexKey,this.keyRetentionDurationSecond,1),this.logger.debug("Scheduler extends mutex key"))}))}schedule(){const e=Object.create(null,{schedule:{get:()=>super.schedule}});return r(this,void 0,void 0,(function*(){this.redisClient||(this.redisClient=new l.default(this.redisServerUrl));if(yield this.redisClient.exists(this.holdMutexKey))return void this.logger.info("Scheduler is active, ignore");const t=new c.default([this.redisClient]);try{const n=yield t.acquire([this.lockMutexKey],this.keyRetentionDurationSecond);yield e.schedule.call(this),yield this.extendMutexKey(),yield n.release(),this.logger.debug("Schedule finished"),this.mutexHoldInterval=setInterval((()=>{this.extendMutexKey()}),Math.trunc(1e3*this.keyRetentionDurationSecond/2)+1)}catch(e){console.log(e),this.logger.info("Failed to lock mutex key, ignore")}}))}scheduleJob(e){if(e.interval){const t=setInterval((()=>this.jobExecutor.executeJob(e,0)),1e3*e.interval);this.intervals.push(t)}else if(e.cron){if(!d.default.validate(e.cron))throw a.ErrorBuilder.systemError(`Invalid cron job expression for job ${e.jobName}: ${e.cron}`);d.default.schedule(e.cron,(()=>this.jobExecutor.executeJob(e,0)))}}};p=i([(0,a.Initable)(),o("design:paramtypes",[a.AbstractLogger,u.AbstractJobExecutor,String,String,String,Number])],p),t.LocalJobScheduler=p},1556:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CustomJob=t.CronJob=t.IntervalJob=void 0;const i=n(2318);t.IntervalJob=(e,t)=>(n,o)=>{const r=(0,i.initObjectMetadata)(n);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,interval:t,handlerName:o})};t.CronJob=(e,t)=>(n,o)=>{const r=(0,i.initObjectMetadata)(n);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,cron:t,handlerName:o})};t.CustomJob=e=>(t,n)=>{const o=(0,i.initObjectMetadata)(t);o.jobs||(o.jobs=[]),o.jobs.push({jobName:e,handlerName:n})}},2363:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5572:function(e,t,n){var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FileLogMedium=void 0;const d=a(n(7147)),l=a(n(1017)),c=n(2318);let u=i=class FileLogMedium{constructor(e){const t=e.separated?i.levels.map((t=>l.default.join(e.destination,t+".log"))):[e.destination];this.destination=t.map((e=>(d.default.existsSync(l.default.dirname(e))||d.default.mkdirSync(l.default.dirname(e),{recursive:!0}),d.default.openSync(e,"a")))),this.separated=!!e.separated}init(){return s(this,void 0,void 0,(function*(){}))}exit(){this.destination.forEach((e=>d.default.closeSync(e)))}write(e,t){const n=this.separated?this.destination[i.levels.indexOf(e)]:0;d.default.appendFileSync(n,t)}};u.levels=Object.values(c.LogLevel),u=i=o([(0,c.Initable)(),r("design:paramtypes",[Object])],u),t.FileLogMedium=u},7577:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractCacheService=void 0;t.AbstractCacheService=class AbstractCacheService{}},8709:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileService=void 0;t.AbstractFileService=class AbstractFileService{}},204:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=n(7048);t.AbstractService=class AbstractService{constructor(e){this.databaseAdapter=e}createTransaction(){return this.databaseAdapter.createTransaction()}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,o.getTransactionFromContext)(this)}))}}},6862:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const i=n(2318);t.AbstractServerSocket=class AbstractServerSocket{constructor(e){this.socketInfo=e}getId(){return this.socketInfo.id}getAuthInfo(){return this.socketInfo.authInfo}send(e,t){t?this.socketInfo.channels.find((e=>e.name===t&&e.serverToClientAllowed))&&this.sendRaw({type:i.MessageType.PLAIN,data:{message:e,channel:t}}):this.sendRaw({type:i.MessageType.PLAIN,data:{message:e}})}sendRaw(e){this.physicSend(e)}disconnect(){this.physicClose()}removeChannels(e){this.socketInfo.channels=this.socketInfo.channels.filter((t=>!e.includes(t.name)))}addChannels(e){this.socketInfo.channels.push(...e)}getChannelsInfo(){return this.socketInfo.channels}}},5530:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const s=n(2318),a=r(n(1495)),d=n(9990),l=n(2665),c=n(2255),u=n(1532),h="x-socket-action",p="read",f="write";let g=class SocketReadCondition extends c.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===p}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_read",description:"Can receive message from channel",valueType:s.AccessConditionValueType.BOOLEAN}}};g=i([(0,s.Register)()],g);let v=class SocketWriteCondition extends c.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===f}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_write",description:"Can send message to channel",valueType:s.AccessConditionValueType.BOOLEAN}}};v=i([(0,s.Register)()],v);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e,t,n,i,o){this.requireAuthentication=e,this.logger=t,this.redisServerUrl=n,this.authProvider=i,this.authResolver=o,this._connectionHandler=null,this.redisClient=new a.default(this.redisServerUrl)}getUniqueChannelPrefix(){return"CHANNEL:"}getConnectionHandler(){return o(this,void 0,void 0,(function*(){if(null===this._connectionHandler){const e=(0,s.getServiceProvider)().getInjector();this._connectionHandler=e.resolveOptional(d.AbstractSocketConnectionHandler),yield e.initInstances()}return this._connectionHandler}))}formatBroadcastData(e,t){return{type:s.MessageType.PLAIN,data:{channel:e,message:t}}}getUniqueChannelName(e){return`${this.getUniqueChannelPrefix()}${e}`}getSocketIdsOfChannel(e){return o(this,void 0,void 0,(function*(){return(yield this.redisClient.smembers(this.getUniqueChannelName(e)))||[]}))}addSocketToChannel(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getById(e);n&&(n.addChannels(t),yield Promise.all(t.map((t=>this.redisClient.sadd(this.getUniqueChannelName(t.name),e)))),yield n.saveSocketInfo())}))}removeSocketFromChannel(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getById(e);n&&(n.removeChannels(t),yield Promise.all(t.map((t=>this.redisClient.srem(this.getUniqueChannelName(t),e)))),yield n.saveSocketInfo())}))}handle(e){var t;return o(this,void 0,void 0,(function*(){const n=yield this.getConnectionHandler();switch(e.method){case s.SocketMethod.CONNECT:{this.logger.debug("Socket connection attempt",e);const i=this.authResolver(null===(t=e.data)||void 0===t?void 0:t.queries),o=yield this.authProvider.getPrincipalResolver().resolvePrincipal(i);if(!o&&this.requireAuthentication)throw s.ErrorBuilder.error(s.Errors.AUTHENTICATION_ERROR);const r=yield this.addSocket({id:e.socketId,authInfo:o,channels:[],createdAt:Date.now()},e.data);if(!r)throw s.ErrorBuilder.error(s.Errors.SYSTEM_ERROR,"Socket not found after create: "+e.socketId);null==n||n.onSocketConnect(r);break}case s.SocketMethod.DISCONNECT:{this.logger.debug("Socket disconnect",e);const t=yield this.getById(e.socketId);if(t){const i=yield this.getMountedEndpointInfo();for(const n of t.getChannelsInfo()){const o=i.find((e=>e.endpointMetadata.url===n.name));o&&(o.endpoint.controller.onChannelLeave(t),yield this.removeSocketFromChannel(e.socketId,t.getChannelsInfo().map((e=>e.name))))}null==n||n.onSocketDisconnect(t),t.disconnect(),yield this.removeSocket(e.socketId)}break}case s.SocketMethod.MESSAGE:{this.logger.debug("Socket message",e);const t=e.data,i=yield this.getById(e.socketId);if(i)switch(t.type){case s.MessageType.PING_PONG:null==i||i.sendRaw({type:s.MessageType.PING_PONG,data:t.data});break;case s.MessageType.CHANNEL_JOIN:{const e=t.data,n=[];for(const t of e){let e=!1,o=!1;const r=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));if(r){try{const e=new u.HttpRequest({method:s.SocketMethod.MESSAGE,pathName:t,headers:{[h]:p}},r.endpointMetadata);yield this.authProvider.authorize(i.getAuthInfo(),e,r),o=!0}catch(e){}try{const n=new u.HttpRequest({method:s.SocketMethod.MESSAGE,pathName:t,headers:{[h]:f}},r.endpointMetadata);yield this.authProvider.authorize(i.getAuthInfo(),n,r),e=!0}catch(e){}(e||o)&&(this.logger.debug("Adding channel info",t,e,o),n.push({name:t,clientToServerAllowed:e,serverToClientAllowed:o})),r.endpoint.controller.onChannelJoin(i)}}yield this.addSocketToChannel(i.getId(),n),i.sendRaw({type:s.MessageType.CHANNEL_JOIN,data:n.map((e=>e.name))})}break;case s.MessageType.CHANNEL_LEAVE:{const e=t.data;for(const t of e){const e=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));e&&e.endpoint.controller.onChannelLeave(i)}yield this.removeSocketFromChannel(i.getId(),e)}break;case s.MessageType.PLAIN:{const e=t.data.channel,o=t.data.message;if(e){if(i.getChannelsInfo().find((t=>t.name===e&&t.clientToServerAllowed))){const t=(yield this.getMountedEndpointInfo()).find((t=>t.endpointMetadata.url===e));if(t){!1!==t.endpoint.controller.onMessage(i,o)&&(this.logger.debug("broadcasting to channel",e,o),this.broadcastToChannel(e,o))}}}else null==n||n.onMessage(i,o)}break;default:this.logger.debug("Invalid message format",t)}else this.logger.debug("Socket not found",e.socketId);break}default:return}}))}getMountedEndpointInfo(){return o(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const e=(0,s.getServiceProvider)().getInjector(),t=e.resolveMultiple(l.AbstractSocketController);yield e.initInstances(),this.mountedEndpointInfo=t.map((e=>({endpoint:{httpMethod:s.SocketMethod.MESSAGE,mount:e.channel,controller:e,handlerFunctionName:e.onMessage.name},endpointMetadata:{httpMethod:s.SocketMethod.MESSAGE,description:"Send / Receive message to / from channel",dataType:s.DataType.OBJECT,url:e.channel,name:e.channel,accessConditions:[g,v]}})))}return this.mountedEndpointInfo}))}}},9990:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketConnectionHandler=void 0;t.AbstractSocketConnectionHandler=class AbstractSocketConnectionHandler{}},2665:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketController=void 0;t.AbstractSocketController=class AbstractSocketController{constructor(e){this.channel=e}onChannelJoin(e){}onChannelLeave(e){}onMessage(e,t){}}},7152:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsSocketManager=void 0;const a=n(2318),d=s(n(9336)),l=n(767),c=n(5530),u=n(6862),h=n(859);class ApiGatewaySocket extends u.AbstractServerSocket{constructor(e,t,n,i,o,r){super(n),this.socketManager=e,this.logger=t,this.socketInfo=n,this.apiGateway=i,this.socketNamespace=o,this.redisClient=r}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.socketNamespace,this.socketInfo.id,JSON.stringify(this.socketInfo))}))}physicSend(e){this.socketManager.physicSend(this.getId(),e).catch((e=>this.logger.debug("Socket send error",e)))}physicClose(){this.socketManager.removeSocketFromRedis(this.getId()).catch((e=>this.logger.debug("Socket close error",e)))}serialize(){return JSON.stringify(this.socketInfo)}}let p=class AwsSocketManager extends c.AbstractServerSocketManager{constructor(e,t,n,i,o,r,s,a){super(e,a,i,r,s),this.authenticationRequired=e,this.region=t,this.socketDomainUrl=n,this.redisServerUrl=i,this.httpRequestHandler=o,this.authorizationProvider=r,this.authResolver=s,this.logger=a,this.apiGatewayManagement=new d.default.ApiGatewayManagementApi({region:t,apiVersion:"2018-11-29",endpoint:n})}init(){return r(this,void 0,void 0,(function*(){this.logger.info("AwsSocketManager init")}))}exit(){this.redisClient.disconnect(),this.logger.info("AwsSocketManager exit")}removeSocketFromRedis(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.hdel(this.getSocketInfoHashKey(),e)}))}getSocketInfoHashKey(){return"__SOCKET_INFO__"}physicSend(e,t){return r(this,void 0,void 0,(function*(){try{yield this.apiGatewayManagement.postToConnection({ConnectionId:e,Data:JSON.stringify(t)}).promise(),this.logger.debug(`Socket ${e} send OK`,t)}catch(t){throw this.logger.debug(`Socket ${e} post error`,t),410===t.statusCode&&(this.logger.debug(`Stale socket ${e}`),this.logger.debug(`Disconnecting ${e}`),this.logger.debug(`Removing socket ${e}`),yield Promise.all([this.removeSocket(e),this.removeSocketFromRedis(e)]),this.logger.debug(`Socket removed ${e}`)),t}}))}configure(e){this.logger.debug("Aws socket manager configure")}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){const t=yield this.getSocketIdsOfChannel(e);if(!t.length)return[];return(yield this.redisClient.hmget(this.getSocketInfoHashKey(),...t)).filter((e=>!!e)).map((e=>this.getSocketBySerialized(e)))}))}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const n=yield this.getSocketIdsOfChannel(e);if(n.length){const i=this.formatBroadcastData(e,t);yield Promise.all(n.map((e=>this.physicSend(e,i))))}}))}addSocket(e,t){return r(this,void 0,void 0,(function*(){const t=new ApiGatewaySocket(this,this.logger,e,this.apiGatewayManagement,this.getSocketInfoHashKey(),this.redisClient);return yield t.saveSocketInfo(),t}))}removeSocket(e){return r(this,void 0,void 0,(function*(){this.apiGatewayManagement.deleteConnection({ConnectionId:e}).promise().catch((e=>this.logger.error(e)))}))}getSocketBySerialized(e){return new ApiGatewaySocket(this,this.logger,JSON.parse(e),this.apiGatewayManagement,this.getSocketInfoHashKey(),this.redisClient)}getById(e){return r(this,void 0,void 0,(function*(){const t=yield this.redisClient.hget(this.getSocketInfoHashKey(),e);if(!t)throw a.ErrorBuilder.error(a.Errors.NOT_FOUND,"Cannot find socket with id: "+e);return this.logger.debug("Serialized aws socket",t),this.getSocketBySerialized(t)}))}};p=i([(0,a.Initable)(),o("design:paramtypes",[Boolean,String,String,String,l.AbstractHttpRequestHandler,h.AbstractHttpAuthorizationProvider,Function,a.AbstractLogger])],p),t.AwsSocketManager=p},8577:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},2841:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalSocketManager=void 0;const a=n(2318),d=s(n(5352)),l=s(n(9215)),c=s(n(9103)),u=n(5530),h=n(6862),p=n(859);var f;!function(e){e.SEND="SEND",e.CLOSE="CLOSE",e.SAVE="SAVE"}(f||(f={}));class RedisSocket extends h.AbstractServerSocket{constructor(e,t,n){super(n),this.socketChannelName=e,this.redisClient=t,this.socketInfo=n}physicSend(e){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.SEND,data:e}))}physicClose(){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.CLOSE}))}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.SAVE,data:this.socketInfo}))}))}}class ExpressSocket extends h.AbstractServerSocket{constructor(e,t,n){super(t),this.socket=e,this.socketInfo=t,this.infoSaver=n}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.infoSaver(this.socketInfo)}))}physicSend(e){this.socket.send(JSON.stringify(e))}physicClose(){this.socket.close()}}let g=class LocalSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n,i,o){super(e,n,t,i,o),this.authenticationRequired=e,this.redisServerUrl=t,this.logger=n,this.authProvider=i,this.authResolver=o,this.allSockets=[],this.subscribedChannels=[],this.subClient=this.redisClient.duplicate(),this.channelSubClient=this.redisClient.duplicate(),this.sendClient=this.redisClient.duplicate()}init(){return r(this,void 0,void 0,(function*(){this.logger.info("LocalSocketManager init"),this.channelSubClient.on("message",((e,t)=>{this.logger.debug("channelSubClient: ",t,e),this.channelMessageListenner(t,e)})),this.subClient.on("message",((e,t)=>{this.logger.debug("subClient: ",t,e),this.socketMessageListener(t,e)}))}))}exit(){this.sendClient.disconnect(),this.subClient.disconnect(),this.channelSubClient.disconnect(),this.redisClient.disconnect(),this.logger.info("LocalSocketManager exit")}channelMessageListenner(e,t){this.logger.debug("Receiving message from channel",t,e);const n=JSON.parse(e);n.type===a.MessageType.PLAIN&&this.allSockets.forEach((e=>{e.send(n.data.message,n.data.channel)}))}socketMessageListener(e,t){this.logger.debug("Receiving message from remote socket channel",t,e);const n=t.substring(this.getSocketChannelKeyPrefix().length),i=this.allSockets.find((e=>e.getId()===n));if(i){const t=JSON.parse(e);switch(t.type){case f.SEND:i.physicSend(t.data);break;case f.SAVE:i.socketInfo.channels=t.data,i.saveSocketInfo();break;case f.CLOSE:i.disconnect();break;default:this.logger.debug("Invalid remote command",t)}}}getUniqueDataChannelName(e){return`CHANNEL_DATA:${e}`}getSocketChannelKeyPrefix(){return"SOCKET_CHANNEL:"}getSocketInfoHashKey(){return"__SOCKET_INFO__"}getSocketChannelKey(e){return`${this.getSocketChannelKeyPrefix()}${e}`}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("Broadcasting",e,t);const n=this.formatBroadcastData(e,t);yield this.redisClient.publish(this.getUniqueDataChannelName(e),JSON.stringify(n))}))}addSocketToChannel(e,t){const n=Object.create(null,{addSocketToChannel:{get:()=>super.addSocketToChannel}});return r(this,void 0,void 0,(function*(){yield n.addSocketToChannel.call(this,e,t);const i=t.map((e=>e.name)).filter((e=>!this.subscribedChannels.includes(e)));i.length&&(yield Promise.all(i.map((e=>this.channelSubClient.subscribe(this.getUniqueDataChannelName(e))))),this.subscribedChannels.push(...i))}))}removeSocketFromChannel(e,t){const n=Object.create(null,{removeSocketFromChannel:{get:()=>super.removeSocketFromChannel}});return r(this,void 0,void 0,(function*(){yield n.removeSocketFromChannel.call(this,e,t),yield Promise.all(t.map((e=>this.channelSubClient.unsubscribe(this.getUniqueChannelName(e))))),this.subscribedChannels=this.subscribedChannels.filter((e=>!t.includes(e)))}))}addSocket(e,{socket:t}){return r(this,void 0,void 0,(function*(){const n=new ExpressSocket(t,e,(e=>r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.getSocketInfoHashKey(),e.id,JSON.stringify(e))})))),i=this.getSocketChannelKey(e.id);return this.subClient.subscribe(i),this.allSockets.push(n),n}))}removeSocket(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.hdel(this.getSocketInfoHashKey(),e);const t=this.getSocketChannelKey(e);this.subClient.unsubscribe(t),this.allSockets=this.allSockets.filter((t=>t.getId()!==e))}))}getById(e){return r(this,void 0,void 0,(function*(){let t=this.allSockets.find((t=>t.getId()===e));if(!t){const n=yield new Promise((t=>this.redisClient.hget(this.getSocketInfoHashKey(),e).then((e=>t(e?JSON.parse(e):void 0))).catch((e=>{this.logger.error(e),t(void 0)}))));n&&(t=new RedisSocket(this.getSocketChannelKey(e),this.sendClient,n))}return t}))}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){const t=yield this.getSocketIdsOfChannel(e);return(yield Promise.all(t.map((e=>this.getById(e))))).filter((e=>!!e))}))}configure(e){if(!e)return;this.logger.debug("Local socket manager configure");new d.default.Server({server:e}).on("connection",((e,t)=>{const n=t.headers["sec-websocket-key"],i=(0,l.default)({url:t.url}),o=c.default.parse(decodeURIComponent(i.search||""));this.handle({method:a.SocketMethod.CONNECT,socketId:n,data:{queries:o,socket:e}}).catch((t=>{e.close(1e3,`${t.name}:${t.message}`)})),e.onmessage=e=>{this.handle({method:a.SocketMethod.MESSAGE,socketId:n,data:e.data&&JSON.parse(e.data)}).catch((e=>{this.logger.error(e)}))},e.onclose=()=>{this.handle({method:a.SocketMethod.DISCONNECT,socketId:n}).catch((e=>{this.logger.error(e)}))}}))}};g=i([(0,a.Initable)(),o("design:paramtypes",[Boolean,String,a.AbstractLogger,p.AbstractHttpAuthorizationProvider,Function])],g),t.LocalSocketManager=g},5537:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const o=n(2318),r=n(137),s=n(4972);class ClaireServer extends o.ClaireApp{constructor(e,t,n){super(),this.logger=e,this.httpRequestHandler=t,this.socketManager=n,this.booted=!1}init(){return i(this,void 0,void 0,(function*(){if(this.booted)return;const e=[];if(this.httpRequestHandler){const t=yield this.httpRequestHandler.getMountedEndpointInfo();e.push(...t)}if(this.socketManager){const t=yield this.socketManager.getMountedEndpointInfo();e.push(...t)}for(const t of e)this.logger.info(`Mounting: ${(0,s.getEndpointId)(t.endpoint)}`);(0,o.getGlobalStore)().mountedEndpointInfo=e,this.logger.debug("Claire server initing"),this.logger.debug("Setting up exception handlers"),process.on("SIGTERM",(()=>(this.logger.warn("SIGTERM interrupt signal"),this.stop(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("SIGINT",(()=>(this.logger.warn("SIGINT interrupt signal"),this.stop(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("uncaughtException",(e=>{this.logger.error("uncaughtException",e.name,e.stack)})),process.on("unhandledRejection",(e=>{this.logger.error("unhandledRejection",e.name,e.stack)})),this.booted=!0}))}exit(){super.exit()}stop(e){this.logger.debug("Server is shutting down"),this.exit(),process.exit(e)}}t.ClaireServer=ClaireServer},226:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressWrapper=void 0;const r=n(2318),s=o(n(6860)),a=o(n(3685)),d=o(n(3582)),l=o(n(6674)),c=n(5530),u=n(767);t.ExpressWrapper=class ExpressWrapper{constructor(e,t){this.injector=(0,r.getServiceProvider)().getInjector(),this.server=e,this.config=t,this.logger=this.injector.resolve(r.AbstractLogger),this.socketManager=this.injector.resolveOptional(c.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(u.AbstractHttpRequestHandler)}close(){var e;null===(e=this.httpServer)||void 0===e||e.close(),this.server.exit()}listen(e){var t,n;return i(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const o=(0,s.default)(),c=a.default.createServer(o);return null===(t=this.socketManager)||void 0===t||t.configure(c),o.use((0,d.default)()),o.use(s.default.raw({limit:1024*((null===(n=this.config)||void 0===n?void 0:n.maxBodySizeKB)||4096)})),o.use((0,l.default)()),o.use(((e,t,n)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),n()})),o.use(s.default.urlencoded({extended:!1})),o.use(s.default.json()),o.all("*",((e,t)=>{(()=>i(this,void 0,void 0,(function*(){if(!!e.headers["x-amzn-apigateway-api-id"]){if(!this.socketManager)throw r.ErrorBuilder.systemError("Socket manager not found");const n={socketId:e.body.connectionId,data:e.body.data,method:e.body.type.toLowerCase()};if(n.method===r.SocketMethod.CONNECT){const t=e.body.data.querystring,i=t.substring(1,t.length-1).split(",").map((e=>e.trim().split("="))).reduce(((e,t)=>Object.assign(e,{[t[0]]:t[1]})),{});n.data={queries:i}}yield this.socketManager.handle(n).then((()=>{t.status(200).send()})).catch((e=>{var t;this.logger.debug("Handle error",e),null===(t=this.socketManager)||void 0===t||t.removeSocket(n.socketId).catch((e=>{this.logger.debug(e)}))}))}else{if(!this.httpRequestHandler)throw r.ErrorBuilder.systemError("Http request handler not found");const n={fullPath:e.url,method:e.method.toLowerCase(),headers:e.headers,body:e.body},i=yield this.httpRequestHandler.handle(n);i.headers&&Object.keys(i.headers).forEach((e=>{t.set(e,i.headers[e])})),t.status(i.code).send(i.value)}})))().catch((e=>{this.logger.error(e),t.status(400).json({name:e.name,message:e.message})}))})),new Promise(((t,n)=>{this.httpServer=c.listen(e,t).on("error",n)}))}))}}},8836:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const o=n(2318),r=n(767),s=n(5530),a=n(6721),toApiGatewayFormat=(e,t)=>({statusCode:e,body:t&&JSON.stringify(t),headers:{"Access-Control-Allow-Headers":"*","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"*","Content-Type":"application/json"}});t.LambdaWrapper=class LambdaWrapper{constructor(e,t){this.serverFactory=e,this.requestMapper=t,this.requestMapper=t,this.handler=this.handler.bind(this),this.injector=(0,o.getServiceProvider)().getInjector(),this.socketManager=this.injector.resolveOptional(s.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(r.AbstractHttpRequestHandler)}bootServer(){var e;return i(this,void 0,void 0,(function*(){return this._server||(this._server=yield this.serverFactory(),yield this.injector.initInstances(),null===(e=this.socketManager)||void 0===e||e.configure(),yield this._server.init()),this._server}))}handler(e){return i(this,void 0,void 0,(function*(){yield this.bootServer();const t=this.requestMapper(e);if(!t)return toApiGatewayFormat(400,"Cannot resolve event");if(t.method===o.HttpMethod.OPTIONS)return toApiGatewayFormat(200);try{if(Object.values(o.HttpMethod).includes(t.method)){if(!this.httpRequestHandler)throw o.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Http request handler not found");const e={fullPath:t.rawPath,method:t.method,headers:t.headers,body:t.body},n=yield this.httpRequestHandler.handle(e);return toApiGatewayFormat(n.code,n.value)}if(!Object.values(o.SocketMethod).includes(t.method))throw o.ErrorBuilder.error(a.Errors.HTTP_REQUEST_ERROR,"Not allow request method: "+t.method);{if(!this.socketManager)throw o.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Socket manager not found");const e={socketId:t.rawPath,method:t.method,data:t.body};yield this.socketManager.handle(e)}return toApiGatewayFormat(200)}catch(e){return toApiGatewayFormat(400,{name:e.name,message:e.message})}}))}}},9627:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6721:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Errors=void 0;const i=n(2318);t.Errors=Object.assign(Object.assign({},i.Errors),{TFA_REQUIRED:"TFA_REQUIRED"})},889:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lambdaRequestMapper=void 0;const i=n(2318);t.lambdaRequestMapper=e=>{if(e.requestContext.eventType){const t=e.requestContext.eventType.toLowerCase(),n=e.body&&JSON.parse(e.body);return{method:t,rawPath:e.requestContext.connectionId,body:t===i.SocketMethod.CONNECT?{queries:e.queryStringParameters}:n}}return{method:e.requestContext.http.method.toLowerCase(),rawPath:`${e.rawPath}?${e.rawQueryString}`,body:e.body&&JSON.parse(e.body),headers:e.headers}}},2318:e=>{e.exports=require("@clairejs/core")},9336:e=>{e.exports=require("aws-sdk")},3582:e=>{e.exports=require("cors")},6860:e=>{e.exports=require("express")},6674:e=>{e.exports=require("express-fileupload")},1495:e=>{e.exports=require("ioredis")},8311:e=>{e.exports=require("node-cron")},9215:e=>{e.exports=require("parseurl")},99:e=>{e.exports=require("path-to-regexp")},9103:e=>{e.exports=require("query-string")},9896:e=>{e.exports=require("redlock")},496:e=>{e.exports=require("sequelize")},5352:e=>{e.exports=require("ws")},2081:e=>{e.exports=require("child_process")},7147:e=>{e.exports=require("fs")},3685:e=>{e.exports=require("http")},1017:e=>{e.exports=require("path")}},t={};return function __webpack_require__(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,__webpack_require__),o.exports}(341)})()));
1
+ !function webpackUniversalModuleDefinition(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,(()=>(()=>{"use strict";var e={9025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FileOperation=void 0,function(e){e.GET="getObject",e.PUT="putObject",e.DELETE="deleteObject"}(t.FileOperation||(t.FileOperation={}))},4638:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractPrincipalResolver=void 0;t.AbstractPrincipalResolver=class AbstractPrincipalResolver{}},1820:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},137:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExitCode=t.INJECTED_TRANSACTION=void 0,t.INJECTED_TRANSACTION="__INJECTED_TRANSACTION__",t.ExitCode={SIGTERM_INTERUPTION:-1,SIGINT_INTERUPTION:-2,UNCAUGHT_EXCEPTION:-3,UNHANDLED_REJECTION:-4}},4435:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},4972:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEndpointId=void 0;t.getEndpointId=e=>`${e.httpMethod}:${e.mount}`},1870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3e3:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},120:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseAdapter=void 0;const o=n(2318);t.AbstractDatabaseAdapter=class AbstractDatabaseAdapter{constructor(){this.modelMetadata=[],this.models=[],this.modelConnections={}}init(){return i(this,void 0,void 0,(function*(){this.models=((0,o.getGlobalStore)().models||[]).slice(),this.modelMetadata=this.models.map((e=>(0,o.getObjectMetadata)(e))),this.modelConnections=this.modelMetadata.reduce(((e,t)=>Object.assign(e,{[t.id]:{connection:void 0}})),{})}))}exit(){}}},5549:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractQuery=void 0;const i=n(2318);t.AbstractQuery=class AbstractQuery{constructor(e){const t=(0,i.getObjectMetadata)(e);this.model=(0,i.getModelById)(t.id)||e,this.metadata=(0,i.getObjectMetadata)(this.model)}convertToLogicObjects(e,t){return e.map((e=>{let n=new this.model;return this.metadata.fields.filter((e=>!t||t.includes(e.name))).forEach((t=>{const i=e[t.name];void 0!==i&&(t.isBigInt?n[t.name]=Number(i):t.vectorProps?n[t.name]=JSON.parse(i):n[t.name]=i)})),n}))}convertToDataObjects(e,t){const n=Date.now();return e.map((e=>{let i=new this.model;for(const o of this.metadata.fields){let r=e[o.name];o.vectorProps?r=JSON.stringify(r):(o.modificationTimestamp||o.creationTimestamp&&!t)&&(r=n),i[o.name]=r}return i}))}}},9171:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseAdapter=void 0;const s=n(2318),a=n(496),d=n(4618),l=n(120),c=n(5549),u=n(7220),h=n(7048),getModelId=e=>{const t=(0,s.getObjectMetadata)(e);if(!t)throw s.ErrorBuilder.systemError(`Metadata for ${e.name} not found, check @Model decorator`);return t.id},p=["_and","_or"],f=[["_and",a.Op.and],["_or",a.Op.or],["_eq",a.Op.eq],["_neq",a.Op.ne],["_gt",a.Op.gt],["_lt",a.Op.lt],["_gte",a.Op.gte],["_lte",a.Op.lte],["_regex",a.Op.regexp],["_sub",a.Op.like],["_in",a.Op.in],["_nin",a.Op.notIn]],convertOp=e=>f.find((t=>t[0]===e))[1],safetifyColumn=(e,t)=>{const n=t===u.SqlProvider.MYSQL?"`":'"';return e.split(".").map((e=>`${n}${e}${n}`)).join(".")},getAggregatorColumn=(e,t)=>{const n=safetifyColumn(e.field,t);switch(e.fn){case"count":return`${!0===e.args?`COUNT(DISTINCT(${n}))`:`COUNT(${n})`}${t===u.SqlProvider.POSTGRES?"::int":""}`;case"sum":return`SUM(${n})`;case"avg":return`AVG(${n})`;case"min":return`MIN(${n})`;case"max":return`MAX(${n})`;case"join":return t===u.SqlProvider.POSTGRES?`string_agg(${n}, '${e.args}')`:`GROUP_CONCAT(${n} SEPARATOR '${e.args}')`;case"is":return n;default:throw s.ErrorBuilder.systemError(`Not supported agg function: ${e.fn}`)}};class Joiner{constructor(e){this.adapter=e,this.joinInfo=[],this.columnId=0}join(e,t,n,i){return this.joinInfo.push({rightModel:e,leftField:t,rightField:n,joinMode:i||"inner"}),this}where(e){return this.queryCondition=e,this}groupBy(e){return this.groupByFields=e,this}having(e){return this.havingCondition=e,this}getExecuteCondition(){const e=[],t=this.convertHavingCondition(this.havingCondition||{},e);return{conditions:{where:this.adapter.getQueryObjectFromQueryConditions(this.queryCondition,!0),transaction:this.adapter.transaction,include:this.joinInfo.map((e=>{const t=(0,s.getTableName)(e.rightModel);return{attributes:[],model:this.adapter.modelConnections[t].connection,duplicating:!1,required:"inner"===e.joinMode,right:"right"===e.joinMode,on:{[`$${e.leftField}$`]:{[convertOp("_eq")]:a.Sequelize.col(e.rightField)}}}})),group:this.groupByFields,attributes:this.adapter.sqlProvider===u.SqlProvider.POSTGRES?[]:e.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId])),having:t,raw:!0},collector:e}}countWithCondition(e){var t;return r(this,void 0,void 0,(function*(){e.offset=0,e.limit=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?1:0,e.attributes=[...this.adapter.sqlProvider===u.SqlProvider.MYSQL&&e.attributes||[],[this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.literal("(COUNT(*) OVER ())::int"):a.Sequelize.literal("COUNT(*)"),"count"]];const n=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?yield this.adapter.getCurrentConnection().findAll(e):yield this.adapter.getCurrentConnection().count(e);return(null===(t=n[0])||void 0===t?void 0:t.count)||0}))}count(){return r(this,void 0,void 0,(function*(){const{conditions:e}=this.getExecuteCondition();return this.countWithCondition(e)}))}rows(e,t){return r(this,void 0,void 0,(function*(){const{conditions:n,collector:i}=this.getExecuteCondition();n.attributes=[...n.attributes||[],...Object.keys(e).map((t=>[a.Sequelize.literal(getAggregatorColumn(e[t],this.adapter.sqlProvider)),t]))],n.limit=null==t?void 0:t.limit,n.offset=(null==t?void 0:t.limit)&&t.limit*((t.page||1)-1),(null==t?void 0:t.order)&&(n.order="random"===t.order?this.adapter.dbConnection.random():t.order);const o=yield this.adapter.getCurrentConnection().findAll(n);return{total:yield this.countWithCondition(Object.assign(Object.assign({},n),{attributes:i.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId]))})),records:o}}))}convertHavingOperation(e,t){const n=getAggregatorColumn(t[0],this.adapter.sqlProvider);return{columnId:"col__"+this.columnId++,sequelizeColumn:n,sequelizeOps:{[convertOp(e)]:t[1]}}}convertHavingCondition(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>{if(p.includes(n))return{[convertOp(n)]:e[n].map((e=>this.convertHavingCondition(e,t)))};{const i=this.convertHavingOperation(n,e[n]);return t.push(i),this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.where(a.Sequelize.literal(i.sequelizeColumn),i.sequelizeOps):{[i.columnId]:i.sequelizeOps}}}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class ModelAdapter extends c.AbstractQuery{constructor(e){super(e.model),this.dbConnection=e.dbConnection,this.modelConnections=e.modelConnections,this.transaction=e.transaction,this.sqlProvider=e.sqlProvider,this.logger=null==e?void 0:e.logger}getCurrentConnection(){const e=(0,s.getObjectMetadata)(this.model).id;return this.modelConnections[e].connection}resolveNestedIncludes(e){return e&&e.map((e=>({model:this.modelConnections[e.modelId].connection,where:this.getQueryObjectFromQueryConditions(e.queries)})))}join(e,t,n,i){const o=new Joiner(this);return o.join(e,t,n,i),o}count(e,t,n){return r(this,void 0,void 0,(function*(){const i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};return(null==t?void 0:t.distinct)&&Object.assign(i,{distinct:!0,col:t.distinct}),yield this.getCurrentConnection().count(i)}))}getById(e,t){return this.getOne({_eq:{id:e}},t)}getByIds(e,t){return this.getRecords({_in:{id:e}},t)}getOne(e,t){return r(this,void 0,void 0,(function*(){const n=yield this.getMany(e,{limit:1});return n.records.length?this.convertToLogicObjects(n.records,null==t?void 0:t.projection)[0]:void 0}))}getRecords(e,t,n){return r(this,void 0,void 0,(function*(){return(yield this.getMany(e,t,n)).records}))}getMany(e,t,n){return r(this,void 0,void 0,(function*(){let i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};if((null==t?void 0:t.order)&&Object.assign(i,{order:"random"===t.order?this.dbConnection.random():t.order}),(null==t?void 0:t.projection)&&Object.assign(i,{attributes:t.projection}),(null==t?void 0:t.limit)&&(i=Object.assign(i,{limit:t.limit}),t.page&&(i=Object.assign(i,{offset:t.limit*(t.page-1)}))),1!==(null==t?void 0:t.limit)||t.page){if(null==t?void 0:t.limit){const{count:e,rows:n}=yield this.getCurrentConnection().findAndCountAll(i);return{total:e,records:this.convertToLogicObjects(n,null==t?void 0:t.projection)}}{const e=yield this.getCurrentConnection().findAll(i);return{total:0,records:this.convertToLogicObjects(e,null==t?void 0:t.projection)}}}{const e=yield this.getCurrentConnection().findOne(i);return{total:0,records:e?this.convertToLogicObjects([e],t.projection):[]}}}))}createOne(e){return r(this,void 0,void 0,(function*(){return(yield this.createMany([e]))[0]}))}createMany(e){return r(this,void 0,void 0,(function*(){let t=yield this.getCurrentConnection().bulkCreate(this.convertToDataObjects(e),{transaction:this.transaction});return this.convertToLogicObjects(t)}))}updateOne(e){return r(this,void 0,void 0,(function*(){return yield this.getCurrentConnection().update(this.convertToDataObjects([e],!0)[0],{where:this.getQueryObjectFromQueryConditions({_eq:{id:e.id}}),transaction:this.transaction}),e}))}updateMany(e,t,n){return r(this,void 0,void 0,(function*(){if(n){const n=yield this.getRecords(e,{projection:["id"]});if(!n.length)return[];const i=n.map((e=>e.id));return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions({_in:{id:i}}),transaction:this.transaction}),i}return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}deleteOne(e){return r(this,void 0,void 0,(function*(){return yield this.deleteMany({_eq:{id:e.id}}),e}))}deleteMany(e,t){return r(this,void 0,void 0,(function*(){if(t){const t=yield this.getMany(e);if(!t.records.length)return[];const n=t.records.map((e=>e.id));return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions({_in:{id:n}}),transaction:this.transaction}),t.records}return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}rawQuery(...e){return r(this,void 0,void 0,(function*(){const t=e[0],n=e[1]||{};if("string"!=typeof t)throw s.ErrorBuilder.error(s.Errors.QUERY_ERROR,"First argument of raw sql expected to be string");return this.dbConnection.query(t,Object.assign({transaction:this.transaction,raw:!0},n))}))}mapToSequelizeOperator(e,t,n,i,o){const r=o?a.Sequelize.literal(safetifyColumn(n,e)):a.Sequelize.col(n);switch(t){case"_sub":switch(this.sqlProvider){case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_cs`)});default:return a.Sequelize.where(r,{[a.Op.like]:`%${i}%`})}case"_isub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(r,{[a.Op.iLike]:`%${i}%`});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_ci`)})}case"_usub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)}) COLLATE utf8mb4_0900_as_cs`)})}case"_iusub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.iLike]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_ai_ci`)})}case"_in":case"_nin":const o=i||[],s=o.filter((e=>null!==e)),d=s.length<o.length,l=convertOp(t);return d?a.Sequelize.or(a.Sequelize.where(r,{[a.Op.eq]:null}),...s.length?[a.Sequelize.where(e===u.SqlProvider.MYSQL?a.Sequelize.literal(`CAST(${safetifyColumn(n,e)} as BINARY)`):r,{[l]:s})]:[]):a.Sequelize.where(e===u.SqlProvider.MYSQL?a.Sequelize.literal(`CAST(${safetifyColumn(n,e)} as BINARY)`):r,{[l]:o});default:return a.Sequelize.where(r,{[convertOp(t)]:i})}}getQueryObjectFromQueryConditions(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>p.includes(n)?{[convertOp(n)]:e[n].map((e=>this.getQueryObjectFromQueryConditions(e)))}:{[convertOp("_and")]:Object.keys(e[n]).map((i=>this.mapToSequelizeOperator(this.sqlProvider,n,i,e[n][i],t)))}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class TransactionAdapter{constructor(e){this.modelAdapters={},this.transaction=e.transaction,this.dbConnection=e.dbConnection,this.logger=e.logger,this.modelConnections=e.modelConnections,this.sqlProvider=e.sqlProvider,this.transactionState=d.TransactionState.EXECUTING}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(this.modelAdapters,n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,transaction:this.transaction,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}commit(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.COMMITTED,this.transaction.commit()}))}rollback(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.ROLLED_BACK,this.transaction.rollback()}))}getState(){return this.transactionState}}let g=class DefaultSqlDatabaseAdapter extends l.AbstractDatabaseAdapter{constructor(e,t,n){super(),this.logger=n,this.modelAdapters={},this.sqlProvider=e,this.dbConnection=new a.Sequelize(`${e}://${t}`,{dialect:this.sqlProvider,logging:e=>this.logger.debug(e),define:{timestamps:!1}})}createTransaction(){return r(this,void 0,void 0,(function*(){let e=yield this.dbConnection.transaction();return new TransactionAdapter({transaction:e,dbConnection:this.dbConnection,logger:this.logger,modelConnections:this.modelConnections,sqlProvider:this.sqlProvider})}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});var t,n,i,o;return r(this,void 0,void 0,(function*(){yield e.init.call(this),null===(t=this.logger)||void 0===t||t.debug("Connecting to database"),yield this.dbConnection.authenticate(),null===(n=this.logger)||void 0===n||n.debug("Generating in-memory schema");for(const e of this.modelMetadata){const t=this.generateSchemaObject(e);this.modelConnections[e.id].connection=t}for(const e of this.modelMetadata){const t=this.modelConnections[e.id].connection,n=e.fields.filter((e=>e.fk));for(const o of n){const n=null===(i=o.fk)||void 0===i?void 0:i.dtoId;if(!n)throw s.ErrorBuilder.systemError(`FK model id not resolved for ${e.id}:${o.name}`);const r=this.modelConnections[n].connection;t.belongsTo(r,{foreignKey:o.name}),r.hasMany(t,{foreignKey:o.name})}}null===(o=this.logger)||void 0===o||o.debug("Database adapter init succeeded")}))}exit(){var e;return null===(e=this.logger)||void 0===e||e.debug("Closing connection to database"),this.dbConnection.close(),0}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}generateSchemaObject(e){let t={};const n=(0,h.getDirectFields)(e);for(const e of n){switch(t[e.name]={},e.dataType){case s.DataType.NUMBER:e.floating?t[e.name].type=a.DataTypes.FLOAT:e.isBigInt?t[e.name].type=a.DataTypes.BIGINT:t[e.name].type=a.DataTypes.INTEGER;break;case s.DataType.STRING:e.textLength?t[e.name].type=a.DataTypes.STRING(e.textLength):t[e.name].type=a.DataTypes.STRING;break;case s.DataType.BOOLEAN:t[e.name].type=a.DataTypes.BOOLEAN;break;case s.DataType.ARRAY:case s.DataType.OBJECT:t[e.name].type=a.DataTypes.TEXT}e.pk&&(t[e.name].primaryKey=!0,e.pk.isAutoIncrement&&(t[e.name].autoIncrement=!0)),void 0!==e.defaultValue&&(t[e.name].defaultValue=e.defaultValue),t[e.name].allowNull=!e.isRequired}return this.dbConnection.define(e.id,t,{tableName:e.id,freezeTableName:!0,name:{singular:e.id,plural:e.id}})}};g=i([(0,s.Initable)(),(0,s.Injectable)(),o("design:paramtypes",[String,String,s.AbstractLogger])],g),t.DefaultSqlDatabaseAdapter=g},1319:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},9461:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3757:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._is=t._join=t._max=t._min=t._avg=t._sum=t._count=void 0;t._count=(e,t)=>({fn:"count",field:e,args:t});t._sum=e=>({fn:"sum",field:e});t._avg=e=>({fn:"avg",field:e});t._min=e=>({fn:"min",field:e});t._max=e=>({fn:"max",field:e});t._join=(e,t)=>({fn:"join",field:e,args:t});t._is=e=>({fn:"is",field:e})},7220:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqlProvider=t.NoSqlProvider=void 0,function(e){e.MONGODB="mongodb",e.DYNAMODB="dynamodb"}(t.NoSqlProvider||(t.NoSqlProvider={})),function(e){e.MYSQL="mysql",e.POSTGRES="postgres"}(t.SqlProvider||(t.SqlProvider={}))},6793:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Transactional=void 0;const o=n(2318),r=n(137),s=n(873),a=n(4618);t.Transactional=e=>(t,n,d)=>{const l=(0,o.initObjectMetadata)(t);(0,o.initFieldMetadata)(t,n),l.transactional=!0;const c=d.value;d.value=function(...d){return i(this,void 0,void 0,(function*(){const i=this;let l,u,h;try{l=yield i.getCurrentTransaction()}catch(e){}switch(e){case s.TransactionLink.CREATE_NEW:u=!0,h=yield i.createTransaction();break;case s.TransactionLink.INHERIT_OR_CREATE:u=!l,h=l||(yield i.createTransaction());break;case s.TransactionLink.INHERIT_OR_THROW:if(u=!1,!l)throw o.ErrorBuilder.systemError(`No transaction to inherit when executing ${t.constructor.name}:${n}`);h=l}const p=Object.assign(Object.create(i),i),f=Object.keys(p).filter((e=>{var t,n;return(null===(t=p[e])||void 0===t?void 0:t.constructor)&&(null===(n=(0,o.getObjectMetadata)(p[e].constructor))||void 0===n?void 0:n.transactional)}));for(const e of f){const t=p[e],n=Object.assign(Object.create(t),t,{[r.INJECTED_TRANSACTION]:h});p[e]=n}try{Object.assign(p,{[r.INJECTED_TRANSACTION]:h});let e=yield c.call(p,...d);return h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.commit()),e}catch(e){throw h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.rollback()),e}}))},Object.defineProperty(d.value,"name",{value:n})}},5670:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseMigrator=void 0;t.AbstractDatabaseMigrator=class AbstractDatabaseMigrator{}},4963:function(e,t,n){var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseMigrator=void 0;const d=a(n(1017)),l=a(n(7147)),c=n(2081),u=n(2318),h=n(496),p=n(7220),f=n(7048),g=n(5670),uniqueGroupComparator=(e,t)=>!e.groupName&&!t.groupName&&e.fieldNames[0]===t.fieldNames[0]||!!e.groupName&&e.groupName===t.groupName;let v=i=class DefaultSqlDatabaseMigrator extends g.AbstractDatabaseMigrator{constructor(e,t,n,i){super(),this.cliPath=e,this.sqlProvider=t,this.connectionString=n,this.logger=i,this.cliPath=e,this.databaseURL=`${t}://${n}`,this.modelMetadata=((0,u.getGlobalStore)().models||[]).map((e=>(0,u.getObjectMetadata)(e)))}getUniqueConstraintGroups(e){const t=[],n=(0,f.getDirectFields)(e).filter((e=>!!e.unique));for(const e of n)if(e.unique.groupName){let n=t.find((t=>t.groupName===e.unique.groupName));n||(n={groupName:e.unique.groupName,fieldNames:[]},t.push(n)),n.fieldNames.push(e.name)}else t.push({fieldNames:[e.name]});return t}generateFieldPropertiesQuery(e){let t="{";if(e.pk&&(t+="primaryKey:true,",e.pk.isAutoIncrement&&(t+="autoIncrement:true,")),void 0!==e.defaultValue&&(t+=`defaultValue:${JSON.stringify(e.defaultValue)},`),t+=`allowNull:${e.isRequired?"false":"true"},`,void 0!==e.dataType)switch(e.dataType){case u.DataType.STRING:e.textLength?t+=`type:Sequelize.STRING(${e.textLength}),`:t+="type:Sequelize.TEXT,";break;case u.DataType.NUMBER:e.floating?t+="type:Sequelize.FLOAT,":e.isBigInt?t+="type:Sequelize.BIGINT,":t+="type:Sequelize.INTEGER,";break;case u.DataType.BOOLEAN:t+="type:Sequelize.BOOLEAN,";break;case u.DataType.ARRAY:case u.DataType.OBJECT:t+="type:Sequelize.TEXT,"}return t+="}",t}getUniqueConstraintUpDown(e,t){const n=`${e}_${t.groupName||t.fieldNames[0]}_un`;return[`queryInterface.addConstraint("${e}",{fields:${JSON.stringify(t.fieldNames)},type:"unique",name:"${n}","transaction":t})`,`queryInterface.removeConstraint("${e}","${n}",{"transaction":t})`]}getSqlCascadeAction(e){switch(e){case"delete":return"CASCADE";case"restrict":return"RESTRICT";case"nullify":return"SET NULL";default:return"RESTRICT"}}getForeignKeyConstraintUpDown(e,t,n){var i,o,r;if(!e)throw u.ErrorBuilder.systemError(`Refer table ${null===(i=n.fk)||void 0===i?void 0:i.dtoId} not found at ${t}:${n.name}`);const s=`${t}_${n.name}_fk`;return[`queryInterface.addConstraint("${t}",{fields:["${n.name}"],type:"foreign key",name:"${s}",references:{table:"${e.id}",field:"id"},onDelete:'${this.getSqlCascadeAction(null===(o=n.fk)||void 0===o?void 0:o.cascade)}',onUpdate:'${this.getSqlCascadeAction(null===(r=n.fk)||void 0===r?void 0:r.cascade)}',"transaction":t})`,`queryInterface.removeConstraint("${t}","${s}",{"transaction":t})`]}getAddColumnUpDown(e,t){return[`queryInterface.addColumn('${e}','${t.name}',${this.generateFieldPropertiesQuery(t)},{"transaction":t})`,`queryInterface.removeColumn('${e}','${t.name}',{"transaction":t})`]}generateCreateTableQuery(e){let t={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]},n="",i="";n+="{\n";for(const t of(0,f.getDirectFields)(e)){let e=this.generateFieldPropertiesQuery(t);n+=`${t.name}:${e},\n`}n+="}\n",i+='{charset:"utf8",transaction:t}',t.upTableAdd.push(`queryInterface.createTable("${e.id}",${n},{charset:"utf8",transaction:t})`),t.downTableRemove.push(`queryInterface.dropTable("${e.id}",{"transaction":t})`);const o=this.getUniqueConstraintGroups(e);for(const n of o){const[i,o]=this.getUniqueConstraintUpDown(e.id,n);t.upConstraintAdd.push(i),t.downConstraintRemove.push(o)}for(const n of(0,f.getDirectFields)(e))if(n.fk){let i=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=n.fk)||void 0===t?void 0:t.dtoId)}));const[o,r]=this.getForeignKeyConstraintUpDown(i,e.id,n);t.upConstraintAdd.push(o),t.downConstraintRemove.push(r)}return t}isBooleanDiff(e,t){return!!e&&!t||!!t&&!e}runProcess(e){return s(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{(0,c.exec)(e,{env:process.env},(e=>(e&&n(e),t())))}))}))}rollback(e){return s(this,void 0,void 0,(function*(){let t=d.default.join(e,"scripts");if(!l.default.existsSync)throw u.ErrorBuilder.systemError("Migration directory not found");this.logger.debug("Rolling back last migration"),yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${t} db:migrate:undo`),this.logger.debug("Rollback completed")}))}migrate(e){var t,n,o,r,a,c,g,v;return s(this,void 0,void 0,(function*(){let y=d.default.join(e,"metadata.json"),m=d.default.join(e,"scripts");l.default.existsSync(m)||(this.logger.debug("Migration directory not exists, creating empty folder"),l.default.mkdirSync(m,{recursive:!0})),l.default.existsSync(y)||(this.logger.debug("Migration metadata does not exist, creating one"),l.default.writeFileSync(y,JSON.stringify([]))),this.logger.debug("Parsing migration metadata file");let b=JSON.parse(String(l.default.readFileSync(y)));this.logger.debug("Calculating differences...");const C=this.modelMetadata.filter((e=>!b.find((t=>e.id===t.id)))),M=this.modelMetadata.filter((e=>b.find((t=>t.id===e.id)))).map((e=>e.id));let S=[];S.push(...C.map((e=>this.generateCreateTableQuery(e))));for(const e of M){const i=b.find((t=>t.id===e)),s=this.modelMetadata.find((t=>t.id===e));i.id!==s.id&&S.push({upTableAdd:[`queryInterface.query("ALTER TABLE ${i.id} RENAME TO ${s.id}",{"transaction":t})`],downTableRemove:[`queryInterface.query("ALTER TABLE ${s.id} RENAME TO ${i.id}",{"transaction":t})`],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]});let d={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]};const l=(0,f.getDirectFields)(i).filter((e=>!(0,f.getDirectFields)(s).find((t=>e.name===t.name))));for(const e of l){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableRemove.push(n),d.downTableAdd.push(t),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.dtoId)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintRemove.push(i),d.downConstraintAdd.push(n)}}const u=(0,f.getDirectFields)(s).filter((e=>!(0,f.getDirectFields)(i).find((t=>e.name===t.name))));for(const e of u){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableAdd.push(t),d.downTableRemove.push(n),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.dtoId)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintAdd.push(n),d.downConstraintRemove.push(i)}}const h=(0,f.getDirectFields)(s).filter((e=>(0,f.getDirectFields)(i).find((t=>e.name===t.name)))).map((e=>e.name));for(const e of h){const l=(0,f.getFieldByName)(i,e),u=(0,f.getFieldByName)(s,e);if((this.isBooleanDiff(l.floating,u.floating)||this.isBooleanDiff(l.isBigInt,u.isBigInt)||this.isBooleanDiff(l.isRequired,u.isRequired)||this.isBooleanDiff(null===(t=l.pk)||void 0===t?void 0:t.isAutoIncrement,null===(n=u.pk)||void 0===n?void 0:n.isAutoIncrement)||l.dataType!==u.dataType||l.textLength!==u.textLength||l.defaultValue!==u.defaultValue)&&(d.upTableAdd.push(`queryInterface.changeColumn("${s.id}","${u.name}",${this.generateFieldPropertiesQuery(u)},{"transaction":t})`),d.downTableRemove.push(`queryInterface.changeColumn("${s.id}","${l.name}",${this.generateFieldPropertiesQuery(l)},{"transaction":t})`)),(null===(o=l.fk)||void 0===o?void 0:o.dtoId)!==(null===(r=u.fk)||void 0===r?void 0:r.dtoId)||(null===(a=l.fk)||void 0===a?void 0:a.cascade)!==(null===(c=u.fk)||void 0===c?void 0:c.cascade)){if(null===(g=l.fk)||void 0===g?void 0:g.dtoId){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=l.fk)||void 0===t?void 0:t.dtoId)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,l);d.upTableAdd.push(n),d.downTableRemove.push(t)}if(null===(v=u.fk)||void 0===v?void 0:v.dtoId){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=u.fk)||void 0===t?void 0:t.dtoId)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,u);d.upTableAdd.push(t),d.downTableRemove.push(n)}}}const p=this.getUniqueConstraintGroups(i),y=this.getUniqueConstraintGroups(s),m=p.filter((e=>!!y.find((t=>uniqueGroupComparator(e,t))))),C=p.filter((e=>!m.find((t=>uniqueGroupComparator(e,t)))));for(const e of C){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintRemove.push(n),d.downConstraintAdd.push(t)}const M=y.filter((e=>!m.find((t=>uniqueGroupComparator(e,t)))));for(const e of M){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintAdd.push(t),d.downConstraintRemove.push(n)}for(const e of m){const t=p.find((t=>uniqueGroupComparator(t,e))),n=y.find((t=>uniqueGroupComparator(t,e)));if(t.fieldNames.length!==n.fieldNames.length||t.fieldNames.some((e=>!n.fieldNames.includes(e)))){const[e,i]=this.getUniqueConstraintUpDown(s.id,t),[o,r]=this.getUniqueConstraintUpDown(s.id,n);d.upConstraintRemove.push(i),d.upConstraintAdd.push(o),d.downConstraintRemove.push(r),d.downConstraintAdd.push(e)}}(d.upTableAdd.length||d.downTableRemove.length||d.upConstraintAdd.length||d.downConstraintRemove.length||d.upConstraintRemove.length||d.downConstraintAdd.length||d.upTableRemove.length||d.downTableAdd.length)&&S.push(d)}if(S.length){let e=`${Date.now()}-auto-migration.js`;const getTransactionalScript=e=>`const t = await queryInterface.sequelize.transaction({autoCommit: false}); \n try {\n ${e.reduce(((e,t)=>e+`await ${t};`),"")}\n await t.commit();\n } catch(err){\n await t.rollback(); \n throw(err);\n }`,migrationFunction=(e,t)=>s(this,void 0,void 0,(function*(){if(!e.up.length&&!e.down.length)return;let n=d.default.join(m,t),o=i.MIGRATION_TEMPLATE,r=new RegExp(i.COMMENT_BLOCK_REGEX_PATTERN),s=getTransactionalScript(e.up),a=getTransactionalScript(e.down);o=o.replace(r,s),o=o.replace(r,a),this.logger.debug("Writing to file",n),l.default.writeFileSync(n,o)}));throw yield migrationFunction({up:[...S.reduce(((e,t)=>e.concat(t.upConstraintRemove)),[]),...S.reduce(((e,t)=>e.concat(t.upTableRemove)),[]),...S.reduce(((e,t)=>e.concat(t.upTableAdd)),[]),...S.reduce(((e,t)=>e.concat(t.upConstraintAdd)),[])],down:[...S.reduce(((e,t)=>e.concat(t.downConstraintRemove)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downTableRemove)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downTableAdd)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downConstraintAdd)),[]).reverse()]},e),this.logger.debug("Updating metadata file"),l.default.writeFileSync(y,JSON.stringify(this.modelMetadata.map((e=>this.getLeanModelMetadata(e))))),u.ErrorBuilder.systemError(`Migration review needed: ${e}`)}this.logger.debug("No difference, running migration"),this.logger.debug("Create database if not exist");try{yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} db:create`)}catch(e){if(String(e).indexOf("already exists")<0)throw e}if(this.logger.debug("Running migration"),this.sqlProvider===p.SqlProvider.POSTGRES){this.logger.debug("Creating unaccent extension for postgres");const e=new h.Sequelize(this.databaseURL);yield e.query("CREATE EXTENSION IF NOT EXISTS unaccent;")}else if(this.sqlProvider===p.SqlProvider.MYSQL){this.logger.debug("Creating unaccent function for mysql");const e=new h.Sequelize(this.databaseURL,{dialectOptions:{multipleStatements:!0}}),t="ĂÂÀÁẢÃẠẰẮẲẴẶẦẤẨẪẬÔƠÒÓỎÕỌỒỐỔỖỘỜỚỞỠỢÈÉẺẼẸÊỀẾỂỄỆÙÚỦŨỤƯỪỨỬỮỰÌÍỈĨỊỲÝỶỸỴ",n="AAAAAAAAAAAAAAAAAOOOOOOOOOOOOOOOOOEEEEEEEEEEEUUUUUUUUUUUIIIIIYYYYY",i=`SET GLOBAL log_bin_trust_function_creators = 1; \nDROP FUNCTION IF EXISTS unaccent; \nCREATE FUNCTION unaccent( textvalue TEXT ) RETURNS TEXT \nBEGIN \nSET @textvalue = textvalue; \nSET @withaccents = 'ŠšŽžÄÅÆÇËÎÏÑÖØÛÜŸÞäåæçëîïñõöøûüÿþƒ${t}${t.toLowerCase()}'; \nSET @withoutaccents = 'SsZzAAACEIINOOUUYBaaaceiinooouuybf${n}${n.toLowerCase()}'; \nSET @count = LENGTH(@withaccents); \nWHILE @count > 0 DO \nSET @textvalue = REPLACE(@textvalue, SUBSTRING(@withaccents, @count, 1), SUBSTRING(@withoutaccents, @count, 1)); \nSET @count = @count - 1; \nEND WHILE; \nRETURN @textvalue; \nEND; \n`;yield e.query(i,{type:h.QueryTypes.RAW})}yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${m} db:migrate`),this.logger.debug("Migration finished")}))}remove(e,t){return Object.keys(e).filter((e=>!t.includes(e))).reduce(((t,n)=>Object.assign(t,{[n]:e[n]})),{})}getLeanModelMetadata(e){return{id:e.id,fields:(0,f.getDirectFields)(e).map((e=>Object.assign({},this.remove(e,["vectorProps","stateMachineTransition","serverValue","searchable","regex","rangeProps","modificationTimestamp","mimeProps","isTimestamp","isSymbol","isLabel","injecteeSuperClass","hasMany","elementDto","creationTimestamp"]))))}}};v.COMMENT_BLOCK_REGEX_PATTERN="/\\*(\\*(?!/)|[^*])*\\*\\/",v.MIGRATION_TEMPLATE="'use strict';\n module.exports = {\n up: async (queryInterface, Sequelize) => {\n /**\n */\n },\n \n down: async (queryInterface, Sequelize) => {\n /**\n */\n }\n };",v=i=o([(0,u.Injectable)(),r("design:paramtypes",[String,String,String,u.AbstractLogger])],v),t.DefaultSqlDatabaseMigrator=v},6042:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5616:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},873:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionLink=void 0,function(e){e.CREATE_NEW="create_new",e.INHERIT_OR_CREATE="inherit_or_create",e.INHERIT_OR_THROW="inherit_or_throw"}(t.TransactionLink||(t.TransactionLink={}))},4618:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionState=void 0,function(e){e.EXECUTING="executing",e.COMMITTED="commited",e.ROLLED_BACK="rolled_back"}(t.TransactionState||(t.TransactionState={}))},7048:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getDirectFields=t.getFieldByName=t.getTransactionFromContext=void 0;const i=n(2318),o=n(137);t.getTransactionFromContext=e=>{const t=e[o.INJECTED_TRANSACTION];if(!t)throw i.ErrorBuilder.systemError("Cannot get transaction from current context");return t};t.getFieldByName=(e,t)=>e.fields.find((e=>e.name===t));t.getDirectFields=e=>e.fields.filter((e=>!e.hasMany))},859:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpAuthorizationProvider=void 0;t.AbstractHttpAuthorizationProvider=class AbstractHttpAuthorizationProvider{}},2085:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRbacAuthProvider=void 0;const o=n(2318),r=n(859),s=n(4972);class AbstractRbacAuthProvider extends r.AbstractHttpAuthorizationProvider{constructor(e,t,n){super(),this.authDataResolver=e,this.principalResolver=t,this.logger=n}getPrincipalResolver(){return this.principalResolver}resolvePrincipal(e){return this.principalResolver.resolvePrincipal(this.authDataResolver(e))}authorize(e,t,n){return i(this,void 0,void 0,(function*(){if(n.endpointMetadata.openAccess)return;const i=yield this.getRbacCache();if(!i)throw o.ErrorBuilder.error(o.Errors.SYSTEM_ERROR,"Cannot read rbac cache");let r=[];if(e){const t=yield this.getRolesOfPrincipal(e);r=(i.roles||[]).filter((e=>!!t.find((t=>t===e.roleId))))}else r=(i.roles||[]).filter((e=>e.isAnonymousRole));if(!r.length)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,"No role attached");if(r.find((e=>e.isSuperRole)))return;const a=(i.rolePolicies||[]).filter((e=>!!r.find((t=>t.roleId===e.roleId)))),d=(i.policies||[]).filter((e=>!!a.find((t=>t.policyId===e.policyId)))),l=(i.policyPermissions||[]).filter((e=>!!d.find((t=>t.policyId===e.policyId)))),c=(i.policyPermissionConditions||[]).filter((e=>!!l.find((t=>t.id===e.policyPermissionId)))),u=l.filter((e=>e.permission===(0,s.getEndpointId)(n.endpoint)));if(!u.length)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,`Not permitted: ${(0,s.getEndpointId)(n.endpoint)}`);let h=!1;for(const e of u){const i=c.filter((t=>t.policyPermissionId===e.id));if(i.length){let e=!0;const r=(0,o.getServiceProvider)().getInjector(),s=(n.endpointMetadata.accessConditions||[]).map((e=>r.resolve(e)));yield r.initInstances();for(const n of i){const i=s.find((e=>e.getConditionMetadata().name===n.conditionName));if(!i)continue;const o=yield i.resolveConditionValue(t),r=JSON.parse(n.conditionValue);if(e=yield i.validate(o,r),!e){this.logger.debug("Condition check failed: condition, requested, permitted",n.conditionName,o,r);break}}h=e}else h=!0;if(h)break}if(!h)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,"Condition check failed")}))}}t.AbstractRbacAuthProvider=AbstractRbacAuthProvider},531:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.RedisRbacAuthProvider=void 0;const o=n(2085);class RedisRbacAuthProvider extends o.AbstractRbacAuthProvider{constructor(e,t,n,i,o,r,s,a=3e4){super(i,o,s),this.serviceId=e,this.rbacChannel=t,this.principalChannel=n,this.authDataResolver=i,this.principalResolver=o,this.cacheService=r,this.logger=s,this.redisDataRetentionDurationMs=a,this.lastRbacFetchTimestamp=0,this.principalCache={}}getRbacCache(){return i(this,void 0,void 0,(function*(){if(this.lastRbacFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.rbacChannel,this.serviceId);this.rbacCache=e,this.lastRbacFetchTimestamp=Date.now()}return this.rbacCache}))}getRolesOfPrincipal(e){return i(this,void 0,void 0,(function*(){const t=String(e.id);let n=this.principalCache[t];if(!n||n.lastFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.principalChannel,t),i=e?"string"==typeof e?JSON.parse(e):e:[];n={lastFetchTimestamp:Date.now(),roles:i},this.principalCache[t]=n}return n.roles}))}}t.RedisRbacAuthProvider=RedisRbacAuthProvider},7825:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SocketRbacAuthProvider=void 0;const s=n(2318),a=n(2085),d=n(4638);let l=class SocketRbacAuthProvider extends a.AbstractRbacAuthProvider{constructor(e,t,n,i,o,r){super(n,i,o),this.rbacCacheChannel=e,this.principalCacheChannel=t,this.authDataResolver=n,this.principalResolver=i,this.logger=o,this.socketProvider=r,this.idResolvers=[]}exit(){var e;null===(e=this.socket)||void 0===e||e.close()}init(){return r(this,void 0,void 0,(function*(){this.socket=yield this.socketProvider(),this.socket.onMessage(((e,t)=>{switch(t){case this.rbacCacheChannel:this.rbacCache=e;break;case this.principalCacheChannel:const{principalId:t,roleIds:n}=e,i=this.idResolvers.find((e=>e.principalId===t));if(i){for(const e of i.resolvers)e(n);i.resolvers=[]}}})),this.socket.joinChannels([this.rbacCacheChannel,this.principalCacheChannel])}))}getRbacCache(){return r(this,void 0,void 0,(function*(){return this.rbacCache}))}getRolesOfPrincipal(e){return r(this,void 0,void 0,(function*(){return new Promise((t=>{var n;let i=this.idResolvers.find((t=>t.principalId===e.id));i||(i={principalId:e.id,resolvers:[]},this.idResolvers.push(i)),i.resolvers.length||null===(n=this.socket)||void 0===n||n.send(e.id,this.principalCacheChannel),i.resolvers.push(t)}))}))}};l=i([(0,s.Initable)(),o("design:paramtypes",[String,String,Function,d.AbstractPrincipalResolver,s.AbstractLogger,Function])],l),t.SocketRbacAuthProvider=l},9837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},1532:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HttpRequest=void 0;const i=n(2318);t.HttpRequest=class HttpRequest{constructor(e,t){this.valueHolder={},this.method=e.method,this.pathName=e.pathName,this.headers=e.headers||{},this.hash=e.hash||"",this.params=e.params||{},(null==t?void 0:t.paramsValidationDto)&&(this.params=(0,i.validateData)(this.params,null==t?void 0:t.paramsValidationDto)),this.query=e.query||{},(null==t?void 0:t.queriesValidationDto)&&(this.query=(0,i.validateData)(this.jsonParsing(this.query,t.queriesValidationDto),t.queriesValidationDto)),this.body=e.body||{},t&&(t.httpMethod===i.HttpMethod.POST||t.httpMethod===i.HttpMethod.PUT)&&(null==t?void 0:t.bodyValidationDto)&&(this.body=(0,i.validateData)(this.body||{},t.bodyValidationDto))}jsonParsing(e,t){const n=Object.assign({},e);for(const o of t.fields)try{(void 0!==e[o.name]||o.isRequired)&&(n[o.name]=JSON.parse(e[o.name]))}catch(e){throw i.ErrorBuilder.error(i.Errors.VALIDATION_ERROR,`JSON parsing failed for field ${o.name}`)}return n}getAuthInfo(){return this.authInfo}setAuthInfo(e){this.authInfo=e}getHeaders(){return this.headers}getMethod(){return this.method}getHash(){return this.hash}getPathName(){return this.pathName}getValue(e){return this.valueHolder[e]}setValue(e,t){this.valueHolder[e]=t}getParams(){return this.params}getQuery(){return this.query}getBody(){return this.body}}},8903:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseBuilder=t.HttpResponse=void 0;class HttpResponse{constructor(){this.code=200,this.headers={},this.cookies={}}}t.HttpResponse=HttpResponse;class ResponseBuilder{constructor(){this.response=new HttpResponse}status(e){return this.response.code=e,this}header(e,t){return this.response.headers[e]=t,this}cookie(e,t){return this.response.headers[e]=t,this}get(){return this.response}static json(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/json",t}static html(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="text/html; charset=UTF-8",t}static binary(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/octet-stream",t}static success(){const e=new ResponseBuilder;return e.response.code=200,e.response}static notFound(e){const t=new ResponseBuilder;return t.response.code=404,t.response.value=e,t.response}static accessDenied(e){const t=new ResponseBuilder;return t.response.code=400,t.response.value=e,t.response}}t.ResponseBuilder=ResponseBuilder},6004:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=n(2318),r=n(7048);t.AbstractHttpController=class AbstractHttpController{constructor(e){this.databaseAdapter=e}createTransaction(){return i(this,void 0,void 0,(function*(){return this.databaseAdapter.createTransaction()}))}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,r.getTransactionFromContext)(this)}))}getEndpointMetadata(){const e=(0,o.getObjectMetadata)(this.constructor);return e?e.fields.filter((e=>{return!!(t=e).httpMethod||void 0!==t.openAccess||!!t.accessConditions;var t})).map((t=>Object.assign(Object.assign({},t),{permissionGroup:e.permissionGroup}))):[]}}},225:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpMiddleware=void 0;t.AbstractHttpMiddleware=class AbstractHttpMiddleware{}},767:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;const o=n(2318),r=n(4972),s=n(6004);t.AbstractHttpRequestHandler=class AbstractHttpRequestHandler{constructor(e,t){this.mountPoint=e,this.logger=t}resolverMountPoint(e,t){if(!e)return"";const n=[];return n.push(...t),n.reduce(((e,t)=>`${e}/${t}`),"").replace(/(\/)\/+/g,"$1")}getMountedEndpointInfo(){var e,t,n;return i(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const i=[],a=(0,o.getServiceProvider)().getInjector(),d=a.resolveMultiple(s.AbstractHttpController);yield a.initInstances();for(const e of d){const t=(0,o.getObjectMetadata)(e.constructor),n=e.getEndpointMetadata();for(const r of n){const n={mount:r.httpMethod===o.SocketMethod.MESSAGE?r.url:this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),httpMethod:r.httpMethod,controller:e,handlerFunctionName:r.name};i.push({endpointMetadata:r,endpoint:n})}}const l=[];for(const o of i){const i=l.find((e=>e.endpoint.mount===o.endpoint.mount&&e.endpoint.httpMethod===o.endpoint.httpMethod));i?null===(e=this.logger)||void 0===e||e.warn(`Implicit overriding endpoint: ${(0,r.getEndpointId)(i.endpoint)} of ${null===(t=i.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${i.endpoint.handlerFunctionName}`,`Ignore ${(0,r.getEndpointId)(o.endpoint)} of ${null===(n=o.endpoint.controller)||void 0===n?void 0:n.constructor.name}:${o.endpoint.handlerFunctionName}`):l.push(o)}this.mountedEndpointInfo=l}return this.mountedEndpointInfo}))}}},7282:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const a=n(2318),d=n(1071),l=n(1532),c=n(6793),u=n(873),h=n(2417),p=n(6004),f=n(859),g=n(8903),v=n(3198),y=n(4192);class CrudHttpController extends p.AbstractHttpController{constructor(e,t,n){super(n),this.model=e,this.crudRepository=t,this.databaseAdapter=n,this.modelMetadata=(0,a.getObjectMetadata)(e)}getMountedUrl(){return`/${this.model.name.toLowerCase()}`}static queryFieldDto(e){const t={id:"",fields:CrudHttpController.getRequestQueryFieldFromModel(e)},n={name:"fields",description:"Filter records by value of their fields."};return n.dataType=a.DataType.OBJECT,n.elementDto=t,n}static projectionFieldDto(e){const t={name:"projection",description:"Project the returning records to contain only certain fields. Omit to return all."};return t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.fields.map((e=>e.name)),allowDuplicated:!1,minLength:1,elementDataType:a.DataType.STRING},t}static getBodyDtoRecordClass(e,t,n){const i={id:"",fields:[]};let o=e.fields.filter((e=>!e.hasMany));o="get_response"===t||"query"===t?o:"create_response"===t?o.filter((e=>e.pk||e.serverValue)):"create_body"===t||"update_body"===t?o.filter((e=>{var t;return!e.serverValue&&!(null===(t=e.pk)||void 0===t?void 0:t.isAutoIncrement)||!!n&&!n.fields.find((t=>{var n;return(null===(n=t.hasMany)||void 0===n?void 0:n.column)===e.name}))})):[];const r=e.fields.filter((e=>!!e.hasMany));return i.fields.push(...o.map((e=>Object.assign(Object.assign({},e),{elementDto:e.elementDto&&("update_body"===t?(0,a.partialize)(e.elementDto):e.elementDto),isRequired:!("query"===t||"update_body"===t||"get_response"===t&&!n)&&e.isRequired}))),...r.map((n=>{var i;const o=CrudHttpController.getBodyDtoRecordClass(n.hasMany.relationDto,t,e);return{description:`All records of "${null===(i=n.hasMany)||void 0===i?void 0:i.relationDto.id}" table in this relationship.`,name:n.name,dataType:a.DataType.ARRAY,isRequired:"create_response"===t,vectorProps:{elementDataType:a.DataType.OBJECT,minLength:0},elementDto:Object.assign(Object.assign({},o),{fields:("create_body"===t||"update_body"===t?o.fields.filter((e=>{var t;return e.name!==(null===(t=n.hasMany)||void 0===t?void 0:t.column)})):o.fields).map((e=>"update_body"===t?Object.assign(Object.assign({},e),{isRequired:!1,allowNull:!0}):e))})}}))),i}static getRequestQueryFieldFromModel(e){return e.fields.map((e=>{const t={};if(t.name=e.name,t.description=e.description,t.isRequired=!1,e.pk||e.fk||e.isSymbol)t.dataType=a.DataType.ARRAY,t.vectorProps={elementDataType:e.dataType,allowDuplicated:!1,allowNull:e.allowNull,minLength:1};else if(e.hasMany){const n={id:"",fields:CrudHttpController.getRequestQueryFieldFromModel(e.hasMany.relationDto).filter((t=>{var n;return t.name!==(null===(n=e.hasMany)||void 0===n?void 0:n.column)})),relaxed:!0};t.dataType=a.DataType.OBJECT,t.elementDto=n}else if(e.enum)t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.enum,allowDuplicated:!1,minLength:1,elementDataType:e.dataType,allowNull:e.allowNull};else switch(e.dataType){case a.DataType.STRING:t.dataType=a.DataType.STRING;break;case a.DataType.NUMBER:t.dataType=a.DataType.OBJECT,t.elementDto=(0,a.getObjectMetadata)(a.RangeQueryDto)}return t}))}getAuthProvider(){return s(this,void 0,void 0,(function*(){if(void 0===this.authProvider){const e=(0,a.getServiceProvider)().getInjector();this.authProvider=e.resolveOptional(f.AbstractHttpAuthorizationProvider)||null,yield e.initInstances()}return this.authProvider}))}createManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.POST,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.createMany.name,e.displayName="createMany"+this.model.name,e.bodyValidationDto=CrudHttpController.getCreateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getCreateManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,y.DtoFieldValidation)(this.model,(e=>e.getBody().records))],e.params={0:{source:"raw"}},e}getManyEndpointMetadata(){const e={};return e.httpMethod=a.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queriesValidationDto=CrudHttpController.getGetManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getGetManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,y.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields])),(0,d.FilterModelFieldAccessCondition)(this.model,(e=>e.getQuery().projection)),v.MaximumQueryLimit],e.params={0:{source:"raw"}},e}updateManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.PUT,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.updateMany.name,e.displayName="update"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.bodyValidationDto=CrudHttpController.getUpdateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,d.FilterModelFieldAccessCondition)(this.model,(e=>{const t=e.getBody().update;return t?Object.keys((0,a.leanData)(t)):[]})),(0,y.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]),"dto_field_validation_query"),(0,y.DtoFieldValidation)(this.model,(e=>[e.getBody().update]),"dto_field_validation_body")],e.params={0:{source:"raw"}},e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.params={0:{source:"raw"}},e.accessConditions=[(0,y.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]))],e}static getCreateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records to be created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_body"),t.fields.push(n),t}static getCreateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records had just been created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_response"),t.fields.push(n),t}static getGetManyResponseValidator(e){const t={id:"",fields:[]},n={name:"total",description:"Number of records found, zero is returned if the request is not paged."};n.dataType=a.DataType.NUMBER,n.isRequired=!0,t.fields.push(n);const i={name:"records",description:"The found records. All records will be returned if the request is not paged."};return i.dataType=a.DataType.ARRAY,i.isRequired=!0,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},i.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(i),t}static getGetManyQueryValidator(e){const t={id:"",fields:[CrudHttpController.queryFieldDto(e)]},n={name:"search",description:"Filter records for their @Searchable denoted fields."};n.dataType=a.DataType.STRING,t.fields.push(n),t.fields.push(CrudHttpController.projectionFieldDto(e));const i={name:"order",description:"Sort the dataset before getting result by order given in the array. Field appears first in the array will be sorted first."};i.dataType=a.DataType.ARRAY,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:1};const o={id:"",fields:[]};o.fields.push(...e.fields.filter((e=>!e.hasMany)).map((e=>{const t={};return t.name=e.name,t.isRequired=!1,t.dataType=a.DataType.STRING,t.enum=["asc","desc"],t}))),i.elementDto=o,t.fields.push(i);const r={name:"limit",description:"Limit the number of returning result."};r.dataType=a.DataType.NUMBER,r.rangeProps={min:1},t.fields.push(r);const s={name:"page",description:"Page the returning result, default to 1 if ommited. Has no effect if limit is not set."};return s.dataType=a.DataType.NUMBER,s.rangeProps={min:1},t.fields.push(s),t}static getUpdateManyQueryValidator(e){const t={name:"returning",description:"Whether to return the affected records by this request."};return t.dataType=a.DataType.BOOLEAN,t.isRequired=!1,{id:"",fields:[t,CrudHttpController.queryFieldDto(e)]}}static getUpdateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"update",isRequired:!0,description:"The update data to apply to found records."};return n.dataType=a.DataType.OBJECT,n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"update_body"),t.fields.push(n),t}static getUpdateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"modified",description:"Array of affected records."};return n.dataType=a.DataType.ARRAY,n.vectorProps={minLength:0,elementDataType:a.DataType.OBJECT},n.elementDto=n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(n),t}getEndpointMetadata(){var e,t,n,i;let o=super.getEndpointMetadata();const r=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(a.HttpMethod.GET))?o=o.filter((e=>e.name!==CrudHttpController.prototype.getMany.name)):r.push(this.getManyEndpointMetadata()),(null===(t=this.modelMetadata.ignoreCrud)||void 0===t?void 0:t.includes(a.HttpMethod.POST))?o=o.filter((e=>e.name!==CrudHttpController.prototype.createMany.name)):r.push(this.createManyEndpoinMetadata()),(null===(n=this.modelMetadata.ignoreCrud)||void 0===n?void 0:n.includes(a.HttpMethod.PUT))?o=o.filter((e=>e.name!==CrudHttpController.prototype.updateMany.name)):r.push(this.updateManyEndpoinMetadata()),(null===(i=this.modelMetadata.ignoreCrud)||void 0===i?void 0:i.includes(a.HttpMethod.DEL))?o=o.filter((e=>e.name!==CrudHttpController.prototype.deleteMany.name)):r.push(this.deleteManyEndpoinMetadata());for(const e of r){const t=o.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name&&(!t.httpMethod||!t.url)));t>=0?o[t]=Object.assign(Object.assign(Object.assign({},e),o[t]),{accessConditions:[...e.accessConditions||[],...o[t].accessConditions||[]]}):o.push(e)}return o}createMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),i=n&&(yield n.resolvePrincipal(e)),o=yield this.crudRepository.createMany({principal:i,body:e.getBody(),tx:t});return g.ResponseBuilder.json(o).get()}))}getMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.crudRepository.getMany({queries:e.getQuery(),queryProvider:this.databaseAdapter});return g.ResponseBuilder.json(t).get()}))}updateMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),i=n&&(yield n.resolvePrincipal(e)),o=yield this.crudRepository.updateMany({principal:i,queries:e.getQuery(),body:e.getBody(),tx:t});return g.ResponseBuilder.json(o).get()}))}deleteMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.crudRepository.deleteMany({queries:e.getQuery(),tx:t});return g.ResponseBuilder.json({modified:n.modified.map((e=>e.id)).map((e=>({id:e})))}).get()}))}}i([(0,c.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Create records of this table."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[l.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),i([(0,h.AccessCondition)([]),(0,h.ApiDescription)("Get records of this table."),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[l.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),i([(0,c.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and update records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[l.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),i([(0,c.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and remove records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[l.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},5879:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultHttpRequestHandler=void 0;const a=n(2318),d=s(n(9215)),l=n(99),c=s(n(9103)),u=n(8903),h=n(1532),p=n(859),f=n(767),g=n(6721);let v=class DefaultHttpRequestHandler extends f.AbstractHttpRequestHandler{constructor(e,t){super("",e),this.logger=e,this.authorizationProvider=t}accessControl(e,t){return r(this,void 0,void 0,(function*(){if(e.endpointMetadata.httpMethod!==a.SocketMethod.MESSAGE){const n=yield this.authorizationProvider.resolvePrincipal(t);if(t.setAuthInfo(n),!e.endpointMetadata.openAccess&&(yield this.authorizationProvider.authorize(n,t,e),e.endpointMetadata.tfaRequired&&!(null==n?void 0:n.hasTfa)))throw a.ErrorBuilder.error(g.Errors.TFA_REQUIRED)}}))}handleRequest(e,t){return r(this,void 0,void 0,(function*(){yield this.accessControl(e,t);const n=Object.values(e.endpointMetadata.params||{}).map((e=>{switch(e.source){case"body":return t.getBody();case"params":return t.getParams();case"queries":return t.getQuery();case"headers":return t.getHeaders();case"raw":return t}})),i=yield e.endpoint.controller[e.endpointMetadata.name](...n);return e.endpointMetadata.responseValidationDto&&(i.value=(0,a.stripData)(i.value,e.endpointMetadata.responseValidationDto)),i}))}exit(){}handle(e){return r(this,void 0,void 0,(function*(){const t=e.method,n=(0,d.default)({url:e.fullPath});let i={};const o=(yield this.getMountedEndpointInfo()).find((e=>{const o=e.endpointMetadata.httpMethod===t&&(0,l.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname);return!!o&&(i=o,!0)}));if(!o)throw this.logger.debug(e),a.ErrorBuilder.error(g.Errors.NOT_FOUND,"Handler not found");const r=new h.HttpRequest({method:t,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:c.default.parse(decodeURIComponent(n.search||"")),params:i.params,body:e.body},o.endpointMetadata);let s;try{for(const e of this.getMiddleware())if(s=yield e.intercept(r),s)break;if(s||(s=yield this.handleRequest(o,r)),!(s&&s instanceof u.HttpResponse))throw a.ErrorBuilder.systemError(`Invalid response value returned ${o.endpoint.httpMethod}:${o.endpoint.mount}, required instance of ${u.HttpResponse.name}, found ${s?null==s?void 0:s.constructor.name:s}`)}catch(e){this.logger.error(e),s=u.ResponseBuilder.json({name:e.name,message:e.message}).status([g.Errors.ACCESS_DENIED,g.Errors.AUTHENTICATION_ERROR,g.Errors.SESSION_EXPIRED].includes(e.name)?401:[g.Errors.SYSTEM_ERROR,g.Errors.CANNOT_LOCK].includes(e.name)?500:400).get()}return s}))}getMiddleware(){return[]}};v=i([(0,a.Injectable)(),o("design:paramtypes",[a.AbstractLogger,p.AbstractHttpAuthorizationProvider])],v),t.DefaultHttpRequestHandler=v},2417:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CurrentUser=t.UriMapper=t.Raw=t.Socket=t.Headers=t.Queries=t.Params=t.Body=t.AccessCondition=t.TfaRequired=t.OpenAccess=t.ApiResponse=t.Get=t.Del=t.Put=t.Post=t.Endpoint=t.ApiDescription=t.Controller=void 0;const i=n(2318);t.Controller=e=>t=>{(0,i.getServiceProvider)().register(t,"singleton");(0,i.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup};t.ApiDescription=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).description=e};t.Endpoint=e=>(t,n)=>{const o=(0,i.initFieldMetadata)(t,n);o.httpMethod=e.method,o.url=e.url};t.Post=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.POST,url:e})(n,o);t.Put=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.PUT,url:e})(n,o);t.Del=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.DEL,url:e})(n,o);t.Get=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.GET,url:e})(n,o);t.ApiResponse=e=>(t,n,o)=>{const r=(0,i.initFieldMetadata)(t,n);e===String?r.responseValidationDto={id:"",primitiveType:i.DataType.STRING,fields:[]}:e===Number?r.responseValidationDto={id:"",primitiveType:i.DataType.NUMBER,fields:[]}:e===Boolean?r.responseValidationDto={id:"",primitiveType:i.DataType.BOOLEAN,fields:[]}:r.responseValidationDto=(0,i.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,i.initFieldMetadata)(e,t).openAccess=!0};t.TfaRequired=()=>(e,t)=>{(0,i.initFieldMetadata)(e,t).tfaRequired=!0};t.AccessCondition=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).accessConditions=e};const RequestDeco=e=>(t,n,o)=>{const r=(0,i.initFieldMetadata)(t,n),s=Reflect.getMetadata("design:paramtypes",t,n)||[];switch(e){case"body":r.bodyValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"params":r.paramsValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"queries":r.queriesValidationDto=(0,i.getObjectMetadata)(s[o])}r.params||(r.params={}),r.params[o]={source:e,diClass:s[o]}};t.Body=()=>RequestDeco("body");t.Params=()=>RequestDeco("params");t.Queries=()=>RequestDeco("queries");t.Headers=()=>RequestDeco("headers");t.Socket=()=>RequestDeco("socket");t.Raw=()=>RequestDeco("raw");t.UriMapper=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).uriMapper=e};t.CurrentUser=e=>(t,n)=>{const o=(0,i.initFieldMetadata)(t,n);o.userResolver=e,o.serverValue=!0}},6507:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},4839:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FileUploadHandler=void 0;const s=n(2318),a=n(8709),d=n(6507);let l=class FileUploadHandler extends d.AbstractFileUploadHandler{constructor(e){super(),this.fileService=e}moveFile(e,t){return r(this,void 0,void 0,(function*(){yield this.fileService.moveObject(e,t)}))}removeFile(e){return r(this,void 0,void 0,(function*(){yield this.fileService.removeObject(e)}))}resolvePublicUrl(e){return r(this,void 0,void 0,(function*(){return this.fileService.getAccessUrl(e,!0)}))}resolvePrivateUrl(e){return r(this,void 0,void 0,(function*(){return this.fileService.getAccessUrl(e,!1)}))}};l=i([(0,s.Injectable)(),o("design:paramtypes",[a.AbstractFileService])],l),t.FileUploadHandler=l},5232:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5048:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRepository=void 0;const o=n(2318);t.AbstractRepository=class AbstractRepository{constructor(e){this.model=e,this.modelMetadata=(0,o.getObjectMetadata)(this.model)}beforeCreating(e,t){return i(this,void 0,void 0,(function*(){for(const n of t)for(const t of this.modelMetadata.fields)t.userResolver&&e&&(n[t.name]=t.userResolver(e))}))}project(e,t){return t?e.map((e=>t.reduce(((t,n)=>Object.assign(t,{[n]:e[n]})),{}))):e}}},9073:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoRepository=t.MultipleMap=t.SingleMap=void 0;const o=n(2318),r=n(5048),s=n(3355);t.SingleMap=(e,t,n,i,o)=>({multiple:!1,modelClass:e,forwardOps:t,forwardMapping:e=>{const t=n(e[0]||{});return t&&[t]},rootMapping:e=>{const t=e&&e[0];return i(t)},nestedMapping:o});t.MultipleMap=(e,t,n,i,o)=>({multiple:!0,modelClass:e,forwardOps:t,forwardMapping:n,rootMapping:i,nestedMapping:o});class DtoRepository extends r.AbstractRepository{constructor(e,t){super(e),this.model=e,this.dissolver=t}getMapValue(e,t,n,r,s){return i(this,void 0,void 0,(function*(){for(const i of n){const n=yield t(i);let a=r?yield r(i,i.forwardMapping(n),n):i.forwardMapping(n);if(i.nestedMapping&&a)for(const n of a)yield this.getMapValue(e,t,i.nestedMapping(n),r,s);s&&(a=yield s(i,i.forwardMapping(n),n));const d=i.rootMapping(a);(0,o.deepMerge)(e,d)}}))}createMany({principal:e,body:t,tx:n}){return i(this,void 0,void 0,(function*(){const r=[];yield this.beforeCreating(e,t.records);for(const a of t.records)yield this.getMapValue(a,(e=>i(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(),queryProvider:n})).records}))),this.dissolver(a),((t,r,a)=>i(this,void 0,void 0,(function*(){if(!r)return[];const i=new s.ModelRepository(t.modelClass),d=t.forwardOps();if(t.multiple){yield i.deleteMany({ops:d,tx:n});return(yield i.createMany({principal:e,body:{records:r},tx:n})).records}{const s=r[0];if(!s)return[];if(0===a.length){return(yield i.createMany({principal:e,body:{records:r},tx:n})).records}if(1===a.length){const t=yield i.updateMany({principal:e,ops:d,body:{update:s},tx:n});return[Object.assign(Object.assign(Object.assign({},a[0]),s),t.modified[0])]}throw o.ErrorBuilder.validationError(`Found multiple record when creating ${t.modelClass.name}`)}})))),r.push(a);return{records:r}}))}updateMany({principal:e,queries:t,ops:n,body:r,tx:a}){var d;return i(this,void 0,void 0,(function*(){if(!(null===(d=null==t?void 0:t.fields)||void 0===d?void 0:d.id)||1!==t.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const l=Object.assign(Object.assign({},r.update),{id:t.fields.id[0]});yield this.beforeCreating(e,[l]),yield this.getMapValue(l,(e=>i(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(n),queryProvider:a})).records}))),this.dissolver(l),((t,o,r)=>i(this,void 0,void 0,(function*(){if(!o)return[];const i=new s.ModelRepository(t.modelClass),d=t.forwardOps(n);if(t.multiple){yield i.deleteMany({ops:d,tx:a});return(yield i.createMany({principal:e,body:{records:o},tx:a})).records}{const t=o[0];return t?0==r.length?[]:(r.length>1?(yield i.deleteMany({ops:d,tx:a}),yield i.createMany({principal:e,body:{records:[t]},tx:a})):yield i.updateMany({principal:e,ops:d,body:{update:t},tx:a}),r.map((e=>Object.assign(Object.assign({},e),t)))):[]}}))));let c=["id"];return t.returning&&(c=[...c,...Object.keys(r.update).filter((e=>void 0!==r.update[e]))]),{modified:l.id?this.project([l],c):[]}}))}getMany({queries:e,ops:t,queryProvider:n}){var r;return i(this,void 0,void 0,(function*(){if(!(null===(r=null==e?void 0:e.fields)||void 0===r?void 0:r.id)||1!==e.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>i(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),(e=>i(this,void 0,void 0,(function*(){const i=new s.ModelRepository(e.modelClass);return(yield i.getMany({ops:e.forwardOps(t),queryProvider:n})).records})))),a.id?{records:this.project([a],e.projection),total:1}:{records:[],total:0}}))}deleteMany({queries:e,ops:t,tx:n}){var r;return i(this,void 0,void 0,(function*(){if(!(null===(r=null==e?void 0:e.fields)||void 0===r?void 0:r.id)||1!==e.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>i(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),void 0,(o=>i(this,void 0,void 0,(function*(){const i=new s.ModelRepository(o.modelClass),r=o.forwardOps(t);return(yield i.deleteMany({queries:{returning:null==e?void 0:e.returning},ops:r,tx:n})).modified})))),{modified:a.id?[a]:[]}}))}}t.DtoRepository=DtoRepository},8023:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3355:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const o=n(2318),r=n(7048),s=n(6507),a=n(5048);class ModelRepository extends a.AbstractRepository{constructor(e){super(e),this.model=e}getNestedQueries(e){return this.modelMetadata.fields.filter((e=>e.hasMany)).filter((t=>(null==e?void 0:e.fields)&&e.fields[t.name])).map((t=>{const n=t.hasMany.relationDto,i=this.getRequestQueryConditionFromQuery(null==e?void 0:e.fields[t.name],Object.assign(Object.assign({},n),{fields:n.fields.filter((e=>{var t;return e.name!==(null===(t=e.hasMany)||void 0===t?void 0:t.column)}))}));return{modelId:t.hasMany.relationDto.id,queries:i.length?{_and:i}:{}}}))}getUploadHandler(){return i(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=(0,o.getServiceProvider)().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){var n;const i=[];for(const s of(0,r.getDirectFields)(t))if(e[s.name])if(s.pk||s.fk||s.isSymbol)i.push({_in:{[s.name]:e[s.name]}});else if(s.enum)i.push({_in:{[s.name]:e[s.name]}});else switch(s.dataType){case o.DataType.STRING:if(s.searchable){const t={[(null==s?void 0:s.searchable.caseSensitive)?(null==s?void 0:s.searchable.accentSensitive)?"_sub":"_usub":(null===(n=null==s?void 0:s.searchable)||void 0===n?void 0:n.accentSensitive)?"_isub":"_iusub"]:{[s.name]:e[s.name]}};i.push(t)}else i.push({_eq:{[s.name]:e[s.name]}});break;case o.DataType.NUMBER:const t=new o.RangeQueryDto;Object.assign(t,e[s.name]),t.min&&(t.minExclusive?i.push({_gt:{[s.name]:t.min}}):i.push({_gte:{[s.name]:t.min}})),t.max&&(t.maxExclusive?i.push({_lt:{[s.name]:t.max}}):i.push({_lte:{[s.name]:t.max}}))}return i}uriHandling(e,t){return i(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();if(!n)return;const i=t.use(this.model);for(const o of this.modelMetadata.fields)if(o.uriMapper)for(const r of e){const e=r[o.name];if(!e)continue;const s=yield o.uriMapper(t,r,e);s&&(yield n.moveFile(e,s),r[o.name]=s,yield i.updateOne(r))}}))}beforeReturning(e){var t;return i(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();for(const i of e)for(const e of this.modelMetadata.fields)if(e.uriMapper&&n){if(!i[e.name])continue;i[e.name]=(null===(t=e.mimeProps)||void 0===t?void 0:t.public)?yield n.resolvePublicUrl(i[e.name]):yield n.resolvePrivateUrl(i[e.name])}}))}createMany({principal:e,body:t,tx:n}){return i(this,void 0,void 0,(function*(){const i=t.records;if(!i.length)return{records:[]};const s=(0,r.getDirectFields)(this.modelMetadata),a=this.modelMetadata.fields.filter((e=>!!e.hasMany));t.records=i.map((e=>s.reduce(((t,n)=>Object.assign(t,void 0!==e[n.name]?{[n.name]:e[n.name]}:{})),{}))),yield this.beforeCreating(e,t.records);let d=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(d,n),yield this.beforeReturning(d);const l=this.modelMetadata.fields.filter((e=>e.pk||e.serverValue||e.mimeProps)).map((e=>e.name));d=this.project(d,l);for(const r of a){const s=d.map(((e,t)=>(i[t][r.name]||[]).map((t=>Object.assign(Object.assign({},t),{[r.hasMany.column]:e.id}))))).reduce(((e,t)=>e.concat(t)),[]);if(s.length){const i=new ModelRepository((0,o.getModelById)(r.hasMany.relationDto.id));t.records=s;const a=yield i.createMany({principal:e,body:t,tx:n});for(let e=0;e<a.records.length;e++)s[e]=Object.assign(Object.assign({},s[e]),a.records[e]);for(let e=0;e<d.length;e++){const t=[];for(let n=0;n<s.length;n++)s[n][r.hasMany.column]===d[e].id&&t.push(a.records[e]);d[e]=Object.assign(Object.assign({},d[e]),{[r.name]:t})}}}return{records:d}}))}updateMany({principal:e,ops:t,queries:n,body:s,tx:a}){return i(this,void 0,void 0,(function*(){const i=t||[],d=this.modelMetadata.fields.filter((e=>!!e.hasMany)),l=(0,r.getDirectFields)(this.modelMetadata).filter((e=>void 0!==s.update[e.name])),c=l.reduce(((e,t)=>Object.assign(e,{[t.name]:s.update[t.name]})),{});if(null==n?void 0:n.fields){const e=this.getRequestQueryConditionFromQuery(n.fields,this.modelMetadata);e.length&&i.push(...e)}const u=i.length?{_and:[...i]}:{},h=this.getNestedQueries(n);let p=[];if(h.length){const e=yield a.use(this.model).getMany(u,{projection:["id"]},h);p=e.records.map((e=>e.id)),p.length&&l.length&&(yield a.use(this.model).updateMany({_in:{id:p}},c,!1))}else if(l.length)p=yield a.use(this.model).updateMany(u,c,!0);else{const e=yield a.use(this.model).getMany(u,{projection:["id"]});p=e.records.map((e=>e.id))}let f=p.map((e=>Object.assign(Object.assign({},c),{id:e})));yield this.uriHandling(f,a),yield this.beforeReturning(f);for(const t of d){const n=s.update[t.name];if(void 0===n||!p.length)continue;if(p.length>1)throw o.ErrorBuilder.systemError(`Multiple records found while updating @HasMany field: ${t.name}`);const i=f.find((e=>e.id===p[0])),r=(0,o.getModelById)(t.hasMany.relationDto.id),d=a.use(r),l=(yield d.getRecords({_eq:{[t.hasMany.column]:i.id}})).map((e=>e.id)),c=n.map((e=>e.id)).filter((e=>!!e)),u=l.filter((e=>!c.includes(e))),h=n.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:i.id}))),g=n.filter((e=>!!e.id));yield d.deleteMany({_in:{id:u}});const v=new ModelRepository(r),y=yield v.createMany({principal:e,body:{records:h},tx:a}),m=h.map(((e,t)=>Object.assign(Object.assign({},e),y.records[t])));i[t.name]=m.concat(g)}let g=["id"];return(null==n?void 0:n.returning)&&(g=[...g,...Object.keys(s.update).filter((e=>void 0!==s.update[e]))]),{modified:this.project(f,g)}}))}getMany({queries:e,ops:t,queryProvider:n}){var r;return i(this,void 0,void 0,(function*(){const i=t||[];if((null==e?void 0:e.fields)&&i.push(...this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata)),null==e?void 0:e.search){const t=this.modelMetadata.fields.filter((e=>e.searchable)).map((t=>({_iusub:{[t.name]:e.search}})));t.length&&i.push({_or:t})}const s=yield n.use(this.model).getMany(i.length?{_and:i}:{},{limit:null==e?void 0:e.limit,page:null==e?void 0:e.page,projection:null==e?void 0:e.projection,order:null===(r=null==e?void 0:e.order)||void 0===r?void 0:r.map((e=>{const t=Object.keys(e).find((t=>!!e[t]));return[t,e[t]]}))},this.getNestedQueries(e)),a=s.records.map((e=>e.id));for(const t of this.modelMetadata.fields){if(!t.hasMany||(null==e?void 0:e.projection)&&!e.projection.includes(t.name))continue;const i=(0,o.getModelById)(t.hasMany.relationDto.id),r=new ModelRepository(i),d=a.length?yield r.getMany({queries:{fields:{[t.hasMany.column]:a}},queryProvider:n}):{records:[]};for(const e of s.records)e[t.name]=d.records.filter((n=>n[t.hasMany.column]===e.id))}return yield this.beforeReturning(s.records),{total:s.total,records:this.project(s.records,null==e?void 0:e.projection)}}))}deleteMany({queries:e,ops:t,tx:n}){return i(this,void 0,void 0,(function*(){let i=t||[];if(null==e?void 0:e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&i.push(...t)}const o=i.length?{_and:[...i,...t||[]]}:{},r=this.getNestedQueries(e);let s=[];if(r.length){const e=yield n.use(this.model).getRecords(o,{},r);yield n.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}}),s=e}else s=yield n.use(this.model).deleteMany(o,null==e?void 0:e.returning);return{modified:s}}))}}t.ModelRepository=ModelRepository},2255:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractAccessCondition=void 0;t.AbstractAccessCondition=class AbstractAccessCondition{}},4192:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoFieldValidation=void 0;const r=n(2318),s=n(2255);t.DtoFieldValidation=(e,t,n)=>{let a=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:n||"dto_field_condition",valueType:r.AccessConditionValueType.DTO,valueConstraint:JSON.stringify((0,r.getObjectMetadata)(e))}}validate(e,t){return o(this,void 0,void 0,(function*(){try{for(const n of e)(0,r.validateData)(n,t);return!0}catch(e){return!1}}))}};return a=i([(0,r.Register)()],a),a}},1071:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const r=n(2318),s=n(2255);t.FilterModelFieldAccessCondition=(e,t)=>{let n=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:"filter_model_field",valueType:r.AccessConditionValueType.CHOICES,valueConstraint:(0,r.getObjectMetadata)(e).fields.map((e=>e.name))}}validate(e,t){return o(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return n=i([(0,r.Register)()],n),n}},3198:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.MaximumQueryLimit=void 0;const r=n(2318),s=n(2255);let a=class MaximumQueryLimit extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){let t=e.getQuery().limit;return t&&(t=parseInt(t)),t||0}))}validate(e,t){return o(this,void 0,void 0,(function*(){return e>0&&e<=t}))}getConditionMetadata(){return{name:"maximum_query_limit",valueType:r.AccessConditionValueType.NUMBER,valueConstraint:JSON.stringify({min:1})}}};a=i([(0,r.Register)()],a),t.MaximumQueryLimit=a},341:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.QueryTypes=void 0,o(n(9025),t),o(n(4638),t),o(n(1820),t),o(n(1870),t),o(n(4972),t),o(n(8903),t),o(n(2417),t),o(n(1532),t),o(n(5879),t),o(n(6004),t),o(n(7282),t),o(n(4435),t),o(n(767),t),o(n(225),t),o(n(2255),t),o(n(1071),t),o(n(3198),t),o(n(4192),t),o(n(859),t),o(n(2085),t),o(n(531),t),o(n(7825),t),o(n(9837),t),o(n(3355),t),o(n(9073),t),o(n(8023),t),o(n(5048),t),o(n(5530),t),o(n(2841),t),o(n(7152),t),o(n(8577),t),o(n(2665),t),o(n(9990),t),o(n(6507),t),o(n(4839),t),o(n(5232),t),o(n(5572),t),o(n(889),t),o(n(5537),t),o(n(226),t),o(n(8836),t),o(n(9627),t),o(n(6721),t),o(n(204),t),o(n(7577),t),o(n(8709),t),o(n(6793),t),o(n(3e3),t),o(n(3643),t),o(n(5616),t),o(n(6042),t),o(n(873),t),o(n(1319),t),o(n(3757),t),o(n(7220),t),o(n(9461),t),o(n(120),t),o(n(9171),t),o(n(4963),t),o(n(5670),t),o(n(1556),t),o(n(2363),t),o(n(4683),t),o(n(3346),t),o(n(9527),t),o(n(3581),t),o(n(3376),t),o(n(8104),t),o(n(5033),t);var r=n(496);Object.defineProperty(t,"QueryTypes",{enumerable:!0,get:function(){return r.QueryTypes}})},4683:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobController=void 0;const i=n(2318);t.AbstractJobController=class AbstractJobController{getAllJobs(){const e=(0,i.getObjectMetadata)(this.constructor);return(null==e?void 0:e.jobs)||[]}}},3346:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobExecutor=void 0;const o=n(2318),r=n(4683);t.AbstractJobExecutor=class AbstractJobExecutor{constructor(){this._allJobs=null}init(){return i(this,void 0,void 0,(function*(){}))}getAllJobs(){return i(this,void 0,void 0,(function*(){if(!this._allJobs){const e=(0,o.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances(),this._allJobs=t.map((e=>e.getAllJobs().map((t=>({jobName:t.jobName,handlerFn:e[t.handlerName].bind(e)}))))).reduce(((e,t)=>e.concat(t)),[])}return this._allJobs}))}}},9527:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobScheduler=void 0;const o=n(2318),r=n(4683);t.AbstractJobScheduler=class AbstractJobScheduler{constructor(e){this.logger=e}schedule(){return i(this,void 0,void 0,(function*(){const e=(0,o.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances();const n=t.map((e=>e.getAllJobs())).reduce(((e,t)=>e.concat(t)),[]).filter((e=>e.interval||e.cron));for(const e of n)this.logger.debug(`Scheduling: ${e.jobName}, at: ${e.cron||e.interval}`),this.scheduleJob({jobName:e.jobName,cron:e.cron,interval:e.interval}),this.logger.debug(`Job scheduled: ${e.jobName}`)}))}}},3581:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobExecutor=void 0;const o=n(3346);class AwsJobExecutor extends o.AbstractJobExecutor{constructor(e){super(),this.logger=e}executeJob(e,t){return i(this,void 0,void 0,(function*(){(yield this.getAllJobs()).find((t=>t.jobName===e.jobName))?e.interval||e.cron:this.logger.error(`Job not found: ${e.jobName}`)}))}}t.AwsJobExecutor=AwsJobExecutor},3376:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobScheduler=void 0;const i=n(9527);class AwsJobScheduler extends i.AbstractJobScheduler{scheduleJob(e){}}t.AwsJobScheduler=AwsJobScheduler},8104:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalJobExecutor=void 0;const o=n(3346);class LocalJobExecutor extends o.AbstractJobExecutor{constructor(e){super(),this.logger=e}executeJob(e,t){return i(this,void 0,void 0,(function*(){const t=(yield this.getAllJobs()).find((t=>t.jobName===e.jobName));t?yield t.handlerFn(e):this.logger.error(`Job not found: ${e.jobName}`)}))}}t.LocalJobExecutor=LocalJobExecutor},5033:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalJobScheduler=void 0;const a=n(2318),d=s(n(8311)),l=s(n(1495)),c=s(n(9896)),u=n(3346),h=n(9527);let p=class LocalJobScheduler extends h.AbstractJobScheduler{constructor(e,t,n,i,o,r=30){super(e),this.logger=e,this.jobExecutor=t,this.redisServerUrl=n,this.lockMutexKey=i,this.holdMutexKey=o,this.keyRetentionDurationSecond=r,this.intervals=[]}init(){return r(this,void 0,void 0,(function*(){this.logger.debug("LocalJobScheduler init")}))}exit(){var e;this.mutexHoldInterval&&clearInterval(this.mutexHoldInterval),null===(e=this.redisClient)||void 0===e||e.quit();for(const e of this.intervals)clearInterval(e);this.logger.debug("LocalJobScheduler exit")}extendMutexKey(){return r(this,void 0,void 0,(function*(){this.redisClient&&(yield this.redisClient.setex(this.holdMutexKey,this.keyRetentionDurationSecond,1),this.logger.debug("Scheduler extends mutex key"))}))}schedule(){const e=Object.create(null,{schedule:{get:()=>super.schedule}});return r(this,void 0,void 0,(function*(){this.redisClient||(this.redisClient=new l.default(this.redisServerUrl));if(yield this.redisClient.exists(this.holdMutexKey))return void this.logger.info("Scheduler is active, ignore");const t=new c.default([this.redisClient]);try{const n=yield t.acquire([this.lockMutexKey],this.keyRetentionDurationSecond);yield e.schedule.call(this),yield this.extendMutexKey(),yield n.release(),this.logger.debug("Schedule finished"),this.mutexHoldInterval=setInterval((()=>{this.extendMutexKey()}),Math.trunc(1e3*this.keyRetentionDurationSecond/2)+1)}catch(e){console.log(e),this.logger.info("Failed to lock mutex key, ignore")}}))}scheduleJob(e){if(e.interval){const t=setInterval((()=>this.jobExecutor.executeJob(e,0)),1e3*e.interval);this.intervals.push(t)}else if(e.cron){if(!d.default.validate(e.cron))throw a.ErrorBuilder.systemError(`Invalid cron job expression for job ${e.jobName}: ${e.cron}`);d.default.schedule(e.cron,(()=>this.jobExecutor.executeJob(e,0)))}}};p=i([(0,a.Initable)(),o("design:paramtypes",[a.AbstractLogger,u.AbstractJobExecutor,String,String,String,Number])],p),t.LocalJobScheduler=p},1556:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CustomJob=t.CronJob=t.IntervalJob=void 0;const i=n(2318);t.IntervalJob=(e,t)=>(n,o)=>{const r=(0,i.initObjectMetadata)(n);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,interval:t,handlerName:o})};t.CronJob=(e,t)=>(n,o)=>{const r=(0,i.initObjectMetadata)(n);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,cron:t,handlerName:o})};t.CustomJob=e=>(t,n)=>{const o=(0,i.initObjectMetadata)(t);o.jobs||(o.jobs=[]),o.jobs.push({jobName:e,handlerName:n})}},2363:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5572:function(e,t,n){var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FileLogMedium=void 0;const d=a(n(7147)),l=a(n(1017)),c=n(2318);let u=i=class FileLogMedium{constructor(e){const t=e.separated?i.levels.map((t=>l.default.join(e.destination,t+".log"))):[e.destination];this.destination=t.map((e=>(d.default.existsSync(l.default.dirname(e))||d.default.mkdirSync(l.default.dirname(e),{recursive:!0}),d.default.openSync(e,"a")))),this.separated=!!e.separated}init(){return s(this,void 0,void 0,(function*(){}))}exit(){this.destination.forEach((e=>d.default.closeSync(e)))}write(e,t){const n=this.separated?this.destination[i.levels.indexOf(e)]:0;d.default.appendFileSync(n,t)}};u.levels=Object.values(c.LogLevel),u=i=o([(0,c.Initable)(),r("design:paramtypes",[Object])],u),t.FileLogMedium=u},7577:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractCacheService=void 0;t.AbstractCacheService=class AbstractCacheService{}},8709:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileService=void 0;t.AbstractFileService=class AbstractFileService{}},204:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=n(7048);t.AbstractService=class AbstractService{constructor(e){this.databaseAdapter=e}createTransaction(){return this.databaseAdapter.createTransaction()}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,o.getTransactionFromContext)(this)}))}}},6862:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const i=n(2318);t.AbstractServerSocket=class AbstractServerSocket{constructor(e){this.socketInfo=e}getId(){return this.socketInfo.id}getAuthInfo(){return this.socketInfo.authInfo}send(e,t){t?this.socketInfo.channels.find((e=>e.name===t&&e.serverToClientAllowed))&&this.sendRaw({type:i.MessageType.PLAIN,data:{message:e,channel:t}}):this.sendRaw({type:i.MessageType.PLAIN,data:{message:e}})}sendRaw(e){this.physicSend(e)}disconnect(e){this.physicClose(e)}removeChannels(e){this.socketInfo.channels=this.socketInfo.channels.filter((t=>!e.includes(t.name)))}addChannels(e){this.socketInfo.channels.push(...e)}getChannelsInfo(){return this.socketInfo.channels}}},5530:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const s=n(2318),a=r(n(1495)),d=n(9990),l=n(2665),c=n(2255),u=n(1532),h="x-socket-action",p="read",f="write";let g=class SocketReadCondition extends c.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===p}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_read",description:"Can receive message from channel",valueType:s.AccessConditionValueType.BOOLEAN}}};g=i([(0,s.Register)()],g);let v=class SocketWriteCondition extends c.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===f}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_write",description:"Can send message to channel",valueType:s.AccessConditionValueType.BOOLEAN}}};v=i([(0,s.Register)()],v);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e,t,n,i,o){this.requireAuthentication=e,this.logger=t,this.redisServerUrl=n,this.authProvider=i,this.authResolver=o,this._connectionHandler=null,this.redisClient=new a.default(this.redisServerUrl)}getUniqueChannelPrefix(){return"CHANNEL:"}getConnectionHandler(){return o(this,void 0,void 0,(function*(){if(null===this._connectionHandler){const e=(0,s.getServiceProvider)().getInjector();this._connectionHandler=e.resolveOptional(d.AbstractSocketConnectionHandler),yield e.initInstances()}return this._connectionHandler}))}formatBroadcastData(e,t){return{type:s.MessageType.PLAIN,data:{channel:e,message:t}}}getUniqueChannelName(e){return`${this.getUniqueChannelPrefix()}${e}`}getSocketIdsOfChannel(e){return o(this,void 0,void 0,(function*(){return(yield this.redisClient.smembers(this.getUniqueChannelName(e)))||[]}))}addSocketToChannel(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getById(e);n&&(n.addChannels(t),yield Promise.all(t.map((t=>this.redisClient.sadd(this.getUniqueChannelName(t.name),e)))),yield n.saveSocketInfo())}))}removeSocketFromChannel(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getById(e);n&&(n.removeChannels(t),yield Promise.all(t.map((t=>this.redisClient.srem(this.getUniqueChannelName(t),e)))),yield n.saveSocketInfo())}))}handle(e){var t;return o(this,void 0,void 0,(function*(){const n=yield this.getConnectionHandler();switch(e.method){case s.SocketMethod.CONNECT:{this.logger.debug("Socket connection attempt",e);const i=this.authResolver(null===(t=e.data)||void 0===t?void 0:t.queries),o=yield this.authProvider.getPrincipalResolver().resolvePrincipal(i);if(!o&&this.requireAuthentication)throw s.ErrorBuilder.error(s.Errors.AUTHENTICATION_ERROR);const r=yield this.addSocket({id:e.socketId,authInfo:o,channels:[],createdAt:Date.now()},e.data);if(!r)throw s.ErrorBuilder.error(s.Errors.SYSTEM_ERROR,"Socket not found after create: "+e.socketId);null==n||n.onSocketConnect(r);break}case s.SocketMethod.DISCONNECT:{this.logger.debug("Socket disconnect",e);const t=yield this.getById(e.socketId);if(t){const i=yield this.getMountedEndpointInfo();for(const n of t.getChannelsInfo()){const o=i.find((e=>e.endpointMetadata.url===n.name));o&&(o.endpoint.controller.onChannelLeave(t),yield this.removeSocketFromChannel(e.socketId,t.getChannelsInfo().map((e=>e.name))))}null==n||n.onSocketDisconnect(t),t.disconnect(),yield this.removeSocket(e.socketId)}break}case s.SocketMethod.MESSAGE:{this.logger.debug("Socket message",e);const t=e.data,i=yield this.getById(e.socketId);if(i)switch(t.type){case s.MessageType.PING_PONG:null==i||i.sendRaw({type:s.MessageType.PING_PONG,data:t.data});break;case s.MessageType.CHANNEL_JOIN:{const e=t.data,n=[];for(const t of e){let e=!1,o=!1;const r=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));if(r){try{const e=new u.HttpRequest({method:s.SocketMethod.MESSAGE,pathName:t,headers:{[h]:p}},r.endpointMetadata);yield this.authProvider.authorize(i.getAuthInfo(),e,r),o=!0}catch(e){}try{const n=new u.HttpRequest({method:s.SocketMethod.MESSAGE,pathName:t,headers:{[h]:f}},r.endpointMetadata);yield this.authProvider.authorize(i.getAuthInfo(),n,r),e=!0}catch(e){}(e||o)&&(this.logger.debug("Adding channel info",t,e,o),n.push({name:t,clientToServerAllowed:e,serverToClientAllowed:o})),r.endpoint.controller.onChannelJoin(i)}}yield this.addSocketToChannel(i.getId(),n),i.sendRaw({type:s.MessageType.CHANNEL_JOIN,data:n.map((e=>e.name))})}break;case s.MessageType.CHANNEL_LEAVE:{const e=t.data;for(const t of e){const e=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));e&&e.endpoint.controller.onChannelLeave(i)}yield this.removeSocketFromChannel(i.getId(),e)}break;case s.MessageType.PLAIN:{const e=t.data.channel,o=t.data.message;if(e){if(i.getChannelsInfo().find((t=>t.name===e&&t.clientToServerAllowed))){const t=(yield this.getMountedEndpointInfo()).find((t=>t.endpointMetadata.url===e));if(t){!1!==t.endpoint.controller.onMessage(i,o)&&(this.logger.debug("broadcasting to channel",e,o),this.broadcastToChannel(e,o))}}}else null==n||n.onMessage(i,o)}break;default:this.logger.debug("Invalid message format",t)}else this.logger.debug("Socket not found",e.socketId);break}default:return}}))}getMountedEndpointInfo(){return o(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const e=(0,s.getServiceProvider)().getInjector(),t=e.resolveMultiple(l.AbstractSocketController);yield e.initInstances(),this.mountedEndpointInfo=t.map((e=>({endpoint:{httpMethod:s.SocketMethod.MESSAGE,mount:e.channel,controller:e,handlerFunctionName:e.onMessage.name},endpointMetadata:{httpMethod:s.SocketMethod.MESSAGE,description:"Send / Receive message to / from channel",dataType:s.DataType.OBJECT,url:e.channel,name:e.channel,accessConditions:[g,v]}})))}return this.mountedEndpointInfo}))}}},9990:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketConnectionHandler=void 0;t.AbstractSocketConnectionHandler=class AbstractSocketConnectionHandler{}},2665:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketController=void 0;t.AbstractSocketController=class AbstractSocketController{constructor(e){this.channel=e}onChannelJoin(e){}onChannelLeave(e){}onMessage(e,t){}}},7152:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsSocketManager=void 0;const a=n(2318),d=s(n(9336)),l=n(767),c=n(5530),u=n(6862),h=n(859);class ApiGatewaySocket extends u.AbstractServerSocket{constructor(e,t,n,i,o,r){super(n),this.socketManager=e,this.logger=t,this.socketInfo=n,this.apiGateway=i,this.socketNamespace=o,this.redisClient=r}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.socketNamespace,this.socketInfo.id,JSON.stringify(this.socketInfo))}))}physicSend(e){this.socketManager.physicSend(this.getId(),e).catch((e=>this.logger.debug("Socket send error",e)))}physicClose(e){e&&this.physicSend(e),this.socketManager.removeSocketFromRedis(this.getId()).catch((e=>this.logger.debug("Socket close error",e))),this.socketManager.removeSocket(this.getId()).catch((e=>this.logger.debug("Socket remove error",e)))}serialize(){return JSON.stringify(this.socketInfo)}}let p=class AwsSocketManager extends c.AbstractServerSocketManager{constructor(e,t,n,i,o,r,s,a){super(e,a,i,r,s),this.authenticationRequired=e,this.region=t,this.socketDomainUrl=n,this.redisServerUrl=i,this.httpRequestHandler=o,this.authorizationProvider=r,this.authResolver=s,this.logger=a,this.apiGatewayManagement=new d.default.ApiGatewayManagementApi({region:t,apiVersion:"2018-11-29",endpoint:n})}init(){return r(this,void 0,void 0,(function*(){this.logger.info("AwsSocketManager init")}))}exit(){this.redisClient.disconnect(),this.logger.info("AwsSocketManager exit")}removeSocketFromRedis(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.hdel(this.getSocketInfoHashKey(),e)}))}getSocketInfoHashKey(){return"__SOCKET_INFO__"}physicSend(e,t){return r(this,void 0,void 0,(function*(){try{yield this.apiGatewayManagement.postToConnection({ConnectionId:e,Data:JSON.stringify(t)}).promise(),this.logger.debug(`Socket ${e} send OK`,t)}catch(t){throw this.logger.debug(`Socket ${e} post error`,t),410===t.statusCode&&(this.logger.debug(`Stale socket ${e}`),this.logger.debug(`Disconnecting ${e}`),this.logger.debug(`Removing socket ${e}`),yield Promise.all([this.removeSocket(e),this.removeSocketFromRedis(e)]),this.logger.debug(`Socket removed ${e}`)),t}}))}configure(e){this.logger.debug("Aws socket manager configure")}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){const t=yield this.getSocketIdsOfChannel(e);if(!t.length)return[];return(yield this.redisClient.hmget(this.getSocketInfoHashKey(),...t)).filter((e=>!!e)).map((e=>this.getSocketBySerialized(e)))}))}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const n=yield this.getSocketIdsOfChannel(e);if(n.length){const i=this.formatBroadcastData(e,t);yield Promise.all(n.map((e=>this.physicSend(e,i))))}}))}addSocket(e,t){return r(this,void 0,void 0,(function*(){const t=new ApiGatewaySocket(this,this.logger,e,this.apiGatewayManagement,this.getSocketInfoHashKey(),this.redisClient);return yield t.saveSocketInfo(),t}))}removeSocket(e){return r(this,void 0,void 0,(function*(){yield this.apiGatewayManagement.deleteConnection({ConnectionId:e}).promise()}))}getSocketBySerialized(e){return new ApiGatewaySocket(this,this.logger,JSON.parse(e),this.apiGatewayManagement,this.getSocketInfoHashKey(),this.redisClient)}getById(e){return r(this,void 0,void 0,(function*(){const t=yield this.redisClient.hget(this.getSocketInfoHashKey(),e);if(t)return this.logger.debug("Serialized aws socket",t),this.getSocketBySerialized(t);this.logger.error("Cannot find socket with id: "+e)}))}};p=i([(0,a.Initable)(),o("design:paramtypes",[Boolean,String,String,String,l.AbstractHttpRequestHandler,h.AbstractHttpAuthorizationProvider,Function,a.AbstractLogger])],p),t.AwsSocketManager=p},8577:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},2841:function(e,t,n){var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalSocketManager=void 0;const a=n(2318),d=s(n(5352)),l=s(n(9215)),c=s(n(9103)),u=n(5530),h=n(6862),p=n(859);var f;!function(e){e.SEND="SEND",e.CLOSE="CLOSE",e.SAVE="SAVE"}(f||(f={}));class RedisSocket extends h.AbstractServerSocket{constructor(e,t,n){super(n),this.socketChannelName=e,this.redisClient=t,this.socketInfo=n}physicSend(e){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.SEND,data:e}))}physicClose(){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.CLOSE}))}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.SAVE,data:this.socketInfo}))}))}}class ExpressSocket extends h.AbstractServerSocket{constructor(e,t,n){super(t),this.socket=e,this.socketInfo=t,this.infoSaver=n}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.infoSaver(this.socketInfo)}))}physicSend(e){this.socket.send(JSON.stringify(e))}physicClose(e){this.socket.close(1e3,e&&JSON.stringify(e))}}let g=class LocalSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n,i,o){super(e,n,t,i,o),this.authenticationRequired=e,this.redisServerUrl=t,this.logger=n,this.authProvider=i,this.authResolver=o,this.allSockets=[],this.subscribedChannels=[],this.subClient=this.redisClient.duplicate(),this.channelSubClient=this.redisClient.duplicate(),this.sendClient=this.redisClient.duplicate()}init(){return r(this,void 0,void 0,(function*(){this.logger.info("LocalSocketManager init"),this.channelSubClient.on("message",((e,t)=>{this.logger.debug("channelSubClient: ",t,e),this.channelMessageListenner(t,e)})),this.subClient.on("message",((e,t)=>{this.logger.debug("subClient: ",t,e),this.socketMessageListener(t,e)}))}))}exit(){this.sendClient.disconnect(),this.subClient.disconnect(),this.channelSubClient.disconnect(),this.redisClient.disconnect(),this.logger.info("LocalSocketManager exit")}channelMessageListenner(e,t){this.logger.debug("Receiving message from channel",t,e);const n=JSON.parse(e);n.type===a.MessageType.PLAIN&&this.allSockets.forEach((e=>{e.send(n.data.message,n.data.channel)}))}socketMessageListener(e,t){this.logger.debug("Receiving message from remote socket channel",t,e);const n=t.substring(this.getSocketChannelKeyPrefix().length),i=this.allSockets.find((e=>e.getId()===n));if(i){const t=JSON.parse(e);switch(t.type){case f.SEND:i.physicSend(t.data);break;case f.SAVE:i.socketInfo.channels=t.data,i.saveSocketInfo();break;case f.CLOSE:i.disconnect();break;default:this.logger.debug("Invalid remote command",t)}}}getUniqueDataChannelName(e){return`CHANNEL_DATA:${e}`}getSocketChannelKeyPrefix(){return"SOCKET_CHANNEL:"}getSocketInfoHashKey(){return"__SOCKET_INFO__"}getSocketChannelKey(e){return`${this.getSocketChannelKeyPrefix()}${e}`}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("Broadcasting",e,t);const n=this.formatBroadcastData(e,t);yield this.redisClient.publish(this.getUniqueDataChannelName(e),JSON.stringify(n))}))}addSocketToChannel(e,t){const n=Object.create(null,{addSocketToChannel:{get:()=>super.addSocketToChannel}});return r(this,void 0,void 0,(function*(){yield n.addSocketToChannel.call(this,e,t);const i=t.map((e=>e.name)).filter((e=>!this.subscribedChannels.includes(e)));i.length&&(yield Promise.all(i.map((e=>this.channelSubClient.subscribe(this.getUniqueDataChannelName(e))))),this.subscribedChannels.push(...i))}))}removeSocketFromChannel(e,t){const n=Object.create(null,{removeSocketFromChannel:{get:()=>super.removeSocketFromChannel}});return r(this,void 0,void 0,(function*(){yield n.removeSocketFromChannel.call(this,e,t),yield Promise.all(t.map((e=>this.channelSubClient.unsubscribe(this.getUniqueChannelName(e))))),this.subscribedChannels=this.subscribedChannels.filter((e=>!t.includes(e)))}))}addSocket(e,{socket:t}){return r(this,void 0,void 0,(function*(){const n=new ExpressSocket(t,e,(e=>r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.getSocketInfoHashKey(),e.id,JSON.stringify(e))})))),i=this.getSocketChannelKey(e.id);return this.subClient.subscribe(i),this.allSockets.push(n),n}))}removeSocket(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.hdel(this.getSocketInfoHashKey(),e);const t=this.getSocketChannelKey(e);this.subClient.unsubscribe(t),this.allSockets=this.allSockets.filter((t=>t.getId()!==e))}))}getById(e){return r(this,void 0,void 0,(function*(){let t=this.allSockets.find((t=>t.getId()===e));if(!t){const n=yield new Promise((t=>this.redisClient.hget(this.getSocketInfoHashKey(),e).then((e=>t(e?JSON.parse(e):void 0))).catch((e=>{this.logger.error(e),t(void 0)}))));n&&(t=new RedisSocket(this.getSocketChannelKey(e),this.sendClient,n))}return t}))}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){const t=yield this.getSocketIdsOfChannel(e);return(yield Promise.all(t.map((e=>this.getById(e))))).filter((e=>!!e))}))}configure(e){if(!e)return;this.logger.debug("Local socket manager configure");new d.default.Server({server:e}).on("connection",((e,t)=>{const n=t.headers["sec-websocket-key"],i=(0,l.default)({url:t.url}),o=c.default.parse(decodeURIComponent(i.search||""));this.handle({method:a.SocketMethod.CONNECT,socketId:n,data:{queries:o,socket:e}}).catch((t=>{e.close(1e3,`${t.name}:${t.message}`)})),e.onmessage=e=>{this.handle({method:a.SocketMethod.MESSAGE,socketId:n,data:e.data&&JSON.parse(e.data)}).catch((e=>{this.logger.error(e)}))},e.onclose=()=>{this.handle({method:a.SocketMethod.DISCONNECT,socketId:n}).catch((e=>{this.logger.error(e)}))}}))}};g=i([(0,a.Initable)(),o("design:paramtypes",[Boolean,String,a.AbstractLogger,p.AbstractHttpAuthorizationProvider,Function])],g),t.LocalSocketManager=g},5537:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const o=n(2318),r=n(137),s=n(4972);class ClaireServer extends o.ClaireApp{constructor(e,t,n){super(),this.logger=e,this.httpRequestHandler=t,this.socketManager=n,this.booted=!1}init(){return i(this,void 0,void 0,(function*(){if(this.booted)return;const e=[];if(this.httpRequestHandler){const t=yield this.httpRequestHandler.getMountedEndpointInfo();e.push(...t)}if(this.socketManager){const t=yield this.socketManager.getMountedEndpointInfo();e.push(...t)}for(const t of e)this.logger.info(`Mounting: ${(0,s.getEndpointId)(t.endpoint)}`);(0,o.getGlobalStore)().mountedEndpointInfo=e,this.logger.debug("Claire server initing"),this.logger.debug("Setting up exception handlers"),process.on("SIGTERM",(()=>(this.logger.warn("SIGTERM interrupt signal"),this.stop(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("SIGINT",(()=>(this.logger.warn("SIGINT interrupt signal"),this.stop(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("uncaughtException",(e=>{this.logger.error("uncaughtException",e.name,e.stack)})),process.on("unhandledRejection",(e=>{this.logger.error("unhandledRejection",e.name,e.stack)})),this.booted=!0}))}exit(){super.exit()}stop(e){this.logger.debug("Server is shutting down"),this.exit(),process.exit(e)}}t.ClaireServer=ClaireServer},226:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressWrapper=void 0;const r=n(2318),s=o(n(6860)),a=o(n(3685)),d=o(n(3582)),l=o(n(6674)),c=n(5530),u=n(767);t.ExpressWrapper=class ExpressWrapper{constructor(e,t){this.injector=(0,r.getServiceProvider)().getInjector(),this.server=e,this.config=t,this.logger=this.injector.resolve(r.AbstractLogger),this.socketManager=this.injector.resolveOptional(c.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(u.AbstractHttpRequestHandler)}close(){var e;null===(e=this.httpServer)||void 0===e||e.close(),this.server.exit()}listen(e){var t,n;return i(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const o=(0,s.default)(),c=a.default.createServer(o);return null===(t=this.socketManager)||void 0===t||t.configure(c),o.use((0,d.default)()),o.use(s.default.raw({limit:1024*((null===(n=this.config)||void 0===n?void 0:n.maxBodySizeKB)||4096)})),o.use((0,l.default)()),o.use(((e,t,n)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),n()})),o.use(s.default.urlencoded({extended:!1})),o.use(s.default.json()),o.all("*",((e,t)=>{(()=>i(this,void 0,void 0,(function*(){if(!!e.headers["x-amzn-apigateway-api-id"]){if(!this.socketManager)throw r.ErrorBuilder.systemError("Socket manager not found");const n={socketId:e.body.connectionId,data:e.body.data,method:e.body.type.toLowerCase()};if(n.method===r.SocketMethod.CONNECT){const t=e.body.data.querystring,i=t.substring(1,t.length-1).split(",").map((e=>e.trim().split("="))).reduce(((e,t)=>Object.assign(e,{[t[0]]:t[1]})),{});n.data={queries:i}}yield this.socketManager.handle(n).then((()=>{t.status(200).send()})).catch((e=>{var t;this.logger.debug("Handle error",e),null===(t=this.socketManager)||void 0===t||t.removeSocket(n.socketId).catch((e=>{this.logger.debug(e)}))}))}else{if(!this.httpRequestHandler)throw r.ErrorBuilder.systemError("Http request handler not found");const n={fullPath:e.url,method:e.method.toLowerCase(),headers:e.headers,body:e.body},i=yield this.httpRequestHandler.handle(n);i.headers&&Object.keys(i.headers).forEach((e=>{t.set(e,i.headers[e])})),t.status(i.code).send(i.value)}})))().catch((e=>{this.logger.error(e),t.status(400).json({name:e.name,message:e.message})}))})),new Promise(((t,n)=>{this.httpServer=c.listen(e,t).on("error",n)}))}))}}},8836:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const o=n(2318),r=n(767),s=n(5530),a=n(6721),toApiGatewayFormat=(e,t)=>({statusCode:e,body:t&&JSON.stringify(t),headers:{"Access-Control-Allow-Headers":"*","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"*","Content-Type":"application/json"}});t.LambdaWrapper=class LambdaWrapper{constructor(e,t){this.serverFactory=e,this.requestMapper=t,this.requestMapper=t,this.handler=this.handler.bind(this),this.injector=(0,o.getServiceProvider)().getInjector(),this.socketManager=this.injector.resolveOptional(s.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(r.AbstractHttpRequestHandler)}bootServer(){var e;return i(this,void 0,void 0,(function*(){return this._server||(this._server=yield this.serverFactory(),yield this.injector.initInstances(),null===(e=this.socketManager)||void 0===e||e.configure(),yield this._server.init()),this._server}))}handler(e){return i(this,void 0,void 0,(function*(){yield this.bootServer();const t=this.requestMapper(e);if(!t)return toApiGatewayFormat(400,"Cannot resolve event");if(t.method===o.HttpMethod.OPTIONS)return toApiGatewayFormat(200);try{if(Object.values(o.HttpMethod).includes(t.method)){if(!this.httpRequestHandler)throw o.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Http request handler not found");const e={fullPath:t.rawPath,method:t.method,headers:t.headers,body:t.body},n=yield this.httpRequestHandler.handle(e);return toApiGatewayFormat(n.code,n.value)}if(!Object.values(o.SocketMethod).includes(t.method))throw o.ErrorBuilder.error(a.Errors.HTTP_REQUEST_ERROR,"Not allow request method: "+t.method);{if(!this.socketManager)throw o.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Socket manager not found");const e={socketId:t.rawPath,method:t.method,data:t.body};yield this.socketManager.handle(e)}return toApiGatewayFormat(200)}catch(e){return toApiGatewayFormat(400,{name:e.name,message:e.message})}}))}}},9627:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6721:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Errors=void 0;const i=n(2318);t.Errors=Object.assign(Object.assign({},i.Errors),{TFA_REQUIRED:"TFA_REQUIRED"})},889:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lambdaRequestMapper=void 0;const i=n(2318);t.lambdaRequestMapper=e=>{if(e.requestContext.eventType){const t=e.requestContext.eventType.toLowerCase(),n=e.body&&JSON.parse(e.body);return{method:t,rawPath:e.requestContext.connectionId,body:t===i.SocketMethod.CONNECT?{queries:e.queryStringParameters}:n}}return{method:e.requestContext.http.method.toLowerCase(),rawPath:`${e.rawPath}?${e.rawQueryString}`,body:e.body&&JSON.parse(e.body),headers:e.headers}}},2318:e=>{e.exports=require("@clairejs/core")},9336:e=>{e.exports=require("aws-sdk")},3582:e=>{e.exports=require("cors")},6860:e=>{e.exports=require("express")},6674:e=>{e.exports=require("express-fileupload")},1495:e=>{e.exports=require("ioredis")},8311:e=>{e.exports=require("node-cron")},9215:e=>{e.exports=require("parseurl")},99:e=>{e.exports=require("path-to-regexp")},9103:e=>{e.exports=require("query-string")},9896:e=>{e.exports=require("redlock")},496:e=>{e.exports=require("sequelize")},5352:e=>{e.exports=require("ws")},2081:e=>{e.exports=require("child_process")},7147:e=>{e.exports=require("fs")},3685:e=>{e.exports=require("http")},1017:e=>{e.exports=require("path")}},t={};return function __webpack_require__(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,__webpack_require__),o.exports}(341)})()));
@@ -9,11 +9,11 @@ export declare abstract class AbstractServerSocket implements IServerSocket {
9
9
  getAuthInfo(): IPrincipal | undefined;
10
10
  send(data: any, channel?: string): void;
11
11
  sendRaw(data: SocketMessage): void;
12
- disconnect(): void;
12
+ disconnect(err?: any): void;
13
13
  removeChannels(channels: string[]): void;
14
14
  addChannels(channelInfos: ChannelInfo[]): void;
15
15
  getChannelsInfo(): ChannelInfo[];
16
16
  abstract physicSend(data: any): void;
17
- abstract physicClose(): void;
17
+ abstract physicClose(err?: any): void;
18
18
  abstract saveSocketInfo(): Promise<void>;
19
19
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clairejs/server",
3
- "version": "3.5.1",
3
+ "version": "3.5.4",
4
4
  "description": "Claire server NodeJs framework written in Typescript.",
5
5
  "types": "dist/index.d.ts",
6
6
  "main": "dist/index.js",
@@ -34,7 +34,7 @@
34
34
  "ws": "^7.5.5"
35
35
  },
36
36
  "peerDependencies": {
37
- "@clairejs/core": "^3.1.7"
37
+ "@clairejs/core": "^3.1.9"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/body-parser": "^1.19.0",